void CommandHandler::processCommand(const Command &command) const
{
    QWebEngineView *webView = ElectricWebView::instance()->webView();

    if (command.name() == "load") {
        if (command.arguments().isEmpty())
            webView->load(QUrl("about:blank"));
        else
            webView->load(QUrl(command.arguments().first()));
    } else if (command.name() == "stop") {
        webView->stop();
    } else if (command.name() == "reload") {
        webView->reload();
    } else if (command.name() == "back") {
        webView->back();
    } else if (command.name() == "forward") {
        webView->forward();
    } else if (command.name() == "open") {
        QString mode = command.arguments().value(0);

        if (mode == "maximized") {
            webView->showMaximized();
        } else if (mode == "fullscreen") {
            webView->setGeometry(qApp->desktop()->screenGeometry());
            webView->showFullScreen();
        }
    } else if (command.name() == "close") {
        webView->close();
    } else if (command.name() == "current_url") {
        command.sendResponse(webView->url().toString().toLocal8Bit());
    } else if (command.name() == "set_html") {
        QString type = command.arguments().value(0);
        QString value = command.arguments().mid(1, -1).join(' ');

        if (type == "string") {
            webView->page()->setHtml(value.toLocal8Bit());
        } else if (type == "file") {
            QFile file(value);
            file.open(QFile::ReadOnly);

            webView->page()->setHtml(file.readAll());
        }
    } else if (command.name() == "get_html") {
        QString format = command.arguments().value(0);

        QEventLoop loop;

        if (format == "html") {
            webView->page()->toHtml([&command, &loop](const QString &html) {
                if (!command.client().isNull()) {
                    command.sendResponse(QUrl::toPercentEncoding(html));

                    if (command.isGetter())
                        command.client()->close();
                }
                loop.quit();
            });
        } else if (format == "text") {
            webView->page()->toPlainText([&command, &loop](const QString &text) {
                if (!command.client().isNull()) {
                    command.sendResponse(QUrl::toPercentEncoding(text));

                    if (command.isGetter())
                        command.client()->close();
                }
                loop.quit();
            });
        } else {
            return;
        }

        loop.exec();
    } else if (command.name() == "current_title") {
        command.sendResponse(webView->title().toLocal8Bit());
    } else if (command.name() == "screenshot") {
        processScreenshotCommand(command);
    } else if (command.name() == "subscribe") {
        QString eventName = command.arguments().value(0);
        QStringList events = QStringList()
                << "title_changed"
                << "url_changed"
                << "load_started"
                << "load_finished"
                << "user_activity"
                << "info_message_raised"
                << "warning_message_raised"
                << "error_message_raised"
                << "feature_permission_requested";

        if (events.contains(eventName)) {
            Event event(command);
            event.setName(eventName);

            ElectricWebView::instance()->eventManager()->subscribe(event);
        }
    } else if (command.name() == "exec_js") {
        processJavaScriptCommand(command);
    } else if (command.name() == "inject_js") {
        QMap<QString, QWebEngineScript::ScriptWorldId> worlds;
        worlds["main"] = QWebEngineScript::MainWorld;
        worlds["application"] = QWebEngineScript::ApplicationWorld;
        worlds["user"] = QWebEngineScript::UserWorld;

        QMap<QString, QWebEngineScript::InjectionPoint> injectionPoints;
        injectionPoints["document_creation"] = QWebEngineScript::DocumentCreation;
        injectionPoints["document_ready"] = QWebEngineScript::DocumentReady;
        injectionPoints["deferred"] = QWebEngineScript::Deferred;

        QWebEngineScript::ScriptWorldId world = worlds[command.arguments().value(0)];
        QWebEngineScript::InjectionPoint injectionPoint = injectionPoints[command.arguments().value(1)];

        QWebEngineScript script;
        script.setWorldId(world);
        script.setInjectionPoint(injectionPoint);

        QString source = command.arguments().value(2);
        QString value = command.arguments().mid(3, -1).join(' ');

        if (source == "string") {
            script.setSourceCode(value);
        } else if (source == "file") {
            QFile file(value);
            file.open(QFile::ReadOnly);

            script.setSourceCode(file.readAll());
        }

        ElectricWebView::instance()->webView()->page()->scripts().insert(script);
    } else if (command.name() == "idle_time") {
        command.sendResponse(QString("%1").arg(ElectricWebView::instance()->inputEventFilter()->idle()).toLocal8Bit());
    } else if (command.name() == "block_user_activity") {
        bool block = QVariant(command.arguments().value(0)).toBool();
        ElectricWebView::instance()->inputEventFilter()->setBlock(block);
    } else if (command.name() == "exec_cmd") {
        bool sync = command.arguments().value(0) == "sync";

        if (sync) {
            QProcess *process = new QProcess;
            process->start(command.arguments().mid(1, -1).join(' '));
            process->waitForFinished(-1);
            command.sendResponse(QUrl::toPercentEncoding(process->readAllStandardOutput()));
        } else {
            QProcess::startDetached(command.arguments().mid(1, -1).join(' '));
        }
    } else if (command.name() == "accept_feature_request" || command.name() == "reject_feature_request") {
        QMap<QString, QWebEnginePage::Feature> features;
        features["geolocation"] = QWebEnginePage::Geolocation;
        features["audio_capture"] = QWebEnginePage::MediaAudioCapture;
        features["video_capture"] = QWebEnginePage::MediaVideoCapture;
        features["audio_video_capture"] = QWebEnginePage::MediaAudioVideoCapture;
        features["mouse_lock"] = QWebEnginePage::MouseLock;

        QUrl securityOrigin(command.arguments().value(1));
        QWebEnginePage::Feature feature = features[command.arguments().value(0)];
        QWebEnginePage::PermissionPolicy policy;

        if (command.name() == "accept_feature_request")
            policy = QWebEnginePage::PermissionGrantedByUser;
        else
            policy = QWebEnginePage::PermissionDeniedByUser;

        ElectricWebView::instance()->webView()->page()->setFeaturePermission(securityOrigin, feature, policy);
    } else if (command.name() == "quit") {
        int exitCode = command.arguments().value(0).toInt();
        qApp->exit(exitCode);
    }
}
Ejemplo n.º 2
0
QString Manage::makeOSX()
{
    QEventLoop eventLoop;
    QString reply;

    QtConcurrent::run( [ this, &eventLoop, &reply ]()
    {
        try
        {
            this->realMakeOSX();
        }
        catch(const bool &)
        {
            reply = "saveToFileError";
            eventLoop.quit();
        }

        reply = "OK";
        eventLoop.quit();
    } );

    eventLoop.exec();

    return reply;
}
bool ClientManage::send(const QByteArray &send, QByteArray &accepted)
{
    this->waitForRun();

    QEventLoop eventLoop;
    quint32 currentRunFlag = this->getRunFlag();
    bool doneFlag = false;

    m_start->send(send, currentRunFlag);

    auto c = connect(this, &ClientManage::finished, [&](const quint32 &flag, const QByteArray &data, const bool &done)
    {
        if(flag != currentRunFlag)
        {
            return;
        }

        doneFlag = done;
        if(doneFlag)
        {
            accepted = data;
        }

        eventLoop.quit();
    });

    eventLoop.exec();
    disconnect(c);

    return doneFlag;
}
void CommandHandler::processJavaScriptCommand(QPointer<IpcClient> client, QStringList args)
{
    QString type = args.value(0);
    QString value = args.value(1);

    QEventLoop loop;

    // Process JavaScript response from Web View and tells the even loop to exit
    auto processJavaScriptResponse = [client, &loop](const QVariant &out) mutable {
        if (!client.isNull())
            client->write(out.toByteArray() + "\n");
        loop.quit();
    };

    if (type == "string") {
        m_eventManager->webView()->page()->runJavaScript(value, processJavaScriptResponse);
    } else if (type == "file") {
        QFile file(value);
        file.open(QFile::ReadOnly);

        m_eventManager->webView()->page()->runJavaScript(file.readAll(), processJavaScriptResponse);
    } else {
        return;
    }

    // Wait for JavaScript response from the Web View
    loop.exec();
}
void CommandHandler::processJavaScriptCommand(const Command &command) const
{
    QString type = command.arguments().value(0);
    QString value = command.arguments().mid(1, -1).join(' ');

    QEventLoop loop;

    // Process JavaScript response from Web View and tells the even loop to exit
    auto processJavaScriptResponse = [&command, &loop](const QVariant &out) mutable {
        if (!command.client().isNull()) {
            command.sendResponse(QUrl::toPercentEncoding(out.toString()));

            if (command.isGetter())
                command.client()->close();
        }
        loop.quit();
    };

    if (type == "string") {
        ElectricWebView::instance()->webView()->page()->runJavaScript(value, processJavaScriptResponse);
    } else if (type == "file") {
        QFile file(value);
        file.open(QFile::ReadOnly);

        ElectricWebView::instance()->webView()->page()->runJavaScript(file.readAll(), processJavaScriptResponse);
    } else {
        return;
    }

    // Wait for JavaScript response from the Web View
    loop.exec();
}
Ejemplo n.º 6
0
void CodeLinesTest::codeLines()
{
    int fileCount = 0, lineCount = 0;

    QString currentPath = "../";
    if( currentPath.isEmpty() )
    {
        return;
    }

    QSet<QString> availableSuffixs;
    availableSuffixs << "h" << "c" << "cc" << "cp" << "cpp" << "hpp" << "inc"
                     << "i" << "ii" << "m" << "qml" << "pro" << "pri" << "prf" << "prl";

    QMap<QString, int> categorys;

    QEventLoop eventLoop;
    QtConcurrent::run( [&]()
    {
        foreachFileFromDirectory( { currentPath }, [&](const QFileInfo &info)
        {
            QString suffix = info.suffix().toLower();
            if(suffix.isEmpty())
            {
               suffix = "other";
            }
            categorys.insert(suffix, categorys[suffix] + 1);

            QFile file(info.filePath());
            if(!file.open(QIODevice::ReadOnly))
            {
                return;
            }

            fileCount++;

            const auto &&fileAllData = file.readAll();
            if(fileAllData.isEmpty())
            {
                return;
            }

            if(availableSuffixs.contains(suffix))
            {
                lineCount += fileAllData.count('\n') + 1;
            }
            file.close();
        }, true);

        eventLoop.quit();
    } );
    eventLoop.exec();

    qDebug() << "All File Count " << fileCount;
    qDebug() << "All Meet The Requirements Line Count " << lineCount;
    foreach(const QString &key, categorys.keys())
    {
        qDebug() << QString(".%1 Type  All count %2").arg(key).arg(categorys[key]);
    }
}
Ejemplo n.º 7
0
QVariantList Promise::wait()
{
  QEventLoop el;
  QVariantList result;

  auto quitter = [&] (QVariantList results) {
      result = std::move(results);
      el.quit();
  };
  connect(this, &Promise::resolved, quitter);
  connect(this, &Promise::rejected, quitter);

  el.exec();
  return result;
}
Ejemplo n.º 8
0
void ScriptJob::requestAbort()
{
    QMutexLocker locker( m_mutex );
    if ( m_quit || !m_engine ) {
        // Is already aborting/finished
        return;
    }

    m_quit = true;
    if ( m_eventLoop ) {
        QEventLoop *loop = m_eventLoop;
        m_eventLoop = 0;
        loop->quit();
    }

    if ( !isFinished() && m_objects.network->hasRunningRequests() ) {
        m_objects.network->abortAllRequests();
    }
}
Ejemplo n.º 9
0
QImage Qgs3DUtils::captureSceneImage( QgsAbstract3DEngine &engine, Qgs3DMapScene *scene )
{
  QImage resImage;
  QEventLoop evLoop;

  auto requestImageFcn = [&engine, scene]
  {
    if ( scene->sceneState() == Qgs3DMapScene::Ready )
    {
      engine.requestCaptureImage();
    }
  };

  auto saveImageFcn = [&evLoop, &resImage]( const QImage & img )
  {
    resImage = img;
    evLoop.quit();
  };

  QMetaObject::Connection conn1 = QObject::connect( &engine, &QgsAbstract3DEngine::imageCaptured, saveImageFcn );
  QMetaObject::Connection conn2;

  if ( scene->sceneState() == Qgs3DMapScene::Ready )
  {
    requestImageFcn();
  }
  else
  {
    // first wait until scene is loaded
    conn2 = QObject::connect( scene, &Qgs3DMapScene::sceneStateChanged, requestImageFcn );
  }

  evLoop.exec();

  QObject::disconnect( conn1 );
  if ( conn2 )
    QObject::disconnect( conn2 );

  return resImage;
}
Ejemplo n.º 10
0
 // Connect to API, and test if the URL is working
void ApiFuncs::ConnectToApi(QString a_filename, QString a_url, bool &a_errorTest, QString a_search)
{
    // If the given cache-file not exists and is old, get a new one. If else, do nothing
    if (this->fileFuncs->CheckIfFileExists(a_filename) == false || this->fileFuncs->CheckIfFileIsTheLatest(a_filename) == false)
    {
        // Do a bunch of stuff for setting up a connection
        // with reponse and reply
        QNetworkRequest networkRequest;
        networkRequest.setUrl(QUrl(a_url));
        QNetworkAccessManager *networkManager = new QNetworkAccessManager();
        QNetworkReply *networkReply = networkManager->get(networkRequest);
        QEventLoop loop;

        // Check if the download of data from the connection is done
        connect(networkReply, SIGNAL(finished()), &loop, SLOT(quit())); // A sort of eventlistener for signal/slots

        // Check if the there was an error
        connect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); // A sort of eventlistener for signal/slots
        loop.exec();

        // If there was an error, set the test for it to false
        // and send it back with the callback in the method-parameters,
        // to the mainwindow-class.
        if (networkReply->error())
        {
            a_errorTest = false;
            disconnect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); // Remove eventlistener
        }

        // If the download of data from the connection was done,
        // load the method for saving the data to a given cache-file
        else if (networkReply->isFinished())
        {
            this->SaveApiData(a_filename, networkReply->readAll(), a_search);
            disconnect(networkReply, SIGNAL(finished()), &loop, SLOT(quit())); // Remove eventlistener
            loop.quit();
        }
    }
}
Ejemplo n.º 11
0
QString QgsLayoutItemHtml::fetchHtml( const QUrl &url )
{
  //pause until HTML fetch
  bool loaded = false;
  QEventLoop loop;
  connect( mFetcher, &QgsNetworkContentFetcher::finished, &loop, [&loaded, &loop ] { loaded = true; loop.quit(); } );
  mFetcher->fetchContent( url );

  if ( !loaded )
    loop.exec( QEventLoop::ExcludeUserInputEvents );

  mFetchedHtml = mFetcher->contentAsString();
  mActualFetchedUrl = mFetcher->reply()->url().toString();
  return mFetchedHtml;
}
Ejemplo n.º 12
0
void QgsLayoutItemHtml::loadHtml( const bool useCache, const QgsExpressionContext *context )
{
  if ( !mWebPage )
  {
    return;
  }

  QgsExpressionContext scopedContext = createExpressionContext();
  const QgsExpressionContext *evalContext = context ? context : &scopedContext;

  QString loadedHtml;
  switch ( mContentMode )
  {
    case QgsLayoutItemHtml::Url:
    {

      QString currentUrl = mUrl.toString();

      //data defined url set?
      bool ok = false;
      currentUrl = mDataDefinedProperties.valueAsString( QgsLayoutObject::SourceUrl, *evalContext, currentUrl, &ok );
      if ( ok )
      {
        currentUrl = currentUrl.trimmed();
        QgsDebugMsg( QString( "exprVal Source Url:%1" ).arg( currentUrl ) );
      }
      if ( currentUrl.isEmpty() )
      {
        return;
      }
      if ( !( useCache && currentUrl == mLastFetchedUrl ) )
      {
        loadedHtml = fetchHtml( QUrl( currentUrl ) );
        mLastFetchedUrl = currentUrl;
      }
      else
      {
        loadedHtml = mFetchedHtml;
      }

      break;
    }
    case QgsLayoutItemHtml::ManualHtml:
      loadedHtml = mHtml;
      break;
  }

  //evaluate expressions
  if ( mEvaluateExpressions )
  {
    loadedHtml = QgsExpression::replaceExpressionText( loadedHtml, evalContext, &mDistanceArea );
  }

  bool loaded = false;

  QEventLoop loop;
  connect( mWebPage.get(), &QWebPage::loadFinished, &loop, [&loaded, &loop ] { loaded = true; loop.quit(); } );
  connect( mFetcher, &QgsNetworkContentFetcher::finished, &loop, [&loaded, &loop ] { loaded = true; loop.quit(); } );

  //reset page size. otherwise viewport size increases but never decreases again
  mWebPage->setViewportSize( QSize( maxFrameWidth() * mHtmlUnitsToLayoutUnits, 0 ) );

  //set html, using the specified url as base if in Url mode or the project file if in manual mode
  const QUrl baseUrl = mContentMode == QgsLayoutItemHtml::Url ?
                       QUrl( mActualFetchedUrl ) :
                       QUrl::fromLocalFile( mLayout->project()->fileInfo().absoluteFilePath() );

  mWebPage->mainFrame()->setHtml( loadedHtml, baseUrl );

  //set user stylesheet
  QWebSettings *settings = mWebPage->settings();
  if ( mEnableUserStylesheet && ! mUserStylesheet.isEmpty() )
  {
    QByteArray ba;
    ba.append( mUserStylesheet.toUtf8() );
    QUrl cssFileURL = QUrl( "data:text/css;charset=utf-8;base64," + ba.toBase64() );
    settings->setUserStyleSheetUrl( cssFileURL );
  }
  else
  {
    settings->setUserStyleSheetUrl( QUrl() );
  }

  if ( !loaded )
    loop.exec( QEventLoop::ExcludeUserInputEvents );

  //inject JSON feature
  if ( !mAtlasFeatureJSON.isEmpty() )
  {
    mWebPage->mainFrame()->evaluateJavaScript( QStringLiteral( "if ( typeof setFeature === \"function\" ) { setFeature(%1); }" ).arg( mAtlasFeatureJSON ) );
    //needs an extra process events here to give JavaScript a chance to execute
    qApp->processEvents();
  }

  recalculateFrameSizes();
  //trigger a repaint
  emit contentsChanged();
}
Ejemplo n.º 13
0
int main(int argc, char *argv[])
{
    Application app(argc, argv);

    QEventLoop loop;

    auto s(std::async(std::launch::async, [&loop]{ Datum::Solve solve(Datum::solve()); if (loop.isRunning()) { loop.quit(); } return std::move(solve); }));

    QLabel splash;
    splash.setMovie(new QMovie(([](){
        static const QString basePath(":/splash/busy/");
        const QStringList files(QDir(basePath).entryList(QStringList() << "*.gif"));

        std::random_device rd;
        std::mt19937 gen(rd());

        std::uniform_int_distribution<> d(0,files.size() - 1);
        const QString& result(files.at(d(gen)));
        return basePath + result;
    })()));
    splash.movie()->start();
    splash.show();
    splash.setWindowTitle("computing. . .");

    if (s.wait_until(std::chrono::system_clock::now()) != std::future_status::ready) {
        loop.exec();
    }
    splash.hide();
    app.showBarley();

    Datum::Solve solve(s.get());

    Datum d;
    while (!solve.empty()) {
        Application::showDatum(d);
        d = d.realize(solve.top());
        solve.pop();
    }
    Application::showDatum(d, false);

    app.quit();
    return 0;
}
Ejemplo n.º 14
0
InputInterpreter::InterpreterResult InputInterpreter::interpret(const QString &text, InterpreterFlags flags)
{
	InterpreterResult result;

	if (text.isEmpty())
	{
		return result;
	}

	if (!flags.testFlag(NoSearchKeywordsFlag))
	{
		const QString keyword(text.section(QLatin1Char(' '), 0, 0));
		const SearchEnginesManager::SearchEngineDefinition searchEngine(SearchEnginesManager::getSearchEngine(keyword, true));

		if (searchEngine.isValid())
		{
			result.searchEngine = searchEngine.identifier;
			result.searchQuery = text.section(QLatin1Char(' '), 1);
			result.type = InterpreterResult::SearchType;

			return result;
		}

		if (keyword == QLatin1String("?"))
		{
			result.searchQuery = text.section(QLatin1Char(' '), 1);
			result.type = InterpreterResult::SearchType;

			return result;
		}
	}

	if (text.startsWith(QLatin1String("bookmarks:")))
	{
		BookmarksItem *bookmark(text.startsWith(QLatin1String("bookmarks:/")) ? BookmarksManager::getModel()->getItem(text.mid(11)) : BookmarksManager::getBookmark(text.mid(10).toULongLong()));

		if (bookmark)
		{
			result.bookmark = bookmark;
			result.type = InterpreterResult::BookmarkType;

			return result;
		}
	}

	if (!flags.testFlag(NoBookmarkKeywordsFlag))
	{
		BookmarksItem *bookmark(BookmarksManager::getBookmark(text));

		if (bookmark)
		{
			result.bookmark = bookmark;
			result.type = InterpreterResult::BookmarkType;

			return result;
		}
	}

	const QString localPath(Utils::normalizePath(text));

	if (localPath != text)
	{
		result.url = QUrl::fromLocalFile(localPath);
		result.type = InterpreterResult::UrlType;

		return result;
	}

	const QFileInfo fileInformation(text);

	if (fileInformation.exists() && fileInformation.isAbsolute())
	{
		result.url = QUrl::fromLocalFile(fileInformation.canonicalFilePath());
		result.type = InterpreterResult::UrlType;

		return result;
	}

	const QUrl url(QUrl::fromUserInput(text));

	if (!QHostAddress(text).isNull() || (url.isValid() && (url.isLocalFile() || QRegularExpression(QLatin1String("^(\\w+\\:\\S+)|([\\w\\-]+\\.[a-zA-Z]{2,}(/\\S*)?$)")).match(text).hasMatch())))
	{
		result.url = url;
		result.type = InterpreterResult::UrlType;

		return result;
	}

#if QT_VERSION >= 0x050900
	if (!flags.testFlag(NoHostLookupFlag))
	{
		const int lookupTimeout(SettingsManager::getOption(SettingsManager::AddressField_HostLookupTimeoutOption).toInt());

		if (url.isValid() && lookupTimeout > 0)
		{
			QEventLoop eventLoop;
			const int lookupIdentifier(QHostInfo::lookupHost(url.host(), [&](const QHostInfo &information)
			{
				if (information.error() == QHostInfo::NoError)
				{
					result.url = QUrl::fromUserInput(text);
					result.type = InterpreterResult::UrlType;
				}

				eventLoop.quit();
			}));

			QTimer timer;
			timer.setSingleShot(true);

			connect(&timer, &QTimer::timeout, [&]()
			{
				QHostInfo::abortHostLookup(lookupIdentifier);

				eventLoop.quit();
			});

			timer.start(lookupTimeout);

			if (result.type == InterpreterResult::UnknownType)
			{
				eventLoop.exec();
			}

			if (result.type == InterpreterResult::UrlType)
			{
				return result;
			}
		}
	}
#endif

	result.searchQuery = text;
	result.type = InterpreterResult::SearchType;

	return result;
}