Example #1
1
void
CommandSender::sendToServer( const int profileId, const CliOptions& options )
{
    ENTER()(profileId)(options);

    QString uname = qgetenv( "USER" ); // UNIX
    if( uname.isEmpty() )
        uname = qgetenv( "USERNAME" ); // Windows
    QString serverName = QString("redtimer-%1-%2").arg(uname).arg(profileId);

    DEBUG()(serverName);

    QLocalSocket* socket = new QLocalSocket( this );
    sockets_.insert( socket, true );

    connect( socket, &QLocalSocket::connected,    [=](){ sendToSocket(socket, options); } );
    connect( socket, &QLocalSocket::disconnected, [=](){ deleteSocket(socket); } );

    socket->connectToServer( serverName, QIODevice::ReadWrite );
    if( !socket->waitForConnected() )
        deleteSocket( socket );

    RETURN();
}
Example #2
1
void ApplicationCore::slotHandleUniqueApplicationConnection()
{
    QLocalSocket *socket = m_uniqueApplicationServer.nextPendingConnection();
    connect(socket, &QLocalSocket::readyRead, socket, [this, socket](){
        if (!socket->canReadLine())
            return;
        while (socket->canReadLine()) {
            const QByteArray data = socket->readLine().trimmed();
            if (data.startsWith(StartTaskCommand)) {
                bool ok = true;
                const TaskId id = data.mid(StartTaskCommand.length()).toInt(&ok);
                if (ok) {
                    m_timeTracker.slotStartEvent(id);
                } else {
                    qWarning() << "Received invalid argument:" << data;
                }
            } else if (data.startsWith(RaiseWindowCommand)) {
                // nothing to do, see below
            }
        }
        socket->deleteLater();
        showMainWindow(ApplicationCore::ShowMode::ShowAndRaise);
    });
}
bool ServerCatchcopy::listen()
{
	QLocalSocket socketTestConnection;
	pathSocket=ExtraSocketCatchcopy::pathSocket();
	socketTestConnection.connectToServer(pathSocket);
	if(socketTestConnection.waitForConnected(CATCHCOPY_COMMUNICATION_TIMEOUT))
	{
		error_string="Other server is listening";
		emit error(error_string);
		return false;
	}
	else
	{
		server.removeServer(pathSocket);
		if(server.listen(pathSocket))
			return true;
		else
		{
			error_string=QString("Unable to listen %1: %2").arg(pathSocket).arg(server.errorString());
			emit error(error_string);
			return false;
		}
	}
}
Example #4
0
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() );
        }
    }
}
bool GUISingleApplication::sendMessage(const QByteArray &message, int timeout)
{
    QLocalSocket socket;
    bool connected = false;
    for(int i = 0; i < 2; i++) {
        socket.connectToServer(d_ptr->serverName);
        connected = socket.waitForConnected(timeout/2);
        if (connected || i > 0)
            break;
        int ms = 250;
#if defined(Q_OS_WIN)
        Sleep(DWORD(ms));
#else
        usleep(ms*1000);
#endif
    }
    if (!connected)
        return false;

    QDataStream ds(&socket);
    ds << message;
    socket.waitForBytesWritten(timeout);
    return true;
}
Example #6
0
void BrowserApplication::newLocalSocketConnection()
{
    QLocalSocket *socket = m_localServer->nextPendingConnection();
    if (!socket)
        return;
    socket->waitForReadyRead(1000);
    QTextStream stream(socket);
    QString url;
    stream >> url;
    if (!url.isEmpty()) {
        QSettings settings;
        settings.beginGroup(QLatin1String("general"));
        int openLinksIn = settings.value(QLatin1String("openLinksIn"), 0).toInt();
        settings.endGroup();
        if (openLinksIn == 1)
            newMainWindow();
        else
            mainWindow()->tabWidget()->newTab();
        openUrl(url);
    }
    delete socket;
    mainWindow()->raise();
    mainWindow()->activateWindow();
}
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;
}
Example #8
0
bool QtLocalPeer::sendMessage(const QString& message, int timeout)
{
	if(!isClient())
	{
		return false;
	}

	QLocalSocket socket;
	bool connOk = false;

	for(int i = 0; i < 2; i++)
	{
		// Try twice, in case the other instance is just starting up
		socket.connectToServer(socketName);
		connOk = socket.waitForConnected(timeout / 2);

		if(connOk || i)
		{
			break;
		}

		int ms = 250;
#if defined(Q_OS_WIN)
		Sleep(DWORD (ms));
#else
		struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
		nanosleep(&ts, NULL);
#endif
	}

	if(!connOk)
	{
		return false;
	}

	QByteArray uMsg(message.toUtf8());
	QDataStream ds(&socket);
	ds.writeBytes(uMsg.constData(), uMsg.size());
	bool res = socket.waitForBytesWritten(timeout);

	if(res)
	{
		res &= socket.waitForReadyRead(timeout);   // wait for ack

		if(res)
		{
			res &= (socket.read(qstrlen(ack)) == ack);
		}
	}

	return res;
}
Example #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;
}
Example #10
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();

}
Example #11
0
void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    // Why doesn't Qt have a blocking stream that takes care of this shait???
    while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {
        if (!socket->isValid()) // stale request
            return;
        socket->waitForReadyRead(1000);
    }
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    //qDebug() << "RCV: remaining" << remaining;
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
        //qDebug() << "RCV: got" << got << "remaining" << remaining;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    //### error check: got<0
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    // ### async this
    QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    emit messageReceived(message, socket); // ##(might take a long time to return)
}
Example #12
0
void QtLocalPeer::receiveConnection()
{
	QLocalSocket* socket = server->nextPendingConnection();

	if(!socket)
	{
		return;
	}

	while(socket->bytesAvailable() < (int) sizeof(quint32))
	{
		socket->waitForReadyRead();
	}

	QDataStream ds(socket);
	QByteArray uMsg;
	quint32 remaining;
	ds >> remaining;
	uMsg.resize(remaining);
	int got = 0;
	char* uMsgBuf = uMsg.data();

	do
	{
		got = ds.readRawData(uMsgBuf, remaining);
		remaining -= got;
		uMsgBuf += got;
	}
	while(remaining && got >= 0 && socket->waitForReadyRead(2000));

	if(got < 0)
	{
		qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
		delete socket;
		return;
	}

	QString message(QString::fromUtf8(uMsg));
	socket->write(ack, qstrlen(ack));
	socket->waitForBytesWritten(1000);
	delete socket;
	emit messageReceived(message);  //### (might take a long time to return)
}
Example #13
0
bool mASocketManager::openFileOnRemote(const QString &_path)
{
    bool r = false;
    
    QString path = QFileInfo(_path).canonicalFilePath();
    path.append('\n');
    
    QLocalSocket socket;
    socket.connectToServer(MA_LOCAL_SERVER_NAME);
    
    if(socket.waitForConnected(MAX_TIMEOUT_CLIENT))
    {
        socket.write(path.toUtf8());
        socket.flush();
        socket.waitForBytesWritten(MAX_TIMEOUT_CLIENT);
        r = true;
    }
    
    socket.close();
    
    return r;
}
Example #14
0
void SocketExternalInstance::loadFile(const QString &file_name) const
{
#ifdef _WIN32
    ::AllowSetForegroundWindow(-1);
#endif
    QLocalSocket socket;
    socket.connectToServer(GLOG_SERVICE_NAME);
    if (!socket.waitForConnected(1000)) {
        LOG( logERROR ) << "Failed to connect to socket";
        return;
    }

    socket.write(file_name.toUtf8());
    if (!socket.waitForBytesWritten(1000)) {
        LOG( logERROR ) << "Failed to send filename";
    }

    socket.close();
}
AuthorizationRecord QJsonUIDAuthority::clientConnected(QJsonStream *stream)
{
    AuthorizationRecord authRecord;
    authRecord.state = QJsonAuthority::StateNotAuthorized;

    if (!stream)
        return authRecord;

    QLocalSocket *socket = qobject_cast<QLocalSocket*>(stream->device());

    if (!socket)
        return authRecord;

    if (socket->socketDescriptor() == (qintptr)-1) {
        qWarning() << Q_FUNC_INFO << "no socket descriptor available for connection" << socket;
        return authRecord;
    }

    uid_t euid;
#if defined(Q_OS_MAC)
    gid_t egid;
    if (::getpeereid(socket->socketDescriptor(), &euid, &egid) != 0) {
        qWarning() << "getpeereid failed with errcode" << errno << socket->socketDescriptor();
        return authRecord;
    }
#else
    // Check the UID table and return Authorized if appropriate.
    struct ucred cr;
    socklen_t len = sizeof(struct ucred);
    if (::getsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_PEERCRED, &cr, &len) != 0) {
        qWarning() << "getsockopt failed with errcode" << errno << socket->socketDescriptor();
        return authRecord;
    }
    euid = cr.uid;
#endif

    if (m_nameForUid.contains(euid)) {
        authRecord.identifier = m_nameForUid.value(euid);
        authRecord.state      = StateAuthorized;
    }

    return authRecord;
}
Example #16
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;
}
Example #17
0
void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    int client_id = this->client_seq ++;
    this->clients.insert(socket, client_id);
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
    QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));

    return; 
    // multi client long connection support
    while (socket->bytesAvailable() < (int)sizeof(quint32))
        socket->waitForReadyRead();
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    QString message(QString::fromUtf8(uMsg));
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    // delete socket;
    emit messageReceived(message); //### (might take a long time to return)
}
/**
 * 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;
}
Example #19
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();
}
Example #20
0
unsigned int LocalPeer::get_hwnd_and_activate()
{
    unsigned int hwnd = 0;

#ifdef _WIN32
    QLocalSocket socket;
    bool connOk = false;
    int timeout = 5000;

    for(int i = 0; i < 2; i++) 
    {
        socket.connectToServer(socket_name_);
        connOk = socket.waitForConnected(timeout/2);
        if (connOk || i)
            break;
        int ms = 250;
        Sleep(DWORD(ms));
    }

    if (!connOk)
        return false;

    QByteArray uMsg((QString(crossprocess_message_get_hwnd_activate)).toUtf8());
    QDataStream ds(&socket);
    ds.writeBytes(uMsg.constData(), uMsg.size());

    if (socket.waitForBytesWritten(timeout))
    {
        if (socket.waitForReadyRead(timeout))
        {
            QByteArray data_read = socket.readAll();
            if (data_read.size() == sizeof(hwnd))
            {
                hwnd = *(unsigned int*) data_read.data();
            }
        }
    }
#endif _WIN32

    return hwnd;
}
Example #21
0
QString ControlPeer::sendRawMessage(const QString & msg, int timeout)
{
    if (mode() != ModeClient) {
        p->error = NotInClientModeError;
        return QString();
    }

    QString controlSocketPath = Guzum::Config::controlSocketPath();
    QLocalSocket socket;
    bool res = false;

    socket.connectToServer(controlSocketPath);
    res = socket.waitForConnected(timeout);

    if (!res) {
        p->error = ReadFailedError;
        return QString();
    }

    QByteArray bytes(msg.toUtf8());
    QByteArray responseBytes;
    QDataStream ds(&socket);
    ds.writeBytes(bytes.constData(), bytes.size());
    res = socket.waitForBytesWritten(timeout);
    if (res) {
        res &= socket.waitForReadyRead(timeout);   // wait for ack
        if (res) {
            responseBytes = socket.read(qstrlen(ACK));
            res &= (responseBytes == ACK);
        }
    }

    if (!res) {
        p->error = ReadFailedError;
        return QString();
    }
    p->error = NoError;
    return QString::fromUtf8(responseBytes.constData());
}
Example #22
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);
		});
	}
Example #23
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;
}
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;
}
Example #25
0
TSBrowserApplication::TSBrowserApplication(int &argc, char **argv)
    : QApplication(argc, argv)
    , m_localServer(0)
	, bOpenLinkInTab(false)
{
    QCoreApplication::setOrganizationName(QLatin1String("IJAB"));
    QCoreApplication::setApplicationName(QLatin1String("SpeechNav"));
    QCoreApplication::setApplicationVersion(QLatin1String("1.0.0"));
#ifdef Q_WS_QWS
    // Use a different server name for QWS so we can run an X11
    // browser and a QWS browser in parallel on the same machine for
    // debugging
    QString serverName = QCoreApplication::applicationName() + QLatin1String("_qws");
#else
    QString serverName = QCoreApplication::applicationName();
#endif
    QLocalSocket socket;
    socket.connectToServer(serverName);
    if (socket.waitForConnected(500)) {
        QTextStream stream(&socket);
        QStringList args = QCoreApplication::arguments();
        if (args.count() > 1)
            stream << args.last();
        else
            stream << QString();
        stream.flush();
        socket.waitForBytesWritten();
        return;
    }

#if defined(Q_WS_MAC)
    QApplication::setQuitOnLastWindowClosed(false);
#else
    QApplication::setQuitOnLastWindowClosed(true);
#endif

    m_localServer = new QLocalServer(this);
    connect(m_localServer, SIGNAL(newConnection()),
            this, SLOT(newLocalSocketConnection()));

    if (!m_localServer->listen(serverName)) {
        if (m_localServer->serverError() == QAbstractSocket::AddressInUseError
            && QFile::exists(m_localServer->serverName())) {
            QFile::remove(m_localServer->serverName());
            m_localServer->listen(serverName);
        }
    }

#ifndef QT_NO_OPENSSL
    if (!QSslSocket::supportsSsl()) {
    QMessageBox::information(0, "SpeechNav",
                 "This system does not support OpenSSL. SSL websites will not be available.");
    }
#endif

    QDesktopServices::setUrlHandler(QLatin1String("http"), this, "openUrl");
    QString localSysName = QLocale::system().name();

    installTranslator(QLatin1String("qt_") + localSysName);

#if defined(Q_WS_MAC)
    connect(this, SIGNAL(lastWindowClosed()),
            this, SLOT(lastWindowClosed()));
#endif

    QTimer::singleShot(0, this, SLOT(postLaunch()));

	// Set logger
	QsLogging::Logger& logger = QsLogging::Logger::instance();
	
	const QString sLogPath(QDir(applicationDirPath()).filePath("tsweb.log"));
	
	logFileDestination = QsLogging::DestinationFactory::MakeFileDestination(sLogPath);
	logger.addDestination(logFileDestination.get());
}
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);
                    }
                }
            }
void CLocalSvrCommunication::SocketError( QLocalSocket::LocalSocketError )
{
    QLocalSocket* pSocket = qobject_cast< QLocalSocket* >( sender( ) );
    emit NotifyMsg( pSocket->errorString( ) );
}
void CLocalSvrCommunication::HandleServerDisconnect( )
{
    QLocalSocket* pSocket = qobject_cast< QLocalSocket* >( sender( ) );
    pSocket->close( );
    pSocket->deleteLater( );
}
Example #29
0
void Application::newConnection()
{
	QLocalSocket *socket = m_localServer->nextPendingConnection();

	if (!socket)
	{
		return;
	}

	socket->waitForReadyRead(1000);

	MainWindow *window = (getWindows().isEmpty() ? NULL : getWindow());
	QString data;
	QTextStream stream(socket);
	stream >> data;

	const QStringList encodedArguments = QString(QByteArray::fromBase64(data.toUtf8())).split(QLatin1Char(' '));
	QStringList decodedArguments;

	for (int i = 0; i < encodedArguments.count(); ++i)
	{
		decodedArguments.append(QString(QByteArray::fromBase64(encodedArguments.at(i).toUtf8())));
	}

	m_commandLineParser.parse(decodedArguments);

	const QString session = m_commandLineParser.value(QLatin1String("session"));
	const bool isPrivate = m_commandLineParser.isSet(QLatin1String("privatesession"));

	if (session.isEmpty())
	{
		if (!window || !SettingsManager::getValue(QLatin1String("Browser/OpenLinksInNewTab")).toBool() || (isPrivate && !window->getWindowsManager()->isPrivate()))
		{
			window = createWindow(isPrivate);
		}
	}
	else
	{
		const SessionInformation sessionData = SessionsManager::getSession(session);

		if (sessionData.isClean || QMessageBox::warning(NULL, tr("Warning"), tr("This session was not saved correctly.\nAre you sure that you want to restore this session anyway?"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
		{
			for (int i = 0; i < sessionData.windows.count(); ++i)
			{
				createWindow(isPrivate, false, sessionData.windows.at(i));
			}
		}
	}

	if (window)
	{
		if (m_commandLineParser.positionalArguments().isEmpty())
		{
			window->triggerAction(ActionsManager::NewTabAction);
		}
		else
		{
			const QStringList urls = m_commandLineParser.positionalArguments();

			for (int i = 0; i < urls.count(); ++i)
			{
				window->openUrl(urls.at(i));
			}
		}
	}

	delete socket;

	if (window)
	{
		window->raise();
		window->activateWindow();

		if (m_isHidden)
		{
			setHidden(false);
		}
		else
		{
			window->storeWindowState();
			window->restoreWindowState();
		}
	}
}
Example #30
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    settings("Zeal", "Zeal"),
    settingsDialog(zealList)
{
    trayIcon = nullptr;
    trayIconMenu = nullptr;

    // Use the platform-specific proxy settings
    QNetworkProxyFactory::setUseSystemConfiguration(true);

    // server for detecting already running instances
    localServer = new QLocalServer(this);
    connect(localServer, &QLocalServer::newConnection, [&]() {
        QLocalSocket *connection = localServer->nextPendingConnection();
        // Wait a little while the other side writes the bytes
        connection->waitForReadyRead();
        QString indata = connection->readAll();
        if(!indata.isEmpty()) {
            bringToFrontAndSearch(indata);
        }
    });
    QLocalServer::removeServer(serverName);  // remove in case previous instance crashed
    localServer->listen(serverName);

    // initialise icons
#if defined(WIN32) || defined(OSX)
    icon = qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation);
#else
    icon = QIcon::fromTheme("edit-find");
#endif
    setWindowIcon(icon);
    if(settings.value("hidingBehavior", "systray").toString() == "systray")
        createTrayIcon();

    QKeySequence keySequence;
    if(settings.value("hotkey").isNull()) {
        keySequence = QKeySequence("Alt+Space");
    } else {
        keySequence = settings.value("hotkey").value<QKeySequence>();
    }

    // initialise key grabber
    connect(&nativeFilter, &ZealNativeEventFilter::gotHotKey, [&]() {
        if(!isVisible() || !isActiveWindow()) {
            bringToFront(true);
        } else {
            if(trayIcon) {
                hide();
            } else {
                showMinimized();
            }
        }
    });
    qApp->eventDispatcher()->installNativeEventFilter(&nativeFilter);
    setHotKey(keySequence);

    // initialise docsets
    docsets->initialiseDocsets();

    // initialise ui
    ui->setupUi(this);

    setupShortcuts();

    restoreGeometry(settings.value("geometry").toByteArray());
    ui->splitter->restoreState(settings.value("splitter").toByteArray());
    connect(ui->splitter, &QSplitter::splitterMoved, [=](int, int) {
        settings.setValue("splitter", ui->splitter->saveState());
    });
    ui->webView->settings()->setFontSize(QWebSettings::MinimumFontSize, settings.value("minFontSize").toInt());
    ZealNetworkAccessManager * zealNaManager = new ZealNetworkAccessManager();
    ui->webView->page()->setNetworkAccessManager(zealNaManager);

    // menu
    ui->action_Quit->setShortcut(QKeySequence::Quit);
    connect(ui->action_Quit, &QAction::triggered, [=]() { settings.setValue("geometry", saveGeometry()); });
    connect(ui->action_Quit, SIGNAL(triggered()), qApp, SLOT(quit()));

    connect(&settingsDialog, SIGNAL(refreshRequested()), this, SLOT(refreshRequest()));
    connect(&settingsDialog, SIGNAL(minFontSizeChanged(int)), this, SLOT(changeMinFontSize(int)));

    connect(ui->action_Options, &QAction::triggered, [=]() {
        settingsDialog.setHotKey(hotKey);
        nativeFilter.setEnabled(false);
        if(settingsDialog.exec()) {
            setHotKey(settingsDialog.hotKey());
            if(settings.value("hidingBehavior").toString() == "systray") {
                createTrayIcon();
            } else if(trayIcon) {
                trayIcon->deleteLater();
                trayIconMenu->deleteLater();
                trayIcon = nullptr;
                trayIconMenu = nullptr;
            }
        } else {
            // cancelled - restore previous value
            ui->webView->settings()->setFontSize(QWebSettings::MinimumFontSize, settings.value("minFontSize").toInt());
        }
        nativeFilter.setEnabled(true);
        ui->treeView->reset();
    });

    ui->action_Back->setShortcut(QKeySequence::Back);
    ui->action_Forward->setShortcut(QKeySequence::Forward);
    connect(ui->action_Back, &QAction::triggered, this, &MainWindow::back);
    connect(ui->action_Forward, &QAction::triggered, this, &MainWindow::forward);

    connect(ui->action_About, &QAction::triggered,
            [&]() { QMessageBox::about(this, "About Zeal",
                QString("This is Zeal ") + ZEAL_VERSION + " - a documentation browser.\n\n"
                "For details see http://zealdocs.org/"); });
    connect(ui->action_About_QT, &QAction::triggered,
            [&]() { QMessageBox::aboutQt(this); });
    displayViewActions();

    // treeView and lineEdit
    ui->lineEdit->setTreeView(ui->treeView);
    ui->lineEdit->setFocus();
    ui->treeView->setModel(&zealList);
    ui->treeView->setColumnHidden(1, true);
    ui->treeView->setItemDelegate(new ZealSearchItemDelegate(ui->treeView, ui->lineEdit, ui->treeView));
#if QT_VERSION < QT_VERSION_CHECK(5, 1, 0) && defined(WIN32)
    // overriding subElementRect doesn't work with Qt 5.0.0, but is required to display
    // selected item frame correctly in Windows (for patch see https://codereview.qt-project.org/#change,46559)
    // This is a workaround for Qt < 5.1 - selecting whole rows leads to always rendering the frame.
    // (Only the frame is larger than the list item, which is different from default behaviour.)
    ui->treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
#endif
    connect(ui->treeView, &QTreeView::clicked, [&](const QModelIndex& index) {
       ui->treeView->activated(index);
    });
    connect(ui->treeView, &QTreeView::activated, [&](const QModelIndex& index) {
        if(!index.sibling(index.row(), 1).data().isNull()) {
            QStringList url_l = index.sibling(index.row(), 1).data().toString().split('#');
            QUrl url = QUrl::fromLocalFile(url_l[0]);
            if(url_l.count() > 1) {
                url.setFragment(url_l[1]);
            }
            ui->webView->load(url);
        }
    });
    connect(ui->forwardButton, &QPushButton::clicked, this, &MainWindow::forward);
    connect(ui->backButton, &QPushButton::clicked, this, &MainWindow::back);

    connect(ui->webView, &SearchableWebView::urlChanged, [&](const QUrl &url) {
        QString urlPath = url.path();
        QString docsetName = getDocsetName(urlPath);
        QPixmap docsetMap = docsets->icon(docsetName).pixmap(32,32);

        // paint label with the icon
        ui->pageIcon->setPixmap(docsetMap);
        displayViewActions();
    });

    connect(ui->webView, &SearchableWebView::titleChanged, [&](const QString &title) {
        if (!title.isEmpty()) {
            ui->pageTitle->setText(title);
        }
    });

    connect(&zealSearch, &ZealSearchModel::queryCompleted, [&]() {
        ui->treeView->setModel(&zealSearch);
        ui->treeView->reset();
        ui->treeView->setColumnHidden(1, true);
        ui->treeView->setCurrentIndex(zealSearch.index(0, 0, QModelIndex()));
        ui->treeView->activated(ui->treeView->currentIndex());
    });
    connect(ui->lineEdit, &QLineEdit::textChanged, [&](const QString& text) {
        zealSearch.setQuery(text);
        if(text.isEmpty()) {
            ui->treeView->setModel(&zealList);
        }
    });
}