Esempio n. 1
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QLocalSocket localSocket;
    localSocket.connectToServer("bloggerQml", QIODevice::ReadOnly);
    if(localSocket.waitForConnected(5000))
    {
        // there is already an application running
        qDebug() << "Application is already running.";
        QMessageBox::information(0, QObject::tr("Erro"), QObject::tr("A aplicação já está a ser executada."), QMessageBox::Ok);
        return 0;
    }
    QLocalServer localServer;
    localServer.listen("bloggerQml");

    BloggerLoader bloggerloader;
    bloggerloader.loadBlogsFromFile();

    BloggerProxyModel model;
    model.setSourceModel(bloggerloader.model());

    Helper helper;
    QtQuick2ApplicationViewer viewer;
    viewer.rootContext()->setContextProperty("blogsModel", &model);
    viewer.rootContext()->setContextProperty("helper", &helper);
    viewer.rootContext()->setContextProperty("bloggerloader", &bloggerloader);

    viewer.setMainQmlFile(QStringLiteral("qml/blogerQML/main.qml"));
    viewer.showExpanded();

    int res = app.exec();
    bloggerloader.saveDB();
    return res;
}
/*!
  Configure the QJsonServer to listen on a new Unix local socket \a socketname using QJsonAuthority file \a authority.
  If the \a authority is omitted or NULL, all connections will be automatically authorized and
  a unique identifier generated for each new connection. Returns true if the socket could be opened.

  Does \b{not} take ownership of the \a authority object.
 */
bool QJsonServer::listen(const QString &socketname, QJsonAuthority *authority)
{
    QLocalServer::removeServer(socketname);
    QLocalServer *server = new QLocalServer(this);
    Q_D(QJsonServer);
    d->m_localServers.insert(server, authority);
    QObject::connect(server, SIGNAL(newConnection()), this, SLOT(handleLocalConnection()));
    if (!server->listen(socketname)) {
        qCritical() << Q_FUNC_INFO << "Unable to listen on socket:" << socketname;
        d->m_localServers.remove(server);
        return false;
    }
    return true;
}
void MobilityConnection::connectToSimulator()
{
    // 1. check availability
    QLocalSocket *socket = new QLocalSocket;
    QString simVersion = SimulatorConnection::instance()->simulatorVersion().toString();
    socket->connectToServer(QLatin1String(SIMULATOR_MOBILITY_SERVERNAME) + simVersion, QLocalSocket::ReadWrite);
    if (!socket->waitForConnected(1000)) {
        qFatal("Could not connect to mobility server");
        socket->deleteLater();
        return;
    }
    mSendSocket = socket;

    // 2. Create the local server used for initiating the backchannel.
    const qint64 pid = QCoreApplication::applicationPid();
    QLocalServer *server = new QLocalServer(this);
    if (!server->listen(qt_mobilityServerName(simVersion, pid)))
        qFatal("Can't create local mobility server for this application.");

    // 3. Send initial application connect command.
    ApplicationConnectCommand command;
    ApplicationConnectCommand::Request &request = command.request;
    request.applicationPid = pid;
    request.applicationName[0] = 0;
    request.version = mobilityVersion;
    qt_sendAndReceiveApplicationConnect(socket, command);

    mSimulatorVersion = command.reply.version;

    // We usually want to get the initial state from the simulator directly, probably
    // before the event loop is started up. Hence we block until the simulator has established
    // the back channel.
    if (!server->waitForNewConnection(1000))
        qFatal("Simulator didn't establish mobility-backchannel on time");
    mReceiveSocket = server->nextPendingConnection();
    server->close();

    connect(mReceiveSocket, SIGNAL(readyRead()), SLOT(onReadyRead()));
}
Esempio n. 4
0
int main(int argc, char* argv[])
{
    QApplication application(argc, argv);

    application.setApplicationName(PROJECT_NAME);
    application.setOrganizationName(ORGANIZATION_NAME);
    application.setOrganizationDomain(ORGANIZATION_DOMAIN);

    // Check for other instances already running

    QLocalSocket singleInstanceSocket;
    singleInstanceSocket.connectToServer(PROJECT_NAME);

    if (singleInstanceSocket.waitForConnected(500))
    {
        singleInstanceSocket.close();
        qCritical() << "Application is already started";
        return EXIT_FAILURE;
    }

    // Initialize single instance server to prevent other instances to start

    QLocalServer::removeServer(PROJECT_NAME);
    QLocalServer singleInstanceServer;

    if (!singleInstanceServer.listen(PROJECT_NAME))
    {
        qCritical() << "Unable to start single instance server";
        return EXIT_FAILURE;
    }

    application.setQuitOnLastWindowClosed(false);

    MainWindow mainWindow;
    mainWindow.show();

    return application.exec();
}
Esempio n. 5
0
void Server::start() {
  QString sockPath = "/tmp/qeventloop_test";
  QLocalServer* server = new QLocalServer();
  QFile sockFile(sockPath);
  if (sockFile.exists()) {
    sockFile.remove();
  }
  server->listen(sockPath);
  QObject::connect(server, &QLocalServer::newConnection, [this, server]() {
    m_sock = server->nextPendingConnection();
    QObject::connect(m_sock, &QLocalSocket::disconnected, m_sock, &QLocalSocket::deleteLater);
    QObject::connect(m_sock, &QLocalSocket::readyRead, this, &Server::onReadyRead,
                     Qt::QueuedConnection);

    sendData(m_sock, 1);

    QEventLoop loop;
    QObject::connect(&m_result1, &Result::ready, &loop, &QEventLoop::quit);
    qDebug("start event loop to wait for 1");
    loop.exec();
    qDebug("end event loop to wait for 1");
  });
}
Esempio n. 6
0
int main(int argc, char *argv[])
{
	Local a(argc, argv);
	int single;
	if ((single = Config::getValue("/Interface/Single", 1))){
		QLocalSocket socket;
		socket.connectToServer("BiliLocalInstance");
		if (socket.waitForConnected()){
			QDataStream s(&socket);
			s << a.arguments().mid(1);
			socket.waitForBytesWritten();
			return 0;
		}
	}
	loadTranslator();
	setDefaultFont();
	setToolTipBase();
	Interface w;
	Plugin::loadPlugins();
	if (!w.testAttribute(Qt::WA_WState_ExplicitShowHide)){
		w.show();
	}
	w.tryLocal(a.arguments().mid(1));
	QLocalServer *server = nullptr;
	if (single){
		server = new QLocalServer(lApp);
		server->listen("BiliLocalInstance");
		QObject::connect(server, &QLocalServer::newConnection, [&](){
			QLocalSocket *r = server->nextPendingConnection();
			r->waitForReadyRead();
			QDataStream s(r);
			QStringList args;
			s >> args;
			delete r;
			w.tryLocal(args);
		});
	}
Esempio n. 7
0
int main(int argc, const char* argv[]) {
    disableQtBearerPoll(); // Fixes wifi ping spikes
    
    QString applicationName = "High Fidelity Interface - " + qgetenv("USERNAME");

    bool instanceMightBeRunning = true;

#ifdef Q_OS_WIN
    // Try to create a shared memory block - if it can't be created, there is an instance of
    // interface already running. We only do this on Windows for now because of the potential
    // for crashed instances to leave behind shared memory instances on unix.
    QSharedMemory sharedMemory { applicationName };
    instanceMightBeRunning = !sharedMemory.create(1, QSharedMemory::ReadOnly);
#endif

    if (instanceMightBeRunning) {
        // Try to connect and send message to existing interface instance
        QLocalSocket socket;

        socket.connectToServer(applicationName);

        static const int LOCAL_SERVER_TIMEOUT_MS = 500;

        // Try to connect - if we can't connect, interface has probably just gone down
        if (socket.waitForConnected(LOCAL_SERVER_TIMEOUT_MS)) {

            QStringList arguments;
            for (int i = 0; i < argc; ++i) {
                arguments << argv[i];
            }

            QCommandLineParser parser;
            QCommandLineOption urlOption("url", "", "value");
            parser.addOption(urlOption);
            parser.process(arguments);

            if (parser.isSet(urlOption)) {
                QUrl url = QUrl(parser.value(urlOption));
                if (url.isValid() && url.scheme() == HIFI_URL_SCHEME) {
                    qDebug() << "Writing URL to local socket";
                    socket.write(url.toString().toUtf8());
                    if (!socket.waitForBytesWritten(5000)) {
                        qDebug() << "Error writing URL to local socket";
                    }
                }
            }

            socket.close();

            qDebug() << "Interface instance appears to be running, exiting";

            return EXIT_SUCCESS;
        }

#ifdef Q_OS_WIN
        return EXIT_SUCCESS;
#endif
    }

    // Check OpenGL version.
    // This is done separately from the main Application so that start-up and shut-down logic within the main Application is
    // not made more complicated than it already is.
    {
        OpenGLVersionChecker openGLVersionChecker(argc, const_cast<char**>(argv));
        if (!openGLVersionChecker.isValidVersion()) {
            qCDebug(interfaceapp, "Early exit due to OpenGL version.");
            return 0;
        }
    }

    QElapsedTimer startupTime;
    startupTime.start();

    // Debug option to demonstrate that the client's local time does not
    // need to be in sync with any other network node. This forces clock
    // skew for the individual client
    const char* CLOCK_SKEW = "--clockSkew";
    const char* clockSkewOption = getCmdOption(argc, argv, CLOCK_SKEW);
    if (clockSkewOption) {
        int clockSkew = atoi(clockSkewOption);
        usecTimestampNowForceClockSkew(clockSkew);
        qCDebug(interfaceapp, "clockSkewOption=%s clockSkew=%d", clockSkewOption, clockSkew);
    }

    // Oculus initialization MUST PRECEDE OpenGL context creation.
    // The nature of the Application constructor means this has to be either here,
    // or in the main window ctor, before GL startup.
    Application::initPlugins();

    int exitCode;
    {
        QSettings::setDefaultFormat(QSettings::IniFormat);
        Application app(argc, const_cast<char**>(argv), startupTime);

        // Setup local server
        QLocalServer server { &app };

        // We failed to connect to a local server, so we remove any existing servers.
        server.removeServer(applicationName);
        server.listen(applicationName);

        QObject::connect(&server, &QLocalServer::newConnection, &app, &Application::handleLocalServerConnection);

        QTranslator translator;
        translator.load("i18n/interface_en");
        app.installTranslator(&translator);

        qCDebug(interfaceapp, "Created QT Application.");
        exitCode = app.exec();
        server.close();
    }

    Application::shutdownPlugins();

    qCDebug(interfaceapp, "Normal exit.");
    return exitCode;
}
Esempio n. 8
0
RunControl *WinRtDebugSupport::createDebugRunControl(WinRtRunConfiguration *runConfig,
                                                     Core::Id mode,
                                                     QString *errorMessage)
{
    // FIXME: This is just working for local debugging;
    using namespace Debugger;
    DebuggerStartParameters params;
    params.startMode = AttachExternal;
    // The first Thread needs to be resumed manually.
    params.commandsAfterConnect = "~0 m";

    QFileInfo debuggerHelper(QCoreApplication::applicationDirPath()
                             + QLatin1String("/winrtdebughelper.exe"));
    if (!debuggerHelper.isExecutable()) {
        *errorMessage = tr("The WinRT debugging helper is missing from your Qt Creator "
                           "installation. It was assumed to be located at %1").arg(
                    debuggerHelper.absoluteFilePath());
        return 0;
    }

    if (useQmlDebugging(runConfig)) {
        quint16 qmlDebugPort = 0;
        if (!getFreePort(qmlDebugPort, errorMessage))
            return 0;
        runConfig->setArguments(runConfig->arguments() + QLatin1Char(' ')
                    + QmlDebug::qmlDebugTcpArguments(QmlDebug::QmlDebuggerServices, qmlDebugPort));
        params.qmlServerAddress = QHostAddress::LocalHost;
        params.qmlServerPort = qmlDebugPort;
    }

    WinRtRunnerHelper *runner = new WinRtRunnerHelper(runConfig, errorMessage);
    if (!errorMessage->isEmpty())
        return 0;

    QLocalServer server;
    server.listen(QLatin1String("QtCreatorWinRtDebugPIDPipe"));

    runner->debug(debuggerHelper.absoluteFilePath());
    if (!runner->waitForStarted()) {
        *errorMessage = tr("Cannot start the WinRT Runner Tool.");
        return 0;
    }

    if (!server.waitForNewConnection(10000)) {
        *errorMessage = tr("Cannot establish connection to the WinRT debugging helper.");
        return 0;
    }

    while (server.hasPendingConnections()) {
        QLocalSocket *connection = server.nextPendingConnection();
        if (connection->waitForReadyRead(1000)) {
            const QByteArray &output = connection->readAll();
            QList<QByteArray> arg = output.split(':');
            if (arg.first() == "PID") {
                bool ok =false;
                params.attachPID = arg.last().toInt(&ok);
                if (!ok) {
                    *errorMessage = tr("Cannot extract the PID from the WinRT debugging helper. "
                                       "(output: %1)").arg(QString::fromLocal8Bit(output));
                    return 0;
                }
                server.close();
                Debugger::DebuggerRunControl *debugRunControl
                        = createDebuggerRunControl(params, runConfig, errorMessage, mode);
                runner->setDebugRunControl(debugRunControl);
                new WinRtDebugSupport(debugRunControl, runner);
                return debugRunControl;
            }
        }
    }

    server.close();

    *errorMessage = tr("Cannot create an appropriate run control for "
                       "the current run configuration.");

    return 0;
}
void QHelpSearchIndexWriter::run()
{
#if !defined(QT_NO_EXCEPTIONS)
    try {
#endif
        QMutexLocker mutexLocker(&mutex);

        if (m_cancel)
            return;

        const bool reindex = this->m_reindex;
        const QString collectionFile(this->m_collectionFile);

        mutexLocker.unlock();

        QHelpEngineCore engine(collectionFile, 0);
        if (!engine.setupData())
            return;

        const QLatin1String key("CluceneIndexedNamespaces");
        if (reindex)
            engine.setCustomValue(key, QLatin1String(""));

        QMap<QString, QDateTime> indexMap;
        const QLatin1String oldKey("CluceneSearchNamespaces");
        if (!engine.customValue(oldKey, QString()).isNull()) {
            // old style qhc file < 4.4.2, need to convert...
            const QStringList indexedNamespaces
                = engine.customValue(oldKey).toString()
                  .split(QLatin1String("|"), QString::SkipEmptyParts);
            foreach (const QString &nameSpace, indexedNamespaces)
                indexMap.insert(nameSpace, QDateTime());
            engine.removeCustomValue(oldKey);
        } else {
            QDataStream dataStream(engine.customValue(key).toByteArray());
            dataStream >> indexMap;
        }

        QString indexPath = m_indexFilesFolder;

        QFileInfo fInfo(indexPath);
        if (fInfo.exists() && !fInfo.isWritable()) {
            qWarning("Full Text Search, could not create index (missing permissions for '%s').",
                     qPrintable(indexPath));
            return;
        }

        emit indexingStarted();

        QCLuceneIndexWriter *writer = 0;
        QCLuceneStandardAnalyzer analyzer;
        const QStringList registeredDocs = engine.registeredDocumentations();

        QLocalSocket localSocket;
        localSocket.connectToServer(QString(QLatin1String("QtAssistant%1"))
                                    .arg(QLatin1String(QT_VERSION_STR)));

        QLocalServer localServer;
        bool otherInstancesRunning = true;
        if (!localSocket.waitForConnected()) {
            otherInstancesRunning = false;
            localServer.listen(QString(QLatin1String("QtAssistant%1"))
                               .arg(QLatin1String(QT_VERSION_STR)));
        }

        // check if it's locked, and if the other instance is running
        if (!otherInstancesRunning && QCLuceneIndexReader::isLocked(indexPath))
            QCLuceneIndexReader::unlock(indexPath);

        if (QCLuceneIndexReader::isLocked(indexPath)) {
            // poll unless indexing finished to fake progress
            while (QCLuceneIndexReader::isLocked(indexPath)) {
                mutexLocker.relock();
                if (m_cancel)
                    break;
                mutexLocker.unlock();
                this->sleep(1);
            }
            emit indexingFinished();
            return;
        }

        if (QCLuceneIndexReader::indexExists(indexPath) && !reindex) {
            foreach(const QString &namespaceName, registeredDocs) {
                mutexLocker.relock();
                if (m_cancel) {
                    emit indexingFinished();
                    return;
                }
                mutexLocker.unlock();

                if (!indexMap.contains(namespaceName)) {
                    // make sure we remove some partly indexed stuff
                    removeDocuments(indexPath, namespaceName);
                } else {
                    QString path = engine.documentationFileName(namespaceName);
                    if (indexMap.value(namespaceName)
                        < QFileInfo(path).lastModified()) {
                        // make sure we remove some outdated indexed stuff
                        indexMap.remove(namespaceName);
                        removeDocuments(indexPath, namespaceName);
                    }

                    if (indexMap.contains(namespaceName)) {
                        // make sure we really have content indexed for namespace
                        QCLuceneTermQuery query(QCLuceneTerm(NamespaceField, namespaceName));
                        QCLuceneIndexSearcher indexSearcher(indexPath);
                        QCLuceneHits hits = indexSearcher.search(query);
                        if (hits.length() <= 0)
                            indexMap.remove(namespaceName);
                    }
                }
            }
Esempio n. 10
0
RunControl *WinRtDebugSupport::createDebugRunControl(WinRtRunConfiguration *runConfig,
                                                     RunMode mode,
                                                     QString *errorMessage)
{
    // FIXME: This is just working for local debugging;
    using namespace Debugger;
    DebuggerStartParameters params;
    params.startMode = AttachExternal;
    params.languages |= CppLanguage;
    params.breakOnMain = mode == DebugRunModeWithBreakOnMain;
    // The first Thread needs to be resumed manually.
    params.commandsAfterConnect = "~0 m";
    Kit *kit = runConfig->target()->kit();
    params.debuggerCommand = DebuggerKitInformation::debuggerCommand(kit).toString();
    if (ToolChain *tc = ToolChainKitInformation::toolChain(kit))
        params.toolChainAbi = tc->targetAbi();

    QFileInfo debuggerHelper(QCoreApplication::applicationDirPath()
                             + QLatin1String("/winrtdebughelper.exe"));
    if (!debuggerHelper.isExecutable()) {
        *errorMessage = tr("The WinRT debugging helper is missing from your Qt Creator "
                           "installation. It was assumed to be located at %1").arg(
                    debuggerHelper.absoluteFilePath());
        return 0;
    }

    WinRtRunnerHelper *runner = new WinRtRunnerHelper(runConfig, errorMessage);
    if (!errorMessage->isEmpty())
        return 0;

    QLocalServer server;
    server.listen(QLatin1String("QtCreatorWinRtDebugPIDPipe"));

    runner->debug(debuggerHelper.absoluteFilePath());
    if (!runner->waitForStarted()) {
        *errorMessage = tr("Cannot start the WinRT Runner Tool.");
        return 0;
    }

    if (!server.waitForNewConnection(10000)) {
        *errorMessage = tr("Cannot establish connection to the WinRT debugging helper.");
        return 0;
    }

    while (server.hasPendingConnections()) {
        QLocalSocket *connection = server.nextPendingConnection();
        if (connection->waitForReadyRead(1000)) {
            const QByteArray &output = connection->readAll();
            QList<QByteArray> arg = output.split(':');
            if (arg.first() == "PID") {
                bool ok =false;
                params.attachPID = arg.last().toInt(&ok);
                if (!ok) {
                    *errorMessage = tr("Cannot extract the PID from the WinRT debugging helper. "
                                       "(output: %1)").arg(QString::fromLocal8Bit(output));
                    return 0;
                }
                server.close();
                params.runConfiguration = runConfig;
                Debugger::DebuggerRunControl *debugRunControl
                        = createDebuggerRunControl(params, errorMessage);
                runner->setRunControl(debugRunControl);
                new WinRtDebugSupport(debugRunControl, runner);
                return debugRunControl;
            }
        }
    }

    server.close();

    *errorMessage = tr("Cannot create an appropriate run control for "
                       "the current run configuration.");

    return 0;
}