//! [1] int Environment::setInterval(const QScriptValue &expression, int delay) { if (expression.isString() || expression.isFunction()) { int timerId = startTimer(delay); m_intervalHash.insert(timerId, expression); return timerId; } return -1; }
void JavascriptInstance::GetObjectInformation(const QScriptValue &object, QSet<qint64> &ids, uint &valueCount, uint &objectCount, uint &nullCount, uint &numberCount, uint &boolCount, uint &stringCount, uint &arrayCount, uint &funcCount, uint &qobjCount, uint &qobjMethodCount) { if (!ids.contains(object.objectId())) ids << object.objectId(); QScriptValueIterator iter(object); while(iter.hasNext()) { iter.next(); QScriptValue v = iter.value(); if (ids.contains(v.objectId())) continue; ids << v.objectId(); valueCount++; if (v.isNull()) nullCount++; if (v.isNumber()) numberCount++; else if (v.isBool()) boolCount++; else if (v.isString()) stringCount++; else if (v.isArray()) arrayCount++; else if (v.isFunction()) funcCount++; else if (v.isQObject()) qobjCount++; if (v.isObject()) objectCount++; if (v.isQMetaObject()) qobjMethodCount += v.toQMetaObject()->methodCount(); // Recurse if ((v.isObject() || v.isArray()) && !v.isFunction() && !v.isString() && !v.isNumber() && !v.isBool() && !v.isQObject() && !v.isQMetaObject()) GetObjectInformation(v, ids, valueCount, objectCount, nullCount, numberCount, boolCount, stringCount, arrayCount, funcCount, qobjCount, qobjMethodCount); } }
static JSAgentWatchData fromScriptValue(const QString &expression, const QScriptValue &value) { static const QString arrayStr = QCoreApplication::translate ("Debugger::JSAgentWatchData", "[Array of length %1]"); static const QString undefinedStr = QCoreApplication::translate ("Debugger::JSAgentWatchData", "<undefined>"); JSAgentWatchData data; data.exp = expression.toUtf8(); data.name = data.exp; data.hasChildren = false; data.value = value.toString().toUtf8(); data.objectId = value.objectId(); if (value.isArray()) { data.type = "Array"; data.value = arrayStr.arg(value.property(QLatin1String("length")).toString()).toUtf8(); data.hasChildren = true; } else if (value.isBool()) { data.type = "Bool"; // data.value = value.toBool() ? "true" : "false"; } else if (value.isDate()) { data.type = "Date"; data.value = value.toDateTime().toString().toUtf8(); } else if (value.isError()) { data.type = "Error"; } else if (value.isFunction()) { data.type = "Function"; } else if (value.isUndefined()) { data.type = undefinedStr.toUtf8(); } else if (value.isNumber()) { data.type = "Number"; } else if (value.isRegExp()) { data.type = "RegExp"; } else if (value.isString()) { data.type = "String"; } else if (value.isVariant()) { data.type = "Variant"; } else if (value.isQObject()) { const QObject *obj = value.toQObject(); data.type = "Object"; data.value += '['; data.value += obj->metaObject()->className(); data.value += ']'; data.hasChildren = true; } else if (value.isObject()) { data.type = "Object"; data.hasChildren = true; data.value = "[Object]"; } else if (value.isNull()) { data.type = "<null>"; } else { data.type = "<unknown>"; } return data; }
static QString currentImportScopeName(QScriptContext *context) { for (; context; context = context->parentContext()) { QScriptValue v = context->thisObject() .property(StringConstants::importScopeNamePropertyInternal()); if (v.isString()) return v.toString(); } return QString(); }
void tst_QScriptContext::toString() { QScriptEngine eng; eng.globalObject().setProperty("parentContextToString", eng.newFunction(parentContextToString)); QScriptValue ret = eng.evaluate("function foo(first, second, third) {\n" " return parentContextToString();\n" "}; foo(1, 2, 3)", "script.qs"); QVERIFY(ret.isString()); QCOMPARE(ret.toString(), QString::fromLatin1("foo(first = 1, second = 2, third = 3) at script.qs:2")); }
QColor convert_script_value_f<QColor>::operator()( QScriptEngine *, const QScriptValue & args ) const { int r = 0; int g = 0; int b = 0; qreal a = 255; QScriptValue obj; bool smellArray = ( args.isArray() || ! args.property("length").isUndefined() ); if( smellArray ) { obj = args.property(0); } else if( args.isObject() ) { obj = args; } if( smellArray && !obj.isObject() ) { #define ARG(X) args.property(X).toInt32() int argc = args.property("length").toInt32(); QScriptValue arg = args.property(0); if( (1 == argc) && arg.isString() ) { return QColor( arg.toString() ); } r = (argc > 0) ? ARG(0) : 0; g = (argc > 1) ? ARG(1) : 0; b = (argc > 2) ? ARG(2) : 0; a = (argc > 3) ? args.property(3).toNumber() : 255.0; #undef ARG } else { #define ARG(X) obj.property(X).toInt32() r = ARG("red"); g = ARG("green"); b = ARG("blue"); #undef ARG QScriptValue av( obj.property("alpha") ); if( ! av.isUndefined() ) { a = av.toNumber(); } } QColor c( r, g, b ); if( a <= 1.0 ) c.setAlphaF(a); else c.setAlpha( int(a) ); return c; }
void fromScriptValueAssetReference(const QScriptValue &obj, AssetReference &s) { if (obj.isString()) s.ref = obj.toString(); else { if (!obj.property("ref").isValid() || !obj.property("ref").isString()) LogError("Can't convert QScriptValue to AssetReference! QScriptValue is not a string and it doesn't contain a ref attribute!"); s.ref = obj.property("ref").toString(); s.type = obj.property("type").toString(); } }
void qColorFromScriptValue(const QScriptValue& object, QColor& color) { if (object.isNumber()) { color.setRgb(object.toUInt32()); } else if (object.isString()) { color.setNamedColor(object.toString()); } else { QScriptValue alphaValue = object.property("alpha"); color.setRgb(object.property("red").toInt32(), object.property("green").toInt32(), object.property("blue").toInt32(), alphaValue.isNumber() ? alphaValue.toInt32() : 255); } }
QScriptValue UniversalInputDialogScript::get(const QScriptValue& id){ if (id.isNumber()) { int i = id.toInt32(); if (i < 0 || i > properties.size()) return QScriptValue(); return engine->newVariant(properties[i].valueToQVariant()); } if (id.isString()) { QString sid = id.toString(); foreach (const ManagedProperty& mp, properties) if (mp.name == sid) return engine->newVariant(mp.valueToQVariant()); return QScriptValue(); }
QScriptValue UtilitiesExtension::js_canonicalArchitecture(QScriptContext *context, QScriptEngine *engine) { const QScriptValue value = context->argument(0); if (value.isUndefined() || value.isNull()) return value; if (context->argumentCount() == 1 && value.isString()) return engine->toScriptValue(canonicalArchitecture(value.toString())); return context->throwError(QScriptContext::SyntaxError, QStringLiteral("canonicalArchitecture expects one argument of type string")); }
void AnimVariantMap::animVariantMapFromScriptValue(const QScriptValue& source) { if (QThread::currentThread() != source.engine()->thread()) { qCWarning(animation) << "Cannot examine Javacript object from non-script thread" << QThread::currentThread(); Q_ASSERT(false); return; } // POTENTIAL OPTIMIZATION: cache the types we've seen. I.e, keep a dictionary mapping property names to an enumeration of types. // Whenever we identify a new outbound type in animVariantMapToScriptValue above, or a new inbound type in the code that follows here, // we would enter it into the dictionary. Then switch on that type here, with the code that follow being executed only if // the type is not known. One problem with that is that there is no checking that two different script use the same name differently. QScriptValueIterator property(source); // Note: QScriptValueIterator iterates only over source's own properties. It does not follow the prototype chain. while (property.hasNext()) { property.next(); QScriptValue value = property.value(); if (value.isBool()) { set(property.name(), value.toBool()); } else if (value.isString()) { set(property.name(), value.toString()); } else if (value.isNumber()) { int asInteger = value.toInt32(); float asFloat = value.toNumber(); if (asInteger == asFloat) { set(property.name(), asInteger); } else { set(property.name(), asFloat); } } else { // Try to get x,y,z and possibly w if (value.isObject()) { QScriptValue x = value.property("x"); if (x.isNumber()) { QScriptValue y = value.property("y"); if (y.isNumber()) { QScriptValue z = value.property("z"); if (z.isNumber()) { QScriptValue w = value.property("w"); if (w.isNumber()) { set(property.name(), glm::quat(w.toNumber(), x.toNumber(), y.toNumber(), z.toNumber())); } else { set(property.name(), glm::vec3(x.toNumber(), y.toNumber(), z.toNumber())); } continue; // we got either a vector or quaternion object, so don't fall through to warning } } } } qCWarning(animation) << "Ignoring unrecognized data" << value.toString() << "for animation property" << property.name(); Q_ASSERT(false); } } }
void ScriptEngine::hostInfo_Ready(const QHostInfo &myInfo) { QScriptValue myVal = myHostLookups.take(myInfo.lookupId()); if(myVal.isString()) { QString info = myInfo.hostName(); eval("var name = '"+info+"';"+myVal.toString()); } else { if(myVal.isFunction()) { QScriptValueList arguments; arguments << QString(myInfo.hostName()); myVal.call(QScriptValue(), arguments); } } }
void YT3ListParser::parseItem(const QScriptValue &item) { Video *video = new Video(); QScriptValue id = item.property("id"); if (id.isString()) video->setId(id.toString()); else { QString videoId = id.property("videoId").toString(); video->setId(videoId); } QScriptValue snippet = item.property("snippet"); bool isLiveBroadcastContent = snippet.property("liveBroadcastContent").toString() != QLatin1String("none"); if (isLiveBroadcastContent) { delete video; return; } QString publishedAt = snippet.property("publishedAt").toString(); QDateTime publishedDateTime = QDateTime::fromString(publishedAt, Qt::ISODate); video->setPublished(publishedDateTime); video->setChannelId(snippet.property("channelId").toString()); video->setTitle(snippet.property("title").toString()); video->setDescription(snippet.property("description").toString()); QScriptValue thumbnails = snippet.property("thumbnails"); video->setThumbnailUrl(thumbnails.property("medium").property("url").toString()); video->setMediumThumbnailUrl(thumbnails.property("high").property("url").toString()); video->setChannelTitle(snippet.property("channelTitle").toString()); // These are only for "videos" requests QScriptValue contentDetails = item.property("contentDetails"); if (contentDetails.isObject()) { QString isoPeriod = contentDetails.property("duration").toString(); int duration = DataUtils::parseIsoPeriod(isoPeriod); video->setDuration(duration); } QScriptValue statistics = item.property("statistics"); if (statistics.isObject()) { uint viewCount = statistics.property("viewCount").toUInt32(); video->setViewCount(viewCount); } videos.append(video); }
/* * loadScript 方法 * @param string js路径(支持本地路径以及http与https协议下远程js获取) * @param function 调用函数 * @return * 如果第二个参数不存在, load 失败,返回 false 。 * 如果第二个参数不存在, load 成功,则返回 true 。 * 如果第二参数存在,则立即调用内部函数,返回执行结果。 * load的内容将以回调函数参数传入: * @param bool err 表明是否正常读取内容 * @param function callback 回一个load函数引用 */ QScriptValue ScriptBinding::loadScript(QScriptContext *context, QScriptEngine *interpreter) { QScriptValue path = context->argument(0); QScriptValue scriptFunc = context->argument(1); if (context->argumentCount() == 0) return QScriptValue(false); if (!path.isString()) return QScriptValue(false); QString pathStr = path.toString().toLower().trimmed(); QString content = ""; bool err = false; // 如果是 HTTP 、 HTTPS 则尝试从远端获取源码 if (pathStr.indexOf("http://") == 0 || pathStr.indexOf("https://") == 0 ) { QNetworkReply* reply; QNetworkAccessManager* manager = new QNetworkAccessManager(); reply = manager->get(QNetworkRequest(QUrl(pathStr))); QEventLoop eventLoop; connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); eventLoop.exec(); QByteArray responseData; responseData = reply->readAll(); // 通过 Content-Type 来嗅探字节流编码 // 默认为 utf-8 编码 QString charset = QString(reply->rawHeader("Content-Type")).toLower(); QRegExp charsetRegExp("charset=([\\w-]+)\\b"); int pos = charset.indexOf(charsetRegExp); if (pos > 0) { if (charsetRegExp.cap().size() < 2) { charset = "utf-8"; } else { charset = charsetRegExp.cap(1); } } else { charset = "utf-8"; } QTextStream stream(responseData); stream.setCodec(getCodec(charset)); content = QString(stream.readAll()); } else {
TFrameId Level::getFid(const QScriptValue &arg, QString &err) { if (arg.isNumber() || arg.isString()) { QString s = arg.toString(); QRegExp re("(-?\\d+)(\\w?)"); if (re.exactMatch(s)) { int d = re.cap(1).toInt(); QString c = re.cap(2); TFrameId fid; if (c.length() == 1) #if QT_VERSION >= 0x050500 fid = TFrameId(d, c[0].unicode()); #else fid = TFrameId(d, c[0].toAscii()); #endif else
static QStringList toStringList(const QScriptValue &scriptValue) { if (scriptValue.isString()) { return QStringList(scriptValue.toString()); } else if (scriptValue.isArray()) { QStringList lst; int i = 0; forever { QScriptValue elem = scriptValue.property(i++); if (!elem.isValid()) break; lst.push_back(elem.toString()); } return lst; }
void Environment::timerEvent(QTimerEvent *event) { int id = event->timerId(); QScriptValue expression = m_intervalHash.value(id); if (!expression.isValid()) { expression = m_timeoutHash.value(id); if (expression.isValid()) killTimer(id); } if (expression.isString()) { evaluate(expression.toString()); } else if (expression.isFunction()) { expression.call(); } maybeEmitScriptError(); }
void JavaScriptCommand::fillFromScriptValue(const QScriptValue *scriptValue, const CodeLocation &codeLocation) { AbstractCommand::fillFromScriptValue(scriptValue, codeLocation); const QScriptValue importScope = scriptValue->property( StringConstants::importScopeNamePropertyInternal()); if (importScope.isString()) m_scopeName = importScope.toString(); const QScriptValue sourceCode = scriptValue->property(StringConstants::sourceCodeProperty()); m_sourceCode = invokedSourceCode(sourceCode); m_predefinedProperties << StringConstants::classNameProperty() << StringConstants::sourceCodeProperty() << StringConstants::importScopeNamePropertyInternal(); applyCommandProperties(scriptValue); }
//! [2] QScriptValue ByteArrayClass::construct(QScriptContext *ctx, QScriptEngine *) { ByteArrayClass *cls = qscriptvalue_cast<ByteArrayClass*>(ctx->callee().data()); if (!cls) return QScriptValue(); QScriptValue arg = ctx->argument(0); if (arg.instanceOf(ctx->callee())) return cls->newInstance(qscriptvalue_cast<QByteArray>(arg)); if (arg.isString()) return cls->newInstance(arg.toString()); int size = arg.toInt32(); return cls->newInstance(size); }
void TarryTown::timerEvent(QTimerEvent *event) { int id = event->timerId(); QScriptValue expression = p_intervalHash.value(id); if (!expression.isValid()) { expression = p_timeoutHash.value(id); if (expression.isValid()) { killTimer(id); } } if (expression.isString()) { evaluate(expression.toString()); } else if (expression.isFunction()) { //qDebug() << "Calling expression"; expression.call(); } emitScriptError(); }
EnumDataInformation* toEnum(const QScriptValue& value, bool flags, const ParserInfo& info) { EnumParsedData epd(info); QScriptValue enumType = value.property(PROPERTY_TYPE); if (enumType.isString()) epd.type = enumType.toString(); else if (enumType.isObject()) epd.type = enumType.property(PROPERTY_TYPE).toString(); //else it stays empty epd.enumName = value.property(PROPERTY_ENUM_NAME).toString(); epd.enumValuesObject = value.property(PROPERTY_ENUM_VALUES); if (flags) return DataInformationFactory::newFlags(epd); else return DataInformationFactory::newEnum(epd); }
void ArrayBufferClass::fromScriptValue(const QScriptValue& object, QByteArray& byteArray) { if (object.isString()) { // UTF-8 encoded String byteArray = object.toString().toUtf8(); } else if (object.isArray()) { // Array of uint8s eg: [ 128, 3, 25, 234 ] auto Uint8Array = object.engine()->globalObject().property("Uint8Array"); auto typedArray = Uint8Array.construct(QScriptValueList{object}); if (QByteArray* buffer = qscriptvalue_cast<QByteArray*>(typedArray.property("buffer"))) { byteArray = *buffer; } } else if (object.isObject()) { // ArrayBuffer instance (or any JS class that supports coercion into QByteArray*) if (QByteArray* buffer = qscriptvalue_cast<QByteArray*>(object.data())) { byteArray = *buffer; } } }
void ScriptHandler::validateData(DataInformation* data) { Q_CHECK_PTR(data); if (data->hasBeenValidated()) return; //first validate the children for (uint i = 0; i < data->childCount(); ++i) validateData(data->childAt(i)); //check if has a validation function: QScriptValue validationFunc = data->validationFunc(); if (validationFunc.isValid()) { QScriptValue result = callFunction(validationFunc, data, ScriptHandlerInfo::Validating); if (result.isError()) { mTopLevel->logger()->error(data) << "Error occurred while validating element: " << result.toString(); data->setValidationError(QStringLiteral("Error occurred in validation: ") + result.toString()); } else if (mEngine->hasUncaughtException()) { mTopLevel->logger()->error(data) << "Error occurred while validating element:" << result.toString() << "\nBacktrace:" << mEngine->uncaughtExceptionBacktrace(); data->setValidationError(QStringLiteral("Error occurred in validation: ") + result.toString()); mEngine->clearExceptions(); } if (result.isBool() || result.isBoolean()) { data->mValidationSuccessful = result.toBool(); } if (result.isString()) { //error string QString str = result.toString(); if (!str.isEmpty()) data->setValidationError(str); } data->mHasBeenValidated = true; } }
int ScriptEngine::setTimer(const QScriptValue &code, int delay, bool repeats) { if (delay <= 0) { return -1; } if ((!code.isFunction()) && (!code.isString())) { warn("setTimer(code, delay, repeats)", "code must be string or function."); return -1; } QTimer *t = new QTimer(); timerEvents[t] = code; t->setSingleShot(!repeats); t->start(delay); connect(t, SIGNAL(timeout()), SLOT(timer()), Qt::DirectConnection); return t->timerId(); }
void xColorFromScriptValue(const QScriptValue &object, xColor& color) { if (!object.isValid()) { return; } if (object.isNumber()) { color.red = color.green = color.blue = (uint8_t)object.toUInt32(); } else if (object.isString()) { QColor qcolor(object.toString()); if (qcolor.isValid()) { color.red = (uint8_t)qcolor.red(); color.blue = (uint8_t)qcolor.blue(); color.green = (uint8_t)qcolor.green(); } } else { color.red = object.property("red").toVariant().toInt(); color.green = object.property("green").toVariant().toInt(); color.blue = object.property("blue").toVariant().toInt(); } }
QImage ActionInstance::evaluateImage(bool &ok, const QString ¶meterName, const QString &subParameterName) { if(!ok) return QImage(); const SubParameter &subParameter = retreiveSubParameter(parameterName, subParameterName); QString filename; if(subParameter.isCode()) { QScriptValue evaluationResult = evaluateCode(ok, subParameter); if(auto codeImage = qobject_cast<Code::Image*>(evaluationResult.toQObject())) return codeImage->image(); if(!evaluationResult.isString()) { ok = false; emit executionException(ActionException::InvalidParameterException, tr("Invalid image.")); return QImage(); } filename = evaluationResult.toString(); } else filename = evaluateText(ok, subParameter); if(!ok || filename.isEmpty()) return QImage(); QImage image(filename); if(!image.isNull()) return image; ok = false; emit executionException(ActionException::InvalidParameterException, tr("Unable to load image: %1").arg(filename)); return QImage(); }
void SaveFlagsfromScriptValue(const QScriptValue &obj, enum SaveFlags &en) { if (obj.isNumber()) en = (enum SaveFlags)obj.toInt32(); else if (obj.isString()) { if (obj.toString() == "CHECK") en = CHECK; else if (obj.toString() == "CHANGEONE") en = CHANGEONE; else if (obj.toString() == "CHANGEALL") en = CHANGEALL; else qWarning("string %s could not be converted to SaveFlags", qPrintable(obj.toString())); } else qWarning("object %s could not be converted to SaveFlags", qPrintable(obj.toString())); }
QScriptValue notificationsSend(QScriptContext *ctxt, QScriptEngine *e) { if (ctxt->argumentCount() < 1) return e->undefinedValue(); QScriptValue arg = ctxt->argument(0); if (arg.isNumber() && ctxt->argumentCount() > 1) { NotificationRequest request; request.setType(static_cast<Notification::Type>(arg.toInt32())); request.setObject(ctxt->argument(1).toQObject()); if (ctxt->argumentCount() > 2) request.setText(ctxt->argument(2).toString()); return e->newQObject(request.send()); } else if (arg.isString()) { return e->newQObject(Notification::send(arg.toString())); } else if (arg.isObject()) { Message msg = qscriptvalue_cast<Message>(arg); return e->newQObject(Notification::send(msg)); } return e->undefinedValue(); }
JsonData JsonHandler::property(const QString &data, const QString &prop) { QScriptValue sc; QScriptEngine engine; JsonData errorData; JsonData propData;; sc = engine.evaluate("(" + QString(data) + ")"); if (sc.property("error").isObject()) { JsonData result; result.setType(JsonData::Error); QScriptValue errorObj = sc.property("error").toObject(); qDebug() << Q_FUNC_INFO << "Error in Result" << errorObj.property("type").toString() << errorObj.property("message").toString(); errorData = result; } QScriptValue propValue = sc.property(prop); if (!propValue.isValid() || propValue.isUndefined()) { return errorData; }else { qDebug() << Q_FUNC_INFO << "Start parsing property :" << propValue.isObject(); if (propValue.isObject()) { QVariantMap list = qscriptvalue_cast<QVariantMap>(propValue); propData.setType(JsonData::Object); propData.addData(prop, QVariant(list)); return propData; } else if (propValue.isString()) { propData.setType(JsonData::String); propData.addData(prop, QVariant(propValue.toString())); return propData; } else if (propValue.isArray()) { propData.setType(JsonData::Array); propData.addData(prop, QVariant(arrayToMap(propValue))); return propData; } } }
void Level::setPath(const QScriptValue &pathArg) { TFilePath fp; FilePath *filePath = qscriptvalue_cast<FilePath *>(pathArg); if (filePath) fp = filePath->getToonzFilePath(); else if (pathArg.isString()) fp = TFilePath(pathArg.toString().toStdString()); else context()->throwError( tr("Bad argument (%1). It should be FilePath or string") .arg(pathArg.toString())); if (m_sl) { m_sl->setPath(fp); try { m_sl->load(); } catch (...) { context()->throwError( tr("Exception loading level (%1)") .arg(QString::fromStdWString(fp.getWideString()))); } } }