Ejemplo n.º 1
0
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
    bool fResult = false;
    for (const QString& r : savedPaymentRequests)
    {
        QLocalSocket* socket = new QLocalSocket();
        socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
        if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
        {
            delete socket;
            socket = nullptr;
            return false;
        }

        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_0);
        out << r;
        out.device()->seek(0);

        socket->write(block);
        socket->flush();
        socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
        socket->disconnectFromServer();

        delete socket;
        socket = nullptr;
        fResult = true;
    }

    return fResult;
}
Ejemplo n.º 2
0
void IPCEngineHost::rpcCall(Function f, QByteArray payload)
{
    if (m_localGuest) {
        QMetaObject::invokeMethod(m_localGuest,
                "rpcCallback",
                Qt::QueuedConnection,
                Q_ARG(quint64, f),
                Q_ARG(QByteArray, payload));
    } else if (m_device) {
        QByteArray header;
        {
            QDataStream s(&header, QIODevice::WriteOnly);
            SET_NATIVE_BYTE_ORDER(s);
            s << m_cookie++;
            s << (quint64) f;
            s << (quint64) payload.size();
        }
        m_device->write(header);
        m_device->write(payload);
        m_device->putChar('T');
        QLocalSocket *sock = qobject_cast<QLocalSocket *>(m_device);
        if (sock)
            sock->flush();
    }
}
Ejemplo n.º 3
0
bool N810GpsPlugin::sendToGpsDriverCtrl(QString cmd)
{
    QLocalSocket *gpsCtrlSocket;
    gpsCtrlSocket = new QLocalSocket(this);

    QByteArray socketPath = ( "/var/lib/gps/gps_driver_ctrl");
    gpsCtrlSocket->connectToServer(socketPath.data());

    if(gpsCtrlSocket->waitForConnected()) {
        qLog(Hardware)<< __PRETTY_FUNCTION__ << "connected" << cmd;

        QByteArray data;
        data.append(cmd);
        data.append("\n");
        gpsCtrlSocket->write(data);


        gpsCtrlSocket->flush();
        gpsCtrlSocket->disconnectFromServer();
        return true;
    } else {
        qLog(Hardware) << __PRETTY_FUNCTION__ << "Could not connect to socket" << gpsCtrlSocket;
    }
    return false;
}
Ejemplo n.º 4
0
bool MonavRunnerPrivate::retrieveData( const RouteRequest *route, const QString &mapDir, RoutingResult* reply ) const
{
    QLocalSocket socket;
    socket.connectToServer( "MoNavD" );
    if ( socket.waitForConnected() ) {
        if ( m_plugin->monavVersion() == MonavPlugin::Monav_0_3 ) {
            CommandType commandType;
            commandType.value = CommandType::RoutingCommand;
            commandType.post( &socket );
        }

        RoutingCommand command;
        QVector<Node> waypoints;

        for ( int i = 0; i < route->size(); ++i ) {
            Node coordinate;
            coordinate.longitude = route->at( i ).longitude( GeoDataCoordinates::Degree );
            coordinate.latitude = route->at( i ).latitude( GeoDataCoordinates::Degree );
            waypoints << coordinate;
        }

        command.dataDirectory = mapDir;
        command.lookupRadius = 1500;
        command.waypoints = waypoints;
        command.lookupStrings = true;

        command.post( &socket );
        socket.flush();

        if ( reply->read( &socket ) ) {
            switch ( reply->type ) {
            case RoutingResult::LoadFailed:
                mDebug() << "failed to load monav map from " << mapDir;
                return false;
                break;
            case RoutingResult::RouteFailed:
                mDebug() << "failed to retrieve route from monav daemon";
                return false;
                break;
            case RoutingResult::TypeLookupFailed:
                mDebug() << "failed to lookup type from monav daemon";
                return false;
                break;
            case RoutingResult::NameLookupFailed:
                mDebug() << "failed to lookup name from monav daemon";
                return false;
                break;
            case RoutingResult::Success:
                return true;
            }
        } else {
            mDebug() << "Failed to read reply";
        }
    } else {
        mDebug() << "No connection to MoNavD";
    }

    return false;
}
void YACReaderLocalServer::sendResponse()
{
	/*QLocalSocket *clientConnection = localServer->nextPendingConnection();

    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    QDataStream in(clientConnection);
    in.setVersion(QDataStream::Qt_4_0);

    if (clientConnection->bytesAvailable() == 0)
		return;
 
    if (in.atEnd())
        return;

    QString message;
    in >> message;

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << QString("OK");

    clientConnection->write(block);
    clientConnection->flush();
    clientConnection->disconnectFromServer();*/

	     QByteArray block;
     QDataStream out(&block, QIODevice::WriteOnly);
     out.setVersion(QDataStream::Qt_4_0);
     out << (quint16)0;
     out << QString("ok");
     out.device()->seek(0);
     out << (quint16)(block.size() - sizeof(quint16));

     QLocalSocket *clientConnection = localServer->nextPendingConnection();
     connect(clientConnection, SIGNAL(disconnected()),
             clientConnection, SLOT(deleteLater()));

     clientConnection->write(block);
     clientConnection->flush();
     clientConnection->disconnectFromServer();

}
Ejemplo n.º 6
0
void Server::sendFortune()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint16)0;
    out << fortunes.at(qrand() % fortunes.size());
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    QLocalSocket *clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->flush();
    clientConnection->disconnectFromServer();
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{

#if QT_NO_DEBUG
    QLocalSocket socket;
    socket.connectToServer(SERVER);
    if(socket.waitForConnected(1000))
    {
        if (argc == 2)
        {

            socket.write(argv[1]);
            socket.flush();
            socket.waitForBytesWritten();

        }
        socket.disconnectFromServer();

        exit(0);
    }
    else
    {
        if (argc != 1)
            exit(0);

    }
#endif

    QApplication a(argc, argv);
    MainWindow w;





    QTranslator translator ;
    translator.load("/usr/share/qt/translations/qt_cs");
    a.installTranslator(&translator);

    //w.show();
    
    return a.exec();

}
Ejemplo n.º 8
0
void qt_flushOutBuffer()
{
	if (!qt_initialized)
		return;

	// Write the block size at the beginning of the bock
	QDataStream sizeStream(&qt_socket);
	sizeStream << (quint32)(qt_outBuffer.size());
	// Write the block to the QLocalSocket
	qt_socket.write(qt_outBuffer);
	// waitForBytesWritten(-1) is supposed implement this loop, but it does not seem to work !
	// update: seems to work with Qt 4.5
	while (qt_socket.bytesToWrite() > 0)
	{
		qt_socket.flush();
		qt_socket.waitForBytesWritten(-1);
	}
	// Reset the buffer
	qt_out.device()->seek(0);
	qt_outBuffer.clear();
}
Ejemplo n.º 9
0
size_t callback_read_file(void *ptr, size_t size, size_t nmemb, void *userp)
{
    // qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<size<<nmemb<<userp;

    size_t tlen = size * nmemb, rlen = 0;
    QBuffer strbuf;
    QByteArray line;
    int n = 0, wlen = 0;

    CurlFtp *ftp = static_cast<CurlFtp*>(userp);
    QLocalSocket *router = ftp->getDataSock2();

    strbuf.setData((const char*)ptr, tlen);
    strbuf.open(QBuffer::ReadOnly);
    // Q_ASSERT(strbuf.canReadLine()); //  ???
    rlen = 0;
    while (!strbuf.atEnd()) {
        if (strbuf.canReadLine()) {
            line = strbuf.readLine();
        } else {
            line = strbuf.readAll();
        }
        rlen += line.length();
        wlen = router->write(line);
        // qDebug()<<"Line: "<<n++<<line.length()<<wlen;
        // fprintf(stdout, "%s", ".");
        // fflush(stdout);
        Q_ASSERT(line.length() == wlen);
        // break;
    }
    strbuf.close();
    router->flush();

    // qDebug()<<"can rw:"<<router->isReadable()<<router->isWritable()<<router->isOpen();
    // fprintf(stdout, "route read file:. %p %d %s", router, router->bytesAvailable(), "\n");
    fflush(stdout);

    return rlen;
    return 0;
}
Ejemplo n.º 10
0
bool mASocketManager::openFileOnRemote(const QString &_path)
{
    bool r = false;
    
    QString path = QFileInfo(_path).canonicalFilePath();
    path.append('\n');
    
    QLocalSocket socket;
    socket.connectToServer(MA_LOCAL_SERVER_NAME);
    
    if(socket.waitForConnected(MAX_TIMEOUT_CLIENT))
    {
        socket.write(path.toUtf8());
        socket.flush();
        socket.waitForBytesWritten(MAX_TIMEOUT_CLIENT);
        r = true;
    }
    
    socket.close();
    
    return r;
}
Ejemplo n.º 11
0
int main( int argc, char *argv[] ) {
	CommandType commandType;
	UnpackCommand unpackCommand;
	RoutingCommand routingCommand;
	routingCommand.lookupStrings = true;

	if ( !processArguments( &commandType, &unpackCommand, &routingCommand, argc, argv ) ) {
		qDebug() << "usage:" << argv[0] << "data-directory latitude1 longitude1 latitude2 longitude2 [...latitudeN longitudeN]";
		qDebug() << "\tcomputes a route using between the specified waypoints";
		qDebug() << "usage:" << argv[0] << "monav-map-module-file";
		qDebug() << "\tunpacks a map module";
		return 1;
	}

	QLocalSocket connection;
	connection.connectToServer( "MoNavD" );
	if ( !connection.waitForConnected() ) {
		qDebug() << "failed to connect to daemon:" << connection.error();
		return 2;
	}

	commandType.post( &connection );

	if ( commandType.value == CommandType::UnpackCommand ) {
		unpackCommand.post( &connection );
		connection.flush();
		UnpackResult reply;
		reply.type = UnpackResult::FailUnpacking;
		reply.read( &connection );
		qDebug() << connection.state();

		if ( reply.type == UnpackResult::FailUnpacking ) {
			qDebug() << "failed to unpack map file";
			return 3;
		}
		qDebug() << "finished unpacking map file";
		return 0;
	}

	routingCommand.post( &connection );
	connection.flush();
	RoutingResult reply;
	reply.read( &connection );
	qDebug() << connection.state();

	if ( reply.type == RoutingResult::LoadFailed ) {
		qDebug() << "failed to load data directory";
		return 3;
	} else if ( reply.type == RoutingResult::RouteFailed ) {
		qDebug() << "failed to compute route";
		return 3;
	} else if ( reply.type == RoutingResult::NameLookupFailed ) {
		qDebug() << "failed to compute route";
		return 3;
	} else if ( reply.type == RoutingResult::TypeLookupFailed ) {
		qDebug() << "failed to compute route";
		return 3;
	}else if ( reply.type == RoutingResult::Success ) {
		int seconds = reply.seconds;
		qDebug() << "distance:" << seconds / 60 / 60 << "h" << ( seconds / 60 ) % 60 << "m" << seconds % 60 << "s";
		qDebug() << "nodes:" << reply.pathNodes.size();
		qDebug() << "edges:" << reply.pathEdges.size();

		unsigned node = 0;
		for ( int i = 0; i < reply.pathEdges.size(); i++ ) {
			QString name = reply.nameStrings[reply.pathEdges[i].name];
			QString type = reply.typeStrings[reply.pathEdges[i].type];
			qDebug() << "name:" << name.toUtf8() << "type:" << type << "nodes:" << reply.pathEdges[i].length + 1 << "seconds:" << reply.pathEdges[i].seconds << "branching possible:" << reply.pathEdges[i].branchingPossible;
			for ( unsigned j = 0; j <= reply.pathEdges[i].length; j++ ) {
				QString latitude, longitude;
				latitude.setNum( reply.pathNodes[j + node].latitude, 'g', 10 );
				longitude.setNum( reply.pathNodes[j + node].longitude, 'g', 10 );
				qDebug() << latitude.toLatin1().data() << longitude.toLatin1().data();
			}
			node += reply.pathEdges[i].length;
		}
	} else {
		qDebug() << "return value not recognized";
		return 5;
	}
}
Ejemplo n.º 12
0
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);
}