Пример #1
0
bool KNSingletonApplication::sendMessages(const QString &uniqueKey,
                                          const QStringList &messages)
{
    //Create sender client.
    QLocalSocket client;
    //Link to the server which is listening to the unique key.
    client.connectToServer(uniqueKey, QIODevice::WriteOnly);
    //If connecting failed, return false.
    if(!client.waitForConnected(TimeoutLimit))
    {
        qDebug("Cannot connect to the local server.");
        //Disconnect from the server.
        client.disconnectFromServer();
        return false;
    }
    //Generate the message data.
    QByteArray messageData;
    QDataStream dataWriter(&messageData, QIODevice::WriteOnly);
    dataWriter << messages;
    //Send the data to local server.
    client.write(messageData);
    //Check sending status.
    if(!client.waitForBytesWritten(TimeoutLimit))
    {
        qDebug("Send arguments failed.");
        client.disconnectFromServer();
        return false;
    }
    //Send the arguments success.
    client.disconnectFromServer();
    return true;
}
Пример #2
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;
}
Пример #3
0
void qt_connectToServer()
{
	if (!qt_initialized)
		return;

	// Determine to which server we should connect
	QString server = qt_localServerName;
	if (!qt_optionWidget.isEmpty())
		server = qt_optionWidget;

	// Check if we are already connected
	if (qt_socket.serverName() == server)
		return;

	// Disconnect
	if (qt_socket.state() == QLocalSocket::ConnectedState)
	{
		qt_socket.disconnectFromServer();
		qt_socket.waitForDisconnected(1000);
	}

	// Connect to server, or local server if not available.
	qt_socket.connectToServer(server);
	if (!qt_socket.waitForConnected(3000))
		while (qt_socket.state() != QLocalSocket::ConnectedState)
			qt_socket.connectToServer(qt_localServerName);
}
Пример #4
0
// Called before a plot to connect to the terminal window, if needed
void qt_connectToServer()
{
	if (!qt_initialized)
		return;

	// Determine to which server we should connect
	bool connectToWidget = !qt_optionWidget.isEmpty();
	QString server = connectToWidget ? qt_optionWidget : qt_localServerName;

	if (qt_socket.state() == QLocalSocket::ConnectedState)
	{
		// Check if we are already connected to the correct server
		if (qt_socket.serverName() == server)
			return;

		// Otherwise disconnect
		qt_socket.disconnectFromServer();
		while (qt_socket.state() == QLocalSocket::ConnectedState)
			qt_socket.waitForDisconnected(1000);
	}

	// Start the gnuplot_qt helper program if not already started
	if (!connectToWidget && !qt_gnuplot_qtStarted)
		execGnuplotQt();

	// Connect to the server, or local server if not available.
	qt_connectToServer(server);
}
Пример #5
0
// 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;
}
Пример #6
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;
}
Пример #7
0
bool LH_QtPlugin_WebKit::sendQuit()
{
    QLocalSocket sock;
    sock.connectToServer("LCDHost_WebKitServer");
    if( !sock.waitForConnected(100) ) return false;
    WebKitCommand('Q').write(&sock);
    sock.waitForBytesWritten(100);
    sock.disconnectFromServer();
    return true;
}
Пример #8
0
bool
socket_test_connect(QString server, int timeout)
{
  QLocalSocket sock;
  sock.connectToServer(server);
  if (!sock.waitForConnected(timeout)) {
    return false;
  }
  sock.disconnectFromServer();
  return true;
}
Пример #9
0
bool DebugEngine::tryConnect()
{
    QLocalSocket localSocket;
    localSocket.connectToServer(ExtraSocket::pathSocket(ULTRACOPIER_SOCKETNAME),QIODevice::WriteOnly|QIODevice::Unbuffered);
    if(localSocket.waitForConnected(1000))
    {
        localSocket.disconnectFromServer();
        return true;
    }
    else
        return false;
}
Пример #10
0
bool DebugEngine::tryConnect()
{
    ULTRACOPIER_DEBUGCONSOLE(DebugLevel_custom_Notice,"start");
    QLocalSocket localSocket;
    localSocket.connectToServer(ExtraSocket::pathSocket(ULTRACOPIER_SOCKETNAME),QIODevice::WriteOnly|QIODevice::Unbuffered);
    if(localSocket.waitForConnected(1000))
    {
        localSocket.disconnectFromServer();
        return true;
    }
    else
        return false;
}
Пример #11
0
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();
}
Пример #12
0
int HLocalServer::isServerRun(const QString &servername)
{
    // 用一个localsocket去连一下,如果能连上就说明有一个在运行了
    QLocalSocket ls;
    ls.connectToServer(servername);
    if (ls.waitForConnected(1000))
    {
        ls.disconnectFromServer();
        ls.close();
        return 1;
    }
    return 0;
}
Пример #13
0
void Application::receiveMessage()
{
    QLocalSocket *localSocket = d_ptr->localServer.nextPendingConnection();

    if (!localSocket->waitForReadyRead(GUI_APPLICATION_LOCAL_SOCKET_TIMEOUT))
        return;

    QByteArray byteArray = localSocket->readAll();
    const QString message = QString::fromUtf8(byteArray.constData());

    if (message == "raise")
        emit raiseRequested();

    localSocket->disconnectFromServer();
}
Пример #14
0
//New messages detected
void LSingleApplication::newInputsAvailable(){
  while(lserver->hasPendingConnections()){
    QLocalSocket *sock = lserver->nextPendingConnection();
    QByteArray bytes;
    sock->waitForReadyRead();
    while(sock->bytesAvailable() > 0){ //if(sock->waitForReadyRead()){
	//qDebug() << "Info Available";
	bytes.append( sock->readAll() );
    }
    sock->disconnectFromServer();
    QStringList inputs = QString::fromLocal8Bit(bytes).split("::::");
    //qDebug() << " - New Inputs Detected:" << inputs;
    emit InputsAvailable(inputs);
  }
}
Пример #15
0
void DebconfFrontendSocket::newConnection()
{
    qCDebug(DEBCONF);
    if (m_socket) {
        QLocalSocket *socket = m_server->nextPendingConnection();
        socket->disconnectFromServer();
        socket->deleteLater();
        return;
    }

    m_socket = m_server->nextPendingConnection();
    if (m_socket) {
        connect(m_socket, SIGNAL(readyRead()), this, SLOT(process()));
        connect(m_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    }
}
Пример #16
0
void MegaSyncLogger::clientConnected()
{
    disconnected();

    while (megaServer->hasPendingConnections())
    {
        QLocalSocket *socket = megaServer->nextPendingConnection();
        socket->disconnectFromServer();
        socket->deleteLater();
    }

    client = new QLocalSocket();
    connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(client, SIGNAL(error(QLocalSocket::LocalSocketError)), SLOT(disconnected()));
    client->connectToServer(MEGA_LOGGER);
    connected = true;
}
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();

}
Пример #18
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();
}
Пример #19
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();

}
Пример #20
0
bool Application::sendRaiseRequest()
{
    if (!d_ptr->isRunning)
        return false;

    QLocalSocket localSocket;
    localSocket.connectToServer(GUI_APPLICATION_SHARED_MEMORY_KEY, QIODevice::WriteOnly);

    if (!localSocket.waitForConnected(GUI_APPLICATION_LOCAL_SOCKET_TIMEOUT))
        return false;

    localSocket.write(QString("raise").toUtf8());

    if (!localSocket.waitForBytesWritten(GUI_APPLICATION_LOCAL_SOCKET_TIMEOUT))
        return false;

    localSocket.disconnectFromServer();
    return true;
}
/**
 * Sets in motion the communication necessary to ensure that only one instance
 * survives.
 * @returns true if a single instance is assured, false if it was not possible
 *          to enforce the policy
 */
bool InstanceManager::ensureSingleInstance(ResolutionScheme scheme)
{
  // If the server exists, it's because we're already the dominant instance
  if (mServer) {
    return true;
  }

  QLocalSocket socket;
  socket.connectToServer(mKey);
  if (!socket.waitForConnected(10000)) {
    // No remote server? Let's try starting our own.
    startServer();
    return false;
  }

  switch (scheme) {
    case ThisInstanceWins:
      tellServerToQuit(&socket);
      break;

    case HighestVersionWins:
    default:
      QTextStream stream(&socket);
      stream << "version\n";
      stream.flush();
      socket.waitForReadyRead();
      QString remoteVersion = stream.readLine();

      if (VersionNumber(remoteVersion) < VersionNumber(APP_VERSION)) {
        tellServerToQuit(&socket);
        startServer();
      } else {
        QTimer::singleShot(0, qApp, SLOT(quit()));
      }
      break;
  }

  socket.disconnectFromServer();
  socket.waitForDisconnected();

  return true;
}
Пример #22
0
void GPUSiftClient::operator ()(const cv::Mat1b &img,
                                const cv::Mat &mask,
                                std::vector<cv::KeyPoint> &keypoints,
                                std::vector<float> &descriptors) const
{
  QLocalSocket socket;
  socket.connectToServer("nestk_sift_gpu");
  if (!socket.waitForConnected(1000))
  {
    ntk_dbg(0) << "Could not connect to GPU SIFT server!";
    keypoints.clear();
    descriptors.clear();
    return;
  }

  // Send image
  QDataStream stream(&socket);
  ntk_dbg(2) << "Sending " << img.rows << " " << img.cols;
  stream << (qint32)img.rows << (qint32)img.cols;
  int num_bytes = stream.writeRawData((const char*)img.data, img.rows*img.cols);
  ntk_assert(num_bytes == img.rows*img.cols, "Could not send all data");

  // Read keypoints
  socket.waitForReadyRead();
  qint32 num_features = -1;
  stream >> num_features;
  ntk_dbg_print(num_features, 2);

  keypoints.resize(num_features);
  readFullRawData(socket, stream, (char*)&keypoints[0], num_features*sizeof(KeyPoint));
  ntk_assert(stream.status() == QDataStream::Ok, "Bad transmission.");

  descriptors.resize(num_features*descriptorSize());
  readFullRawData(socket, stream, (char*)&descriptors[0],
                  num_features*descriptorSize()*sizeof(float));
  ntk_assert(stream.status() == QDataStream::Ok, "Bad transmission.");

  stream << (qint32) 42;
  socket.waitForBytesWritten();
  socket.disconnectFromServer();
}
Пример #23
0
bool Application::IsAlreadyRunning () const
{
	QLocalSocket socket;
	socket.connectToServer (GetSocketName ());
	if (socket.waitForConnected () ||
			socket.state () == QLocalSocket::ConnectedState)
	{
		QByteArray toSend;
		{
			QDataStream out (&toSend, QIODevice::WriteOnly);
			out << Arguments_;
		}
		socket.write (toSend);
		socket.disconnectFromServer ();
		socket.waitForDisconnected ();
		return true;
	}
	else
	{
		switch (socket.error ())
		{
			case QLocalSocket::ServerNotFoundError:
			case QLocalSocket::ConnectionRefusedError:
				break;
			default:
				qWarning () << Q_FUNC_INFO
					<< "socket error"
					<< socket.error ();
				return true;
		}
	}

	// Clear any halted servers and their messages
	QLocalServer::removeServer (GetSocketName ());
	return false;
}
Пример #24
0
int main(int argc, char *argv[])
{
    qRegisterMetaType<JoyButtonSlot*>();
    qRegisterMetaType<AdvanceButtonDialog*>();
    //qRegisterMetaType<Joystick*>();
    qRegisterMetaType<InputDevice*>();

    // If running Win version, check if an explicit style
    // was defined on the command-line. If so, make a note
    // of it.
#ifdef Q_OS_WIN
    bool styleChangeFound = false;
    for (int i=0; i < argc && !styleChangeFound; i++)
    {
        char *tempchrstr = argv[i];
        QString temp = QString::fromUtf8(tempchrstr);
        if (temp == "-style")
        {
            styleChangeFound = true;
        }
    }
#endif

    QApplication a(argc, argv);
    //QString defaultStyleName = qApp->style()->objectName();

    // If running Win version and no explicit style was
    // defined, use the style Fusion by default. I find the
    // windowsvista style a tad ugly
#ifdef Q_OS_WIN
    if (!styleChangeFound)
    {
        qApp->setStyle(QStyleFactory::create("Fusion"));
    }
#endif

    CommandLineUtility cmdutility;
    QStringList cmdarguments = a.arguments();
    cmdutility.parseArguments(cmdarguments);

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    a.installTranslator(&qtTranslator);

    QTranslator myappTranslator;
#if defined(Q_OS_UNIX)
    myappTranslator.load("antimicro_" + QLocale::system().name(), QApplication::applicationDirPath().append("/../share/antimicro/translations"));
#elif defined(Q_OS_WIN)
    myappTranslator.load("antimicro_" + QLocale::system().name(), QApplication::applicationDirPath().append("\\share\\antimicro\\translations"));
#endif
    a.installTranslator(&myappTranslator);

    if (cmdutility.hasError())
    {
        return 1;
    }
    else if (cmdutility.isHelpRequested())
    {
        cmdutility.printHelp();
        return 0;
    }
    else if (cmdutility.isVersionRequested())
    {
        cmdutility.printVersionString();
        return 0;
    }

    Q_INIT_RESOURCE(resources);
    a.setQuitOnLastWindowClosed(false);

    QDir configDir (PadderCommon::configPath);
    if (!configDir.exists())
    {
        configDir.mkpath(PadderCommon::configPath);
    }

#ifdef USE_SDL_2
    QHash<SDL_JoystickID, InputDevice*> *joysticks = new QHash<SDL_JoystickID, InputDevice*>();
#else
    QHash<int, InputDevice*> *joysticks = new QHash<int, InputDevice*>();
#endif

    // Cross-platform way of performing IPC. Currently,
    // only establish a connection and then disconnect.
    // In the future, there might be a reason to actually send
    // messages to the QLocalServer.
    QLocalSocket socket;
    socket.connectToServer(PadderCommon::localSocketKey);
    socket.waitForConnected(1000);
    if (socket.state() == QLocalSocket::ConnectedState)
    {
        // An instance of this program is already running.
        // Save app config and exit.
        InputDaemon *joypad_worker = new InputDaemon(joysticks, false);
        MainWindow w(joysticks, &cmdutility, false);

        if (!cmdutility.hasError() && cmdutility.hasProfile())
        {
            w.saveAppConfig();
        }

        joypad_worker->quit();
        w.removeJoyTabs();

        socket.disconnectFromServer();

#ifdef USE_SDL_2
        QHashIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
#else
        QHashIterator<int, InputDevice*> iter(*joysticks);
#endif

        while (iter.hasNext())
        {
            InputDevice *joystick = iter.next().value();
            if (joystick)
            {
                delete joystick;
                joystick = 0;
            }
        }

        joysticks->clear();
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        return 0;
    }

    InputDaemon *joypad_worker = new InputDaemon (joysticks);
    MainWindow w(joysticks, &cmdutility);
    w.startLocalServer();

#ifdef USE_SDL_2
    QObject::connect(joypad_worker, SIGNAL(joysticksRefreshed(QHash<SDL_JoystickID, InputDevice*>*)), &w, SLOT(fillButtons(QHash<SDL_JoystickID, InputDevice*>*)));
#else
    QObject::connect(joypad_worker, SIGNAL(joysticksRefreshed(QHash<int, InputDevice*>*)), &w, SLOT(fillButtons(QHash<int, InputDevice*>*)));
#endif
    QObject::connect(&w, SIGNAL(joystickRefreshRequested()), joypad_worker, SLOT(refresh()));
    QObject::connect(joypad_worker, SIGNAL(joystickRefreshed(InputDevice*)), &w, SLOT(fillButtons(InputDevice*)));
    QObject::connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
    QObject::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(saveAppConfig()));
    QObject::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(removeJoyTabs()));
    QObject::connect(&a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));
#ifdef USE_SDL_2
    QObject::connect(&w, SIGNAL(mappingUpdated(QString,InputDevice*)), joypad_worker, SLOT(refreshMapping(QString,InputDevice*)));
    QObject::connect(joypad_worker, SIGNAL(deviceUpdated(int,InputDevice*)), &w, SLOT(testMappingUpdateNow(int,InputDevice*)));
    QObject::connect(joypad_worker, SIGNAL(deviceRemoved(SDL_JoystickID)), &w, SLOT(removeJoyTab(SDL_JoystickID)));
    QObject::connect(joypad_worker, SIGNAL(deviceAdded(InputDevice*)), &w, SLOT(addJoyTab(InputDevice*)));
#endif

    /*if (!cmdutility.isHiddenRequested() && (!cmdutility.isLaunchInTrayEnabled() || !QSystemTrayIcon::isSystemTrayAvailable()))
    {
        w.show();
    }*/

    int app_result = a.exec();

#ifdef USE_SDL_2
    QHashIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);
#else
    QHashIterator<int, InputDevice*> iter(*joysticks);
#endif

    while (iter.hasNext())
    {
        InputDevice *joystick = iter.next().value();
        if (joystick)
        {
            delete joystick;
            joystick = 0;
        }
    }

    joysticks->clear();
    delete joysticks;
    joysticks = 0;

    delete joypad_worker;
    joypad_worker = 0;

    return app_result;
}
Пример #25
0
int main(int argc, char *argv[])
{
    Application app(argc, argv);
    QApplication::setOrganizationName(Common::ORG_NAME);
    QApplication::setOrganizationDomain(Common::ORG_DOMAIN);
    QApplication::setApplicationName(Common::APP_NAME);
    QApplication::setWindowIcon( QIcon(":/res/ico/anonymous.png") );
    QSettings settings;
    NetworkAccessManager::instance()->setCache(0);
    LocalServer localServer;
    //LocalServer::removeServer(Common::APP_NAME);
    bool serverStarted = localServer.listen(Common::APP_NAME);
    QStringList argList;
    QStringList urlList;
    bool fillingUrlList = false;

    for (int i = 0; i < argc; ++i)
    {
        QString arg(argv[i]);

        if ( arg.at(0) == LocalServer::PREFIX.at(0) )
        {
            argList << arg;

            if (fillingUrlList)
                fillingUrlList = false;
            else if (LocalServer::ARG_URLS == arg)
                fillingUrlList = true;
        }
        else if (fillingUrlList)
        {
            urlList << QUrl::fromUserInput(arg).toString();
        }
    }

    if ( !serverStarted && !argList.contains(LocalServer::ARG_MULTIPLE) )
    {
        if ( argList.contains(LocalServer::ARG_URLS) )
        {
            QLocalSocket socket;
            socket.connectToServer(Common::APP_NAME, QIODevice::WriteOnly);

            if ( !socket.waitForConnected() )
                return 1;

            QByteArray data;

            for (int i = 0; i < argc; ++i)
            {
                data.append(argv[i]).append('\0');
            }

            if ( -1 == socket.write(data) )
                return 2;

            if ( !socket.waitForBytesWritten() )
                return 3;

            socket.disconnectFromServer();
        }

        return 0;
    }

    qRegisterMetaType<ParceTask::Result>("ParceTask::Result");
    qRegisterMetaType<SaveTask::Result>("SaveTask::Result");
    qRegisterMetaType<SavePageTask::Result>("SavePageTask::Result");
    qRegisterMetaType<RmdirTask::Result>("RmdirTask::Result");
    qRegisterMetaType<ImageboardThread*>("ImageboardThread*");
    qRegisterMetaType<InfoWidget*>("InfoWidget*");
    qRegisterMetaType<QModelIndex>("QModelIndex");
    qRegisterMetaType<ImageboardThread::Modifiable>("ImageboardThread::Modifiable");
    QThreadPool::globalInstance()->setMaxThreadCount(10);
    ThreadManager threadManager(0);
    QObject::connect( &localServer,
             SIGNAL( addThreadSilent(ImageboardThread::Parameters, bool) ),
             &threadManager,
             SLOT( requestAddThread(ImageboardThread::Parameters, bool) ) );

    if ( argList.contains(LocalServer::ARG_DEFAULT) && !urlList.isEmpty() )
    {
        bool start = argList.contains(LocalServer::ARG_START);
        settings.beginGroup(ParametersDialog::GROUP_PARAMETERS);
          settings.beginGroup(ThreadManager::SUB_GROUP_DEFAULT);
            ImageboardThread::Parameters param =
                    ImageboardThread::readParameters(settings);
          settings.endGroup();
        settings.endGroup();

        for (int i = 0; i < urlList.count(); ++i)
        {
            param.url = urlList.at(i);
            param.added = QDateTime::currentDateTime();
            threadManager.requestAddThread(param, start);
        }
    }

    MainWindow *mainWindow = new MainWindow(threadManager.threadModel(),
                                            threadManager.categoryModel(), 0);
    QObject::connect(&app, SIGNAL( requestWriteSettings() ),
                     mainWindow, SLOT( writeSettings() ),
                     Qt::DirectConnection);
    QObject::connect(
                mainWindow,
                SIGNAL( requestAddThread(ImageboardThread::Parameters, bool) ),
                &threadManager,
                SLOT( requestAddThread(ImageboardThread::Parameters, bool) ) );
    QObject::connect( mainWindow, SIGNAL( requestBackup(QString) ),
                      &threadManager, SLOT( requestBackup(QString) ) );
    QObject::connect( mainWindow,
                      SIGNAL( requestRemoveThread(QList<int>, bool) ),
                      &threadManager,
                      SLOT( requestRemoveThread(QList<int>, bool) ) );
    QObject::connect( mainWindow, SIGNAL( requestStartThread(int) ),
                      &threadManager, SLOT( requestStartThread(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestStopThread(int) ),
                      &threadManager, SLOT( requestStopThread(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestOpenDir(int) ),
                      &threadManager, SLOT( requestOpenDir(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestOpenUrl(int) ),
                      &threadManager, SLOT( requestOpenUrl(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestOpenLocal(int) ),
                      &threadManager, SLOT( requestOpenLocal(int) ) );
    QObject::connect( mainWindow,
                      SIGNAL(requestSetObservedThread(int, InfoWidget*) ),
                      &threadManager,
                      SLOT( requestSetObservedThread(int, InfoWidget*) ) );
    QObject::connect( mainWindow,
                      SIGNAL( requestModifyParameters(
                                 QList<int>, ImageboardThread::Modifiable) ),
                      &threadManager,
                      SLOT( requestModifyParameters(
                               QList<int>, ImageboardThread::Modifiable) ) );
    QObject::connect( mainWindow, SIGNAL( requestRetranslate() ),
                      &threadManager, SLOT( requestRetranslate() ) );
    QObject::connect( mainWindow, SIGNAL( requestWriteSettings() ),
                      &threadManager, SLOT( requestWriteSettings() ) );
    QObject::connect( &localServer, SIGNAL( addThreads(QStringList) ),
                      mainWindow, SLOT( callAddThreadDialog(QStringList) ) );
    ParametersDialog::CommonParameters commonParam =
            ParametersDialog::readCommonParameters(settings);
    mainWindow->setVisibility(!commonParam.startMinimized);

    if ( !argList.contains(LocalServer::ARG_DEFAULT) && !urlList.isEmpty() )
        mainWindow->callAddThreadDialog(urlList);

    int err = app.exec();
    //LocalServer::removeServer(Common::APP_NAME);
    localServer.close();
    return err;
}
Пример #26
0
 ~SCIpcClient()
 {
     mSocket->disconnectFromServer();
 }
Пример #27
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);
    app.setApplicationName(APP_NAME);
    app.setApplicationVersion("2.0");
    app.setOrganizationName(ORGANIZATION_NAME);

    bool bCallRequest = false;

    g_LanguagesPath         = QApplication::applicationDirPath() + "/lang";
    g_AppSettingsFolderPath = QDir::homePath() + "/OutCALL";
    g_AppDirPath            = QApplication::applicationDirPath();

    if (argc==2 && QString(argv[1]) == "installer")
    {
        // Setup log file paths
        QDir().mkpath(g_AppSettingsFolderPath);
        QFile(g_AppSettingsFolderPath + "/outcall.log").remove();

        if (global::IsOutlookInstalled())
        {
            if (global::EnableOutlookIntegration(true))
                global::log("Outlook plugin installed successfully.", LOG_INFORMATION);
            else
                global::log("Could not install Outlook plugin.", LOG_ERROR);
        }
        else
        {
            global::log("Outlook was not detected.", LOG_INFORMATION);
        }
        return 0;
    }

    if (argc == 2)
    {
        bCallRequest = QString(argv[1]).contains("Dial#####");
    }

    if (bCallRequest)
    {
        QStringList arguments = QString(argv[1]).split("#####");
        QString contactName = arguments[1];
        QString numbers = QString(arguments[2]).replace("outcall://", "");

        contactName.replace("&&&", " ");
        numbers.replace("&&&", " ");

        QLocalSocket s;
        s.connectToServer(LOCAL_SERVER_NAME);

        global::log("MAIN LOCAL", LOG_INFORMATION);

        QString msg = QObject::tr("It appears that %1 is not running.\n" \
                                  "Note for Windows 7/Vista users: please make sure that %2 and Outlook are running under same level of privileges. " \
                                  "Either both elevated (Run as Administrator option) or non-elevated.").arg(APP_NAME).arg(APP_NAME);

        if (!s.waitForConnected(2000))
        {
            MsgBoxInformation(msg);
        }
        else
        {
            if (!s.waitForReadyRead(2000)) // wait for "OK" from the local server
            {
                MsgBoxInformation(QObject::tr("Timeout on local socket. Maybe %1 is not running?").arg(APP_NAME));
            }
            else
            {
                QByteArray socket_data = QString("outlook_call %1 %2\n").arg(QString(contactName.toLatin1().toBase64())).
                                         arg(QString(numbers.toLatin1().toBase64())).toLatin1();
                s.write(socket_data);

                if (!s.waitForBytesWritten(2000))
                    MsgBoxError(QObject::tr("Failed local socket write()."));
            }
        }
        s.disconnectFromServer();
        s.close();

        return 0;
    }

    Notifier notifier;
    QString lang = global::getSettingsValue("language", "general").toString();
    QTranslator translator;
    if (!lang.isEmpty())
    {
        if (translator.load(QString("%1/%2.lang").arg(g_LanguagesPath).arg(lang)))
        {
            qApp->installTranslator(&translator);
        }
        else
        {
            global::setSettingsValue("language", "", "general");
            MsgBoxError(QObject::tr("Failed to load language file."));
        }
    }

    QString username  = global::getSettingsValue("username", "settings").toString();
    QByteArray secret = global::getSettingsValue("password", "settings").toByteArray();
    AsteriskManager manager(username, QString(QByteArray::fromBase64(secret)));

    OutCall outcall;
    outcall.show();

    LocalServer localServer;
    return app.exec();
}
Пример #28
0
int main(int argc, char * argv[])
{
    QCoreApplication app(argc, argv);

    QStringList args;
    for (int i = 1; i < argc; ++i)
        args << QString(argv[i]);

    if (args.count() == 0 )
        qFatal("No connection name supplied to lackey process");

    // This is a workaround for the fact that we cannot use stdin/stdout/stderr
    // to communicate with a process on WinCE or Symbian systems.
    // We use sockets instead, and the first argument given is the port number.

    QString connectionName = args.takeFirst();
    QLocalSocket oopSocket;

    if (connectionName != QString("NoComms")) {
        oopSocket.connectToServer(connectionName);
        oopSocket.waitForConnected(-1);
    }

    if (args.count() == 0 )
        qFatal("No arguments supplied to lackey process");

    int retVal = 0;

    if (args[0] == "ReadLock") {
        // 1)read-lock
        // 2)unlock
        QSystemReadWriteLock testRwLock("Viper");
        write(&oopSocket, qPrintable(Lackey::BeforeLockForRead));
        testRwLock.lockForRead();
        write(&oopSocket, qPrintable(Lackey::AfterLockForRead));

        testRwLock.unlock();
        QTest::qSleep(1000);
        write(&oopSocket, qPrintable(Lackey::AfterUnlockForRead));
    } else if (args[0] == "WriteLock") {
        // 1) write-lock
        // 2) unlock
        QSystemReadWriteLock testRwLock("Viper");
        write(&oopSocket, qPrintable(Lackey::BeforeLockForWrite));
        testRwLock.lockForWrite();
        write(&oopSocket, qPrintable(Lackey::AfterLockForWrite));

        testRwLock.unlock();
        QTest::qSleep(1000);
        write(&oopSocket, qPrintable(Lackey::AfterUnlockForWrite));
    } else if (args[0] == "ReadLockReleaseable") {
        // 1) read-lock
        // 2) wait for input on stdin
        // 3) unlock
        QSystemReadWriteLock testRwLock("Viper");
        write(&oopSocket, qPrintable(Lackey::BeforeLockForRead));
        testRwLock.lockForRead();
        QTest::qSleep(1000);
        write(&oopSocket, qPrintable(Lackey::AfterLockForRead));

        readLine(&oopSocket);

        testRwLock.unlock();
        write(&oopSocket, qPrintable(Lackey::AfterUnlockForRead));
    } else if (args[0] == "WriteLockReleaseable") {
        // 1) write-lock
        // 2) wait for input on stdin
        // 3) unlock
        QSystemReadWriteLock testRwLock("Viper");
        write(&oopSocket, qPrintable(Lackey::BeforeLockForWrite));
        testRwLock.lockForWrite();
        write(&oopSocket, qPrintable(Lackey::AfterLockForWrite));

        readLine(&oopSocket);

        testRwLock.unlock();
        write(&oopSocket, qPrintable(Lackey::AfterUnlockForWrite));
    } else if (args[0] == "ReadLockLoop") {
        // for(runTime msecs):
        // 1) read-lock
        // 2) sleep(holdTime msecs)
        // 3) unlock
        // 4) sleep(waitTime msecs)
        Q_ASSERT(args.count() == 4);
        int runTime = args[1].toInt();
        int holdTime = args[2].toInt();
        int waitTime = args[3].toInt();

        QSystemReadWriteLock testRwLock("Viper");
        QTime t;
        t.start();
        while(t.elapsed() < runTime) {
            testRwLock.lockForRead();
            if (holdTime)
                QTest::qSleep(holdTime);
            testRwLock.unlock();
            if(waitTime)
                QTest::qSleep(waitTime);
        }
    } else if (args[0]  == "WriteLockLoop") {
        // for(runTime msecs):
        // 1) read-lock
        // 2) sleep(holdTime msecs)
        // 3) unlock
        // 4) sleep(waitTime msecs)
        Q_ASSERT(args.count() == 4);
        int runTime = args[1].toInt();
        int holdTime = args[2].toInt();
        int waitTime = args[3].toInt();

        QSystemReadWriteLock testRwLock("Viper");
        QTime t;
        t.start();
        while (t.elapsed() < runTime) {
            testRwLock.lockForWrite();
            if (holdTime)
                QTest::qSleep(holdTime);
            testRwLock.unlock();
            if (waitTime)
                QTest::qSleep(waitTime);
        }
    } else if (args[0] == "ReadLockExcl") {
        // for (runTime msecs):
        // 1) read-lock
        // 2) check that the exclusive file does not
        //    exist, if it does qFatal
        // 3) sleep(holdTime msecs)
        // 4) unlock
        // 5) sleep(waitTime msecs)
        Q_ASSERT(args.count() == 4);
        int runTime = args[1].toInt();
        int holdTime = args[2].toInt();
        int waitTime = args[3].toInt();

        QSystemReadWriteLock testRwLock("Viper");
        QTime t;
        t.start();
        while (t.elapsed() < runTime) {
            testRwLock.lockForRead();
            QDir cwd;
            if (cwd.exists("writeLockExcl.tmp"))
                qFatal("writeLockExcl.tmp file found during read!");
            if (holdTime)
                QTest::qSleep(holdTime);
            testRwLock.unlock();
            if (waitTime)
                QTest::qSleep(waitTime);
        }
    } else if (args[0] == "WriteLockExcl") {
        // for(runTime msecs)
        // 1) write-lock
        // 2) check that exclusive file does not
        //      exist, if it does qFatal
        // 3) create the exclusive file,
        //    sleep(holdTime msecs), delete the file
        // 4) unlock
        // 5) sleep(waitTime msecs)
        Q_ASSERT(args.count() == 4);
        int runTime = args[1].toInt();
        int holdTime = args[2].toInt();
        int waitTime = args[3].toInt();

        QSystemReadWriteLock testRwLock("Viper");
        QTime t;
        t.start();
        while(t.elapsed() < runTime) {
            testRwLock.lockForWrite();
            QDir cwd;
            if (cwd.exists("writeLockExcl.tmp"))
                qFatal("writeLockExcl.tmp file found during write!");
            QFile file("writeLockExcl.tmp");
            file.open(QIODevice::ReadWrite);
            if (holdTime)
                QTest::qSleep(holdTime);
            file.close();
            cwd.remove("writeLockExcl.tmp");
            testRwLock.unlock();
            if(waitTime)
                QTest::qSleep(waitTime);
        }
    } else {
        retVal = 1;
    }

    if (connectionName != QString("NoComms")) {
        oopSocket.disconnectFromServer();
        oopSocket.waitForDisconnected(-1);
    }

    return retVal;
}
Пример #29
0
int main(int argc, char *argv[])
{
    qRegisterMetaType<JoyButtonSlot*>();
    qRegisterMetaType<InputDevice*>();
    qRegisterMetaType<AutoProfileInfo*>();

    QTextStream outstream(stdout);
    QTextStream errorstream(stderr);

    // If running Win version, check if an explicit style
    // was defined on the command-line. If so, make a note
    // of it.
#ifdef Q_OS_WIN
    bool styleChangeFound = false;
    for (int i=0; i < argc && !styleChangeFound; i++)
    {
        char *tempchrstr = argv[i];
        QString temp = QString::fromUtf8(tempchrstr);
        if (temp == "-style")
        {
            styleChangeFound = true;
        }
    }
#endif

    CommandLineUtility cmdutility;
    QStringList cmdarguments = PadderCommon::arguments(argc, argv);
    cmdarguments.removeFirst();
    cmdutility.parseArguments(cmdarguments);

    Logger appLogger(&outstream, &errorstream);

    if (cmdutility.hasError())
    {
        appLogger.LogError(cmdutility.getErrorText());
        return 1;
    }
    else if (cmdutility.isHelpRequested())
    {
        appLogger.LogInfo(cmdutility.generateHelpString(), false);
        //cmdutility.printHelp();
        return 0;
    }
    else if (cmdutility.isVersionRequested())
    {
        appLogger.LogInfo(cmdutility.generateVersionString());
        //cmdutility.printVersionString();
        return 0;
    }

    if (cmdutility.getCurrentLogLevel() != appLogger.getCurrentLogLevel())
    {
        appLogger.setLogLevel(cmdutility.getCurrentLogLevel());
    }

    Q_INIT_RESOURCE(resources);

    QDir configDir(PadderCommon::configPath);
    if (!configDir.exists())
    {
        configDir.mkpath(PadderCommon::configPath);
    }

    QMap<SDL_JoystickID, InputDevice*> *joysticks = new QMap<SDL_JoystickID, InputDevice*>();

    // Cross-platform way of performing IPC. Currently,
    // only establish a connection and then disconnect.
    // In the future, there might be a reason to actually send
    // messages to the QLocalServer.
    QLocalSocket socket;
    socket.connectToServer(PadderCommon::localSocketKey);
    socket.waitForConnected(1000);
    if (socket.state() == QLocalSocket::ConnectedState)
    {
        // An instance of this program is already running.
        // Save app config and exit.
        QApplication a(argc, argv);
        AntiMicroSettings settings(PadderCommon::configFilePath, QSettings::IniFormat);
        InputDaemon *joypad_worker = new InputDaemon(joysticks, &settings, false);
        MainWindow w(joysticks, &cmdutility, &settings, false);

        if (!cmdutility.hasError() && cmdutility.hasProfile())
        {
            w.saveAppConfig();
        }

        joypad_worker->quit();
        w.removeJoyTabs();

        settings.sync();
        socket.disconnectFromServer();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        return 0;
    }

    LocalAntiMicroServer *localServer = 0;
    QApplication *a = 0;

#ifndef Q_OS_WIN
    if (cmdutility.launchAsDaemon())
    {
        pid_t pid, sid;

        //Fork the Parent Process
        pid = fork();

        if (pid == 0)
        {
            appLogger.LogInfo(QObject::tr("Daemon launched"));
            //outstream << QObject::tr("Daemon launched") << endl;

            a = new QApplication(argc, argv);
            localServer = new LocalAntiMicroServer();
            localServer->startLocalServer();
        }
        else if (pid < 0)
        {
            appLogger.LogError(QObject::tr("Failed to launch daemon"));
            //errorstream << QObject::tr("Failed to launch daemon") << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            exit(EXIT_FAILURE);
        }
        //We got a good pid, Close the Parent Process
        else if (pid > 0)
        {
            appLogger.LogInfo(QObject::tr("Launching daemon"));
            //outstream << QObject::tr("Launching daemon") << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            exit(EXIT_SUCCESS);
        }


    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif

        if (cmdutility.getDisplayString().isEmpty())
        {
            X11Extras::getInstance()->syncDisplay();
        }
        else
        {
            X11Extras::getInstance()->syncDisplay(cmdutility.getDisplayString());
            if (X11Extras::getInstance()->display() == NULL)
            {
                appLogger.LogError(QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()));
                //errorstream << QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()) << endl;

                deleteInputDevices(joysticks);
                delete joysticks;
                joysticks = 0;

                delete localServer;
                localServer = 0;

                X11Extras::deleteInstance();

                exit(EXIT_FAILURE);
            }
        }

        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif

    #endif

        //Change File Mask
        umask(0);

        //Create a new Signature Id for our child
        sid = setsid();
        if (sid < 0)
        {
            appLogger.LogError(QObject::tr("Failed to set a signature id for the daemon"));
            //errorstream << QObject::tr("Failed to set a signature id for the daemon") << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            delete localServer;
            localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
            if (QApplication::platformName() == QStringLiteral("xcb"))
            {
        #endif
            X11Extras::deleteInstance();

        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
            }
        #endif
    #endif

            exit(EXIT_FAILURE);
        }

        if ((chdir("/")) < 0)
        {
            appLogger.LogError(QObject::tr("Failed to change working directory to /"));
            //errorstream << QObject::tr("Failed to change working directory to /")
            //            << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            delete localServer;
            localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

            if (QApplication::platformName() == QStringLiteral("xcb"))
            {
        #endif
            X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
            }
        #endif
    #endif

            exit(EXIT_FAILURE);
        }

        //Close Standard File Descriptors
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
    }
    else
    {
        a = new QApplication(argc, argv);
        localServer = new LocalAntiMicroServer();
        localServer->startLocalServer();

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif
        if (!cmdutility.getDisplayString().isEmpty())
        {
            X11Extras::getInstance()->syncDisplay(cmdutility.getDisplayString());
            if (X11Extras::getInstance()->display() == NULL)
            {
                appLogger.LogError(QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()));
                //errorstream << QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()) << endl;

                deleteInputDevices(joysticks);
                delete joysticks;
                joysticks = 0;

                delete localServer;
                localServer = 0;

                X11Extras::deleteInstance();

                exit(EXIT_FAILURE);
            }
        }

        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif
    #endif
    }

#else
    a = new QApplication (argc, argv);
    localServer = new LocalAntiMicroServer();
    localServer->startLocalServer();
#endif

    a->setQuitOnLastWindowClosed(false);

    //QString defaultStyleName = qApp->style()->objectName();

    // If running Win version and no explicit style was
    // defined, use the style Fusion by default. I find the
    // windowsvista style a tad ugly
#ifdef Q_OS_WIN
    if (!styleChangeFound)
    {
        qApp->setStyle(QStyleFactory::create("Fusion"));
    }

    QIcon::setThemeName("/");
#endif

    AntiMicroSettings settings(PadderCommon::configFilePath, QSettings::IniFormat);
    settings.importFromCommandLine(cmdutility);

    QString targetLang = QLocale::system().name();
    if (settings.contains("Language"))
    {
        targetLang = settings.value("Language").toString();
    }

    QTranslator qtTranslator;
    qtTranslator.load(QString("qt_").append(targetLang), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    a->installTranslator(&qtTranslator);

    QTranslator myappTranslator;
#if defined(Q_OS_UNIX)
    myappTranslator.load(QString("antimicro_").append(targetLang), QApplication::applicationDirPath().append("/../share/antimicro/translations"));
#elif defined(Q_OS_WIN)
    myappTranslator.load(QString("antimicro_").append(targetLang), QApplication::applicationDirPath().append("\\share\\antimicro\\translations"));
#endif
    a->installTranslator(&myappTranslator);

    InputDaemon *joypad_worker = new InputDaemon(joysticks, &settings);

#ifndef Q_OS_WIN
    // Have program handle SIGTERM
    struct sigaction termaction;
    termaction.sa_handler = &termSignalTermHandler;
    sigemptyset(&termaction.sa_mask);
    termaction.sa_flags = 0;

    sigaction(SIGTERM, &termaction, 0);

    // Have program handle SIGINT
    struct sigaction termint;
    termint.sa_handler = &termSignalIntHandler;
    sigemptyset(&termint.sa_mask);
    termint.sa_flags = 0;

    sigaction(SIGINT, &termint, 0);

#endif

    if (cmdutility.shouldListControllers())
    {
        AppLaunchHelper mainAppHelper(&settings, false);
        mainAppHelper.printControllerList(joysticks);

        joypad_worker->quit();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        delete localServer;
        localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif
        X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif
    #endif

        delete a;
        a = 0;

        return 0;
    }

#ifdef USE_SDL_2
    else if (cmdutility.shouldMapController())
    {
        MainWindow *w = new MainWindow(joysticks, &cmdutility, &settings);

        QObject::connect(a, SIGNAL(aboutToQuit()), w, SLOT(removeJoyTabs()));
        QObject::connect(a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));

        int app_result = a->exec();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        delete localServer;
        localServer = 0;

#ifdef WITH_X11
    #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
    #endif
        X11Extras::deleteInstance();
    #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
    #endif
#endif

        delete w;
        w = 0;

        delete a;
        a = 0;

        return app_result;
    }
#endif

#ifdef Q_OS_UNIX
    bool status = true;
    EventHandlerFactory *factory = EventHandlerFactory::getInstance(cmdutility.getEventGenerator());
    if (!factory)
    {
        status = false;
    }
    else
    {
        status = factory->handler()->init();
    }

#if defined(WITH_UINPUT) && defined(WITH_XTEST)
    // Use xtest as a fallback.
    if (!status && cmdutility.getEventGenerator() != EventHandlerFactory::fallBackIdentifier())
    {
        QString eventDisplayName = EventHandlerFactory::handlerDisplayName(
                    EventHandlerFactory::fallBackIdentifier());
        appLogger.LogInfo(QObject::tr("Attempting to use fallback option %1 for event generation.")
                                     .arg(eventDisplayName));
        //outstream << QObject::tr("Attempting to use fallback option %1 for event generation.")
        //             .arg(eventDisplayName) << endl;

        factory->deleteInstance();
        factory = EventHandlerFactory::getInstance(EventHandlerFactory::fallBackIdentifier());
        if (!factory)
        {
            status = false;
        }
        else
        {
            status = factory->handler()->init();
        }
    }
#endif

    if (!status)
    {
        appLogger.LogError(QObject::tr("Failed to open event generator. Exiting."));
        //errorstream << QObject::tr("Failed to open event generator. Exiting.") << endl;

        joypad_worker->quit();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        delete localServer;
        localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif
        X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif
    #endif

        delete a;
        a = 0;

        return EXIT_FAILURE;
    }
    else
    {
        appLogger.LogInfo(QObject::tr("Using %1 as the event generator.").arg(factory->handler()->getName()));
        //outstream << QObject::tr("Using %1 as the event generator.").arg(factory->handler()->getName())
        //          << endl;
        factory->handler()->printPostMessages();
    }
#endif

    AntKeyMapper::getInstance(cmdutility.getEventGenerator());

    MainWindow *w = new MainWindow(joysticks, &cmdutility, &settings);

    FirstRunWizard *runWillard = 0;

    if (w->getGraphicalStatus() && FirstRunWizard::shouldDisplay(&settings))
    {
        runWillard = new FirstRunWizard(&settings, &qtTranslator, &myappTranslator);
        QObject::connect(runWillard, SIGNAL(finished(int)), w, SLOT(changeWindowStatus()));
        runWillard->show();
    }
    else
    {
        w->changeWindowStatus();
    }

    w->setAppTranslator(&qtTranslator);
    w->setTranslator(&myappTranslator);

    AppLaunchHelper mainAppHelper(&settings, w->getGraphicalStatus());
    mainAppHelper.initRunMethods();

    QObject::connect(joypad_worker,
                     SIGNAL(joysticksRefreshed(QMap<SDL_JoystickID, InputDevice*>*)),
                     w, SLOT(fillButtons(QMap<SDL_JoystickID, InputDevice*>*)));

    QObject::connect(w, SIGNAL(joystickRefreshRequested()), joypad_worker, SLOT(refresh()));
    QObject::connect(joypad_worker, SIGNAL(joystickRefreshed(InputDevice*)),
                     w, SLOT(fillButtons(InputDevice*)));

    QObject::connect(a, SIGNAL(aboutToQuit()), localServer, SLOT(close()));
    QObject::connect(a, SIGNAL(aboutToQuit()), w, SLOT(saveAppConfig()));
    QObject::connect(a, SIGNAL(aboutToQuit()), w, SLOT(removeJoyTabs()));
    QObject::connect(a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));

#ifdef Q_OS_WIN
    QObject::connect(a, SIGNAL(aboutToQuit()), &mainAppHelper, SLOT(appQuitPointerPrecision()));
#endif
    QObject::connect(localServer, SIGNAL(clientdisconnect()), w, SLOT(handleInstanceDisconnect()));

#ifdef USE_SDL_2
    QObject::connect(w, SIGNAL(mappingUpdated(QString,InputDevice*)), joypad_worker, SLOT(refreshMapping(QString,InputDevice*)));
    QObject::connect(joypad_worker, SIGNAL(deviceUpdated(int,InputDevice*)), w, SLOT(testMappingUpdateNow(int,InputDevice*)));
    QObject::connect(joypad_worker, SIGNAL(deviceRemoved(SDL_JoystickID)), w, SLOT(removeJoyTab(SDL_JoystickID)));
    QObject::connect(joypad_worker, SIGNAL(deviceAdded(InputDevice*)), w, SLOT(addJoyTab(InputDevice*)));
#endif

#ifdef Q_OS_WIN
    // Raise process priority. Helps reduce timer delays caused by
    // the running of other processes.
    bool raisedPriority = WinExtras::raiseProcessPriority();
    if (!raisedPriority)
    {
        appLogger.LogInfo(QObject::tr("Could not raise process priority."));
        //outstream << QObject::tr("Could not raise process priority.") << endl;
    }
#else
    // Raise main thread prority. Helps reduce timer delays caused by
    // the running of other processes.
    QThread::currentThread()->setPriority(QThread::HighPriority);
#endif

    int app_result = a->exec();

    appLogger.LogInfo(QObject::tr("Quitting Program"));

    deleteInputDevices(joysticks);
    delete joysticks;
    joysticks = 0;

    delete joypad_worker;
    joypad_worker = 0;

    delete localServer;
    localServer = 0;

    AntKeyMapper::getInstance()->deleteInstance();

#ifdef Q_OS_UNIX
    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

    if (QApplication::platformName() == QStringLiteral("xcb"))
    {
        #endif
    X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    }
        #endif
    #endif

    EventHandlerFactory::getInstance()->handler()->cleanup();
    EventHandlerFactory::getInstance()->deleteInstance();
#endif

    delete w;
    w = 0;

    delete a;
    a = 0;

    return app_result;
}