void tst_QScriptContext::inheritActivationAndThisObject()
{
    QScriptEngine eng;
    eng.globalObject().setProperty("myEval", eng.newFunction(myEval));
    {
        QScriptValue ret = eng.evaluate("var a = 123; myEval('a')");
        QVERIFY(ret.isNumber());
        QCOMPARE(ret.toInt32(), 123);
    }
    {
        QScriptValue ret = eng.evaluate("(function() { return myEval('this'); }).call(Number)");
        QVERIFY(ret.isFunction());
        QVERIFY(ret.equals(eng.globalObject().property("Number")));
    }
    {
        QScriptValue ret = eng.evaluate("(function(a) { return myEval('a'); })(123)");
        QVERIFY(ret.isNumber());
        QCOMPARE(ret.toInt32(), 123);
    }

    // QT-2219
    {
        eng.globalObject().setProperty("a", 123);
        QScriptValue ret = eng.evaluate("(function() { myEval('var a = 456'); return a; })()");
        QVERIFY(ret.isNumber());
        QCOMPARE(ret.toInt32(), 456);
        QEXPECT_FAIL("", "QT-2219: Wrong activation object is returned from native function's parent context", Continue);
        QVERIFY(eng.globalObject().property("a").strictlyEquals(123));
    }
}
Example #2
0
static bool _q_equal(const QScriptValue &v1, const QScriptValue &v2)
{
    if (v1.strictlyEquals(v2))
        return true;
    if (v1.isNumber() && v2.isNumber() && qIsNaN(v1.toNumber()) && qIsNaN(v2.toNumber()))
        return true;
    return false;
}
Example #3
0
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);
    }
}
Example #4
0
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);
        }
    }
}
Example #5
0
//---------------------------------------------------------------------------------------
QScriptValue JSQChar::constructor( QScriptContext* ctx, QScriptEngine* eng ) {
    if( !ctx->isCalledAsConstructor() ) {
        return ctx->throwError( "MarcSubField must be called as a constructor with the new operand." );
    };

    switch( ctx->argumentCount() ) {
    case 0:
        return eng->newQObject( ctx->thisObject(), new JSQChar(), QScriptEngine::ScriptOwnership );

    case 1:
        {
            QScriptValue arg = ctx->argument( 0 );

            if( arg.isNumber() ) {
                return eng->newQObject( ctx->thisObject(), new JSQChar( QSharedPointer<QChar>( new QChar( arg.toInt32() ) ) ), QScriptEngine::ScriptOwnership );
            }
            else {
                return ctx->throwError( "Wrong data type of argument." );
            }
        }

    default:
        return ctx->throwError( "Wrong number of arguments." );
    }

}
Example #6
0
QScriptValue TextImportDialog_script_changeFontSize(QScriptContext *context, QScriptEngine */*engine*/)
{
	QObject *obj = context->argument(0).toQObject();
	if(!obj)
	{
		qDebug() << "TextImportDialog_script_changeFontSize(textbox,fontSize): Must give Slide (QObject) as first argument"; 
		return QScriptValue(QScriptValue::NullValue);
	}
	TextBoxItem *text = dynamic_cast<TextBoxItem*>(obj);
	if(!text)
	{
		qDebug() << "TextImportDialog_script_changeFontSize(textbox,fontSize): First argument is not a Slide"; 
		return QScriptValue(QScriptValue::NullValue);
	}
	
	
	QScriptValue fontSizeVal = context->argument(1);
	if(!fontSizeVal.isNumber())
	{
		qDebug() << "TextImportDialog_script_changeFontSize(textbox,fontSize): Second argument is not a number"; 
		return QScriptValue(QScriptValue::NullValue);
	}
	double size = (double)fontSizeVal.toNumber();
	text->changeFontSize(size);
	return QScriptValue(text->findFontSize());
}
Example #7
0
QScriptDebuggerValue::QScriptDebuggerValue(const QScriptValue &value)
    : d_ptr(0)
{
    if (value.isValid()) {
        d_ptr = new QScriptDebuggerValuePrivate;
        if (value.isUndefined())
            d_ptr->type = UndefinedValue;
        else if (value.isNull())
            d_ptr->type = NullValue;
        else if (value.isNumber()) {
            d_ptr->type = NumberValue;
            d_ptr->numberValue = value.toNumber();
        } else if (value.isBoolean()) {
            d_ptr->type = BooleanValue;
            d_ptr->booleanValue = value.toBoolean();
        } else if (value.isString()) {
            d_ptr->type = StringValue;
            d_ptr->stringValue = new QString(value.toString());
        } else {
            Q_ASSERT(value.isObject());
            d_ptr->type = ObjectValue;
            d_ptr->objectId = value.objectId();
        }
        d_ptr->ref.ref();
    }
}
void tst_QScriptContext::qobjectAsActivationObject()
{
    QScriptEngine eng;
    QObject object;
    QScriptValue scriptObject = eng.newQObject(&object);
    QScriptContext *ctx = eng.pushContext();
    ctx->setActivationObject(scriptObject);
    QVERIFY(ctx->activationObject().equals(scriptObject));

    QVERIFY(!scriptObject.property("foo").isValid());
    eng.evaluate("function foo() { return 123; }");
    {
        QScriptValue val = scriptObject.property("foo");
        QVERIFY(val.isValid());
        QVERIFY(val.isFunction());
    }
    QVERIFY(!eng.globalObject().property("foo").isValid());

    QVERIFY(!scriptObject.property("bar").isValid());
    eng.evaluate("var bar = 123");
    {
        QScriptValue val = scriptObject.property("bar");
        QVERIFY(val.isValid());
        QVERIFY(val.isNumber());
        QCOMPARE(val.toInt32(), 123);
    }
    QVERIFY(!eng.globalObject().property("bar").isValid());

    {
        QScriptValue val = eng.evaluate("delete foo");
        QVERIFY(val.isBool());
        QVERIFY(val.toBool());
        QVERIFY(!scriptObject.property("foo").isValid());
    }
}
Example #9
0
void fromScriptValueEntityReference(const QScriptValue &obj, EntityReference &s)
{
    if (obj.isString())
        s.ref = obj.toString();
    else
    {
        if (!obj.property("ref").isValid())
            LogError("Can't convert QScriptValue to EntityReference! QScriptValue does not contain ref attribute!");
        else
        {
            QScriptValue ref = obj.property("ref");
            if (ref.isNull())
                s.ref = ""; // Empty the reference
            else if (ref.isString())
                s.ref = ref.toString();
            else if (ref.isQObject())
            {
                // If the object is an Entity, call EntityReference::Set() with it
                Entity* entity = dynamic_cast<Entity*>(ref.toQObject());
                s.Set(entity);
            }
            else if (ref.isNumber() || ref.isVariant())
                s.ref = QString::number(ref.toInt32());
            else
                LogError("Can't convert QScriptValue to EntityReference! Ref attribute is not null, string, a number, or an entity");
        }
    }
}
QScriptValue UniversalInputDialogScript::add(const QScriptValue& def, const QScriptValue& description, const QScriptValue& id){
	QWidget* w = 0;
	if (def.isArray()) {
		QStringList options;
		QScriptValueIterator it(def);
		while (it.hasNext()) {
			it.next();
			if (it.flags() & QScriptValue::SkipInEnumeration)
				continue;
			if (it.value().isString() || it.value().isNumber()) options << it.value().toString();
			else engine->currentContext()->throwError("Invalid default value in array (must be string or number): "+it.value().toString());
		}
		w = addComboBox(ManagedProperty::fromValue(options), description.toString());
	} else if (def.isBool()) {
		w = addCheckBox(ManagedProperty::fromValue(def.toBool()), description.toString());
	} else if (def.isNumber()) {
		w = addDoubleSpinBox(ManagedProperty::fromValue(def.toNumber()), description.toString());
	} else if (def.isString()) {
		w = addLineEdit(ManagedProperty::fromValue(def.toString()), description.toString());
	} else {	
		
		engine->currentContext()->throwError(tr("Invalid default value: %1").arg(def.toString()));
		return QScriptValue();
	}
	if (id.isValid()) properties.last().name = id.toString();
	return engine->newQObject(w);
}
Example #11
0
QAction *KWin::AbstractScript::scriptValueToAction(QScriptValue &value, QMenu *parent)
{
    QScriptValue titleValue = value.property(QStringLiteral("text"));
    QScriptValue checkableValue = value.property(QStringLiteral("checkable"));
    QScriptValue checkedValue = value.property(QStringLiteral("checked"));
    QScriptValue itemsValue = value.property(QStringLiteral("items"));
    QScriptValue triggeredValue = value.property(QStringLiteral("triggered"));

    if (!titleValue.isValid()) {
        // title not specified - does not make any sense to include
        return nullptr;
    }
    const QString title = titleValue.toString();
    const bool checkable = checkableValue.isValid() && checkableValue.toBool();
    const bool checked = checkable && checkedValue.isValid() && checkedValue.toBool();
    // either a menu or a menu item
    if (itemsValue.isValid()) {
        if (!itemsValue.isArray()) {
            // not an array, so cannot be a menu
            return nullptr;
        }
        QScriptValue lengthValue = itemsValue.property(QStringLiteral("length"));
        if (!lengthValue.isValid() || !lengthValue.isNumber() || lengthValue.toInteger() == 0) {
            // length property missing
            return nullptr;
        }
        return createMenu(title, itemsValue, parent);
    } else if (triggeredValue.isValid()) {
        // normal item
        return createAction(title, checkable, checked, triggeredValue, parent);
    }
    return nullptr;
}
Example #12
0
QScriptValue ModuleProperties::moduleProperties(QScriptContext *context, QScriptEngine *engine,
                                                bool oneValue)
{
    if (Q_UNLIKELY(context->argumentCount() < 2)) {
        return context->throwError(QScriptContext::SyntaxError,
                                   Tr::tr("Function moduleProperties() expects 2 arguments"));
    }

    const QScriptValue objectWithProperties = context->thisObject();
    const QScriptValue typeScriptValue = objectWithProperties.property(typeKey());
    if (Q_UNLIKELY(!typeScriptValue.isString())) {
        return context->throwError(QScriptContext::TypeError,
                QLatin1String("Internal error: __type not set up"));
    }
    const QScriptValue ptrScriptValue = objectWithProperties.property(ptrKey());
    if (Q_UNLIKELY(!ptrScriptValue.isNumber())) {
        return context->throwError(QScriptContext::TypeError,
                QLatin1String("Internal error: __internalPtr not set up"));
    }

    const void *ptr = reinterpret_cast<const void *>(qscriptvalue_cast<quintptr>(ptrScriptValue));
    PropertyMapConstPtr properties;
    const Artifact *artifact = 0;
    if (typeScriptValue.toString() == productType()) {
        properties = static_cast<const ResolvedProduct *>(ptr)->moduleProperties;
    } else if (typeScriptValue.toString() == artifactType()) {
        artifact = static_cast<const Artifact *>(ptr);
        properties = artifact->properties;
    } else {
        return context->throwError(QScriptContext::TypeError,
                                   QLatin1String("Internal error: invalid type"));
    }

    ScriptEngine * const qbsEngine = static_cast<ScriptEngine *>(engine);
    const QString moduleName = context->argument(0).toString();
    const QString propertyName = context->argument(1).toString();

    QVariant value;
    if (qbsEngine->isPropertyCacheEnabled())
        value = qbsEngine->retrieveFromPropertyCache(moduleName, propertyName, oneValue,
                                                     properties);
    if (!value.isValid()) {
        if (oneValue)
            value = PropertyFinder().propertyValue(properties->value(), moduleName, propertyName);
        else
            value = PropertyFinder().propertyValues(properties->value(), moduleName, propertyName);
        const Property p(moduleName, propertyName, value);
        if (artifact)
            qbsEngine->addPropertyRequestedFromArtifact(artifact, p);
        else
            qbsEngine->addPropertyRequestedInScript(p);

        // Cache the variant value. We must not cache the QScriptValue here, because it's a
        // reference and the user might change the actual object.
        if (qbsEngine->isPropertyCacheEnabled())
            qbsEngine->addToPropertyCache(moduleName, propertyName, oneValue, properties, value);
    }
    return engine->toScriptValue(value);
}
Example #13
0
void PointerEvent::fromScriptValue(const QScriptValue& object, PointerEvent& event) {
    if (object.isObject()) {
        QScriptValue type = object.property("type");
        QString typeStr = type.isString() ? type.toString() : "Move";
        if (typeStr == "Press") {
            event._type = Press;
        } else if (typeStr == "DoublePress") {
            event._type = DoublePress;
        } else if (typeStr == "Release") {
            event._type = Release;
        } else {
            event._type = Move;
        }

        QScriptValue id = object.property("id");
        event._id = id.isNumber() ? (uint32_t)id.toNumber() : 0;

        glm::vec2 pos2D;
        vec2FromScriptValue(object.property("pos2D"), event._pos2D);

        glm::vec3 pos3D;
        vec3FromScriptValue(object.property("pos3D"), event._pos3D);

        glm::vec3 normal;
        vec3FromScriptValue(object.property("normal"), event._normal);

        glm::vec3 direction;
        vec3FromScriptValue(object.property("direction"), event._direction);

        QScriptValue button = object.property("button");
        QString buttonStr = type.isString() ? button.toString() : "NoButtons";

        if (buttonStr == "Primary") {
            event._button = PrimaryButton;
        } else if (buttonStr == "Secondary") {
            event._button = SecondaryButton;
        } else if (buttonStr == "Tertiary") {
            event._button = TertiaryButton;
        } else {
            event._button = NoButtons;
        }

        bool primary = object.property("isPrimaryHeld").toBool();
        bool secondary = object.property("isSecondaryHeld").toBool();
        bool tertiary = object.property("isTertiaryHeld").toBool();
        event._buttons = 0;
        if (primary) {
            event._buttons |= PrimaryButton;
        }
        if (secondary) {
            event._buttons |= SecondaryButton;
        }
        if (tertiary) {
            event._buttons |= TertiaryButton;
        }

        event._keyboardModifiers = (Qt::KeyboardModifiers)(object.property("keyboardModifiers").toUInt32());
    }
}
	QScriptValue QtScriptObject::validateNumber(const QString& parameterName, QScriptValue value)
	{
		if (!value.isNumber())
		{
			return this->throwError(QString(QT_TR_NOOP("Parameter %1 must be a number")).arg(parameterName));
		}

		return QScriptValue(QScriptValue::UndefinedValue);
	}
Example #15
0
double EnvWrap::evalDouble( const QString& nm )
{
	QScriptValue result = evalExp(nm);
	if (result.isNumber())
		return result.toNumber();
	else
		throw ExpressionHasNotThisTypeException("Double",nm);
	return double();
}
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);
    }
}
Example #17
0
const std::string QCATs::sprintf(const CSmallString& fname, QScriptContext* p_context,
                                QScriptEngine* p_engine)
{
    if( p_context->argumentCount() < 1 ) {
        CSmallString error;
        error << fname << "(format[,value1,value2,..]) - illegal number of arguments, at least one is expected";
        p_context->throwError(QString(error));
        return("");
    }

    QString format;
    format = p_context->argument(0).toString();

    // prepare format
    boost::format my_format;
    try {
        my_format.parse(format.toStdString());
    } catch(...) {
        CSmallString error;
        error << fname << "(format[,value1,value2,..]) - unable to parse format";
        p_context->throwError(QString(error));
        return("");
    }

    if( my_format.expected_args() != (p_context->argumentCount() - 1) ){
        CSmallString error;
        error << fname << "(format[,value1,value2,..]) - format requires different number of values (";
        error << my_format.expected_args() << ") than it is provided (" << (p_context->argumentCount() - 1) << ")";
        p_context->throwError(QString(error));
        return("");
    }

    // parse individual arguments
    for(int i=0; i < my_format.expected_args(); i++ ){
        QScriptValue val = p_context->argument(i+1);

        try {
            if( val.isNumber() ){
                double sval = val.toNumber();
                my_format % sval;
            } else {
                QString sval = val.toString();
                my_format % sval.toStdString();
            }
        } catch(...){
            CSmallString error;
            error << fname << "(format[,value1,value2,..]) - unable to process argument (";
            error << i + 1 << ")";
            p_context->throwError(QString(error));
            return("");
        }
    }

    // return string
    return( my_format.str() );
}
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;
}
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();
	}
void tst_QScriptContext::lineNumber()
{
    QScriptEngine eng;

    QScriptValue result = eng.evaluate("try { eval(\"foo = 123;\\n this[is{a{syntax|error@#$%@#% \"); } catch (e) { e.lineNumber; }", "foo.qs", 123);
    QVERIFY(!eng.hasUncaughtException());
    QVERIFY(result.isNumber());
    QCOMPARE(result.toInt32(), 2);

    result = eng.evaluate("foo = 123;\n bar = 42\n0 = 0");
    QVERIFY(eng.hasUncaughtException());
    QCOMPARE(eng.uncaughtExceptionLineNumber(), 3);
    QCOMPARE(result.property("lineNumber").toInt32(), 3);
}
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
Example #22
0
QScriptValue TypedArray::newInstance(QScriptValue array) {
    const QString ARRAY_LENGTH_HANDLE = "length";
    if (array.property(ARRAY_LENGTH_HANDLE).isValid()) {
        quint32 length = array.property(ARRAY_LENGTH_HANDLE).toInt32();
        QScriptValue newArray = newInstance(length);
        for (quint32 i = 0; i < length; ++i) {
            QScriptValue value = array.property(QString::number(i));
            setProperty(newArray, engine()->toStringHandle(QString::number(i)),
                        i * _bytesPerElement, (value.isNumber()) ? value : QScriptValue(0));
        }
        return newArray;
    }
    engine()->evaluate("throw \"ArgumentError: not an array\"");
    return QScriptValue();
}
void tst_QScriptContext::evaluateInFunction()
{
    QScriptEngine eng;

    QScriptValue fun = eng.newFunction(evaluate);
    eng.globalObject().setProperty("evaluate", fun);

    QScriptValue result = eng.evaluate("evaluate()");
    QCOMPARE(result.isError(), false);
    QCOMPARE(result.isNumber(), true);
    QCOMPARE(result.toNumber(), 123.0);
    QCOMPARE(eng.hasUncaughtException(), false);

    QCOMPARE(eng.evaluate("a").toNumber(), 123.0);
}
Example #24
0
QScriptValue ScriptRunner::setInterval(QScriptContext *context, QScriptEngine *engine)
{
    ScriptRunner * me = (ScriptRunner *) engine->parent();
    QScriptValue error;
    if (!me->argCount(context, error, 2))
        return error;
    QScriptValue func = context->argument(0);
    if (!me->maybeThrowArgumentError(context, error, func.isFunction()))
        return error;
    QScriptValue ms = context->argument(1);
    if (!me->maybeThrowArgumentError(context, error, ms.isNumber()))
        return error;

    return me->setTimeout(func, ms.toInt32(), context->parentContext()->thisObject(), true);
}
Example #25
0
void tst_QScriptValueGenerated::assignAndCopyConstruct_test(const char *, const QScriptValue &value)
{
    QScriptValue copy(value);
    QCOMPARE(copy.strictlyEquals(value), !value.isNumber() || !qIsNaN(value.toNumber()));
    QCOMPARE(copy.engine(), value.engine());

    QScriptValue assigned = copy;
    QCOMPARE(assigned.strictlyEquals(value), !copy.isNumber() || !qIsNaN(copy.toNumber()));
    QCOMPARE(assigned.engine(), assigned.engine());

    QScriptValue other(!value.toBool());
    assigned = other;
    QVERIFY(!assigned.strictlyEquals(copy));
    QVERIFY(assigned.strictlyEquals(other));
    QCOMPARE(assigned.engine(), other.engine());
}
Example #26
0
void Planar3DOverlay::setProperties(const QScriptValue& properties) {
    Base3DOverlay::setProperties(properties);

    QScriptValue dimensions = properties.property("dimensions");

    // if "dimensions" property was not there, check to see if they included aliases: scale
    if (!dimensions.isValid()) {
        dimensions = properties.property("scale");
        if (!dimensions.isValid()) {
            dimensions = properties.property("size");
        }
    }

    if (dimensions.isValid()) {
        bool validDimensions = false;
        glm::vec2 newDimensions;

        QScriptValue x = dimensions.property("x");
        QScriptValue y = dimensions.property("y");

        if (x.isValid() && y.isValid()) {
            newDimensions.x = x.toVariant().toFloat();
            newDimensions.y = y.toVariant().toFloat();
            validDimensions = true;
        } else {
            QScriptValue width = dimensions.property("width");
            QScriptValue height = dimensions.property("height");
            if (width.isValid() && height.isValid()) {
                newDimensions.x = width.toVariant().toFloat();
                newDimensions.y = height.toVariant().toFloat();
                validDimensions = true;
            }
        }

        // size, scale, dimensions is special, it might just be a single scalar, check that here
        if (!validDimensions && dimensions.isNumber()) {
            float size = dimensions.toVariant().toFloat();
            newDimensions.x = size;
            newDimensions.y = size;
            validDimensions = true;
        }

        if (validDimensions) {
            setDimensions(newDimensions);
        }
    }
}
Example #27
0
QScriptValue ScriptRunner::clearTimeout(QScriptContext *context, QScriptEngine *engine)
{
    ScriptRunner * me = (ScriptRunner *) engine->parent();
    QScriptValue error;
    if (!me->argCount(context, error, 1))
        return error;
    QScriptValue id = context->argument(0);
    if (!me->maybeThrowArgumentError(context, error, id.isNumber()))
        return error;

    int int_id = id.toInt32();
    QTimer * ptr = me->m_timer_ptrs.value(int_id, NULL);
    me->m_timer_ptrs.remove(int_id);
    me->m_script_timers.remove(ptr);
    delete ptr;
    return QScriptValue();
}
Example #28
0
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();
    }
}
Example #29
0
void Calculate::run() {
    mutex.lock();
    const QString q = query;
    mutex.unlock();

    QScriptEngine engine;
    QScriptValue result;
    QString op;

    sleep(1000);
    result = engine.evaluate(q);

    if (result.isNumber())
        op = query + " = " + result.toString();
    else
        op = "Error!";

    emit haveAnswer(op);
}
Example #30
0
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()));
}