int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QJSEngine engine; //! [0] engine.globalObject().setProperty("foo", 123); qDebug() << "foo times two is:" << engine.evaluate("foo * 2").toNumber(); //! [0] return 0; }
void EnginioQmlClientPrivate::_setEngine() { QJSEngine *engine = QtQml::qmlEngine(q_ptr); _engine = engine; _stringify = engine->evaluate("JSON.stringify"); _parse = engine->evaluate("JSON.parse"); Q_ASSERT(_stringify.isCallable()); Q_ASSERT(_parse.isCallable()); }
Authenticate::Authenticate(std::map<std::string, std::string> config, QObject *parent) : QObject(parent) { QSettings settings; authorized = settings.value("authorized").toStringList(); QJSEngine engine; QJSValue eventEngineValue = engine.newQObject(this); engine.globalObject().setProperty("auth", eventEngineValue); QString str = config["authSettings"].c_str(); QFile file(str); if(!file.open(QIODevice::ReadOnly)) { qDebug()<<"failed to open config file: "<<str; return; } QString script = file.readAll(); file.close(); engine.evaluate(script); }
void MainWindow::init() { QFile fJsonApi(":/api.json"); if (!fJsonApi.open(QIODevice::ReadOnly)) { qWarning() << "Unable to open api.json"; qApp->quit(); return; } QString jsonData = fJsonApi.readAll(); QJSEngine eng; eng.evaluate(QString("a = %1").arg(jsonData)); sAppHash = eng.evaluate("a.app_hash").toString(); sAppId = eng.evaluate("a.app_id").toInt(); m_configDir = QDir::homePath() + "/.config/sail-e-gram"; if (!QFileInfo(m_configDir).exists()) { qDebug("Had to make the config directory"); QDir cfg(QDir::homePath() + "/.config"); if (!cfg.exists()) { qWarning() << ".config dir does not exist!!"; qApp->quit(); return; } if (!cfg.mkdir("sail-e-gram")) { qWarning() << "Failed to created sail-e-gram"; qApp->quit(); return; } } QString file = m_configDir + "/settings.ini"; m_settings = new QSettings(file, QSettings::IniFormat, this); QString msisdn = m_settings->value(SK_MSISDN).toString(); if (!msisdn.isEmpty()) { userLoginWithMSISDN(msisdn); } m_view->rootContext()->setContextProperty("g_mainwindow", this); m_view->show(); }//MainWindow::init
void tst_QJSValueIterator::iterateString() { QJSEngine engine; QJSValue obj = engine.evaluate("new String('ciao')"); QVERIFY(obj.property("length").isNumber()); int length = obj.property("length").toInt(); QCOMPARE(length, 4); QJSValueIterator it(obj); QHash<QString, QJSValue> stringProperties; bool iteratedThruLength = false; while (it.hasNext()) { it.next(); const QString name = it.name(); if (name == QString::fromLatin1("length")) { QVERIFY(it.value().isNumber()); QCOMPARE(it.value().toInt(), length); QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration."); iteratedThruLength = true; continue; } QVERIFY2(!stringProperties.contains(name), "property appeared more than once during iteration."); stringProperties.insert(name, it.value()); QVERIFY(it.value().strictlyEquals(obj.property(name))); } QVERIFY(iteratedThruLength); QCOMPARE(stringProperties.size(), length); #if 0 // And going backwards iteratedThruLength = false; stringProperties.clear(); it.toBack(); while (it.hasPrevious()) { it.previous(); const QString name = it.name(); if (name == QString::fromLatin1("length")) { QVERIFY(it.value().isNumber()); QCOMPARE(it.value().toInt(), length); QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration."); iteratedThruLength = true; continue; } QVERIFY2(!stringProperties.contains(name), "property appeared more than once during iteration."); stringProperties.insert(name, it.value()); QVERIFY(it.value().strictlyEquals(obj.property(name))); } #endif }
/** * Handles the loading of trashed notes * * @brief OwnCloudService::handleTrashedLoading * @param data */ void OwnCloudService::handleTrashedLoading(QString data) { mainWindow->enableShowTrashButton(); mainWindow->showStatusBarMessage( tr("done with loading trashed notes"), 2000); // check if we get any data at all if (data == "") { showOwnCloudServerErrorMessage(); return; } // we have to add [], so the string can be parsed as JSON data = QString("[") + data + QString("]"); QJSEngine engine; QJSValue result = engine.evaluate(data); // get a possible error messages // we are casting to QVariant first because otherwise we might get a // "undefined" string if "message" is not set QString message = result.property(0).property("message").toVariant() .toString(); // check if we got an error message if (!message.isEmpty()) { showOwnCloudServerErrorMessage(message); return; } // get the directory to check if everything is all right QString directory = result.property(0).property("directory").toString(); // check if we got no useful data if (directory == "") { showOwnCloudServerErrorMessage(); return; } // get the versions QJSValue notes = result.property(0).property("notes"); // check if we got no usefull data if (notes.toString() == "") { QMessageBox::information(0, "no other version", "There are no trashed notes on the server."); return; } TrashDialog *dialog = new TrashDialog(notes, mainWindow); dialog->exec(); }
void tst_QJSValueIterator::value() { QFETCH(QString, code); QJSEngine engine; QJSValue object = engine.evaluate(code); Q_ASSERT(object.isObject()); QJSValueIterator it(object); it.next(); QBENCHMARK { for (int i = 0; i < 50000; ++i) it.value(); } }
/** * Handles the versions loading * * @brief OwnCloudService::handleVersionsLoading * @param data */ void OwnCloudService::handleVersionsLoading(QString data) { mainWindow->enableShowVersionsButton(); mainWindow->showStatusBarMessage( tr("done with loading note versions"), 2000); // check if we get any data at all if (data.isEmpty()) { showOwnCloudServerErrorMessage(); return; } // we have to add [], so the string can be parsed as JSON data = QString("[") + data + QString("]"); QJSEngine engine; QJSValue result = engine.evaluate(data); // get the information if versioning is available // we are casting to QVariant first because otherwise we might get a // "undefined" string if "message" is not set QString message = result.property(0).property("message").toVariant() .toString(); // check if we got an error message if (!message.isEmpty()) { showOwnCloudServerErrorMessage(message); return; } // get the filename to check if everything is all right QString fileName = result.property(0).property("file_name").toVariant() .toString(); // get the versions QJSValue versions = result.property(0).property("versions"); QJSValueIterator versionsIterator(versions); // check if we got no useful data, we also need to do this to prevent crashs if (fileName.isEmpty() || !versionsIterator.hasNext() || versions.toString().isEmpty()) { QMessageBox::information( 0, tr("no other version"), tr("There are no other versions on the server for this note.")); return; } VersionDialog *dialog = new VersionDialog(versions, mainWindow); dialog->exec(); }
bool TemplateEngine::evaluateBooleanJavaScriptExpression(QJSEngine &engine, const QString &expression, bool *result, QString *errorMessage) { if (errorMessage) errorMessage->clear(); if (result) *result = false; const QJSValue value = engine.evaluate(expression); if (value.isError()) { if (errorMessage) *errorMessage = QString::fromLatin1("Error in \"%1\": %2") .arg(expression, value.toString()); return false; } // Try to convert to bool, be that an int or whatever. if (value.isBool()) { if (result) *result = value.toBool(); return true; } if (value.isNumber()) { if (result) *result = !qFuzzyCompare(value.toNumber(), 0); return true; } if (value.isString()) { if (result) *result = !value.toString().isEmpty(); return true; } if (errorMessage) *errorMessage = QString::fromLatin1("Cannot convert result of \"%1\" (\"%2\"to bool.") .arg(expression, value.toString()); return false; }
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] QJSEngine myEngine; QJSValue three = myEngine.evaluate("1 + 2"); //! [0] //! [1] QJSValue fun = myEngine.evaluate("(function(a, b) { return a + b; })"); QJSValueList args; args << 1 << 2; QJSValue threeAgain = fun.call(QJSValue(), args); //! [1] //! [2] QString fileName = "helloworld.qs"; QFile scriptFile(fileName); if (!scriptFile.open(QIODevice::ReadOnly))
void OwnCloudService::checkAppInfo(QNetworkReply *reply) { QString data = QString(reply->readAll()); // qDebug() << data; // we have to add [], so the string can be parsed as JSON data = QString("[") + data + QString("]"); QJSEngine engine; QJSValue result = engine.evaluate(data); bool appIsValid = result.property(0).property("versioning").toBool(); QString appVersion = result.property(0).property("app_version") .toVariant().toString(); QString serverVersion = result.property(0).property("server_version") .toVariant().toString(); // reset to "unknown" in case we can't test if versions // and trash app are enabled settingsDialog->setOKLabelData(6, "unknown", SettingsDialog::Unknown); settingsDialog->setOKLabelData(7, "unknown", SettingsDialog::Unknown); if (serverVersion != "") { VersionNumber serverAppVersion = VersionNumber(appVersion); VersionNumber minAppVersion = VersionNumber(QOWNNOTESAPI_MIN_VERSION); if (minAppVersion > serverAppVersion) { settingsDialog->setOKLabelData(4, "version " + appVersion + " too low", SettingsDialog::Warning); } else { settingsDialog->setOKLabelData(4, "ok", SettingsDialog::OK); } // check if versions and trash app are enabled after QOwnNotesAPI v0.3.1 if (serverAppVersion >= VersionNumber("0.3.1")) { bool versionsAppEnabled = result.property(0).property( "versions_app").toBool(); bool trashAppEnabled = result.property(0).property( "trash_app").toBool(); if (versionsAppEnabled) { settingsDialog->setOKLabelData(6, "ok", SettingsDialog::OK); } else { settingsDialog->setOKLabelData(6, "not enabled", SettingsDialog::Failure); } if (trashAppEnabled) { settingsDialog->setOKLabelData(7, "ok", SettingsDialog::OK); } else { settingsDialog->setOKLabelData(7, "not enabled", SettingsDialog::Failure); } } // check if notes path was found after QOwnNotesAPI v0.4. if (serverAppVersion >= VersionNumber("0.4.1")) { bool notesPathExists = result.property(0).property( "notes_path_exists").toBool(); if (notesPathExists) { settingsDialog->setOKLabelData(8, "ok", SettingsDialog::OK); } else { settingsDialog->setOKLabelData(8, "not found", SettingsDialog::Failure); } } } else { settingsDialog->setOKLabelData(4, "not connected", SettingsDialog::Failure); } // call callback in settings dialog settingsDialog->connectTestCallback(appIsValid, appVersion, serverVersion, reply->errorString()); }
QStringList VideoAnalyzer::analyze(QString pageUrl, int videoClarity) { qDebug()<< pageUrl; //目前使用flvsp.com解析 QEventLoop loop; QByteArray url = pageUrl.replace("//","##").toLatin1(); QFile scriptFile(":/base64.js"); scriptFile.open(QIODevice::ReadOnly); QTextStream out(&scriptFile); QString contents = out.readAll(); scriptFile.close(); QJSEngine myEngine; QJSValue fun = myEngine.evaluate(contents); QJSValueList args; args << QJSValue(QString(url)) ; QJSValue base64_encode = myEngine.globalObject().property("base64_encode"); QJSValue encodeResult = base64_encode.call(args).toString(); //qDebug()<<encodeResult.toString(); //qDebug()<<base64_encode(&a,strlen(&a)); QNetworkRequest request; request.setUrl(QUrl("http://www.flvsp.com/parse/getData.php?url="+encodeResult.toString())); request.setRawHeader("Accept","text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01"); request.setRawHeader("Accept-Encoding","gzip, deflate, sdch"); request.setRawHeader("Referer","http://www.flvsp.com/?url=https://www.letv.com/ptv/vplay/22827477.html"); request.setRawHeader("X-Requested-With","XMLHttpRequest"); request.setRawHeader("User-Agent","Mozilla/5.0 (Linux; U; Android 4.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 "); QNetworkReply *reply = manager->get(request); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QString data = reply->readAll(); qDebug()<<"get flvsp data start"; QStringList videoClarityList = data.split("panel-heading"); if(videoClarityList.count()>2) { videoClarityList.removeFirst(); videoClarityList.removeFirst(); }else { return QStringList()<<"null"; } //搜寻符合清晰度的视频 int videoClarityIndex = 10-videoClarity;//flvsp的解析结果中排在前面的清晰度高 QString videos; for(int i=0;i<10;i++)//往清晰度低的方向查找合适的 { videos = videoClarityList.value(videoClarityIndex+i,""); if(videos.isEmpty()) { continue; }else { break; } } if(videos.isEmpty())//上述循环找不到,往清晰度高的方向找 { for(int i=0;i<10;i++) { videos = videoClarityList.value(videoClarityIndex-i,""); if(videos.isEmpty()) { continue; }else { break; } } } qDebug()<<"get flvsp data end"; //得到真实地址列表realUrlList QStringList realUrlList; QRegExp rx("class=\"file_url\" href=\".*\""); rx.setMinimal(true); int pos = 0; while ((pos = rx.indexIn(videos, pos)) != -1) { QString href = rx.cap(0); realUrlList.append(href.replace(QRegExp("class=\"file_url\" href=\"|\""),"")); pos += rx.matchedLength(); } qDebug()<<realUrlList; return realUrlList; }