Example #1
0
void ExposedModel::updateElement(const QString &key, QScriptValue value)
{
    tinia::model::StateSchemaElement schemaElement = m_model->getStateSchemaElement(key.toStdString());
    std::string type = schemaElement.getXSDType();

    if(type.find("xsd:") != std::string::npos) {
        type = type.substr(4);
    }


    if (type == std::string("double")) {
        m_model->updateElement(key.toStdString(), double(value.toNumber()));
    }
    else if(type==std::string("integer"))  {
        m_model->updateElement(key.toStdString(), int(value.toNumber()));
    }
    else if(type==std::string("bool")) {
        m_model->updateElement(key.toStdString(), value.toBool());
    }
    else if(type==std::string("string")) {
        m_model->updateElement(key.toStdString(), value.toString().toStdString());
    }
    else if(type==std::string("complexType")) {
        m_model->updateElement(key.toStdString(), static_cast<Viewer*>(value.toQObject())->viewer());
    }

}
	QScriptValue SegmentCollectionPrototype::add(QScriptValue startTime, QScriptValue duration, QScriptValue videoIndex)
	{
		if (!this->_editor->getVideoCount())
        {
            return this->throwError(QString(QT_TR_NOOP("A video must be open to perform this operation.")));
        }

        QScriptValue result;

        while (true)
        {
            result = this->validateNumber("videoIndex", videoIndex, 0, this->_editor->getVideoCount());

            if (!result.isUndefined())
            {
                break;
            }

            this->_editor->addSegment(videoIndex.toNumber(), startTime.toNumber(), duration.toNumber());

            result = this->_editor->getNbSegment() - 1;

            break;
        }

        return result;
	}
Example #3
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 #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 PHIBaseItem::pos( const QScriptValue &x, const QScriptValue &y )
{
    if ( !x.isValid() ) {
        QPointF p=adjustedPos();
        QScriptValue v=scriptEngine()->newObject();
        v.setProperty( L1( "left" ), qRound( realX()+p.x() ) );
        v.setProperty( L1( "top" ), qRound( realY()+p.y() ) );
        v.setProperty( L1( "x" ), qRound( realX() ) );
        v.setProperty( L1( "y" ), qRound( realY() ) );
        return v;
    }
    setPos( x.toNumber(), y.toNumber() );
    return self();
}
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 #7
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 #8
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::thisObject()
{
    QScriptEngine eng;

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

    {
        QScriptValue result = eng.evaluate("get_thisObject()");
        QCOMPARE(result.isObject(), true);
        QCOMPARE(result.toString(), QString("[object global]"));
    }

    {
        QScriptValue result = eng.evaluate("get_thisObject.apply(new Number(123))");
        QCOMPARE(result.isObject(), true);
        QCOMPARE(result.toNumber(), 123.0);
    }

    {
        QScriptValue obj = eng.newObject();
        eng.currentContext()->setThisObject(obj);
        QVERIFY(eng.currentContext()->thisObject().equals(obj));
        eng.currentContext()->setThisObject(QScriptValue());
        QVERIFY(eng.currentContext()->thisObject().equals(obj));

        QScriptEngine eng2;
        QScriptValue obj2 = eng2.newObject();
        QTest::ignoreMessage(QtWarningMsg, "QScriptContext::setThisObject() failed: cannot set an object created in a different engine");
        eng.currentContext()->setThisObject(obj2);
    }
}
void tst_QScriptContext::callee()
{
    QScriptEngine eng;

    {
        QScriptValue fun = eng.newFunction(get_callee);
        fun.setProperty("foo", QScriptValue(&eng, "bar"));
        eng.globalObject().setProperty("get_callee", fun);

        QScriptValue result = eng.evaluate("get_callee()");
        QCOMPARE(result.isFunction(), true);
        QCOMPARE(result.property("foo").toString(), QString("bar"));
    }

    // callee when toPrimitive() is called internally
    {
        QScriptValue fun = eng.newFunction(store_callee_and_return_primitive);
        QScriptValue obj = eng.newObject();
        obj.setProperty("toString", fun);
        QVERIFY(!obj.property("callee").isValid());
        (void)obj.toString();
        QVERIFY(obj.property("callee").isFunction());
        QVERIFY(obj.property("callee").strictlyEquals(fun));

        obj.setProperty("callee", QScriptValue());
        QVERIFY(!obj.property("callee").isValid());
        obj.setProperty("valueOf", fun);
        (void)obj.toNumber();
        QVERIFY(obj.property("callee").isFunction());
        QVERIFY(obj.property("callee").strictlyEquals(fun));
    }
}
Example #11
0
double MainWindow::str2double(QString s){

    QScriptEngine e;
    s.replace(QRegExp("PI"),"Math.PI");
    QScriptValue v = e.evaluate(s);
    return v.toNumber();
}
Example #12
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());
    }
}
Example #13
0
double EnvWrap::evalDouble( const QString& nm )
{
	QScriptValue result = evalExp(nm);
	if (result.isNumber())
		return result.toNumber();
	else
		throw ExpressionHasNotThisTypeException("Double",nm);
	return double();
}
Example #14
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() );
}
void tst_QScriptContext::throwValue()
{
    QScriptEngine eng;

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

    {
        QScriptValue result = eng.evaluate("throw_value(123)");
        QCOMPARE(result.isError(), false);
        QCOMPARE(result.toNumber(), 123.0);
        QCOMPARE(eng.hasUncaughtException(), true);
    }
}
static void breakpointDataFromScriptValue(const QScriptValue &in, QScriptBreakpointData &out)
{
    QScriptValue scriptId = in.property(QString::fromLatin1("scriptId"));
    if (scriptId.isValid())
        out.setScriptId((qint64)scriptId.toNumber());
    out.setFileName(in.property(QString::fromLatin1("fileName")).toString());
    out.setLineNumber(in.property(QString::fromLatin1("lineNumber")).toInt32());
    QScriptValue enabled = in.property(QString::fromLatin1("enabled"));
    if (enabled.isValid())
        out.setEnabled(enabled.toBoolean());
    QScriptValue singleShot = in.property(QString::fromLatin1("singleShot"));
    if (singleShot.isValid())
        out.setSingleShot(singleShot.toBoolean());
    out.setIgnoreCount(in.property(QString::fromLatin1("ignoreCount")).toInt32());
    out.setCondition(in.property(QString::fromLatin1("condition")).toString());
}
Example #17
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());
}
Direction PongAI::nextMove(ProgrammedObject *paddle, ProgrammedObject *ball)
{
	// Cache 'paddle' and 'ball' wrapper objects to pass to 'nextMove' function.
	QScriptValue jsBall = _scriptEngine.newQObject(ball);
	_scriptEngine.globalObject().setProperty("ball", jsBall);

	QScriptValue jsPaddle = _scriptEngine.newQObject(paddle);
	_scriptEngine.globalObject().setProperty("paddle", jsPaddle);

	QScriptValue scriptResult = _jsNextMoveFunction.call(QScriptValue(),
		QScriptValueList() << jsPaddle << jsBall);

	if (_scriptEngine.hasUncaughtException())
	{
		 int lineNo = _scriptEngine.uncaughtExceptionLineNumber();
		 qWarning() << "line: " << lineNo << " : " << scriptResult.toString();
	}

	return (Direction)scriptResult.toNumber();
}
	QScriptValue QtScriptObject::validateNumber(const QString& parameterName, QScriptValue value, double minValue, double maxValue)
	{
		QScriptValue result = this->validateNumber(parameterName, value);

		if (result.isUndefined())
		{
			qsreal number = value.toNumber();

			if (number < minValue)
			{
				result = this->throwError(QString(QT_TR_NOOP("Parameter %1 must be greater than %2")).arg(parameterName).arg(minValue));
			}
			else if (number > maxValue)
			{
				result = this->throwError(QString(QT_TR_NOOP("Parameter %1 must be less than %2")).arg(parameterName).arg(maxValue));
			}
			else
			{
				result = QScriptValue(QScriptValue::UndefinedValue);
			}
		}

		return result;
	}
Example #20
0
void MetaCallArgument::fromScriptValue(int callType, QDeclarativeEngine *engine, const QScriptValue &value)
{
    if (type != 0) { cleanup(); type = 0; }

    if (callType == qMetaTypeId<QScriptValue>()) {
        new (&data) QScriptValue(value);
        type = qMetaTypeId<QScriptValue>();
    } else if (callType == QMetaType::Int) {
        *((int *)&data) = int(value.toInt32());
        type = callType;
    } else if (callType == QMetaType::UInt) {
        *((uint *)&data) = uint(value.toUInt32());
        type = callType;
    } else if (callType == QMetaType::Bool) {
        *((bool *)&data) = value.toBool();
        type = callType;
    } else if (callType == QMetaType::Double) {
        *((double *)&data) = double(value.toNumber());
        type = callType;
    } else if (callType == QMetaType::Float) {
        *((float *)&data) = float(value.toNumber());
        type = callType;
    } else if (callType == QMetaType::QString) {
        if (value.isNull() || value.isUndefined())
            new (&data) QString();
        else
            new (&data) QString(value.toString());
        type = callType;
    } else if (callType == QMetaType::QObjectStar) {
        *((QObject **)&data) = value.toQObject();
        type = callType;
    } else if (callType == qMetaTypeId<QVariant>()) {
        new (&data) QVariant(QDeclarativeEnginePrivate::get(engine)->scriptValueToVariant(value));
        type = callType;
    } else if (callType == qMetaTypeId<QList<QObject*> >()) {
        QList<QObject *> *list = new (&data) QList<QObject *>(); 
        if (value.isArray()) {
            int length = value.property(QLatin1String("length")).toInt32();
            for (int ii = 0; ii < length; ++ii) {
                QScriptValue arrayItem = value.property(ii);
                QObject *d = arrayItem.toQObject();
                list->append(d);
            }
        } else if (QObject *d = value.toQObject()) {
            list->append(d);
        }
        type = callType;
    } else {
        new (&data) QVariant();
        type = -1;

        QVariant v = QDeclarativeEnginePrivate::get(engine)->scriptValueToVariant(value);
        if (v.userType() == callType) {
            *((QVariant *)&data) = v;
        } else if (v.canConvert((QVariant::Type)callType)) {
            *((QVariant *)&data) = v;
            ((QVariant *)&data)->convert((QVariant::Type)callType);
        } else {
            *((QVariant *)&data) = QVariant(callType, (void *)0);
        }
    }
}
Example #21
0
bool operator==(const QScriptValue& first, const QScriptValue& second) {
    if (first.isUndefined()) {
        return second.isUndefined();
        
    } else if (first.isNull()) {
        return second.isNull();
    
    } else if (first.isBool()) {
        return second.isBool() && first.toBool() == second.toBool();
    
    } else if (first.isNumber()) {
        return second.isNumber() && first.toNumber() == second.toNumber();
    
    } else if (first.isString()) {
        return second.isString() && first.toString() == second.toString();
    
    } else if (first.isVariant()) {
        return second.isVariant() && first.toVariant() == second.toVariant();
        
    } else if (first.isQObject()) {
        return second.isQObject() && first.toQObject() == second.toQObject();
    
    } else if (first.isQMetaObject()) {
        return second.isQMetaObject() && first.toQMetaObject() == second.toQMetaObject();
        
    } else if (first.isDate()) {
        return second.isDate() && first.toDateTime() == second.toDateTime();
    
    } else if (first.isRegExp()) {
        return second.isRegExp() && first.toRegExp() == second.toRegExp();
    
    } else if (first.isArray()) {
        if (!second.isArray()) {
            return false;
        }
        int length = first.property(ScriptCache::getInstance()->getLengthString()).toInt32();
        if (second.property(ScriptCache::getInstance()->getLengthString()).toInt32() != length) {
            return false;
        }
        for (int i = 0; i < length; i++) {
            if (first.property(i) != second.property(i)) {
                return false;
            }
        }
        return true;
        
    } else if (first.isObject()) {
        if (!second.isObject()) {
            return false;
        }
        int propertyCount = 0;
        for (QScriptValueIterator it(first); it.hasNext(); ) {
            it.next();
            if (second.property(it.scriptName()) != it.value()) {
                return false;
            }
            propertyCount++;
        }
        // make sure the second has exactly as many properties as the first
        for (QScriptValueIterator it(second); it.hasNext(); ) {
            it.next();
            if (--propertyCount < 0) {
                return false;
            }
        }
        return true;
        
    } else {
        // if none of the above tests apply, first must be invalid
        return !second.isValid();
    }
}
void MetaCallArgument::fromScriptValue(int callType, QDeclarativeEngine *engine, const QScriptValue &value)
{
    if (type != 0) { cleanup(); type = 0; }

    if (callType == qMetaTypeId<QScriptValue>()) {
        qscriptValuePtr = new (&allocData) QScriptValue(value);
        type = qMetaTypeId<QScriptValue>();
    } else if (callType == QMetaType::Int) {
        intValue = quint32(value.toInt32());
        type = callType;
    } else if (callType == QMetaType::UInt) {
        intValue = quint32(value.toUInt32());
        type = callType;
    } else if (callType == QMetaType::Bool) {
        boolValue = value.toBool();
        type = callType;
    } else if (callType == QMetaType::Double) {
        doubleValue = double(value.toNumber());
        type = callType;
    } else if (callType == QMetaType::Float) {
        floatValue = float(value.toNumber());
        type = callType;
    } else if (callType == QMetaType::QString) {
        if (value.isNull() || value.isUndefined())
            qstringPtr = new (&allocData) QString();
        else
            qstringPtr = new (&allocData) QString(value.toString());
        type = callType;
    } else if (callType == QMetaType::QObjectStar) {
        qobjectPtr = value.toQObject();
        type = callType;
    } else if (callType == qMetaTypeId<QVariant>()) {
        QVariant other = QDeclarativeEnginePrivate::get(engine)->scriptValueToVariant(value);
        qvariantPtr = new (&allocData) QVariant(other);
        type = callType;
    } else if (callType == qMetaTypeId<QList<QObject*> >()) {
        qlistPtr = new (&allocData) QList<QObject *>(); 
        if (value.isArray()) {
            int length = value.property(QLatin1String("length")).toInt32();
            for (int ii = 0; ii < length; ++ii) {
                QScriptValue arrayItem = value.property(ii);
                QObject *d = arrayItem.toQObject();
                qlistPtr->append(d);
            }
        } else if (QObject *d = value.toQObject()) {
            qlistPtr->append(d);
        }
        type = callType;
    } else {
        qvariantPtr = new (&allocData) QVariant();
        type = -1;

        QDeclarativeEnginePrivate *priv = QDeclarativeEnginePrivate::get(engine);
        QVariant v = priv->scriptValueToVariant(value);
        if (v.userType() == callType) {
            *qvariantPtr = v;
        } else if (v.canConvert((QVariant::Type)callType)) {
            *qvariantPtr = v;
            qvariantPtr->convert((QVariant::Type)callType);
        } else if (const QMetaObject *mo = priv->rawMetaObjectForType(callType)) {
            QObject *obj = priv->toQObject(v);
            
            if (obj) {
                const QMetaObject *objMo = obj->metaObject();
                while (objMo && objMo != mo) objMo = objMo->superClass();
                if (!objMo) obj = 0;
            }

            *qvariantPtr = QVariant(callType, &obj);
        } else {
            *qvariantPtr = QVariant(callType, (void *)0);
        }
    }
}
double QtScriptForceCondition3D::w()
{
    QScriptValue func = engine_.globalObject().property("w");
    QScriptValue result = func.call(object_, QScriptValueList() << x_ << y_ << z_);
    return result.toNumber();
}
Example #24
0
void tst_QScriptClass::extension()
{
    QScriptEngine eng;
    {
        TestClass cls(&eng);
        cls.setCallableMode(TestClass::NotCallable);
        QVERIFY(!cls.supportsExtension(QScriptClass::Callable));
        QVERIFY(!cls.supportsExtension(QScriptClass::HasInstance));
    }
    // Callable
    {
        TestClass cls(&eng);
        cls.setCallableMode(TestClass::CallableReturnsSum);
        QVERIFY(cls.supportsExtension(QScriptClass::Callable));

        QScriptValue obj = eng.newObject(&cls);
        obj.setProperty("one", QScriptValue(&eng, 1));
        obj.setProperty("two", QScriptValue(&eng, 2));
        obj.setProperty("three", QScriptValue(&eng, 3));
        {
            QScriptValueList args;
            args << QScriptValue(&eng, 4) << QScriptValue(&eng, 5);
            QScriptValue ret = obj.call(obj, args);
            QCOMPARE(ret.toNumber(), qsreal(15));
        }

        cls.setCallableMode(TestClass::CallableReturnsArgument);
        {
            QScriptValue ret = obj.call(obj, QScriptValueList() << 123);
            QVERIFY(ret.isNumber());
            QCOMPARE(ret.toInt32(), 123);
        }
        {
            QScriptValue ret = obj.call(obj, QScriptValueList() << true);
            QVERIFY(ret.isBoolean());
            QCOMPARE(ret.toBoolean(), true);
        }
        {
            QScriptValue ret = obj.call(obj, QScriptValueList() << QString::fromLatin1("ciao"));
            QVERIFY(ret.isString());
            QCOMPARE(ret.toString(), QString::fromLatin1("ciao"));
        }
        {
            QScriptValue objobj = eng.newObject();
            QScriptValue ret = obj.call(obj, QScriptValueList() << objobj);
            QVERIFY(ret.isObject());
            QVERIFY(ret.strictlyEquals(objobj));
        }
        {
            QScriptValue ret = obj.call(obj, QScriptValueList() << QScriptValue());
            QVERIFY(ret.isUndefined());
        }

        cls.setCallableMode(TestClass::CallableReturnsInvalidVariant);
        {
            QScriptValue ret = obj.call(obj);
            QVERIFY(ret.isUndefined());
        }
    }
    // HasInstance
    {
        TestClass cls(&eng);
        cls.setHasInstance(true);
        QVERIFY(cls.supportsExtension(QScriptClass::HasInstance));

        QScriptValue obj = eng.newObject(&cls);
        obj.setProperty("foo", QScriptValue(&eng, 123));
        QScriptValue plain = eng.newObject();
        QVERIFY(!plain.instanceOf(obj));

        eng.globalObject().setProperty("HasInstanceTester", obj);
        eng.globalObject().setProperty("hasInstanceValue", plain);
        {
            QScriptValue ret = eng.evaluate("hasInstanceValue instanceof HasInstanceTester");
            QVERIFY(ret.isBoolean());
            QVERIFY(!ret.toBoolean());
        }

        plain.setProperty("foo", QScriptValue(&eng, 456));
        QVERIFY(!plain.instanceOf(obj));
        {
            QScriptValue ret = eng.evaluate("hasInstanceValue instanceof HasInstanceTester");
            QVERIFY(ret.isBoolean());
            QVERIFY(!ret.toBoolean());
        }

        plain.setProperty("foo", obj.property("foo"));
        QVERIFY(plain.instanceOf(obj));
        {
            QScriptValue ret = eng.evaluate("hasInstanceValue instanceof HasInstanceTester");
            QVERIFY(ret.isBoolean());
            QVERIFY(ret.toBoolean());
        }
    }
}
Example #25
0
static void marshall_basetype(Marshall *m)
{
    switch(m->type().element()) {        
    case Smoke::t_bool:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (!value.isBool()) {
                m->item().s_bool = false;
            } else {
                m->item().s_bool = value.toBool();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_bool);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
    
    case Smoke::t_char:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_char = 0;
            } else {
                m->item().s_char = (char) value.toInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_char);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
    
    case Smoke::t_uchar:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_uchar = 0;
            } else {
                m->item().s_uchar = (uchar) value.toUInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_uchar);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
    
    case Smoke::t_short:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_short = 0;
            } else {
                m->item().s_short = (short) value.toInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_short);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_ushort:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_ushort = 0;
            } else {
                m->item().s_ushort = value.toUInt16();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_ushort);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_int:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_int = 0;
            } else {
                m->item().s_int = value.toInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_int);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_uint:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_uint = 0;
            } else {
                m->item().s_uint = value.toUInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_uint);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_long:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_long = 0;
            } else {
                m->item().s_long = (long) value.toInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), (int) m->item().s_long);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_ulong:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_ulong = 0;
            } else {
                m->item().s_ulong = (ulong) value.toUInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), (uint) m->item().s_ulong);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_float:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_float = 0.0;
            } else {
                m->item().s_float = (float) value.toNumber();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_float);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_double:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_double = 0.0;
            } else {
                m->item().s_double = value.toNumber();
            }
            break;
        }
        case Marshall::ToQScriptValue:
            *(m->var()) = QScriptValue(m->engine(), m->item().s_double);
            break;
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_enum:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_enum = 0;
            } else if (value.instanceOf(JSmoke::Global::QtEnum)) {
                m->item().s_enum = value.property("value").toUInt32();
            } else {
                m->item().s_enum = value.toUInt32();
            }
            break;
        }
        case Marshall::ToQScriptValue:
        {
            QScriptValueList args;
            args << (uint) m->item().s_enum << m->type().name();
            *(m->var()) = JSmoke::Global::QtEnum.call(QScriptValue(), args);
            break;
        }
        default:
            m->unsupported();
            break;
        }
        break;
        
    case Smoke::t_class:
        switch(m->action()) {
        case Marshall::FromQScriptValue:
        {
            QScriptValue value = *(m->var());

            if (value.isNull()) {
                m->item().s_class = 0;
                return;
            }
            
            if (value.isDate()) {
                Smoke::ModuleIndex classId = Smoke::findClass(m->smoke()->classes[m->type().classId()].className);
                if (classId == JSmoke::Global::QDateClassId) {
                    m->item().s_class = new QDate(value.toDateTime().date());
                } else if (classId == JSmoke::Global::QDateTimeClassId) {
                     m->item().s_class = new QDateTime(value.toDateTime());
                } else if (classId == JSmoke::Global::QTimeClassId) {
                     m->item().s_class = new QTime(value.toDateTime().time());
                } else {
                    m->item().s_class = 0;
                }
                
                return;
            } else if (value.isRegExp()) {
                m->item().s_class = new QRegExp(value.toRegExp());
                return;
            }
            
            if (!Object::Instance::isSmokeObject(value)) {
                m->item().s_class = 0;
                return;
            }
            
            Object::Instance * instance = Object::Instance::get(value);
            void * ptr = instance->value;
            
            if (!m->cleanup() && m->type().isStack()) {
                ptr = constructCopy(instance);
            }
            
            ptr = instance->classId.smoke->cast(    ptr, 
                                                    instance->classId, 
                                                    Smoke::ModuleIndex(m->smoke(), m->type().classId()) );
            
            m->item().s_class = ptr;
            break;
        }
        
        case Marshall::ToQScriptValue:
        {
            if (m->item().s_voidp == 0) {
                *(m->var()) = m->engine()->nullValue();
                return;
            }
            
            void * ptr = m->item().s_voidp;
            QScriptValue * value = JSmoke::Global::getScriptValue(ptr);
            
            if (value != 0) {
                *(m->var()) = *value;
                return ;
            }
            
            QByteArray className(m->smoke()->classes[m->type().classId()].className);
            QScriptValue obj = Global::wrapInstance(    m->engine(), 
                                                        Smoke::findClass(className), 
                                                        ptr,
                                                        QScriptEngine::QtOwnership );
            
            if (m->type().isConst() && m->type().isRef()) {
                Object::Instance * instance = Object::Instance::get(obj);
                ptr = constructCopy(instance);

                if (ptr != 0) {
                    instance->value = ptr;
                    instance->ownership = QScriptEngine::ScriptOwnership;
                    Global::mapPointer(new QScriptValue(obj), instance, instance->classId);
                }
            }

            *(m->var()) = obj;
            break;
        }
        
        default:
            m->unsupported();
            break;
        }
        break;
        
    default:
        m->unsupported();
        break;
    }
}
Example #26
0
QScriptValue PHIBaseItem::top( const QScriptValue &v )
{
    if ( !v.isValid() ) return qRound( realY()+adjustedPos().y() );
    setY( v.toNumber()-adjustedPos().y() );
    return self();
}
Example #27
0
QScriptValue PHIBaseItem::left( const QScriptValue &v )
{
    if ( !v.isValid() ) return qRound( realX()+adjustedPos().x() );
    setX( v.toNumber()-adjustedPos().x() );
    return self();
}
Example #28
0
QScriptValue PHIBaseItem::width( const QScriptValue &v )
{
    if ( !v.isValid() ) return qRound( realWidth() );
    setWidth( v.toNumber() );
    return self();
}
void QDeclarativeObjectScriptClass::setProperty(QObject *obj,
                                                const Identifier &name,
                                                const QScriptValue &value,
                                                QScriptContext *context,
                                                QDeclarativeContextData *evalContext)
{
    Q_UNUSED(name);

    Q_ASSERT(obj);
    Q_ASSERT(lastData);
    Q_ASSERT(context);

    if (!lastData->isValid()) {
        QString error = QLatin1String("Cannot assign to non-existent property \"") +
                        toString(name) + QLatin1Char('\"');
        context->throwError(error);
        return;
    }

    if (!(lastData->flags & QDeclarativePropertyCache::Data::IsWritable) && 
        !(lastData->flags & QDeclarativePropertyCache::Data::IsQList)) {
        QString error = QLatin1String("Cannot assign to read-only property \"") +
                        toString(name) + QLatin1Char('\"');
        context->throwError(error);
        return;
    }

    QDeclarativeEnginePrivate *enginePriv = QDeclarativeEnginePrivate::get(engine);

    if (!evalContext) {
        // Global object, QScriptContext activation object, QDeclarativeContext object
        QScriptValue scopeNode = scopeChainValue(context, -3);
        if (scopeNode.isValid()) {
            Q_ASSERT(scriptClass(scopeNode) == enginePriv->contextClass);

            evalContext = enginePriv->contextClass->contextFromValue(scopeNode);
        }
    }

    QDeclarativeBinding *newBinding = 0;
    if (value.isFunction() && !value.isRegExp()) {
        QScriptContextInfo ctxtInfo(context);
        QDeclarativePropertyCache::ValueTypeData valueTypeData;

        newBinding = new QDeclarativeBinding(value, obj, evalContext);
        newBinding->setSourceLocation(ctxtInfo.fileName(), ctxtInfo.functionStartLineNumber());
        newBinding->setTarget(QDeclarativePropertyPrivate::restore(*lastData, valueTypeData, obj, evalContext));
        if (newBinding->expression().contains(QLatin1String("this")))
            newBinding->setEvaluateFlags(newBinding->evaluateFlags() | QDeclarativeBinding::RequiresThisObject);
    }

    QDeclarativeAbstractBinding *delBinding =
        QDeclarativePropertyPrivate::setBinding(obj, lastData->coreIndex, -1, newBinding);
    if (delBinding)
        delBinding->destroy();

    if (value.isNull() && lastData->flags & QDeclarativePropertyCache::Data::IsQObjectDerived) {
        QObject *o = 0;
        int status = -1;
        int flags = 0;
        void *argv[] = { &o, 0, &status, &flags };
        QMetaObject::metacall(obj, QMetaObject::WriteProperty, lastData->coreIndex, argv);
    } else if (value.isUndefined() && lastData->flags & QDeclarativePropertyCache::Data::IsResettable) {
        void *a[] = { 0 };
        QMetaObject::metacall(obj, QMetaObject::ResetProperty, lastData->coreIndex, a);
    } else if (value.isUndefined() && lastData->propType == qMetaTypeId<QVariant>()) {
        QDeclarativePropertyPrivate::write(obj, *lastData, QVariant(), evalContext);
    } else if (value.isUndefined()) {
        QString error = QLatin1String("Cannot assign [undefined] to ") +
                        QLatin1String(QMetaType::typeName(lastData->propType));
        context->throwError(error);
    } else if (value.isFunction() && !value.isRegExp()) {
        // this is handled by the binding creation above
    } else {
        //### expand optimization for other known types
        if (lastData->propType == QMetaType::Int && value.isNumber()) {
            int rawValue = qRoundDouble(value.toNumber());
            int status = -1;
            int flags = 0;
            void *a[] = { (void *)&rawValue, 0, &status, &flags };
            QMetaObject::metacall(obj, QMetaObject::WriteProperty,
                                  lastData->coreIndex, a);
            return;
        } else if (lastData->propType == QMetaType::QReal && value.isNumber()) {
            qreal rawValue = qreal(value.toNumber());
            int status = -1;
            int flags = 0;
            void *a[] = { (void *)&rawValue, 0, &status, &flags };
            QMetaObject::metacall(obj, QMetaObject::WriteProperty,
                                  lastData->coreIndex, a);
            return;
        } else if (lastData->propType == QMetaType::QString && value.isString()) {
            const QString &rawValue = value.toString();
            int status = -1;
            int flags = 0;
            void *a[] = { (void *)&rawValue, 0, &status, &flags };
            QMetaObject::metacall(obj, QMetaObject::WriteProperty,
                                  lastData->coreIndex, a);
            return;
        }

        QVariant v;
        if (lastData->flags & QDeclarativePropertyCache::Data::IsQList)
            v = enginePriv->scriptValueToVariant(value, qMetaTypeId<QList<QObject *> >());
        else
            v = enginePriv->scriptValueToVariant(value, lastData->propType);

        if (!QDeclarativePropertyPrivate::write(obj, *lastData, v, evalContext)) {
            const char *valueType = 0;
            if (v.userType() == QVariant::Invalid) valueType = "null";
            else valueType = QMetaType::typeName(v.userType());

            QString error = QLatin1String("Cannot assign ") +
                            QLatin1String(valueType) +
                            QLatin1String(" to ") +
                            QLatin1String(QMetaType::typeName(lastData->propType));
            context->throwError(error);
        }
    }
}
Example #30
0
QScriptValue PHIBaseItem::height( const QScriptValue &v )
{
    if ( !v.isValid() ) return qRound( realHeight() );
    setHeight( v.toNumber() );
    return self();
}