Beispiel #1
0
void quatFromScriptValue(const QScriptValue &object, glm::quat& quat) {
    quat.x = object.property("x").toVariant().toFloat();
    quat.y = object.property("y").toVariant().toFloat();
    quat.z = object.property("z").toVariant().toFloat();
    quat.w = object.property("w").toVariant().toFloat();
}
Beispiel #2
0
void ScriptEngine::run() {
    if (!_isInitialized) {
        init();
    }
    _isRunning = true;
    _isFinished = false;
    emit runningStateChanged();

    QScriptValue result = evaluate(_scriptContents);
    if (hasUncaughtException()) {
        int line = uncaughtExceptionLineNumber();
        qDebug() << "Uncaught exception at (" << _fileNameString << ") line" << line << ":" << result.toString();
        emit errorMessage("Uncaught exception at (" + _fileNameString + ") line" + QString::number(line) + ":" + result.toString());
        clearExceptions();
    }

    QElapsedTimer startTime;
    startTime.start();

    int thisFrame = 0;

    NodeList* nodeList = NodeList::getInstance();

    qint64 lastUpdate = usecTimestampNow();

    while (!_isFinished) {
        int usecToSleep = (thisFrame++ * SCRIPT_DATA_CALLBACK_USECS) - startTime.nsecsElapsed() / 1000; // nsec to usec
        if (usecToSleep > 0) {
            usleep(usecToSleep);
        }

        if (_isFinished) {
            break;
        }

        QCoreApplication::processEvents();

        if (_isFinished) {
            break;
        }

        if (_voxelsScriptingInterface.getVoxelPacketSender()->serversExist()) {
            // release the queue of edit voxel messages.
            _voxelsScriptingInterface.getVoxelPacketSender()->releaseQueuedMessages();

            // since we're in non-threaded mode, call process so that the packets are sent
            if (!_voxelsScriptingInterface.getVoxelPacketSender()->isThreaded()) {
                _voxelsScriptingInterface.getVoxelPacketSender()->process();
            }
        }

        if (_particlesScriptingInterface.getParticlePacketSender()->serversExist()) {
            // release the queue of edit voxel messages.
            _particlesScriptingInterface.getParticlePacketSender()->releaseQueuedMessages();

            // since we're in non-threaded mode, call process so that the packets are sent
            if (!_particlesScriptingInterface.getParticlePacketSender()->isThreaded()) {
                _particlesScriptingInterface.getParticlePacketSender()->process();
            }
        }

        if (_entityScriptingInterface.getEntityPacketSender()->serversExist()) {
            // release the queue of edit voxel messages.
            _entityScriptingInterface.getEntityPacketSender()->releaseQueuedMessages();

            // since we're in non-threaded mode, call process so that the packets are sent
            if (!_entityScriptingInterface.getEntityPacketSender()->isThreaded()) {
                _entityScriptingInterface.getEntityPacketSender()->process();
            }
        }

        if (_isAvatar && _avatarData) {

            const int SCRIPT_AUDIO_BUFFER_SAMPLES = floor(((SCRIPT_DATA_CALLBACK_USECS * SAMPLE_RATE) / (1000 * 1000)) + 0.5);
            const int SCRIPT_AUDIO_BUFFER_BYTES = SCRIPT_AUDIO_BUFFER_SAMPLES * sizeof(int16_t);

            QByteArray avatarPacket = byteArrayWithPopulatedHeader(PacketTypeAvatarData);
            avatarPacket.append(_avatarData->toByteArray());

            nodeList->broadcastToNodes(avatarPacket, NodeSet() << NodeType::AvatarMixer);

            if (_isListeningToAudioStream || _avatarSound) {
                // if we have an avatar audio stream then send it out to our audio-mixer
                bool silentFrame = true;

                int16_t numAvailableSamples = SCRIPT_AUDIO_BUFFER_SAMPLES;
                const int16_t* nextSoundOutput = NULL;

                if (_avatarSound) {

                    const QByteArray& soundByteArray = _avatarSound->getByteArray();
                    nextSoundOutput = reinterpret_cast<const int16_t*>(soundByteArray.data()
                                                                       + _numAvatarSoundSentBytes);

                    int numAvailableBytes = (soundByteArray.size() - _numAvatarSoundSentBytes) > SCRIPT_AUDIO_BUFFER_BYTES
                        ? SCRIPT_AUDIO_BUFFER_BYTES
                        : soundByteArray.size() - _numAvatarSoundSentBytes;
                    numAvailableSamples = numAvailableBytes / sizeof(int16_t);


                    // check if the all of the _numAvatarAudioBufferSamples to be sent are silence
                    for (int i = 0; i < numAvailableSamples; ++i) {
                        if (nextSoundOutput[i] != 0) {
                            silentFrame = false;
                            break;
                        }
                    }

                    _numAvatarSoundSentBytes += numAvailableBytes;
                    if (_numAvatarSoundSentBytes == soundByteArray.size()) {
                        // we're done with this sound object - so set our pointer back to NULL
                        // and our sent bytes back to zero
                        _avatarSound = NULL;
                        _numAvatarSoundSentBytes = 0;
                    }
                }
                
                QByteArray audioPacket = byteArrayWithPopulatedHeader(silentFrame
                                                                      ? PacketTypeSilentAudioFrame
                                                                      : PacketTypeMicrophoneAudioNoEcho);

                QDataStream packetStream(&audioPacket, QIODevice::Append);

                // pack a placeholder value for sequence number for now, will be packed when destination node is known
                int numPreSequenceNumberBytes = audioPacket.size();
                packetStream << (quint16) 0;

                if (silentFrame) {
                    if (!_isListeningToAudioStream) {
                        // if we have a silent frame and we're not listening then just send nothing and break out of here
                        break;
                    }

                    // write the number of silent samples so the audio-mixer can uphold timing
                    packetStream.writeRawData(reinterpret_cast<const char*>(&SCRIPT_AUDIO_BUFFER_SAMPLES), sizeof(int16_t));

                    // use the orientation and position of this avatar for the source of this audio
                    packetStream.writeRawData(reinterpret_cast<const char*>(&_avatarData->getPosition()), sizeof(glm::vec3));
                    glm::quat headOrientation = _avatarData->getHeadOrientation();
                    packetStream.writeRawData(reinterpret_cast<const char*>(&headOrientation), sizeof(glm::quat));

                } else if (nextSoundOutput) {
                    // assume scripted avatar audio is mono and set channel flag to zero
                    packetStream << (quint8)0;

                    // use the orientation and position of this avatar for the source of this audio
                    packetStream.writeRawData(reinterpret_cast<const char*>(&_avatarData->getPosition()), sizeof(glm::vec3));
                    glm::quat headOrientation = _avatarData->getHeadOrientation();
                    packetStream.writeRawData(reinterpret_cast<const char*>(&headOrientation), sizeof(glm::quat));

                    // write the raw audio data
                    packetStream.writeRawData(reinterpret_cast<const char*>(nextSoundOutput), numAvailableSamples * sizeof(int16_t));
                }
                
                // write audio packet to AudioMixer nodes
                NodeList* nodeList = NodeList::getInstance();
                foreach(const SharedNodePointer& node, nodeList->getNodeHash()) {
                    // only send to nodes of type AudioMixer
                    if (node->getType() == NodeType::AudioMixer) {
                        // pack sequence number
                        quint16 sequence = _outgoingScriptAudioSequenceNumbers[node->getUUID()]++;
                        memcpy(audioPacket.data() + numPreSequenceNumberBytes, &sequence, sizeof(quint16));

                        // send audio packet
                        nodeList->writeDatagram(audioPacket, node);
                    }
                }
            }
        }

        qint64 now = usecTimestampNow();
        float deltaTime = (float) (now - lastUpdate) / (float) USECS_PER_SECOND;

        if (hasUncaughtException()) {
            int line = uncaughtExceptionLineNumber();
            qDebug() << "Uncaught exception at (" << _fileNameString << ") line" << line << ":" << uncaughtException().toString();
            emit errorMessage("Uncaught exception at (" + _fileNameString + ") line" + QString::number(line) + ":" + uncaughtException().toString());
            clearExceptions();
        }

        emit update(deltaTime);
        lastUpdate = now;
    }
Beispiel #3
0
void inputControllerFromScriptValue(const QScriptValue &object, AbstractInputController* &out) {
    out = qobject_cast<AbstractInputController*>(object.toQObject());
}
static QScriptValue qtscript_QProcess_ExitStatus_toScriptValue(QScriptEngine *engine, const QProcess::ExitStatus &value)
{
    QScriptValue clazz = engine->globalObject().property(QString::fromLatin1("QProcess"));
    return clazz.property(qtscript_QProcess_ExitStatus_toStringHelper(value));
}
static void qtscript_QProcess_fromScriptValue(const QScriptValue &value, QProcess* &out)
{
    out = qobject_cast<QProcess*>(value.toQObject());
}
Beispiel #6
0
QScriptValue DefaultScriptClass::property(const QScriptValue& object, const QScriptString& name, uint id)
{
    Q_ASSERT(mHandlerInfo->mode() != ScriptHandlerInfo::None);
    DataInformation* data = toDataInformation(object);
    if (!data)
    {
        mHandlerInfo->logger()->error() << "could not cast data from" << object.data().toString();
        return engine()->currentContext()->throwError(QScriptContext::ReferenceError,
                QStringLiteral("Attempting to access an invalid object"));
    }
    if (name == s_valid)
    {
        return data->validationSuccessful();
    }
    else if (name == s_wasAbleToRead)
    {
        return data->wasAbleToRead();
    }
    else if (name == s_parent)
    {
        Q_CHECK_PTR(data->parent());
        //parent() cannot be null
        if (data->parent()->isTopLevel())
            return engine()->nullValue();
        return data->parent()->asDataInformation()->toScriptValue(engine(), mHandlerInfo);
    }
    else if (name == s_datatype)
    {
        return data->typeName();
    }
    else if (name == s_updateFunc)
    {
        return data->updateFunc();
    }
    else if (name == s_validationFunc)
    {
        return data->validationFunc();
    }
    else if (name == s_validationError)
    {
        return data->validationError();
    }
    else if (name == s_byteOrder)
    {
        return ParserUtils::byteOrderToString(data->byteOrder());
    }
    else if (name == s_name)
    {
        return data->name();
    }
    else if (name == s_customTypeName)
    {
        return data->typeName();
    }
    else if (name == s_asStringFunc)
    {
        return data->toStringFunction();
    }
    QScriptValue other = additionalProperty(data, name, id);
    if (other.isValid())
        return other;
    else
    {
        data->logError() << "could not find property with name" << name.toString();
        return engine()->currentContext()->throwError(QScriptContext::ReferenceError,
                QStringLiteral("Cannot read property ") + name.toString());
    }
}
void tst_QScriptJSTestSuite::runTestFunction(int testIndex)
{
    if (!(testIndex & 1)) {
        // data
        QTest::addColumn<TestRecord>("record");
        bool hasData = false;

        QString testsShellPath = testsDir.absoluteFilePath("shell.js");
        QString testsShellContents = readFile(testsShellPath);

        QDir subSuiteDir(subSuitePaths.at(testIndex / 2));
        QString subSuiteShellPath = subSuiteDir.absoluteFilePath("shell.js");
        QString subSuiteShellContents = readFile(subSuiteShellPath);

        QDir testSuiteDir(subSuiteDir);
        testSuiteDir.cdUp();
        QString suiteJsrefPath = testSuiteDir.absoluteFilePath("jsref.js");
        QString suiteJsrefContents = readFile(suiteJsrefPath);
        QString suiteShellPath = testSuiteDir.absoluteFilePath("shell.js");
        QString suiteShellContents = readFile(suiteShellPath);

        QFileInfoList testFileInfos = subSuiteDir.entryInfoList(QStringList() << "*.js", QDir::Files);
        foreach (QFileInfo tfi, testFileInfos) {
            if ((tfi.fileName() == "shell.js") || (tfi.fileName() == "browser.js"))
                continue;

            QString abspath = tfi.absoluteFilePath();
            QString relpath = testsDir.relativeFilePath(abspath);
            QString excludeMessage;
            if (isExcludedFile(relpath, &excludeMessage)) {
                QTest::newRow(relpath.toLatin1()) << TestRecord(excludeMessage, relpath);
                continue;
            }

            QScriptEngine eng;
            QScriptValue global = eng.globalObject();
            global.setProperty("print", eng.newFunction(qscript_void));
            global.setProperty("quit", eng.newFunction(qscript_quit));
            global.setProperty("options", eng.newFunction(qscript_options));

            eng.evaluate(testsShellContents, testsShellPath);
            if (eng.hasUncaughtException()) {
                QStringList bt = eng.uncaughtExceptionBacktrace();
                QString err = eng.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
                break;
            }

            eng.evaluate(suiteJsrefContents, suiteJsrefPath);
            if (eng.hasUncaughtException()) {
                QStringList bt = eng.uncaughtExceptionBacktrace();
                QString err = eng.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
                break;
            }

            eng.evaluate(suiteShellContents, suiteShellPath);
            if (eng.hasUncaughtException()) {
                QStringList bt = eng.uncaughtExceptionBacktrace();
                QString err = eng.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
                break;
            }

            eng.evaluate(subSuiteShellContents, subSuiteShellPath);
            if (eng.hasUncaughtException()) {
                QStringList bt = eng.uncaughtExceptionBacktrace();
                QString err = eng.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
                break;
            }

            QScriptValue origTestCaseCtor = global.property("TestCase");
            QScriptValue myTestCaseCtor = eng.newFunction(qscript_TestCase);
            myTestCaseCtor.setData(origTestCaseCtor);
            global.setProperty("TestCase", myTestCaseCtor);

            global.setProperty("gTestfile", tfi.fileName());
            global.setProperty("gTestsuite", testSuiteDir.dirName());
            global.setProperty("gTestsubsuite", subSuiteDir.dirName());
            QString testFileContents = readFile(abspath);
//                qDebug() << relpath;
            eng.evaluate(testFileContents, abspath);
            if (eng.hasUncaughtException() && !relpath.endsWith("-n.js")) {
                QStringList bt = eng.uncaughtExceptionBacktrace();
                QString err = eng.uncaughtException().toString();
                qWarning("%s\n%s\n", qPrintable(err), qPrintable(bt.join("\n")));
                continue;
            }

            QScriptValue testcases = global.property("testcases");
            if (!testcases.isArray())
                testcases = global.property("gTestcases");
            int count = testcases.property("length").toInt32();
            if (count == 0)
                continue;

            hasData = true;
            QString title = global.property("TITLE").toString();
            for (int i = 0; i < count; ++i) {
                QScriptValue kase = testcases.property(i);
                QString description = kase.property("description").toString();
                QScriptValue expect = kase.property("expect");
                QScriptValue actual = kase.property("actual");
                bool passed = kase.property("passed").toBoolean();
                int lineNumber = kase.property("__lineNumber__").toInt32();

                TestRecord rec(description, passed,
                               actual.toString(), expect.toString(),
                               relpath, lineNumber);

                QTest::newRow(description.toLatin1()) << rec;
            }
        }
        if (!hasData)
            QTest::newRow("") << TestRecord(); // dummy
    } else {
Beispiel #8
0
void vec4FromScriptValue(const QScriptValue& object, glm::vec4& vec4) {
    vec4.x = object.property("x").toVariant().toFloat();
    vec4.y = object.property("y").toVariant().toFloat();
    vec4.z = object.property("z").toVariant().toFloat();
    vec4.w = object.property("w").toVariant().toFloat();
}
Beispiel #9
0
void vec3FromScriptValue(const QScriptValue &object, glm::vec3 &vec3) {
    vec3.x = object.property("x").toVariant().toFloat();
    vec3.y = object.property("y").toVariant().toFloat();
    vec3.z = object.property("z").toVariant().toFloat();
}
Beispiel #10
0
QScriptValue qSizeFToScriptValue(QScriptEngine* engine, const QSizeF& qSizeF) {
    QScriptValue obj = engine->newObject();
    obj.setProperty("width", qSizeF.width());
    obj.setProperty("height", qSizeF.height());
    return obj;
}
Beispiel #11
0
void qSizeFFromScriptValue(const QScriptValue& object, QSizeF& qSizeF) {
    qSizeF.setWidth(object.property("width").toVariant().toFloat());
    qSizeF.setHeight(object.property("height").toVariant().toFloat());
}
Beispiel #12
0
void qURLFromScriptValue(const QScriptValue& object, QUrl& url) {
    url = object.toString();
}
Beispiel #13
0
void xColorFromScriptValue(const QScriptValue &object, xColor& color) {
    color.red = object.property("red").toVariant().toInt();
    color.green = object.property("green").toVariant().toInt();
    color.blue = object.property("blue").toVariant().toInt();
}
Beispiel #14
0
void qRectFromScriptValue(const QScriptValue &object, QRect& rect) {
    rect.setX(object.property("x").toVariant().toInt());
    rect.setY(object.property("y").toVariant().toInt());
    rect.setWidth(object.property("width").toVariant().toInt());
    rect.setHeight(object.property("height").toVariant().toInt());
}
static void qtscript_QPropertyAnimation_fromScriptValue(const QScriptValue &value, QPropertyAnimation* &out)
{
    out = qobject_cast<QPropertyAnimation*>(value.toQObject());
}
void PainterPathClass::fromScriptValue(const QScriptValue& obj, QPainterPath& pp)
{
    pp = qvariant_cast<QPainterPath>(obj.data().toVariant());
}
                 void REcmaAddObjectOperation::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RAddObjectOperation*) 0)));
        protoCreated = true;
    }

    
        // primary base class RAddObjectsOperation:
        
            QScriptValue dpt = engine.defaultPrototype(
                qMetaTypeId<RAddObjectsOperation*>());

            if (dpt.isValid()) {
                proto->setPrototype(dpt);
            }
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RAddObjectsOperation
        REcmaHelper::registerFunction(&engine, proto, getRAddObjectsOperation, "getRAddObjectsOperation");
        
        // conversion for base class ROperation
        REcmaHelper::registerFunction(&engine, proto, getROperation, "getROperation");
        
        // conversion for base class RRequireHeap
        REcmaHelper::registerFunction(&engine, proto, getRRequireHeap, "getRRequireHeap");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
        engine.setDefaultPrototype(
            qMetaTypeId<RAddObjectOperation*>(), *proto);

        
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    

    // static properties:
    

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RAddObjectOperation",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
Beispiel #18
0
QScriptValue ScShiftDatabase::addType(QScriptContext *ctx, QScriptEngine *engine)
  {
  ScProfileFunction
  SProperty **propPtr = getThis(ctx);
  SDatabase *db = 0;
  if(propPtr)
    {
    db = (*propPtr)->uncheckedCastTo<SDatabase>();
    }
  if(!db)
    {
    ctx->throwError(QScriptContext::SyntaxError, "Incorrect this argument to SPropertyContainer.size(...);");
    }

  if(ctx->argumentCount() != 1)
    {
    ctx->throwError(QScriptContext::SyntaxError, "Incorrect number of arguments to SDatabase.addType(...);");
    return QScriptValue();
    }

  QScriptValue typeObject = ctx->argument(0);
  if(!typeObject.isObject())
    {
    ctx->throwError(QScriptContext::SyntaxError, "Incorrect argument type to SDatabase.addType(...); expected object");
    return QScriptValue();
    }

  QScriptValue tempObject;

  tempObject = typeObject.property("name");
  QString name = tempObject.toString();
  if(name == "" || STypeRegistry::findType(name) != 0)
    {
    ctx->throwError(QScriptContext::SyntaxError, "Unique, non zero-lengthed string expected as 'name' property");
    return QScriptValue();
    }

  tempObject = typeObject.property("parent");
  const SPropertyInformation *parent = 0;
  if(tempObject.isString())
    {
    parent = STypeRegistry::findType(tempObject.toString());
    }
  if(parent == 0)
    {
    ctx->throwError(QScriptContext::SyntaxError, "Defined property type expected as 'parent' property");
    return QScriptValue();
    }

  tempObject = typeObject.property("version");
  xuint32 version = tempObject.toUInt32();

  xsize endOfUsedMemory = parent->dynamicSize();
  QList<SPropertyInstanceInformation*> properties;

  tempObject = typeObject.property("properties");
  if(tempObject.isArray())
    {
    xuint32 i = 0;
    QScriptValue val = tempObject.property(i);
    QScriptValue tempArrayObject;
    while(val.isObject())
      {
      tempArrayObject = val.property("name");
      if(!tempArrayObject.isString())
        {
        ctx->throwError(QScriptContext::SyntaxError, "String expected as 'properties' array 'name' entry");
        break;
        }
      QString propName = tempArrayObject.toString();

      tempArrayObject = val.property("type");
      const SPropertyInformation *propType = 0;
      if(tempArrayObject.isString())
        {
        propType = STypeRegistry::findType(tempArrayObject.toString());
        }
      if(!propType)
        {
        ctx->throwError(QScriptContext::SyntaxError, "String expected as 'properties' array 'type' entry");
        break;
        }

      SPropertyInstanceInformation::ComputeFunction computeFn = 0;
      tempArrayObject = val.property("compute");
      if(tempArrayObject.isFunction())
        {
        computeFn = computeNode;
        }

      SPropertyInstanceInformation *info = propType->createInstanceInformation()(propType, propName, i, *reinterpret_cast<SProperty SPropertyContainer::**>(&endOfUsedMemory));
      info->setCompute(computeFn);
      info->setExtra(true);

      endOfUsedMemory += propType->size();
      properties << info;

      if(computeFn)
        {
        info->setData(g_computeKey, qVariantFromValue(tempArrayObject));
        }

      val = tempObject.property(++i);
      }

    i = 0;
    val = tempObject.property(i);
    while(val.isObject())
      {
      SProperty SPropertyContainer::* *affects = 0;
      tempArrayObject = val.property("affects");
      bool affectsIsValid = false;
      if(tempArrayObject.isArray())
        {
        affectsIsValid = true;
        xuint32 length = tempArrayObject.property("length").toUInt32();
        affects = new SProperty SPropertyContainer::* [length+1];
        affects[length] = 0;
        for(xuint32 i=0; i<length; ++i)
          {
          affects[i] = 0;
          QString name = tempArrayObject.property(i).toString();

          for(int propIdx=0, s=properties.size(); propIdx<s; ++propIdx)
            {
            if(name == properties[propIdx]->name())
              {
              affects[i] = properties[propIdx]->location();
              break;
              }
            }

          if(!affects[i])
            {
            affectsIsValid = false;
            ctx->throwError(QScriptContext::SyntaxError, "Defined sibling property name expected for affectedBy members.");
            break;
            }
          }
        }

      if(!affectsIsValid)
        {
        delete [] affects;
        affects = 0;
        }


      SPropertyInstanceInformation *info = properties[i];
      info->setAffects(affects);


      val = tempObject.property(++i);
      }
    }

#warning check what happens if you embed a script type in a script type... etc, i think it will crash and burn?
  SPropertyInformation *newType = new SPropertyInformation(*parent);

  newType->setVersion(version);
  newType->typeName() = name;
  newType->setParentTypeInformation(parent);
  newType->setSize(endOfUsedMemory);

  newType->children() << parent->children() << properties;

  STypeRegistry::addType(newType);

  return QScriptValue();
  }
Beispiel #19
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());
        }
    }
}
                 void REcmaSharedPointerDimRadialEntity::initEcma(QScriptEngine& engine, QScriptValue* proto 
    
    ) 
    
    {

    bool protoCreated = false;
    if(proto == NULL){
        proto = new QScriptValue(engine.newVariant(qVariantFromValue(
                (RDimRadialEntityPointer*) 0)));
        protoCreated = true;
    }

    
        // primary base class RDimensionEntity:
        
            proto->setPrototype(engine.defaultPrototype(
            qMetaTypeId<RDimensionEntityPointer>()));
          
        /*
        
        */
    

    QScriptValue fun;

    // toString:
    REcmaHelper::registerFunction(&engine, proto, toString, "toString");
    
        // shared pointer support:
        REcmaHelper::registerFunction(&engine, proto, data, "data");
        

        REcmaHelper::registerFunction(&engine, proto, isNull, "isNull");
        

    // destroy:
    REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
    
        // conversion for base class RDimensionEntity
        REcmaHelper::registerFunction(&engine, proto, getRDimensionEntity, "getRDimensionEntity");
        
        // conversion for base class REntity
        REcmaHelper::registerFunction(&engine, proto, getREntity, "getREntity");
        
        // conversion for base class RObject
        REcmaHelper::registerFunction(&engine, proto, getRObject, "getRObject");
        

    // get class name
    REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
    

    // conversion to all base classes (multiple inheritance):
    REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
    

    // properties:
    

    // methods:
    
            REcmaHelper::registerFunction(&engine, proto, clone, "clone");
            
            REcmaHelper::registerFunction(&engine, proto, getType, "getType");
            
            REcmaHelper::registerFunction(&engine, proto, setProperty, "setProperty");
            
            REcmaHelper::registerFunction(&engine, proto, getProperty, "getProperty");
            
            REcmaHelper::registerFunction(&engine, proto, getData, "getData");
            
            REcmaHelper::registerFunction(&engine, proto, setData, "setData");
            
            REcmaHelper::registerFunction(&engine, proto, setChordPoint, "setChordPoint");
            
            REcmaHelper::registerFunction(&engine, proto, getChordPoint, "getChordPoint");
            
        engine.setDefaultPrototype(
            qMetaTypeId<RDimRadialEntityPointer>(), *proto);
      
    

    QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
    
    // static methods:
    
            REcmaHelper::registerFunction(&engine, &ctor, init, "init");
            
            REcmaHelper::registerFunction(&engine, &ctor, getStaticPropertyTypeIds, "getStaticPropertyTypeIds");
            

    // static properties:
    
            ctor.setProperty("PropertyCustom",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyCustom),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyHandle",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyHandle),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyProtected",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyProtected),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyType",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyType),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyBlock",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyBlock),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLayer",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyLayer),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLinetype",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyLinetype),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLinetypeScale",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyLinetypeScale),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLineweight",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyLineweight),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyColor",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyColor),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyDisplayedColor",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyDisplayedColor),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyDrawOrder",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyDrawOrder),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyMiddleOfTextX",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyMiddleOfTextX),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyMiddleOfTextY",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyMiddleOfTextY),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyMiddleOfTextZ",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyMiddleOfTextZ),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyText",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyText),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyUpperTolerance",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyUpperTolerance),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLowerTolerance",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyLowerTolerance),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyMeasuredValue",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyMeasuredValue),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyLinearFactor",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyLinearFactor),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyDimScale",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyDimScale),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyDimBlockName",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyDimBlockName),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyAutoTextPos",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyAutoTextPos),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyFontName",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyFontName),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyCenterPointX",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyCenterPointX),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyCenterPointY",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyCenterPointY),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyCenterPointZ",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyCenterPointZ),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyChordPointX",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyChordPointX),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyChordPointY",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyChordPointY),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            
            ctor.setProperty("PropertyChordPointZ",
                qScriptValueFromValue(&engine, RDimRadialEntity::PropertyChordPointZ),
                QScriptValue::SkipInEnumeration | QScriptValue::ReadOnly);
            

    // enum values:
    

    // enum conversions:
    
        
    // init class:
    engine.globalObject().setProperty("RDimRadialEntityPointer",
    ctor, QScriptValue::SkipInEnumeration);
    
    if( protoCreated ){
       delete proto;
    }
    
    }
static void qtscript_QProcess_ProcessState_fromScriptValue(const QScriptValue &value, QProcess::ProcessState &out)
{
    out = qvariant_cast<QProcess::ProcessState>(value.toVariant());
}
Beispiel #22
0
//! [35]
QScriptValue Person_prototype_toString(QScriptContext *context, QScriptEngine *engine)
{
  QString name = context->thisObject().property("name").toString();
  QString result = QString::fromLatin1("Person(name: %0)").arg(name);
  return result;
}
//! [35]


//! [36]
QScriptEngine engine;
QScriptValue ctor = engine.newFunction(Person_ctor);
ctor.property("prototype").setProperty("toString", engine.newFunction(Person_prototype_toString));
QScriptValue global = engine.globalObject();
global.setProperty("Person", ctor);
//! [36]


//! [37]
QScriptValue Employee_ctor(QScriptContext *context, QScriptEngine *engine)
{
  QScriptValue super = context->callee().property("prototype").property("constructor");
  super.call(context->thisObject(), QScriptValueList() << context->argument(0));
  context->thisObject().setProperty("salary", context->argument(1));
  return engine->undefinedValue();
}
//! [37]

static void qtscript_QProcess_ExitStatus_fromScriptValue(const QScriptValue &value, QProcess::ExitStatus &out)
{
    out = qvariant_cast<QProcess::ExitStatus>(value.toVariant());
}
Beispiel #24
0
//! [67]
QScriptValue sort(QScriptContext *ctx, QScriptEngine *eng)
{
    QScriptValue comparefn = ctx->argument(0);
    if (comparefn.isUndefined())
        comparefn = /* the built-in comparison function */;
    else if (!comparefn.isFunction())
QScriptValue qtscript_create_QProcess_class(QScriptEngine *engine)
{
    static const int function_lengths[] = {
        1
        // static
        , 2
        , 4
        , 0
        // prototype
        , 1
        , 0
        , 0
        , 0
        , 0
        , 0
        , 0
        , 0
        , 0
        , 0
        , 1
        , 1
        , 1
        , 2
        , 1
        , 2
        , 1
        , 1
        , 3
        , 0
        , 1
        , 1
        , 0
        , 0
    };
    engine->setDefaultPrototype(qMetaTypeId<QProcess*>(), QScriptValue());
    QScriptValue proto = engine->newVariant(qVariantFromValue((QProcess*)0));
    proto.setPrototype(engine->defaultPrototype(qMetaTypeId<QIODevice*>()));
    for (int i = 0; i < 24; ++i) {
        QScriptValue fun = engine->newFunction(qtscript_QProcess_prototype_call, function_lengths[i+4]);
        fun.setData(QScriptValue(engine, uint(0xBABE0000 + i)));
        proto.setProperty(QString::fromLatin1(qtscript_QProcess_function_names[i+4]),
            fun, QScriptValue::SkipInEnumeration);
    }

    qScriptRegisterMetaType<QProcess*>(engine, qtscript_QProcess_toScriptValue, 
        qtscript_QProcess_fromScriptValue, proto);

    QScriptValue ctor = engine->newFunction(qtscript_QProcess_static_call, proto, function_lengths[0]);
    ctor.setData(QScriptValue(engine, uint(0xBABE0000 + 0)));
    for (int i = 0; i < 3; ++i) {
        QScriptValue fun = engine->newFunction(qtscript_QProcess_static_call,
            function_lengths[i+1]);
        fun.setData(QScriptValue(engine, uint(0xBABE0000 + i+1)));
        ctor.setProperty(QString::fromLatin1(qtscript_QProcess_function_names[i+1]),
            fun, QScriptValue::SkipInEnumeration);
    }

    ctor.setProperty(QString::fromLatin1("ProcessError"),
        qtscript_create_QProcess_ProcessError_class(engine, ctor));
    ctor.setProperty(QString::fromLatin1("ProcessChannelMode"),
        qtscript_create_QProcess_ProcessChannelMode_class(engine, ctor));
    ctor.setProperty(QString::fromLatin1("ProcessChannel"),
        qtscript_create_QProcess_ProcessChannel_class(engine, ctor));
    ctor.setProperty(QString::fromLatin1("ProcessState"),
        qtscript_create_QProcess_ProcessState_class(engine, ctor));
    ctor.setProperty(QString::fromLatin1("ExitStatus"),
        qtscript_create_QProcess_ExitStatus_class(engine, ctor));
    return ctor;
}
Beispiel #26
0
//! [74]
QScriptValue counter_hybrid(QScriptContext *ctx, QScriptEngine *eng)
{
    QScriptValue act = ctx->activationObject();
    act.setProperty("count", 0);
    return eng->evaluate("(function() { return count++; })");
}
Beispiel #27
0
void injectorFromScriptValue(const QScriptValue &object, AudioInjector* &out) {
    out = qobject_cast<AudioInjector*>(object.toQObject());
}
Beispiel #28
0
QScriptObjectSnapshot::Delta QScriptObjectSnapshot::capture(const QScriptValue &object)
{
    Delta result;
    QMap<QString, QScriptValueProperty> currProps;
    QHash<QString, int> propertyNameToIndex;
    {
        int i = 0;
        QScriptValueIterator it(object);
        while (it.hasNext()) {
            it.next();
            QScriptValueProperty prop(it.name(), it.value(), it.flags());
            currProps.insert(it.name(), prop);
            propertyNameToIndex.insert(it.name(), i);
            ++i;
        }
        if (object.prototype().isValid()) {
            QString __proto__ = QString::fromLatin1("__proto__");
            QScriptValueProperty protoProp(
                __proto__, object.prototype(),
                QScriptValue::Undeletable | QScriptValue::ReadOnly);
            currProps.insert(__proto__, protoProp);
            propertyNameToIndex.insert(__proto__, i);
            ++i;
        }
    }

    QSet<QString> prevSet;
    for (int i = 0; i < m_properties.size(); ++i)
        prevSet.insert(m_properties.at(i).name());
    QSet<QString> currSet = currProps.keys().toSet();
    QSet<QString> removedProperties = prevSet - currSet;
    QSet<QString> addedProperties = currSet - prevSet;
    QSet<QString> maybeChangedProperties = currSet & prevSet;

    {
        QMap<int, QScriptValueProperty> am;
        QSet<QString>::const_iterator it;
        for (it = addedProperties.constBegin(); it != addedProperties.constEnd(); ++it) {
            int idx = propertyNameToIndex[*it];
            am[idx] = currProps[*it];
        }
        result.addedProperties = am.values();
    }

    {
        QSet<QString>::const_iterator it;
        for (it = maybeChangedProperties.constBegin(); it != maybeChangedProperties.constEnd(); ++it) {
            const QScriptValueProperty &p1 = currProps[*it];
            const QScriptValueProperty &p2 = findProperty(*it);
            if (!_q_equal(p1.value(), p2.value())
                || (p1.flags() != p2.flags())) {
                result.changedProperties.append(p1);
            }
        }
    }

    result.removedProperties = removedProperties.toList();

    m_properties = currProps.values();

    return result;
}
Beispiel #29
0
int tst_Suite::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        QString name = testNames.at(_id);
        QString path = testsDir.absoluteFilePath(name + ".js");
        QString excludeMessage;
        if (isExcludedTest(name, &excludeMessage)) {
            QTest::qSkip(excludeMessage.toLatin1(), QTest::SkipAll, path.toLatin1(), -1);
        } else {
            QScriptEngine engine;
            engine.evaluate(mjsunitContents).toString();
            if (engine.hasUncaughtException()) {
                QStringList bt = engine.uncaughtExceptionBacktrace();
                QString err = engine.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
            } else {
                QScriptValue fakeFail = engine.newFunction(qscript_fail);
                fakeFail.setData(engine.globalObject().property("fail"));
                engine.globalObject().setProperty("fail", fakeFail);
                QString contents = readFile(path);
                QScriptValue ret = engine.evaluate(contents);
                if (engine.hasUncaughtException()) {
                    if (!ret.isError()) {
                        Q_ASSERT(ret.instanceOf(engine.globalObject().property("MjsUnitAssertionError")));
                        QString actual = ret.property("actual").toString();
                        QString expected = ret.property("expected").toString();
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QString failMessage;
                        if (isExpectedFailure(name, actual, expected, &failMessage)) {
                            QTest::qExpectFail("", failMessage.toLatin1(),
                                               QTest::Continue, path.toLatin1(),
                                               lineNumber);
                        }
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
                        else {
                            generatedAddExpectedFailureCode.append(
                                "    addExpectedFailure(\"" + name
                                + "\", \"" + actual + "\", \"" + expected
                                + "\", willFixInNextReleaseMessage);\n");
                        }
#endif
                        QTest::qCompare(actual, expected, "actual", "expect",
                                        path.toLatin1(), lineNumber);
                    } else {
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QTest::qExpectFail("", ret.toString().toLatin1(),
                                           QTest::Continue, path.toLatin1(), lineNumber);
                        QTest::qVerify(false, ret.toString().toLatin1(), "", path.toLatin1(), lineNumber);
                    }
                }
            }
        }
        _id -= testNames.size();
    }
    return _id;
}
Beispiel #30
0
void vec2FromScriptValue(const QScriptValue &object, glm::vec2 &vec2) {
    vec2.x = object.property("x").toVariant().toFloat();
    vec2.y = object.property("y").toVariant().toFloat();
}