id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
21,218
tst_benchmark.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/benchmark/tst_benchmark.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QScopedPointer> #include <QtCore/QEventLoop> #include <QtCore/QVariant> #include <QtTest/QtTest> #include <QElapsedTimer> #include <QThread> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpcabstractserver.h" #include "qjsonrpcsocket.h" #include "qjsonrpcservice.h" #include "qjsonrpcmessage.h" class TestBenchmark: public QObject { Q_OBJECT private Q_SLOTS: void simple(); void namedParameters(); }; class TestService : public QJsonRpcService { Q_OBJECT Q_CLASSINFO("serviceName", "service") public: TestService(QObject *parent = 0) : QJsonRpcService(parent) {} QJsonRpcMessage testDispatch(const QJsonRpcMessage &message) { return QJsonRpcService::dispatch(message); } public Q_SLOTS: QString singleParam(int i) const { return QString::number(i); } QString singleParam(const QString &string) const { return string; } QString singleParam(const QVariant &k) const { return k.toString(); } QString namedParams(int integer, const QString &string, double doub) { (void) integer; (void) doub; return string; } }; class TestServiceProvider : public QJsonRpcServiceProvider { public: TestServiceProvider() {} }; void TestBenchmark::simple() { TestServiceProvider provider; TestService service; provider.addService(&service); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.singleParam", QString("test")); QBENCHMARK { QJsonRpcMessage response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); } } void TestBenchmark::namedParameters() { TestServiceProvider provider; TestService service; provider.addService(&service); QJsonObject obj; obj["integer"] = 1; obj["string"] = QLatin1String("str"); obj["doub"] = 1.2; QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.namedParams", obj); QBENCHMARK { QJsonRpcMessage response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); } } QTEST_MAIN(TestBenchmark) #include "tst_benchmark.moc"
2,898
C++
.cpp
94
27.265957
79
0.737976
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,219
testservice.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/localserver/testservice.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QDebug> #include "testservice.h" TestService::TestService(QObject *parent) : QJsonRpcService(parent) { } void TestService::testMethod() { qDebug() << Q_FUNC_INFO << "called" << endl; } void TestService::testMethodWithParams(const QString &first, bool second, double third) { qDebug() << Q_FUNC_INFO << "called with parameters: " << endl << " first: " << first << endl << "second: " << second << endl << " third: " << third << endl; } void TestService::testMethodWithVariantParams(const QString &first, bool second, double third, const QVariant &fourth) { qDebug() << Q_FUNC_INFO << "called with variant parameters: " << endl << " first: " << first << endl << "second: " << second << endl << " third: " << third << endl << "fourth: " << fourth << endl; } QString TestService::testMethodWithParamsAndReturnValue(const QString &name) { qDebug() << Q_FUNC_INFO << "called" << endl; return QString("Hello %1").arg(name); } void TestService::testMethodWithDefaultParameter(const QString &first, const QString &second) { qDebug() << Q_FUNC_INFO << endl << "first: " << first << endl << (second.isEmpty() ? "not defined, default parameter" : second) << endl; }
1,984
C++
.cpp
52
33.942308
118
0.664935
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,220
localserver.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/localserver/localserver.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QCoreApplication> #include <QLocalServer> #include <QFile> #include <QDir> #include "qjsonrpclocalserver.h" #include "testservice.h" int main(int argc, char **argv) { QCoreApplication app(argc, argv); QString serviceName = QDir::temp().absoluteFilePath("testservice"); if (QFile::exists(serviceName)) { if (!QFile::remove(serviceName)) { qDebug() << "couldn't delete temporary service"; return -1; } } QJsonRpcLocalServer rpcServer; rpcServer.addService(new TestService); if (!rpcServer.listen(serviceName)) { qDebug() << "could not start server: " << rpcServer.errorString(); return -1; } return app.exec(); }
1,386
C++
.cpp
40
30.875
74
0.713115
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,222
tcpclient.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/tcpclient/tcpclient.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QHostAddress> #include <QTcpSocket> #include "qjsonrpcsocket.h" #include "qjsonrpcservice.h" #include "qjsonrpcservicereply.h" #include "tcpclient.h" TcpClient::TcpClient(QObject *parent) : QObject(parent), m_client(0) { } void TcpClient::run() { QTcpSocket *socket = new QTcpSocket(this); socket->connectToHost(QHostAddress::LocalHost, 5555); if (!socket->waitForConnected()) { qDebug() << "could not connect to server: " << socket->errorString(); return; } // run tests m_client = new QJsonRpcSocket(socket, this); QJsonRpcServiceReply *reply = m_client->invokeRemoteMethod("agent.testMethod"); connect(reply, SIGNAL(finished()), this, SLOT(processResponse())); reply = m_client->invokeRemoteMethod("agent.testMethodWithParams", "one", false, 10); connect(reply, SIGNAL(finished()), this, SLOT(processResponse())); reply = m_client->invokeRemoteMethod("agent.testMethodWithVariantParams", "one", false, 10, QVariant(2.5)); connect(reply, SIGNAL(finished()), this, SLOT(processResponse())); reply = m_client->invokeRemoteMethod("agent.testMethodWithParamsAndReturnValue", "matt"); connect(reply, SIGNAL(finished()), this, SLOT(processResponse())); connect(m_client, SIGNAL(messageReceived(QJsonRpcMessage)), this, SLOT(processMessage(QJsonRpcMessage))); reply = m_client->invokeRemoteMethod("agent.testNotifyConnectedClients", "some data"); } void TcpClient::processResponse() { QJsonRpcServiceReply *reply = static_cast<QJsonRpcServiceReply *>(sender()); if (!reply) { qDebug() << "invalid response received"; return; } qDebug() << "response received: " << reply->response(); } void TcpClient::processMessage(const QJsonRpcMessage &message) { if (message.method() == "callback") qDebug() << "received message: " << message.method() << message.params(); }
2,579
C++
.cpp
62
38.048387
111
0.724661
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,223
testservice.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/tcpserver/testservice.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QDebug> #include "testservice.h" TestService::TestService(QObject *parent) : QJsonRpcService(parent) { } void TestService::testMethod() { qDebug() << Q_FUNC_INFO << "called" << endl; } void TestService::testMethodWithParams(const QString &first, bool second, double third) { qDebug() << Q_FUNC_INFO << "called with parameters: " << endl << " first: " << first << endl << "second: " << second << endl << " third: " << third << endl; } void TestService::testMethodWithVariantParams(const QString &first, bool second, double third, const QVariant &fourth) { qDebug() << Q_FUNC_INFO << "called with variant parameters: " << endl << " first: " << first << endl << "second: " << second << endl << " third: " << third << endl << "fourth: " << fourth << endl; } QString TestService::testMethodWithParamsAndReturnValue(const QString &name) { qDebug() << Q_FUNC_INFO << "called" << endl; return QString("Hello %1").arg(name); } void TestService::testMethodWithDefaultParameter(const QString &first, const QString &second) { qDebug() << Q_FUNC_INFO << endl << "first: " << first << endl << (second.isEmpty() ? "not defined, default parameter" : second) << endl; } void TestService::testNotifyConnectedClients(const QString &message) { QJsonArray args; args.append(message); Q_EMIT notifyConnectedClients("callback", args); }
2,158
C++
.cpp
58
33.103448
118
0.673996
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,224
tcpserver.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/tcpserver/tcpserver.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QCoreApplication> #include "qjsonrpctcpserver.h" #include "testservice.h" int main(int argc, char **argv) { QCoreApplication app(argc, argv); QJsonRpcTcpServer rpcServer; rpcServer.addService(new TestService); if (!rpcServer.listen(QHostAddress::LocalHost, 5555)) { qDebug() << "can't start tcp server: " << rpcServer.errorString(); return -1; } return app.exec(); }
1,089
C++
.cpp
30
33.366667
74
0.739583
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,225
tst_qjsonrpcserver.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpcserver/tst_qjsonrpcserver.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QLocalSocket> #include <QTcpSocket> #include <QScopedPointer> #include <QtCore/QEventLoop> #include <QtCore/QVariant> #include <QtTest/QtTest> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpcabstractserver.h" #include "qjsonrpclocalserver.h" #include "qjsonrpctcpserver.h" #include "qjsonrpchttpserver.h" #include "qjsonrpchttpclient.h" #include "qjsonrpcsocket.h" #include "qjsonrpcmessage.h" #include "qjsonrpcservicereply.h" #include "testservices.h" class TestQJsonRpcServer: public QObject { Q_OBJECT public: TestQJsonRpcServer(); enum ServerType { TcpServer, LocalServer, HttpServer }; private Q_SLOTS: void initTestCase_data(); void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); void noParameter(); void singleParameter(); void multiParameter(); void variantParameter(); void variantListParameter(); void variantResult(); void invalidArgs(); void methodNotFound(); void invalidRequest(); void notifyConnectedClients_data(); void notifyConnectedClients(); void numberParameters(); void hugeResponse(); void complexMethod(); void defaultParameters(); void overloadedMethod(); void qVariantMapInvalidParam(); void stringListParameter(); void outputParameter(); #if QT_VERSION >= 0x050200 void jsonReturnTypes(); #endif void notifyServiceSocket(); void userDeletesReplyOnDelayedResponse(); void delayedResponseBasic(); void delayedResponseSocketClosed(); void addRemoveService(); void serviceWithNoGivenName(); void cantRemoveInvalidService(); void cantAddServiceTwice(); private: QJsonRpcAbstractSocket *createClient(); // client related QScopedPointer<QJsonRpcAbstractSocket> clientSocket; QList<QTcpSocket*> tcpSockets; QList<QLocalSocket*> localSockets; // server related QJsonRpcAbstractServer *server; QThread serverThread; QScopedPointer<QJsonRpcTcpServer> tcpServer; QScopedPointer<QJsonRpcLocalServer> localServer; QScopedPointer<QJsonRpcHttpServer> httpServer; quint16 tcpServerPort; quint16 httpServerPort; private: // temporarily disabled // void testListOfInts(); }; Q_DECLARE_METATYPE(TestQJsonRpcServer::ServerType) Q_DECLARE_METATYPE(QJsonRpcMessage::Type) TestQJsonRpcServer::TestQJsonRpcServer() : server(0) { } void TestQJsonRpcServer::initTestCase_data() { QTest::addColumn<ServerType>("serverType"); QTest::newRow("tcp") << TcpServer; QTest::newRow("local") << LocalServer; QTest::newRow("http") << HttpServer; } void TestQJsonRpcServer::initTestCase() { serverThread.start(); } void TestQJsonRpcServer::cleanupTestCase() { serverThread.quit(); QVERIFY(serverThread.wait()); } QJsonRpcAbstractSocket *TestQJsonRpcServer::createClient() { QFETCH_GLOBAL(ServerType, serverType); QJsonRpcAbstractSocket *socket = 0; if (serverType == LocalServer) { QLocalSocket *localSocket = new QLocalSocket; connect(localServer.data(), SIGNAL(clientConnected()), &QTestEventLoop::instance(), SLOT(exitLoop())); localSocket->connectToServer("qjsonrpc-test-local-server"); QTestEventLoop::instance().enterLoop(5); if (QTestEventLoop::instance().timeout() || !localSocket->waitForConnected()) { delete localSocket; return 0; } socket = new QJsonRpcSocket(localSocket); localSockets.append(localSocket); } else if (serverType == TcpServer) { QTcpSocket *tcpSocket = new QTcpSocket; connect(tcpServer.data(), SIGNAL(clientConnected()), &QTestEventLoop::instance(), SLOT(exitLoop())); tcpSocket->connectToHost(QHostAddress::LocalHost, tcpServerPort); QTestEventLoop::instance().enterLoop(5); if (QTestEventLoop::instance().timeout() || !tcpSocket->waitForConnected()) { delete tcpSocket; return 0; } socket = new QJsonRpcSocket(tcpSocket); tcpSockets.append(tcpSocket); } else if (serverType == HttpServer) { QJsonRpcHttpClient *client = new QJsonRpcHttpClient; client->setEndPoint("http://127.0.0.1:" + QString::number(httpServerPort)); socket = client; } return socket; } void TestQJsonRpcServer::init() { QFETCH_GLOBAL(ServerType, serverType); if (serverType == LocalServer) { localServer.reset(new QJsonRpcLocalServer); QVERIFY(localServer->listen("qjsonrpc-test-local-server")); localServer->moveToThread(&serverThread); server = localServer.data(); } else if (serverType == TcpServer) { tcpServer.reset(new QJsonRpcTcpServer); tcpServerPort = quint16(91919 + qrand() % 1000); QVERIFY(tcpServer->listen(QHostAddress::LocalHost, tcpServerPort)); tcpServer->moveToThread(&serverThread); server = tcpServer.data(); } else if (serverType == HttpServer) { httpServer.reset(new QJsonRpcHttpServer); httpServerPort = quint16(8118 + qrand() % 1000); QVERIFY(httpServer->listen(QHostAddress::LocalHost, httpServerPort)); httpServer->moveToThread(&serverThread); server = httpServer.data(); } clientSocket.reset(createClient()); QVERIFY(!clientSocket.isNull()); if (serverType == LocalServer || serverType == TcpServer) QCOMPARE(server->connectedClientCount(), 1); } void TestQJsonRpcServer::cleanup() { QFETCH_GLOBAL(ServerType, serverType); if (serverType == TcpServer) { // disconnect clients while (!tcpSockets.isEmpty()) { QTcpSocket *tcpSocket = tcpSockets.takeFirst(); connect(tcpServer.data(), SIGNAL(clientDisconnected()), &QTestEventLoop::instance(), SLOT(exitLoop())); if (tcpSocket->state() == QAbstractSocket::ConnectedState) { tcpSocket->disconnectFromHost(); QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); } delete tcpSocket; } // close server tcpServer->close(); } else if (serverType == LocalServer) { // disconnect clients while (!localSockets.isEmpty()) { QLocalSocket *localSocket = localSockets.takeFirst(); connect(localServer.data(), SIGNAL(clientDisconnected()), &QTestEventLoop::instance(), SLOT(exitLoop())); if (localSocket->state() == QLocalSocket::ConnectedState) { localSocket->disconnectFromServer(); QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); } delete localSocket; } // close server localServer->close(); } else if (serverType == HttpServer) { httpServer->close(); } QCOMPARE(server->connectedClientCount(), 0); } void TestQJsonRpcServer::noParameter() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); QCOMPARE(spyMessageReceived.count(), 1); } void TestQJsonRpcServer::singleParameter() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.singleParam", QString("single")); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); QCOMPARE(response.result().toString(), QLatin1String("single")); } void TestQJsonRpcServer::overloadedMethod() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage stringRequest = QJsonRpcMessage::createRequest("service.overloadedMethod", QString("single")); QJsonRpcMessage stringResponse = clientSocket->sendMessageBlocking(stringRequest); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(stringResponse.errorCode() == QJsonRpc::NoError); QCOMPARE(stringRequest.id(), stringResponse.id()); QCOMPARE(stringResponse.result().toBool(), false); QJsonRpcMessage intRequest = QJsonRpcMessage::createRequest("service.overloadedMethod", 10); QJsonRpcMessage intResponse = clientSocket->sendMessageBlocking(intRequest); QCOMPARE(spyMessageReceived.count(), 2); QVERIFY(intResponse.errorCode() == QJsonRpc::NoError); QCOMPARE(intRequest.id(), intResponse.id()); QCOMPARE(intResponse.result().toBool(), true); QVariantMap testMap; testMap["one"] = 1; testMap["two"] = 2; testMap["three"] = 3; QJsonRpcMessage mapRequest = QJsonRpcMessage::createRequest("service.overloadedMethod", QJsonValue::fromVariant(testMap)); QJsonRpcMessage mapResponse = clientSocket->sendMessageBlocking(mapRequest); QCOMPARE(spyMessageReceived.count(), 3); QVERIFY(mapResponse.errorCode() == QJsonRpc::InvalidParams); QCOMPARE(mapRequest.id(), mapResponse.id()); } void TestQJsonRpcServer::multiParameter() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonArray params; params.append(QLatin1String("a")); params.append(QLatin1String("b")); params.append(QLatin1String("c")); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.multipleParam", params); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); QCOMPARE(response.result().toString(), QLatin1String("abc")); } void TestQJsonRpcServer::variantParameter() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonArray params; params.append(QJsonValue::fromVariant(QVariant(true))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.variantParameter", params); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); QVERIFY(response.result() == true); } void TestQJsonRpcServer::variantListParameter() { QVERIFY(server->addService(new TestService)); QJsonArray data; data.append(1); data.append(20); data.append(QLatin1String("hello")); data.append(false); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonArray params; params.append(data); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.variantListParameter", params); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); QCOMPARE(response.result().toArray(), data); } void TestQJsonRpcServer::variantResult() { QVERIFY(server->addService(new TestService)); QJsonRpcMessage response = clientSocket->invokeRemoteMethodBlocking("service.variantStringResult"); QVERIFY(response.errorCode() == QJsonRpc::NoError); QString stringResult = response.result().toString(); QCOMPARE(stringResult, QLatin1String("hello")); } void TestQJsonRpcServer::invalidArgs() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam", false); clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVariant message = spyMessageReceived.takeFirst().at(0); QJsonRpcMessage error = message.value<QJsonRpcMessage>(); QCOMPARE(request.id(), error.id()); QVERIFY(error.errorCode() == QJsonRpc::InvalidParams); } void TestQJsonRpcServer::methodNotFound() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.doesNotExist"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(response.isValid()); QVariant message = spyMessageReceived.takeFirst().at(0); QJsonRpcMessage error = message.value<QJsonRpcMessage>(); QCOMPARE(request.id(), error.id()); QVERIFY(error.errorCode() == QJsonRpc::MethodNotFound); } void TestQJsonRpcServer::invalidRequest() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::fromJson("{\"jsonrpc\": \"2.0\", \"id\": 666}"); clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVariant message = spyMessageReceived.takeFirst().at(0); QJsonRpcMessage error = message.value<QJsonRpcMessage>(); QCOMPARE(request.id(), error.id()); QVERIFY(error.errorCode() == QJsonRpc::InvalidRequest); } void TestQJsonRpcServer::qVariantMapInvalidParam() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); const char *invalid = "{\"jsonrpc\": \"2.0\", \"id\": 0, \"method\": \"service.variantMapInvalidParam\",\"params\": [[{\"foo\":\"bar\",\"baz\":\"quux\"}, {\"foo\":\"bar\"}]]}"; QJsonRpcMessage request = QJsonRpcMessage::fromJson(invalid); clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVariant message = spyMessageReceived.takeFirst().at(0); QJsonRpcMessage error = message.value<QJsonRpcMessage>(); QCOMPARE(request.id(), error.id()); QVERIFY(error.errorCode() == QJsonRpc::InvalidParams); } class ServerNotificationHelper : public QObject { Q_OBJECT public: ServerNotificationHelper(const QJsonRpcMessage &message, QJsonRpcAbstractServer *provider) : m_provider(provider), m_notification(message) {} public Q_SLOTS: void activate() { m_provider->notifyConnectedClients(m_notification); } private: QJsonRpcAbstractServer *m_provider; QJsonRpcMessage m_notification; }; void TestQJsonRpcServer::notifyConnectedClients_data() { QTest::addColumn<QString>("method"); QTest::addColumn<QJsonRpcMessage::Type>("type"); QTest::addColumn<QJsonArray>("parameters"); QTest::addColumn<bool>("sendAsMessage"); QTest::newRow("notification-message") << "testNotification" << QJsonRpcMessage::Notification << QJsonArray() << true; QTest::newRow("notification-direct") << "testNotification" << QJsonRpcMessage::Notification << QJsonArray() << false; QJsonArray parameters; parameters.append(QLatin1String("test")); QTest::newRow("request-message") << "testRequest" << QJsonRpcMessage::Request << parameters << true; QTest::newRow("request-direct") << "testRequest" << QJsonRpcMessage::Request << parameters << false; } void TestQJsonRpcServer::notifyConnectedClients() { QFETCH(QString, method); QFETCH(QJsonRpcMessage::Type, type); QFETCH(QJsonArray, parameters); QFETCH(bool, sendAsMessage); QFETCH_GLOBAL(ServerType, serverType); if (serverType == HttpServer) { #if QT_VERSION >= 0x050000 QSKIP("Not supported for HTTP connections"); #else QSKIP("Not supported for HTTP connections", SkipAll); #endif } QVERIFY(server->addService(new TestService)); QEventLoop loop; connect(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit())); QSignalSpy spy(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage message; if (sendAsMessage) { switch (type) { case QJsonRpcMessage::Request: message = QJsonRpcMessage::createRequest(method, parameters); break; case QJsonRpcMessage::Notification: message = QJsonRpcMessage::createNotification(method, parameters); break; default: break; } if (serverType == TcpServer) QMetaObject::invokeMethod(tcpServer.data(), "notifyConnectedClients", Q_ARG(QJsonRpcMessage, message)); else if (serverType == LocalServer) QMetaObject::invokeMethod(localServer.data(), "notifyConnectedClients", Q_ARG(QJsonRpcMessage, message)); // server->notifyConnectedClients(message); } else { if (serverType == TcpServer) QMetaObject::invokeMethod(tcpServer.data(), "notifyConnectedClients", Q_ARG(QString, method), Q_ARG(QJsonArray, parameters)); else if (serverType == LocalServer) QMetaObject::invokeMethod(localServer.data(), "notifyConnectedClients", Q_ARG(QString, method), Q_ARG(QJsonArray, parameters)); // server->notifyConnectedClients(method, parameters); } QTimer::singleShot(2000, &loop, SLOT(quit())); loop.exec(); QCOMPARE(spy.count(), 1); QJsonRpcMessage receivedMessage = spy.takeFirst().first().value<QJsonRpcMessage>(); if (sendAsMessage) { QCOMPARE(receivedMessage, message); } else { QCOMPARE(receivedMessage.method(), method); QCOMPARE(receivedMessage.params().toArray(), parameters); } } void TestQJsonRpcServer::numberParameters() { TestService *service = new TestService; QVERIFY(server->addService(service)); QJsonArray params; params.append(10); params.append(3.14159); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.numberParameters", params); clientSocket->sendMessageBlocking(request); QCOMPARE(service->callCount(), 1); } void TestQJsonRpcServer::hugeResponse() { QVERIFY(server->addService(new TestService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.hugeResponse"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(response.isValid()); } void TestQJsonRpcServer::complexMethod() { QVERIFY(server->addService(new TestComplexMethodService)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.complex.prefix.for.testMethod"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); } void TestQJsonRpcServer::defaultParameters() { QVERIFY(server->addService(new TestService)); // test without name QJsonRpcMessage noNameRequest = QJsonRpcMessage::createRequest("service.defaultParametersMethod"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(noNameRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toString(), QLatin1String("empty string")); // test with name QJsonRpcMessage nameRequest = QJsonRpcMessage::createRequest("service.defaultParametersMethod", QLatin1String("matt")); response = clientSocket->sendMessageBlocking(nameRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toString(), QLatin1String("hello matt")); // test multiparameter QJsonRpcMessage konyRequest = QJsonRpcMessage::createRequest("service.defaultParametersMethod2", QLatin1String("KONY")); response = clientSocket->sendMessageBlocking(konyRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toString(), QLatin1String("KONY2012")); } void TestQJsonRpcServer::notifyServiceSocket() { QFETCH_GLOBAL(ServerType, serverType); if (serverType == HttpServer) { #if QT_VERSION >= 0x050000 QSKIP("Not supported for HTTP connections"); #else QSKIP("Not supported for HTTP connections", SkipAll); #endif } QScopedPointer<QJsonRpcServiceSocket> serviceSocket; clientSocket.reset(); // we only want a service socket, this would override that if (serverType == TcpServer) { serviceSocket.reset(new QJsonRpcServiceSocket(tcpSockets.first())); } else if (serverType == LocalServer) { serviceSocket.reset(new QJsonRpcServiceSocket(localSockets.first())); } TestService *service = new TestService; QVERIFY(serviceSocket->addService(service)); QCOMPARE(service->callCount(), 0); connect(service, SIGNAL(numberParametersCalled()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); QJsonArray params; params.append(10); params.append(3.14159); QJsonRpcMessage notification = QJsonRpcMessage::createNotification("service.numberParameters", params); if (serverType == TcpServer) QMetaObject::invokeMethod(tcpServer.data(), "notifyConnectedClients", Q_ARG(QJsonRpcMessage, notification)); else if (serverType == LocalServer) QMetaObject::invokeMethod(localServer.data(), "notifyConnectedClients", Q_ARG(QJsonRpcMessage, notification)); QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); QCOMPARE(service->callCount(), 1); } /* Q_DECLARE_METATYPE(QList<int>) void TestQJsonRpcServer::testListOfInts() { server->addService(new TestService); qRegisterMetaType<QList<int> >("QList<int>"); QList<int> intList = QList<int>() << 300 << 30 << 3; QVariant variant = QVariant::fromValue(intList); QJsonRpcMessage intRequest = QJsonRpcMessage::createRequest("service.methodWithListOfInts", variant); QJsonRpcMessage response = clientSocket->sendMessageBlocking(intRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QVERIFY(response.result().toBool()); } */ void TestQJsonRpcServer::stringListParameter() { QVERIFY(server->addService(new TestService)); QStringList strings = QStringList() << "one" << "two" << "three"; QJsonArray params; params.append(1); params.append(QLatin1String("A")); params.append(QLatin1String("B")); params.append(QJsonValue::fromVariant(strings)); QJsonRpcMessage strRequest = QJsonRpcMessage::createRequest("service.stringListParameter", params); QJsonRpcMessage response = clientSocket->sendMessageBlocking(strRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QVERIFY(response.result().toBool()); } void TestQJsonRpcServer::outputParameter() { QVERIFY(server->addService(new TestService)); // use argument 2 as in/out parameter QJsonArray arrParams; arrParams.push_back(1); arrParams.push_back(0); arrParams.push_back(2); QJsonRpcMessage strRequest = QJsonRpcMessage::createRequest("service.outputParameter", arrParams); QJsonRpcMessage response = clientSocket->sendMessageBlocking(strRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE((int) response.result().toDouble(), 3); // only input parameters are provided QJsonObject objParams; objParams["in1"] = 1; objParams["in2"] = 3; strRequest = QJsonRpcMessage::createRequest("service.outputParameter", objParams); response = clientSocket->sendMessageBlocking(strRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE((int) response.result().toDouble(), 4); // also provide the in/out parameter objParams["out"] = 2; strRequest = QJsonRpcMessage::createRequest("service.outputParameter", objParams); response = clientSocket->sendMessageBlocking(strRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE((int) response.result().toDouble(), 6); // test strings QJsonArray stringParams; stringParams.push_back(QLatin1String("Sherlock")); stringParams.push_back(QLatin1String("")); stringParams.push_back(QLatin1String("Holmes")); strRequest = QJsonRpcMessage::createRequest("service.outputParameterWithStrings", stringParams); response = clientSocket->sendMessageBlocking(strRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toString(), QLatin1String("Sherlock Holmes")); // only input parameters are provided QJsonObject stringObjectParams; stringObjectParams["first"] = QLatin1String("Sherlock"); stringObjectParams["output"] = QLatin1String("Hello"); stringObjectParams["last"] = QLatin1String("Holmes"); strRequest = QJsonRpcMessage::createRequest("service.outputParameterWithStrings", stringObjectParams); response = clientSocket->sendMessageBlocking(strRequest); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toString(), QLatin1String("Hello Sherlock Holmes")); } void TestQJsonRpcServer::userDeletesReplyOnDelayedResponse() { QVERIFY(server->addService(new TestService)); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.delayedResponse"); connect(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage)), &QTestEventLoop::instance(), SLOT(exitLoop())); QJsonRpcServiceReply *reply = clientSocket->sendMessage(request); delete reply; // While this is not applicable for HTTP connections, I've left the code // up until this point to ensure that no memory is leaked QFETCH_GLOBAL(ServerType, serverType); if (serverType == HttpServer) { #if QT_VERSION >= 0x050000 QSKIP("Not applicable for HTTP connections"); #else QSKIP("Not applicable for HTTP connections", SkipAll); #endif } QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); } #if QT_VERSION >= 0x050200 void TestQJsonRpcServer::jsonReturnTypes() { QVERIFY(server->addService(new TestService)); { QJsonArray array; array.append(1); array.append(QLatin1String("two")); array.append(true); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.returnQJsonArray"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toArray(), array); } { QJsonObject object; object.insert("one", QLatin1String("one")); object.insert("two", 2); object.insert("three", true); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.returnQJsonObject"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toObject(), object); } } #endif class QJsonRpcServiceReplySpy : public QObject { Q_OBJECT public: explicit QJsonRpcServiceReplySpy(int expectedReplies, QObject *parent = 0) : QObject(parent), m_expectedReplies(expectedReplies) { } QList<QJsonRpcMessage> responses() const { return m_responses; } Q_SIGNALS: void finished(); public Q_SLOTS: void replyFinished() { QJsonRpcServiceReply *reply = qobject_cast<QJsonRpcServiceReply*>(sender()); if (!reply) return; m_responses.append(reply->response()); reply->deleteLater(); if (m_responses.size() == m_expectedReplies) Q_EMIT finished(); } private: int m_expectedReplies; QList<QJsonRpcMessage> m_responses; }; void TestQJsonRpcServer::delayedResponseBasic() { QFETCH_GLOBAL(ServerType, serverType); if (serverType == HttpServer) { #if QT_VERSION >= 0x050000 QSKIP("QNAM makes deterministic order impossible here"); #else QSKIP("QNAM makes deterministic order impossible here", SkipAll); #endif } QVERIFY(server->addService(new TestDelayedResponseService)); QJsonRpcServiceReplySpy spy(6); connect(&spy, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); int delayedMessageId = 0; { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.delayedResponse"); QJsonRpcServiceReply *reply = clientSocket->sendMessage(request); connect(reply, SIGNAL(finished()), &spy, SLOT(replyFinished())); delayedMessageId = request.id(); } QList<int> expectedMessageOrder; for (int i = 0; i < 5; ++i) { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.immediateResponse"); QJsonRpcServiceReply *reply = clientSocket->sendMessage(request); connect(reply, SIGNAL(finished()), &spy, SLOT(replyFinished())); expectedMessageOrder.append(request.id()); } expectedMessageOrder.append(delayedMessageId); QTestEventLoop::instance().enterLoop(10); QVERIFY(!QTestEventLoop::instance().timeout()); QList<int> actualMessageOrder; foreach (QJsonRpcMessage response, spy.responses()) actualMessageOrder.append(response.id()); QCOMPARE(expectedMessageOrder, actualMessageOrder); } void TestQJsonRpcServer::delayedResponseSocketClosed() { QFETCH_GLOBAL(ServerType, serverType); if (serverType == HttpServer) { #if QT_VERSION >= 0x050000 QSKIP("Not applicable for HTTP connections"); #else QSKIP("Not applicable for HTTP connections", SkipAll); #endif } TestDelayedResponseService *service = new TestDelayedResponseService; QVERIFY(server->addService(service)); QSignalSpy spy(service, SIGNAL(responseResult(bool))); connect(service, SIGNAL(responseResult(bool)), &QTestEventLoop::instance(), SLOT(exitLoop())); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.delayedResponseWithClosedSocket"); QScopedPointer<QJsonRpcServiceReply> reply(clientSocket->sendMessage(request)); if (serverType == TcpServer) tcpSockets.first()->disconnectFromHost(); else if (serverType == LocalServer) localSockets.first()->disconnectFromServer(); QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); QList<QVariant> arguments = spy.takeFirst(); QCOMPARE(arguments.at(0).toBool(), false); } void TestQJsonRpcServer::addRemoveService() { TestService service; QVERIFY(server->addService(&service)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam"); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); QCOMPARE(spyMessageReceived.count(), 1); QVERIFY(server->removeService(&service)); response = clientSocket->sendMessageBlocking(request); QVERIFY(response.errorCode() == QJsonRpc::MethodNotFound); QFETCH_GLOBAL(ServerType, serverType); if (serverType == TcpServer) QVERIFY(tcpServer->errorString().isEmpty()); else if (serverType == LocalServer) QVERIFY(localServer->errorString().isEmpty()); } void TestQJsonRpcServer::serviceWithNoGivenName() { QVERIFY(server->addService(new TestServiceWithoutServiceName)); QSignalSpy spyMessageReceived(clientSocket.data(), SIGNAL(messageReceived(QJsonRpcMessage))); QJsonRpcMessage request = QJsonRpcMessage::createRequest("testservicewithoutservicename.testMethod", QLatin1String("foo")); QJsonRpcMessage response = clientSocket->sendMessageBlocking(request); QVERIFY(response.errorCode() == QJsonRpc::NoError); QCOMPARE(request.id(), response.id()); QCOMPARE(spyMessageReceived.count(), 1); } void TestQJsonRpcServer::cantRemoveInvalidService() { TestService service; QCOMPARE(server->removeService(&service), false); } void TestQJsonRpcServer::cantAddServiceTwice() { TestService service; QVERIFY(server->addService(&service)); QCOMPARE(server->addService(&service), false); } QTEST_MAIN(TestQJsonRpcServer) #include "tst_qjsonrpcserver.moc"
33,835
C++
.cpp
804
36.7699
180
0.726187
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,226
testservices.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpcserver/testservices.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QEventLoop> #include <QTimer> #include <QDebug> #include <QtTest> #include "qjsonrpcsocket.h" #include "testservices.h" TestService::TestService(QObject *parent) : QJsonRpcService(parent), m_called(0) { } void TestService::resetCount() { m_called = 0; } int TestService::callCount() const { return m_called; } void TestService::noParam() const { } QString TestService::singleParam(const QString &string) const { return string; } QString TestService::multipleParam(const QString &first, const QString &second, const QString &third) const { return first + second + third; } void TestService::numberParameters(int intParam, double doubleParam) { if (intParam == 10 && doubleParam == 3.14159) { m_called++; Q_EMIT numberParametersCalled(); } } bool TestService::variantParameter(const QVariant &variantParam) const { return variantParam.toBool(); } QVariantList TestService::variantListParameter(const QVariantList &data) { return data; } QVariant TestService::variantStringResult() { return QLatin1String("hello"); } QVariantList TestService::variantListResult() { return QVariantList() << "one" << 2 << 3.0; } QVariantMap TestService::variantMapResult() { QVariantMap result; result["one"] = 1; result["two"] = 2.0; return result; } /* NOTE: suppress binding warnings bool TestService::methodWithListOfInts(const QList<int> &list) { if (list.size() < 3) return false; if (list.at(0) != 300) return false; if (list.at(1) != 30) return false; if (list.at(2) != 3) return false; return true; } */ QString TestService::variantMapInvalidParam(const QVariantMap &map) { return map["foo"].toString(); } void TestService::outputParameter(int in1, int &out, int in2) { out = in1 + out + in2; } void TestService::outputParameterWithStrings(const QString &first, QString &output, const QString &last) { if (output.isEmpty()) output = QString("%1 %2").arg(first).arg(last); else output.append(QString(" %1 %2").arg(first).arg(last)); } bool TestService::overloadedMethod(int input) { Q_UNUSED(input) return true; } bool TestService::overloadedMethod(const QString &input) { Q_UNUSED(input) return false; } bool TestService::stringListParameter(int one, const QString &two, const QString &three, const QStringList &list) { Q_UNUSED(one); Q_UNUSED(two); Q_UNUSED(three); Q_UNUSED(list); return true; } QJsonArray TestService::returnQJsonArray() { QJsonArray array; array.append(1); array.append(QLatin1String("two")); array.append(true); return array; } QJsonObject TestService::returnQJsonObject() { QJsonObject object; object.insert("one", QLatin1String("one")); object.insert("two", 2); object.insert("three", true); return object; } QVariantMap TestService::hugeResponse() { QVariantMap result; for (int i = 0; i < 1000; i++) { QString key = QString("testKeyForHugeResponse%1").arg(i); result[key] = "some sample data to make the response larger"; } return result; } QString TestService::defaultParametersMethod(const QString &name) { if (name.isEmpty()) return "empty string"; return QString("hello %1").arg(name); } QString TestService::defaultParametersMethod2(const QString &name, int year) { return QString("%1%2").arg(name).arg(year); } TestServiceWithoutServiceName::TestServiceWithoutServiceName(QObject *parent) : QJsonRpcService(parent) { } QString TestServiceWithoutServiceName::testMethod(const QString &string) const { return string; } TestComplexMethodService::TestComplexMethodService(QObject *parent) : QJsonRpcService(parent) { } void TestComplexMethodService::testMethod() { } TestDelayedResponseService::TestDelayedResponseService(QObject *parent) : QJsonRpcService(parent) { } void TestDelayedResponseService::delayedResponse() { QVERIFY(currentRequest().isValid()); beginDelayedResponse(); m_request = currentRequest(); QTimer::singleShot(250, this, SLOT(delayedResponseComplete())); } void TestDelayedResponseService::delayedResponseWithClosedSocket() { QVERIFY(currentRequest().isValid()); beginDelayedResponse(); m_request = currentRequest(); QTimer::singleShot(250, this, SLOT(delayedResponseWithClosedSocketComplete())); } QString TestDelayedResponseService::immediateResponse() { return QLatin1String("immediate"); } void TestDelayedResponseService::delayedResponseComplete() { m_request.respond(QLatin1String("delayed")); } void TestDelayedResponseService::delayedResponseWithClosedSocketComplete() { QJsonRpcMessage requestMessage = m_request.request(); QJsonRpcMessage responseMessage = requestMessage.createResponse(QLatin1String("delayed")); bool result = m_request.respond(responseMessage); Q_EMIT responseResult(result); }
5,626
C++
.cpp
206
24.286408
113
0.740527
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,228
tst_qjsonrpcmetatype.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpcmetatype/tst_qjsonrpcmetatype.cpp
/* * Copyright (C) 2013 Fargier Sylvain * Copyright (C) 2014 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QtCore/QVariant> #include <QtTest/QtTest> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpcmetatype.h" #include "qjsonrpcabstractserver.h" #include "qjsonrpcmessage.h" #include "qjsonrpcservice.h" class TestQJsonRpcMetaType: public QObject { Q_OBJECT private slots: void initTestCase(); void customParameterTypes(); void customReturnTypes(); void invalidParameterTypes(); void enums(); private: /* * There's no way to guess which method is the best to dispatch a custom type * for the moment, something like a signature, or a typetesting functor might * be good. * * This test will fail until then */ void commonMethodName(); }; class CustomClass : public QObject { public: CustomClass(int data = 0, QObject *parent = 0) : QObject(parent), data(data) {} CustomClass(const CustomClass &other) : QObject(), data(other.data) {} CustomClass &operator=(const CustomClass &other) { if (&other != this) data = other.data; return *this; } QJsonValue toJson() const { return QJsonValue(data); } static CustomClass fromJson(const QJsonValue &value) { return CustomClass(value.toInt()); } int data; }; Q_DECLARE_METATYPE(CustomClass) class AnotherCustomClass { public: explicit AnotherCustomClass(const QString &str = QString()) : data(str) {} QJsonValue toJson() const { return QJsonValue(data); } static AnotherCustomClass fromJson(const QJsonValue &value) { return AnotherCustomClass(value.toString()); } QString data; }; Q_DECLARE_METATYPE(AnotherCustomClass) class UnboundClass : public QObject { public: UnboundClass(QObject *parent = 0) : QObject(parent) {} }; class TestService : public QJsonRpcService { Q_OBJECT Q_CLASSINFO("serviceName", "service") Q_ENUMS(TestEnum) public: TestService(QObject *parent = 0) : QJsonRpcService(parent) {} QJsonRpcMessage testDispatch(const QJsonRpcMessage &message) { return QJsonRpcService::dispatch(message); } enum TestEnum { ZERO = 0, ONE = 1, TWO = 2, THREE = 3 }; static QMetaEnum TestMetaEnum() { static int i = TestService::staticMetaObject.indexOfEnumerator("TestEnum"); return TestService::staticMetaObject.enumerator(i); } public Q_SLOTS: void customParameterType(const CustomClass &param) const { QCOMPARE(param.data, 42); } CustomClass customReturnType(const CustomClass &param) const { CustomClass ret(param); ++ret.data; return ret; } void invalidParameterType(const UnboundClass &) const { QVERIFY(false); } void enums(TestService::TestEnum) { QVERIFY(true); } int commonMethodName(const CustomClass &c) { return c.data; } QString commonMethodName(const AnotherCustomClass &c) { return c.data; } }; Q_DECLARE_METATYPE(TestService::TestEnum) QJsonValue toJson(TestService::TestEnum e) { return QString(TestService::TestMetaEnum().valueToKey(e)); } TestService::TestEnum fromJson(const QJsonValue &val) { if (val.isString()) { QString str(val.toString()); if (str.isEmpty()) return TestService::ZERO; return (TestService::TestEnum) TestService::TestMetaEnum().keysToValue(str.toLatin1().constData()); } else if (val.isDouble()) { int idx = (int) val.toDouble(); if (!TestService::TestMetaEnum().valueToKey(idx)) return TestService::ZERO; return (TestService::TestEnum) idx; } return TestService::ZERO; } class TestServiceProvider : public QObject, public QJsonRpcServiceProvider { public: TestServiceProvider() {} }; void TestQJsonRpcMetaType::initTestCase() { qRegisterJsonRpcMetaType<CustomClass>("CustomClass"); qRegisterJsonRpcMetaType<AnotherCustomClass>("CustomClass"); // TODO: incorporate enums into qRegisterJsonRpcMetaType QMetaType::registerConverter<TestService::TestEnum, QJsonValue>(&toJson); QMetaType::registerConverter<QJsonValue, TestService::TestEnum>(&fromJson); } /* * Custom class parameter */ void TestQJsonRpcMetaType::customParameterTypes() { TestServiceProvider provider; TestService service; provider.addService(&service); CustomClass custom(42); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.customParameterType", custom.toJson()); QJsonRpcMessage response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); } void TestQJsonRpcMetaType::customReturnTypes() { TestServiceProvider provider; TestService service; provider.addService(&service); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.customReturnType", CustomClass().toJson()); QJsonRpcMessage response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); QVariant result = response.result(); QVERIFY(result.canConvert<CustomClass>()); QCOMPARE(result.value<CustomClass>().data, 1); } void TestQJsonRpcMetaType::invalidParameterTypes() { TestServiceProvider provider; TestService service; provider.addService(&service); UnboundClass custom; QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.invalidParameterType", QJsonValue::fromVariant(QVariant::fromValue(CustomClass()))); QJsonRpcMessage response = service.testDispatch(request); QVERIFY(response.type() == QJsonRpcMessage::Error); QCOMPARE(response.errorCode(), (int) QJsonRpc::MethodNotFound); } void TestQJsonRpcMetaType::enums() { TestServiceProvider provider; TestService service; provider.addService(&service); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.enums", TestService::ONE); QJsonRpcMessage response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); request = QJsonRpcMessage::createRequest("service.enums", QLatin1String("ONE")); response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); } void TestQJsonRpcMetaType::commonMethodName() { TestServiceProvider provider; TestService service; provider.addService(&service); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.commonMethodName", CustomClass(42).toJson()); QJsonRpcMessage response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); CustomClass c(CustomClass::fromJson(response.result())); QCOMPARE(c.data, 42); request = QJsonRpcMessage::createRequest("service.commonMethodName", AnotherCustomClass("test string").toJson()); response = service.testDispatch(request); QVERIFY(response.type() != QJsonRpcMessage::Error); AnotherCustomClass ac(AnotherCustomClass::fromJson(response.result())); QCOMPARE(ac.data, QLatin1String("test string")); } QTEST_MAIN(TestQJsonRpcMetaType) #include "tst_qjsonrpcmetatype.moc"
7,982
C++
.cpp
241
28.431535
107
0.722569
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,229
tst_qjsonrpcmessage.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpcmessage/tst_qjsonrpcmessage.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QtCore/QVariant> #include <QtTest/QtTest> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpcmessage.h" class TestQJsonRpcMessage: public QObject { Q_OBJECT private slots: void debugStreams_data(); void debugStreams(); void invalidData(); void invalidStringData_data(); void invalidStringData(); void invalidDataResponseWithId(); void invalidDataResponseWithoutId(); void responseSameId(); void notificationNoId(); void messageTypes(); void positionalParameters(); void equivalence_data(); void equivalence(); void withVariantListArgs(); void idSentAsString(); }; void TestQJsonRpcMessage::debugStreams_data() { QTest::addColumn<QJsonRpcMessage>("message"); QTest::addColumn<QString>("expectedOutput"); QTest::newRow("invalid-message") << QJsonRpcMessage() << "QJsonRpcMessage(type=QJsonRpcMessage::Invalid, id=0)"; QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.method"); QTest::newRow("request-message") << request << "QJsonRpcMessage(type=QJsonRpcMessage::Request, id=1, method=\"service.method\", params=QJsonValue(undefined) )"; QJsonRpcMessage response = request.createResponse(QLatin1String("response")); QTest::newRow("response-message") << response << "QJsonRpcMessage(type=QJsonRpcMessage::Response, id=1, result=QJsonValue(string, \"response\") )"; QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::MethodNotFound); QTest::newRow("error-message") << error << "QJsonRpcMessage(type=QJsonRpcMessage::Error, id=1, code=-32601, message=\"\", data=QJsonValue(null) )"; QJsonRpcMessage notification = QJsonRpcMessage::createNotification("service.notification"); QTest::newRow("notification-message") << notification << "QJsonRpcMessage(type=QJsonRpcMessage::Notification, method=\"service.notification\", params=QJsonValue(undefined) )"; } void TestQJsonRpcMessage::debugStreams() { QFETCH(QJsonRpcMessage, message); QFETCH(QString, expectedOutput); QString actualOutput; QDebug debug(&actualOutput); debug << message; QCOMPARE(actualOutput.trimmed(), expectedOutput.trimmed()); } void TestQJsonRpcMessage::invalidData() { QJsonObject invalidData; QJsonRpcMessage message = QJsonRpcMessage::fromObject(invalidData); QCOMPARE(message.isValid(), false); QCOMPARE(message.type(), QJsonRpcMessage::Invalid); QVERIFY(message.toObject().isEmpty()); } void TestQJsonRpcMessage::invalidStringData_data() { QTest::addColumn<QByteArray>("stringData"); QTest::newRow("not-json") << QByteArray("invalid json string"); QTest::newRow("not-an-object") << QByteArray("[\"string\"]"); } void TestQJsonRpcMessage::invalidStringData() { QFETCH(QByteArray, stringData); QJsonRpcMessage message = QJsonRpcMessage::fromJson(stringData); QCOMPARE(message.isValid(), false); QCOMPARE(message.type(), QJsonRpcMessage::Invalid); QVERIFY(message.toObject().isEmpty()); QVERIFY(message.params().isUndefined() || message.params().isNull()); QVERIFY(message.result().isUndefined() || message.params().isNull()); QVERIFY(message.errorData().isUndefined() || message.params().isNull()); } void TestQJsonRpcMessage::invalidDataResponseWithId() { // invalid with id const char *invalid = "{\"jsonrpc\": \"2.0\", \"params\": [], \"id\": 666}"; QJsonRpcMessage request = QJsonRpcMessage::fromJson(invalid); QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError, QString()); QJsonRpcMessage response = request.createResponse(QString()); QCOMPARE(request.type(), QJsonRpcMessage::Invalid); QCOMPARE(response.id(), request.id()); QCOMPARE(error.type(), QJsonRpcMessage::Error); } void TestQJsonRpcMessage::invalidDataResponseWithoutId() { // invalid without id const char *invalid = "{\"jsonrpc\": \"2.0\", \"params\": []}"; QJsonRpcMessage request = QJsonRpcMessage::fromJson(invalid); QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError, QString()); QJsonRpcMessage response = request.createResponse(QString()); QCOMPARE(request.type(), QJsonRpcMessage::Invalid); QCOMPARE(response.type(), QJsonRpcMessage::Invalid); QCOMPARE(error.id(), 0); } void TestQJsonRpcMessage::responseSameId() { QJsonRpcMessage request = QJsonRpcMessage::createRequest("testMethod"); QJsonRpcMessage response = request.createResponse(QLatin1String("testResponse")); QCOMPARE(response.id(), request.id()); } void TestQJsonRpcMessage::notificationNoId() { QJsonRpcMessage notification = QJsonRpcMessage::createNotification("testNotification"); QCOMPARE(notification.id(), -1); } void TestQJsonRpcMessage::messageTypes() { QJsonRpcMessage invalid; QCOMPARE(invalid.type(), QJsonRpcMessage::Invalid); QJsonRpcMessage request = QJsonRpcMessage::createRequest("testMethod"); QCOMPARE(request.type(), QJsonRpcMessage::Request); QJsonRpcMessage response = request.createResponse(QLatin1String("testResponse")); QCOMPARE(response.type(), QJsonRpcMessage::Response); QJsonRpcMessage error = request.createErrorResponse(QJsonRpc::NoError); QCOMPARE(error.type(), QJsonRpcMessage::Error); QJsonRpcMessage notification = QJsonRpcMessage::createNotification("testNotification"); QCOMPARE(notification.type(), QJsonRpcMessage::Notification); } // this is from the spec, I don't think it proves much.. void TestQJsonRpcMessage::positionalParameters() { const char *first = "{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}"; QJsonObject firstObject = QJsonDocument::fromJson(first).object(); const char *second = "{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [23, 42], \"id\": 2}"; QJsonObject secondObject = QJsonDocument::fromJson(second).object(); QVERIFY2(firstObject.value("params").toArray() != secondObject.value("params").toArray(), "params should maintain order"); } void TestQJsonRpcMessage::equivalence_data() { QTest::addColumn<QJsonRpcMessage>("lhs"); QTest::addColumn<QJsonRpcMessage>("rhs"); QTest::addColumn<bool>("equal"); QJsonRpcMessage invalid; { // REQUESTS const char *simpleData = "{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"request\" }"; QJsonRpcMessage simpleRequest = QJsonRpcMessage::fromJson(simpleData); QJsonRpcMessage simpleRequestCopyCtor(simpleRequest); QJsonRpcMessage simpleRequestEqualsOp = simpleRequest; const char *withParametersData = "{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"request\", \"params\": [\"with\", \"parameters\"]}"; QJsonRpcMessage simpleRequestWithParameters = QJsonRpcMessage::fromJson(withParametersData); const char *withNamedParametersData = "{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"request\", \"params\": {\"firstName\": \"yogi\", \"lastName\": \"thebear\"}}"; QJsonRpcMessage simpleRequestWithNamedParameters = QJsonRpcMessage::fromJson(withNamedParametersData); QTest::newRow("simpleRequestCopiesEqual_1") << simpleRequest << simpleRequestCopyCtor << true; QTest::newRow("simpleRequestCopiesEqual_2") << simpleRequest << simpleRequestEqualsOp << true; QTest::newRow("simpleRequestAndSimpleRequestWithParamsNotEqual") << simpleRequest << simpleRequestWithParameters << false; QTest::newRow("simpleRequestAndSimpleRequestWithNamedParamsNotEqual") << simpleRequest << simpleRequestWithNamedParameters << false; QTest::newRow("requestWithParamsNotEqualWithNamedParameters") << simpleRequestWithParameters << simpleRequestWithNamedParameters << false; QTest::newRow("simpleRequestNotEqualInvalid") << simpleRequest << invalid << false; } { // NOTIFICATIONS QJsonRpcMessage simpleNotification = QJsonRpcMessage::createNotification("notification"); QJsonRpcMessage simpleNotificationCopyCtor(simpleNotification); QJsonRpcMessage simpleNotificationEqualsOp = simpleNotification; QJsonArray params; params.append(QLatin1String("yogi")); params.append(QLatin1String("thebear")); QJsonRpcMessage simpleNotificationWithParams = QJsonRpcMessage::createNotification("notification", params); QJsonObject namedParameters; namedParameters.insert("firstName", QLatin1String("yogi")); namedParameters.insert("lastName", QLatin1String("thebear")); QJsonRpcMessage simpleNotificationWithNamedParameters = QJsonRpcMessage::createNotification("notification", namedParameters); QTest::newRow("simpleNotificationCopiesEqual_1") << simpleNotification << simpleNotificationCopyCtor << true; QTest::newRow("simpleNotificationCopiesEqual_2") << simpleNotification << simpleNotificationEqualsOp << true; QTest::newRow("simpleNotificationNotEqualNotificationWithParams") << simpleNotification << simpleNotificationWithParams << false; QTest::newRow("simpleNotificationNotEqualNotificationWithNamedParameters") << simpleNotification << simpleNotificationWithNamedParameters << false; QTest::newRow("notificationWithParamsNotEqualWithNamedParameters") << simpleNotificationWithParams << simpleNotificationWithNamedParameters << false; QTest::newRow("simpleNotificationNotEqualInvalid") << simpleNotification << invalid << false; } { // ERRORS QJsonRpcMessage basicRequest = QJsonRpcMessage::createRequest("blah", QLatin1String("first")); QJsonRpcMessage lhs = basicRequest.createErrorResponse(QJsonRpc::InternalError, "some error"); QJsonRpcMessage rhs = basicRequest.createErrorResponse(QJsonRpc::InternalError, "some error"); QJsonRpcMessage invalidRhs = basicRequest.createErrorResponse(QJsonRpc::InvalidRequest, "some error"); QTest::newRow("errorResponseEqual") << lhs << rhs << true; QTest::newRow("errorResponseNotEqual") << lhs << invalidRhs << false; } } void TestQJsonRpcMessage::equivalence() { QFETCH(QJsonRpcMessage, lhs); QFETCH(QJsonRpcMessage, rhs); QFETCH(bool, equal); if (equal) QCOMPARE(lhs, rhs); else QVERIFY(lhs != rhs); } void TestQJsonRpcMessage::withVariantListArgs() { const char *varListArgsFormat = "{ " \ "\"id\": %1, " \ "\"jsonrpc\": \"2.0\", " \ "\"method\": \"service.variantListParameter\", " \ "\"params\": [[ 1, 20, \"hello\", false ]] " \ "}"; QVariantList firstParameter; firstParameter << 1 << 20 << "hello" << false; QJsonArray params; params.append(QJsonArray::fromVariantList(firstParameter)); QJsonRpcMessage requestFromQJsonRpc = QJsonRpcMessage::createRequest("service.variantListParameter", params); // QJsonRpcMessage::createRequest is creating objects with an unique id, // and to allow a random test execution order - json data must have the same id int id = requestFromQJsonRpc.id(); QByteArray varListArgs = QString(varListArgsFormat).arg(id).toLatin1(); QJsonRpcMessage requestFromData = QJsonRpcMessage::fromJson(varListArgs); QCOMPARE(requestFromQJsonRpc, requestFromData); } void TestQJsonRpcMessage::idSentAsString() { const char *messageWithStringId = "{ " \ "\"id\": \"%1\", " \ "\"jsonrpc\": \"2.0\", " \ "\"method\": \"service.someMethod\", " \ "\"params\": [[ 1, 20, \"hello\", false ]] " \ "}"; const char *errorMessageWithStringId = "{ " \ "\"id\": \"%1\", " \ "\"jsonrpc\": \"2.0\", " \ "\"error\": { \"code\": \"-32601\", \"data\": null } " \ "}"; QVariantList firstParameter; firstParameter << 1 << 20 << "hello" << false; QJsonArray params; params.append(QJsonArray::fromVariantList(firstParameter)); QJsonRpcMessage requestFromQJsonRpc = QJsonRpcMessage::createRequest("service.someMethod", params); int id = requestFromQJsonRpc.id(); QByteArray messageData = QString(messageWithStringId).arg(id).toLatin1(); QJsonRpcMessage requestFromData = QJsonRpcMessage::fromJson(messageData); QJsonRpcMessage errorFromQJsonRpc = requestFromQJsonRpc.createErrorResponse(QJsonRpc::MethodNotFound); QByteArray errorData = QString(errorMessageWithStringId).arg(id).toLatin1(); QJsonRpcMessage errorFromData = QJsonRpcMessage::fromJson(errorData); QCOMPARE(requestFromQJsonRpc, requestFromData); QCOMPARE(errorFromQJsonRpc, errorFromData); } QTEST_MAIN(TestQJsonRpcMessage) #include "tst_qjsonrpcmessage.moc"
13,666
C++
.cpp
290
41.355172
139
0.708959
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,230
testhttpserver.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpchttpclient/testhttpserver.cpp
#include <QtTest> #include <QPointer> #include <QTcpSocket> #include "http_parser.h" #include "testhttpserver.h" class TestHttpServerPrivate { public: TestHttpServerPrivate(); virtual ~TestHttpServerPrivate(); // http parsing http_parser *httpParser; http_parser_settings httpParserSettings; QByteArray currentHeaderField; QByteArray currentHeaderValue; static int onMessageBegin(http_parser *parser); static int onUrl(http_parser *parser, const char *at, size_t length); static int onHeaderField(http_parser *parser, const char *at, size_t length); static int onHeaderValue(http_parser *parser, const char *at, size_t length); static int onHeadersComplete(http_parser *parser); static int onBody(http_parser *parser, const char *at, size_t length); static int onMessageComplete(http_parser *parser); // private slots void _q_socketReadyRead(); void _q_socketError(QAbstractSocket::SocketError error); void _q_handleRequest(); TestHttpServerRequestHandler *requestHandler; QPointer<QTcpSocket> socket; QNetworkAccessManager::Operation operation; QNetworkRequest request; QByteArray body; }; TestHttpServerPrivate::TestHttpServerPrivate() : httpParser(0), requestHandler(0) { // initialize request parser httpParser = (http_parser*)malloc(sizeof(http_parser)); http_parser_init(httpParser, HTTP_REQUEST); httpParserSettings.on_message_begin = onMessageBegin; httpParserSettings.on_url = onUrl; httpParserSettings.on_header_field = onHeaderField; httpParserSettings.on_header_value = onHeaderValue; httpParserSettings.on_headers_complete = onHeadersComplete; httpParserSettings.on_body = onBody; httpParserSettings.on_message_complete = onMessageComplete; httpParser->data = this; } TestHttpServerPrivate::~TestHttpServerPrivate() { free(httpParser); } int TestHttpServerPrivate::onMessageBegin(http_parser *parser) { TestHttpServerPrivate *priv = (TestHttpServerPrivate *)parser->data; priv->request = QNetworkRequest(); priv->currentHeaderField.clear(); priv->currentHeaderValue.clear(); priv->body.clear(); return 0; } int TestHttpServerPrivate::onUrl(http_parser *parser, const char *at, size_t length) { TestHttpServerPrivate *priv = (TestHttpServerPrivate *)parser->data; QUrl requestUrl = priv->request.url(); requestUrl.setPath(QByteArray(at, length)); priv->request.setUrl(requestUrl); return 0; } int TestHttpServerPrivate::onHeaderField(http_parser *parser, const char *at, size_t length) { TestHttpServerPrivate *priv = (TestHttpServerPrivate *)parser->data; if (!priv->currentHeaderField.isEmpty() && !priv->currentHeaderValue.isEmpty()) { priv->request.setRawHeader(priv->currentHeaderField, priv->currentHeaderValue); priv->currentHeaderField.clear(); priv->currentHeaderValue.clear(); } priv->currentHeaderField.append(at, length); return 0; } int TestHttpServerPrivate::onHeaderValue(http_parser *parser, const char *at, size_t length) { TestHttpServerPrivate *priv = (TestHttpServerPrivate *)parser->data; priv->currentHeaderValue.append(at, length); return 0; } int TestHttpServerPrivate::onHeadersComplete(http_parser *parser) { Q_UNUSED(parser); return 0; } int TestHttpServerPrivate::onBody(http_parser *parser, const char *at, size_t length) { TestHttpServerPrivate *priv = (TestHttpServerPrivate *)parser->data; priv->body.append(at, length); return 0; } int TestHttpServerPrivate::onMessageComplete(http_parser *parser) { TestHttpServerPrivate *priv = (TestHttpServerPrivate *)parser->data; switch (parser->method) { case HTTP_HEAD: priv->operation = QNetworkAccessManager::HeadOperation; break; case HTTP_GET: priv->operation = QNetworkAccessManager::GetOperation; break; case HTTP_PUT: priv->operation = QNetworkAccessManager::PutOperation; break; case HTTP_POST: priv->operation = QNetworkAccessManager::PostOperation; break; case HTTP_DELETE: priv->operation = QNetworkAccessManager::DeleteOperation; break; default: priv->operation = QNetworkAccessManager::CustomOperation; break; } priv->_q_handleRequest(); return 0; } void TestHttpServerPrivate::_q_socketReadyRead() { Q_ASSERT(httpParser); Q_ASSERT(!socket.isNull()); QByteArray buffer = socket->readAll(); http_parser_execute(httpParser, &httpParserSettings, buffer.constData(), buffer.size()); } void TestHttpServerPrivate::_q_socketError(QAbstractSocket::SocketError error) { Q_UNUSED(error) Q_ASSERT(!socket.isNull()); socket->close(); socket->deleteLater(); } void TestHttpServerPrivate::_q_handleRequest() { if (!requestHandler) { qDebug() << Q_FUNC_INFO << "no request handler installed"; return; } QByteArray response = requestHandler->handleRequest(operation, request, body); QCOMPARE(socket->write(response), (qint64)response.size()); } class TestHttpServerSimpleRequestHandler : public TestHttpServerRequestHandler { public: explicit TestHttpServerSimpleRequestHandler(const QByteArray &d) : data(d) { } virtual QByteArray handleRequest(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, const QByteArray &body) { Q_UNUSED(operation); Q_UNUSED(request); Q_UNUSED(body); return data; } private: QByteArray data; }; TestHttpServer::TestHttpServer(QObject *parent) : QTcpServer(parent), d_ptr(new TestHttpServerPrivate) { } TestHttpServer::TestHttpServer(TestHttpServerRequestHandler *requestHandler, QObject *parent) : QTcpServer(parent), d_ptr(new TestHttpServerPrivate) { d_func()->requestHandler = requestHandler; } TestHttpServer::~TestHttpServer() { Q_D(TestHttpServer); if (d->requestHandler) { delete d->requestHandler; d->requestHandler = 0; } } TestHttpServerRequestHandler *TestHttpServer::requestHandler() const { Q_D(const TestHttpServer); return d->requestHandler; } void TestHttpServer::setRequestHandler(TestHttpServerRequestHandler *requestHandler) { Q_D(TestHttpServer); if (d->requestHandler) { delete d->requestHandler; d->requestHandler = 0; } d->requestHandler = requestHandler; } void TestHttpServer::setResponseData(const QByteArray &data) { setRequestHandler(new TestHttpServerSimpleRequestHandler(data)); } #if QT_VERSION >= 0x050000 void TestHttpServer::incomingConnection(qintptr socketDescriptor) #else void TestHttpServer::incomingConnection(int socketDescriptor) #endif { Q_D(TestHttpServer); d->socket = new QTcpSocket(this); QVERIFY(d->socket->setSocketDescriptor(socketDescriptor)); connect(d->socket.data(), SIGNAL(readyRead()), this, SLOT(_q_socketReadyRead())); connect(d->socket.data(), SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(_q_socketError(QAbstractSocket::SocketError))); } #include "moc_testhttpserver.cpp"
7,234
C++
.cpp
215
29.139535
93
0.734536
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,231
tst_qjsonrpchttpclient.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpchttpclient/tst_qjsonrpchttpclient.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QtTest/QtTest> #include "testhttpserver.h" #include "qjsonrpcmessage.h" #include "qjsonrpchttpclient.h" #if QT_VERSION < 0x050000 template <typename T> struct QScopedPointerObjectDeleteLater { static inline void cleanup(T *pointer) { if (pointer) pointer->deleteLater(); } }; class QObject; typedef QScopedPointerObjectDeleteLater<QObject> QScopedPointerDeleteLater; #endif class TestQJsonRpcHttpClient : public QObject { Q_OBJECT private Q_SLOTS: void init(); void properties(); void basicRequest(); void invalidResponse_data(); void invalidResponse(); void connectionRefused(); void requestTimedOut(); void issue23_doubleFinishedEmitted(); }; void TestQJsonRpcHttpClient::init() { } class JsonRpcRequestHandler : public TestHttpServerRequestHandler { public: virtual QByteArray handleRequest(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, const QByteArray &body) { Q_UNUSED(operation) Q_UNUSED(request) QJsonRpcMessage requestMessage = QJsonRpcMessage::fromJson(body); QJsonRpcMessage responseMessage = requestMessage.createResponse(QLatin1String("some response data")); QByteArray responseData = responseMessage.toJson(); QByteArray reply; reply += "HTTP/1.0 200\r\n"; reply += "Content-Type: application/json\r\n"; reply += "Content-length: " + QByteArray::number(responseData.size()) + "\r\n"; reply += "\r\n"; reply += responseData; return reply; } }; void TestQJsonRpcHttpClient::properties() { QJsonRpcHttpClient client; client.setEndPoint("testing"); QCOMPARE(client.endPoint(), QUrl("http://testing")); client.setEndPoint(QUrl("http://www.google.com")); QCOMPARE(client.endPoint(), QUrl("http://www.google.com")); QNetworkAccessManager manager; QJsonRpcHttpClient withManager(&manager); QCOMPARE(withManager.networkAccessManager(), &manager); } void TestQJsonRpcHttpClient::basicRequest() { TestHttpServer server; server.setRequestHandler(new JsonRpcRequestHandler); QVERIFY(server.listen()); QString url = QString("%1://localhost:%2").arg("http").arg(server.serverPort()); QJsonRpcHttpClient client(url); QJsonRpcMessage message = QJsonRpcMessage::createRequest("testMethod"); QJsonRpcMessage response = client.sendMessageBlocking(message); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(response.result().toString(), QLatin1String("some response data")); } void TestQJsonRpcHttpClient::invalidResponse_data() { QTest::addColumn<QByteArray>("responseData"); QTest::addColumn<QJsonRpc::ErrorCode>("expectedError"); QTest::newRow("empty-data") << QByteArray("HTTP/1.0 200\r\nContent-Type: application/json\r\nContent-length: 0\r\n\r\n") << QJsonRpc::ParseError; QTest::newRow("invalid-json") << QByteArray("HTTP/1.0 200\r\nContent-Type: application/json\r\nContent-length: 2\r\n\r\n{}") << QJsonRpc::InternalError; } void TestQJsonRpcHttpClient::invalidResponse() { QFETCH(QByteArray, responseData); QFETCH(QJsonRpc::ErrorCode, expectedError); TestHttpServer server; server.setResponseData(responseData); QVERIFY(server.listen()); QString url = QString("%1://localhost:%2").arg("http").arg(server.serverPort()); QJsonRpcHttpClient client(url); QJsonRpcMessage message = QJsonRpcMessage::createRequest("someMethod"); QJsonRpcMessage response = client.sendMessageBlocking(message); QCOMPARE(response.type(), QJsonRpcMessage::Error); QCOMPARE(response.errorCode(), int(expectedError)); } void TestQJsonRpcHttpClient::connectionRefused() { QString url = QString("%1://localhost:%2").arg("http").arg(9191); QJsonRpcHttpClient client(url); QJsonRpcMessage message = QJsonRpcMessage::createRequest("someMethod"); QJsonRpcMessage response = client.sendMessageBlocking(message); QCOMPARE(response.type(), QJsonRpcMessage::Error); QCOMPARE(response.errorCode(), int(QJsonRpc::InternalError)); } void TestQJsonRpcHttpClient::requestTimedOut() { TestHttpServer server; server.setResponseData("HTTP/1.0 200\r\n\r\n"); QVERIFY(server.listen()); QString url = QString("%1://localhost:%2").arg("http").arg(server.serverPort()); QJsonRpcHttpClient client(url); QJsonRpcMessage message = QJsonRpcMessage::createRequest("someMethod"); QJsonRpcMessage response = client.sendMessageBlocking(message, 1); QCOMPARE(response.type(), QJsonRpcMessage::Error); QCOMPARE(response.errorCode(), int(QJsonRpc::TimeoutError)); } void TestQJsonRpcHttpClient::issue23_doubleFinishedEmitted() { QString url = QString("%1://localhost:%2").arg("http").arg(9191); QJsonRpcHttpClient client(url); QJsonRpcMessage message = QJsonRpcMessage::createRequest("someMethod"); QJsonRpcServiceReply *reply = client.sendMessage(message); QScopedPointer<QJsonRpcServiceReply> replyPtr(reply); QSignalSpy spy(reply, SIGNAL(finished())); QEventLoop responseLoop; connect(reply, SIGNAL(finished()), &responseLoop, SLOT(quit())); QTimer::singleShot(10000, &responseLoop, SLOT(quit())); responseLoop.exec(); QJsonRpcMessage response = reply->response(); QCOMPARE(response.type(), QJsonRpcMessage::Error); QCOMPARE(response.errorCode(), int(QJsonRpc::InternalError)); QCOMPARE(spy.size(), 1); } QTEST_MAIN(TestQJsonRpcHttpClient) #include "tst_qjsonrpchttpclient.moc"
6,248
C++
.cpp
155
35.954839
127
0.737189
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,232
tst_issue22.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/issue22/tst_issue22.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QLocalSocket> #include <QTcpSocket> #include <QScopedPointer> #include <QtCore/QEventLoop> #include <QtCore/QVariant> #include <QtTest/QtTest> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpcabstractserver.h" #include "qjsonrpctcpserver.h" #include "qjsonrpcsocket.h" #include "qjsonrpcmessage.h" #include "signalspy.h" class TestIssue22: public QObject { Q_OBJECT public: TestIssue22(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); void testIssue21(); private: QThread serverThread; QScopedPointer<QJsonRpcTcpServer> tcpServer; quint16 tcpServerPort; }; TestIssue22::TestIssue22() { tcpServerPort = quint16(8118 + qrand() % 1000); } void TestIssue22::initTestCase() { serverThread.start(); } void TestIssue22::cleanupTestCase() { serverThread.quit(); QVERIFY(serverThread.wait()); } void TestIssue22::init() { tcpServer.reset(new QJsonRpcTcpServer); QVERIFY(tcpServer->listen(QHostAddress::LocalHost, tcpServerPort)); tcpServer->moveToThread(&serverThread); } void TestIssue22::cleanup() { tcpServer->close(); } class Issue21Service : public QJsonRpcService { Q_OBJECT Q_CLASSINFO("serviceName", "service") public: Issue21Service(QObject *parent = 0) : QJsonRpcService(parent) {} public Q_SLOTS: QString fastMethod(const QString &name) { QEventLoop loop; QTimer::singleShot(150, &loop, SLOT(quit())); loop.exec(); return QString("fast %1").arg(name); } QString slowMethod(const QString &name) { QEventLoop loop; QTimer::singleShot(2000, &loop, SLOT(quit())); loop.exec(); return QString("slow %1").arg(name); } }; class TestClientRunnable : public QObject, public QRunnable { Q_OBJECT public: TestClientRunnable(bool slow, quint16 port) : m_slow(slow), m_port(port) { setAutoDelete(true); } virtual void run() { QTcpSocket socket; socket.connectToHost(QHostAddress::LocalHost, m_port); QVERIFY(socket.waitForConnected()); // run tests QJsonRpcSocket client(&socket); QJsonRpcMessage request = m_slow ? QJsonRpcMessage::createRequest("service.slowMethod", QLatin1String("slow")) : QJsonRpcMessage::createRequest("service.fastMethod", QLatin1String("fast")); QJsonRpcMessage response = client.sendMessageBlocking(request); Q_EMIT messageReceived(request, response); socket.disconnectFromHost(); } Q_SIGNALS: void messageReceived(const QJsonRpcMessage &request, const QJsonRpcMessage &response); private: bool m_slow; quint16 m_port; QJsonRpcMessage m_message; }; void TestIssue22::testIssue21() { QVERIFY(tcpServer->addService(new Issue21Service)); TestClientRunnable *fastClient = new TestClientRunnable(false, tcpServerPort); SignalSpy fastClientSpy(fastClient, SIGNAL(messageReceived(QJsonRpcMessage, QJsonRpcMessage))); TestClientRunnable *slowClient = new TestClientRunnable(true, tcpServerPort); SignalSpy slowClientSpy(slowClient, SIGNAL(messageReceived(QJsonRpcMessage, QJsonRpcMessage))); QThreadPool::globalInstance()->setMaxThreadCount(10); QThreadPool::globalInstance()->start(fastClient); QThreadPool::globalInstance()->start(slowClient); fastClientSpy.wait(); slowClientSpy.wait(); QCOMPARE(fastClientSpy.length(), slowClientSpy.length()); QList<QVariant> fastClientPair = fastClientSpy.first(); QJsonRpcMessage fastRequest = fastClientPair.at(0).value<QJsonRpcMessage>(); QJsonRpcMessage fastResponse = fastClientPair.at(1).value<QJsonRpcMessage>(); QCOMPARE(fastRequest.id(), fastResponse.id()); QList<QVariant> slowClientPair = slowClientSpy.first(); QJsonRpcMessage slowRequest = slowClientPair.at(0).value<QJsonRpcMessage>(); QJsonRpcMessage slowResponse = slowClientPair.at(1).value<QJsonRpcMessage>(); QCOMPARE(slowRequest.id(), slowResponse.id()); } QTEST_MAIN(TestIssue22) #include "tst_issue22.moc"
4,844
C++
.cpp
146
29.130137
99
0.736932
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,233
tst_qjsonrpcservice.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpcservice/tst_qjsonrpcservice.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QtCore/QVariant> #include <QtTest/QtTest> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpcabstractserver.h" #include "qjsonrpcmessage.h" #include "qjsonrpcservice.h" class TestQJsonRpcService: public QObject { Q_OBJECT private slots: void dispatch_data(); void dispatch(); void ambiguousDispatch(); void dispatchSignals_data(); void dispatchSignals(); }; class TestService : public QJsonRpcService { Q_OBJECT Q_CLASSINFO("serviceName", "service") public: TestService(QObject *parent = 0) : QJsonRpcService(parent), m_stringCount(0), m_intCount(0), m_variantCount(0) {} QJsonRpcMessage testDispatch(const QJsonRpcMessage &message) { return QJsonRpcService::dispatch(message); } int stringCount() const { return m_stringCount; } int intCount() const { return m_intCount; } int variantCount() const { return m_variantCount; } void resetCounters() { m_stringCount = m_intCount = m_variantCount = 0; } Q_SIGNALS: void testSignal(); void testSignalWithParameter(const QString &param); public Q_SLOTS: QString testMethod(const QString &string) const { return string; } // note: order of definition matters here for ambiguousDispatch test void ambiguousMethod(const QString &) { m_stringCount++; } void ambiguousMethod(int) { m_intCount++; } void ambiguousMethod(const QVariant &) { m_variantCount++; } private: int m_stringCount; int m_intCount; int m_variantCount; }; class TestServiceProvider : public QJsonRpcServiceProvider { public: TestServiceProvider() {} }; void TestQJsonRpcService::dispatch_data() { QTest::addColumn<QJsonRpcMessage>("request"); QTest::addColumn<bool>("shouldSucceed"); { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.testMethod", QLatin1String("testParam")); QTest::newRow("valid-request-dispatch") << request << true; QJsonRpcMessage response = request.createResponse(QLatin1String("testResult")); QTest::newRow("invalid-response-dispatch") << response << false; } { QJsonObject namedParameters; namedParameters.insert("string", QLatin1String("testParam")); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.testMethod", namedParameters); QTest::newRow("valid-request-dispatch-with-named-parameters") << request << true; } { QJsonObject invalidNamedParameters; invalidNamedParameters.insert("testParameter", QLatin1String("testParam")); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.testMethod", invalidNamedParameters); QTest::newRow("invalid-request-dispatch-with-named-parameters") << request << false; } { QJsonRpcMessage request = QJsonRpcMessage::createNotification("service.testMethod", QLatin1String("testParam")); QTest::newRow("valid-notification-dispatch") << request << true; } { QJsonObject namedParameters; namedParameters.insert("string", QLatin1String("testParam")); QJsonRpcMessage request = QJsonRpcMessage::createNotification("service.testMethod", namedParameters); QTest::newRow("valid-notification-dispatch-with-named-parameters") << request << true; } QTest::newRow("invalid-dispatch") << QJsonRpcMessage() << false; } void TestQJsonRpcService::dispatch() { QFETCH(QJsonRpcMessage, request); QFETCH(bool, shouldSucceed); TestServiceProvider provider; TestService service; provider.addService(&service); QJsonRpcMessage response = service.testDispatch(request); if (shouldSucceed) QVERIFY(response.type() != QJsonRpcMessage::Error); else QVERIFY(response.type() == QJsonRpcMessage::Error); } void TestQJsonRpcService::ambiguousDispatch() { TestServiceProvider provider; TestService service; provider.addService(&service); QJsonRpcMessage stringDispatch = QJsonRpcMessage::createRequest("service.ambiguousMethod", QLatin1String("testParam")); service.testDispatch(stringDispatch); QCOMPARE(service.stringCount(), 1); QCOMPARE(service.intCount(), 0); QCOMPARE(service.variantCount(), 0); QJsonRpcMessage intDispatch = QJsonRpcMessage::createRequest("service.ambiguousMethod", 10); service.testDispatch(intDispatch); QCOMPARE(service.stringCount(), 1); QCOMPARE(service.intCount(), 1); QCOMPARE(service.variantCount(), 0); QStringList stringList = QStringList() << "test" << "string" << "list"; QJsonRpcMessage stringListDispatch = QJsonRpcMessage::createRequest("service.ambiguousMethod", QJsonValue::fromVariant(stringList)); service.testDispatch(stringListDispatch); QCOMPARE(service.stringCount(), 1); QCOMPARE(service.intCount(), 1); QCOMPARE(service.variantCount(), 1); } void TestQJsonRpcService::dispatchSignals_data() { QTest::addColumn<QJsonRpcMessage>("request"); QTest::addColumn<bool>("shouldSucceed"); { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.testSignal"); QTest::newRow("valid-request-signal-dispatch") << request << true; } { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.testSignalWithParameter", QLatin1String("testParam")); QTest::newRow("valid-request-signal-with-param-dispatch") << request << true; } { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.testSignal", QLatin1String("testParam")); QTest::newRow("invalid-request-signal-dispatch") << request << false; } } void TestQJsonRpcService::dispatchSignals() { QFETCH(QJsonRpcMessage, request); QFETCH(bool, shouldSucceed); TestServiceProvider provider; TestService service; provider.addService(&service); QJsonRpcMessage response = service.testDispatch(request); QJsonRpcMessage::Type messageType = shouldSucceed ? QJsonRpcMessage::Response : QJsonRpcMessage::Error; QCOMPARE(response.type(), messageType); } QTEST_MAIN(TestQJsonRpcService) #include "tst_qjsonrpcservice.moc"
7,046
C++
.cpp
191
31.685864
106
0.718204
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,234
tst_qjsonrpchttpserver.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpchttpserver/tst_qjsonrpchttpserver.cpp
#include <QtCore/QEventLoop> #include <QtCore/QVariant> #include <QtTest/QtTest> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpchttpclient.h" #include "qjsonrpcservice.h" #include "qjsonrpchttpserver.h" #include "qjsonrpcmessage.h" class TestQJsonRpcHttpServer: public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void quickTest(); void statusCodes_data(); void statusCodes(); void invalidMethod_data(); void invalidMethod(); void missingHeaders_data(); void missingHeaders(); void testAccessControlHeader(); void testMissingAccessControlHeader(); private: // temporarily disabled void sslTest(); private: QSslConfiguration serverSslConfiguration; QSslConfiguration clientSslConfiguration; }; Q_DECLARE_METATYPE(QNetworkAccessManager::Operation) class TestService : public QJsonRpcService { Q_OBJECT Q_CLASSINFO("serviceName", "service") public: TestService(QObject *parent = 0) : QJsonRpcService(parent), m_called(0) {} void resetCount() { m_called = 0; } int callCount() const { return m_called; } public Q_SLOTS: void noParam() const {} QString singleParam(const QString &string) const { return string; } QString multipleParam(const QString &first, const QString &second, const QString &third) const { return first + second + third; } void numberParameters(int intParam, double doubleParam, float floatParam) { Q_UNUSED(intParam) Q_UNUSED(doubleParam) Q_UNUSED(floatParam) } bool variantParameter(const QVariant &variantParam) const { return variantParam.toBool(); } QVariant variantStringResult() { return "hello"; } QVariantList variantListResult() { return QVariantList() << "one" << 2 << 3.0; } QVariantMap variantMapResult() { QVariantMap result; result["one"] = 1; result["two"] = 2.0; return result; } void increaseCalled() { m_called++; } private: int m_called; }; void TestQJsonRpcHttpServer::initTestCase() { // setup ssl configuration for tests QList<QSslCertificate> caCerts = QSslCertificate::fromPath(QLatin1String(":/certs/qt-test-server-cacert.pem")); serverSslConfiguration.setCaCertificates(caCerts); serverSslConfiguration.setProtocol(QSsl::AnyProtocol); } void TestQJsonRpcHttpServer::quickTest() { QJsonRpcHttpServer server; server.addService(new TestService); QVERIFY(server.listen(QHostAddress::LocalHost, 8118)); QJsonRpcHttpClient client; client.setEndPoint("http://127.0.0.1:8118"); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam"); QJsonRpcMessage response = client.sendMessageBlocking(request); QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(request.id(), response.id()); } void TestQJsonRpcHttpServer::sslTest() { QJsonRpcHttpServer server; server.setSslConfiguration(serverSslConfiguration); server.addService(new TestService); server.listen(QHostAddress::LocalHost, 8118); QJsonRpcHttpClient client; client.setEndPoint("http://127.0.0.1:8118"); client.setSslConfiguration(serverSslConfiguration); QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam"); QJsonRpcMessage response = client.sendMessageBlocking(request); qDebug() << response; QVERIFY(response.type() != QJsonRpcMessage::Error); QCOMPARE(request.id(), response.id()); } void TestQJsonRpcHttpServer::statusCodes_data() { QTest::addColumn<QByteArray>("body"); QTest::addColumn<int>("statusCode"); QTest::addColumn<QByteArray>("statusReason"); QTest::addColumn<QByteArray>("contentType"); { QJsonRpcMessage invalidMethod = QJsonRpcMessage::createRequest("invalidMethod"); QTest::newRow("404-not-found") << invalidMethod.toJson() << 404 << QByteArray("Not Found") << QByteArray("application/json"); } { QTest::newRow("400-bad-request") << QByteArray("{\"jsonrpc\": \"2.0\", \"id\": 666}") << 400 << QByteArray("Bad Request") << QByteArray("application/json"); } { QJsonRpcMessage invalidParameters = QJsonRpcMessage::createRequest("service.numberParameters", false); QTest::newRow("500-internal-server-error") << invalidParameters.toJson() << 500 << QByteArray("Internal Server Error") << QByteArray("application/json"); } { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam"); QTest::newRow("200-ok") << request.toJson() << 200 << QByteArray("OK") << QByteArray("application/json"); } { QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam"); QTest::newRow("200-composite-content-type") << request.toJson() << 200 << QByteArray("OK") << QByteArray("application/json;charset=UTF-8"); } /* * TODO: support notifications { QJsonRpcMessage notification = QJsonRpcMessage::createNotification("service.noParam"); QTest::newRow("204-no-content") << notification.toJson() << 204 << QByteArray("No Content") << QByteArray("OK") << QByteArray("application/json"); } */ } void TestQJsonRpcHttpServer::statusCodes() { QFETCH(QByteArray, body); QFETCH(int, statusCode); QFETCH(QByteArray, statusReason); QFETCH(QByteArray, contentType); QJsonRpcHttpServer server; server.addService(new TestService); QVERIFY(server.listen(QHostAddress::LocalHost, 8118)); QNetworkAccessManager manager; QNetworkRequest request(QUrl("http://127.0.0.1:8118")); request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); request.setRawHeader("Accept", "application/json-rpc"); QScopedPointer<QNetworkReply> reply(manager.post(request, body)); connect(reply.data(), SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); connect(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), &QTestEventLoop::instance(), SLOT(exitLoop())); QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode); QCOMPARE(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray(), statusReason); } void TestQJsonRpcHttpServer::invalidMethod_data() { QTest::addColumn<QNetworkAccessManager::Operation>("operation"); QTest::newRow("head-request") << QNetworkAccessManager::HeadOperation; QTest::newRow("put-request") << QNetworkAccessManager::PutOperation; QTest::newRow("delete-request") << QNetworkAccessManager::DeleteOperation; } void TestQJsonRpcHttpServer::invalidMethod() { QJsonRpcHttpServer server; server.addService(new TestService); QVERIFY(server.listen(QHostAddress::LocalHost, 8118)); QNetworkAccessManager manager; QNetworkRequest request(QUrl("http://127.0.0.1:8118")); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setRawHeader("Accept", "application/json-rpc"); QJsonRpcMessage requestMessage = QJsonRpcMessage::createRequest("service.noParam"); QScopedPointer<QNetworkReply> reply; QFETCH(QNetworkAccessManager::Operation, operation); switch (operation) { case QNetworkAccessManager::HeadOperation: reply.reset(manager.head(request)); break; case QNetworkAccessManager::PutOperation: reply.reset(manager.put(request, requestMessage.toJson())); break; case QNetworkAccessManager::DeleteOperation: reply.reset(manager.deleteResource(request)); break; default: QFAIL("untested operation"); } connect(reply.data(), SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); connect(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), &QTestEventLoop::instance(), SLOT(exitLoop())); QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 405); QCOMPARE(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray(), QByteArray("Method Not Allowed")); } void TestQJsonRpcHttpServer::missingHeaders_data() { QTest::addColumn<QNetworkRequest>("request"); { QNetworkRequest request(QUrl("http://127.0.0.1:8118")); request.setRawHeader("Accept", "application/json-rpc"); QTest::newRow("no-content-type") << request; } { QNetworkRequest request(QUrl("http://127.0.0.1:8118")); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QTest::newRow("no-accept") << request; } { QNetworkRequest request(QUrl("http://127.0.0.1:8118")); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setRawHeader("Accept", "application/invalid"); QTest::newRow("no-invalid-accept") << request; } { QNetworkRequest request(QUrl("http://127.0.0.1:8118")); QTest::newRow("no-jsonpc-headers") << request; } } void TestQJsonRpcHttpServer::missingHeaders() { QJsonRpcHttpServer server; server.addService(new TestService); QVERIFY(server.listen(QHostAddress::LocalHost, 8118)); QFETCH(QNetworkRequest, request); QNetworkAccessManager manager; QJsonRpcMessage requestMessage = QJsonRpcMessage::createRequest("service.noParam"); QScopedPointer<QNetworkReply> reply(manager.post(request, requestMessage.toJson())); connect(reply.data(), SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); connect(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), &QTestEventLoop::instance(), SLOT(exitLoop())); QTestEventLoop::instance().enterLoop(5); QVERIFY(!QTestEventLoop::instance().timeout()); QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 400); QCOMPARE(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray(), QByteArray("Bad Request")); } void TestQJsonRpcHttpServer::testMissingAccessControlHeader() { QJsonRpcHttpServer server; server.addService(new TestService); QVERIFY(server.listen(QHostAddress::LocalHost, 8118)); //OPTIONS call *missing* headers on reply QNetworkAccessManager manager; QNetworkRequest request(QUrl("http://127.0.0.1:8118")); request.setRawHeader("content-type", "text/plain"); QScopedPointer<QNetworkReply> reply(manager.sendCustomRequest(request,QByteArray("OPTIONS"))); QJsonRpcMessage request_client = QJsonRpcMessage::createRequest("service.noParam"); connect(reply.data(), SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); connect(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), &QTestEventLoop::instance(), SLOT(exitLoop())); QTestEventLoop::instance().enterLoop(1); QVERIFY(!QTestEventLoop::instance().timeout()); QCOMPARE(reply->rawHeader("Access-Control-Allow-Origin"), QByteArray("")); QCOMPARE(reply->rawHeader("Access-Control-Allow-Methods"), QByteArray("")); QCOMPARE(reply->rawHeader("Access-Control-Allow-Headers"), QByteArray("")); QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); } void TestQJsonRpcHttpServer::testAccessControlHeader() { QJsonRpcHttpServer server; server.addService(new TestService); QVERIFY(server.listen(QHostAddress::LocalHost, 8118)); //OPTIONS call check headers on reply QNetworkAccessManager manager; QNetworkRequest request(QUrl("http://127.0.0.1:8118")); request.setRawHeader("access-control-request-method", "POST"); request.setRawHeader("access-control-request-headers", "accept, content-type"); request.setRawHeader("content-type", "text/plain"); request.setRawHeader("origin", "http://127.0.0.1:8118"); QScopedPointer<QNetworkReply> reply(manager.sendCustomRequest(request,QByteArray("OPTIONS"))); QJsonRpcMessage request_client = QJsonRpcMessage::createRequest("service.noParam"); connect(reply.data(), SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); connect(reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), &QTestEventLoop::instance(), SLOT(exitLoop())); QTestEventLoop::instance().enterLoop(1); QVERIFY(!QTestEventLoop::instance().timeout()); QVERIFY(reply->hasRawHeader("Access-Control-Allow-Origin")); QCOMPARE(reply->rawHeader("Access-Control-Allow-Origin"), QByteArray("http://127.0.0.1:8118")); QVERIFY(reply->hasRawHeader("Access-Control-Allow-Methods")); QCOMPARE(reply->rawHeader("Access-Control-Allow-Methods"), QByteArray("POST")); QVERIFY(reply->hasRawHeader("Access-Control-Allow-Headers")); QCOMPARE(reply->rawHeader("Access-Control-Allow-Headers"), QByteArray("accept, content-type")); } QTEST_MAIN(TestQJsonRpcHttpServer) #include "tst_qjsonrpchttpserver.moc"
13,525
C++
.cpp
310
37.664516
123
0.709778
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,235
tst_qjsonrpcsocket.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/auto/qjsonrpcsocket/tst_qjsonrpcsocket.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QLocalServer> #include <QLocalSocket> #include <QtCore/QEventLoop> #include <QtCore/QVariant> #include <QtTest/QtTest> #if QT_VERSION >= 0x050000 #include <QJsonDocument> #else #include "json/qjsondocument.h" #endif #include "qjsonrpcservice_p.h" #include "qjsonrpcservice.h" #include "qjsonrpcmessage.h" #include "qjsonrpcservicereply.h" #include "qjsonrpcsocket_p.h" #include "qjsonrpcsocket.h" class QBufferBackedQJsonRpcSocketPrivate : public QJsonRpcSocketPrivate { public: QBufferBackedQJsonRpcSocketPrivate(QBuffer *b, QJsonRpcSocket *q) : QJsonRpcSocketPrivate(q), buffer(b) { device = b; } virtual void _q_processIncomingData() { buffer->seek(0); QJsonRpcSocketPrivate::_q_processIncomingData(); } QBuffer *buffer; }; class QBufferBackedQJsonRpcSocket : public QJsonRpcSocket { Q_OBJECT public: QBufferBackedQJsonRpcSocket(QBuffer *buffer, QObject *parent = 0) : QJsonRpcSocket(*new QBufferBackedQJsonRpcSocketPrivate(buffer, this), parent) { } }; class TestQJsonRpcSocket: public QObject { Q_OBJECT public: enum InvokeType { SendMessage, InvokeRemoteMethod }; private Q_SLOTS: void initTestCase_data(); void noParameters(); void multiParameter(); void notification(); void response(); void delayedMessageReceive(); private: // benchmark parsing speed void jsonParsingBenchmark(); }; Q_DECLARE_METATYPE(TestQJsonRpcSocket::InvokeType) void TestQJsonRpcSocket::initTestCase_data() { QTest::addColumn<InvokeType>("invokeType"); QTest::newRow("sendMessage") << SendMessage; QTest::newRow("invokeRemoteMethod") << InvokeRemoteMethod; } void TestQJsonRpcSocket::noParameters() { QFETCH_GLOBAL(InvokeType, invokeType); QBuffer buffer; buffer.open(QIODevice::ReadWrite); QJsonRpcSocket serviceSocket(&buffer, this); QSignalSpy spyMessageReceived(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage))); QVERIFY(serviceSocket.isValid()); QJsonRpcMessage request; QScopedPointer<QJsonRpcServiceReply> reply; if (invokeType == SendMessage) { request = QJsonRpcMessage::createRequest(QString("test.noParam")); reply.reset(serviceSocket.sendMessage(request)); } else if (invokeType == InvokeRemoteMethod) { reply.reset(serviceSocket.invokeRemoteMethod("test.noParam")); request = reply->request(); } QJsonRpcMessage bufferMessage = QJsonRpcMessage::fromJson(buffer.data()); QCOMPARE(request.id(), bufferMessage.id()); QCOMPARE(request.type(), bufferMessage.type()); QCOMPARE(request.method(), bufferMessage.method()); QCOMPARE(request.params(), bufferMessage.params()); QCOMPARE(spyMessageReceived.count(), 0); } void TestQJsonRpcSocket::multiParameter() { QFETCH_GLOBAL(InvokeType, invokeType); QBuffer buffer; buffer.open(QIODevice::ReadWrite); QJsonRpcSocket serviceSocket(&buffer, this); QSignalSpy spyMessageReceived(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage))); QVERIFY(serviceSocket.isValid()); QJsonArray params; params.append(false); params.append(true); QJsonRpcMessage request; QScopedPointer<QJsonRpcServiceReply> reply; if (invokeType == SendMessage) { request = QJsonRpcMessage::createRequest("test.multiParam", params); reply.reset(serviceSocket.sendMessage(request)); } else if (invokeType == InvokeRemoteMethod) { #if QT_VERSION <= 0x050000 QVariant paramsVariant = QVariant::fromValue(params); reply.reset(serviceSocket.invokeRemoteMethod("test.multiParam", paramsVariant)); #else reply.reset(serviceSocket.invokeRemoteMethod("test.multiParam", params)); #endif request = reply->request(); } QJsonRpcMessage bufferMessage = QJsonRpcMessage::fromJson(buffer.data()); QCOMPARE(request.id(), bufferMessage.id()); QCOMPARE(request.type(), bufferMessage.type()); QCOMPARE(request.method(), bufferMessage.method()); QCOMPARE(request.params(), bufferMessage.params()); QCOMPARE(spyMessageReceived.count(), 0); } void TestQJsonRpcSocket::notification() { QFETCH_GLOBAL(InvokeType, invokeType); QBuffer buffer; buffer.open(QIODevice::ReadWrite); QJsonRpcSocket serviceSocket(&buffer, this); QSignalSpy spyMessageReceived(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage))); QVERIFY(serviceSocket.isValid()); QJsonRpcMessage notification; QScopedPointer<QJsonRpcServiceReply> reply; if (invokeType == SendMessage) { notification = QJsonRpcMessage::createRequest("test.notify"); reply.reset(serviceSocket.sendMessage(notification)); } else if (invokeType == InvokeRemoteMethod) { reply.reset(serviceSocket.invokeRemoteMethod("test.notify")); notification = reply->request(); } QJsonRpcMessage bufferMessage = QJsonRpcMessage::fromJson(buffer.data()); QCOMPARE(notification.id(), bufferMessage.id()); QCOMPARE(notification.type(), bufferMessage.type()); QCOMPARE(notification.method(), bufferMessage.method()); QCOMPARE(notification.params(), bufferMessage.params()); QCOMPARE(spyMessageReceived.count(), 0); } void TestQJsonRpcSocket::response() { QBuffer buffer; buffer.open(QIODevice::ReadWrite); QJsonRpcSocket serviceSocket(&buffer, this); QSignalSpy spyMessageReceived(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage))); QVERIFY(serviceSocket.isValid()); QJsonRpcMessage response = QJsonRpcMessage::createRequest("test.response"); response = response.createResponse(QJsonValue()); QScopedPointer<QJsonRpcServiceReply> reply; reply.reset(serviceSocket.sendMessage(response)); QJsonRpcMessage bufferMessage = QJsonRpcMessage::fromJson(buffer.data()); QCOMPARE(response.id(), bufferMessage.id()); QCOMPARE(response.type(), bufferMessage.type()); QCOMPARE(response.method(), bufferMessage.method()); QCOMPARE(response.params(), bufferMessage.params()); QCOMPARE(spyMessageReceived.count(), 0); } void TestQJsonRpcSocket::jsonParsingBenchmark() { QFile testData(":/testwire.json"); QVERIFY(testData.open(QIODevice::ReadOnly)); QByteArray jsonData = testData.readAll(); QJsonRpcSocketPrivate socketPrivate(0); int messageCount = 0; while (!jsonData.isEmpty()) { int pos = 0; QBENCHMARK { pos = socketPrivate.findJsonDocumentEnd(jsonData); } if (pos > -1) { messageCount++; jsonData = jsonData.mid(pos + 1); } else { break; } } QCOMPARE(messageCount, 8); } void TestQJsonRpcSocket::delayedMessageReceive() { QBuffer buffer; buffer.open(QIODevice::ReadWrite); QBufferBackedQJsonRpcSocket serviceSocket(&buffer, this); QSignalSpy spyMessageReceived(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage))); QVERIFY(serviceSocket.isValid()); QJsonRpcMessage request = QJsonRpcMessage::createRequest("test.multiParam"); QJsonRpcMessage response = serviceSocket.sendMessageBlocking(request, 1); QVERIFY(response.type() == QJsonRpcMessage::Error); spyMessageReceived.removeLast(); // this should cause a crash, before the fix const char *fakeDelayedResult = "{" \ "\"id\": %1," \ "\"jsonrpc\": \"2.0\"," \ "\"result\": true" \ "}"; buffer.write(QString(fakeDelayedResult).arg(request.id()).toLatin1()); while (!spyMessageReceived.size()) qApp->processEvents(); } QTEST_MAIN(TestQJsonRpcSocket) #include "tst_qjsonrpcsocket.moc"
8,538
C++
.cpp
231
31.541126
88
0.715685
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,236
qjsonrpcservicereply.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/src/qjsonrpcservicereply.cpp
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include "qjsonrpcservicereply_p.h" #include "qjsonrpcservicereply.h" QJsonRpcServiceReply::QJsonRpcServiceReply(QObject *parent) #if defined(USE_QT_PRIVATE_HEADERS) : QObject(*new QJsonRpcServiceReplyPrivate, parent) #else : QObject(parent), d_ptr(new QJsonRpcServiceReplyPrivate) #endif { } QJsonRpcServiceReply::~QJsonRpcServiceReply() { } QJsonRpcServiceReply::QJsonRpcServiceReply(QJsonRpcServiceReplyPrivate &dd, QObject *parent) #if defined(USE_QT_PRIVATE_HEADERS) : QObject(dd, parent) #else : QObject(parent), d_ptr(&dd) #endif { } QJsonRpcMessage QJsonRpcServiceReply::request() const { Q_D(const QJsonRpcServiceReply); return d->request; } QJsonRpcMessage QJsonRpcServiceReply::response() const { Q_D(const QJsonRpcServiceReply); return d->response; }
1,481
C++
.cpp
49
27.918367
92
0.776454
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
21,242
qjsonrpcabstractserver.cpp
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/src/qjsonrpcabstractserver.cpp
#include "qjsonrpcsocket.h" #include "qjsonrpcabstractserver_p.h" #include "qjsonrpcabstractserver.h" QJsonRpcAbstractServer::~QJsonRpcAbstractServer() { } void QJsonRpcAbstractServerPrivate::_q_notifyConnectedClients(const QString &method, const QJsonArray &params) { QJsonRpcMessage notification = QJsonRpcMessage::createNotification(method, params); _q_notifyConnectedClients(notification); } void QJsonRpcAbstractServerPrivate::_q_notifyConnectedClients(const QJsonRpcMessage &message) { for (int i = 0; i < clients.size(); ++i) clients[i]->notify(message); }
657
C++
.cpp
18
30.333333
93
0.713836
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
21,255
main.cpp
visualfc_liteide/liteidex/src/3rdparty/fakevim/test/main.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "fakevimhandler.h" #include <QApplication> #include <QFontMetrics> #include <QMainWindow> #include <QMessageBox> #include <QPainter> #include <QPlainTextEdit> #include <QStatusBar> #include <QTextBlock> #include <QTextEdit> #include <QTextStream> #include <QTemporaryFile> #include <QTimer> #define EDITOR(editor, call) \ if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(editor)) { \ (ed->call); \ } else if (QTextEdit *ed = qobject_cast<QTextEdit *>(editor)) { \ (ed->call); \ } using namespace FakeVim::Internal; typedef QLatin1String _; /** * Simple editor widget. * @tparam TextEdit QTextEdit or QPlainTextEdit as base class */ template <typename TextEdit> class Editor : public TextEdit { public: Editor(QWidget *parent = 0) : TextEdit(parent) { TextEdit::setCursorWidth(0); } void paintEvent(QPaintEvent *e) { TextEdit::paintEvent(e); if ( !m_cursorRect.isNull() && e->rect().intersects(m_cursorRect) ) { QRect rect = m_cursorRect; m_cursorRect = QRect(); TextEdit::viewport()->update(rect); } // Draw text cursor. QRect rect = TextEdit::cursorRect(); if ( e->rect().intersects(rect) ) { QPainter painter(TextEdit::viewport()); if ( TextEdit::overwriteMode() ) { QFontMetrics fm(TextEdit::font()); const int position = TextEdit::textCursor().position(); const QChar c = TextEdit::document()->characterAt(position); rect.setWidth(fm.width(c)); painter.setPen(Qt::NoPen); painter.setBrush(TextEdit::palette().color(QPalette::Base)); painter.setCompositionMode(QPainter::CompositionMode_Difference); } else { rect.setWidth(TextEdit::cursorWidth()); painter.setPen(TextEdit::palette().color(QPalette::Text)); } painter.drawRect(rect); m_cursorRect = rect; } } private: QRect m_cursorRect; }; class Proxy : public QObject { Q_OBJECT public: Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0) : QObject(parent), m_widget(widget), m_mainWindow(mw) { QTimer::singleShot(0, this, SLOT(parseArguments())); } void openFile(const QString &fileName) { emit handleInput(QString(_(":r %1<CR>")).arg(fileName)); m_fileName = fileName; } signals: void handleInput(const QString &keys); public slots: void changeStatusData(const QString &info) { m_statusData = info; updateStatusBar(); } void highlightMatches(const QString &pattern) { QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget); if (!ed) return; QTextCursor cur = ed->textCursor(); QTextEdit::ExtraSelection selection; selection.format.setBackground(Qt::yellow); selection.format.setForeground(Qt::black); // Highlight matches. QTextDocument *doc = ed->document(); QRegExp re(pattern); cur = doc->find(re); m_searchSelection.clear(); int a = cur.position(); while ( !cur.isNull() ) { if ( cur.hasSelection() ) { selection.cursor = cur; m_searchSelection.append(selection); } else { cur.movePosition(QTextCursor::NextCharacter); } cur = doc->find(re, cur); int b = cur.position(); if (a == b) { cur.movePosition(QTextCursor::NextCharacter); cur = doc->find(re, cur); b = cur.position(); if (a == b) break; } a = b; } updateExtraSelections(); } void changeStatusMessage(const QString &contents, int cursorPos) { m_statusMessage = cursorPos == -1 ? contents : contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos); updateStatusBar(); } void changeExtraInformation(const QString &info) { QMessageBox::information(m_widget, tr("Information"), info); } void updateStatusBar() { int slack = 80 - m_statusMessage.size() - m_statusData.size(); QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData; m_mainWindow->statusBar()->showMessage(msg); } void handleExCommand(bool *handled, const ExCommand &cmd) { if ( wantSaveAndQuit(cmd) ) { // :wq if (save()) cancel(); } else if ( wantSave(cmd) ) { save(); // :w } else if ( wantQuit(cmd) ) { if (cmd.hasBang) invalidate(); // :q! else cancel(); // :q } else { *handled = false; return; } *handled = true; } void requestSetBlockSelection(bool on = false) { QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget); if (!ed) return; QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette() : QApplication::palette(); m_blockSelection.clear(); m_clearSelection.clear(); if (on) { QTextCursor cur = ed->textCursor(); QTextEdit::ExtraSelection selection; selection.format.setBackground( pal.color(QPalette::Base) ); selection.format.setForeground( pal.color(QPalette::Text) ); selection.cursor = cur; m_clearSelection.append(selection); selection.format.setBackground( pal.color(QPalette::Highlight) ); selection.format.setForeground( pal.color(QPalette::HighlightedText) ); int from = cur.positionInBlock(); int to = cur.anchor() - cur.document()->findBlock(cur.anchor()).position(); const int min = qMin(cur.position(), cur.anchor()); const int max = qMax(cur.position(), cur.anchor()); for ( QTextBlock block = cur.document()->findBlock(min); block.isValid() && block.position() < max; block = block.next() ) { cur.setPosition( block.position() + qMin(from, block.length()) ); cur.setPosition( block.position() + qMin(to, block.length()), QTextCursor::KeepAnchor ); selection.cursor = cur; m_blockSelection.append(selection); } connect( ed, SIGNAL(selectionChanged()), SLOT(requestSetBlockSelection()), Qt::UniqueConnection ); QPalette pal2 = ed->palette(); pal2.setColor(QPalette::Highlight, Qt::transparent); pal2.setColor(QPalette::HighlightedText, Qt::transparent); ed->setPalette(pal2); } else { ed->setPalette(pal); disconnect( ed, SIGNAL(selectionChanged()), this, SLOT(requestSetBlockSelection()) ); } updateExtraSelections(); } void requestHasBlockSelection(bool *on) { *on = !m_blockSelection.isEmpty(); } private slots: void parseArguments() { QStringList args = qApp->arguments(); const QString editFileName = args.value(1, QString(_("/usr/share/vim/vim74/tutor/tutor"))); openFile(editFileName); foreach (const QString &cmd, args.mid(2)) emit handleInput(cmd); } private: void updateExtraSelections() { QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget); if (ed) ed->setExtraSelections(m_clearSelection + m_searchSelection + m_blockSelection); } bool wantSaveAndQuit(const ExCommand &cmd) { return cmd.cmd == "wq"; } bool wantSave(const ExCommand &cmd) { return cmd.matches("w", "write") || cmd.matches("wa", "wall"); } bool wantQuit(const ExCommand &cmd) { return cmd.matches("q", "quit") || cmd.matches("qa", "qall"); } bool save() { if (!hasChanges()) return true; QTemporaryFile tmpFile; if (!tmpFile.open()) { QMessageBox::critical(m_widget, tr("FakeVim Error"), tr("Cannot create temporary file: %1").arg(tmpFile.errorString())); return false; } QTextStream ts(&tmpFile); ts << content(); ts.flush(); QFile::remove(m_fileName); if (!QFile::copy(tmpFile.fileName(), m_fileName)) { QMessageBox::critical(m_widget, tr("FakeVim Error"), tr("Cannot write to file \"%1\"").arg(m_fileName)); return false; } return true; } void cancel() { if (hasChanges()) { QMessageBox::critical(m_widget, tr("FakeVim Warning"), tr("File \"%1\" was changed").arg(m_fileName)); } else { invalidate(); } } void invalidate() { QApplication::quit(); } bool hasChanges() { if (m_fileName.isEmpty() && content().isEmpty()) return false; QFile f(m_fileName); if (!f.open(QIODevice::ReadOnly)) return true; QTextStream ts(&f); return content() != ts.readAll(); } QTextDocument *document() const { QTextDocument *doc = NULL; if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget)) doc = ed->document(); else if (QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget)) doc = ed->document(); return doc; } QString content() const { return document()->toPlainText(); } QWidget *m_widget; QMainWindow *m_mainWindow; QString m_statusMessage; QString m_statusData; QString m_fileName; QList<QTextEdit::ExtraSelection> m_searchSelection; QList<QTextEdit::ExtraSelection> m_clearSelection; QList<QTextEdit::ExtraSelection> m_blockSelection; }; QWidget *createEditorWidget(bool usePlainTextEdit) { QWidget *editor = 0; if (usePlainTextEdit) { Editor<QPlainTextEdit> *w = new Editor<QPlainTextEdit>; w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); editor = w; } else { Editor<QTextEdit> *w = new Editor<QTextEdit>; w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); editor = w; } editor->setObjectName(_("Editor")); editor->setFocus(); return editor; } void initHandler(FakeVimHandler &handler) { handler.handleCommand(_("set nopasskeys")); handler.handleCommand(_("set nopasscontrolkey")); // Set some Vim options. handler.handleCommand(_("set expandtab")); handler.handleCommand(_("set shiftwidth=8")); handler.handleCommand(_("set tabstop=16")); handler.handleCommand(_("set autoindent")); // Try to source file "fakevimrc" from current directory. handler.handleCommand(_("source fakevimrc")); handler.installEventFilter(); handler.setupWidget(); } void initMainWindow(QMainWindow &mainWindow, QWidget *centralWidget, const QString &title) { mainWindow.setWindowTitle(QString(_("FakeVim (%1)")).arg(title)); mainWindow.setCentralWidget(centralWidget); mainWindow.resize(600, 650); mainWindow.move(0, 0); mainWindow.show(); // Set monospace font for editor and status bar. QFont font = QApplication::font(); font.setFamily(_("Monospace")); centralWidget->setFont(font); mainWindow.statusBar()->setFont(font); } void clearUndoRedo(QWidget *editor) { EDITOR(editor, setUndoRedoEnabled(false)); EDITOR(editor, setUndoRedoEnabled(true)); } void connectSignals(FakeVimHandler &handler, Proxy &proxy) { QObject::connect(&handler, SIGNAL(commandBufferChanged(QString,int,int,int,QObject*)), &proxy, SLOT(changeStatusMessage(QString,int))); QObject::connect(&handler, SIGNAL(extraInformationChanged(QString)), &proxy, SLOT(changeExtraInformation(QString))); QObject::connect(&handler, SIGNAL(statusDataChanged(QString)), &proxy, SLOT(changeStatusData(QString))); QObject::connect(&handler, SIGNAL(highlightMatches(QString)), &proxy, SLOT(highlightMatches(QString))); QObject::connect(&handler, SIGNAL(handleExCommandRequested(bool*,ExCommand)), &proxy, SLOT(handleExCommand(bool*,ExCommand))); QObject::connect(&handler, SIGNAL(requestSetBlockSelection(bool)), &proxy, SLOT(requestSetBlockSelection(bool))); QObject::connect(&handler, SIGNAL(requestHasBlockSelection(bool*)), &proxy, SLOT(requestHasBlockSelection(bool*))); QObject::connect(&proxy, SIGNAL(handleInput(QString)), &handler, SLOT(handleInput(QString))); } int main(int argc, char *argv[]) { QApplication app(argc, argv); QStringList args = app.arguments(); // If FAKEVIM_PLAIN_TEXT_EDIT environment variable is 1 use QPlainTextEdit instead on QTextEdit; bool usePlainTextEdit = qgetenv("FAKEVIM_PLAIN_TEXT_EDIT") == "1"; // Create editor widget. QWidget *editor = createEditorWidget(usePlainTextEdit); // Create FakeVimHandler instance which will emulate Vim behavior in editor widget. FakeVimHandler handler(editor, 0); // Create main window. QMainWindow mainWindow; initMainWindow(mainWindow, editor, usePlainTextEdit ? _("QPlainTextEdit") : _("QTextEdit")); // Connect slots to FakeVimHandler signals. Proxy proxy(editor, &mainWindow); connectSignals(handler, proxy); // Initialize FakeVimHandler. initHandler(handler); // Clear undo and redo queues. clearUndoRedo(editor); return app.exec(); } #include "main.moc"
15,858
C++
.cpp
413
29.486683
105
0.602226
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,256
fakevimproxy.cpp
visualfc_liteide/liteidex/src/3rdparty/fakevim/python/fakevimproxy.cpp
#include "python/fakevimproxy.h" #include <QMetaMethod> #include <QMetaObject> #include <QObject> #include <QString> #include <QTextCursor> #include <QTextEdit> FakeVimProxy::FakeVimProxy(QObject *handler, QObject *parent) : QObject(parent) { const QMetaObject *mo = metaObject(); for (int i = 0; i < mo->methodCount(); ++i) { QMetaMethod method = mo->method(i); QByteArray signature = #if QT_VERSION < 0x050000 method.signature(); #else method.methodSignature(); #endif if (method.methodType() == QMetaMethod::Slot && signature.startsWith("on_")) { const QByteArray signalSignature = signature.mid(3); const int signalIndex = handler->metaObject()->indexOfSignal(signalSignature); Q_ASSERT(signalIndex != -1); connect(handler, handler->metaObject()->method(signalIndex), this, method); } } } void FakeVimProxy::on_commandBufferChanged(const QString &msg, int cursorPos, int anchorPos, int messageLevel, QObject *eventFilter) { commandBufferChanged(msg, cursorPos, anchorPos, messageLevel, eventFilter); } void FakeVimProxy::on_statusDataChanged(const QString &msg) { statusDataChanged(msg); } void FakeVimProxy::on_extraInformationChanged(const QString &msg) { extraInformationChanged(msg); } void FakeVimProxy::on_selectionChanged(const QList<QTextEdit::ExtraSelection> &selection) { selectionChanged(selection); } void FakeVimProxy::on_highlightMatches(const QString &needle) { highlightMatches(needle); } void FakeVimProxy::on_writeAllRequested(QString *error) { *error = writeAllRequested(); } void FakeVimProxy::on_moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor) { const QTextCursor cursor2 = moveToMatchingParenthesis(); *moved = cursor2.isNull(); if (*moved) { *moved = true; *forward = cursor2.position() > cursor->position(); *cursor = cursor2; } } void FakeVimProxy::on_checkForElectricCharacter(bool *result, QChar c) { *result = checkForElectricCharacter(c); } void FakeVimProxy::on_indentRegion(int beginLine, int endLine, QChar typedChar) { indentRegion(beginLine, endLine, typedChar); } void FakeVimProxy::on_completionRequested() { completionRequested(); } void FakeVimProxy::on_simpleCompletionRequested(const QString &needle, bool forward) { simpleCompletionRequested(needle, forward); } void FakeVimProxy::on_windowCommandRequested(const QString &key, int count) { windowCommandRequested(key, count); } void FakeVimProxy::on_findRequested(bool reverse) { findRequested(reverse); } void FakeVimProxy::on_findNextRequested(bool reverse) { findNextRequested(reverse); } void FakeVimProxy::on_handleExCommandRequested(bool *handled, const FakeVim::Internal::ExCommand &cmd) { *handled = handleExCommand(cmd); } void FakeVimProxy::on_requestDisableBlockSelection() { disableBlockSelection(); } void FakeVimProxy::on_requestSetBlockSelection(const QTextCursor &cursor) { enableBlockSelection(cursor); } void FakeVimProxy::on_requestBlockSelection(QTextCursor *cursor) { *cursor = blockSelection(); } void FakeVimProxy::on_requestHasBlockSelection(bool *on) { *on = hasBlockSelection(); } void FakeVimProxy::on_foldToggle(int depth) { foldToggle(depth); } void FakeVimProxy::on_foldAll(bool fold) { foldAll(fold); } void FakeVimProxy::on_fold(int depth, bool fold) { this->fold(depth, fold); } void FakeVimProxy::on_foldGoTo(int count, bool current) { foldGoTo(count, current); } void FakeVimProxy::on_jumpToGlobalMark(QChar mark, bool backTickMode, const QString &fileName) { jumpToGlobalMark(mark, backTickMode, fileName); }
3,919
C++
.cpp
130
25.669231
103
0.72337
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,257
fakevimactions.cpp
visualfc_liteide/liteidex/src/3rdparty/fakevim/fakevim/fakevimactions.cpp
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "fakevimactions.h" #include "fakevimhandler.h" // Please do not add any direct dependencies to other Qt Creator code here. // Instead emit signals and let the FakeVimPlugin channel the information to // Qt Creator. The idea is to keep this file here in a "clean" state that // allows easy reuse with any QTextEdit or QPlainTextEdit derived class. #include <utils/qtcassert.h> #include <QDebug> #include <QObject> #include <QCoreApplication> #ifdef FAKEVIM_STANDALONE using namespace FakeVim::Internal::Utils; #else using namespace Utils; #endif /////////////////////////////////////////////////////////////////////// // // FakeVimSettings // /////////////////////////////////////////////////////////////////////// namespace FakeVim { namespace Internal { typedef QLatin1String _; #ifdef FAKEVIM_STANDALONE namespace Utils { SavedAction::SavedAction(QObject *parent) : QObject(parent) { } void SavedAction::setValue(const QVariant &value) { m_value = value; } QVariant SavedAction::value() const { return m_value; } void SavedAction::setDefaultValue(const QVariant &value) { m_defaultValue = value; } QVariant SavedAction::defaultValue() const { return m_defaultValue; } void SavedAction::setSettingsKey(const QString &key) { m_settingsKey = key; } QString SavedAction::settingsKey() const { return m_settingsKey; } } // namespace Utils #endif // FAKEVIM_STANDALONE FakeVimSettings::FakeVimSettings() {} FakeVimSettings::~FakeVimSettings() { qDeleteAll(m_items); } void FakeVimSettings::insertItem(int code, SavedAction *item, const QString &longName, const QString &shortName) { QTC_ASSERT(!m_items.contains(code), qDebug() << code; return); m_items[code] = item; if (!longName.isEmpty()) { m_nameToCode[longName] = code; m_codeToName[code] = longName; } if (!shortName.isEmpty()) m_nameToCode[shortName] = code; } #ifndef FAKEVIM_STANDALONE void FakeVimSettings::readSettings(QSettings *settings) { foreach (SavedAction *item, m_items) item->readSettings(settings); } void FakeVimSettings::writeSettings(QSettings *settings) { foreach (SavedAction *item, m_items) item->writeSettings(settings); } #endif // FAKEVIM_STANDALONE SavedAction *FakeVimSettings::item(int code) { QTC_ASSERT(m_items.value(code, 0), qDebug() << "CODE: " << code; return 0); return m_items.value(code, 0); } SavedAction *FakeVimSettings::item(const QString &name) { return m_items.value(m_nameToCode.value(name, -1), 0); } QString FakeVimSettings::trySetValue(const QString &name, const QString &value) { int code = m_nameToCode.value(name, -1); if (code == -1) return FakeVimHandler::tr("Unknown option: %1").arg(name); if (code == ConfigTabStop || code == ConfigShiftWidth) { if (value.toInt() <= 0) return FakeVimHandler::tr("Argument must be positive: %1=%2") .arg(name).arg(value); } SavedAction *act = item(code); if (!act) return FakeVimHandler::tr("Unknown option: %1").arg(name); act->setValue(value); return QString(); } SavedAction *createAction(FakeVimSettings *instance, int code, const QVariant &value, const QString &settingsKey = QString(), const QString &shortKey = QString()) { SavedAction *item = new SavedAction(instance); item->setValue(value); #ifndef FAKEVIM_STANDALONE item->setSettingsKey(_("FakeVim"), settingsKey); item->setDefaultValue(value); item->setCheckable( value.canConvert<bool>() ); #endif instance->insertItem(code, item, settingsKey.toLower(), shortKey); return item; } FakeVimSettings *theFakeVimSettings() { static FakeVimSettings *s = 0; if (s) return s; s = new FakeVimSettings; // Specific FakeVim settings createAction(s, ConfigReadVimRc, false, _("ReadVimRc")); createAction(s, ConfigVimRcPath, QString(), _("VimRcPath")); #ifndef FAKEVIM_STANDALONE createAction(s, ConfigUseFakeVim, false, _("UseFakeVim")); s->item(ConfigUseFakeVim)->setText(QCoreApplication::translate("FakeVim::Internal", "Use Vim-style Editing")); s->item(ConfigReadVimRc)->setText(QCoreApplication::translate("FakeVim::Internal", "Read .vimrc")); s->item(ConfigVimRcPath)->setText(QCoreApplication::translate("FakeVim::Internal", "Path to .vimrc")); #endif createAction(s, ConfigShowMarks, false, _("ShowMarks"), _("sm")); createAction(s, ConfigPassControlKey, false, _("PassControlKey"), _("pck")); createAction(s, ConfigPassKeys, true, _("PassKeys"), _("pk")); // Emulated Vim setting createAction(s, ConfigStartOfLine, true, _("StartOfLine"), _("sol")); createAction(s, ConfigTabStop, 8, _("TabStop"), _("ts")); createAction(s, ConfigSmartTab, false, _("SmartTab"), _("sta")); createAction(s, ConfigHlSearch, true, _("HlSearch"), _("hls")); createAction(s, ConfigShiftWidth, 8, _("ShiftWidth"), _("sw")); createAction(s, ConfigExpandTab, false, _("ExpandTab"), _("et")); createAction(s, ConfigAutoIndent, false, _("AutoIndent"), _("ai")); createAction(s, ConfigSmartIndent, false, _("SmartIndent"), _("si")); createAction(s, ConfigIncSearch, true, _("IncSearch"), _("is")); createAction(s, ConfigUseCoreSearch, false, _("UseCoreSearch"), _("ucs")); createAction(s, ConfigSmartCase, false, _("SmartCase"), _("scs")); createAction(s, ConfigIgnoreCase, false, _("IgnoreCase"), _("ic")); createAction(s, ConfigWrapScan, true, _("WrapScan"), _("ws")); createAction(s, ConfigTildeOp, false, _("TildeOp"), _("top")); createAction(s, ConfigShowCmd, true, _("ShowCmd"), _("sc")); createAction(s, ConfigRelativeNumber, false, _("RelativeNumber"),_("rnu")); createAction(s, ConfigScrollOff, 0, _("ScrollOff"), _("so")); createAction(s, ConfigBackspace, _("indent,eol,start"), _("ConfigBackspace"), _("bs")); createAction(s, ConfigIsKeyword, _("@,48-57,_,192-255,a-z,A-Z"), _("IsKeyword"), _("isk")); createAction(s, ConfigClipboard, QString(), _("Clipboard"), _("cb")); return s; } SavedAction *theFakeVimSetting(int code) { return theFakeVimSettings()->item(code); } } // namespace Internal } // namespace FakeVim
8,199
C++
.cpp
202
35.975248
101
0.643713
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,259
qtcassert.cpp
visualfc_liteide/liteidex/src/3rdparty/fakevim/fakevim/utils/qtcassert.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qtcassert.h" namespace Utils { void writeAssertLocation(const char *msg) { qDebug("SOFT ASSERT: %s", msg); } } // namespace Utils
1,640
C++
.cpp
35
44.514286
78
0.679399
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
21,260
main.cpp
visualfc_liteide/liteidex/src/3rdparty/fakevim/tests/main.cpp
#include <iostream> #include <string> class SomeClass { public: SomeClass(const std::string &var) : m_var(var) {} private: std::string m_var; }; int main(int argc, const char *argv[]) { using namespace std; cout << "TESTING..."; cout << "1"; cout << "2"; cout << "3"; return 0; }
333
C++
.cpp
17
15.470588
54
0.570513
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,262
searchresultwidget.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_searchresult/searchresultwidget.cpp
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "searchresultwidget.h" #include "searchresulttreeview.h" #include "searchresulttreemodel.h" #include "searchresulttreeitems.h" #include "searchresulttreeitemroles.h" //#include "treeviewfind.h" //#include <aggregation/aggregate.h> #include <QDir> #include <QFrame> #include <QLabel> #include <QLineEdit> #include <QToolButton> #include <QCheckBox> #include <QVBoxLayout> #include <QHBoxLayout> #include <QToolBar> static const int SEARCHRESULT_WARNING_LIMIT = 200000; static const char SIZE_WARNING_ID[] = "sizeWarningLabel"; namespace Find { namespace Internal { class WideEnoughLineEdit : public QLineEdit { Q_OBJECT public: WideEnoughLineEdit(QWidget *parent):QLineEdit(parent){ connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateGeometry())); } ~WideEnoughLineEdit(){} QSize sizeHint() const { QSize sh = QLineEdit::minimumSizeHint(); sh.rwidth() += qMax(25 * fontMetrics().width(QLatin1Char('x')), fontMetrics().width(text())); return sh; } public slots: void updateGeometry() { QLineEdit::updateGeometry(); } }; } // Internal } // Find using namespace Find; using namespace Find::Internal; SearchResultWidget::SearchResultWidget(QWidget *parent) : QWidget(parent), m_count(0), m_isShowingReplaceUI(false), m_searchAgainSupported(false), m_preserveCaseSupported(false), m_cancelSupported(true) { QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(2); layout->setSpacing(1); setLayout(layout); QFrame *topWidget = new QFrame; // QPalette pal = topWidget->palette(); // pal.setColor(QPalette::Window, QColor(255, 255, 225)); // pal.setColor(QPalette::WindowText, Qt::black); // topWidget->setPalette(pal); topWidget->setFrameStyle(QFrame::Panel);// | QFrame::Raised); topWidget->setLineWidth(0); //topWidget->setAutoFillBackground(true); QHBoxLayout *topLayout = new QHBoxLayout(topWidget); topLayout->setMargin(0); topWidget->setLayout(topLayout); layout->addWidget(topWidget); m_infoWidget = new QFrame; // pal = m_infoWidget->palette(); // pal.setColor(QPalette::Window, QColor(255, 255, 225)); // pal.setColor(QPalette::WindowText, Qt::black); // m_infoWidget->setPalette(pal); m_infoWidget->setFrameStyle(QFrame::Panel);// | QFrame::Raised); m_infoWidget->setLineWidth(0); //m_infoWidget->setAutoFillBackground(true); QHBoxLayout *infoLayout = new QHBoxLayout(m_infoWidget); infoLayout->setMargin(2); m_infoLabel = new QLabel(); infoLayout->addWidget(m_infoLabel); layout->addWidget(m_infoWidget); m_messageWidget = new QFrame; // pal.setColor(QPalette::Window, QColor(255, 255, 225)); // pal.setColor(QPalette::WindowText, Qt::red); // m_messageWidget->setPalette(pal); m_messageWidget->setFrameStyle(QFrame::Panel);// | QFrame::Raised); m_messageWidget->setLineWidth(0); //m_messageWidget->setAutoFillBackground(true); QHBoxLayout *messageLayout = new QHBoxLayout(m_messageWidget); messageLayout->setMargin(2); m_messageWidget->setLayout(messageLayout); QLabel *messageLabel = new QLabel(tr("Search was canceled.")); //messageLabel->setPalette(pal); messageLayout->addWidget(messageLabel); layout->addWidget(m_messageWidget); m_messageWidget->setVisible(false); m_searchResultTreeView = new Internal::SearchResultTreeView(this); //m_searchResultTreeView->setFrameStyle(QFrame::NoFrame); //m_searchResultTreeView->setAttribute(Qt::WA_MacShowFocusRect, false); // Aggregation::Aggregate * agg = new Aggregation::Aggregate; // agg->add(m_searchResultTreeView); // agg->add(new TreeViewFind(m_searchResultTreeView, // ItemDataRoles::ResultLineRole)); layout->addWidget(m_searchResultTreeView); // m_infoBarDisplay.setTarget(layout, 2); // m_infoBarDisplay.setInfoBar(&m_infoBar); m_descriptionContainer = new QWidget(topWidget); QHBoxLayout *descriptionLayout = new QHBoxLayout(m_descriptionContainer); m_descriptionContainer->setLayout(descriptionLayout); descriptionLayout->setMargin(0); m_descriptionContainer->setMinimumWidth(200); m_descriptionContainer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_label = new QLabel(m_descriptionContainer); m_label->setVisible(false); m_searchTerm = new QLabel(m_descriptionContainer); m_searchTerm->setVisible(false); descriptionLayout->addWidget(m_label); descriptionLayout->addWidget(m_searchTerm); m_cancelButton = new QToolButton(topWidget); m_cancelButton->setText(tr("Cancel")); m_cancelButton->setToolButtonStyle(Qt::ToolButtonTextOnly); connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); m_searchAgainButton = new QToolButton(topWidget); m_searchAgainButton->setToolTip(tr("Repeat the search with same parameters")); m_searchAgainButton->setText(tr("Search again")); m_searchAgainButton->setToolButtonStyle(Qt::ToolButtonTextOnly); m_searchAgainButton->setVisible(false); connect(m_searchAgainButton, SIGNAL(clicked()), this, SLOT(searchAgain())); m_showReplaceModeButton = new QToolButton(topWidget); m_showReplaceModeButton->setToolTip(tr("Set show replace mode ui")); m_showReplaceModeButton->setText(tr("Show Replace")); m_showReplaceModeButton->setToolButtonStyle(Qt::ToolButtonTextOnly); m_showReplaceModeButton->setVisible(false); connect(m_showReplaceModeButton,SIGNAL(clicked()),this,SLOT(showReplaceMode())); m_replaceLabel = new QLabel(tr("Replace with:"), topWidget); m_replaceTextEdit = new WideEnoughLineEdit(topWidget); m_replaceTextEdit->setMinimumWidth(120); m_replaceTextEdit->setEnabled(false); m_replaceTextEdit->setTabOrder(m_replaceTextEdit, m_searchResultTreeView); m_replaceButton = new QToolButton(topWidget); m_replaceButton->setToolTip(tr("Replace all occurrences")); m_replaceButton->setText(tr("Replace")); m_replaceButton->setToolButtonStyle(Qt::ToolButtonTextOnly); m_replaceButton->setEnabled(false); m_preserveCaseCheck = new QCheckBox(topWidget); m_preserveCaseCheck->setText(tr("Preserve case")); m_preserveCaseCheck->setEnabled(false); // if (FindPlugin * plugin = FindPlugin::instance()) { // m_preserveCaseCheck->setChecked(plugin->hasFindFlag(FindPreserveCase)); // connect(m_preserveCaseCheck, SIGNAL(clicked(bool)), plugin, SLOT(setPreserveCase(bool))); // } m_matchesFoundLabel = new QLabel(topWidget); endMatchesFoundLabel(); m_expandAll = new QToolButton; m_expandAll->setText("+"); m_expandAll->setToolTip(tr("Expand all items")); connect(m_expandAll,SIGNAL(clicked()),this,SLOT(expandAll())); m_collapseAll = new QToolButton; m_collapseAll->setText("-"); m_collapseAll->setToolTip(tr("Collapse all items")); connect(m_collapseAll,SIGNAL(clicked()),this,SLOT(collapseAll())); topLayout->addWidget(m_expandAll); topLayout->addWidget(m_collapseAll); topLayout->addWidget(m_descriptionContainer); topLayout->addWidget(m_cancelButton); topLayout->addWidget(m_searchAgainButton); topLayout->addWidget(m_showReplaceModeButton); topLayout->addWidget(m_replaceLabel); topLayout->addWidget(m_replaceTextEdit); topLayout->addWidget(m_replaceButton); topLayout->addWidget(m_preserveCaseCheck); topLayout->addStretch(2); topLayout->addWidget(m_matchesFoundLabel); topWidget->setMinimumHeight(m_cancelButton->sizeHint().height() + topLayout->contentsMargins().top() + topLayout->contentsMargins().bottom() + topWidget->lineWidth()); setShowReplaceUI(false); connect(m_searchResultTreeView, SIGNAL(jumpToSearchResult(SearchResultItem)), this, SLOT(handleJumpToSearchResult(SearchResultItem))); connect(m_replaceTextEdit, SIGNAL(returnPressed()), this, SLOT(handleReplaceButton())); connect(m_replaceButton, SIGNAL(clicked()), this, SLOT(handleReplaceButton())); } SearchResultWidget::~SearchResultWidget() { // if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID))) // cancelAfterSizeWarning(); } void SearchResultWidget::setInfo(const QString &label, const QString &toolTip, const QString &term) { m_label->setText(label); m_label->setVisible(!label.isEmpty()); m_descriptionContainer->setToolTip(toolTip); m_searchTerm->setText(term); m_searchTerm->setVisible(!term.isEmpty()); } QString SearchResultWidget::searchText() const { return m_searchTerm->text(); } void SearchResultWidget::addResult(const QString &fileName, int lineNumber, const QString &rowText, int searchTermStart, int searchTermLength, const QVariant &userData) { SearchResultItem item; item.path = QStringList() << QDir::toNativeSeparators(fileName); item.lineNumber = lineNumber; item.text = rowText; item.textMarkPos = searchTermStart; item.textMarkLength = searchTermLength; item.useTextEditorFont = true; item.userData = userData; addResults(QList<SearchResultItem>() << item, AddOrdered); } void SearchResultWidget::addResults(const QList<SearchResultItem> &items, AddMode mode, bool revert) { bool firstItems = (m_count == 0); m_count += items.size(); m_searchResultTreeView->addResults(items, mode); updateMatchesFoundLabel(revert); if (firstItems) { // if (!m_dontAskAgainGroup.isEmpty()) { // Core::Id undoWarningId = Core::Id("warninglabel/").withSuffix(m_dontAskAgainGroup); // if (m_infoBar.canInfoBeAdded(undoWarningId)) { // Core::InfoBarEntry info(undoWarningId, tr("This change cannot be undone."), // Core::InfoBarEntry::GlobalSuppressionEnabled); // m_infoBar.addInfo(info); // } // } m_replaceTextEdit->setEnabled(true); // We didn't have an item before, set the focus to the search widget or replace text edit if (m_isShowingReplaceUI) { m_replaceTextEdit->setFocus(); m_replaceTextEdit->selectAll(); } else { m_searchResultTreeView->setFocus(); } m_searchResultTreeView->selectionModel()->select(m_searchResultTreeView->model()->index(0, 0, QModelIndex()), QItemSelectionModel::Select); emit navigateStateChanged(); } else if (m_count <= SEARCHRESULT_WARNING_LIMIT) { return; } else { // Core::Id sizeWarningId(SIZE_WARNING_ID); // if (!m_infoBar.canInfoBeAdded(sizeWarningId)) // return; // emit paused(true); // Core::InfoBarEntry info(sizeWarningId, // tr("The search resulted in more than %n items, do you still want to continue?", // 0, SEARCHRESULT_WARNING_LIMIT)); // info.setCancelButtonInfo(tr("Cancel"), this, SLOT(cancelAfterSizeWarning())); // info.setCustomButtonInfo(tr("Continue"), this, SLOT(continueAfterSizeWarning())); // m_infoBar.addInfo(info); // emit requestPopup(false/*no focus*/); } } void SearchResultWidget::setRevertMode(const QString &replaceText, const QString &searchText) { m_searchTerm->setText(replaceText); this->setTextToReplace(searchText); this->m_replaceLabel->setText(tr("Revert with:")); this->m_replaceButton->setText(tr("Revert")); this->m_replaceButton->setToolTip(tr("Revert all occurrences")); } int SearchResultWidget::count() const { return m_count; } QString SearchResultWidget::dontAskAgainGroup() const { return m_dontAskAgainGroup; } void SearchResultWidget::setDontAskAgainGroup(const QString &group) { m_dontAskAgainGroup = group; } void SearchResultWidget::setTextToReplace(const QString &textToReplace) { m_replaceTextEdit->setText(textToReplace); } QString SearchResultWidget::textToReplace() const { return m_replaceTextEdit->text(); } void SearchResultWidget::setShowReplaceUI(bool visible) { m_searchResultTreeView->model()->setShowReplaceUI(visible); m_replaceLabel->setVisible(visible); m_replaceTextEdit->setVisible(visible); m_replaceButton->setVisible(visible); m_preserveCaseCheck->setVisible(m_preserveCaseSupported && visible); m_isShowingReplaceUI = visible; m_infoWidget->setVisible(visible); m_showReplaceModeButton->setVisible(false); } void SearchResultWidget::setReadOnly(bool readOnly) { m_isReadOnly = readOnly; } void SearchResultWidget::setInfoWidgetLabel(const QString &infoText) { m_infoLabel->setText(infoText); } bool SearchResultWidget::hasFocusInternally() const { return m_searchResultTreeView->hasFocus() || (m_isShowingReplaceUI && m_replaceTextEdit->hasFocus()); } void SearchResultWidget::setFocusInternally() { if (m_count > 0) { if (m_isShowingReplaceUI) { if (!focusWidget() || focusWidget() == m_replaceTextEdit) { m_replaceTextEdit->setFocus(); m_replaceTextEdit->selectAll(); } else { m_searchResultTreeView->setFocus(); } } else { m_searchResultTreeView->setFocus(); } } } bool SearchResultWidget::canFocusInternally() const { return m_count > 0; } void SearchResultWidget::notifyVisibilityChanged(bool visible) { emit visibilityChanged(visible); } void SearchResultWidget::setTextEditorFont(const QFont &font, const SearchResultColor color) { m_searchResultTreeView->setTextEditorFont(font, color); } void SearchResultWidget::setAutoExpandResults(bool expand) { m_searchResultTreeView->setAutoExpandResults(expand); } void SearchResultWidget::goToNext() { if (m_count == 0) return; QModelIndex idx = m_searchResultTreeView->model()->next(m_searchResultTreeView->currentIndex()); if (idx.isValid()) { m_searchResultTreeView->setCurrentIndex(idx); m_searchResultTreeView->emitJumpToSearchResult(idx); } } void SearchResultWidget::goToPrevious() { if (!m_searchResultTreeView->model()->rowCount()) return; QModelIndex idx = m_searchResultTreeView->model()->prev(m_searchResultTreeView->currentIndex()); if (idx.isValid()) { m_searchResultTreeView->setCurrentIndex(idx); m_searchResultTreeView->emitJumpToSearchResult(idx); } } void SearchResultWidget::restart() { m_replaceTextEdit->setEnabled(false); m_replaceButton->setEnabled(false); m_searchResultTreeView->clear(); m_count = 0; // Core::Id sizeWarningId(SIZE_WARNING_ID); // m_infoBar.removeInfo(sizeWarningId); // m_infoBar.enableInfo(sizeWarningId); m_cancelButton->setVisible(m_cancelSupported); m_searchAgainButton->setVisible(false); m_messageWidget->setVisible(false); m_replaceLabel->setText(tr("Replace with:")); m_replaceButton->setToolTip(tr("Replace all occurrences")); m_replaceButton->setText(tr("Replace")); //updateMatchesFoundLabel(); beginMatchesFoundLabel(); emit restarted(); } void SearchResultWidget::clear() { m_searchResultTreeView->clear(); m_count = 0; endMatchesFoundLabel(); } void SearchResultWidget::setCancelSupported(bool supported) { m_cancelSupported = supported; } void SearchResultWidget::setSearchAgainSupported(bool supported) { m_searchAgainSupported = supported; m_searchAgainButton->setVisible(supported && !m_cancelButton->isVisible()); } void SearchResultWidget::setSearchAgainEnabled(bool enabled) { m_searchAgainButton->setEnabled(enabled); } void SearchResultWidget::setPreserveCaseSupported(bool supported) { m_preserveCaseSupported = supported; m_preserveCaseCheck->setVisible(supported); } void SearchResultWidget::finishSearch(bool canceled) { endMatchesFoundLabel(); m_replaceTextEdit->setEnabled(m_count > 0); m_replaceButton->setEnabled(m_count > 0); m_preserveCaseCheck->setEnabled(m_count > 0); m_cancelButton->setVisible(false); m_messageWidget->setVisible(canceled); m_searchAgainButton->setVisible(m_searchAgainSupported); m_showReplaceModeButton->setVisible(!this->m_isShowingReplaceUI && !canceled && m_count > 0 && !m_isReadOnly); } void SearchResultWidget::sendRequestPopup() { emit requestPopup(true/*focus*/); } void SearchResultWidget::continueAfterSizeWarning() { //m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID)); emit paused(false); } void SearchResultWidget::cancelAfterSizeWarning() { //m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID)); emit cancelled(); emit paused(false); } void SearchResultWidget::handleJumpToSearchResult(const SearchResultItem &item) { emit activated(item); } void SearchResultWidget::handleReplaceButton() { // check if button is actually enabled, because this is also triggered // by pressing return in replace line edit if (m_replaceButton->isEnabled()) { //m_infoBar.clear(); emit replaceButtonClicked(m_replaceTextEdit->text(), checkedItems(), m_preserveCaseCheck->isChecked()); } } void SearchResultWidget::cancel() { m_cancelButton->setVisible(false); // if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID))) // cancelAfterSizeWarning(); // else emit cancelled(); } void SearchResultWidget::searchAgain() { emit searchAgainRequested(); } void SearchResultWidget::expandAll() { m_searchResultTreeView->expandAll(); m_searchResultTreeView->repaint(); } void SearchResultWidget::collapseAll() { m_searchResultTreeView->collapseAll(); m_searchResultTreeView->repaint(); } void SearchResultWidget::showReplaceMode() { this->setShowReplaceUI(true); Internal::SearchResultTreeModel *model = m_searchResultTreeView->model(); const int fileCount = model->rowCount(QModelIndex()); for (int i = 0; i < fileCount; ++i) { QModelIndex fileIndex = model->index(i, 0, QModelIndex()); Internal::SearchResultTreeItem *fileItem = static_cast<Internal::SearchResultTreeItem *>(fileIndex.internalPointer()); fileItem->setIsUserCheckable(true); fileItem->setCheckState(Qt::Checked); for (int rowIndex = 0; rowIndex < fileItem->childrenCount(); ++rowIndex) { QModelIndex textIndex = model->index(rowIndex, 0, fileIndex); Internal::SearchResultTreeItem *rowItem = static_cast<Internal::SearchResultTreeItem *>(textIndex.internalPointer()); rowItem->setIsUserCheckable(true); rowItem->setCheckState(Qt::Checked); } } this->m_replaceTextEdit->setFocus(); this->m_searchResultTreeView->repaint(); } QList<SearchResultItem> SearchResultWidget::checkedItems() const { QList<SearchResultItem> result; Internal::SearchResultTreeModel *model = m_searchResultTreeView->model(); const int fileCount = model->rowCount(QModelIndex()); for (int i = 0; i < fileCount; ++i) { QModelIndex fileIndex = model->index(i, 0, QModelIndex()); Internal::SearchResultTreeItem *fileItem = static_cast<Internal::SearchResultTreeItem *>(fileIndex.internalPointer()); Q_ASSERT(fileItem != 0); for (int rowIndex = 0; rowIndex < fileItem->childrenCount(); ++rowIndex) { QModelIndex textIndex = model->index(rowIndex, 0, fileIndex); Internal::SearchResultTreeItem *rowItem = static_cast<Internal::SearchResultTreeItem *>(textIndex.internalPointer()); if (rowItem->checkState()) result << rowItem->item; } } return result; } void SearchResultWidget::updateMatchesFoundLabel(bool revert) { if (revert) { m_matchesFoundLabel->setText(tr("%n matches replaced.", 0, m_count)); } else { m_matchesFoundLabel->setText(tr("searching... %n matches found.", 0, m_count)); } } void SearchResultWidget::beginMatchesFoundLabel() { m_matchesFoundLabel->setText(tr("searching ...")); } void SearchResultWidget::endMatchesFoundLabel() { if (m_count == 0) m_matchesFoundLabel->setText(tr("No matches found.")); else m_matchesFoundLabel->setText(tr("%n matches found.", 0, m_count)); } #include "searchresultwidget.moc"
21,775
C++
.cpp
541
36.092421
147
0.715454
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,269
basetextblockselection.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_texteditor/basetextblockselection.cpp
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "basetextblockselection.h" #include <QTextBlock> #include <QTextCursor> #include <QTextDocument> using namespace TextEditor; BaseTextBlockSelection::BaseTextBlockSelection() :firstVisualColumn(0), lastVisualColumn(0), anchor(BottomRight) { } void BaseTextBlockSelection::moveAnchor(int blockNumber, int visualColumn) { if (visualColumn >= 0) { if (anchor % 2) { lastVisualColumn = visualColumn; if (lastVisualColumn < firstVisualColumn) { qSwap(firstVisualColumn, lastVisualColumn); anchor = (Anchor) (anchor - 1); } } else { firstVisualColumn = visualColumn; if (firstVisualColumn > lastVisualColumn) { qSwap(firstVisualColumn, lastVisualColumn); anchor = (Anchor) (anchor + 1); } } } if (blockNumber >= 0 && blockNumber < firstBlock.document()->blockCount()) { if (anchor <= TopRight) { firstBlock.setPosition(firstBlock.document()->findBlockByNumber(blockNumber).position()); if (firstBlock.blockNumber() > lastBlock.blockNumber()) { qSwap(firstBlock, lastBlock); anchor = (Anchor) (anchor + 2); } } else { lastBlock.setPosition(firstBlock.document()->findBlockByNumber(blockNumber).position()); if (lastBlock.blockNumber() < firstBlock.blockNumber()) { qSwap(firstBlock, lastBlock); anchor = (Anchor) (anchor - 2); } } } firstBlock.movePosition(QTextCursor::StartOfBlock); lastBlock.movePosition(QTextCursor::EndOfBlock); } int BaseTextBlockSelection::position(const TabSettings &ts) const { const QTextBlock &block = anchor <= TopRight ? lastBlock.block() : firstBlock.block(); const int column = anchor % 2 ? firstVisualColumn : lastVisualColumn; return block.position() + ts.positionAtColumn(block.text(), column); } QTextCursor BaseTextBlockSelection::selection(const TabSettings &ts) const { QTextCursor cursor = firstBlock; if (anchor <= TopRight) { cursor.setPosition(lastBlock.block().position() + ts.positionAtColumn(lastBlock.block().text(), lastVisualColumn)); cursor.setPosition(firstBlock.block().position() + ts.positionAtColumn(firstBlock.block().text(), firstVisualColumn), QTextCursor::KeepAnchor); } else { cursor.setPosition(firstBlock.block().position() + ts.positionAtColumn(firstBlock.block().text(), firstVisualColumn)); cursor.setPosition(lastBlock.block().position() + ts.positionAtColumn(lastBlock.block().text(), lastVisualColumn), QTextCursor::KeepAnchor); } return cursor; } void BaseTextBlockSelection::fromSelection(const TabSettings &ts, const QTextCursor &selection) { firstBlock = selection; firstBlock.setPosition(selection.selectionStart()); firstVisualColumn = ts.columnAt(firstBlock.block().text(), firstBlock.positionInBlock()); lastBlock = selection; lastBlock.setPosition(selection.selectionEnd()); lastVisualColumn = ts.columnAt(lastBlock.block().text(), lastBlock.positionInBlock()); if (selection.anchor() > selection.position()) anchor = TopLeft; else anchor = BottomRight; firstBlock.movePosition(QTextCursor::StartOfBlock); lastBlock.movePosition(QTextCursor::EndOfBlock); }
4,919
C++
.cpp
107
40.009346
126
0.679575
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,270
syntaxhighlighter.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_texteditor/syntaxhighlighter.cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "syntaxhighlighter.h" #include "basetextdocumentlayout.h" #include <qtextdocument.h> #include <qtextlayout.h> #include <qpointer.h> #include <qtextobject.h> #include <qtextcursor.h> #include <qdebug.h> #include <qtextedit.h> #include <qtimer.h> using namespace TextEditor; class TextEditor::SyntaxHighlighterPrivate { SyntaxHighlighter *q_ptr; Q_DECLARE_PUBLIC(SyntaxHighlighter) public: inline SyntaxHighlighterPrivate() : q_ptr(0), rehighlightPending(false), inReformatBlocks(false) {} QPointer<QTextDocument> doc; void _q_reformatBlocks(int from, int charsRemoved, int charsAdded); void reformatBlocks(int from, int charsRemoved, int charsAdded); void reformatBlock(const QTextBlock &block, int from, int charsRemoved, int charsAdded); inline void rehighlight(QTextCursor &cursor, QTextCursor::MoveOperation operation) { inReformatBlocks = true; cursor.beginEditBlock(); int from = cursor.position(); cursor.movePosition(operation); reformatBlocks(from, 0, cursor.position() - from); cursor.endEditBlock(); inReformatBlocks = false; } inline void _q_delayedRehighlight() { if (!rehighlightPending) return; rehighlightPending = false; q_func()->rehighlight(); } void applyFormatChanges(int from, int charsRemoved, int charsAdded); QVector<QTextCharFormat> formatChanges; QTextBlock currentBlock; QList<SyntaxToken> tokens; SyntaxComment comment; bool rehighlightPending; bool inReformatBlocks; }; static bool adjustRange(QTextLayout::FormatRange &range, int from, int charsRemoved, int charsAdded) { if (range.start >= from) { range.start += charsAdded - charsRemoved; return true; } else if (range.start + range.length > from) { range.length += charsAdded - charsRemoved; return true; } return false; } void SyntaxHighlighterPrivate::applyFormatChanges(int from, int charsRemoved, int charsAdded) { bool formatsChanged = false; QTextLayout *layout = currentBlock.layout(); QList<QTextLayout::FormatRange> ranges = layout->additionalFormats(); bool doAdjustRange = currentBlock.contains(from); QList<QTextLayout::FormatRange> old_ranges; if (!ranges.isEmpty()) { QList<QTextLayout::FormatRange>::Iterator it = ranges.begin(); while (it != ranges.end()) { if (it->format.property(QTextFormat::UserProperty).toBool()) { if (doAdjustRange) formatsChanged = adjustRange(*it, from - currentBlock.position(), charsRemoved, charsAdded) || formatsChanged; ++it; } else { old_ranges.append(*it); it = ranges.erase(it); } } } QTextCharFormat emptyFormat; QTextLayout::FormatRange r; r.start = -1; QList<QTextLayout::FormatRange> new_ranges; int i = 0; while (i < formatChanges.count()) { while (i < formatChanges.count() && formatChanges.at(i) == emptyFormat) ++i; if (i >= formatChanges.count()) break; r.start = i; r.format = formatChanges.at(i); while (i < formatChanges.count() && formatChanges.at(i) == r.format) ++i; if (i >= formatChanges.count()) break; r.length = i - r.start; new_ranges << r; r.start = -1; } if (r.start != -1) { r.length = formatChanges.count() - r.start; new_ranges << r; } formatsChanged = formatsChanged || (new_ranges.size() != old_ranges.size()); for (int i = 0; !formatsChanged && i < new_ranges.size(); ++i) { const QTextLayout::FormatRange &o = old_ranges.at(i); const QTextLayout::FormatRange &n = new_ranges.at(i); formatsChanged = (o.start != n.start || o.length != n.length || o.format != n.format); } if (formatsChanged) { ranges.append(new_ranges); layout->setAdditionalFormats(ranges); doc->markContentsDirty(currentBlock.position(), currentBlock.length()); } } void SyntaxHighlighterPrivate::_q_reformatBlocks(int from, int charsRemoved, int charsAdded) { if (!inReformatBlocks) reformatBlocks(from, charsRemoved, charsAdded); } void SyntaxHighlighterPrivate::reformatBlocks(int from, int charsRemoved, int charsAdded) { rehighlightPending = false; QTextBlock block = doc->findBlock(from); if (!block.isValid()) return; int endPosition; QTextBlock lastBlock = doc->findBlock(from + charsAdded + (charsRemoved > 0 ? 1 : 0)); if (lastBlock.isValid()) endPosition = lastBlock.position() + lastBlock.length(); else endPosition = doc->lastBlock().position() + doc->lastBlock().length(); //doc->docHandle()->length(); bool forceHighlightOfNextBlock = false; while (block.isValid() && (block.position() < endPosition || forceHighlightOfNextBlock)) { const int stateBeforeHighlight = block.userState(); reformatBlock(block, from, charsRemoved, charsAdded); forceHighlightOfNextBlock = (block.userState() != stateBeforeHighlight); block = block.next(); } formatChanges.clear(); } void SyntaxHighlighterPrivate::reformatBlock(const QTextBlock &block, int from, int charsRemoved, int charsAdded) { Q_Q(SyntaxHighlighter); Q_ASSERT_X(!currentBlock.isValid(), "SyntaxHighlighter::reformatBlock()", "reFormatBlock() called recursively"); currentBlock = block; tokens.clear(); formatChanges.fill(QTextCharFormat(), block.length() - 1); q->highlightBlock(block.text()); BaseTextDocumentLayout::userData(block)->setTokens(tokens); BaseTextDocumentLayout::setLexerState(block,q->currentBlockState()); applyFormatChanges(from, charsRemoved, charsAdded); currentBlock = QTextBlock(); } const SyntaxHighlighter::KateFormatMap SyntaxHighlighter::m_kateFormats; SyntaxHighlighter::KateFormatMap::KateFormatMap() { m_ids.insert(QLatin1String("dsNormal"), SyntaxHighlighter::Normal); m_ids.insert(QLatin1String("dsKeyword"), SyntaxHighlighter::Keyword); m_ids.insert(QLatin1String("dsDataType"), SyntaxHighlighter::DataType); m_ids.insert(QLatin1String("dsDecVal"), SyntaxHighlighter::Decimal); m_ids.insert(QLatin1String("dsBaseN"), SyntaxHighlighter::BaseN); m_ids.insert(QLatin1String("dsFloat"), SyntaxHighlighter::Float); m_ids.insert(QLatin1String("dsChar"), SyntaxHighlighter::Char); m_ids.insert(QLatin1String("dsString"), SyntaxHighlighter::String); m_ids.insert(QLatin1String("dsComment"), SyntaxHighlighter::Comment); m_ids.insert(QLatin1String("dsOthers"), SyntaxHighlighter::Others); m_ids.insert(QLatin1String("dsAlert"), SyntaxHighlighter::Alert); m_ids.insert(QLatin1String("dsFunction"), SyntaxHighlighter::Function); m_ids.insert(QLatin1String("dsRegionMarker"), SyntaxHighlighter::RegionMarker); m_ids.insert(QLatin1String("dsError"), SyntaxHighlighter::Error); m_ids.insert(QLatin1String("dsSymbol"),SyntaxHighlighter::Symbol); m_ids.insert(QLatin1String("dsBuiltinFunc"), SyntaxHighlighter::BuiltinFunc); m_ids.insert(QLatin1String("dsPredeclared"), SyntaxHighlighter::Predeclared); m_ids.insert(QLatin1String("dsFuncDecl"), SyntaxHighlighter::FuncDecl); m_ids.insert(QLatin1String("dsPlaceholder"), SyntaxHighlighter::Placeholder); m_ids.insert(QLatin1String("dsToDo"), SyntaxHighlighter::ToDo); m_ids.insert(QLatin1String("dsPreprocessorFormat"),SyntaxHighlighter::PreprocessorFormat); } void SyntaxHighlighter::configureFormat(TextFormatId id, const QTextCharFormat &format) { m_creatorFormats[id] = format; } void SyntaxHighlighter::setTabSize(int /*tabSize*/) { } SyntaxComment SyntaxHighlighter::comment() const { Q_D(const SyntaxHighlighter); return d->comment; } void SyntaxHighlighter::setupComment(const SyntaxComment &comment) { Q_D(SyntaxHighlighter); d->comment = comment; } /*! \class SyntaxHighlighter \reentrant \brief The SyntaxHighlighter class allows you to define syntax highlighting rules, and in addition you can use the class to query a document's current formatting or user data. \since 4.1 \ingroup richtext-processing The SyntaxHighlighter class is a base class for implementing QTextEdit syntax highlighters. A syntax highligher automatically highlights parts of the text in a QTextEdit, or more generally in a QTextDocument. Syntax highlighters are often used when the user is entering text in a specific format (for example source code) and help the user to read the text and identify syntax errors. To provide your own syntax highlighting, you must subclass SyntaxHighlighter and reimplement highlightBlock(). When you create an instance of your SyntaxHighlighter subclass, pass it the QTextEdit or QTextDocument that you want the syntax highlighting to be applied to. For example: \snippet doc/src/snippets/code/src_gui_text_SyntaxHighlighter.cpp 0 After this your highlightBlock() function will be called automatically whenever necessary. Use your highlightBlock() function to apply formatting (e.g. setting the font and color) to the text that is passed to it. SyntaxHighlighter provides the setFormat() function which applies a given QTextCharFormat on the current text block. For example: \snippet doc/src/snippets/code/src_gui_text_SyntaxHighlighter.cpp 1 Some syntaxes can have constructs that span several text blocks. For example, a C++ syntax highlighter should be able to cope with \c{/}\c{*...*}\c{/} multiline comments. To deal with these cases it is necessary to know the end state of the previous text block (e.g. "in comment"). Inside your highlightBlock() implementation you can query the end state of the previous text block using the previousBlockState() function. After parsing the block you can save the last state using setCurrentBlockState(). The currentBlockState() and previousBlockState() functions return an int value. If no state is set, the returned value is -1. You can designate any other value to identify any given state using the setCurrentBlockState() function. Once the state is set the QTextBlock keeps that value until it is set set again or until the corresponding paragraph of text is deleted. For example, if you're writing a simple C++ syntax highlighter, you might designate 1 to signify "in comment": \snippet doc/src/snippets/code/src_gui_text_SyntaxHighlighter.cpp 2 In the example above, we first set the current block state to 0. Then, if the previous block ended within a comment, we higlight from the beginning of the current block (\c {startIndex = 0}). Otherwise, we search for the given start expression. If the specified end expression cannot be found in the text block, we change the current block state by calling setCurrentBlockState(), and make sure that the rest of the block is higlighted. In addition you can query the current formatting and user data using the format() and currentBlockUserData() functions respectively. You can also attach user data to the current text block using the setCurrentBlockUserData() function. QTextBlockUserData can be used to store custom settings. In the case of syntax highlighting, it is in particular interesting as cache storage for information that you may figure out while parsing the paragraph's text. For an example, see the setCurrentBlockUserData() documentation. \sa QTextEdit, {Syntax Highlighter Example} */ /*! Constructs a SyntaxHighlighter with the given \a parent. */ SyntaxHighlighter::SyntaxHighlighter(QObject *parent) : QObject(parent), d_ptr(new SyntaxHighlighterPrivate) { d_ptr->q_ptr = this; } /*! Constructs a SyntaxHighlighter and installs it on \a parent. The specified QTextDocument also becomes the owner of the SyntaxHighlighter. */ SyntaxHighlighter::SyntaxHighlighter(QTextDocument *parent) : QObject(parent), d_ptr(new SyntaxHighlighterPrivate) { d_ptr->q_ptr = this; setDocument(parent); } /*! Constructs a SyntaxHighlighter and installs it on \a parent 's QTextDocument. The specified QTextEdit also becomes the owner of the SyntaxHighlighter. */ SyntaxHighlighter::SyntaxHighlighter(QTextEdit *parent) : QObject(parent), d_ptr(new SyntaxHighlighterPrivate) { d_ptr->q_ptr = this; setDocument(parent->document()); } /*! Destructor. Uninstalls this syntax highlighter from the text document. */ SyntaxHighlighter::~SyntaxHighlighter() { setDocument(0); } /*! Installs the syntax highlighter on the given QTextDocument \a doc. A SyntaxHighlighter can only be used with one document at a time. */ void SyntaxHighlighter::setDocument(QTextDocument *doc) { Q_D(SyntaxHighlighter); if (d->doc) { disconnect(d->doc, SIGNAL(contentsChange(int,int,int)), this, SLOT(_q_reformatBlocks(int,int,int))); QTextCursor cursor(d->doc); cursor.beginEditBlock(); for (QTextBlock blk = d->doc->begin(); blk.isValid(); blk = blk.next()) blk.layout()->clearAdditionalFormats(); cursor.endEditBlock(); } d->doc = doc; if (d->doc) { connect(d->doc, SIGNAL(contentsChange(int,int,int)), this, SLOT(_q_reformatBlocks(int,int,int))); d->rehighlightPending = true; QTimer::singleShot(0, this, SLOT(_q_delayedRehighlight())); } } /*! Returns the QTextDocument on which this syntax highlighter is installed. */ QTextDocument *SyntaxHighlighter::document() const { Q_D(const SyntaxHighlighter); return d->doc; } /*! \since 4.2 Reapplies the highlighting to the whole document. \sa rehighlightBlock() */ void SyntaxHighlighter::rehighlight() { Q_D(SyntaxHighlighter); if (!d->doc) return; QTextCursor cursor(d->doc); d->rehighlight(cursor, QTextCursor::End); } /*! \since 4.6 Reapplies the highlighting to the given QTextBlock \a block. \sa rehighlight() */ void SyntaxHighlighter::rehighlightBlock(const QTextBlock &block) { Q_D(SyntaxHighlighter); if (!d->doc || !block.isValid() || block.document() != d->doc) return; const bool rehighlightPending = d->rehighlightPending; QTextCursor cursor(block); d->rehighlight(cursor, QTextCursor::EndOfBlock); if (rehighlightPending) d->rehighlightPending = rehighlightPending; } /*! \fn void SyntaxHighlighter::highlightBlock(const QString &text) Highlights the given text block. This function is called when necessary by the rich text engine, i.e. on text blocks which have changed. To provide your own syntax highlighting, you must subclass SyntaxHighlighter and reimplement highlightBlock(). In your reimplementation you should parse the block's \a text and call setFormat() as often as necessary to apply any font and color changes that you require. For example: \snippet doc/src/snippets/code/src_gui_text_SyntaxHighlighter.cpp 3 Some syntaxes can have constructs that span several text blocks. For example, a C++ syntax highlighter should be able to cope with \c{/}\c{*...*}\c{/} multiline comments. To deal with these cases it is necessary to know the end state of the previous text block (e.g. "in comment"). Inside your highlightBlock() implementation you can query the end state of the previous text block using the previousBlockState() function. After parsing the block you can save the last state using setCurrentBlockState(). The currentBlockState() and previousBlockState() functions return an int value. If no state is set, the returned value is -1. You can designate any other value to identify any given state using the setCurrentBlockState() function. Once the state is set the QTextBlock keeps that value until it is set set again or until the corresponding paragraph of text gets deleted. For example, if you're writing a simple C++ syntax highlighter, you might designate 1 to signify "in comment". For a text block that ended in the middle of a comment you'd set 1 using setCurrentBlockState, and for other paragraphs you'd set 0. In your parsing code if the return value of previousBlockState() is 1, you would highlight the text as a C++ comment until you reached the closing \c{*}\c{/}. \sa previousBlockState(), setFormat(), setCurrentBlockState() */ /*! This function is applied to the syntax highlighter's current text block (i.e. the text that is passed to the highlightBlock() function). The specified \a format is applied to the text from the \a start position for a length of \a count characters (if \a count is 0, nothing is done). The formatting properties set in \a format are merged at display time with the formatting information stored directly in the document, for example as previously set with QTextCursor's functions. Note that the document itself remains unmodified by the format set through this function. \sa format(), highlightBlock() */ void SyntaxHighlighter::setFormat(int start, int count, const QTextCharFormat &format, int id) { Q_D(SyntaxHighlighter); if (start < 0 || start >= d->formatChanges.count()) return; const int end = qMin(start + count, d->formatChanges.count()); for (int i = start; i < end; ++i) d->formatChanges[i] = format; if (id >= Normal) { int offset = start; int count = end-start; if (!d->tokens.empty()) { SyntaxToken &last = d->tokens.last(); if ((last.id == id) && (last.offset+last.count == offset)) { last.count += count; return; } } SyntaxToken token; token.offset = offset; token.count = count; token.id = id; d->tokens.append(token); } } /*! \overload The specified \a color is applied to the current text block from the \a start position for a length of \a count characters. The other attributes of the current text block, e.g. the font and background color, are reset to default values. \sa format(), highlightBlock() */ //void SyntaxHighlighter::setFormat(int start, int count, const QColor &color) //{ // QTextCharFormat format; // format.setForeground(color); // setFormat(start, count, format); //} /*! \overload The specified \a font is applied to the current text block from the \a start position for a length of \a count characters. The other attributes of the current text block, e.g. the font and background color, are reset to default values. \sa format(), highlightBlock() */ //void SyntaxHighlighter::setFormat(int start, int count, const QFont &font) //{ // QTextCharFormat format; // format.setFont(font); // setFormat(start, count, format); //} void SyntaxHighlighter::applyFormatToSpaces(const QString &text, const QTextCharFormat &format) { int offset = 0; const int length = text.length(); while (offset < length) { if (text.at(offset).isSpace()) { int start = offset++; while (offset < length && text.at(offset).isSpace()) ++offset; setFormat(start, offset - start, format); } else { ++offset; } } } /*! \fn QTextCharFormat SyntaxHighlighter::format(int position) const Returns the format at \a position inside the syntax highlighter's current text block. */ QTextCharFormat SyntaxHighlighter::format(int pos) const { Q_D(const SyntaxHighlighter); if (pos < 0 || pos >= d->formatChanges.count()) return QTextCharFormat(); return d->formatChanges.at(pos); } /*! Returns the end state of the text block previous to the syntax highlighter's current block. If no value was previously set, the returned value is -1. \sa highlightBlock(), setCurrentBlockState() */ int SyntaxHighlighter::previousBlockState() const { Q_D(const SyntaxHighlighter); if (!d->currentBlock.isValid()) return -1; const QTextBlock previous = d->currentBlock.previous(); if (!previous.isValid()) return -1; return previous.userState(); } /*! Returns the state of the current text block. If no value is set, the returned value is -1. */ int SyntaxHighlighter::currentBlockState() const { Q_D(const SyntaxHighlighter); if (!d->currentBlock.isValid()) return -1; return d->currentBlock.userState(); } /*! Sets the state of the current text block to \a newState. \sa highlightBlock() */ void SyntaxHighlighter::setCurrentBlockState(int newState) { Q_D(SyntaxHighlighter); if (!d->currentBlock.isValid()) return; d->currentBlock.setUserState(newState); } /*! Attaches the given \a data to the current text block. The ownership is passed to the underlying text document, i.e. the provided QTextBlockUserData object will be deleted if the corresponding text block gets deleted. QTextBlockUserData can be used to store custom settings. In the case of syntax highlighting, it is in particular interesting as cache storage for information that you may figure out while parsing the paragraph's text. For example while parsing the text, you can keep track of parenthesis characters that you encounter ('{[(' and the like), and store their relative position and the actual QChar in a simple class derived from QTextBlockUserData: \snippet doc/src/snippets/code/src_gui_text_SyntaxHighlighter.cpp 4 During cursor navigation in the associated editor, you can ask the current QTextBlock (retrieved using the QTextCursor::block() function) if it has a user data object set and cast it to your \c BlockData object. Then you can check if the current cursor position matches with a previously recorded parenthesis position, and, depending on the type of parenthesis (opening or closing), find the next opening or closing parenthesis on the same level. In this way you can do a visual parenthesis matching and highlight from the current cursor position to the matching parenthesis. That makes it easier to spot a missing parenthesis in your code and to find where a corresponding opening/closing parenthesis is when editing parenthesis intensive code. \sa QTextBlock::setUserData() */ void SyntaxHighlighter::setCurrentBlockUserData(QTextBlockUserData *data) { Q_D(SyntaxHighlighter); if (!d->currentBlock.isValid()) return; d->currentBlock.setUserData(data); } /*! Returns the QTextBlockUserData object previously attached to the current text block. \sa QTextBlock::userData(), setCurrentBlockUserData() */ QTextBlockUserData *SyntaxHighlighter::currentBlockUserData() const { Q_D(const SyntaxHighlighter); if (!d->currentBlock.isValid()) return 0; return d->currentBlock.userData(); } /*! \since 4.4 Returns the current text block. */ QTextBlock SyntaxHighlighter::currentBlock() const { Q_D(const SyntaxHighlighter); return d->currentBlock; } static bool byStartOfRange(const QTextLayout::FormatRange &range, const QTextLayout::FormatRange &other) { return range.start < other.start; } void SyntaxHighlighter::setExtraAdditionalFormats(const QTextBlock& block, const QList<QTextLayout::FormatRange> &fmts) { // qDebug() << "setAdditionalFormats() on block" << block.blockNumber(); // for (int i = 0; i < overrides.count(); ++i) // qDebug() << " from " << overrides.at(i).start << "length" // << overrides.at(i).length // << "color:" << overrides.at(i).format.foreground().color(); Q_D(SyntaxHighlighter); if (block.layout() == 0) return; QList<QTextLayout::FormatRange> formats; formats.reserve(fmts.size()); foreach (QTextLayout::FormatRange r, fmts) { r.format.setProperty(QTextFormat::UserProperty, true); formats.append(r); } qSort(formats.begin(), formats.end(), byStartOfRange); QList<QTextLayout::FormatRange> previousSemanticFormats; QList<QTextLayout::FormatRange> formatsToApply; const QList<QTextLayout::FormatRange> all = block.layout()->additionalFormats(); foreach (const QTextLayout::FormatRange &r, all) { if (r.format.hasProperty(QTextFormat::UserProperty)) previousSemanticFormats.append(r); else formatsToApply.append(r); } if (formats.size() == previousSemanticFormats.size()) { qSort(previousSemanticFormats.begin(), previousSemanticFormats.end(), byStartOfRange); int index = 0; for (; index != formats.size(); ++index) { const QTextLayout::FormatRange &range = formats.at(index); const QTextLayout::FormatRange &previousRange = previousSemanticFormats.at(index); if (range.start != previousRange.start || range.length != previousRange.length || range.format != previousRange.format) break; } if (index == formats.size()) return; } formatsToApply += formats; bool wasInReformatBlocks = d->inReformatBlocks; d->inReformatBlocks = true; block.layout()->setAdditionalFormats(formatsToApply); document()->markContentsDirty(block.position(), block.length()-1); d->inReformatBlocks = wasInReformatBlocks; } #include "moc_syntaxhighlighter.cpp"
27,476
C++
.cpp
671
35.789866
116
0.70652
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,273
katehighlighter.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_texteditor/katehighlighter.cpp
#include "katehighlighter.h" #include "generichighlighter/highlighter.h" #include "generichighlighter/highlightdefinition.h" #include "generichighlighter/highlightdefinitionhandler.h" #include "generichighlighter/highlighterexception.h" #include "generichighlighter/highlightdefinitionmetadata.h" #include "generichighlighter/manager2.h" #include "texteditorconstants.h" #include <QDir> #include <QFileInfo> #include <QXmlStreamReader> #include "colorstyle/colorstyle.h" using namespace TextEditor::Internal; using namespace TextEditor::Constants; using namespace TextEditor; KateHighlighter::KateHighlighter(QObject *parent) : QObject(parent) { } void KateHighlighter::loadPath(const QString &definitionsPaths) { Manager2::instance()->loadPath(QStringList(definitionsPaths)); } QStringList KateHighlighter::mimeTypes() const { return Manager2::instance()->mimeTypes(); } QString KateHighlighter::mimeTypeName(const QString &mimeType) const { QString id = Manager2::instance()->definitionIdByMimeType(mimeType); QSharedPointer<HighlightDefinitionMetaData> data = Manager2::instance()->definitionMetaData(id); if (data) { return data->name(); } return QString(); } QStringList KateHighlighter::mimeTypePatterns(const QString &mimeType) const { QString id = Manager2::instance()->definitionIdByMimeType(mimeType); QSharedPointer<HighlightDefinitionMetaData> data = Manager2::instance()->definitionMetaData(id); if (data) { return data->patterns(); } return QStringList(); } TextEditor::SyntaxHighlighter *KateHighlighter::create(QTextDocument *doc, const QString &mimeType) { Highlighter *h = new Highlighter(doc); //reset(h); QString id = Manager2::instance()->definitionIdByMimeType(mimeType); QSharedPointer<HighlightDefinition> def = Manager2::instance()->definition(id); if (def) { SyntaxComment comment; comment.singleLineComment = def->singleLineComment(); comment.multiLineCommentStart = def->multiLineCommentStart(); comment.multiLineCommentEnd = def->multiLineCommentEnd(); comment.isCommentAfterWhiteSpaces = def->isCommentAfterWhiteSpaces(); if (comment.isCommentAfterWhiteSpaces) { comment.isCommentAfterWhiteSpacesAddSpace = true; } h->setupComment(comment); h->setDefaultContext(def->initialContext()); } return h; }
2,419
C++
.cpp
65
33.307692
100
0.765885
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,278
manager2.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_texteditor/generichighlighter/manager2.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "manager2.h" #include "highlighter.h" #include "highlightdefinition.h" #include "highlightdefinitionhandler.h" #include "highlighterexception.h" #include "highlightdefinitionmetadata.h" #include <QDir> #include <QFileInfo> #include <QXmlStreamReader> using namespace TextEditor::Internal; Manager2 *Manager2::instance() { static Manager2 manager; return &manager; } QSharedPointer<HighlightDefinitionMetaData> Manager2::parseMetadata(const QFileInfo &fileInfo) { static const QLatin1Char kSemiColon(';'); static const QLatin1Char kSpace(' '); static const QLatin1Char kDash('-'); static const QLatin1String kLanguage("language"); static const QLatin1String kArtificial("text/x-artificial-"); QFile definitionFile(fileInfo.absoluteFilePath()); if (!definitionFile.open(QIODevice::ReadOnly | QIODevice::Text)) return QSharedPointer<HighlightDefinitionMetaData>(); QSharedPointer<HighlightDefinitionMetaData> metaData(new HighlightDefinitionMetaData); QXmlStreamReader reader(&definitionFile); while (!reader.atEnd() && !reader.hasError()) { if (reader.readNext() == QXmlStreamReader::StartElement && reader.name() == kLanguage) { const QXmlStreamAttributes &atts = reader.attributes(); metaData->setFileName(fileInfo.fileName()); metaData->setId(fileInfo.absoluteFilePath()); metaData->setName(atts.value(HighlightDefinitionMetaData::kName).toString()); metaData->setVersion(atts.value(HighlightDefinitionMetaData::kVersion).toString()); metaData->setPriority(atts.value(HighlightDefinitionMetaData::kPriority).toString() .toInt()); metaData->setPatterns(atts.value(HighlightDefinitionMetaData::kExtensions) .toString().split(kSemiColon, qtSkipEmptyParts)); QStringList mimeTypes = atts.value(HighlightDefinitionMetaData::kMimeType). toString().split(kSemiColon, qtSkipEmptyParts); if (mimeTypes.isEmpty()) { // There are definitions which do not specify a MIME type, but specify file // patterns. Creating an artificial MIME type is a workaround. QString artificialType(kArtificial); artificialType.append(metaData->name().trimmed().replace(kSpace, kDash)); mimeTypes.append(artificialType); } metaData->setMimeTypes(mimeTypes); break; } } reader.clear(); definitionFile.close(); return metaData; } struct PriorityComp { bool operator()(const QSharedPointer<HighlightDefinitionMetaData> &a, const QSharedPointer<HighlightDefinitionMetaData> &b) { return a->priority() > b->priority(); } }; void Manager2::loadPath(const QStringList &definitionsPaths) { foreach (const QString &path, definitionsPaths) { if (path.isEmpty()) continue; QDir definitionsDir(path); QStringList filter(QLatin1String("*.xml")); definitionsDir.setNameFilters(filter); QList<QSharedPointer<HighlightDefinitionMetaData> > allMetaData; const QFileInfoList &filesInfo = definitionsDir.entryInfoList(); foreach (const QFileInfo &fileInfo, filesInfo) { const QSharedPointer<HighlightDefinitionMetaData> &metaData = parseMetadata(fileInfo); if (!metaData.isNull()) allMetaData.append(metaData); } // Consider definitions with higher priority first. qSort(allMetaData.begin(), allMetaData.end(), PriorityComp()); foreach (const QSharedPointer<HighlightDefinitionMetaData> &metaData, allMetaData) { if (m_idByName.contains(metaData->name())) // Name already exists... This is a fallback item, do not consider it. continue; const QString &id = metaData->id(); m_idByName.insert(metaData->name(), id); m_definitionsMetaData.insert(id, metaData); foreach (const QString &type, metaData->mimeTypes()) { if (m_idByMimeType.contains(type)) continue; m_idByMimeType.insert(type, id); } // static const QStringList textPlain(QLatin1String("text/plain")); // // A definition can specify multiple MIME types and file extensions/patterns. // // However, each thing is done with a single string. There is no direct way to // // tell which patterns belong to which MIME types nor whether a MIME type is just // // an alias for the other. Currently, I associate all patterns with all MIME // // types from a definition. // QList<Core::MimeGlobPattern> globPatterns; // foreach (const QString &type, metaData->mimeTypes()) { // if (m_idByMimeType.contains(type)) // continue; // m_idByMimeType.insert(type, id); // Core::MimeType mimeType = mimeDatabase->findByType(type); // if (mimeType.isNull()) { // mimeType.setType(type); // mimeType.setSubClassesOf(textPlain); // mimeType.setComment(metaData->name()); // // If there's a user modification for this mime type, we want to use the // // modified patterns and rule-based matchers. If not, just consider what // // is specified in the definition file. // QHash<QString, Core::MimeType>::const_iterator it = // userModified.find(mimeType.type()); // if (it == userModified.end()) { // if (globPatterns.isEmpty()) { // foreach (const QString &pattern, metaData->patterns()) { // static const QLatin1String mark("*."); // if (pattern.startsWith(mark)) { // const QString &suffix = pattern.right(pattern.length() - 2); // if (!knownSuffixes.contains(suffix)) // knownSuffixes.insert(suffix); // else // continue; // } // QRegExp regExp(pattern, Qt::CaseSensitive, QRegExp::Wildcard); // globPatterns.append(Core::MimeGlobPattern(regExp, 50)); // } // } // mimeType.setGlobPatterns(globPatterns); // } else { // mimeType.setGlobPatterns(it.value().globPatterns()); // mimeType.setMagicRuleMatchers(it.value().magicRuleMatchers()); // } // mimeDatabase->addMimeType(mimeType); // future.reportResult(mimeType); // } // } } } } QString Manager2::definitionIdByName(const QString &name) const { return m_idByName.value(name); } QString Manager2::definitionIdByMimeType(const QString &mimeType) const { return m_idByMimeType.value(mimeType); } QStringList Manager2::mimeTypes() const { return m_idByMimeType.keys(); } QString Manager2::definitionIdByAnyMimeType(const QStringList &mimeTypes) const { QString definitionId; foreach (const QString &mimeType, mimeTypes) { definitionId = definitionIdByMimeType(mimeType); if (!definitionId.isEmpty()) break; } return definitionId; } QSharedPointer<HighlightDefinition> Manager2::definition(const QString &id) { if (!id.isEmpty() && !m_definitions.contains(id)) { QFile definitionFile(id); if (!definitionFile.open(QIODevice::ReadOnly | QIODevice::Text)) return QSharedPointer<HighlightDefinition>(); QSharedPointer<HighlightDefinition> definition(new HighlightDefinition); HighlightDefinitionHandler handler(definition); QXmlInputSource source(&definitionFile); QXmlSimpleReader reader; reader.setContentHandler(&handler); m_isBuilding.insert(id); try { reader.parse(source); } catch (HighlighterException &) { definition.clear(); } m_isBuilding.remove(id); definitionFile.close(); m_definitions.insert(id, definition); } return m_definitions.value(id); } QSharedPointer<HighlightDefinitionMetaData> Manager2::definitionMetaData(const QString &id) const { return m_definitionsMetaData.value(id); } bool Manager2::isBuildingDefinition(const QString &id) const { return m_isBuilding.contains(id); }
10,289
C++
.cpp
216
41.958333
98
0.626408
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,281
context.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_texteditor/generichighlighter/context.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "context.h" using namespace TextEditor; using namespace Internal; Context::Context() : m_fallthrough(false), m_dynamic(false) {} Context::Context(const Context &context) : m_id(context.m_id), m_name(context.m_name), m_lineBeginContext(context.m_lineBeginContext), m_lineEndContext(context.m_lineEndContext), m_fallthroughContext(context.m_fallthroughContext), m_itemData(context.m_itemData), m_fallthrough(context.m_fallthrough), m_dynamic(context.m_dynamic), m_instructions(context.m_instructions), m_definition(context.m_definition) { // Rules need to be deeply copied because of dynamic contexts. foreach (const QSharedPointer<Rule> &rule, context.m_rules) m_rules.append(QSharedPointer<Rule>(rule->clone())); } Context::~Context() {}
2,167
C++
.cpp
50
41.48
99
0.711374
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,285
manager.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_texteditor/generichighlighter/manager.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "manager.h" #include "highlightdefinition.h" #include "highlightdefinitionhandler.h" #include "highlighterexception.h" //#include "definitiondownloader.h" //#include "highlightersettings.h" #include <QtCore/QtAlgorithms> #include <QtCore/QtPlugin> #include <QtCore/QString> #include <QtCore/QLatin1Char> #include <QtCore/QLatin1String> #include <QtCore/QStringList> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QDir> #include <QtCore/QRegExp> #include <QtCore/QFuture> #include <QtCore/QtConcurrentRun> #include <QtCore/QtConcurrentMap> #include <QtCore/QUrl> #include <QtCore/QSet> #include <QtGui/QDesktopServices> #include <QtGui/QMessageBox> #include <QtXml/QXmlSimpleReader> #include <QtXml/QXmlInputSource> #include <QtXml/QXmlStreamReader> #include <QtXml/QXmlStreamAttributes> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <QtAlgorithms> using namespace TextEditor; using namespace Internal; Manager::Manager() : m_downloadingDefinitions(false), m_registeringMimeTypes(false), m_queuedMimeTypeRegistrations(0) { //connect(&m_mimeTypeWatcher, SIGNAL(resultReadyAt(int)), this, SLOT(registerMimeType(int))); //connect(&m_mimeTypeWatcher, SIGNAL(finished()), this, SLOT(registerMimeTypesFinished())); connect(&m_downloadWatcher, SIGNAL(finished()), this, SLOT(downloadDefinitionsFinished())); } Manager::~Manager() {} Manager *Manager::instance() { static Manager manager; return &manager; } QString Manager::definitionIdByName(const QString &name) const { return m_idByName.value(name); } QString Manager::definitionIdByMimeType(const QString &mimeType) const { return m_idByMimeType.value(mimeType); } QString Manager::definitionIdByAnyMimeType(const QStringList &mimeTypes) const { QString definitionId; foreach (const QString &mimeType, mimeTypes) { definitionId = definitionIdByMimeType(mimeType); if (!definitionId.isEmpty()) break; } return definitionId; } QSharedPointer<HighlightDefinition> Manager::definition(const QString &id) { if (!id.isEmpty() && !m_definitions.contains(id)) { QFile definitionFile(id); if (!definitionFile.open(QIODevice::ReadOnly | QIODevice::Text)) return QSharedPointer<HighlightDefinition>(); QSharedPointer<HighlightDefinition> definition(new HighlightDefinition); HighlightDefinitionHandler handler(definition); QXmlInputSource source(&definitionFile); QXmlSimpleReader reader; reader.setContentHandler(&handler); m_isBuilding.insert(id); try { reader.parse(source); } catch (HighlighterException &) { definition.clear(); } m_isBuilding.remove(id); definitionFile.close(); m_definitions.insert(id, definition); } return m_definitions.value(id); } QSharedPointer<HighlightDefinitionMetaData> Manager::definitionMetaData(const QString &id) const { return m_definitionsMetaData.value(id); } bool Manager::isBuildingDefinition(const QString &id) const { return m_isBuilding.contains(id); } void Manager::loadFromPath(const QStringList & definitionsPaths) { foreach (const QString &path, definitionsPaths) { if (path.isEmpty()) continue; QDir definitionsDir(path); QStringList filter(QLatin1String("*.xml")); definitionsDir.setNameFilters(filter); QList<QSharedPointer<HighlightDefinitionMetaData> > allMetaData; const QFileInfoList &filesInfo = definitionsDir.entryInfoList(); foreach (const QFileInfo &fileInfo, filesInfo) { const QSharedPointer<HighlightDefinitionMetaData> &metaData = parseMetadata(fileInfo); if (!metaData.isNull()) allMetaData.append(metaData); } // Consider definitions with higher priority first. qSort(allMetaData.begin(), allMetaData.end(), PriorityComp()); foreach (const QSharedPointer<HighlightDefinitionMetaData> &metaData, allMetaData) { if (m_idByName.contains(metaData->name())) // Name already exists... This is a fallback item, do not consider it. continue; const QString &id = metaData->id(); m_idByName.insert(metaData->name(), id); m_definitionsMetaData.insert(id, metaData); qDebug() << metaData->mimeTypes(); foreach (const QString &type, metaData->mimeTypes()) { if (m_idByMimeType.contains(type)) continue; m_idByMimeType.insert(type, id); } // static const QStringList textPlain(QLatin1String("text/plain")); // // A definition can specify multiple MIME types and file extensions/patterns. // // However, each thing is done with a single string. There is no direct way to // // tell which patterns belong to which MIME types nor whether a MIME type is just // // an alias for the other. Currently, I associate all patterns with all MIME // // types from a definition. // QList<Core::MimeGlobPattern> globPatterns; // foreach (const QString &type, metaData->mimeTypes()) { // if (m_idByMimeType.contains(type)) // continue; // m_idByMimeType.insert(type, id); // Core::MimeType mimeType = mimeDatabase->findByType(type); // if (mimeType.isNull()) { // mimeType.setType(type); // mimeType.setSubClassesOf(textPlain); // mimeType.setComment(metaData->name()); // // If there's a user modification for this mime type, we want to use the // // modified patterns and rule-based matchers. If not, just consider what // // is specified in the definition file. // QHash<QString, Core::MimeType>::const_iterator it = // userModified.find(mimeType.type()); // if (it == userModified.end()) { // if (globPatterns.isEmpty()) { // foreach (const QString &pattern, metaData->patterns()) { // static const QLatin1String mark("*."); // if (pattern.startsWith(mark)) { // const QString &suffix = pattern.right(pattern.length() - 2); // if (!knownSuffixes.contains(suffix)) // knownSuffixes.insert(suffix); // else // continue; // } // QRegExp regExp(pattern, Qt::CaseSensitive, QRegExp::Wildcard); // globPatterns.append(Core::MimeGlobPattern(regExp, 50)); // } // } // mimeType.setGlobPatterns(globPatterns); // } else { // mimeType.setGlobPatterns(it.value().globPatterns()); // mimeType.setMagicRuleMatchers(it.value().magicRuleMatchers()); // } // mimeDatabase->addMimeType(mimeType); // future.reportResult(mimeType); // } // } } } } void Manager::registerMimeTypes() { // if (!m_registeringMimeTypes) { // m_registeringMimeTypes = true; // clear(); // QFuture<Core::MimeType> future = // QtConcurrent::run(&Manager::gatherDefinitionsMimeTypes, this); // m_mimeTypeWatcher.setFuture(future); // Core::ICore::instance()->progressManager()->addTask(future, // tr("Registering definitions"), // Constants::TASK_REGISTER_DEFINITIONS); // } else { // // QFutures returned from QConcurrent::run cannot be cancelled. So the queue. // ++m_queuedMimeTypeRegistrations; // } } //void Manager::gatherDefinitionsMimeTypes(QFutureInterface<Core::MimeType> &future) //{ // // Please be aware of the following limitation in the current implementation. // // The generic highlighter only register its types after all other plugins // // have populated Creator's MIME database (so it does not override anything). // // When the generic highlighter settings change only its internal data is cleaned-up // // and rebuilt. Creator's MIME database is not touched. So depending on how the // // user plays around with the generic highlighter file definitions (changing // // duplicated patterns, for example), some changes might not be reflected. // // A definitive implementation would require some kind of re-load or update // // (considering hierarchies, aliases, etc) of the MIME database whenever there // // is a change in the generic highlighter settings. // QStringList definitionsPaths; // const HighlighterSettings &settings = TextEditorSettings::instance()->highlighterSettings(); // definitionsPaths.append(settings.definitionFilesPath()); // if (settings.useFallbackLocation()) // definitionsPaths.append(settings.fallbackDefinitionFilesPath()); // Core::MimeDatabase *mimeDatabase = Core::ICore::instance()->mimeDatabase(); // QSet<QString> knownSuffixes = QSet<QString>::fromList(mimeDatabase->suffixes()); // QHash<QString, Core::MimeType> userModified; // const QList<Core::MimeType> &userMimeTypes = mimeDatabase->readUserModifiedMimeTypes(); // foreach (const Core::MimeType &userMimeType, userMimeTypes) // userModified.insert(userMimeType.type(), userMimeType); // foreach (const QString &path, definitionsPaths) { // if (path.isEmpty()) // continue; // QDir definitionsDir(path); // QStringList filter(QLatin1String("*.xml")); // definitionsDir.setNameFilters(filter); // QList<QSharedPointer<HighlightDefinitionMetaData> > allMetaData; // const QFileInfoList &filesInfo = definitionsDir.entryInfoList(); // foreach (const QFileInfo &fileInfo, filesInfo) { // const QSharedPointer<HighlightDefinitionMetaData> &metaData = parseMetadata(fileInfo); // if (!metaData.isNull()) // allMetaData.append(metaData); // } // // Consider definitions with higher priority first. // qSort(allMetaData.begin(), allMetaData.end(), PriorityComp()); // foreach (const QSharedPointer<HighlightDefinitionMetaData> &metaData, allMetaData) { // if (m_idByName.contains(metaData->name())) // // Name already exists... This is a fallback item, do not consider it. // continue; // const QString &id = metaData->id(); // m_idByName.insert(metaData->name(), id); // m_definitionsMetaData.insert(id, metaData); // static const QStringList textPlain(QLatin1String("text/plain")); // // A definition can specify multiple MIME types and file extensions/patterns. // // However, each thing is done with a single string. There is no direct way to // // tell which patterns belong to which MIME types nor whether a MIME type is just // // an alias for the other. Currently, I associate all patterns with all MIME // // types from a definition. // QList<Core::MimeGlobPattern> globPatterns; // foreach (const QString &type, metaData->mimeTypes()) { // if (m_idByMimeType.contains(type)) // continue; // m_idByMimeType.insert(type, id); // Core::MimeType mimeType = mimeDatabase->findByType(type); // if (mimeType.isNull()) { // mimeType.setType(type); // mimeType.setSubClassesOf(textPlain); // mimeType.setComment(metaData->name()); // // If there's a user modification for this mime type, we want to use the // // modified patterns and rule-based matchers. If not, just consider what // // is specified in the definition file. // QHash<QString, Core::MimeType>::const_iterator it = // userModified.find(mimeType.type()); // if (it == userModified.end()) { // if (globPatterns.isEmpty()) { // foreach (const QString &pattern, metaData->patterns()) { // static const QLatin1String mark("*."); // if (pattern.startsWith(mark)) { // const QString &suffix = pattern.right(pattern.length() - 2); // if (!knownSuffixes.contains(suffix)) // knownSuffixes.insert(suffix); // else // continue; // } // QRegExp regExp(pattern, Qt::CaseSensitive, QRegExp::Wildcard); // globPatterns.append(Core::MimeGlobPattern(regExp, 50)); // } // } // mimeType.setGlobPatterns(globPatterns); // } else { // mimeType.setGlobPatterns(it.value().globPatterns()); // mimeType.setMagicRuleMatchers(it.value().magicRuleMatchers()); // } // mimeDatabase->addMimeType(mimeType); // future.reportResult(mimeType); // } // } // } // } //} void Manager::registerMimeType(int index) const { //const Core::MimeType &mimeType = m_mimeTypeWatcher.resultAt(index); //TextEditorPlugin::instance()->editorFactory()->addMimeType(mimeType.type()); } void Manager::registerMimeTypesFinished() { m_registeringMimeTypes = false; if (m_queuedMimeTypeRegistrations > 0) { --m_queuedMimeTypeRegistrations; registerMimeTypes(); } else { emit mimeTypesRegistered(); } } QSharedPointer<HighlightDefinitionMetaData> Manager::parseMetadata(const QFileInfo &fileInfo) { static const QLatin1Char kSemiColon(';'); static const QLatin1Char kSpace(' '); static const QLatin1Char kDash('-'); static const QLatin1String kLanguage("language"); static const QLatin1String kArtificial("text/x-artificial-"); QFile definitionFile(fileInfo.absoluteFilePath()); if (!definitionFile.open(QIODevice::ReadOnly | QIODevice::Text)) return QSharedPointer<HighlightDefinitionMetaData>(); QSharedPointer<HighlightDefinitionMetaData> metaData(new HighlightDefinitionMetaData); QXmlStreamReader reader(&definitionFile); while (!reader.atEnd() && !reader.hasError()) { if (reader.readNext() == QXmlStreamReader::StartElement && reader.name() == kLanguage) { const QXmlStreamAttributes &atts = reader.attributes(); metaData->setFileName(fileInfo.fileName()); metaData->setId(fileInfo.absoluteFilePath()); metaData->setName(atts.value(HighlightDefinitionMetaData::kName).toString()); metaData->setVersion(atts.value(HighlightDefinitionMetaData::kVersion).toString()); metaData->setPriority(atts.value(HighlightDefinitionMetaData::kPriority).toString() .toInt()); metaData->setPatterns(atts.value(HighlightDefinitionMetaData::kExtensions) .toString().split(kSemiColon, QString::SkipEmptyParts)); QStringList mimeTypes = atts.value(HighlightDefinitionMetaData::kMimeType). toString().split(kSemiColon, QString::SkipEmptyParts); if (mimeTypes.isEmpty()) { // There are definitions which do not specify a MIME type, but specify file // patterns. Creating an artificial MIME type is a workaround. QString artificialType(kArtificial); artificialType.append(metaData->name().trimmed().replace(kSpace, kDash)); mimeTypes.append(artificialType); } metaData->setMimeTypes(mimeTypes); break; } } reader.clear(); definitionFile.close(); return metaData; } QList<HighlightDefinitionMetaData> Manager::parseAvailableDefinitionsList(QIODevice *device) const { static const QLatin1Char kSlash('/'); static const QLatin1String kDefinition("Definition"); QList<HighlightDefinitionMetaData> metaDataList; QXmlStreamReader reader(device); while (!reader.atEnd() && !reader.hasError()) { if (reader.readNext() == QXmlStreamReader::StartElement && reader.name() == kDefinition) { const QXmlStreamAttributes &atts = reader.attributes(); HighlightDefinitionMetaData metaData; metaData.setName(atts.value(HighlightDefinitionMetaData::kName).toString()); metaData.setVersion(atts.value(HighlightDefinitionMetaData::kVersion).toString()); QString url(atts.value(HighlightDefinitionMetaData::kUrl).toString()); metaData.setUrl(QUrl(url)); const int slash = url.lastIndexOf(kSlash); if (slash != -1) metaData.setFileName(url.right(url.length() - slash - 1)); metaDataList.append(metaData); } } reader.clear(); return metaDataList; } void Manager::downloadAvailableDefinitionsMetaData() { // QUrl url(QLatin1String("http://www.kate-editor.org/syntax/update-3.2.xml")); // QNetworkRequest request(url); // Currently this takes a couple of seconds on Windows 7: QTBUG-10106. // QNetworkReply *reply = m_networkManager.get(request); // connect(reply, SIGNAL(finished()), this, SLOT(downloadAvailableDefinitionsListFinished())); } void Manager::downloadAvailableDefinitionsListFinished() { // if (QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender())) { // if (reply->error() == QNetworkReply::NoError) // emit definitionsMetaDataReady(parseAvailableDefinitionsList(reply)); // else // emit errorDownloadingDefinitionsMetaData(); // reply->deleteLater(); // } } void Manager::downloadDefinitions(const QList<QUrl> &urls, const QString &savePath) { // m_downloaders.clear(); // foreach (const QUrl &url, urls) // m_downloaders.append(new DefinitionDownloader(url, savePath)); // m_downloadingDefinitions = true; // QFuture<void> future = QtConcurrent::map(m_downloaders, DownloaderStarter()); // m_downloadWatcher.setFuture(future); // Core::ICore::instance()->progressManager()->addTask(future, // tr("Downloading definitions"), // Constants::TASK_DOWNLOAD_DEFINITIONS); } void Manager::downloadDefinitionsFinished() { // int errors = 0; // bool writeError = false; // foreach (DefinitionDownloader *downloader, m_downloaders) { // DefinitionDownloader::Status status = downloader->status(); // if (status != DefinitionDownloader::Ok) { // ++errors; // if (status == DefinitionDownloader::WriteError && !writeError) // writeError = true; // } // delete downloader; // } // if (errors > 0) { // QString text; // if (errors == m_downloaders.size()) // text = tr("Error downloading selected definition(s)."); // else // text = tr("Error downloading one or more definitions."); // if (writeError) // text.append(tr("\nPlease check the directory's access rights.")); // QMessageBox::critical(0, tr("Download Error"), text); // } // m_downloadingDefinitions = false; } bool Manager::isDownloadingDefinitions() const { return m_downloadingDefinitions; } void Manager::clear() { m_idByName.clear(); m_idByMimeType.clear(); m_definitions.clear(); m_definitionsMetaData.clear(); }
21,864
C++
.cpp
453
44.406181
100
0.62678
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,294
proxymodel.cpp
visualfc_liteide/liteidex/src/3rdparty/qtc_itemview/proxymodel.cpp
#include "proxymodel.h" using namespace Core; ProxyModel::ProxyModel(QObject *parent) : QAbstractProxyModel(parent) { } QModelIndex ProxyModel::mapFromSource(const QModelIndex &sourceIndex) const { // root if (!sourceIndex.isValid()) return QModelIndex(); // hide the <no document> int row = sourceIndex.row() - 1; if (row < 0) return QModelIndex(); return createIndex(row, sourceIndex.column()); } QModelIndex ProxyModel::mapToSource(const QModelIndex &proxyIndex) const { if (!proxyIndex.isValid()) return QModelIndex(); // handle missing <no document> return sourceModel()->index(proxyIndex.row() + 1, proxyIndex.column()); } QModelIndex ProxyModel::index(int row, int column, const QModelIndex &parent) const { if (parent.isValid() || row < 0 || row >= sourceModel()->rowCount(mapToSource(parent)) - 1 || column < 0 || column > 1) return QModelIndex(); return createIndex(row, column); } QModelIndex ProxyModel::parent(const QModelIndex &child) const { Q_UNUSED(child) return QModelIndex(); } int ProxyModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) return sourceModel()->rowCount(mapToSource(parent)) - 1; return 0; } int ProxyModel::columnCount(const QModelIndex &parent) const { return sourceModel()->columnCount(mapToSource(parent)); } void ProxyModel::setSourceModel(QAbstractItemModel *sm) { QAbstractItemModel *previousModel = sourceModel(); if (previousModel) { disconnect(previousModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(sourceDataChanged(QModelIndex,QModelIndex))); disconnect(previousModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceRowsInserted(QModelIndex,int,int))); disconnect(previousModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceRowsRemoved(QModelIndex,int,int))); disconnect(previousModel, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(sourceRowsAboutToBeInserted(QModelIndex,int,int))); disconnect(previousModel, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(sourceRowsAboutToBeRemoved(QModelIndex,int,int))); } QAbstractProxyModel::setSourceModel(sm); if (sm) { connect(sm, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(sourceDataChanged(QModelIndex,QModelIndex))); connect(sm, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceRowsInserted(QModelIndex,int,int))); connect(sm, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceRowsRemoved(QModelIndex,int,int))); connect(sm, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(sourceRowsAboutToBeInserted(QModelIndex,int,int))); connect(sm, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(sourceRowsAboutToBeRemoved(QModelIndex,int,int))); } } QModelIndex ProxyModel::sibling(int row, int column, const QModelIndex &idx) const { return QAbstractItemModel::sibling(row, column, idx); } Qt::DropActions ProxyModel::supportedDragActions() const { return sourceModel()->supportedDragActions(); } void ProxyModel::sourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { QModelIndex topLeftIndex = mapFromSource(topLeft); if (!topLeftIndex.isValid()) topLeftIndex = index(0, topLeft.column()); QModelIndex bottomRightIndex = mapFromSource(bottomRight); if (!bottomRightIndex.isValid()) bottomRightIndex = index(0, bottomRight.column()); emit dataChanged(topLeftIndex, bottomRightIndex); } void ProxyModel::sourceRowsRemoved(const QModelIndex &parent, int start, int end) { Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) endRemoveRows(); } void ProxyModel::sourceRowsInserted(const QModelIndex &parent, int start, int end) { Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) endInsertRows(); } void ProxyModel::sourceRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) { int realStart = parent.isValid() || start == 0 ? start : start - 1; int realEnd = parent.isValid() || end == 0 ? end : end - 1; beginRemoveRows(parent, realStart, realEnd); } void ProxyModel::sourceRowsAboutToBeInserted(const QModelIndex &parent, int start, int end) { int realStart = parent.isValid() || start == 0 ? start : start - 1; int realEnd = parent.isValid() || end == 0 ? end : end - 1; beginInsertRows(parent, realStart, realEnd); }
4,839
C++
.cpp
118
34.542373
95
0.693325
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,295
testparser.cpp
visualfc_liteide/liteidex/src/3rdparty/qjson/tests/parser/testparser.cpp
/* This file is part of QJson * * Copyright (C) 2008 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <cmath> #include <QtCore/QVariant> #include <QtTest/QtTest> #include <QJson/Parser> #include <QJson/Serializer> class TestParser: public QObject { Q_OBJECT private slots: void parseNonAsciiString(); void parseSimpleObject(); void parseEmptyObject(); void parseEmptyValue(); void parseUrl(); void parseMultipleObject(); void parseSimpleArray(); void parseInvalidObject(); void parseInvalidObject_data(); void parseMultipleArray(); void testTrueFalseNullValues(); void testEscapeChars(); void testNumbers(); void testNumbers_data(); void testTopLevelValues(); void testTopLevelValues_data(); void testSpecialNumbers(); void testSpecialNumbers_data(); void testReadWrite(); void testReadWrite_data(); }; Q_DECLARE_METATYPE(QVariant) Q_DECLARE_METATYPE(QVariant::Type) using namespace QJson; void TestParser::parseSimpleObject() { QByteArray json = "{\"foo\":\"bar\"}"; QVariantMap map; map.insert (QLatin1String("foo"), QLatin1String("bar")); QVariant expected(map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseEmptyObject() { QByteArray json = "{}"; QVariantMap map; QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseEmptyValue() { QByteArray json = "{\"value\": \"\"}"; QVariantMap map; map.insert (QLatin1String("value"), QString(QLatin1String(""))); QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVERIFY (result.toMap().value(QLatin1String("value")).type() == QVariant::String); QString value = result.toMap().value(QLatin1String("value")).toString(); QVERIFY (value.isEmpty()); } void TestParser::parseInvalidObject() { QFETCH(QByteArray, json); Parser parser; bool ok; parser.parse (json, &ok); QVERIFY (!ok); } void TestParser::parseInvalidObject_data() { QTest::addColumn<QByteArray>("json"); QTest::newRow("unclosed object") << QByteArray("{\"foo\":\"bar\""); QTest::newRow("infinum (disallow") << QByteArray("Infinum"); QTest::newRow("Nan (disallow") << QByteArray("NaN"); } void TestParser::parseNonAsciiString() { QByteArray json = "{\"artist\":\"Queensr\\u00ffche\"}"; QVariantMap map; QChar unicode_char (0x00ff); QString unicode_string; unicode_string.setUnicode(&unicode_char, 1); unicode_string = QLatin1String("Queensr") + unicode_string + QLatin1String("che"); map.insert (QLatin1String("artist"), unicode_string); QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseMultipleObject() { //put also some extra spaces inside the json string QByteArray json = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QVariantMap map; map.insert (QLatin1String("foo"), QLatin1String("bar")); map.insert (QLatin1String("number"), 51.3); QVariantList list; list.append (QLatin1String("item1")); list.append (QLatin1String("123")); map.insert (QLatin1String("array"), list); QVariant expected (map); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVERIFY (result.toMap().value(QLatin1String("number")).canConvert<float>()); QVERIFY (result.toMap().value(QLatin1String("array")).canConvert<QVariantList>()); } void TestParser::parseUrl(){ //"http:\/\/www.last.fm\/venue\/8926427" QByteArray json = "[\"http:\\/\\/www.last.fm\\/venue\\/8926427\"]"; QVariantList list; list.append (QVariant(QLatin1String("http://www.last.fm/venue/8926427"))); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseSimpleArray() { QByteArray json = "[\"foo\",\"bar\"]"; QVariantList list; list.append (QLatin1String("foo")); list.append (QLatin1String("bar")); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::parseMultipleArray() { //put also some extra spaces inside the json string QByteArray json = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QVariantMap map; map.insert (QLatin1String("foo"), QLatin1String("bar")); QVariantList array; array.append (QLatin1String("item1")); array.append (123); QVariantList list; list.append (map); list.append (QLatin1String("number")); list.append (QLatin1String("51.3")); list.append ((QVariant) array); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestParser::testTrueFalseNullValues() { QByteArray json = "[true,false, null, {\"foo\" : true}]"; QVariantList list; list.append (QVariant(true)); list.append (QVariant(false)); list.append (QVariant()); QVariantMap map; map.insert (QLatin1String("foo"), true); list.append (map); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QCOMPARE (result.toList().at(0).toBool(), true); QCOMPARE (result.toList().at(1).toBool(), false); QVERIFY (result.toList().at(2).isNull()); } void TestParser::testEscapeChars() { QByteArray json = "[\"\\b \\f \\n \\r \\t \", \" \\\\ \\/ \\\\\", \"http:\\/\\/foo.com\"]"; QVariantList list; list.append (QLatin1String("\b \f \n \r \t ")); list.append (QLatin1String(" \\ / \\")); list.append (QLatin1String("http://foo.com")); QVariant expected (list); Parser parser; bool ok; QVariant result = parser.parse (json, &ok); QVERIFY (ok); QCOMPARE(result.toList().size(), expected.toList().size() ); QCOMPARE(result, expected); } void TestParser::testNumbers() { QFETCH(QByteArray, input); QFETCH(QVariant, expected); QFETCH(QVariant::Type, type); Parser parser; bool ok; QVariant result = parser.parse ('[' + input + ']', &ok); QVERIFY (ok); QVariant value = result.toList().at(0); QCOMPARE(value, expected); QCOMPARE( value.type(), type); } void TestParser::testNumbers_data() { QTest::addColumn<QByteArray>( "input" ); QTest::addColumn<QVariant>( "expected" ); QTest::addColumn<QVariant::Type>( "type" ); QByteArray input; QVariant output; // simple ulonglong input = QByteArray("1"); output = QVariant(QVariant::ULongLong); output.setValue(1); QTest::newRow("simple ulonglong") << input << output << QVariant::ULongLong; // big number input = QByteArray("12345678901234567890"); output = QVariant(QVariant::ULongLong); output.setValue(12345678901234567890ull); QTest::newRow("big number") << input << output << QVariant::ULongLong; // simple double input = QByteArray("2.004"); output = QVariant(QVariant::Double); output.setValue(2.004); QTest::newRow("simple double") << input << output << QVariant::Double; // negative int input = QByteArray("-100"); output = QVariant(QVariant::LongLong); output.setValue(-100); QTest::newRow("negative int") << input << output << QVariant::LongLong; // negative double input = QByteArray("-3.4"); output = QVariant(QVariant::Double); output.setValue(-3.4); QTest::newRow("negative double") << input << output << QVariant::Double; // exp1 input = QByteArray("-5e+"); output = QVariant(QVariant::ByteArray); output.setValue(input); QTest::newRow("exp1") << input << output << QVariant::ByteArray; // exp2 input = QByteArray("2e"); output = QVariant(QVariant::ByteArray); output.setValue(input); QTest::newRow("exp2") << input << output << QVariant::ByteArray; // exp3 input = QByteArray("3e+"); output = QVariant(QVariant::ByteArray); output.setValue(input); QTest::newRow("exp3") << input << output << QVariant::ByteArray; // exp4 input = QByteArray("4.3E"); output = QVariant(QVariant::ByteArray); output.setValue(input); QTest::newRow("exp4") << input << output << QVariant::ByteArray; // exp5 input = QByteArray("5.4E-"); output = QVariant(QVariant::ByteArray); output.setValue(input); QTest::newRow("exp5") << input << output << QVariant::ByteArray; } void TestParser::testTopLevelValues() { QFETCH(QByteArray, input); QFETCH(QVariant, expected); QFETCH(QVariant::Type, type); Parser parser; bool ok; QVariant result = parser.parse (input, &ok); QVERIFY (ok); QCOMPARE(result, expected); QCOMPARE(result.type(), type); } void TestParser::testTopLevelValues_data() { QTest::addColumn<QByteArray>( "input" ); QTest::addColumn<QVariant>( "expected" ); QTest::addColumn<QVariant::Type>( "type" ); QByteArray input; QVariant output; // string input = QByteArray("\"foo bar\""); output = QVariant(QLatin1String("foo bar")); QTest::newRow("string") << input << output << QVariant::String; // number input = QByteArray("2.4"); output = QVariant(QVariant::Double); output.setValue(2.4); QTest::newRow("simple double") << input << output << QVariant::Double; // boolean input = QByteArray("true"); output = QVariant(QVariant::Bool); output.setValue(true); QTest::newRow("bool") << input << output << QVariant::Bool; // null input = QByteArray("null"); output = QVariant(); QTest::newRow("null") << input << output << QVariant::Invalid; // array input = QByteArray("[1,2,3]"); QVariantList list; list << QVariant(1) << QVariant(2) << QVariant(3); output = QVariant(QVariant::List); output.setValue(list); QTest::newRow("array") << input << output << QVariant::List; // object input = QByteArray("{\"foo\" : \"bar\"}"); QVariantMap map; map.insert(QLatin1String("foo"), QLatin1String("bar")); output = QVariant(QVariant::Map); output.setValue(map); QTest::newRow("object") << input << output << QVariant::Map; } void TestParser::testSpecialNumbers() { QFETCH(QByteArray, input); QFETCH(bool, isOk); QFETCH(bool, isInfinity); QFETCH(bool, isNegative); QFETCH(bool, isNan); Parser parser; QVERIFY(!parser.specialNumbersAllowed()); parser.allowSpecialNumbers(true); QVERIFY(parser.specialNumbersAllowed()); bool ok; QVariant value = parser.parse(input, &ok); QCOMPARE(ok, isOk); QVERIFY(value.type() == QVariant::Double); if (ok) { double v = value.toDouble(); #ifdef Q_OS_SYMBIAN QCOMPARE(bool(isinf(v)), isInfinity); #else // skip this test for MSVC, because there is no "isinf" function. #ifndef Q_CC_MSVC QCOMPARE(bool(std::isinf(v)), isInfinity); #endif #endif QCOMPARE(v<0, isNegative); #ifdef Q_OS_SYMBIAN QCOMPARE(bool(isnan(v)), isNan); #else // skip this test for MSVC, because there is no "isinf" function. #ifndef Q_CC_MSVC QCOMPARE(bool(std::isnan(v)), isNan); #endif #endif } } void TestParser::testSpecialNumbers_data() { QTest::addColumn<QByteArray>("input"); QTest::addColumn<bool>("isOk"); QTest::addColumn<bool>("isInfinity"); QTest::addColumn<bool>("isNegative"); QTest::addColumn<bool>("isNan"); QTest::newRow("42.0") << QByteArray("42.0") << true << false << false << false; QTest::newRow("0.0") << QByteArray("0.0") << true << false << false << false; QTest::newRow("-42.0") << QByteArray("-42.0") << true << false << true << false; QTest::newRow("Infinity") << QByteArray("Infinity") << true << true << false << false; QTest::newRow("-Infinity") << QByteArray("-Infinity") << true << true << true << false; QTest::newRow("NaN") << QByteArray("NaN") << true << false << false << true; } void TestParser::testReadWrite() { QFETCH( QVariant, variant ); Serializer serializer; bool ok; QByteArray json = serializer.serialize(variant); QVERIFY(!json.isNull()); Parser parser; QVariant result = parser.parse( json, &ok ); QVERIFY(ok); QCOMPARE( result, variant ); } void TestParser::testReadWrite_data() { QTest::addColumn<QVariant>( "variant" ); // array tests QTest::newRow( "empty array" ) << QVariant(QVariantList()); // basic array QVariantList list; list << QString(QLatin1String("hello")); list << 12; QTest::newRow( "basic array" ) << QVariant(list); // simple map QVariantMap map; map[QString(QLatin1String("Name"))] = 32; QTest::newRow( "complicated array" ) << QVariant(map); } QTEST_MAIN(TestParser) #ifdef QMAKE_BUILD #include "testparser.moc" #else #include "moc_testparser.cxx" #endif
13,589
C++
.cpp
411
30.014599
93
0.693731
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
21,296
person.cpp
visualfc_liteide/liteidex/src/3rdparty/qjson/tests/qobjecthelper/person.cpp
#include "person.h" Person::Person(QObject* parent) : QObject(parent) , m_name() , m_phoneNumber(0) , m_gender(Female) { } Person::~Person() { } QString Person::name() const { return m_name; } void Person::setName(const QString& name) { m_name = name; } int Person::phoneNumber() const { return m_phoneNumber; } void Person::setPhoneNumber(const int phoneNumber) { m_phoneNumber = phoneNumber; } void Person::setGender(Gender gender) { m_gender = gender; } Person::Gender Person::gender() const { return m_gender; } QDate Person::dob() const { return m_dob; } void Person::setDob(const QDate& dob) { m_dob = dob; } QVariant Person::customField() const { return m_customField; } void Person::setCustomField(const QVariant& customField) { m_customField = customField; }
809
C++
.cpp
51
14.058824
56
0.736913
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
21,297
testqobjecthelper.cpp
visualfc_liteide/liteidex/src/3rdparty/qjson/tests/qobjecthelper/testqobjecthelper.cpp
/* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <limits> #include <QtCore/QVariant> #include <QtCore/QVariantList> #include <QtTest/QtTest> #include <QJson/Parser> #include <QJson/Serializer> #include <QJson/QObjectHelper> #include "person.h" class TestQObjectHelper: public QObject { Q_OBJECT private slots: void testQObject2QVariant(); void testQVariant2QObject(); }; using namespace QJson; void TestQObjectHelper::testQObject2QVariant() { QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); QVariantList nicknames; nicknames << QLatin1String("nickname1") << QLatin1String("nickname2"); Person person; person.setName(name); person.setPhoneNumber(phoneNumber); person.setGender(gender); person.setDob(dob); person.setCustomField(nicknames); QVariantMap expected; expected[QLatin1String("name")] = QVariant(name); expected[QLatin1String("phoneNumber")] = QVariant(phoneNumber); expected[QLatin1String("gender")] = QVariant(gender); expected[QLatin1String("dob")] = QVariant(dob); expected[QLatin1String("customField")] = nicknames; QVariantMap result = QObjectHelper::qobject2qvariant(&person); QCOMPARE(result, expected); } void TestQObjectHelper::testQVariant2QObject() { bool ok; QString name = QLatin1String("Flavio Castelli"); int phoneNumber = 123456; Person::Gender gender = Person::Male; QDate dob (1982, 7, 12); QVariantList nicknames; nicknames << QLatin1String("nickname1") << QLatin1String("nickname2"); Person expected_person; expected_person.setName(name); expected_person.setPhoneNumber(phoneNumber); expected_person.setGender(gender); expected_person.setDob(dob); expected_person.setCustomField(nicknames); QVariantMap variant = QObjectHelper::qobject2qvariant(&expected_person); Serializer serializer; QByteArray json = serializer.serialize(variant); Parser parser; QVariant parsedVariant = parser.parse(json,&ok); QVERIFY(ok); QVERIFY(parsedVariant.canConvert(QVariant::Map)); Person person; QObjectHelper::qvariant2qobject(parsedVariant.toMap(), &person); QCOMPARE(person.name(), name); QCOMPARE(person.phoneNumber(),phoneNumber); QCOMPARE(person.gender(), gender); QCOMPARE(person.dob(), dob); QCOMPARE(person.customField(), QVariant(nicknames)); } QTEST_MAIN(TestQObjectHelper) #ifdef QMAKE_BUILD #include "testqobjecthelper.moc" #else #include "moc_testqobjecthelper.cxx" #endif
3,295
C++
.cpp
94
32.468085
75
0.772399
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
21,298
testserializer.cpp
visualfc_liteide/liteidex/src/3rdparty/qjson/tests/serializer/testserializer.cpp
/* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <limits> #include <QtCore/QVariant> #include <QtTest/QtTest> #include <QJson/Parser> #include <QJson/Serializer> class TestSerializer: public QObject { Q_OBJECT private slots: void testReadWriteEmptyDocument(); void testReadWrite(); void testReadWrite_data(); void testValueNull(); void testValueString(); void testValueString_data(); void testValueStringList(); void testValueStringList_data(); void testValueInteger(); void testValueInteger_data(); void testValueDouble(); void testValueDouble_data(); void testSetDoublePrecision(); void testValueFloat(); void testValueFloat_data(); void testValueBoolean(); void testValueBoolean_data(); void testSpecialNumbers(); void testSpecialNumbers_data(); void testIndentation(); void testIndentation_data(); void testSerializetoQIODevice(); private: void valueTest( const QVariant& value, const QString& expectedRegExp, bool errorExpected = false ); void valueTest( const QObject* object, const QString& expectedRegExp ); }; Q_DECLARE_METATYPE(QVariant) using namespace QJson; void TestSerializer::testReadWriteEmptyDocument() { QByteArray json = ""; Parser parser; bool ok; QVariant result = parser.parse( json, &ok ); QVERIFY(ok); QVERIFY( ! result.isValid() ); Serializer serializer; const QByteArray serialized = serializer.serialize( result ); QVERIFY( !serialized.isNull() ); QByteArray expected = "null"; QCOMPARE(expected, serialized); } void TestSerializer::testReadWrite() { QFETCH( QByteArray, json ); Parser parser; bool ok; QVariant result = parser.parse( json, &ok ); QVERIFY(ok); Serializer serializer; const QByteArray serialized = serializer.serialize( result ); QVariant writtenThenRead = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( result, writtenThenRead ); } void TestSerializer::testReadWrite_data() { QTest::addColumn<QByteArray>( "json" ); // array tests QTest::newRow( "empty array" ) << QByteArray("[]"); QTest::newRow( "basic array" ) << QByteArray("[\"person\",\"bar\"]"); QTest::newRow( "single int array" ) << QByteArray("[6]"); QTest::newRow( "int array" ) << QByteArray("[6,5,6,7]"); const QByteArray json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]"; QTest::newRow( QByteArray("array of various numbers") ) << json; // document tests QTest::newRow( "empty object" ) << QByteArray("{}"); QTest::newRow( "basic document" ) << QByteArray("{\"person\":\"bar\"}"); QTest::newRow( "object with ints" ) << QByteArray("{\"person\":6}"); const QByteArray json2 = "{ \"person\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QTest::newRow( "complicated document" ) << json2; // more complex cases const QByteArray json3 = "[ {\"person\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QTest::newRow( "complicated array" ) << json3; } void TestSerializer::testIndentation() { QFETCH( QByteArray, json ); QFETCH( QByteArray, expected_compact ); QFETCH( QByteArray, expected_min ); QFETCH( QByteArray, expected_med ); QFETCH( QByteArray, expected_full ); // parse Parser parser; bool ok; QVariant parsed = parser.parse( json, &ok ); QVERIFY(ok); Serializer serializer; QVariant reparsed; QByteArray serialized; // serialize with indent compact and reparse serializer.setIndentMode(QJson::IndentCompact); serialized = serializer.serialize( parsed ); QCOMPARE( serialized, expected_compact); reparsed = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( parsed, reparsed); // serialize with indent minimum and reparse serializer.setIndentMode(QJson::IndentMinimum); serialized = serializer.serialize( parsed ); QCOMPARE( serialized, expected_min); reparsed = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( parsed, reparsed); // serialize with indent medium and reparse serializer.setIndentMode(QJson::IndentMedium); serialized = serializer.serialize( parsed ); QCOMPARE( serialized, expected_med); reparsed = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( parsed, reparsed); // serialize with indent full and reparse serializer.setIndentMode(QJson::IndentFull); serialized = serializer.serialize( parsed ); QCOMPARE( serialized, expected_full); reparsed = parser.parse( serialized, &ok ); QVERIFY(ok); QCOMPARE( parsed, reparsed); } void TestSerializer::testIndentation_data() { QTest::addColumn<QByteArray>( "json" ); QTest::addColumn<QByteArray>( "expected_compact" ); QTest::addColumn<QByteArray>( "expected_min" ); QTest::addColumn<QByteArray>( "expected_med" ); QTest::addColumn<QByteArray>( "expected_full" ); const QByteArray json = " { \"foo\" : 0, \"foo1\" : 1, \"foo2\" : [ { \"foo3\" : 3, \"foo4\" : 4 } ] }"; const QByteArray ex_compact = "{\"foo\":0,\"foo1\":1,\"foo2\":[{\"foo3\":3,\"foo4\":4}]}"; const QByteArray ex_min = "{ \"foo\" : 0, \"foo1\" : 1, \"foo2\" : [\n { \"foo3\" : 3, \"foo4\" : 4 }\n] }"; const QByteArray ex_med = "{\n \"foo\" : 0, \"foo1\" : 1, \"foo2\" : [\n {\n \"foo3\" : 3, \"foo4\" : 4\n }\n ]\n}"; const QByteArray ex_full = "{\n \"foo\" : 0,\n \"foo1\" : 1,\n \"foo2\" : [\n {\n \"foo3\" : 3,\n \"foo4\" : 4\n }\n ]\n}"; QTest::newRow( "test indents" ) << json << ex_compact << ex_min << ex_med << ex_full; } void TestSerializer::valueTest( const QVariant& value, const QString& expectedRegExp, bool errorExpected ) { Serializer serializer; const QByteArray serialized = serializer.serialize( value ); QCOMPARE(serialized.isNull(), errorExpected); const QString serializedUnicode = QString::fromUtf8( serialized ); if (!errorExpected) { QRegExp expected( expectedRegExp ); QVERIFY( expected.isValid() ); QVERIFY2( expected.exactMatch( serializedUnicode ), qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) ) .arg( expectedRegExp ).arg( serializedUnicode ) ) ); } } void TestSerializer::valueTest( const QObject* object, const QString& expectedRegExp ) { Serializer serializer; const QByteArray serialized = serializer.serialize( object ); const QString serializedUnicode = QString::fromUtf8( serialized ); QRegExp expected( expectedRegExp ); QVERIFY( expected.isValid() ); QVERIFY2( expected.exactMatch( serializedUnicode ), qPrintable( QString( QLatin1String( "Expected regexp \"%1\" but got \"%2\"." ) ) .arg( expectedRegExp ).arg( serializedUnicode ) ) ); } void TestSerializer::testValueNull() { valueTest( QVariant(), QLatin1String( "\\s*null\\s*" ) ); QVariantMap map; map[QLatin1String("value")] = QVariant(); valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:\\s*null\\s*\\}\\s*" ) ); } void TestSerializer::testValueString() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueString_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "null string" ) << QVariant( QString() ) << QString( QLatin1String( "\\s*\"\"\\s*" ) ); QTest::newRow( "empty string" ) << QVariant( QString( QLatin1String( "" ) ) ) << QString( QLatin1String( "\\s*\"\"\\s*" ) ); QTest::newRow( "Simple String" ) << QVariant( QString( QLatin1String( "simpleString" ) ) ) << QString( QLatin1String( "\\s*\"simpleString\"\\s*" ) ); QTest::newRow( "string with tab" ) << QVariant( QString( QLatin1String( "string\tstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\tstring\"\\s*" ) ); QTest::newRow( "string with newline" ) << QVariant( QString( QLatin1String( "string\nstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\nstring\"\\s*" ) ); QTest::newRow( "string with bell" ) << QVariant( QString( QLatin1String( "string\bstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\bstring\"\\s*" ) ); QTest::newRow( "string with return" ) << QVariant( QString( QLatin1String( "string\rstring" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\rstring\"\\s*" ) ); QTest::newRow( "string with double quote" ) << QVariant( QString( QLatin1String( "string\"string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\"string\"\\s*" ) ); QTest::newRow( "string with backslash" ) << QVariant( QString( QLatin1String( "string\\string" ) ) ) << QString( QLatin1String( "\\s*\"string\\\\\\\\string\"\\s*" ) ); QString testStringWithUnicode = QString( QLatin1String( "string" ) ) + QChar( 0x2665 ) + QLatin1String( "string" ); QString testEscapedString = QString( QLatin1String( "string" ) ) + QLatin1String("\\\\u2665") + QLatin1String( "string" ); QTest::newRow( "string with unicode" ) << QVariant( testStringWithUnicode ) << QLatin1String( "\\s*\"" ) + testEscapedString + QLatin1String( "\"\\s*" ); } void TestSerializer::testValueStringList() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueStringList_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QStringList stringlist; QString expected; // simple QStringList stringlist << QLatin1String("hello") << QLatin1String("world"); expected = QLatin1String( "\\s*\\[\\s*\"hello\"\\s*,\\s*\"world\"\\s*\\]\\s*" ); QTest::newRow( "simple QStringList" ) << QVariant( stringlist) << expected; } void TestSerializer::testValueInteger() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueInteger_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "int 0" ) << QVariant( static_cast<int>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) ); QTest::newRow( "uint 0" ) << QVariant( static_cast<uint>( 0 ) ) << QString( QLatin1String( "\\s*0\\s*" ) ); QTest::newRow( "int -1" ) << QVariant( static_cast<int>( -1 ) ) << QString( QLatin1String( "\\s*-1\\s*" ) ); QTest::newRow( "int 2133149800" ) << QVariant( static_cast<int>(2133149800) ) << QString( QLatin1String( "\\s*2133149800\\s*" ) ); QTest::newRow( "uint 4133149800" ) << QVariant( static_cast<uint>(4133149800u) ) << QString( QLatin1String( "\\s*4133149800\\s*" ) ); QTest::newRow( "uint64 932838457459459" ) << QVariant( Q_UINT64_C(932838457459459) ) << QString( QLatin1String( "\\s*932838457459459\\s*" ) ); QTest::newRow( "max unsigned long long" ) << QVariant( std::numeric_limits<unsigned long long>::max() ) << QString( QLatin1String( "\\s*%1\\s*" ) ).arg(std::numeric_limits<unsigned long long>::max()); } void TestSerializer::testValueDouble() { QFETCH( QVariant, value ); QFETCH( QString, expected ); QFETCH( bool, errorExpected ); valueTest( value, expected, errorExpected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ), errorExpected ); } void TestSerializer::testValueDouble_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::addColumn<bool>( "errorExpected" ); QTest::newRow( "double 0" ) << QVariant( 0.0 ) << QString( QLatin1String( "\\s*0.0\\s*" ) ) << false; QTest::newRow( "double -1" ) << QVariant( -1.0 ) << QString( QLatin1String( "\\s*-1.0\\s*" ) ) << false; QTest::newRow( "double 1.5E-20" ) << QVariant( 1.5e-20 ) << QString( QLatin1String( "\\s*1.5[Ee]-20\\s*" ) ) << false; QTest::newRow( "double -1.5E-20" ) << QVariant( -1.5e-20 ) << QString( QLatin1String( "\\s*-1.5[Ee]-20\\s*" ) ) << false; QTest::newRow( "double 2.0E-20" ) << QVariant( 2.0e-20 ) << QString( QLatin1String( "\\s*2(?:.0)?[Ee]-20\\s*" ) ) << false; QTest::newRow( "double infinity" ) << QVariant( std::numeric_limits< double >::infinity() ) << QString( ) << true; QTest::newRow( "double -infinity" ) << QVariant( -std::numeric_limits< double >::infinity() ) << QString( ) << true; QTest::newRow( "double NaN" ) << QVariant( std::numeric_limits< double >::quiet_NaN() ) << QString( ) << true; } void TestSerializer::testSetDoublePrecision() { Serializer serializer; QByteArray actual; QString expected, actualUnicode; double num = 0.12345678; // Set 1 as double precision serializer.setDoublePrecision(1); expected = QString(QLatin1String("0.1")); actual = serializer.serialize( QVariant(num) ); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); // Set 2 as double precision serializer.setDoublePrecision(2); expected = QString(QLatin1String("0.12")); actual = serializer.serialize( QVariant(num) ); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); // Set 4 as double precision serializer.setDoublePrecision(4); expected = QString(QLatin1String("0.1235")); actual = serializer.serialize( QVariant(num) ); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); // Set 14 as double precision serializer.setDoublePrecision(14); expected = QString(QLatin1String("0.12345678")); actual = serializer.serialize( QVariant(num) ); actualUnicode = QString::fromUtf8(actual); QVERIFY2( QString::compare(expected, actualUnicode ) == 0, qPrintable( QString( QLatin1String( "Expected \"%1\" but got \"%2\"." ) ) .arg( expected ).arg( actualUnicode ) ) ); } void TestSerializer::testValueFloat() { QFETCH( QVariant, value ); QFETCH( QString, expected ); QFETCH( bool, errorExpected ); valueTest( value, expected, errorExpected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ), errorExpected ); } void TestSerializer::testValueFloat_data() { QVariant v (QMetaType::Float); float value; QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::addColumn<bool>( "errorExpected" ); value = 0; v.setValue(value); QTest::newRow( "float 0" ) << v << QString( QLatin1String( "\\s*0.0\\s*" ) ) << false; value = -1; v.setValue(value); QTest::newRow( "float -1" ) << v << QString( QLatin1String( "\\s*-1.0\\s*" ) ) << false; value = 1.12f; v.setValue(value); QTest::newRow( "float 1.12" ) << v << QString( QLatin1String( "\\s*1.12\\s*" ) ) << false; } void TestSerializer::testValueBoolean() { QFETCH( QVariant, value ); QFETCH( QString, expected ); valueTest( value, expected ); QVariantMap map; map[QLatin1String("value")] = value; valueTest( QVariant(map), QLatin1String( "\\s*\\{\\s*\"value\"\\s*:" ) + expected + QLatin1String( "\\}\\s*" ) ); } void TestSerializer::testValueBoolean_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "bool false" ) << QVariant( false ) << QString( QLatin1String( "\\s*false\\s*" ) ); QTest::newRow( "bool true" ) << QVariant( true ) << QString( QLatin1String( "\\s*true\\s*" ) ); } void TestSerializer::testSpecialNumbers() { QFETCH( QVariant, value ); QFETCH( QString, expected ); Serializer specialSerializer; QVERIFY(!specialSerializer.specialNumbersAllowed()); specialSerializer.allowSpecialNumbers(true); QVERIFY(specialSerializer.specialNumbersAllowed()); QByteArray serialized = specialSerializer.serialize(value); QCOMPARE(QString::fromLocal8Bit(serialized), expected); } void TestSerializer::testSpecialNumbers_data() { QTest::addColumn<QVariant>( "value" ); QTest::addColumn<QString>( "expected" ); QTest::newRow( "Infinity" ) << QVariant( std::numeric_limits< double >::infinity() ) << QString::fromLocal8Bit("Infinity"); QTest::newRow( "-Infinity" ) << QVariant( -std::numeric_limits< double >::infinity() ) << QString::fromLocal8Bit("-Infinity"); QTest::newRow( "Infinity" ) << QVariant( std::numeric_limits< double >::quiet_NaN() ) << QString::fromLocal8Bit("NaN"); } void TestSerializer::testSerializetoQIODevice() { QBuffer buffer; QVariantList variant; variant << QVariant(QLatin1String("Hello")); variant << QVariant(QLatin1String("world!")); Serializer serializer; bool ok; serializer.serialize(variant, &buffer, &ok); QCOMPARE(QString(QLatin1String(buffer.data())), QString(QLatin1String("[ \"Hello\", \"world!\" ]"))); QVERIFY(ok); } QTEST_MAIN(TestSerializer) #ifdef QMAKE_BUILD #include "testserializer.moc" #else #include "moc_testserializer.cxx" #endif
18,464
C++
.cpp
401
42.810474
202
0.673281
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
21,299
cmdlineparser.cpp
visualfc_liteide/liteidex/src/3rdparty/qjson/tests/cmdline_tester/cmdlineparser.cpp
/* This file is part of qjson * * Copyright (C) 2010 Flavio Castelli <flavio@castelli.name> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <QtCore/QStringBuilder> #include <QtGui/QMessageBox> #include "cmdlineparser.h" using namespace QJson; const QString CmdLineParser::m_helpMessage = QLatin1String( "Usage: cmdline_tester [options] file\n\n" "This program converts the json data read from 'file' to a QVariant object.\n" "--quiet Do not print output generated by parser and serializer.\n" "--serialize Parses the QVariant object back to json.\n" "--indent Sets the indentation level used by the 'serialize' option.\n" " Allowed values:\n" " - none [default]\n" " - minimum\n" " - medium\n" " - full\n" "--help Displays this help.\n" ); CmdLineParser::CmdLineParser(const QStringList &arguments) : m_pos(0), m_indentationMode(IndentNone), m_serialize(false), m_quiet(false) { for (int i = 1; i < arguments.count(); ++i) { const QString &arg = arguments.at(i); m_arguments.append(arg); } } CmdLineParser::Result CmdLineParser::parse() { bool showHelp = false; while (m_error.isEmpty() && hasMoreArgs()) { const QString &arg = nextArg(); if (arg.toLower() == QLatin1String("--indent")) handleSetIndentationMode(); else if (arg.toLower() == QLatin1String("--help")) showHelp = true; else if (arg.toLower() == QLatin1String("--serialize")) m_serialize = true; else if (arg.toLower() == QLatin1String("--quiet")) m_quiet = true; else if (!arg.startsWith(QLatin1String("--"))) m_file = arg; else m_error = QString(QLatin1String("Unknown option: %1")).arg(arg); } if (m_file.isEmpty()) { m_error = QLatin1String("You have to specify the file containing the json data."); } if (!m_error.isEmpty()) { showMessage(m_error + QLatin1String("\n\n\n") + m_helpMessage, true); return Error; } else if (showHelp) { showMessage(m_helpMessage, false); return Help; } return Ok; } bool CmdLineParser::hasMoreArgs() const { return m_pos < m_arguments.count(); } const QString &CmdLineParser::nextArg() { Q_ASSERT(hasMoreArgs()); return m_arguments.at(m_pos++); } void CmdLineParser::handleSetIndentationMode() { if (hasMoreArgs()) { const QString &indentationMode = nextArg(); if (indentationMode.compare(QLatin1String("none"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentNone; else if (indentationMode.compare(QLatin1String("minimum"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentMinimum; else if (indentationMode.compare(QLatin1String("medium"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentMedium; else if (indentationMode.compare(QLatin1String("full"), Qt::CaseInsensitive) == 0) m_indentationMode = IndentFull; else m_error = QString(QLatin1String("Unknown indentation mode '%1'.")). arg(indentationMode); } else { m_error = QLatin1String("Missing indentation level."); } } void CmdLineParser::showMessage(const QString &msg, bool error) { #ifdef Q_OS_WIN QString message = QLatin1String("<pre>") % msg % QLatin1String("</pre>"); if (error) QMessageBox::critical(0, QLatin1String("Error"), message); else QMessageBox::information(0, QLatin1String("Notice"), message); #else fprintf(error ? stderr : stdout, "%s\n", qPrintable(msg)); #endif } void CmdLineParser::setIndentationMode(const IndentMode &mode) { m_indentationMode = mode; } IndentMode CmdLineParser::indentationMode() const { return m_indentationMode; } QString CmdLineParser::file() const { return m_file; } bool CmdLineParser::serialize() { return m_serialize; } bool CmdLineParser::quiet() { return m_quiet; }
4,862
C++
.cpp
138
29.695652
93
0.650649
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
21,300
cmdline_tester.cpp
visualfc_liteide/liteidex/src/3rdparty/qjson/tests/cmdline_tester/cmdline_tester.cpp
/* This file is part of QJson * * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QStringList> #include <QtCore/QVariant> #include <QtCore/QTime> #include <QJson/Parser> #include <QJson/Serializer> #include "cmdlineparser.h" using namespace QJson; int main(int argc, char *argv[]) { QCoreApplication app (argc, argv); QTime time; int duration; CmdLineParser cmd (app.arguments()); CmdLineParser::Result res = cmd.parse(); if (res == CmdLineParser::Help) return 0; else if (res == CmdLineParser::Error) return -1; QString filename = cmd.file(); if (!QFile::exists ( filename )) { qCritical ("The file you specified doesn't exist!"); exit (1); } Parser parser; bool ok; QFile file (filename); time.start(); QVariant data = parser.parse (&file, &ok); duration = time.elapsed(); if (!ok) { qCritical("%s:%i - Error: %s", filename.toLatin1().data(), parser.errorLine(), qPrintable(parser.errorString())); exit (1); } else { qDebug() << "Parsing of" << filename << "took" << duration << "ms"; if (!cmd.quiet()) qDebug() << data; } if (cmd.serialize()) { // serializer tests qDebug() << "Serializing... "; QJson::Serializer serializer; serializer.setIndentMode(cmd.indentationMode()); time.start(); QByteArray b = serializer.serialize(data); duration = time.elapsed(); qDebug() << "Serialization took:" << duration << "ms"; if (!cmd.quiet()) qDebug() << b; } qDebug() << "JOB DONE, BYE"; return 0; }
2,379
C++
.cpp
74
28.891892
117
0.690559
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
21,306
libcmark.cpp
visualfc_liteide/liteidex/src/3rdparty/cmark/libcmark.cpp
#include "libcmark.h" #include "src/cmark.h" namespace cmark { QByteArray markdown_to_html(const QByteArray &data) { char *buf = cmark_markdown_to_html(data.data(),size_t(data.size()),CMARK_OPT_UNSAFE); QByteArray out(buf); free(buf); return out; } } //cmark
279
C++
.cpp
11
22.636364
89
0.70566
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,310
gokeyword.cpp
visualfc_liteide/liteidex/src/3rdparty/cplusplus/gokeyword.cpp
#include "Lexer.h" #include "Token.h" /* T_GO_GO, T_GO_IF, T_GO_MAP, T_GO_FOR, T_GO_VAR, T_GO_FUNC, T_GO_CASE, T_GO_CHAN, T_GO_ELSE, T_GO_GOTO, T_GO_TYPE, T_GO_BREAK, T_GO_DEFER, T_GO_CONST, T_GO_RANGE, T_GO_SELECT, T_GO_STRUCT, T_GO_SWITCH, T_GO_IMPORT, T_GO_RETURN, T_GO_DEFAULT, T_GO_PACKAGE, T_GO_CONTINUE, T_GO_INTERFACE, T_GO_FALLTHROUGH, */ /* ("go"),("if"),("map"),("for"),("var"),("func"), ("case"),("chan"),("else"),("goto"),("type"),("break"), ("defer"),("const"),("range"),("select"),("struct"),("switch"), ("import"),("return"),("default"),("package"),("continue"),("interface"), ("fallthrough"), */ namespace CPlusPlus { static inline int golangKeywords2(const char *s) { if (s[0] == 'g') { if (s[1] == 'o') { return T_GO_GO; } } else if (s[0] == 'i') { if (s[1] == 'f') { return T_GO_IF; } } return T_IDENTIFIER; } static inline int golangKeywords3(const char *s) { if (s[0] == 'f') { if (s[1] == 'o') { if (s[2] == 'r') { return T_GO_FOR; } } } else if (s[0] == 'm') { if (s[1] == 'a') { if (s[2] == 'p') { return T_GO_MAP; } } } else if (s[0] == 'v') { if (s[1] == 'a') { if (s[2] == 'r') { return T_GO_VAR; } } } return T_IDENTIFIER; } static inline int golangKeywords4(const char *s) { if (s[0] == 'c') { if (s[1] == 'a') { if (s[2] == 's') { if (s[3] == 'e') { return T_GO_CASE; } } } else if (s[1] == 'h') { if (s[2] == 'a') { if (s[3] == 'n') { return T_GO_CHAN; } } } } else if (s[0] == 'e') { if (s[1] == 'l') { if (s[2] == 's') { if (s[3] == 'e') { return T_GO_ELSE; } } } } else if (s[0] == 'f') { if (s[1] == 'u') { if (s[2] == 'n') { if (s[3] == 'c') { return T_GO_FUNC; } } } } else if (s[0] == 'g') { if (s[1] == 'o') { if (s[2] == 't') { if (s[3] == 'o') { return T_GO_GOTO; } } } } else if (s[0] == 't') { if (s[1] == 'y') { if (s[2] == 'p') { if (s[3] == 'e') { return T_GO_TYPE; } } } } return T_IDENTIFIER; } static inline int golangKeywords5(const char *s) { if (s[0] == 'b') { if (s[1] == 'r') { if (s[2] == 'e') { if (s[3] == 'a') { if (s[4] == 'k') { return T_GO_BREAK; } } } } } else if (s[0] == 'c') { if (s[1] == 'o') { if (s[2] == 'n') { if (s[3] == 's') { if (s[4] == 't') { return T_GO_CONST; } } } } } else if (s[0] == 'd') { if (s[1] == 'e') { if (s[2] == 'f') { if (s[3] == 'e') { if (s[4] == 'r') { return T_GO_DEFER; } } } } } else if (s[0] == 'r') { if (s[1] == 'a') { if (s[2] == 'n') { if (s[3] == 'g') { if (s[4] == 'e') { return T_GO_RANGE; } } } } } return T_IDENTIFIER; } static inline int golangKeywords6(const char *s) { if (s[0] == 'i') { if (s[1] == 'm') { if (s[2] == 'p') { if (s[3] == 'o') { if (s[4] == 'r') { if (s[5] == 't') { return T_GO_IMPORT; } } } } } } else if (s[0] == 'r') { if (s[1] == 'e') { if (s[2] == 't') { if (s[3] == 'u') { if (s[4] == 'r') { if (s[5] == 'n') { return T_GO_RETURN; } } } } } } else if (s[0] == 's') { if (s[1] == 'e') { if (s[2] == 'l') { if (s[3] == 'e') { if (s[4] == 'c') { if (s[5] == 't') { return T_GO_SELECT; } } } } } else if (s[1] == 't') { if (s[2] == 'r') { if (s[3] == 'u') { if (s[4] == 'c') { if (s[5] == 't') { return T_GO_STRUCT; } } } } } else if (s[1] == 'w') { if (s[2] == 'i') { if (s[3] == 't') { if (s[4] == 'c') { if (s[5] == 'h') { return T_GO_SWITCH; } } } } } } return T_IDENTIFIER; } static inline int golangKeywords7(const char *s) { if (s[0] == 'd') { if (s[1] == 'e') { if (s[2] == 'f') { if (s[3] == 'a') { if (s[4] == 'u') { if (s[5] == 'l') { if (s[6] == 't') { return T_GO_DEFAULT; } } } } } } } else if (s[0] == 'p') { if (s[1] == 'a') { if (s[2] == 'c') { if (s[3] == 'k') { if (s[4] == 'a') { if (s[5] == 'g') { if (s[6] == 'e') { return T_GO_PACKAGE; } } } } } } } return T_IDENTIFIER; } static inline int golangKeywords8(const char *s) { if (s[0] == 'c') { if (s[1] == 'o') { if (s[2] == 'n') { if (s[3] == 't') { if (s[4] == 'i') { if (s[5] == 'n') { if (s[6] == 'u') { if (s[7] == 'e') { return T_GO_CONTINUE; } } } } } } } } return T_IDENTIFIER; } static inline int golangKeywords9(const char *s) { if (s[0] == 'i') { if (s[1] == 'n') { if (s[2] == 't') { if (s[3] == 'e') { if (s[4] == 'r') { if (s[5] == 'f') { if (s[6] == 'a') { if (s[7] == 'c') { if (s[8] == 'e') { return T_GO_INTERFACE; } } } } } } } } } return T_IDENTIFIER; } static inline int golangKeywords11(const char *s) { if (s[0] == 'f') { if (s[1] == 'a') { if (s[2] == 'l') { if (s[3] == 'l') { if (s[4] == 't') { if (s[5] == 'h') { if (s[6] == 'r') { if (s[7] == 'o') { if (s[8] == 'u') { if (s[9] == 'g') { if (s[10] == 'h') { return T_GO_FALLTHROUGH; } } } } } } } } } } } return T_IDENTIFIER; } int Lexer::golangKeywords(const char *s, int n) { switch (n) { case 2: return golangKeywords2(s); case 3: return golangKeywords3(s); case 4: return golangKeywords4(s); case 5: return golangKeywords5(s); case 6: return golangKeywords6(s); case 7: return golangKeywords7(s); case 8: return golangKeywords8(s); case 9: return golangKeywords9(s); case 11: return golangKeywords11(s); default: return T_IDENTIFIER; } // switch } } //namespace CPlusPlus
7,189
C++
.cpp
356
12.921348
73
0.33392
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,311
gopredecl.cpp
visualfc_liteide/liteidex/src/3rdparty/cplusplus/gopredecl.cpp
#include "Lexer.h" #include "Token.h" /* T_GO_NIL, T_GO_TRUE, T_GO_IOTA, T_GO_FALSE, */ /* ("nil"),("true"),("iota"),("false"), */ namespace CPlusPlus { static inline int golangPredecl3(const char *s) { if (s[0] == 'n') { if (s[1] == 'i') { if (s[2] == 'l') { return T_GO_NIL; } } } return T_IDENTIFIER; } static inline int golangPredecl4(const char *s) { if (s[0] == 'i') { if (s[1] == 'o') { if (s[2] == 't') { if (s[3] == 'a') { return T_GO_IOTA; } } } } else if (s[0] == 't') { if (s[1] == 'r') { if (s[2] == 'u') { if (s[3] == 'e') { return T_GO_TRUE; } } } } return T_IDENTIFIER; } static inline int golangPredecl5(const char *s) { if (s[0] == 'f') { if (s[1] == 'a') { if (s[2] == 'l') { if (s[3] == 's') { if (s[4] == 'e') { return T_GO_FALSE; } } } } } return T_IDENTIFIER; } int Lexer::golangPredecl(const char *s, int n) { switch (n) { case 3: return golangPredecl3(s); case 4: return golangPredecl4(s); case 5: return golangPredecl5(s); default: return T_IDENTIFIER; } // switch } } //namespace CPlusPlus
1,266
C++
.cpp
66
14.409091
49
0.470984
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,312
gobuiltin.cpp
visualfc_liteide/liteidex/src/3rdparty/cplusplus/gobuiltin.cpp
#include "Lexer.h" #include "Token.h" /* T_GO_CAP, T_GO_LEN, T_GO_NEW, T_GO_COPY, T_GO_IMAG, T_GO_MAKE, T_GO_REAL, T_GO_CLOSE, T_GO_PANIC, T_GO_PRINT, T_GO_APPEND, T_GO_DELETE, T_GO_COMPLEX, T_GO_PRINTLN, T_GO_RECOVER, */ /* ("cap"),("len"),("new"),("copy"),("imag"),("make"), ("real"),("close"),("panic"),("print"),("append"),("delete"), ("complex"),("println"),("recover"), */ namespace CPlusPlus { static inline int golangBuiltinFunc3(const char *s) { if (s[0] == 'c') { if (s[1] == 'a') { if (s[2] == 'p') { return T_GO_CAP; } } } else if (s[0] == 'l') { if (s[1] == 'e') { if (s[2] == 'n') { return T_GO_LEN; } } } else if (s[0] == 'n') { if (s[1] == 'e') { if (s[2] == 'w') { return T_GO_NEW; } } } return T_IDENTIFIER; } static inline int golangBuiltinFunc4(const char *s) { if (s[0] == 'c') { if (s[1] == 'o') { if (s[2] == 'p') { if (s[3] == 'y') { return T_GO_COPY; } } } } else if (s[0] == 'i') { if (s[1] == 'm') { if (s[2] == 'a') { if (s[3] == 'g') { return T_GO_IMAG; } } } } else if (s[0] == 'm') { if (s[1] == 'a') { if (s[2] == 'k') { if (s[3] == 'e') { return T_GO_MAKE; } } } } else if (s[0] == 'r') { if (s[1] == 'e') { if (s[2] == 'a') { if (s[3] == 'l') { return T_GO_REAL; } } } } return T_IDENTIFIER; } static inline int golangBuiltinFunc5(const char *s) { if (s[0] == 'c') { if (s[1] == 'l') { if (s[2] == 'o') { if (s[3] == 's') { if (s[4] == 'e') { return T_GO_CLOSE; } } } } } else if (s[0] == 'p') { if (s[1] == 'a') { if (s[2] == 'n') { if (s[3] == 'i') { if (s[4] == 'c') { return T_GO_PANIC; } } } } else if (s[1] == 'r') { if (s[2] == 'i') { if (s[3] == 'n') { if (s[4] == 't') { return T_GO_PRINT; } } } } } return T_IDENTIFIER; } static inline int golangBuiltinFunc6(const char *s) { if (s[0] == 'a') { if (s[1] == 'p') { if (s[2] == 'p') { if (s[3] == 'e') { if (s[4] == 'n') { if (s[5] == 'd') { return T_GO_APPEND; } } } } } } else if (s[0] == 'd') { if (s[1] == 'e') { if (s[2] == 'l') { if (s[3] == 'e') { if (s[4] == 't') { if (s[5] == 'e') { return T_GO_DELETE; } } } } } } return T_IDENTIFIER; } static inline int golangBuiltinFunc7(const char *s) { if (s[0] == 'c') { if (s[1] == 'o') { if (s[2] == 'm') { if (s[3] == 'p') { if (s[4] == 'l') { if (s[5] == 'e') { if (s[6] == 'x') { return T_GO_COMPLEX; } } } } } } } else if (s[0] == 'p') { if (s[1] == 'r') { if (s[2] == 'i') { if (s[3] == 'n') { if (s[4] == 't') { if (s[5] == 'l') { if (s[6] == 'n') { return T_GO_PRINTLN; } } } } } } } else if (s[0] == 'r') { if (s[1] == 'e') { if (s[2] == 'c') { if (s[3] == 'o') { if (s[4] == 'v') { if (s[5] == 'e') { if (s[6] == 'r') { return T_GO_RECOVER; } } } } } } } return T_IDENTIFIER; } int Lexer::golangBuiltinFunc(const char *s, int n) { switch (n) { case 3: return golangBuiltinFunc3(s); case 4: return golangBuiltinFunc4(s); case 5: return golangBuiltinFunc5(s); case 6: return golangBuiltinFunc6(s); case 7: return golangBuiltinFunc7(s); default: return T_IDENTIFIER; } // switch } } //namespace CPlusPlus
4,124
C++
.cpp
210
13.071429
61
0.35555
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,315
gotypes.cpp
visualfc_liteide/liteidex/src/3rdparty/cplusplus/gotypes.cpp
#include "Lexer.h" #include "Token.h" namespace CPlusPlus { static inline int golangTypes3(const char *s) { if (s[0] == 'a') { if (s[1] == 'n') { if (s[2] == 'y') { return T_GO_ANY; } } } else if (s[0] == 'i') { if (s[1] == 'n') { if (s[2] == 't') { return T_GO_INT; } } } return T_IDENTIFIER; } static inline int golangTypes4(const char *s) { if (s[0] == 'b') { if (s[1] == 'o') { if (s[2] == 'o') { if (s[3] == 'l') { return T_GO_BOOL; } } } else if (s[1] == 'y') { if (s[2] == 't') { if (s[3] == 'e') { return T_GO_BYTE; } } } } else if (s[0] == 'i') { if (s[1] == 'n') { if (s[2] == 't') { if (s[3] == '8') { return T_GO_INT8; } } } } else if (s[0] == 'r') { if (s[1] == 'u') { if (s[2] == 'n') { if (s[3] == 'e') { return T_GO_RUNE; } } } } else if (s[0] == 'u') { if (s[1] == 'i') { if (s[2] == 'n') { if (s[3] == 't') { return T_GO_UINT; } } } } return T_IDENTIFIER; } static inline int golangTypes5(const char *s) { if (s[0] == 'e') { if (s[1] == 'r') { if (s[2] == 'r') { if (s[3] == 'o') { if (s[4] == 'r') { return T_GO_ERROR; } } } } } else if (s[0] == 'i') { if (s[1] == 'n') { if (s[2] == 't') { if (s[3] == '1') { if (s[4] == '6') { return T_GO_INT16; } } else if (s[3] == '3') { if (s[4] == '2') { return T_GO_INT32; } } else if (s[3] == '6') { if (s[4] == '4') { return T_GO_INT64; } } } } } else if (s[0] == 'u') { if (s[1] == 'i') { if (s[2] == 'n') { if (s[3] == 't') { if (s[4] == '8') { return T_GO_UINT8; } } } } } return T_IDENTIFIER; } static inline int golangTypes6(const char *s) { if (s[0] == 's') { if (s[1] == 't') { if (s[2] == 'r') { if (s[3] == 'i') { if (s[4] == 'n') { if (s[5] == 'g') { return T_GO_STRING; } } } } } } else if (s[0] == 'u') { if (s[1] == 'i') { if (s[2] == 'n') { if (s[3] == 't') { if (s[4] == '1') { if (s[5] == '6') { return T_GO_UINT16; } } else if (s[4] == '3') { if (s[5] == '2') { return T_GO_UINT32; } } else if (s[4] == '6') { if (s[5] == '4') { return T_GO_UINT64; } } } } } } return T_IDENTIFIER; } static inline int golangTypes7(const char *s) { if (s[0] == 'f') { if (s[1] == 'l') { if (s[2] == 'o') { if (s[3] == 'a') { if (s[4] == 't') { if (s[5] == '3') { if (s[6] == '2') { return T_GO_FLOAT32; } } else if (s[5] == '6') { if (s[6] == '4') { return T_GO_FLOAT64; } } } } } } } else if (s[0] == 'u') { if (s[1] == 'i') { if (s[2] == 'n') { if (s[3] == 't') { if (s[4] == 'p') { if (s[5] == 't') { if (s[6] == 'r') { return T_GO_UINTPTR; } } } } } } } return T_IDENTIFIER; } static inline int golangTypes9(const char *s) { if (s[0] == 'c') { if (s[1] == 'o') { if (s[2] == 'm') { if (s[3] == 'p') { if (s[4] == 'l') { if (s[5] == 'e') { if (s[6] == 'x') { if (s[7] == '6') { if (s[8] == '4') { return T_GO_COMPLEX64; } } } } } } } } } return T_IDENTIFIER; } static inline int golangTypes10(const char *s) { if (s[0] == 'c') { if (s[1] == 'o') { if (s[2] == 'm') { if (s[3] == 'p') { if (s[4] == 'a') { if (s[5] == 'r') { if (s[6] == 'a') { if (s[7] == 'b') { if (s[8] == 'l') { if (s[9] == 'e') { return T_GO_COMPARABLE; } } } } } } else if (s[4] == 'l') { if (s[5] == 'e') { if (s[6] == 'x') { if (s[7] == '1') { if (s[8] == '2') { if (s[9] == '8') { return T_GO_COMPLEX128; } } } } } } } } } } return T_IDENTIFIER; } int Lexer::golangTypes(const char *s, int n) { switch (n) { case 3: return golangTypes3(s); case 4: return golangTypes4(s); case 5: return golangTypes5(s); case 6: return golangTypes6(s); case 7: return golangTypes7(s); case 9: return golangTypes9(s); case 10: return golangTypes10(s); default: return T_IDENTIFIER; } // switch } }
5,482
C++
.cpp
261
12.482759
48
0.297697
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,317
liteshell.cpp
visualfc_liteide/liteidex/src/liteshell/liteshell.cpp
// liteshell.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #include <windows.h> #include <shlobj.h> BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { CoInitialize(NULL); } return TRUE; } extern "C" _declspec(dllexport) BOOL BrowseToFile(const wchar_t* filename) { ITEMIDLIST *pidl = ILCreateFromPath(filename); if(pidl) { SHOpenFolderAndSelectItems(pidl,0,0,0); ILFree(pidl); return TRUE; } return FALSE; }
621
C++
.cpp
26
19.192308
68
0.664957
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,318
quickopeneditor.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopeneditor.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopeneditor.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopeneditor.h" #include "quickopen_global.h" #include <QStandardItemModel> #include <QSortFilterProxyModel> #include <QStandardItem> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenEditor::QuickOpenEditor(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpen(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); m_proxyModel = new QSortFilterProxyModel(this); m_proxyModel->setSourceModel(m_model); m_matchCase = Qt::CaseInsensitive; } QString QuickOpenEditor::id() const { return "quickopen/editor"; } QString QuickOpenEditor::info() const { return tr("Show All Opened Editors"); } QString QuickOpenEditor::placeholderText() const { return QString(); } void QuickOpenEditor::activate() { } QAbstractItemModel *QuickOpenEditor::model() const { return m_proxyModel; } QModelIndex QuickOpenEditor::rootIndex() const { return QModelIndex(); } void QuickOpenEditor::updateModel() { m_matchCase = m_liteApp->settings()->value(QUICKOPNE_EDITOR_MATCHCASE,false).toBool() ? Qt::CaseSensitive : Qt::CaseInsensitive; m_model->clear(); m_proxyModel->setFilterFixedString(""); m_proxyModel->setFilterCaseSensitivity(m_matchCase); m_proxyModel->setFilterKeyColumn(2); foreach(LiteApi::IEditor *editor, m_liteApp->editorManager()->editorList()) { if (editor->filePath().isEmpty()) { continue; } m_model->appendRow(QList<QStandardItem*>() << new QStandardItem(editor->name()) << new QStandardItem(editor->filePath()) ); } m_proxyModel->sort(0); } QModelIndex QuickOpenEditor::filterChanged(const QString &text) { m_proxyModel->setFilterFixedString(text); for(int i = 0; i < m_proxyModel->rowCount(); i++) { QModelIndex index = m_proxyModel->index(i,0); QString name = index.data().toString(); if (name.startsWith(text,m_matchCase)) { return index; } } if (m_proxyModel->rowCount() > 0) return m_proxyModel->index(0,0); return QModelIndex(); } void QuickOpenEditor::indexChanged(const QModelIndex &/*index*/) { } bool QuickOpenEditor::selected(const QString &text, const QModelIndex &index) { if (!index.isValid()) { return false; } QString filePath = m_proxyModel->index(index.row(),1).data().toString(); if (!m_liteApp->fileManager()->openFile(filePath)) { return false; } return true; } void QuickOpenEditor::cancel() { }
3,969
C++
.cpp
114
30.333333
133
0.668064
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,319
quickopenaction.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenaction.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenaction.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenaction.h" #include <QStandardItem> #include <QStandardItemModel> #include <QModelIndex> #include <QSortFilterProxyModel> #include <QMenu> #include <QAction> #include <QTimer> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenAction::QuickOpenAction(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpen(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); m_proxyModel = new QSortFilterProxyModel(this); m_proxyModel->setSourceModel(m_model); m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModel->setFilterKeyColumn(0); } QString QuickOpenAction::id() const { return "quickopen/command"; } QString QuickOpenAction::info() const { return tr("Show and Run Commands"); } QString QuickOpenAction::placeholderText() const { return QString(); } void QuickOpenAction::activate() { } QAbstractItemModel *QuickOpenAction::model() const { return m_proxyModel; } QModelIndex QuickOpenAction::rootIndex() const { return QModelIndex(); } static QString makeTitle(const QString &id) { return id[0].toUpper()+id.mid(1); } static QString makeMenuName(const QString &idMenu) { if (idMenu.startsWith("menu/")) { return makeTitle(idMenu.mid(5)); } return makeTitle(idMenu); } void QuickOpenAction::updateModel() { m_model->clear(); m_itemActionMap.clear(); m_proxyModel->setFilterFixedString(""); LiteApi::IActionManager *manager = m_liteApp->actionManager(); // ("menu/build", "menu/debug", "menu/edit", "menu/file", "menu/find", "menu/help", "menu/recent", "menu/view") // ("App", "Build", "Find", "Editor", "Document", "Debug", "JsonEdit", "GoPkg", "GolangEdit", "GoFmt", "Bookmarks") foreach (QString idMenu, manager->menuList()) { if (idMenu == "menu/recent") { continue; } QMenu *menu = manager->loadMenu(idMenu); if (!menu) { continue; } QAction *menuAct = menu->menuAction(); if (!menuAct) { continue; } QMenu *realMenu = menuAct->menu(); if (!realMenu) { continue; } QList<QAction*> actionList; QString menuName = makeMenuName(idMenu); foreach (QAction *act, realMenu->actions()) { if (act->isSeparator()) { continue; } QMenu *childMenu = act->menu(); if (childMenu) { foreach (QAction *act, childMenu->actions()) { if (act->isSeparator()) { continue; } if (act->menu() != 0) { continue; } actionList << act; } } else { actionList << act; } } foreach (QAction *act, actionList) { if (!act->isEnabled()) { continue; } if (act->data().isNull()) { continue; } QString text = act->data().toString(); if (text.isEmpty()) { continue; } QStandardItem *item = new QStandardItem(menuName+"."+text); QStandardItem *info = new QStandardItem(); if (text != act->text()) { info->setText(act->text()); } QStandardItem *shortcut = new QStandardItem(act->shortcut().toString(QKeySequence::NativeText)); m_model->appendRow(QList<QStandardItem*>() << item << info << shortcut); m_itemActionMap.insert(item,act); } } } QModelIndex QuickOpenAction::filterChanged(const QString &text) { m_proxyModel->setFilterFixedString(text); for(int i = 0; i < m_proxyModel->rowCount(); i++) { QModelIndex index = m_proxyModel->index(i,0); QString name = index.data().toString(); if (name.startsWith(text,Qt::CaseInsensitive)) { return index; } } if (m_proxyModel->rowCount() > 0) return m_proxyModel->index(0,0); return QModelIndex(); } void QuickOpenAction::indexChanged(const QModelIndex &/*index*/) { } bool QuickOpenAction::selected(const QString &/*text*/, const QModelIndex &index) { if (!index.isValid()) { return false; } QModelIndex sourceIndex = m_proxyModel->mapToSource(index); QStandardItem *item = m_model->item(sourceIndex.row(),0); if (item) { QAction *act = m_itemActionMap.value(item); if (act) { QTimer::singleShot(1,act,SLOT(trigger())); return true; } } return false; } void QuickOpenAction::cancel() { }
6,258
C++
.cpp
185
26.308108
120
0.586275
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,320
quickopenoption.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenoption.h" #include "ui_quickopenoption.h" #include "quickopen_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenOption::QuickOpenOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::QuickOpenOption) { ui->setupUi(m_widget); } QuickOpenOption::~QuickOpenOption() { delete m_widget; delete ui; } QWidget *QuickOpenOption::widget() { return m_widget; } QString QuickOpenOption::name() const { return "QuickOpen"; } QString QuickOpenOption::mimeType() const { return OPTION_QUICKOPEN; } void QuickOpenOption::load() { ui->checkFilesMatchCase->setChecked(m_liteApp->settings()->value(QUICKOPNE_FILES_MATCHCASE,false).toBool()); ui->checkEditorMatchCase->setChecked(m_liteApp->settings()->value(QUICKOPNE_EDITOR_MATCHCASE,false).toBool()); ui->spinBoxFilesMaxCount->setValue(m_liteApp->settings()->value(QUICKOPEN_FILES_MAXCOUNT,100000).toInt()); } void QuickOpenOption::save() { m_liteApp->settings()->setValue(QUICKOPNE_FILES_MATCHCASE,ui->checkFilesMatchCase->isChecked()); m_liteApp->settings()->setValue(QUICKOPNE_EDITOR_MATCHCASE,ui->checkEditorMatchCase->isChecked()); m_liteApp->settings()->setValue(QUICKOPEN_FILES_MAXCOUNT,ui->spinBoxFilesMaxCount->value()); }
2,749
C++
.cpp
71
35.239437
115
0.688204
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,321
quickopenmimetype.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenmimetype.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenmimetype.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenmimetype.h" #include <QStandardItemModel> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenMimeType::QuickOpenMimeType(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpenMimeType(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); m_id = "quickopen/symbol"; m_info = tr("Go to Symbol in File"); m_message = tr("not found symbol"); } QString QuickOpenMimeType::id() const { return m_id; } QString QuickOpenMimeType::info() const { return m_info; } QString QuickOpenMimeType::placeholderText() const { return QString(); } void QuickOpenMimeType::activate() { QString mimeType; LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor) { mimeType = editor->mimeType(); } foreach (LiteApi::IQuickOpenAdapter *factory, m_adapterList) { LiteApi::IQuickOpen *symbol = factory->load(mimeType); if (symbol) { m_symbol = symbol; m_symbol->activate(); break; } } } QAbstractItemModel *QuickOpenMimeType::model() const { if (m_symbol) { return m_symbol->model(); } return m_model; } QModelIndex QuickOpenMimeType::rootIndex() const { if (m_symbol) { return m_symbol->rootIndex(); } return QModelIndex(); } void QuickOpenMimeType::updateModel() { if (m_symbol) { m_symbol->updateModel(); } else { m_model->clear(); m_model->appendRow(new QStandardItem(m_message)); } } QModelIndex QuickOpenMimeType::filterChanged(const QString &text) { if (m_symbol) { return m_symbol->filterChanged(text); } return QModelIndex(); } void QuickOpenMimeType::indexChanged(const QModelIndex &index) { if (m_symbol) { m_symbol->indexChanged(index); } } bool QuickOpenMimeType::selected(const QString &text, const QModelIndex &index) { if (m_symbol) { return m_symbol->selected(text,index); } return false; } void QuickOpenMimeType::addAdapter(LiteApi::IQuickOpenAdapter *factory) { m_adapterList.push_back(factory); } void QuickOpenMimeType::setId(const QString &id) { m_id = id; } void QuickOpenMimeType::setInfo(const QString &info) { m_info = info; } void QuickOpenMimeType::setNoFoundMessage(const QString &message) { m_message = message; } void QuickOpenMimeType::cancel() { if (m_symbol) { m_symbol->cancel(); } }
3,948
C++
.cpp
134
24.873134
83
0.649471
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,322
quickopenplugin.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenplugin.h" #include "quickopenmanager.h" #include "quickopenlines.h" #include "quickopenmimetype.h" #include "quickopenoptionfactory.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenPlugin::QuickOpenPlugin() { } bool QuickOpenPlugin::load(LiteApi::IApplication *app) { QuickOpenManager *manager = new QuickOpenManager(app); if (!manager->initWithApp(app)) { return false; } manager->addFilter(":",new QuickOpenLines(app,this)); app->optionManager()->addFactory(new QuickOpenOptionFactory(app,this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,057
C++
.cpp
53
35.584906
83
0.675351
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,323
quickopenfilesystem.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenfilesystem.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenfilesystem.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenfilesystem.h" #include "folderview/filesystemmodelex.h" #include "folderview/dirsortfilterproxymodel.h" #include <QFileSystemModel> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenFileSystem::QuickOpenFileSystem(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpenFileSystem(parent) { m_liteApp = app; m_model = new FileSystemModelEx(this); bool proxyMode = false; #ifdef Q_OS_MAC proxyMode = true; #endif if (proxyMode) { m_proxy = new FileSystemProxyModel(this); m_proxy->setSourceModel(m_model); m_proxy->sort(0); } else { m_proxy = 0; } } QString QuickOpenFileSystem::id() const { return "quickopen/filesystem"; } QString QuickOpenFileSystem::placeholderText() const { return m_placehoderText; } void QuickOpenFileSystem::activate() { } QAbstractItemModel *QuickOpenFileSystem::model() const { if (m_proxy) { return m_proxy; } return m_model; } QModelIndex QuickOpenFileSystem::rootIndex() const { if (m_proxy) { return m_proxy->mapFromSource(m_rootIndex); } return m_rootIndex; } void QuickOpenFileSystem::updateModel() { } QModelIndex QuickOpenFileSystem::filterChanged(const QString &text) { int count = m_model->rowCount(m_rootIndex); for (int i = 0; i < count; i++) { QModelIndex index = m_model->index(i,0,m_rootIndex); if (m_model->fileName(index).startsWith(text,Qt::CaseInsensitive)) { if (m_proxy) { return m_proxy->mapFromSource(index); } return index; } } return QModelIndex(); } void QuickOpenFileSystem::cancel() { } void QuickOpenFileSystem::setRootPath(const QString &path) { m_rootIndex = m_model->setRootPath(path); } void QuickOpenFileSystem::setPlaceholderText(const QString &text) { m_placehoderText = text; } QModelIndex QuickOpenFileSystem::indexForPath(const QString &filePath) const { QModelIndex index = m_model->index(filePath,0); if (m_proxy) { index = m_proxy->mapFromSource(index); } return index; } QString QuickOpenFileSystem::pathForIndex(const QModelIndex &index) const { QModelIndex i = index; if (m_proxy) { i = m_proxy->mapToSource(index); } return m_model->filePath(index); } bool QuickOpenFileSystem::selected(const QString &/*text*/, const QModelIndex &index) { if (!index.isValid()) { return false; } QModelIndex fileIndex = index; if (m_proxy) { fileIndex = m_proxy->mapToSource(index); } if (m_model->isDir(fileIndex)) { return false; } QString filePath = m_model->filePath(fileIndex); if (!m_liteApp->fileManager()->openFile(filePath)) { return false; } return true; } void QuickOpenFileSystem::indexChanged(const QModelIndex &index) { } QString QuickOpenFileSystem::info() const { return tr("File System"); }
4,282
C++
.cpp
145
25.896552
125
0.681001
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,324
quickopenoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenoption.h" #include "quickopenoptionfactory.h" #include "quickopen_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenOptionFactory::QuickOpenOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList QuickOpenOptionFactory::mimeTypes() const { return QStringList() << OPTION_QUICKOPEN; } LiteApi::IOption *QuickOpenOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_QUICKOPEN) { return new QuickOpenOption(m_liteApp,this); } return 0; }
1,979
C++
.cpp
50
36.24
92
0.672566
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,325
quickopenmanager.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenmanager.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenmanager.h" #include "quickopen_global.h" #include "quickopenfiles.h" #include "quickopenfolder.h" #include "quickopeneditor.h" #include "quickopenmimetype.h" #include "quickopenaction.h" #include "quickopenhelp.h" #include "quickopenfilesystem.h" #include "liteapi/liteids.h" #include <QTreeView> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenManager::QuickOpenManager(QObject *parent) : LiteApi::IQuickOpenManager(parent) { } bool QuickOpenManager::initWithApp(IApplication *app) { if (!IQuickOpenManager::initWithApp(app)) { return false; } m_liteApp->extension()->addObject("LiteApi.IQuickOpenManager",this); m_widget = new QuickOpenWidget(m_liteApp,m_liteApp->mainWindow()); connect(m_widget,SIGNAL(filterChanged(QString)),this,SLOT(filterChanged(QString))); connect(m_widget->editor(),SIGNAL(returnPressed()),this,SLOT(selected())); connect(m_widget->view(),SIGNAL(clicked(QModelIndex)),this,SLOT(selected())); connect(m_widget->view(),SIGNAL(activated(QModelIndex)),this,SLOT(selected())); connect(m_widget,SIGNAL(hideWidget()),this,SLOT(hideWidget())); connect(m_widget,SIGNAL(indexChanage(QModelIndex)),this,SLOT(indexChanage(QModelIndex))); m_quickOpenFiles = new QuickOpenFiles(app,this); m_quickOpenFolder = new QuickOpenFolder(app,this); m_quickOpenFileSystem = new QuickOpenFileSystem(app,this); this->addFilter("",m_quickOpenFiles); this->addFilter("",m_quickOpenFolder); this->addFilter("",m_quickOpenFileSystem); this->addFilter("~",new QuickOpenEditor(m_liteApp,this)); this->addFilter(">",new QuickOpenAction(m_liteApp,this)); this->addFilter("?",new QuickOpenHelp(m_liteApp,this)); this->registerQuickOpenMimeType("@"); m_quickOpenAct = new QAction(tr("Quick Open File"),this); m_quickOpenEditAct = new QAction(tr("Quick Open Editor"),this); m_quickOpenSymbolAct = new QAction(tr("Quick Open Symbol"),this); m_quickOpenActionAct = new QAction(tr("Quick Open Command"),this); m_quickOpenHelpAct = new QAction(tr("Show All Quick Open Actions"),this); m_liteApp->actionManager()->setViewMenuSeparator("sep/quickopen",true); LiteApi::IActionContext *context = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); context->regAction(m_quickOpenAct,"QuickOpen","CTRL+P"); context->regAction(m_quickOpenEditAct,"QuickOpenEditor","CTRL+ALT+P"); context->regAction(m_quickOpenActionAct,"QuickOpenCommand","CTRL+SHIFT+P"); context->regAction(m_quickOpenSymbolAct,"QuickOpenSymbol","CTRL+SHIFT+O"); context->regAction(m_quickOpenHelpAct,"QuickOpenHelp",""); m_liteApp->actionManager()->insertMenuActions(ID_MENU_TOOLS,"sep/quickopen",true, QList<QAction*>() << m_quickOpenAct << m_quickOpenActionAct << m_quickOpenEditAct << m_quickOpenSymbolAct << m_quickOpenHelpAct ); connect(m_quickOpenAct,SIGNAL(triggered(bool)),this,SLOT(quickOpen())); connect(m_quickOpenEditAct,SIGNAL(triggered(bool)),this,SLOT(quickOpenEditor())); connect(m_quickOpenSymbolAct,SIGNAL(triggered(bool)),this,SLOT(quickOpenSymbol())); connect(m_quickOpenActionAct,SIGNAL(triggered(bool)),this,SLOT(quickOpenCommand())); connect(m_quickOpenHelpAct,SIGNAL(triggered(bool)),this,SLOT(quickOpenHelp())); connect(m_liteApp,SIGNAL(aboutToQuit()),this,SLOT(appAboutToQuit())); return true; } void QuickOpenManager::addFilter(const QString &sym, IQuickOpen *filter) { if (filter == 0) { return; } if (m_filterList.contains(filter)) { return; } m_filterList.push_back(filter); if (!sym.isEmpty()) { m_symFilterMap.insert(sym,filter); } } void QuickOpenManager::removeFilter(IQuickOpen *filter) { m_filterList.removeAll(filter); QMutableMapIterator<QString,IQuickOpen*> i(m_symFilterMap); while (i.hasNext()) { i.next(); if (i.value() == filter) { m_symFilterMap.remove(i.key()); break; } } } QList<IQuickOpen *> QuickOpenManager::filterList() const { return m_filterList; } QMap<QString, IQuickOpen *> QuickOpenManager::symFilterMap() const { return m_symFilterMap; } void QuickOpenManager::setCurrentFilter(IQuickOpen *filter) { if (filter) { filter->activate(); m_widget->editor()->setPlaceholderText(filter->placeholderText()); } if (m_currentFilter == filter) { return; } m_currentFilter = filter; if (m_currentFilter) { m_sym = m_symFilterMap.key(filter); m_widget->setModel(m_currentFilter->model(),m_currentFilter->rootIndex()); } } IQuickOpen *QuickOpenManager::currentFilter() const { return m_currentFilter; } QModelIndex QuickOpenManager::currentIndex() const { return m_widget->view()->currentIndex(); } void QuickOpenManager::showById(const QString &id) { IQuickOpen *i = findById(id); if (i) { setCurrentFilter(i); showPopup(); } } void QuickOpenManager::showBySymbol(const QString &sym) { IQuickOpen *i = findBySymbol(sym); if (i == 0) { i = m_quickOpenFiles; } if (i) { setCurrentFilter(i); showPopup(); } } IQuickOpen *QuickOpenManager::findById(const QString &id) { foreach (LiteApi::IQuickOpen *filter, m_filterList) { if (filter->id() == id) { return filter; } } return 0; } IQuickOpen *QuickOpenManager::findBySymbol(const QString &sym) { QMutableMapIterator<QString,IQuickOpen*> i(m_symFilterMap); while (i.hasNext()) { i.next(); if (i.key() == sym) { return i.value(); } } return 0; } QWidget *QuickOpenManager::widget() const { return m_widget; } QTreeView *QuickOpenManager::modelView() const { return m_widget->view(); } QLineEdit *QuickOpenManager::lineEdit() const { return m_widget->editor(); } void QuickOpenManager::setTempToolBar(QToolBar *toolBar) { m_widget->setTempToolBar(toolBar); } bool QuickOpenManager::showOpenFolder(const QString &folder, QPoint *pos) { m_quickOpenFolder->setFolder(folder); this->setCurrentFilter(m_quickOpenFolder); this->showPopup(pos); return true; } IQuickOpenMimeType *QuickOpenManager::registerQuickOpenMimeType(const QString &sym) { IQuickOpenMimeType *symbol = m_quickOpenSymbolMap[sym]; if (!symbol) { symbol = new QuickOpenMimeType(m_liteApp,this); this->addFilter(sym,symbol); m_quickOpenSymbolMap[sym] = symbol; } return symbol; } void QuickOpenManager::quickOpen() { m_updateMap.clear(); QString sym; QAction *act = (QAction*)sender(); if (act) { sym = act->data().toString(); } showBySymbol(sym); } void QuickOpenManager::quickOpenEditor() { showById("quickopen/editor"); } void QuickOpenManager::quickOpenSymbol() { showById("quickopen/symbol"); } void QuickOpenManager::quickOpenCommand() { showById("quickopen/command"); } void QuickOpenManager::quickOpenHelp() { showById("quickopen/help"); } void QuickOpenManager::updateModel() { if (!m_currentFilter) { return; } if (m_updateMap.value(m_currentFilter)) { return; } m_updateMap.insert(m_currentFilter,true); m_currentFilter->updateModel(); m_widget->view()->resizeColumnToContents(0); } void QuickOpenManager::showPopup(QPoint *pos) { updateModel(); m_widget->editor()->setText(m_sym); m_widget->showView(pos); } void QuickOpenManager::hideWidget() { if (m_currentFilter) { m_currentFilter->cancel(); } m_currentFilter = 0; m_updateMap.clear(); m_sym.clear(); } void QuickOpenManager::hidePopup() { m_widget->closeWidget(); } void QuickOpenManager::filterChanged(const QString &text) { bool checkSym = false; if (m_currentFilter == m_quickOpenFiles) { checkSym = true; } else if (!m_sym.isEmpty()) { checkSym = true; } // check register symbol qucik open if (checkSym) { IQuickOpen *quick = 0; if (!text.isEmpty()) { QMapIterator<QString,IQuickOpen*> i(m_symFilterMap); while (i.hasNext()) { i.next(); if (i.key().isEmpty()) { continue; } if (text.startsWith(i.key())) { quick = i.value(); break; } } } if (quick == 0) { quick = m_quickOpenFiles; } if (quick != m_currentFilter) { this->setCurrentFilter(quick); updateModel(); } } if (m_currentFilter) { QModelIndex index = m_currentFilter->filterChanged(text.mid(m_sym.size())); m_widget->view()->setCurrentIndex(index); m_widget->view()->scrollTo(index); } } void QuickOpenManager::indexChanage(const QModelIndex &index) { if (m_currentFilter) { m_currentFilter->indexChanged(index); } } void QuickOpenManager::selected() { if (!m_currentFilter) { return; } QString text = m_widget->editor()->text(); QModelIndex index = m_widget->view()->currentIndex(); if (index.isValid() && m_widget->view()->model()->hasChildren(index)) { bool expand = m_widget->view()->isExpanded(index); m_widget->view()->setExpanded(index,!expand); return; } if (!m_currentFilter->selected(text.mid(m_sym.size()),index)) { return; } hidePopup(); } void QuickOpenManager::appAboutToQuit() { hidePopup(); }
11,597
C++
.cpp
345
27.089855
104
0.637179
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,326
quickopenfiles.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenfiles.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenfiles.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenfiles.h" #include "quickopen_global.h" #include <QStandardItemModel> #include <QStandardItem> #include <QSortFilterProxyModel> #include <QDir> #include <QFileInfo> #include <QTimer> #include <QApplication> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenFiles::QuickOpenFiles(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpen(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); m_filesModel = new QStandardItemModel(this); m_proxyModel = new QSortFilterProxyModel(this); m_proxyModel->setSourceModel(m_model); m_matchCase = Qt::CaseInsensitive; m_maxCount = 10000; m_thread = new FindFilesThread(this); connect(m_thread,SIGNAL(findResult(QStringList)),this,SLOT(findResult(QStringList))); } QuickOpenFiles::~QuickOpenFiles() { if (m_thread) { m_thread->stop(); delete m_thread; } } QString QuickOpenFiles::id() const { return "quickopen/files"; } QString QuickOpenFiles::info() const { return tr("Go to File"); } QString QuickOpenFiles::placeholderText() const { return tr("Type '?' to get help on the actions you can take from here"); } void QuickOpenFiles::activate() { } QAbstractItemModel *QuickOpenFiles::model() const { return m_proxyModel; } QModelIndex QuickOpenFiles::rootIndex() const { return QModelIndex(); } void QuickOpenFiles::updateModel() { cancel(); m_maxCount = m_liteApp->settings()->value(QUICKOPEN_FILES_MAXCOUNT,10000).toInt(); m_matchCase = m_liteApp->settings()->value(QUICKOPNE_FILES_MATCHCASE,false).toBool() ? Qt::CaseSensitive : Qt::CaseInsensitive; m_model->clear(); m_filesModel->clear(); m_proxyModel->setSourceModel(m_model); m_proxyModel->setFilterFixedString(""); m_proxyModel->setFilterKeyColumn(2); m_proxyModel->setFilterCaseSensitivity(m_matchCase); m_editors.clear(); QStringList names; foreach(LiteApi::IEditor *editor, m_liteApp->editorManager()->editorList()) { if (editor->filePath().isEmpty()) { continue; } names.push_back(editor->name()+";"+editor->filePath()); m_editors.push_back(editor->filePath()); } qSort(names); foreach (QString text, names) { QStringList ar = text.split(";"); m_model->appendRow(QList<QStandardItem*>() << new QStandardItem("*") << new QStandardItem(ar[0]) << new QStandardItem(ar[1])); m_filesModel->appendRow(QList<QStandardItem*>() << new QStandardItem("*") << new QStandardItem(ar[0]) << new QStandardItem(ar[1])); } startFindThread(); } void QuickOpenFiles::startFindThread() { QSet<QString> extSet; foreach(LiteApi::IMimeType* type, m_liteApp->mimeTypeManager()->mimeTypeList()) { foreach (QString ext, type->allPatterns()) { if (ext.startsWith(".")) { extSet << ext.mid(1); } else if (ext.startsWith("*.")) { extSet << ext.mid(2); } } } int count = m_model->rowCount(); int maxcount = count+m_liteApp->settings()->value(QUICKOPEN_FILES_MAXCOUNT,100000).toInt(); QSet<QString> editorSet = m_editors.toSet(); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); QStringList folderList; if (editor && !editor->filePath().isEmpty()) { folderList << QFileInfo(editor->filePath()).path(); } folderList << m_liteApp->fileManager()->folderList(); m_thread->setFolderList(folderList,extSet,editorSet,maxcount); m_thread->start(); } void QuickOpenFiles::findResult(const QStringList &fileList) { foreach (QString filePath, fileList) { m_filesModel->appendRow(QList<QStandardItem*>() << new QStandardItem("f") << new QStandardItem(QFileInfo(filePath).fileName()) << new QStandardItem(filePath)); } } QModelIndex QuickOpenFiles::filterChanged(const QString &text) { m_proxyModel->setFilterFixedString(text); //check text size >= 3 for files or editor if (text.size() >= 3) { m_proxyModel->setSourceModel(m_filesModel); } else { m_proxyModel->setSourceModel(m_model); } for(int i = 0; i < m_proxyModel->rowCount(); i++) { QModelIndex index = m_proxyModel->index(i,1); QString name = index.data().toString(); if (name.startsWith(text,m_matchCase)) { return index; } } if (m_proxyModel->rowCount() > 0) return m_proxyModel->index(0,0); QFileInfo file(text); if (file.exists() && file.isFile()) { m_filesModel->appendRow(QList<QStandardItem*>() << new QStandardItem("f") << new QStandardItem(file.fileName()) << new QStandardItem(file.filePath())); return m_model->index(0,0); } return QModelIndex(); } void QuickOpenFiles::indexChanged(const QModelIndex &/*index*/) { } bool QuickOpenFiles::selected(const QString &/*text*/, const QModelIndex &index) { if (!index.isValid()) { return false; } QString filePath = m_proxyModel->index(index.row(),2).data().toString(); if (!m_liteApp->fileManager()->openFile(filePath)) { return false; } return true; } void QuickOpenFiles::cancel() { m_thread->stop(); }
6,768
C++
.cpp
184
31.375
168
0.650597
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,327
quickopenfolder.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenfolder.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2018 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenfolder.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenfolder.h" #include "quickopen_global.h" #include <QStandardItemModel> #include <QStandardItem> #include <QSortFilterProxyModel> #include <QDir> #include <QFileInfo> #include <QTimer> #include <QApplication> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenFolder::QuickOpenFolder(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpenFolder(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); m_proxyModel = new QSortFilterProxyModel(this); m_proxyModel->setSourceModel(m_model); m_matchCase = Qt::CaseInsensitive; m_maxCount = 100000; m_thread = new FindFilesThread(this); connect(m_thread,SIGNAL(findResult(QStringList)),this,SLOT(findResult(QStringList))); } QuickOpenFolder::~QuickOpenFolder() { if (m_thread) { m_thread->stop(); delete m_thread; } } QString QuickOpenFolder::id() const { return "quickopen/folder"; } QString QuickOpenFolder::info() const { return tr("Browser Folder"); } QString QuickOpenFolder::placeholderText() const { return m_placeholderText; } void QuickOpenFolder::activate() { } QAbstractItemModel *QuickOpenFolder::model() const { return m_proxyModel; } QModelIndex QuickOpenFolder::rootIndex() const { return QModelIndex(); } void QuickOpenFolder::updateModel() { m_maxCount = m_liteApp->settings()->value(QUICKOPEN_FOLDER_MAXCOUNT,100000).toInt(); m_matchCase = m_liteApp->settings()->value(QUICKOPNE_FOLDER_MATCHCASE,false).toBool() ? Qt::CaseSensitive : Qt::CaseInsensitive; m_model->clear(); m_proxyModel->setFilterFixedString(""); m_proxyModel->setFilterKeyColumn(2); m_proxyModel->setFilterCaseSensitivity(m_matchCase); startFindThread(); } void QuickOpenFolder::startFindThread() { QSet<QString> extSet; foreach(LiteApi::IMimeType* type, m_liteApp->mimeTypeManager()->mimeTypeList()) { foreach (QString ext, type->allPatterns()) { if (ext.startsWith(".")) { extSet << ext.mid(1); } else if (ext.startsWith("*.")) { extSet << ext.mid(2); } } } int count = m_model->rowCount(); int maxcount = count+m_liteApp->settings()->value(QUICKOPEN_FOLDER_MAXCOUNT,100000).toInt(); QSet<QString> editorSet; QStringList folderList; folderList << m_folder; m_thread->setFolderList(folderList,extSet,editorSet,maxcount); m_thread->stop(); m_thread->start(); } void QuickOpenFolder::findResult(const QStringList &fileList) { foreach (QString filePath, fileList) { m_model->appendRow(QList<QStandardItem*>() << new QStandardItem(QFileInfo(filePath).fileName()) << new QStandardItem(filePath)); } } QModelIndex QuickOpenFolder::filterChanged(const QString &text) { m_proxyModel->setFilterFixedString(text); for(int i = 0; i < m_proxyModel->rowCount(); i++) { QModelIndex index = m_proxyModel->index(i,0); QString name = index.data().toString(); if (name.startsWith(text,m_matchCase)) { return index; } } if (m_proxyModel->rowCount() > 0) return m_proxyModel->index(0,0); return QModelIndex(); } void QuickOpenFolder::indexChanged(const QModelIndex &/*index*/) { } bool QuickOpenFolder::selected(const QString &/*text*/, const QModelIndex &index) { if (!index.isValid()) { return false; } QString filePath = m_proxyModel->index(index.row(),1).data().toString(); if (!m_liteApp->fileManager()->openFile(filePath)) { return false; } return true; } void QuickOpenFolder::cancel() { m_thread->stop(); } void QuickOpenFolder::setFolder(const QString &folder) { m_folder = folder; } void QuickOpenFolder::setPlaceholderText(const QString &text) { m_placeholderText = text; }
5,359
C++
.cpp
159
28.90566
137
0.666731
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,328
quickopenhelp.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenhelp.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenhelp.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenhelp.h" #include <QStandardItemModel> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenHelp::QuickOpenHelp(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpen(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); } QString QuickOpenHelp::id() const { return "quickopen/help"; } QString QuickOpenHelp::info() const { return tr("Show All Quick Open Actions"); } QString QuickOpenHelp::placeholderText() const { return QString(); } void QuickOpenHelp::activate() { } QAbstractItemModel *QuickOpenHelp::model() const { return m_model; } QModelIndex QuickOpenHelp::rootIndex() const { return QModelIndex(); } void QuickOpenHelp::updateModel() { LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); m_model->clear(); QMapIterator<QString,LiteApi::IQuickOpen*> i(mgr->symFilterMap()); while(i.hasNext()) { i.next(); if (i.value() == this) { continue; } m_model->appendRow(QList<QStandardItem*>() << new QStandardItem(i.key()) << new QStandardItem(i.value()->info())); } } QModelIndex QuickOpenHelp::filterChanged(const QString &text) { if (!text.isEmpty()) { LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); LiteApi::IQuickOpen *p = mgr->findBySymbol(text); if (p) { mgr->showBySymbol(text); } } return m_model->index(0,0); } void QuickOpenHelp::indexChanged(const QModelIndex &/*index*/) { } bool QuickOpenHelp::selected(const QString &/*text*/, const QModelIndex &index) { if (!index.isValid()) { return false; } QString key = index.data(0).toString(); LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); mgr->showBySymbol(key); return false; } void QuickOpenHelp::cancel() { }
3,328
C++
.cpp
101
28.623762
123
0.655927
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,329
quickopenlines.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenlines.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenlines.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenlines.h" #include <QStandardItemModel> #include <QTextDocument> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenLines::QuickOpenLines(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpen(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); } QString QuickOpenLines::id() const { return "quickopen/lines"; } QString QuickOpenLines::info() const { return tr("Go to Line"); } QString QuickOpenLines::placeholderText() const { return QString(); } void QuickOpenLines::activate() { } QAbstractItemModel *QuickOpenLines::model() const { return m_model; } QModelIndex QuickOpenLines::rootIndex() const { return QModelIndex(); } bool QuickOpenLines::update(const QString &text) { m_model->clear(); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { m_model->appendRow(new QStandardItem(tr("Open a text file first to go to a line"))); return false; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { m_model->appendRow(new QStandardItem(tr("Open a text file first to go to a line"))); return false; } int maxcount = textEditor->document()->blockCount(); bool ok = false; int line = 0; if (!text.isEmpty()) { line = text.toInt(&ok); } if (line <= 0 || line > maxcount) { ok = false; } if (!ok) { m_model->appendRow(new QStandardItem(QString(tr("Type a line number between %1 and %2 to navigate to")).arg(1).arg(maxcount))); return false; } m_model->appendRow(new QStandardItem(QString(tr("Go to Line %1")).arg(line))); return true; } void QuickOpenLines::updateModel() { update(""); } QModelIndex QuickOpenLines::filterChanged(const QString &text) { update(text); return m_model->index(0,0); } void QuickOpenLines::indexChanged(const QModelIndex &/*index*/) { } bool QuickOpenLines::selected(const QString &text, const QModelIndex &/*index*/) { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return false; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { return false; } int maxcount = textEditor->document()->blockCount(); bool ok = false; int line = 0; if (!text.isEmpty()) { line = text.toInt(&ok); } if (!ok) { return false; } if (line <= 0 || line > maxcount) { return false; } if (line-1 != textEditor->line()) { m_liteApp->editorManager()->addNavigationHistory(); } textEditor->gotoLine(line-1,0,true); return true; } void QuickOpenLines::cancel() { }
4,263
C++
.cpp
135
26.918519
136
0.640694
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,330
quickopenwidget.cpp
visualfc_liteide/liteidex/src/plugins/quickopen/quickopenwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: quickopenwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "quickopenwidget.h" #include "liteapi/liteids.h" #include <QVBoxLayout> #include <QComboBox> #include <QTreeView> #include <QFocusEvent> #include <QHeaderView> #include <QDebug> #include <QApplication> #include <QToolBar> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QuickOpenWidget::QuickOpenWidget(LiteApi::IApplication *app, QWidget *parent) : QWidget(parent, Qt::Popup),// Qt::ToolTip | Qt::WindowStaysOnTopHint), m_liteApp(app) { //this->setFocusPolicy(Qt::NoFocus); m_edit = new Utils::FilterLineEdit(300); m_view = new QTreeView; m_view->setHeaderHidden(true); m_view->setTextElideMode(Qt::ElideLeft); #if QT_VERSION >= 0x050000 m_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else m_view->header()->setResizeMode(QHeaderView::ResizeToContents); #endif m_view->setEditTriggers(QAbstractItemView::NoEditTriggers); m_wrap = true; m_layout = new QVBoxLayout; m_layout->setMargin(0); m_layout->setSpacing(0); m_layout->addWidget(m_edit); m_layout->addWidget(m_view); this->setMinimumWidth(600); this->setMinimumHeight(300); this->setLayout(m_layout); connect(m_edit,SIGNAL(filterChanged(QString)),this,SIGNAL(filterChanged(QString))); m_edit->installEventFilter(this); } void QuickOpenWidget::setModel(QAbstractItemModel *model,const QModelIndex &rootIndex) { m_view->setModel(model); m_view->setRootIndex(rootIndex); setTempToolBar(0); } QLineEdit *QuickOpenWidget::editor() { return m_edit; } QTreeView *QuickOpenWidget::view() { return m_view; } void QuickOpenWidget::setTempToolBar(QToolBar *toolBar) { if (!m_tmpToolBar.isNull()) { m_layout->removeWidget(m_tmpToolBar.data()); m_tmpToolBar->clear(); } m_tmpToolBar.reset(toolBar); if (!toolBar) { return; } m_tmpToolBar->show(); m_layout->insertWidget(0,toolBar); } void QuickOpenWidget::hideEvent(QHideEvent *e) { emit hideWidget(); QWidget::hideEvent(e); } void QuickOpenWidget::closeWidget() { QWidget::close(); } void QuickOpenWidget::showView(QPoint *pos) { if (pos == 0) { QPoint pt(0,0); this->move(m_liteApp->editorManager()->widget()->mapToGlobal(pt)); } else { this->move(pos->x(),pos->y()); } m_edit->setFocus(); this->show(); } bool QuickOpenWidget::eventFilter(QObject *o, QEvent *e) { if (e->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(e); QAbstractItemModel *model = m_view->model(); if (!model) { return false; } const int key = ke->key(); switch (key) { case Qt::Key_Up: { QModelIndex index = m_view->indexAbove(m_view->currentIndex()); if (!index.isValid()) { index = model->index(model->rowCount(m_view->rootIndex())-1,0,m_view->rootIndex()); } m_view->setCurrentIndex(index); emit indexChanage(index); return true; } case Qt::Key_Down: { QModelIndex index = m_view->indexBelow(m_view->currentIndex()); if (!index.isValid()) { index = model->index(0,0,m_view->rootIndex()); } m_view->setCurrentIndex(index); emit indexChanage(index); return true; } // case Qt::Key_Return: { // QModelIndex index = m_view->currentIndex(); // if (model->hasChildren(index)) { // m_view->setExpanded(index,!m_view->isExpanded(index)); // } else { // emit indexEnter(index); // } // return true; // } } } else if (e->type() == QEvent::FocusOut) { if (QWidget::focusWidget() == m_view ) { m_edit->setFocus(); } return true; } return QWidget::eventFilter(o,e); }
5,440
C++
.cpp
161
28.043478
100
0.611143
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,331
liteenvoption.cpp
visualfc_liteide/liteidex/src/plugins/liteenv/liteenvoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: liteenvoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteenvoption.h" #include "ui_liteenvoption.h" #include <QDir> #include <QFileInfo> #include <QFileSystemModel> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteEnvOption::LiteEnvOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::LiteEnvOption) { ui->setupUi(m_widget); m_fileModel = new QFileSystemModel(this); QString path = m_liteApp->resourcePath()+"/liteenv"; QModelIndex root = m_fileModel->setRootPath(path); ui->fileTreeView->setEditTriggers(0); ui->fileTreeView->setModel(m_fileModel); ui->fileTreeView->setRootIndex(root); #if QT_VERSION >= 0x050000 ui->fileTreeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else ui->fileTreeView->header()->setResizeMode(QHeaderView::ResizeToContents); #endif connect(ui->fileTreeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedFile(QModelIndex))); } LiteEnvOption::~LiteEnvOption() { delete m_widget; delete ui; } QWidget *LiteEnvOption::widget() { return m_widget; } QString LiteEnvOption::name() const { return "LiteEnv"; } QString LiteEnvOption::mimeType() const { return "option/liteenv"; } void LiteEnvOption::load() { } void LiteEnvOption::save() { } void LiteEnvOption::doubleClickedFile(QModelIndex index) { if (!index.isValid()) { return; } QFileInfo info = m_fileModel->fileInfo(index); if (!info.isFile()) { return; } if (info.suffix() == QLatin1String("env")) { m_liteApp->fileManager()->openEditor(info.filePath()); } }
2,966
C++
.cpp
92
29.456522
107
0.691582
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,332
envmanager.cpp
visualfc_liteide/liteidex/src/plugins/liteenv/envmanager.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: envmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "envmanager.h" #include "goenvmanager.h" #include "liteenv_global.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "liteapi/liteids.h" #include <QDir> #include <QFile> #include <QFileInfo> #include <QRegExp> #include <QToolBar> #include <QMenu> #include <QComboBox> #include <QLabel> #include <QAction> #include <QActionGroup> #include <QSysInfo> #include <QProcess> #include <QStringList> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end static QString updateValue(const QString &value,const QProcessEnvironment &env) { QString v = value; QRegExp rx("\\$\\((\\w+)\\)"); int pos = 0; QStringList list; while ((pos = rx.indexIn(v, pos)) != -1) { list << rx.cap(1); pos += rx.matchedLength(); } foreach (QString str, list) { if (env.contains(str)) { v.replace("$("+str+")",env.value(str)); } } return v; } Env::Env(LiteApi::IApplication *app, QObject *parent) : LiteApi::IEnv(parent), m_liteApp(app) { m_ideEnvMap.insert("LITEIDE_ROOT_PATH",app->rootPath()); m_ideEnvMap.insert("LITEIDE_APP_PATH",app->applicationPath()); m_ideEnvMap.insert("LITEIDE_TOOL_PATH",app->toolPath()); m_ideEnvMap.insert("LITEIDE_RES_PATH",app->resourcePath()); m_ideEnvMap.insert("LITEIDE_PLUGIN_PATH",app->pluginPath()); m_env = QProcessEnvironment::systemEnvironment(); updateIdeEnv(m_env); m_process = 0; } QString Env::id() const { return m_id; } QString Env::filePath() const { return m_filePath; } QProcessEnvironment& Env::environment() { return m_env; } QStringList Env::orgEnvLines() const { return m_orgEnvLines; } QMap<QString, QString> Env::goEnvMap() const { return m_goEnvMap; } void Env::reload() { if (!m_filePath.isEmpty()) { QFile f(m_filePath); if (f.open(QIODevice::ReadOnly)) { loadEnvFile(&f); f.close(); loadGoEnv(); } } else { emit goenvChanged(m_id); } } void Env::loadGoEnv() { if (!m_process) { m_process = new Process(this); connect(m_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readStdout())); connect(m_process,SIGNAL(readyReadStandardError()),this,SLOT(readStderr())); connect(m_process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finished(int,QProcess::ExitStatus))); connect(m_process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(error(QProcess::ProcessError))); } m_process->stopAndWait(100,200); m_goEnvMap.clear(); QString gocmd = FileUtil::lookPath("go",m_env,false); if (gocmd.isEmpty()) { QString goroot = m_env.value("GOROOT"); if (goroot.isEmpty()) { goroot = LiteApi::getDefaultGOROOT(); } gocmd = FileUtil::lookPathInDir("go",goroot+"/bin"); if (gocmd.isEmpty()) { emit goenvError(m_id,"cannot find go in PATH"); return; } } m_process->setProcessEnvironment(m_env); m_process->start(gocmd,QStringList() << "env"); } void Env::loadEnvFile(QIODevice *dev) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); updateIdeEnv(env); m_orgEnvLines.clear(); #ifdef Q_OS_WIN QRegExp rx("\\%([\\w]+)\\%"); #else QRegExp rx("\\$([\\w]+)"); #endif while (!dev->atEnd()) { QString line = QString::fromUtf8(dev->readLine().trimmed()); if (line.indexOf("#") == 0) { continue; } int pos = line.indexOf("="); if (pos == -1) { continue; } m_orgEnvLines.append(line); QString key = line.left(pos).trimmed(); QString value = line.right(line.length()-pos-1).trimmed(); QStringList cap0; QStringList cap1; pos = 0; while ((pos = rx.indexIn(value, pos)) != -1) { cap0 << rx.cap(0); cap1 << rx.cap(1); pos += rx.matchedLength(); } for (int i = 0; i < cap0.size(); i++) { if (env.contains(cap1.at(i))) { value.replace(cap0.at(i),env.value(cap1.at(i))); } } if (value.contains("$")) { value = updateValue(value,env); } env.insert(key,value); } m_env = env; } void Env::loadEnv(EnvManager *manager, const QString &filePath) { QFile f(filePath); if (!f.open(QIODevice::ReadOnly)) { return; } Env *env = new Env(manager->application(),manager); env->m_filePath = filePath; env->m_id = QFileInfo(filePath).baseName(); env->loadEnvFile(&f); f.close(); manager->addEnv(env); } static QStringList envFilter = QString("GOROOT;GOPATH;GOEXE;GOOS;GOARCH;GOBIN;GOVERSION;GO111MODULE").split(";"); void Env::readStdout() { QByteArray data = m_process->readAllStandardOutput(); // set GOARCH=amd64 // GOARCH="amd64" m_liteApp->appendLog("LiteEnv","go env\n"+QString::fromUtf8(data).trimmed(),false); foreach (QByteArray line, data.split('\n')) { QString info = QString::fromUtf8(line).trimmed(); if (info.startsWith("set ")) { info = info.mid(4); } int index = info.indexOf("="); if (index > 0) { QString key = info.left(index); if (!envFilter.contains(key)) { continue; } QString value = info.right(info.length()-index-1); if (value.startsWith("\"") && value.endsWith("\"")) { value = value.mid(1,value.length()-2); } else if (value.startsWith("\'") && value.endsWith("\'")) { value = value.mid(1,value.length()-2); } m_goEnvMap[key] = value; } } // emit goenvChanged(m_id); } void Env::readStderr() { QByteArray data = m_process->readAllStandardError(); m_liteApp->appendLog("LiteEnv","go env\n"+QString::fromUtf8(data).trimmed(),true); // emit goenvError(m_id,QString::fromUtf8(data)); } void Env::finished(int code, QProcess::ExitStatus /*status*/) { if (code == 0) { emit goenvChanged(m_id); } else { emit goenvError(m_id,QString("go env exit code %1").arg(code)); } } void Env::error(QProcess::ProcessError error) { emit goenvError(m_id, ProcessEx::processErrorText(error)); } void Env::updateIdeEnv(QProcessEnvironment &env) { QMapIterator<QString,QString> i(m_ideEnvMap); while(i.hasNext()) { i.next(); env.insert(i.key(),i.value()); } } EnvManager::EnvManager(QObject *parent) : LiteApi::IEnvManager(parent), m_curEnv(0),m_toolBar(0), m_envCmb(0), m_appLoaded(false) { m_goEnvManager = new GoEnvManager(this); } EnvManager::~EnvManager() { if (m_toolBar) { m_liteApp->actionManager()->removeToolBar(m_toolBar); } if (m_curEnv) { m_liteApp->settings()->setValue(LITEENV_CURRENTENV,m_curEnv->id()); } delete m_selectMenu; } void EnvManager::addEnv(LiteApi::IEnv *env) { m_envList.append(env); connect(env,SIGNAL(goenvError(QString,QString)),this,SLOT(goenvError(QString,QString))); connect(env,SIGNAL(goenvChanged(QString)),this,SLOT(goenvChanged(QString))); } void EnvManager::removeEnv(LiteApi::IEnv *env) { if (env) { disconnect(env,0); } m_envList.removeAll(env); } LiteApi::IEnv *EnvManager::findEnv(const QString &id, const QString &backup) const { foreach (LiteApi::IEnv *env, m_envList) { if (env->id() == id) { return env; } } if (!backup.isEmpty()) { foreach (LiteApi::IEnv *env, m_envList) { if (env->id() == backup) { return env; } } } return NULL; } QList<LiteApi::IEnv*> EnvManager::envList() const { return m_envList; } void EnvManager::setCurrentEnv(LiteApi::IEnv *env) { if (m_curEnv == env) { return; } m_curEnv = env; if (m_curEnv) { m_curEnv->reload(); m_liteApp->settings()->setValue(LITEENV_CURRENTENV,m_curEnv->id()); m_liteApp->appendLog("LiteEnv",QString("load environment %1").arg(m_curEnv->id()),false); } } LiteApi::IEnv *EnvManager::currentEnv() const { return m_curEnv; } QProcessEnvironment EnvManager::currentEnvironment() const { if (m_curEnv) { return m_curEnv->environment(); } return QProcessEnvironment::systemEnvironment(); } void EnvManager::appLoaded() { m_appLoaded = true; m_liteApp->appendLog("EnvManager","init load environment"); //emitEnvChanged(); QString id = m_liteApp->settings()->value(LITEENV_CURRENTENV,"system").toString(); //commandline //liteide --select-env system QString flagSelectEnv = "--select-env"; QString selectEnv = m_liteApp->globalCookie().value(flagSelectEnv).toString(); if (!selectEnv.isEmpty()) { id = selectEnv; m_liteApp->globalCookie().remove(flagSelectEnv); } if (id.isEmpty()) { id = "system"; } this->setCurrentEnvId(id); } void EnvManager::loadEnvFiles(const QString &path) { QDir dir = path; m_liteApp->appendLog("LiteEnv","Loaded environment files from "+path); dir.setFilter(QDir::Files | QDir::NoSymLinks); dir.setNameFilters(QStringList("*.env")); foreach (QString fileName, dir.entryList()) { Env::loadEnv(this,QFileInfo(dir,fileName).absoluteFilePath()); } } void EnvManager::emitEnvChanged() { if (!m_appLoaded) { return; } m_goEnvManager->updateGoEnv(); emit currentEnvChanged(m_curEnv); } //static QString defaultEnvid() //{ //#ifdef Q_OS_WIN // if (QSysInfo::WordSize == 32) { // return "win32"; // } else { // return "win64"; // } //#endif //#ifdef Q_OS_LINUX // if (QSysInfo::WordSize == 32) { // return "linux32"; // } else { // return "linux64"; // } //#endif //#ifdef Q_OS_DARWIN // if (QSysInfo::WordSize == 32) { // return "darwin32"; // } else { // return "darwin64"; // } //#endif //#ifdef Q_OS_FREEBSD // if (QSysInfo::WordSize == 32) { // return "freebsd32"; // } else { // return "freebsd64"; // } //#endif //#ifdef Q_OS_OPENBSD // if (QSysInfo::WordSize == 32) { // return "openbsd32"; // } else { // return "openbsd64"; // } //#endif //} bool EnvManager::initWithApp(LiteApi::IApplication *app) { if (!LiteApi::IEnvManager::initWithApp(app)) { return false; } loadEnvFiles(m_liteApp->resourcePath()+"/liteenv"); m_toolBar = m_liteApp->actionManager()->insertToolBar(ID_TOOLBAR_ENV,tr("Environment Toolbar")); m_liteApp->actionManager()->insertViewMenu(LiteApi::ViewMenuToolBarPos,m_toolBar->toggleViewAction()); m_envCmb = new QComboBox; m_envCmb->setSizeAdjustPolicy(QComboBox::AdjustToContents); m_envCmb->setMinimumContentsLength(6); m_envCmb->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Preferred); m_envCmb->setToolTip(tr("Switching current environment")); m_toolBar->addWidget(m_envCmb); QAction *editAct = new QAction(QIcon("icon:liteenv/images/setenv.png"),tr("Edit current environment"),this); QAction *reloadAct = new QAction(QIcon("icon:liteenv/images/reload.png"),tr("Reload current environment"),this); m_toolBar->addAction(reloadAct); m_toolBar->addAction(editAct); m_selectMenu = new QMenu(tr("Select Environment")); m_liteApp->actionManager()->insertMenuActions(ID_MENU_TOOLS,"sep/env",true, QList<QAction*>() << reloadAct << editAct << m_selectMenu->menuAction()); m_selectActionGroup = new QActionGroup(this); foreach (LiteApi::IEnv *env, m_envList) { m_envCmb->addItem(env->id()); QAction *act = new QAction(env->id(),this); act->setCheckable(true); m_selectActionGroup->addAction(act); } m_selectMenu->addActions(m_selectActionGroup->actions()); m_liteApp->extension()->addObject("LiteApi.IEnvManager",this); connect(m_envCmb,SIGNAL(activated(QString)),this,SLOT(envActivated(QString))); connect(m_selectActionGroup,SIGNAL(triggered(QAction*)),this,SLOT(selectEnvAction(QAction*))); connect(editAct,SIGNAL(triggered()),this,SLOT(editCurrentEnv())); connect(reloadAct,SIGNAL(triggered()),this,SLOT(reloadCurrentEnv())); connect(m_liteApp->editorManager(),SIGNAL(editorSaved(LiteApi::IEditor*)),this,SLOT(editorSaved(LiteApi::IEditor*))); connect(m_liteApp,SIGNAL(broadcast(QString,QString,QVariant)),this,SLOT(broadcast(QString,QString,QVariant))); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); m_goEnvManager->initWithApp(app); return true; } void EnvManager::setCurrentEnvId(const QString &id) { LiteApi::IEnv *env = findEnv(id); if (!env) { return; } for (int i = 0; i < m_envCmb->count(); i++) { if (m_envCmb->itemText(i) == env->id()) { m_envCmb->setCurrentIndex(i); QAction *act = m_selectActionGroup->actions().at(i); if (act) { act->setChecked(true); } break; } } setCurrentEnv(env); } void EnvManager::envActivated(QString id) { setCurrentEnvId(id); } void EnvManager::editCurrentEnv() { if (!m_curEnv) { return; } m_liteApp->fileManager()->openEditor(m_curEnv->filePath(),true); } void EnvManager::reloadCurrentEnv() { if (!m_curEnv) { return; } m_curEnv->reload(); m_liteApp->appendLog("LiteEnv",QString("reload environment %1").arg(m_curEnv->id()),false); //emitEnvChanged(); } void EnvManager::broadcast(QString /*module*/,QString /*id*/,QVariant) { // if (module == "golangpackage" && id == "reloadgopath") { // reloadCurrentEnv(); // } } void EnvManager::editorSaved(LiteApi::IEditor *editor) { LiteApi::ITextEditor *ed = LiteApi::getTextEditor(editor); if (!ed) { return; } if (m_curEnv && m_curEnv->filePath() == ed->filePath()) { m_curEnv->reload(); } } void EnvManager::goenvError(const QString &id, const QString &msg) { m_liteApp->appendLog(QString("%1: go env error").arg(id),msg,true); emitEnvChanged(); } void EnvManager::goenvChanged(const QString &id) { if (id == m_curEnv->id()) { m_liteApp->appendLog("LiteEnv",QString("reset %1 environment for \"go env\"").arg(id),false); emitEnvChanged(); } } void EnvManager::selectEnvAction(QAction *act) { QString id = act->text(); setCurrentEnvId(id); }
15,932
C++
.cpp
508
26.48622
123
0.630174
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,333
liteenvoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/liteenv/liteenvoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: liteenvoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteenvoption.h" #include "liteenvoptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteEnvOptionFactory::LiteEnvOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList LiteEnvOptionFactory::mimeTypes() const { return QStringList() << "option/liteenv"; } LiteApi::IOption *LiteEnvOptionFactory::create(const QString &mimeType) { if (mimeType == "option/liteenv") { return new LiteEnvOption(m_liteApp,this); } return 0; }
1,879
C++
.cpp
49
36.061224
87
0.684009
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,334
goenvmanager.cpp
visualfc_liteide/liteidex/src/plugins/liteenv/goenvmanager.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: goenvmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "goenvmanager.h" #include "fileutil/fileutil.h" #include <QDir> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end using namespace LiteApi; GoEnvManager::GoEnvManager(QObject *parent) : IGoEnvManger(parent) { } bool GoEnvManager::initWithApp(IApplication *app) { if (!IGoEnvManger::initWithApp(app)) { return false; } m_liteApp->extension()->addObject("LiteApi.IGoEnvManger",this); m_envManager = LiteApi::getEnvManager(app); return true; } QString GoEnvManager::gocmd() const { return m_gocmd; } QString GoEnvManager::gotools() const { return m_gotools; } QString GoEnvManager::GOROOT() const { return m_goroot; } QStringList GoEnvManager::GOPATH() const { return m_gopathList; } QProcessEnvironment GoEnvManager::environment() const { return LiteApi::getGoEnvironment(m_liteApp); } QProcessEnvironment GoEnvManager::customEnvironment(const QString &buildFilePath, QString *pCustomBuildPath) const { return LiteApi::getCustomGoEnvironment(m_liteApp,buildFilePath,pCustomBuildPath); } QStringList GoEnvManager::customGOPATH(const QString &buildPath, QString *pCustomBuildPath) const { #ifdef Q_OS_WIN QString sep = ";"; #else QString sep = ":"; #endif QProcessEnvironment env = this->customEnvironment(buildPath,pCustomBuildPath); return env.value("GOPATH").split(sep); } QString GoEnvManager::findRealCustomBuildPath(const QString &buildPath) const { if (buildPath.isEmpty()) { return QString(); } QString customKey = "litebuild-custom/"+buildPath; QString customBuildPath = buildPath; bool use_custom_gopath = m_liteApp->settings()->value(customKey+"#use_custom_gopath",false).toBool(); if (!use_custom_gopath) { QString srcRoot = LiteApi::lookupSrcRoot(buildPath); if (!srcRoot.isEmpty()) { customKey = LiteApi::lookupParentHasCustom(m_liteApp,buildPath,srcRoot, &customBuildPath); if (!customKey.isEmpty()) { use_custom_gopath = true; return customBuildPath; } } } return QString(); } bool GoEnvManager::hasCustomGOPATH(const QString &buildPath) const { return !findRealCustomBuildPath(buildPath).isEmpty(); } void GoEnvManager::updateGoEnv() { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); m_gotools = LiteApi::getGotools(m_liteApp); m_gocmd = FileUtil::lookupGoBin("go",m_liteApp,env,false); m_goroot = env.value("GOROOT"); #ifdef Q_OS_WIN QString sep = ";"; #else QString sep = ":"; #endif QStringList pathList; QString goroot = QDir::toNativeSeparators(env.value("GOROOT")); foreach (QString path, env.value("GOPATH").split(sep,qtSkipEmptyParts)) { pathList.append(QDir::toNativeSeparators(path)); } pathList.removeAll(goroot); pathList.removeDuplicates(); if (m_gopathList != pathList) { m_gopathList = pathList; emit globalGOPATHChanged(); } } void GoEnvManager::updateCustomGOPATH(const QString &buildPath) { emit customGOPATHChanged(buildPath); }
4,560
C++
.cpp
133
29.646617
115
0.680628
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,335
liteenvplugin.cpp
visualfc_liteide/liteidex/src/plugins/liteenv/liteenvplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: liteenvplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteenvplugin.h" #include "envmanager.h" #include "liteenvoptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteEnvPlugin::LiteEnvPlugin() { } bool LiteEnvPlugin::load(LiteApi::IApplication *app) { m_envManager = new EnvManager(this); if (!m_envManager->initWithApp(app)) { return false; } app->optionManager()->addFactory(new LiteEnvOptionFactory(app,this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,830
C++
.cpp
49
35.183673
82
0.682611
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,336
rustedit.cpp
visualfc_liteide/liteidex/src/plugins/rustedit/rustedit.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: rustedit.cpp // Creator: visualfc <visualfc@gmail.com> #include "rustedit.h" #include "fileutil/fileutil.h" #include <QProcess> #include <QTemporaryFile> #include <QFileInfo> #include <QDir> #include <QFile> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end RustEdit::RustEdit(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app) { m_completer = 0; m_editor = 0; m_racerCmd = "racer"; m_process = new QProcess(this); connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finished(int,QProcess::ExitStatus))); LiteApi::IEnvManager *env = LiteApi::getEnvManager(m_liteApp); if (env) { connect(env,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); } } void RustEdit::editorCreated(LiteApi::IEditor *editor) { if (editor->mimeType() != "text/x-rust") { return; } LiteApi::ILiteEditor *ed = LiteApi::getLiteEditor(editor); if (ed) { ed->setTabOption(4,true); ed->setEnableAutoIndentAction(true); } } void RustEdit::currentEditorChanged(LiteApi::IEditor *editor) { if (!editor) { return; } if (editor->mimeType() != "text/x-rust") { return; } LiteApi::ICompleter *completer = LiteApi::findExtensionObject<LiteApi::ICompleter*>(editor,"LiteApi.ICompleter"); if (completer) { setCompleter(completer); } m_editor = LiteApi::getLiteEditor(editor); } void RustEdit::prefixChanged(const QTextCursor &/*cur*/, const QString &pre, bool /*force*/) { if (pre.endsWith("::")) { m_completer->setSeparator("::"); } else if (pre.endsWith(".")) { m_completer->setSeparator("."); } if (m_completer->completionContext() != LiteApi::CompleterCodeContext) { return; } if (m_racerCmd.isEmpty()) { return; } if (m_process->state() != QProcess::NotRunning) { return; } /* int offset = -1; if (pre.endsWith('.')) { m_preWord = pre; offset = 0; } else if (pre.length() == 1) { m_preWord.clear(); } else { if (!force) { return; } m_preWord.clear(); int index = pre.lastIndexOf("."); if (index != -1) { m_preWord = pre.left(index); } }*/ if (!(pre.endsWith("::") || pre.endsWith("."))) { return; } m_prefix = pre; m_lastPrefix = m_prefix; QStringList args; args << "complete"; args << QString("%1").arg(m_editor->line()+1); args << QString("%1").arg(m_editor->column()); args << "racer_temp.rs"; QString path = QDir::tempPath(); QFile file(path+"//racer_temp.rs"); if (file.open(QFile::WriteOnly|QFile::Truncate)) { file.write(m_editor->utf8Data()); file.close(); } m_process->setWorkingDirectory(path); m_process->start(m_racerCmd,args); } void RustEdit::wordCompleted(QString, QString, QString) { } // PREFIX 21,21, // MATCH Arc,115,11,C:\Rust\rust-nightly\src\liballoc\arc.rs,Struct,pub struct Arc<T> { // MATCH Weak,131,11,C:\Rust\rust-nightly\src\liballoc\arc.rs,Struct,pub struct Weak<T> { // MATCH weak_count,205,7,C:\Rust\rust-nightly\src\liballoc\arc.rs,Function,pub fn weak_count<T>(this: &Arc<T>) -> uint { this.inner().weak.load(SeqCst) - 1 } // MATCH strong_count,210,7,C:\Rust\rust-nightly\src\liballoc\arc.rs,Function,pub fn strong_count<T>(this: &Arc<T>) -> uint { this.inner().strong.load(SeqCst) } // PREFIX 16,16, // MATCH core,1,0,C:\Rust\rust-nightly\src\libcore\lib.rs,Module,C:\Rust\rust-nightly\src\libcore\lib.rs // MATCH libc,1,0,C:\Rust\rust-nightly\src\liblibc\lib.rs,Module,C:\Rust\rust-nightly\src\liblibc\lib.rs // MATCH std,1,0,C:\Rust\rust-nightly\src\libstd\lib.rs,Module,C:\Rust\rust-nightly\src\libstd\lib.rs // MATCH log,1,0,C:\Rust\rust-nightly\src\liblog\lib.rs,Module,C:\Rust\rust-nightly\src\liblog\lib.rs // MATCH boxed,1,0,C:\Rust\rust-nightly\src\liballoc\boxed.rs,Module,C:\Rust\rust-nightly\src\liballoc\boxed.rs // MATCH heap,1,0,C:\Rust\rust-nightly\src\liballoc\heap.rs,Module,C:\Rust\rust-nightly\src\liballoc\heap.rs // MATCH boxed,1,0,C:\Rust\rust-nightly\src\liballoc\boxed.rs,Module,C:\Rust\rust-nightly\src\liballoc\boxed.rs // MATCH arc,1,0,C:\Rust\rust-nightly\src\liballoc\arc.rs,Module,C:\Rust\rust-nightly\src\liballoc\arc.rs // MATCH rc,1,0,C:\Rust\rust-nightly\src\liballoc\rc.rs,Module,C:\Rust\rust-nightly\src\liballoc\rc.rs // MATCH oom,100,7,C:\Rust\rust-nightly\src\liballoc\lib.rs,Function,pub fn oom() -> ! { // MATCH fixme_14344_be_sure_to_link_to_collections,120,7,C:\Rust\rust-nightly\src\liballoc\lib.rs,Function,pub fn fixme_14344_be_sure_to_link_to_collections() {} // PREFIX 6,6, // MATCH value,10,4,main.rs,StructField,value // PREFIX 26,29,new // MATCH new,161,11,C:\Rust\rust-nightly\src\liballoc\arc.rs,Function,pub fn new(data: T) -> Arc<T> { void RustEdit::finished(int code, QProcess::ExitStatus) { if (code != 0) { m_liteApp->appendLog("racer",QString::fromUtf8(m_process->readAll()),false); return; } QByteArray data = m_process->readAllStandardOutput(); int count = 0; foreach (QString line, QString::fromUtf8(data).split("\n")) { if (line.startsWith("MATCH")) { QStringList array = line.mid(5).split(",",qtSkipEmptyParts); if (array.size() > 0) { count++; m_completer->appendItem(m_prefix+array[0].trimmed(),QIcon(),true); } } } if (count > 0) { m_completer->updateCompleterModel(); m_completer->showPopup(); } } void RustEdit::setCompleter(LiteApi::ICompleter *completer) { if (m_completer) { disconnect(m_completer,0,this,0); } m_completer = completer; if (m_completer) { if (!m_racerCmd.isEmpty()) { m_completer->setSearchSeparator(false); m_completer->setExternalMode(false); m_completer->setSeparator("."); connect(m_completer,SIGNAL(prefixChanged(QTextCursor,QString,bool)),this,SLOT(prefixChanged(QTextCursor,QString,bool))); connect(m_completer,SIGNAL(wordCompleted(QString,QString,QString)),this,SLOT(wordCompleted(QString,QString,QString))); } else { m_completer->setSearchSeparator(true); m_completer->setExternalMode(false); } } } void RustEdit::currentEnvChanged(LiteApi::IEnv*) { QProcessEnvironment env = LiteApi::getCurrentEnvironment(m_liteApp); m_racerCmd = FileUtil::lookPath("racer",env,false); if (m_racerCmd.isEmpty()) { #ifdef Q_OS_WIN m_racerCmd = "c:\\rust\\bin\\racer.exe"; #endif } m_process->setProcessEnvironment(env); }
8,493
C++
.cpp
206
36.417476
173
0.639352
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,337
rusteditplugin.cpp
visualfc_liteide/liteidex/src/plugins/rustedit/rusteditplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: rusteditplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "rusteditplugin.h" #include "rustedit.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end RustEditPlugin::RustEditPlugin() { } bool RustEditPlugin::load(LiteApi::IApplication *app) { new RustEdit(app,this); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,661
C++
.cpp
45
35.088889
82
0.681762
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,338
dlvdebuggeroptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/dlvdebugger/dlvdebuggeroptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: dlvdebuggeroptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "dlvdebuggeroption.h" #include "dlvdebuggeroptionfactory.h" #include "dlvdebugger_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end DlvDebuggerOptionFactory::DlvDebuggerOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList DlvDebuggerOptionFactory::mimeTypes() const { return QStringList() << OPTION_DLVDEBUGGER; } LiteApi::IOption *DlvDebuggerOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_DLVDEBUGGER) { return new DlvDebuggerOption(m_liteApp,this); } return 0; }
1,947
C++
.cpp
50
36.68
95
0.694136
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,339
dlvdebuggerplugin.cpp
visualfc_liteide/liteidex/src/plugins/dlvdebugger/dlvdebuggerplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gdbdebuggerplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "dlvdebuggerplugin.h" #include "dlvdebugger.h" #ifdef USE_DLVCLIENT #include "dlvrpcdebugger.h" #endif #include "dlvdebuggeroptionfactory.h" #include "litedebugapi/litedebugapi.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end DlvDebuggerPlugin::DlvDebuggerPlugin() { } bool DlvDebuggerPlugin::load(LiteApi::IApplication *app) { LiteApi::IDebuggerManager *manager = LiteApi::getDebugManager(app); if (!manager) { return false; } #ifdef USE_DLVCLIENT DlvRpcDebugger *debug = new DlvRpcDebugger(app); #else DlvDebugger *debug = new DlvDebugger(app); #endif manager->addDebugger(debug); manager->setCurrentDebugger(debug); app->optionManager()->addFactory(new DlvDebuggerOptionFactory(app,this)); return true; } QStringList DlvDebuggerPlugin::dependPluginList() const { return QStringList() << "plugin/litedebug"; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,281
C++
.cpp
64
33.375
82
0.705749
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,340
dlvdebugger.cpp
visualfc_liteide/liteidex/src/plugins/dlvdebugger/dlvdebugger.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: dlvdebugger.cpp // Creator: visualfc <visualfc@gmail.com> #include "dlvdebugger.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "dlvdebuggeroption.h" #include "../litedebug/litedebug_global.h" #include <QStandardItemModel> #include <QProcess> #include <QFile> #include <QDir> #include <QFileInfo> #include <QTextCodec> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end static void GdbMiValueToItem(QStandardItem *item, const GdbMiValue &value) { switch (value.type()) { case GdbMiValue::Invalid: item->appendRow(new QStandardItem("Invalid")); break; case GdbMiValue::Const: if (value.name().isEmpty()) { item->appendRow(new QStandardItem(QString(value.data()))); } else { item->appendRow(new QStandardItem(QString(value.name()+"="+value.data()))); } break; case GdbMiValue::List: { QStandardItem *in = new QStandardItem(QString(value.name())); item->appendRow(in); for (int i = 0; i < value.childCount(); i++) { QStandardItem *iv = new QStandardItem(QString("[%1]").arg(i)); in->appendRow(iv); GdbMiValueToItem(iv,value.childAt(i)); } break; } case GdbMiValue::Tuple: { QStandardItem *iv = item; if (!value.name().isEmpty()) { iv = new QStandardItem(QString(value.name())); item->appendRow(iv); } foreach (const GdbMiValue &v, value.children()) { GdbMiValueToItem(iv,v); } break; } } } DlvDebugger::DlvDebugger(LiteApi::IApplication *app, QObject *parent) : LiteApi::IDebugger(parent), m_liteApp(app), m_envManager(0) { m_process = new LiteProcess(m_liteApp,this); m_process->setUseCtrlC(true); m_asyncModel = new QStandardItemModel(this); m_asyncItem = new QStandardItem; m_asyncModel->appendRow(m_asyncItem); /* m_asyncModel->setHeaderData(0,Qt::Horizontal,"Reason"); m_asyncModel->setHeaderData(1,Qt::Horizontal,"Address"); m_asyncModel->setHeaderData(2,Qt::Horizontal,"Function"); m_asyncModel->setHeaderData(3,Qt::Horizontal,"File"); m_asyncModel->setHeaderData(4,Qt::Horizontal,"Line"); m_asyncModel->setHeaderData(5,Qt::Horizontal,"Thread ID"); m_asyncModel->setHeaderData(6,Qt::Horizontal,"Stoped Threads"); */ m_varsModel = new QStandardItemModel(0,2,this); m_varsModel->setHeaderData(0,Qt::Horizontal,"Name"); m_varsModel->setHeaderData(1,Qt::Horizontal,"Value"); //m_varsModel->setHeaderData(2,Qt::Horizontal,"Type"); m_watchModel = new QStandardItemModel(0,2,this); m_watchModel->setHeaderData(0,Qt::Horizontal,"Name"); m_watchModel->setHeaderData(1,Qt::Horizontal,"Value"); //m_watchModel->setHeaderData(2,Qt::Horizontal,"Type"); m_framesModel = new QStandardItemModel(0,5,this); m_framesModel->setHeaderData(0,Qt::Horizontal,"Level"); m_framesModel->setHeaderData(1,Qt::Horizontal,"Address"); m_framesModel->setHeaderData(2,Qt::Horizontal,"Function"); m_framesModel->setHeaderData(3,Qt::Horizontal,"File"); m_framesModel->setHeaderData(4,Qt::Horizontal,"Line"); m_libraryModel = new QStandardItemModel(0,2,this); m_libraryModel->setHeaderData(0,Qt::Horizontal,"Id"); m_libraryModel->setHeaderData(1,Qt::Horizontal,"Thread Groups"); m_dlvInit = false; m_dlvExit = false; m_readDataBusy = false; m_writeDataBusy = false; m_headlessMode = true; m_headlessInitAddress = false; m_headlessProcess = new LiteProcess(m_liteApp,this); m_headlessProcess->setUseCtrlC(true); m_dlvRunningCmdList << "c" << "continue" << "n" << "next" << "s" << "step" << "si" << "step-instruction" << "stepout"; connect(app,SIGNAL(loaded()),this,SLOT(appLoaded())); connect(m_process,SIGNAL(started()),this,SIGNAL(debugStarted())); connect(m_process,SIGNAL(finished(int)),this,SLOT(finished(int))); connect(m_process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(error(QProcess::ProcessError))); connect(m_process,SIGNAL(readyReadStandardError()),this,SLOT(readStdError())); connect(m_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readStdOutput())); connect(m_headlessProcess,SIGNAL(started()),this,SIGNAL(debugStarted())); connect(m_headlessProcess,SIGNAL(finished(int)),this,SLOT(headlessFinished(int))); connect(m_headlessProcess,SIGNAL(error(QProcess::ProcessError)),this,SLOT(headlessError(QProcess::ProcessError))); connect(m_headlessProcess,SIGNAL(readyReadStandardError()),this,SLOT(headlessReadStdError())); connect(m_headlessProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(headlessReadStdOutput())); } DlvDebugger::~DlvDebugger() { stop(); } void DlvDebugger::appLoaded() { m_envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); } QString DlvDebugger::mimeType() const { return QLatin1String("debugger/delve1"); } QAbstractItemModel *DlvDebugger::debugModel(LiteApi::DEBUG_MODEL_TYPE type) { if (type == LiteApi::ASYNC_MODEL) { return m_asyncModel; } else if (type == LiteApi::VARS_MODEL) { return m_varsModel; } else if (type == LiteApi::WATCHES_MODEL) { return m_watchModel; }else if (type == LiteApi::FRAMES_MODEL) { return m_framesModel; } else if (type == LiteApi::LIBRARY_MODEL) { return m_libraryModel; } return 0; } void DlvDebugger::setWorkingDirectory(const QString &dir) { m_headlessProcess->setWorkingDirectory(dir); m_process->setWorkingDirectory(dir); } void DlvDebugger::setEnvironment (const QStringList &environment) { m_headlessProcess->setEnvironment(environment); m_process->setEnvironment(environment); } bool DlvDebugger::start(const QString &cmd, const QString &arguments) { if (!m_envManager) { return false; } QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString goroot = env.value("GOROOT"); if (!goroot.isEmpty()) { m_runtimeFilePath = QFileInfo(QDir(goroot),"src/pkg/runtime/").path(); } QString dlv = FileUtil::lookupGoBin("dlv",m_liteApp,env,true); if (dlv.isEmpty()) { dlv = FileUtil::lookPath("dlv",env,false); } m_dlvFilePath = dlv; //m_checkFuncDecl = false; if (m_dlvFilePath.isEmpty()) { m_liteApp->appendLog("DlvDebugger","dlv was not found on system PATH (hint: is Delve installed?)",true); return false; } clear(); if (m_headlessMode) { QStringList argsList; argsList << "--headless" << "--api-version=2" << "--accept-multiclient"; argsList << "exec" << cmd; if (!arguments.isEmpty()) { argsList << "--" << arguments; } #ifdef Q_OS_WIN //m_headlessProcess->setNativeArguments(argsList.join(" ")); m_headlessProcess->startEx("\""+m_dlvFilePath+"\"", argsList.join(" ")); #else m_headlessProcess->startEx(m_dlvFilePath, argsList.join(" ")); #endif QString log = QString("%1 %2 [%3]").arg(m_dlvFilePath).arg(argsList.join(" ")).arg(m_headlessProcess->workingDirectory()); emit debugLog(LiteApi::DebugRuntimeLog,log); } else { QStringList argsList; argsList << "exec" << cmd; if (!arguments.isEmpty()) { argsList << "--" << arguments; } #ifdef Q_OS_WIN //m_process->setNativeArguments(argsList.join(" ")); m_process->startEx("\""+m_dlvFilePath+"\"",argsList.join(" ")); #else m_process->startEx(m_dlvFilePath,argsList.join(" ")); #endif QString log = QString("%1 %2 [%3]").arg(m_dlvFilePath).arg(argsList.join(" ")).arg(m_process->workingDirectory()); emit debugLog(LiteApi::DebugRuntimeLog,log); } return true; } void DlvDebugger::stop() { if (m_dlvExit) { return; } m_dlvExit = true; if (m_headlessMode) { if (!m_headlessProcess->isStop()) { m_headlessProcess->interrupt(); } if (!m_process->isStop()) { m_process->interrupt(); } if (!m_headlessProcess->isStop() && !m_headlessProcess->waitForFinished(500)) { m_headlessProcess->kill(); } if (!m_process->isStop() && !m_process->waitForFinished(500)) { command_helper("exit",true); if (!m_process->waitForFinished(500)) { m_process->kill(); } } } else { if (!m_process->isStop()) { m_process->interrupt(); } command_helper("exit",true); if (!m_process->isStop() && !m_process->waitForFinished(1000)) { m_process->kill(); } } } bool DlvDebugger::isRunning() { return m_process->state() != QProcess::NotRunning; } void DlvDebugger::continueRun() { command("continue"); } void DlvDebugger::stepOver() { command("next"); } void DlvDebugger::stepInto() { command("step"); } void DlvDebugger::stepOut() { command("stepout"); // QString cmd = LiteApi::getGotools(m_liteApp); // QProcess process; // process.setEnvironment(LiteApi::getCurrentEnvironment(m_liteApp).toStringList()); // QFileInfo info(m_lastFileName); // process.setWorkingDirectory(info.path()); // QStringList args; // args << "finddecl" << "-file" << info.fileName() << "-line" << QString("%1").arg(m_lastFileLine+1); // process.start(cmd,args); // if (!process.waitForFinished(3000)) { // emit debugLog(LiteApi::DebugErrorLog,"error wait find decl process"); // process.kill(); // return; // } // if (process.exitCode() != 0) { // emit debugLog(LiteApi::DebugErrorLog,"error get find decl result"); // return; // } // QByteArray data = process.readAll().trimmed(); // QStringList ar = QString::fromUtf8(data).split(" "); // if (ar.size() != 4 || ar[0] != "func") { // emit debugLog(LiteApi::DebugErrorLog,"error find func decl in line"); // return; // } // m_funcDecl.fileName = m_lastFileName; // m_funcDecl.funcName = ar[1]; // m_funcDecl.start = ar[2].toInt()-1; // m_funcDecl.end = ar[3].toInt()-1; // m_checkFuncDecl = true; // command("next"); } void DlvDebugger::runToLine(const QString &fileName, int line) { bool find = findBreakPoint(fileName,line); if (!find) { insertBreakPoint(fileName,line); command("continue"); removeBreakPoint(fileName,line); } else { command("continue"); } } void DlvDebugger::createWatch(const QString &var) { QString cmd = "vars "+QRegExp::escape(var); m_updateCmdHistroy.push_back(cmd); command_helper(cmd.toUtf8(),true); } void DlvDebugger::removeWatch(const QString &value) { m_watchNameMap.remove(value); for (int i = 0; i < m_watchModel->rowCount(); i++) { QStandardItem *nameItem = m_watchModel->item(i,0); if (nameItem->text() == value) { m_watchModel->removeRow(i); break; } } emit watchRemoved(value); } void DlvDebugger::removeAllWatch() { m_watchNameMap.clear(); m_watchModel->removeRows(0,m_watchModel->rowCount()); } void DlvDebugger::showFrame(QModelIndex index) { QStandardItem* file = m_framesModel->item( index.row(), 3 ); QStandardItem* line = m_framesModel->item( index.row(), 4 ); if( !file || !line ) { return; } QString filename = file->text(); int lineno = line->text().toInt(); if( lineno <= 0 ) { return; } emit gotoLine(filename, lineno - 1 ); } void DlvDebugger::dbclickItem(QModelIndex index, LiteApi::DEBUG_MODEL_TYPE type) { } void DlvDebugger::expandItem(QModelIndex index, LiteApi::DEBUG_MODEL_TYPE type) { QStandardItem *parent = 0; if (type == LiteApi::VARS_MODEL) { parent = m_varsModel->itemFromIndex(index); } else if (type == LiteApi::WATCHES_MODEL) { parent = m_watchModel->itemFromIndex(index); } if (!parent) { return; } if (parent->data(VarExpanded).toInt() == 1) { return; } parent->setData(1,VarExpanded); } void DlvDebugger::setInitBreakTable(const QMultiMap<QString,int> &bks) { m_initBks = bks; } void DlvDebugger::setInitWatchList(const QStringList &names) { foreach (QString name, names) { m_watchNameMap.insert(name,""); } } void DlvDebugger::insertBreakPoint(const QString &fileName, int line) { insertBreakPointHelper(fileName,line,false); } void DlvDebugger::insertBreakPointHelper(const QString &fileName, int line, bool force) { line++; QString location = QString("%1:%2").arg(fileName).arg(line); if (m_locationBkMap.contains(location)) { return; } QString id = QString("bk%1").arg(qHash(location)); m_locationBkMap.insert(location,id); QStringList args; args << "break"; args << id; args << QString("%1:%2").arg(fileName).arg(line); command_helper(args.join(" ").toUtf8(),force); } void DlvDebugger::removeBreakPoint(const QString &fileName, int line) { line++; QString location = QString("%1:%2").arg(fileName).arg(line); QString id = m_locationBkMap.value(location); if (id.isEmpty()) { return; } m_locationBkMap.remove(location); QStringList args; args << "clear"; args << id; command_helper(args.join(" ").toUtf8(),false); } bool DlvDebugger::findBreakPoint(const QString &fileName, int line) { QString location = QString("%1:%2").arg(fileName).arg(line); QString id = m_locationBkMap.value(location); return m_locationBkMap.contains(location); } void DlvDebugger::command_helper(const QByteArray &cmd, bool force) { if (m_writeDataBusy && !force) { return; } m_writeDataBusy = true; m_lastCmd = cmd; if (m_dlvRunningCmdList.contains(cmd)) { m_asyncItem->removeRows(0,m_asyncItem->rowCount()); m_asyncItem->setText("runing"); } #ifdef Q_OS_WIN m_process->write(cmd+"\r\n"); #else m_process->write(cmd+"\n"); #endif } void DlvDebugger::enterAppText(const QString &text) { m_updateCmdList.clear(); m_updateCmdHistroy.clear(); QString cmd = text.trimmed(); if (cmd == "r" || cmd == "restart") { m_processId.clear(); } if (m_headlessMode) { m_headlessProcess->write(text.toUtf8()); } else { m_process->write(text.toUtf8()); } } void DlvDebugger::enterDebugText(const QString &text) { m_updateCmdList.clear(); m_updateCmdHistroy.clear(); QString cmd = text.trimmed(); if (cmd == "r" || cmd == "restart") { m_processId.clear(); } command(text.toUtf8()); } void DlvDebugger::command(const QByteArray &cmd) { command_helper(cmd,false); } void DlvDebugger::readStdError() { //Process 4084 has exited with status 0 QString data = QString::fromUtf8(m_process->readAllStandardError()); // qDebug() << data << m_processId; //QRegExp reg; emit debugLog(LiteApi::DebugConsoleLog,data); foreach (QString line, data.split("\n",qtSkipEmptyParts)) { if (line.startsWith("Process "+m_processId)) { m_processId.clear(); this->stop(); } } } //static bool isNameChar(char c) //{ // // could be 'stopped' or 'shlibs-added' // return (c >= 'a' && c <= 'z') || c == '-'; //} void DlvDebugger::handleResponse(const QByteArray &buff) { if (buff.isEmpty()) { return; } if (!m_headlessMode) { if (m_processId.isEmpty()) { //Process restarted with PID int n = buff.indexOf("PID"); if (n != -1) { m_processId = buff.mid(n+3).replace("(dlv)","").trimmed(); } } } //Process restarted with PID 4532 //> main.main() H:/goproj/src/hello/main.go:13 (hits goroutine(1):1 total:1) (PC: 0x401172) //> main.main() H:/goproj/src/hello/main.go:14 (PC: 0x401179) //> main.main() H:/goproj/src/hello/main.go:21 (hits goroutine(1):1 total:1) (PC: 0x40161a) //> fmt.Println() c:/go/go1.6/src/fmt/print.go:263 (PC: 0x45aeca) //> runtime.convT2E() c:/go/go1.6/src/runtime/iface.go:128 (PC: 0x40caaa)" //> github.com/derekparker/delve/cmd/dlv/cmds.New() /src/github.com/derekparker/delve/cmd/dlv/cmds/commands.go:61 (PC: 0x45d09f) //> [bk6767010] main.test() H:/goproj/src/hello/main.go:12 (hits goroutine(1):1 total:1) (PC: 0x401066) //> [bk101903173] github.com/derekparker/delve/vendor/github.com/spf13/cobra.(*Command).Execute() github.com/derekparker/delve/vendor/github.com/spf13/cobra/command.go:615 (hits goroutine(1):1 total:1) (PC: 0x524ea6) //> qlang.io/qlang%2espec%2ev1.Import() //> main.main() goapi/_test/_testmain.go:50 (hits goroutine(1):1 total:1) (PC: 0x4011ca) if (buff.contains("> ")) { static QRegExp reg(">(\\s+\\[[\\w\\d]+\\])?\\s+([\\w\\d_\\.\\%\\*\\(\\)\\/]+)\\(\\)\\s+((?:[a-zA-Z]:)?[\\w\\d_@\\s\\-\\/\\.\\\\]+):(\\d+)\\s?(.*)\\s?(\\(PC:\\s+.*)"); int n = reg.indexIn(QString::fromUtf8(buff)); if (n < 0) { return; } QString fileName = reg.cap(3); if (fileName.startsWith("./")) { fileName = QDir::cleanPath(m_process->workingDirectory()+"/"+fileName); } QString line = reg.cap(4); if (!fileName.isEmpty() && !line.isEmpty()) { bool ok = false; int n = line.toInt(&ok); if (ok) { m_lastFileName = fileName; m_lastFileLine = n-1; //check step out emit setCurrentLine(fileName,n-1); } } m_handleState.setStopped(true); m_asyncItem->removeRows(0,m_asyncItem->rowCount()); m_asyncItem->setText("stopped"); QString func = reg.cap(2).trimmed(); //hack if (func.contains("%")) { func.replace("%2e","."); } QString hits = reg.cap(5).trimmed(); QString pc = reg.cap(6).trimmed(); int pos = pc.indexOf('\n'); if (pos != -1) { pc.truncate(pos); } if (!hits.isEmpty()) { m_asyncItem->appendRow(new QStandardItem(hits)); } m_asyncItem->appendRow(new QStandardItem(pc)); m_asyncItem->appendRow(new QStandardItem("func="+func)); m_asyncItem->appendRow(new QStandardItem("file="+fileName)); m_asyncItem->appendRow(new QStandardItem("line="+line)); emit setExpand(LiteApi::ASYNC_MODEL,m_asyncModel->indexFromItem(m_asyncItem),true); } } void DlvDebugger::cleanup() { stop(); } void DlvDebugger::clear() { m_headlessInitAddress = false; m_lastFileLine = 0; m_lastFileName.clear(); m_dlvInit = false; m_dlvExit = false; m_readDataBusy = false; m_writeDataBusy = false; m_handleState.clear(); m_varNameMap.clear(); m_watchNameMap.clear(); m_watchList.clear(); m_updateCmdHistroy.clear(); m_nameItemMap.clear(); m_varChangedItemList.clear(); m_inbuffer.clear(); m_locationBkMap.clear(); m_cmdList.clear(); m_framesModel->removeRows(0,m_framesModel->rowCount()); m_libraryModel->removeRows(0,m_libraryModel->rowCount()); m_varsModel->removeRows(0,m_varsModel->rowCount()); m_watchModel->removeRows(0,m_watchModel->rowCount()); } void DlvDebugger::initDebug() { //get thread id m_processId.clear(); if (!m_headlessMode) { command_helper("restart",true); } QMapIterator<QString,int> i(m_initBks); while (i.hasNext()) { i.next(); QString fileName = i.key(); QList<int> lines = m_initBks.values(fileName); foreach(int line, lines) { insertBreakPointHelper(fileName,line,true); } } if (m_liteApp->settings()->value(LITEDEBUG_AUTOBREAKMAIN,false).toBool()) { command_helper("break main.main",true); } command_helper("continue",true); emit debugLoaded(); } static QString valueToolTip(const QString &value) { int offset = 0; QString toolTip; QString text = value; text.replace(", ",","); for (int i = 0; i < text.size(); i++) { // if (text[i] == '[') { // int j = i; // for (; j++; j < text.size()) { // if (text[j] == ']') { // break; // } // } // toolTip += text.mid(i,j+1-i); // i = j; // continue; // } if (text[i] == '{') { if ( (i+1) < text.size() && text[i+1] == '}' ) { toolTip += "{}"; i++; } else { offset++; toolTip += text[i]; toolTip += "\n"+QString("\t").repeated(offset); } } else if (text[i] == '}') { offset--; toolTip += "\n"+QString("\t").repeated(offset); toolTip += text[i]; } else if (text[i] == ',') { toolTip += text[i]; int pos = text.lastIndexOf(QRegExp("\\{|\\[|\\]|\\}"),i-1); if (pos != -1 && text[pos] == '[') { continue; } toolTip += "\n"+QString("\t").repeated(offset); } else { toolTip += text[i]; } } return toolTip; } void DlvDebugger::readStdOutput() { QByteArray data = m_process->readAllStandardOutput(); if (!m_dlvInit) { m_dlvInit = true; initDebug(); } m_writeDataBusy = false; if (m_dlvExit) { return; } int newstart = 0; int scan = m_inbuffer.size(); m_inbuffer.append(data); //hack check (dlv) static bool first_check = true; static bool dlv_check = false; if (first_check) { first_check = false; dlv_check = m_inbuffer.indexOf("(dlv)") != -1; } if (dlv_check && !m_inbuffer.endsWith("(dlv) ")) { return; } // This can trigger when a dialog starts a nested event loop. if (m_readDataBusy) return; QStringList dataList; while (newstart < m_inbuffer.size()) { int start = newstart; int end = m_inbuffer.indexOf('\n', scan); if (end < 0) { //m_inbuffer.remove(0, start); //return; end = m_inbuffer.size()-1; } newstart = end + 1; scan = newstart; if (end == start) continue; #ifdef Q_OS_WIN if (m_inbuffer.at(end - 1) == '\r') { --end; if (end == start) continue; } #endif m_readDataBusy = true; QByteArray data = QByteArray::fromRawData(m_inbuffer.constData() + start, end - start); dataList.append(QString::fromUtf8(data)); handleResponse(data); m_readDataBusy = false; } // if (m_checkFuncDecl) { // if (m_lastFileName == m_funcDecl.fileName && m_lastFileLine >= m_funcDecl.start && m_lastFileLine <= m_funcDecl.end) { // command("next"); // m_inbuffer.clear(); // return; // } // m_checkFuncDecl = false; // m_funcDecl.clear(); // } bool emitLog = true; if (!m_updateCmdHistroy.isEmpty()) { QString cmdHistroy = m_updateCmdHistroy.takeFirst(); if (cmdHistroy == "stack") { // 0 0x000000000040135a in main.main // at H:/goproj/src/hello/main.go:24 // 1 0x000000000042c629 in runtime.main // at c:/go/go1.6/src/runtime/proc.go:188 // 2 0x0000000000456560 in runtime.goexit // at c:/go/go1.6/src/runtime/asm_amd64.s:1998 m_framesModel->removeRows(0,m_framesModel->rowCount()); QString data = QString::fromUtf8(m_inbuffer); QStringList dataList = data.split("\n",qtSkipEmptyParts); bool head = true; QList<QStandardItem*> items; foreach (QString data, dataList) { if (head) { // data. items.clear(); QStringList ar = data.split(" ",qtSkipEmptyParts); if (ar.size() == 4) { items << new QStandardItem(ar[0]); items << new QStandardItem(ar[1]); items << new QStandardItem(ar[3]); } } else { data = data.trimmed(); if (data.startsWith("at")) { data = data.mid(2).trimmed(); int n = data.lastIndexOf(":"); if (n > 0) { items << new QStandardItem(data.left(n)); items << new QStandardItem(data.mid(n+1)); m_framesModel->appendRow(items); } } } head = !head; } } else if (cmdHistroy == "stack 0 -full") { // s = " \x04S\x00\x00\x00\x00\x00\x1d\x00\x00\x00\x00\x00\x00\x00" // v = []int len: 0, cap: 4257785, []" // args = []string len: 1, cap: 1, ["H:\\goproj\\src\\hello\\debug"] m_varsModel->removeRows(0,m_varsModel->rowCount()); QString data = QString::fromUtf8(m_inbuffer); QStringList dataList = data.split("\n",qtSkipEmptyParts); QMap<QString,QString> nameMap; foreach(QString text, dataList) { int n = text.indexOf("="); if (n == -1) { continue; } QString name = text.left(n).trimmed(); QString value = text.mid(n+1).trimmed(); n = value.indexOf("(unreadable"); if (n != -1) { value = value.left(n)+"(unreadable ..."; } nameMap.insert(name,value); QStandardItem *nameItem = new QStandardItem(name); QStandardItem *valueItem = new QStandardItem(value); valueItem->setToolTip(valueToolTip(value)); QMap<QString,QString>::iterator it = m_varNameMap.find(name); if (it != m_varNameMap.end() && it.value() != value) { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::red),Qt::TextColorRole); #else valueItem->setData(Qt::red,Qt::TextColorRole); #endif } m_varsModel->appendRow(QList<QStandardItem*>() << nameItem << valueItem); } m_varNameMap = nameMap; } else if (cmdHistroy.startsWith("vars ")) { foreach (QString data, QString::fromUtf8(m_inbuffer).split("\n",qtSkipEmptyParts)) { int n = data.indexOf("="); if (n >= 0) { QString name = data.left(n-1); QString value = data.mid(n+1).trimmed(); if (name.isEmpty() || value.isEmpty() || name.contains(" ")) { continue; } bool find = false; for (int i = 0; i < m_watchModel->rowCount(); i++) { QStandardItem *nameItem = m_watchModel->item(i,0); QStandardItem *valueItem = m_watchModel->item(i,1); if (nameItem->text() == name) { find = true; if (m_watchNameMap.value(name) == value) { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::black),Qt::TextColorRole); #else valueItem->setData(Qt::black,Qt::TextColorRole); #endif } else { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::red),Qt::TextColorRole); #else valueItem->setData(Qt::red,Qt::TextColorRole); #endif valueItem->setText(value); } } } if (!find) { QStandardItem *nameItem = new QStandardItem(name); nameItem->setData(name,VarNameRole); QStandardItem *valueItem = new QStandardItem(value); valueItem->setToolTip(valueToolTip(value)); m_watchModel->appendRow(QList<QStandardItem*>() << nameItem << valueItem ); emit watchCreated(name,name); } m_watchNameMap.insert(name,value); } } } emitLog = false; } else if (!m_headlessMode) { emit debugLog(LiteApi::DebugApplationLog,QString::fromUtf8(m_inbuffer)); } if (emitLog) { emit debugLog(LiteApi::DebugConsoleLog,QString::fromUtf8(m_inbuffer)); } m_inbuffer.clear(); if (m_handleState.exited() && !m_dlvExit) { m_dlvExit = true; stop(); } else if (m_handleState.stopped()) { m_updateCmdList.clear(); m_updateCmdList << "stack" << "stack 0 -full"; foreach (QString s, m_watchNameMap.keys()) { if (s.isEmpty()) { continue; } m_updateCmdList << "vars "+QRegExp::escape(s); } } m_handleState.clear(); if (!m_updateCmdList.isEmpty()) { foreach(QString cmd, m_updateCmdList.takeFirst().split("|")) { m_updateCmdHistroy.push_back(cmd.trimmed()); command(cmd.trimmed().toUtf8()); } } } void DlvDebugger::finished(int code) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv exited with code %1").arg(code)); cleanup(); } void DlvDebugger::error(QProcess::ProcessError err) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv error! %1").arg(ProcessEx::processErrorText(err))); cleanup(); } void DlvDebugger::readTty(const QByteArray &data) { emit debugLog(LiteApi::DebugApplationLog,QString::fromUtf8(data)); } void DlvDebugger::headlessReadStdError() { QString data = QString::fromUtf8(m_headlessProcess->readAllStandardError()); //qDebug() << data; emit debugLog(LiteApi::DebugErrorLog,data); } void DlvDebugger::headlessReadStdOutput() { QString data = QString::fromUtf8(m_headlessProcess->readAllStandardOutput()); //API server listening at: 127.0.0.1:54151 if (!m_headlessInitAddress) { QString tmp = data.trimmed(); QString addr; if (tmp.startsWith("API")) { int pos = tmp.lastIndexOf(" "); if (pos != -1) { addr = tmp.mid(pos+1); if (addr.indexOf(":") > 0) { m_headlessInitAddress = true; } } } if (m_headlessInitAddress) { QStringList argsList; argsList << "connect" << addr; #ifdef Q_OS_WIN m_process->setNativeArguments(argsList.join(" ")); m_process->start("\""+m_dlvFilePath+"\""); #else m_process->start(m_dlvFilePath + " " + argsList.join(" ")); #endif QString log = QString("%1 %2 [%3]").arg(m_dlvFilePath).arg(argsList.join(" ")).arg(m_process->workingDirectory()); emit debugLog(LiteApi::DebugRuntimeLog,log); } } emit debugLog(LiteApi::DebugApplationLog,data); } void DlvDebugger::headlessFinished(int code) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv server exited with code %1").arg(code)); cleanup(); } void DlvDebugger::headlessError(QProcess::ProcessError err) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv server error! %1").arg(ProcessEx::processErrorText(err))); cleanup(); }
33,327
C++
.cpp
927
28.728155
220
0.586671
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,341
dlvdebuggeroption.cpp
visualfc_liteide/liteidex/src/plugins/dlvdebugger/dlvdebuggeroption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: dlvdebuggeroption.cpp // Creator: visualfc <visualfc@gmail.com> #include "dlvdebuggeroption.h" #include "ui_dlvdebuggeroption.h" #include "dlvdebugger_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end DlvDebuggerOption::DlvDebuggerOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::DlvDebuggerOption) { ui->setupUi(m_widget); } DlvDebuggerOption::~DlvDebuggerOption() { delete m_widget; delete ui; } QWidget *DlvDebuggerOption::widget() { return m_widget; } QString DlvDebuggerOption::name() const { return "DlvDebugger"; } QString DlvDebuggerOption::mimeType() const { return OPTION_DLVDEBUGGER; } void DlvDebuggerOption::load() { ui->flagsLineEdit->setText(m_liteApp->settings()->value(DLVDEBUGGER_EXTFLAGS,"").toString()); int id = m_liteApp->settings()->value(DLVDEBUGGER_ASMSYNTAX,1).toInt(); if (id >= 0 && id < ui->buttonGroup->buttons().size()) { ui->buttonGroup->buttons().at(id)->setChecked(true); } } void DlvDebuggerOption::save() { m_liteApp->settings()->setValue(DLVDEBUGGER_EXTFLAGS,ui->flagsLineEdit->text()); int size = ui->buttonGroup->buttons().size(); for (int i = 0; i < size; i++) { if (ui->buttonGroup->buttons().at(i)->isChecked()) { m_liteApp->settings()->setValue(DLVDEBUGGER_ASMSYNTAX,i); break; } } }
2,702
C++
.cpp
78
31.679487
97
0.672401
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,342
dlvrpcdebugger.cpp
visualfc_liteide/liteidex/src/plugins/dlvdebugger/dlvrpcdebugger.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: dlvrpcdebugger.cpp // Creator: visualfc <visualfc@gmail.com> #include "dlvrpcdebugger.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "dlvdebuggeroption.h" #include "dlvdebugger_global.h" #include "../litedebug/litedebug_global.h" #include <QStandardItemModel> #include <QProcess> #include <QFile> #include <QDir> #include <QFileInfo> #include <QTextCodec> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end static void GdbMiValueToItem(QStandardItem *item, const GdbMiValue &value) { switch (value.type()) { case GdbMiValue::Invalid: item->appendRow(new QStandardItem("Invalid")); break; case GdbMiValue::Const: if (value.name().isEmpty()) { item->appendRow(new QStandardItem(QString(value.data()))); } else { item->appendRow(new QStandardItem(QString(value.name()+"="+value.data()))); } break; case GdbMiValue::List: { QStandardItem *in = new QStandardItem(QString(value.name())); item->appendRow(in); for (int i = 0; i < value.childCount(); i++) { QStandardItem *iv = new QStandardItem(QString("[%1]").arg(i)); in->appendRow(iv); GdbMiValueToItem(iv,value.childAt(i)); } break; } case GdbMiValue::Tuple: { QStandardItem *iv = item; if (!value.name().isEmpty()) { iv = new QStandardItem(QString(value.name())); item->appendRow(iv); } foreach (const GdbMiValue &v, value.children()) { GdbMiValueToItem(iv,v); } break; } } } DlvRpcDebugger::DlvRpcDebugger(LiteApi::IApplication *app, QObject *parent) : LiteApi::IDebugger(parent), m_liteApp(app), m_envManager(0) { m_process = new LiteProcess(m_liteApp,this); m_process->setUseCtrlC(true); m_asyncModel = new QStandardItemModel(0,1,this); m_asyncItem = new QStandardItem; m_asyncModel->appendRow(m_asyncItem); /* m_asyncModel->setHeaderData(0,Qt::Horizontal,"Reason"); m_asyncModel->setHeaderData(1,Qt::Horizontal,"Address"); m_asyncModel->setHeaderData(2,Qt::Horizontal,"Function"); m_asyncModel->setHeaderData(3,Qt::Horizontal,"File"); m_asyncModel->setHeaderData(4,Qt::Horizontal,"Line"); m_asyncModel->setHeaderData(5,Qt::Horizontal,"Thread ID"); m_asyncModel->setHeaderData(6,Qt::Horizontal,"Stoped Threads"); */ m_varsModel = new QStandardItemModel(0,4,this); m_varsModel->setHeaderData(0,Qt::Horizontal,"Name"); m_varsModel->setHeaderData(1,Qt::Horizontal,"Type"); m_varsModel->setHeaderData(2,Qt::Horizontal,"Value"); m_varsModel->setHeaderData(3,Qt::Horizontal,"Address"); m_watchModel = new QStandardItemModel(0,4,this); m_watchModel->setHeaderData(0,Qt::Horizontal,"Name"); m_watchModel->setHeaderData(1,Qt::Horizontal,"Type"); m_watchModel->setHeaderData(2,Qt::Horizontal,"Value"); m_watchModel->setHeaderData(3,Qt::Horizontal,"Address"); connect(m_watchModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(watchItemChanged(QStandardItem*))); m_framesModel = new QStandardItemModel(0,5,this); m_framesModel->setHeaderData(0,Qt::Horizontal,"Level"); m_framesModel->setHeaderData(1,Qt::Horizontal,"Address"); m_framesModel->setHeaderData(2,Qt::Horizontal,"Function"); m_framesModel->setHeaderData(3,Qt::Horizontal,"File"); m_framesModel->setHeaderData(4,Qt::Horizontal,"Line"); m_goroutinesModel = new QStandardItemModel(0,5,this); m_goroutinesModel->setHeaderData(0,Qt::Horizontal,"Goroutine"); m_goroutinesModel->setHeaderData(1,Qt::Horizontal,"Address"); m_goroutinesModel->setHeaderData(2,Qt::Horizontal,"Function"); m_goroutinesModel->setHeaderData(3,Qt::Horizontal,"File"); m_goroutinesModel->setHeaderData(4,Qt::Horizontal,"Line"); m_threadsModel = new QStandardItemModel(0,6,this); m_threadsModel->setHeaderData(0,Qt::Horizontal,"Thread"); m_threadsModel->setHeaderData(1,Qt::Horizontal,"Goroutine"); m_threadsModel->setHeaderData(2,Qt::Horizontal,"Address"); m_threadsModel->setHeaderData(3,Qt::Horizontal,"Function"); m_threadsModel->setHeaderData(4,Qt::Horizontal,"File"); m_threadsModel->setHeaderData(5,Qt::Horizontal,"Line"); m_registersModel = new QStandardItemModel(0,2,this); m_registersModel->setHeaderData(0,Qt::Horizontal,"Name"); m_registersModel->setHeaderData(1,Qt::Horizontal,"Value"); //m_libraryModel->setHeaderData(0,Qt::Horizontal,"Id"); //m_libraryModel->setHeaderData(1,Qt::Horizontal,"Thread Groups");` // m_asynJsonItem = new QStandardItem(0,2); // m_asynJsonItem->setText("stop"); //m_libraryModel->appendRow(m_asynJsonItem); m_asmModel = new QStandardItemModel(0,6,this); m_asmModel->setHeaderData(0,Qt::Horizontal,"State"); m_asmModel->setHeaderData(1,Qt::Horizontal,"Address"); m_asmModel->setHeaderData(2,Qt::Horizontal,"Code"); m_asmModel->setHeaderData(3,Qt::Horizontal,"Text"); m_asmModel->setHeaderData(4,Qt::Horizontal,"File"); m_asmModel->setHeaderData(5,Qt::Horizontal,"Line"); m_dlvInit = false; m_dlvExit = false; m_readDataBusy = false; m_writeDataBusy = false; m_headlessInitAddress = false; m_headlessProcess = new Process(this); // m_headlessProcess->setUseCtrlC(true); m_dlvClient = new DlvClient(this); connect(m_dlvClient,SIGNAL(commandSuccess(QString,DebuggerState,QVariant)),this,SLOT(clientCommandSuccess(QString,DebuggerState,QVariant))); m_dlvRunningCmdList << "c" << "continue" << "n" << "next" << "s" << "step" << "si" << "step-instruction" << "stepout"; connect(app,SIGNAL(loaded()),this,SLOT(appLoaded())); connect(m_process,SIGNAL(started()),this,SIGNAL(debugStarted())); connect(m_process,SIGNAL(finished(int)),this,SLOT(finished(int))); connect(m_process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(error(QProcess::ProcessError))); connect(m_process,SIGNAL(readyReadStandardError()),this,SLOT(readStdError())); connect(m_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readStdOutput())); connect(m_headlessProcess,SIGNAL(started()),this,SIGNAL(debugStarted())); connect(m_headlessProcess,SIGNAL(finished(int)),this,SLOT(headlessFinished(int))); connect(m_headlessProcess,SIGNAL(error(QProcess::ProcessError)),this,SLOT(headlessError(QProcess::ProcessError))); connect(m_headlessProcess,SIGNAL(readyReadStandardError()),this,SLOT(headlessReadStdError())); connect(m_headlessProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(headlessReadStdOutput())); } DlvRpcDebugger::~DlvRpcDebugger() { stop(); } void DlvRpcDebugger::appLoaded() { m_envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); } QString DlvRpcDebugger::mimeType() const { return QLatin1String("debugger/delve"); } QAbstractItemModel *DlvRpcDebugger::debugModel(LiteApi::DEBUG_MODEL_TYPE type) { if (type == LiteApi::ASYNC_MODEL) { return m_asyncModel; } else if (type == LiteApi::VARS_MODEL) { return m_varsModel; } else if (type == LiteApi::WATCHES_MODEL) { return m_watchModel; }else if (type == LiteApi::FRAMES_MODEL) { return m_framesModel; } else if (type == LiteApi::GOROUTINES_MODEL) { return m_goroutinesModel; } else if (type == LiteApi::THREADS_MODEL) { return m_threadsModel; } else if (type == LiteApi::REGS_MODEL) { return m_registersModel; } else if (type == LiteApi::ASM_MODEL) { return m_asmModel; } return 0; } void DlvRpcDebugger::setWorkingDirectory(const QString &dir) { m_headlessProcess->setWorkingDirectory(dir); m_process->setWorkingDirectory(dir); } void DlvRpcDebugger::setEnvironment (const QStringList &environment) { m_headlessProcess->setEnvironment(environment); m_process->setEnvironment(environment); } bool DlvRpcDebugger::start(const QString &cmd, const QString &arguments) { if (!m_envManager) { return false; } QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString goroot = env.value("GOROOT"); if (!goroot.isEmpty()) { m_runtimeFilePath = QFileInfo(QDir(goroot),"src/pkg/runtime/").path(); } QString dlv = FileUtil::lookupGoBin("dlv",m_liteApp,env,true); if (dlv.isEmpty()) { dlv = FileUtil::lookPath("dlv",env,false); } m_dlvFilePath = dlv; //m_checkFuncDecl = false; if (m_dlvFilePath.isEmpty()) { m_liteApp->appendLog("DlvRpcDebugger","dlv was not found on system PATH (hint: is Delve installed? \"go install github.com/go-delve/delve/cmd/dlv@latest\")",true); return false; } clear(); QStringList argsList; argsList << "--headless" << "--api-version=2" << "--accept-multiclient"; QStringList flags = m_liteApp->settings()->value(DLVDEBUGGER_EXTFLAGS).toString().split(" ",qtSkipEmptyParts); if (!flags.isEmpty()) { foreach(QString flag, flags) { if (flag.startsWith("--")) { argsList << flag; } } } //argsList << "--log"; argsList << "exec" << cmd; if (!arguments.isEmpty()) { argsList << "--" << arguments; } #ifdef Q_OS_WIN //m_headlessProcess->setNativeArguments(argsList.join(" ")); m_headlessProcess->startEx("\""+m_dlvFilePath+"\"", argsList.join(" ")); #else m_headlessProcess->startEx(m_dlvFilePath, argsList.join(" ")); #endif QString log = QString("%1 %2 [%3]").arg(m_dlvFilePath).arg(argsList.join(" ")).arg(m_headlessProcess->workingDirectory()); emit debugLog(LiteApi::DebugRuntimeLog,log); return true; } void DlvRpcDebugger::stop() { m_dlvExit = true; if (!m_headlessProcess->isStop()) { m_dlvClient->Detach(); m_headlessProcess->waitForFinished(500); } if (!m_process->isStop()) { m_process->interrupt(); } if (!m_headlessProcess->isStop() && !m_headlessProcess->waitForFinished(500)) { m_headlessProcess->kill(); } if (!m_process->isStop() && !m_process->waitForFinished(500)) { command_helper("exit",true); if (!m_process->waitForFinished(500)) { m_process->kill(); } } } bool DlvRpcDebugger::isRunning() { return m_headlessProcess->state() != QProcess::NotRunning; } void DlvRpcDebugger::continueRun() { command("continue"); } void DlvRpcDebugger::stepOver() { command("next"); } void DlvRpcDebugger::stepInto() { command("step"); } void DlvRpcDebugger::stepOut() { command("stepout"); } void DlvRpcDebugger::runToLine(const QString &fileName, int line) { bool find = findBreakPoint(fileName,line); if (!find) { insertBreakPointHelper(fileName,line,true); command_helper("continue",true); removeBreakPointHelper(fileName,line,true); } else { command("continue"); } } void DlvRpcDebugger::createWatch(const QString &var) { if (var.isEmpty()) { return; } if (m_watchList.contains(var)) { return; } //m_watchNameMap.insert(var,""); m_watchList.push_back(var); emit watchCreated(var,var); if (var.contains(".")) { updateWatch(-1); return; } DebuggerState state = m_dlvClient->GetState(); if (!state.pCurrentThread) { return; } updateWatch(state.pCurrentThread->GoroutineID); // QString cmd = "vars "+QRegExp::escape(var); // m_updateCmdHistroy.push_back(cmd); // command_helper(cmd.toUtf8(),true); } void DlvRpcDebugger::removeWatch(const QString &value) { //m_watchNameMap.remove(value); m_watchList.removeAll(value); for (int i = 0; i < m_watchModel->rowCount(); i++) { QStandardItem *nameItem = m_watchModel->item(i,0); if (nameItem->text() == value) { m_watchModel->removeRow(i); break; } } emit watchRemoved(value); } void DlvRpcDebugger::removeAllWatch() { m_watchNameMap.clear(); m_watchList.clear(); m_watchModel->removeRows(0,m_watchModel->rowCount()); } void DlvRpcDebugger::gotoFileByIndex(const QStandardItemModel *model, QModelIndex index, int ifile, int iline) { QVariant file = index.sibling(index.row(),ifile).data(); QVariant line = index.sibling(index.row(),iline).data(); if( !file.isValid() || !line.isValid() ) { return; } QString filename = file.toString(); int lineno = line.toInt(); if( lineno <= 0 ) { return; } emit gotoLine(filename, lineno - 1 ); } void DlvRpcDebugger::dbclickItem(QModelIndex index, LiteApi::DEBUG_MODEL_TYPE type) { switch (type) { case LiteApi::FRAMES_MODEL: gotoFileByIndex(m_framesModel,index,3,4); break; case LiteApi::THREADS_MODEL: gotoFileByIndex(m_threadsModel,index,4,5); break; case LiteApi::GOROUTINES_MODEL: gotoFileByIndex(m_goroutinesModel,index,3,4); break; case LiteApi::ASM_MODEL: gotoFileByIndex(m_asmModel,index,4,5); break; } } void DlvRpcDebugger::expandItem(QModelIndex index, LiteApi::DEBUG_MODEL_TYPE type) { QStandardItem *parent = 0; if (type == LiteApi::VARS_MODEL) { parent = m_varsModel->itemFromIndex(index); } else if (type == LiteApi::WATCHES_MODEL) { parent = m_watchModel->itemFromIndex(index); } if (!parent) { return; } if (parent->data(VarExpanded).toInt() == 1) { return; } parent->setData(1,VarExpanded); } void DlvRpcDebugger::setInitBreakTable(const QMultiMap<QString,int> &bks) { m_initBks = bks; } void DlvRpcDebugger::setInitWatchList(const QStringList &names) { m_watchList = names; foreach (QString name, names) { emit watchCreated(name,name); } } void DlvRpcDebugger::insertBreakPoint(const QString &fileName, int line) { insertBreakPointHelper(fileName,line,false); } void DlvRpcDebugger::insertBreakPointHelper(const QString &fileName, int line, bool force) { line++; QString location = QString("%1:%2").arg(fileName).arg(line); if (m_locationBkMap.contains(location)) { return; } QString id = QString("bk%1").arg(qHash(location)); m_locationBkMap.insert(location,id); QStringList args; args << "break"; args << id; args << QString("%1:%2").arg(fileName).arg(line); command_helper(args.join(" ").toUtf8(),force); } void DlvRpcDebugger::removeBreakPoint(const QString &fileName, int line) { removeBreakPointHelper(fileName,line,false); } void DlvRpcDebugger::removeBreakPointHelper(const QString &fileName, int line, bool force) { line++; QString location = QString("%1:%2").arg(fileName).arg(line); QString id = m_locationBkMap.value(location); if (id.isEmpty()) { return; } m_locationBkMap.remove(location); QStringList args; args << "clear"; args << id; command_helper(args.join(" ").toUtf8(),force); } bool DlvRpcDebugger::findBreakPoint(const QString &fileName, int line) { QString location = QString("%1:%2").arg(fileName).arg(line); QString id = m_locationBkMap.value(location); return m_locationBkMap.contains(location); } void DlvRpcDebugger::command_helper(const QByteArray &cmd, bool force) { if (m_writeDataBusy && !force) { return; } m_writeDataBusy = true; m_lastCmd = cmd; if (m_dlvRunningCmdList.contains(cmd)) { m_asyncItem->removeRows(0,m_asyncItem->rowCount()); m_asyncItem->setText("runing"); } #ifdef Q_OS_WIN m_process->write(cmd+"\r\n"); #else m_process->write(cmd+"\n"); #endif } void DlvRpcDebugger::enterAppText(const QString &text) { m_updateCmdList.clear(); m_updateCmdHistroy.clear(); QString cmd = text.trimmed(); if (cmd == "r" || cmd == "restart") { m_processId.clear(); } m_headlessProcess->write(text.toUtf8()); } void DlvRpcDebugger::enterDebugText(const QString &text) { m_updateCmdList.clear(); m_updateCmdHistroy.clear(); QString cmd = text.trimmed(); if (cmd == "r" || cmd == "restart") { m_processId.clear(); } command(text.toUtf8()); } void DlvRpcDebugger::command(const QByteArray &cmd) { command_helper(cmd,false); } void DlvRpcDebugger::readStdError() { //Process 4084 has exited with status 0 QString data = QString::fromUtf8(m_process->readAllStandardError()); // qDebug() << data << m_processId; //QRegExp reg; emit debugLog(LiteApi::DebugConsoleLog,data); foreach (QString line, data.split("\n",qtSkipEmptyParts)) { if (line.startsWith("Process "+m_processId)) { m_processId.clear(); this->stop(); } } } //static bool isNameChar(char c) //{ // // could be 'stopped' or 'shlibs-added' // return (c >= 'a' && c <= 'z') || c == '-'; //} void DlvRpcDebugger::handleResponse(const QByteArray &buff) { if (buff.isEmpty()) { return; } //Process restarted with PID 4532 //> main.main() H:/goproj/src/hello/main.go:13 (hits goroutine(1):1 total:1) (PC: 0x401172) //> main.main() H:/goproj/src/hello/main.go:14 (PC: 0x401179) //> main.main() H:/goproj/src/hello/main.go:21 (hits goroutine(1):1 total:1) (PC: 0x40161a) //> fmt.Println() c:/go/go1.6/src/fmt/print.go:263 (PC: 0x45aeca) //> runtime.convT2E() c:/go/go1.6/src/runtime/iface.go:128 (PC: 0x40caaa)" //> github.com/derekparker/delve/cmd/dlv/cmds.New() /src/github.com/derekparker/delve/cmd/dlv/cmds/commands.go:61 (PC: 0x45d09f) //> [bk6767010] main.test() H:/goproj/src/hello/main.go:12 (hits goroutine(1):1 total:1) (PC: 0x401066) //> [bk101903173] github.com/derekparker/delve/vendor/github.com/spf13/cobra.(*Command).Execute() github.com/derekparker/delve/vendor/github.com/spf13/cobra/command.go:615 (hits goroutine(1):1 total:1) (PC: 0x524ea6) //> qlang.io/qlang%2espec%2ev1.Import() //> main.main() goapi/_test/_testmain.go:50 (hits goroutine(1):1 total:1) (PC: 0x4011ca) //> [bk3711824616] main.test[go.shape.int_0]() ./main.go:9 (hits goroutine(1):1 total:1) (PC: 0x10b2be2) //> [bk1584098684] main.(*My[go.shape.int]).Test1() c:/dev/demo/main.go:16 (hits goroutine(1):1 total:1) (PC: 0x4daa88) if (buff.contains("> ")) { // [bk] main.test[shape]() file:line static QRegExp reg(">(\\s+\\[[\\w\\d]+\\])?\\s+([\\w\\d_\\-\\.\\%\\*\\[\\]\\(\\)\\/]+)\\(\\)\\s+((?:[a-zA-Z]:)?[\\w\\d_@\\s\\-\\/\\.\\\\]+):(\\d+)\\s?(.*)\\s?(\\(PC:\\s+.*)"); int n = reg.indexIn(QString::fromUtf8(buff)); if (n < 0) { return; } QString fileName = reg.cap(3); if (fileName.startsWith("./")) { fileName = QDir::cleanPath(m_process->workingDirectory()+"/"+fileName); } QString line = reg.cap(4); if (!fileName.isEmpty() && !line.isEmpty()) { bool ok = false; int n = line.toInt(&ok); if (ok) { m_lastFileName = fileName; m_lastFileLine = n-1; //check step out emit setCurrentLine(fileName,n-1); } } m_handleState.setStopped(true); m_asyncItem->removeRows(0,m_asyncItem->rowCount()); m_asyncItem->setText("stopped"); QString func = reg.cap(2).trimmed(); //hack if (func.contains("%")) { func.replace("%2e","."); } QString hits = reg.cap(5).trimmed(); QString pc = reg.cap(6).trimmed(); int pos = pc.indexOf('\n'); if (pos != -1) { pc.truncate(pos); } if (!hits.isEmpty()) { m_asyncItem->appendRow(new QStandardItem(hits)); } m_asyncItem->appendRow(new QStandardItem(pc)); m_asyncItem->appendRow(new QStandardItem("func="+func)); m_asyncItem->appendRow(new QStandardItem("file="+fileName)); m_asyncItem->appendRow(new QStandardItem("line="+line)); emit setExpand(LiteApi::ASYNC_MODEL,m_asyncModel->indexFromItem(m_asyncItem),true); } } void DlvRpcDebugger::cleanup() { stop(); } void DlvRpcDebugger::clear() { m_headlessInitAddress = false; m_lastFileLine = 0; m_lastFileName.clear(); m_dlvInit = false; m_dlvExit = false; m_readDataBusy = false; m_writeDataBusy = false; m_handleState.clear(); m_checkVarsMap.clear(); m_watchNameMap.clear(); m_watchList.clear(); m_updateCmdHistroy.clear(); m_nameItemMap.clear(); m_varChangedItemList.clear(); m_inbuffer.clear(); m_locationBkMap.clear(); m_cmdList.clear(); m_framesModel->removeRows(0,m_framesModel->rowCount()); m_threadsModel->removeRows(0,m_threadsModel->rowCount()); m_goroutinesModel->removeRows(0,m_goroutinesModel->rowCount()); m_varsModel->removeRows(0,m_varsModel->rowCount()); m_watchModel->removeRows(0,m_watchModel->rowCount()); m_asmModel->removeRows(0,m_asmModel->rowCount()); } void DlvRpcDebugger::initDebug() { //get thread id m_processId.clear(); QMapIterator<QString,int> i(m_initBks); while (i.hasNext()) { i.next(); QString fileName = i.key(); QList<int> lines = m_initBks.values(fileName); foreach(int line, lines) { insertBreakPointHelper(fileName,line,true); } } if (m_liteApp->settings()->value(LITEDEBUG_AUTOBREAKMAIN,false).toBool()) { command_helper("break main.main",true); } command_helper("continue",true); emit debugLoaded(); } static QString valueToolTip(const QString &value) { int offset = 0; QString toolTip; QString text = value; text.replace(", ",","); for (int i = 0; i < text.size(); i++) { // if (text[i] == '[') { // int j = i; // for (; j++; j < text.size()) { // if (text[j] == ']') { // break; // } // } // toolTip += text.mid(i,j+1-i); // i = j; // continue; // } if (text[i] == '{') { if ( (i+1) < text.size() && text[i+1] == '}' ) { toolTip += "{}"; i++; } else { offset++; toolTip += text[i]; toolTip += "\n"+QString("\t").repeated(offset); } } else if (text[i] == '}') { offset--; toolTip += "\n"+QString("\t").repeated(offset); toolTip += text[i]; } else if (text[i] == ',') { toolTip += text[i]; int pos = text.lastIndexOf(QRegExp("\\{|\\[|\\]|\\}"),i-1); if (pos != -1 && text[pos] == '[') { continue; } toolTip += "\n"+QString("\t").repeated(offset); } else { toolTip += text[i]; } } return toolTip; } void DlvRpcDebugger::readStdOutput() { QByteArray data = m_process->readAllStandardOutput(); if (!m_dlvInit) { m_dlvInit = true; initDebug(); } m_writeDataBusy = false; if (m_dlvExit) { return; } int newstart = 0; int scan = m_inbuffer.size(); m_inbuffer.append(data); //hack check (dlv) static bool first_check = true; static bool dlv_check = false; if (first_check) { first_check = false; dlv_check = m_inbuffer.indexOf("(dlv)") != -1; } if (dlv_check && !m_inbuffer.endsWith("(dlv) ")) { return; } // This can trigger when a dialog starts a nested event loop. if (m_readDataBusy) return; QStringList dataList; while (newstart < m_inbuffer.size()) { int start = newstart; int end = m_inbuffer.indexOf('\n', scan); if (end < 0) { //m_inbuffer.remove(0, start); //return; end = m_inbuffer.size()-1; } newstart = end + 1; scan = newstart; if (end == start) continue; #ifdef Q_OS_WIN if (m_inbuffer.at(end - 1) == '\r') { --end; if (end == start) continue; } #endif m_readDataBusy = true; QByteArray data = QByteArray::fromRawData(m_inbuffer.constData() + start, end - start); dataList.append(QString::fromUtf8(data)); handleResponse(data); m_readDataBusy = false; } // if (m_checkFuncDecl) { // if (m_lastFileName == m_funcDecl.fileName && m_lastFileLine >= m_funcDecl.start && m_lastFileLine <= m_funcDecl.end) { // command("next"); // m_inbuffer.clear(); // return; // } // m_checkFuncDecl = false; // m_funcDecl.clear(); // } bool emitLog = true; if (!m_updateCmdHistroy.isEmpty()) { QString cmdHistroy = m_updateCmdHistroy.takeFirst(); if (cmdHistroy == "stack") { // 0 0x000000000040135a in main.main // at H:/goproj/src/hello/main.go:24 // 1 0x000000000042c629 in runtime.main // at c:/go/go1.6/src/runtime/proc.go:188 // 2 0x0000000000456560 in runtime.goexit // at c:/go/go1.6/src/runtime/asm_amd64.s:1998 m_framesModel->removeRows(0,m_framesModel->rowCount()); QString data = QString::fromUtf8(m_inbuffer); QStringList dataList = data.split("\n",qtSkipEmptyParts); bool head = true; QList<QStandardItem*> items; foreach (QString data, dataList) { if (head) { // data. items.clear(); QStringList ar = data.split(" ",qtSkipEmptyParts); if (ar.size() == 4) { items << new QStandardItem(ar[0]); items << new QStandardItem(ar[1]); items << new QStandardItem(ar[3]); } } else { data = data.trimmed(); if (data.startsWith("at")) { data = data.mid(2).trimmed(); int n = data.lastIndexOf(":"); if (n > 0) { QString fileName = data.left(n); QString fileLine = data.mid(n+1); if (fileName.startsWith("./")) { fileName = QDir::cleanPath(m_process->workingDirectory()+"/"+fileName); } items << new QStandardItem(fileName); items << new QStandardItem(fileLine); m_framesModel->appendRow(items); } } } head = !head; } } else if (cmdHistroy == "stack 0 -full") { // s = " \x04S\x00\x00\x00\x00\x00\x1d\x00\x00\x00\x00\x00\x00\x00" // v = []int len: 0, cap: 4257785, []" // args = []string len: 1, cap: 1, ["H:\\goproj\\src\\hello\\debug"] m_varsModel->removeRows(0,m_varsModel->rowCount()); QString data = QString::fromUtf8(m_inbuffer); QStringList dataList = data.split("\n",qtSkipEmptyParts); QMap<QString,QString> nameMap; foreach(QString text, dataList) { int n = text.indexOf("="); if (n == -1) { continue; } QString name = text.left(n).trimmed(); QString value = text.mid(n+1).trimmed(); n = value.indexOf("(unreadable"); if (n != -1) { value = value.left(n)+"(unreadable ..."; } nameMap.insert(name,value); QStandardItem *nameItem = new QStandardItem(name); QStandardItem *valueItem = new QStandardItem(value); valueItem->setToolTip(valueToolTip(value)); QMap<QString,QString>::iterator it = m_checkVarsMap.find(name); if (it != m_checkVarsMap.end() && it.value() != value) { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::red),Qt::TextColorRole); #else valueItem->setData(Qt::red,Qt::TextColorRole); #endif } m_varsModel->appendRow(QList<QStandardItem*>() << nameItem << valueItem); } m_checkVarsMap = nameMap; } else if (cmdHistroy.startsWith("vars ")) { foreach (QString data, QString::fromUtf8(m_inbuffer).split("\n",qtSkipEmptyParts)) { int n = data.indexOf("="); if (n >= 0) { QString name = data.left(n-1); QString value = data.mid(n+1).trimmed(); if (name.isEmpty() || value.isEmpty() || name.contains(" ")) { continue; } bool find = false; for (int i = 0; i < m_watchModel->rowCount(); i++) { QStandardItem *nameItem = m_watchModel->item(i,0); QStandardItem *valueItem = m_watchModel->item(i,1); if (nameItem->text() == name) { find = true; if (m_watchNameMap.value(name) == value) { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::black),Qt::TextColorRole); #else valueItem->setData(Qt::black,Qt::TextColorRole); #endif } else { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::red),Qt::TextColorRole); #else valueItem->setData(Qt::red,Qt::TextColorRole); #endif valueItem->setText(value); } } } if (!find) { QStandardItem *nameItem = new QStandardItem(name); nameItem->setData(name,VarNameRole); QStandardItem *valueItem = new QStandardItem(value); valueItem->setToolTip(valueToolTip(value)); m_watchModel->appendRow(QList<QStandardItem*>() << nameItem << valueItem ); emit watchCreated(name,name); } m_watchNameMap.insert(name,value); } } } emitLog = false; } if (emitLog) { emit debugLog(LiteApi::DebugConsoleLog,QString::fromUtf8(m_inbuffer)); } m_inbuffer.clear(); if (m_handleState.exited() && !m_dlvExit) { m_dlvExit = true; stop(); } else if (m_handleState.stopped()) { DebuggerState state = m_dlvClient->GetState(); if (state.pCurrentThread) { m_updateCmdList.clear(); //m_updateCmdList << "stack";// << "stack 0 -full"; int id = state.pCurrentThread->GoroutineID; updateStackframe(id); updateVariable(id); updateWatch(id); updateThreads(state.Threads); updateGoroutines(); updateRegisters(state.pCurrentThread->ID,true); updateAsm(id,state.pCurrentThread->PC); } } m_handleState.clear(); if (!m_updateCmdList.isEmpty()) { foreach(QString cmd, m_updateCmdList.takeFirst().split("|")) { m_updateCmdHistroy.push_back(cmd.trimmed()); command(cmd.trimmed().toUtf8()); } } } void DlvRpcDebugger::updateWatch(int id) { QList<Variable> watch; QList<QString> errList; foreach (QString s, m_watchList) { if (s.isEmpty()) { continue; } int gid = id; if (s.contains(".")) { gid = -1; } VariablePointer pt = m_dlvClient->EvalVariable(EvalScope(gid),s,LoadConfig::Long128(3)); if (pt) { watch.push_back(*pt); } else { errList.push_back(s); } } emit beginUpdateModel(LiteApi::WATCHES_MODEL); m_watchModel->removeRows(0,m_watchModel->rowCount()); foreach (QString name, errList) { QStandardItem *item = new QStandardItem(name); item->setData(name,VarNameRole); QStandardItem *type = new QStandardItem("not find"); #if QT_VERSION >= 0x050000 type->setData(QColor(Qt::red),Qt::TextColorRole); #else type->setData(Qt::red,Qt::TextColorRole); #endif m_watchModel->appendRow(QList<QStandardItem*>() << item << type); } QMap<QString,QString> saveMap; updateVariableHelper(watch,m_watchModel,0,"",0,saveMap,m_checkWatchMap); m_checkWatchMap = saveMap; emit endUpdateModel(LiteApi::WATCHES_MODEL); } void DlvRpcDebugger::updateVariable(int id) { QList<Variable> vars = m_dlvClient->ListLocalVariables(EvalScope(id),LoadConfig::Long128(3)); QList<Variable> args = m_dlvClient->ListFunctionArgs(EvalScope(id),LoadConfig::Long128(3)); QMap<QString,QString> saveMap; emit beginUpdateModel(LiteApi::VARS_MODEL); m_varsModel->removeRows(0,m_varsModel->rowCount()); updateVariableHelper(args,m_varsModel,0,"",0,saveMap,m_checkVarsMap); updateVariableHelper(vars,m_varsModel,0,"",0,saveMap,m_checkVarsMap); m_checkVarsMap = saveMap; emit endUpdateModel(LiteApi::VARS_MODEL); } void DlvRpcDebugger::updateStackframe(int id) { QList<Stackframe> frames = m_dlvClient->Stacktrace(id,128,LoadConfig::Long128(3)); emit beginUpdateModel(LiteApi::FRAMES_MODEL); m_framesModel->removeRows(0,m_framesModel->rowCount()); int index = 0; foreach(Stackframe f, frames) { QList<QStandardItem*> items; items << new QStandardItem(QString("%1").arg(index)); items << new QStandardItem(QString("0x%1").arg(f.PC,0,16)); if (f.pFunction) { items << new QStandardItem(f.pFunction->Name); } else { items << new QStandardItem(""); } items << new QStandardItem(f.File); items << new QStandardItem(QString("%1").arg(f.Line)); m_framesModel->appendRow(items); index++; } emit endUpdateModel(LiteApi::FRAMES_MODEL); } static bool threadIdThan(const Thread &s1, const Thread &s2) { if (s1.GoroutineID != s2.GoroutineID) { return s1.GoroutineID > s2.GoroutineID; } return s1.ID < s2.ID; } void DlvRpcDebugger::updateThreads(const QList<Thread> &threads) { QList<Thread> ths = threads; qSort(ths.begin(),ths.end(),threadIdThan); emit beginUpdateModel(LiteApi::THREADS_MODEL); m_threadsModel->removeRows(0,m_threadsModel->rowCount()); foreach (Thread t, ths) { QStandardItem *item = new QStandardItem(QString("%1").arg(t.ID)); QStandardItem *gitem = new QStandardItem(QString("%1").arg(t.GoroutineID)); QStandardItem *file = new QStandardItem(t.File); QStandardItem *line = new QStandardItem(QString("%1").arg(t.Line)); QStandardItem *pc = new QStandardItem(QString("0x%1").arg(t.PC,0,16)); QStandardItem *func = new QStandardItem; if (t.pFunction) { func->setText(t.pFunction->Name); } m_threadsModel->appendRow(QList<QStandardItem*>() << item << gitem << pc << func << file << line); } emit endUpdateModel(LiteApi::THREADS_MODEL); } static void appendLocationItem(QStandardItem *parent, const QString &name, const Location &loc) { QStandardItem *item = new QStandardItem(name); QStandardItem *file = new QStandardItem(loc.File); QStandardItem *line = new QStandardItem(QString("%1").arg(loc.Line)); QStandardItem *pc = new QStandardItem(QString("0x%1").arg(loc.PC,0,16)); QStandardItem *func = new QStandardItem; if (loc.pFunction) { func->setText(loc.pFunction->Name); } parent->appendRow(QList<QStandardItem*>() << item << pc << func << file << line); } static void appendLocationRoot(QStandardItemModel *parent, QStandardItem *item, const Location &loc) { QStandardItem *file = new QStandardItem(loc.File); QStandardItem *line = new QStandardItem(QString("%1").arg(loc.Line)); QStandardItem *pc = new QStandardItem(QString("0x%1").arg(loc.PC,0,16)); QStandardItem *func = new QStandardItem; if (loc.pFunction) { func->setText(loc.pFunction->Name); } parent->appendRow(QList<QStandardItem*>() << item << pc << func << file << line); } /* const ( Gidle uint64 = iota // 0 Grunnable // 1 runnable and on a run queue Grunning // 2 Gsyscall // 3 Gwaiting // 4 GmoribundUnused // 5 currently unused, but hardcoded in gdb scripts Gdead // 6 Genqueue // 7 Only the Gscanenqueue is used. Gcopystack // 8 in this state when newstack is moving the stack ) */ void DlvRpcDebugger::updateGoroutines() { QList<Goroutine> lst = m_dlvClient->ListGoroutines(); emit beginUpdateModel(LiteApi::GOROUTINES_MODEL); m_goroutinesModel->removeRows(0,m_goroutinesModel->rowCount()); foreach (Goroutine g, lst) { QString value; if (g.ThreadId != 0) { value = QString("(thread %1)").arg(g.ThreadId); } if ( (g.Status == 4 || g.Status == 3) && g.WaitReason != 0) { if (!value.isEmpty()) { value += " "; } value += "["+waitReason(int(g.WaitReason)); if (g.WaitSince > 0) { value += QString(" %1").arg(g.WaitSince); } value += "]"; } QStandardItem *item = new QStandardItem(QString("Goroutine %1 %2").arg(g.ID).arg(value)); appendLocationItem(item,"Runtime",g.CurrentLoc); appendLocationItem(item,"Go",g.GoStatementLoc); appendLocationItem(item,"Star",g.StartLoc); appendLocationRoot(m_goroutinesModel,item,g.UserCurrentLoc); } emit endUpdateModel(LiteApi::GOROUTINES_MODEL); } void DlvRpcDebugger::updateAsm(int id, quint64 pc) { int flag = m_liteApp->settings()->value(DLVDEBUGGER_ASMSYNTAX,1).toInt(); QList<AsmInstruction> asms = m_dlvClient->DisassemblePC(EvalScope(id),pc,AssemblyFlavour(flag)); emit beginUpdateModel(LiteApi::ASM_MODEL); m_asmModel->removeRows(0,m_asmModel->rowCount()); QModelIndex at; foreach(AsmInstruction a, asms) { QString head; if (a.AtPC) { head = "=>"; } if (a.Breakpoint) { head += "*"; } QStandardItem *item = new QStandardItem(head); QStandardItem *pc = new QStandardItem(QString("0x%1").arg(a.Loc.PC,0,16)); QStandardItem *file = new QStandardItem(a.Loc.File); QStandardItem *line = new QStandardItem(QString("%1").arg(a.Loc.Line)); QStandardItem *inst = new QStandardItem(QString(a.Bytes.toHex())); QStandardItem *text = new QStandardItem(a.Text); m_asmModel->appendRow(QList<QStandardItem*>() << item << pc << inst << text << file << line); if (a.AtPC) { at = m_asmModel->indexFromItem(item); } } emit endUpdateModel(LiteApi::ASM_MODEL); if (at.isValid()) { emit scrollTo(LiteApi::ASM_MODEL, at); } } void DlvRpcDebugger::updateRegisters(int threadid, bool includeFp) { QList<Register> regs = m_dlvClient->ListRegisters(threadid,includeFp); emit beginUpdateModel(LiteApi::REGS_MODEL); m_registersModel->removeRows(0,m_registersModel->rowCount()); QMap<QString,QString> saveMap; foreach (Register r, regs) { QStandardItem *name = new QStandardItem(r.Name); QStandardItem *valueItem = new QStandardItem(r.Value); QMap<QString,QString>::const_iterator it = m_checkRegsMap.find(r.Name); if (it != m_checkRegsMap.end() && it.value() != r.Value) { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::red),Qt::TextColorRole); #else valueItem->setData(Qt::red,Qt::TextColorRole); #endif } saveMap.insert(r.Name,r.Value); m_registersModel->appendRow(QList<QStandardItem*>() << name << valueItem); } m_checkRegsMap = saveMap; emit endUpdateModel(LiteApi::REGS_MODEL); } static Variable parserRealVar(const Variable &var) { if (var.Type.startsWith("*")) { if (var.Children.size() == 1) { return parserRealVar(var.Children[0]); } } return var; } void DlvRpcDebugger::updateVariableHelper(const QList<Variable> &vars, QStandardItemModel *model, QStandardItem *parent, const QString &parentName, int flag, QMap<QString,QString> &saveMap, const QMap<QString,QString> &checkMap) { int index = -1; foreach (Variable var, vars) { index++; QStandardItem *nameItem = new QStandardItem(var.Name); nameItem->setData(var.Name,VarNameRole); QStandardItem *typeItem = new QStandardItem(var.Type); QStandardItem *valueItem = new QStandardItem(var.Value); valueItem->setToolTip(var.Value); QStandardItem *addrItem = new QStandardItem(QString("0x%1").arg(var.Addr,0,16)); QString checkName = parentName+"."+var.Name; // slice [] if (flag == 2) { checkName = parentName+"."+QString("%1").arg(index); nameItem->setText(QString("[%1]").arg(index)); } QString rtype = var.Type; int rlen = var.Len; int rcap = var.Cap; QList<Variable> children = var.Children; if (var.Type.startsWith("*")) { Variable rv = parserRealVar(var); rtype = rv.Type; rlen = rv.Len; rcap = rv.Cap; children = rv.Children; if (var.Addr != rv.Addr) { addrItem->setText(QString("0x%1 => 0x%2").arg(var.Addr,0,16).arg(rv.Addr,0,16)); } } //children flag int cflag = 1; if (rtype.startsWith("[]")) { cflag = 2; typeItem->setText(QString("%1 <len:%2,cap:%3>").arg(var.Type).arg(rlen).arg(rcap)); //valueItem->setText(QString("(len:%1,cap:%2)").arg(var.Len).arg(var.Cap)); } else if (rtype.startsWith("map[")) { cflag = 3; typeItem->setText(QString("%1 <len:%2>").arg(var.Type).arg(rlen)); } else if (rtype == "string") { cflag = 4; typeItem->setText(QString("%1 <len:%2>").arg(var.Type).arg(rlen)); } else if (!children.isEmpty()) { cflag = 5; if (rlen > 0) { typeItem->setText(QString("%1 <size:%2>").arg(var.Type).arg(rlen)); } } if (!children.isEmpty()) { updateVariableHelper(children,model,nameItem,checkName,cflag,saveMap,checkMap); } QMap<QString,QString>::const_iterator it = checkMap.find(checkName); if (it != checkMap.end() && it.value() != var.Value) { #if QT_VERSION >= 0x050000 valueItem->setData(QColor(Qt::red),Qt::TextColorRole); #else valueItem->setData(Qt::red,Qt::TextColorRole); #endif } saveMap.insert(checkName,var.Value); if (parent) { parent->appendRow(QList<QStandardItem*>() << nameItem << typeItem << valueItem << addrItem); } else { model->appendRow(QList<QStandardItem*>() << nameItem << typeItem << valueItem << addrItem); } } } void DlvRpcDebugger::finished(int code) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv exited with code %1").arg(code)); cleanup(); } void DlvRpcDebugger::error(QProcess::ProcessError err) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv error! %1").arg(ProcessEx::processErrorText(err))); cleanup(); } void DlvRpcDebugger::readTty(const QByteArray &data) { emit debugLog(LiteApi::DebugApplationLog,QString::fromUtf8(data)); } void DlvRpcDebugger::headlessReadStdError() { QString data = QString::fromUtf8(m_headlessProcess->readAllStandardError()); //qDebug() << data; emit debugLog(LiteApi::DebugErrorLog,data); } static void buildMap(QStandardItem *item, const QMap<QString, QVariant> &m) { QMapIterator<QString,QVariant> i(m); while (i.hasNext()) { i.next(); QString key = i.key(); QVariant value = i.value(); if (!key.isEmpty() && value.isValid()) { if (value.type() == QVariant::Map) { QStandardItem *child = new QStandardItem(key); buildMap(child,value.toMap()); item->appendRow(child); } else if (value.type() == QVariant::List) { QStandardItem *child = new QStandardItem(key); item->appendRow(child); int index = 0; foreach (QVariant v, value.toList()) { QStandardItem *aitem = new QStandardItem(QString("[%1]").arg(index++)); child->appendRow(aitem); if (v.type() == QVariant::Map) { buildMap(aitem,v.toMap()); } else { aitem->appendColumn(QList<QStandardItem*>() << new QStandardItem(v.toString())); } } } else { item->appendRow(QList<QStandardItem*>() << new QStandardItem(key) << new QStandardItem(value.toString())); } } } } static void buildMapId(QStandardItem *item, const QVariant &var, const QString &id) { item->setText(id); buildMap(item,var.toMap().value(id).toMap()); } static void buildListId(QStandardItem *item, const QVariant &var, const QString &id) { item->setText(id); //buildMap(item,var.toMap().value(id).toList()); foreach (QVariant li, var.toMap().value(id).toList()) { buildMap(item,li.toMap()); } } void DlvRpcDebugger::headlessReadStdOutput() { QString data = QString::fromUtf8(m_headlessProcess->readAllStandardOutput()); //API server listening at: 127.0.0.1:54151 if (!m_headlessInitAddress) { QString tmp = data.trimmed(); QString addr; if (tmp.startsWith("API")) { int pos = tmp.lastIndexOf(" "); if (pos != -1) { addr = tmp.mid(pos+1); if (addr.indexOf(":") > 0) { m_headlessInitAddress = true; } } } if (m_headlessInitAddress) { m_dlvClient->Connect(addr); // b = m_dlvInfo->Connect(addr); // if (b) { // QMapIterator<QString,int> i(m_initBks); // while (i.hasNext()) { // i.next(); // QString fileName = i.key(); // QList<int> lines = m_initBks.values(fileName); // foreach(int line, lines) { // //insertBreakPointHelper(fileName,line,true); // Breakpoint bp; // bp.File = fileName; // bp.Line = line; // BreakpointPointer p = m_dlvClient->CreateBreakpoint(bp); // qDebug() << p; // } // } // m_dlvClient->CreateBreakpointByFuncName("main.main"); // DebuggerState state = m_dlvClient->Continue(); // updateState(state,m_dlvClient->LastJsonData()); // //command_helper("break main.main",true); // //command_helper("continue",true); // emit debugLoaded(); // return; // } QStringList argsList; argsList << "connect" << addr; #ifdef Q_OS_WIN m_process->setNativeArguments(argsList.join(" ")); m_process->start("\""+m_dlvFilePath+"\""); #else m_process->start(m_dlvFilePath + " " + argsList.join(" ")); #endif QString log = QString("%1 %2 [%3]").arg(m_dlvFilePath).arg(argsList.join(" ")).arg(m_process->workingDirectory()); emit debugLog(LiteApi::DebugRuntimeLog,log); } } emit debugLog(LiteApi::DebugApplationLog,data); } void DlvRpcDebugger::headlessFinished(int code) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv server exited with code %1").arg(code)); cleanup(); } void DlvRpcDebugger::headlessError(QProcess::ProcessError err) { emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Dlv server error! %1").arg(ProcessEx::processErrorText(err))); cleanup(); } void DlvRpcDebugger::clientCommandSuccess(const QString &/*method*/, const DebuggerState &/*state*/, const QVariant &/*jsonData*/) { } void DlvRpcDebugger::updateState(const DebuggerState &state, const QVariant &jsonData) { if (state.Exited) { stop(); } if (state.NextInProgress) { m_asyncItem->setText("Running"); } else { m_asyncItem->setText("Stopped"); } m_asyncItem->removeRows(0,m_asyncItem->rowCount()); if (state.pCurrentThread) { QString fileName = state.pCurrentThread->File; int line = state.pCurrentThread->Line; if (!fileName.isEmpty() && line >= 0) { emit setCurrentLine(fileName,line-1); } QList<QStandardItem*> items; items << new QStandardItem(QString("goroutine(%1)").arg(state.pCurrentThread->GoroutineID)); if (state.pCurrentThread->pFunction) { items << new QStandardItem(QString("func=%1").arg(state.pCurrentThread->pFunction->Name)); } items << new QStandardItem(QString("file=%1").arg(fileName)); items << new QStandardItem(QString("line=%1").arg(line)); m_asyncItem->appendRows(items); } // m_asyncItem->removeRows(0,m_asyncItem->rowCount()); // buildMapId(m_asyncItem,jsonData,"State"); // if (!state.pCurrentThread.isNull()) { // QString fileName = state.pCurrentThread->File; // int line = state.pCurrentThread->Line; // if (!fileName.isEmpty() && line >= 0) { // emit setCurrentLine(fileName,line-1); // } // } emit setExpand(LiteApi::ASYNC_MODEL,m_asyncModel->indexFromItem(m_asyncItem),true); } void DlvRpcDebugger::watchItemChanged(QStandardItem *item) { if (!item || item->column() != 0) { return; } QString oldName = item->data(VarNameRole).toString(); QString newName = item->text(); if (oldName == newName) { return; } emit watchRemoved(oldName); if (!m_watchList.contains(newName)) { int i = m_watchList.indexOf(oldName); if (i >= 0) { m_watchList.replace(i,newName); } emit watchCreated(newName,newName); } else { m_watchList.removeAll(oldName); } DebuggerState state = m_dlvClient->GetState(); if (!state.pCurrentThread) { return; } updateWatch(state.pCurrentThread->GoroutineID); }
52,690
C++
.cpp
1,379
31.014503
228
0.601414
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,343
packagebrowser.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/packagebrowser.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: packagebrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "packagebrowser.h" #include "golangpackageoption.h" #include "golangpackage_global.h" #include "liteenvapi/liteenvapi.h" #include "golangdocapi/golangdocapi.h" #include "qjson/include/QJson/Parser" #include "fileutil/fileutil.h" #include "packageproject.h" #include "liteapi/liteids.h" #include <QTreeView> #include <QStandardItemModel> #include <QStandardItem> #include <QHeaderView> #include <QDir> #include <QVBoxLayout> #include <QHBoxLayout> #include <QMenu> #include <QToolBar> #include <QAction> #include <QUrl> #include <QClipboard> #include <QApplication> #include <QTimer> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end PackageBrowser::PackageBrowser(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_bLoaded(false) { m_goTool = new GoTool(m_liteApp,this); m_widget = new QWidget; m_groupByPath = true; m_hideStandard = false; QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); m_model = new QStandardItemModel(this); m_treeView = new SymbolTreeView; m_treeView->setContextMenuPolicy(Qt::CustomContextMenu); m_treeView->setModel(m_model); m_treeView->setEditTriggers(QTreeView::NoEditTriggers); m_treeView->setExpandsOnDoubleClick(false); layout->addWidget(m_treeView); m_widget->setLayout(layout); m_rootMenu = new QMenu; m_pkgMenu = new QMenu; m_fileMenu = new QMenu; m_reloadAct = new QAction(tr("Reload All"),this); m_setupGopathAct = new QAction(QIcon("icon:images/gopath.png"),tr("Manage GOPATH/Modules ..."),this); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"GoPkg"); actionContext->regAction(m_setupGopathAct,"SetupGOPATH",""); m_godocAct = new QAction(tr("Use godoc View"),this); m_loadPackageInNewWindowAct = new QAction(tr("Load Package in New Window"),this); m_addToFoldersAct = new QAction(tr("Add Package to Folders"),this); m_openSrcAct = new QAction(tr("Open Source File"),this); m_copyNameAct = new QAction(tr("Copy Name to Clipboard"),this); m_liteApp->actionManager()->insertMenuActions(ID_MENU_TOOLS,"sep/gopath",true,QList<QAction*>() << m_setupGopathAct); m_rootMenu->addAction(m_reloadAct); m_rootMenu->addAction(m_setupGopathAct); m_pkgMenu->addAction(m_loadPackageInNewWindowAct); m_pkgMenu->addAction(m_addToFoldersAct); m_pkgMenu->addSeparator(); m_pkgMenu->addAction(m_godocAct); m_pkgMenu->addAction(m_copyNameAct); m_pkgMenu->addSeparator(); m_pkgMenu->addAction(m_reloadAct); m_pkgMenu->addAction(m_setupGopathAct); m_fileMenu->addAction(m_openSrcAct); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_reloadAct); m_fileMenu->addAction(m_setupGopathAct); m_toolWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_widget,"GoPackageBrowser",tr("Go Package Browser"),true); connect(m_toolWindowAct,SIGNAL(triggered(bool)),this,SLOT(toggledToolWindow(bool))); connect(m_goTool,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finished(int,QProcess::ExitStatus))); connect(m_goTool,SIGNAL(error(QProcess::ProcessError)),this,SLOT(error(QProcess::ProcessError))); connect(m_treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(customContextMenuRequested(QPoint))); connect(m_treeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClicked())); connect(m_treeView,SIGNAL(enterKeyPressed(QModelIndex)),this,SLOT(enterKeyPressed(QModelIndex))); connect(m_reloadAct,SIGNAL(triggered()),this,SLOT(reloadAll())); connect(m_setupGopathAct,SIGNAL(triggered()),this,SLOT(setupGopath())); connect(m_godocAct,SIGNAL(triggered()),this,SLOT(loadPackageDoc())); connect(m_loadPackageInNewWindowAct,SIGNAL(triggered()),this,SLOT(loadPackageInNewWindow())); connect(m_addToFoldersAct,SIGNAL(triggered()),this,SLOT(addPackageToFolders())); connect(m_openSrcAct,SIGNAL(triggered()),this,SLOT(doubleClicked())); connect(m_copyNameAct,SIGNAL(triggered()),this,SLOT(copyPackageName())); //QAction *act = new QAction(QIcon("icon:images/gopath.png"),tr("GOPATH Setup"),this); //connect(act,SIGNAL(triggered()),this,SLOT(setupGopath())); QToolBar *toolBar = m_liteApp->actionManager()->loadToolBar(ID_TOOLBAR_STD); if (toolBar) { toolBar->addSeparator(); toolBar->addAction(m_setupGopathAct); } LiteApi::IEnvManager *env = LiteApi::getEnvManager(m_liteApp); if (env) { connect(env,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); } connect(m_liteApp->fileManager(),SIGNAL(fileWizardFinished(QString,QString,QString)),this,SLOT(fileWizardFinished(QString,QString,QString))); } PackageBrowser::~PackageBrowser() { delete m_goTool; delete m_rootMenu; delete m_pkgMenu; delete m_fileMenu; if (m_widget) { delete m_widget; } } void PackageBrowser::toggledToolWindow(bool b) { if (b && !m_bLoaded) { this->reloadAll(); } } void PackageBrowser::fileWizardFinished(const QString&, const QString&, const QString&) { /*if (scheme == "gopkg") { reloadAll(); }*/ } void PackageBrowser::currentEnvChanged(LiteApi::IEnv */*env*/) { reloadAll(); } void PackageBrowser::reloadAll() { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString gocmd = FileUtil::lookupGoBin("go",m_liteApp,env,false); if (!gocmd.isEmpty()) { m_liteApp->appendLog("GolangPackage","Found go bin at "+QDir::toNativeSeparators(gocmd)); } else { m_liteApp->appendLog("GolangPackage","Could not find go bin, (hint: is Go installed?)",true); } QString goroot = env.value("GOROOT"); m_liteApp->appendLog("GolangPackage","GOROOT="+goroot); QStringList gopathList = LiteApi::getGOPATH(m_liteApp,false); #ifdef Q_OS_WIN m_liteApp->appendLog("GolangPackage","GOPATH="+gopathList.join(";")); #else m_liteApp->appendLog("GolangPackage","GOPATH="+gopathList.join(":")); #endif m_bLoaded = false; if (!m_toolWindowAct->isChecked()) { return; } // if (!LiteApi::hasGoEnv(env)) { // return; // } m_liteApp->appendLog("GolangPackages","reload all packages"); m_bLoaded = true; if (m_model->rowCount() == 0) { m_model->appendRow(new QStandardItem(tr("Loading Go package list..."))); } QString root = LiteApi::getGOROOT(m_liteApp); m_goTool->setProcessEnvironment(env); m_goTool->setWorkDir(root); //m_goTool->start(QStringList() << "list" << "-e" << "-json" << "..."); m_goTool->start_list_json(); } //static bool hasSameList(const QStringList &list1, const QStringList &list2) //{ // if (list1.size() != list2.size()) { // return false; // } // for (int i = 0; i < list1.size(); i++) { // if (list1[i] != list2[i]) { // return false; // } // } // return true; //} void PackageBrowser::setupGopath() { m_liteApp->optionManager()->exec("option/golangpackage"); // SetupGopathDialog *dlg = new SetupGopathDialog(m_liteApp->mainWindow()); // dlg->setSysPathList(m_goTool->sysGopath()); // dlg->setLitePathList(m_goTool->liteGopath()); // dlg->setUseSysGopath(m_liteApp->settings()->value(LITEIDE_USESYSGOPATH,true).toBool()); // dlg->setUseLiteGopath(m_liteApp->settings()->value(LITEIDE_USELITEIDEGOPATH,true).toBool()); // dlg->setUseGoModule(m_liteApp->settings()->value(LITEIDE_CUSTOMGO111MODULE,false).toBool()); // dlg->setGo111Module(m_liteApp->settings()->value(LITEIDE_GO111MODULE,"auto").toString()); // dlg->setUseGoProxy(m_liteApp->settings()->value(LITEIDE_USEGOPROXY,false).toBool()); // dlg->setGoProxy(m_liteApp->settings()->value(LITEIDE_GOPROXY,"").toString()); // dlg->setUseGoPrivate(GO_PRIVATE,m_liteApp->settings()->value(LITEIDE_USEGOPRIVATE,false).toBool()); // dlg->setGoPrivate(GO_PRIVATE,m_liteApp->settings()->value(LITEIDE_GOPRIVATE,"").toString()); // dlg->setUseGoPrivate(GO_NOPROXY,m_liteApp->settings()->value(LITEIDE_USEGONOPROXY,false).toBool()); // dlg->setGoPrivate(GO_NOPROXY,m_liteApp->settings()->value(LITEIDE_GONOPROXY,"").toString()); // dlg->setUseGoPrivate(GO_NOSUMDB,m_liteApp->settings()->value(LITEIDE_USEGONOSUMDB,false).toBool()); // dlg->setGoPrivate(GO_NOSUMDB,m_liteApp->settings()->value(LITEIDE_GONOSUMDB,"").toString()); // QProcessEnvironment env = LiteApi::getCurrentEnvironment(m_liteApp); // QString info = env.value("GO111MODULE"); // if (!info.isEmpty()) { // dlg->setSysGoModuleInfo(QString("system GO111MODULE=%1").arg(info)); // } else { // dlg->setSysGoModuleInfo("system GO111MODULE unset"); // } // bool useMod = dlg->isUseGoModule(); // QString goMod = dlg->go111Module(); // if (dlg->exec() == QDialog::Accepted) { // //QStringList orgLitePath = m_goTool->liteGopath(); // QStringList newLitePath = dlg->litePathList(); // //m_liteApp->sendBroadcast("golangpackage","reloadgopath"); // m_liteApp->settings()->setValue(LITEIDE_USESYSGOPATH,dlg->isUseSysGopath()); // m_liteApp->settings()->setValue(LITEIDE_USELITEIDEGOPATH,dlg->isUseLiteGopath()); // m_liteApp->settings()->setValue(LITEIDE_CUSTOMGO111MODULE,dlg->isUseGoModule()); // m_liteApp->settings()->setValue(LITEIDE_GO111MODULE,dlg->go111Module()); // m_liteApp->settings()->setValue(LITEIDE_USEGOPROXY,dlg->isUseGoProxy()); // m_liteApp->settings()->setValue(LITEIDE_GOPROXY,dlg->goProxy()); // m_liteApp->settings()->setValue(LITEIDE_USEGOPRIVATE,dlg->isUseGoPrivate(GO_PRIVATE)); // m_liteApp->settings()->setValue(LITEIDE_GOPRIVATE,dlg->goPrivate(GO_PRIVATE)); // m_liteApp->settings()->setValue(LITEIDE_USEGONOPROXY,dlg->isUseGoPrivate(GO_NOPROXY)); // m_liteApp->settings()->setValue(LITEIDE_GONOPROXY,dlg->goPrivate(GO_NOPROXY)); // m_liteApp->settings()->setValue(LITEIDE_USEGONOSUMDB,dlg->isUseGoPrivate(GO_NOSUMDB)); // m_liteApp->settings()->setValue(LITEIDE_GONOSUMDB,dlg->goPrivate(GO_NOSUMDB)); // //if (!hasSameList(orgLitePath,newLitePath)) { // m_goTool->setLiteGopath(newLitePath); // this->reloadAll(); // if (useMod != dlg->isUseGoModule() || goMod != dlg->go111Module()) { // LiteApi::IEnvManager *env = LiteApi::getEnvManager(m_liteApp); // if (env) { // env->reloadCurrentEnv(); // } // } else { // LiteApi::IGoEnvManger *env = LiteApi::getGoEnvManager(m_liteApp); // if (env) { // env->updateGoEnv(); // } // } // } } void PackageBrowser::loadPackageDoc() { QModelIndex index = m_treeView->currentIndex(); if (!index.isValid()) { return; } int type = index.data(PackageType::RoleItem).toInt(); if (type != PackageType::ITEM_PACKAGE && type != PackageType::ITEM_DEP && type != PackageType::ITEM_IMPORT) { return; } QString pkgName = index.data(PackageType::RoleImportPath).toString(); if (pkgName.isEmpty()) { pkgName = index.data(Qt::DisplayRole).toString(); QString modPkg = m_modPkgMap[pkgName]; if (!modPkg.isEmpty()) { pkgName = modPkg; } qDebug() << pkgName << modPkg; } if (!pkgName.isEmpty()) { LiteApi::IGolangDoc *doc = LiteApi::getGolangDoc(m_liteApp); if (doc) { doc->openUrl(QUrl(QString("pdoc:%1").arg(pkgName))); doc->activeBrowser(); } } } void PackageBrowser::copyPackageName() { QModelIndex index = m_treeView->currentIndex(); if (!index.isValid()) { return; } QString name = index.data(Qt::DisplayRole).toString(); QApplication::clipboard()->setText(name); } void PackageBrowser::loadPackageInNewWindow() { QModelIndex index = m_treeView->currentIndex(); if (!index.isValid()) { return; } loadPackageFolderHelper(index,false); } void PackageBrowser::addPackageToFolders() { QModelIndex index = m_treeView->currentIndex(); if (!index.isValid()) { return; } loadPackageFolderHelper(index,true); } bool PackageBrowser::loadPackageFolderHelper(QModelIndex index, bool add) { if (!index.isValid()) { return false; } int type = index.data(PackageType::RoleItem).toInt(); if (type != PackageType::ITEM_PACKAGE && type != PackageType::ITEM_DEP && type != PackageType::ITEM_IMPORT) { return false; } QString pkgName = index.data(Qt::DisplayRole).toString(); QVariant json = m_pkgJson.value(pkgName); if (json.isNull()) { return false; } QDir dir(json.toMap().value("Dir").toString()); if (dir.exists()) { if (add) { m_liteApp->fileManager()->addFolderList(dir.path()); } else { m_liteApp->fileManager()->openFolderInNewWindow(dir.path()); } return true; } return false; } void PackageBrowser::doubleClicked() { QModelIndex index = m_treeView->currentIndex(); if (!index.isValid()) { return; } int type = index.data(PackageType::RoleItem).toInt(); if (type == PackageType::ITEM_SOURCE) { QString path = index.data(PackageType::RoleDir).toString(); if (!path.isEmpty()) { m_liteApp->fileManager()->openEditor(path); } } else if (type == PackageType::ITEM_PACKAGE) { if (loadPackageFolderHelper(index,true)) { return; } } if (m_treeView->isExpanded(index)) { m_treeView->collapse(index); } else { m_treeView->expand(index); } } void PackageBrowser::enterKeyPressed(const QModelIndex &index) { int type = index.data(PackageType::RoleItem).toInt(); if (type == PackageType::ITEM_SOURCE) { QString path = index.data(PackageType::RoleDir).toString(); if (!path.isEmpty()) { m_liteApp->fileManager()->openEditor(path); } } if (m_treeView->isExpanded(index)) { m_treeView->collapse(index); } else { m_treeView->expand(index); } } void PackageBrowser::customContextMenuRequested(QPoint pos) { QMenu *contextMenu = m_rootMenu; QModelIndex index = m_treeView->currentIndex(); if (index.isValid()) { int type = index.data(PackageType::RoleItem).toInt(); if (type == PackageType::ITEM_PACKAGE || type == PackageType::ITEM_IMPORT || type == PackageType::ITEM_DEP) { contextMenu = m_pkgMenu; } else if (type == PackageType::ITEM_SOURCE) { contextMenu = m_fileMenu; } } if (contextMenu && contextMenu->actions().count() > 0) { contextMenu->popup(m_treeView->mapToGlobal(pos)); } } void PackageBrowser::error(QProcess::ProcessError code) { m_model->clear(); QString goroot = LiteApi::getGOROOT(m_liteApp); m_model->appendRow(new QStandardItem(QString("Load Package Error %1\nGOROOT=%2").arg(code).arg(goroot))); } void PackageBrowser::finished(int code,QProcess::ExitStatus) { if (code == 0) { QByteArray data = m_goTool->stdOutputData(); resetTree(data); } else { m_model->clear(); QString goroot = LiteApi::getGOROOT(m_liteApp); m_model->appendRow(new QStandardItem(QString("Load Package Error %1\nGOROOT=%2").arg(code).arg(goroot))); } } //github.com/gorilla/securecookie@v1.1.1/fuzz static QString cleanModPkgName(const QString &pkg) { int pos = pkg.indexOf("@"); if (pos > 0) { int p2 = pkg.indexOf("/",pos); if (p2 > 0) { return pkg.left(pos)+pkg.mid(p2); } else { return pkg.left(pos); } } return pkg; } void PackageBrowser::resetTree(const QByteArray &data) { //save state SymbolTreeState state; m_treeView->saveState(&state); m_model->clear(); m_modPkgMap.clear(); //load tree QStringList rootList = LiteApi::getGOPATH(m_liteApp,true); foreach (QString root, rootList) { QStandardItem *item = new QStandardItem(root); QStandardItem *cmd = new QStandardItem("cmd"); item->appendRow(cmd); QStandardItem *pkg = new QStandardItem("pkg"); item->appendRow(pkg); m_model->appendRow(item); m_treeView->expand(m_model->indexFromItem(item)); } QByteArray jsonData; foreach(QByteArray line, data.split('\n')) { jsonData.append(line); if (line == "}") { QJson::Parser parser; bool ok = false; QVariant json = parser.parse(jsonData, &ok).toMap(); jsonData.clear(); if (!ok) { continue; } QVariantMap jsonMap = json.toMap(); QString root = QDir::toNativeSeparators(jsonMap.value("Root").toString()); if (root.isEmpty()) { continue; } QStandardItem *parent = 0; for (int i = 0; i < m_model->rowCount(); i++) { QModelIndex index = m_model->index(i,0); if (index.data() == root) { parent = m_model->itemFromIndex(index); break; } } if (parent == 0) { continue; } QString pkgName = jsonMap.value("ImportPath").toString(); if (pkgName.contains("@") && pkgName.startsWith("mod/")) { //skip main if (jsonMap.value("Name").toString() == "main") { continue; } if (parent->rowCount() == 2) { parent->appendRow(new QStandardItem("pkg/mod")); } parent = parent->child(2,0); } else { if (jsonMap.value("Name").toString() == "main") { parent = parent->child(0,0); } else { parent = parent->child(1,0); } } //if (bRoot && pkgName.indexOf("_") == 0) { // parent = 0; //} if (parent) { QString pkgName = jsonMap.value("ImportPath").toString(); QString importPath = pkgName; if (pkgName.contains("@") && pkgName.startsWith("mod/")) { pkgName.remove(0,4); m_modPkgMap.insert(cleanModPkgName(pkgName),importPath); } QStandardItem *item = new QStandardItem(pkgName); item->setToolTip(pkgName); item->setData(PackageType::ITEM_PACKAGE,PackageType::RoleItem); item->setData(importPath,PackageType::RoleImportPath); m_pkgJson.insert(pkgName,json); QStandardItem *base = new QStandardItem("BaseInfo"); item->appendRow(base); QDir dir(jsonMap.value("Dir").toString()); foreach (QString key, jsonMap.keys()) { QVariant var = jsonMap.value(key); if (key == "ImportPath") { var = cleanModPkgName(pkgName); } if (key.indexOf("Error") >= 0) { QString text = QString("%1 : true").arg(key); QStandardItem *ic = new QStandardItem(text); ic->setToolTip(text); base->appendRow(ic); continue; } if (var.type() == QVariant::String || var.type() == QVariant::Bool) { QString text = QString("%1 : %2").arg(key).arg(var.toString()); QStandardItem *ic = new QStandardItem(text); ic->setToolTip(text); base->appendRow(ic); } else if (var.type() == QVariant::List) { PackageType::ITEM_TYPE type = PackageType::ITEM_NONE; if (key.indexOf("Deps") >= 0) { type = PackageType::ITEM_DEP; } else if (key.indexOf("Imports") >= 0) { type = PackageType::ITEM_IMPORT; } else if (key.indexOf("Files") >= 0) { type = PackageType::ITEM_SOURCE; } QStandardItem *ic = new QStandardItem(key); foreach(QVariant v, var.toList()) { if (v.type() == QVariant::String) { QStandardItem *iv = new QStandardItem(v.toString()); iv->setData(type,PackageType::RoleItem); if (type == PackageType::ITEM_SOURCE) { iv->setData(QFileInfo(dir,v.toString()).filePath(),PackageType::RoleDir); } ic->appendRow(iv); } } item->appendRow(ic); } } parent->appendRow(item); } } } //load state m_treeView->loadState(m_model,&state); }
22,836
C++
.cpp
556
33.802158
150
0.613263
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,344
golangpackageoption.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/golangpackageoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangpackageoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangpackageoption.h" #include "ui_golangpackageoption.h" #include "golangpackage_global.h" #include "liteenvapi/liteenvapi.h" #include "gotool.h" #include <QFileDialog> #include <QLineEdit> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangPackageOption::GolangPackageOption(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), ui(new Ui::GolangPackageOption), m_widget(new QWidget) { ui->setupUi(m_widget); ui->cmbGoModule->addItems(QStringList() << "auto" << "on" << "off"); ui->cmbGoModule->setCurrentIndex(0); ui->cmbGoModule->setEnabled(false); ui->cmbGoProxy->setEnabled(false); ui->editGoPrivate->setEnabled(false); ui->editGoNoProxy->setEnabled(false); ui->editGoNoSumdb->setEnabled(false); ui->cmbGoProxy->addItems(QStringList() << "https://proxy.golang.org,direct" << "https://goproxy.io" << "https://goproxy.io,direct" << "https://goproxy.cn" << "https://goproxy.cn,direct"); connect(ui->browserButton,SIGNAL(clicked()),this,SLOT(browser())); connect(ui->clearButton,SIGNAL(clicked()),ui->litePathTextEdit,SLOT(clear())); connect(ui->chkUseSysGopath,SIGNAL(toggled(bool)),ui->sysPathTextEdit,SLOT(setEnabled(bool))); connect(ui->chkUseLiteGopath,SIGNAL(toggled(bool)),ui->litePathTextEdit,SLOT(setEnabled(bool))); connect(ui->chkUseGoModule,SIGNAL(toggled(bool)),ui->cmbGoModule,SLOT(setEnabled(bool))); connect(ui->chkUseGoProxy,SIGNAL(toggled(bool)),ui->cmbGoProxy,SLOT(setEnabled(bool))); connect(ui->chkUseGoPrivate,SIGNAL(toggled(bool)),ui->editGoPrivate,SLOT(setEnabled(bool))); connect(ui->chkUseGoNoProxy,SIGNAL(toggled(bool)),ui->editGoNoProxy,SLOT(setEnabled(bool))); connect(ui->chkUseGoNoSumdb,SIGNAL(toggled(bool)),ui->editGoNoSumdb,SLOT(setEnabled(bool))); } GolangPackageOption::~GolangPackageOption() { delete ui; } void GolangPackageOption::setSysPathList(const QStringList &pathList) { ui->sysPathTextEdit->clear(); foreach (QString path, pathList) { ui->sysPathTextEdit->appendPlainText(path); } } void GolangPackageOption::setLitePathList(const QStringList &pathList) { ui->litePathTextEdit->clear(); foreach (QString path, pathList) { ui->litePathTextEdit->appendPlainText(path); } } void GolangPackageOption::setUseSysGopath(bool b) { ui->chkUseSysGopath->setChecked(b); } bool GolangPackageOption::isUseSysGopath() const { return ui->chkUseSysGopath->isChecked(); } void GolangPackageOption::setUseLiteGopath(bool b) { ui->chkUseLiteGopath->setChecked(b); } bool GolangPackageOption::isUseLiteGopath() const { return ui->chkUseLiteGopath->isChecked(); } void GolangPackageOption::setUseGoModule(bool b) { ui->chkUseGoModule->setChecked(b); } bool GolangPackageOption::isUseGoModule() const { return ui->chkUseGoModule->isChecked(); } void GolangPackageOption::setSysGoModuleInfo(const QString &value) { ui->sysGoModuleInfo->setText(value); } void GolangPackageOption::setGo111Module(const QString &value) { for (int i = 0; i < ui->cmbGoModule->count(); i++) { if (ui->cmbGoModule->itemText(i) == value) { ui->cmbGoModule->setCurrentIndex(i); break; } } } QString GolangPackageOption::go111Module() const { return ui->cmbGoModule->currentText(); } QStringList GolangPackageOption::litePathList() const { return ui->litePathTextEdit->toPlainText().split("\n",qtSkipEmptyParts); } void GolangPackageOption::setUseGoProxy(bool b) { ui->chkUseGoProxy->setChecked(b); } bool GolangPackageOption::isUseGoProxy() const { return ui->chkUseGoProxy->isChecked(); } void GolangPackageOption::setGoProxy(const QString &v) { ui->cmbGoProxy->lineEdit()->setText(v); } QString GolangPackageOption::goProxy() const { return ui->cmbGoProxy->currentText(); } void GolangPackageOption::setUseGoPrivate(ENUM_GO_PRIVATE id, bool b) { switch (id) { case GO_PRIVATE: ui->chkUseGoPrivate->setChecked(b); break; case GO_NOPROXY: ui->chkUseGoNoProxy->setChecked(b); break; case GO_NOSUMDB: ui->chkUseGoNoSumdb->setChecked(b); break; } } bool GolangPackageOption::isUseGoPrivate(ENUM_GO_PRIVATE id) const { switch (id) { case GO_PRIVATE: return ui->chkUseGoPrivate->isChecked(); case GO_NOPROXY: return ui->chkUseGoNoProxy->isChecked(); case GO_NOSUMDB: return ui->chkUseGoNoSumdb->isChecked(); } return false; } void GolangPackageOption::setGoPrivate(ENUM_GO_PRIVATE id, const QString &value) { switch (id) { case GO_PRIVATE: ui->editGoPrivate->setText(value); break; case GO_NOPROXY: ui->editGoNoProxy->setText(value); break; case GO_NOSUMDB: ui->editGoNoSumdb->setText(value); break; } } QString GolangPackageOption::goPrivate(ENUM_GO_PRIVATE id) const { switch (id) { case GO_PRIVATE: return ui->editGoPrivate->text(); case GO_NOPROXY: return ui->editGoNoProxy->text(); case GO_NOSUMDB: return ui->editGoNoSumdb->text(); } return QString(); } QString GolangPackageOption::name() const { return "GolangPackage"; } QString GolangPackageOption::mimeType() const { return "option/golangpackage"; } void GolangPackageOption::save() { QStringList newLitePath = this->litePathList(); //m_liteApp->sendBroadcast("golangpackage","reloadgopath"); m_liteApp->settings()->setValue(LITEIDE_USESYSGOPATH,this->isUseSysGopath()); m_liteApp->settings()->setValue(LITEIDE_USELITEIDEGOPATH,this->isUseLiteGopath()); m_liteApp->settings()->setValue(LITEIDE_CUSTOMGO111MODULE,this->isUseGoModule()); m_liteApp->settings()->setValue(LITEIDE_GO111MODULE,this->go111Module()); m_liteApp->settings()->setValue(LITEIDE_USEGOPROXY,this->isUseGoProxy()); m_liteApp->settings()->setValue(LITEIDE_GOPROXY,this->goProxy()); m_liteApp->settings()->setValue(LITEIDE_USEGOPRIVATE,this->isUseGoPrivate(GO_PRIVATE)); m_liteApp->settings()->setValue(LITEIDE_GOPRIVATE,this->goPrivate(GO_PRIVATE)); m_liteApp->settings()->setValue(LITEIDE_USEGONOPROXY,this->isUseGoPrivate(GO_NOPROXY)); m_liteApp->settings()->setValue(LITEIDE_GONOPROXY,this->goPrivate(GO_NOPROXY)); m_liteApp->settings()->setValue(LITEIDE_USEGONOSUMDB,this->isUseGoPrivate(GO_NOSUMDB)); m_liteApp->settings()->setValue(LITEIDE_GONOSUMDB,this->goPrivate(GO_NOSUMDB)); //if (!hasSameList(orgLitePath,newLitePath)) { setLiteGopath(m_liteApp,newLitePath); // this->reloadAll(); LiteApi::IEnvManager *env = LiteApi::getEnvManager(m_liteApp); if (env) { env->reloadCurrentEnv(); } } void GolangPackageOption::load() { this->setSysPathList(sysGopath(m_liteApp)); this->setLitePathList(liteGopath(m_liteApp)); this->setUseSysGopath(m_liteApp->settings()->value(LITEIDE_USESYSGOPATH,true).toBool()); this->setUseLiteGopath(m_liteApp->settings()->value(LITEIDE_USELITEIDEGOPATH,true).toBool()); this->setUseGoModule(m_liteApp->settings()->value(LITEIDE_CUSTOMGO111MODULE,false).toBool()); this->setGo111Module(m_liteApp->settings()->value(LITEIDE_GO111MODULE,"auto").toString()); this->setUseGoProxy(m_liteApp->settings()->value(LITEIDE_USEGOPROXY,false).toBool()); this->setGoProxy(m_liteApp->settings()->value(LITEIDE_GOPROXY,"").toString()); this->setUseGoPrivate(GO_PRIVATE,m_liteApp->settings()->value(LITEIDE_USEGOPRIVATE,false).toBool()); this->setGoPrivate(GO_PRIVATE,m_liteApp->settings()->value(LITEIDE_GOPRIVATE,"").toString()); this->setUseGoPrivate(GO_NOPROXY,m_liteApp->settings()->value(LITEIDE_USEGONOPROXY,false).toBool()); this->setGoPrivate(GO_NOPROXY,m_liteApp->settings()->value(LITEIDE_GONOPROXY,"").toString()); this->setUseGoPrivate(GO_NOSUMDB,m_liteApp->settings()->value(LITEIDE_USEGONOSUMDB,false).toBool()); this->setGoPrivate(GO_NOSUMDB,m_liteApp->settings()->value(LITEIDE_GONOSUMDB,"").toString()); QProcessEnvironment env = LiteApi::getCurrentEnvironment(m_liteApp); QString info = env.value("GO111MODULE"); if (!info.isEmpty()) { this->setSysGoModuleInfo(QString("system GO111MODULE=%1").arg(info)); } else { this->setSysGoModuleInfo("system GO111MODULE unset"); } } QWidget *GolangPackageOption::widget() { return m_widget; } void GolangPackageOption::browser() { static QString last = QDir::homePath(); QString dir = QFileDialog::getExistingDirectory(m_widget, tr("Choose directory to add to GOPATH:"), last, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!dir.isEmpty()) { last = dir; ui->litePathTextEdit->appendPlainText(dir); } }
10,429
C++
.cpp
271
33.623616
104
0.695265
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,345
golangpackageplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/golangpackageplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangpackageplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangpackageplugin.h" #include "packagebrowser.h" #include "packageproject.h" #include "packageprojectfactory.h" #include "golangpackageoptionfactory.h" #include <QAction> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangPackagePlugin::GolangPackagePlugin() { } bool GolangPackagePlugin::load(LiteApi::IApplication *app) { new PackageBrowser(app,this); //PackageProjectFactory *factory = new PackageProjectFactory(app,this); //m_liteApp->projectManager()->addFactory(factory); app->optionManager()->addFactory(new GolangPackageOptionFactory(app,this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,014
C++
.cpp
51
37.490196
82
0.705161
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,346
packageproject.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/packageproject.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: packageproject.cpp // Creator: visualfc <visualfc@gmail.com> #include "packageproject.h" #include "filepathmodel.h" #include "gotool.h" #include "qjson/include/QJson/Parser" #include "fileutil/fileutil.h" #include "golangdocapi/golangdocapi.h" #include <QDir> #include <QFileInfo> #include <QTreeView> #include <QStandardItemModel> #include <QStandardItem> #include <QVBoxLayout> #include <QTimer> #include <QUrl> #include <QMenu> #include <QAction> #include <QInputDialog> #include <QMessageBox> #include <QFile> #include <QDesktopServices> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end PackageProject::PackageProject(LiteApi::IApplication *app) : m_liteApp(app) { m_goTool = new GoTool(m_liteApp,this); m_widget = new QWidget; m_reloadTimer = new QTimer(this); m_reloadTimer->setSingleShot(true); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); m_treeView = new PackageTree(m_widget); m_treeView->setEditTriggers(QTreeView::NoEditTriggers); m_treeView->setHeaderHidden(true); m_treeView->setContextMenuPolicy(Qt::CustomContextMenu); layout->addWidget(m_treeView); m_widget->setLayout(layout); m_contextMenu = new QMenu; QAction *reloadAct = new QAction(tr("Reload Package"),this); QAction *explorerAct = new QAction(tr("Open Explorer Here"),this); QAction *addSource = new QAction(tr("Add Source File"),this); m_contextMenu->addAction(reloadAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(explorerAct); m_contextMenu->addAction(addSource); connect(m_treeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClicked(QModelIndex))); connect(m_goTool,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finished(int,QProcess::ExitStatus))); //connect(m_liteApp->editorManager(),SIGNAL(editorSaved(LiteApi::IEditor*)),this,SLOT(editorSaved(LiteApi::IEditor*))); connect(m_reloadTimer,SIGNAL(timeout()),this,SLOT(reload())); connect(addSource,SIGNAL(triggered()),this,SLOT(addSource())); connect(reloadAct,SIGNAL(triggered()),this,SLOT(reload())); connect(explorerAct,SIGNAL(triggered()),this,SLOT(openExplorer())); connect(m_treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(customContextMenuRequested(QPoint))); } PackageProject::~PackageProject() { if (m_reloadTimer) { m_reloadTimer->stop(); delete m_reloadTimer; } if (m_goTool) { delete m_goTool; } if (m_contextMenu) { delete m_contextMenu; } if (m_widget) { delete m_widget; } } void PackageProject::customContextMenuRequested(QPoint pos) { QMenu *contextMenu = m_contextMenu; /* if (node->isDir()) { contextMenu = m_folderMenu; } else { contextMenu = m_fileMenu; } */ if (contextMenu && contextMenu->actions().count() > 0) { contextMenu->popup(m_treeView->mapToGlobal(pos)); } } void PackageProject::loadProject(LiteApi::IApplication *app, const QString &path) { PackageProject *project = new PackageProject(app); project->setPath(path); project->reload(); app->projectManager()->setCurrentProject(project); QAction *act = app->toolWindowManager()->findToolWindow(app->projectManager()->widget()); if (act) { act->setChecked(true); } } void PackageProject::setPath(const QString &path) { m_filePath = path; m_goTool->setWorkDir(path); } void PackageProject::reload() { if (m_reloadTimer->isActive()) { m_reloadTimer->stop(); } m_goTool->start_list_json(); } void PackageProject::setJson(const QMap<QString,QVariant> &json) { m_json = json; } QWidget *PackageProject::widget() { return m_widget; } QString PackageProject::name() const { return m_json.value("ImportPath").toString(); } QString PackageProject::filePath() const { return m_filePath; } QString PackageProject::mimeType() const { return "text/x-gopackage"; } QStringList PackageProject::folderList() const { return QStringList() << m_filePath; } QStringList PackageProject::fileNameList() const { return m_treeView->nameList; } QStringList PackageProject::filePathList() const { return m_treeView->fileList; } QString PackageProject::fileNameToFullPath(const QString &filePath) { QDir dir(m_filePath); return QFileInfo(dir,filePath).filePath(); } /* valueForKey EDITORPATH EDITORNAME EDITORDIR PROJECTPATH PROJECTNAME PROJECTDIR WORKDIR TARGETPATH TARGETNAME TARGETDIR */ QMap<QString,QString> PackageProject::targetInfo() const { QMap<QString,QString> m; QDir dir(m_filePath); m.insert("WORKDIR",dir.path()); QString name = m_json.value("ImportPath").toString(); name = QFileInfo(name).fileName(); m.insert("TARGETPATH",QFileInfo(dir,name).filePath()); m.insert("TARGETNAME",name); m.insert("TARGETDIR",dir.path()); return m; } void PackageProject::load() { m_treeView->loadJson(m_json); } void PackageProject::doubleClicked(QModelIndex index) { if (!index.isValid()) { return; } QStandardItem *item = m_treeView->model->itemFromIndex(index); if (!item) { return; } switch (item->data(PackageType::RoleItem).toInt()) { case PackageType::ITEM_SOURCE: { QString path = item->data(RolePath).toString(); m_liteApp->fileManager()->openEditor(path,true); } break; case PackageType::ITEM_DEP: case PackageType::ITEM_IMPORT: { QString pkg = item->data(Qt::DisplayRole).toString(); LiteApi::IGolangDoc *doc = LiteApi::getGolangDoc(m_liteApp); if (doc) { doc->openUrl(QUrl(QString("pdoc:%1").arg(pkg))); doc->activeBrowser(); } } break; } } void PackageProject::finished(int code, QProcess::ExitStatus) { if (code != 0) { return; } QJson::Parser parser; bool ok = false; QVariant json = parser.parse(m_goTool->stdOutputData(), &ok).toMap(); if (ok) { m_json = json.toMap(); load(); emit reloaded(); } } void PackageProject::editorSaved(LiteApi::IEditor *editor) { if (!editor) { return; } QString filePath = editor->filePath(); bool find = false; foreach(QString path, m_treeView->fileList) { if (FileUtil::compareFile(filePath,path)) { find = true; break; } } if (find) { //m_reloadTimer->start(10000); } } void PackageProject::openExplorer() { QDesktopServices::openUrl(QUrl::fromLocalFile(this->filePath())); } void PackageProject::addSource() { QString source = QInputDialog::getText(m_widget,tr("Add Source File"),tr("File Name:")); if (source.isEmpty()) { return; } QDir dir(m_filePath); QFileInfo info(dir,source); QString fileName = info.filePath(); if (info.suffix().isEmpty()) { fileName += ".go"; } if (QFile::exists(fileName)) { QMessageBox::information(m_widget,tr("Error"),QString(tr("File %1 already exists.")).arg(fileName)); return; } QFile file(fileName); if (!file.open(QFile::WriteOnly)) { QMessageBox::information(m_widget,tr("Error"),QString(tr("Could not open %1 for writing.")).arg(fileName)); return; } file.write(QString("package %1\n").arg(m_json.value("Name").toString()).toLatin1()); file.close(); this->reload(); }
8,726
C++
.cpp
290
26.068966
123
0.67912
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,347
packageprojectfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/packageprojectfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: packageprojectfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "packageprojectfactory.h" #include "packageproject.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end PackageProjectFactory::PackageProjectFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IProjectFactory(parent), m_liteApp(app) { m_mimeTypes.append("text/x-gopackage"); m_mimeTypes.append("text/x-gocommand"); } QStringList PackageProjectFactory::mimeTypes() const { return m_mimeTypes; } LiteApi::IProject *PackageProjectFactory::open(const QString &fileName, const QString &mimeType) { if (!m_mimeTypes.contains(mimeType)) { return 0; } PackageProject *project = new PackageProject(m_liteApp); project->setPath(fileName); project->reload(); return project; } bool PackageProjectFactory::findTargetInfo(const QString&, const QString&, QMap<QString,QString>&) const { return false; }
2,197
C++
.cpp
58
35.37931
104
0.695734
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,348
golangpackageoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/golangpackageoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangpackageoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangpackageoptionfactory.h" #include "golangpackageoption.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangPackageOptionFactory::GolangPackageOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GolangPackageOptionFactory::mimeTypes() const { return QStringList() << "option/golangpackage"; } LiteApi::IOption *GolangPackageOptionFactory::create(const QString &mimeType) { if (mimeType == "option/golangpackage") { return new GolangPackageOption(m_liteApp,this); } return 0; }
1,940
C++
.cpp
49
37.285714
99
0.694062
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,349
packagetree.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/packagetree.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: packagetree.cpp // Creator: visualfc <visualfc@gmail.com> #include "packagetree.h" #include <QStandardItem> #include <QStandardItemModel> #include <QDir> #include <QFileInfo> #include "packagebrowser.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end PackageTree::PackageTree(QWidget *parent) : SymbolTreeView(parent), root(0) { model = new QStandardItemModel(this); this->setModel(model); } void PackageTree::loadJson(const QMap<QString, QVariant> &jsonMap) { SymbolTreeState state; this->saveState(&state); model->clear(); QStandardItem *item = new QStandardItem(jsonMap.value("ImportPath").toString()); QStandardItem *base = new QStandardItem("BaseInfo"); item->appendRow(base); QDir dir(jsonMap.value("Dir").toString()); foreach (QString key, jsonMap.keys()) { QVariant var = jsonMap.value(key); if (key.indexOf("Error") >= 0) { QString text = QString("%1 : true").arg(key); QStandardItem *ic = new QStandardItem(text); ic->setToolTip(text); base->appendRow(ic); continue; } if (var.type() == QVariant::String || var.type() == QVariant::Bool) { QString text = QString("%1 : %2").arg(key).arg(var.toString()); QStandardItem *ic = new QStandardItem(text); ic->setToolTip(text); base->appendRow(ic); } else if (var.type() == QVariant::List) { PackageType::ITEM_TYPE type = PackageType::ITEM_NONE; if (key.indexOf("Deps") >= 0) { type = PackageType::ITEM_DEP; } else if (key.indexOf("Imports") >= 0) { type = PackageType::ITEM_IMPORT; } else if (key.indexOf("Files") >= 0) { type = PackageType::ITEM_SOURCE; } QStandardItem *ic = new QStandardItem(key); foreach(QVariant v, var.toList()) { if (v.type() == QVariant::String) { QStandardItem *iv = new QStandardItem(v.toString()); iv->setData(type,PackageType::RoleItem); if (type == PackageType::ITEM_SOURCE) { iv->setData(QFileInfo(dir,v.toString()).filePath(),PackageType::RoleDir); } ic->appendRow(iv); } } item->appendRow(ic); } } model->appendRow(item); this->loadState(this->model,&state); fileList.clear(); nameList.clear(); QStringList nameFilter; nameFilter << "*.go" << "*.h" << "*.c" << "*.cpp" << "*.s"; foreach(QFileInfo info, dir.entryInfoList(nameFilter,QDir::Files,QDir::Type|QDir::Name)) { fileList.append(info.filePath()); nameList.append(info.fileName()); } }
4,077
C++
.cpp
102
32.941176
97
0.598487
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,350
filepathmodel.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/filepathmodel.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: filepathmodel.cpp // Creator: visualfc <visualfc@gmail.com> #include "filepathmodel.h" #include "liteapi/liteqt.h" #include <QFileInfo> #include <QDir> #include <QIcon> #include <QFont> #include <QFileIconProvider> #include <QFileSystemWatcher> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end PathNode::PathNode(FilePathModel *model) : m_model(model), m_parent(0), m_children(0) { } PathNode::PathNode(FilePathModel *model, const QString &path, PathNode *parent) : m_model(model), m_parent(parent), m_children(0), m_path(path) { QFileInfo info(path); if (parent && parent->parent() == 0) { m_text = info.filePath(); } else { m_text = info.fileName(); } if (info.isDir() && !m_path.isEmpty()) { m_model->fileWatcher()->addPath(m_path); } } PathNode::~PathNode() { if (this->isDir() && !m_path.isEmpty()) { m_model->fileWatcher()->removePath(m_path); } if (m_children) { qDeleteAll(m_children->begin(),m_children->end()); delete m_children; } } QList<PathNode*>* PathNode::children() { if (m_children == 0) { m_children = new QList<PathNode*>(); if (!m_path.isEmpty()) { QFileInfo info(m_path); if (info.isDir()) { QDir dir(m_path); foreach(QFileInfo childInfo, dir.entryInfoList(this->m_model->filter(),this->m_model->sort())) { m_children->append(new PathNode(this->m_model,childInfo.filePath(),this)); } } } } return m_children; } PathNode* PathNode::parent() { return m_parent; } PathNode* PathNode::child(int row) { return children()->at(row); } int PathNode::childCount() { return children()->count(); } int PathNode::row() const { if (m_parent) { return m_parent->children()->indexOf(const_cast<PathNode*>(this)); } return 0; } QString PathNode::path() const { return m_path; } QString PathNode::text() const { return m_text; } bool PathNode::isDir() const { return QFileInfo(m_path).isDir(); } bool PathNode::isFile() const { return QFileInfo(m_path).isFile(); } QFileInfo PathNode::fileInfo() const { return QFileInfo(m_path); } void PathNode::clear() { if (m_children) { qDeleteAll(m_children->begin(),m_children->end()); m_children->clear(); } } void PathNode::reload() { clear(); if (m_children == 0) { m_children = new QList<PathNode*>(); } if (!m_path.isEmpty()) { QFileInfo info(m_path); if (info.isDir()) { QDir dir(m_path); foreach(QFileInfo childInfo, dir.entryInfoList(this->m_model->filter(),this->m_model->sort())) { m_children->append(new PathNode(this->m_model,childInfo.filePath(),this)); } } } } PathNode *PathNode::findPath(const QString &path) { if (!path.startsWith(m_path)) { return 0; } if (path == m_path) { return this; } QStringList nameList = path.right(path.length()-m_path.length()).split("/",qtSkipEmptyParts); PathNode *parent = this; bool find = false; foreach (QString name,nameList) { find = false; QList<PathNode*>* chilren = parent->children(); for (int i = 0; i < chilren->count(); i++) { PathNode *node = chilren->at(i); if (!node->isDir()) { continue; } if (node->m_text == name) { parent = node; find = true; break; } } if (!find) { return 0; } } return parent; } FilePathModel::FilePathModel(QObject *parent) : QAbstractItemModel(parent), m_rootNode(new PathNode(this)), m_iconProvider(new QFileIconProvider), m_fileWatcher(new QFileSystemWatcher(this)) { m_filters = QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot; m_sorts = QDir::DirsFirst | QDir::Name | QDir::Type; connect(m_fileWatcher,SIGNAL(directoryChanged(QString)),this,SLOT(directoryChanged(QString))); } FilePathModel::~FilePathModel() { delete m_rootNode; delete m_iconProvider; } void FilePathModel::directoryChanged(const QString &path) { foreach(QModelIndex index,this->findPaths(path)) { PathNode *node = nodeFromIndex(index); this->beginRemoveRows(index,0,this->rowCount(index)-1); node->reload(); this->endRemoveRows(); } } PathNode *FilePathModel::nodeFromIndex(const QModelIndex &index) const { if (index.isValid()) { return static_cast<PathNode*>(index.internalPointer()); } return m_rootNode; } void FilePathModel::setStartIndex(const QModelIndex &index) { m_startPath = filePath(index); } void FilePathModel::setStartPath(const QString &path) { m_startPath = path; } QModelIndex FilePathModel::startIndex() const { return findPath(m_startPath); } QString FilePathModel::startPath() const { return m_startPath; } QString FilePathModel::filePath(const QModelIndex &index) const { return nodeFromIndex(index)->path(); } void FilePathModel::setFilter(QDir::Filters filters) { if (m_filters != filters) { m_filters = filters; m_rootNode->reload(); } } void FilePathModel::setSort(QDir::SortFlags flags) { if (m_sorts != flags) { m_sorts = flags; m_rootNode->reload(); } } QDir::Filters FilePathModel::filter() const { return m_filters; } QDir::SortFlags FilePathModel::sort() const { return m_sorts; } void FilePathModel::setRootPath(const QString &path) { this->setRootPathList(QStringList() << path); this->setStartPath(path); } void FilePathModel::setRootPathList(const QStringList &pathList) { this->beginResetModel(); m_rootNode->clear(); m_pathList.clear(); foreach(QString path, pathList) { QString spath = QDir::fromNativeSeparators(QDir::cleanPath(path)); m_pathList.append(spath); m_rootNode->children()->append(new PathNode(this,spath,m_rootNode)); } if (m_startPath.isEmpty() && !pathList.isEmpty()) { m_startPath = pathList.first(); } this->endResetModel(); } QModelIndex FilePathModel::findPathHelper(const QString &path, const QModelIndex &parentIndex) const { PathNode *node = nodeFromIndex(parentIndex); if (!path.startsWith(node->path())) { return QModelIndex(); } if (path == node->path()) { return parentIndex; } QStringList nameList = path.right(path.length()-node->path().length()).split("/",qtSkipEmptyParts); QModelIndex parent = parentIndex; bool find = false; int count = nameList.count(); for (int i = 0; i < count; i++) { find = false; for (int j = 0; j < this->rowCount(parent); j++) { QModelIndex index = this->index(j,0,parent); PathNode *node = nodeFromIndex(index); if ( ( (i == count-1) || node->isDir()) && node->text() == nameList.at(i)) { parent = index; find = true; break; } } if (!find) { return QModelIndex(); } } return parent; } QList<QModelIndex> FilePathModel::findPaths(const QString &path) const { QList<QModelIndex> list; QString cpath = QDir::fromNativeSeparators(QDir::cleanPath(path)); for (int i = 0; i < this->rowCount(); i++) { QModelIndex find = findPathHelper(cpath,this->index(i,0)); if (find.isValid()) { list.append(find); } } return list; } QModelIndex FilePathModel::findPath(const QString &path) const { QList<QModelIndex> list = this->findPaths(path); if (!list.isEmpty()) { return list.last(); } return QModelIndex(); } int FilePathModel::rowCount(const QModelIndex &parent) const { PathNode *node = nodeFromIndex(parent); return node->childCount(); } int FilePathModel::columnCount(const QModelIndex&) const { return 1; } QModelIndex FilePathModel::parent(const QModelIndex &child) const { PathNode *node = nodeFromIndex(child); PathNode *parent = node->parent(); if (parent == m_rootNode) { return QModelIndex(); } return createIndex(parent->row(),0,parent); } QModelIndex FilePathModel::index(int row, int column,const QModelIndex &parent) const { if (!hasIndex(row,column,parent)) return QModelIndex(); PathNode *node = nodeFromIndex(parent); return createIndex(row,column,node->child(row)); } QVariant FilePathModel::data(const QModelIndex &index, int role) const { PathNode *node = nodeFromIndex(index); if (!node) { return QVariant(); } switch(role) { case Qt::DisplayRole: return node->text(); case Qt::DecorationRole: return m_iconProvider->icon(node->fileInfo()); case Qt::FontRole: { QFont font; if (node->path() == m_startPath) { font.setBold(true); } return font; } } return QVariant(); } QFileSystemWatcher* FilePathModel::fileWatcher() const { return m_fileWatcher; }
10,471
C++
.cpp
374
23.106952
112
0.632014
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,351
gotool.cpp
visualfc_liteide/liteidex/src/plugins/golangpackage/gotool.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gotool.cpp // Creator: visualfc <visualfc@gmail.com> #include "gotool.h" #include "liteenvapi/liteenvapi.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include <QProcess> #include <QDir> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GoTool::GoTool(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app) { m_process = new Process(this); connect(m_process,SIGNAL(readyReadStandardError()),this,SLOT(readError())); connect(m_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readOutput())); connect(m_process,SIGNAL(error(QProcess::ProcessError)),this,SIGNAL(error(QProcess::ProcessError))); connect(m_process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SIGNAL(finished(int,QProcess::ExitStatus))); } GoTool::~GoTool() { kill(); } void GoTool::kill() { m_process->stopAndWait(100,200); } void GoTool::setProcessEnvironment(const QProcessEnvironment &environment) { m_process->setProcessEnvironment(environment); } void GoTool::setWorkDir(const QString &dir) { m_process->setWorkingDirectory(dir); } QString GoTool::workDir() const { return m_process->workingDirectory(); } void GoTool::start_list_json() { this->kill(); m_stdOutput.clear(); m_stdError.clear(); QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "pkgs" << "-list" << "-json"; QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); m_process->setEnvironment(env.toStringList()); m_process->start(cmd,args); } void GoTool::readError() { m_stdError.append(m_process->readAllStandardError()); } void GoTool::readOutput() { m_stdOutput.append(m_process->readAllStandardOutput()); }
3,011
C++
.cpp
88
31.681818
114
0.699209
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,352
liteshellplugin.cpp
visualfc_liteide/liteidex/src/plugins/liteshell/liteshellplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: liteshellplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteshellplugin.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteShellPlugin::LiteShellPlugin() { m_info->setId("plugin/LiteShell"); m_info->setName("LiteShell"); m_info->setAuthor("visualfc"); m_info->setInfo("LiteShell Plugin"); } bool LiteShellPlugin::initWithApp(LiteApi::IApplication *app) { if (!LiteApi::IPlugin::initWithApp(app)) { return false; } return true; } Q_EXPORT_PLUGIN(LiteShellPlugin)
1,781
C++
.cpp
47
35.510638
82
0.671676
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,353
golangplayplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangplay/golangplayplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangplayplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangplayplugin.h" #include "goplaybrowser.h" #include "liteapi/liteobj.h" #include <QAction> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangPlayPlugin::GolangPlayPlugin() { } bool GolangPlayPlugin::load(LiteApi::IApplication *app) { GoplayBrowser *gopaly = new GoplayBrowser(app,this); QAction *act = app->editorManager()->registerBrowser(gopaly); act->setIcon(QIcon("icon:images/gopher.png")); app->actionManager()->insertViewMenu(LiteApi::ViewMenuBrowserPos,act); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,925
C++
.cpp
49
37.285714
82
0.693376
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,354
goplaybrowser.cpp
visualfc_liteide/liteidex/src/plugins/golangplay/goplaybrowser.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: goplaybrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "goplaybrowser.h" #include "liteenvapi/liteenvapi.h" #include "fileutil/fileutil.h" #include "textoutput/textoutput.h" #include "processex/processex.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QSplitter> #include <QToolBar> #include <QLabel> #include <QPushButton> #include <QPlainTextEdit> #include <QProcess> #include <QTextCodec> #include <QDesktopServices> #include <QFileInfo> #include <QDir> #include <QFile> #include <QInputDialog> #include <QMessageBox> #include <QUrl> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QString data = "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tfmt.Println(\"Hello World\")\n}"; GoplayBrowser::GoplayBrowser(LiteApi::IApplication *app, QObject *parent) : LiteApi::IBrowserEditor(parent), m_liteApp(app) { m_widget = new QWidget; m_output = new TextOutput(m_liteApp); m_editor = m_liteApp->fileManager()->createEditor(data,"text/x-gosrc"); QToolBar *toolBar = new QToolBar; QVBoxLayout *layout = new QVBoxLayout; QSplitter *spliter = new QSplitter(Qt::Vertical); QLabel *label = new QLabel(QString("%1").arg(tr("Go Playground"))); QAction *run = new QAction(tr("Run"),this); QAction *stop = new QAction(tr("Stop"),this); QAction *_new = new QAction(tr("New"),this); QAction *load = new QAction(tr("Load..."),this); QAction *save = new QAction(tr("Save..."),this); QAction *shell = new QAction(tr("Explore Folder"),this); m_editLabel = new QLabel; toolBar->addWidget(label); toolBar->addSeparator(); toolBar->addAction(run); toolBar->addAction(stop); toolBar->addAction(_new); toolBar->addAction(load); toolBar->addAction(save); toolBar->addSeparator(); toolBar->addAction(shell); toolBar->addSeparator(); toolBar->addWidget(m_editLabel); layout->addWidget(toolBar); spliter->addWidget(m_editor->widget()); spliter->addWidget(m_output); spliter->setStretchFactor(0,2); spliter->setStretchFactor(1,1); layout->addWidget(spliter); m_widget->setLayout(layout); m_process = new ProcessEx(this); m_codec = QTextCodec::codecForName("utf-8"); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); actionContext->regAction(run,"GoplayRun","Ctrl+R"); connect(run,SIGNAL(triggered()),this,SLOT(run())); connect(stop,SIGNAL(triggered()),this,SLOT(stop())); connect(_new,SIGNAL(triggered()),this,SLOT(newPlay())); connect(load,SIGNAL(triggered()),this,SLOT(loadPlay())); connect(save,SIGNAL(triggered()),this,SLOT(savePlay())); connect(shell,SIGNAL(triggered()),this,SLOT(shell())); connect(m_process,SIGNAL(started()),this,SLOT(runStarted())); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(runOutput(QByteArray,bool))); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(runFinish(bool,int,QString))); m_liteApp->extension()->addObject("LiteApi.Goplay",this); m_liteApp->extension()->addObject("LiteApi.Goplay.IEditor",m_editor); } GoplayBrowser::~GoplayBrowser() { delete m_editor; delete m_widget; } QWidget *GoplayBrowser::widget() { return m_widget; } QString GoplayBrowser::name() const { return tr("Go Playground"); } QString GoplayBrowser::mimeType() const { return "browser/goplay"; } void GoplayBrowser::onActive() { static bool init = false; if (!init) { init = true; QDir dir(m_liteApp->storagePath()); dir.mkpath("goplay"); m_dataPath = dir.path()+"/goplay"; m_playFile = QFileInfo(dir,"goplay.go").filePath(); QFile file(m_playFile); if (file.open(QFile::WriteOnly|QIODevice::Text)) { file.write(data.toUtf8()); file.close(); } m_process->setWorkingDirectory(dir.path()); m_editor->open(m_playFile,"text/x-gosrc"); } } void GoplayBrowser::run() { m_editor->saveAs(m_playFile); if (!m_editFile.isEmpty()) { m_editor->saveAs(m_editFile); } QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString go = FileUtil::lookPath("go",env,false); QStringList args; args << "run"; args << "goplay.go"; m_process->stopAndWait(100,2000); m_output->clear(); m_output->appendTag(tr("Running...")+"\n\n"); m_process->setEnvironment(env.toStringList()); m_process->start(go,args); } void GoplayBrowser::stop() { m_process->stop(100); } void GoplayBrowser::runOutput(const QByteArray &data,bool) { m_output->append(m_codec->toUnicode(data)); } void GoplayBrowser::runFinish(bool err,int code,const QString &msg) { m_output->setReadOnly(true); if (err || code != 0) { m_output->appendTag("\n"+tr("Error: %1.").arg(msg),true); } else { m_output->appendTag("\n"+tr("Success: %2.").arg(msg)); } } void GoplayBrowser::runStarted() { m_output->setReadOnly(false); } void GoplayBrowser::newPlay() { /* if (m_editor->isModified()) { int r = QMessageBox::question(m_widget,tr("Goplay"),tr("File is Modified, save or cancel?"),QMessageBox::Save,QMessageBox::No,QMessageBox::Cancel); if (r == QMessageBox::Cancel) { return; } if (r == QMessageBox::Save) { savePlay(); } } */ m_editFile.clear(); QPlainTextEdit *edit = LiteApi::findExtensionObject<QPlainTextEdit*>(m_editor,"LiteApi.QPlainTextEdit"); if (edit) { edit->setPlainText(data); } m_editLabel->setText(""); } void GoplayBrowser::loadPlay() { /* if (m_editor->isModified()) { int r = QMessageBox::question(m_widget,tr("Goplay"),tr("File is Modified, save or cancel?"),QMessageBox::Save,QMessageBox::No,QMessageBox::Cancel); if (r == QMessageBox::Cancel) { return; } if (r == QMessageBox::Save) { savePlay(); } } */ QDir dir(m_dataPath); QStringList items = dir.entryList(QStringList() << "*.go",QDir::Files); if (items.isEmpty()) { return; } bool ok = false; QString name = QInputDialog::getItem(m_widget,tr("Load File"),tr("Select a file to load:"),items,0,false,&ok); if (!ok) { return; } if (name.isEmpty()) { return; } m_editLabel->setText(name); m_editFile = QFileInfo(QDir(m_dataPath),name).filePath(); m_editor->open(m_editFile,"text/x-gosrc"); } void GoplayBrowser::savePlay() { if (m_editFile.isEmpty()) { bool ok = false; QString name = QInputDialog::getText(m_widget,tr("Save File"),tr("New File Name:"),QLineEdit::Normal,"",&ok); if (!ok) { return; } if (name.isEmpty()) { return; } if (name.right(3) != ".go") { name += ".go"; } m_editLabel->setText(name); m_editFile = QFileInfo(QDir(m_dataPath),name).filePath(); } m_editor->saveAs(m_editFile); } void GoplayBrowser::shell() { QDesktopServices::openUrl(QUrl::fromLocalFile(m_dataPath)); }
8,730
C++
.cpp
251
29.087649
156
0.632862
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,355
sockettty.cpp
visualfc_liteide/liteidex/src/plugins/litetty/sockettty.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: sockettty.cpp // Creator: visualfc <visualfc@gmail.com> #include "sockettty.h" #include <QLocalServer> #include <QLocalSocket> #include <QCoreApplication> #include <stdlib.h> #include <time.h> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SocketTty::SocketTty(QObject *parent) : LiteApi::ITty(parent), m_server(0),m_socket(0) { } SocketTty::~SocketTty() { shutdown(); } QString SocketTty::serverName() const { return m_server->fullServerName(); } QString SocketTty::errorString() const { return m_server->errorString(); } bool SocketTty::listen() { if (m_server) { return m_server->isListening(); } m_server = new QLocalServer(this); srand(time(0)); connect(m_server, SIGNAL(newConnection()), SLOT(newConnectionAvailable())); return m_server->listen(QString::fromLatin1("liteide-%1-%2") .arg(QCoreApplication::applicationPid()) .arg(rand())); } void SocketTty::shutdown() { if (m_server) { delete m_server; m_server = 0; m_socket = 0; } } void SocketTty::write(const QByteArray &data) { m_socket->write(data); } void SocketTty::newConnectionAvailable() { if (m_socket) return; m_socket = m_server->nextPendingConnection(); connect(m_socket, SIGNAL(readyRead()), SLOT(bytesAvailable())); } void SocketTty::bytesAvailable() { emit byteDelivery(m_socket->readAll()); }
2,701
C++
.cpp
88
27.431818
82
0.660008
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,356
fifotty.cpp
visualfc_liteide/liteidex/src/plugins/litetty/fifotty.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: fifotty.cpp // Creator: visualfc <visualfc@gmail.com> #include "fifotty.h" #include <QFile> #include <QSocketNotifier> #include <QTemporaryFile> #include <QVarLengthArray> #include <QDebug> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #ifdef Q_OS_SOLARIS # include <sys/filio.h> // FIONREAD #endif #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FiFoTty::FiFoTty(QObject *parent) : LiteApi::ITty(parent) { } FiFoTty::~FiFoTty() { shutdown(); } QString FiFoTty::serverName() const { return m_serverPath; } QString FiFoTty::errorString() const { return m_errorString; } bool FiFoTty::listen() { if (!m_serverPath.isEmpty()) return true; if (!m_serverPath.isEmpty()) return true; QByteArray codedServerPath; forever { { QTemporaryFile tf; if (!tf.open()) { m_errorString = tr("Cannot create temporary file: %1").arg(tf.errorString()); m_serverPath.clear(); return false; } m_serverPath = tf.fileName(); } // By now the temp file was deleted again codedServerPath = QFile::encodeName(m_serverPath); if (!::mkfifo(codedServerPath.constData(), 0600)) break; if (errno != EEXIST) { m_errorString = tr("Cannot create FiFo %1: %2"). arg(m_serverPath, QString::fromLocal8Bit(strerror(errno))); m_serverPath.clear(); return false; } } if ((m_serverFd = ::open(codedServerPath.constData(), O_RDWR|O_NONBLOCK)) < 0) { m_errorString = tr("Cannot open FiFo %1: %2"). arg(m_serverPath, QString::fromLocal8Bit(strerror(errno))); m_serverPath.clear(); return false; } m_serverNotifier = new QSocketNotifier(m_serverFd, QSocketNotifier::Read, this); connect(m_serverNotifier, SIGNAL(activated(int)), SLOT(bytesAvailable())); return true; } void FiFoTty::shutdown() { if (!m_serverPath.isEmpty()) { ::close(m_serverFd); ::unlink(QFile::encodeName(m_serverPath).constData()); delete m_serverNotifier; m_serverPath.clear(); } } void FiFoTty::write(const QByteArray &data) { ::write(m_serverFd,data.data(),data.length()); } void FiFoTty::bytesAvailable() { size_t nbytes = 0; if (::ioctl(m_serverFd, FIONREAD, (char *) &nbytes) < 0) return; QByteArray buff(nbytes,0); if (::read(m_serverFd, buff.data(), nbytes) != (int)nbytes) return; if (nbytes) // Skip EOF notifications emit byteDelivery(buff); }
3,992
C++
.cpp
125
27.104
93
0.632044
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,357
litetty.cpp
visualfc_liteide/liteidex/src/plugins/litetty/litetty.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litetty.cpp // Creator: visualfc <visualfc@gmail.com> #include "litetty.h" #ifdef Q_OS_WIN #include "sockettty.h" #else #include "sockettty.h" #include "fifotty.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end #endif LiteTty::LiteTty(QObject *parent) : LiteApi::ILiteTty(parent) { } LiteApi::ITty *LiteTty::createTty(QObject *parent) const { #ifdef Q_OS_WIN return new SocketTty(parent); #else return new FiFoTty(parent); #endif }
1,707
C++
.cpp
50
32.34
82
0.675937
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,358
litettyplugin.cpp
visualfc_liteide/liteidex/src/plugins/litetty/litettyplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litettyplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "litettyplugin.h" #include "litetty.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteTtyPlugin::LiteTtyPlugin() { } bool LiteTtyPlugin::load(LiteApi::IApplication *app) { app->extension()->addObject("LiteApi.ILiteTty",new LiteTty(this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,698
C++
.cpp
45
35.911111
82
0.682232
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,359
bookmarkmanager.cpp
visualfc_liteide/liteidex/src/plugins/bookmarks/bookmarkmanager.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: bookmarkmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "bookmarkmanager.h" #include <QStandardItemModel> #include <QTreeView> #include <QHeaderView> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end BookmarkManager::BookmarkManager(QObject *parent) : LiteApi::IManager(parent) { } BookmarkManager::~BookmarkManager() { delete m_contextMenu; delete m_treeView; } bool BookmarkManager::initWithApp(LiteApi::IApplication *app) { if (!IManager::initWithApp(app)) { return false; } LiteApi::IEditorMarkManager *manager = LiteApi::getEditorMarkManager(app); if (!manager) { return false; } manager->registerMark(BookMarkType,QIcon("icon:bookmarks/images/bookmark16.png")); m_toggleBookmarkAct = new QAction(tr("Toggle Bookmark"),this); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Bookmarks"); #ifdef Q_OS_MAC actionContext->regAction(m_toggleBookmarkAct,"ToggleBookmark","Meta+M"); #else actionContext->regAction(m_toggleBookmarkAct,"ToggleBookmark","Ctrl+M"); #endif connect(m_toggleBookmarkAct,SIGNAL(triggered()),this,SLOT(toggledBookmark())); connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(editorAboutToClose(LiteApi::IEditor*)),this,SLOT(editorAboutToClose(LiteApi::IEditor*))); connect(manager,SIGNAL(editorMarkListChanged(LiteApi::IEditorMark*,int)),this,SLOT(editorMarkListChanged(LiteApi::IEditorMark*,int))); connect(manager,SIGNAL(editorMarkNodeCreated(LiteApi::IEditorMark*,LiteApi::IEditorMarkNode*)),this,SLOT(editorMarkNodeCreated(LiteApi::IEditorMark*,LiteApi::IEditorMarkNode*))); connect(manager,SIGNAL(editorMarkNodeRemoved(LiteApi::IEditorMark*,LiteApi::IEditorMarkNode*)),this,SLOT(editorMarkNodeRemoved(LiteApi::IEditorMark*,LiteApi::IEditorMarkNode*))); connect(manager,SIGNAL(editorMarkNodeChanged(LiteApi::IEditorMark*,LiteApi::IEditorMarkNode*)),this,SLOT(editorMarkNodeChanged(LiteApi::IEditorMark*,LiteApi::IEditorMarkNode*))); m_treeView = new SymbolTreeView(); m_treeView->setHeaderHidden(true); m_treeView->setEditTriggers(QTreeView::NoEditTriggers); m_treeView->setRootIsDecorated(false); m_bookmarkModel = new BookmarkModel(this); m_proxyModel = new BookmarkSortProxyModel(this); m_proxyModel->setSourceModel(m_bookmarkModel); m_proxyModel->sort(0); m_treeView->setModel(m_proxyModel); m_treeView->setItemDelegate(new BookmarkDelegate(this)); m_treeView->setFrameStyle(QFrame::NoFrame); m_treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_treeView->setContextMenuPolicy(Qt::CustomContextMenu); m_gotoBookmarkAct = new QAction(tr("Goto bookmark"),this); m_removeBookmarkAct = new QAction(tr("Remove bookmark"),this); m_removeFileBookmaraksAct = new QAction(tr("Remove all bookmarks for this file"),this); m_removeAllFileBookmarksAct = new QAction(tr("Remove all bookmarks for all files"),this); m_contextMenu = new QMenu; m_contextMenu->addAction(m_gotoBookmarkAct); m_contextMenu->addAction(m_removeBookmarkAct); m_contextMenu->addAction(m_removeFileBookmaraksAct); m_contextMenu->addAction(m_removeAllFileBookmarksAct); // m_treeView->setFocusPolicy(Qt::NoFocus); // m_treeView->setSelectionModel(manager->selectionModel()); // m_treeView->setSelectionMode(QAbstractItemView::SingleSelection); // m_treeView->setSelectionBehavior(QAbstractItemView::SelectRows); // m_treeView->setDragEnabled(true); // m_treeView->setDragDropMode(QAbstractItemView::DragOnly); m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_treeView,"Bookmarks",tr("Bookmarks"),true); connect(m_treeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(gotoBookmark(QModelIndex))); connect(m_treeView,SIGNAL(enterKeyPressed(QModelIndex)),this,SLOT(gotoBookmark(QModelIndex))); connect(m_treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(contextMenuRequested(QPoint))); connect(m_gotoBookmarkAct,SIGNAL(triggered(bool)),this,SLOT(gotoBookmarkAction())); connect(m_removeBookmarkAct,SIGNAL(triggered(bool)),this,SLOT(removeBookmarkAction())); connect(m_removeFileBookmaraksAct,SIGNAL(triggered(bool)),this,SLOT(removeFileBookmarksAction())); connect(m_removeAllFileBookmarksAct,SIGNAL(triggered(bool)),this,SLOT(removeAllFileBookmarksAction())); return true; } void BookmarkManager::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } LiteApi::IEditorMark *mark = LiteApi::getEditorMark(editor); if (!mark) { return; } QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_toggleBookmarkAct); } menu = LiteApi::getContextMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_toggleBookmarkAct); } bool ok; QString key = QString("bookmarks/%1").arg(editor->filePath()); QList<int> bpList; foreach(QString bp, m_liteApp->settings()->value(key).toStringList()) { int i = bp.toInt(&ok); if (ok) { bpList << i; } } mark->addMarkList(bpList,BookMarkType); } void BookmarkManager::editorAboutToClose(LiteApi::IEditor *editor) { if (!editor) { return; } LiteApi::IEditorMark *mark = LiteApi::getEditorMark(editor); if (!mark) { return; } QList<int> bpList = mark->markLinesByType(BookMarkType); QStringList save; foreach(int bp, bpList) { save.append(QString("%1").arg(bp)); } QString key = QString("bookmarks/%1").arg(editor->filePath()); if (save.isEmpty()) { m_liteApp->settings()->remove(key); } else { m_liteApp->settings()->setValue(key,save); } mark->removeMarkList(bpList,BookMarkType); } void BookmarkManager::toggledBookmark() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::IEditorMark *mark = LiteApi::getEditorMark(editor); if (!mark) { return; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); int line = textEditor->line(); QList<int> types = mark->markTypesByLine(line); if (types.contains(BookMarkType)) { mark->removeMark(line,BookMarkType); } else { mark->addMark(line,BookMarkType); } } void BookmarkManager::editorMarkListChanged(LiteApi::IEditorMark *mark, int type) { if (type != BookMarkType) { return; } } void BookmarkManager::editorMarkNodeCreated(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { if (node->type() != BookMarkType) { return; } // MarkNodeItem *item = new MarkNodeItem(); // item->mark = mark; // item->node = node; // item->setText(QString("%1\t%2").arg(mark->fileName()).arg(node->lineNumber())); // item->setToolTip(QString("%1").arg(mark->filePath())); // m_bookmarkModel->appendRow(item); m_bookmarkModel->addNode(mark,node); } void BookmarkManager::editorMarkNodeRemoved(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { if (node->type() != BookMarkType) { return; } m_bookmarkModel->removeNode(mark,node); // for (int i = 0; i < m_bookmarkModel->rowCount(); i++) { // MarkNodeItem *item = (MarkNodeItem*)m_bookmarkModel->item(i,0); // if (item->mark == mark && item->node == node) { // m_bookmarkModel->removeRow(i); // break; // } // } } void BookmarkManager::editorMarkNodeChanged(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { if (node->type() != BookMarkType) { return; } m_bookmarkModel->updateNode(mark,node); // for (int i = 0; i < m_bookmarkModel->rowCount(); i++) { // MarkNodeItem *item = (MarkNodeItem*)m_bookmarkModel->item(i,0); // if (item->mark == mark && item->node == node) { // item->setText(QString("%1\t%2").arg(mark->fileName()).arg(node->lineNumber())); // break; // } // } } void BookmarkManager::gotoBookmark(const QModelIndex &index) { if (!index.isValid()) { return; } QString filePath = index.data(BookmarkModel::FilePath).toString(); int lineNumber = index.data(BookmarkModel::LineNumber).toInt(); if (!filePath.isEmpty() && (lineNumber > 0)) { LiteApi::gotoLine(m_liteApp,filePath,lineNumber-1,0,true,true); } } void BookmarkManager::contextMenuRequested(QPoint pt) { QModelIndex index = m_treeView->indexAt(pt); m_contextIndex = index; if (!index.isValid()) { return; } m_contextMenu->popup(m_treeView->mapToGlobal(pt)); } void BookmarkManager::gotoBookmarkAction() { gotoBookmark(m_contextIndex); } void BookmarkManager::removeBookmarkAction() { if (!m_contextIndex.isValid()) { return; } QString filePath = m_contextIndex.data(BookmarkModel::FilePath).toString(); int line = m_contextIndex.data(BookmarkModel::LineNumber).toInt()-1; LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(filePath,true); if (!editor) { return; } LiteApi::IEditorMark *mark = LiteApi::getEditorMark(editor); if (!mark) { return; } QList<int> types = mark->markTypesByLine(line); if (types.contains(BookMarkType)) { mark->removeMark(line,BookMarkType); } } void BookmarkManager::removeFileBookmarksAction() { if (!m_contextIndex.isValid()) { return; } QString filePath = m_contextIndex.data(BookmarkModel::FilePath).toString(); removeFileBookmarks(filePath); } void BookmarkManager::removeFileBookmarks(const QString &filePath) { LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(filePath,true); if (!editor) { return; } LiteApi::IEditorMark *mark = LiteApi::getEditorMark(editor); if (!mark) { return; } QList<int> lines = mark->markLinesByType(BookMarkType); mark->removeMarkList(lines,BookMarkType); } void BookmarkManager::removeAllFileBookmarksAction() { int count = m_bookmarkModel->rowCount(); QSet<QString> files; for (int i = 0; i < count; i++) { QModelIndex index = m_bookmarkModel->index(i,0); QString filePath = index.data(BookmarkModel::FilePath).toString(); files.insert(filePath); } foreach (QString file, files) { removeFileBookmarks(file); } }
12,252
C++
.cpp
303
35.089109
183
0.67902
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,360
bookmarksplugin.cpp
visualfc_liteide/liteidex/src/plugins/bookmarks/bookmarksplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: bookmarksplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "bookmarksplugin.h" #include "bookmarkmanager.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end BookmarksPlugin::BookmarksPlugin() { } bool BookmarksPlugin::load(LiteApi::IApplication *app) { BookmarkManager *manager = new BookmarkManager(app); if (!manager->initWithApp(app)) { return false; } return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,820
C++
.cpp
48
34.729167
83
0.663265
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,361
bookmarkmodel.cpp
visualfc_liteide/liteidex/src/plugins/bookmarks/bookmarkmodel.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: bookmarkmodel.cpp // Creator: visualfc <visualfc@gmail.com> #include "bookmarkmodel.h" #include <QPainter> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end void BookmarkModel::addNode(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { beginInsertRows(QModelIndex(), m_nodeList.size(), m_nodeList.size()); BookmarkNode *bn = createBookmarkNode(mark,node); m_nodeList.append(bn); m_nodeMap.insert(node,bn); endInsertRows(); //selectionModel()->setCurrentIndex(index(m_bookmarksList.size()-1 , 0, QModelIndex()), QItemSelectionModel::Select | QItemSelectionModel::Clear); } void BookmarkModel::removeNode(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { BookmarkNode *bn = findBookmarkNode(mark,node); if (!bn) { return; } int idx = m_nodeList.indexOf(bn); beginRemoveRows(QModelIndex(), idx, idx); m_nodeMap.remove(node); delete bn; m_nodeList.removeAt(idx); endRemoveRows(); // if (selectionModel()->currentIndex().isValid()) // selectionModel()->setCurrentIndex(selectionModel()->currentIndex(), QItemSelectionModel::Select | QItemSelectionModel::Clear); } void BookmarkModel::updateNode(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { BookmarkNode *bn = findBookmarkNode(mark,node); if (!bn) { return; } bn->setLineNumber(node->blockNumber()+1); bn->setLineText(node->block().text()); int idx = m_nodeList.indexOf(bn); QModelIndex i = index(idx,0,QModelIndex()); emit dataChanged(i,i); } BookmarkNode *BookmarkModel::createBookmarkNode(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) const { BookmarkNode *n = new BookmarkNode(); n->setFilePath(mark->filePath()); n->setLineNumber(node->blockNumber()+1); n->setLineText(node->block().text()); return n; } BookmarkNode *BookmarkModel::bookmarkNodeForIndex(const QModelIndex &index) const { if (!index.isValid() || index.row() >= m_nodeList.size()) return 0; return m_nodeList.at(index.row()); } BookmarkNode *BookmarkModel::findBookmarkNode(LiteApi::IEditorMark */*mark*/, LiteApi::IEditorMarkNode *node) const { return m_nodeMap.value(node); } BookmarkModel::BookmarkModel(QObject *parent) : QAbstractItemModel(parent) { } QModelIndex BookmarkModel::index(int row, int column, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); else return createIndex(row, column); } QModelIndex BookmarkModel::parent(const QModelIndex &index) const { return QModelIndex(); } int BookmarkModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_nodeList.size(); } int BookmarkModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 1; } QVariant BookmarkModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.column() !=0 || index.row() < 0 || index.row() >= m_nodeList.count()) return QVariant(); BookmarkNode *node = m_nodeList.at(index.row()); if (role == BookmarkModel::FileName) return node->fileName(); if (role == BookmarkModel::LineNumber) return node->lineNumber(); if (role == BookmarkModel::FilePath) return node->filePath(); if (role == BookmarkModel::LineText) return node->lineText(); if (role == BookmarkModel::Note) return node->noteText(); if (role == Qt::ToolTipRole) return QDir::toNativeSeparators(node->filePath()); return QVariant(); } BookmarkDelegate::BookmarkDelegate(QObject *parent) : QStyledItemDelegate(parent) { } QSize BookmarkDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); QFontMetrics fm(option.font); QSize s; s.setWidth(option.rect.width()); s.setHeight(fm.height() * 2 + 10); return s; } void BookmarkDelegate::generateGradientPixmap(int width, int height, const QColor &color, bool selected) const { QColor c = color; c.setAlpha(0); QPixmap pixmap(width+1, height); pixmap.fill(c); QPainter painter(&pixmap); painter.setPen(Qt::NoPen); QLinearGradient lg; lg.setCoordinateMode(QGradient::ObjectBoundingMode); lg.setFinalStop(1,0); lg.setColorAt(0, c); lg.setColorAt(0.4, color); painter.setBrush(lg); painter.drawRect(0, 0, width+1, height); if (selected) m_selectedPixmap = pixmap; else m_normalPixmap = pixmap; } void BookmarkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); painter->save(); QFontMetrics fm(opt.font); static int lwidth = fm.width(QLatin1String("8888")) + 18; QColor backgroundColor; QColor textColor; bool selected = opt.state & QStyle::State_Selected; if (selected) { painter->setBrush(opt.palette.highlight().color()); backgroundColor = opt.palette.highlight().color(); if (!m_selectedPixmap) generateGradientPixmap(lwidth, fm.height()+1, backgroundColor, selected); } else { painter->setBrush(opt.palette.background().color()); backgroundColor = opt.palette.background().color(); if (!m_normalPixmap) generateGradientPixmap(lwidth, fm.height(), backgroundColor, selected); } painter->setPen(Qt::NoPen); painter->drawRect(opt.rect); // Set Text Color if (opt.state & QStyle::State_Selected) textColor = opt.palette.highlightedText().color(); else textColor = opt.palette.text().color(); painter->setPen(textColor); // TopLeft QString topLeft = index.data(BookmarkModel::FileName).toString(); //painter->drawText(6, 2 + opt.rect.top() + fm.ascent(), topLeft); QString topRight = index.data(BookmarkModel::LineNumber).toString(); // Check whether we need to be fancy and paint some background int fwidth = fm.width(topLeft); if (fwidth + lwidth > opt.rect.width()) { int left = opt.rect.right() - lwidth; painter->drawPixmap(left, opt.rect.top(), selected ? m_selectedPixmap : m_normalPixmap); } // topRight painter->drawText(opt.rect.right() - fm.width(topRight) - 6 , 2 + opt.rect.top() + fm.ascent(), topRight); // Directory QColor mix; mix.setRgbF(0.7 * textColor.redF() + 0.3 * backgroundColor.redF(), 0.7 * textColor.greenF() + 0.3 * backgroundColor.greenF(), 0.7 * textColor.blueF() + 0.3 * backgroundColor.blueF()); painter->setPen(mix); QString directory = index.data(BookmarkModel::FilePath).toString(); int availableSpace = opt.rect.width() - fm.width("888"); if (fm.width(directory) > availableSpace) { // We need a shorter directory availableSpace -= fm.width("..."); int pos = directory.size(); int idx; forever { idx = directory.lastIndexOf("/", pos-1); if (idx == -1) { // Can't happen, this means the string did fit after all? break; } int width = fm.width(directory.mid(idx, pos-idx)); if (width > availableSpace) { directory = "..." + directory.mid(pos); break; } else { pos = idx; availableSpace -= width; } } } //painter->drawText(3, opt.rect.top() + fm.ascent() + fm.height() + 6, directory); painter->drawText(6, 2 + opt.rect.top() + fm.ascent(), directory); QString lineText = index.data(BookmarkModel::Note).toString().trimmed(); if (lineText.isEmpty()) lineText = index.data(BookmarkModel::LineText).toString().trimmed(); painter->drawText(6, opt.rect.top() + fm.ascent() + fm.height() + 6, lineText); // Separator lines const QRectF innerRect = QRectF(opt.rect).adjusted(0.5, 0.5, -0.5, -0.5); painter->setPen(QColor::fromRgb(150,150,150)); painter->drawLine(innerRect.bottomLeft(), innerRect.bottomRight()); painter->restore(); }
9,842
C++
.cpp
249
33.148594
151
0.647784
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,362
golanglint.cpp
visualfc_liteide/liteidex/src/plugins/golanglint/golanglint.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2014 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golanglint.cpp // Creator: Hai Thanh Nguyen <phaikawl@gmail.com> #include "golanglint.h" #include "golanglint_global.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "litebuildapi/litebuildapi.h" #include "liteeditorapi/liteeditorapi.h" #include <QDebug> #include <QProcess> #include <QFileInfo> #include <QPlainTextEdit> #include <QTextCodec> #include <QTextCursor> #include <QTextBlock> #include <QScrollBar> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangLint::GolangLint(LiteApi::IApplication *app,QObject *parent) : QObject(parent), m_liteApp(app), m_autolint(false), m_synclint(false), m_timeout(600), m_confidence(50) { m_process = new ProcessEx(this); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(lintOutput(QByteArray,bool))); connect(m_process,SIGNAL(started()),this,SLOT(started())); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(lintFinish(bool,int,QString))); m_envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); if (m_envManager) { connect(m_envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); currentEnvChanged(m_envManager->currentEnv()); } connect(m_liteApp->editorManager(),SIGNAL(editorAboutToSave(LiteApi::IEditor*)),this,SLOT(editorAboutToSave(LiteApi::IEditor*))); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); applyOption("option/golanglint"); } void GolangLint::applyOption(QString id) { if (id != "option/golanglint") { return; } m_autolint = m_liteApp->settings()->value(GOLANGLINT_AUTOLINT,false).toBool(); m_confidence = m_liteApp->settings()->value(GOLANGLINT_CONFIDENCE,0).toInt(); m_synclint = true; m_timeout = m_liteApp->settings()->value(GOLANGLINT_SYNCTIMEOUT,500).toInt(); } void GolangLint::syncLintEditor(LiteApi::IEditor *editor, bool save, bool check, int timeout) { LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { return; } QString fileName = editor->filePath(); if (fileName.isEmpty() && check) { return; } QFileInfo info(fileName); if (info.suffix() != "go" && check) { return; } QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (!ed) { return; } QString text = ed->toPlainText(); if (text.isEmpty()) { return; } QStringList args; args << QString("-min_confidence=%1").arg(m_confidence/100); args << editor->filePath(); if (timeout < 0) { timeout = m_timeout; } if (save) { m_liteApp->editorManager()->saveEditor(editor,false); } QProcess process; process.setEnvironment(LiteApi::getCurrentEnvironment(m_liteApp).toStringList()); process.start(m_golintCmd,args); if (!process.waitForStarted(timeout)) { // m_liteApp->appendLog("golint",QString("Timed out after %1ms when starting go code format").arg(timeout),false); return; } if (!process.waitForFinished(timeout)) { // m_liteApp->appendLog("golint",QString("Timed out after %1ms while running go code format").arg(timeout),false); return; } LiteApi::ILiteEditor *liteEditor = LiteApi::getLiteEditor(editor); liteEditor->clearAllNavigateMark(LiteApi::EditorNavigateBad, GOLANGLINT_TAG); QTextCodec *codec = QTextCodec::codecForName("utf-8"); QByteArray error = process.readAllStandardOutput(); QString errmsg = codec->toUnicode(error); if (!errmsg.isEmpty()) { //<standard input>:23:1: expected declaration, found 'INT' 1 foreach(QString msg,errmsg.split("\n")) { QRegExp re(":(\\d+):\\d+:"); int idx = re.indexIn(msg); if (idx >= 0) { bool ok = false; int line = re.cap(1).toInt(&ok); if (ok) { liteEditor->insertNavigateMark(line-1,LiteApi::EditorNavigateWarning,msg.mid(idx+re.matchedLength()), GOLANGLINT_TAG); } } } liteEditor->setNavigateHead(LiteApi::EditorNavigateNormal,"go code lint output\n"+errmsg); m_liteApp->appendLog("go lint suggestions: ",errmsg,false); return; } } void GolangLint::lintEditor(LiteApi::IEditor *editor, bool) { if (!editor) { return; } if (editor->filePath().isEmpty()) { return; } QFileInfo info(editor->filePath()); if (info.suffix() != "go") { return; } if (m_golintCmd.isEmpty()) { return; } if (m_process->isRunning()) { return; } QPlainTextEdit *edit = LiteApi::getPlainTextEdit(editor); if (!edit) { return; } QStringList args; args << QString("-min_confidence=%1").arg(m_confidence/100); args << editor->filePath(); m_data.clear();; m_errData.clear(); m_process->start(m_golintCmd,args); } void GolangLint::editorAboutToSave(LiteApi::IEditor* editor) { if (!m_autolint) { return; } if (m_synclint) { syncLintEditor(editor,true); } else { lintEditor(editor,true); } } void GolangLint::currentEnvChanged(LiteApi::IEnv*) { QProcessEnvironment env = m_envManager->currentEnvironment(); m_golintCmd = FileUtil::lookupGoBin("golint",m_liteApp,false); if (m_golintCmd.isEmpty()) { m_liteApp->appendLog("GolangLint",QString("Could not find %1").arg(m_golintCmd),false); } else { m_liteApp->appendLog("GolangLint",QString("Found %1").arg(m_golintCmd),false); } m_process->setProcessEnvironment(env); } void GolangLint::golint() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } m_liteApp->editorManager()->saveEditor(editor,false); syncLintEditor(editor,false,true,-1); } void GolangLint::started() { // QString text = m_process->userData(1).toString(); // m_process->write(text.toUtf8()); // m_process->closeWriteChannel(); } void GolangLint::lintOutput(QByteArray data,bool) { m_errData.append(data); m_data.append(data); } void GolangLint::lintFinish(bool error,int code,QString) { QString fileName = m_process->userData(0).toString(); if (fileName.isEmpty()) { return; } bool save = m_process->userData(2).toBool(); LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(fileName,true); if (!editor) { return; } LiteApi::ILiteEditor *liteEditor = LiteApi::getLiteEditor(editor); if (!liteEditor) { return; } QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor); if (!ed) { return; } if (ed->document()->isModified()) { return; } QTextCodec *codec = QTextCodec::codecForName("utf-8"); if (!error && code == 0) { liteEditor->setNavigateHead(LiteApi::EditorNavigateNormal,"go code lint success"); if (save) { m_liteApp->editorManager()->saveEditor(editor,false); } } else if (!m_errData.isEmpty()) { QString errmsg = codec->toUnicode(m_errData); if (!errmsg.isEmpty()) { //<standard input>:23:1: expected declaration, found 'INT' 1 foreach(QString msg,errmsg.split("\n")) { QRegExp re(":(\\d+):"); if (re.indexIn(msg,16) >= 0) { bool ok = false; int line = re.cap(1).toInt(&ok); if (ok) { liteEditor->insertNavigateMark(line-1,LiteApi::EditorNavigateWarning,msg.mid(16),GOLANGLINT_TAG); } } } } QString log = errmsg; } m_data.clear(); }
9,190
C++
.cpp
259
29.787645
138
0.643146
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,363
golanglintoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/golanglint/golanglintoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2014 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golanglintoptionfactory.cpp // Creator: Hai Thanh Nguyen <phaikawl@gmail.com> #include "golanglintoption.h" #include "golanglintoptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangLintOptionFactory::GolangLintOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GolangLintOptionFactory::mimeTypes() const { return QStringList() << "option/golanglint"; } LiteApi::IOption *GolangLintOptionFactory::create(const QString &mimeType) { if (mimeType == "option/golanglint") { return new GolangLintOption(m_liteApp,this); } return 0; }
1,917
C++
.cpp
49
36.836735
93
0.689378
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,364
golanglintoption.cpp
visualfc_liteide/liteidex/src/plugins/golanglint/golanglintoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2014 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golanglintoption.cpp // Creator: Hai Thanh Nguyen <phaikawl@gmail.com> #include "golanglintoption.h" #include "golanglint_global.h" #include "ui_golanglintoption.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangLintOption::GolangLintOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::GolangLintOption) { ui->setupUi(m_widget); int confidence = m_liteApp->settings()->value(GOLANGLINT_CONFIDENCE,0).toInt(); int timeout = m_liteApp->settings()->value(GOLANGLINT_SYNCTIMEOUT,500).toInt(); bool autolint = m_liteApp->settings()->value(GOLANGLINT_AUTOLINT,false).toBool(); ui->checkBoxAutoLint->setChecked(autolint); ui->syncTimeoutLineEdit->setText(QString("%1").arg(timeout)); ui->lintConfidenceValLabel->setText(QString("%1").arg((float)confidence/10)); ui->confidenceSlider->setValue(confidence); connect(ui->confidenceSlider, SIGNAL(valueChanged(int)), this, SLOT(on_confidenceSlider_valueChanged(int))); } GolangLintOption::~GolangLintOption() { delete m_widget; delete ui; } QWidget *GolangLintOption::widget() { return m_widget; } QString GolangLintOption::name() const { return "GolangLint"; } QString GolangLintOption::mimeType() const { return "option/golanglint"; } void GolangLintOption::apply() { bool autolint = ui->checkBoxAutoLint->isChecked(); int confidence = ui->confidenceSlider->value(); m_liteApp->settings()->setValue(GOLANGLINT_AUTOLINT,autolint); m_liteApp->settings()->setValue(GOLANGLINT_CONFIDENCE,confidence); int timeout = ui->syncTimeoutLineEdit->text().toInt(); if (timeout < 500) { timeout = 500; } ui->syncTimeoutLineEdit->setText(QString("%1").arg(timeout)); m_liteApp->settings()->setValue(GOLANGLINT_SYNCTIMEOUT,timeout); } void GolangLintOption::on_confidenceSlider_valueChanged(int value) { ui->lintConfidenceValLabel->setText(QString("%1").arg((float)value/10)); }
3,277
C++
.cpp
84
36.166667
112
0.704053
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,365
golanglintplugin.cpp
visualfc_liteide/liteidex/src/plugins/golanglint/golanglintplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2014 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golanglint.cpp // Creator: Hai Thanh Nguyen <phaikawl@gmail.com> #include "golanglintplugin.h" #include "golanglint.h" #include "fileutil/fileutil.h" #include "golanglintoptionfactory.h" #include <QMenu> #include <QAction> #include <QToolButton> #include <QFileInfo> #include <QDir> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangLintPlugin::GolangLintPlugin() : m_lint(0) { } bool GolangLintPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; app->optionManager()->addFactory(new GolangLintOptionFactory(app,this)); m_lint = new GolangLint(app,this); m_golintAct = new QAction(QIcon("icon:golanglint/images/golint.png"),tr("Lint Code"),this); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"GoLint"); actionContext->regAction(m_golintAct,"GoLint","Ctrl+Shift+F7"); m_goplayAct = new QAction(QIcon("icon:golanglint/images/golint.png"),tr("Lint Code"),this); actionContext->regAction(m_goplayAct,"GoplayLint","Ctrl+Shift+F7"); connect(m_golintAct,SIGNAL(triggered()),m_lint,SLOT(golint())); connect(m_goplayAct,SIGNAL(triggered()),this,SLOT(goplayLint())); connect(app->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(app,SIGNAL(loaded()),this,SLOT(appLoaded())); return true; } QStringList GolangLintPlugin::dependPluginList() const{ return QStringList() << "plugin/liteenv"; } void GolangLintPlugin::goplayLint() { m_lint->syncLintEditor(m_playEditor,false,false,2000); /* QPlainTextEdit* ed=LiteApi::getPlainTextEdit(m_playEditor); ed->document()->setModified(false); m_lint->lintEditor(m_playEditor,false); */ } void GolangLintPlugin::appLoaded() { m_playEditor = LiteApi::findExtensionObject<LiteApi::IEditor*>(m_liteApp->extension(),"LiteApi.Goplay.IEditor"); if (m_playEditor) { if (m_playEditor->mimeType() != "text/x-gosrc") { return; } m_playEditor->widget()->addAction(m_goplayAct); QMenu *menu = LiteApi::getContextMenu(m_playEditor); if (menu) { menu->addSeparator(); menu->addAction(m_goplayAct); } } } void GolangLintPlugin::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } if (editor->mimeType() != "text/x-gosrc") { return; } QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_golintAct); } menu = LiteApi::getContextMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_golintAct); } } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
4,053
C++
.cpp
110
32.918182
119
0.678808
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,366
astwidget.cpp
visualfc_liteide/liteidex/src/plugins/golangast/astwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: astwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "astwidget.h" #include "golangastitem.h" #include "golangasticon.h" #include "golangdocapi/golangdocapi.h" #include "liteenvapi/liteenvapi.h" #include <QAction> #include <QMenu> #include <QStandardItemModel> #include <QSortFilterProxyModel> #include <QFont> #include <QVBoxLayout> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end AstWidget::AstWidget(bool outline, LiteApi::IApplication *app, QWidget *parent) : QWidget(parent), m_bOutline(outline), m_liteApp(app) { m_bFirst = true; QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); m_tree = new SymbolTreeView; m_tree->setExpandsOnDoubleClick(false); m_filterEdit = new Utils::FilterLineEdit(200); m_model = new QStandardItemModel(this); proxyModel = new QSortFilterProxyModel(this); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setDynamicSortFilter(true); proxyModel->setSourceModel(m_model); layout->addWidget(m_filterEdit); layout->addWidget(m_tree); this->setLayout(layout); m_tree->setModel(proxyModel); //m_tree->setExpandsOnDoubleClick(false); m_tree->setContextMenuPolicy(Qt::CustomContextMenu); m_gotoPosAct = new QAction(tr("Go To Definition"),this); m_importDocAct = new QAction(tr("View Import Document"),this); m_contextMenu = new QMenu(this); m_contextMenu->addAction(m_gotoPosAct); m_contextMenu->addAction(m_importDocAct); m_contextItem = 0; connect(m_tree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClicked(QModelIndex))); connect(m_tree,SIGNAL(enterKeyPressed(QModelIndex)),this,SLOT(enterKeyPressed(QModelIndex))); connect(m_filterEdit,SIGNAL(filterChanged(QString)),this,SLOT(filterChanged(QString))); connect(m_tree,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeContextMenuRequested(QPoint))); connect(m_gotoPosAct,SIGNAL(triggered()),this,SLOT(gotoDefinition())); connect(m_importDocAct,SIGNAL(triggered()),this,SLOT(viewImportDoc())); } void AstWidget::clear() { m_model->clear(); m_filterEdit->clear(); } static QModelIndexList filterModelList(QString filter, QAbstractItemModel *model, QModelIndex parent) { QModelIndexList list; for (int i = 0; i < model->rowCount(parent); i++) { QModelIndex index = model->index(i,0,parent); if (index.data().toString().indexOf(filter,0,Qt::CaseInsensitive) >= 0) { list.append(index); } list.append(filterModelList(filter,model,index)); } return list; } void AstWidget::clearFilter(QModelIndex parent) { for (int i = 0; i < m_model->rowCount(parent); i++) { QModelIndex index = m_model->index(i,0,parent); clearFilter(index); GolangAstItem *item = (GolangAstItem*)m_model->itemFromIndex(index); if (!item) { continue; } if (item->m_tagName.indexOf("+") >= 0) { continue; } QFont font = item->font(); font.setBold(false); item->setFont(font); } } bool AstWidget::filterModel(QString filter, QModelIndex parent, QModelIndex &first) { bool b = false; for (int i = 0; i < proxyModel->rowCount(parent); i++) { QModelIndex index = proxyModel->index(i,0,parent); GolangAstItem *item = astItemFromIndex(index); if (!item) { continue; } if (item->m_tagName.indexOf("+") < 0) { QFont font = item->font(); if (index.data().toString().indexOf(filter,0,Qt::CaseInsensitive) >= 0) { font.setBold(true); if (!b) { b = true; if (!first.isValid()) { first = index; } } } else { font.setBold(false); } item->setFont(font); } if (filterModel(filter,index,first)) { m_tree->expand(index); b = true; } else { //if (!m_bOutline) { m_tree->collapse(index); //} } } return b; } void AstWidget::filterChanged(QString filter) { if (filter.isEmpty()) { clearFilter(m_tree->rootIndex()); m_tree->expandToDepth(0); /* for(int i = 0; i < proxyModel->rowCount(); i++) { QModelIndex index = proxyModel->index(i,0); m_tree->expand(index); if (m_bOutline) { for (int j = 0; j < proxyModel->rowCount(index);j++) { m_tree->expand(proxyModel->index(j,0,index)); } } } */ } else { QModelIndex first; filterModel(filter,m_tree->rootIndex(),first); if (first.isValid()) { m_tree->scrollTo(first); } } } void AstWidget::treeContextMenuRequested(QPoint pt) { QModelIndex index = m_tree->indexAt(pt); if (!index.isValid()) { return; } GolangAstItem *item = astItemFromIndex(index); if (item->isFolder() || item->m_tagFlag == LiteApi::TagPackage) { return; } m_contextItem = item; m_importDocAct->setVisible(item->m_tagFlag == LiteApi::TagImport); m_contextMenu->popup(m_tree->mapToGlobal(pt)); } void AstWidget::gotoDefinition() { gotoItemDefinition(m_contextItem); } void AstWidget::viewImportDoc() { QString pkg = m_contextItem->text(); QString orgPkg = pkg; //check mod and vendor pkg QString gotools = LiteApi::getGotools(m_liteApp); if (!gotools.isEmpty()) { QProcess process(this); process.setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); process.setWorkingDirectory(m_workPath); QStringList args; args << "pkgcheck" << "-pkg" << pkg; process.start(gotools,args); if (!process.waitForFinished(3000)) { process.kill(); } QByteArray ar = process.readAllStandardOutput(); QString pkgs = QString::fromUtf8(ar).trimmed(); if (!pkgs.isEmpty()) { QStringList pkgInfo = pkgs.split(","); if (pkgInfo.size() == 2 && !pkgInfo[0].isEmpty()) { pkg = pkgInfo[0]; } } } LiteApi::IGolangDoc *doc = LiteApi::getGolangDoc(m_liteApp); if (!doc) { return; } QUrl url; url.setScheme("pdoc"); url.setPath(pkg); QString addin; if (pkg != orgPkg) { addin = orgPkg; } doc->openUrl(url,addin); doc->activeBrowser(); } void AstWidget::doubleClicked(QModelIndex index) { GolangAstItem *item = astItemFromIndex(index); if (!item) { return; } if (!item->isFolder()) { gotoItemDefinition(item); } else { m_tree->setExpanded(index,!m_tree->isExpanded(index)); } } void AstWidget::enterKeyPressed(const QModelIndex &index) { GolangAstItem *item = astItemFromIndex(index); if (!item) { return; } if (item->isFolder()) { m_tree->setExpanded(index,!m_tree->isExpanded(index)); } else { gotoItemDefinition(item); } } void AstWidget::gotoItemDefinition(GolangAstItem *item) { if (item->m_posList.isEmpty()) { return; } AstItemPos pos = item->m_posList.at(0); QFileInfo info(QDir(m_workPath),pos.fileName); LiteApi::gotoLine(m_liteApp,info.filePath(),pos.line-1,pos.column-1,true,true); return; // LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(info.filePath()); // if (!editor) { // return; // } // editor->widget()->setFocus(); // LiteApi::ITextEditor *textEditor = LiteApi::findExtensionObject<LiteApi::ITextEditor*>(editor,"LiteApi.ITextEditor"); // if (!textEditor) { // return; // } // textEditor->gotoLine(pos.line-1,pos.column,true); } GolangAstItem *AstWidget::astItemFromIndex(QModelIndex index) { QModelIndex i = proxyModel->mapToSource(index); if (!i.isValid()) { return 0; } return (GolangAstItem*)m_model->itemFromIndex(i); } /* tools/goastview/packageview.go const ( tag_package = "p" tag_imports_folder = "+m" tag_import = "mm" tag_type = "t" tag_struct = "s" tag_interface = "i" tag_value = "v" tag_const = "c" tag_func = "f" tag_value_folder = "+v" tag_const_folder = "+c" tag_func_folder = "+f" tag_type_method = "tm" tag_type_factor = "tf" tag_type_value = "tv" ) */ static QString tagInfo(const QString &tag) { if (tag == "p") { return "package"; } else if (tag == "+m") { return "imports folder"; } else if (tag == "mm") { return "import"; } else if (tag == "t") { return "type"; } else if (tag == "s") { return "struct"; } else if (tag == "i") { return "interface"; } else if (tag == "v") { return "value"; } else if (tag == "c") { return "const"; } else if (tag == "f") { return "func"; } else if (tag == "+v") { return "values folder"; } else if (tag == "+c") { return "const folder"; } else if (tag == "+f") { return "funcs folder"; } else if (tag == "tm") { return "method"; } else if (tag == "tf") { return "factory"; } else if (tag == "tv") { return "field"; } return QString(); } static LiteApi::ASTTAG_ENUM toTagFlag(const QString &tag) { if (tag == "p") { return LiteApi::TagPackage; } else if (tag == "+m") { return LiteApi::TagImportFolder; } else if (tag == "mm") { return LiteApi::TagImport; } else if (tag == "t") { return LiteApi::TagType; } else if (tag == "s") { return LiteApi::TagStruct; } else if (tag == "i") { return LiteApi::TagInterface; } else if (tag == "v") { return LiteApi::TagValue; } else if (tag == "c") { return LiteApi::TagConst; } else if (tag == "f") { return LiteApi::TagFunc; } else if (tag == "+v") { return LiteApi::TagValueFolder; } else if (tag == "+c") { return LiteApi::TagConstFolder; } else if (tag == "+f") { return LiteApi::TagFuncFolder; } else if (tag == "tm") { return LiteApi::TagTypeMethod; } else if (tag == "tf") { return LiteApi::TagTypeFactor; } else if (tag == "tv") { return LiteApi::TagTypeValue; } else if (tag == "b") { return LiteApi::TagTodo; } else if (tag == "+b") { return LiteApi::TagTodoFolder; } return LiteApi::TagNone; } void AstWidget::parserModel(QStandardItemModel *model, const QByteArray &data, const QByteArray &sep, bool flatMode, bool skipimport) { QList<QString> array = QString::fromUtf8(data).split('\n'); QMap<int,QStandardItem*> items; QStringList indexFiles; bool ok = false; bool bmain = false; QMap<QString,GolangAstItem*> level1NameItemMap; foreach (QString line, array) { int pos = line.indexOf('@'); QString tip; if (pos == 0) { indexFiles.append(line.mid(1)); continue; } else if (pos >= 1) { tip = line.mid(pos+1); line = line.left(pos); } line = line.trimmed(); QList<QString> info = line.split(sep); if (info.size() < 3) { continue; } int level = info[0].toInt(&ok); if (!ok) { continue; } QString tag = info[1]; QString name = info[2]; if (name.isEmpty() || tag.isEmpty()) { continue; } if (flatMode && tag.startsWith("+")) { continue; } if (level == 0) { level1NameItemMap.clear(); } if (tag == "p") { if (name == "main") { bmain = true; } else { bmain = false; } if (name == "documentation") { continue; } if (flatMode) { continue; } } if (skipimport && tag == "mm") { continue; } GolangAstItem *item = 0; if (level == 1) { item = level1NameItemMap.value(name); if (item != 0) { items[level] = item; continue; } } item = new GolangAstItem; if (level == 1) { level1NameItemMap.insert(name,item); } item->m_tagName = tag; item->m_tagFlag = toTagFlag(tag); item->setText(name); if (!bmain && (name.at(0).isLower() || name.at(0) == '_')) { item->setIcon(GolangAstIcon::instance()->iconFromTag(tag,false)); } else { item->setIcon(GolangAstIcon::instance()->iconFromTag(tag)); } if (!tip.isEmpty()) { item->setToolTip(tip); // todo comment use tip if (tag == "b") { item->setText(tip); item->setToolTip(name); } } else if (tag.at(0) == '+') { item->setToolTip(QString("%1").arg(tagInfo(tag))); } else { item->setToolTip(QString("%1 %2").arg(tagInfo(tag)).arg(name)); } if (info.size() >= 4) { foreach (QString pos, info[3].split(';')) { QList<QString> ar = pos.split(':'); if (ar.size() == 3) { bool ok = false; int index = ar[0].toInt(&ok); if (ok && index >= 0 && index < indexFiles.size()) { bool ok1,ok2; int line = ar[1].toInt(&ok1); int col = ar[2].toInt(&ok2); if (ok1 && ok2) { AstItemPos pos = {indexFiles[index],line,col,-1,-1}; item->m_posList.append(pos); } } } else if (ar.size() == 5) { bool ok = false; int index = ar[0].toInt(&ok); if (ok && index >= 0 && index < indexFiles.size()) { bool ok1,ok2,ok3,ok4; int line = ar[1].toInt(&ok1); int col = ar[2].toInt(&ok2); int endLine = ar[3].toInt(&ok3); int endCol = ar[4].toInt(&ok4); if (ok1 && ok2 && ok3 && ok4) { AstItemPos pos = {indexFiles[index],line,col,endLine,endCol}; item->m_posList.append(pos); } } } } } QStandardItem *parent = items.value(level-1,0); if (parent ) { if (flatMode) { if (tag == "tv") { item->setText(parent->text()+"."+item->text()); } model->appendRow(item); } else { parent->appendRow(item); } } else { model->appendRow(item); } items[level] = item; } } bool AstWidget::trySyncIndex(const QString &filePath, int line, int column) { QModelIndexList finds; QFileInfo info(filePath); findModelIndex(QModelIndex(),info.fileName(),line+1,column+1,finds); if (finds.isEmpty()) { return false; } m_tree->setCurrentIndex(finds.last()); m_tree->scrollTo(finds.last()); return true; } void AstWidget::findModelIndex(const QModelIndex &parent, const QString &fileName, int line, int column, QModelIndexList &finds) { for (int i = 0; i < proxyModel->rowCount(parent); i++) { QModelIndex index = proxyModel->index(i,0,parent); GolangAstItem *item = astItemFromIndex(index); if (!item) { continue; } foreach (AstItemPos pos, item->m_posList) { if (pos.fileName == fileName && line >= pos.line && column >= pos.column && line <= pos.endLine) { if (line < pos.endLine || (line == pos.endLine && column <= pos.endColumn) ) { finds.push_back(index); } } } if (item->hasChildItem()) { findModelIndex(index,fileName,line,column,finds); } } } // level,tag,name,pos,@info void AstWidget::updateModel(const QByteArray &data, const QByteArray &sep) { //save state SymbolTreeState state; m_tree->saveState(&state); m_model->clear(); parserModel(m_model,data,sep,false,false); //load state if (!m_tree->isExpanded(m_tree->rootIndex())) { m_tree->expandToDepth(0); } m_tree->loadState(proxyModel,&state); /* if (m_bOutline && m_bFirst) { //m_tree->expandToDepth(1); for(int i = 0; i < proxyModel->rowCount(); i++) { QModelIndex index = proxyModel->index(i,0); m_tree->expand(index); for (int j = 0; j < proxyModel->rowCount(index);j++) { m_tree->expand(proxyModel->index(j,0,index)); } } m_bFirst = false; } */ QString text = m_filterEdit->text().trimmed(); if (!text.isEmpty()) { this->filterChanged(text); } }
18,794
C++
.cpp
572
25.022727
133
0.553582
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,367
golangasticon.cpp
visualfc_liteide/liteidex/src/plugins/golangast/golangasticon.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangasticon.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangasticon.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end /* tools/goastview/packageview.go const ( tag_package = "p" tag_imports_folder = "+m" tag_import = "mm" tag_type = "t" tag_struct = "s" tag_interface = "i" tag_value = "v" tag_const = "c" tag_func = "f" tag_value_folder = "+v" tag_const_folder = "+c" tag_func_folder = "+f" tag_type_method = "tm" tag_type_factor = "tf" tag_type_value = "tv" ) */ GolangAstIconPublic::GolangAstIconPublic() : iconPackage(QIcon("icon:golangast/images/package.png")), iconImport(QIcon("icon:golangast/images/import.png")), iconImports(QIcon("icon:golangast/images/imports.png")), iconType(QIcon("icon:golangast/images/type.png")), iconStruct(QIcon("icon:golangast/images/struct.png")), iconInterface(QIcon("icon:golangast/images/interface.png")), iconFunc(QIcon("icon:golangast/images/func.png")), iconFuncs(QIcon("icon:golangast/images/funcs.png")), iconVar(QIcon("icon:golangast/images/var.png")), iconVars(QIcon("icon:golangast/images/vars.png")), iconConst(QIcon("icon:golangast/images/const.png")), iconConsts(QIcon("icon:golangast/images/consts.png")), iconTypeMethod(QIcon("icon:golangast/images/type_method.png")), iconTypeFactor(QIcon("icon:golangast/images/type_factor.png")), iconTypeVar(QIcon("icon:golangast/images/type_var.png")), iconTodo(QIcon("icon:golangast/images/todo.png")), iconTodos(QIcon("icon:golangast/images/todos.png")), iconGofile(QIcon("icon:golangast/images/gofile.png")), iconMakefile(QIcon("icon:golangast/images/makefile.png")), iconProfile(QIcon("icon:golangast/images/project.png")) { } QIcon GolangAstIconPublic::iconFromTag(const QString &tag) const { if (tag == "p") return iconPackage; else if (tag == "+m") return iconImports; else if (tag == "mm") return iconImport; else if (tag == "t") return iconType; else if (tag == "i") return iconInterface; else if (tag == "s") return iconStruct; else if (tag == "v") return iconVar; else if (tag == "c") return iconConst; else if (tag == "f") return iconFunc; else if (tag == "+v") return iconVars; else if (tag == "+c") return iconConsts; else if (tag == "+f") return iconFuncs; else if (tag == "tm") return iconTypeMethod; else if (tag == "tf") return iconTypeFactor; else if (tag == "tv") return iconTypeVar; else if (tag == "b") return iconTodo; else if (tag == "+b") return iconTodos; return QIcon(); } QIcon GolangAstIconPublic::iconFromTagEnum(LiteApi::ASTTAG_ENUM tag, bool) const { if (tag == LiteApi::TagPackage) return iconPackage; else if (tag == LiteApi::TagImportFolder) return iconImports; else if (tag == LiteApi::TagImport) return iconImport; else if (tag == LiteApi::TagType) return iconType; else if (tag == LiteApi::TagInterface) return iconInterface; else if (tag == LiteApi::TagStruct) return iconStruct; else if (tag == LiteApi::TagValue) return iconVar; else if (tag == LiteApi::TagConst) return iconConst; else if (tag == LiteApi::TagFunc) return iconFunc; else if (tag == LiteApi::TagValueFolder) return iconVars; else if (tag == LiteApi::TagConstFolder) return iconConsts; else if (tag == LiteApi::TagFuncFolder) return iconFuncs; else if (tag == LiteApi::TagTypeMethod) return iconTypeMethod; else if (tag == LiteApi::TagTypeFactor) return iconTypeFactor; else if (tag == LiteApi::TagTypeValue) return iconTypeVar; else if (tag == LiteApi::TagTodo) return iconTodo; else if (tag == LiteApi::TagTodoFolder) return iconTodos; return QIcon(); } GolangAstIconPrivate::GolangAstIconPrivate() : iconPackage(QIcon("icon:golangast/images/package.png")), iconImport(QIcon("icon:golangast/images/import.png")), iconImports(QIcon("icon:golangast/images/imports.png")), iconType(QIcon("icon:golangast/images/type_p.png")), iconStruct(QIcon("icon:golangast/images/struct_p.png")), iconInterface(QIcon("icon:golangast/images/interface_p.png")), iconFunc(QIcon("icon:golangast/images/func_p.png")), iconFuncs(QIcon("icon:golangast/images/funcs.png")), iconVar(QIcon("icon:golangast/images/var_p.png")), iconVars(QIcon("icon:golangast/images/vars.png")), iconConst(QIcon("icon:golangast/images/const_p.png")), iconConsts(QIcon("icon:golangast/images/consts.png")), iconTypeMethod(QIcon("icon:golangast/images/type_method_p.png")), iconTypeFactor(QIcon("icon:golangast/images/type_factor_p.png")), iconTypeVar(QIcon("icon:golangast/images/type_var_p.png")), iconTodo(QIcon("icon:golangast/images/todo.png")), iconTodos(QIcon("icon:golangast/images/todos.png")) { } QIcon GolangAstIconPrivate::iconFromTag(const QString &tag) const { if (tag == "p") return iconPackage; else if (tag == "+m") return iconImports; else if (tag == "mm") return iconImport; else if (tag == "t") return iconType; else if (tag == "i") return iconInterface; else if (tag == "s") return iconStruct; else if (tag == "v") return iconVar; else if (tag == "c") return iconConst; else if (tag == "f") return iconFunc; else if (tag == "+v") return iconVars; else if (tag == "+c") return iconConsts; else if (tag == "+f") return iconFuncs; else if (tag == "tm") return iconTypeMethod; else if (tag == "tf") return iconTypeFactor; else if (tag == "tv") return iconTypeVar; else if (tag == "b") return iconTodo; else if (tag == "+b") return iconTodos; return QIcon(); } QIcon GolangAstIconPrivate::iconFromTagEnum(LiteApi::ASTTAG_ENUM tag, bool) const { if (tag == LiteApi::TagPackage) return iconPackage; else if (tag == LiteApi::TagImportFolder) return iconImports; else if (tag == LiteApi::TagImport) return iconImport; else if (tag == LiteApi::TagType) return iconType; else if (tag == LiteApi::TagInterface) return iconInterface; else if (tag == LiteApi::TagStruct) return iconStruct; else if (tag == LiteApi::TagValue) return iconVar; else if (tag == LiteApi::TagConst) return iconConst; else if (tag == LiteApi::TagFunc) return iconFunc; else if (tag == LiteApi::TagValueFolder) return iconVars; else if (tag == LiteApi::TagConstFolder) return iconConsts; else if (tag == LiteApi::TagFuncFolder) return iconFuncs; else if (tag == LiteApi::TagTypeMethod) return iconTypeMethod; else if (tag == LiteApi::TagTypeFactor) return iconTypeFactor; else if (tag == LiteApi::TagTypeValue) return iconTypeVar; else if (tag == LiteApi::TagTodo) return iconTodo; else if (tag == LiteApi::TagTodoFolder) return iconTodos; return QIcon(); } GolangAstIcon::GolangAstIcon() { } GolangAstIcon *GolangAstIcon::instance() { static GolangAstIcon icons; return &icons; } QIcon GolangAstIcon::iconFromTag(const QString &tag, bool pub) const { if (pub) { return icons.iconFromTag(tag); } return icons_p.iconFromTag(tag); } QIcon GolangAstIcon::iconFromTagEnum(LiteApi::ASTTAG_ENUM tag, bool pub) const { if (pub) { return icons.iconFromTagEnum(tag); } return icons_p.iconFromTagEnum(tag); }
9,164
C++
.cpp
269
28.873606
82
0.648874
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,368
golangastoption.cpp
visualfc_liteide/liteidex/src/plugins/golangast/golangastoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangastoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangastoption.h" #include "ui_golangastoption.h" #include "golangast_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangAstOption::GolangAstOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::GolangAstOption) { ui->setupUi(m_widget); } GolangAstOption::~GolangAstOption() { delete m_widget; delete ui; } QWidget *GolangAstOption::widget() { return m_widget; } QString GolangAstOption::name() const { return "GolangAst"; } QString GolangAstOption::mimeType() const { return OPTION_GOLANGAST; } void GolangAstOption::load() { ui->checkQuickSymbolImportPath->setChecked(m_liteApp->settings()->value(GOLANGAST_QUICKOPNE_SYMBOL_IMPORTPATH,true).toBool()); ui->checkQuickSymbolMatchCase->setChecked(m_liteApp->settings()->value(GOLANGAST_QUICKOPEN_SYMBOL_MATCHCASE,false).toBool()); } void GolangAstOption::save() { m_liteApp->settings()->setValue(GOLANGAST_QUICKOPNE_SYMBOL_IMPORTPATH,ui->checkQuickSymbolImportPath->isChecked()); m_liteApp->settings()->setValue(GOLANGAST_QUICKOPEN_SYMBOL_MATCHCASE,ui->checkQuickSymbolMatchCase->isChecked()); }
2,606
C++
.cpp
69
34.362319
131
0.689409
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,369
golangast.cpp
visualfc_liteide/liteidex/src/plugins/golangast/golangast.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangast.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangast.h" #include "golangastitem.h" #include "golangasticon.h" #include "astwidget.h" #include "liteenvapi/liteenvapi.h" #include "golangast_global.h" #include <QStackedWidget> #include <QDockWidget> #include <QVBoxLayout> #include <QFileInfo> #include <QStandardItem> #include <QStandardItemModel> #include <QSortFilterProxyModel> #include <QTimer> #include <QDir> #include <QAction> #include <QLabel> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangAst::GolangAst(LiteApi::IApplication *app, QObject *parent) : LiteApi::IGolangAst(parent), m_liteApp(app) { m_astviewSep = ",,,"; m_currentEditor = 0; m_currentPlainTextEditor = 0; m_blankWidget = new QLabel(tr("No outline available")); m_blankWidget->setAlignment(Qt::AlignCenter); m_stackedWidget = new QStackedWidget; m_stackedWidget->addWidget(m_blankWidget); m_projectAstWidget = new AstWidget(false,m_liteApp); m_process = new QProcess(this); m_timer = new QTimer(this); m_processFile = new QProcess(this); m_timerFile = new QTimer(this); m_syncClassViewAct = new QAction(QIcon("icon:images/sync.png"),tr("Synchronize with editor"),this); m_syncClassViewAct->setCheckable(true); m_syncOutlineAct = new QAction(QIcon("icon:images/sync.png"),tr("Synchronize with editor"),this); m_syncOutlineAct->setCheckable(true); m_classViewToolAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_projectAstWidget,"GoClassView",tr("Go Class View"),false, QList<QAction*>() << m_syncClassViewAct); m_outlineToolAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_stackedWidget,"GoOutline",tr("Go Outline"),false, QList<QAction*>() << m_syncOutlineAct); connect(m_classViewToolAct,SIGNAL(toggled(bool)),this,SLOT(astProjectEnable(bool))); connect(m_outlineToolAct,SIGNAL(toggled(bool)),this,SLOT(astFileEnable(bool))); connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(editorAboutToClose(LiteApi::IEditor*)),this,SLOT(editorAboutToClose(LiteApi::IEditor*))); connect(m_liteApp->projectManager(),SIGNAL(currentProjectChanged(LiteApi::IProject*)),this,SLOT(projectChanged(LiteApi::IProject*))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(editorChanged(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(editorSaved(LiteApi::IEditor*)),this,SLOT(editorSaved(LiteApi::IEditor*))); connect(m_process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finishedProcess(int,QProcess::ExitStatus))); connect(m_timer,SIGNAL(timeout()),this,SLOT(updateAstNow())); connect(m_processFile,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finishedProcessFile(int,QProcess::ExitStatus))); connect(m_timerFile,SIGNAL(timeout()),this,SLOT(updateAstNowFile())); connect(m_syncClassViewAct,SIGNAL(triggered(bool)),this,SLOT(syncClassView(bool))); connect(m_syncOutlineAct,SIGNAL(triggered(bool)),this,SLOT(syncOutline(bool))); m_liteApp->extension()->addObject("LiteApi.IGolangAst",this); m_isSyncClassView = m_liteApp->settings()->value(GOLANGAST_CLASSVIEW_SYNCEDITOR,false).toBool(); m_syncClassViewAct->setChecked(m_isSyncClassView); m_isSyncOutline = m_liteApp->settings()->value(GOLANGAST_OUTLINE_SYNCEDITOR,false).toBool(); m_syncOutlineAct->setChecked(m_isSyncOutline); } GolangAst::~GolangAst() { if (m_timer->isActive()) { m_timer->stop(); } delete m_process; if (m_timerFile->isActive()) { m_timerFile->stop(); } delete m_processFile; m_liteApp->toolWindowManager()->removeToolWindow(m_projectAstWidget); m_liteApp->toolWindowManager()->removeToolWindow(m_stackedWidget); delete m_projectAstWidget; delete m_stackedWidget; } QIcon GolangAst::iconFromTag(const QString &tag, bool pub) const { return GolangAstIcon::instance()->iconFromTag(tag,pub); } QIcon GolangAst::iconFromTagEnum(LiteApi::ASTTAG_ENUM tag, bool pub) const { return GolangAstIcon::instance()->iconFromTagEnum(tag,pub); } void GolangAst::astProjectEnable(bool b) { if (b) { //loadProject(m_liteApp->projectManager()->currentProject()); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } QString fileName = editor->filePath(); if (!fileName.isEmpty()) { QFileInfo info(fileName); loadProjectPath(info.path()); } } } void GolangAst::astFileEnable(bool b) { if (b) { editorChanged(m_liteApp->editorManager()->currentEditor()); } } void GolangAst::setEnable(bool b) { if (b) { m_stackedWidget->setVisible(true); loadProject(m_liteApp->projectManager()->currentProject()); editorChanged(m_liteApp->editorManager()->currentEditor()); updateAst(); } else { //m_stackedWidget->setVisible(false); } } void GolangAst::projectChanged(LiteApi::IProject *project) { return; if (project) { m_projectAstWidget->clear(); } loadProject(project); if (project) { connect(project,SIGNAL(reloaded()),this,SLOT(projectReloaded())); } } void GolangAst::projectReloaded() { LiteApi::IProject *project = (LiteApi::IProject*)sender(); loadProject(project); } void GolangAst::loadProjectPath(const QString &path) { if (m_projectAstWidget->isHidden()) { return; } m_updateFileNames.clear(); m_updateFilePaths.clear(); QDir dir(path); if (!dir.exists()) { return; } foreach (QFileInfo info, dir.entryInfoList(QStringList()<<"*.go",QDir::Files)) { m_updateFileNames.append(info.fileName()); m_updateFilePaths.append(info.filePath()); } m_workPath = path; m_process->setWorkingDirectory(m_workPath); m_projectAstWidget->setWorkPath(m_workPath); updateAst(); /* if (project) { foreach(QString file, project->fileNameList()) { if (QFileInfo(file).suffix() == "go") { m_updateFileNames.append(file); } } foreach(QString file, project->filePathList()) { QFileInfo info(file); if (info.suffix() == "go") { m_updateFilePaths.append(info.filePath()); } } QFileInfo info(project->filePath()); if (info.isDir()) { m_workPath = info.filePath(); } else { m_workPath = info.path(); } m_process->setWorkingDirectory(m_workPath); m_projectAstWidget->setWorkPath(m_workPath); updateAst(); } else { m_projectAstWidget->clear(); } */ } void GolangAst::loadProject(LiteApi::IProject *project) { return; m_updateFileNames.clear(); m_updateFilePaths.clear(); if (project) { foreach(QString file, project->fileNameList()) { if (QFileInfo(file).suffix() == "go") { m_updateFileNames.append(file); } } foreach(QString file, project->filePathList()) { QFileInfo info(file); if (info.suffix() == "go") { m_updateFilePaths.append(info.filePath()); } } QFileInfo info(project->filePath()); if (info.isDir()) { m_workPath = info.filePath(); } else { m_workPath = info.path(); } m_process->setWorkingDirectory(m_workPath); m_projectAstWidget->setWorkPath(m_workPath); updateAst(); } else { m_projectAstWidget->clear(); } } void GolangAst::editorCreated(LiteApi::IEditor *editor) { AstWidget *w = m_editorAstWidgetMap.value(editor); if (w) { return; } if (editor) { QString fileName = editor->filePath(); if (!fileName.isEmpty()) { QFileInfo info(fileName); if (info.suffix() == "go") { AstWidget *w = new AstWidget(true,m_liteApp); w->setWorkPath(info.absolutePath()); m_stackedWidget->addWidget(w); m_editorAstWidgetMap.insert(editor,w); } } } } void GolangAst::editorAboutToClose(LiteApi::IEditor *editor) { AstWidget *w = m_editorAstWidgetMap.value(editor); if (w == 0) { return; } m_stackedWidget->removeWidget(w); m_editorAstWidgetMap.remove(editor); } void GolangAst::editorChanged(LiteApi::IEditor *editor) { m_editorFileName.clear(); m_editorFilePath.clear(); if (m_currentPlainTextEditor) { disconnect(m_currentPlainTextEditor,0,this,0); } m_currentEditor = editor; m_currentPlainTextEditor = LiteApi::getPlainTextEdit(editor); if (m_currentPlainTextEditor) { connect(m_currentPlainTextEditor,SIGNAL(cursorPositionChanged()),this,SLOT(editorPositionChanged())); } AstWidget *w = m_editorAstWidgetMap.value(editor); if (w) { m_stackedWidget->setCurrentWidget(w); } else { m_stackedWidget->setCurrentWidget(m_blankWidget); } if (editor) { QString fileName = editor->filePath(); if (!fileName.isEmpty()) { QFileInfo info(fileName); m_workPath = info.absolutePath(); if (info.suffix() == "go") { m_processFile->setWorkingDirectory(info.absolutePath()); m_editorFileName.append(info.fileName()); m_editorFilePath.append(info.filePath()); loadProjectPath(info.path()); } updateAstFile(); } } } void GolangAst::editorSaved(LiteApi::IEditor *editor) { if (editor) { QString fileName = editor->filePath(); QFileInfo info(fileName); if (!fileName.isEmpty() && info.suffix() == "go") { updateAstFile(); if (m_updateFilePaths.contains(info.filePath())) { updateAst(); } } } } void GolangAst::updateAst() { m_timer->start(1500); } void GolangAst::updateAstNow() { if (m_timer->isActive()) { m_timer->stop(); } if (m_updateFileNames.isEmpty()) { return; } QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "astview" << "-end"; args << "-todo"; args << "-sep" << m_astviewSep; args << "-tp"; args << m_updateFileNames; m_process->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); m_process->start(cmd,args); } void GolangAst::updateAstFile() { m_timerFile->start(1000); } void GolangAst::updateAstNowFile() { if (m_timerFile->isActive()) { m_timerFile->stop(); } if (m_editorFileName.isEmpty()) { return; } QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "astview" << "-end"; args << "-todo"; args << "-outline"; args << "-sep" << m_astviewSep; args << "-tp"; args << m_editorFileName; m_processFile->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); m_processFile->start(cmd,args); } void GolangAst::syncClassView(bool b) { m_isSyncClassView = b; m_liteApp->settings()->setValue(GOLANGAST_CLASSVIEW_SYNCEDITOR,m_isSyncClassView); } void GolangAst::syncOutline(bool b) { m_isSyncOutline = b; m_liteApp->settings()->setValue(GOLANGAST_OUTLINE_SYNCEDITOR,m_isSyncOutline); } void GolangAst::editorPositionChanged() { if (!m_currentEditor || !m_currentPlainTextEditor) { return; } QTextCursor cursor = m_currentPlainTextEditor->textCursor(); if (m_isSyncClassView && m_classViewToolAct->isChecked()) { m_projectAstWidget->trySyncIndex(m_currentEditor->filePath(),cursor.blockNumber(),cursor.positionInBlock()); } if (m_isSyncOutline && m_outlineToolAct->isChecked()) { AstWidget *w = m_editorAstWidgetMap.value(m_currentEditor); if (w) { w->trySyncIndex(m_currentEditor->filePath(),cursor.blockNumber(),cursor.positionInBlock()); } } } void GolangAst::finishedProcess(int code,QProcess::ExitStatus status) { if (code == 0 && status == QProcess::NormalExit) { // if (m_liteApp->projectManager()->currentProject()) { m_projectAstWidget->updateModel(m_process->readAllStandardOutput(),m_astviewSep); if (m_isSyncClassView && m_currentPlainTextEditor) { QTextCursor cursor = m_currentPlainTextEditor->textCursor(); m_projectAstWidget->trySyncIndex(m_currentEditor->filePath(),cursor.blockNumber(),cursor.positionInBlock()); } // } } else { //qDebug() << m_process->readAllStandardError(); } } void GolangAst::finishedProcessFile(int code,QProcess::ExitStatus status) { if (code == 0 && status == QProcess::NormalExit) { if (m_currentEditor) { AstWidget *w = m_editorAstWidgetMap.value(m_currentEditor); if (w) { w->updateModel(m_processFile->readAllStandardOutput(),m_astviewSep); if (m_isSyncOutline && m_currentPlainTextEditor) { QTextCursor cursor = m_currentPlainTextEditor->textCursor(); w->trySyncIndex(m_currentEditor->filePath(),cursor.blockNumber(),cursor.positionInBlock()); } } } } else { //qDebug() << m_process->readAllStandardError(); } }
14,924
C++
.cpp
413
30.157385
195
0.655053
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,370
golangastoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangast/golangastoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangastoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangastoption.h" #include "golangastoptionfactory.h" #include "golangast_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangAstOptionFactory::GolangAstOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GolangAstOptionFactory::mimeTypes() const { return QStringList() << OPTION_GOLANGAST; } LiteApi::IOption *GolangAstOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_GOLANGAST) { return new GolangAstOption(m_liteApp,this); } return 0; }
1,979
C++
.cpp
50
36.24
92
0.672566
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,371
golangsymbol.cpp
visualfc_liteide/liteidex/src/plugins/golangast/golangsymbol.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangsymbol.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangsymbol.h" #include "astwidget.h" #include "golangastitem.h" #include "golangast_global.h" #include <liteenvapi/liteenvapi.h> #include <QStandardItemModel> #include <QSortFilterProxyModel> #include <QProcess> #include <QFileInfo> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangSymbol::GolangSymbol(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpen(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); m_proxy = new QSortFilterProxyModel(this); m_proxy->setSourceModel(m_model); m_process = new QProcess(this); connect(m_process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finished(int,QProcess::ExitStatus))); m_matchCase = Qt::CaseInsensitive; m_importPath = true; m_astviewSep = ",,,"; } QString GolangSymbol::id() const { return "quickopen/golangsymbol"; } QString GolangSymbol::info() const { return tr("Quick Open Symbol by Name"); } QString GolangSymbol::placeholderText() const { return QString(); } void GolangSymbol::activate() { // m_liteApp->editorManager()->addNavigationHistory(); } QAbstractItemModel *GolangSymbol::model() const { return m_proxy; } QModelIndex GolangSymbol::rootIndex() const { return QModelIndex(); } void GolangSymbol::updateModel() { m_matchCase = m_liteApp->settings()->value(GOLANGAST_QUICKOPEN_SYMBOL_MATCHCASE,false).toBool()?Qt::CaseSensitive:Qt::CaseInsensitive; m_importPath = m_liteApp->settings()->value(GOLANGAST_QUICKOPNE_SYMBOL_IMPORTPATH,true).toBool(); m_model->clear(); m_proxy->setFilterCaseSensitivity(m_matchCase); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } QString filePath = editor->filePath(); if (filePath.isEmpty()) { return; } QFileInfo info(filePath); QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "astview"; args << "-outline"; args << "-sep" << m_astviewSep; args << "-tp"; args << info.fileName(); m_process->setWorkingDirectory(info.path()); m_process->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); m_process->start(cmd,args); } QModelIndex GolangSymbol::filterChanged(const QString &text) { m_proxy->setFilterFixedString(text); for (int i = 0; i < m_proxy->rowCount(); i++) { QModelIndex index = m_proxy->index(i,0); if (index.data().toString().startsWith(text,m_matchCase)) { gotoIndex(index,false); return index; } } return m_proxy->index(0,0); } bool GolangSymbol::gotoIndex(const QModelIndex &index,bool saveHistroy) { QModelIndex i = m_proxy->mapToSource(index); if (!i.isValid()) { return false; } GolangAstItem* item = (GolangAstItem*)m_model->itemFromIndex(i); if (item->m_posList.isEmpty()) { return false; } AstItemPos pos = item->m_posList.at(0); QFileInfo info(QDir(m_process->workingDirectory()),pos.fileName); LiteApi::gotoLine(m_liteApp,info.filePath(),pos.line-1,pos.column-1,true,saveHistroy); return true; } void GolangSymbol::indexChanged(const QModelIndex &index) { gotoIndex(index,false); } bool GolangSymbol::selected(const QString &/*text*/, const QModelIndex &index) { return gotoIndex(index,false); } void GolangSymbol::cancel() { } void GolangSymbol::finished(int code, QProcess::ExitStatus status) { if (code == 0 && status == QProcess::NormalExit) { QByteArray ar = m_process->readAll(); AstWidget::parserModel(m_model,ar,m_astviewSep,true,!m_importPath); LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); if (mgr) { mgr->modelView()->expandAll(); } } } GolangSymbolFactory::GolangSymbolFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IQuickOpenAdapter(parent), m_liteApp(app) { m_symbol = new GolangSymbol(app,this); } QStringList GolangSymbolFactory::mimeTypes() const { return QStringList() << "text/x-gosrc"; } LiteApi::IQuickOpen *GolangSymbolFactory::load(const QString &mimeType) { if (mimeType == "text/x-gosrc") { return m_symbol; } return 0; }
5,763
C++
.cpp
167
29.808383
139
0.669189
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,372
golangastplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangast/golangastplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangastplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangastplugin.h" #include "golangsymbol.h" #include "golangastoptionfactory.h" #include <QAction> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangAstPlugin::GolangAstPlugin() { } bool GolangAstPlugin::load(LiteApi::IApplication *app) { new GolangAst(app,this); LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(app); if (mgr) { LiteApi::IQuickOpenMimeType *symbol = mgr->registerQuickOpenMimeType("@"); if (symbol) { symbol->addAdapter(new GolangSymbolFactory(app,this)); } } app->optionManager()->addFactory(new GolangAstOptionFactory(app,this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,059
C++
.cpp
54
35.462963
82
0.6845
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,373
golangdoc.cpp
visualfc_liteide/liteidex/src/plugins/golangdoc/golangdoc.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangdoc.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangdoc.h" #include "litebuildapi/litebuildapi.h" #include "processex/processex.h" #include "fileutil/fileutil.h" #include "htmlutil/htmlutil.h" #include "golangapi/golangapi.h" #include "documentbrowser/documentbrowser.h" #include "qjson/include/QJson/Parser" #include "finddocwidget.h" #include "findapiwidget.h" #include <QListView> #include <QStringListModel> #include <QSortFilterProxyModel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QComboBox> #include <QToolBar> #include <QStatusBar> #include <QPushButton> #include <QMenu> #include <QAction> #include <QFile> #include <QDir> #include <QTextBrowser> #include <QUrl> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #endif #include <QPlainTextEdit> #include <QTextCursor> #include <QGroupBox> #include <QToolButton> #include <QTextCodec> #include <QTextCursor> #include <QDesktopServices> #include <QDomDocument> #include <QScrollBar> #include <QTextBlock> #include <QToolTip> #include <QTimer> #include <QDateTime> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end void ListViewEx::currentChanged(const QModelIndex &current, const QModelIndex&) { emit currentIndexChanged(current); } GolangDoc::GolangDoc(LiteApi::IApplication *app, QObject *parent) : LiteApi::IGolangDoc(parent), m_liteApp(app) { m_findProcess = new ProcessEx(this); m_godocProcess = new ProcessEx(this); m_findDocWidget = new FindDocWidget(m_liteApp); m_docSearchWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::BottomDockWidgetArea,m_findDocWidget,"GoDocSearch",tr("Go Doc Search"),true); m_findApiWidget = new FindApiWidget(m_liteApp); m_apiSearchWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::BottomDockWidgetArea,m_findApiWidget,"GoApiIndex",tr("Go Api Index"),true); connect(m_findApiWidget,SIGNAL(openApiUrl(QStringList)),this,SLOT(openApiUrl(QStringList))); m_docBrowser = new DocumentBrowser(m_liteApp,this); m_docBrowser->setName(tr("Godoc Search")); QStringList paths; paths << m_liteApp->resourcePath()+"/packages/go/godoc"; m_docBrowser->setSearchPaths(paths); m_godocFindComboBox = new QComboBox; m_godocFindComboBox->setMinimumWidth(100); m_godocFindComboBox->setEditable(true); //m_godocFindComboBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); m_docBrowser->toolBar()->addSeparator(); m_docBrowser->toolBar()->addWidget(new QLabel(tr("Find Package:"))); m_docBrowser->toolBar()->addWidget(m_godocFindComboBox); m_browserAct = m_liteApp->editorManager()->registerBrowser(m_docBrowser); m_liteApp->actionManager()->insertViewMenu(LiteApi::ViewMenuBrowserPos,m_browserAct); connect(m_apiSearchWindowAct,SIGNAL(toggled(bool)),this,SLOT(toggledApiSearchWindow(bool))); connect(m_docSearchWindowAct,SIGNAL(toggled(bool)),this,SLOT(toggledDocSearchWindow(bool))); connect(m_docBrowser,SIGNAL(requestUrl(QUrl)),this,SLOT(openUrl(QUrl))); connect(m_docBrowser,SIGNAL(linkHovered(QUrl)),this,SLOT(highlighted(QUrl))); connect(m_docBrowser,SIGNAL(documentLoaded()),this,SLOT(documentLoaded())); connect(m_docBrowser,SIGNAL(anchorChanged(QString)),this,SLOT(anchorChanged(QString))); connect(m_godocFindComboBox,SIGNAL(activated(QString)),this,SLOT(godocFindPackage(QString))); connect(m_godocProcess,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(godocOutput(QByteArray,bool))); connect(m_godocProcess,SIGNAL(extFinish(bool,int,QString)),this,SLOT(godocFinish(bool,int,QString))); connect(m_findProcess,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(findOutput(QByteArray,bool))); connect(m_findProcess,SIGNAL(extFinish(bool,int,QString)),this,SLOT(findFinish(bool,int,QString))); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); m_envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); if (m_envManager) { connect(m_envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); } m_liteApp->extension()->addObject("LiteApi.IGolangDoc",this); //m_liteApp->extension()->addObject("LiteApi.IGolangApi",m_golangApiThread); QString path = m_liteApp->resourcePath()+"/packages/go/godoc/godoc.html"; QFile file(path); if (file.open(QIODevice::ReadOnly)) { m_templateData = file.readAll(); file.close(); } QString about = m_liteApp->resourcePath()+"/packages/go/godoc/about.html"; QFileInfo info(about); if(info.exists()) { m_templateData.replace("{about}",info.filePath()); } QUrl url; url.setScheme("file"); url.setPath(info.filePath()); openUrl(url); } GolangDoc::~GolangDoc() { m_liteApp->settings()->setValue("golangdoc/goroot",m_goroot); if (m_docBrowser) { delete m_docBrowser; } delete m_findDocWidget; delete m_findApiWidget; } void GolangDoc::currentEnvChanged(LiteApi::IEnv*) { loadEnv(); // if (!m_bApiLoaded) { // return; // } //loadApi(); } void GolangDoc::loadEnv() { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp);//m_envManager->currentEnvironment(); // if (!LiteApi::hasGoEnv(env)) { // return; // } // m_godocCmd = FileUtil::lookupGoBin("godoc",m_liteApp,env,false); // m_findProcess->setEnvironment(env.toStringList()); // m_godocProcess->setEnvironment(env.toStringList()); // if (!m_godocCmd.isEmpty()) { // m_liteApp->appendLog("GolangDoc",QString("Found godoc at %1").arg(m_godocCmd),false); // } else { // m_liteApp->appendLog("GolangDoc",QString("Could not find godoc, (hint: is godoc installed?)"),true); // } m_pathFileMap.clear(); loadGoroot(); } void GolangDoc::loadGoroot() { m_goroot = LiteApi::getGOROOT(m_liteApp); if (m_goroot.isEmpty()) { return; } QDir dir(m_goroot); if (dir.exists() && dir.cd("doc")) { foreach(QFileInfo info, dir.entryInfoList(QStringList()<<"*.html",QDir::Files)) { QFile f(info.filePath()); if (f.open(QFile::ReadOnly)) { QByteArray line = f.read(1024); int start = line.indexOf("<!--"); if (start == 0 ) { int end = line.indexOf("-->"); if (end > start) { QByteArray jsonData = line.mid(start+4,end-start-4); QJson::Parser parser; bool ok = false; QVariant json = parser.parse(jsonData, &ok).toMap(); if (ok) { QVariantMap jsonMap = json.toMap(); if (jsonMap.contains("Path")) { m_pathFileMap.insert(jsonMap.value("Path").toString(),info.filePath()); } } } } } } } } void GolangDoc::activeBrowser() { m_liteApp->editorManager()->activeBrowser(m_docBrowser); } //void GolangDoc::rebuildApiData() //{ // if (!m_liteApp->globalCookie().value("golangdoc.goapi.rebuild").toBool()) { // QFileInfo info(m_findApiWidget->apiDataFile()); // if (!info.exists()) { // m_findApiWidget->rebuildApiData(); // } // QDateTime dt = info.lastModified(); // if (dt.toLocalTime().date() < QDate::currentDate()) { // m_findApiWidget->rebuildApiData(); // } // m_liteApp->globalCookie().value("golangdoc.goapi.rebuild",true); // } //} void GolangDoc::listPkg() { QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "docview" << "-mode=lite" << "-list=pkg"; m_findData.clear(); m_findProcess->start(cmd,args); } void GolangDoc::listCmd() { QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "docview" << "-mode" << "lite" << "-list"<<"cmd"; m_findData.clear(); m_findProcess->start(cmd,args); } void GolangDoc::godocFindPackage(QString pkgname) { if (pkgname.isEmpty()) { pkgname = m_godocFindComboBox->currentText(); } if (pkgname.isEmpty()) { return; } QUrl url; url.setScheme("find"); url.setPath(pkgname); openUrl(url); } //void GolangDoc::findPackage(QString pkgname) //{ // if (pkgname.isEmpty()) { // pkgname = m_findDocEdit->text(); // } // if (pkgname.isEmpty()) { // return; // } // QString cmd = LiteApi::liteide_stub_cmd(m_liteApp); // QStringList args; // args << "docview" << "-mode=lite" << "-find" << pkgname; // m_findData.clear(); // m_findProcess->start(cmd,args); //} void GolangDoc::findOutput(QByteArray data,bool bStderr) { if (bStderr) { return; } m_findData.append(data); } void GolangDoc::findFinish(bool error,int code,QString /*msg*/) { if (!error && code == 0) { QStringList array = QString(m_findData.trimmed()).split(','); if (array.size() >= 2 && array.at(0) == "$find") { array.removeFirst(); QString best = array.at(0); if (best.isEmpty()) { array.removeFirst(); } else { activeBrowser(); QUrl url; url.setScheme("pdoc"); url.setPath(best); openUrl(url); } // if (array.isEmpty()) { // m_findResultModel->setStringList(QStringList() << "<nofind>"); // } else { // m_findResultModel->setStringList(array); // } }/* else if (array.size() >= 1 && array.at(0) == "$list") { //array.removeFirst(); m_findResultModel->setStringList(array); }*/ } /*else { m_findResultModel->setStringList(QStringList() << "<error>"); }*/ } void GolangDoc::godocOutput(QByteArray data,bool bStderr) { if (bStderr) { QTextCodec *codec = QTextCodec::codecForName("utf8"); m_liteApp->appendLog("GolangDoc",codec->toUnicode(data),false); return; } m_godocData.append(data); } void GolangDoc::godocFinish(bool error,int code,QString /*msg*/) { if (!error && code == 0 && m_docBrowser != 0) { bool nav = true; QString header; if (m_openUrl.scheme() == "list") { nav = false; header = "Package List"; } else if (m_openUrl.scheme() == "find") { nav = false; header = "Find Package "+m_openUrl.path(); } else if (m_openUrl.scheme() == "pdoc") { nav = false; header = "Package "+m_openUrl.path(); } if (m_godocData.indexOf("<!--") == 0) { updateHtmlDoc(m_openUrl,m_godocData,header,nav); } else { updateTextDoc(m_openUrl,m_godocData,header); } } } void GolangDoc::updateTextDoc(const QUrl &url, const QByteArray &ba, const QString &header) { m_lastUrl = url; QTextCodec *codec = QTextCodec::codecForUtfText(ba,QTextCodec::codecForName("utf-8")); #if QT_VERSION >= 0x050000 QString html = codec->toUnicode(ba).toHtmlEscaped(); #else QString html = Qt::escape(codec->toUnicode(ba)); #endif QString data = m_templateData; data.replace("{header}",header); data.replace("{nav}",""); data.replace("{content}",QString("<pre>%1</pre>").arg(html)); m_docBrowser->setUrlHtml(url,data); } void GolangDoc::updateHtmlDoc(const QUrl &url, const QByteArray &ba, const QString &header, bool toNav) { m_lastUrl = url; if (m_lastUrl.scheme() == "pdoc") { m_targetList.clear(); QString pkgname = m_lastUrl.path(); QString goroot = LiteApi::getGOROOT(m_liteApp); QFileInfo i1(QFileInfo(goroot,"src/cmd").filePath(),pkgname); if (i1.exists()) { m_targetList.append(i1.filePath()); } QFileInfo i2(QFileInfo(goroot,"src/pkg").filePath(),pkgname); if (i2.exists()) { m_targetList.append(i2.filePath()); } else { QFileInfo i3(QFileInfo(goroot,"src").filePath(),pkgname); m_targetList.append(i3.filePath()); } foreach(QString path,LiteApi::getGOPATH(m_liteApp,false)) { QFileInfo info(QFileInfo(path,"src").filePath(),pkgname); if (info.exists()) { m_targetList.append(info.filePath()); } } } QTextCodec *codec = QTextCodec::codecForName("utf-8"); QString genHeader; QString nav; if (ba.contains("{{if $.GoogleCN}}")) { } QString content = HtmlUtil::docToNavdoc(codec->toUnicode(ba),genHeader,nav); QString data = m_templateData; if (genHeader.isEmpty()) { data.replace("{header}",header); } else { data.replace("{header}",genHeader); } if (toNav) { data.replace("{nav}",nav); } else { data.replace("{nav}",""); } data.replace("{content}",content); data.replace("#pkg-constants","#constants"); data.replace("#pkg-variables","#variables"); data.replace("id=\"pkg-constants\"","id=\"constants\""); data.replace("id=\"pkg-variables\"","id=\"variables\""); //hard code, clean go1.11 docs.html if (data.contains("{{if $.GoogleCN}}")) { data.replace("{{if $.GoogleCN}}",""); int i = data.indexOf(" A Tour of Go"); if (i > 0) { data.replace(i,13,""); } data.replace("{{if not $.GoogleCN}}",""); data.replace("{{else}}",""); data.replace("{{end}}",""); } if (!m_openUrlAddin.isNull()) { QString realPath = m_openUrlAddin.toString(); if (!realPath.isEmpty()) { data.replace(QString("import \"%1\"").arg(m_lastUrl.path()),QString("import \"%1\"").arg(realPath)); if (data.contains("import \".\"")) { QDir dir(m_lastUrl.path()); if (dir.exists()) { data.replace(QString("import \".\""),QString("import \"%1\"").arg(realPath)); } } } } m_docBrowser->setUrlHtml(url,data); } void GolangDoc::openUrlList(const QUrl &url) { if (url.scheme() != "list") { return; } QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "docview" << "-mode=html"<< QString("-list=%1").arg(url.path()); m_godocData.clear(); m_godocProcess->start(cmd,args); } void GolangDoc::openUrlFind(const QUrl &url) { if (url.scheme() != "find") { return; } QString cmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "docview" << "-mode=html" << "-find" << url.path(); m_godocData.clear(); m_godocProcess->start(cmd,args); return; } void GolangDoc::openUrlPdoc(const QUrl &url) { if (url.scheme() != "pdoc") { return; } // if (m_godocCmd.isEmpty()) { // QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); // m_godocCmd = FileUtil::lookupGoBin("godoc",m_liteApp,env,false); // } // if (m_godocCmd.isEmpty()) { // m_liteApp->appendLog("GolangDoc",QString("not lookup godoc in PATH"),true); // return; // } m_godocProcess->stopAndWait(100,2000); m_godocData.clear(); QString godocCmd = LiteApi::getGotools(m_liteApp); QStringList args; args << "godoc"; //check additional path bool local = false; QDir dir(url.path()); if (dir.exists()) { QStringList nameFilter("*.go"); if (!dir.entryList(nameFilter).isEmpty()) { local = true; } } if (local) { QStringList gopathList = LiteApi::getGOPATH(m_liteApp,true); QStringList pkgList; foreach (QString gopath, gopathList) { gopath = QDir::fromNativeSeparators(QDir::cleanPath(gopath)); QString urlpath = QDir::fromNativeSeparators(QDir::cleanPath(url.path())); if (urlpath.startsWith(gopath+"/src/")) { pkgList << urlpath.mid(gopath.length()+5); } } if (pkgList.size() == 1) { m_godocProcess->setWorkingDirectory(m_goroot); m_openUrl.setPath(pkgList.at(0)); args /*<< "-html=true"*/ << pkgList.at(0); } else { m_godocProcess->setWorkingDirectory(url.path()); args /*<< "-html=true"*/ << "."; } } else { m_godocProcess->setWorkingDirectory(m_goroot); args /*<< "-html=true"*/ << url.path(); } m_godocProcess->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); m_godocProcess->start(godocCmd,args); } void GolangDoc::openUrlFile(const QUrl &url) { QFileInfo info(url.toLocalFile()); if (!info.exists()) { info.setFile(url.path()); } QString ext = info.suffix().toLower(); if (ext == "html") { QFile file(info.filePath()); if (file.open(QIODevice::ReadOnly)) { QByteArray ba = file.readAll(); file.close(); if (info.fileName().compare("docs.html",Qt::CaseInsensitive) == 0) { updateHtmlDoc(url,ba,info.fileName(),false); } else { updateHtmlDoc(url,ba,info.fileName(),true); } } } else if (ext == "go") { LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(info.filePath(),true); if (!editor) { editor = m_liteApp->fileManager()->openEditor(info.filePath(),true); editor->setReadOnly(true); } else { m_liteApp->editorManager()->setCurrentEditor(editor); } if (editor) { QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); #if QT_VERSION >= 0x050000 if (ed && QUrlQuery(url).hasQueryItem("s")) { QStringList pos = QUrlQuery(url).queryItemValue("s").split(":"); #else if (ed && url.hasQueryItem("s")) { QStringList pos = url.queryItemValue("s").split(":"); #endif if (pos.length() == 2) { bool ok = false; int begin = pos.at(0).toInt(&ok); if (ok) { QTextCursor cur = ed->textCursor(); cur.setPosition(begin); ed->setTextCursor(cur); ed->centerCursor(); } } } } } else if (ext == "pdf") { QDesktopServices::openUrl(info.filePath()); } else { QFile file(info.filePath()); if (file.open(QIODevice::ReadOnly)) { QByteArray ba = file.readAll(); updateTextDoc(url,ba,info.fileName()); } } } QUrl GolangDoc::parserUrl(const QUrl &_url) { if (m_goroot.isEmpty()) { loadGoroot(); } QUrl url = _url; if (url.path().isEmpty() && !url.fragment().isEmpty()) { return url; } #ifdef Q_OS_WIN //fix windows "f:/hg/zmq" -> scheme="f" path="/hg/zmq" if (url.scheme().length() == 1) { QString path = QDir::fromNativeSeparators(url.toString()); QFileInfo info(path); url.setScheme(""); url.setPath(path); if (info.exists()) { if (info.isFile()) { url.setScheme("file"); } else if (info.isDir()) { url.setScheme("pdoc"); } } return url; } #endif if (!url.scheme().isEmpty()) { return url; } if (url.isRelative() && !url.path().isEmpty()) { if (m_pathFileMap.contains(url.path())) { url.setScheme("file"); url.setPath(m_pathFileMap.value(url.path())); } else if (url.path().compare("/src/pkg/") == 0 || url.path().compare("/pkg/") == 0) { url.setScheme("list"); url.setPath("pkg"); } else if (url.path().compare("/src/cmd/") == 0 || url.path().compare("/cmd/") == 0){ url.setScheme("list"); url.setPath("cmd"); } else if (url.path().indexOf("/pkg/") == 0) { url.setScheme("pdoc"); if (url.path().at(url.path().length()-1) == '/') { url.setPath(url.path().mid(5,url.path().length()-6)); } else { url.setPath(url.path().right(url.path().length()-5)); } } else if (url.path().indexOf("/cmd/") == 0) { url.setScheme("pdoc"); if (url.path().at(url.path().length()-1) == '/') { url.setPath(url.path().mid(5,url.path().length()-6)); } else { url.setPath(url.path().right(url.path().length()-5)); } } else if (url.path() == "..") { // check ".." is root if (m_lastUrl.scheme() == "pdoc") { QString path = QDir::cleanPath(m_lastUrl.path()+"/"+url.path()); if (path != "..") { url.setScheme("pdoc"); url.setPath(path); } } } else if (url.path().indexOf("/target/") == 0 && m_lastUrl.scheme() == "pdoc") { QString name = url.path().right(url.path().length()-8); foreach (QString path, m_targetList) { QFileInfo info(path,name); if (info.exists()) { url.setScheme("file"); url.setPath(info.filePath()); break; } } } else if (url.path().indexOf("/src/pkg/target/") == 0 && m_lastUrl.scheme() == "pdoc") { QString name = url.path().right(url.path().length()-16); foreach (QString path, m_targetList) { QFileInfo info(path,name); if (info.exists()) { url.setScheme("file"); url.setPath(info.filePath()); break; } } } else if (url.path().indexOf("/src/target/") == 0 && m_lastUrl.scheme() == "pdoc") { QString name = url.path().right(url.path().length()-12); foreach (QString path, m_targetList) { QFileInfo info(path,name); if (info.exists()) { url.setScheme("file"); url.setPath(info.filePath()); break; } } } else { QFileInfo info; info.setFile(url.path()); if (!info.exists()) { info.setFile(url.toLocalFile()); } if (!info.exists()) { QString path = url.path(); if (path.startsWith("/")) { if (path.endsWith(".go")) { QStringList gopathList = LiteApi::getGOPATH(m_liteApp,true); foreach (QString gopath, gopathList) { QFileInfo _info(gopath+path); if (_info.exists()) { info.setFile(_info.filePath()); break; } } } else { info.setFile(QDir(m_goroot),path.right(path.length()-1)); } } else if (m_lastUrl.scheme() == "file") { info.setFile(QFileInfo(m_lastUrl.toLocalFile()).absoluteDir(),path); } if (!info.exists()) { //fix godoc path="f:/hg/zmq/gozmq" "href=/gozmq/gozmq.go" if (m_lastUrl.scheme() == "pdoc") { QDir dir(m_lastUrl.path()); if (dir.exists()) { if (path.indexOf(dir.dirName()) == 1) { path.remove(0,dir.dirName().length()+2); } info.setFile(dir,path); } } } } //check index.html if (info.exists() && info.isDir()) { QFileInfo test(info.dir(),"index.html"); if (test.exists()) { info = test; } } if (info.exists() && info.isFile()) { url.setScheme("file"); url.setPath(QDir::cleanPath(info.filePath())); } else { url.setScheme("pdoc"); if (info.exists()) { url.setPath(info.filePath()); } else { if (m_lastUrl.scheme() == "pdoc" && url.path().endsWith('/')) { url.setPath(QDir::cleanPath(m_lastUrl.path()+"/"+url.path())); } else { url.setPath(url.path()); } } } } } return url; } void GolangDoc::highlighted(const QUrl &_url) { QUrl url = parserUrl(_url); m_liteApp->mainWindow()->statusBar()->showMessage(url.toString()); // if (_url.isEmpty()) { // m_docBrowser->statusBar()->showMessage(QString("GOROOT=%1").arg(m_goroot)); // } else { // QUrl url = parserUrl(_url); // m_docBrowser->statusBar()->showMessage(QString("%1 [%2]").arg(_url.toString()).arg(url.toString())); // } } void GolangDoc::openUrl(const QUrl &_url, const QVariant &addin) { m_liteApp->mainWindow()->statusBar()->clearMessage(); QUrl url = parserUrl(_url); /* if (url.scheme() != "file") { if (url.path().isEmpty() && !url.fragment().isEmpty()) { m_docBrowser->scrollToAnchor(url.fragment()); return; } if ( (m_openUrl.scheme() == url.scheme()) && m_openUrl.path() == url.path()) { m_docBrowser->scrollToAnchor(url.fragment()); m_openUrl = url; return; } } */ m_openUrl = url; m_openUrlAddin = addin; if (url.path().isEmpty() && !url.fragment().isEmpty()) { m_docBrowser->scrollToAnchor(url.fragment()); } else if (url.scheme() == "find") { openUrlFind(url); } else if (url.scheme() == "pdoc") { openUrlPdoc(url); } else if (url.scheme() == "list") { openUrlList(url); } else if (url.scheme() == "file") { openUrlFile(url); } else { QDesktopServices::openUrl(url); } } //void GolangDoc::findTag(const QString &tag) //{ // if (!tag.isEmpty()){ // QStringList urlList = m_golangApiThread->api()->findDocUrl(tag); // if (!urlList.isEmpty()) { // if (urlList.size() >= 2) { // m_docFind = urlList.at(1); // } else { // m_docFind.clear(); // } // QString text = urlList.at(0); // if (!text.isEmpty()) { // activeBrowser(); // QUrl url(QString("pdoc:%1").arg(text)); // openUrl(url); // } // } // } //} //void GolangDoc::doubleClickListView(QModelIndex index) //{ // //TODO // if (!index.isValid()) { // return; // } // QModelIndex src = m_findFilterModel->mapToSource(index); // if (!src.isValid()) { // return; // } // QString tag = m_findResultModel->data(src,Qt::DisplayRole).toString(); // if (!tag.isEmpty()){ // QStringList urlList;// = m_golangApiThread->api()->findDocUrl(tag); // if (!urlList.isEmpty()) { // if (urlList.size() >= 2) { // m_docFind = urlList.at(1); // } else { // m_docFind.clear(); // } // QString text = urlList.at(0); // if (!text.isEmpty()) { // activeBrowser(); // QUrl url(QString("pdoc:%1").arg(text)); // openUrl(url); // } // } // } //} //void GolangDoc::currentIndexChanged(QModelIndex index) //{ // if (!index.isValid()) { // return; // } // QModelIndex src = m_findFilterModel->mapToSource(index); // if (!src.isValid()) { // return; // } // QString tag = m_findResultModel->data(src,Qt::DisplayRole).toString(); // if (!tag.isEmpty()){ // //m_tagInfo->setText(m_golangApiThread->api()->findDocInfo(tag)); // } //} void GolangDoc::documentLoaded() { } void GolangDoc::anchorChanged(const QString &/*anchor*/) { if (!m_docFind.isEmpty()) { m_docBrowser->htmlWidget()->findText(m_docFind,QTextDocument::FindCaseSensitively|QTextDocument::FindWholeWords); m_docFind.clear(); } } void GolangDoc::openApiUrl(QStringList urlList) { if (urlList.isEmpty()) { return; } if (urlList.size() >= 2) { m_docFind = urlList.at(1); } else { m_docFind.clear(); } QString text = urlList.at(0); if (!text.isEmpty()) { activeBrowser(); QUrl url(QString("pdoc:%1").arg(text)); openUrl(url); } } void GolangDoc::appLoaded() { } void GolangDoc::toggledApiSearchWindow(bool /*b*/) { // if (b) { // rebuildApiData(); // } } void GolangDoc::toggledDocSearchWindow(bool /*b*/) { }
30,670
C++
.cpp
851
28.60517
154
0.560866
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,374
findapiwidget.cpp
visualfc_liteide/liteidex/src/plugins/golangdoc/findapiwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: findapiwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "findapiwidget.h" #include "liteenvapi/liteenvapi.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QToolButton> #include <QActionGroup> #include <QAction> #include <QPlainTextEdit> #include <QListView> #include <QStandardItemModel> #include <QStandardItem> #include <QTreeView> #include <QHeaderView> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FindApiThread::FindApiThread(QObject *parent) : QThread(parent) { m_bMatchCase = true; } FindApiThread::~FindApiThread() { stopFind(); } void FindApiThread::setRootPath(const QString &rootPath) { m_rootPath = rootPath; } void FindApiThread::findApi(const QString &text) { if (this->isRunning()) { this->terminate(); } m_text = text; this->start(); } void FindApiThread::stopFind() { this->terminate(); } void FindApiThread::setMatchCase(bool b) { m_bMatchCase = b; } void FindApiThread::findInFile(const QString &filePath, const QString &baseName) { QFile f(filePath); if (!f.open(QFile::ReadOnly)) { return; } QTextStream *stream = new QTextStream(&f); QRegExp reg("^pkg\\s([\\w\\-\\.\\/]+)(\\s\\(([\\w\\-]+)\\))?,\\s(\\w+)"); QRegExp regm("\\(\\*?([\\w\\-]+)\\)\\s*(\\w+)"); while (!stream->atEnd()) { QString line = stream->readLine(); int pos = reg.indexIn(line); if (pos < 0) { continue; } // 1 pkgname // 2 ? (system) // 3 ? system // 4 const|func|method|var|type QString pkgName = reg.cap(1); // if (!reg.cap(3).isEmpty()) { // pkg = reg.cap(2)+"."+pkg; // } // if (!lastPkg || lastPkg->name != pkgName) { // lastPkg = m_pkgs.findPackage(pkgName); // if (!lastPkg) { // lastPkg = new Package(pkgName); // m_pkgs.pkgList.append(lastPkg); // lastType = 0; // } // } QString right = line.mid(reg.cap().length()).trimmed(); QString findText; QStringList findUrl; QString flag = reg.cap(4); if (flag == "var") { ///pkg archive/tar, var ErrFieldTooLong error int pos = right.indexOf(" "); QString name = right.left(pos); if (pos != -1) { findText = pkgName+"."+name+" "+right.mid(pos+1); findUrl << pkgName+"#variables"<< name; } //if (pos != -1 && lastPkg->findValue(name) == 0) { // lastPkg->valueList.append(new Value(VarApi,name,right.mid(pos+1))); //} } else if (flag == "const") { //pkg syscall (windows-amd64), const ECOMM Errno int pos = right.indexOf(" "); QString name = right.left(pos); if (pos != -1) { QString exp = right.mid(pos+1); findText = pkgName+"."+name+" "+exp; //if (exp.startsWith("ideal-") || exp == "uint16") { findUrl << pkgName+"#constants" << name; // } else { // findUrl << pkgName+"."+name; // } } // if (pos != -1 && lastPkg->findValue(name) == 0) { // lastPkg->valueList.append(new Value(ConstApi,name,right.mid(pos+1))); // } } else if (flag == "func") { //pkg bytes, func FieldsFunc([]byte, func(rune) bool) [][]byte int pos = right.indexOf("("); QString name = right.left(pos); if (pos != -1) { findText = pkgName+"."+name+" "+right.mid(pos); findUrl << pkgName+"#"+name; } // if (pos != -1 && lastPkg->findValue(name) == 0) { // lastPkg->valueList.append(new Value(FuncApi,name,right.mid(pos))); // } } else if (flag == "method") { //pkg archive/tar, method (*Reader) Next() (*Header, error) //pkg archive/zip, method (*File) Open() (io.ReadCloser, error) //pkg bufio, method (ReadWriter) Available() int int pos = regm.indexIn(right); if (pos != -1) { QString typeName = regm.cap(1); QString name = regm.cap(2); QString exp = right.mid(regm.cap().length()).trimmed(); findText = pkgName+"."+typeName+"."+name+" "+exp; findUrl << pkgName+"#"+typeName+"."+name; // if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) { // lastType = lastPkg->findType(typeName); // if (!lastType) { // lastType = new Type(StructApi,typeName,"struct"); // lastPkg->typeList.append(lastType); // } // } // if (lastType->findValue(name) == 0) { // lastType->valueList.append(new Value(TypeMethodApi,name,exp)); // } } } else if (flag == "type") { //pkg go/ast, type ObjKind int //pkg archive/tar, type Header struct //pkg archive/tar, type Header struct, AccessTime time.Time //pkg container/heap, type Interface interface { Len, Less, Pop, Push, Swap } //pkg container/heap, type Interface interface, Len() int int pos = right.indexOf(" "); if (pos != -1) { QString typeName = right.left(pos); QString exp = right.mid(pos+1); if (exp == "struct") { findText = pkgName+"."+typeName+" "+exp; findUrl << pkgName+"#"+typeName; // lastType = lastPkg->findType(typeName); // if (!lastType) { // lastType = new Type(StructApi,typeName,exp); // lastPkg->typeList.append(lastType); // } } else if (exp.startsWith("struct,")) { QString last = exp.mid(7).trimmed(); int pos2 = last.indexOf(" "); if (pos2 != -1) { findText = pkgName+"."+typeName; // if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) { // lastType = lastPkg->findType(typeName); // if (!lastType) { // lastType = new Type(StructApi,typeName,"struct"); // lastPkg->typeList.append(lastType); // } // } QString name = last.left(pos2); if (name == "embedded") { QString emName = last.mid(pos2+1); findText = pkgName+"."+typeName+"."+emName; findUrl << pkgName+"#"+typeName << emName; // if (!lastType->embeddedList.contains(emName)) { // lastType->embeddedList.append(emName); // } } else { findText = pkgName+"."+typeName+"."+name+" "+last.mid(pos2+1); findUrl << pkgName+"#"+typeName << name; } /*else if (lastType->findValue(name) == 0){ lastType->valueList.append(new Value(TypeVarApi,name,last.mid(pos2+1))); }*/ } } else if (exp.startsWith("interface {")) { findText = pkgName+"."+typeName+" "+exp; findUrl << pkgName+"#"+typeName; // lastType = lastPkg->findType(typeName); // if (!lastType) { // lastType = new Type(InterfaceApi,typeName,exp); // lastPkg->typeList.append(lastType); // } } else if (exp.startsWith("interface,")) { QString last = exp.mid(10).trimmed(); int pos2 = last.indexOf("("); if (pos2 != -1) { // if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) { // lastType = lastPkg->findType(typeName); // if (!lastType) { // lastType = new Type(InterfaceApi,typeName,"struct"); // lastPkg->typeList.append(lastType); // } // } QString name = last.left(pos2); //if (lastType->findValue(name) == 0) { findText = pkgName+"."+typeName+"."+name+" "+last.mid(pos2); findUrl << pkgName+"#"+typeName+"."+name; //lastType->valueList.append(new Value(TypeMethodApi,name,last.mid(pos2))); //} } } else { findText = pkgName+"."+typeName+" "+exp; findUrl << pkgName+"#"+typeName; // lastType = lastPkg->findType(typeName); // if (!lastType) { // lastType = new Type(TypeApi,typeName,exp); // lastPkg->typeList.append(lastType); // } } } } if (findText.indexOf(m_text,0,m_bMatchCase?Qt::CaseSensitive:Qt::CaseInsensitive) >= 0) { emit findApiOut(line,baseName,line,findUrl); } } } void FindApiThread::run() { QDir dir(m_rootPath); if (!dir.exists()) { return; } QStringList names; names << "next.txt" << "except.txt" << "go*.txt"; foreach(QFileInfo info,dir.entryInfoList(names)) { findInFile(info.filePath(),info.completeBaseName()); } } FindApiWidget::FindApiWidget(LiteApi::IApplication *app, QWidget *parent) : QWidget(parent), m_liteApp(app) { m_findEdit = new FindApiEdit; m_findEdit->setPlaceholderText(tr("Search")); m_chaseWidget = new ChaseWidget; m_chaseWidget->setMinimumSize(QSize(16,16)); m_chaseWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); m_apiView = new QTreeView; m_model = new QStandardItemModel(this); m_model->setColumnCount(2); m_apiView->setModel(m_model); m_apiView->setEditTriggers(QTreeView::NoEditTriggers); m_apiView->setHeaderHidden(true); //#if QT_VERSION >= 0x050000 // m_apiView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //#else // m_apiView->header()->setResizeMode(QHeaderView::ResizeToContents); //#endif m_apiView->header()->setStretchLastSection(true); QToolButton *findBtn = new QToolButton; findBtn->setPopupMode(QToolButton::MenuButtonPopup); findBtn->setText(tr("Find")); QHBoxLayout *findLayout = new QHBoxLayout; findLayout->setMargin(2); findLayout->addWidget(m_findEdit); findLayout->addWidget(findBtn); findLayout->addWidget(m_chaseWidget); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setMargin(1); mainLayout->setSpacing(1); mainLayout->addLayout(findLayout); mainLayout->addWidget(m_apiView); this->setLayout(mainLayout); m_findThread = new FindApiThread(this); connect(m_findThread,SIGNAL(findApiOut(QString,QString,QString,QStringList)),this,SLOT(findApiOut(QString,QString,QString,QStringList))); connect(m_findThread,SIGNAL(finished()),this,SLOT(findApiFinished())); //connect(m_findThread,SIGNAL(terminated()),this,SLOT(findApiTerminated())); //connect(findBtn,SIGNAL(clicked()),this,SLOT(findApi())); connect(m_findEdit,SIGNAL(returnPressed()),this,SLOT(findApi())); //connect(m_findEdit,SIGNAL(rightButtonClicked()),m_findThread,SLOT(terminate())); connect(m_apiView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedApi(QModelIndex))); //m_rebuildThread = new ProcessEx(this); m_findAct = new QAction("Search",this); m_caseCheckAct = new QAction("Match case",this); m_caseCheckAct->setCheckable(true); //m_rebuildAct = new QAction(tr("Rebuild database"),this); QMenu *menu = new QMenu(tr("Find"),findBtn); menu->addAction(m_caseCheckAct); menu->addSeparator(); //menu->addAction(m_rebuildAct); findBtn->setMenu(menu); findBtn->setDefaultAction(m_findAct); connect(m_findAct,SIGNAL(triggered()),this,SLOT(findApi())); //connect(m_rebuildAct,SIGNAL(triggered()),this,SLOT(rebuildApiData())); m_caseCheckAct->setChecked(m_liteApp->settings()->value("goapisearch/match_case",true).toBool()); } FindApiWidget::~FindApiWidget() { m_liteApp->settings()->setValue("goapisearch/match_case",m_caseCheckAct->isChecked()); // if (m_rebuildThread->isRunning()) { // if (!m_rebuildThread->waitForFinished(10000)) { // m_rebuildThread->terminate(); // } // } } void FindApiWidget::findApi() { QString text = m_findEdit->text().trimmed(); if (text.length() <= 1) { return; } m_model->clear(); m_chaseWidget->setAnimated(true); m_findEdit->showStopButton(true); QString goroot = LiteApi::getGOROOT(m_liteApp); m_findThread->setRootPath(QFileInfo(goroot,"api").filePath()); m_findThread->setMatchCase(m_caseCheckAct->isChecked()); m_findThread->findApi(text); } void FindApiWidget::findApiOut(const QString &text, const QString &baseName, const QString &tipInfo, const QStringList &url) { QStandardItem *fitem = new QStandardItem(baseName); fitem->setData(url,Qt::UserRole+1); QStandardItem *item = new QStandardItem(text); item->setToolTip(tipInfo); //item->setData(url,Qt::UserRole+1); m_model->appendRow(QList<QStandardItem*>() << fitem << item); } void FindApiWidget::findApiFinished() { m_chaseWidget->setAnimated(false); m_findEdit->showStopButton(false); } void FindApiWidget::doubleClickedApi(QModelIndex index) { if (!index.isValid()) { return; } emit openApiUrl(index.sibling(index.row(),0).data(Qt::UserRole+1).toStringList()); } //void FindApiWidget::rebuildApiData() //{ // if (m_rebuildThread->isRunning()) { // return; // } // m_rebuildThread->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); // QString cmd = LiteApi::getGotools(m_liteApp); // m_rebuildThread->setWorkingDirectory(m_liteApp->storagePath()); // QStringList args; // args << "goapi" << "-o" << "golangapi.txt" << "all"; // m_rebuildThread->start(cmd,args); //} //QString FindApiWidget::apiDataFile() const //{ // return m_liteApp->storagePath()+"/golangapi.txt"; //}
16,160
C++
.cpp
385
35.316883
141
0.555196
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false