Example #1
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 #2
0
bool HttpHandlerQtScript::handleRequest(Pillow::HttpRequest *request)
{
    if (!_scriptFunction.isFunction()) return false;

    QScriptEngine* engine = _scriptFunction.engine();
    QScriptValue requestObject = engine->newObject();
    requestObject.setProperty("nativeRequest", _scriptFunction.engine()->newQObject(request));
    requestObject.setProperty("requestMethod", QUrl::fromPercentEncoding(request->requestMethod()));
    requestObject.setProperty("requestUri", QUrl::fromPercentEncoding(request->requestUri()));
    requestObject.setProperty("requestFragment", QUrl::fromPercentEncoding(request->requestFragment()));
    requestObject.setProperty("requestPath", QUrl::fromPercentEncoding(request->requestPath()));
    requestObject.setProperty("requestQueryString", QUrl::fromPercentEncoding(request->requestQueryString()));
    requestObject.setProperty("requestHeaders", qScriptValueFromValue(engine, request->requestHeaders()));

    QList<QPair<QString, QString> > queryParams = QUrl(request->requestUri()).queryItems();
    QScriptValue queryParamsObject = engine->newObject();
    for (int i = 0, iE = queryParams.size(); i < iE; ++i)
        queryParamsObject.setProperty(queryParams.at(i).first, queryParams.at(i).second);
    requestObject.setProperty("requestQueryParams", queryParamsObject);

    QScriptValue result = _scriptFunction.call(_scriptFunction, QScriptValueList() << requestObject);

    if (result.isError())
    {
        if (request->state() == HttpRequest::SendingHeaders)
        {
            // Nothing was sent yet... We have a chance to let the client know we had an error.
            request->writeResponseString(500, HttpHeaderCollection(), objectToString(result));
        }
        engine->clearExceptions();
        return true;
    }

    return result.toBool();
}
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 #4
0
void TestKernel::engineSetup()
{
    GraphDocumentPtr document;
    NodePtr nodeA, nodeB;
    EdgePtr edge;

    QVERIFY(GraphDocument::objects() == 0);
    QVERIFY(Node::objects() == 0);
    QVERIFY(Edge::objects() == 0);

    // test destroy graph document
    document = GraphDocument::create();
    nodeA = Node::create(document);
    nodeB = Node::create(document);
    edge = Edge::create(nodeA, nodeB);

    // create kernel
    QString script = "return true;";
    Kernel kernel;
    QScriptValue result = kernel.execute(document, script);
    QCOMPARE(result.toBool(), true);

    document->destroy();
    document.reset();
    nodeA.reset();
    nodeB.reset();
    edge.reset();
    QCOMPARE(Edge::objects(), uint(0));
    QCOMPARE(Node::objects(), uint(0));
    QCOMPARE(GraphDocument::objects(), uint(0));
}
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 #6
0
ImageDataPtr CountPixel::startHandle(ImageDataPtr src1, const ImageDataPtr)
{
    QScriptEngine engine;
    QString originalQuery = m_listParameters[SCRIPT]->toString();

    unsigned long long int total = 0;

    auto lambda = [&total, &originalQuery, &engine](unsigned char & r, unsigned char & b, unsigned char & g)
    {
        QString query = originalQuery;
        query.replace("Gr", QString::number(0.33*b + 0.56*g + 0.11*r) );
        query.replace("B", QString::number(b) );
        query.replace("G", QString::number(g) );
        query.replace("R", QString::number(r) );
        if( ! engine.canEvaluate(query) )
            total = -1;
        QScriptValue value = engine.evaluate(query);

        total += value.toBool();
    };
    src1->forEachPixel( lambda);

    src1->addResults( m_listParameters[NAME]->toString(), total);

    return src1;
}
Example #7
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());
    }

}
Example #8
0
void TestKernel::edgeProperties()
{
    GraphDocumentPtr document = GraphDocument::create();
    document->edgeTypes().first()->setDirection(EdgeType::Unidirectional);
    NodePtr nodeA = Node::create(document);
    NodePtr nodeB = Node::create(document);
    EdgePtr edge = Edge::create(nodeA, nodeB);

    // test nodes
    Kernel kernel;
    QString script;
    QScriptValue result;

    script = "Document.nodes()[0].edges()[0].from().id;";
    result = kernel.execute(document, script);
    QCOMPARE(result.toString().toInt(), nodeA->id());

    script = "Document.nodes()[0].edges()[0].to().id;";
    result = kernel.execute(document, script);
    QCOMPARE(result.toString().toInt(), nodeB->id());

    script = "Document.nodes()[0].edges()[0].directed();";
    result = kernel.execute(document, script);
    QCOMPARE(result.toBool(), true);

    // cleanup
    document->destroy();
}
 void setProperty(QScriptValue &object,
                   const QScriptString &name, uint, const QScriptValue & value)
 {
     if (name == str_forwardOnly) {
         QSqlQuery query = qscriptvalue_cast<QSqlQuery>(object.data());
         query.setForwardOnly(value.toBool());
     }
 }
Example #10
0
void ScriptHandler::validateData(DataInformation* data)
{
    if (!data)
        return;

    data->setHasBeenValidated(false); //not yet validated

    if (data->hasChildren())
    {
        //first validate the children
        for (uint i = 0; i < data->childCount(); ++i)
        {
            validateData(data->childAt(i));
        }
    }

    //check if has a validation function:
    AdditionalData* additionalData = data->additionalData();
    if (additionalData && additionalData->validationFunction().isValid())
    {
        //value exists, we assume it has been checked to be a function
#ifdef OKTETA_DEBUG_SCRIPT
        mDebugger->attachTo(mEngine);
        mDebugger->action(QScriptEngineDebugger::InterruptAction)->trigger();
        kDebug()
        << "validating element: " << data->name();
#endif

//         QScriptValue thisObject = mEngine->newQObject(data,
//                 QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater);
//         QScriptValue mainStruct = mEngine->newQObject(data->mainStructure(),
//                 QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater);
        QScriptValue thisObject = data->toScriptValue(mEngine, &mHandlerInfo);
        QScriptValue mainStruct = data->mainStructure()->toScriptValue(mEngine, &mHandlerInfo);
        QScriptValueList args;
        args << mainStruct;
        QScriptValue result = additionalData->validationFunction().call(thisObject, args);
        if (result.isError())
        {
            ScriptUtils::object()->logScriptError(QLatin1String("error occurred while "
                "validating element ") + data->name(), result);
            data->setValidationError(QLatin1String("Error occurred in validation: ")
                    + result.toString());
        }
        if (mEngine->hasUncaughtException())
        {
            ScriptUtils::object()->logScriptError(
                    mEngine->uncaughtExceptionBacktrace());
            data->setValidationError(QLatin1String("Error occurred in validation: ")
                    + result.toString());
        }
        if (result.isBool() || result.isBoolean())
        {
            data->setValidationSuccessful(result.toBool());
        }
    }
}
Example #11
0
bool EnvWrap::evalBool( const QString& nm )
{
	QScriptValue result = evalExp(nm);
	if (result.isBool())
		return result.toBool();
	else
		throw ExpressionHasNotThisTypeException("Bool",nm);
	return false;
}
bool QtScriptForceCondition3D::isApplied(msh::PointPointer point)
{
    QScriptValue func = engine_.globalObject().property("isApplied");
    QScriptValue result = func.call(object_, QScriptValueList() << point->x() << point->y() << point->z());
    x_ = point->x();
    y_ = point->y();
    z_ = point->z();
    return result.toBool();
}
Example #13
0
/*
var conference = qutim.protocol("jabber").account("*****@*****.**").unit("*****@*****.**", false);
var msg = new Message;
msg.text = "Hi!";
conference.sendMessage(msg);
*/
void ScriptMessage::setProperty(QScriptValue &object, const QScriptString &name,
								uint id, const QScriptValue &value)
{
	Q_UNUSED(id);
	Message *msg = message_get_value(object);
	if (name == m_incoming)
		msg->setIncoming(value.toBool());
	else
		msg->setProperty(name.toString().toUtf8(), value.toVariant());
}
Example #14
0
/*! Emits the \a saving() signal which triggers any widgets to save that have a mapped \a savedMethod()
  specified by \sa insert().  Also reloads metrics, privileges, preferences, and the menubar in the
  main application.  The screen will close if \a close is true.

  \sa apply()
  */
void setup::save(bool close)
{
  emit saving();

  QMapIterator<QString, ItemProps> i(_itemMap);
  while (i.hasNext())
  {
    bool ok = false;

    i.next();

    XAbstractConfigure *cw = qobject_cast<XAbstractConfigure*>(i.value().implementation);
    QScriptEngine  *engine = qobject_cast<QScriptEngine*>(i.value().implementation);
    QString method = QString(i.value().saveMethod).remove("(").remove(")");

    if (! i.value().implementation)
      continue;
    else if (cw)
      ok = cw->sSave();
    else if (engine && engine->globalObject().property(method).isFunction())
    {
      QScriptValue saveresult = engine->globalObject().property(method).call();
      if (saveresult.isBool())
        ok = saveresult.toBool();
      else
        qWarning("Problem executing %s method for script %s",
                 qPrintable(i.value().saveMethod), qPrintable(i.key()));
    }
    else
    {
      qWarning("Could not call save method for %s; it's a(n) %s (%p)",
               qPrintable(i.key()),
               qobject_cast<QObject*>(i.value().implementation) ?
               qobject_cast<QObject*>(i.value().implementation)->metaObject()->className() : "unknown class",
               i.value().implementation);
      ok = true;
    }

    if (! ok)
    {
      setCurrentIndex(i.key());
      return;
    }
  }

  _metrics->load();
  _privileges->load();
  _preferences->load();
  omfgThis->initMenuBar();

  if (close)
    accept();
}
Example #15
0
bool display::setParams(ParameterList & params)
{
  bool ret = _data->setParams(params);
  if(engine() && engine()->globalObject().property("setParams").isFunction())
  {
    QScriptValue paramArg = ParameterListtoScriptValue(engine(), params);
    QScriptValue tmp = engine()->globalObject().property("setParams").call(QScriptValue(), QScriptValueList() << paramArg);
    ret = ret && tmp.toBool();
    params.clear();
    ParameterListfromScriptValue(paramArg, params);
  }
  return ret;
}
Example #16
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);
        }
    }
}
QScriptValue ScriptableSyntaxDefinition::OPTION_(QScriptContext* context, QScriptEngine* engine)
{
	checkNumberOfArguments(context, 2);
	const char* name = 0;
	constCharFromScriptValue(context->argument(0), name);
	QScriptValue value = context->argument(1);
	if (value.isBool())
		super(context)->OPTION(name, value.toBool());
	/*else if (value.isNumber())
		super(context)->OPTION(name, value.toInt32());
	else if (value.isString())
		super(context)->OPTION(name, value.toString());*/
	return QScriptValue();
}
Example #18
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 #19
0
void Image3DOverlay::setProperties(const QScriptValue &properties) {
    Billboard3DOverlay::setProperties(properties);

    QScriptValue urlValue = properties.property("url");
    if (urlValue.isValid()) {
        QString newURL = urlValue.toVariant().toString();
        if (newURL != _url) {
            setURL(newURL);
        }
    }

    QScriptValue subImageBounds = properties.property("subImage");
    if (subImageBounds.isValid()) {
        if (subImageBounds.isNull()) {
            _fromImage = QRect();
        } else {
            QRect oldSubImageRect = _fromImage;
            QRect subImageRect = _fromImage;
            if (subImageBounds.property("x").isValid()) {
                subImageRect.setX(subImageBounds.property("x").toVariant().toInt());
            } else {
                subImageRect.setX(oldSubImageRect.x());
            }
            if (subImageBounds.property("y").isValid()) {
                subImageRect.setY(subImageBounds.property("y").toVariant().toInt());
            } else {
                subImageRect.setY(oldSubImageRect.y());
            }
            if (subImageBounds.property("width").isValid()) {
                subImageRect.setWidth(subImageBounds.property("width").toVariant().toInt());
            } else {
                subImageRect.setWidth(oldSubImageRect.width());
            }
            if (subImageBounds.property("height").isValid()) {
                subImageRect.setHeight(subImageBounds.property("height").toVariant().toInt());
            } else {
                subImageRect.setHeight(oldSubImageRect.height());
            }
            setClipFromSource(subImageRect);
        }
    }

    QScriptValue emissiveValue = properties.property("emissive");
    if (emissiveValue.isValid()) {
        _emissive = emissiveValue.toBool();
    }
}
Example #20
0
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;
    }
}
bool BreakpointConditionChecker::evaluateCondition(const AttributeScript *conditionContext) {
    Q_ASSERT(NULL != conditionContext);

    QMutexLocker lock(&engineGuard);

    if (NULL == engine || NULL == engine->getWorkflowContext()) {
        return false;
    }
    if (conditionText.isEmpty() || !enabled) {
        return true;
    }

    QMap<QString, QScriptValue> scriptVars;
    foreach (const Descriptor & key, conditionContext->getScriptVars().uniqueKeys()) {
        assert(!key.getId().isEmpty());
        scriptVars[key.getId()] = engine->newVariant(conditionContext->getScriptVars().value(key));
    }
    TaskStateInfo stateInfo;
    QScriptValue evaluationResult = ScriptTask::runScript(engine, scriptVars, conditionText,
        stateInfo);
    if (stateInfo.hasError()) {
        coreLog.error("Breakpoint condition evaluation failed. Error:\n" + stateInfo.getError());
        return false;
    } else if (evaluationResult.isBool()) {
        bool evaluatedResult = evaluationResult.toBool();
        if (HAS_CHANGED == parameter) {
            const bool returningValue = (DEFAULT_CONDITION_EVAL_RESULT == lastConditionEvaluation)
                ? false : (static_cast<bool>(lastConditionEvaluation) != evaluatedResult);
            lastConditionEvaluation = static_cast<int>(evaluatedResult);
            evaluatedResult = returningValue;
        }
        coreLog.trace(QString("Condition of breakpoint is %1").arg(evaluatedResult
            ? "true" : "false"));
        return evaluatedResult;
    } else {
        coreLog.error("Breakpoint condition's evaluation has provided no boolean value");
        return false;
    }
}
bool JavaScriptEnclosureRequest::getEnclosure(const QString &url, const QVariantMap &settings) {
    if (status() == Active) {
        return false;
    }
    
    initEngine();
    QScriptValue func = m_engine->globalObject().property("getEnclosure");

    if (func.isFunction()) {
        const QScriptValue result = func.call(QScriptValue(), QScriptValueList() << url
                                                                                 << m_engine->toScriptValue(settings));

        if (result.isError()) {
            const QString errorString = result.toString();
            Logger::log("JavaScriptEnclosureRequest::getEnclosure(). Error calling getEnclosure(): " + errorString);
            setErrorString(errorString);
            setResult(Enclosure());
            setStatus(Error);
            emit finished(this);
            return false;
        }

        if (result.toBool()) {
            setErrorString(QString());
            setStatus(Active);
            return true;
        }
    }
    else {
        Logger::log("JavaScriptEnclosureRequest::getEnclosure(). getEnclosure() function not defined");
        setErrorString(tr("getEnclosure() function not defined"));
        setResult(Enclosure());
        setStatus(Error);
        emit finished(this);
    }

    return false;
}
Example #23
0
/*!
 \brief

 \param tag
 \param fileInfo
 \param log
 \return bool
*/
bool PlayList::evaluateScript( Tag* tag, const QFileInfo& fileInfo, QString *log, QString *extInf, QString *sortBy ) const {

    if(script_.isEmpty()){
        return true;
    }

    ScriptEngine engine;
    QHash<QString,QVariant> frameFields = guiSettings->value("frameFields").toHash();

    //add all possible/specified id3v2 frames/ape items etc. to script, with empty array as value
    QHash< QString, QHash<QString,QStringList> > tagFrames = tag->frames(); //returns both ID3v2,asf,mp4,xiph and APE frames/items
    QStringList frameTypes = frameFields.keys(); //defined list of possible frames
    for(int j=0;j<frameTypes.size();j++){
        QString type = frameTypes[j]; //e.g. APE, ID3V2 etc.
        QStringList frameTypeKeys = frameFields[type].toStringList();
        QScriptValue array = engine.newArray(frameTypeKeys.size());
        QHash<QString,QStringList> tagTypeFrames = tagFrames[type];
        QStringList tagTypeFramesKeys = tagTypeFrames.keys();
        //loop for instance all ID3V2 frames
        QScriptValue v = engine.newArray(0);
        for(int i=0;i<frameTypeKeys.size();i++){
            v.setProperty(0, QScriptValue(&engine, "")); //set default value an empty array
            array.setProperty(frameTypeKeys[i].toUpper(), v);
        }//now add all frames from current tag
        for(int i=0;i<tagTypeFramesKeys.size();i++){
            QStringList list = tagTypeFrames[tagTypeFramesKeys[i]];
            for(int k=0;k<list.size();k++){
                v.setProperty(k, list[k]);
            }
            array.setProperty(tagTypeFramesKeys[i].toUpper(), v);
        }
        engine.globalObject().setProperty(type,array);
    }


    //add tag data  as variables to script
    engine.globalObject().setProperty("ARTIST",tag->artist());
    engine.globalObject().setProperty("ALBUM",tag->album());
    engine.globalObject().setProperty("GENRE",tag->genre());
    engine.globalObject().setProperty("TITLE",tag->title());
    engine.globalObject().setProperty("COMMENT",tag->comment());
    engine.globalObject().setProperty("YEAR",tag->year());
    engine.globalObject().setProperty("TRACK",tag->track());
    engine.globalObject().setProperty("LENGTH",tag->length());
    engine.globalObject().setProperty("BITRATE",tag->bitRate());
    engine.globalObject().setProperty("SAMPLERATE",tag->sampleRate());
    engine.globalObject().setProperty("CHANNELS",tag->channels());
    engine.globalObject().setProperty("TAGOK",tag->tagOk());
    engine.globalObject().setProperty("AUDIOPROPERTIESOK",tag->audioPropertiesOk());

    engine.globalObject().setProperty("FILENAME",fileInfo.fileName());
    engine.globalObject().setProperty("FILEPATH",fileInfo.filePath());    

    QScriptValue result = engine.evaluate( script_ );

    *extInf = engine.globalObject().property("EXTINF").toString();
    *sortBy = "";
    QScriptValue sortByValue = engine.globalObject().property("SORTBY");
    if( sortByValue.isValid() ){
        *sortBy = sortByValue.toString();
    }

    if( engine.hasUncaughtException() ){
        QString err = engine.uncaughtExceptionBacktrace().join("\n");
        log->append(err);
        return false;
    }
    bool res=false;
    if( result.isBool() ){
        res = result.toBool();
    }else{
        log->append("\nResult of evaluated script is not boolean");
    }
    return res;

}
Example #24
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 #25
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();
    }
}
Example #26
0
void DefaultScriptClass::setProperty(QScriptValue& object, const QScriptString& name, uint id, const QScriptValue& value)
{
    const ScriptHandlerInfo::Mode mode = mHandlerInfo->mode();
    Q_ASSERT(mode != ScriptHandlerInfo::None);
    DataInformation* data = toDataInformation(object);
    if (!data)
    {
        mHandlerInfo->logger()->error() << "could not cast data from" << object.data().toString();
        engine()->currentContext()->throwError(QScriptContext::ReferenceError,
                QStringLiteral("Attempting to access an invalid object"));
        return;
    }
    if (mode == ScriptHandlerInfo::Validating)
    {
        //only way write access is allowed is when validating: valid and validationError
        if (data->hasBeenValidated())
            data->logError() << "Cannot modify this object, it has already been validated!";
        else if (name == s_valid)
            data->mValidationSuccessful = value.toBool();
        else if (name == s_validationError)
            data->setValidationError(value.toString());
        else
            data->logError() << "Cannot write to property" << name.toString() << "while validating!";
        return;
    }

    if (mode != ScriptHandlerInfo::Updating)
    {
        data->logError() << "Writing to property" << name.toString() << "is only allowed when updating.";
        return;
    }
    Q_ASSERT(mode == ScriptHandlerInfo::Updating);

    if (name == s_byteOrder)
    {
        data->setByteOrder(ParserUtils::byteOrderFromString(value.toString(),
                LoggerWithContext(data->logger(), data->fullObjectPath())));
    }
    else if (name == s_datatype)
    {
        //change the type of the underlying object
        setDataType(value, data);
    }
    else if (name == s_updateFunc)
    {
        data->setUpdateFunc(value);
    }
    else if (name == s_validationFunc)
    {
        data->setValidationFunc(value);
    }
    else if (name == s_name)
    {
        data->setName(value.toString());
    }
    else if (name == s_customTypeName)
    {
        if (!value.isValid() || value.isNull() || value.isUndefined())
            data->setCustomTypeName(QString()); //unset
        else
            data->setCustomTypeName(value.toString());
    }
    else if (name == s_asStringFunc)
    {
        data->setToStringFunction(value);
    }
    else
    {
        bool setAdditional = setAdditionalProperty(data, name, id, value);
        if (setAdditional)
            return;
        else
        {
            data->logError() << "could not set property with name" << name.toString();
            engine()->currentContext()->throwError(QScriptContext::ReferenceError,
                QStringLiteral("Cannot write property ") + name.toString());
        }
    }
}
static void convertToPropertyType_impl(const QString &pathPropertiesBaseDir, const Item *item,
                                       const PropertyDeclaration& decl,
                                       const CodeLocation &location, QScriptValue &v)
{
    if (v.isUndefined() || v.isError())
        return;
    QString srcDir;
    QString actualBaseDir;
    if (item && !pathPropertiesBaseDir.isEmpty()) {
        const VariantValueConstPtr itemSourceDir
                = item->variantProperty(QLatin1String("sourceDirectory"));
        actualBaseDir = itemSourceDir ? itemSourceDir->value().toString() : pathPropertiesBaseDir;
    }
    switch (decl.type()) {
    case PropertyDeclaration::UnknownType:
    case PropertyDeclaration::Variant:
        break;
    case PropertyDeclaration::Boolean:
        if (!v.isBool())
            v = v.toBool();
        break;
    case PropertyDeclaration::Integer:
        if (!v.isNumber())
            makeTypeError(decl, location, v);
        break;
    case PropertyDeclaration::Path:
    {
        if (!v.isString()) {
            makeTypeError(decl, location, v);
            break;
        }
        const QString srcDir = item ? overriddenSourceDirectory(item, actualBaseDir)
                                    : pathPropertiesBaseDir;
        if (!srcDir.isEmpty())
            v = v.engine()->toScriptValue(QDir::cleanPath(
                                              FileInfo::resolvePath(srcDir, v.toString())));
        break;
    }
    case PropertyDeclaration::String:
        if (!v.isString())
            makeTypeError(decl, location, v);
        break;
    case PropertyDeclaration::PathList:
        srcDir = item ? overriddenSourceDirectory(item, actualBaseDir)
                      : pathPropertiesBaseDir;
        // Fall-through.
    case PropertyDeclaration::StringList:
    {
        if (!v.isArray()) {
            QScriptValue x = v.engine()->newArray(1);
            x.setProperty(0, v);
            v = x;
        }
        const quint32 c = v.property(StringConstants::lengthProperty()).toUInt32();
        for (quint32 i = 0; i < c; ++i) {
            QScriptValue elem = v.property(i);
            if (elem.isUndefined()) {
                ErrorInfo error(Tr::tr("Element at index %1 of list property '%2' is undefined. "
                                       "String expected.").arg(i).arg(decl.name()), location);
                makeTypeError(error, v);
                break;
            }
            if (elem.isNull()) {
                ErrorInfo error(Tr::tr("Element at index %1 of list property '%2' is null. "
                                       "String expected.").arg(i).arg(decl.name()), location);
                makeTypeError(error, v);
                break;
            }
            if (!elem.isString()) {
                ErrorInfo error(Tr::tr("Element at index %1 of list property '%2' does not have "
                                       "string type.").arg(i).arg(decl.name()), location);
                makeTypeError(error, v);
                break;
            }
            if (srcDir.isEmpty())
                continue;
            elem = v.engine()->toScriptValue(
                        QDir::cleanPath(FileInfo::resolvePath(srcDir, elem.toString())));
            v.setProperty(i, elem);
        }
        break;
    }
    case PropertyDeclaration::VariantList:
        if (!v.isArray()) {
            QScriptValue x = v.engine()->newArray(1);
            x.setProperty(0, v);
            v = x;
        }
        break;
    }
}
Example #28
0
void ReflectiveScriptClass::fromScriptValue(
        const QScriptValue& value, Node_ptr node)
{
    // std::cout << __FUNCTION__ << std::endl;

    using namespace gsim::core;

    const descriptor_type type =
        node->descriptor->get_type();

    node->check_for_initialized();

    holder& hold = node->holder;
    descriptor_base const * descriptor = node->descriptor;

    switch(type)
    {

        case TYPE_STRUCT:
            {
                if (value.isObject())
                {
                    unsigned int count = 
                        node->descriptor->get_children_count();

                    // Search by name
                    for (unsigned int i = 0; i < count; i++) 
                    {
                        const char *childName = descriptor->get_child_name(i);
                        QScriptValue childValue = value.property(childName);

                        if (childValue.isValid())
                            fromScriptValue(childValue, node->children[i]);
                    }
                }
                else
                {
                    std::cerr << "Must be an object!" << std::endl;
                }
            }
            break;

        case TYPE_ARRAY:
            if (descriptor->get_slice()->get_type() == TYPE_CHAR)
            {
                const std::string str(value.toString().toStdString());
                descriptor->from_string(hold, str);
                break;
            }
        case TYPE_SEQUENCE:
            {
                unsigned int length = descriptor->get_length(hold);
                unsigned int newLength = value.property("length").toUInt32();

                if (descriptor->is_variable_length() &&
                        length != newLength)
                {
                    descriptor->set_length(hold, newLength);

                    node->reset();
                    node->check_for_initialized();
                }

                for (unsigned int i = 0; i < newLength && i < length; i++) 
                {
                    fromScriptValue(value.property(i),
                            node->children[i]);
                }
            }
            break;

        case TYPE_BOOL:
            hold.to_value< bool >() = value.toBool();
            break;
        case TYPE_OCTET:
            hold.to_value< unsigned char >() = value.toInteger();
            break;
        case TYPE_CHAR:
            hold.to_value< char >() = value.toInteger();
            break;
        case TYPE_SHORT:
            hold.to_value< short >() = value.toInteger();
            break;
        case TYPE_USHORT:
            hold.to_value< unsigned short >() = value.toUInt16();
            break;
        case TYPE_LONG:
            hold.to_value< int32_t >() = value.toInteger();
            break;
        case TYPE_ULONG:
            hold.to_value< uint32_t >() = value.toUInt32();
            break;
        case TYPE_LONGLONG:
            hold.to_value< int64_t >() = value.toInteger();
            break;
        case TYPE_ULONGLONG:
            hold.to_value< uint64_t >() = value.toInteger();
            break;

        case TYPE_STRING:
        case TYPE_WSTRING:
            {
                const std::string str(value.toString().toStdString());
                descriptor->from_string(hold, str);
            }
            break;

        case TYPE_ENUM:
            {
                const unsigned int count = descriptor->get_children_count();

                const QString str (value.toString());

                unsigned int idx = 
                    descriptor->get_child_index(
                            str.toStdString().c_str());

                if (idx < count)
                {
                    core::holder tmp(
                            descriptor->get_child_value(hold, idx));
                    descriptor->copy(tmp, hold);
                }

                // TODO debería devolverse excepción si se introdujo
                // un literal no válido.
            }
            break;

        case TYPE_DOUBLE:
            hold.to_value< double >() = value.toNumber();
            break;
        case TYPE_FLOAT:
            hold.to_value< float >() = value.toNumber();
        default:
            break;
    }

}
Example #29
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;
    }
}
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);
        }
    }
}