예제 #1
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);
}
예제 #2
0
파일: qt_term.cpp 프로젝트: zsx/gnuplot
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);
}
예제 #3
0
// Helper function called by qt_connectToServer()
void qt_connectToServer(const QString& server, bool retry = true)
{
	bool connectToWidget = (server != qt_localServerName);

	// The QLocalSocket::waitForConnected does not respect the time out argument when the
	// gnuplot_qt application is not yet started. To wait for it, we need to implement the timeout ourselves
	QDateTime timeout = QDateTime::currentDateTime().addMSecs(1000);
	do
	{
		qt_socket.connectToServer(server);
		qt_socket.waitForConnected(200);
		// TODO: yield CPU ?
	}
	while((qt_socket.state() != QLocalSocket::ConnectedState) && (QDateTime::currentDateTime() < timeout));

	// Still not connected...
	if ((qt_socket.state() != QLocalSocket::ConnectedState) && retry)
	{
		// The widget could not be reached: start a gnuplot_qt program which will create a QtGnuplotApplication
		if (connectToWidget)
		{
			qDebug() << "Could not connect to widget" << qt_optionWidget << ". Starting a QtGnuplotApplication";
			qt_optionWidget = QString();
			qt_connectToServer(qt_localServerName);
		}
		// The gnuplot_qt program could not be reached: try to start a new one
		else
		{
			qDebug() << "Could not connect gnuplot_qt" << qt_optionWidget << ". Starting a new one";
			execGnuplotQt();
			qt_connectToServer(qt_localServerName, false);
		}
	}
}
예제 #4
0
bool Application::IsAlreadyRunning () const
{
	QLocalSocket socket;
	socket.connectToServer (GetSocketName ());
	if (socket.waitForConnected () ||
			socket.state () == QLocalSocket::ConnectedState)
	{
		QDataStream out (&socket);
		out << Arguments_;
		if (socket.waitForBytesWritten ())
			return true;
        if (socket.error() == QLocalSocket::UnknownSocketError)
            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;
}
예제 #5
0
    void connectToRemote(const QString & remoteName)
    {
        emit pulseOutboundConnect(remoteName);

        QMutexLocker locker(&outboundLock);
        while (outbound.state() != QLocalSocket::ConnectedState) {
            outboundWait.wait(&outboundLock,30*1000);

        }
    }
RKGraphicsDeviceBackendTransmitter* RKGraphicsDeviceBackendTransmitter::instance () {
	if (_instance) return _instance;
	RK_TRACE (GRAPHICS_DEVICE);

	QLocalSocket *con = new QLocalSocket ();
	con->connectToServer (RKRBackendProtocolBackend::rkdServerName ());
	con->waitForConnected (2000);
	if (con->state () == QLocalSocket::ConnectedState) {
		con->write (RKRBackendTransmitter::instance ()->connectionToken ().toLocal8Bit ().data ());
		con->write ("\n");
		con->waitForBytesWritten (1000);
		_instance = new RKGraphicsDeviceBackendTransmitter (con, true);
		return _instance;
	}
	return 0;
}
예제 #7
0
파일: qt_term.cpp 프로젝트: zsx/gnuplot
int qt_waitforinput(void)
{
#ifdef USE_MOUSE
	fd_set read_fds;
	int stdin_fd  = fileno(stdin);
	int socket_fd = qt_socket.socketDescriptor();

	if (!qt_initialized || (socket_fd < 0) || (qt_socket.state() != QLocalSocket::ConnectedState))
		return getchar();

	// Gnuplot event loop
	do
	{
		// Watch file descriptors
		FD_ZERO(&read_fds);
		FD_SET(socket_fd, &read_fds);
		if (!paused_for_mouse)
			FD_SET(stdin_fd, &read_fds);

		// Wait for input
		if (select(socket_fd+1, &read_fds, NULL, NULL, NULL) < 0)
		{
			fprintf(stderr, "Qt terminal communication error: select() error\n");
			break;
		}

		// Terminal event coming
		if (FD_ISSET(socket_fd, &read_fds))
		{
			qt_socket.waitForReadyRead(-1);
			while (qt_socket.bytesAvailable() >= sizeof(gp_event_t))
			{
				struct gp_event_t event;
				qt_socket.read((char*) &event, sizeof(gp_event_t));
				/// @todo don't process mouse move events if others are in the queue
				if (qt_processTermEvent(&event))
					return '\0'; // exit from paused_for_mouse
			}
		}
	} while (paused_for_mouse || (!paused_for_mouse && !FD_ISSET(stdin_fd, &read_fds)));
#endif
	return getchar();
}
예제 #8
0
int CurlFtp::closeDataChannel2()
{
    QLocalSocket *depSock = this->qdsock2;
    qDebug()<<"sock2:"<<depSock<<depSock->isOpen()<<depSock->state();
    // this->qdsock2->close();
    // delete this->qdsock2;
    // this->qdsock2 = NULL;
    
    // this->qdsock2 = NULL;

    this->curlWriteDataRouteServer->close();
    delete this->curlWriteDataRouteServer;
    this->curlWriteDataRouteServer = NULL;

    depSock->deleteLater();
    // depSock->close();
    // delete depSock;
    // depSock = NULL;

    return 0;
}
예제 #9
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;
}
예제 #10
0
파일: server.cpp 프로젝트: ext5/CopyQ
void Server::onNewConnection()
{
    QLocalSocket* socket = m_server->nextPendingConnection();
    if (!socket) {
        log("No pending client connections!", LogError);
    } else if ( socket->state() != QLocalSocket::ConnectedState ) {
        log("Client is not connected!", LogError);
        socket->deleteLater();
    } else {
        QScopedPointer<ClientSocket> clientSocket( new ClientSocket(socket) );

        const Arguments args = clientSocket->readArguments();
        if ( !args.isEmpty() ) {
            ++m_socketCount;
            connect( clientSocket.data(), SIGNAL(destroyed()),
                     this, SLOT(onSocketClosed()) );
            connect( this, SIGNAL(destroyed()),
                     clientSocket.data(), SLOT(close()) );
            connect( this, SIGNAL(destroyed()),
                     clientSocket.data(), SLOT(deleteAfterDisconnected()) );
            emit newConnection( args, clientSocket.take() );
        }
    }
}
예제 #11
0
파일: main.cpp 프로젝트: phob/antimicro
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;
}
예제 #12
0
int qt_waitforinput(void)
{
#ifdef USE_MOUSE
	fd_set read_fds;
	int stdin_fd  = fileno(stdin);
	int socket_fd = qt_socket.socketDescriptor();

	if (!qt_initialized || (socket_fd < 0) || (qt_socket.state() != QLocalSocket::ConnectedState))
		return getchar();

	// Gnuplot event loop
	do
	{
		// Watch file descriptors
		FD_ZERO(&read_fds);
		FD_SET(socket_fd, &read_fds);
		if (!paused_for_mouse)
			FD_SET(stdin_fd, &read_fds);

		// Wait for input
		if (select(socket_fd+1, &read_fds, NULL, NULL, NULL) < 0)
		{
			// Display the error message except when Ctrl + C is pressed
			if (errno != 4)
				fprintf(stderr, "Qt terminal communication error: select() error %i %s\n", errno, strerror(errno));
			break;
		}

		// Terminal event coming
		if (FD_ISSET(socket_fd, &read_fds))
		{
			if (!(qt_socket.waitForReadyRead(-1))) {
				// Must be a socket error; we need to restart qt_gnuplot
				qDebug() << "Error: gnuplot_qt socket not responding";
				qt_gnuplot_qtStarted = false;
				return '\0';
			}

			// Temporary event for mouse move events. If several consecutive
			// move events are received, only transmit the last one.
			gp_event_t tempEvent;
			tempEvent.type = -1;
			if (qt_socket.bytesAvailable() < sizeof(gp_event_t)) {
				qDebug() << "Error: short read from gnuplot_qt socket";
				return '\0';
			}
			while (qt_socket.bytesAvailable() >= sizeof(gp_event_t))
			{
				struct gp_event_t event;
				qt_socket.read((char*) &event, sizeof(gp_event_t));
				// Delay move events
				if (event.type == GE_motion)
					tempEvent = event;
				// Other events. Replay the last move event if present
				else
				{
					if (tempEvent.type == GE_motion)
					{
						qt_processTermEvent(&tempEvent);
						tempEvent.type = -1;
					}
					if (qt_processTermEvent(&event))
						return '\0'; // exit from paused_for_mouse
				}
			}
			// Replay move event
			if (tempEvent.type == GE_motion)
				qt_processTermEvent(&tempEvent);
		}
	} while (paused_for_mouse || (!paused_for_mouse && !FD_ISSET(stdin_fd, &read_fds)));
#endif
	return getchar();
}
예제 #13
0
파일: test.cpp 프로젝트: waitman/monav
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;
	}
}
예제 #14
0
파일: main.cpp 프로젝트: Pater1/antimicro
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;
}