void SocketListener::onNewConnection() { JUFFENTRY; QLocalSocket* socket = server_->nextPendingConnection(); if ( !socket->waitForReadyRead(1000) ) { qDebug() << "Couldn't read data:" << socket->errorString(); return; } QByteArray data = socket->readAll(); JUFFDEBUG(QString::fromLocal8Bit(data)); if ( data.isEmpty() ) { return; } QStringList list = QString::fromLocal8Bit(data).split(";"); foreach (QString arg, list) { if ( arg[0] == '-' ) { if ( arg.compare("--newfile") == 0 ) { emit newFileRequested(); } } else { if ( !arg.isEmpty() ) emit fileRecieved(QFileInfo(arg).absoluteFilePath()); } } }
void LocalClient::run() { QLocalSocket *socket = new QLocalSocket(this); socket->connectToServer("/tmp/testservice"); if (!socket->waitForConnected()) { qDebug() << "could not connect to server: " << socket->errorString(); return; } 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())); // test bulk messages /* QJsonRpcMessage first = QJsonRpcMessage::createRequest("agent.testMethodWithParamsAndReturnValue", "testSendMessage"); m_client->sendMessage(first); QJsonRpcMessage second = QJsonRpcMessage::createRequest("agent.testMethodWithParamsAndReturnValue", "testSendMessages1"); QJsonRpcMessage third = QJsonRpcMessage::createRequest("agent.testMethodWithParamsAndReturnValue", "testSendMessages2"); m_client->sendMessage(QList<QJsonRpcMessage>() << second << third); */ }
void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); if (!socket) return; while (socket->bytesAvailable() < (int)sizeof(quint32)) socket->waitForReadyRead(); QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); if (got < 0) { qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } QString message(QString::fromUtf8(uMsg)); socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); delete socket; emit messageReceived(message); //### (might take a long time to return) }
bool SingleInstance::hasPrevious(const QString &name, const QStringList &args) { qDebug() << "Checking for previous instance..."; QLocalSocket socket; socket.connectToServer(name, QLocalSocket::ReadWrite); if (socket.waitForConnected()) { qDebug() << "Connection found!"; qDebug() << "Forwarding argument to existing instance..."; QByteArray buffer; for (auto item : args) { buffer.append(item+"\n"); } qDebug() << "Forwading buffer=" << buffer; socket.write(buffer); return true; } qDebug() << socket.errorString(); qDebug() << "No connection found"; return false; }
void ControlPeer::receiveConnection() { QLocalSocket* socket = p->server->nextPendingConnection(); if (!socket) { return; } while (socket->bytesAvailable() < (int)sizeof(quint32)) { socket->waitForReadyRead(); } QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); if (got < 0) { qWarning("Guzum.ControlPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } QString message(QString::fromUtf8(uMsg)); socket->write(ACK, qstrlen(ACK)); socket->waitForBytesWritten(1000); delete socket; // split message into the tokens, the format is the following: // <method_name>\n<arg0>\n<arg1> etc QStringList tokens = message.split("\n"); QString methodName = tokens[0]; if (methodName == SHOW_DIALOG_METHOD) { showFileSelectorDialog(); } else if (methodName == OPEN_FILE_METHOD) { if (tokens.size() == 2) { // just open file using default gnupg home QString filename = tokens[1]; editFile(filename); } else if (tokens.size() == 3) { // use file and custom gnupg home QString filename = tokens[1]; QString gnupgHome = tokens[2]; editFile(filename, gnupgHome); } QString filename = message.mid(qstrlen(OPEN_FILE_METHOD)+1); } }
void SingleApp::receiveMessage() { QLocalSocket *localSocket = localServer->nextPendingConnection(); if (!localSocket->waitForReadyRead(timeout)) { qDebug("%s", qPrintable(localSocket->errorString().toLatin1())); return; } QByteArray byteArray = localSocket->readAll(); QString message = QString::fromUtf8(byteArray.constData()); emit messageReceived(message); localSocket->disconnectFromServer(); }
HOOK_EVAL_API void hook_eval(char* str,unsigned long length) { QByteArray string(str,length); QLocalSocket socket; socket.connectToServer("phpdecoder"); if ( socket.waitForConnected(1000) ) { qDebug()<<"connected!"; qDebug()<<socket.write(string); qDebug()<<socket.waitForBytesWritten(1000); socket.close(); } else { qDebug()<<socket.error()<<socket.errorString(); } qDebug()<<string; }
void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); if (!socket) return; while (socket->bytesAvailable() < (int)sizeof(quint32)) socket->waitForReadyRead(); QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); if (got < 0) { qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString(); delete socket; return; } QString message(QString::fromUtf8(uMsg)); #ifdef Q_OS_WIN if (message == "qbt://pid") { qint64 pid = GetCurrentProcessId(); socket->write((const char *)&pid, sizeof pid); } else { socket->write(ack, qstrlen(ack)); } #else socket->write(ack, qstrlen(ack)); #endif socket->waitForBytesWritten(1000); delete socket; #ifdef Q_OS_WIN if (message == "qbt://pid") return; #endif emit messageReceived(message); //### (might take a long time to return) }
void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); if (!socket) return; // Why doesn't Qt have a blocking stream that takes care of this shait??? while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) { if (!socket->isValid()) // stale request return; socket->waitForReadyRead(1000); } QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); //qDebug() << "RCV: remaining" << remaining; do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; //qDebug() << "RCV: got" << got << "remaining" << remaining; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); //### error check: got<0 if (got < 0) { qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString(); delete socket; return; } // ### async this QString message = QString::fromUtf8(uMsg.constData(), uMsg.size()); socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); emit messageReceived(message, socket); // ##(might take a long time to return) }
void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); if (!socket) return; int client_id = this->client_seq ++; this->clients.insert(socket, client_id); QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage())); QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); return; // multi client long connection support while (socket->bytesAvailable() < (int)sizeof(quint32)) socket->waitForReadyRead(); QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); if (got < 0) { qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString(); delete socket; return; } QString message(QString::fromUtf8(uMsg)); socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); // delete socket; emit messageReceived(message); //### (might take a long time to return) }
void CLocalSvrCommunication::SocketError( QLocalSocket::LocalSocketError ) { QLocalSocket* pSocket = qobject_cast< QLocalSocket* >( sender( ) ); emit NotifyMsg( pSocket->errorString( ) ); }
ApplicationCore::ApplicationCore(TaskId startupTask, bool hideAtStart, QObject *parent) : QObject(parent) , m_actionStopAllTasks(this) , m_actionQuit(this) , m_actionAboutDialog(this) , m_actionPreferences(this) , m_actionExportToXml(this) , m_actionImportFromXml(this) , m_actionSyncTasks(this) , m_actionImportTasks(this) , m_actionExportTasks(this) , m_actionCheckForUpdates(this) , m_actionEnterVacation(this) , m_actionActivityReport(this) , m_actionWeeklyTimesheetReport(this) , m_actionMonthlyTimesheetReport(this) , m_uiElements( { &m_timeTracker, &m_tasksView, &m_eventView }), m_startupTask(startupTask) , m_hideAtStart(hideAtStart) #ifdef Q_OS_WIN , m_windowsJumpList(new QWinJumpList(this)) #endif , m_dateChangeWatcher(new DateChangeWatcher(this)) { // QApplication setup QApplication::setQuitOnLastWindowClosed(false); // application metadata setup // note that this modifies the behaviour of QSettings: QCoreApplication::setOrganizationName(QStringLiteral("KDAB")); QCoreApplication::setOrganizationDomain(QStringLiteral("kdab.com")); QCoreApplication::setApplicationName(QStringLiteral("Charm")); QCoreApplication::setApplicationVersion(CharmVersion()); QLocalSocket uniqueApplicationSocket; QString serverName(QStringLiteral("com.kdab.charm")); QString charmHomeEnv(QString::fromLocal8Bit(qgetenv("CHARM_HOME"))); if (!charmHomeEnv.isEmpty()) { serverName.append(QStringLiteral("_%1").arg( charmHomeEnv.replace(QRegExp(QLatin1String(":?/|:?\\\\")), QStringLiteral("_")))); } #ifndef NDEBUG serverName.append(QStringLiteral("_debug")); #endif uniqueApplicationSocket.connectToServer(serverName, QIODevice::ReadWrite); if (uniqueApplicationSocket.waitForConnected(1000)) { QByteArray command; if (startupTask != -1) { command = StartTaskCommand + QByteArray::number(startupTask); } else { command = RaiseWindowCommand; } command += '\n'; qint64 written = uniqueApplicationSocket.write(command); if (written == -1 || written != command.length()) { qWarning() << "Failed to pass " << command << " to running charm instance, error: " << uniqueApplicationSocket.errorString(); } uniqueApplicationSocket.flush(); uniqueApplicationSocket.waitForBytesWritten(); throw AlreadyRunningException(); } connect(&m_uniqueApplicationServer, &QLocalServer::newConnection, this, &ApplicationCore::slotHandleUniqueApplicationConnection, Qt::QueuedConnection); QFile::remove(QDir::tempPath() + QLatin1Char('/') + serverName); bool listening = m_uniqueApplicationServer.listen(serverName); if (!listening) qDebug() << "Failed to create QLocalServer for unique application support:" << m_uniqueApplicationServer.errorString(); Q_INIT_RESOURCE(CharmResources); Q_ASSERT_X(m_instance == 0, "Application ctor", "Application is a singleton and cannot be created more than once"); m_instance = this; qRegisterMetaType<State>("State"); qRegisterMetaType<Event>("Event"); // exit process (app will only exit once controller says it is ready) connect(&m_controller, &Controller::readyToQuit, this, &ApplicationCore::slotControllerReadyToQuit); connectControllerAndModel(&m_controller, m_model.charmDataModel()); Charm::connectControllerAndView(&m_controller, &m_timeTracker); // save the configuration (configuration is managed by the application) connect(&m_timeTracker, &CharmWindow::saveConfiguration, this, &ApplicationCore::slotSaveConfiguration); connect(&m_timeTracker, &TimeTrackingWindow::showNotification, this, &ApplicationCore::slotShowNotification); connect(&m_timeTracker, &TimeTrackingWindow::taskMenuChanged, this, &ApplicationCore::slotPopulateTrayIconMenu); // save the configuration (configuration is managed by the application) connect(&m_tasksView, &TasksView::saveConfiguration, this, &ApplicationCore::slotSaveConfiguration); // due to multiple inheritence we can't use the new style connects here connect(&m_tasksView, SIGNAL(emitCommand(CharmCommand*)), &m_timeTracker, SLOT(sendCommand(CharmCommand*))); connect(&m_tasksView, SIGNAL(emitCommandRollback(CharmCommand*)), &m_timeTracker, SLOT(sendCommandRollback(CharmCommand*))); connect(&m_eventView, SIGNAL(emitCommand(CharmCommand*)), &m_timeTracker, SLOT(sendCommand(CharmCommand*))); connect(&m_eventView, SIGNAL(emitCommandRollback(CharmCommand*)), &m_timeTracker, SLOT(sendCommandRollback(CharmCommand*))); // my own signals: connect(this, &ApplicationCore::goToState, this, &ApplicationCore::setState, Qt::QueuedConnection); // system tray icon: m_actionStopAllTasks.setText(tr("Stop Current Task")); m_actionStopAllTasks.setShortcut(Qt::Key_Escape); m_actionStopAllTasks.setShortcutContext(Qt::ApplicationShortcut); mainView().addAction(&m_actionStopAllTasks); // for the shortcut to work connect(&m_actionStopAllTasks, &QAction::triggered, this, &ApplicationCore::slotStopAllTasks); m_systrayContextMenu.addAction(&m_actionStopAllTasks); m_systrayContextMenu.addSeparator(); m_systrayContextMenu.addAction(m_timeTracker.openCharmAction()); m_systrayContextMenu.addAction(&m_actionQuit); m_trayIcon.setContextMenu(&m_systrayContextMenu); m_trayIcon.setToolTip(tr("No active events")); m_trayIcon.setIcon(Data::charmTrayIcon()); m_trayIcon.show(); QApplication::setWindowIcon(Data::charmIcon()); // set up actions: m_actionQuit.setShortcut(Qt::CTRL + Qt::Key_Q); m_actionQuit.setText(tr("Quit")); m_actionQuit.setIcon(Data::quitCharmIcon()); connect(&m_actionQuit, &QAction::triggered, this, &ApplicationCore::slotQuitApplication); m_actionAboutDialog.setText(tr("About Charm")); connect(&m_actionAboutDialog, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotAboutDialog); m_actionPreferences.setText(tr("Preferences")); m_actionPreferences.setIcon(Data::configureIcon()); connect(&m_actionPreferences, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotEditPreferences); m_actionPreferences.setEnabled(true); m_actionImportFromXml.setText(tr("Import Database from Previous Export...")); connect(&m_actionImportFromXml, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotImportFromXml); m_actionExportToXml.setText(tr("Export Database...")); connect(&m_actionExportToXml, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotExportToXml); m_actionSyncTasks.setText(tr("Update Task Definitions...")); //the signature of QAction::triggered does not match slotSyncTasks connect(&m_actionSyncTasks,&QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotSyncTasksVerbose); m_actionImportTasks.setText(tr("Import and Merge Task Definitions...")); connect(&m_actionImportTasks, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotImportTasks); m_actionExportTasks.setText(tr("Export Task Definitions...")); connect(&m_actionExportTasks, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotExportTasks); m_actionCheckForUpdates.setText(tr("Check for Updates...")); #if 0 // TODO this role should be set to have the action in the app menu, but that // leads to duplicated entries, as each of the three main windows adds the action to the menu // and Qt doesn't prevent duplicates (#222) m_actionCheckForUpdates.setMenuRole(QAction::ApplicationSpecificRole); #endif connect(&m_actionCheckForUpdates, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotCheckForUpdatesManual); m_actionEnterVacation.setText(tr("Enter Vacation...")); connect(&m_actionEnterVacation, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotEnterVacation); m_actionActivityReport.setText(tr("Activity Report...")); m_actionActivityReport.setShortcut(Qt::CTRL + Qt::Key_A); connect(&m_actionActivityReport, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotActivityReport); m_actionWeeklyTimesheetReport.setText(tr("Weekly Timesheet...")); m_actionWeeklyTimesheetReport.setShortcut(Qt::CTRL + Qt::Key_R); connect(&m_actionWeeklyTimesheetReport, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotWeeklyTimesheetReport); m_actionMonthlyTimesheetReport.setText(tr("Monthly Timesheet...")); m_actionMonthlyTimesheetReport.setShortcut(Qt::CTRL + Qt::Key_M); connect(&m_actionMonthlyTimesheetReport, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotMonthlyTimesheetReport); // set up idle detection m_idleDetector = IdleDetector::createIdleDetector(this); Q_ASSERT(m_idleDetector); connect(m_idleDetector, SIGNAL(maybeIdle()), SLOT(slotMaybeIdle())); setHttpActionsVisible(Lotsofcake::Configuration().isConfigured()); // add default plugin path for deployment QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath() + QStringLiteral("/plugins")); if (QCoreApplication::applicationDirPath().endsWith(QLatin1String("MacOS"))) QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath() + QStringLiteral("/../plugins")); // set up command interface #ifdef CHARM_CI_SUPPORT m_cmdInterface = new CharmCommandInterface(this); #endif // CHARM_CI_SUPPORT // Ladies and gentlemen, please raise upon your seats - // the show is about to begin: emit goToState(StartingUp); }
// Process incoming IPC command. First check if monero-wallet-gui is // already running. If it is, send it to that instance instead, if not, // queue the command for later use inside our QML engine. Returns true // when queued, false if sent to another instance, at which point we can // kill the current process. bool IPC::saveCommand(QString cmdString){ qDebug() << QString("saveCommand called: %1").arg(cmdString); QLocalSocket ls; QByteArray buffer; buffer = buffer.append(cmdString); QString socketFilePath = this->socketFile().filePath(); ls.connectToServer(socketFilePath, QIODevice::WriteOnly); if(ls.waitForConnected(1000)){ ls.write(buffer); if (!ls.waitForBytesWritten(1000)){ qDebug() << QString("Could not send command \"%1\" over IPC %2: \"%3\"").arg(cmdString, socketFilePath, ls.errorString()); return false; } qDebug() << QString("Sent command \"%1\" over IPC \"%2\"").arg(cmdString, socketFilePath); return false; } if(ls.isOpen()) ls.disconnectFromServer(); // Queue for later this->SetQueuedCmd(cmdString); return true; }