bool Commands::sqlExec(const QString &sql) { QMetaObject::invokeMethod(m_sqlWorker, "execute", Qt::QueuedConnection, Q_ARG(QString, sql)); return true; }
int main(int argc, char *argv[]) { QOptions options(get_common_options()); options.add("QMLPlayer options") ("scale", 1.0, "scale of graphics context. 0: auto") ; options.parse(argc, argv); if (options.value("help").toBool()) { options.print(); return 0; } QGuiApplication app(argc, argv); set_opengl_backend(options.option("gl").value().toString(), app.arguments().first()); load_qm(QStringList() << "QMLPlayer", options.value("language").toString()); QtQuick2ApplicationViewer viewer; viewer.engine()->rootContext()->setContextProperty("PlayerConfig", &Config::instance()); qDebug(">>>>>>>>devicePixelRatio: %f", qApp->devicePixelRatio()); QScreen *sc = app.primaryScreen(); qDebug() << "dpi phy: " << sc->physicalDotsPerInch() << ", logical: " << sc->logicalDotsPerInch() << ", dpr: " << sc->devicePixelRatio() << "; vis rect:" << sc->virtualGeometry(); // define a global var for js and qml viewer.engine()->rootContext()->setContextProperty("screenPixelDensity", qApp->primaryScreen()->physicalDotsPerInch()*qApp->primaryScreen()->devicePixelRatio()); qreal r = sc->physicalDotsPerInch()/sc->logicalDotsPerInch(); if (std::isinf(r) || std::isnan(r)) #if defined(Q_OS_ANDROID) r = 2.0; #else r = 1.0; #endif float sr = options.value("scale").toFloat(); if (qFuzzyIsNull(sr)) sr = r; viewer.engine()->rootContext()->setContextProperty("scaleRatio", sr); QString qml = "qml/QMLPlayer/main.qml"; if (QFile(qApp->applicationDirPath() + "/" + qml).exists()) qml.prepend(qApp->applicationDirPath() + "/"); else qml.prepend("qrc:///"); viewer.setMainQmlFile(qml); viewer.showExpanded(); QOption op = options.option("width"); if (op.isSet()) viewer.setWidth(op.value().toInt()); op = options.option("height"); if (op.isSet()) viewer.setHeight(op.value().toInt()); op = options.option("x"); if (op.isSet()) viewer.setX(op.value().toInt()); op = options.option("y"); if (op.isSet()) viewer.setY(op.value().toInt()); if (options.value("fullscreen").toBool()) viewer.showFullScreen(); viewer.setTitle("QMLPlayer based on QtAV. [email protected]"); /* * find root item, then root.init(argv). so we can deal with argv in qml */ #if 1 QString json = app.arguments().join("\",\""); json.prepend("[\"").append("\"]"); json.replace("\\", "/"); //FIXME QMetaObject::invokeMethod(viewer.rootObject(), "init", Q_ARG(QVariant, json)); //#else if (app.arguments().size() > 1) { qDebug("arguments > 1"); QObject *player = viewer.rootObject()->findChild<QObject*>("player"); QString file = options.value("file").toString(); if (file.isEmpty()) { if (argc > 1 && !app.arguments().last().startsWith('-') && !app.arguments().at(argc-2).startsWith('-')) file = app.arguments().last(); } if (player && !file.isEmpty()) { if (QFile(file).exists()) file.prepend("file:"); //qml use url and will add qrc: if no scheme file.replace("\\", "/"); //qurl QMetaObject::invokeMethod(player, "play", Q_ARG(QUrl, QUrl(file))); } } #endif QObject::connect(viewer.rootObject(), SIGNAL(requestFullScreen()), &viewer, SLOT(showFullScreen())); QObject::connect(viewer.rootObject(), SIGNAL(requestNormalSize()), &viewer, SLOT(showNormal())); ScreenSaver::instance().disable(); //restore in dtor return app.exec(); }
void ScriptService::post(const QByteArray& operation, const APIParameters ¶meters, const QByteArray &data, APIServiceResponse &response) { Q_UNUSED(data); if(operation=="run") { //retrieve detail about a single script QString scriptId = QString::fromUtf8(parameters.value("id")); if(scriptMgr->scriptIsRunning()) { response.setData("error: a script is already running"); return; } QString script; //Prepare the script. Through a refactor, this is separate from actually running the script, //and can be done in the HTTP thread. It can also notify the caller of an invalid script ID. bool ret = scriptMgr->prepareScript(script,scriptId); if(!ret) { response.setData("error: could not prepare script, wrong id?"); return; } //ret = scriptMgr->runScript(scriptId); //we may be in another thread! for the actual execution of the script, we need to invoke the event queue //we can not use blocking connection here because runPreprocessedScript is blocking! //there is also no way to check if the script was actually started except for polling some time later QMetaObject::invokeMethod(scriptMgr,"runPreprocessedScript", Qt::QueuedConnection,Q_ARG(QString,script),Q_ARG(QString,scriptId)); response.setData("ok"); } else if(operation=="direct") { //directly runs the given script code QString code = QString::fromUtf8(parameters.value("code")); QString useIncludes = QString::fromUtf8(parameters.value("useIncludes")); if(code.isEmpty()) { response.writeRequestError("need parameter: code"); } else { if(scriptMgr->scriptIsRunning()) { response.setData("error: a script is already running"); return; } //use QVariant logic to convert to bool bool bUseIncludes = QVariant(useIncludes).toBool(); //also requires queued connection QMetaObject::invokeMethod(scriptMgr,"runScriptDirect", Qt::QueuedConnection, Q_ARG(QString,code), Q_ARG(QString,bUseIncludes ? QStringLiteral("") : QString() )); response.setData("ok"); } } else if(operation=="stop") { //scriptMgr->stopScript(); QMetaObject::invokeMethod(scriptMgr,"stopScript",SERVICE_DEFAULT_INVOKETYPE); response.setData("ok"); } else { //TODO some sort of service description? response.writeRequestError("unsupported operation. GET: list,info,status POST: run,direct,stop"); } }
void Game::placeTokenSlot(QVariant r, QVariant c, QVariant crd){ int row = r.toInt(); int col = c.toInt(); int card = crd.toInt(); Player* currentPlayer = players[currentTurn]; if(currentPlayer->hasCard(card) && !board.occupied(row, col)){ QVariant returnVal; QVariant arg = "has card"; QMetaObject::invokeMethod(qmlRoot, "placeToken", Q_RETURN_ARG(QVariant, returnVal), Q_ARG(QVariant, row), Q_ARG(QVariant, col)); currentPlayer->performTurn(row, col, card); board.setToken(row, col, currentPlayer->team); currentTurn++; } }
void ExperimentManager_Dialog::LogMessage(QString sMessage) { QMetaObject::invokeMethod(MainAppInfo::getMainWindow(), MainAppInfo::getMainWindowLogSlotName().toLatin1(), Qt::DirectConnection, Q_ARG(QString, sMessage)); }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); app.setOrganizationName("Cockatrice"); app.setApplicationName("Servatrice"); QStringList args = app.arguments(); bool testRandom = args.contains("--test-random"); bool testHashFunction = args.contains("--test-hash"); bool logToConsole = args.contains("--log-to-console"); QString configPath; int hasConfigPath=args.indexOf("--config"); if(hasConfigPath > -1 && args.count() > hasConfigPath + 1) configPath = args.at(hasConfigPath + 1); qRegisterMetaType<QList<int> >("QList<int>"); #if QT_VERSION < 0x050000 // gone in Qt5, all source files _MUST_ be utf8-encoded QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); #endif configPath = SettingsCache::guessConfigurationPath(configPath); qWarning() << "Using configuration file: " << configPath; settingsCache = new SettingsCache(configPath); loggerThread = new QThread; loggerThread->setObjectName("logger"); logger = new ServerLogger(logToConsole); logger->moveToThread(loggerThread); loggerThread->start(); QMetaObject::invokeMethod(logger, "startLog", Qt::BlockingQueuedConnection, Q_ARG(QString, settingsCache->value("server/logfile", QString("server.log")).toString())); #if QT_VERSION < 0x050000 if (logToConsole) qInstallMsgHandler(myMessageOutput); else qInstallMsgHandler(myMessageOutput2); #else if (logToConsole) qInstallMessageHandler(myMessageOutput); else qInstallMessageHandler(myMessageOutput2); #endif #ifdef Q_OS_UNIX struct sigaction hup; hup.sa_handler = ServerLogger::hupSignalHandler; sigemptyset(&hup.sa_mask); hup.sa_flags = 0; hup.sa_flags |= SA_RESTART; sigaction(SIGHUP, &hup, 0); struct sigaction segv; segv.sa_handler = sigSegvHandler; segv.sa_flags = SA_RESETHAND; sigemptyset(&segv.sa_mask); sigaction(SIGSEGV, &segv, 0); sigaction(SIGABRT, &segv, 0); signal(SIGPIPE, SIG_IGN); #endif rng = new RNG_SFMT; std::cerr << "Servatrice " << VERSION_STRING << " starting." << std::endl; std::cerr << "-------------------------" << std::endl; PasswordHasher::initialize(); if (testRandom) testRNG(); if (testHashFunction) testHash(); Servatrice *server = new Servatrice(); QObject::connect(server, SIGNAL(destroyed()), &app, SLOT(quit()), Qt::QueuedConnection); int retval = 0; if (server->initServer()) { std::cerr << "-------------------------" << std::endl; std::cerr << "Server initialized." << std::endl; #if QT_VERSION < 0x050000 qInstallMsgHandler(myMessageOutput); #else qInstallMessageHandler(myMessageOutput); #endif retval = app.exec(); std::cerr << "Server quit." << std::endl; std::cerr << "-------------------------" << std::endl; } delete rng; delete settingsCache; logger->deleteLater(); loggerThread->wait(); delete loggerThread; // Delete all global objects allocated by libprotobuf. google::protobuf::ShutdownProtobufLibrary(); return retval; }
// Asynchronously load the new scene given by sceneName void SceneManager::setScene( const char* sceneName ) { QMetaObject::invokeMethod(this, "onLoadNewScene", Qt::QueuedConnection, Q_ARG(QString, QString(sceneName))); }
void SocketController::getVlanSettings() { if (!connectionLost) { vlanSubtab->setProperty("init", true); vlanTabId->setProperty("init", true); //QString vlanType = "portBased";//"802.1q";// QString vlanType = getParamInfo("VlanType"); if(vlanType == emptyString) { logOutSignal(); return; } vlanTypeComboBox->setProperty("currentIndex", findIndexByValue(vlanTypeList, vlanTypeCount, vlanType)); if(vlanType != "noVlan") { //portCount = 8; QString portCountStr = getParamInfo("PortCount"); if(portCountStr == emptyString) { logOutSignal(); return; } portCount = portCountStr.toInt(); QVariant retValue; QMetaObject::invokeMethod(vlanCurrentModel, "init", Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, portCount), Q_ARG(QVariant, vlanCount)); portRepeater->setProperty("model", portCount); QMetaObject::invokeMethod(vlanCurrentModel, "deleteAllChecks", Q_RETURN_ARG(QVariant, retValue)); VlanSettingsParser* parser = new VlanSettingsParser(); QString portVlanData = getParamInfo("VlanSettings"); // QString portVlanData = "1 1\n2 1\n3 1\n1 3\n4 2\n5 2\n6 2\n7 3\n8 3\n";// if(portVlanData == emptyString) { logOutSignal(); return; } QList<QPair<int, int>> portVlanDataResult = parser->parsePortVlanData(portVlanData); for (int i = 0; i < portVlanDataResult.count(); i++) { QPair<int, int> portVlanPair = portVlanDataResult.at(i); QMetaObject::invokeMethod(vlanCurrentModel, "addPortVlanEnabled", Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, portVlanPair.first), Q_ARG(QVariant, portVlanPair.second)); } //QString portPvidData = "1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7\n8 8\n"; // QString portPvidData = getParamInfo("PortsPvid"); if(portPvidData == emptyString) { logOutSignal(); return; } QMap<int, int> portPvidDataResult = parser->parsePortPvidData(portPvidData); for(int port = 1; port <= portCount; port++) { QMetaObject::invokeMethod(vlanCurrentModel, "setPortPvid", Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, port), Q_ARG(QVariant, portPvidDataResult[port])); } if (vlanType == "802.1q") { //QString portTaggingData = "1 On\n2 Off\n3 On\n4 On\n5 On\n6 On\n7 On\n8 On\n";// QString portTaggingData = getParamInfo("PortsTaggingStatus"); if(portTaggingData == emptyString) { logOutSignal(); return; } QMap<int, QString> portTaggingDataResult = parser->parsePortTaggingData(portTaggingData); for(int port = 1; port <= portCount; port++) { QMetaObject::invokeMethod(vlanCurrentModel, "setPortTaggingStatus", Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, port), Q_ARG(QVariant, findIndexByValue(portTaggingStatusList, portTaggingStatusCount, portTaggingDataResult[port]))); } } } vlanSubtab->setProperty("init", false); vlanTabId->setProperty("init", false); } }
bool EventPlugin::createEvent(const QString &event_name, const QVariantMap &event_params) { qfLogFuncFrame(); closeEvent(); qff::MainWindow *fwk = qff::MainWindow::frameWork(); EventPlugin::ConnectionType connection_type = connectionType(); QStringList existing_event_ids; if(connection_type == ConnectionType::SingleFile) existing_event_ids = existingFileEventNames(); else existing_event_ids = existingSqlEventNames(); QString event_id = event_name; QVariantMap new_params = event_params; do { qfd::Dialog dlg(fwk); dlg.setButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); EventDialogWidget *event_w = new EventDialogWidget(); event_w->setEventId(event_id); event_w->loadParams(new_params); dlg.setCentralWidget(event_w); if(!dlg.exec()) return false; event_id = event_w->eventId(); new_params = event_w->saveParams(); if(event_id.isEmpty()) { qf::qmlwidgets::dialogs::MessageBox::showError(fwk, tr("Event ID cannot be empty.")); continue; } if(existing_event_ids.contains(event_id)) { qf::qmlwidgets::dialogs::MessageBox::showError(fwk, tr("Event ID %1 exists already.").arg(event_id)); continue; } break; } while(true); bool ok = false; Event::EventConfig event_config; //ConnectionSettings connection_settings; event_config.setValue("event", new_params); int stage_count = event_params.value("stageCount").toInt(); if(stage_count == 0) stage_count = event_config.stageCount(); qfInfo() << "createEvent, stage_count:" << stage_count; QF_ASSERT(stage_count > 0, "Stage count have to be greater than 0", return false); qfInfo() << "will create:" << event_id; qfs::Connection conn = qfs::Connection::forName(); //QF_ASSERT(conn.isOpen(), "Connection is not open", return false); if(connection_type == ConnectionType::SingleFile) { QString event_fn = eventNameToFileName(event_id); conn.close(); conn.setDatabaseName(event_fn); conn.open(); } if(conn.isOpen()) { QVariantMap create_options; create_options["schemaName"] = event_id; create_options["driverName"] = conn.driverName(); QVariant ret_val; QMetaObject::invokeMethod(this, "createDbSqlScript", Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret_val), Q_ARG(QVariant, create_options)); QStringList create_script = ret_val.toStringList(); qfInfo().nospace() << create_script.join(";\n") << ';'; qfs::Query q(conn); do { qfs::Transaction transaction(conn); ok = run_sql_script(q, create_script); if(!ok) break; qfDebug() << "creating stages:" << stage_count; QString stage_table_name = "stages"; if(connection_type == ConnectionType::SqlServer) stage_table_name = event_id + '.' + stage_table_name; q.prepare("INSERT INTO " + stage_table_name + " (id) VALUES (:id)"); for(int i=0; i<stage_count; i++) { q.bindValue(":id", i+1); ok = q.exec(); if(!ok) { break; } } if(!ok) break; conn.setCurrentSchema(event_id); event_config.save(); transaction.commit(); } while(false); if(!ok) { qfd::MessageBox::showError(fwk, tr("Create Database Error: %1").arg(q.lastError().text())); } } else { qfd::MessageBox::showError(fwk, tr("Cannot create event, database is not open: %1").arg(conn.lastError().text())); } if(ok) { ok = openEvent(event_id); } return ok; }
void LogicManager::restartWithNewProfile(QString uid) { QMetaObject::invokeMethod(this, "onRestartWithNewProfile", Qt::QueuedConnection, Q_ARG(QString, uid)); }
bool SourceDelegate::editorEvent( QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index ) { QMouseEvent* mEvent = 0; switch ( event->type() ) { // case QEvent::MouseTrackingChange: case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: mEvent = static_cast< QMouseEvent* >( event ); default: break; } bool hoveringTrack = false; if ( m_trackRects.contains( index ) && mEvent ) { const QRect trackRect = m_trackRects[ index ]; hoveringTrack = trackRect.contains( mEvent->pos() ); if ( hoveringTrack ) { if ( m_trackHovered != index ) { m_trackHovered = index; QMetaObject::invokeMethod( m_parent, "update", Qt::QueuedConnection, Q_ARG( QModelIndex, index ) ); } } } if ( !hoveringTrack ) { if ( m_trackHovered.isValid() ) QMetaObject::invokeMethod( m_parent, "update", Qt::QueuedConnection, Q_ARG( QModelIndex, m_trackHovered ) ); m_trackHovered = QPersistentModelIndex(); } bool lockRectContainsClick = false, headphonesRectContainsClick = false; if ( m_headphoneRects.contains( index ) && mEvent ) { const QRect headphoneRect = m_headphoneRects[ index ]; headphonesRectContainsClick = headphoneRect.contains( mEvent->pos() ); } if ( m_lockRects.contains( index ) && mEvent ) { const QRect lockRect = m_lockRects[ index ]; lockRectContainsClick = lockRect.contains( mEvent->pos() ); } if ( event->type() == QEvent::MouseMove ) { if ( hoveringTrack || lockRectContainsClick || headphonesRectContainsClick ) m_parent->setCursor( Qt::PointingHandCursor ); else m_parent->setCursor( Qt::ArrowCursor ); } if ( event->type() == QEvent::MouseButtonRelease || event->type() == QEvent::MouseButtonPress ) { SourcesModel::RowType type = static_cast< SourcesModel::RowType >( index.data( SourcesModel::SourceTreeItemTypeRole ).toInt() ); if ( type == SourcesModel::TemporaryPage || type == SourcesModel::DeletablePage || type == SourcesModel::RemovablePage ) { SourceTreeItem* gpi = index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >(); Q_ASSERT( gpi ); QStyleOptionViewItemV4 o = option; initStyleOption( &o, index ); const int padding = m_margin / 8; const QRect r( o.rect.right() - padding - m_iconHeight, padding + o.rect.y(), m_iconHeight, m_iconHeight ); if ( r.contains( mEvent->pos() ) ) { if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { gpi->removeFromList(); // Send a new mouse event to the view, since if the mouse is now over another item's delete area we want it to show up QMouseEvent* ev = new QMouseEvent( QEvent::MouseMove, m_parent->viewport()->mapFromGlobal( QCursor::pos() ), Qt::NoButton, Qt::NoButton, Qt::NoModifier ); QApplication::postEvent( m_parent->viewport(), ev ); } return true; } } else if ( type == SourcesModel::Source ) { SourceItem* colItem = qobject_cast< SourceItem* >( index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >() ); Q_ASSERT( colItem ); if ( hoveringTrack && colItem->source() && colItem->source()->currentTrack() ) { if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { ViewManager::instance()->show( colItem->source()->currentTrack() ); return true; } else if ( event->type() == QEvent::MouseButtonPress && mEvent->button() == Qt::RightButton ) { Tomahawk::ContextMenu* contextMenu = new Tomahawk::ContextMenu( m_parent ); contextMenu->setQuery( colItem->source()->currentTrack() ); contextMenu->exec( QCursor::pos() ); return true; } } if ( !colItem->source().isNull() && !colItem->source()->currentTrack().isNull() && !colItem->source()->isLocal() ) { if ( headphonesRectContainsClick || lockRectContainsClick ) { if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { if ( headphonesRectContainsClick ) { if ( index.data( SourcesModel::LatchedOnRole ).toBool() ) // unlatch emit latchOff( colItem->source() ); else emit latchOn( colItem->source() ); } else // it's in the lock rect emit toggleRealtimeLatch( colItem->source(), !index.data( SourcesModel::LatchedRealtimeRole ).toBool() ); } return true; } } } else if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton && type == SourcesModel::StaticPlaylist ) { PlaylistItem* plItem = qobject_cast< PlaylistItem* >( index.data( SourcesModel::SourceTreeItemRole ).value< SourceTreeItem* >() ); Q_ASSERT( plItem ); if ( plItem->canSubscribe() && !plItem->subscribedIcon().isNull() ) { const int padding = m_margin / 16; const int imgWidth = option.rect.height() - 2 * padding; const QRect subRect( option.rect.right() - padding - imgWidth, option.rect.top() + padding, imgWidth, imgWidth ); if ( subRect.contains( mEvent->pos() ) ) { // Toggle playlist subscription plItem->setSubscribed( !plItem->subscribed() ); } } } } // We emit our own clicked() signal instead of relying on QTreeView's, because that is fired whether or not a delegate accepts // a mouse press event. Since we want to swallow click events when they are on headphones other action items, here we make sure we only // emit if we really want to if ( event->type() == QEvent::MouseButtonRelease && mEvent->button() == Qt::LeftButton ) { if ( m_lastClicked == -1 ) { m_lastClicked = QDateTime::currentMSecsSinceEpoch(); emit clicked( index ); } else { qint64 elapsed = QDateTime::currentMSecsSinceEpoch() - m_lastClicked; if ( elapsed < QApplication::doubleClickInterval() ) { m_lastClicked = -1; emit doubleClicked( index ); } else { m_lastClicked = QDateTime::currentMSecsSinceEpoch(); emit clicked( index ); } } } return QStyledItemDelegate::editorEvent( event, model, option, index ); }
void QxtMDNSPrivate::avahiRecordBrowserCallback(AvahiRecordBrowser *b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, uint16_t clazz, uint16_t type, const void *rdata, size_t size, AvahiLookupResultFlags flags, void *userdata) { ///@TODO Support IPv6 Q_UNUSED(interface); Q_UNUSED(protocol); Q_UNUSED(name); Q_UNUSED(clazz); Q_UNUSED(type); Q_UNUSED(size); Q_UNUSED(flags); QxtMDNSPrivate* self = static_cast<QxtMDNSPrivate*>(userdata); self->recordbrowser = b; // qDebug() << "Return thing" << md->name << name << size; switch (event) { case AVAHI_BROWSER_NEW: { //Found an entry! uint32_t ip = qFromBigEndian(*static_cast<const uint32_t*>(rdata)); if (self->sent) { QHostInfo info(self->info.lookupId()); info.setAddresses(QList<QHostAddress>() << QHostAddress(ip)); QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, info)); } else { self->addresses << QHostAddress(ip); } break; } case AVAHI_BROWSER_REMOVE: { uint32_t ip = qFromBigEndian(*static_cast<const uint32_t*>(rdata)); self->addresses.removeAll(QHostAddress(ip)); break; } case AVAHI_BROWSER_CACHE_EXHAUSTED: break; case AVAHI_BROWSER_ALL_FOR_NOW: if (self->addresses.count() == 0) { self->info.setError(QHostInfo::HostNotFound); self->info.setErrorString("The host was not found."); } else { self->info.setAddresses(self->addresses); self->addresses.clear(); } QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, self->info)); self->sent = true; break; case AVAHI_BROWSER_FAILURE: if (self->sent) { QHostInfo info(self->info.lookupId()); info.setError(QHostInfo::UnknownError); info.setErrorString(avahi_strerror(avahi_client_errno(self->client))); info.setAddresses(self->addresses); QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, info)); } else { self->info.setError(QHostInfo::UnknownError); self->info.setErrorString(avahi_strerror(avahi_client_errno(self->client))); self->info.setAddresses(self->addresses); self->addresses.clear(); QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, self->info)); self->sent = true; } break; } }
void PresentationDisplayTask::PresentationGui_alignPageScrollerToPageNumber(int pageNo) { QVariant iPageNo = QVariant::fromValue(pageNo); QMetaObject::invokeMethod(m_panel, "alignPageScrollerToPageNumber", Q_ARG(QVariant, iPageNo)); }
void PresentationDisplayTask::setSlideNumberDisplay(QString text) { QVariant txt = QVariant::fromValue(text); QMetaObject::invokeMethod(m_panel, "setSlideNumber", Q_ARG(QVariant, txt)); }
void Core::GetUsersForAccount (const QString& accountID) { QMetaObject::invokeMethod (StorageThread_->GetStorage (), "getUsersForAccount", Qt::QueuedConnection, Q_ARG (QString, accountID)); } void Core::GetChatLogs (const QString& accountId, const QString& entryId, int backpages, int amount) { QMetaObject::invokeMethod (StorageThread_->GetStorage (), "getChatLogs", Qt::QueuedConnection, Q_ARG (QString, accountId), Q_ARG (QString, entryId), Q_ARG (int, backpages), Q_ARG (int, amount)); } void Core::Search (const QString& accountId, const QString& entryId, const QString& text, int shift, bool cs) { QMetaObject::invokeMethod (StorageThread_->GetStorage (), "search", Qt::QueuedConnection, Q_ARG (QString, accountId), Q_ARG (QString, entryId), Q_ARG (QString, text), Q_ARG (int, shift),
void EAPDaemonAdapter::Login(const QVariantMap &userinfo) { // handle method call com.qh3client.EAPDaemon.Login QMetaObject::invokeMethod(parent(), "Login", Q_ARG(QVariantMap, userinfo)); }
void RssCommandsApiController::service(HttpRequest& request, HttpResponse& response) { if (!CheckCreditinals(request, response)) { return; } QString method = request.getMethod(); if (method.compare("post", Qt::CaseInsensitive) == 0) { QString feedId = request.getParameter("feedId"); #ifdef Q_WS_WIN feedId = QString("{%1}").arg(feedId); #endif QUuid uid(feedId); QString action = request.getParameter("action"); RssFeed* pFeed = m_pRssManager->findFeed(uid); if (pFeed != NULL) { if (action.compare("remove", Qt::CaseInsensitive) == 0) { //QEventLoop loop; if (!QMetaObject::invokeMethod(m_pRssManager.get(), "removeFeed", Qt::QueuedConnection, Q_ARG(QUuid, uid))) { qWarning() << "QMetaObject::invokeMethod removeFeed failed"; } //m_pRssManager->removeFeed(uid); } else if (action.compare("downloadItem", Qt::CaseInsensitive) == 0) { } } else { response.setStatus(404, "Not Found"); response.write("<BODY><h3>404 RSS Feed not found.</h3>"); response.write("</BODY>"); } } else { response.setStatus(405, "Method Not Allowed"); response.write("<BODY><h3>405 Method Not Allowed.</h3>"); response.write("</BODY>"); } }
/// /// \brief queues up the execution of a function by calling the execute slot /// via queued connection /// \param func /// void DeferHelper::queue(const DeferHelper::VoidFunc &func) { qRegisterMetaType<VoidFunc>("VoidFunc"); QMetaObject::invokeMethod( this, "execute", Qt::QueuedConnection, Q_ARG( VoidFunc, func)); }
MediaTools::MediaTools(QQmlApplicationEngine *engine, QObject *parent): QObject(parent) { this->m_appEngine = engine; this->m_playAudioFromSource = true; this->m_recordAudioFrom = RecordFromMic; this->m_recording = false; this->m_windowWidth = 0; this->m_windowHeight = 0; this->m_advancedMode = false; this->m_enableVirtualCamera = false; Ak::setQmlEngine(engine); this->m_pipeline = AkElement::create("Bin", "pipeline"); if (this->m_pipeline) { QFile jsonFile(":/Webcamoid/share/mainpipeline.json"); jsonFile.open(QFile::ReadOnly); QString description(jsonFile.readAll()); jsonFile.close(); this->m_pipeline->setProperty("description", description); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_source), Q_ARG(QString, "source")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_audioSwitch), Q_ARG(QString, "audioSwitch")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_audioOutput), Q_ARG(QString, "audioOutput")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_mic), Q_ARG(QString, "mic")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_record), Q_ARG(QString, "record")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_videoCapture), Q_ARG(QString, "videoCapture")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_desktopCapture), Q_ARG(QString, "desktopCapture")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_videoMux), Q_ARG(QString, "videoMux")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_videoOutput), Q_ARG(QString, "videoOutput")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_videoGen), Q_ARG(QString, "videoGen")); QMetaObject::invokeMethod(this->m_pipeline.data(), "element", Q_RETURN_ARG(AkElementPtr, this->m_virtualCamera), Q_ARG(QString, "virtualCamera")); if (this->m_videoOutput) this->m_videoOutput->link(this); if (this->m_source) { QObject::connect(this->m_source.data(), SIGNAL(error(const QString &)), this, SIGNAL(error(const QString &))); QObject::connect(this->m_source.data(), SIGNAL(stateChanged(AkElement::ElementState)), this, SIGNAL(stateChanged(AkElement::ElementState))); QObject::connect(this->m_source.data(), SIGNAL(stateChanged(AkElement::ElementState)), this->m_audioOutput.data(), SLOT(setState(AkElement::ElementState))); }
void start(const QVariant &vrequest, Mode mode) { outSeq = 0; outCredits = 0; quiet = false; ZhttpRequestPacket request; if(!request.fromVariant(vrequest)) { log_warning("failed to parse zurl request"); QVariantHash vhash = vrequest.toHash(); rid = vhash.value("id").toByteArray(); toAddress = vhash.value("from").toByteArray(); QByteArray type = vhash.value("type").toByteArray(); if(!toAddress.isEmpty() && type != "error" && type != "cancel") { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); } else { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); } return; } rid = request.id; toAddress = request.from; userData = request.userData; sentHeader = false; stuffToRead = false; bytesReceived = 0; ignorePolicies = request.ignorePolicies; if(request.uri.isEmpty()) { log_warning("missing request uri"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } QString scheme = request.uri.scheme(); if(scheme == "https" || scheme == "http") { transport = HttpTransport; } else if(scheme == "wss" || scheme == "ws") { transport = WebSocketTransport; } else { log_warning("unsupported scheme"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } if(transport == WebSocketTransport && mode != Worker::Stream) { log_warning("websocket must be used from stream interface"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } int defaultPort; if(scheme == "https" || scheme == "wss") defaultPort = 443; else // http || wss defaultPort = 80; HttpHeaders headers = request.headers; if(transport == HttpTransport) { // fire and forget if(mode == Worker::Stream && (rid.isEmpty() || toAddress.isEmpty())) quiet = true; // streaming only allowed on streaming interface if(mode == Worker::Stream) outStream = request.stream; else outStream = false; if(request.method.isEmpty()) { log_warning("missing request method"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data()); // inbound streaming must start with sequence number of 0 if(mode == Worker::Stream && request.more && request.seq != 0) { log_warning("streamed input must start with seq 0"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } // can't use these two together if(mode == Worker::Single && request.more) { log_warning("cannot use streamed input on router interface"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } bodySent = false; inSeq = request.seq; if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost))) { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation")); return; } QByteArray hostHeader = request.uri.host().toUtf8(); // only tack on the port if it isn't being overridden int port = request.uri.port(defaultPort); if(request.connectPort == -1 && port != defaultPort) hostHeader += ":" + QByteArray::number(port); headers.removeAll("Host"); headers += HttpHeader("Host", hostHeader); hreq = new HttpRequest(dns, this); connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &))); connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead())); connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int))); connect(hreq, SIGNAL(error()), SLOT(req_error())); maxResponseSize = request.maxSize; sessionTimeout = request.timeout; if(!request.connectHost.isEmpty()) hreq->setConnectHost(request.connectHost); if(request.connectPort != -1) request.uri.setPort(request.connectPort); hreq->setIgnoreTlsErrors(request.ignoreTlsErrors); if(request.followRedirects) hreq->setFollowRedirects(8); if(request.credits != -1) outCredits += request.credits; } else // WebSocketTransport { log_info("IN id=%s, %s", request.id.data(), request.uri.toEncoded().data()); // inbound streaming must start with sequence number of 0 if(request.seq != 0) { log_warning("websocket input must start with seq 0"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } if(toAddress.isEmpty()) { log_warning("websocket input must provide from address"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } inSeq = request.seq; if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost))) { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation")); return; } QByteArray hostHeader = request.uri.host().toUtf8(); // only tack on the port if it isn't being overridden int port = request.uri.port(defaultPort); if(request.connectPort == -1 && port != defaultPort) hostHeader += ":" + QByteArray::number(port); headers.removeAll("Host"); headers += HttpHeader("Host", hostHeader); ws = new WebSocket(dns, this); connect(ws, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &))); connect(ws, SIGNAL(connected()), SLOT(ws_connected())); connect(ws, SIGNAL(readyRead()), SLOT(ws_readyRead())); connect(ws, SIGNAL(framesWritten(int)), SLOT(ws_framesWritten(int))); connect(ws, SIGNAL(peerClosing()), SLOT(ws_peerClosing())); connect(ws, SIGNAL(closed()), SLOT(ws_closed())); connect(ws, SIGNAL(error()), SLOT(ws_error())); if(!request.connectHost.isEmpty()) ws->setConnectHost(request.connectHost); if(request.connectPort != -1) request.uri.setPort(request.connectPort); ws->setIgnoreTlsErrors(request.ignoreTlsErrors); ws->setMaxFrameSize(config->sessionBufferSize); if(request.credits != -1) outCredits += request.credits; } httpActivityTimer = new QTimer(this); connect(httpActivityTimer, SIGNAL(timeout()), SLOT(httpActivity_timeout())); httpActivityTimer->setSingleShot(true); httpActivityTimer->start(config->activityTimeout * 1000); if(sessionTimeout != -1) { httpSessionTimer = new QTimer(this); connect(httpSessionTimer, SIGNAL(timeout()), SLOT(httpSession_timeout())); httpSessionTimer->setSingleShot(true); httpSessionTimer->start(sessionTimeout); } if(transport == WebSocketTransport || (transport == HttpTransport && mode == Worker::Stream)) { expireTimer = new QTimer(this); connect(expireTimer, SIGNAL(timeout()), SLOT(expire_timeout())); expireTimer->setSingleShot(true); expireTimer->start(SESSION_EXPIRE); keepAliveTimer = new QTimer(this); connect(keepAliveTimer, SIGNAL(timeout()), SLOT(keepAlive_timeout())); keepAliveTimer->start(SESSION_EXPIRE / 2); } if(transport == HttpTransport) { if(!request.body.isEmpty() && !request.more && !headers.contains("Content-Length")) headers += HttpHeader("Content-Length", QByteArray::number(request.body.size())); bool hasOrMightHaveBody = (!request.body.isEmpty() || request.more); hreq->start(request.method, request.uri, headers, hasOrMightHaveBody); if(hasOrMightHaveBody) { if(!request.body.isEmpty()) hreq->writeBody(request.body); if(!request.more) { bodySent = true; hreq->endBody(); } } else bodySent = true; if(mode == Stream) { if(request.more) { // send cts ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::Credit; resp.credits = config->sessionBufferSize; writeResponse(resp); } else { // send ack ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::KeepAlive; writeResponse(resp); } } } else // WebSocketTransport { ws->start(request.uri, headers); } }
void QDeviceWatcherPrivate::emitDeviceChanged(const QString &dev) { if (!QMetaObject::invokeMethod(watcher, "deviceChanged", Q_ARG(QString, dev))) qWarning("invoke deviceChanged failed"); }
void CWebAPI::OnRequestCompleted() { CHttpSocket* pRequest = (CHttpSocket*)sender(); ASSERT(pRequest->GetState() == CHttpSocket::eHandling); QString Path = pRequest->GetPath(); TArguments Cookies = GetArguments(pRequest->GetHeader("Cookie")); TArguments Arguments = GetArguments(pRequest->GetQuery().mid(1),'&'); switch(pRequest->GetType()) { case CHttpSocket::eDELETE: pRequest->RespondWithError(501); case CHttpSocket::eHEAD: case CHttpSocket::eOPTIONS: pRequest->SendResponse(); return; } if(Path.compare("/WebAPI/") == 0) pRequest->RespondWithError(403); else if(Path.left(14).compare("/WebAPI/Icons/") == 0) { int Size; if(Arguments["Size"] == "Small") Size = 16; else // if(Arguments["Size"] == "Large") Size = 32; QString Ext = Split2(Path.mid(14), ".").first; QString IconPath = theCore->Cfg()->GetSettingsDir() + "/Cache/Icons/" + Ext + QString::number(Size) + ".png"; if(!QFile::exists(IconPath)) { if(theLoader) QMetaObject::invokeMethod(theLoader, "CreateFileIcon", Qt::BlockingQueuedConnection, Q_ARG(QString, Ext)); else IconPath = ":/Icon" + QString::number(Size) + ".png"; } pRequest->SetCaching(HR2S(48)); pRequest->RespondWithFile(IconPath); } else if(Path.left(11).compare("/WebAPI/FS/") == 0) { StrPair CmdExt = Split2(Path.mid(11),"."); QVariantMap Result; if(CmdExt.first.compare("dir", Qt::CaseInsensitive) == 0) { QVariantList Entrys; QString DirPath = Arguments["Path"]; QDir Dir(DirPath); foreach (const QString& Name, Dir.entryList()) { if (Name.compare(".") == 0 || Name.compare("..") == 0) continue; QVariantMap Entry; QFileInfo Info(DirPath + "/" + Name); Entry["Name"] = Info.fileName(); Entry["Created"] = Info.created(); Entry["Modifyed"] = Info.lastModified(); if (Info.isDir()) Entry["Size"] = "dir"; else Entry["Size"] = Info.size(); Entrys.append(Entry); } Result["List"] = Entrys; }
SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif
void PresentationDisplayTask::showHidePanel(bool show) { QVariant showHide = QVariant::fromValue(show); QMetaObject::invokeMethod(m_panel, "showHidePresentation", Q_ARG(QVariant, showHide)); }
void setTitle(const QString &title) { const auto text = QString("<b>%1</b>").arg(title.toHtmlEscaped()); //cannot call setText in calling thread, forward to the label slot QMetaObject::invokeMethod(_label, "setText", Qt::QueuedConnection, Q_ARG(QString, text)); }
void ZealDocsetsRegistry::runQuery(const QString& query) { lastQuery += 1; QMetaObject::invokeMethod(this, "_runQuery", Qt::QueuedConnection, Q_ARG(QString, query), Q_ARG(int, lastQuery)); }
void write(const QVariant &vrequest) { ZhttpRequestPacket request; if(!request.fromVariant(vrequest)) { QVariantHash vhash = vrequest.toHash(); if(vhash["type"].toByteArray() != "cancel") { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); } else { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); } return; } // cancel session if a wrong sequenced packet is received if(inSeq == -1 || request.seq == -1 || request.seq != inSeq + 1) { if(request.type != ZhttpRequestPacket::Cancel) { QMetaObject::invokeMethod(this, "respondCancel", Qt::QueuedConnection); } else { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); } return; } if(request.type == ZhttpRequestPacket::Cancel) { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); return; } inSeq = request.seq; refreshTimeout(); // all we care about from follow-up writes are body and credits if(request.credits != -1) outCredits += request.credits; if(transport == HttpTransport) { if(request.type == ZhttpRequestPacket::Data) { if(bodySent) { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } refreshActivityTimeout(); if(!request.body.isEmpty()) hreq->writeBody(request.body); // the 'more' flag only has significance if body field present if(!request.more) { bodySent = true; hreq->endBody(); } } } else // WebSocketTransport { if(request.type == ZhttpRequestPacket::Data || request.type == ZhttpRequestPacket::Close || request.type == ZhttpRequestPacket::Ping || request.type == ZhttpRequestPacket::Pong) { refreshActivityTimeout(); if(request.type == ZhttpRequestPacket::Data) { WebSocket::Frame::Type ftype; if(wsSendingMessage) ftype = WebSocket::Frame::Continuation; else if(request.contentType == "binary") ftype = WebSocket::Frame::Binary; else ftype = WebSocket::Frame::Text; wsSendingMessage = request.more; wsPendingWrites += request.body.size(); ws->writeFrame(WebSocket::Frame(ftype, request.body, request.more)); } else if(request.type == ZhttpRequestPacket::Ping) { wsPendingWrites += 0; ws->writeFrame(WebSocket::Frame(WebSocket::Frame::Ping, QByteArray(), false)); } else if(request.type == ZhttpRequestPacket::Pong) { wsPendingWrites += 0; ws->writeFrame(WebSocket::Frame(WebSocket::Frame::Pong, QByteArray(), false)); } else if(request.type == ZhttpRequestPacket::Close) ws->close(request.code); } } // if we needed credits to send something, take care of that now if(request.credits != -1 && stuffToRead) trySend(); }
void dispatch(QString type, QJSValue message) { for (int i = 0 ; i < 3;i++) { QMetaObject::invokeMethod(this,"dispatched",Q_ARG(QString, type), Q_ARG(QJSValue, message)); } }
Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { Q_UNUSED(wallet); Q_UNUSED(hash); Q_UNUSED(status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection); } static void ShowProgress(WalletModel *walletmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly) { QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveWatchonly)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
char* QmlBridge_SendToGo(void* ptr, char* data) { QString returnArg; QMetaObject::invokeMethod(static_cast<QmlBridge*>(ptr), "sendToGo", Q_RETURN_ARG(QString, returnArg), Q_ARG(QString, QString(data))); return returnArg.toUtf8().data(); }