diff --git a/assignment-client/src/Agent.cpp b/assignment-client/src/Agent.cpp index 27685fbcda..5a01275d11 100644 --- a/assignment-client/src/Agent.cpp +++ b/assignment-client/src/Agent.cpp @@ -505,8 +505,8 @@ void Agent::executeScript() { scriptEngine->registerGlobalObject("AnimationCache", DependencyManager::get().data()); scriptEngine->registerGlobalObject("SoundCache", DependencyManager::get().data()); - ScriptValuePointer webSocketServerConstructorValue = scriptEngine->newFunction(WebSocketServerClass::constructor); - scriptEngine->globalObject()->setProperty("WebSocketServer", webSocketServerConstructorValue); + ScriptValue webSocketServerConstructorValue = scriptEngine->newFunction(WebSocketServerClass::constructor); + scriptEngine->globalObject().setProperty("WebSocketServer", webSocketServerConstructorValue); auto entityScriptingInterface = DependencyManager::get(); diff --git a/assignment-client/src/scripts/EntityScriptServer.cpp b/assignment-client/src/scripts/EntityScriptServer.cpp index 32752bf6fe..0032c31e0a 100644 --- a/assignment-client/src/scripts/EntityScriptServer.cpp +++ b/assignment-client/src/scripts/EntityScriptServer.cpp @@ -452,7 +452,7 @@ void EntityScriptServer::resetEntitiesScriptEngine() { auto newEngine = newManager->engine(); auto webSocketServerConstructorValue = newEngine->newFunction(WebSocketServerClass::constructor); - newEngine->globalObject()->setProperty("WebSocketServer", webSocketServerConstructorValue); + newEngine->globalObject().setProperty("WebSocketServer", webSocketServerConstructorValue); newEngine->registerGlobalObject("SoundCache", DependencyManager::get().data()); newEngine->registerGlobalObject("AvatarList", DependencyManager::get().data()); diff --git a/interface/src/AvatarBookmarks.cpp b/interface/src/AvatarBookmarks.cpp index f2c55df268..95c1b10982 100644 --- a/interface/src/AvatarBookmarks.cpp +++ b/interface/src/AvatarBookmarks.cpp @@ -55,7 +55,7 @@ void addAvatarEntities(const QVariantList& avatarEntities) { const QVariantMap& avatarEntityProperties = avatarEntities.at(index).toMap(); QVariant variantProperties = avatarEntityProperties["properties"]; QVariantMap asMap = variantProperties.toMap(); - ScriptValuePointer scriptProperties = variantMapToScriptValue(asMap, *scriptEngine); + ScriptValue scriptProperties = variantMapToScriptValue(asMap, *scriptEngine); EntityItemProperties entityProperties; EntityItemPropertiesFromScriptValueIgnoreReadOnly(scriptProperties, entityProperties); @@ -322,8 +322,8 @@ QVariantMap AvatarBookmarks::getAvatarDataToBookmark() { desiredProperties -= PROP_JOINT_TRANSLATIONS; EntityItemProperties entityProperties = entity->getProperties(desiredProperties); - ScriptValuePointer scriptProperties = EntityItemPropertiesToScriptValue(scriptEngine.get(), entityProperties); - avatarEntityData["properties"] = scriptProperties->toVariant(); + ScriptValue scriptProperties = EntityItemPropertiesToScriptValue(scriptEngine.get(), entityProperties); + avatarEntityData["properties"] = scriptProperties.toVariant(); wearableEntities.append(QVariant(avatarEntityData)); } } diff --git a/interface/src/LODManager.cpp b/interface/src/LODManager.cpp index d5da45341b..9a80c5478b 100644 --- a/interface/src/LODManager.cpp +++ b/interface/src/LODManager.cpp @@ -426,13 +426,13 @@ WorldDetailQuality LODManager::getWorldDetailQuality() const { return qApp->isHMDMode() ? _hmdWorldDetailQuality : _desktopWorldDetailQuality; } -ScriptValuePointer worldDetailQualityToScriptValue(ScriptEngine* engine, const WorldDetailQuality& worldDetailQuality) { +ScriptValue worldDetailQualityToScriptValue(ScriptEngine* engine, const WorldDetailQuality& worldDetailQuality) { return engine->newValue(worldDetailQuality); } -void worldDetailQualityFromScriptValue(const ScriptValuePointer& object, WorldDetailQuality& worldDetailQuality) { +void worldDetailQualityFromScriptValue(const ScriptValue& object, WorldDetailQuality& worldDetailQuality) { worldDetailQuality = - static_cast(std::min(std::max(object->toInt32(), (int)WORLD_DETAIL_LOW), (int)WORLD_DETAIL_HIGH)); + static_cast(std::min(std::max(object.toInt32(), (int)WORLD_DETAIL_LOW), (int)WORLD_DETAIL_HIGH)); } void LODManager::setLODQualityLevel(float quality) { diff --git a/interface/src/LODManager.h b/interface/src/LODManager.h index 52a1c3ea44..1ab64b2dc1 100644 --- a/interface/src/LODManager.h +++ b/interface/src/LODManager.h @@ -14,7 +14,6 @@ #define hifi_LODManager_h #include -#include #include #include @@ -23,10 +22,9 @@ #include #include #include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc *

The world detail quality rendered.

@@ -384,7 +382,7 @@ private: glm::vec4 _pidOutputs{ 0.0f }; }; -ScriptValuePointer worldDetailQualityToScriptValue(ScriptEngine* engine, const WorldDetailQuality& worldDetailQuality); -void worldDetailQualityFromScriptValue(const ScriptValuePointer& object, WorldDetailQuality& worldDetailQuality); +ScriptValue worldDetailQualityToScriptValue(ScriptEngine* engine, const WorldDetailQuality& worldDetailQuality); +void worldDetailQualityFromScriptValue(const ScriptValue& object, WorldDetailQuality& worldDetailQuality); #endif // hifi_LODManager_h diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index 915adc0367..191770642b 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -736,8 +736,8 @@ AvatarSharedPointer AvatarManager::getAvatarBySessionID(const QUuid& sessionID) } RayToAvatarIntersectionResult AvatarManager::findRayIntersection(const PickRay& ray, - const ScriptValuePointer& avatarIdsToInclude, - const ScriptValuePointer& avatarIdsToDiscard, + const ScriptValue& avatarIdsToInclude, + const ScriptValue& avatarIdsToDiscard, bool pickAgainstMesh) { QVector avatarsToInclude = qVectorEntityItemIDFromScriptValue(avatarIdsToInclude); QVector avatarsToDiscard = qVectorEntityItemIDFromScriptValue(avatarIdsToDiscard); @@ -981,10 +981,10 @@ float AvatarManager::getAvatarSortCoefficient(const QString& name) { } // HACK -void AvatarManager::setAvatarSortCoefficient(const QString& name, const ScriptValuePointer& value) { +void AvatarManager::setAvatarSortCoefficient(const QString& name, const ScriptValue& value) { bool somethingChanged = false; - if (value->isNumber()) { - float numericalValue = (float)value->toNumber(); + if (value.isNumber()) { + float numericalValue = (float)value.toNumber(); if (name == "size") { AvatarData::_avatarSortCoefficientSize = numericalValue; somethingChanged = true; diff --git a/interface/src/avatar/AvatarManager.h b/interface/src/avatar/AvatarManager.h index 3a57c71a93..e278400821 100644 --- a/interface/src/avatar/AvatarManager.h +++ b/interface/src/avatar/AvatarManager.h @@ -26,6 +26,7 @@ #include #include #include // for SetOfEntities +#include #include "AvatarMotionState.h" #include "DetailedMotionState.h" @@ -33,9 +34,7 @@ #include "OtherAvatar.h" class ScriptEngine; -class ScriptValue; using SortedAvatar = std::pair>; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The AvatarManager API provides information about avatars within the current domain. The avatars available are @@ -187,8 +186,8 @@ public: * } */ Q_INVOKABLE RayToAvatarIntersectionResult findRayIntersection(const PickRay& ray, - const ScriptValuePointer& avatarIdsToInclude = ScriptValuePointer(), - const ScriptValuePointer& avatarIdsToDiscard = ScriptValuePointer(), + const ScriptValue& avatarIdsToInclude = ScriptValue(), + const ScriptValue& avatarIdsToDiscard = ScriptValue(), bool pickAgainstMesh = true); /*@jsdoc * @function AvatarManager.findRayIntersectionVector @@ -231,7 +230,7 @@ public: * @param {number} value - Value. * @deprecated This function is deprecated and will be removed. */ - Q_INVOKABLE void setAvatarSortCoefficient(const QString& name, const ScriptValuePointer& value); + Q_INVOKABLE void setAvatarSortCoefficient(const QString& name, const ScriptValue& value); /*@jsdoc * Gets PAL (People Access List) data for one or more avatars. Using this method is faster than iterating over each avatar diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 6e7eb0c9d4..ccb89e62e9 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -440,15 +440,15 @@ void MyAvatar::enableHandTouchForID(const QUuid& entityID) { } void MyAvatar::registerMetaTypes(ScriptEnginePointer engine) { - ScriptValuePointer value = engine->newQObject(this, ScriptEngine::QtOwnership); - engine->globalObject()->setProperty("MyAvatar", value); + ScriptValue value = engine->newQObject(this, ScriptEngine::QtOwnership); + engine->globalObject().setProperty("MyAvatar", value); - ScriptValuePointer driveKeys = engine->newObject(); + ScriptValue driveKeys = engine->newObject(); auto metaEnum = QMetaEnum::fromType(); for (int i = 0; i < MAX_DRIVE_KEYS; ++i) { - driveKeys->setProperty(metaEnum.key(i), metaEnum.value(i)); + driveKeys.setProperty(metaEnum.key(i), metaEnum.value(i)); } - engine->globalObject()->setProperty("DriveKeys", driveKeys); + engine->globalObject().setProperty("DriveKeys", driveKeys); scriptRegisterMetaType(engine.data(), audioListenModeToScriptValue, audioListenModeFromScriptValue); scriptRegisterMetaType(engine.data(), driveKeysToScriptValue, driveKeysFromScriptValue); @@ -2674,8 +2674,8 @@ QVariantList MyAvatar::getAvatarEntitiesVariant() { EntityItemProperties entityProperties = entity->getProperties(desiredProperties); { std::lock_guard guard(_scriptEngineLock); - ScriptValuePointer scriptProperties = EntityItemPropertiesToScriptValue(_scriptEngine.data(), entityProperties); - avatarEntityData["properties"] = scriptProperties->toVariant(); + ScriptValue scriptProperties = EntityItemPropertiesToScriptValue(_scriptEngine.data(), entityProperties); + avatarEntityData["properties"] = scriptProperties.toVariant(); } avatarEntitiesData.append(QVariant(avatarEntityData)); } @@ -5704,20 +5704,20 @@ void MyAvatar::setAudioListenerMode(AudioListenerMode audioListenerMode) { } } -ScriptValuePointer audioListenModeToScriptValue(ScriptEngine* engine, const AudioListenerMode& audioListenerMode) { +ScriptValue audioListenModeToScriptValue(ScriptEngine* engine, const AudioListenerMode& audioListenerMode) { return engine->newValue(audioListenerMode); } -void audioListenModeFromScriptValue(const ScriptValuePointer& object, AudioListenerMode& audioListenerMode) { - audioListenerMode = static_cast(object->toUInt16()); +void audioListenModeFromScriptValue(const ScriptValue& object, AudioListenerMode& audioListenerMode) { + audioListenerMode = static_cast(object.toUInt16()); } -ScriptValuePointer driveKeysToScriptValue(ScriptEngine* engine, const MyAvatar::DriveKeys& driveKeys) { +ScriptValue driveKeysToScriptValue(ScriptEngine* engine, const MyAvatar::DriveKeys& driveKeys) { return engine->newValue(driveKeys); } -void driveKeysFromScriptValue(const ScriptValuePointer& object, MyAvatar::DriveKeys& driveKeys) { - driveKeys = static_cast(object->toUInt16()); +void driveKeysFromScriptValue(const ScriptValue& object, MyAvatar::DriveKeys& driveKeys) { + driveKeys = static_cast(object.toUInt16()); } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 645494b95a..5ef1733213 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -32,6 +32,7 @@ #include #include #include +#include #include "AtRestDetector.h" #include "MyCharacterController.h" @@ -42,8 +43,6 @@ class ModelItemID; class MyHead; class DetailedMotionState; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; using ScriptEnginePointer = QSharedPointer; /*@jsdoc @@ -874,7 +873,7 @@ public: * MyAvatar.removeAnimationStateHandler(handler); * }, 100); */ - Q_INVOKABLE ScriptValuePointer addAnimationStateHandler(ScriptValuePointer handler, ScriptValuePointer propertiesList) { return _skeletonModel->getRig().addAnimationStateHandler(handler, propertiesList); } + Q_INVOKABLE ScriptValue addAnimationStateHandler(const ScriptValue& handler, const ScriptValue& propertiesList) { return _skeletonModel->getRig().addAnimationStateHandler(handler, propertiesList); } /*@jsdoc * Removes an animation state handler function. @@ -882,7 +881,7 @@ public: * @param {number} handler - The ID of the animation state handler function to remove. */ // Removes a handler previously added by addAnimationStateHandler. - Q_INVOKABLE void removeAnimationStateHandler(ScriptValuePointer handler) { _skeletonModel->getRig().removeAnimationStateHandler(handler); } + Q_INVOKABLE void removeAnimationStateHandler(const ScriptValue& handler) { _skeletonModel->getRig().removeAnimationStateHandler(handler); } /*@jsdoc @@ -3120,11 +3119,11 @@ private: QTimer _addAvatarEntitiesToTreeTimer; }; -ScriptValuePointer audioListenModeToScriptValue(ScriptEngine* engine, const AudioListenerMode& audioListenerMode); -void audioListenModeFromScriptValue(const ScriptValuePointer& object, AudioListenerMode& audioListenerMode); +ScriptValue audioListenModeToScriptValue(ScriptEngine* engine, const AudioListenerMode& audioListenerMode); +void audioListenModeFromScriptValue(const ScriptValue& object, AudioListenerMode& audioListenerMode); -ScriptValuePointer driveKeysToScriptValue(ScriptEngine* engine, const MyAvatar::DriveKeys& driveKeys); -void driveKeysFromScriptValue(const ScriptValuePointer& object, MyAvatar::DriveKeys& driveKeys); +ScriptValue driveKeysToScriptValue(ScriptEngine* engine, const MyAvatar::DriveKeys& driveKeys); +void driveKeysFromScriptValue(const ScriptValue& object, MyAvatar::DriveKeys& driveKeys); bool isWearableEntity(const EntityItemPointer& entity); diff --git a/interface/src/raypick/LaserPointerScriptingInterface.cpp b/interface/src/raypick/LaserPointerScriptingInterface.cpp index 5aacd72459..ed5fd2ecb6 100644 --- a/interface/src/raypick/LaserPointerScriptingInterface.cpp +++ b/interface/src/raypick/LaserPointerScriptingInterface.cpp @@ -14,11 +14,11 @@ #include "PointerScriptingInterface.h" #include -void LaserPointerScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreItems) const { +void LaserPointerScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValue& ignoreItems) const { DependencyManager::get()->setIgnoreItems(uid, qVectorQUuidFromScriptValue(ignoreItems)); } -void LaserPointerScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValuePointer& includeItems) const { +void LaserPointerScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValue& includeItems) const { DependencyManager::get()->setIncludeItems(uid, qVectorQUuidFromScriptValue(includeItems)); } diff --git a/interface/src/raypick/LaserPointerScriptingInterface.h b/interface/src/raypick/LaserPointerScriptingInterface.h index 9796508ca9..fe70509a0c 100644 --- a/interface/src/raypick/LaserPointerScriptingInterface.h +++ b/interface/src/raypick/LaserPointerScriptingInterface.h @@ -12,13 +12,11 @@ #define hifi_LaserPointerScriptingInterface_h #include -#include #include "DependencyManager.h" #include class ScriptValue; -using ScriptValuePointer = QSharedPointer; class LaserPointerScriptingInterface : public QObject, public Dependency { Q_OBJECT @@ -117,7 +115,7 @@ public: * @param {number} id - The ID of the pointer. * @param {Uuid[]} ignoreItems - A list of IDs to ignore. */ - Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreEntities) const; + Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValue& ignoreEntities) const; /*@jsdoc * Sets a list of entity and avatar IDs that a pointer should include during intersection, instead of intersecting with @@ -126,7 +124,7 @@ public: * @param {number} id - The ID of the pointer. * @param {Uuid[]} includeItems - A list of IDs to include. */ - Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValuePointer& includeEntities) const; + Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValue& includeEntities) const; /*@jsdoc diff --git a/interface/src/raypick/PickScriptingInterface.cpp b/interface/src/raypick/PickScriptingInterface.cpp index 954b6be3ea..eba2dec19e 100644 --- a/interface/src/raypick/PickScriptingInterface.cpp +++ b/interface/src/raypick/PickScriptingInterface.cpp @@ -427,11 +427,11 @@ void PickScriptingInterface::setPrecisionPicking(unsigned int uid, bool precisio DependencyManager::get()->setPrecisionPicking(uid, precisionPicking); } -void PickScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreItems) { +void PickScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValue& ignoreItems) { DependencyManager::get()->setIgnoreItems(uid, qVectorQUuidFromScriptValue(ignoreItems)); } -void PickScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValuePointer& includeItems) { +void PickScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValue& includeItems) { DependencyManager::get()->setIncludeItems(uid, qVectorQUuidFromScriptValue(includeItems)); } @@ -447,21 +447,21 @@ bool PickScriptingInterface::isMouse(unsigned int uid) { return DependencyManager::get()->isMouse(uid); } -ScriptValuePointer pickTypesToScriptValue(ScriptEngine* engine, const PickQuery::PickType& pickType) { +ScriptValue pickTypesToScriptValue(ScriptEngine* engine, const PickQuery::PickType& pickType) { return engine->newValue(pickType); } -void pickTypesFromScriptValue(const ScriptValuePointer& object, PickQuery::PickType& pickType) { - pickType = static_cast(object->toUInt16()); +void pickTypesFromScriptValue(const ScriptValue& object, PickQuery::PickType& pickType) { + pickType = static_cast(object.toUInt16()); } void PickScriptingInterface::registerMetaTypes(ScriptEngine* engine) { - ScriptValuePointer pickTypes = engine->newObject(); + ScriptValue pickTypes = engine->newObject(); auto metaEnum = QMetaEnum::fromType(); for (int i = 0; i < PickQuery::PickType::NUM_PICK_TYPES; ++i) { - pickTypes->setProperty(metaEnum.key(i), metaEnum.value(i)); + pickTypes.setProperty(metaEnum.key(i), metaEnum.value(i)); } - engine->globalObject()->setProperty("PickType", pickTypes); + engine->globalObject().setProperty("PickType", pickTypes); scriptRegisterMetaType(engine, pickTypesToScriptValue, pickTypesFromScriptValue); } diff --git a/interface/src/raypick/PickScriptingInterface.h b/interface/src/raypick/PickScriptingInterface.h index 2ce8b2026c..8afe5c45d3 100644 --- a/interface/src/raypick/PickScriptingInterface.h +++ b/interface/src/raypick/PickScriptingInterface.h @@ -9,7 +9,6 @@ #define hifi_PickScriptingInterface_h #include -#include #include #include @@ -18,7 +17,6 @@ class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The Picks API lets you create and manage objects for repeatedly calculating intersections. @@ -250,7 +248,7 @@ public: * @param {number} id - The ID of the pick. * @param {Uuid[]} ignoreItems - The list of IDs to ignore. */ - Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreItems); + Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValue& ignoreItems); /*@jsdoc * Sets a list of entity and avatar IDs that a pick should include during intersection, instead of intersecting with @@ -260,7 +258,7 @@ public: * @param {number} id - The ID of the pick. * @param {Uuid[]} includeItems - The list of IDs to include. */ - Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValuePointer& includeItems); + Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValue& includeItems); /*@jsdoc * Checks if a pick is associated with the left hand: a ray or parabola pick with joint property set to diff --git a/interface/src/raypick/PointerScriptingInterface.cpp b/interface/src/raypick/PointerScriptingInterface.cpp index 58fc736bb9..259fbf428d 100644 --- a/interface/src/raypick/PointerScriptingInterface.cpp +++ b/interface/src/raypick/PointerScriptingInterface.cpp @@ -25,11 +25,11 @@ static const glm::quat X_ROT_NEG_90{ 0.70710678f, -0.70710678f, 0.0f, 0.0f }; static const glm::vec3 DEFAULT_POSITION_OFFSET{0.0f, 0.0f, -StylusPick::WEB_STYLUS_LENGTH / 2.0f}; static const glm::vec3 DEFAULT_MODEL_DIMENSIONS{0.01f, 0.01f, StylusPick::WEB_STYLUS_LENGTH}; -void PointerScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreItems) const { +void PointerScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValue& ignoreItems) const { DependencyManager::get()->setIgnoreItems(uid, qVectorQUuidFromScriptValue(ignoreItems)); } -void PointerScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValuePointer& includeItems) const { +void PointerScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValue& includeItems) const { DependencyManager::get()->setIncludeItems(uid, qVectorQUuidFromScriptValue(includeItems)); } diff --git a/interface/src/raypick/PointerScriptingInterface.h b/interface/src/raypick/PointerScriptingInterface.h index 226e10433a..836a86b7bd 100644 --- a/interface/src/raypick/PointerScriptingInterface.h +++ b/interface/src/raypick/PointerScriptingInterface.h @@ -9,7 +9,6 @@ #define hifi_PointerScriptingInterface_h #include -#include #include "DependencyManager.h" #include "RegisteredMetaTypes.h" @@ -17,7 +16,6 @@ #include class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The Pointers API lets you create, manage, and visually represent objects for repeatedly calculating @@ -369,7 +367,7 @@ public: * @param {number} id - The ID of the pointer. * @param {Uuid[]} ignoreItems - A list of IDs to ignore. */ - Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreEntities) const; + Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValue& ignoreEntities) const; /*@jsdoc * Sets a list of entity and avatar IDs that a pointer should include during intersection, instead of intersecting with @@ -379,7 +377,7 @@ public: * @param {number} id - The ID of the pointer. * @param {Uuid[]} includeItems - A list of IDs to include. */ - Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValuePointer& includeEntities) const; + Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValue& includeEntities) const; /*@jsdoc diff --git a/interface/src/raypick/RayPickScriptingInterface.cpp b/interface/src/raypick/RayPickScriptingInterface.cpp index 1ddbb48766..6371632368 100644 --- a/interface/src/raypick/RayPickScriptingInterface.cpp +++ b/interface/src/raypick/RayPickScriptingInterface.cpp @@ -46,11 +46,11 @@ void RayPickScriptingInterface::setPrecisionPicking(unsigned int uid, bool preci DependencyManager::get()->setPrecisionPicking(uid, precisionPicking); } -void RayPickScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreItems) { +void RayPickScriptingInterface::setIgnoreItems(unsigned int uid, const ScriptValue& ignoreItems) { DependencyManager::get()->setIgnoreItems(uid, qVectorQUuidFromScriptValue(ignoreItems)); } -void RayPickScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValuePointer& includeItems) { +void RayPickScriptingInterface::setIncludeItems(unsigned int uid, const ScriptValue& includeItems) { DependencyManager::get()->setIncludeItems(uid, qVectorQUuidFromScriptValue(includeItems)); } diff --git a/interface/src/raypick/RayPickScriptingInterface.h b/interface/src/raypick/RayPickScriptingInterface.h index 33f6fe099e..acc11111c7 100644 --- a/interface/src/raypick/RayPickScriptingInterface.h +++ b/interface/src/raypick/RayPickScriptingInterface.h @@ -12,7 +12,6 @@ #define hifi_RayPickScriptingInterface_h #include -#include #include "RegisteredMetaTypes.h" #include @@ -20,7 +19,6 @@ #include "PickScriptingInterface.h" class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The RayPick API is a subset of the {@link Picks} API, as used for ray picks. @@ -125,7 +123,7 @@ public: * @param {number} id - The ID of the ray pick. * @param {Uuid[]} ignoreItems - The list of IDs to ignore. */ - Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValuePointer& ignoreEntities); + Q_INVOKABLE void setIgnoreItems(unsigned int uid, const ScriptValue& ignoreEntities); /*@jsdoc * Sets a list of entity and avatar IDs that a ray pick should include during intersection, instead of intersecting with @@ -134,7 +132,7 @@ public: * @param {number} id - The ID of the ray pick. * @param {Uuid[]} includeItems - The list of IDs to include. */ - Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValuePointer& includeEntities); + Q_INVOKABLE void setIncludeItems(unsigned int uid, const ScriptValue& includeEntities); /*@jsdoc diff --git a/interface/src/scripting/AccountServicesScriptingInterface.cpp b/interface/src/scripting/AccountServicesScriptingInterface.cpp index a909a5af0a..55d5b25acf 100644 --- a/interface/src/scripting/AccountServicesScriptingInterface.cpp +++ b/interface/src/scripting/AccountServicesScriptingInterface.cpp @@ -123,27 +123,27 @@ DownloadInfoResult::DownloadInfoResult() : * @property {number[]} downloading - The download percentage remaining of each asset currently downloading. * @property {number} pending - The number of assets pending download. */ -ScriptValuePointer DownloadInfoResultToScriptValue(ScriptEngine* engine, const DownloadInfoResult& result) { - ScriptValuePointer object = engine->newObject(); +ScriptValue DownloadInfoResultToScriptValue(ScriptEngine* engine, const DownloadInfoResult& result) { + ScriptValue object = engine->newObject(); - ScriptValuePointer array = engine->newArray(result.downloading.count()); + ScriptValue array = engine->newArray(result.downloading.count()); for (int i = 0; i < result.downloading.count(); i += 1) { - array->setProperty(i, result.downloading[i]); + array.setProperty(i, result.downloading[i]); } - object->setProperty("downloading", array); - object->setProperty("pending", result.pending); + object.setProperty("downloading", array); + object.setProperty("pending", result.pending); return object; } -void DownloadInfoResultFromScriptValue(const ScriptValuePointer& object, DownloadInfoResult& result) { - QList downloading = object->property("downloading")->toVariant().toList(); +void DownloadInfoResultFromScriptValue(const ScriptValue& object, DownloadInfoResult& result) { + QList downloading = object.property("downloading").toVariant().toList(); result.downloading.clear(); for (int i = 0; i < downloading.count(); i += 1) { result.downloading.append(downloading[i].toFloat()); } - result.pending = object->property("pending")->toVariant().toFloat(); + result.pending = object.property("pending").toVariant().toFloat(); } DownloadInfoResult AccountServicesScriptingInterface::getDownloadInfo() { diff --git a/interface/src/scripting/AccountServicesScriptingInterface.h b/interface/src/scripting/AccountServicesScriptingInterface.h index 86412a29c7..241db84c0d 100644 --- a/interface/src/scripting/AccountServicesScriptingInterface.h +++ b/interface/src/scripting/AccountServicesScriptingInterface.h @@ -15,14 +15,12 @@ #include #include #include -#include #include #include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class DownloadInfoResult { public: @@ -33,8 +31,8 @@ public: Q_DECLARE_METATYPE(DownloadInfoResult) -ScriptValuePointer DownloadInfoResultToScriptValue(ScriptEngine* engine, const DownloadInfoResult& result); -void DownloadInfoResultFromScriptValue(const ScriptValuePointer& object, DownloadInfoResult& result); +ScriptValue DownloadInfoResultToScriptValue(ScriptEngine* engine, const DownloadInfoResult& result); +void DownloadInfoResultFromScriptValue(const ScriptValue& object, DownloadInfoResult& result); class AccountServicesScriptingInterface : public QObject { Q_OBJECT diff --git a/interface/src/scripting/HMDScriptingInterface.cpp b/interface/src/scripting/HMDScriptingInterface.cpp index cca6954819..609037b714 100644 --- a/interface/src/scripting/HMDScriptingInterface.cpp +++ b/interface/src/scripting/HMDScriptingInterface.cpp @@ -152,7 +152,7 @@ bool HMDScriptingInterface::getAwayStateWhenFocusLostInVREnabled() { } -ScriptValuePointer HMDScriptingInterface::getHUDLookAtPosition2D(ScriptContext* context, ScriptEngine* engine) { +ScriptValue HMDScriptingInterface::getHUDLookAtPosition2D(ScriptContext* context, ScriptEngine* engine) { glm::vec3 hudIntersection; auto instance = DependencyManager::get(); if (instance->getHUDLookAtPosition3D(hudIntersection)) { @@ -162,7 +162,7 @@ ScriptValuePointer HMDScriptingInterface::getHUDLookAtPosition2D(ScriptContext* return engine->nullValue(); } -ScriptValuePointer HMDScriptingInterface::getHUDLookAtPosition3D(ScriptContext* context, ScriptEngine* engine) { +ScriptValue HMDScriptingInterface::getHUDLookAtPosition3D(ScriptContext* context, ScriptEngine* engine) { glm::vec3 result; auto instance = DependencyManager::get(); if (instance->getHUDLookAtPosition3D(result)) { diff --git a/interface/src/scripting/HMDScriptingInterface.h b/interface/src/scripting/HMDScriptingInterface.h index d7fb0b3dce..ad0bcad100 100644 --- a/interface/src/scripting/HMDScriptingInterface.h +++ b/interface/src/scripting/HMDScriptingInterface.h @@ -19,12 +19,10 @@ #include #include -#include +#include class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The HMD API provides access to the HMD used in VR display mode. @@ -444,14 +442,14 @@ public: * @function HMD.getHUDLookAtPosition2D * @returns {Vec2} The position on the HUD overlay that your HMD is looking at, in pixels. */ - static ScriptValuePointer getHUDLookAtPosition2D(ScriptContext* context, ScriptEngine* engine); + static ScriptValue getHUDLookAtPosition2D(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Gets the position on the HUD overlay that your HMD is looking at, in world coordinates. * @function HMD.getHUDLookAtPosition3D * @returns {Vec3} The position on the HUD overlay the your HMD is looking at, in world coordinates. */ - static ScriptValuePointer getHUDLookAtPosition3D(ScriptContext* context, ScriptEngine* engine); + static ScriptValue getHUDLookAtPosition3D(ScriptContext* context, ScriptEngine* engine); bool isMounted() const override; diff --git a/interface/src/scripting/TestScriptingInterface.cpp b/interface/src/scripting/TestScriptingInterface.cpp index 1b7ef709e0..2985ae6e50 100644 --- a/interface/src/scripting/TestScriptingInterface.cpp +++ b/interface/src/scripting/TestScriptingInterface.cpp @@ -154,9 +154,9 @@ void TestScriptingInterface::savePhysicsSimulationStats(QString originalPath) { qApp->saveNextPhysicsStats(path); } -void TestScriptingInterface::profileRange(const QString& name, ScriptValuePointer fn) { +void TestScriptingInterface::profileRange(const QString& name, const ScriptValue& fn) { PROFILE_RANGE(script, name); - fn->call(); + fn.call(); } void TestScriptingInterface::clearCaches() { diff --git a/interface/src/scripting/TestScriptingInterface.h b/interface/src/scripting/TestScriptingInterface.h index 2bc2092396..b5305d1df2 100644 --- a/interface/src/scripting/TestScriptingInterface.h +++ b/interface/src/scripting/TestScriptingInterface.h @@ -12,10 +12,7 @@ #include #include -#include - -class ScriptValue; -using ScriptValuePointer = QSharedPointer; +#include class TestScriptingInterface : public QObject { Q_OBJECT @@ -129,7 +126,7 @@ public slots: * @param {string} name - Name used to reference the function * @param {function} function - Function to profile */ - Q_INVOKABLE void profileRange(const QString& name, ScriptValuePointer function); + Q_INVOKABLE void profileRange(const QString& name, const ScriptValue& function); /*@jsdoc * Clear all caches (menu command Reload Content) diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index 46f089c94c..f8443a2da6 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -76,7 +76,7 @@ WindowScriptingInterface::~WindowScriptingInterface() { _messageBoxes.clear(); } -ScriptValuePointer WindowScriptingInterface::hasFocus() { +ScriptValue WindowScriptingInterface::hasFocus() { return engine()->newValue(qApp->hasFocus()); } @@ -96,26 +96,26 @@ void WindowScriptingInterface::raise() { /// Display an alert box /// \param const QString& message message to display -/// \return ScriptValuePointer::UndefinedValue +/// \return ScriptValue::UndefinedValue void WindowScriptingInterface::alert(const QString& message) { OffscreenUi::asyncWarning("", message, QMessageBox::Ok, QMessageBox::Ok); } /// Display a confirmation box with the options 'Yes' and 'No' /// \param const QString& message message to display -/// \return ScriptValuePointer `true` if 'Yes' was clicked, `false` otherwise -ScriptValuePointer WindowScriptingInterface::confirm(const QString& message) { +/// \return ScriptValue `true` if 'Yes' was clicked, `false` otherwise +ScriptValue WindowScriptingInterface::confirm(const QString& message) { return engine()->newValue((QMessageBox::Yes == OffscreenUi::question("", message, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))); } /// Display a prompt with a text box /// \param const QString& message message to display /// \param const QString& defaultText default text in the text box -/// \return ScriptValuePointer string text value in text box if the dialog was accepted, `null` otherwise. -ScriptValuePointer WindowScriptingInterface::prompt(const QString& message, const QString& defaultText) { +/// \return ScriptValue string text value in text box if the dialog was accepted, `null` otherwise. +ScriptValue WindowScriptingInterface::prompt(const QString& message, const QString& defaultText) { QString result = OffscreenUi::getText(nullptr, "", message, QLineEdit::Normal, defaultText); auto sResult = engine()->newValue(result); - if (sResult->equals(engine()->newValue(""))) { + if (sResult.equals(engine()->newValue(""))) { return engine()->nullValue(); } return sResult; @@ -218,8 +218,8 @@ void WindowScriptingInterface::ensureReticleVisible() const { /// working directory. /// \param const QString& title title of the window /// \param const QString& directory directory to start the directory browser at -/// \return ScriptValuePointer file path as a string if one was selected, otherwise `ScriptValuePointer::NullValue` -ScriptValuePointer WindowScriptingInterface::browseDir(const QString& title, const QString& directory) { +/// \return ScriptValue file path as a string if one was selected, otherwise `ScriptValue::NullValue` +ScriptValue WindowScriptingInterface::browseDir(const QString& title, const QString& directory) { ensureReticleVisible(); QString path = directory; if (path.isEmpty()) { @@ -262,8 +262,8 @@ void WindowScriptingInterface::browseDirAsync(const QString& title, const QStrin /// \param const QString& title title of the window /// \param const QString& directory directory to start the file browser at /// \param const QString& nameFilter filter to filter filenames by - see `QFileDialog` -/// \return ScriptValuePointer file path as a string if one was selected, otherwise `ScriptValuePointer::NullValue` -ScriptValuePointer WindowScriptingInterface::browse(const QString& title, const QString& directory, const QString& nameFilter) { +/// \return ScriptValue file path as a string if one was selected, otherwise `ScriptValue::NullValue` +ScriptValue WindowScriptingInterface::browse(const QString& title, const QString& directory, const QString& nameFilter) { ensureReticleVisible(); QString path = directory; if (path.isEmpty()) { @@ -309,8 +309,8 @@ void WindowScriptingInterface::browseAsync(const QString& title, const QString& /// \param const QString& title title of the window /// \param const QString& directory directory to start the file browser at /// \param const QString& nameFilter filter to filter filenames by - see `QFileDialog` -/// \return ScriptValuePointer file path as a string if one was selected, otherwise `ScriptValuePointer::NullValue` -ScriptValuePointer WindowScriptingInterface::save(const QString& title, const QString& directory, const QString& nameFilter) { +/// \return ScriptValue file path as a string if one was selected, otherwise `ScriptValue::NullValue` +ScriptValue WindowScriptingInterface::save(const QString& title, const QString& directory, const QString& nameFilter) { ensureReticleVisible(); QString path = directory; if (path.isEmpty()) { @@ -356,8 +356,8 @@ void WindowScriptingInterface::saveAsync(const QString& title, const QString& di /// \param const QString& title title of the window /// \param const QString& directory directory to start the asset browser at /// \param const QString& nameFilter filter to filter asset names by - see `QFileDialog` -/// \return ScriptValuePointer asset path as a string if one was selected, otherwise `ScriptValuePointer::NullValue` -ScriptValuePointer WindowScriptingInterface::browseAssets(const QString& title, const QString& directory, const QString& nameFilter) { +/// \return ScriptValue asset path as a string if one was selected, otherwise `ScriptValue::NullValue` +ScriptValue WindowScriptingInterface::browseAssets(const QString& title, const QString& directory, const QString& nameFilter) { ensureReticleVisible(); QString path = directory; if (path.isEmpty()) { diff --git a/interface/src/scripting/WindowScriptingInterface.h b/interface/src/scripting/WindowScriptingInterface.h index 47bfe95c20..3611ca5afd 100644 --- a/interface/src/scripting/WindowScriptingInterface.h +++ b/interface/src/scripting/WindowScriptingInterface.h @@ -18,15 +18,12 @@ #include #include #include -#include #include #include +#include -class ScriptValue; -using ScriptValuePointer = QSharedPointer; - /*@jsdoc * The Window API provides various facilities not covered elsewhere, including: window dimensions, window focus, * camera view, announcements, user connections, common dialog boxes, snapshots, file import, domain navigation, domain changes, @@ -74,7 +71,7 @@ public slots: * @function Window.hasFocus * @returns {boolean} true if the Interface window has focus, false if it doesn't. */ - ScriptValuePointer hasFocus(); + ScriptValue hasFocus(); /*@jsdoc * Makes the Interface window have focus. On Windows, if Interface doesn't already have focus, the task bar icon flashes to @@ -109,7 +106,7 @@ public slots: * var answer = Window.confirm("Are you sure?"); * print(answer); // true or false */ - ScriptValuePointer confirm(const QString& message = ""); + ScriptValue confirm(const QString& message = ""); /*@jsdoc * Prompts the user to enter some text. Displays a modal dialog with a message and a text box, plus "OK" and "Cancel" @@ -126,7 +123,7 @@ public slots: * print("User answer: " + answer); * } */ - ScriptValuePointer prompt(const QString& message, const QString& defaultText); + ScriptValue prompt(const QString& message, const QString& defaultText); /*@jsdoc * Prompts the user to enter some text. Displays a non-modal dialog with a message and a text box, plus "OK" and "Cancel" @@ -156,7 +153,7 @@ public slots: * var directory = Window.browseDir("Select Directory", Paths.resources); * print("Directory: " + directory); */ - ScriptValuePointer browseDir(const QString& title = "", const QString& directory = ""); + ScriptValue browseDir(const QString& title = "", const QString& directory = ""); /*@jsdoc * Prompts the user to choose a directory. Displays a non-modal dialog that navigates the directory tree. A @@ -188,7 +185,7 @@ public slots: * var filename = Window.browse("Select Image File", Paths.resources, "Images (*.png *.jpg *.svg)"); * print("File: " + filename); */ - ScriptValuePointer browse(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); + ScriptValue browse(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /*@jsdoc * Prompts the user to choose a file. Displays a non-modal dialog that navigates the directory tree. A @@ -224,7 +221,7 @@ public slots: * var filename = Window.save("Save to JSON file", Paths.resources, "*.json"); * print("File: " + filename); */ - ScriptValuePointer save(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); + ScriptValue save(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /*@jsdoc * Prompts the user to specify the path and name of a file to save to. Displays a non-modal dialog that navigates the @@ -259,7 +256,7 @@ public slots: * var asset = Window.browseAssets("Select FBX File", "/", "*.fbx"); * print("FBX file: " + asset); */ - ScriptValuePointer browseAssets(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); + ScriptValue browseAssets(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /*@jsdoc * Prompts the user to choose an Asset Server item. Displays a non-modal dialog that navigates the tree of assets on the diff --git a/interface/src/ui/InteractiveWindow.cpp b/interface/src/ui/InteractiveWindow.cpp index e86b667696..f74c61dea3 100644 --- a/interface/src/ui/InteractiveWindow.cpp +++ b/interface/src/ui/InteractiveWindow.cpp @@ -97,15 +97,13 @@ void registerInteractiveWindowMetaType(ScriptEngine* engine) { scriptRegisterMetaType(engine, interactiveWindowPointerToScriptValue, interactiveWindowPointerFromScriptValue); } -ScriptValuePointer interactiveWindowPointerToScriptValue(ScriptEngine* engine, const InteractiveWindowPointer& in) { +ScriptValue interactiveWindowPointerToScriptValue(ScriptEngine* engine, const InteractiveWindowPointer& in) { return engine->newQObject(in, ScriptEngine::ScriptOwnership); } -void interactiveWindowPointerFromScriptValue(const ScriptValuePointer& object, InteractiveWindowPointer& out) { - if (!object) { - if (const auto interactiveWindow = qobject_cast(object->toQObject())) { - out = interactiveWindow; - } +void interactiveWindowPointerFromScriptValue(const ScriptValue& object, InteractiveWindowPointer& out) { + if (const auto interactiveWindow = qobject_cast(object.toQObject())) { + out = interactiveWindow; } } diff --git a/interface/src/ui/InteractiveWindow.h b/interface/src/ui/InteractiveWindow.h index 160ddb122c..f11140b3c3 100644 --- a/interface/src/ui/InteractiveWindow.h +++ b/interface/src/ui/InteractiveWindow.h @@ -15,17 +15,15 @@ #define hifi_InteractiveWindow_h #include -#include #include #include #include #include #include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class QmlWindowProxy : public QmlWrapper { Q_OBJECT @@ -412,8 +410,8 @@ private: typedef InteractiveWindow* InteractiveWindowPointer; -ScriptValuePointer interactiveWindowPointerToScriptValue(ScriptEngine* engine, const InteractiveWindowPointer& in); -void interactiveWindowPointerFromScriptValue(const ScriptValuePointer& object, InteractiveWindowPointer& out); +ScriptValue interactiveWindowPointerToScriptValue(ScriptEngine* engine, const InteractiveWindowPointer& in); +void interactiveWindowPointerFromScriptValue(const ScriptValue& object, InteractiveWindowPointer& out); void registerInteractiveWindowMetaType(ScriptEngine* engine); diff --git a/interface/src/ui/JSConsole.cpp b/interface/src/ui/JSConsole.cpp index de35259816..71472d439a 100644 --- a/interface/src/ui/JSConsole.cpp +++ b/interface/src/ui/JSConsole.cpp @@ -187,7 +187,7 @@ JSConsole::JSConsole(QWidget* parent, const ScriptManagerPointer& scriptManager) resizeTextInput(); - connect(&_executeWatcher, &QFutureWatcher::finished, this, &JSConsole::commandFinished); + connect(&_executeWatcher, &QFutureWatcher::finished, this, &JSConsole::commandFinished); } void JSConsole::insertCompletion(const QModelIndex& completion) { @@ -351,12 +351,12 @@ void JSConsole::executeCommand(const QString& command) { QWeakPointer weakScriptManager = _scriptManager; auto consoleFileName = _consoleFileName; - QFuture future = QtConcurrent::run([weakScriptManager, consoleFileName, command]() -> ScriptValuePointer { - ScriptValuePointer result; + QFuture future = QtConcurrent::run([weakScriptManager, consoleFileName, command]() -> ScriptValue { + ScriptValue result; auto scriptManager = weakScriptManager.lock(); if (scriptManager) { BLOCKING_INVOKE_METHOD(scriptManager.data(), "evaluate", - Q_RETURN_ARG(ScriptValuePointer, result), + Q_RETURN_ARG(ScriptValue, result), Q_ARG(const QString&, command), Q_ARG(const QString&, consoleFileName)); } @@ -366,7 +366,7 @@ void JSConsole::executeCommand(const QString& command) { } void JSConsole::commandFinished() { - ScriptValuePointer result = _executeWatcher.result(); + ScriptValue result = _executeWatcher.result(); _ui->promptTextEdit->setDisabled(false); @@ -375,10 +375,10 @@ void JSConsole::commandFinished() { _ui->promptTextEdit->setFocus(); } - bool error = (_scriptManager->engine()->hasUncaughtException() || (result && result->isError())); + bool error = (_scriptManager->engine()->hasUncaughtException() || result.isError()); QString gutter = error ? GUTTER_ERROR : GUTTER_PREVIOUS_COMMAND; QString resultColor = error ? RESULT_ERROR_STYLE : RESULT_SUCCESS_STYLE; - QString resultStr = result ? "" + result->toString().toHtmlEscaped() + "" : ""; + QString resultStr = "" + result.toString().toHtmlEscaped() + ""; appendMessage(gutter, resultStr); resetCurrentCommandHistory(); diff --git a/interface/src/ui/JSConsole.h b/interface/src/ui/JSConsole.h index 362c98ec3f..b07f972f9a 100644 --- a/interface/src/ui/JSConsole.h +++ b/interface/src/ui/JSConsole.h @@ -16,14 +16,13 @@ #include #include #include +#include #include "ui_console.h" class QStandardItemModel; class ScriptManager; -class ScriptValue; using ScriptManagerPointer = QSharedPointer; -using ScriptValuePointer = QSharedPointer; const QString CONSOLE_TITLE = "Scripting Console"; const float CONSOLE_WINDOW_OPACITY = 0.95f; @@ -71,7 +70,7 @@ private: QStandardItemModel* getAutoCompleteModel(const QString& memberOf = nullptr); - QFutureWatcher _executeWatcher; + QFutureWatcher _executeWatcher; Ui::Console* _ui; int _currentCommandInHistory; QString _savedHistoryFilename; diff --git a/interface/src/ui/overlays/Overlays.cpp b/interface/src/ui/overlays/Overlays.cpp index 6e7b8b65ba..ee2bcc75ff 100644 --- a/interface/src/ui/overlays/Overlays.cpp +++ b/interface/src/ui/overlays/Overlays.cpp @@ -633,7 +633,7 @@ EntityItemProperties Overlays::convertOverlayToEntityProperties(QVariantMap& ove } ScriptEnginePointer scriptEngine = newScriptEngine(); - ScriptValuePointer props = variantMapToScriptValue(overlayProps, *scriptEngine); + ScriptValue props = variantMapToScriptValue(overlayProps, *scriptEngine); EntityItemProperties toReturn; EntityItemPropertiesFromScriptValueHonorReadOnly(props, toReturn); return toReturn; @@ -641,7 +641,7 @@ EntityItemProperties Overlays::convertOverlayToEntityProperties(QVariantMap& ove QVariantMap Overlays::convertEntityToOverlayProperties(const EntityItemProperties& properties) { ScriptEnginePointer scriptEngine = newScriptEngine(); - QVariantMap overlayProps = EntityItemPropertiesToScriptValue(scriptEngine.data(), properties)->toVariant().toMap(); + QVariantMap overlayProps = EntityItemPropertiesToScriptValue(scriptEngine.data(), properties).toVariant().toMap(); QString type = overlayProps["type"].toString(); overlayProps["type"] = entityToOverlayType(type); @@ -1041,8 +1041,8 @@ QVariantMap Overlays::getOverlaysProperties(const QVariant& propertiesById) { } RayToOverlayIntersectionResult Overlays::findRayIntersection(const PickRay& ray, bool precisionPicking, - const ScriptValuePointer& overlayIDsToInclude, - const ScriptValuePointer& overlayIDsToDiscard, + const ScriptValue& overlayIDsToInclude, + const ScriptValue& overlayIDsToDiscard, bool visibleOnly, bool collidableOnly) { const QVector include = qVectorEntityItemIDFromScriptValue(overlayIDsToInclude); const QVector discard = qVectorEntityItemIDFromScriptValue(overlayIDsToDiscard); @@ -1110,38 +1110,38 @@ ParabolaToOverlayIntersectionResult Overlays::findParabolaIntersectionVector(con return overlayResult; } -ScriptValuePointer RayToOverlayIntersectionResultToScriptValue(ScriptEngine* engine, const RayToOverlayIntersectionResult& value) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("intersects", value.intersects); - ScriptValuePointer overlayIDValue = quuidToScriptValue(engine, value.overlayID); - obj->setProperty("overlayID", overlayIDValue); - obj->setProperty("distance", value.distance); - obj->setProperty("face", boxFaceToString(value.face)); +ScriptValue RayToOverlayIntersectionResultToScriptValue(ScriptEngine* engine, const RayToOverlayIntersectionResult& value) { + ScriptValue obj = engine->newObject(); + obj.setProperty("intersects", value.intersects); + ScriptValue overlayIDValue = quuidToScriptValue(engine, value.overlayID); + obj.setProperty("overlayID", overlayIDValue); + obj.setProperty("distance", value.distance); + obj.setProperty("face", boxFaceToString(value.face)); - ScriptValuePointer intersection = vec3ToScriptValue(engine, value.intersection); - obj->setProperty("intersection", intersection); - ScriptValuePointer surfaceNormal = vec3ToScriptValue(engine, value.surfaceNormal); - obj->setProperty("surfaceNormal", surfaceNormal); - obj->setProperty("extraInfo", engine->toScriptValue(value.extraInfo)); + ScriptValue intersection = vec3ToScriptValue(engine, value.intersection); + obj.setProperty("intersection", intersection); + ScriptValue surfaceNormal = vec3ToScriptValue(engine, value.surfaceNormal); + obj.setProperty("surfaceNormal", surfaceNormal); + obj.setProperty("extraInfo", engine->toScriptValue(value.extraInfo)); return obj; } -void RayToOverlayIntersectionResultFromScriptValue(const ScriptValuePointer& object, RayToOverlayIntersectionResult& value) { - value.intersects = object->property("intersects")->toVariant().toBool(); - ScriptValuePointer overlayIDValue = object->property("overlayID"); +void RayToOverlayIntersectionResultFromScriptValue(const ScriptValue& object, RayToOverlayIntersectionResult& value) { + value.intersects = object.property("intersects").toVariant().toBool(); + ScriptValue overlayIDValue = object.property("overlayID"); quuidFromScriptValue(overlayIDValue, value.overlayID); - value.distance = object->property("distance")->toVariant().toFloat(); - value.face = boxFaceFromString(object->property("face")->toVariant().toString()); + value.distance = object.property("distance").toVariant().toFloat(); + value.face = boxFaceFromString(object.property("face").toVariant().toString()); - ScriptValuePointer intersection = object->property("intersection"); - if (intersection->isValid()) { + ScriptValue intersection = object.property("intersection"); + if (intersection.isValid()) { vec3FromScriptValue(intersection, value.intersection); } - ScriptValuePointer surfaceNormal = object->property("surfaceNormal"); - if (surfaceNormal->isValid()) { + ScriptValue surfaceNormal = object.property("surfaceNormal"); + if (surfaceNormal.isValid()) { vec3FromScriptValue(surfaceNormal, value.surfaceNormal); } - value.extraInfo = object->property("extraInfo")->toVariant().toMap(); + value.extraInfo = object.property("extraInfo").toVariant().toMap(); } bool Overlays::isLoaded(const QUuid& id) { diff --git a/interface/src/ui/overlays/Overlays.h b/interface/src/ui/overlays/Overlays.h index ccbbf209fd..167a0e1d7d 100644 --- a/interface/src/ui/overlays/Overlays.h +++ b/interface/src/ui/overlays/Overlays.h @@ -22,7 +22,7 @@ #include #include -#include +#include #include "Overlay.h" @@ -30,8 +30,6 @@ class PickRay; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The result of a {@link PickRay} search using {@link Overlays.findRayIntersection|findRayIntersection}. @@ -55,8 +53,8 @@ public: QVariantMap extraInfo; }; Q_DECLARE_METATYPE(RayToOverlayIntersectionResult); -ScriptValuePointer RayToOverlayIntersectionResultToScriptValue(ScriptEngine* engine, const RayToOverlayIntersectionResult& value); -void RayToOverlayIntersectionResultFromScriptValue(const ScriptValuePointer& object, RayToOverlayIntersectionResult& value); +ScriptValue RayToOverlayIntersectionResultToScriptValue(ScriptEngine* engine, const RayToOverlayIntersectionResult& value); +void RayToOverlayIntersectionResultFromScriptValue(const ScriptValue& object, RayToOverlayIntersectionResult& value); class ParabolaToOverlayIntersectionResult { public: @@ -414,8 +412,8 @@ public slots: */ RayToOverlayIntersectionResult findRayIntersection(const PickRay& ray, bool precisionPicking = false, - const ScriptValuePointer& include = ScriptValuePointer(), - const ScriptValuePointer& discard = ScriptValuePointer(), + const ScriptValue& include = ScriptValue(), + const ScriptValue& discard = ScriptValue(), bool visibleOnly = false, bool collidableOnly = false); diff --git a/libraries/animation/src/AnimVariant.cpp b/libraries/animation/src/AnimVariant.cpp index db877bf91a..0b44dfd8db 100644 --- a/libraries/animation/src/AnimVariant.cpp +++ b/libraries/animation/src/AnimVariant.cpp @@ -18,32 +18,32 @@ const AnimVariant AnimVariant::False = AnimVariant(); -ScriptValuePointer AnimVariantMap::animVariantMapToScriptValue(ScriptEngine* engine, const QStringList& names, bool useNames) const { +ScriptValue AnimVariantMap::animVariantMapToScriptValue(ScriptEngine* engine, const QStringList& names, bool useNames) const { if (QThread::currentThread() != engine->thread()) { qCWarning(animation) << "Cannot create Javacript object from non-script thread" << QThread::currentThread(); Q_ASSERT(false); - return ScriptValuePointer(); + return ScriptValue(); } - ScriptValuePointer target = engine->newObject(); + ScriptValue target = engine->newObject(); auto setOne = [&] (const QString& name, const AnimVariant& value) { switch (value.getType()) { case AnimVariant::Type::Bool: - target->setProperty(name, value.getBool()); + target.setProperty(name, value.getBool()); break; case AnimVariant::Type::Int: - target->setProperty(name, value.getInt()); + target.setProperty(name, value.getInt()); break; case AnimVariant::Type::Float: - target->setProperty(name, value.getFloat()); + target.setProperty(name, value.getFloat()); break; case AnimVariant::Type::String: - target->setProperty(name, value.getString()); + target.setProperty(name, value.getString()); break; case AnimVariant::Type::Vec3: - target->setProperty(name, vec3ToScriptValue(engine, value.getVec3())); + target.setProperty(name, vec3ToScriptValue(engine, value.getVec3())); break; case AnimVariant::Type::Quat: - target->setProperty(name, quatToScriptValue(engine, value.getQuat())); + target.setProperty(name, quatToScriptValue(engine, value.getQuat())); break; default: // Unknown type @@ -56,7 +56,7 @@ ScriptValuePointer AnimVariantMap::animVariantMapToScriptValue(ScriptEngine* eng if (search != _map.end()) { setOne(name, search->second); } else if (_triggers.count(name) == 1) { - target->setProperty(name, true); + target.setProperty(name, true); } // scripts are allowed to request names that do not exist } @@ -74,8 +74,8 @@ void AnimVariantMap::copyVariantsFrom(const AnimVariantMap& other) { } } -void AnimVariantMap::animVariantMapFromScriptValue(const ScriptValuePointer& source) { - if (QThread::currentThread() != source->engine()->thread()) { +void AnimVariantMap::animVariantMapFromScriptValue(const ScriptValue& source) { + if (QThread::currentThread() != source.engine()->thread()) { qCWarning(animation) << "Cannot examine Javacript object from non-script thread" << QThread::currentThread(); Q_ASSERT(false); return; @@ -84,43 +84,43 @@ void AnimVariantMap::animVariantMapFromScriptValue(const ScriptValuePointer& sou // 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. - ScriptValueIteratorPointer property(source->newIterator()); + ScriptValueIteratorPointer property(source.newIterator()); // Note: ScriptValueIterator iterates only over source's own properties. It does not follow the prototype chain. while (property->hasNext()) { property->next(); - ScriptValuePointer value = property->value(); - if (value && value->isBool()) { - set(property->name(), value->toBool()); - } else if (value && value->isString()) { - set(property->name(), value->toString()); - } else if (value && value->isNumber()) { - int asInteger = value->toInt32(); - float asFloat = value->toNumber(); + ScriptValue 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 && value->isObject()) { - ScriptValuePointer x = value->property("x"); - if (x && x->isNumber()) { - ScriptValuePointer y = value->property("y"); - if (y && y->isNumber()) { - ScriptValuePointer z = value->property("z"); - if (z && z->isNumber()) { - ScriptValuePointer w = value->property("w"); - if (w && w->isNumber()) { - set(property->name(), glm::quat(w->toNumber(), x->toNumber(), y->toNumber(), z->toNumber())); + if (value.isObject()) { + ScriptValue x = value.property("x"); + if (x.isNumber()) { + ScriptValue y = value.property("y"); + if (y.isNumber()) { + ScriptValue z = value.property("z"); + if (z.isNumber()) { + ScriptValue 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())); + 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 ? value->toString() : "(undefined)") << " for animation property " << property->name(); + qCWarning(animation) << "Ignoring unrecognized data " << value.toString() << " for animation property " << property->name(); Q_ASSERT(false); } } diff --git a/libraries/animation/src/AnimVariant.h b/libraries/animation/src/AnimVariant.h index 15a0b0d48d..83cebaa7af 100644 --- a/libraries/animation/src/AnimVariant.h +++ b/libraries/animation/src/AnimVariant.h @@ -20,11 +20,9 @@ #include #include #include "AnimationLogging.h" -#include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class AnimVariant { public: @@ -233,9 +231,9 @@ public: } // Answer a Plain Old Javascript Object (for the given engine) all of our values set as properties. - ScriptValuePointer animVariantMapToScriptValue(ScriptEngine* engine, const QStringList& names, bool useNames) const; + ScriptValue animVariantMapToScriptValue(ScriptEngine* engine, const QStringList& names, bool useNames) const; // Side-effect us with the value of object's own properties. (No inherited properties.) - void animVariantMapFromScriptValue(const ScriptValuePointer& object); + void animVariantMapFromScriptValue(const ScriptValue& object); void copyVariantsFrom(const AnimVariantMap& other); // For stat debugging. @@ -278,7 +276,7 @@ protected: glm::quat _rigToGeometryRot; }; -typedef std::function AnimVariantResultHandler; +typedef std::function AnimVariantResultHandler; Q_DECLARE_METATYPE(AnimVariantResultHandler); Q_DECLARE_METATYPE(AnimVariantMap) diff --git a/libraries/animation/src/Rig.cpp b/libraries/animation/src/Rig.cpp index 935efd3030..34c592504e 100644 --- a/libraries/animation/src/Rig.cpp +++ b/libraries/animation/src/Rig.cpp @@ -1586,10 +1586,10 @@ void Rig::computeMotionAnimationState(float deltaTime, const glm::vec3& worldPos } // Allow script to add/remove handlers and report results, from within their thread. -ScriptValuePointer Rig::addAnimationStateHandler(ScriptValuePointer handler, ScriptValuePointer propertiesList) { // called in script thread +ScriptValue Rig::addAnimationStateHandler(const ScriptValue& handler, const ScriptValue& propertiesList) { // called in script thread // validate argument types - if (handler && handler->isFunction() && (isListOfStrings(propertiesList) || propertiesList->isUndefined() || propertiesList->isNull())) { + if (handler.isFunction() && (isListOfStrings(propertiesList) || propertiesList.isUndefined() || propertiesList.isNull())) { QMutexLocker locker(&_stateMutex); // Find a safe id, even if there are lots of many scripts add and remove handlers repeatedly. while (!_nextStateHandlerId || _stateHandlers.contains(_nextStateHandlerId)) { // 0 is unused, and don't reuse existing after wrap. @@ -1597,28 +1597,28 @@ ScriptValuePointer Rig::addAnimationStateHandler(ScriptValuePointer handler, Scr } StateHandler& data = _stateHandlers[_nextStateHandlerId]; data.function = handler; - data.useNames = propertiesList->isArray(); + data.useNames = propertiesList.isArray(); if (data.useNames) { - data.propertyNames = propertiesList->toVariant().toStringList(); + data.propertyNames = propertiesList.toVariant().toStringList(); } - return handler->engine()->newValue(_nextStateHandlerId); // suitable for giving to removeAnimationStateHandler + return handler.engine()->newValue(_nextStateHandlerId); // suitable for giving to removeAnimationStateHandler } else { qCWarning(animation) << "Rig::addAnimationStateHandler invalid arguments, expected (function, string[])"; - return handler ? handler->engine()->undefinedValue() : ScriptValuePointer(); + return handler.engine() ? handler.engine()->undefinedValue() : ScriptValue(); } } -void Rig::removeAnimationStateHandler(ScriptValuePointer identifier) { // called in script thread +void Rig::removeAnimationStateHandler(const ScriptValue& identifier) { // called in script thread // validate arguments - if (identifier && identifier->isNumber()) { + if (identifier.isNumber()) { QMutexLocker locker(&_stateMutex); - _stateHandlers.remove(identifier->toInt32()); // silently continues if handler not present. 0 is unused + _stateHandlers.remove(identifier.toInt32()); // silently continues if handler not present. 0 is unused } else { qCWarning(animation) << "Rig::removeAnimationStateHandler invalid argument, expected a number"; } } -void Rig::animationStateHandlerResult(int identifier, ScriptValuePointer result) { // called synchronously from script +void Rig::animationStateHandlerResult(int identifier, const ScriptValue& result) { // called synchronously from script QMutexLocker locker(&_stateMutex); auto found = _stateHandlers.find(identifier); if (found == _stateHandlers.end()) { @@ -1637,9 +1637,9 @@ void Rig::updateAnimationStateHandlers() { // called on avatar update thread (wh // call out: int identifier = data.key(); StateHandler& value = data.value(); - ScriptValuePointer& function = value.function; + ScriptValue& function = value.function; int rigId = _rigId; - auto handleResult = [rigId, identifier](ScriptValuePointer result) { // called in script thread to get the result back to us. + auto handleResult = [rigId, identifier](const ScriptValue& result) { // called in script thread to get the result back to us. // Hold the rigRegistryMutex to ensure thread-safe access to the rigRegistry, but // also to prevent the rig from being deleted while this lambda is being executed. std::lock_guard guard(rigRegistryMutex); @@ -1658,20 +1658,20 @@ void Rig::updateAnimationStateHandlers() { // called on avatar update thread (wh // Copies of AnimVariantMap do copy the underlying map, so this will correctly capture // the state of _animVars and allow continued changes to _animVars in this thread without conflict. const AnimVariantMap& animVars = _animVars; - ScriptEnginePointer engine = function->engine(); + ScriptEnginePointer engine = function.engine(); const QStringList& names = value.propertyNames; bool useNames = value.useNames; QMetaObject::invokeMethod( engine->manager(), [function, animVars, names, useNames, handleResult, engine] { - ScriptValuePointer javascriptParameters = animVars.animVariantMapToScriptValue(engine.get(), names, useNames); + ScriptValue javascriptParameters = animVars.animVariantMapToScriptValue(engine.get(), names, useNames); ScriptValueList callingArguments; callingArguments << javascriptParameters; - ScriptValuePointer result = function->call(ScriptValuePointer(), callingArguments); + ScriptValue result = function.call(ScriptValue(), callingArguments); // validate result from callback function. - if (result->isValid() && result->isObject()) { + if (result.isValid() && result.isObject()) { handleResult(result); } else { qCWarning(animation) << "Rig::updateAnimationStateHandlers invalid return argument from " diff --git a/libraries/animation/src/Rig.h b/libraries/animation/src/Rig.h index b5c7d222ac..32ddeea6fc 100644 --- a/libraries/animation/src/Rig.h +++ b/libraries/animation/src/Rig.h @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include "AnimNode.h" #include "AnimNodeLoader.h" @@ -30,8 +30,6 @@ class Rig; class AnimInverseKinematics; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; // Rig instances are reentrant. // However only specific methods thread-safe. Noted below. @@ -42,7 +40,7 @@ public: struct StateHandler { AnimVariantMap results; QStringList propertyNames; - ScriptValuePointer function; + ScriptValue function; bool useNames; }; @@ -207,9 +205,9 @@ public: AnimNode::ConstPointer getAnimNode() const { return _animNode; } AnimNode::ConstPointer findAnimNodeByName(const QString& name) const; AnimSkeleton::ConstPointer getAnimSkeleton() const { return _animSkeleton; } - ScriptValuePointer addAnimationStateHandler(ScriptValuePointer handler, ScriptValuePointer propertiesList); - void removeAnimationStateHandler(ScriptValuePointer handler); - void animationStateHandlerResult(int identifier, ScriptValuePointer result); + ScriptValue addAnimationStateHandler(const ScriptValue& handler, const ScriptValue& propertiesList); + void removeAnimationStateHandler(const ScriptValue& handler); + void animationStateHandlerResult(int identifier, const ScriptValue& result); // rig space bool getModelRegistrationPoint(glm::vec3& modelRegistrationPointOut) const; diff --git a/libraries/audio-client/CMakeLists.txt b/libraries/audio-client/CMakeLists.txt index 6b88292dd4..03a9fc087b 100644 --- a/libraries/audio-client/CMakeLists.txt +++ b/libraries/audio-client/CMakeLists.txt @@ -6,6 +6,7 @@ setup_hifi_library(Network Multimedia ${PLATFORM_QT_COMPONENTS}) link_hifi_libraries(audio plugins) include_hifi_library_headers(shared) include_hifi_library_headers(networking) +include_hifi_library_headers(script-engine) if (ANDROID) else () diff --git a/libraries/audio/src/AudioEffectOptions.cpp b/libraries/audio/src/AudioEffectOptions.cpp index 4fb7d93983..8edddd9092 100644 --- a/libraries/audio/src/AudioEffectOptions.cpp +++ b/libraries/audio/src/AudioEffectOptions.cpp @@ -18,8 +18,8 @@ STATIC_SCRIPT_INITIALIZER(+[](ScriptManager* manager) { auto scriptEngine = manager->engine().data(); - ScriptValuePointer audioEffectOptionsConstructorValue = scriptEngine->newFunction(AudioEffectOptions::constructor); - scriptEngine->globalObject()->setProperty("AudioEffectOptions", audioEffectOptionsConstructorValue); + ScriptValue audioEffectOptionsConstructorValue = scriptEngine->newFunction(AudioEffectOptions::constructor); + scriptEngine->globalObject().setProperty("AudioEffectOptions", audioEffectOptionsConstructorValue); }); static const QString BANDWIDTH_HANDLE = "bandwidth"; @@ -66,8 +66,8 @@ static const float LATE_MIX_LEFT_DEFAULT = 90.0f; static const float LATE_MIX_RIGHT_DEFAULT = 90.0f; static const float WET_DRY_MIX_DEFAULT = 50.0f; -static void setOption(ScriptValuePointer arguments, const QString name, float defaultValue, float& variable) { - variable = arguments && arguments->property(name)->isNumber() ? (float)arguments->property(name)->toNumber() : defaultValue; +static void setOption(const ScriptValue& arguments, const QString name, float defaultValue, float& variable) { + variable = arguments.property(name).isNumber() ? (float)arguments.property(name).toNumber() : defaultValue; } /*@jsdoc @@ -95,7 +95,7 @@ static void setOption(ScriptValuePointer arguments, const QString name, float de * @property {number} lateMixRight=90 - The apparent distance of the source (percent) in the reverb tail. * @property {number} wetDryMix=50 - Adjusts the wet/dry ratio, from completely dry (0%) to completely wet (100%). */ -AudioEffectOptions::AudioEffectOptions(ScriptValuePointer arguments) { +AudioEffectOptions::AudioEffectOptions(const ScriptValue& arguments) { setOption(arguments, BANDWIDTH_HANDLE, BANDWIDTH_DEFAULT, _bandwidth); setOption(arguments, PRE_DELAY_HANDLE, PRE_DELAY_DEFAULT, _preDelay); setOption(arguments, LATE_DELAY_HANDLE, LATE_DELAY_DEFAULT, _lateDelay); @@ -149,6 +149,6 @@ AudioEffectOptions& AudioEffectOptions::operator=(const AudioEffectOptions &othe return *this; } -ScriptValuePointer AudioEffectOptions::constructor(ScriptContext* context, ScriptEngine* engine) { +ScriptValue AudioEffectOptions::constructor(ScriptContext* context, ScriptEngine* engine) { return engine->newQObject(new AudioEffectOptions(context->argument(0))); } diff --git a/libraries/audio/src/AudioEffectOptions.h b/libraries/audio/src/AudioEffectOptions.h index 4f02a765f6..7ac2c83a24 100644 --- a/libraries/audio/src/AudioEffectOptions.h +++ b/libraries/audio/src/AudioEffectOptions.h @@ -12,12 +12,10 @@ #define hifi_AudioEffectOptions_h #include -#include +#include class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * Audio effect options used by the {@link Audio} API. @@ -82,11 +80,11 @@ class AudioEffectOptions : public QObject { Q_PROPERTY(float wetDryMix READ getWetDryMix WRITE setWetDryMix) public: - AudioEffectOptions(ScriptValuePointer arguments = ScriptValuePointer()); + AudioEffectOptions(const ScriptValue& arguments = ScriptValue()); AudioEffectOptions(const AudioEffectOptions &other); AudioEffectOptions& operator=(const AudioEffectOptions &other); - static ScriptValuePointer constructor(ScriptContext* context, ScriptEngine* engine); + static ScriptValue constructor(ScriptContext* context, ScriptEngine* engine); float getBandwidth() const { return _bandwidth; } void setBandwidth(float bandwidth) { _bandwidth = bandwidth; } diff --git a/libraries/audio/src/AudioInjectorOptions.cpp b/libraries/audio/src/AudioInjectorOptions.cpp index 27ca80687f..94597e4757 100644 --- a/libraries/audio/src/AudioInjectorOptions.cpp +++ b/libraries/audio/src/AudioInjectorOptions.cpp @@ -32,18 +32,18 @@ AudioInjectorOptions::AudioInjectorOptions() : { } -ScriptValuePointer injectorOptionsToScriptValue(ScriptEngine* engine, const AudioInjectorOptions& injectorOptions) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue injectorOptionsToScriptValue(ScriptEngine* engine, const AudioInjectorOptions& injectorOptions) { + ScriptValue obj = engine->newObject(); if (injectorOptions.positionSet) { - obj->setProperty("position", vec3ToScriptValue(engine, injectorOptions.position)); + obj.setProperty("position", vec3ToScriptValue(engine, injectorOptions.position)); } - obj->setProperty("volume", injectorOptions.volume); - obj->setProperty("loop", injectorOptions.loop); - obj->setProperty("orientation", quatToScriptValue(engine, injectorOptions.orientation)); - obj->setProperty("ignorePenumbra", injectorOptions.ignorePenumbra); - obj->setProperty("localOnly", injectorOptions.localOnly); - obj->setProperty("secondOffset", injectorOptions.secondOffset); - obj->setProperty("pitch", injectorOptions.pitch); + obj.setProperty("volume", injectorOptions.volume); + obj.setProperty("loop", injectorOptions.loop); + obj.setProperty("orientation", quatToScriptValue(engine, injectorOptions.orientation)); + obj.setProperty("ignorePenumbra", injectorOptions.ignorePenumbra); + obj.setProperty("localOnly", injectorOptions.localOnly); + obj.setProperty("secondOffset", injectorOptions.secondOffset); + obj.setProperty("pitch", injectorOptions.pitch); return obj; } @@ -66,8 +66,8 @@ ScriptValuePointer injectorOptionsToScriptValue(ScriptEngine* engine, const Audi * @property {boolean} ignorePenumbra=false -

Deprecated: This property is deprecated and will be * removed.

*/ -void injectorOptionsFromScriptValue(const ScriptValuePointer& object, AudioInjectorOptions& injectorOptions) { - if (!object || !object->isObject()) { +void injectorOptionsFromScriptValue(const ScriptValue& object, AudioInjectorOptions& injectorOptions) { + if (!object.isObject()) { qWarning() << "Audio injector options is not an object."; return; } @@ -77,48 +77,48 @@ void injectorOptionsFromScriptValue(const ScriptValuePointer& object, AudioInjec } injectorOptions.positionSet = false; - ScriptValueIteratorPointer it(object->newIterator()); + ScriptValueIteratorPointer it(object.newIterator()); while (it->hasNext()) { it->next(); if (it->name() == "position") { - vec3FromScriptValue(object->property("position"), injectorOptions.position); + vec3FromScriptValue(object.property("position"), injectorOptions.position); injectorOptions.positionSet = true; } else if (it->name() == "orientation") { - quatFromScriptValue(object->property("orientation"), injectorOptions.orientation); + quatFromScriptValue(object.property("orientation"), injectorOptions.orientation); } else if (it->name() == "volume") { - if (it->value()->isNumber()) { - injectorOptions.volume = it->value()->toNumber(); + if (it->value().isNumber()) { + injectorOptions.volume = it->value().toNumber(); } else { qCWarning(audio) << "Audio injector options: volume is not a number"; } } else if (it->name() == "loop") { - if (it->value()->isBool()) { - injectorOptions.loop = it->value()->toBool(); + if (it->value().isBool()) { + injectorOptions.loop = it->value().toBool(); } else { qCWarning(audio) << "Audio injector options: loop is not a boolean"; } } else if (it->name() == "ignorePenumbra") { - if (it->value()->isBool()) { - injectorOptions.ignorePenumbra = it->value()->toBool(); + if (it->value().isBool()) { + injectorOptions.ignorePenumbra = it->value().toBool(); } else { qCWarning(audio) << "Audio injector options: ignorePenumbra is not a boolean"; } } else if (it->name() == "localOnly") { - if (it->value()->isBool()) { - injectorOptions.localOnly = it->value()->toBool(); + if (it->value().isBool()) { + injectorOptions.localOnly = it->value().toBool(); } else { qCWarning(audio) << "Audio injector options: localOnly is not a boolean"; } } else if (it->name() == "secondOffset") { - if (it->value()->isNumber()) { - injectorOptions.secondOffset = it->value()->toNumber(); + if (it->value().isNumber()) { + injectorOptions.secondOffset = it->value().toNumber(); } else { qCWarning(audio) << "Audio injector options: secondOffset is not a number"; } } else if (it->name() == "pitch") { - if (it->value()->isNumber()) { - injectorOptions.pitch = it->value()->toNumber(); + if (it->value().isNumber()) { + injectorOptions.pitch = it->value().toNumber(); } else { qCWarning(audio) << "Audio injector options: pitch is not a number"; } diff --git a/libraries/audio/src/AudioInjectorOptions.h b/libraries/audio/src/AudioInjectorOptions.h index 3605bc2a06..0dd3ab1cb1 100644 --- a/libraries/audio/src/AudioInjectorOptions.h +++ b/libraries/audio/src/AudioInjectorOptions.h @@ -14,11 +14,9 @@ #include #include -#include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class AudioInjectorOptions { public: @@ -38,7 +36,7 @@ public: Q_DECLARE_METATYPE(AudioInjectorOptions); -ScriptValuePointer injectorOptionsToScriptValue(ScriptEngine* engine, const AudioInjectorOptions& injectorOptions); -void injectorOptionsFromScriptValue(const ScriptValuePointer& object, AudioInjectorOptions& injectorOptions); +ScriptValue injectorOptionsToScriptValue(ScriptEngine* engine, const AudioInjectorOptions& injectorOptions); +void injectorOptionsFromScriptValue(const ScriptValue& object, AudioInjectorOptions& injectorOptions); #endif // hifi_AudioInjectorOptions_h diff --git a/libraries/audio/src/ScriptAudioInjector.cpp b/libraries/audio/src/ScriptAudioInjector.cpp index 67a761c149..d50bf6f163 100644 --- a/libraries/audio/src/ScriptAudioInjector.cpp +++ b/libraries/audio/src/ScriptAudioInjector.cpp @@ -23,7 +23,7 @@ STATIC_SCRIPT_INITIALIZER(+[](ScriptManager* manager) { scriptRegisterMetaType(scriptEngine, injectorToScriptValue, injectorFromScriptValue); }); -ScriptValuePointer injectorToScriptValue(ScriptEngine* engine, ScriptAudioInjector* const& in) { +ScriptValue injectorToScriptValue(ScriptEngine* engine, ScriptAudioInjector* const& in) { // The AudioScriptingInterface::playSound method can return null, so we need to account for that. if (!in) { return engine->nullValue(); @@ -32,8 +32,8 @@ ScriptValuePointer injectorToScriptValue(ScriptEngine* engine, ScriptAudioInject return engine->newQObject(in, ScriptEngine::ScriptOwnership); } -void injectorFromScriptValue(const ScriptValuePointer& object, ScriptAudioInjector*& out) { - out = qobject_cast(object->toQObject()); +void injectorFromScriptValue(const ScriptValue& object, ScriptAudioInjector*& out) { + out = qobject_cast(object.toQObject()); } ScriptAudioInjector::ScriptAudioInjector(const AudioInjectorPointer& injector) : diff --git a/libraries/audio/src/ScriptAudioInjector.h b/libraries/audio/src/ScriptAudioInjector.h index 5ff594643d..382ce16772 100644 --- a/libraries/audio/src/ScriptAudioInjector.h +++ b/libraries/audio/src/ScriptAudioInjector.h @@ -16,13 +16,11 @@ #define hifi_ScriptAudioInjector_h #include -#include +#include #include "AudioInjectorManager.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * Plays or "injects" the content of an audio file. @@ -148,13 +146,13 @@ signals: private: QWeakPointer _injector; - friend ScriptValuePointer injectorToScriptValue(ScriptEngine* engine, ScriptAudioInjector* const& in); + friend ScriptValue injectorToScriptValue(ScriptEngine* engine, ScriptAudioInjector* const& in); }; Q_DECLARE_METATYPE(ScriptAudioInjector*) -ScriptValuePointer injectorToScriptValue(ScriptEngine* engine, ScriptAudioInjector* const& in); -void injectorFromScriptValue(const ScriptValuePointer& object, ScriptAudioInjector*& out); +ScriptValue injectorToScriptValue(ScriptEngine* engine, ScriptAudioInjector* const& in); +void injectorFromScriptValue(const ScriptValue& object, ScriptAudioInjector*& out); #endif // hifi_ScriptAudioInjector_h diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 84eb731cd5..6329ade515 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -424,12 +424,12 @@ SoundProcessor::AudioProperties SoundProcessor::interpretAsMP3(const QByteArray& } -ScriptValuePointer soundSharedPointerToScriptValue(ScriptEngine* engine, const SharedSoundPointer& in) { +ScriptValue soundSharedPointerToScriptValue(ScriptEngine* engine, const SharedSoundPointer& in) { return engine->newQObject(new SoundScriptingInterface(in), ScriptEngine::ScriptOwnership); } -void soundSharedPointerFromScriptValue(const ScriptValuePointer& object, SharedSoundPointer& out) { - if (auto soundInterface = qobject_cast(object->toQObject())) { +void soundSharedPointerFromScriptValue(const ScriptValue& object, SharedSoundPointer& out) { + if (auto soundInterface = qobject_cast(object.toQObject())) { out = soundInterface->getSound(); } } diff --git a/libraries/audio/src/Sound.h b/libraries/audio/src/Sound.h index 976c543c29..f98822249f 100644 --- a/libraries/audio/src/Sound.h +++ b/libraries/audio/src/Sound.h @@ -19,14 +19,13 @@ #include #include +#include #include "AudioConstants.h" class AudioData; class ScriptEngine; -class ScriptValue; using AudioDataPointer = std::shared_ptr; -using ScriptValuePointer = QSharedPointer; Q_DECLARE_METATYPE(AudioDataPointer); @@ -172,7 +171,7 @@ private: }; Q_DECLARE_METATYPE(SharedSoundPointer) -ScriptValuePointer soundSharedPointerToScriptValue(ScriptEngine* engine, const SharedSoundPointer& in); -void soundSharedPointerFromScriptValue(const ScriptValuePointer& object, SharedSoundPointer& out); +ScriptValue soundSharedPointerToScriptValue(ScriptEngine* engine, const SharedSoundPointer& in); +void soundSharedPointerFromScriptValue(const ScriptValue& object, SharedSoundPointer& out); #endif // hifi_Sound_h diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index df95f3de52..0c2992cebd 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -3159,40 +3159,40 @@ glm::mat4 AvatarData::getControllerRightHandMatrix() const { * @property {SubmeshIntersection} extraInfo - Extra information on the mesh intersected if mesh was picked against, * {} if it wasn't. */ -ScriptValuePointer RayToAvatarIntersectionResultToScriptValue(ScriptEngine* engine, const RayToAvatarIntersectionResult& value) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("intersects", value.intersects); - ScriptValuePointer avatarIDValue = quuidToScriptValue(engine, value.avatarID); - obj->setProperty("avatarID", avatarIDValue); - obj->setProperty("distance", value.distance); - obj->setProperty("face", boxFaceToString(value.face)); - ScriptValuePointer intersection = vec3ToScriptValue(engine, value.intersection); +ScriptValue RayToAvatarIntersectionResultToScriptValue(ScriptEngine* engine, const RayToAvatarIntersectionResult& value) { + ScriptValue obj = engine->newObject(); + obj.setProperty("intersects", value.intersects); + ScriptValue avatarIDValue = quuidToScriptValue(engine, value.avatarID); + obj.setProperty("avatarID", avatarIDValue); + obj.setProperty("distance", value.distance); + obj.setProperty("face", boxFaceToString(value.face)); + ScriptValue intersection = vec3ToScriptValue(engine, value.intersection); - obj->setProperty("intersection", intersection); - ScriptValuePointer surfaceNormal = vec3ToScriptValue(engine, value.surfaceNormal); - obj->setProperty("surfaceNormal", surfaceNormal); - obj->setProperty("jointIndex", value.jointIndex); - obj->setProperty("extraInfo", engine->toScriptValue(value.extraInfo)); + obj.setProperty("intersection", intersection); + ScriptValue surfaceNormal = vec3ToScriptValue(engine, value.surfaceNormal); + obj.setProperty("surfaceNormal", surfaceNormal); + obj.setProperty("jointIndex", value.jointIndex); + obj.setProperty("extraInfo", engine->toScriptValue(value.extraInfo)); return obj; } -void RayToAvatarIntersectionResultFromScriptValue(const ScriptValuePointer& object, RayToAvatarIntersectionResult& value) { - value.intersects = object->property("intersects")->toVariant().toBool(); - ScriptValuePointer avatarIDValue = object->property("avatarID"); +void RayToAvatarIntersectionResultFromScriptValue(const ScriptValue& object, RayToAvatarIntersectionResult& value) { + value.intersects = object.property("intersects").toVariant().toBool(); + ScriptValue avatarIDValue = object.property("avatarID"); quuidFromScriptValue(avatarIDValue, value.avatarID); - value.distance = object->property("distance")->toVariant().toFloat(); - value.face = boxFaceFromString(object->property("face")->toVariant().toString()); + value.distance = object.property("distance").toVariant().toFloat(); + value.face = boxFaceFromString(object.property("face").toVariant().toString()); - ScriptValuePointer intersection = object->property("intersection"); - if (intersection && intersection->isValid()) { + ScriptValue intersection = object.property("intersection"); + if (intersection.isValid()) { vec3FromScriptValue(intersection, value.intersection); } - ScriptValuePointer surfaceNormal = object->property("surfaceNormal"); - if (surfaceNormal && surfaceNormal->isValid()) { + ScriptValue surfaceNormal = object.property("surfaceNormal"); + if (surfaceNormal.isValid()) { vec3FromScriptValue(surfaceNormal, value.surfaceNormal); } - value.jointIndex = object->property("jointIndex")->toInt32(); - value.extraInfo = object->property("extraInfo")->toVariant().toMap(); + value.jointIndex = object.property("jointIndex").toInt32(); + value.extraInfo = object.property("extraInfo").toVariant().toMap(); } // these coefficients can be changed via JS for experimental tuning @@ -3205,8 +3205,8 @@ float AvatarData::_avatarSortCoefficientAge { 1.0f }; * An object with the UUIDs of avatar entities as keys and avatar entity properties objects as values. * @typedef {Object.} AvatarEntityMap */ -ScriptValuePointer AvatarEntityMapToScriptValue(ScriptEngine* engine, const AvatarEntityMap& value) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue AvatarEntityMapToScriptValue(ScriptEngine* engine, const AvatarEntityMap& value) { + ScriptValue obj = engine->newObject(); for (auto entityID : value.keys()) { QByteArray entityProperties = value.value(entityID); OVERTE_IGNORE_DEPRECATED_BEGIN @@ -3218,22 +3218,22 @@ ScriptValuePointer AvatarEntityMapToScriptValue(ScriptEngine* engine, const Avat QVariant variantEntityProperties = jsonEntityProperties.toVariant(); QVariantMap entityPropertiesMap = variantEntityProperties.toMap(); - ScriptValuePointer scriptEntityProperties = variantMapToScriptValue(entityPropertiesMap, *engine); + ScriptValue scriptEntityProperties = variantMapToScriptValue(entityPropertiesMap, *engine); QString key = entityID.toString(); - obj->setProperty(key, scriptEntityProperties); + obj.setProperty(key, scriptEntityProperties); } return obj; } -void AvatarEntityMapFromScriptValue(const ScriptValuePointer& object, AvatarEntityMap& value) { - ScriptValueIteratorPointer itr(object->newIterator()); +void AvatarEntityMapFromScriptValue(const ScriptValue& object, AvatarEntityMap& value) { + ScriptValueIteratorPointer itr(object.newIterator()); while (itr->hasNext()) { itr->next(); QUuid EntityID = QUuid(itr->name()); - ScriptValuePointer scriptEntityProperties = itr->value(); - QVariant variantEntityProperties = scriptEntityProperties->toVariant(); + ScriptValue scriptEntityProperties = itr->value(); + QVariant variantEntityProperties = scriptEntityProperties.toVariant(); QJsonDocument jsonEntityProperties = QJsonDocument::fromVariant(variantEntityProperties); OVERTE_IGNORE_DEPRECATED_BEGIN QByteArray binaryEntityProperties = jsonEntityProperties.toBinaryData(); diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 8ac03fb62b..d6a0d5e6fa 100644 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -34,7 +34,6 @@ #include #include #include -#include #include #include @@ -51,6 +50,7 @@ #include #include #include "Scriptable.h" +#include #include "AABox.h" #include "AvatarTraits.h" @@ -58,8 +58,6 @@ #include "PathUtils.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; using AvatarSharedPointer = std::shared_ptr; using AvatarWeakPointer = std::weak_ptr; @@ -1973,8 +1971,8 @@ public: QVariantMap extraInfo; }; Q_DECLARE_METATYPE(RayToAvatarIntersectionResult) -ScriptValuePointer RayToAvatarIntersectionResultToScriptValue(ScriptEngine* engine, const RayToAvatarIntersectionResult& results); -void RayToAvatarIntersectionResultFromScriptValue(const ScriptValuePointer& object, RayToAvatarIntersectionResult& results); +ScriptValue RayToAvatarIntersectionResultToScriptValue(ScriptEngine* engine, const RayToAvatarIntersectionResult& results); +void RayToAvatarIntersectionResultFromScriptValue(const ScriptValue& object, RayToAvatarIntersectionResult& results); // No JSDoc because it's not provided as a type to the script engine. class ParabolaToAvatarIntersectionResult { @@ -1991,8 +1989,8 @@ public: Q_DECLARE_METATYPE(AvatarEntityMap) -ScriptValuePointer AvatarEntityMapToScriptValue(ScriptEngine* engine, const AvatarEntityMap& value); -void AvatarEntityMapFromScriptValue(const ScriptValuePointer& object, AvatarEntityMap& value); +ScriptValue AvatarEntityMapToScriptValue(ScriptEngine* engine, const AvatarEntityMap& value); +void AvatarEntityMapFromScriptValue(const ScriptValue& object, AvatarEntityMap& value); // faux joint indexes (-1 means invalid) const int NO_JOINT_INDEX = 65535; // -1 diff --git a/libraries/avatars/src/ScriptAvatarData.cpp b/libraries/avatars/src/ScriptAvatarData.cpp index 6f322190c0..5b33f53cd5 100644 --- a/libraries/avatars/src/ScriptAvatarData.cpp +++ b/libraries/avatars/src/ScriptAvatarData.cpp @@ -14,11 +14,11 @@ #include #include -ScriptValuePointer avatarDataToScriptValue(ScriptEngine* engine, ScriptAvatarData* const& in) { +ScriptValue avatarDataToScriptValue(ScriptEngine* engine, ScriptAvatarData* const& in) { return engine->newQObject(in, ScriptEngine::ScriptOwnership); } -void avatarDataFromScriptValue(const ScriptValuePointer& object, ScriptAvatarData*& out) { +void avatarDataFromScriptValue(const ScriptValue& object, ScriptAvatarData*& out) { // This is not implemented because there are no slots/properties that take an AvatarSharedPointer from a script assert(false); out = nullptr; diff --git a/libraries/baking/src/MaterialBaker.cpp b/libraries/baking/src/MaterialBaker.cpp index afe9129ebb..f8d846285c 100644 --- a/libraries/baking/src/MaterialBaker.cpp +++ b/libraries/baking/src/MaterialBaker.cpp @@ -212,13 +212,13 @@ void MaterialBaker::outputMaterial() { if (_materialResource->parsedMaterials.networkMaterials.size() == 1) { auto networkMaterial = _materialResource->parsedMaterials.networkMaterials.begin(); auto scriptableMaterial = scriptable::ScriptableMaterial(networkMaterial->second); - QVariant materialVariant = scriptable::scriptableMaterialToScriptValue(_scriptEngine.data(), scriptableMaterial)->toVariant(); + QVariant materialVariant = scriptable::scriptableMaterialToScriptValue(_scriptEngine.data(), scriptableMaterial).toVariant(); json.insert("materials", QJsonDocument::fromVariant(materialVariant).object()); } else { QJsonArray materialArray; for (auto networkMaterial : _materialResource->parsedMaterials.networkMaterials) { auto scriptableMaterial = scriptable::ScriptableMaterial(networkMaterial.second); - QVariant materialVariant = scriptable::scriptableMaterialToScriptValue(_scriptEngine.data(), scriptableMaterial)->toVariant(); + QVariant materialVariant = scriptable::scriptableMaterialToScriptValue(_scriptEngine.data(), scriptableMaterial).toVariant(); materialArray.append(QJsonDocument::fromVariant(materialVariant).object()); } json.insert("materials", materialArray); diff --git a/libraries/controllers/src/controllers/Pose.cpp b/libraries/controllers/src/controllers/Pose.cpp index ec58a6443e..bfb6f6afc4 100644 --- a/libraries/controllers/src/controllers/Pose.cpp +++ b/libraries/controllers/src/controllers/Pose.cpp @@ -40,25 +40,25 @@ namespace controller { * @property {Vec3} angularVelocity - Angular velocity in rad/s. * @property {boolean} valid - true if the pose is valid, otherwise false. */ - ScriptValuePointer Pose::toScriptValue(ScriptEngine* engine, const Pose& pose) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("translation", vec3ToScriptValue(engine, pose.translation)); - obj->setProperty("rotation", quatToScriptValue(engine, pose.rotation)); - obj->setProperty("velocity", vec3ToScriptValue(engine, pose.velocity)); - obj->setProperty("angularVelocity", vec3ToScriptValue(engine, pose.angularVelocity)); - obj->setProperty("valid", pose.valid); + ScriptValue Pose::toScriptValue(ScriptEngine* engine, const Pose& pose) { + ScriptValue obj = engine->newObject(); + obj.setProperty("translation", vec3ToScriptValue(engine, pose.translation)); + obj.setProperty("rotation", quatToScriptValue(engine, pose.rotation)); + obj.setProperty("velocity", vec3ToScriptValue(engine, pose.velocity)); + obj.setProperty("angularVelocity", vec3ToScriptValue(engine, pose.angularVelocity)); + obj.setProperty("valid", pose.valid); return obj; } - void Pose::fromScriptValue(const ScriptValuePointer& object, Pose& pose) { - auto translation = object->property("translation"); - auto rotation = object->property("rotation"); - auto velocity = object->property("velocity"); - auto angularVelocity = object->property("angularVelocity"); - if (translation->isValid() && - rotation->isValid() && - velocity->isValid() && - angularVelocity->isValid()) { + void Pose::fromScriptValue(const ScriptValue& object, Pose& pose) { + auto translation = object.property("translation"); + auto rotation = object.property("rotation"); + auto velocity = object.property("velocity"); + auto angularVelocity = object.property("angularVelocity"); + if (translation.isValid() && + rotation.isValid() && + velocity.isValid() && + angularVelocity.isValid()) { vec3FromScriptValue(translation, pose.translation); quatFromScriptValue(rotation, pose.rotation); vec3FromScriptValue(velocity, pose.velocity); diff --git a/libraries/controllers/src/controllers/Pose.h b/libraries/controllers/src/controllers/Pose.h index 0dff0293d1..7a71c7c5bb 100644 --- a/libraries/controllers/src/controllers/Pose.h +++ b/libraries/controllers/src/controllers/Pose.h @@ -10,11 +10,9 @@ #pragma once #ifndef hifi_controllers_Pose_h #define hifi_controllers_Pose_h -#include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; #include @@ -46,8 +44,8 @@ namespace controller { Pose transform(const glm::mat4& mat) const; Pose postTransform(const glm::mat4& mat) const; - static ScriptValuePointer toScriptValue(ScriptEngine* engine, const Pose& event); - static void fromScriptValue(const ScriptValuePointer& object, Pose& event); + static ScriptValue toScriptValue(ScriptEngine* engine, const Pose& event); + static void fromScriptValue(const ScriptValue& object, Pose& event); }; } diff --git a/libraries/controllers/src/controllers/ScriptingInterface.cpp b/libraries/controllers/src/controllers/ScriptingInterface.cpp index 396e7cb5d4..9e538b999b 100644 --- a/libraries/controllers/src/controllers/ScriptingInterface.cpp +++ b/libraries/controllers/src/controllers/ScriptingInterface.cpp @@ -33,12 +33,12 @@ Q_DECLARE_METATYPE(controller::InputController*) //static int inputControllerPointerId = qRegisterMetaType(); -ScriptValuePointer inputControllerToScriptValue(ScriptEngine* engine, controller::InputController* const& in) { +ScriptValue inputControllerToScriptValue(ScriptEngine* engine, controller::InputController* const& in) { return engine->newQObject(in, ScriptEngine::QtOwnership); } -void inputControllerFromScriptValue(const ScriptValuePointer& object, controller::InputController*& out) { - out = qobject_cast(object->toQObject()); +void inputControllerFromScriptValue(const ScriptValue& object, controller::InputController*& out) { + out = qobject_cast(object.toQObject()); } STATIC_SCRIPT_INITIALIZER(+[](ScriptManager* manager) { diff --git a/libraries/controllers/src/controllers/UserInputMapper.cpp b/libraries/controllers/src/controllers/UserInputMapper.cpp index 6ac29c85f1..59427671eb 100644 --- a/libraries/controllers/src/controllers/UserInputMapper.cpp +++ b/libraries/controllers/src/controllers/UserInputMapper.cpp @@ -392,58 +392,58 @@ int inputPairMetaTypeId = qRegisterMetaType(); int poseMetaTypeId = qRegisterMetaType("Pose"); int handMetaTypeId = qRegisterMetaType(); -ScriptValuePointer inputToScriptValue(ScriptEngine* engine, const Input& input); -void inputFromScriptValue(const ScriptValuePointer& object, Input& input); -ScriptValuePointer actionToScriptValue(ScriptEngine* engine, const Action& action); -void actionFromScriptValue(const ScriptValuePointer& object, Action& action); -ScriptValuePointer inputPairToScriptValue(ScriptEngine* engine, const Input::NamedPair& inputPair); -void inputPairFromScriptValue(const ScriptValuePointer& object, Input::NamedPair& inputPair); -ScriptValuePointer handToScriptValue(ScriptEngine* engine, const controller::Hand& hand); -void handFromScriptValue(const ScriptValuePointer& object, controller::Hand& hand); +ScriptValue inputToScriptValue(ScriptEngine* engine, const Input& input); +void inputFromScriptValue(const ScriptValue& object, Input& input); +ScriptValue actionToScriptValue(ScriptEngine* engine, const Action& action); +void actionFromScriptValue(const ScriptValue& object, Action& action); +ScriptValue inputPairToScriptValue(ScriptEngine* engine, const Input::NamedPair& inputPair); +void inputPairFromScriptValue(const ScriptValue& object, Input::NamedPair& inputPair); +ScriptValue handToScriptValue(ScriptEngine* engine, const controller::Hand& hand); +void handFromScriptValue(const ScriptValue& object, controller::Hand& hand); -ScriptValuePointer inputToScriptValue(ScriptEngine* engine, const Input& input) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("device", input.getDevice()); - obj->setProperty("channel", input.getChannel()); - obj->setProperty("type", (unsigned short)input.getType()); - obj->setProperty("id", input.getID()); +ScriptValue inputToScriptValue(ScriptEngine* engine, const Input& input) { + ScriptValue obj = engine->newObject(); + obj.setProperty("device", input.getDevice()); + obj.setProperty("channel", input.getChannel()); + obj.setProperty("type", (unsigned short)input.getType()); + obj.setProperty("id", input.getID()); return obj; } -void inputFromScriptValue(const ScriptValuePointer& object, Input& input) { - input.id = object->property("id")->toInt32(); +void inputFromScriptValue(const ScriptValue& object, Input& input) { + input.id = object.property("id").toInt32(); } -ScriptValuePointer actionToScriptValue(ScriptEngine* engine, const Action& action) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue actionToScriptValue(ScriptEngine* engine, const Action& action) { + ScriptValue obj = engine->newObject(); auto userInputMapper = DependencyManager::get(); - obj->setProperty("action", (int)action); - obj->setProperty("actionName", userInputMapper->getActionName(action)); + obj.setProperty("action", (int)action); + obj.setProperty("actionName", userInputMapper->getActionName(action)); return obj; } -void actionFromScriptValue(const ScriptValuePointer& object, Action& action) { - action = Action(object->property("action")->toVariant().toInt()); +void actionFromScriptValue(const ScriptValue& object, Action& action) { + action = Action(object.property("action").toVariant().toInt()); } -ScriptValuePointer inputPairToScriptValue(ScriptEngine* engine, const Input::NamedPair& inputPair) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("input", inputToScriptValue(engine, inputPair.first)); - obj->setProperty("inputName", inputPair.second); +ScriptValue inputPairToScriptValue(ScriptEngine* engine, const Input::NamedPair& inputPair) { + ScriptValue obj = engine->newObject(); + obj.setProperty("input", inputToScriptValue(engine, inputPair.first)); + obj.setProperty("inputName", inputPair.second); return obj; } -void inputPairFromScriptValue(const ScriptValuePointer& object, Input::NamedPair& inputPair) { - inputFromScriptValue(object->property("input"), inputPair.first); - inputPair.second = QString(object->property("inputName")->toVariant().toString()); +void inputPairFromScriptValue(const ScriptValue& object, Input::NamedPair& inputPair) { + inputFromScriptValue(object.property("input"), inputPair.first); + inputPair.second = QString(object.property("inputName").toVariant().toString()); } -ScriptValuePointer handToScriptValue(ScriptEngine* engine, const controller::Hand& hand) { +ScriptValue handToScriptValue(ScriptEngine* engine, const controller::Hand& hand) { return engine->newValue((int)hand); } -void handFromScriptValue(const ScriptValuePointer& object, controller::Hand& hand) { - hand = Hand(object->toVariant().toInt()); +void handFromScriptValue(const ScriptValue& object, controller::Hand& hand) { + hand = Hand(object.toVariant().toInt()); } void UserInputMapper::registerControllerTypes(ScriptEngine* engine) { @@ -662,21 +662,21 @@ Endpoint::Pointer UserInputMapper::endpointFor(const QJSValue& endpoint) { return Endpoint::Pointer(); } -Endpoint::Pointer UserInputMapper::endpointFor(const ScriptValuePointer& endpoint) { - if (endpoint->isNumber()) { - return endpointFor(Input(endpoint->toInt32())); +Endpoint::Pointer UserInputMapper::endpointFor(const ScriptValue& endpoint) { + if (endpoint.isNumber()) { + return endpointFor(Input(endpoint.toInt32())); } - if (endpoint->isFunction()) { + if (endpoint.isFunction()) { auto result = std::make_shared(endpoint); return result; } - if (endpoint->isArray()) { - int length = endpoint->property("length")->toInteger(); + if (endpoint.isArray()) { + int length = endpoint.property("length").toInteger(); Endpoint::List children; for (int i = 0; i < length; i++) { - ScriptValuePointer arrayItem = endpoint->property(i); + ScriptValue arrayItem = endpoint.property(i); Endpoint::Pointer destination = endpointFor(arrayItem); if (!destination) { return Endpoint::Pointer(); @@ -687,7 +687,7 @@ Endpoint::Pointer UserInputMapper::endpointFor(const ScriptValuePointer& endpoin } - qWarning() << "Unsupported input type " << endpoint->toString(); + qWarning() << "Unsupported input type " << endpoint.toString(); return Endpoint::Pointer(); } @@ -887,12 +887,12 @@ Conditional::Pointer UserInputMapper::conditionalFor(const QJSValue& condition) return Conditional::Pointer(); } -Conditional::Pointer UserInputMapper::conditionalFor(const ScriptValuePointer& condition) { - if (condition->isArray()) { - int length = condition->property("length")->toInteger(); +Conditional::Pointer UserInputMapper::conditionalFor(const ScriptValue& condition) { + if (condition.isArray()) { + int length = condition.property("length").toInteger(); Conditional::List children; for (int i = 0; i < length; i++) { - Conditional::Pointer destination = conditionalFor(condition->property(i)); + Conditional::Pointer destination = conditionalFor(condition.property(i)); if (!destination) { return Conditional::Pointer(); } @@ -901,15 +901,15 @@ Conditional::Pointer UserInputMapper::conditionalFor(const ScriptValuePointer& c return std::make_shared(children); } - if (condition->isNumber()) { - return conditionalFor(Input(condition->toInt32())); + if (condition.isNumber()) { + return conditionalFor(Input(condition.toInt32())); } - if (condition->isFunction()) { + if (condition.isFunction()) { return std::make_shared(condition); } - qWarning() << "Unsupported conditional type " << condition->toString(); + qWarning() << "Unsupported conditional type " << condition.toString(); return Conditional::Pointer(); } diff --git a/libraries/controllers/src/controllers/UserInputMapper.h b/libraries/controllers/src/controllers/UserInputMapper.h index 6e67ca22ee..3fcce461c0 100644 --- a/libraries/controllers/src/controllers/UserInputMapper.h +++ b/libraries/controllers/src/controllers/UserInputMapper.h @@ -16,7 +16,6 @@ #include #include #include -#include #include @@ -34,7 +33,6 @@ class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; namespace controller { @@ -168,10 +166,10 @@ namespace controller { void enableMapping(const MappingPointer& mapping); void disableMapping(const MappingPointer& mapping); EndpointPointer endpointFor(const QJSValue& endpoint); - EndpointPointer endpointFor(const ScriptValuePointer& endpoint); + EndpointPointer endpointFor(const ScriptValue& endpoint); EndpointPointer compositeEndpointFor(EndpointPointer first, EndpointPointer second); ConditionalPointer conditionalFor(const QJSValue& endpoint); - ConditionalPointer conditionalFor(const ScriptValuePointer& endpoint); + ConditionalPointer conditionalFor(const ScriptValue& endpoint); ConditionalPointer conditionalFor(const Input& endpoint) const; MappingPointer parseMapping(const QJsonValue& json); diff --git a/libraries/controllers/src/controllers/impl/MappingBuilderProxy.cpp b/libraries/controllers/src/controllers/impl/MappingBuilderProxy.cpp index 8c24ac079c..64c837f34b 100644 --- a/libraries/controllers/src/controllers/impl/MappingBuilderProxy.cpp +++ b/libraries/controllers/src/controllers/impl/MappingBuilderProxy.cpp @@ -27,8 +27,8 @@ QObject* MappingBuilderProxy::fromQml(const QJSValue& source) { return from(sourceEndpoint); } -QObject* MappingBuilderProxy::from(const ScriptValuePointer& source) { - qCDebug(controllers) << "Creating new Route builder proxy from " << source->toString(); +QObject* MappingBuilderProxy::from(const ScriptValue& source) { + qCDebug(controllers) << "Creating new Route builder proxy from " << source.toString(); auto sourceEndpoint = _parent.endpointFor(source); return from(sourceEndpoint); } @@ -50,7 +50,7 @@ QObject* MappingBuilderProxy::makeAxisQml(const QJSValue& source1, const QJSValu return from(_parent.compositeEndpointFor(source1Endpoint, source2Endpoint)); } -QObject* MappingBuilderProxy::makeAxis(const ScriptValuePointer& source1, const ScriptValuePointer& source2) { +QObject* MappingBuilderProxy::makeAxis(const ScriptValue& source1, const ScriptValue& source2) { auto source1Endpoint = _parent.endpointFor(source1); auto source2Endpoint = _parent.endpointFor(source2); return from(_parent.compositeEndpointFor(source1Endpoint, source2Endpoint)); diff --git a/libraries/controllers/src/controllers/impl/MappingBuilderProxy.h b/libraries/controllers/src/controllers/impl/MappingBuilderProxy.h index 3d03c784b4..e86399b12a 100644 --- a/libraries/controllers/src/controllers/impl/MappingBuilderProxy.h +++ b/libraries/controllers/src/controllers/impl/MappingBuilderProxy.h @@ -11,7 +11,6 @@ #include #include -#include #include "Mapping.h" #include "Endpoint.h" @@ -19,7 +18,6 @@ class QJSValue; class QJsonValue; class ScriptValue; -using ScriptValuePointer = QSharedPointer; namespace controller { @@ -167,7 +165,7 @@ public: * of the route data. If a function, it must return a number or a {@link Pose} value as the route data. * @returns {RouteObject} A route ready for mapping to an action or function using {@link RouteObject} methods. */ - Q_INVOKABLE QObject* from(const ScriptValuePointer& source); + Q_INVOKABLE QObject* from(const ScriptValue& source); /*@jsdoc * Creates a new {@link RouteObject} from two numeric {@link Controller.Hardware} outputs, one applied in the negative @@ -189,7 +187,7 @@ public: * Controller.disableMapping(MAPPING_NAME); * }); */ - Q_INVOKABLE QObject* makeAxis(const ScriptValuePointer& source1, const ScriptValuePointer& source2); + Q_INVOKABLE QObject* makeAxis(const ScriptValue& source1, const ScriptValue& source2); /*@jsdoc * Enables or disables the mapping. When enabled, the routes in the mapping take effect. diff --git a/libraries/controllers/src/controllers/impl/RouteBuilderProxy.cpp b/libraries/controllers/src/controllers/impl/RouteBuilderProxy.cpp index 010e491fc6..c747e920a4 100644 --- a/libraries/controllers/src/controllers/impl/RouteBuilderProxy.cpp +++ b/libraries/controllers/src/controllers/impl/RouteBuilderProxy.cpp @@ -44,8 +44,8 @@ void RouteBuilderProxy::toQml(const QJSValue& destination) { return to(destinationEndpoint); } -void RouteBuilderProxy::to(const ScriptValuePointer& destination) { - qCDebug(controllers) << "Completing route " << destination->toString(); +void RouteBuilderProxy::to(const ScriptValue& destination) { + qCDebug(controllers) << "Completing route " << destination.toString(); auto destinationEndpoint = _parent.endpointFor(destination); return to(destinationEndpoint); } @@ -66,7 +66,7 @@ QObject* RouteBuilderProxy::peek(bool enable) { return this; } -QObject* RouteBuilderProxy::when(const ScriptValuePointer& expression) { +QObject* RouteBuilderProxy::when(const ScriptValue& expression) { // FIXME: Support "!" conditional in simple expression and array expression. // Note that "!" is supported when parsing a JSON file, in UserInputMapper::parseConditional(). auto newConditional = _parent.conditionalFor(expression); diff --git a/libraries/controllers/src/controllers/impl/RouteBuilderProxy.h b/libraries/controllers/src/controllers/impl/RouteBuilderProxy.h index 7f6f106b2f..9196a211d3 100644 --- a/libraries/controllers/src/controllers/impl/RouteBuilderProxy.h +++ b/libraries/controllers/src/controllers/impl/RouteBuilderProxy.h @@ -10,7 +10,6 @@ #define hifi_Controllers_Impl_RouteBuilderProxy_h #include -#include #include "Filter.h" #include "Route.h" @@ -21,7 +20,6 @@ class QJSValue; class QJsonValue; class ScriptValue; -using ScriptValuePointer = QSharedPointer; namespace controller { @@ -117,7 +115,7 @@ class RouteBuilderProxy : public QObject { * Controller.disableMapping(MAPPING_NAME); * }); */ - Q_INVOKABLE void to(const ScriptValuePointer& destination); + Q_INVOKABLE void to(const ScriptValue& destination); /*@jsdoc * Enables or disables writing debug information for a route to the program log. @@ -195,7 +193,7 @@ class RouteBuilderProxy : public QObject { * Controller.disableMapping(MAPPING_NAME); * }); */ - Q_INVOKABLE QObject* when(const ScriptValuePointer& expression); + Q_INVOKABLE QObject* when(const ScriptValue& expression); /*@jsdoc * Filters numeric route values to lie between two values; values outside this range are not passed on through the diff --git a/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.cpp b/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.cpp index d868ad343e..bd459ca3ff 100644 --- a/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.cpp +++ b/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.cpp @@ -25,5 +25,5 @@ void ScriptConditional::updateValue() { return; } - _lastValue = _callable->call()->toBool(); + _lastValue = _callable.call().toBool(); } diff --git a/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.h b/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.h index 0ac4cc4434..156fdaff44 100644 --- a/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.h +++ b/libraries/controllers/src/controllers/impl/conditionals/ScriptConditional.h @@ -11,24 +11,21 @@ #define hifi_Controllers_ScriptConditional_h #include -#include +#include #include "../Conditional.h" -class ScriptValue; -using ScriptValuePointer = QSharedPointer; - namespace controller { class ScriptConditional : public QObject, public Conditional { Q_OBJECT; public: - ScriptConditional(const ScriptValuePointer& callable) : _callable(callable) {} + ScriptConditional(const ScriptValue& callable) : _callable(callable) {} virtual bool satisfied() override; protected: Q_INVOKABLE void updateValue(); private: - ScriptValuePointer _callable; + ScriptValue _callable; bool _lastValue { false }; }; diff --git a/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.cpp b/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.cpp index 90184afd23..8ed5222160 100644 --- a/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.cpp +++ b/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.cpp @@ -17,14 +17,14 @@ using namespace controller; -QString formatException(const ScriptValuePointer& exception) { +QString formatException(const ScriptValue& exception) { QString note { "UncaughtException" }; QString result; - const auto message = exception->toString(); - const auto fileName = exception->property("fileName")->toString(); - const auto lineNumber = exception->property("lineNumber")->toString(); - const auto stacktrace = exception->property("stack")->toString(); + const auto message = exception.toString(); + const auto fileName = exception.property("fileName").toString(); + const auto lineNumber = exception.property("lineNumber").toString(); + const auto stacktrace = exception.property("stack").toString(); const QString SCRIPT_EXCEPTION_FORMAT = "[%0] %1 in %2:%3"; const QString SCRIPT_BACKTRACE_SEP = "\n "; @@ -47,13 +47,13 @@ void ScriptEndpoint::updateValue() { return; } - ScriptValuePointer result = _callable->call(); - if (result->isError()) { + ScriptValue result = _callable.call(); + if (result.isError()) { // print JavaScript exception qCDebug(controllers).noquote() << formatException(result); _lastValueRead = 0.0f; - } else if (result->isNumber()) { - _lastValueRead = (float)_callable->call()->toNumber(); + } else if (result.isNumber()) { + _lastValueRead = (float)_callable.call().toNumber(); } else { Pose::fromScriptValue(result, _lastPoseRead); _returnPose = true; @@ -75,10 +75,10 @@ void ScriptEndpoint::internalApply(float value, int sourceID) { Q_ARG(int, sourceID)); return; } - ScriptEnginePointer engine = _callable->engine(); - ScriptValuePointer result = _callable->call(ScriptValuePointer(), + ScriptEnginePointer engine = _callable.engine(); + ScriptValue result = _callable.call(ScriptValue(), ScriptValueList({ engine->newValue(value), engine->newValue(sourceID) })); - if (result->isError()) { + if (result.isError()) { // print JavaScript exception qCDebug(controllers).noquote() << formatException(result); } @@ -94,8 +94,8 @@ void ScriptEndpoint::updatePose() { QMetaObject::invokeMethod(this, "updatePose", Qt::QueuedConnection); return; } - ScriptValuePointer result = _callable->call(); - if (result->isError()) { + ScriptValue result = _callable.call(); + if (result.isError()) { // print JavaScript exception qCDebug(controllers).noquote() << formatException(result); } @@ -117,10 +117,10 @@ void ScriptEndpoint::internalApply(const Pose& newPose, int sourceID) { Q_ARG(int, sourceID)); return; } - ScriptEnginePointer engine = _callable->engine(); - ScriptValuePointer result = _callable->call(ScriptValuePointer(), + ScriptEnginePointer engine = _callable.engine(); + ScriptValue result = _callable.call(ScriptValue(), ScriptValueList({ Pose::toScriptValue(engine.get(), newPose), engine->newValue(sourceID) })); - if (result->isError()) { + if (result.isError()) { // print JavaScript exception qCDebug(controllers).noquote() << formatException(result); } diff --git a/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.h b/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.h index ff42812c4b..327cb40eaa 100644 --- a/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.h +++ b/libraries/controllers/src/controllers/impl/endpoints/ScriptEndpoint.h @@ -10,20 +10,17 @@ #ifndef hifi_Controllers_ScriptEndpoint_h #define hifi_Controllers_ScriptEndpoint_h -#include +#include #include "../Endpoint.h" -class ScriptValue; -using ScriptValuePointer = QSharedPointer; - namespace controller { class ScriptEndpoint : public Endpoint { Q_OBJECT; public: using Endpoint::apply; - ScriptEndpoint(const ScriptValuePointer& callable) + ScriptEndpoint(const ScriptValue& callable) : Endpoint(Input::INVALID_INPUT), _callable(callable) { } @@ -42,7 +39,7 @@ protected: Q_INVOKABLE void updatePose(); Q_INVOKABLE virtual void internalApply(const Pose& newValue, int sourceID); private: - ScriptValuePointer _callable; + ScriptValue _callable; float _lastValueRead { 0.0f }; AxisValue _lastValueWritten { 0.0f, 0, false }; diff --git a/libraries/entities-renderer/src/ModelScriptingInterface.cpp b/libraries/entities-renderer/src/ModelScriptingInterface.cpp index 8fef3f0534..0c5dd33a69 100644 --- a/libraries/entities-renderer/src/ModelScriptingInterface.cpp +++ b/libraries/entities-renderer/src/ModelScriptingInterface.cpp @@ -41,7 +41,7 @@ QString ModelScriptingInterface::meshToOBJ(MeshProxyList in) { return writeOBJToString(meshes); } -ScriptValuePointer ModelScriptingInterface::appendMeshes(MeshProxyList in) { +ScriptValue ModelScriptingInterface::appendMeshes(MeshProxyList in) { // figure out the size of the resulting mesh size_t totalVertexCount { 0 }; size_t totalColorCount { 0 }; @@ -149,13 +149,13 @@ ScriptValuePointer ModelScriptingInterface::appendMeshes(MeshProxyList in) { return meshToScriptValue(_modelScriptEngine.get(), resultProxy); } -ScriptValuePointer ModelScriptingInterface::transformMesh(glm::mat4 transform, MeshProxy* meshProxy) { +ScriptValue ModelScriptingInterface::transformMesh(glm::mat4 transform, MeshProxy* meshProxy) { if (!meshProxy) { - return ScriptValuePointer(false); + return ScriptValue(); } MeshPointer mesh = meshProxy->getMeshPointer(); if (!mesh) { - return ScriptValuePointer(false); + return ScriptValue(); } const auto inverseTransposeTransform = glm::inverse(glm::transpose(transform)); @@ -167,13 +167,13 @@ ScriptValuePointer ModelScriptingInterface::transformMesh(glm::mat4 transform, M return meshToScriptValue(_modelScriptEngine.get(), resultProxy); } -ScriptValuePointer ModelScriptingInterface::getVertexCount(MeshProxy* meshProxy) { +ScriptValue ModelScriptingInterface::getVertexCount(MeshProxy* meshProxy) { if (!meshProxy) { - return ScriptValuePointer(false); + return ScriptValue(); } MeshPointer mesh = meshProxy->getMeshPointer(); if (!mesh) { - return ScriptValuePointer(false); + return ScriptValue(); } gpu::BufferView::Index numVertices = (gpu::BufferView::Index)mesh->getNumVertices(); @@ -181,20 +181,20 @@ ScriptValuePointer ModelScriptingInterface::getVertexCount(MeshProxy* meshProxy) return _modelScriptEngine->newValue(numVertices); } -ScriptValuePointer ModelScriptingInterface::getVertex(MeshProxy* meshProxy, int vertexIndex) { +ScriptValue ModelScriptingInterface::getVertex(MeshProxy* meshProxy, int vertexIndex) { if (!meshProxy) { - return ScriptValuePointer(false); + return ScriptValue(); } MeshPointer mesh = meshProxy->getMeshPointer(); if (!mesh) { - return ScriptValuePointer(false); + return ScriptValue(); } const gpu::BufferView& vertexBufferView = mesh->getVertexBuffer(); gpu::BufferView::Index numVertices = (gpu::BufferView::Index)mesh->getNumVertices(); if (vertexIndex < 0 || vertexIndex >= numVertices) { - return ScriptValuePointer(false); + return ScriptValue(); } glm::vec3 pos = vertexBufferView.get(vertexIndex); @@ -202,7 +202,7 @@ ScriptValuePointer ModelScriptingInterface::getVertex(MeshProxy* meshProxy, int } -ScriptValuePointer ModelScriptingInterface::newMesh(const QVector& vertices, +ScriptValue ModelScriptingInterface::newMesh(const QVector& vertices, const QVector& normals, const QVector& faces) { graphics::MeshPointer mesh(std::make_shared()); diff --git a/libraries/entities-renderer/src/ModelScriptingInterface.h b/libraries/entities-renderer/src/ModelScriptingInterface.h index 25806716ec..1f11703ad6 100644 --- a/libraries/entities-renderer/src/ModelScriptingInterface.h +++ b/libraries/entities-renderer/src/ModelScriptingInterface.h @@ -19,11 +19,10 @@ #include #include +#include class ScriptEngine; -class ScriptValue; using ScriptEnginePointer = QSharedPointer; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The Model API provides the ability to manipulate meshes. You can get the meshes for an entity using @@ -61,7 +60,7 @@ public: * @param {MeshProxy[]} meshes - The meshes to combine. * @returns {MeshProxy} The combined mesh. */ - Q_INVOKABLE ScriptValuePointer appendMeshes(MeshProxyList in); + Q_INVOKABLE ScriptValue appendMeshes(MeshProxyList in); /*@jsdoc * Transforms the vertices in a mesh. @@ -70,7 +69,7 @@ public: * @param {MeshProxy} mesh - The mesh to apply the transform to. * @returns {MeshProxy|boolean} The transformed mesh, if valid. false if an error. */ - Q_INVOKABLE ScriptValuePointer transformMesh(glm::mat4 transform, MeshProxy* meshProxy); + Q_INVOKABLE ScriptValue transformMesh(glm::mat4 transform, MeshProxy* meshProxy); /*@jsdoc * Creates a new mesh. @@ -80,7 +79,7 @@ public: * @param {MeshFace[]} faces - The faces in the mesh. * @returns {MeshProxy} A new mesh. */ - Q_INVOKABLE ScriptValuePointer newMesh(const QVector& vertices, + Q_INVOKABLE ScriptValue newMesh(const QVector& vertices, const QVector& normals, const QVector& faces); @@ -90,7 +89,7 @@ public: * @param {MeshProxy} mesh - The mesh to count the vertices in. * @returns {number|boolean} The number of vertices in the mesh, if valid. false if an error. */ - Q_INVOKABLE ScriptValuePointer getVertexCount(MeshProxy* meshProxy); + Q_INVOKABLE ScriptValue getVertexCount(MeshProxy* meshProxy); /*@jsdoc * Gets the position of a vertex in a mesh. @@ -99,7 +98,7 @@ public: * @param {number} index - The index of the vertex to get. * @returns {Vec3|boolean} The local position of the vertex relative to the mesh, if valid. false if an error. */ - Q_INVOKABLE ScriptValuePointer getVertex(MeshProxy* meshProxy, int vertexIndex); + Q_INVOKABLE ScriptValue getVertex(MeshProxy* meshProxy, int vertexIndex); private: ScriptEnginePointer _modelScriptEngine { nullptr }; diff --git a/libraries/entities/src/AmbientLightPropertyGroup.cpp b/libraries/entities/src/AmbientLightPropertyGroup.cpp index 1958594373..b88e7904b1 100644 --- a/libraries/entities/src/AmbientLightPropertyGroup.cpp +++ b/libraries/entities/src/AmbientLightPropertyGroup.cpp @@ -19,14 +19,14 @@ const float AmbientLightPropertyGroup::DEFAULT_AMBIENT_LIGHT_INTENSITY = 0.5f; -void AmbientLightPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, +void AmbientLightPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_AMBIENT_LIGHT_INTENSITY, AmbientLight, ambientLight, AmbientIntensity, ambientIntensity); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_AMBIENT_LIGHT_URL, AmbientLight, ambientLight, AmbientURL, ambientURL); } -void AmbientLightPropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void AmbientLightPropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(ambientLight, ambientIntensity, float, setAmbientIntensity); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(ambientLight, ambientURL, QString, setAmbientURL); diff --git a/libraries/entities/src/AmbientLightPropertyGroup.h b/libraries/entities/src/AmbientLightPropertyGroup.h index dba6d74cac..4eb447cb77 100644 --- a/libraries/entities/src/AmbientLightPropertyGroup.h +++ b/libraries/entities/src/AmbientLightPropertyGroup.h @@ -17,7 +17,6 @@ #include -#include #include "EntityItemPropertiesMacros.h" #include "PropertyGroup.h" @@ -28,7 +27,6 @@ class EntityTreeElementExtraEncodeData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * Ambient light is defined by the following properties: @@ -41,10 +39,10 @@ using ScriptValuePointer = QSharedPointer; class AmbientLightPropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const AmbientLightPropertyGroup& other); diff --git a/libraries/entities/src/AnimationPropertyGroup.cpp b/libraries/entities/src/AnimationPropertyGroup.cpp index 2546251ddb..fd19e4e9b8 100644 --- a/libraries/entities/src/AnimationPropertyGroup.cpp +++ b/libraries/entities/src/AnimationPropertyGroup.cpp @@ -65,7 +65,7 @@ bool operator!=(const AnimationPropertyGroup& a, const AnimationPropertyGroup& b * @property {boolean} hold=false - true if the rotations and translations of the last frame played are * maintained when the animation stops playing, false if they aren't. */ -void AnimationPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { +void AnimationPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_ANIMATION_URL, Animation, animation, URL, url); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_ANIMATION_ALLOW_TRANSLATION, Animation, animation, AllowTranslation, allowTranslation); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_ANIMATION_FPS, Animation, animation, FPS, fps); @@ -78,7 +78,7 @@ void AnimationPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desire } -void AnimationPropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void AnimationPropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(animation, url, QString, setURL); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(animation, allowTranslation, bool, setAllowTranslation); diff --git a/libraries/entities/src/AnimationPropertyGroup.h b/libraries/entities/src/AnimationPropertyGroup.h index baa27b9613..4f316568c8 100644 --- a/libraries/entities/src/AnimationPropertyGroup.h +++ b/libraries/entities/src/AnimationPropertyGroup.h @@ -17,7 +17,6 @@ #include -#include #include "EntityItemPropertiesMacros.h" #include "PropertyGroup.h" @@ -28,17 +27,16 @@ class EntityTreeElementExtraEncodeData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; class AnimationPropertyGroup : public PropertyGroup { public: static const float MAXIMUM_POSSIBLE_FRAME; // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const AnimationPropertyGroup& other); diff --git a/libraries/entities/src/BloomPropertyGroup.cpp b/libraries/entities/src/BloomPropertyGroup.cpp index 672b3e9623..8315149925 100644 --- a/libraries/entities/src/BloomPropertyGroup.cpp +++ b/libraries/entities/src/BloomPropertyGroup.cpp @@ -16,13 +16,13 @@ #include "EntityItemProperties.h" #include "EntityItemPropertiesMacros.h" -void BloomPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { +void BloomPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_BLOOM_INTENSITY, Bloom, bloom, BloomIntensity, bloomIntensity); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_BLOOM_THRESHOLD, Bloom, bloom, BloomThreshold, bloomThreshold); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_BLOOM_SIZE, Bloom, bloom, BloomSize, bloomSize); } -void BloomPropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void BloomPropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(bloom, bloomIntensity, float, setBloomIntensity); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(bloom, bloomThreshold, float, setBloomThreshold); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(bloom, bloomSize, float, setBloomSize); diff --git a/libraries/entities/src/BloomPropertyGroup.h b/libraries/entities/src/BloomPropertyGroup.h index e702236954..22e2fb3a9e 100644 --- a/libraries/entities/src/BloomPropertyGroup.h +++ b/libraries/entities/src/BloomPropertyGroup.h @@ -15,8 +15,6 @@ #include #include -#include - #include "PropertyGroup.h" #include "EntityItemPropertiesMacros.h" @@ -27,7 +25,6 @@ class EntityTreeElementExtraEncodeData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; static const float INITIAL_BLOOM_INTENSITY { 0.25f }; static const float INITIAL_BLOOM_THRESHOLD { 0.7f }; @@ -43,10 +40,10 @@ static const float INITIAL_BLOOM_SIZE { 0.9f }; class BloomPropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const BloomPropertyGroup& other); diff --git a/libraries/entities/src/EntityEditFilters.cpp b/libraries/entities/src/EntityEditFilters.cpp index 6d2280f0bf..c9f72bedca 100644 --- a/libraries/entities/src/EntityEditFilters.cpp +++ b/libraries/entities/src/EntityEditFilters.cpp @@ -79,10 +79,10 @@ bool EntityEditFilters::filter(glm::vec3& position, EntityItemProperties& proper auto oldProperties = propertiesIn.getDesiredProperties(); auto specifiedProperties = propertiesIn.getChangedProperties(); propertiesIn.setDesiredProperties(specifiedProperties); - ScriptValuePointer inputValues = propertiesIn.copyToScriptValue(filterData.engine, false, true, true); + ScriptValue inputValues = propertiesIn.copyToScriptValue(filterData.engine, false, true, true); propertiesIn.setDesiredProperties(oldProperties); - auto in = QJsonValue::fromVariant(inputValues->toVariant()); // grab json copy now, because the inputValues might be side effected by the filter. + auto in = QJsonValue::fromVariant(inputValues.toVariant()); // grab json copy now, because the inputValues might be side effected by the filter. ScriptValueList args; args << inputValues; @@ -91,7 +91,7 @@ bool EntityEditFilters::filter(glm::vec3& position, EntityItemProperties& proper // get the current properties for then entity and include them for the filter call if (existingEntity && filterData.wantsOriginalProperties) { auto currentProperties = existingEntity->getProperties(filterData.includedOriginalProperties); - ScriptValuePointer currentValues = currentProperties.copyToScriptValue(filterData.engine, false, true, true); + ScriptValue currentValues = currentProperties.copyToScriptValue(filterData.engine, false, true, true); args << currentValues; } @@ -101,22 +101,22 @@ bool EntityEditFilters::filter(glm::vec3& position, EntityItemProperties& proper auto zoneEntity = _tree->findEntityByEntityItemID(id); if (zoneEntity) { auto zoneProperties = zoneEntity->getProperties(filterData.includedZoneProperties); - ScriptValuePointer zoneValues = zoneProperties.copyToScriptValue(filterData.engine, false, true, true); + ScriptValue zoneValues = zoneProperties.copyToScriptValue(filterData.engine, false, true, true); if (filterData.wantsZoneBoundingBox) { bool success = true; AABox aaBox = zoneEntity->getAABox(success); if (success) { - ScriptValuePointer boundingBox = filterData.engine->newObject(); - ScriptValuePointer bottomRightNear = vec3ToScriptValue(filterData.engine, aaBox.getCorner()); - ScriptValuePointer topFarLeft = vec3ToScriptValue(filterData.engine, aaBox.calcTopFarLeft()); - ScriptValuePointer center = vec3ToScriptValue(filterData.engine, aaBox.calcCenter()); - ScriptValuePointer boundingBoxDimensions = vec3ToScriptValue(filterData.engine, aaBox.getDimensions()); - boundingBox->setProperty("brn", bottomRightNear); - boundingBox->setProperty("tfl", topFarLeft); - boundingBox->setProperty("center", center); - boundingBox->setProperty("dimensions", boundingBoxDimensions); - zoneValues->setProperty("boundingBox", boundingBox); + ScriptValue boundingBox = filterData.engine->newObject(); + ScriptValue bottomRightNear = vec3ToScriptValue(filterData.engine, aaBox.getCorner()); + ScriptValue topFarLeft = vec3ToScriptValue(filterData.engine, aaBox.calcTopFarLeft()); + ScriptValue center = vec3ToScriptValue(filterData.engine, aaBox.calcCenter()); + ScriptValue boundingBoxDimensions = vec3ToScriptValue(filterData.engine, aaBox.getDimensions()); + boundingBox.setProperty("brn", bottomRightNear); + boundingBox.setProperty("tfl", topFarLeft); + boundingBox.setProperty("center", center); + boundingBox.setProperty("dimensions", boundingBoxDimensions); + zoneValues.setProperty("boundingBox", boundingBox); } } @@ -125,32 +125,32 @@ bool EntityEditFilters::filter(glm::vec3& position, EntityItemProperties& proper // to be the fourth parameter, so we need to pad the args accordingly int EXPECTED_ARGS = 3; if (args.length() < EXPECTED_ARGS) { - args << ScriptValuePointer(); + args << ScriptValue(); } assert(args.length() == EXPECTED_ARGS); // we MUST have 3 args by now! args << zoneValues; } } - ScriptValuePointer result = filterData.filterFn->call(_nullObjectForFilter, args); + ScriptValue result = filterData.filterFn.call(_nullObjectForFilter, args); if (filterData.uncaughtExceptions()) { return false; } - if (result->isObject()) { + if (result.isObject()) { // make propertiesIn reflect the changes, for next filter... propertiesIn.copyFromScriptValue(result, false); // and update propertiesOut too. TODO: this could be more efficient... propertiesOut.copyFromScriptValue(result, false); // Javascript objects are == only if they are the same object. To compare arbitrary values, we need to use JSON. - auto out = QJsonValue::fromVariant(result->toVariant()); + auto out = QJsonValue::fromVariant(result.toVariant()); wasChanged |= (in != out); - } else if (result->isBool()) { + } else if (result.isBool()) { // if the filter returned false, then it's authoritative - if (!result->toBool()) { + if (!result.toBool()) { return false; } @@ -235,7 +235,7 @@ static bool hasCorrectSyntax(const ScriptProgramPointer& program) { static bool hadUncaughtExceptions(ScriptEngine& engine, const QString& fileName) { if (engine.hasUncaughtException()) { const auto backtrace = engine.uncaughtExceptionBacktrace(); - const auto exception = engine.uncaughtException()->toString(); + const auto exception = engine.uncaughtException().toString(); const auto line = QString::number(engine.uncaughtExceptionLineNumber()); engine.clearExceptions(); @@ -267,7 +267,7 @@ void EntityEditFilters::scriptRequestFinished(EntityItemID entityID) { engine->setProperty("type", "edit_filter"); engine->setProperty("fileName", urlString); engine->setProperty("entityID", entityID); - engine->globalObject()->setProperty("Script", engine->newQObject(manager.get())); + engine->globalObject().setProperty("Script", engine->newQObject(manager.get())); DependencyManager::get()->runScriptInitializers(engine.data()); engine->evaluate(scriptContents, urlString); if (!hadUncaughtExceptions(*engine, urlString)) { @@ -283,68 +283,68 @@ void EntityEditFilters::scriptRequestFinished(EntityItemID entityID) { // now get the filter function auto global = engine->globalObject(); auto entitiesObject = engine->newObject(); - entitiesObject->setProperty("ADD_FILTER_TYPE", EntityTree::FilterType::Add); - entitiesObject->setProperty("EDIT_FILTER_TYPE", EntityTree::FilterType::Edit); - entitiesObject->setProperty("PHYSICS_FILTER_TYPE", EntityTree::FilterType::Physics); - entitiesObject->setProperty("DELETE_FILTER_TYPE", EntityTree::FilterType::Delete); - global->setProperty("Entities", entitiesObject); - filterData.filterFn = global->property("filter"); - if (!filterData.filterFn->isFunction()) { + entitiesObject.setProperty("ADD_FILTER_TYPE", EntityTree::FilterType::Add); + entitiesObject.setProperty("EDIT_FILTER_TYPE", EntityTree::FilterType::Edit); + entitiesObject.setProperty("PHYSICS_FILTER_TYPE", EntityTree::FilterType::Physics); + entitiesObject.setProperty("DELETE_FILTER_TYPE", EntityTree::FilterType::Delete); + global.setProperty("Entities", entitiesObject); + filterData.filterFn = global.property("filter"); + if (!filterData.filterFn.isFunction()) { qDebug() << "Filter function specified but not found. Will reject all edits for those without lock rights."; engine.reset(); filterData.rejectAll=true; } // if the wantsToFilterEdit is a boolean evaluate as a boolean, otherwise assume true - ScriptValuePointer wantsToFilterAddValue = filterData.filterFn->property("wantsToFilterAdd"); - filterData.wantsToFilterAdd = wantsToFilterAddValue->isBool() ? wantsToFilterAddValue->toBool() : true; + ScriptValue wantsToFilterAddValue = filterData.filterFn.property("wantsToFilterAdd"); + filterData.wantsToFilterAdd = wantsToFilterAddValue.isBool() ? wantsToFilterAddValue.toBool() : true; // if the wantsToFilterEdit is a boolean evaluate as a boolean, otherwise assume true - ScriptValuePointer wantsToFilterEditValue = filterData.filterFn->property("wantsToFilterEdit"); - filterData.wantsToFilterEdit = wantsToFilterEditValue->isBool() ? wantsToFilterEditValue->toBool() : true; + ScriptValue wantsToFilterEditValue = filterData.filterFn.property("wantsToFilterEdit"); + filterData.wantsToFilterEdit = wantsToFilterEditValue.isBool() ? wantsToFilterEditValue.toBool() : true; // if the wantsToFilterPhysics is a boolean evaluate as a boolean, otherwise assume true - ScriptValuePointer wantsToFilterPhysicsValue = filterData.filterFn->property("wantsToFilterPhysics"); - filterData.wantsToFilterPhysics = wantsToFilterPhysicsValue->isBool() ? wantsToFilterPhysicsValue->toBool() : true; + ScriptValue wantsToFilterPhysicsValue = filterData.filterFn.property("wantsToFilterPhysics"); + filterData.wantsToFilterPhysics = wantsToFilterPhysicsValue.isBool() ? wantsToFilterPhysicsValue.toBool() : true; // if the wantsToFilterDelete is a boolean evaluate as a boolean, otherwise assume false - ScriptValuePointer wantsToFilterDeleteValue = filterData.filterFn->property("wantsToFilterDelete"); - filterData.wantsToFilterDelete = wantsToFilterDeleteValue->isBool() ? wantsToFilterDeleteValue->toBool() : false; + ScriptValue wantsToFilterDeleteValue = filterData.filterFn.property("wantsToFilterDelete"); + filterData.wantsToFilterDelete = wantsToFilterDeleteValue.isBool() ? wantsToFilterDeleteValue.toBool() : false; // check to see if the filterFn has properties asking for Original props - ScriptValuePointer wantsOriginalPropertiesValue = filterData.filterFn->property("wantsOriginalProperties"); + ScriptValue wantsOriginalPropertiesValue = filterData.filterFn.property("wantsOriginalProperties"); // if the wantsOriginalProperties is a boolean, or a string, or list of strings, then evaluate as follows: // - boolean - true - include all original properties // false - no properties at all // - string - empty - no properties at all // any valid property - include just that property in the Original properties // - list of strings - include only those properties in the Original properties - if (wantsOriginalPropertiesValue->isBool()) { - filterData.wantsOriginalProperties = wantsOriginalPropertiesValue->toBool(); - } else if (wantsOriginalPropertiesValue->isString()) { - auto stringValue = wantsOriginalPropertiesValue->toString(); + if (wantsOriginalPropertiesValue.isBool()) { + filterData.wantsOriginalProperties = wantsOriginalPropertiesValue.toBool(); + } else if (wantsOriginalPropertiesValue.isString()) { + auto stringValue = wantsOriginalPropertiesValue.toString(); filterData.wantsOriginalProperties = !stringValue.isEmpty(); if (filterData.wantsOriginalProperties) { EntityPropertyFlagsFromScriptValue(wantsOriginalPropertiesValue, filterData.includedOriginalProperties); } - } else if (wantsOriginalPropertiesValue->isArray()) { + } else if (wantsOriginalPropertiesValue.isArray()) { EntityPropertyFlagsFromScriptValue(wantsOriginalPropertiesValue, filterData.includedOriginalProperties); filterData.wantsOriginalProperties = !filterData.includedOriginalProperties.isEmpty(); } // check to see if the filterFn has properties asking for Zone props - ScriptValuePointer wantsZonePropertiesValue = filterData.filterFn->property("wantsZoneProperties"); + ScriptValue wantsZonePropertiesValue = filterData.filterFn.property("wantsZoneProperties"); // if the wantsZoneProperties is a boolean, or a string, or list of strings, then evaluate as follows: // - boolean - true - include all Zone properties // false - no properties at all // - string - empty - no properties at all // any valid property - include just that property in the Zone properties // - list of strings - include only those properties in the Zone properties - if (wantsZonePropertiesValue->isBool()) { - filterData.wantsZoneProperties = wantsZonePropertiesValue->toBool(); + if (wantsZonePropertiesValue.isBool()) { + filterData.wantsZoneProperties = wantsZonePropertiesValue.toBool(); filterData.wantsZoneBoundingBox = filterData.wantsZoneProperties; // include this too - } else if (wantsZonePropertiesValue->isString()) { - auto stringValue = wantsZonePropertiesValue->toString(); + } else if (wantsZonePropertiesValue.isString()) { + auto stringValue = wantsZonePropertiesValue.toString(); filterData.wantsZoneProperties = !stringValue.isEmpty(); if (filterData.wantsZoneProperties) { if (stringValue == "boundingBox") { @@ -353,10 +353,10 @@ void EntityEditFilters::scriptRequestFinished(EntityItemID entityID) { EntityPropertyFlagsFromScriptValue(wantsZonePropertiesValue, filterData.includedZoneProperties); } } - } else if (wantsZonePropertiesValue->isArray()) { - auto length = wantsZonePropertiesValue->property("length")->toInteger(); + } else if (wantsZonePropertiesValue.isArray()) { + auto length = wantsZonePropertiesValue.property("length").toInteger(); for (int i = 0; i < length; i++) { - auto stringValue = wantsZonePropertiesValue->property(i)->toString(); + auto stringValue = wantsZonePropertiesValue.property(i).toString(); if (!stringValue.isEmpty()) { filterData.wantsZoneProperties = true; diff --git a/libraries/entities/src/EntityEditFilters.h b/libraries/entities/src/EntityEditFilters.h index 26dd91cc68..bf0653a6a4 100644 --- a/libraries/entities/src/EntityEditFilters.h +++ b/libraries/entities/src/EntityEditFilters.h @@ -13,7 +13,6 @@ #include #include -#include #include #include @@ -30,7 +29,7 @@ class EntityEditFilters : public QObject, public Dependency { Q_OBJECT public: struct FilterData { - ScriptValuePointer filterFn; + ScriptValue filterFn; bool wantsOriginalProperties { false }; bool wantsZoneProperties { false }; @@ -48,7 +47,7 @@ public: bool rejectAll; FilterData(): engine(nullptr), rejectAll(false) {}; - bool valid() { return (rejectAll || (engine != nullptr && filterFn->isFunction() && uncaughtExceptions)); } + bool valid() { return (rejectAll || (engine != nullptr && filterFn.isFunction() && uncaughtExceptions)); } }; EntityEditFilters() {}; @@ -71,7 +70,7 @@ private: EntityTreePointer _tree {}; bool _rejectAll {false}; - ScriptValuePointer _nullObjectForFilter{}; + ScriptValue _nullObjectForFilter{}; QReadWriteLock _lock; QMap _filterDataMap; diff --git a/libraries/entities/src/EntityItemProperties.cpp b/libraries/entities/src/EntityItemProperties.cpp index 5592eab4c8..c3a36bbbd8 100644 --- a/libraries/entities/src/EntityItemProperties.cpp +++ b/libraries/entities/src/EntityItemProperties.cpp @@ -1576,14 +1576,14 @@ EntityPropertyFlags EntityItemProperties::getChangedProperties() const { * @property {Entities.RingGizmo} ring - The ring gizmo properties. */ -ScriptValuePointer EntityItemProperties::copyToScriptValue(ScriptEngine* engine, bool skipDefaults, bool allowUnknownCreateTime, +ScriptValue EntityItemProperties::copyToScriptValue(ScriptEngine* engine, bool skipDefaults, bool allowUnknownCreateTime, bool strictSemantics, EntityPsuedoPropertyFlags psueudoPropertyFlags) const { // If strictSemantics is true and skipDefaults is false, then all and only those properties are copied for which the property flag // is included in _desiredProperties, or is one of the specially enumerated ALWAYS properties below. // (There may be exceptions, but if so, they are bugs.) // In all other cases, you are welcome to inspect the code and try to figure out what was intended. I wish you luck. -HRS 1/18/17 - ScriptValuePointer properties = engine->newObject(); + ScriptValue properties = engine->newObject(); EntityItemProperties defaultEntityProperties; const bool psuedoPropertyFlagsActive = psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::FlagsActive); @@ -1610,7 +1610,7 @@ ScriptValuePointer EntityItemProperties::copyToScriptValue(ScriptEngine* engine, } } if (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::LastEdited)) { - properties->setProperty("lastEdited", convertScriptValue(engine, _lastEdited)); + properties.setProperty("lastEdited", convertScriptValue(engine, _lastEdited)); } if (!skipDefaults) { COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_DIMENSIONS, naturalDimensions); // gettable, but not settable @@ -1927,9 +1927,9 @@ ScriptValuePointer EntityItemProperties::copyToScriptValue(ScriptEngine* engine, // Handle conversions to old 'textures' property from "imageURL" if (((!psuedoPropertyFlagsButDesiredEmpty && _desiredProperties.isEmpty()) || _desiredProperties.getHasProperty(PROP_IMAGE_URL)) && (!skipDefaults || defaultEntityProperties._imageURL != _imageURL)) { - ScriptValuePointer textures = engine->newObject(); - textures->setProperty("tex.picture", _imageURL); - properties->setProperty("textures", textures); + ScriptValue textures = engine->newObject(); + textures.setProperty("tex.picture", _imageURL); + properties.setProperty("textures", textures); } } @@ -1962,15 +1962,15 @@ ScriptValuePointer EntityItemProperties::copyToScriptValue(ScriptEngine* engine, (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::BoundingBox))) { AABox aaBox = getAABox(); - ScriptValuePointer boundingBox = engine->newObject(); - ScriptValuePointer bottomRightNear = vec3ToScriptValue(engine, aaBox.getCorner()); - ScriptValuePointer topFarLeft = vec3ToScriptValue(engine, aaBox.calcTopFarLeft()); - ScriptValuePointer center = vec3ToScriptValue(engine, aaBox.calcCenter()); - ScriptValuePointer boundingBoxDimensions = vec3ToScriptValue(engine, aaBox.getDimensions()); - boundingBox->setProperty("brn", bottomRightNear); - boundingBox->setProperty("tfl", topFarLeft); - boundingBox->setProperty("center", center); - boundingBox->setProperty("dimensions", boundingBoxDimensions); + ScriptValue boundingBox = engine->newObject(); + ScriptValue bottomRightNear = vec3ToScriptValue(engine, aaBox.getCorner()); + ScriptValue topFarLeft = vec3ToScriptValue(engine, aaBox.calcTopFarLeft()); + ScriptValue center = vec3ToScriptValue(engine, aaBox.calcCenter()); + ScriptValue boundingBoxDimensions = vec3ToScriptValue(engine, aaBox.getDimensions()); + boundingBox.setProperty("brn", bottomRightNear); + boundingBox.setProperty("tfl", topFarLeft); + boundingBox.setProperty("center", center); + boundingBox.setProperty("dimensions", boundingBoxDimensions); COPY_PROPERTY_TO_QSCRIPTVALUE_GETTER_NO_SKIP(boundingBox, boundingBox); // gettable, but not settable } @@ -1983,7 +1983,7 @@ ScriptValuePointer EntityItemProperties::copyToScriptValue(ScriptEngine* engine, if (!skipDefaults && !strictSemantics && (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::RenderInfo))) { - ScriptValuePointer renderInfo = engine->newObject(); + ScriptValue renderInfo = engine->newObject(); /*@jsdoc * Information on how an entity is rendered. Properties are only filled in for Model entities; other @@ -1998,40 +1998,40 @@ ScriptValuePointer EntityItemProperties::copyToScriptValue(ScriptEngine* engine, */ // currently only supported by models if (_type == EntityTypes::Model) { - renderInfo->setProperty("verticesCount", (int)getRenderInfoVertexCount()); // FIXME - theoretically the number of vertex could be > max int - renderInfo->setProperty("texturesSize", (int)getRenderInfoTextureSize()); // FIXME - theoretically the size of textures could be > max int - renderInfo->setProperty("hasTransparent", getRenderInfoHasTransparent()); - renderInfo->setProperty("drawCalls", getRenderInfoDrawCalls()); - renderInfo->setProperty("texturesCount", getRenderInfoTextureCount()); + renderInfo.setProperty("verticesCount", (int)getRenderInfoVertexCount()); // FIXME - theoretically the number of vertex could be > max int + renderInfo.setProperty("texturesSize", (int)getRenderInfoTextureSize()); // FIXME - theoretically the size of textures could be > max int + renderInfo.setProperty("hasTransparent", getRenderInfoHasTransparent()); + renderInfo.setProperty("drawCalls", getRenderInfoDrawCalls()); + renderInfo.setProperty("texturesCount", getRenderInfoTextureCount()); } COPY_PROPERTY_TO_QSCRIPTVALUE_GETTER_NO_SKIP(renderInfo, renderInfo); // Gettable but not settable } if (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::ClientOnly)) { - properties->setProperty("clientOnly", convertScriptValue(engine, getEntityHostType() == entity::HostType::AVATAR)); + properties.setProperty("clientOnly", convertScriptValue(engine, getEntityHostType() == entity::HostType::AVATAR)); } if (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::AvatarEntity)) { - properties->setProperty("avatarEntity", convertScriptValue(engine, getEntityHostType() == entity::HostType::AVATAR)); + properties.setProperty("avatarEntity", convertScriptValue(engine, getEntityHostType() == entity::HostType::AVATAR)); } if (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::LocalEntity)) { - properties->setProperty("localEntity", convertScriptValue(engine, getEntityHostType() == entity::HostType::LOCAL)); + properties.setProperty("localEntity", convertScriptValue(engine, getEntityHostType() == entity::HostType::LOCAL)); } if (_type != EntityTypes::PolyLine && (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::FaceCamera))) { - properties->setProperty("faceCamera", convertScriptValue(engine, getBillboardMode() == BillboardMode::YAW)); + properties.setProperty("faceCamera", convertScriptValue(engine, getBillboardMode() == BillboardMode::YAW)); } if (!psuedoPropertyFlagsActive || psueudoPropertyFlags.test(EntityPsuedoPropertyFlag::IsFacingAvatar)) { - properties->setProperty("isFacingAvatar", convertScriptValue(engine, getBillboardMode() == BillboardMode::FULL)); + properties.setProperty("isFacingAvatar", convertScriptValue(engine, getBillboardMode() == BillboardMode::FULL)); } return properties; } -void EntityItemProperties::copyFromScriptValue(const ScriptValuePointer& object, bool honorReadOnly) { - ScriptValuePointer typeScriptValue = object->property("type"); - if (typeScriptValue->isValid()) { - setType(typeScriptValue->toVariant().toString()); +void EntityItemProperties::copyFromScriptValue(const ScriptValue& object, bool honorReadOnly) { + ScriptValue typeScriptValue = object.property("type"); + if (typeScriptValue.isValid()) { + setType(typeScriptValue.toVariant().toString()); } // Core @@ -2284,8 +2284,8 @@ void EntityItemProperties::copyFromScriptValue(const ScriptValuePointer& object, // Handle conversions from old 'textures' property to "imageURL" { - ScriptValuePointer V = object->property("textures"); - if (_type == EntityTypes::Image && V->isValid() && !object->property("imageURL")->isValid()) { + ScriptValue V = object.property("textures"); + if (_type == EntityTypes::Image && V.isValid() && !object.property("imageURL").isValid()) { bool isValid = false; QString textures = QString_convertFromScriptValue(V, isValid); if (isValid) { @@ -2303,9 +2303,9 @@ void EntityItemProperties::copyFromScriptValue(const ScriptValuePointer& object, // Handle old "faceCamera" and "isFacingAvatar" props if (_type != EntityTypes::PolyLine) { - ScriptValuePointer P = object->property("faceCamera"); - if (P->isValid() && !object->property("billboardMode")->isValid()) { - bool newValue = P->toVariant().toBool(); + ScriptValue P = object.property("faceCamera"); + if (P.isValid() && !object.property("billboardMode").isValid()) { + bool newValue = P.toVariant().toBool(); bool oldValue = getBillboardMode() == BillboardMode::YAW; if (_defaultSettings || newValue != oldValue) { setBillboardMode(newValue ? BillboardMode::YAW : BillboardMode::NONE); @@ -2313,9 +2313,9 @@ void EntityItemProperties::copyFromScriptValue(const ScriptValuePointer& object, } } { - ScriptValuePointer P = object->property("isFacingAvatar"); - if (P->isValid() && !object->property("billboardMode")->isValid() && !object->property("faceCamera")->isValid()) { - bool newValue = P->toVariant().toBool(); + ScriptValue P = object.property("isFacingAvatar"); + if (P.isValid() && !object.property("billboardMode").isValid() && !object.property("faceCamera").isValid()) { + bool newValue = P.toVariant().toBool(); bool oldValue = getBillboardMode() == BillboardMode::FULL; if (_defaultSettings || newValue != oldValue) { setBillboardMode(newValue ? BillboardMode::FULL : BillboardMode::NONE); @@ -2332,7 +2332,7 @@ void EntityItemProperties::copyFromJSONString(ScriptEngine& scriptEngine, const QJsonObject propertiesObj = propertiesDoc.object(); QVariant propertiesVariant(propertiesObj); QVariantMap propertiesMap = propertiesVariant.toMap(); - ScriptValuePointer propertiesScriptValue = variantMapToScriptValue(propertiesMap, scriptEngine); + ScriptValue propertiesScriptValue = variantMapToScriptValue(propertiesMap, scriptEngine); bool honorReadOnly = true; copyFromScriptValue(propertiesScriptValue, honorReadOnly); } @@ -2580,47 +2580,47 @@ void EntityItemProperties::merge(const EntityItemProperties& other) { _lastEdited = usecTimestampNow(); } -ScriptValuePointer EntityItemPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties) { +ScriptValue EntityItemPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties) { return properties.copyToScriptValue(engine, false); } -ScriptValuePointer EntityItemNonDefaultPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties) { +ScriptValue EntityItemNonDefaultPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties) { return properties.copyToScriptValue(engine, true); } -void EntityItemPropertiesFromScriptValueIgnoreReadOnly(const ScriptValuePointer &object, EntityItemProperties& properties) { +void EntityItemPropertiesFromScriptValueIgnoreReadOnly(const ScriptValue &object, EntityItemProperties& properties) { properties.copyFromScriptValue(object, false); } -void EntityItemPropertiesFromScriptValueHonorReadOnly(const ScriptValuePointer &object, EntityItemProperties& properties) { +void EntityItemPropertiesFromScriptValueHonorReadOnly(const ScriptValue &object, EntityItemProperties& properties) { properties.copyFromScriptValue(object, true); } -ScriptValuePointer EntityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags) { +ScriptValue EntityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags) { return EntityItemProperties::entityPropertyFlagsToScriptValue(engine, flags); } -void EntityPropertyFlagsFromScriptValue(const ScriptValuePointer& object, EntityPropertyFlags& flags) { +void EntityPropertyFlagsFromScriptValue(const ScriptValue& object, EntityPropertyFlags& flags) { EntityItemProperties::entityPropertyFlagsFromScriptValue(object, flags); } -ScriptValuePointer EntityItemProperties::entityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags) { - ScriptValuePointer result = engine->newObject(); +ScriptValue EntityItemProperties::entityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags) { + ScriptValue result = engine->newObject(); return result; } -void EntityItemProperties::entityPropertyFlagsFromScriptValue(const ScriptValuePointer& object, EntityPropertyFlags& flags) { - if (object->isString()) { +void EntityItemProperties::entityPropertyFlagsFromScriptValue(const ScriptValue& object, EntityPropertyFlags& flags) { + if (object.isString()) { EntityPropertyInfo propertyInfo; - if (getPropertyInfo(object->toString(), propertyInfo)) { + if (getPropertyInfo(object.toString(), propertyInfo)) { flags << propertyInfo.propertyEnum; } } - else if (object->isArray()) { - quint32 length = object->property("length")->toInt32(); + else if (object.isArray()) { + quint32 length = object.property("length").toInt32(); for (quint32 i = 0; i < length; i++) { - QString propertyName = object->property(i)->toString(); + QString propertyName = object.property(i).toString(); EntityPropertyInfo propertyInfo; if (getPropertyInfo(propertyName, propertyInfo)) { flags << propertyInfo.propertyEnum; @@ -3019,18 +3019,18 @@ bool EntityItemProperties::getPropertyInfo(const QString& propertyName, EntityPr * @property {string} minimum - The minimum numerical value the property may have, if available, otherwise "". * @property {string} maximum - The maximum numerical value the property may have, if available, otherwise "". */ -ScriptValuePointer EntityPropertyInfoToScriptValue(ScriptEngine* engine, const EntityPropertyInfo& propertyInfo) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("propertyEnum", propertyInfo.propertyEnum); - obj->setProperty("minimum", propertyInfo.minimum.toString()); - obj->setProperty("maximum", propertyInfo.maximum.toString()); +ScriptValue EntityPropertyInfoToScriptValue(ScriptEngine* engine, const EntityPropertyInfo& propertyInfo) { + ScriptValue obj = engine->newObject(); + obj.setProperty("propertyEnum", propertyInfo.propertyEnum); + obj.setProperty("minimum", propertyInfo.minimum.toString()); + obj.setProperty("maximum", propertyInfo.maximum.toString()); return obj; } -void EntityPropertyInfoFromScriptValue(const ScriptValuePointer& object, EntityPropertyInfo& propertyInfo) { - propertyInfo.propertyEnum = (EntityPropertyList)object->property("propertyEnum")->toVariant().toUInt(); - propertyInfo.minimum = object->property("minimum")->toVariant(); - propertyInfo.maximum = object->property("maximum")->toVariant(); +void EntityPropertyInfoFromScriptValue(const ScriptValue& object, EntityPropertyInfo& propertyInfo) { + propertyInfo.propertyEnum = (EntityPropertyList)object.property("propertyEnum").toVariant().toUInt(); + propertyInfo.minimum = object.property("minimum").toVariant(); + propertyInfo.maximum = object.property("maximum").toVariant(); } // TODO: Implement support for edit packets that can span an MTU sized buffer. We need to implement a mechanism for the @@ -5205,7 +5205,7 @@ bool EntityItemProperties::blobToProperties(ScriptEngine& scriptEngine, const QB } QVariant variant = jsonProperties.toVariant(); QVariantMap variantMap = variant.toMap(); - ScriptValuePointer scriptValue = variantMapToScriptValue(variantMap, scriptEngine); + ScriptValue scriptValue = variantMapToScriptValue(variantMap, scriptEngine); EntityItemPropertiesFromScriptValueIgnoreReadOnly(scriptValue, properties); // end recipe return true; @@ -5215,10 +5215,10 @@ void EntityItemProperties::propertiesToBlob(ScriptEngine& scriptEngine, const QU const EntityItemProperties& properties, QByteArray& blob, bool allProperties) { // DANGER: this method is NOT efficient. // begin recipe for extracting unfortunately-formatted-binary-blob from EntityItem - ScriptValuePointer scriptValue = allProperties + ScriptValue scriptValue = allProperties ? EntityItemPropertiesToScriptValue(&scriptEngine, properties) : EntityItemNonDefaultPropertiesToScriptValue(&scriptEngine, properties); - QVariant variantProperties = scriptValue->toVariant(); + QVariant variantProperties = scriptValue.toVariant(); QJsonDocument jsonProperties = QJsonDocument::fromVariant(variantProperties); // the ID of the parent/avatar changes from session to session. use a special UUID to indicate the avatar QJsonObject jsonObject = jsonProperties.object(); diff --git a/libraries/entities/src/EntityItemProperties.h b/libraries/entities/src/EntityItemProperties.h index 4184880ad1..c8016461d7 100644 --- a/libraries/entities/src/EntityItemProperties.h +++ b/libraries/entities/src/EntityItemProperties.h @@ -25,7 +25,6 @@ #include #include #include -#include #include #include @@ -34,8 +33,9 @@ #include #include #include "FontFamilies.h" +#include -#include "EntityItemID.h" +#include #include "EntityItemPropertiesDefaults.h" #include "EntityItemPropertiesMacros.h" #include "EntityTypes.h" @@ -70,8 +70,6 @@ #include "TextAlignment.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; const quint64 UNKNOWN_CREATED_TIME = 0; @@ -100,7 +98,7 @@ EntityPropertyInfo makePropertyInfo(EntityPropertyList p, typename std::enable_i } /// A collection of properties of an entity item used in the scripting API. Translates between the actual properties of an -/// entity and a JavaScript style hash/ScriptValuePointer storing a set of properties. Used in scripting to set/get the complete +/// entity and a JavaScript style hash/ScriptValue storing a set of properties. Used in scripting to set/get the complete /// set of entity item properties via JavaScript hashes/QScriptValues /// all units for SI units (meter, second, radian, etc) class EntityItemProperties { @@ -137,13 +135,13 @@ public: EntityTypes::EntityType getType() const { return _type; } void setType(EntityTypes::EntityType type) { _type = type; } - virtual ScriptValuePointer copyToScriptValue(ScriptEngine* engine, bool skipDefaults, bool allowUnknownCreateTime = false, + virtual ScriptValue copyToScriptValue(ScriptEngine* engine, bool skipDefaults, bool allowUnknownCreateTime = false, bool strictSemantics = false, EntityPsuedoPropertyFlags psueudoPropertyFlags = EntityPsuedoPropertyFlags()) const; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool honorReadOnly); + virtual void copyFromScriptValue(const ScriptValue& object, bool honorReadOnly); void copyFromJSONString(ScriptEngine& scriptEngine, const QString& jsonString); - static ScriptValuePointer entityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags); - static void entityPropertyFlagsFromScriptValue(const ScriptValuePointer& object, EntityPropertyFlags& flags); + static ScriptValue entityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags); + static void entityPropertyFlagsFromScriptValue(const ScriptValue& object, EntityPropertyFlags& flags); static bool getPropertyInfo(const QString& propertyName, EntityPropertyInfo& propertyInfo); @@ -543,18 +541,18 @@ private: }; Q_DECLARE_METATYPE(EntityItemProperties); -ScriptValuePointer EntityItemPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties); -ScriptValuePointer EntityItemNonDefaultPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties); -void EntityItemPropertiesFromScriptValueIgnoreReadOnly(const ScriptValuePointer& object, EntityItemProperties& properties); -void EntityItemPropertiesFromScriptValueHonorReadOnly(const ScriptValuePointer& object, EntityItemProperties& properties); +ScriptValue EntityItemPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties); +ScriptValue EntityItemNonDefaultPropertiesToScriptValue(ScriptEngine* engine, const EntityItemProperties& properties); +void EntityItemPropertiesFromScriptValueIgnoreReadOnly(const ScriptValue& object, EntityItemProperties& properties); +void EntityItemPropertiesFromScriptValueHonorReadOnly(const ScriptValue& object, EntityItemProperties& properties); Q_DECLARE_METATYPE(EntityPropertyFlags); -ScriptValuePointer EntityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags); -void EntityPropertyFlagsFromScriptValue(const ScriptValuePointer& object, EntityPropertyFlags& flags); +ScriptValue EntityPropertyFlagsToScriptValue(ScriptEngine* engine, const EntityPropertyFlags& flags); +void EntityPropertyFlagsFromScriptValue(const ScriptValue& object, EntityPropertyFlags& flags); Q_DECLARE_METATYPE(EntityPropertyInfo); -ScriptValuePointer EntityPropertyInfoToScriptValue(ScriptEngine* engine, const EntityPropertyInfo& propertyInfo); -void EntityPropertyInfoFromScriptValue(const ScriptValuePointer& object, EntityPropertyInfo& propertyInfo); +ScriptValue EntityPropertyInfoToScriptValue(ScriptEngine* engine, const EntityPropertyInfo& propertyInfo); +void EntityPropertyInfoFromScriptValue(const ScriptValue& object, EntityPropertyInfo& propertyInfo); // define these inline here so the macros work inline void EntityItemProperties::setPosition(const glm::vec3& value) diff --git a/libraries/entities/src/EntityItemPropertiesMacros.h b/libraries/entities/src/EntityItemPropertiesMacros.h index 550e822ff2..7f08d5b03c 100644 --- a/libraries/entities/src/EntityItemPropertiesMacros.h +++ b/libraries/entities/src/EntityItemPropertiesMacros.h @@ -13,11 +13,11 @@ #ifndef hifi_EntityItemPropertiesMacros_h #define hifi_EntityItemPropertiesMacros_h -#include "EntityItemID.h" +#include #include -#include "ScriptEngine.h" -#include "ScriptValue.h" -#include "ScriptValueUtils.h" +#include +#include +#include #define APPEND_ENTITY_PROPERTY(P,V) \ if (requestedProperties.getHasProperty(P)) { \ @@ -102,118 +102,118 @@ changedProperties += P; \ } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const glm::vec2& v) { return vec2ToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const glm::vec3& v) { return vec3ToScriptValue(e, v); } -inline ScriptValuePointer vec3Color_convertScriptValue(ScriptEngine* e, const glm::vec3& v) { return vec3ColorToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const glm::u8vec3& v) { return u8vec3ToScriptValue(e, v); } -inline ScriptValuePointer u8vec3Color_convertScriptValue(ScriptEngine* e, const glm::u8vec3& v) { return u8vec3ColorToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, float v) { return e->newValue(v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, int v) { return e->newValue(v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, bool v) { return e->newValue(v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, quint16 v) { return e->newValue(v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, quint32 v) { return e->newValue(v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, quint64 v) { return e->newValue((double)v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QString& v) { return e->newValue(v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const glm::vec2& v) { return vec2ToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const glm::vec3& v) { return vec3ToScriptValue(e, v); } +inline ScriptValue vec3Color_convertScriptValue(ScriptEngine* e, const glm::vec3& v) { return vec3ColorToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const glm::u8vec3& v) { return u8vec3ToScriptValue(e, v); } +inline ScriptValue u8vec3Color_convertScriptValue(ScriptEngine* e, const glm::u8vec3& v) { return u8vec3ColorToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, float v) { return e->newValue(v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, int v) { return e->newValue(v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, bool v) { return e->newValue(v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, quint16 v) { return e->newValue(v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, quint32 v) { return e->newValue(v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, quint64 v) { return e->newValue((double)v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const QString& v) { return e->newValue(v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const glm::quat& v) { return quatToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const ScriptValuePointer& v) { return v; } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorVec3ToScriptValue(e, v); } -inline ScriptValuePointer qVectorVec3Color_convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorVec3ColorToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorQuatToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorBoolToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QVector& v) { return qVectorFloatToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QVector& v) { return qVectorQUuidToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const glm::quat& v) { return quatToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const ScriptValue& v) { return v; } +inline ScriptValue convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorVec3ToScriptValue(e, v); } +inline ScriptValue qVectorVec3Color_convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorVec3ColorToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorQuatToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const QVector& v) {return qVectorBoolToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const QVector& v) { return qVectorFloatToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const QVector& v) { return qVectorQUuidToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QRect& v) { return qRectToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const QRect& v) { return qRectToScriptValue(e, v); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const QByteArray& v) { +inline ScriptValue convertScriptValue(ScriptEngine* e, const QByteArray& v) { QByteArray b64 = v.toBase64(); return e->newValue(QString(b64)); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const EntityItemID& v) { return e->newValue(QUuid(v).toString()); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const EntityItemID& v) { return e->newValue(QUuid(v).toString()); } -inline ScriptValuePointer convertScriptValue(ScriptEngine* e, const AACube& v) { return aaCubeToScriptValue(e, v); } +inline ScriptValue convertScriptValue(ScriptEngine* e, const AACube& v) { return aaCubeToScriptValue(e, v); } #define COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(X,G,g,P,p) \ if ((desiredProperties.isEmpty() || desiredProperties.getHasProperty(X)) && \ (!skipDefaults || defaultEntityProperties.get##G().get##P() != get##P())) { \ - ScriptValuePointer groupProperties = properties->property(#g); \ - if (!groupProperties->isValid()) { \ + ScriptValue groupProperties = properties.property(#g); \ + if (!groupProperties.isValid()) { \ groupProperties = engine->newObject(); \ } \ - ScriptValuePointer V = convertScriptValue(engine, get##P()); \ - groupProperties->setProperty(#p, V); \ - properties->setProperty(#g, groupProperties); \ + ScriptValue V = convertScriptValue(engine, get##P()); \ + groupProperties.setProperty(#p, V); \ + properties.setProperty(#g, groupProperties); \ } #define COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_TYPED(X,G,g,P,p,T) \ if ((desiredProperties.isEmpty() || desiredProperties.getHasProperty(X)) && \ (!skipDefaults || defaultEntityProperties.get##G().get##P() != get##P())) { \ - ScriptValuePointer groupProperties = properties->property(#g); \ - if (!groupProperties->isValid()) { \ + ScriptValue groupProperties = properties.property(#g); \ + if (!groupProperties.isValid()) { \ groupProperties = engine->newObject(); \ } \ - ScriptValuePointer V = T##_convertScriptValue(engine, get##P()); \ - groupProperties->setProperty(#p, V); \ - properties->setProperty(#g, groupProperties); \ + ScriptValue V = T##_convertScriptValue(engine, get##P()); \ + groupProperties.setProperty(#p, V); \ + properties.setProperty(#g, groupProperties); \ } #define COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_GETTER(X,G,g,P,p,M) \ if ((desiredProperties.isEmpty() || desiredProperties.getHasProperty(X)) && \ (!skipDefaults || defaultEntityProperties.get##G().get##P() != get##P())) { \ - ScriptValuePointer groupProperties = properties->property(#g); \ - if (!groupProperties->isValid()) { \ + ScriptValue groupProperties = properties.property(#g); \ + if (!groupProperties.isValid()) { \ groupProperties = engine->newObject(); \ } \ - ScriptValuePointer V = convertScriptValue(engine, M()); \ - groupProperties->setProperty(#p, V); \ - properties->setProperty(#g, groupProperties); \ + ScriptValue V = convertScriptValue(engine, M()); \ + groupProperties.setProperty(#p, V); \ + properties.setProperty(#g, groupProperties); \ } #define COPY_PROPERTY_TO_QSCRIPTVALUE(p,P) \ if (((!psuedoPropertyFlagsButDesiredEmpty && _desiredProperties.isEmpty()) || _desiredProperties.getHasProperty(p)) && \ (!skipDefaults || defaultEntityProperties._##P != _##P)) { \ - ScriptValuePointer V = convertScriptValue(engine, _##P); \ - properties->setProperty(#P, V); \ + ScriptValue V = convertScriptValue(engine, _##P); \ + properties.setProperty(#P, V); \ } #define COPY_PROPERTY_TO_QSCRIPTVALUE_TYPED(p,P,T) \ if ((_desiredProperties.isEmpty() || _desiredProperties.getHasProperty(p)) && \ (!skipDefaults || defaultEntityProperties._##P != _##P)) { \ - ScriptValuePointer V = T##_convertScriptValue(engine, _##P); \ - properties->setProperty(#P, V); \ + ScriptValue V = T##_convertScriptValue(engine, _##P); \ + properties.setProperty(#P, V); \ } #define COPY_PROPERTY_TO_QSCRIPTVALUE_GETTER_NO_SKIP(P, G) \ - properties->setProperty(#P, G); + properties.setProperty(#P, G); #define COPY_PROPERTY_TO_QSCRIPTVALUE_GETTER(p, P, G) \ if (((!psuedoPropertyFlagsButDesiredEmpty && _desiredProperties.isEmpty()) || _desiredProperties.getHasProperty(p)) && \ (!skipDefaults || defaultEntityProperties._##P != _##P)) { \ - ScriptValuePointer V = convertScriptValue(engine, G); \ - properties->setProperty(#P, V); \ + ScriptValue V = convertScriptValue(engine, G); \ + properties.setProperty(#P, V); \ } #define COPY_PROPERTY_TO_QSCRIPTVALUE_GETTER_TYPED(p, P, G, T) \ if ((_desiredProperties.isEmpty() || _desiredProperties.getHasProperty(p)) && \ (!skipDefaults || defaultEntityProperties._##P != _##P)) { \ - ScriptValuePointer V = T##_convertScriptValue(engine, G); \ - properties->setProperty(#P, V); \ + ScriptValue V = T##_convertScriptValue(engine, G); \ + properties.setProperty(#P, V); \ } // same as COPY_PROPERTY_TO_QSCRIPTVALUE_GETTER but uses #X instead of #P in the setProperty() step #define COPY_PROXY_PROPERTY_TO_QSCRIPTVALUE_GETTER(p, P, X, G) \ if (((!psuedoPropertyFlagsButDesiredEmpty && _desiredProperties.isEmpty()) || _desiredProperties.getHasProperty(p)) && \ (!skipDefaults || defaultEntityProperties._##P != _##P)) { \ - ScriptValuePointer V = convertScriptValue(engine, G); \ - properties->setProperty(#X, V); \ + ScriptValue V = convertScriptValue(engine, G); \ + properties.setProperty(#X, V); \ } #define COPY_PROPERTY_TO_QSCRIPTVALUE_GETTER_ALWAYS(P, G) \ if (!skipDefaults || defaultEntityProperties._##P != _##P) { \ - ScriptValuePointer V = convertScriptValue(engine, G); \ - properties->setProperty(#P, V); \ + ScriptValue V = convertScriptValue(engine, G); \ + properties.setProperty(#P, V); \ } typedef QVector qVectorVec3; @@ -221,100 +221,100 @@ typedef QVector qVectorQuat; typedef QVector qVectorBool; typedef QVector qVectorFloat; typedef QVector qVectorQUuid; -inline float float_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { return v->toVariant().toFloat(&isValid); } -inline quint64 quint64_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { return v->toVariant().toULongLong(&isValid); } -inline quint32 quint32_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline float float_convertFromScriptValue(const ScriptValue& v, bool& isValid) { return v.toVariant().toFloat(&isValid); } +inline quint64 quint64_convertFromScriptValue(const ScriptValue& v, bool& isValid) { return v.toVariant().toULongLong(&isValid); } +inline quint32 quint32_convertFromScriptValue(const ScriptValue& v, bool& isValid) { // Use QString::toUInt() so that isValid is set to false if the number is outside the quint32 range. - return v->toString().toUInt(&isValid); + return v.toString().toUInt(&isValid); } -inline quint16 quint16_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { return v->toVariant().toInt(&isValid); } -inline uint16_t uint16_t_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { return v->toVariant().toInt(&isValid); } -inline uint32_t uint32_t_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { return v->toVariant().toInt(&isValid); } -inline int int_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { return v->toVariant().toInt(&isValid); } -inline bool bool_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { isValid = true; return v->toVariant().toBool(); } -inline uint8_t uint8_t_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { isValid = true; return (uint8_t)(0xff & v->toVariant().toInt(&isValid)); } -inline QString QString_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { isValid = true; return v->toVariant().toString().trimmed(); } -inline QUuid QUuid_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { isValid = true; return v->toVariant().toUuid(); } -inline EntityItemID EntityItemID_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { isValid = true; return v->toVariant().toUuid(); } +inline quint16 quint16_convertFromScriptValue(const ScriptValue& v, bool& isValid) { return v.toVariant().toInt(&isValid); } +inline uint16_t uint16_t_convertFromScriptValue(const ScriptValue& v, bool& isValid) { return v.toVariant().toInt(&isValid); } +inline uint32_t uint32_t_convertFromScriptValue(const ScriptValue& v, bool& isValid) { return v.toVariant().toInt(&isValid); } +inline int int_convertFromScriptValue(const ScriptValue& v, bool& isValid) { return v.toVariant().toInt(&isValid); } +inline bool bool_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return v.toVariant().toBool(); } +inline uint8_t uint8_t_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return (uint8_t)(0xff & v.toVariant().toInt(&isValid)); } +inline QString QString_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return v.toVariant().toString().trimmed(); } +inline QUuid QUuid_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return v.toVariant().toUuid(); } +inline EntityItemID EntityItemID_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return v.toVariant().toUuid(); } -inline QByteArray QByteArray_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline QByteArray QByteArray_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; - QString b64 = v->toVariant().toString().trimmed(); + QString b64 = v.toVariant().toString().trimmed(); return QByteArray::fromBase64(b64.toUtf8()); } -inline glm::vec2 vec2_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline glm::vec2 vec2_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; glm::vec2 vec2; vec2FromScriptValue(v, vec2); return vec2; } -inline glm::vec3 vec3_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline glm::vec3 vec3_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; glm::vec3 vec3; vec3FromScriptValue(v, vec3); return vec3; } -inline glm::vec3 vec3Color_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline glm::vec3 vec3Color_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; glm::vec3 vec3; vec3FromScriptValue(v, vec3); return vec3; } -inline glm::u8vec3 u8vec3Color_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline glm::u8vec3 u8vec3Color_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; glm::u8vec3 vec3; u8vec3FromScriptValue(v, vec3); return vec3; } -inline AACube AACube_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline AACube AACube_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; AACube result; aaCubeFromScriptValue(v, result); return result; } -inline qVectorFloat qVectorFloat_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline qVectorFloat qVectorFloat_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return qVectorFloatFromScriptValue(v); } -inline qVectorVec3 qVectorVec3_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline qVectorVec3 qVectorVec3_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return qVectorVec3FromScriptValue(v); } -inline qVectorQuat qVectorQuat_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline qVectorQuat qVectorQuat_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return qVectorQuatFromScriptValue(v); } -inline qVectorBool qVectorBool_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline qVectorBool qVectorBool_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return qVectorBoolFromScriptValue(v); } -inline qVectorQUuid qVectorQUuid_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline qVectorQUuid qVectorQUuid_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; return qVectorQUuidFromScriptValue(v); } -inline glm::quat quat_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline glm::quat quat_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = false; /// assume it can't be converted - ScriptValuePointer x = v->property("x"); - ScriptValuePointer y = v->property("y"); - ScriptValuePointer z = v->property("z"); - ScriptValuePointer w = v->property("w"); - if (x->isValid() && y->isValid() && z->isValid() && w->isValid()) { + ScriptValue x = v.property("x"); + ScriptValue y = v.property("y"); + ScriptValue z = v.property("z"); + ScriptValue w = v.property("w"); + if (x.isValid() && y.isValid() && z.isValid() && w.isValid()) { glm::quat newValue; - newValue.x = x->toVariant().toFloat(); - newValue.y = y->toVariant().toFloat(); - newValue.z = z->toVariant().toFloat(); - newValue.w = w->toVariant().toFloat(); + newValue.x = x.toVariant().toFloat(); + newValue.y = y.toVariant().toFloat(); + newValue.z = z.toVariant().toFloat(); + newValue.w = w.toVariant().toFloat(); isValid = !glm::isnan(newValue.x) && !glm::isnan(newValue.y) && !glm::isnan(newValue.z) && @@ -326,7 +326,7 @@ inline glm::quat quat_convertFromScriptValue(const ScriptValuePointer& v, bool& return glm::quat(); } -inline QRect QRect_convertFromScriptValue(const ScriptValuePointer& v, bool& isValid) { +inline QRect QRect_convertFromScriptValue(const ScriptValue& v, bool& isValid) { isValid = true; QRect rect; qRectFromScriptValue(v, rect); @@ -344,8 +344,8 @@ inline QRect QRect_convertFromScriptValue(const ScriptValuePointer& v, bool& isV #define COPY_PROPERTY_FROM_QSCRIPTVALUE(P, T, S) \ { \ - ScriptValuePointer V = object->property(#P); \ - if (V->isValid()) { \ + ScriptValue V = object.property(#P); \ + if (V.isValid()) { \ bool isValid = false; \ T newValue = T##_convertFromScriptValue(V, isValid); \ if (isValid && (_defaultSettings || newValue != _##P)) { \ @@ -356,8 +356,8 @@ inline QRect QRect_convertFromScriptValue(const ScriptValuePointer& v, bool& isV #define COPY_PROPERTY_FROM_QSCRIPTVALUE_GETTER(P, T, S, G) \ { \ - ScriptValuePointer V = object->property(#P); \ - if (V->isValid()) { \ + ScriptValue V = object.property(#P); \ + if (V.isValid()) { \ bool isValid = false; \ T newValue = T##_convertFromScriptValue(V, isValid); \ if (isValid && (_defaultSettings || newValue != G())) { \ @@ -368,8 +368,8 @@ inline QRect QRect_convertFromScriptValue(const ScriptValuePointer& v, bool& isV #define COPY_PROPERTY_FROM_QSCRIPTVALUE_NOCHECK(P, T, S) \ { \ - ScriptValuePointer V = object->property(#P); \ - if (V->isValid()) { \ + ScriptValue V = object.property(#P); \ + if (V.isValid()) { \ bool isValid = false; \ T newValue = T##_convertFromScriptValue(V, isValid); \ if (isValid && (_defaultSettings)) { \ @@ -380,10 +380,10 @@ inline QRect QRect_convertFromScriptValue(const ScriptValuePointer& v, bool& isV #define COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(G, P, T, S) \ { \ - ScriptValuePointer G = object->property(#G); \ - if (G->isValid()) { \ - ScriptValuePointer V = G->property(#P); \ - if (V->isValid()) { \ + ScriptValue G = object.property(#G); \ + if (G.isValid()) { \ + ScriptValue V = G.property(#P); \ + if (V.isValid()) { \ bool isValid = false; \ T newValue = T##_convertFromScriptValue(V, isValid); \ if (isValid && (_defaultSettings || newValue != _##P)) { \ @@ -395,9 +395,9 @@ inline QRect QRect_convertFromScriptValue(const ScriptValuePointer& v, bool& isV #define COPY_PROPERTY_FROM_QSCRIPTVALUE_ENUM(P, S) \ { \ - ScriptValuePointer P = object->property(#P); \ - if (P->isValid()) { \ - QString newValue = P->toVariant().toString(); \ + ScriptValue P = object.property(#P); \ + if (P.isValid()) { \ + QString newValue = P.toVariant().toString(); \ if (_defaultSettings || newValue != get##S##AsString()) { \ set##S##FromString(newValue); \ } \ @@ -406,11 +406,11 @@ inline QRect QRect_convertFromScriptValue(const ScriptValuePointer& v, bool& isV #define COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE_ENUM(G, P, S) \ { \ - ScriptValuePointer G = object->property(#G); \ - if (G->isValid()) { \ - ScriptValuePointer P = G->property(#P); \ - if (P->isValid()) { \ - QString newValue = P->toVariant().toString(); \ + ScriptValue G = object.property(#G); \ + if (G.isValid()) { \ + ScriptValue P = G.property(#P); \ + if (P.isValid()) { \ + QString newValue = P.toVariant().toString(); \ if (_defaultSettings || newValue != get##S##AsString()) { \ set##S##FromString(newValue); \ } \ diff --git a/libraries/entities/src/EntityScriptingInterface.cpp b/libraries/entities/src/EntityScriptingInterface.cpp index f3723b1744..e9098c822b 100644 --- a/libraries/entities/src/EntityScriptingInterface.cpp +++ b/libraries/entities/src/EntityScriptingInterface.cpp @@ -846,7 +846,7 @@ struct EntityPropertiesResult { // Static method to make sure that we have the right script engine. // Using sender() or QtScriptable::engine() does not work for classes used by multiple threads (script-engines) -ScriptValuePointer EntityScriptingInterface::getMultipleEntityProperties(ScriptContext* context, ScriptEngine* engine) { +ScriptValue EntityScriptingInterface::getMultipleEntityProperties(ScriptContext* context, ScriptEngine* engine) { const int ARGUMENT_ENTITY_IDS = 0; const int ARGUMENT_EXTENDED_DESIRED_PROPERTIES = 1; @@ -855,12 +855,12 @@ ScriptValuePointer EntityScriptingInterface::getMultipleEntityProperties(ScriptC return entityScriptingInterface->getMultipleEntityPropertiesInternal(engine, entityIDs, context->argument(ARGUMENT_EXTENDED_DESIRED_PROPERTIES)); } -ScriptValuePointer EntityScriptingInterface::getMultipleEntityPropertiesInternal(ScriptEngine* engine, QVector entityIDs, const ScriptValuePointer& extendedDesiredProperties) { +ScriptValue EntityScriptingInterface::getMultipleEntityPropertiesInternal(ScriptEngine* engine, QVector entityIDs, const ScriptValue& extendedDesiredProperties) { PROFILE_RANGE(script_entities, __FUNCTION__); EntityPsuedoPropertyFlags psuedoPropertyFlags; - const auto readExtendedPropertyStringValue = [&](ScriptValuePointer extendedProperty) { - const auto extendedPropertyString = extendedProperty->toString(); + const auto readExtendedPropertyStringValue = [&](ScriptValue extendedProperty) { + const auto extendedPropertyString = extendedProperty.toString(); if (extendedPropertyString == "id") { psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::ID); } else if (extendedPropertyString == "type") { @@ -890,13 +890,13 @@ ScriptValuePointer EntityScriptingInterface::getMultipleEntityPropertiesInternal } }; - if (extendedDesiredProperties->isString()) { + if (extendedDesiredProperties.isString()) { readExtendedPropertyStringValue(extendedDesiredProperties); psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::FlagsActive); - } else if (extendedDesiredProperties->isArray()) { - const quint32 length = extendedDesiredProperties->property("length")->toInt32(); + } else if (extendedDesiredProperties.isArray()) { + const quint32 length = extendedDesiredProperties.property("length").toInt32(); for (quint32 i = 0; i < length; i++) { - readExtendedPropertyStringValue(extendedDesiredProperties->property(i)); + readExtendedPropertyStringValue(extendedDesiredProperties.property(i)); } psuedoPropertyFlags.set(EntityPsuedoPropertyFlag::FlagsActive); } @@ -948,18 +948,18 @@ ScriptValuePointer EntityScriptingInterface::getMultipleEntityPropertiesInternal }); } } - ScriptValuePointer finalResult = engine->newArray(resultProperties.size()); + ScriptValue finalResult = engine->newArray(resultProperties.size()); quint32 i = 0; if (needsScriptSemantics) { PROFILE_RANGE(script_entities, "EntityScriptingInterface::getMultipleEntityProperties>Script Semantics"); foreach(const auto& result, resultProperties) { - finalResult->setProperty(i++, convertPropertiesToScriptSemantics(result.properties, result.scalesWithParent) + finalResult.setProperty(i++, convertPropertiesToScriptSemantics(result.properties, result.scalesWithParent) .copyToScriptValue(engine, false, false, false, psuedoPropertyFlags)); } } else { PROFILE_RANGE(script_entities, "EntityScriptingInterface::getMultipleEntityProperties>Skip Script Semantics"); foreach(const auto& result, resultProperties) { - finalResult->setProperty(i++, result.properties.copyToScriptValue(engine, false, false, false, psuedoPropertyFlags)); + finalResult.setProperty(i++, result.properties.copyToScriptValue(engine, false, false, false, psuedoPropertyFlags)); } } return finalResult; @@ -1432,7 +1432,7 @@ QVector EntityScriptingInterface::findEntitiesByName(const QString entity } RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersection(const PickRay& ray, bool precisionPicking, - const ScriptValuePointer& entityIdsToInclude, const ScriptValuePointer& entityIdsToDiscard, bool visibleOnly, bool collidableOnly) const { + const ScriptValue& entityIdsToInclude, const ScriptValue& entityIdsToDiscard, bool visibleOnly, bool collidableOnly) const { PROFILE_RANGE(script_entities, __FUNCTION__); QVector entitiesToInclude = qVectorEntityItemIDFromScriptValue(entityIdsToInclude); QVector entitiesToDiscard = qVectorEntityItemIDFromScriptValue(entityIdsToDiscard); @@ -1508,13 +1508,13 @@ bool EntityScriptingInterface::reloadServerScripts(const QUuid& entityID) { return client->reloadServerScript(entityID); } -bool EntityPropertyMetadataRequest::script(EntityItemID entityID, ScriptValuePointer handler) { +bool EntityPropertyMetadataRequest::script(EntityItemID entityID, const ScriptValue& handler) { using LocalScriptStatusRequest = QFutureWatcher; LocalScriptStatusRequest* request = new LocalScriptStatusRequest; QObject::connect(request, &LocalScriptStatusRequest::finished, _manager, [=]() mutable { auto details = request->result().toMap(); - ScriptValuePointer err, result; + ScriptValue err, result; if (details.contains("isError")) { if (!details.contains("message")) { details["message"] = details["errorInfo"]; @@ -1535,14 +1535,14 @@ bool EntityPropertyMetadataRequest::script(EntityItemID entityID, ScriptValuePoi }, entityID); if (!request->isStarted()) { request->deleteLater(); - auto engine = handler->engine(); - callScopedHandlerObject(handler, engine->makeError(engine->newValue("Entities Scripting Provider unavailable"), "InternalError"), ScriptValuePointer()); + auto engine = handler.engine(); + callScopedHandlerObject(handler, engine->makeError(engine->newValue("Entities Scripting Provider unavailable"), "InternalError"), ScriptValue()); return false; } return true; } -bool EntityPropertyMetadataRequest::serverScripts(EntityItemID entityID, ScriptValuePointer handler) { +bool EntityPropertyMetadataRequest::serverScripts(EntityItemID entityID, const ScriptValue& handler) { auto client = DependencyManager::get(); auto request = client->createScriptStatusRequest(entityID); QPointer manager = _manager; @@ -1558,7 +1558,7 @@ bool EntityPropertyMetadataRequest::serverScripts(EntityItemID entityID, ScriptV details["status"] = EntityScriptStatus_::valueToKey(request->getStatus()).toLower(); details["errorInfo"] = request->getErrorInfo(); - ScriptValuePointer err, result; + ScriptValue err, result; if (!details["success"].toBool()) { if (!details.contains("message") && details.contains("errorInfo")) { details["message"] = details["errorInfo"]; @@ -1577,10 +1577,13 @@ bool EntityPropertyMetadataRequest::serverScripts(EntityItemID entityID, ScriptV return true; } -bool EntityScriptingInterface::queryPropertyMetadata(const QUuid& entityID, ScriptValuePointer property, ScriptValuePointer scopeOrCallback, ScriptValuePointer methodOrName) { - auto name = property->toString(); +bool EntityScriptingInterface::queryPropertyMetadata(const QUuid& entityID, + const ScriptValue& property, + const ScriptValue& scopeOrCallback, + const ScriptValue& methodOrName) { + auto name = property.toString(); auto handler = makeScopedHandlerObject(scopeOrCallback, methodOrName); - QPointer manager = handler->engine()->manager(); + QPointer manager = handler.engine()->manager(); if (!manager) { qCDebug(entities) << "queryPropertyMetadata without detectable script manager" << entityID << name; return false; @@ -1591,7 +1594,7 @@ bool EntityScriptingInterface::queryPropertyMetadata(const QUuid& entityID, Scri qDebug() << "queryPropertyMetadata -- engine destroyed!" << (!engine ? "nullptr" : "engine"); }); #endif - if (!handler->property("callback")->isFunction()) { + if (!handler.property("callback").isFunction()) { qDebug() << "!handler.callback.isFunction" << manager; engine->raiseException(engine->makeError(engine->newValue("callback is not a function"), "TypeError")); return false; @@ -1622,11 +1625,11 @@ bool EntityScriptingInterface::queryPropertyMetadata(const QUuid& entityID, Scri } } -bool EntityScriptingInterface::getServerScriptStatus(const QUuid& entityID, ScriptValuePointer callback) { +bool EntityScriptingInterface::getServerScriptStatus(const QUuid& entityID, const ScriptValue& callback) { auto client = DependencyManager::get(); auto request = client->createScriptStatusRequest(entityID); - auto engine = callback->engine(); + auto engine = callback.engine(); auto manager = engine->manager(); if (!manager) { engine->raiseException(engine->makeError(engine->newValue("This script does not belong to a ScriptManager"))); @@ -1636,9 +1639,9 @@ bool EntityScriptingInterface::getServerScriptStatus(const QUuid& entityID, Scri connect(request, &GetScriptStatusRequest::finished, manager, [callback](GetScriptStatusRequest* request) mutable { QString statusString = EntityScriptStatus_::valueToKey(request->getStatus()); - auto engine = callback->engine(); + auto engine = callback.engine(); ScriptValueList args { engine->newValue(request->getResponseReceived()), engine->newValue(request->getIsRunning()), engine->newValue(statusString.toLower()), engine->newValue(request->getErrorInfo()) }; - callback->call(ScriptValuePointer(), args); + callback.call(ScriptValue(), args); request->deleteLater(); }); request->start(); @@ -1669,40 +1672,40 @@ bool EntityScriptingInterface::getDrawZoneBoundaries() const { return ZoneEntityItem::getDrawZoneBoundaries(); } -ScriptValuePointer RayToEntityIntersectionResultToScriptValue(ScriptEngine* engine, const RayToEntityIntersectionResult& value) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("intersects", value.intersects); - obj->setProperty("accurate", value.accurate); - ScriptValuePointer entityItemValue = EntityItemIDtoScriptValue(engine, value.entityID); - obj->setProperty("entityID", entityItemValue); - obj->setProperty("distance", value.distance); - obj->setProperty("face", boxFaceToString(value.face)); +ScriptValue RayToEntityIntersectionResultToScriptValue(ScriptEngine* engine, const RayToEntityIntersectionResult& value) { + ScriptValue obj = engine->newObject(); + obj.setProperty("intersects", value.intersects); + obj.setProperty("accurate", value.accurate); + ScriptValue entityItemValue = EntityItemIDtoScriptValue(engine, value.entityID); + obj.setProperty("entityID", entityItemValue); + obj.setProperty("distance", value.distance); + obj.setProperty("face", boxFaceToString(value.face)); - ScriptValuePointer intersection = vec3ToScriptValue(engine, value.intersection); - obj->setProperty("intersection", intersection); - ScriptValuePointer surfaceNormal = vec3ToScriptValue(engine, value.surfaceNormal); - obj->setProperty("surfaceNormal", surfaceNormal); - obj->setProperty("extraInfo", engine->toScriptValue(value.extraInfo)); + ScriptValue intersection = vec3ToScriptValue(engine, value.intersection); + obj.setProperty("intersection", intersection); + ScriptValue surfaceNormal = vec3ToScriptValue(engine, value.surfaceNormal); + obj.setProperty("surfaceNormal", surfaceNormal); + obj.setProperty("extraInfo", engine->toScriptValue(value.extraInfo)); return obj; } -void RayToEntityIntersectionResultFromScriptValue(const ScriptValuePointer& object, RayToEntityIntersectionResult& value) { - value.intersects = object->property("intersects")->toVariant().toBool(); - value.accurate = object->property("accurate")->toVariant().toBool(); - ScriptValuePointer entityIDValue = object->property("entityID"); +void RayToEntityIntersectionResultFromScriptValue(const ScriptValue& object, RayToEntityIntersectionResult& value) { + value.intersects = object.property("intersects").toVariant().toBool(); + value.accurate = object.property("accurate").toVariant().toBool(); + ScriptValue entityIDValue = object.property("entityID"); quuidFromScriptValue(entityIDValue, value.entityID); - value.distance = object->property("distance")->toVariant().toFloat(); - value.face = boxFaceFromString(object->property("face")->toVariant().toString()); + value.distance = object.property("distance").toVariant().toFloat(); + value.face = boxFaceFromString(object.property("face").toVariant().toString()); - ScriptValuePointer intersection = object->property("intersection"); - if (intersection->isValid()) { + ScriptValue intersection = object.property("intersection"); + if (intersection.isValid()) { vec3FromScriptValue(intersection, value.intersection); } - ScriptValuePointer surfaceNormal = object->property("surfaceNormal"); - if (surfaceNormal->isValid()) { + ScriptValue surfaceNormal = object.property("surfaceNormal"); + if (surfaceNormal.isValid()) { vec3FromScriptValue(surfaceNormal, value.surfaceNormal); } - value.extraInfo = object->property("extraInfo")->toVariant().toMap(); + value.extraInfo = object.property("extraInfo").toVariant().toMap(); } bool EntityScriptingInterface::polyVoxWorker(QUuid entityID, std::function actor) { @@ -2423,15 +2426,15 @@ bool EntityScriptingInterface::AABoxIntersectsCapsule(const glm::vec3& low, cons return aaBox.findCapsulePenetration(start, end, radius, penetration); } -void EntityScriptingInterface::getMeshes(const QUuid& entityID, ScriptValuePointer callback) { +void EntityScriptingInterface::getMeshes(const QUuid& entityID, const ScriptValue& callback) { PROFILE_RANGE(script_entities, __FUNCTION__); - auto engine = callback->engine(); + auto engine = callback.engine(); EntityItemPointer entity = static_cast(_entityTree->findEntityByEntityItemID(entityID)); if (!entity) { qCDebug(entities) << "EntityScriptingInterface::getMeshes no entity with ID" << entityID; ScriptValueList args { engine->undefinedValue(), false }; - callback->call(ScriptValuePointer(), args); + callback.call(ScriptValue(), args); return; } @@ -2439,12 +2442,12 @@ void EntityScriptingInterface::getMeshes(const QUuid& entityID, ScriptValuePoint bool success = entity->getMeshes(result); if (success) { - ScriptValuePointer resultAsScriptValue = meshesToScriptValue(engine.data(), result); + ScriptValue resultAsScriptValue = meshesToScriptValue(engine.data(), result); ScriptValueList args{ resultAsScriptValue, engine->newValue(true) }; - callback->call(ScriptValuePointer(), args); + callback.call(ScriptValue(), args); } else { ScriptValueList args { engine->undefinedValue(), engine->newValue(false) }; - callback->call(ScriptValuePointer(), args); + callback.call(ScriptValue(), args); } } diff --git a/libraries/entities/src/EntityScriptingInterface.h b/libraries/entities/src/EntityScriptingInterface.h index f18a3212a1..3f21a3733f 100644 --- a/libraries/entities/src/EntityScriptingInterface.h +++ b/libraries/entities/src/EntityScriptingInterface.h @@ -29,6 +29,7 @@ #include "PointerEvent.h" #include #include +#include #include "PolyVoxEntityItem.h" #include "LineEntityItem.h" @@ -43,8 +44,6 @@ class EntityTree; class MeshProxy; class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; extern const QString GRABBABLE_USER_DATA; extern const QString NOT_GRABBABLE_USER_DATA; @@ -56,8 +55,8 @@ extern const QString NOT_GRABBABLE_USER_DATA; class EntityPropertyMetadataRequest { public: EntityPropertyMetadataRequest(ScriptManager* manager) : _manager(manager == nullptr ? nullptr : manager){}; - bool script(EntityItemID entityID, ScriptValuePointer handler); - bool serverScripts(EntityItemID entityID, ScriptValuePointer handler); + bool script(EntityItemID entityID, const ScriptValue& handler); + bool serverScripts(EntityItemID entityID, const ScriptValue& handler); private: QPointer _manager; }; @@ -90,8 +89,8 @@ public: QVariantMap extraInfo; }; Q_DECLARE_METATYPE(RayToEntityIntersectionResult) -ScriptValuePointer RayToEntityIntersectionResultToScriptValue(ScriptEngine* engine, const RayToEntityIntersectionResult& results); -void RayToEntityIntersectionResultFromScriptValue(const ScriptValuePointer& object, RayToEntityIntersectionResult& results); +ScriptValue RayToEntityIntersectionResultToScriptValue(ScriptEngine* engine, const RayToEntityIntersectionResult& results); +void RayToEntityIntersectionResultFromScriptValue(const ScriptValue& object, RayToEntityIntersectionResult& results); class ParabolaToEntityIntersectionResult { public: @@ -213,8 +212,8 @@ public: * var propertySets = Entities.getMultipleEntityProperties(entityIDs, "name"); * print("Nearby entity names: " + JSON.stringify(propertySets)); */ - static ScriptValuePointer getMultipleEntityProperties(ScriptContext* context, ScriptEngine* engine); - ScriptValuePointer getMultipleEntityPropertiesInternal(ScriptEngine* engine, QVector entityIDs, const ScriptValuePointer& extendedDesiredProperties); + static ScriptValue getMultipleEntityProperties(ScriptContext* context, ScriptEngine* engine); + ScriptValue getMultipleEntityPropertiesInternal(ScriptEngine* engine, QVector entityIDs, const ScriptValue& extendedDesiredProperties); QUuid addEntityInternal(const EntityItemProperties& properties, entity::HostType entityHostType); @@ -839,7 +838,7 @@ public slots: /// may be inaccurate if the engine is unable to access the visible entities, in which case result.accurate /// will be false. Q_INVOKABLE RayToEntityIntersectionResult findRayIntersection(const PickRay& ray, bool precisionPicking = false, - const ScriptValuePointer& entityIdsToInclude = ScriptValuePointer(), const ScriptValuePointer& entityIdsToDiscard = ScriptValuePointer(), + const ScriptValue& entityIdsToInclude = ScriptValue(), const ScriptValue& entityIdsToDiscard = ScriptValue(), bool visibleOnly = false, bool collidableOnly = false) const; /*@jsdoc @@ -868,7 +867,7 @@ public slots: * @param {string} errorInfo - "" if there is a server entity script running, otherwise it may contain extra * information on the error. */ - Q_INVOKABLE bool getServerScriptStatus(const QUuid& entityID, ScriptValuePointer callback); + Q_INVOKABLE bool getServerScriptStatus(const QUuid& entityID, const ScriptValue& callback); /*@jsdoc * Gets metadata for certain entity properties such as script and serverScripts. @@ -898,8 +897,8 @@ public slots: * @param {object} result - The metadata for the requested entity property if there was no error, otherwise * undefined. */ - Q_INVOKABLE bool queryPropertyMetadata(const QUuid& entityID, ScriptValuePointer property, ScriptValuePointer scopeOrCallback, - ScriptValuePointer methodOrName = ScriptValuePointer()); + Q_INVOKABLE bool queryPropertyMetadata(const QUuid& entityID, const ScriptValue& property, const ScriptValue& scopeOrCallback, + const ScriptValue& methodOrName = ScriptValue()); /*@jsdoc @@ -1912,7 +1911,7 @@ public slots: * {@link Graphics} API instead. */ // FIXME move to a renderable entity interface - Q_INVOKABLE void getMeshes(const QUuid& entityID, ScriptValuePointer callback); + Q_INVOKABLE void getMeshes(const QUuid& entityID, const ScriptValue& callback); /*@jsdoc * Gets the object to world transform, excluding scale, of an entity. diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 38dda4932c..5372492036 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -3089,7 +3089,7 @@ bool EntityTree::readFromMap(QVariantMap& map, const bool isImport) { // map will have a top-level list keyed as "Entities". This will be extracted // and iterated over. Each member of this list is converted to a QVariantMap, then - // to a ScriptValuePointer, and then to EntityItemProperties. These properties are used + // to a ScriptValue, and then to EntityItemProperties. These properties are used // to add the new entity to the EntityTree. QVariantList entitiesQList = map["Entities"].toList(); ScriptEnginePointer scriptEngine = newScriptEngine(); @@ -3103,7 +3103,7 @@ bool EntityTree::readFromMap(QVariantMap& map, const bool isImport) { bool success = true; foreach (QVariant entityVariant, entitiesQList) { - // QVariantMap --> ScriptValuePointer --> EntityItemProperties --> Entity + // QVariantMap --> ScriptValue --> EntityItemProperties --> Entity QVariantMap entityMap = entityVariant.toMap(); // handle parentJointName for wearables @@ -3116,7 +3116,7 @@ bool EntityTree::readFromMap(QVariantMap& map, const bool isImport) { " mapped it to parentJointIndex " << entityMap["parentJointIndex"].toInt(); } - ScriptValuePointer entityScriptValue = variantMapToScriptValue(entityMap, *scriptEngine); + ScriptValue entityScriptValue = variantMapToScriptValue(entityMap, *scriptEngine); EntityItemProperties properties; EntityItemPropertiesFromScriptValueIgnoreReadOnly(entityScriptValue, properties); diff --git a/libraries/entities/src/GrabPropertyGroup.cpp b/libraries/entities/src/GrabPropertyGroup.cpp index f18d1c2c4a..10572dbcb8 100644 --- a/libraries/entities/src/GrabPropertyGroup.cpp +++ b/libraries/entities/src/GrabPropertyGroup.cpp @@ -16,7 +16,7 @@ #include "EntityItemProperties.h" #include "EntityItemPropertiesMacros.h" -void GrabPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, +void GrabPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_GRAB_GRABBABLE, Grab, grab, Grabbable, grabbable); @@ -43,7 +43,7 @@ void GrabPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProp } -void GrabPropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void GrabPropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(grab, grabbable, bool, setGrabbable); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(grab, grabKinematic, bool, setGrabKinematic); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(grab, grabFollowsController, bool, setGrabFollowsController); diff --git a/libraries/entities/src/GrabPropertyGroup.h b/libraries/entities/src/GrabPropertyGroup.h index a6577edda2..ebf0175ea3 100644 --- a/libraries/entities/src/GrabPropertyGroup.h +++ b/libraries/entities/src/GrabPropertyGroup.h @@ -16,8 +16,6 @@ #include -#include - #include "PropertyGroup.h" #include "EntityItemPropertiesMacros.h" @@ -26,7 +24,6 @@ class EncodeBitstreamParams; class OctreePacketData; class ReadBitstreamToTreeParams; class ScriptValue; -using ScriptValuePointer = QSharedPointer; static const bool INITIAL_GRABBABLE { true }; static const bool INITIAL_KINEMATIC { true }; @@ -74,10 +71,10 @@ static const glm::vec3 INITIAL_EQUIPPABLE_INDICATOR_OFFSET { glm::vec3(0.0f) }; class GrabPropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const GrabPropertyGroup& other); diff --git a/libraries/entities/src/HazePropertyGroup.cpp b/libraries/entities/src/HazePropertyGroup.cpp index d9b939babc..04595789e5 100644 --- a/libraries/entities/src/HazePropertyGroup.cpp +++ b/libraries/entities/src/HazePropertyGroup.cpp @@ -16,7 +16,7 @@ #include "EntityItemProperties.h" #include "EntityItemPropertiesMacros.h" -void HazePropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { +void HazePropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_HAZE_RANGE, Haze, haze, HazeRange, hazeRange); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_TYPED(PROP_HAZE_COLOR, Haze, haze, HazeColor, hazeColor, u8vec3Color); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_TYPED(PROP_HAZE_GLARE_COLOR, Haze, haze, HazeGlareColor, hazeGlareColor, u8vec3Color); @@ -34,7 +34,7 @@ void HazePropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProp COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_HAZE_KEYLIGHT_ALTITUDE, Haze, haze, HazeKeyLightAltitude, hazeKeyLightAltitude); } -void HazePropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void HazePropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(haze, hazeRange, float, setHazeRange); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(haze, hazeColor, u8vec3Color, setHazeColor); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(haze, hazeGlareColor, u8vec3Color, setHazeGlareColor); diff --git a/libraries/entities/src/HazePropertyGroup.h b/libraries/entities/src/HazePropertyGroup.h index 208766fde0..249d4c65bc 100644 --- a/libraries/entities/src/HazePropertyGroup.h +++ b/libraries/entities/src/HazePropertyGroup.h @@ -16,8 +16,6 @@ #include -#include - #include "PropertyGroup.h" #include "EntityItemPropertiesMacros.h" @@ -28,7 +26,6 @@ class EntityTreeElementExtraEncodeData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; static const float INITIAL_HAZE_RANGE{ 1000.0f }; static const glm::u8vec3 initialHazeGlareColor { 255, 229, 179 }; @@ -79,10 +76,10 @@ static const float INITIAL_KEY_LIGHT_ALTITUDE{ 200.0f }; class HazePropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const HazePropertyGroup& other); diff --git a/libraries/entities/src/KeyLightPropertyGroup.cpp b/libraries/entities/src/KeyLightPropertyGroup.cpp index f688b47af3..b96f34d07c 100644 --- a/libraries/entities/src/KeyLightPropertyGroup.cpp +++ b/libraries/entities/src/KeyLightPropertyGroup.cpp @@ -25,7 +25,7 @@ const bool KeyLightPropertyGroup::DEFAULT_KEYLIGHT_CAST_SHADOWS { false }; const float KeyLightPropertyGroup::DEFAULT_KEYLIGHT_SHADOW_BIAS { 0.5f }; const float KeyLightPropertyGroup::DEFAULT_KEYLIGHT_SHADOW_MAX_DISTANCE { 40.0f }; -void KeyLightPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, +void KeyLightPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_TYPED(PROP_KEYLIGHT_COLOR, KeyLight, keyLight, Color, color, u8vec3Color); @@ -36,7 +36,7 @@ void KeyLightPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desired COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_KEYLIGHT_SHADOW_MAX_DISTANCE, KeyLight, keyLight, ShadowMaxDistance, shadowMaxDistance); } -void KeyLightPropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void KeyLightPropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(keyLight, color, u8vec3Color, setColor); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(keyLight, intensity, float, setIntensity); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(keyLight, direction, vec3, setDirection); diff --git a/libraries/entities/src/KeyLightPropertyGroup.h b/libraries/entities/src/KeyLightPropertyGroup.h index b88db49798..b04f76a098 100644 --- a/libraries/entities/src/KeyLightPropertyGroup.h +++ b/libraries/entities/src/KeyLightPropertyGroup.h @@ -17,7 +17,6 @@ #include -#include #include "EntityItemPropertiesMacros.h" #include "PropertyGroup.h" @@ -28,7 +27,6 @@ class EntityTreeElementExtraEncodeData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * A key light is defined by the following properties: @@ -48,10 +46,10 @@ using ScriptValuePointer = QSharedPointer; class KeyLightPropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const KeyLightPropertyGroup& other); diff --git a/libraries/entities/src/PropertyGroup.h b/libraries/entities/src/PropertyGroup.h index 9d74388caa..68f3bfb569 100644 --- a/libraries/entities/src/PropertyGroup.h +++ b/libraries/entities/src/PropertyGroup.h @@ -12,8 +12,6 @@ #ifndef hifi_PropertyGroup_h #define hifi_PropertyGroup_h -#include - #include #include "EntityPropertyFlags.h" @@ -26,7 +24,6 @@ class EntityTreeElementExtraEncodeData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; using EntityTreeElementExtraEncodeDataPointer = std::shared_ptr; @@ -35,8 +32,8 @@ public: virtual ~PropertyGroup() = default; // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const = 0; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) = 0; + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const = 0; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) = 0; virtual void debugDump() const { } virtual void listChangedProperties(QList& out) { } diff --git a/libraries/entities/src/PulsePropertyGroup.cpp b/libraries/entities/src/PulsePropertyGroup.cpp index 7db361df6f..b5ebd0cb2e 100644 --- a/libraries/entities/src/PulsePropertyGroup.cpp +++ b/libraries/entities/src/PulsePropertyGroup.cpp @@ -57,7 +57,7 @@ void PulsePropertyGroup::setAlphaModeFromString(const QString& pulseMode) { } } -void PulsePropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, +void PulsePropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_PULSE_MIN, Pulse, pulse, Min, min); @@ -67,7 +67,7 @@ void PulsePropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredPro COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_GETTER(PROP_PULSE_ALPHA_MODE, Pulse, pulse, AlphaMode, alphaMode, getAlphaModeAsString); } -void PulsePropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void PulsePropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(pulse, min, float, setMin); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(pulse, max, float, setMax); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(pulse, period, float, setPeriod); diff --git a/libraries/entities/src/PulsePropertyGroup.h b/libraries/entities/src/PulsePropertyGroup.h index 9f9bc92150..58452fdeea 100644 --- a/libraries/entities/src/PulsePropertyGroup.h +++ b/libraries/entities/src/PulsePropertyGroup.h @@ -13,8 +13,6 @@ #include -#include - #include #include "PropertyGroup.h" @@ -26,7 +24,6 @@ class OctreePacketData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * A color and alpha pulse that an entity may have. @@ -43,10 +40,10 @@ using ScriptValuePointer = QSharedPointer; class PulsePropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const PulsePropertyGroup& other); diff --git a/libraries/entities/src/RecurseOctreeToJSONOperator.cpp b/libraries/entities/src/RecurseOctreeToJSONOperator.cpp index 7e91a8d048..855085cbca 100644 --- a/libraries/entities/src/RecurseOctreeToJSONOperator.cpp +++ b/libraries/entities/src/RecurseOctreeToJSONOperator.cpp @@ -35,7 +35,7 @@ void RecurseOctreeToJSONOperator::processEntity(const EntityItemPointer& entity) return; // we weren't able to resolve a parent from _parentID, so don't save this entity. } - ScriptValuePointer qScriptValues = _skipDefaults + ScriptValue qScriptValues = _skipDefaults ? EntityItemNonDefaultPropertiesToScriptValue(_engine, entity->getProperties()) : EntityItemPropertiesToScriptValue(_engine, entity->getProperties()); @@ -46,6 +46,6 @@ void RecurseOctreeToJSONOperator::processEntity(const EntityItemPointer& entity) _json += "\n "; // Override default toString(): - qScriptValues->setProperty("toString", _toStringMethod); - _json += qScriptValues->toString(); + qScriptValues.setProperty("toString", _toStringMethod); + _json += qScriptValues.toString(); } diff --git a/libraries/entities/src/RecurseOctreeToJSONOperator.h b/libraries/entities/src/RecurseOctreeToJSONOperator.h index 4f4fce5b42..09d383d5a7 100644 --- a/libraries/entities/src/RecurseOctreeToJSONOperator.h +++ b/libraries/entities/src/RecurseOctreeToJSONOperator.h @@ -11,11 +11,9 @@ #include "EntityTree.h" -#include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class RecurseOctreeToJSONOperator : public RecurseOctreeOperator { public: @@ -30,7 +28,7 @@ private: void processEntity(const EntityItemPointer& entity); ScriptEngine* _engine; - ScriptValuePointer _toStringMethod; + ScriptValue _toStringMethod; QString _json; const bool _skipDefaults; diff --git a/libraries/entities/src/RecurseOctreeToMapOperator.cpp b/libraries/entities/src/RecurseOctreeToMapOperator.cpp index e8f1a483f8..deac281d49 100644 --- a/libraries/entities/src/RecurseOctreeToMapOperator.cpp +++ b/libraries/entities/src/RecurseOctreeToMapOperator.cpp @@ -57,7 +57,7 @@ bool RecurseOctreeToMapOperator::postRecursion(const OctreeElementPointer& eleme } EntityItemProperties properties = entityItem->getProperties(); - ScriptValuePointer qScriptValues; + ScriptValue qScriptValues; if (_skipDefaultValues) { qScriptValues = EntityItemNonDefaultPropertiesToScriptValue(_engine, properties); } else { @@ -71,11 +71,11 @@ bool RecurseOctreeToMapOperator::postRecursion(const OctreeElementPointer& eleme auto jointNames = _myAvatar->getJointNames(); auto parentJointIndex = entityItem->getParentJointIndex(); if (parentJointIndex < jointNames.count()) { - qScriptValues->setProperty("parentJointName", jointNames.at(parentJointIndex)); + qScriptValues.setProperty("parentJointName", jointNames.at(parentJointIndex)); } } - entitiesQList << qScriptValues->toVariant(); + entitiesQList << qScriptValues.toVariant(); }); _map["Entities"] = entitiesQList; diff --git a/libraries/entities/src/RingGizmoPropertyGroup.cpp b/libraries/entities/src/RingGizmoPropertyGroup.cpp index 1dcc443609..b9bb3a2b7e 100644 --- a/libraries/entities/src/RingGizmoPropertyGroup.cpp +++ b/libraries/entities/src/RingGizmoPropertyGroup.cpp @@ -20,7 +20,7 @@ const float RingGizmoPropertyGroup::MAX_ALPHA = 1.0f; const float RingGizmoPropertyGroup::MIN_RADIUS = 0.0f; const float RingGizmoPropertyGroup::MAX_RADIUS = 0.5f; -void RingGizmoPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, +void RingGizmoPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_START_ANGLE, Ring, ring, StartAngle, startAngle); @@ -46,7 +46,7 @@ void RingGizmoPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desire COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_TYPED(PROP_MINOR_TICK_MARKS_COLOR, Ring, ring, MinorTickMarksColor, minorTickMarksColor, u8vec3Color); } -void RingGizmoPropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void RingGizmoPropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(ring, startAngle, float, setStartAngle); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(ring, endAngle, float, setEndAngle); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(ring, innerRadius, float, setInnerRadius); diff --git a/libraries/entities/src/RingGizmoPropertyGroup.h b/libraries/entities/src/RingGizmoPropertyGroup.h index ca28b22218..d34f01c9b0 100644 --- a/libraries/entities/src/RingGizmoPropertyGroup.h +++ b/libraries/entities/src/RingGizmoPropertyGroup.h @@ -11,8 +11,6 @@ #include -#include - #include "PropertyGroup.h" #include "EntityItemPropertiesMacros.h" #include "EntityItemPropertiesDefaults.h" @@ -23,7 +21,6 @@ class OctreePacketData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; using u8vec3Color = glm::u8vec3; @@ -59,10 +56,10 @@ using u8vec3Color = glm::u8vec3; class RingGizmoPropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const RingGizmoPropertyGroup& other); diff --git a/libraries/entities/src/SkyboxPropertyGroup.cpp b/libraries/entities/src/SkyboxPropertyGroup.cpp index 4cd16c7579..43ffc878f4 100644 --- a/libraries/entities/src/SkyboxPropertyGroup.cpp +++ b/libraries/entities/src/SkyboxPropertyGroup.cpp @@ -18,12 +18,12 @@ const glm::u8vec3 SkyboxPropertyGroup::DEFAULT_COLOR = { 0, 0, 0 }; -void SkyboxPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { +void SkyboxPropertyGroup::copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const { COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE_TYPED(PROP_SKYBOX_COLOR, Skybox, skybox, Color, color, u8vec3Color); COPY_GROUP_PROPERTY_TO_QSCRIPTVALUE(PROP_SKYBOX_URL, Skybox, skybox, URL, url); } -void SkyboxPropertyGroup::copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) { +void SkyboxPropertyGroup::copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) { COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(skybox, color, u8vec3Color, setColor); COPY_GROUP_PROPERTY_FROM_QSCRIPTVALUE(skybox, url, QString, setURL); } diff --git a/libraries/entities/src/SkyboxPropertyGroup.h b/libraries/entities/src/SkyboxPropertyGroup.h index c95e92c7b3..89b2016802 100644 --- a/libraries/entities/src/SkyboxPropertyGroup.h +++ b/libraries/entities/src/SkyboxPropertyGroup.h @@ -16,8 +16,6 @@ #include -#include - #include #include "PropertyGroup.h" @@ -30,7 +28,6 @@ class EntityTreeElementExtraEncodeData; class ReadBitstreamToTreeParams; class ScriptEngine; class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * A skybox is defined by the following properties: @@ -42,10 +39,10 @@ using ScriptValuePointer = QSharedPointer; class SkyboxPropertyGroup : public PropertyGroup { public: // EntityItemProperty related helpers - virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValuePointer& properties, + virtual void copyToScriptValue(const EntityPropertyFlags& desiredProperties, ScriptValue& properties, ScriptEngine* engine, bool skipDefaults, EntityItemProperties& defaultEntityProperties) const override; - virtual void copyFromScriptValue(const ScriptValuePointer& object, bool& _defaultSettings) override; + virtual void copyFromScriptValue(const ScriptValue& object, bool& _defaultSettings) override; void merge(const SkyboxPropertyGroup& other); diff --git a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp index 8314057225..1bf6c52ca0 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp +++ b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.cpp @@ -319,14 +319,14 @@ namespace scriptable { scriptRegisterSequenceMetaType>>(engine); return scriptRegisterMetaType>( engine, - [](ScriptEngine* engine, const QPointer& object) -> ScriptValuePointer { + [](ScriptEngine* engine, const QPointer& object) -> ScriptValue { if (!object) { return engine->nullValue(); } return engine->newQObject(object, ScriptEngine::QtOwnership, ScriptEngine::AutoCreateDynamicProperties); }, - [](const ScriptValuePointer& value, QPointer& out) { - auto obj = value->toQObject(); + [](const ScriptValue& value, QPointer& out) { + auto obj = value.toQObject(); #ifdef SCRIPTABLE_MESH_DEBUG qCInfo(graphics_scripting) << "qpointer_qobject_cast" << obj << value.toString(); #endif @@ -348,11 +348,11 @@ namespace scriptable { ); } - ScriptValuePointer qVectorScriptableMaterialLayerToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue qVectorScriptableMaterialLayerToScriptValue(ScriptEngine* engine, const QVector& vector) { return scriptValueFromSequence(engine, vector); } - void qVectorScriptableMaterialLayerFromScriptValue(const ScriptValuePointer& array, QVector& result) { + void qVectorScriptableMaterialLayerFromScriptValue(const ScriptValue& array, QVector& result) { scriptValueToSequence(array, result); } @@ -470,197 +470,197 @@ namespace scriptable { * @property {boolean} defaultFallthrough - true if all properties fall through to the material below unless * they are set, false if properties respect their individual fall-through settings. */ - ScriptValuePointer scriptableMaterialToScriptValue(ScriptEngine* engine, const scriptable::ScriptableMaterial &material) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("name", material.name); - obj->setProperty("model", material.model); + ScriptValue scriptableMaterialToScriptValue(ScriptEngine* engine, const scriptable::ScriptableMaterial &material) { + ScriptValue obj = engine->newObject(); + obj.setProperty("name", material.name); + obj.setProperty("model", material.model); bool hasPropertyFallthroughs = !material.propertyFallthroughs.empty(); - const ScriptValuePointer FALLTHROUGH(engine->newValue("fallthrough")); + const ScriptValue FALLTHROUGH(engine->newValue("fallthrough")); if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::OPACITY_VAL_BIT)) { - obj->setProperty("opacity", FALLTHROUGH); + obj.setProperty("opacity", FALLTHROUGH); } else if (material.key.isTranslucentFactor()) { - obj->setProperty("opacity", material.opacity); + obj.setProperty("opacity", material.opacity); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::ALBEDO_VAL_BIT)) { - obj->setProperty("albedo", FALLTHROUGH); + obj.setProperty("albedo", FALLTHROUGH); } else if (material.key.isAlbedo()) { - obj->setProperty("albedo", vec3ColorToScriptValue(engine, material.albedo)); + obj.setProperty("albedo", vec3ColorToScriptValue(engine, material.albedo)); } if (material.model.toStdString() == graphics::Material::HIFI_PBR) { if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::OPACITY_CUTOFF_VAL_BIT)) { - obj->setProperty("opacityCutoff", FALLTHROUGH); + obj.setProperty("opacityCutoff", FALLTHROUGH); } else if (material.key.isOpacityCutoff()) { - obj->setProperty("opacityCutoff", material.opacityCutoff); + obj.setProperty("opacityCutoff", material.opacityCutoff); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::OPACITY_MAP_MODE_BIT)) { - obj->setProperty("opacityMapMode", FALLTHROUGH); + obj.setProperty("opacityMapMode", FALLTHROUGH); } else if (material.key.isOpacityMapMode()) { - obj->setProperty("opacityMapMode", material.opacityMapMode); + obj.setProperty("opacityMapMode", material.opacityMapMode); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::GLOSSY_VAL_BIT)) { - obj->setProperty("roughness", FALLTHROUGH); + obj.setProperty("roughness", FALLTHROUGH); } else if (material.key.isGlossy()) { - obj->setProperty("roughness", material.roughness); + obj.setProperty("roughness", material.roughness); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::METALLIC_VAL_BIT)) { - obj->setProperty("metallic", FALLTHROUGH); + obj.setProperty("metallic", FALLTHROUGH); } else if (material.key.isMetallic()) { - obj->setProperty("metallic", material.metallic); + obj.setProperty("metallic", material.metallic); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::SCATTERING_VAL_BIT)) { - obj->setProperty("scattering", FALLTHROUGH); + obj.setProperty("scattering", FALLTHROUGH); } else if (material.key.isScattering()) { - obj->setProperty("scattering", material.scattering); + obj.setProperty("scattering", material.scattering); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::UNLIT_VAL_BIT)) { - obj->setProperty("unlit", FALLTHROUGH); + obj.setProperty("unlit", FALLTHROUGH); } else if (material.key.isUnlit()) { - obj->setProperty("unlit", material.unlit); + obj.setProperty("unlit", material.unlit); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::EMISSIVE_VAL_BIT)) { - obj->setProperty("emissive", FALLTHROUGH); + obj.setProperty("emissive", FALLTHROUGH); } else if (material.key.isEmissive()) { - obj->setProperty("emissive", vec3ColorToScriptValue(engine, material.emissive)); + obj.setProperty("emissive", vec3ColorToScriptValue(engine, material.emissive)); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::EMISSIVE_MAP_BIT)) { - obj->setProperty("emissiveMap", FALLTHROUGH); + obj.setProperty("emissiveMap", FALLTHROUGH); } else if (!material.emissiveMap.isEmpty()) { - obj->setProperty("emissiveMap", material.emissiveMap); + obj.setProperty("emissiveMap", material.emissiveMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::ALBEDO_MAP_BIT)) { - obj->setProperty("albedoMap", FALLTHROUGH); + obj.setProperty("albedoMap", FALLTHROUGH); } else if (!material.albedoMap.isEmpty()) { - obj->setProperty("albedoMap", material.albedoMap); + obj.setProperty("albedoMap", material.albedoMap); } if (!material.opacityMap.isEmpty()) { - obj->setProperty("opacityMap", material.opacityMap); + obj.setProperty("opacityMap", material.opacityMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::OCCLUSION_MAP_BIT)) { - obj->setProperty("occlusionMap", FALLTHROUGH); + obj.setProperty("occlusionMap", FALLTHROUGH); } else if (!material.occlusionMap.isEmpty()) { - obj->setProperty("occlusionMap", material.occlusionMap); + obj.setProperty("occlusionMap", material.occlusionMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::LIGHT_MAP_BIT)) { - obj->setProperty("lightMap", FALLTHROUGH); + obj.setProperty("lightMap", FALLTHROUGH); } else if (!material.lightMap.isEmpty()) { - obj->setProperty("lightMap", material.lightMap); + obj.setProperty("lightMap", material.lightMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::SCATTERING_MAP_BIT)) { - obj->setProperty("scatteringMap", FALLTHROUGH); + obj.setProperty("scatteringMap", FALLTHROUGH); } else if (!material.scatteringMap.isEmpty()) { - obj->setProperty("scatteringMap", material.scatteringMap); + obj.setProperty("scatteringMap", material.scatteringMap); } // Only set one of each of these if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::METALLIC_MAP_BIT)) { - obj->setProperty("metallicMap", FALLTHROUGH); + obj.setProperty("metallicMap", FALLTHROUGH); } else if (!material.metallicMap.isEmpty()) { - obj->setProperty("metallicMap", material.metallicMap); + obj.setProperty("metallicMap", material.metallicMap); } else if (!material.specularMap.isEmpty()) { - obj->setProperty("specularMap", material.specularMap); + obj.setProperty("specularMap", material.specularMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::ROUGHNESS_MAP_BIT)) { - obj->setProperty("roughnessMap", FALLTHROUGH); + obj.setProperty("roughnessMap", FALLTHROUGH); } else if (!material.roughnessMap.isEmpty()) { - obj->setProperty("roughnessMap", material.roughnessMap); + obj.setProperty("roughnessMap", material.roughnessMap); } else if (!material.glossMap.isEmpty()) { - obj->setProperty("glossMap", material.glossMap); + obj.setProperty("glossMap", material.glossMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::MaterialKey::NORMAL_MAP_BIT)) { - obj->setProperty("normalMap", FALLTHROUGH); + obj.setProperty("normalMap", FALLTHROUGH); } else if (!material.normalMap.isEmpty()) { - obj->setProperty("normalMap", material.normalMap); + obj.setProperty("normalMap", material.normalMap); } else if (!material.bumpMap.isEmpty()) { - obj->setProperty("bumpMap", material.bumpMap); + obj.setProperty("bumpMap", material.bumpMap); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::Material::TEXCOORDTRANSFORM0)) { - obj->setProperty("texCoordTransform0", FALLTHROUGH); + obj.setProperty("texCoordTransform0", FALLTHROUGH); } else if (material.texCoordTransforms[0] != mat4()) { - obj->setProperty("texCoordTransform0", mat4toScriptValue(engine, material.texCoordTransforms[0])); + obj.setProperty("texCoordTransform0", mat4toScriptValue(engine, material.texCoordTransforms[0])); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::Material::TEXCOORDTRANSFORM1)) { - obj->setProperty("texCoordTransform1", FALLTHROUGH); + obj.setProperty("texCoordTransform1", FALLTHROUGH); } else if (material.texCoordTransforms[1] != mat4()) { - obj->setProperty("texCoordTransform1", mat4toScriptValue(engine, material.texCoordTransforms[1])); + obj.setProperty("texCoordTransform1", mat4toScriptValue(engine, material.texCoordTransforms[1])); } // These need to be implemented, but set the fallthrough for now if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::Material::LIGHTMAP_PARAMS)) { - obj->setProperty("lightmapParams", FALLTHROUGH); + obj.setProperty("lightmapParams", FALLTHROUGH); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::Material::MATERIAL_PARAMS)) { - obj->setProperty("materialParams", FALLTHROUGH); + obj.setProperty("materialParams", FALLTHROUGH); } if (hasPropertyFallthroughs && material.propertyFallthroughs.at(graphics::Material::CULL_FACE_MODE)) { - obj->setProperty("cullFaceMode", FALLTHROUGH); + obj.setProperty("cullFaceMode", FALLTHROUGH); } else if (!material.cullFaceMode.isEmpty()) { - obj->setProperty("cullFaceMode", material.cullFaceMode); + obj.setProperty("cullFaceMode", material.cullFaceMode); } } else if (material.model.toStdString() == graphics::Material::HIFI_SHADER_SIMPLE) { - obj->setProperty("procedural", material.procedural); + obj.setProperty("procedural", material.procedural); } - obj->setProperty("defaultFallthrough", material.defaultFallthrough); + obj.setProperty("defaultFallthrough", material.defaultFallthrough); return obj; } - void scriptableMaterialFromScriptValue(const ScriptValuePointer &object, scriptable::ScriptableMaterial& material) { - // No need to convert from ScriptValuePointer to ScriptableMaterial + void scriptableMaterialFromScriptValue(const ScriptValue &object, scriptable::ScriptableMaterial& material) { + // No need to convert from ScriptValue to ScriptableMaterial } - ScriptValuePointer scriptableMaterialLayerToScriptValue(ScriptEngine* engine, const scriptable::ScriptableMaterialLayer &materialLayer) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("material", scriptableMaterialToScriptValue(engine, materialLayer.material)); - obj->setProperty("priority", materialLayer.priority); + ScriptValue scriptableMaterialLayerToScriptValue(ScriptEngine* engine, const scriptable::ScriptableMaterialLayer &materialLayer) { + ScriptValue obj = engine->newObject(); + obj.setProperty("material", scriptableMaterialToScriptValue(engine, materialLayer.material)); + obj.setProperty("priority", materialLayer.priority); return obj; } - void scriptableMaterialLayerFromScriptValue(const ScriptValuePointer &object, scriptable::ScriptableMaterialLayer& materialLayer) { - // No need to convert from ScriptValuePointer to ScriptableMaterialLayer + void scriptableMaterialLayerFromScriptValue(const ScriptValue &object, scriptable::ScriptableMaterialLayer& materialLayer) { + // No need to convert from ScriptValue to ScriptableMaterialLayer } - ScriptValuePointer multiMaterialMapToScriptValue(ScriptEngine* engine, const scriptable::MultiMaterialMap& map) { - ScriptValuePointer obj = engine->newObject(); + ScriptValue multiMaterialMapToScriptValue(ScriptEngine* engine, const scriptable::MultiMaterialMap& map) { + ScriptValue obj = engine->newObject(); for (auto key : map.keys()) { - obj->setProperty(key, qVectorScriptableMaterialLayerToScriptValue(engine, map[key])); + obj.setProperty(key, qVectorScriptableMaterialLayerToScriptValue(engine, map[key])); } return obj; } - void multiMaterialMapFromScriptValue(const ScriptValuePointer& map, scriptable::MultiMaterialMap& result) { - // No need to convert from ScriptValuePointer to MultiMaterialMap + void multiMaterialMapFromScriptValue(const ScriptValue& map, scriptable::MultiMaterialMap& result) { + // No need to convert from ScriptValue to MultiMaterialMap } template int registerDebugEnum(ScriptEngine* engine, const DebugEnums& debugEnums) { static const DebugEnums& instance = debugEnums; return scriptRegisterMetaType( engine, - [](ScriptEngine* engine, const T& topology) -> ScriptValuePointer { + [](ScriptEngine* engine, const T& topology) -> ScriptValue { return engine->newValue(instance.value(topology)); }, - [](const ScriptValuePointer& value, T& topology) { - topology = instance.key(value->toString()); + [](const ScriptValue& value, T& topology) { + topology = instance.key(value.toString()); } ); } diff --git a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.h b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.h index 18f4a2d0da..a2ffb9184b 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.h +++ b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingInterface.h @@ -11,7 +11,6 @@ #ifndef hifi_GraphicsScriptingInterface_h #define hifi_GraphicsScriptingInterface_h -#include #include #include @@ -19,10 +18,9 @@ #include #include "RegisteredMetaTypes.h" #include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The Graphics API enables you to access and manipulate avatar, entity, and overlay models in the rendered scene. @@ -151,7 +149,7 @@ private: }; namespace scriptable { - ScriptValuePointer scriptableMaterialToScriptValue(ScriptEngine* engine, const scriptable::ScriptableMaterial &material); + ScriptValue scriptableMaterialToScriptValue(ScriptEngine* engine, const scriptable::ScriptableMaterial &material); }; Q_DECLARE_METATYPE(NestableType) diff --git a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.cpp b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.cpp index 24ae383120..e42d3ad86a 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.cpp +++ b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.cpp @@ -10,9 +10,9 @@ #include #include #include -#include "ScriptContext.h" -#include "ScriptEngine.h" -#include "ScriptValue.h" +#include +#include +#include using buffer_helpers::glmVecToVariant; @@ -78,27 +78,27 @@ QVariant toVariant(const gpu::Element& element) { }; } -ScriptValuePointer jsBindCallback(ScriptValuePointer value) { - if (value->isObject() && value->property("callback")->isFunction()) { +ScriptValue jsBindCallback(const ScriptValue& value) { + if (value.isObject() && value.property("callback").isFunction()) { // value is already a bound callback return value; } - auto engine = value->engine(); + auto engine = value.engine(); auto context = engine ? engine->currentContext() : nullptr; auto length = context ? context->argumentCount() : 0; - ScriptValuePointer scope = context ? context->thisObject() : engine->nullValue(); - ScriptValuePointer method; + ScriptValue scope = context ? context->thisObject() : engine->nullValue(); + ScriptValue method; #ifdef SCRIPTABLE_MESH_DEBUG qCInfo(graphics_scripting) << "jsBindCallback" << engine << length << scope.toQObject() << method.toString(); #endif // find position in the incoming JS Function.arguments array (so we can test for the two-argument case) for (int i = 0; context && i < length; i++) { - if (context->argument(i)->strictlyEquals(value)) { + if (context->argument(i).strictlyEquals(value)) { method = context->argument(i+1); } } - if (method->isFunction() || method->isString()) { + if (method.isFunction() || method.isString()) { // interpret as `API.func(..., scope, function callback(){})` or `API.func(..., scope, "methodName")` scope = value; } else { @@ -114,7 +114,7 @@ ScriptValuePointer jsBindCallback(ScriptValuePointer value) { template T this_qobject_cast(ScriptEngine* engine) { auto context = engine ? engine->currentContext() : nullptr; - return scriptvalue_cast(context ? context->thisObject() : ScriptValuePointer::NullValue); + return scriptvalue_cast(context ? context->thisObject() : ScriptValue::NullValue); } QString toDebugString(QObject* tmp) { QString s; diff --git a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.h b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.h index ec97904552..53b49d1bd3 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.h +++ b/libraries/graphics-scripting/src/graphics-scripting/GraphicsScriptingUtil.h @@ -1,17 +1,15 @@ #pragma once #include -#include #include #include #include #include #include #include +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class Extents; class AABox; @@ -27,12 +25,12 @@ namespace scriptable { QVariant toVariant(const glm::mat4& mat4); // helper that automatically resolves Qt-signal-like scoped callbacks - // ... C++ side: `void MyClass::asyncMethod(..., ScriptValuePointer callback)` + // ... C++ side: `void MyClass::asyncMethod(..., const ScriptValue& callback)` // ... JS side: // * `API.asyncMethod(..., function(){})` // * `API.asyncMethod(..., scope, function(){})` // * `API.asyncMethod(..., scope, "methodName")` - ScriptValuePointer jsBindCallback(ScriptValuePointer callback); + ScriptValue jsBindCallback(const ScriptValue& callback); // cast engine->thisObject() => C++ class instance template T this_qobject_cast(ScriptEngine* engine); diff --git a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.cpp b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.cpp index f825e5c0ee..f19e58eca9 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.cpp +++ b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.cpp @@ -7,8 +7,6 @@ #include "ScriptableMesh.h" -#include - #include #include #include @@ -266,7 +264,7 @@ bool scriptable::ScriptableMesh::setVertexProperty(glm::uint32 vertexIndex, cons * @param {number} index - The vertex index. * @param {object} properties - The properties of the mesh, per {@link GraphicsMesh}. */ -glm::uint32 scriptable::ScriptableMesh::forEachVertex(ScriptValuePointer _callback) { +glm::uint32 scriptable::ScriptableMesh::forEachVertex(const ScriptValue& _callback) { auto mesh = getMeshPointer(); if (!mesh) { return 0; @@ -274,16 +272,16 @@ glm::uint32 scriptable::ScriptableMesh::forEachVertex(ScriptValuePointer _callba auto scopedHandler = jsBindCallback(_callback); // destructure so we can still invoke callback scoped, but with a custom signature (obj, i, jsMesh) - auto scope = scopedHandler->property("scope"); - auto callback = scopedHandler->property("callback"); - auto js = engine() ? engine() : scopedHandler->engine(); // cache value to avoid resolving each iteration + auto scope = scopedHandler.property("scope"); + auto callback = scopedHandler.property("callback"); + auto js = engine() ? engine() : scopedHandler.engine(); // cache value to avoid resolving each iteration if (!js) { return 0; } auto meshPart = js ? js->toScriptValue(getSelf()) : js->nullValue(); int numProcessed = 0; buffer_helpers::mesh::forEachVertex(mesh, [&](glm::uint32 index, const QVariantMap& values) { - auto result = callback->call(scope, { js->toScriptValue(values), js->newValue(index), meshPart }); + auto result = callback.call(scope, { js->toScriptValue(values), js->newValue(index), meshPart }); if (js->hasUncaughtException()) { js->currentContext()->throwValue(js->uncaughtException()); return false; @@ -304,7 +302,7 @@ glm::uint32 scriptable::ScriptableMesh::forEachVertex(ScriptValuePointer _callba * @returns {Object|boolean} The attribute values to update the vertex with, or * false to not update the vertex. */ -glm::uint32 scriptable::ScriptableMesh::updateVertexAttributes(ScriptValuePointer _callback) { +glm::uint32 scriptable::ScriptableMesh::updateVertexAttributes(const ScriptValue& _callback) { auto mesh = getMeshPointer(); if (!mesh) { return 0; @@ -312,9 +310,9 @@ glm::uint32 scriptable::ScriptableMesh::updateVertexAttributes(ScriptValuePointe auto scopedHandler = jsBindCallback(_callback); // destructure so we can still invoke callback scoped, but with a custom signature (obj, i, jsMesh) - auto scope = scopedHandler->property("scope"); - auto callback = scopedHandler->property("callback"); - auto js = engine() ? engine() : scopedHandler->engine(); // cache value to avoid resolving each iteration + auto scope = scopedHandler.property("scope"); + auto callback = scopedHandler.property("callback"); + auto js = engine() ? engine() : scopedHandler.engine(); // cache value to avoid resolving each iteration if (!js) { return 0; } @@ -323,23 +321,23 @@ glm::uint32 scriptable::ScriptableMesh::updateVertexAttributes(ScriptValuePointe auto attributeViews = buffer_helpers::mesh::getAllBufferViews(mesh); buffer_helpers::mesh::forEachVertex(mesh, [&](glm::uint32 index, const QVariantMap& values) { auto obj = js->toScriptValue(values); - auto result = callback->call(scope, { obj, js->newValue(index), meshPart }); + auto result = callback.call(scope, { obj, js->newValue(index), meshPart }); if (js->hasUncaughtException()) { js->currentContext()->throwValue(js->uncaughtException()); return false; } - if (result->isBool() && !result->toBool()) { + if (result.isBool() && !result.toBool()) { // bail without modifying data if user explicitly returns false return true; } - if (result->isObject() && !result->strictlyEquals(obj)) { + if (result.isObject() && !result.strictlyEquals(obj)) { // user returned a new object (ie: instead of modifying input properties) obj = result; } for (const auto& a : attributeViews) { - const auto& attribute = obj->property(a.first); - if (attribute->isValid()) { - buffer_helpers::setValue(a.second, index, attribute->toVariant()); + const auto& attribute = obj.property(a.first); + if (attribute.isValid()) { + buffer_helpers::setValue(a.second, index, attribute.toVariant()); } } numProcessed++; diff --git a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.h b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.h index 213b58b2ad..4a1419dd45 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.h +++ b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMesh.h @@ -20,7 +20,6 @@ #include #include #include -#include #include "GraphicsScriptingUtil.h" @@ -28,7 +27,6 @@ #include class ScriptValue; -using ScriptValuePointer = QSharedPointer; namespace scriptable { /*@jsdoc @@ -236,7 +234,7 @@ namespace scriptable { * @param {GraphicsMesh~updateVertexAttributesCallback} callback - The function to call for each vertex. * @returns {number} The number of vertices the callback was called for. */ - glm::uint32 updateVertexAttributes(ScriptValuePointer callback); + glm::uint32 updateVertexAttributes(const ScriptValue& callback); /*@jsdoc * Calls a function for each vertex. @@ -244,7 +242,7 @@ namespace scriptable { * @param {GraphicsMesh~forEachVertexCallback} callback - The function to call for each vertex. * @returns {number} The number of vertices the callback was called for. */ - glm::uint32 forEachVertex(ScriptValuePointer callback); + glm::uint32 forEachVertex(const ScriptValue& callback); /*@jsdoc * Checks if an index is valid and, optionally, that vertex has a particular attribute. diff --git a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.cpp b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.cpp index be99b3bd0b..1b93705dc8 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.cpp +++ b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.cpp @@ -77,12 +77,12 @@ QVariantList scriptable::ScriptableMeshPart::queryVertexAttributes(QVariant sele return parentMesh->queryVertexAttributes(selector); } -glm::uint32 scriptable::ScriptableMeshPart::forEachVertex(ScriptValuePointer _callback) { +glm::uint32 scriptable::ScriptableMeshPart::forEachVertex(const ScriptValue& _callback) { // TODO: limit to vertices within the part's indexed range? return isValid() ? parentMesh->forEachVertex(_callback) : 0; } -glm::uint32 scriptable::ScriptableMeshPart::updateVertexAttributes(ScriptValuePointer _callback) { +glm::uint32 scriptable::ScriptableMeshPart::updateVertexAttributes(const ScriptValue& _callback) { // TODO: limit to vertices within the part's indexed range? return isValid() ? parentMesh->updateVertexAttributes(_callback) : 0; } diff --git a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.h b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.h index 49e98e22d3..009d7b257c 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.h +++ b/libraries/graphics-scripting/src/graphics-scripting/ScriptableMeshPart.h @@ -7,13 +7,10 @@ #pragma once -#include - #include "ScriptableMesh.h" #include class ScriptValue; -using ScriptValuePointer = QSharedPointer; namespace scriptable { /*@jsdoc @@ -288,7 +285,7 @@ namespace scriptable { * @param {GraphicsMesh~updateVertexAttributesCallback} callback - The function to call for each vertex. * @returns {number} The number of vertices the callback was called for. */ - glm::uint32 updateVertexAttributes(ScriptValuePointer callback); + glm::uint32 updateVertexAttributes(const ScriptValue& callback); /*@jsdoc * Calls a function for each vertex in the whole mesh (i.e., parent and mesh parts). @@ -296,7 +293,7 @@ namespace scriptable { * @param {GraphicsMesh~forEachVertexCallback} callback - The function to call for each vertex. * @returns {number} The number of vertices the callback was called for. */ - glm::uint32 forEachVertex(ScriptValuePointer callback); + glm::uint32 forEachVertex(const ScriptValue& callback); /*@jsdoc * Checks if an index is valid and, optionally, that vertex has a particular attribute. diff --git a/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp b/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp index 2885a9a5de..ed61fa049f 100644 --- a/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp +++ b/libraries/graphics-scripting/src/graphics-scripting/ScriptableModel.cpp @@ -262,7 +262,7 @@ scriptable::ScriptableMeshes scriptable::ScriptableModel::getMeshes() { } #if 0 -glm::uint32 scriptable::ScriptableModel::forEachVertexAttribute(ScriptValuePointer callback) { +glm::uint32 scriptable::ScriptableModel::forEachVertexAttribute(const ScriptValue& callback) { glm::uint32 result = 0; scriptable::ScriptableMeshes in = getMeshes(); if (in.size()) { diff --git a/libraries/input-plugins/CMakeLists.txt b/libraries/input-plugins/CMakeLists.txt index b1fcc4076a..bc48c10b3a 100644 --- a/libraries/input-plugins/CMakeLists.txt +++ b/libraries/input-plugins/CMakeLists.txt @@ -1,5 +1,6 @@ set(TARGET_NAME input-plugins) setup_hifi_library() link_hifi_libraries(shared plugins ui-plugins controllers ui) +include_hifi_library_headers(script-engine) GroupSources("src/input-plugins") diff --git a/libraries/recording/src/recording/RecordingScriptingInterface.cpp b/libraries/recording/src/recording/RecordingScriptingInterface.cpp index f712a4c813..82fefe2695 100644 --- a/libraries/recording/src/recording/RecordingScriptingInterface.cpp +++ b/libraries/recording/src/recording/RecordingScriptingInterface.cpp @@ -56,19 +56,19 @@ float RecordingScriptingInterface::playerLength() const { return _player->length(); } -void RecordingScriptingInterface::playClip(NetworkClipLoaderPointer clipLoader, const QString& url, ScriptValuePointer callback) { +void RecordingScriptingInterface::playClip(NetworkClipLoaderPointer clipLoader, const QString& url, const ScriptValue& callback) { _player->queueClip(clipLoader->getClip()); - if (callback->isFunction()) { - auto engine = callback->engine(); + if (callback.isFunction()) { + auto engine = callback.engine(); ScriptValueList args{ engine->newValue(true), engine->newValue(url) }; - callback->call(ScriptValuePointer(), args); + callback.call(ScriptValue(), args); } } -void RecordingScriptingInterface::loadRecording(const QString& url, ScriptValuePointer callback) { +void RecordingScriptingInterface::loadRecording(const QString& url, const ScriptValue& callback) { if (QThread::currentThread() != thread()) { - BLOCKING_INVOKE_METHOD(this, "loadRecording", Q_ARG(const QString&, url), Q_ARG(ScriptValuePointer, callback)); + BLOCKING_INVOKE_METHOD(this, "loadRecording", Q_ARG(const QString&, url), Q_ARG(const ScriptValue&, callback)); return; } @@ -85,7 +85,7 @@ void RecordingScriptingInterface::loadRecording(const QString& url, ScriptValueP auto weakClipLoader = clipLoader.toWeakRef(); - auto manager = callback->engine()->manager(); + auto manager = callback.engine()->manager(); if (!manager) { qWarning() << "This script does not belong to a ScriptManager"; return; @@ -110,10 +110,10 @@ void RecordingScriptingInterface::loadRecording(const QString& url, ScriptValueP [this, weakClipLoader, url, callback](QNetworkReply::NetworkError error) mutable { qCDebug(scriptengine) << "Failed to load recording from\"" << url << '"'; - if (callback->isFunction()) { - auto engine = callback->engine(); + if (callback.isFunction()) { + auto engine = callback.engine(); ScriptValueList args{ engine->newValue(false), engine->newValue(url) }; - callback->call(ScriptValuePointer(), args); + callback.call(ScriptValue(), args); } if (auto clipLoader = weakClipLoader.toStrongRef()) { @@ -259,8 +259,8 @@ void RecordingScriptingInterface::saveRecording(const QString& filename) { recording::Clip::toFile(filename, _lastClip); } -bool RecordingScriptingInterface::saveRecordingToAsset(ScriptValuePointer getClipAtpUrl) { - if (!getClipAtpUrl->isFunction()) { +bool RecordingScriptingInterface::saveRecordingToAsset(const ScriptValue& getClipAtpUrl) { + if (!getClipAtpUrl.isFunction()) { qCWarning(scriptengine) << "The argument is not a function."; return false; } @@ -269,7 +269,7 @@ bool RecordingScriptingInterface::saveRecordingToAsset(ScriptValuePointer getCli bool result; BLOCKING_INVOKE_METHOD(this, "saveRecordingToAsset", Q_RETURN_ARG(bool, result), - Q_ARG(ScriptValuePointer, getClipAtpUrl)); + Q_ARG(const ScriptValue&, getClipAtpUrl)); return result; } @@ -278,7 +278,7 @@ bool RecordingScriptingInterface::saveRecordingToAsset(ScriptValuePointer getCli return false; } - auto manager = getClipAtpUrl->engine()->manager(); + auto manager = getClipAtpUrl.engine()->manager(); if (!manager) { qWarning() << "This script does not belong to a ScriptManager"; return false; @@ -297,8 +297,8 @@ bool RecordingScriptingInterface::saveRecordingToAsset(ScriptValuePointer getCli } ScriptValueList args; - args << getClipAtpUrl->engine()->newValue(clip_atp_url); - getClipAtpUrl->call(ScriptValuePointer(), args); + args << getClipAtpUrl.engine()->newValue(clip_atp_url); + getClipAtpUrl.call(ScriptValue(), args); }); upload->start(); return true; diff --git a/libraries/recording/src/recording/RecordingScriptingInterface.h b/libraries/recording/src/recording/RecordingScriptingInterface.h index bad1561695..20cf0e20bc 100644 --- a/libraries/recording/src/recording/RecordingScriptingInterface.h +++ b/libraries/recording/src/recording/RecordingScriptingInterface.h @@ -19,13 +19,12 @@ #include #include +#include + #include "ClipCache.h" #include "Forward.h" #include "Frame.h" -class ScriptValue; -using ScriptValuePointer = QSharedPointer; - /*@jsdoc * The Recording API makes and plays back recordings of voice and avatar movements. Playback may be done on a * user's avatar or an assignment client agent (see the {@link Agent} API). @@ -72,7 +71,7 @@ public slots: * }); * } */ - void loadRecording(const QString& url, ScriptValuePointer callback = ScriptValuePointer()); + void loadRecording(const QString& url, const ScriptValue& callback = ScriptValue()); /*@jsdoc @@ -336,7 +335,7 @@ public slots: * } * }, 5000); */ - bool saveRecordingToAsset(ScriptValuePointer getClipAtpUrl); + bool saveRecordingToAsset(const ScriptValue& getClipAtpUrl); /*@jsdoc * Loads the most recently made recording and plays it back on your avatar. @@ -369,7 +368,7 @@ protected: QSet _clipLoaders; private: - void playClip(recording::NetworkClipLoaderPointer clipLoader, const QString& url, ScriptValuePointer callback); + void playClip(recording::NetworkClipLoaderPointer clipLoader, const QString& url, const ScriptValue& callback); }; #endif // hifi_RecordingScriptingInterface_h diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index d9e193ee50..6ac1a3518e 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -7,6 +7,7 @@ link_hifi_libraries(shared task ktx gpu shaders graphics graphics-scripting mate include_hifi_library_headers(audio) include_hifi_library_headers(networking) include_hifi_library_headers(octree) +include_hifi_library_headers(script-engine) include_hifi_library_headers(hfm) # tell CMake to exclude qrc_fonts.cpp for policy CMP0071 diff --git a/libraries/script-engine/src/AssetScriptingInterface.cpp b/libraries/script-engine/src/AssetScriptingInterface.cpp index 942df370f5..99ef12ab62 100644 --- a/libraries/script-engine/src/AssetScriptingInterface.cpp +++ b/libraries/script-engine/src/AssetScriptingInterface.cpp @@ -63,7 +63,7 @@ bool AssetScriptingInterface::initializeCache() { } } -void AssetScriptingInterface::uploadData(QString data, ScriptValuePointer callback) { +void AssetScriptingInterface::uploadData(QString data, const ScriptValue& callback) { auto handler = jsBindCallback(thisObject(), callback); QByteArray dataByteArray = data.toUtf8(); auto upload = DependencyManager::get()->createUpload(dataByteArray); @@ -88,7 +88,7 @@ void AssetScriptingInterface::uploadData(QString data, ScriptValuePointer callba upload->start(); } -void AssetScriptingInterface::setMapping(QString path, QString hash, ScriptValuePointer callback) { +void AssetScriptingInterface::setMapping(QString path, QString hash, const ScriptValue& callback) { auto handler = jsBindCallback(thisObject(), callback); auto setMappingRequest = assetClient()->createSetMappingRequest(path, hash); Promise deferred = makePromise(__FUNCTION__); @@ -113,7 +113,7 @@ void AssetScriptingInterface::setMapping(QString path, QString hash, ScriptValue * @typedef {object} Assets.DownloadDataError * @property {string} errorMessage - "" if the download was successful, otherwise a description of the error. */ -void AssetScriptingInterface::downloadData(QString urlString, ScriptValuePointer callback) { +void AssetScriptingInterface::downloadData(QString urlString, const ScriptValue& callback) { // FIXME: historically this API method failed silently when given a non-atp prefixed // urlString (or if the AssetRequest failed). // .. is that by design or could we update without breaking things to provide better feedback to scripts? @@ -156,7 +156,7 @@ void AssetScriptingInterface::downloadData(QString urlString, ScriptValuePointer assetRequest->start(); } -void AssetScriptingInterface::setBakingEnabled(QString path, bool enabled, ScriptValuePointer callback) { +void AssetScriptingInterface::setBakingEnabled(QString path, bool enabled, const ScriptValue& callback) { auto setBakingEnabledRequest = DependencyManager::get()->createSetBakingEnabledRequest({ path }, enabled); Promise deferred = jsPromiseReady(makePromise(__FUNCTION__), thisObject(), callback); @@ -186,11 +186,11 @@ void AssetScriptingInterface::sendFakedHandshake() { #endif -void AssetScriptingInterface::getMapping(QString asset, ScriptValuePointer callback) { +void AssetScriptingInterface::getMapping(QString asset, const ScriptValue& callback) { auto path = AssetUtils::getATPUrl(asset).path(); auto handler = jsBindCallback(thisObject(), callback); JS_VERIFY(AssetUtils::isValidFilePath(path), "invalid ATP file path: " + asset + "(path:"+path+")"); - JS_VERIFY(callback->isFunction(), "expected second parameter to be a callback function"); + JS_VERIFY(callback.isFunction(), "expected second parameter to be a callback function"); Promise promise = getAssetInfo(path); auto scriptEngine = engine(); promise->ready([=](QString error, QVariantMap result) { @@ -210,19 +210,19 @@ bool AssetScriptingInterface::jsVerify(bool condition, const QString& error) { return false; } -ScriptValuePointer AssetScriptingInterface::jsBindCallback(ScriptValuePointer scope, ScriptValuePointer callback) { - ScriptValuePointer handler = ::makeScopedHandlerObject(scope, callback); - ScriptValuePointer value = handler->property("callback"); - if (!jsVerify(handler->isObject() && value->isFunction(), - QString("jsBindCallback -- .callback is not a function (%1)").arg(value->toVariant().typeName()))) { - return ScriptValuePointer(); +ScriptValue AssetScriptingInterface::jsBindCallback(const ScriptValue& scope, const ScriptValue& callback) { + ScriptValue handler = ::makeScopedHandlerObject(scope, callback); + ScriptValue value = handler.property("callback"); + if (!jsVerify(handler.isObject() && value.isFunction(), + QString("jsBindCallback -- .callback is not a function (%1)").arg(value.toVariant().typeName()))) { + return ScriptValue(); } return handler; } -Promise AssetScriptingInterface::jsPromiseReady(Promise promise, ScriptValuePointer scope, ScriptValuePointer callback) { +Promise AssetScriptingInterface::jsPromiseReady(Promise promise, const ScriptValue& scope, const ScriptValue& callback) { auto handler = jsBindCallback(scope, callback); - if (!jsVerify(handler->isValid(), "jsPromiseReady -- invalid callback handler")) { + if (!jsVerify(handler.isValid(), "jsPromiseReady -- invalid callback handler")) { return nullptr; } auto scriptEngine = engine(); @@ -231,25 +231,25 @@ Promise AssetScriptingInterface::jsPromiseReady(Promise promise, ScriptValuePoin }); } -void AssetScriptingInterface::jsCallback(const ScriptValuePointer& handler, - const ScriptValuePointer& error, const ScriptValuePointer& result) { +void AssetScriptingInterface::jsCallback(const ScriptValue& handler, + const ScriptValue& error, const ScriptValue& result) { Q_ASSERT(thread() == QThread::currentThread()); - auto errorValue = !error->toBool() ? engine()->nullValue() : error; - JS_VERIFY(handler->isObject() && handler->property("callback")->isFunction(), + auto errorValue = !error.toBool() ? engine()->nullValue() : error; + JS_VERIFY(handler.isObject() && handler.property("callback").isFunction(), QString("jsCallback -- .callback is not a function (%1)") - .arg(handler->property("callback")->toVariant().typeName())); + .arg(handler.property("callback").toVariant().typeName())); ::callScopedHandlerObject(handler, errorValue, result); } -void AssetScriptingInterface::jsCallback(const ScriptValuePointer& handler, - const ScriptValuePointer& error, const QVariantMap& result) { +void AssetScriptingInterface::jsCallback(const ScriptValue& handler, + const ScriptValue& error, const QVariantMap& result) { Q_ASSERT(thread() == QThread::currentThread()); - Q_ASSERT(handler->engine()); - auto engine = handler->engine(); + Q_ASSERT(handler.engine()); + auto engine = handler.engine(); jsCallback(handler, error, engine->toScriptValue(result)); } -void AssetScriptingInterface::deleteAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { +void AssetScriptingInterface::deleteAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { jsVerify(false, "TODO: deleteAsset API"); } @@ -279,14 +279,14 @@ void AssetScriptingInterface::deleteAsset(ScriptValuePointer options, ScriptValu * @property {boolean} [wasRedirected] - true if the downloaded data is the baked version of the asset, * false if it isn't baked. */ -void AssetScriptingInterface::getAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { - JS_VERIFY(options->isObject() || options->isString(), "expected request options Object or URL as first parameter"); +void AssetScriptingInterface::getAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { + JS_VERIFY(options.isObject() || options.isString(), "expected request options Object or URL as first parameter"); - auto decompress = options->property("decompress")->toBool() || options->property("compressed")->toBool(); - auto responseType = options->property("responseType")->toString().toLower(); - auto url = options->property("url")->toString(); - if (options->isString()) { - url = options->toString(); + auto decompress = options.property("decompress").toBool() || options.property("compressed").toBool(); + auto responseType = options.property("responseType").toString().toLower(); + auto url = options.property("url").toString(); + if (options.isString()) { + url = options.toString(); } if (responseType.isEmpty()) { responseType = "text"; @@ -345,10 +345,10 @@ void AssetScriptingInterface::getAsset(ScriptValuePointer options, ScriptValuePo * @property {boolean} [wasRedirected] - true if the resolved data is for the baked version of the asset, * false if it isn't. */ -void AssetScriptingInterface::resolveAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { +void AssetScriptingInterface::resolveAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { const QString& URL{ "url" }; - auto url = (options->isString() ? options : options->property(URL))->toString(); + auto url = (options.isString() ? options : options.property(URL)).toString(); auto asset = AssetUtils::getATPUrl(url).path(); JS_VERIFY(AssetUtils::isValidFilePath(asset) || AssetUtils::isValidHash(asset), @@ -372,10 +372,10 @@ void AssetScriptingInterface::resolveAsset(ScriptValuePointer options, ScriptVal * @property {string|object|ArrayBuffer} [response] - The decompressed data. * @property {Assets.ResponseType} [responseType] - The type of the decompressed data in response. */ -void AssetScriptingInterface::decompressData(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { - auto data = options->property("data"); +void AssetScriptingInterface::decompressData(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { + auto data = options.property("data"); QByteArray dataByteArray = scriptvalue_cast(data); - auto responseType = options->property("responseType")->toString().toLower(); + auto responseType = options.property("responseType").toString().toLower(); if (responseType.isEmpty()) { responseType = "text"; } @@ -413,10 +413,10 @@ namespace { * @property {string} [contentType] - The MIME type of the compressed data, i.e., "application/gzip". * @property {ArrayBuffer} [data] - The compressed data. */ -void AssetScriptingInterface::compressData(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { - auto data = options->property("data")->isValid() ? options->property("data") : options; - QByteArray dataByteArray = data->isString() ? data->toString().toUtf8() : scriptvalue_cast(data); - int level = options->property("level")->isNumber() ? options->property("level")->toInt32() : DEFAULT_GZIP_COMPRESSION_LEVEL; +void AssetScriptingInterface::compressData(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { + auto data = options.property("data").isValid() ? options.property("data") : options; + QByteArray dataByteArray = data.isString() ? data.toString().toUtf8() : scriptvalue_cast(data); + int level = options.property("level").isNumber() ? options.property("level").toInt32() : DEFAULT_GZIP_COMPRESSION_LEVEL; JS_VERIFY(level >= DEFAULT_GZIP_COMPRESSION_LEVEL || level <= MAX_GZIP_COMPRESSION_LEVEL, QString("invalid .level %1").arg(level)); jsPromiseReady(compressBytes(dataByteArray, level), scope, callback); } @@ -442,18 +442,18 @@ void AssetScriptingInterface::compressData(ScriptValuePointer options, ScriptVal * @property {string} [url] - The atp: URL of the content: using the path if specified, otherwise the hash. * @property {string} [path] - The uploaded content's mapped path, if specified. */ -void AssetScriptingInterface::putAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { - auto compress = options->property("compress")->toBool() || options->property("compressed")->toBool(); - auto data = options->isObject() ? options->property("data") : options; - auto rawPath = options->property("path")->toString(); +void AssetScriptingInterface::putAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { + auto compress = options.property("compress").toBool() || options.property("compressed").toBool(); + auto data = options.isObject() ? options.property("data") : options; + auto rawPath = options.property("path").toString(); auto path = AssetUtils::getATPUrl(rawPath).path(); - QByteArray dataByteArray = data->isString() ? data->toString().toUtf8() : scriptvalue_cast(data); + QByteArray dataByteArray = data.isString() ? data.toString().toUtf8() : scriptvalue_cast(data); JS_VERIFY(path.isEmpty() || AssetUtils::isValidFilePath(path), QString("expected valid ATP file path '%1' ('%2')").arg(rawPath).arg(path)); JS_VERIFY(dataByteArray.size() > 0, - QString("expected non-zero .data (got %1 / #%2 bytes)").arg(data->toVariant().typeName()).arg(dataByteArray.size())); + QString("expected non-zero .data (got %1 / #%2 bytes)").arg(data.toVariant().typeName()).arg(dataByteArray.size())); // [compressed] => uploaded to server => [mapped to path] Promise prepared = makePromise("putAsset::prepared"); @@ -498,8 +498,8 @@ void AssetScriptingInterface::putAsset(ScriptValuePointer options, ScriptValuePo * @property {string} url - The URL of the cached asset to get information on. Must start with "atp:" or * "cache:". */ -void AssetScriptingInterface::queryCacheMeta(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { - QString url = options->isString() ? options->toString() : options->property("url")->toString(); +void AssetScriptingInterface::queryCacheMeta(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { + QString url = options.isString() ? options.toString() : options.property("url").toString(); JS_VERIFY(QUrl(url).isValid(), QString("Invalid URL '%1'").arg(url)); jsPromiseReady(Parent::queryCacheMeta(url), scope, callback); } @@ -513,16 +513,16 @@ void AssetScriptingInterface::queryCacheMeta(ScriptValuePointer options, ScriptV * @property {string} url - The URL of the asset to load from cache. Must start with "atp:" or * "cache:". */ -void AssetScriptingInterface::loadFromCache(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { +void AssetScriptingInterface::loadFromCache(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { QString url, responseType; bool decompress = false; - if (options->isString()) { - url = options->toString(); + if (options.isString()) { + url = options.toString(); responseType = "text"; } else { - url = options->property("url")->toString(); - responseType = options->property("responseType")->isValid() ? options->property("responseType")->toString() : "text"; - decompress = options->property("decompress")->toBool() || options->property("compressed")->toBool(); + url = options.property("url").toString(); + responseType = options.property("responseType").isValid() ? options.property("responseType").toString() : "text"; + decompress = options.property("decompress").toBool() || options.property("compressed").toBool(); } JS_VERIFY(QUrl(url).isValid(), QString("Invalid URL '%1'").arg(url)); JS_VERIFY(RESPONSE_TYPES.contains(responseType), @@ -555,17 +555,21 @@ bool AssetScriptingInterface::canWriteCacheValue(const QUrl& url) { * @property {string} [url] - The URL to associate with the cache item. Must start with "atp:" or * "cache:". If not specified, the URL is "atp:" followed by the SHA256 hash of the content. */ -void AssetScriptingInterface::saveToCache(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback) { - JS_VERIFY(options->isObject(), QString("expected options object as first parameter not: %1").arg(options->toVariant().typeName())); +void AssetScriptingInterface::saveToCache(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback) { + JS_VERIFY(options.isObject(), QString("expected options object as first parameter not: %1").arg(options.toVariant().typeName())); - QString url = options->property("url")->toString(); - QByteArray data = scriptvalue_cast(options->property("data")); - QVariantMap headers = scriptvalue_cast(options->property("headers")); + QString url = options.property("url").toString(); + QByteArray data = scriptvalue_cast(options.property("data")); + QVariantMap headers = scriptvalue_cast(options.property("headers")); saveToCache(url, data, headers, scope, callback); } -void AssetScriptingInterface::saveToCache(const QUrl& rawURL, const QByteArray& data, const QVariantMap& metadata, ScriptValuePointer scope, ScriptValuePointer callback) { +void AssetScriptingInterface::saveToCache(const QUrl& rawURL, + const QByteArray& data, + const QVariantMap& metadata, + const ScriptValue& scope, + const ScriptValue& callback) { QUrl url = rawURL; if (url.path().isEmpty() && !data.isEmpty()) { // generate a valid ATP URL from the data -- appending any existing fragment or querystring values diff --git a/libraries/script-engine/src/AssetScriptingInterface.h b/libraries/script-engine/src/AssetScriptingInterface.h index 9a089986ca..ba83ab92a6 100644 --- a/libraries/script-engine/src/AssetScriptingInterface.h +++ b/libraries/script-engine/src/AssetScriptingInterface.h @@ -22,9 +22,11 @@ #include #include #include -#include #include +#include "Scriptable.h" +#include "ScriptValue.h" + /*@jsdoc * The Assets API provides facilities for interacting with the domain's asset server and the client cache. *

Assets are stored in the asset server in files with SHA256 names. These files are mapped to user-friendly URLs of the @@ -74,7 +76,7 @@ public: * }); * }); */ - Q_INVOKABLE void uploadData(QString data, ScriptValuePointer callback); + Q_INVOKABLE void uploadData(QString data, const ScriptValue& callback); /*@jsdoc * Called when an {@link Assets.downloadData} call is complete. @@ -110,7 +112,7 @@ public: * }); * }, 1000); */ - Q_INVOKABLE void downloadData(QString url, ScriptValuePointer callback); + Q_INVOKABLE void downloadData(QString url, const ScriptValue& callback); /*@jsdoc * Called when an {@link Assets.setMapping} call is complete. @@ -124,7 +126,7 @@ public: * @param {string} hash - The hash in the asset server. * @param {Assets~setMappingCallback} callback - The function to call upon completion. */ - Q_INVOKABLE void setMapping(QString path, QString hash, ScriptValuePointer callback); + Q_INVOKABLE void setMapping(QString path, QString hash, const ScriptValue& callback); /*@jsdoc * Called when an {@link Assets.getMapping} call is complete. @@ -148,7 +150,7 @@ public: * }); * } */ - Q_INVOKABLE void getMapping(QString path, ScriptValuePointer callback); + Q_INVOKABLE void getMapping(QString path, const ScriptValue& callback); /*@jsdoc * Called when an {@link Assets.setBakingEnabled} call is complete. @@ -164,7 +166,7 @@ public: * @param {Assets~setBakingEnabledCallback} callback - The function to call upon completion. */ // Note: Second callback parameter not documented because it's always {}. - Q_INVOKABLE void setBakingEnabled(QString path, bool enabled, ScriptValuePointer callback); + Q_INVOKABLE void setBakingEnabled(QString path, bool enabled, const ScriptValue& callback); #if (PR_BUILD || DEV_BUILD) /** @@ -220,7 +222,7 @@ public: * } * ); */ - Q_INVOKABLE void getAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void getAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Called when an {@link Assets.putAsset} call is complete. @@ -257,7 +259,7 @@ public: * } * ); */ - Q_INVOKABLE void putAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void putAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Called when an {@link Assets.deleteAsset} call is complete. @@ -274,7 +276,7 @@ public: * @param {object} scope - The scope that the callback function is defined in. * @param {Assets~deleteAssetCallback} callback - The function to call upon completion. */ - Q_INVOKABLE void deleteAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void deleteAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Called when an {@link Assets.resolveAsset} call is complete. @@ -308,7 +310,7 @@ public: * } * ); */ - Q_INVOKABLE void resolveAsset(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void resolveAsset(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Called when an {@link Assets.decompressData} call is complete. @@ -329,7 +331,7 @@ public: * in a string. If the name of a function or a function identifier, it must be a member of the scope specified by * scopeOrCallback.

*/ - Q_INVOKABLE void decompressData(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void decompressData(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Called when an {@link Assets.compressData} call is complete. @@ -351,7 +353,7 @@ public: * in a string. If the name of a function or a function identifier, it must be a member of the scope specified by * scopeOrCallback.

*/ - Q_INVOKABLE void compressData(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void compressData(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Initializes the cache if it isn't already initialized. @@ -396,7 +398,7 @@ public: * print("- Status: " + JSON.stringify(status)); * }); */ - Q_INVOKABLE void getCacheStatus(ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()) { + Q_INVOKABLE void getCacheStatus(const ScriptValue& scope, const ScriptValue& callback = ScriptValue()) { jsPromiseReady(Parent::getCacheStatus(), scope, callback); } @@ -436,7 +438,7 @@ public: * } * ); */ - Q_INVOKABLE void queryCacheMeta(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void queryCacheMeta(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Called when an {@link Assets.loadFromCache} call is complete. @@ -476,7 +478,7 @@ public: * } * ); */ - Q_INVOKABLE void loadFromCache(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void loadFromCache(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Called when an {@link Assets.saveToCache} call is complete. @@ -515,7 +517,7 @@ public: * } * ); */ - Q_INVOKABLE void saveToCache(ScriptValuePointer options, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void saveToCache(const ScriptValue& options, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); /*@jsdoc * Saves asset data to the cache directly, without downloading it from a URL. @@ -535,13 +537,13 @@ public: * scopeOrCallback.

*/ Q_INVOKABLE void saveToCache(const QUrl& url, const QByteArray& data, const QVariantMap& metadata, - ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); protected: - ScriptValuePointer jsBindCallback(ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); - Promise jsPromiseReady(Promise promise, ScriptValuePointer scope, ScriptValuePointer callback = ScriptValuePointer()); + ScriptValue jsBindCallback(const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); + Promise jsPromiseReady(Promise promise, const ScriptValue& scope, const ScriptValue& callback = ScriptValue()); - void jsCallback(const ScriptValuePointer& handler, const ScriptValuePointer& error, const QVariantMap& result); - void jsCallback(const ScriptValuePointer& handler, const ScriptValuePointer& error, const ScriptValuePointer& result); + void jsCallback(const ScriptValue& handler, const ScriptValue& error, const QVariantMap& result); + void jsCallback(const ScriptValue& handler, const ScriptValue& error, const ScriptValue& result); bool jsVerify(bool condition, const QString& error); }; diff --git a/libraries/script-engine/src/ConsoleScriptingInterface.cpp b/libraries/script-engine/src/ConsoleScriptingInterface.cpp index b36bd547a1..e8a4de24ad 100644 --- a/libraries/script-engine/src/ConsoleScriptingInterface.cpp +++ b/libraries/script-engine/src/ConsoleScriptingInterface.cpp @@ -30,14 +30,14 @@ const QString SPACE_SEPARATOR = " "; const QString STACK_TRACE_FORMAT = "\n[Stacktrace]%1%2"; QList ConsoleScriptingInterface::_groupDetails = QList(); -ScriptValuePointer ConsoleScriptingInterface::info(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::info(ScriptContext* context, ScriptEngine* engine) { if (ScriptManager* scriptManager = engine->manager()) { scriptManager->scriptInfoMessage(appendArguments(context)); } return engine->nullValue(); } -ScriptValuePointer ConsoleScriptingInterface::log(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::log(ScriptContext* context, ScriptEngine* engine) { QString message = appendArguments(context); if (_groupDetails.count() == 0) { if (ScriptManager* scriptManager = engine->manager()) { @@ -49,28 +49,28 @@ ScriptValuePointer ConsoleScriptingInterface::log(ScriptContext* context, Script return engine->nullValue(); } -ScriptValuePointer ConsoleScriptingInterface::debug(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::debug(ScriptContext* context, ScriptEngine* engine) { if (ScriptManager* scriptManager = engine->manager()) { scriptManager->scriptPrintedMessage(appendArguments(context)); } return engine->nullValue(); } -ScriptValuePointer ConsoleScriptingInterface::warn(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::warn(ScriptContext* context, ScriptEngine* engine) { if (ScriptManager* scriptManager = engine->manager()) { scriptManager->scriptWarningMessage(appendArguments(context)); } return engine->nullValue(); } -ScriptValuePointer ConsoleScriptingInterface::error(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::error(ScriptContext* context, ScriptEngine* engine) { if (ScriptManager* scriptManager = engine->manager()) { scriptManager->scriptErrorMessage(appendArguments(context)); } return engine->nullValue(); } -ScriptValuePointer ConsoleScriptingInterface::exception(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::exception(ScriptContext* context, ScriptEngine* engine) { if (ScriptManager* scriptManager = engine->manager()) { scriptManager->scriptErrorMessage(appendArguments(context)); } @@ -108,14 +108,14 @@ void ConsoleScriptingInterface::timeEnd(QString labelName) { } } -ScriptValuePointer ConsoleScriptingInterface::assertion(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::assertion(ScriptContext* context, ScriptEngine* engine) { QString message; bool condition = false; for (int i = 0; i < context->argumentCount(); i++) { if (i == 0) { - condition = context->argument(i)->toBool(); // accept first value as condition + condition = context->argument(i).toBool(); // accept first value as condition } else { - message += SPACE_SEPARATOR + context->argument(i)->toString(); // accept other parameters as message + message += SPACE_SEPARATOR + context->argument(i).toString(); // accept other parameters as message } } @@ -148,19 +148,19 @@ void ConsoleScriptingInterface::clear() { } } -ScriptValuePointer ConsoleScriptingInterface::group(ScriptContext* context, ScriptEngine* engine) { - logGroupMessage(context->argument(0)->toString(), engine); // accept first parameter as label - _groupDetails.push_back(context->argument(0)->toString()); +ScriptValue ConsoleScriptingInterface::group(ScriptContext* context, ScriptEngine* engine) { + logGroupMessage(context->argument(0).toString(), engine); // accept first parameter as label + _groupDetails.push_back(context->argument(0).toString()); return engine->nullValue(); } -ScriptValuePointer ConsoleScriptingInterface::groupCollapsed(ScriptContext* context, ScriptEngine* engine) { - logGroupMessage(context->argument(0)->toString(), engine); // accept first parameter as label - _groupDetails.push_back(context->argument(0)->toString()); +ScriptValue ConsoleScriptingInterface::groupCollapsed(ScriptContext* context, ScriptEngine* engine) { + logGroupMessage(context->argument(0).toString(), engine); // accept first parameter as label + _groupDetails.push_back(context->argument(0).toString()); return engine->nullValue(); } -ScriptValuePointer ConsoleScriptingInterface::groupEnd(ScriptContext* context, ScriptEngine* engine) { +ScriptValue ConsoleScriptingInterface::groupEnd(ScriptContext* context, ScriptEngine* engine) { ConsoleScriptingInterface::_groupDetails.removeLast(); return engine->nullValue(); } @@ -171,7 +171,7 @@ QString ConsoleScriptingInterface::appendArguments(ScriptContext* context) { if (i > 0) { message += SPACE_SEPARATOR; } - message += context->argument(i)->toString(); + message += context->argument(i).toString(); } return message; } diff --git a/libraries/script-engine/src/ConsoleScriptingInterface.h b/libraries/script-engine/src/ConsoleScriptingInterface.h index da3a32ab4a..6e00d559fc 100644 --- a/libraries/script-engine/src/ConsoleScriptingInterface.h +++ b/libraries/script-engine/src/ConsoleScriptingInterface.h @@ -27,14 +27,12 @@ #include #include #include -#include #include "Scriptable.h" +#include "ScriptValue.h" class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * The console API provides program logging facilities. @@ -58,7 +56,7 @@ public: * @function console.info * @param {...*} [message] - The message values to log. */ - static ScriptValuePointer info(ScriptContext* context, ScriptEngine* engine); + static ScriptValue info(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Logs a message to the program log and triggers {@link Script.printedMessage}. @@ -76,7 +74,7 @@ public: * // string 7 true * // INFO - Console.log message: "string 7 true" in [console.js] */ - static ScriptValuePointer log(ScriptContext* context, ScriptEngine* engine); + static ScriptValue log(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Logs a message to the program log and triggers {@link Script.printedMessage}. @@ -84,7 +82,7 @@ public: * @function console.debug * @param {...*} [message] - The message values to log. */ - static ScriptValuePointer debug(ScriptContext* context, ScriptEngine* engine); + static ScriptValue debug(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Logs a "WARNING" message to the program log and triggers {@link Script.warningMessage}. @@ -92,7 +90,7 @@ public: * @function console.warn * @param {...*} [message] - The message values to log. */ - static ScriptValuePointer warn(ScriptContext* context, ScriptEngine* engine); + static ScriptValue warn(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Logs an "ERROR" message to the program log and triggers {@link Script.errorMessage}. @@ -100,7 +98,7 @@ public: * @function console.error * @param {...*} [message] - The message values to log. */ - static ScriptValuePointer error(ScriptContext* context, ScriptEngine* engine); + static ScriptValue error(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * A synonym of {@link console.error}. @@ -109,7 +107,7 @@ public: * @function console.exception * @param {...*} [message] - The message values to log. */ - static ScriptValuePointer exception(ScriptContext* context, ScriptEngine* engine); + static ScriptValue exception(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Logs an "ERROR" message to the program log and triggers {@link Script.errorMessage}, if a test condition fails. @@ -132,7 +130,7 @@ public: * // INFO - Script continues running. */ // Note: Is registered in the script engine as "assert" - static ScriptValuePointer assertion(ScriptContext* context, ScriptEngine* engine); + static ScriptValue assertion(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Logs a message to the program log and triggers {@link Script.printedMessage}, then starts indenting subsequent @@ -160,7 +158,7 @@ public: * // Sentence 5 * //Sentence 6 */ - static ScriptValuePointer group(ScriptContext* context, ScriptEngine* engine); + static ScriptValue group(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Has the same behavior as {@link console.group}. @@ -169,13 +167,13 @@ public: * @function console.groupCollapsed * @param {*} message - The message value to log. */ - static ScriptValuePointer groupCollapsed(ScriptContext* context, ScriptEngine* engine); + static ScriptValue groupCollapsed(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * Finishes a group of indented {@link console.log} messages. * @function console.groupEnd */ - static ScriptValuePointer groupEnd(ScriptContext* context, ScriptEngine* engine); + static ScriptValue groupEnd(ScriptContext* context, ScriptEngine* engine); public slots: diff --git a/libraries/script-engine/src/KeyEvent.cpp b/libraries/script-engine/src/KeyEvent.cpp index 41fdf4332a..a6769c41c1 100644 --- a/libraries/script-engine/src/KeyEvent.cpp +++ b/libraries/script-engine/src/KeyEvent.cpp @@ -174,37 +174,37 @@ KeyEvent::operator QKeySequence() const { * print(JSON.stringify(event)); * }); */ -ScriptValuePointer KeyEvent::toScriptValue(ScriptEngine* engine, const KeyEvent& event) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("key", event.key); - obj->setProperty("text", event.text); - obj->setProperty("isShifted", event.isShifted); - obj->setProperty("isMeta", event.isMeta); - obj->setProperty("isControl", event.isControl); - obj->setProperty("isAlt", event.isAlt); - obj->setProperty("isKeypad", event.isKeypad); - obj->setProperty("isAutoRepeat", event.isAutoRepeat); +ScriptValue KeyEvent::toScriptValue(ScriptEngine* engine, const KeyEvent& event) { + ScriptValue obj = engine->newObject(); + obj.setProperty("key", event.key); + obj.setProperty("text", event.text); + obj.setProperty("isShifted", event.isShifted); + obj.setProperty("isMeta", event.isMeta); + obj.setProperty("isControl", event.isControl); + obj.setProperty("isAlt", event.isAlt); + obj.setProperty("isKeypad", event.isKeypad); + obj.setProperty("isAutoRepeat", event.isAutoRepeat); return obj; } -void KeyEvent::fromScriptValue(const ScriptValuePointer& object, KeyEvent& event) { +void KeyEvent::fromScriptValue(const ScriptValue& object, KeyEvent& event) { event.isValid = false; // assume the worst - event.isMeta = object->property("isMeta")->toVariant().toBool(); - event.isControl = object->property("isControl")->toVariant().toBool(); - event.isAlt = object->property("isAlt")->toVariant().toBool(); - event.isKeypad = object->property("isKeypad")->toVariant().toBool(); - event.isAutoRepeat = object->property("isAutoRepeat")->toVariant().toBool(); + event.isMeta = object.property("isMeta").toVariant().toBool(); + event.isControl = object.property("isControl").toVariant().toBool(); + event.isAlt = object.property("isAlt").toVariant().toBool(); + event.isKeypad = object.property("isKeypad").toVariant().toBool(); + event.isAutoRepeat = object.property("isAutoRepeat").toVariant().toBool(); - ScriptValuePointer key = object->property("key"); - if (key->isValid()) { - event.key = key->toVariant().toInt(); + ScriptValue key = object.property("key"); + if (key.isValid()) { + event.key = key.toVariant().toInt(); event.text = QString(QChar(event.key)); event.isValid = true; } else { - ScriptValuePointer text = object->property("text"); - if (text->isValid()) { - event.text = object->property("text")->toVariant().toString(); + ScriptValue text = object.property("text"); + if (text.isValid()) { + event.text = object.property("text").toVariant().toString(); // if the text is a special command, then map it here... // TODO: come up with more elegant solution here, a map? is there a Qt function that gives nice names for keys? @@ -283,9 +283,9 @@ void KeyEvent::fromScriptValue(const ScriptValuePointer& object, KeyEvent& event } } - ScriptValuePointer isShifted = object->property("isShifted"); - if (isShifted->isValid()) { - event.isShifted = isShifted->toVariant().toBool(); + ScriptValue isShifted = object.property("isShifted"); + if (isShifted.isValid()) { + event.isShifted = isShifted.toVariant().toBool(); } else { // if no isShifted was included, get it from the text QChar character = event.text.at(0); diff --git a/libraries/script-engine/src/KeyEvent.h b/libraries/script-engine/src/KeyEvent.h index 27b3d175d9..95cac8bc9e 100644 --- a/libraries/script-engine/src/KeyEvent.h +++ b/libraries/script-engine/src/KeyEvent.h @@ -16,11 +16,10 @@ #define hifi_KeyEvent_h #include -#include + +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// Represents a keyboard event to the scripting engine. Exposed as KeyEvent class KeyEvent { @@ -30,8 +29,8 @@ public: bool operator==(const KeyEvent& other) const; operator QKeySequence() const; - static ScriptValuePointer toScriptValue(ScriptEngine* engine, const KeyEvent& event); - static void fromScriptValue(const ScriptValuePointer& object, KeyEvent& event); + static ScriptValue toScriptValue(ScriptEngine* engine, const KeyEvent& event); + static void fromScriptValue(const ScriptValue& object, KeyEvent& event); int key; QString text; diff --git a/libraries/script-engine/src/LocationScriptingInterface.cpp b/libraries/script-engine/src/LocationScriptingInterface.cpp index 466ac779da..505af4bbef 100644 --- a/libraries/script-engine/src/LocationScriptingInterface.cpp +++ b/libraries/script-engine/src/LocationScriptingInterface.cpp @@ -21,12 +21,12 @@ LocationScriptingInterface* LocationScriptingInterface::getInstance() { return &sharedInstance; } -ScriptValuePointer LocationScriptingInterface::locationGetter(ScriptContext* context, ScriptEngine* engine) { +ScriptValue LocationScriptingInterface::locationGetter(ScriptContext* context, ScriptEngine* engine) { return engine->newQObject(DependencyManager::get().data()); } -ScriptValuePointer LocationScriptingInterface::locationSetter(ScriptContext* context, ScriptEngine* engine) { - const QVariant& argumentVariant = context->argument(0)->toVariant(); +ScriptValue LocationScriptingInterface::locationSetter(ScriptContext* context, ScriptEngine* engine) { + const QVariant& argumentVariant = context->argument(0).toVariant(); // just try and convert the argument to a string, should be a hifi:// address QMetaObject::invokeMethod(DependencyManager::get().data(), "handleLookupString", diff --git a/libraries/script-engine/src/LocationScriptingInterface.h b/libraries/script-engine/src/LocationScriptingInterface.h index 7603e113fa..0f7f4ded18 100644 --- a/libraries/script-engine/src/LocationScriptingInterface.h +++ b/libraries/script-engine/src/LocationScriptingInterface.h @@ -12,20 +12,18 @@ #ifndef hifi_LocationScriptingInterface_h #define hifi_LocationScriptingInterface_h -#include +#include "ScriptValue.h" class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class LocationScriptingInterface : public QObject { Q_OBJECT public: static LocationScriptingInterface* getInstance(); - static ScriptValuePointer locationGetter(ScriptContext* context, ScriptEngine* engine); - static ScriptValuePointer locationSetter(ScriptContext* context, ScriptEngine* engine); + static ScriptValue locationGetter(ScriptContext* context, ScriptEngine* engine); + static ScriptValue locationSetter(ScriptContext* context, ScriptEngine* engine); private: LocationScriptingInterface() {}; }; diff --git a/libraries/script-engine/src/MIDIEvent.cpp b/libraries/script-engine/src/MIDIEvent.cpp index fb782d07fb..d25ddc7e63 100644 --- a/libraries/script-engine/src/MIDIEvent.cpp +++ b/libraries/script-engine/src/MIDIEvent.cpp @@ -26,18 +26,18 @@ const QString MIDI_EVENT_TYPE_PROP_NAME = "type"; const QString MIDI_DATA_1_PROP_NAME = "data1"; const QString MIDI_DATA_2_PROP_NAME = "data2"; -ScriptValuePointer midiEventToScriptValue(ScriptEngine* engine, const MIDIEvent& event) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty(MIDI_DELTA_TIME_PROP_NAME, event.deltaTime); - obj->setProperty(MIDI_EVENT_TYPE_PROP_NAME, event.type); - obj->setProperty(MIDI_DATA_1_PROP_NAME, event.data1); - obj->setProperty(MIDI_DATA_2_PROP_NAME, event.data2); +ScriptValue midiEventToScriptValue(ScriptEngine* engine, const MIDIEvent& event) { + ScriptValue obj = engine->newObject(); + obj.setProperty(MIDI_DELTA_TIME_PROP_NAME, event.deltaTime); + obj.setProperty(MIDI_EVENT_TYPE_PROP_NAME, event.type); + obj.setProperty(MIDI_DATA_1_PROP_NAME, event.data1); + obj.setProperty(MIDI_DATA_2_PROP_NAME, event.data2); return obj; } -void midiEventFromScriptValue(const ScriptValuePointer &object, MIDIEvent& event) { - event.deltaTime = object->property(MIDI_DELTA_TIME_PROP_NAME)->toVariant().toDouble(); - event.type = object->property(MIDI_EVENT_TYPE_PROP_NAME)->toVariant().toUInt(); - event.data1 = object->property(MIDI_DATA_1_PROP_NAME)->toVariant().toUInt(); - event.data2 = object->property(MIDI_DATA_2_PROP_NAME)->toVariant().toUInt(); +void midiEventFromScriptValue(const ScriptValue &object, MIDIEvent& event) { + event.deltaTime = object.property(MIDI_DELTA_TIME_PROP_NAME).toVariant().toDouble(); + event.type = object.property(MIDI_EVENT_TYPE_PROP_NAME).toVariant().toUInt(); + event.data1 = object.property(MIDI_DATA_1_PROP_NAME).toVariant().toUInt(); + event.data2 = object.property(MIDI_DATA_2_PROP_NAME).toVariant().toUInt(); } \ No newline at end of file diff --git a/libraries/script-engine/src/MIDIEvent.h b/libraries/script-engine/src/MIDIEvent.h index 0d8138d8f6..1b2007cf3b 100644 --- a/libraries/script-engine/src/MIDIEvent.h +++ b/libraries/script-engine/src/MIDIEvent.h @@ -15,11 +15,9 @@ #ifndef hifi_MIDIEvent_h #define hifi_MIDIEvent_h -#include +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// Represents a MIDI protocol event to the scripting engine. class MIDIEvent { @@ -34,8 +32,8 @@ Q_DECLARE_METATYPE(MIDIEvent) void registerMIDIMetaTypes(ScriptEngine* engine); -ScriptValuePointer midiEventToScriptValue(ScriptEngine* engine, const MIDIEvent& event); -void midiEventFromScriptValue(const ScriptValuePointer &object, MIDIEvent& event); +ScriptValue midiEventToScriptValue(ScriptEngine* engine, const MIDIEvent& event); +void midiEventFromScriptValue(const ScriptValue &object, MIDIEvent& event); #endif // hifi_MIDIEvent_h diff --git a/libraries/script-engine/src/MenuItemProperties.cpp b/libraries/script-engine/src/MenuItemProperties.cpp index 34d68981ee..9864d7dd7f 100644 --- a/libraries/script-engine/src/MenuItemProperties.cpp +++ b/libraries/script-engine/src/MenuItemProperties.cpp @@ -47,8 +47,8 @@ void registerMenuItemProperties(ScriptEngine* engine) { scriptRegisterMetaType(engine, menuItemPropertiesToScriptValue, menuItemPropertiesFromScriptValue); } -ScriptValuePointer menuItemPropertiesToScriptValue(ScriptEngine* engine, const MenuItemProperties& properties) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue menuItemPropertiesToScriptValue(ScriptEngine* engine, const MenuItemProperties& properties) { + ScriptValue obj = engine->newObject(); // not supported return obj; } @@ -73,32 +73,32 @@ ScriptValuePointer menuItemPropertiesToScriptValue(ScriptEngine* engine, const M * @property {string} [afterItem] - The name of the menu item to place this menu item after. * @property {string} [grouping] - The name of grouping to add this menu item to. */ -void menuItemPropertiesFromScriptValue(const ScriptValuePointer& object, MenuItemProperties& properties) { - properties.menuName = object->property("menuName")->toVariant().toString(); - properties.menuItemName = object->property("menuItemName")->toVariant().toString(); - properties.isCheckable = object->property("isCheckable")->toVariant().toBool(); - properties.isChecked = object->property("isChecked")->toVariant().toBool(); - properties.isSeparator = object->property("isSeparator")->toVariant().toBool(); +void menuItemPropertiesFromScriptValue(const ScriptValue& object, MenuItemProperties& properties) { + properties.menuName = object.property("menuName").toVariant().toString(); + properties.menuItemName = object.property("menuItemName").toVariant().toString(); + properties.isCheckable = object.property("isCheckable").toVariant().toBool(); + properties.isChecked = object.property("isChecked").toVariant().toBool(); + properties.isSeparator = object.property("isSeparator").toVariant().toBool(); // handle the shortcut key options in order... - ScriptValuePointer shortcutKeyValue = object->property("shortcutKey"); - if (shortcutKeyValue->isValid()) { - properties.shortcutKey = shortcutKeyValue->toVariant().toString(); + ScriptValue shortcutKeyValue = object.property("shortcutKey"); + if (shortcutKeyValue.isValid()) { + properties.shortcutKey = shortcutKeyValue.toVariant().toString(); properties.shortcutKeySequence = properties.shortcutKey; } else { - ScriptValuePointer shortcutKeyEventValue = object->property("shortcutKeyEvent"); - if (shortcutKeyEventValue->isValid()) { + ScriptValue shortcutKeyEventValue = object.property("shortcutKeyEvent"); + if (shortcutKeyEventValue.isValid()) { KeyEvent::fromScriptValue(shortcutKeyEventValue, properties.shortcutKeyEvent); properties.shortcutKeySequence = properties.shortcutKeyEvent; } } - if (object->property("position")->isValid()) { - properties.position = object->property("position")->toVariant().toInt(); + if (object.property("position").isValid()) { + properties.position = object.property("position").toVariant().toInt(); } - properties.beforeItem = object->property("beforeItem")->toVariant().toString(); - properties.afterItem = object->property("afterItem")->toVariant().toString(); - properties.grouping = object->property("grouping")->toVariant().toString(); + properties.beforeItem = object.property("beforeItem").toVariant().toString(); + properties.afterItem = object.property("afterItem").toVariant().toString(); + properties.grouping = object.property("grouping").toVariant().toString(); } diff --git a/libraries/script-engine/src/MenuItemProperties.h b/libraries/script-engine/src/MenuItemProperties.h index 15d93c20bc..2ec69b7ff9 100644 --- a/libraries/script-engine/src/MenuItemProperties.h +++ b/libraries/script-engine/src/MenuItemProperties.h @@ -17,11 +17,9 @@ #include "KeyEvent.h" -#include +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// Represents a menu item a script may declare and bind events to. Exposed as MenuItemProperties class MenuItemProperties { @@ -56,8 +54,8 @@ private: static const int UNSPECIFIED_POSITION = -1; }; Q_DECLARE_METATYPE(MenuItemProperties) -ScriptValuePointer menuItemPropertiesToScriptValue(ScriptEngine* engine, const MenuItemProperties& props); -void menuItemPropertiesFromScriptValue(const ScriptValuePointer& object, MenuItemProperties& props); +ScriptValue menuItemPropertiesToScriptValue(ScriptEngine* engine, const MenuItemProperties& props); +void menuItemPropertiesFromScriptValue(const ScriptValue& object, MenuItemProperties& props); void registerMenuItemProperties(ScriptEngine* engine); diff --git a/libraries/script-engine/src/MouseEvent.cpp b/libraries/script-engine/src/MouseEvent.cpp index b6a3e17c42..c436cb6f35 100644 --- a/libraries/script-engine/src/MouseEvent.cpp +++ b/libraries/script-engine/src/MouseEvent.cpp @@ -86,22 +86,22 @@ MouseEvent::MouseEvent(const QMouseEvent& event) : * print(JSON.stringify(event)); * }); */ -ScriptValuePointer MouseEvent::toScriptValue(ScriptEngine* engine, const MouseEvent& event) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("x", event.x); - obj->setProperty("y", event.y); - obj->setProperty("button", event.button); - obj->setProperty("isLeftButton", event.isLeftButton); - obj->setProperty("isRightButton", event.isRightButton); - obj->setProperty("isMiddleButton", event.isMiddleButton); - obj->setProperty("isShifted", event.isShifted); - obj->setProperty("isMeta", event.isMeta); - obj->setProperty("isControl", event.isControl); - obj->setProperty("isAlt", event.isAlt); +ScriptValue MouseEvent::toScriptValue(ScriptEngine* engine, const MouseEvent& event) { + ScriptValue obj = engine->newObject(); + obj.setProperty("x", event.x); + obj.setProperty("y", event.y); + obj.setProperty("button", event.button); + obj.setProperty("isLeftButton", event.isLeftButton); + obj.setProperty("isRightButton", event.isRightButton); + obj.setProperty("isMiddleButton", event.isMiddleButton); + obj.setProperty("isShifted", event.isShifted); + obj.setProperty("isMeta", event.isMeta); + obj.setProperty("isControl", event.isControl); + obj.setProperty("isAlt", event.isAlt); return obj; } -void MouseEvent::fromScriptValue(const ScriptValuePointer& object, MouseEvent& event) { +void MouseEvent::fromScriptValue(const ScriptValue& object, MouseEvent& event) { // nothing for now... } diff --git a/libraries/script-engine/src/MouseEvent.h b/libraries/script-engine/src/MouseEvent.h index 52e364e25c..2abc8085c0 100644 --- a/libraries/script-engine/src/MouseEvent.h +++ b/libraries/script-engine/src/MouseEvent.h @@ -16,11 +16,10 @@ #define hifi_MouseEvent_h #include -#include + +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// Represents a mouse event to the scripting engine. Exposed as MouseEvent class MouseEvent { @@ -28,10 +27,10 @@ public: MouseEvent(); MouseEvent(const QMouseEvent& event); - static ScriptValuePointer toScriptValue(ScriptEngine* engine, const MouseEvent& event); - static void fromScriptValue(const ScriptValuePointer& object, MouseEvent& event); + static ScriptValue toScriptValue(ScriptEngine* engine, const MouseEvent& event); + static void fromScriptValue(const ScriptValue& object, MouseEvent& event); - ScriptValuePointer toScriptValue(ScriptEngine* engine) const { return MouseEvent::toScriptValue(engine, *this); } + ScriptValue toScriptValue(ScriptEngine* engine) const { return MouseEvent::toScriptValue(engine, *this); } int x; int y; diff --git a/libraries/script-engine/src/PointerEvent.cpp b/libraries/script-engine/src/PointerEvent.cpp index 487ac295c3..87cb95fa95 100644 --- a/libraries/script-engine/src/PointerEvent.cpp +++ b/libraries/script-engine/src/PointerEvent.cpp @@ -125,97 +125,97 @@ void PointerEvent::setButton(Button button) { * * @typedef {number} KeyboardModifiers */ -ScriptValuePointer PointerEvent::toScriptValue(ScriptEngine* engine, const PointerEvent& event) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue PointerEvent::toScriptValue(ScriptEngine* engine, const PointerEvent& event) { + ScriptValue obj = engine->newObject(); switch (event._type) { case Press: - obj->setProperty("type", "Press"); + obj.setProperty("type", "Press"); break; case DoublePress: - obj->setProperty("type", "DoublePress"); + obj.setProperty("type", "DoublePress"); break; case Release: - obj->setProperty("type", "Release"); + obj.setProperty("type", "Release"); break; default: case Move: - obj->setProperty("type", "Move"); + obj.setProperty("type", "Move"); break; }; - obj->setProperty("id", event._id); + obj.setProperty("id", event._id); - ScriptValuePointer pos2D = engine->newObject(); - pos2D->setProperty("x", event._pos2D.x); - pos2D->setProperty("y", event._pos2D.y); - obj->setProperty("pos2D", pos2D); + ScriptValue pos2D = engine->newObject(); + pos2D.setProperty("x", event._pos2D.x); + pos2D.setProperty("y", event._pos2D.y); + obj.setProperty("pos2D", pos2D); - ScriptValuePointer pos3D = engine->newObject(); - pos3D->setProperty("x", event._pos3D.x); - pos3D->setProperty("y", event._pos3D.y); - pos3D->setProperty("z", event._pos3D.z); - obj->setProperty("pos3D", pos3D); + ScriptValue pos3D = engine->newObject(); + pos3D.setProperty("x", event._pos3D.x); + pos3D.setProperty("y", event._pos3D.y); + pos3D.setProperty("z", event._pos3D.z); + obj.setProperty("pos3D", pos3D); - ScriptValuePointer normal = engine->newObject(); - normal->setProperty("x", event._normal.x); - normal->setProperty("y", event._normal.y); - normal->setProperty("z", event._normal.z); - obj->setProperty("normal", normal); + ScriptValue normal = engine->newObject(); + normal.setProperty("x", event._normal.x); + normal.setProperty("y", event._normal.y); + normal.setProperty("z", event._normal.z); + obj.setProperty("normal", normal); - ScriptValuePointer direction = engine->newObject(); - direction->setProperty("x", event._direction.x); - direction->setProperty("y", event._direction.y); - direction->setProperty("z", event._direction.z); - obj->setProperty("direction", direction); + ScriptValue direction = engine->newObject(); + direction.setProperty("x", event._direction.x); + direction.setProperty("y", event._direction.y); + direction.setProperty("z", event._direction.z); + obj.setProperty("direction", direction); bool isPrimaryButton = false; bool isSecondaryButton = false; bool isTertiaryButton = false; switch (event._button) { case NoButtons: - obj->setProperty("button", "None"); + obj.setProperty("button", "None"); break; case PrimaryButton: - obj->setProperty("button", "Primary"); + obj.setProperty("button", "Primary"); isPrimaryButton = true; break; case SecondaryButton: - obj->setProperty("button", "Secondary"); + obj.setProperty("button", "Secondary"); isSecondaryButton = true; break; case TertiaryButton: - obj->setProperty("button", "Tertiary"); + obj.setProperty("button", "Tertiary"); isTertiaryButton = true; break; } if (isPrimaryButton) { - obj->setProperty("isPrimaryButton", isPrimaryButton); - obj->setProperty("isLeftButton", isPrimaryButton); + obj.setProperty("isPrimaryButton", isPrimaryButton); + obj.setProperty("isLeftButton", isPrimaryButton); } if (isSecondaryButton) { - obj->setProperty("isSecondaryButton", isSecondaryButton); - obj->setProperty("isRightButton", isSecondaryButton); + obj.setProperty("isSecondaryButton", isSecondaryButton); + obj.setProperty("isRightButton", isSecondaryButton); } if (isTertiaryButton) { - obj->setProperty("isTertiaryButton", isTertiaryButton); - obj->setProperty("isMiddleButton", isTertiaryButton); + obj.setProperty("isTertiaryButton", isTertiaryButton); + obj.setProperty("isMiddleButton", isTertiaryButton); } - obj->setProperty("isPrimaryHeld", areFlagsSet(event._buttons, PrimaryButton)); - obj->setProperty("isSecondaryHeld", areFlagsSet(event._buttons, SecondaryButton)); - obj->setProperty("isTertiaryHeld", areFlagsSet(event._buttons, TertiaryButton)); + obj.setProperty("isPrimaryHeld", areFlagsSet(event._buttons, PrimaryButton)); + obj.setProperty("isSecondaryHeld", areFlagsSet(event._buttons, SecondaryButton)); + obj.setProperty("isTertiaryHeld", areFlagsSet(event._buttons, TertiaryButton)); - obj->setProperty("keyboardModifiers", engine->newValue(event.getKeyboardModifiers())); + obj.setProperty("keyboardModifiers", engine->newValue(event.getKeyboardModifiers())); return obj; } -void PointerEvent::fromScriptValue(const ScriptValuePointer& object, PointerEvent& event) { - if (object->isObject()) { - ScriptValuePointer type = object->property("type"); - QString typeStr = type->isString() ? type->toString() : "Move"; +void PointerEvent::fromScriptValue(const ScriptValue& object, PointerEvent& event) { + if (object.isObject()) { + ScriptValue type = object.property("type"); + QString typeStr = type.isString() ? type.toString() : "Move"; if (typeStr == "Press") { event._type = Press; } else if (typeStr == "DoublePress") { @@ -226,16 +226,16 @@ void PointerEvent::fromScriptValue(const ScriptValuePointer& object, PointerEven event._type = Move; } - ScriptValuePointer id = object->property("id"); - event._id = id->isNumber() ? (uint32_t)id->toNumber() : 0; + ScriptValue id = object.property("id"); + event._id = id.isNumber() ? (uint32_t)id.toNumber() : 0; - vec2FromScriptValue(object->property("pos2D"), event._pos2D); - vec3FromScriptValue(object->property("pos3D"), event._pos3D); - vec3FromScriptValue(object->property("normal"), event._normal); - vec3FromScriptValue(object->property("direction"), event._direction); + vec2FromScriptValue(object.property("pos2D"), event._pos2D); + vec3FromScriptValue(object.property("pos3D"), event._pos3D); + vec3FromScriptValue(object.property("normal"), event._normal); + vec3FromScriptValue(object.property("direction"), event._direction); - ScriptValuePointer button = object->property("button"); - QString buttonStr = type->isString() ? button->toString() : "NoButtons"; + ScriptValue button = object.property("button"); + QString buttonStr = type.isString() ? button.toString() : "NoButtons"; if (buttonStr == "Primary") { event._button = PrimaryButton; @@ -247,9 +247,9 @@ void PointerEvent::fromScriptValue(const ScriptValuePointer& object, PointerEven event._button = NoButtons; } - bool primary = object->property("isPrimaryHeld")->toBool(); - bool secondary = object->property("isSecondaryHeld")->toBool(); - bool tertiary = object->property("isTertiaryHeld")->toBool(); + bool primary = object.property("isPrimaryHeld").toBool(); + bool secondary = object.property("isSecondaryHeld").toBool(); + bool tertiary = object.property("isTertiaryHeld").toBool(); event._buttons = 0; if (primary) { event._buttons |= PrimaryButton; @@ -261,7 +261,7 @@ void PointerEvent::fromScriptValue(const ScriptValuePointer& object, PointerEven event._buttons |= TertiaryButton; } - event._keyboardModifiers = (Qt::KeyboardModifiers)(object->property("keyboardModifiers")->toUInt32()); + event._keyboardModifiers = (Qt::KeyboardModifiers)(object.property("keyboardModifiers").toUInt32()); } } diff --git a/libraries/script-engine/src/PointerEvent.h b/libraries/script-engine/src/PointerEvent.h index 3fd83ce510..fb4617ba6e 100644 --- a/libraries/script-engine/src/PointerEvent.h +++ b/libraries/script-engine/src/PointerEvent.h @@ -19,11 +19,10 @@ #include #include -#include + +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// Represents a 2D or 3D pointer to the scripting engine. Exposed as PointerEvent class PointerEvent { @@ -52,10 +51,10 @@ public: const glm::vec3& normal, const glm::vec3& direction, Button button = NoButtons, uint32_t buttons = NoButtons, Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier); - static ScriptValuePointer toScriptValue(ScriptEngine* engine, const PointerEvent& event); - static void fromScriptValue(const ScriptValuePointer& object, PointerEvent& event); + static ScriptValue toScriptValue(ScriptEngine* engine, const PointerEvent& event); + static void fromScriptValue(const ScriptValue& object, PointerEvent& event); - ScriptValuePointer toScriptValue(ScriptEngine* engine) const { return PointerEvent::toScriptValue(engine, *this); } + ScriptValue toScriptValue(ScriptEngine* engine) const { return PointerEvent::toScriptValue(engine, *this); } EventType getType() const { return _type; } uint32_t getID() const { return _id; } diff --git a/libraries/script-engine/src/ScriptContext.h b/libraries/script-engine/src/ScriptContext.h index bb1f70da63..733d0b88f1 100644 --- a/libraries/script-engine/src/ScriptContext.h +++ b/libraries/script-engine/src/ScriptContext.h @@ -19,14 +19,14 @@ #include #include +#include "ScriptValue.h" + class ScriptContext; class ScriptEngine; class ScriptFunctionContext; -class ScriptValue; using ScriptContextPointer = QSharedPointer; using ScriptFunctionContextPointer = QSharedPointer; using ScriptEnginePointer = QSharedPointer; -using ScriptValuePointer = QSharedPointer; /// [ScriptInterface] Provides an engine-independent interface for QScriptContextInfo class ScriptFunctionContext { @@ -49,15 +49,15 @@ public: class ScriptContext { public: virtual int argumentCount() const = 0; - virtual ScriptValuePointer argument(int index) const = 0; + virtual ScriptValue argument(int index) const = 0; virtual QStringList backtrace() const = 0; - virtual ScriptValuePointer callee() const = 0; + virtual ScriptValue callee() const = 0; virtual ScriptEnginePointer engine() const = 0; virtual ScriptFunctionContextPointer functionContext() const = 0; virtual ScriptContextPointer parentContext() const = 0; - virtual ScriptValuePointer thisObject() const = 0; - virtual ScriptValuePointer throwError(const QString& text) = 0; - virtual ScriptValuePointer throwValue(const ScriptValuePointer& value) = 0; + virtual ScriptValue thisObject() const = 0; + virtual ScriptValue throwError(const QString& text) = 0; + virtual ScriptValue throwValue(const ScriptValue& value) = 0; }; #endif // hifi_ScriptContext_h diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 3a243da60f..fa791709d4 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -20,36 +20,36 @@ ScriptEnginePointer newScriptEngine(ScriptManager* manager) { return QSharedPointer(new ScriptEngineQtScript(manager)); } -ScriptValuePointer makeScopedHandlerObject(ScriptValuePointer scopeOrCallback, ScriptValuePointer methodOrName) { - auto engine = scopeOrCallback->engine(); +ScriptValue makeScopedHandlerObject(const ScriptValue& scopeOrCallback, const ScriptValue& methodOrName) { + auto engine = scopeOrCallback.engine(); if (!engine) { return scopeOrCallback; } - ScriptValuePointer scope; - ScriptValuePointer callback = scopeOrCallback; - if (scopeOrCallback->isObject()) { - if (methodOrName->isString()) { + ScriptValue scope; + ScriptValue callback = scopeOrCallback; + if (scopeOrCallback.isObject()) { + if (methodOrName.isString()) { scope = scopeOrCallback; - callback = scope->property(methodOrName->toString()); - } else if (methodOrName->isFunction()) { + callback = scope.property(methodOrName.toString()); + } else if (methodOrName.isFunction()) { scope = scopeOrCallback; callback = methodOrName; - } else if (!methodOrName->isValid()) { + } else if (!methodOrName.isValid()) { // instantiate from an existing scoped handler object - if (scopeOrCallback->property("callback")->isFunction()) { - scope = scopeOrCallback->property("scope"); - callback = scopeOrCallback->property("callback"); + if (scopeOrCallback.property("callback").isFunction()) { + scope = scopeOrCallback.property("scope"); + callback = scopeOrCallback.property("callback"); } } } auto handler = engine->newObject(); - handler->setProperty("scope", scope); - handler->setProperty("callback", callback); + handler.setProperty("scope", scope); + handler.setProperty("callback", callback); return handler; } -ScriptValuePointer callScopedHandlerObject(ScriptValuePointer handler, ScriptValuePointer err, ScriptValuePointer result) { - return handler->property("callback")->call(handler->property("scope"), ScriptValueList({ err, result })); +ScriptValue callScopedHandlerObject(const ScriptValue& handler, const ScriptValue& err, const ScriptValue& result) { + return handler.property("callback").call(handler.property("scope"), ScriptValueList({ err, result })); } bool ScriptEngine::IS_THREADSAFE_INVOCATION(const QString& method) { diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index 34b1846d7e..b1fb6d4cd5 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -20,6 +20,8 @@ #include #include +#include "ScriptValue.h" + class QByteArray; class QLatin1String; class QString; @@ -29,19 +31,17 @@ class ScriptContext; class ScriptEngine; class ScriptManager; class ScriptProgram; -class ScriptValue; using ScriptEnginePointer = QSharedPointer; using ScriptProgramPointer = QSharedPointer; -using ScriptValuePointer = QSharedPointer; Q_DECLARE_METATYPE(ScriptEnginePointer); /// [ScriptInterface] Provides an engine-independent interface for QScriptEngine class ScriptEngine { public: - typedef ScriptValuePointer (*FunctionSignature)(ScriptContext*, ScriptEngine*); - typedef ScriptValuePointer (*MarshalFunction)(ScriptEngine*, const void*); - typedef void (*DemarshalFunction)(const ScriptValuePointer&, void*); + typedef ScriptValue (*FunctionSignature)(ScriptContext*, ScriptEngine*); + typedef ScriptValue (*MarshalFunction)(ScriptEngine*, const void*); + typedef void (*DemarshalFunction)(const ScriptValue&, void*); enum ValueOwnership { QtOwnership = 0, @@ -65,47 +65,47 @@ public: public: virtual void abortEvaluation() = 0; virtual void clearExceptions() = 0; - virtual ScriptValuePointer cloneUncaughtException(const QString& detail = QString()) = 0; + virtual ScriptValue cloneUncaughtException(const QString& detail = QString()) = 0; virtual ScriptContext* currentContext() const = 0; - virtual ScriptValuePointer evaluate(const QString& program, const QString& fileName = QString()) = 0; - virtual ScriptValuePointer evaluate(const ScriptProgramPointer &program) = 0; - virtual ScriptValuePointer evaluateInClosure(const ScriptValuePointer& locals, const ScriptProgramPointer& program) = 0; - virtual ScriptValuePointer globalObject() const = 0; + virtual ScriptValue evaluate(const QString& program, const QString& fileName = QString()) = 0; + virtual ScriptValue evaluate(const ScriptProgramPointer &program) = 0; + virtual ScriptValue evaluateInClosure(const ScriptValue& locals, const ScriptProgramPointer& program) = 0; + virtual ScriptValue globalObject() const = 0; virtual bool hasUncaughtException() const = 0; virtual bool isEvaluating() const = 0; - virtual ScriptValuePointer lintScript(const QString& sourceCode, const QString& fileName, const int lineNumber = 1) = 0; - virtual ScriptValuePointer makeError(const ScriptValuePointer& other = ScriptValuePointer(), const QString& type = "Error") = 0; + virtual ScriptValue lintScript(const QString& sourceCode, const QString& fileName, const int lineNumber = 1) = 0; + virtual ScriptValue makeError(const ScriptValue& other = ScriptValue(), const QString& type = "Error") = 0; virtual ScriptManager* manager() const = 0; virtual bool maybeEmitUncaughtException(const QString& debugHint = QString()) = 0; - virtual ScriptValuePointer newArray(uint length = 0) = 0; - virtual ScriptValuePointer newArrayBuffer(const QByteArray& message) = 0; - virtual ScriptValuePointer newFunction(FunctionSignature fun, int length = 0) = 0; - virtual ScriptValuePointer newObject() = 0; + virtual ScriptValue newArray(uint length = 0) = 0; + virtual ScriptValue newArrayBuffer(const QByteArray& message) = 0; + virtual ScriptValue newFunction(FunctionSignature fun, int length = 0) = 0; + virtual ScriptValue newObject() = 0; virtual ScriptProgramPointer newProgram(const QString& sourceCode, const QString& fileName) = 0; - virtual ScriptValuePointer newQObject(QObject *object, ValueOwnership ownership = QtOwnership, const QObjectWrapOptions &options = QObjectWrapOptions()) = 0; - virtual ScriptValuePointer newValue(bool value) = 0; - virtual ScriptValuePointer newValue(int value) = 0; - virtual ScriptValuePointer newValue(uint value) = 0; - virtual ScriptValuePointer newValue(double value) = 0; - virtual ScriptValuePointer newValue(const QString& value) = 0; - virtual ScriptValuePointer newValue(const QLatin1String& value) = 0; - virtual ScriptValuePointer newValue(const char* value) = 0; - virtual ScriptValuePointer newVariant(const QVariant& value) = 0; - virtual ScriptValuePointer nullValue() = 0; - virtual bool raiseException(const ScriptValuePointer& exception) = 0; + virtual ScriptValue newQObject(QObject *object, ValueOwnership ownership = QtOwnership, const QObjectWrapOptions &options = QObjectWrapOptions()) = 0; + virtual ScriptValue newValue(bool value) = 0; + virtual ScriptValue newValue(int value) = 0; + virtual ScriptValue newValue(uint value) = 0; + virtual ScriptValue newValue(double value) = 0; + virtual ScriptValue newValue(const QString& value) = 0; + virtual ScriptValue newValue(const QLatin1String& value) = 0; + virtual ScriptValue newValue(const char* value) = 0; + virtual ScriptValue newVariant(const QVariant& value) = 0; + virtual ScriptValue nullValue() = 0; + virtual bool raiseException(const ScriptValue& exception) = 0; virtual void registerEnum(const QString& enumName, QMetaEnum newEnum) = 0; virtual void registerFunction(const QString& name, FunctionSignature fun, int numArguments = -1) = 0; virtual void registerFunction(const QString& parent, const QString& name, FunctionSignature fun, int numArguments = -1) = 0; virtual void registerGetterSetter(const QString& name, FunctionSignature getter, FunctionSignature setter, const QString& parent = QString("")) = 0; virtual void registerGlobalObject(const QString& name, QObject* object) = 0; - virtual void setDefaultPrototype(int metaTypeId, const ScriptValuePointer& prototype) = 0; + virtual void setDefaultPrototype(int metaTypeId, const ScriptValue& prototype) = 0; virtual void setObjectName(const QString& name) = 0; virtual bool setProperty(const char* name, const QVariant& value) = 0; virtual void setProcessEventsInterval(int interval) = 0; virtual QThread* thread() const = 0; virtual void setThread(QThread* thread) = 0; - virtual ScriptValuePointer undefinedValue() = 0; - virtual ScriptValuePointer uncaughtException() const = 0; + virtual ScriptValue undefinedValue() = 0; + virtual ScriptValue uncaughtException() const = 0; virtual QStringList uncaughtExceptionBacktrace() const = 0; virtual int uncaughtExceptionLineNumber() const = 0; virtual void updateMemoryCost(const qint64& deltaSize) = 0; @@ -116,19 +116,19 @@ public: public: template - inline T fromScriptValue(const ScriptValuePointer& value) { + inline T fromScriptValue(const ScriptValue& value) { return scriptvalue_cast(value); } template - inline ScriptValuePointer toScriptValue(const T& value) { + inline ScriptValue toScriptValue(const T& value) { return scriptValueFromValue(this, value); } public: // not for public use, but I don't like how Qt strings this along with private friend functions - virtual ScriptValuePointer create(int type, const void* ptr) = 0; - virtual bool convert(const ScriptValuePointer& value, int type, void* ptr) = 0; - virtual void registerCustomType(int type, MarshalFunction mf, DemarshalFunction df, const ScriptValuePointer& prototype) = 0; + virtual ScriptValue create(int type, const void* ptr) = 0; + virtual bool convert(const ScriptValue& value, int type, void* ptr) = 0; + virtual void registerCustomType(int type, MarshalFunction mf, DemarshalFunction df, const ScriptValue& prototype) = 0; }; Q_DECLARE_OPERATORS_FOR_FLAGS(ScriptEngine::QObjectWrapOptions); @@ -143,8 +143,8 @@ ScriptEnginePointer newScriptEngine(ScriptManager* manager = nullptr); // auto handler = makeScopedHandlerObject(scopeOrCallback, optionalMethodOrName); // And then invoke the scoped handler later per CPS conventions: // auto result = callScopedHandlerObject(handler, err, result); -ScriptValuePointer makeScopedHandlerObject(ScriptValuePointer scopeOrCallback, ScriptValuePointer methodOrName); -ScriptValuePointer callScopedHandlerObject(ScriptValuePointer handler, ScriptValuePointer err, ScriptValuePointer result); +ScriptValue makeScopedHandlerObject(const ScriptValue& scopeOrCallback, const ScriptValue& methodOrName); +ScriptValue callScopedHandlerObject(const ScriptValue& handler, const ScriptValue& err, const ScriptValue& result); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Inline implementations diff --git a/libraries/script-engine/src/ScriptEngineCast.h b/libraries/script-engine/src/ScriptEngineCast.h index d597efc780..b378302fe2 100644 --- a/libraries/script-engine/src/ScriptEngineCast.h +++ b/libraries/script-engine/src/ScriptEngineCast.h @@ -23,48 +23,48 @@ #include "ScriptValue.h" template -inline ScriptValuePointer scriptValueFromValue(ScriptEngine* engine, const T& t) { +inline ScriptValue scriptValueFromValue(ScriptEngine* engine, const T& t) { if (!engine) { - return ScriptValuePointer(); + return ScriptValue(); } return engine->create(qMetaTypeId(), &t); } template <> -inline ScriptValuePointer scriptValueFromValue(ScriptEngine* engine, const QVariant& v) { +inline ScriptValue scriptValueFromValue(ScriptEngine* engine, const QVariant& v) { if (!engine) { - return ScriptValuePointer(); + return ScriptValue(); } return engine->create(v.userType(), v.data()); } template -T scriptvalue_cast(const ScriptValuePointer& value) { +T scriptvalue_cast(const ScriptValue& value) { T t; const int id = qMetaTypeId(); - auto engine = value->engine(); + auto engine = value.engine(); if (engine && engine->convert(value, id, &t)) { return t; - } else if (value->isVariant()) { - return qvariant_cast(value->toVariant()); + } else if (value.isVariant()) { + return qvariant_cast(value.toVariant()); } return T(); } template <> -inline QVariant scriptvalue_cast(const ScriptValuePointer& value) { - return value->toVariant(); +inline QVariant scriptvalue_cast(const ScriptValue& value) { + return value.toVariant(); } template int scriptRegisterMetaType(ScriptEngine* eng, - ScriptValuePointer (*toScriptValue)(ScriptEngine*, const T& t), - void (*fromScriptValue)(const ScriptValuePointer&, T& t), - const ScriptValuePointer& prototype = ScriptValuePointer(), + ScriptValue (*toScriptValue)(ScriptEngine*, const T& t), + void (*fromScriptValue)(const ScriptValue&, T& t), + const ScriptValue& prototype = ScriptValue(), T* = 0) { const int id = qRegisterMetaType(); // make sure it's registered @@ -74,30 +74,30 @@ int scriptRegisterMetaType(ScriptEngine* eng, } template -ScriptValuePointer scriptValueFromSequence(ScriptEngine* eng, const Container& cont) { - ScriptValuePointer a = eng->newArray(); +ScriptValue scriptValueFromSequence(ScriptEngine* eng, const Container& cont) { + ScriptValue a = eng->newArray(); typename Container::const_iterator begin = cont.begin(); typename Container::const_iterator end = cont.end(); typename Container::const_iterator it; quint32 i; for (it = begin, i = 0; it != end; ++it, ++i) { - a->setProperty(i, eng->toScriptValue(*it)); + a.setProperty(i, eng->toScriptValue(*it)); } return a; } template -void scriptValueToSequence(const ScriptValuePointer& value, Container& cont) { - quint32 len = value->property(QLatin1String("length"))->toUInt32(); +void scriptValueToSequence(const ScriptValue& value, Container& cont) { + quint32 len = value.property(QLatin1String("length")).toUInt32(); for (quint32 i = 0; i < len; ++i) { - ScriptValuePointer item = value->property(i); + ScriptValue item = value.property(i); cont.push_back(scriptvalue_cast(item)); } } template int scriptRegisterSequenceMetaType(ScriptEngine* engine, - const ScriptValuePointer& prototype = ScriptValuePointer(), + const ScriptValue& prototype = ScriptValue(), T* = 0) { return scriptRegisterMetaType(engine, scriptValueFromSequence, scriptValueToSequence, prototype); } diff --git a/libraries/script-engine/src/ScriptManager.cpp b/libraries/script-engine/src/ScriptManager.cpp index 7ebd41ec9d..96bbd80999 100644 --- a/libraries/script-engine/src/ScriptManager.cpp +++ b/libraries/script-engine/src/ScriptManager.cpp @@ -87,7 +87,7 @@ int scriptManagerPointerMetaID = qRegisterMetaType(); Q_DECLARE_METATYPE(ExternalResource::Bucket); -Q_DECLARE_METATYPE(ScriptValuePointer); +Q_DECLARE_METATYPE(ScriptValue); // --- Static script initialization registry @@ -109,21 +109,21 @@ static void runStaticInitializers(ScriptManager* manager) { // --- -static ScriptValuePointer debugPrint(ScriptContext* context, ScriptEngine* engine) { +static ScriptValue debugPrint(ScriptContext* context, ScriptEngine* engine) { // assemble the message by concatenating our arguments QString message = ""; for (int i = 0; i < context->argumentCount(); i++) { if (i > 0) { message += " "; } - message += context->argument(i)->toString(); + message += context->argument(i).toString(); } // was this generated by a script engine? If we don't recognize it then send the message and exit ScriptManager* scriptManager = engine->manager(); if (!scriptManager) { qCDebug(scriptengine_script, "%s", qUtf8Printable(message)); - return ScriptValuePointer(); + return ScriptValue(); } // This message was sent by one of our script engines, let's try to see if we can find the source. @@ -170,7 +170,7 @@ static ScriptValuePointer debugPrint(ScriptContext* context, ScriptEngine* engin qCDebug(scriptengine_script, "[%s] %s", qUtf8Printable(scriptManager->getFilename()), qUtf8Printable(message)); } - return ScriptValuePointer(); + return ScriptValue(); } // FIXME Come up with a way to properly encode entity IDs in filename @@ -193,7 +193,7 @@ QString encodeEntityIdIntoEntityUrl(const QString& url, const QString& entityID) return url + " [EntityID:" + entityID + "]"; } -QString ScriptManager::logException(const ScriptValuePointer& exception) { +QString ScriptManager::logException(const ScriptValue& exception) { auto message = formatException(exception, _enableExtendedJSExceptions.get()); scriptErrorMessage(message); return message; @@ -249,10 +249,10 @@ ScriptManager::ScriptManager(Context context, const QString& scriptContents, con } // this is where all unhandled exceptions end up getting logged - connect(this, &ScriptManager::unhandledException, this, [this](const ScriptValuePointer& err) { - auto output = err->engine() == _engine ? err : _engine->makeError(err); - if (!output->property("detail")->isValid()) { - output->setProperty("detail", "UnhandledException"); + connect(this, &ScriptManager::unhandledException, this, [this](const ScriptValue& err) { + auto output = err.engine() == _engine ? err : _engine->makeError(err); + if (!output.property("detail").isValid()) { + output.setProperty("detail", "UnhandledException"); } logException(output); }); @@ -516,10 +516,10 @@ void ScriptManager::clearDebugLogWindow() { // Templated qScriptRegisterMetaType fails to compile with raw pointers using ScriptableResourceRawPtr = ScriptableResource*; -static ScriptValuePointer scriptableResourceToScriptValue(ScriptEngine* engine, +static ScriptValue scriptableResourceToScriptValue(ScriptEngine* engine, const ScriptableResourceRawPtr& resource) { if (!resource) { - return ScriptValuePointer(); // probably shutting down + return ScriptValue(); // probably shutting down } // The first script to encounter this resource will track its memory. @@ -538,8 +538,8 @@ static ScriptValuePointer scriptableResourceToScriptValue(ScriptEngine* engine, return object; } -static void scriptableResourceFromScriptValue(const ScriptValuePointer& value, ScriptableResourceRawPtr& resource) { - resource = static_cast(value->toQObject()); +static void scriptableResourceFromScriptValue(const ScriptValue& value, ScriptableResourceRawPtr& resource) { + resource = static_cast(value.toQObject()); } /*@jsdoc @@ -555,7 +555,7 @@ static void scriptableResourceFromScriptValue(const ScriptValuePointer& value, S * * @property {Resource.State} State - The possible loading states of a resource. Read-only. */ -static ScriptValuePointer createScriptableResourcePrototype(ScriptManagerPointer manager) { +static ScriptValue createScriptableResourcePrototype(ScriptManagerPointer manager) { auto engine = manager->engine(); auto prototype = engine->newObject(); @@ -569,17 +569,17 @@ static ScriptValuePointer createScriptableResourcePrototype(ScriptManagerPointer auto prototypeState = engine->newQObject(state, ScriptEngine::QtOwnership, ScriptEngine::ExcludeSlots | ScriptEngine::ExcludeSuperClassMethods); - prototype->setProperty("State", prototypeState); + prototype.setProperty("State", prototypeState); return prototype; } -ScriptValuePointer externalResourceBucketToScriptValue(ScriptEngine* engine, ExternalResource::Bucket const& in) { +ScriptValue externalResourceBucketToScriptValue(ScriptEngine* engine, ExternalResource::Bucket const& in) { return engine->newValue((int)in); } -void externalResourceBucketFromScriptValue(const ScriptValuePointer& object, ExternalResource::Bucket& out) { - out = static_cast(object->toInt32()); +void externalResourceBucketFromScriptValue(const ScriptValue& object, ExternalResource::Bucket& out) { + out = static_cast(object.toInt32()); } void ScriptManager::resetModuleCache(bool deleteScriptCache) { @@ -587,33 +587,33 @@ void ScriptManager::resetModuleCache(bool deleteScriptCache) { executeOnScriptThread([=]() { resetModuleCache(deleteScriptCache); }); return; } - auto jsRequire = _engine->globalObject()->property("Script")->property("require"); - auto cache = jsRequire->property("cache"); - auto cacheMeta = jsRequire->data(); + auto jsRequire = _engine->globalObject().property("Script").property("require"); + auto cache = jsRequire.property("cache"); + auto cacheMeta = jsRequire.data(); if (deleteScriptCache) { - auto it = cache->newIterator(); + auto it = cache.newIterator(); while (it->hasNext()) { it->next(); if (it->flags() & ScriptValue::SkipInEnumeration) { continue; } qCDebug(scriptengine) << "resetModuleCache(true) -- staging " << it->name() << " for cache reset at next require"; - cacheMeta->setProperty(it->name(), true); + cacheMeta.setProperty(it->name(), true); } } cache = _engine->newObject(); - if (!cacheMeta->isObject()) { + if (!cacheMeta.isObject()) { cacheMeta = _engine->newObject(); - cacheMeta->setProperty("id", "Script.require.cacheMeta"); - cacheMeta->setProperty("type", "cacheMeta"); - jsRequire->setData(cacheMeta); + cacheMeta.setProperty("id", "Script.require.cacheMeta"); + cacheMeta.setProperty("type", "cacheMeta"); + jsRequire.setData(cacheMeta); } - cache->setProperty("__created__", (double)QDateTime::currentMSecsSinceEpoch(), ScriptValue::SkipInEnumeration); + cache.setProperty("__created__", (double)QDateTime::currentMSecsSinceEpoch(), ScriptValue::SkipInEnumeration); #if DEBUG_JS_MODULES cache.setProperty("__meta__", cacheMeta, READONLY_HIDDEN_PROP_FLAGS); #endif - jsRequire->setProperty("cache", cache, READONLY_PROP_FLAGS); + jsRequire.setProperty("cache", cache, READONLY_PROP_FLAGS); } void ScriptManager::init() { @@ -638,11 +638,11 @@ void ScriptManager::init() { scriptRegisterSequenceMetaType>(scriptEngine); scriptRegisterSequenceMetaType>(scriptEngine); - ScriptValuePointer xmlHttpRequestConstructorValue = scriptEngine->newFunction(XMLHttpRequestClass::constructor); - scriptEngine->globalObject()->setProperty("XMLHttpRequest", xmlHttpRequestConstructorValue); + ScriptValue xmlHttpRequestConstructorValue = scriptEngine->newFunction(XMLHttpRequestClass::constructor); + scriptEngine->globalObject().setProperty("XMLHttpRequest", xmlHttpRequestConstructorValue); - ScriptValuePointer webSocketConstructorValue = scriptEngine->newFunction(WebSocketClass::constructor); - scriptEngine->globalObject()->setProperty("WebSocket", webSocketConstructorValue); + ScriptValue webSocketConstructorValue = scriptEngine->newFunction(WebSocketClass::constructor); + scriptEngine->globalObject().setProperty("WebSocket", webSocketConstructorValue); /*@jsdoc * Prints a message to the program log and emits {@link Script.printedMessage}. @@ -651,7 +651,7 @@ void ScriptManager::init() { * @function print * @param {...*} [message] - The message values to print. */ - scriptEngine->globalObject()->setProperty("print", scriptEngine->newFunction(debugPrint)); + scriptEngine->globalObject().setProperty("print", scriptEngine->newFunction(debugPrint)); scriptRegisterMetaType(scriptEngine, animationDetailsToScriptValue, animationDetailsFromScriptValue); scriptRegisterMetaType(scriptEngine, webSocketToScriptValue, webSocketFromScriptValue); @@ -665,10 +665,10 @@ void ScriptManager::init() { { // set up Script.require.resolve and Script.require.cache - auto Script = scriptEngine->globalObject()->property("Script"); - auto require = Script->property("require"); - auto resolve = Script->property("_requireResolve"); - require->setProperty("resolve", resolve, READONLY_PROP_FLAGS); + auto Script = scriptEngine->globalObject().property("Script"); + auto require = Script.property("require"); + auto resolve = Script.property("_requireResolve"); + require.setProperty("resolve", resolve, READONLY_PROP_FLAGS); resetModuleCache(); } @@ -697,12 +697,12 @@ void ScriptManager::init() { // Scriptable cache access auto resourcePrototype = createScriptableResourcePrototype(qSharedPointerCast(sharedFromThis())); - scriptEngine->globalObject()->setProperty("Resource", resourcePrototype); + scriptEngine->globalObject().setProperty("Resource", resourcePrototype); scriptEngine->setDefaultPrototype(qMetaTypeId(), resourcePrototype); scriptRegisterMetaType(scriptEngine, scriptableResourceToScriptValue, scriptableResourceFromScriptValue); // constants - scriptEngine->globalObject()->setProperty("TREE_SCALE", scriptEngine->newValue(TREE_SCALE)); + scriptEngine->globalObject().setProperty("TREE_SCALE", scriptEngine->newValue(TREE_SCALE)); scriptEngine->registerGlobalObject("Assets", _assetScriptingInterface); scriptEngine->registerGlobalObject("Resources", DependencyManager::get().data()); @@ -718,14 +718,14 @@ void ScriptManager::init() { scriptEngine->registerGlobalObject("StackTest", new StackTestScriptingInterface(this)); #endif - scriptEngine->globalObject()->setProperty("KALILA", "isWaifu"); - scriptEngine->globalObject()->setProperty("Kute", scriptEngine->newFunction([](ScriptContext* context, ScriptEngine* engine) -> ScriptValuePointer { - return context->engine()->newValue(context->argument(0)->toString().toLower() == "kalila" ? true : false); + scriptEngine->globalObject().setProperty("KALILA", "isWaifu"); + scriptEngine->globalObject().setProperty("Kute", scriptEngine->newFunction([](ScriptContext* context, ScriptEngine* engine) -> ScriptValue { + return context->engine()->newValue(context->argument(0).toString().toLower() == "kalila" ? true : false); })); } // Unregister the handlers for this eventName and entityID. -void ScriptManager::removeEventHandler(const EntityItemID& entityID, const QString& eventName, ScriptValuePointer handler) { +void ScriptManager::removeEventHandler(const EntityItemID& entityID, const QString& eventName, const ScriptValue& handler) { if (QThread::currentThread() != thread()) { #ifdef THREAD_DEBUGGING qCDebug(scriptengine) << "*** WARNING *** ScriptManager::removeEventHandler() called on wrong thread [" << QThread::currentThread() << "], invoking on correct thread [" << thread() << "] " @@ -734,7 +734,7 @@ void ScriptManager::removeEventHandler(const EntityItemID& entityID, const QStri QMetaObject::invokeMethod(this, "removeEventHandler", Q_ARG(const EntityItemID&, entityID), Q_ARG(const QString&, eventName), - Q_ARG(ScriptValuePointer, handler)); + Q_ARG(const ScriptValue&, handler)); return; } #ifdef THREAD_DEBUGGING @@ -746,9 +746,9 @@ void ScriptManager::removeEventHandler(const EntityItemID& entityID, const QStri } RegisteredEventHandlers& handlersOnEntity = _registeredHandlers[entityID]; CallbackList& handlersForEvent = handlersOnEntity[eventName]; - // ScriptValuePointer does not have operator==(), so we can't use QList::removeOne and friends. So iterate. + // ScriptValue does not have operator==(), so we can't use QList::removeOne and friends. So iterate. for (int i = 0; i < handlersForEvent.count(); ++i) { - if (handlersForEvent[i].function->equals(handler)) { + if (handlersForEvent[i].function.equals(handler)) { handlersForEvent.removeAt(i); return; // Design choice: since comparison is relatively expensive, just remove the first matching handler. } @@ -771,7 +771,7 @@ void ScriptManager::removeAllEventHandlers(const EntityItemID& entityID) { } // Register the handler. -void ScriptManager::addEventHandler(const EntityItemID& entityID, const QString& eventName, ScriptValuePointer handler) { +void ScriptManager::addEventHandler(const EntityItemID& entityID, const QString& eventName, const ScriptValue& handler) { if (QThread::currentThread() != thread()) { #ifdef THREAD_DEBUGGING qCDebug(scriptengine) << "*** WARNING *** ScriptManager::addEventHandler() called on wrong thread [" << QThread::currentThread() << "], invoking on correct thread [" << thread() << "] " @@ -781,7 +781,7 @@ void ScriptManager::addEventHandler(const EntityItemID& entityID, const QString& QMetaObject::invokeMethod(this, "addEventHandler", Q_ARG(const EntityItemID&, entityID), Q_ARG(const QString&, eventName), - Q_ARG(ScriptValuePointer, handler)); + Q_ARG(const ScriptValue&, handler)); return; } #ifdef THREAD_DEBUGGING @@ -951,7 +951,7 @@ void ScriptManager::run() { // only clear exceptions if we are not in the middle of evaluating if (!_engine->isEvaluating() && _engine->hasUncaughtException()) { qCWarning(scriptengine) << __FUNCTION__ << "---------- UNCAUGHT EXCEPTION --------"; - qCWarning(scriptengine) << "runInThread" << _engine->uncaughtException()->toString(); + qCWarning(scriptengine) << "runInThread" << _engine->uncaughtException().toString(); emit unhandledException(_engine->cloneUncaughtException(__FUNCTION__)); _engine->clearExceptions(); } @@ -1037,7 +1037,7 @@ void ScriptManager::timerFired() { } // call the associated JS function, if it exists - if (timerData.function->isValid()) { + if (timerData.function.isValid()) { PROFILE_RANGE(script, __FUNCTION__); auto preTimer = p_high_resolution_clock::now(); callWithEnvironment(timerData.definingEntityIdentifier, timerData.definingSandboxURL, timerData.function, timerData.function, ScriptValueList()); @@ -1045,11 +1045,11 @@ void ScriptManager::timerFired() { auto elapsed = (postTimer - preTimer); _totalTimerExecution += std::chrono::duration_cast(elapsed); } else { - qCWarning(scriptengine) << "timerFired -- invalid function" << timerData.function->toVariant().toString(); + qCWarning(scriptengine) << "timerFired -- invalid function" << timerData.function.toVariant().toString(); } } -QObject* ScriptManager::setupTimerWithInterval(const ScriptValuePointer& function, int intervalMS, bool isSingleShot) { +QObject* ScriptManager::setupTimerWithInterval(const ScriptValue& function, int intervalMS, bool isSingleShot) { // create the timer, add it to the map, and start it QTimer* newTimer = new QTimer(this); newTimer->setSingleShot(isSingleShot); @@ -1073,7 +1073,7 @@ QObject* ScriptManager::setupTimerWithInterval(const ScriptValuePointer& functio return newTimer; } -QObject* ScriptManager::setInterval(const ScriptValuePointer& function, int intervalMS) { +QObject* ScriptManager::setInterval(const ScriptValue& function, int intervalMS) { if (isStopped()) { scriptWarningMessage("Script.setInterval() while shutting down is ignored... parent script:" + getFilename()); return NULL; // bail early @@ -1082,7 +1082,7 @@ QObject* ScriptManager::setInterval(const ScriptValuePointer& function, int inte return setupTimerWithInterval(function, intervalMS, false); } -QObject* ScriptManager::setTimeout(const ScriptValuePointer& function, int timeoutMS) { +QObject* ScriptManager::setTimeout(const ScriptValue& function, int timeoutMS) { if (isStopped()) { scriptWarningMessage("Script.setTimeout() while shutting down is ignored... parent script:" + getFilename()); return NULL; // bail early @@ -1174,7 +1174,7 @@ QString ScriptManager::_requireResolve(const QString& moduleId, const QString& r } auto message = QString("Cannot find module '%1' (%2)").arg(displayId); - auto throwResolveError = [&](const ScriptValuePointer& error) -> QString { + auto throwResolveError = [&](const ScriptValue& error) -> QString { _engine->raiseException(error); _engine->maybeEmitUncaughtException("require.resolve"); return QString(); @@ -1253,73 +1253,73 @@ QString ScriptManager::_requireResolve(const QString& moduleId, const QString& r } // retrieves the current parent module from the JS scope chain -ScriptValuePointer ScriptManager::currentModule() { +ScriptValue ScriptManager::currentModule() { if (!_engine->IS_THREADSAFE_INVOCATION(__FUNCTION__)) { return _engine->nullValue(); } - auto jsRequire = _engine->globalObject()->property("Script")->property("require"); - auto cache = jsRequire->property("cache"); - ScriptValuePointer candidate; + auto jsRequire = _engine->globalObject().property("Script").property("require"); + auto cache = jsRequire.property("cache"); + ScriptValue candidate; ScriptContextPointer parentContext; // using this variable to maintain parent variable lifespan - for (auto context = _engine->currentContext(); context && (!candidate || !candidate->isObject()); parentContext = context->parentContext(), context = parentContext.data()) { + for (auto context = _engine->currentContext(); context && !candidate.isObject(); parentContext = context->parentContext(), context = parentContext.data()) { auto contextInfo = context->functionContext(); - candidate = cache->property(contextInfo->fileName()); + candidate = cache.property(contextInfo->fileName()); } - if (!candidate || !candidate->isObject()) { - return ScriptValuePointer(); + if (!candidate.isObject()) { + return ScriptValue(); } return candidate; } // replaces or adds "module" to "parent.children[]" array // (for consistency with Node.js and userscript cache invalidation without "cache busters") -bool ScriptManager::registerModuleWithParent(const ScriptValuePointer& module, const ScriptValuePointer& parent) { - auto children = parent->property("children"); - if (children->isArray()) { - auto key = module->property("id"); - auto length = children->property("length")->toInt32(); +bool ScriptManager::registerModuleWithParent(const ScriptValue& module, const ScriptValue& parent) { + auto children = parent.property("children"); + if (children.isArray()) { + auto key = module.property("id"); + auto length = children.property("length").toInt32(); for (int i = 0; i < length; i++) { - if (children->property(i)->property("id")->strictlyEquals(key)) { - qCDebug(scriptengine_module) << key->toString() << " updating parent.children[" << i << "] = module"; - children->setProperty(i, module); + if (children.property(i).property("id").strictlyEquals(key)) { + qCDebug(scriptengine_module) << key.toString() << " updating parent.children[" << i << "] = module"; + children.setProperty(i, module); return true; } } - qCDebug(scriptengine_module) << key->toString() << " appending parent.children[" << length << "] = module"; - children->setProperty(length, module); + qCDebug(scriptengine_module) << key.toString() << " appending parent.children[" << length << "] = module"; + children.setProperty(length, module); return true; - } else if (parent->isValid()) { - qCDebug(scriptengine_module) << "registerModuleWithParent -- unrecognized parent" << parent->toVariant().toString(); + } else if (parent.isValid()) { + qCDebug(scriptengine_module) << "registerModuleWithParent -- unrecognized parent" << parent.toVariant().toString(); } return false; } // creates a new JS "module" Object with default metadata properties -ScriptValuePointer ScriptManager::newModule(const QString& modulePath, const ScriptValuePointer& parent) { +ScriptValue ScriptManager::newModule(const QString& modulePath, const ScriptValue& parent) { auto closure = _engine->newObject(); auto exports = _engine->newObject(); auto module = _engine->newObject(); - qCDebug(scriptengine_module) << "newModule" << parent->property("filename")->toString(); + qCDebug(scriptengine_module) << "newModule" << parent.property("filename").toString(); - closure->setProperty("module", module, READONLY_PROP_FLAGS); + closure.setProperty("module", module, READONLY_PROP_FLAGS); // note: this becomes the "exports" free variable, so should not be set read only - closure->setProperty("exports", exports); + closure.setProperty("exports", exports); // make the closure available to module instantiation - module->setProperty("__closure__", closure, READONLY_HIDDEN_PROP_FLAGS); + module.setProperty("__closure__", closure, READONLY_HIDDEN_PROP_FLAGS); // for consistency with Node.js Module - module->setProperty("id", modulePath, READONLY_PROP_FLAGS); - module->setProperty("filename", modulePath, READONLY_PROP_FLAGS); - module->setProperty("exports", exports); // not readonly - module->setProperty("loaded", false, READONLY_PROP_FLAGS); - module->setProperty("parent", parent, READONLY_PROP_FLAGS); - module->setProperty("children", _engine->newArray(), READONLY_PROP_FLAGS); + module.setProperty("id", modulePath, READONLY_PROP_FLAGS); + module.setProperty("filename", modulePath, READONLY_PROP_FLAGS); + module.setProperty("exports", exports); // not readonly + module.setProperty("loaded", false, READONLY_PROP_FLAGS); + module.setProperty("parent", parent, READONLY_PROP_FLAGS); + module.setProperty("children", _engine->newArray(), READONLY_PROP_FLAGS); // module.require is a bound version of require that always resolves relative to that module's path auto boundRequire = _engine->evaluate("(function(id) { return Script.require(Script.require.resolve(id, this.filename)); })", "(boundRequire)"); - module->setProperty("require", boundRequire, READONLY_PROP_FLAGS); + module.setProperty("require", boundRequire, READONLY_PROP_FLAGS); return module; } @@ -1383,23 +1383,23 @@ QVariantMap ScriptManager::fetchModuleSource(const QString& modulePath, const bo } // evaluate a pending module object using the fetched source code -ScriptValuePointer ScriptManager::instantiateModule(const ScriptValuePointer& module, const QString& sourceCode) { - ScriptValuePointer result; - auto modulePath = module->property("filename")->toString(); - auto closure = module->property("__closure__"); +ScriptValue ScriptManager::instantiateModule(const ScriptValue& module, const QString& sourceCode) { + ScriptValue result; + auto modulePath = module.property("filename").toString(); + auto closure = module.property("__closure__"); qCDebug(scriptengine_module) << QString("require.instantiateModule: %1 / %2 bytes") .arg(QUrl(modulePath).fileName()).arg(sourceCode.length()); - if (module->property("content-type")->toString() == "application/json") { + if (module.property("content-type").toString() == "application/json") { qCDebug(scriptengine_module) << "... parsing as JSON"; - closure->setProperty("__json", sourceCode); + closure.setProperty("__json", sourceCode); result = _engine->evaluateInClosure(closure, _engine->newProgram( "module.exports = JSON.parse(__json)", modulePath )); } else { // scoped vars for consistency with Node.js - closure->setProperty("require", module->property("require")); - closure->setProperty("__filename", modulePath, READONLY_HIDDEN_PROP_FLAGS); - closure->setProperty("__dirname", QString(modulePath).replace(QRegExp("/[^/]*$"), ""), READONLY_HIDDEN_PROP_FLAGS); + closure.setProperty("require", module.property("require")); + closure.setProperty("__filename", modulePath, READONLY_HIDDEN_PROP_FLAGS); + closure.setProperty("__dirname", QString(modulePath).replace(QRegExp("/[^/]*$"), ""), READONLY_HIDDEN_PROP_FLAGS); result = _engine->evaluateInClosure(closure, _engine->newProgram( sourceCode, modulePath )); } _engine->maybeEmitUncaughtException(__FUNCTION__); @@ -1407,19 +1407,19 @@ ScriptValuePointer ScriptManager::instantiateModule(const ScriptValuePointer& mo } // CommonJS/Node.js like require/module support -ScriptValuePointer ScriptManager::require(const QString& moduleId) { +ScriptValue ScriptManager::require(const QString& moduleId) { qCDebug(scriptengine_module) << "ScriptManager::require(" << moduleId.left(MAX_DEBUG_VALUE_LENGTH) << ")"; if (!_engine->IS_THREADSAFE_INVOCATION(__FUNCTION__)) { return _engine->nullValue(); } - auto jsRequire = _engine->globalObject()->property("Script")->property("require"); + auto jsRequire = _engine->globalObject().property("Script").property("require"); auto cacheMeta = jsRequire.data(); - auto cache = jsRequire->property("cache"); + auto cache = jsRequire.property("cache"); auto parent = currentModule(); - auto throwModuleError = [&](const QString& modulePath, const ScriptValuePointer& error) { - cache->setProperty(modulePath, _engine->nullValue()); + auto throwModuleError = [&](const QString& modulePath, const ScriptValue& error) { + cache.setProperty(modulePath, _engine->nullValue()); if (!error.isNull()) { #ifdef DEBUG_JS_MODULES qCWarning(scriptengine_module) << "throwing module error:" << error.toString() << modulePath << error.property("stack").toString(); @@ -1439,7 +1439,7 @@ ScriptValuePointer ScriptManager::require(const QString& moduleId) { } // check the resolved path against the cache - auto module = cache->property(modulePath); + auto module = cache.property(modulePath); // modules get cached in `Script.require.cache` and (similar to Node.js) users can access it // to inspect particular entries and invalidate them by deleting the key: @@ -1449,16 +1449,16 @@ ScriptValuePointer ScriptManager::require(const QString& moduleId) { Setting::Handle getCachebustSetting {"cachebustScriptRequire", false }; // cacheMeta is just used right now to tell deleted keys apart from undefined ones - bool invalidateCache = getCachebustSetting.get() || (module->isUndefined() && cacheMeta->property(moduleId)->isValid()); + bool invalidateCache = getCachebustSetting.get() || (module.isUndefined() && cacheMeta.property(moduleId).isValid()); // reset the cacheMeta record so invalidation won't apply next time, even if the module fails to load - cacheMeta->setProperty(modulePath, ScriptValuePointer()); + cacheMeta.setProperty(modulePath, ScriptValue()); - auto exports = module->property("exports"); - if (!invalidateCache && exports->isObject()) { + auto exports = module.property("exports"); + if (!invalidateCache && exports.isObject()) { // we have found a cached module -- just need to possibly register it with current parent qCDebug(scriptengine_module) << QString("require - using cached module for '%1' (loaded: %2)") - .arg(moduleId).arg(module->property("loaded")->toString()); + .arg(moduleId).arg(module.property("loaded").toString()); registerModuleWithParent(module, parent); _engine->maybeEmitUncaughtException("cached module"); return exports; @@ -1469,7 +1469,7 @@ ScriptValuePointer ScriptManager::require(const QString& moduleId) { registerModuleWithParent(module, parent); // add it to the cache (this is done early so any cyclic dependencies pick up) - cache->setProperty(modulePath, module); + cache.setProperty(modulePath, module); // download the module source auto req = fetchModuleSource(modulePath, invalidateCache); @@ -1487,36 +1487,36 @@ ScriptValuePointer ScriptManager::require(const QString& moduleId) { auto sourceCode = req["contents"].toString(); if (QUrl(modulePath).fileName().endsWith(".json", Qt::CaseInsensitive)) { - module->setProperty("content-type", "application/json"); + module.setProperty("content-type", "application/json"); } else { - module->setProperty("content-type", "application/javascript"); + module.setProperty("content-type", "application/javascript"); } // evaluate the module auto result = instantiateModule(module, sourceCode); - if (result->isError() && !result->strictlyEquals(module->property("exports"))) { - qCWarning(scriptengine_module) << "-- result.isError --" << result->toString(); + if (result.isError() && !result.strictlyEquals(module.property("exports"))) { + qCWarning(scriptengine_module) << "-- result.isError --" << result.toString(); return throwModuleError(modulePath, result); } // mark as fully-loaded - module->setProperty("loaded", true, READONLY_PROP_FLAGS); + module.setProperty("loaded", true, READONLY_PROP_FLAGS); // set up a new reference point for detecting cache key deletion - cacheMeta->setProperty(modulePath, module); + cacheMeta.setProperty(modulePath, module); qCDebug(scriptengine_module) << "//ScriptManager::require(" << moduleId << ")"; _engine->maybeEmitUncaughtException(__FUNCTION__); - return module->property("exports"); + return module.property("exports"); } // If a callback is specified, the included files will be loaded asynchronously and the callback will be called // when all of the files have finished loading. // If no callback is specified, the included files will be loaded synchronously and will block execution until // all of the files have finished loading. -void ScriptManager::include(const QStringList& includeFiles, ScriptValuePointer callback) { +void ScriptManager::include(const QStringList& includeFiles, const ScriptValue& callback) { if (!_engine->IS_THREADSAFE_INVOCATION(__FUNCTION__)) { return; } @@ -1592,8 +1592,8 @@ void ScriptManager::include(const QStringList& includeFiles, ScriptValuePointer } _parentURL = parentURL; - if (callback && callback->isFunction()) { - callWithEnvironment(capturedEntityIdentifier, capturedSandboxURL, callback, ScriptValuePointer(), ScriptValueList()); + if (callback.isFunction()) { + callWithEnvironment(capturedEntityIdentifier, capturedSandboxURL, callback, ScriptValue(), ScriptValueList()); } loader->deleteLater(); @@ -1606,14 +1606,14 @@ void ScriptManager::include(const QStringList& includeFiles, ScriptValuePointer loader->start(processLevelMaxRetries); - if ((!callback || !callback->isFunction()) && !loader->isFinished()) { + if (!callback.isFunction() && !loader->isFinished()) { QEventLoop loop; QObject::connect(loader, &BatchLoader::finished, &loop, &QEventLoop::quit); loop.exec(); } } -void ScriptManager::include(const QString& includeFile, ScriptValuePointer callback) { +void ScriptManager::include(const QString& includeFile, const ScriptValue& callback) { if (isStopped()) { scriptWarningMessage("Script.include() while shutting down is ignored... includeFile:" + includeFile + "parent script:" + getFilename()); @@ -1654,7 +1654,7 @@ void ScriptManager::load(const QString& loadFile) { } // Look up the handler associated with eventName and entityID. If found, evalute the argGenerator thunk and call the handler with those args -void ScriptManager::forwardHandlerCall(const EntityItemID& entityID, const QString& eventName, ScriptValueList eventHandlerArgs) { +void ScriptManager::forwardHandlerCall(const EntityItemID& entityID, const QString& eventName, const ScriptValueList& eventHandlerArgs) { if (QThread::currentThread() != thread()) { qCDebug(scriptengine) << "*** ERROR *** ScriptManager::forwardHandlerCall() called on wrong thread [" << QThread::currentThread() << "], invoking on correct thread [" << thread() << "]"; assert(false); @@ -1674,7 +1674,7 @@ void ScriptManager::forwardHandlerCall(const EntityItemID& entityID, const QStri // and the entity scripts may be for entities other than the one this is a handler for. // Fortunately, the definingEntityIdentifier captured the entity script id (if any) when the handler was added. CallbackData& handler = handlersForEvent[i]; - callWithEnvironment(handler.definingEntityIdentifier, handler.definingSandboxURL, handler.function, ScriptValuePointer(), eventHandlerArgs); + callWithEnvironment(handler.definingEntityIdentifier, handler.definingSandboxURL, handler.function, ScriptValue(), eventHandlerArgs); } } } @@ -1921,13 +1921,13 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c // SYNTAX ERRORS auto syntaxError = _engine->lintScript(contents, fileName); - if (syntaxError->isError()) { - auto message = syntaxError->property("formatted")->toString(); + if (syntaxError.isError()) { + auto message = syntaxError.property("formatted").toString(); if (message.isEmpty()) { - message = syntaxError->toString(); + message = syntaxError.toString(); } setError(QString("Bad syntax (%1)").arg(message), EntityScriptStatus::ERROR_RUNNING_SCRIPT); - syntaxError->setProperty("detail", entityID.toString()); + syntaxError.setProperty("detail", entityID.toString()); emit unhandledException(syntaxError); return; } @@ -1946,7 +1946,7 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c const int SANDBOX_TIMEOUT = 0.25 * MSECS_PER_SECOND; ScriptEnginePointer sandbox = newScriptEngine(); sandbox->setProcessEventsInterval(SANDBOX_TIMEOUT); - ScriptValuePointer testConstructor, exception; + ScriptValue testConstructor, exception; if (atoi(getenv("UNSAFE_ENTITY_SCRIPTS") ? getenv("UNSAFE_ENTITY_SCRIPTS") : "0")) { QTimer timeout; @@ -1966,7 +1966,7 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c if (sandbox->hasUncaughtException()) { exception = sandbox->cloneUncaughtException(QString("(preflight %1)").arg(entityID.toString())); sandbox->clearExceptions(); - } else if (testConstructor && testConstructor->isError()) { + } else if (testConstructor.isError()) { exception = testConstructor; } } else { @@ -2041,7 +2041,7 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c if (sandbox->hasUncaughtException()) { exception = sandbox->cloneUncaughtException(QString("(preflight %1)").arg(entityID.toString())); sandbox->clearExceptions(); - } else if (testConstructor && testConstructor->isError()) { + } else if (testConstructor.isError()) { exception = testConstructor; } } @@ -2051,7 +2051,7 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c // exception = makeError("UNSAFE_ENTITY_SCRIPTS == 0"); } - if (exception && exception->isError()) { + if (exception.isError()) { // create a local copy using makeError to decouple from the sandbox engine exception = _engine->makeError(exception); setError(formatException(exception, _enableExtendedJSExceptions.get()), EntityScriptStatus::ERROR_RUNNING_SCRIPT); @@ -2060,12 +2060,12 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c } // CONSTRUCTOR VIABILITY - if (!testConstructor || !testConstructor->isFunction()) { - QString testConstructorType = QString(testConstructor->toVariant().typeName()); + if (!testConstructor.isFunction()) { + QString testConstructorType = QString(testConstructor.toVariant().typeName()); if (testConstructorType == "") { testConstructorType = "empty"; } - QString testConstructorValue = testConstructor->toString(); + QString testConstructorValue = testConstructor.toString(); if (testConstructorValue.size() > MAX_DEBUG_VALUE_LENGTH) { testConstructorValue = testConstructorValue.mid(0, MAX_DEBUG_VALUE_LENGTH) + "..."; } @@ -2073,8 +2073,8 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c .arg(testConstructorType).arg(testConstructorValue); auto err = _engine->makeError(_engine->newValue(message)); - err->setProperty("fileName", scriptOrURL); - err->setProperty("detail", "(constructor " + entityID.toString() + ")"); + err.setProperty("fileName", scriptOrURL); + err.setProperty("detail", "(constructor " + entityID.toString() + ")"); setError("Could not find constructor (" + testConstructorType + ")", EntityScriptStatus::ERROR_RUNNING_SCRIPT); emit unhandledException(err); @@ -2089,11 +2089,11 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c } // THE ACTUAL EVALUATION AND CONSTRUCTION - ScriptValuePointer entityScriptConstructor, entityScriptObject; + ScriptValue entityScriptConstructor, entityScriptObject; QUrl sandboxURL = currentSandboxURL.isEmpty() ? scriptOrURL : currentSandboxURL; auto initialization = [&]{ entityScriptConstructor = _engine->evaluate(contents, fileName); - entityScriptObject = entityScriptConstructor->construct(); + entityScriptObject = entityScriptConstructor.construct(); if (_engine->hasUncaughtException()) { entityScriptObject = _engine->cloneUncaughtException("(construct " + entityID.toString() + ")"); @@ -2103,7 +2103,7 @@ void ScriptManager::entityScriptContentAvailable(const EntityItemID& entityID, c doWithEnvironment(entityID, sandboxURL, initialization); - if (entityScriptObject && entityScriptObject->isError()) { + if (entityScriptObject.isError()) { auto exception = entityScriptObject; setError(formatException(exception, _enableExtendedJSExceptions.get()), EntityScriptStatus::ERROR_RUNNING_SCRIPT); emit unhandledException(exception); @@ -2266,7 +2266,7 @@ void ScriptManager::doWithEnvironment(const EntityItemID& entityID, const QUrl& currentSandboxURL = sandboxURL; #if DEBUG_CURRENT_ENTITY - ScriptValuePointer oldData = this->globalObject().property("debugEntityID"); + ScriptValue oldData = this->globalObject().property("debugEntityID"); this->globalObject().setProperty("debugEntityID", entityID.toScriptValue(this)); // Make the entityID available to javascript as a global. operation(); this->globalObject().setProperty("debugEntityID", oldData); @@ -2278,9 +2278,9 @@ void ScriptManager::doWithEnvironment(const EntityItemID& entityID, const QUrl& currentSandboxURL = oldSandboxURL; } -void ScriptManager::callWithEnvironment(const EntityItemID& entityID, const QUrl& sandboxURL, ScriptValuePointer function, ScriptValuePointer thisObject, ScriptValueList args) { +void ScriptManager::callWithEnvironment(const EntityItemID& entityID, const QUrl& sandboxURL, const ScriptValue& function, const ScriptValue& thisObject, const ScriptValueList& args) { auto operation = [&]() { - function->call(thisObject, args); + function.call(thisObject, args); }; doWithEnvironment(entityID, sandboxURL, operation); } @@ -2313,7 +2313,7 @@ void ScriptManager::callEntityScriptMethod(const EntityItemID& entityID, const Q QWriteLocker locker { &_entityScriptsLock }; details = _entityScripts[entityID]; } - ScriptValuePointer entityScript = details.scriptObject; // previously loaded + ScriptValue entityScript = details.scriptObject; // previously loaded // If this is a remote call, we need to check to see if the function is remotely callable // we do this by checking for the existance of the 'remotelyCallable' property on the @@ -2323,11 +2323,11 @@ void ScriptManager::callEntityScriptMethod(const EntityItemID& entityID, const Q if (remoteCallerID == QUuid()) { callAllowed = true; } else { - if (entityScript->property("remotelyCallable")->isArray()) { - auto callables = entityScript->property("remotelyCallable"); - auto callableCount = callables->property("length")->toInteger(); + if (entityScript.property("remotelyCallable").isArray()) { + auto callables = entityScript.property("remotelyCallable"); + auto callableCount = callables.property("length").toInteger(); for (int i = 0; i < callableCount; i++) { - auto callable = callables->property(i)->toString(); + auto callable = callables.property(i).toString(); if (callable == methodName) { callAllowed = true; break; @@ -2339,17 +2339,17 @@ void ScriptManager::callEntityScriptMethod(const EntityItemID& entityID, const Q } } - if (callAllowed && entityScript->property(methodName)->isFunction()) { + if (callAllowed && entityScript.property(methodName).isFunction()) { auto scriptEngine = engine().data(); ScriptValueList args; args << EntityItemIDtoScriptValue(scriptEngine, entityID); args << scriptValueFromSequence(scriptEngine, params); - ScriptValuePointer oldData = scriptEngine->globalObject()->property("Script")->property("remoteCallerID"); - scriptEngine->globalObject()->property("Script")->setProperty("remoteCallerID", remoteCallerID.toString()); // Make the remoteCallerID available to javascript as a global. - callWithEnvironment(entityID, details.definingSandboxURL, entityScript->property(methodName), entityScript, args); - scriptEngine->globalObject()->property("Script")->setProperty("remoteCallerID", oldData); + ScriptValue oldData = scriptEngine->globalObject().property("Script").property("remoteCallerID"); + scriptEngine->globalObject().property("Script").setProperty("remoteCallerID", remoteCallerID.toString()); // Make the remoteCallerID available to javascript as a global. + callWithEnvironment(entityID, details.definingSandboxURL, entityScript.property(methodName), entityScript, args); + scriptEngine->globalObject().property("Script").setProperty("remoteCallerID", oldData); } } } @@ -2381,14 +2381,14 @@ void ScriptManager::callEntityScriptMethod(const EntityItemID& entityID, const Q QWriteLocker locker { &_entityScriptsLock }; details = _entityScripts[entityID]; } - ScriptValuePointer entityScript = details.scriptObject; // previously loaded - if (entityScript->property(methodName)->isFunction()) { + ScriptValue entityScript = details.scriptObject; // previously loaded + if (entityScript.property(methodName).isFunction()) { auto scriptEngine = engine().data(); ScriptValueList args; args << EntityItemIDtoScriptValue(scriptEngine, entityID); args << event.toScriptValue(scriptEngine); - callWithEnvironment(entityID, details.definingSandboxURL, entityScript->property(methodName), entityScript, args); + callWithEnvironment(entityID, details.definingSandboxURL, entityScript.property(methodName), entityScript, args); } } } @@ -2421,15 +2421,15 @@ void ScriptManager::callEntityScriptMethod(const EntityItemID& entityID, const Q QWriteLocker locker { &_entityScriptsLock }; details = _entityScripts[entityID]; } - ScriptValuePointer entityScript = details.scriptObject; // previously loaded - if (entityScript->property(methodName)->isFunction()) { + ScriptValue entityScript = details.scriptObject; // previously loaded + if (entityScript.property(methodName).isFunction()) { auto scriptEngine = engine().data(); ScriptValueList args; args << EntityItemIDtoScriptValue(scriptEngine, entityID); args << EntityItemIDtoScriptValue(scriptEngine, otherID); args << collisionToScriptValue(scriptEngine, collision); - callWithEnvironment(entityID, details.definingSandboxURL, entityScript->property(methodName), entityScript, args); + callWithEnvironment(entityID, details.definingSandboxURL, entityScript.property(methodName), entityScript, args); } } } @@ -2438,28 +2438,28 @@ QString ScriptManager::getExternalPath(ExternalResource::Bucket bucket, const QS return ExternalResource::getInstance()->getUrl(bucket, path); } -QString ScriptManager::formatException(const ScriptValuePointer& exception, bool includeExtendedDetails) { +QString ScriptManager::formatException(const ScriptValue& exception, bool includeExtendedDetails) { if (!_engine->IS_THREADSAFE_INVOCATION(__FUNCTION__)) { return QString(); } QString note{ "UncaughtException" }; QString result; - if (!exception->isObject()) { + if (!exception.isObject()) { return result; } - const auto message = exception->toString(); - const auto fileName = exception->property("fileName")->toString(); - const auto lineNumber = exception->property("lineNumber")->toString(); - const auto stacktrace = exception->property("stack")->toString(); + const auto message = exception.toString(); + const auto fileName = exception.property("fileName").toString(); + const auto lineNumber = exception.property("lineNumber").toString(); + const auto stacktrace = exception.property("stack").toString(); if (includeExtendedDetails) { // Display additional exception / troubleshooting hints that can be added via the custom Error .detail property // Example difference: // [UncaughtExceptions] Error: Can't find variable: foobar in atp:/myentity.js\n... // [UncaughtException (construct {1eb5d3fa-23b1-411c-af83-163af7220e3f})] Error: Can't find variable: foobar in atp:/myentity.js\n... - if (exception->property("detail")->isValid()) { - note += " " + exception->property("detail")->toString(); + if (exception.property("detail").isValid()) { + note += " " + exception.property("detail").toString(); } } @@ -2470,6 +2470,6 @@ QString ScriptManager::formatException(const ScriptValuePointer& exception, bool return result; } -ScriptValuePointer ScriptManager::evaluate(const QString& program, const QString& fileName) { +ScriptValue ScriptManager::evaluate(const QString& program, const QString& fileName) { return _engine->evaluate(program, fileName); } diff --git a/libraries/script-engine/src/ScriptManager.h b/libraries/script-engine/src/ScriptManager.h index b180d69753..0ec4f1e379 100644 --- a/libraries/script-engine/src/ScriptManager.h +++ b/libraries/script-engine/src/ScriptManager.h @@ -42,6 +42,7 @@ #include "PointerEvent.h" #include "Quat.h" #include "ScriptUUID.h" +#include "ScriptValue.h" #include "Vec3.h" static const QString NO_SCRIPT(""); @@ -53,17 +54,15 @@ static const int DEFAULT_ENTITY_PPS_PER_SCRIPT = 900; class ScriptEngine; class ScriptEngines; class ScriptManager; -class ScriptValue; using ScriptEnginePointer = QSharedPointer; using ScriptManagerPointer = QSharedPointer; -using ScriptValuePointer = QSharedPointer; -using ScriptValueList = QList; +using ScriptValueList = QList; Q_DECLARE_METATYPE(ScriptManagerPointer) class CallbackData { public: - ScriptValuePointer function; + ScriptValue function; EntityItemID definingEntityIdentifier; QUrl definingSandboxURL; }; @@ -97,7 +96,7 @@ public: QString errorInfo { "" }; QString scriptText { "" }; - ScriptValuePointer scriptObject{ ScriptValuePointer() }; + ScriptValue scriptObject{ ScriptValue() }; int64_t lastModified { 0 }; QUrl definingSandboxURL { QUrl("about:EntityScript") }; }; @@ -286,7 +285,7 @@ public: * @returns {string} String. * @deprecated This function is deprecated and will be removed. */ - Q_INVOKABLE QString formatException(const ScriptValuePointer& exception, bool includeExtendedDetails); + Q_INVOKABLE QString formatException(const ScriptValue& exception, bool includeExtendedDetails); /**jsdoc * Adds a function to the list of functions called when a particular event occurs on a particular entity. @@ -310,7 +309,7 @@ public: * * Script.addEventHandler(entityID, "mousePressOnEntity", reportMousePress); */ - Q_INVOKABLE void addEventHandler(const EntityItemID& entityID, const QString& eventName, ScriptValuePointer handler); + Q_INVOKABLE void addEventHandler(const EntityItemID& entityID, const QString& eventName, const ScriptValue& handler); /**jsdoc * Removes a function from the list of functions called when an entity event occurs on a particular entity. @@ -320,7 +319,7 @@ public: * @param {Script.EntityEvent} eventName - The name of the entity event. * @param {function} handler - The name of the function to no longer call when the entity event occurs on the entity. */ - Q_INVOKABLE void removeEventHandler(const EntityItemID& entityID, const QString& eventName, ScriptValuePointer handler); + Q_INVOKABLE void removeEventHandler(const EntityItemID& entityID, const QString& eventName, const ScriptValue& handler); /**jsdoc * Starts running another script in Interface, if it isn't already running. The script is not automatically loaded next @@ -354,7 +353,7 @@ public: * @param {function} [callback=null] - The function to call back when the scripts have been included. It can be either the * name of a function or an in-line definition. */ - Q_INVOKABLE void include(const QStringList& includeFiles, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void include(const QStringList& includeFiles, const ScriptValue& callback = ScriptValue()); /**jsdoc * Includes JavaScript from another file in the current script. If a callback is specified, the file is loaded and included @@ -379,7 +378,7 @@ public: * // This is script A * // Script A has been included */ - Q_INVOKABLE void include(const QString& includeFile, ScriptValuePointer callback = ScriptValuePointer()); + Q_INVOKABLE void include(const QString& includeFile, const ScriptValue& callback = ScriptValue()); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MODULE related methods @@ -393,7 +392,7 @@ public: * @returns {object|array} The value assigned to module.exports in the JavaScript file, or the value defined * in the JSON file. */ - Q_INVOKABLE ScriptValuePointer require(const QString& moduleId); + Q_INVOKABLE ScriptValue require(const QString& moduleId); /**jsdoc * @function Script.resetModuleCache @@ -402,13 +401,13 @@ public: */ Q_INVOKABLE void resetModuleCache(bool deleteScriptCache = false); - ScriptValuePointer currentModule(); - bool registerModuleWithParent(const ScriptValuePointer& module, const ScriptValuePointer& parent); - ScriptValuePointer newModule(const QString& modulePath, const ScriptValuePointer& parent = ScriptValuePointer()); + ScriptValue currentModule(); + bool registerModuleWithParent(const ScriptValue& module, const ScriptValue& parent); + ScriptValue newModule(const QString& modulePath, const ScriptValue& parent = ScriptValue()); QVariantMap fetchModuleSource(const QString& modulePath, const bool forceDownload = false); - ScriptValuePointer instantiateModule(const ScriptValuePointer& module, const QString& sourceCode); + ScriptValue instantiateModule(const ScriptValue& module, const QString& sourceCode); - Q_INVOKABLE ScriptValuePointer evaluate(const QString& program, const QString& fileName = QString()); + Q_INVOKABLE ScriptValue evaluate(const QString& program, const QString& fileName = QString()); /**jsdoc * Calls a function repeatedly, at a set interval. @@ -421,7 +420,7 @@ public: * print("Interval timer fired"); * }, 1000); */ - Q_INVOKABLE QObject* setInterval(const ScriptValuePointer& function, int intervalMS); + Q_INVOKABLE QObject* setInterval(const ScriptValue& function, int intervalMS); /**jsdoc * Calls a function once, after a delay. @@ -434,7 +433,7 @@ public: * print("Timeout timer fired"); * }, 1000); */ - Q_INVOKABLE QObject* setTimeout(const ScriptValuePointer& function, int timeoutMS); + Q_INVOKABLE QObject* setTimeout(const ScriptValue& function, int timeoutMS); /**jsdoc * Stops an interval timer set by {@link Script.setInterval|setInterval}. @@ -630,7 +629,7 @@ public: void setScriptEngines(QSharedPointer& scriptEngines) { _scriptEngines = scriptEngines; } // call all the registered event handlers on an entity for the specified name. - void forwardHandlerCall(const EntityItemID& entityID, const QString& eventName, ScriptValueList eventHanderArgs); + void forwardHandlerCall(const EntityItemID& entityID, const QString& eventName, const ScriptValueList& eventHanderArgs); // remove all event handlers for the specified entityID (i.e. the entity is being removed) void removeAllEventHandlers(const EntityItemID& entityID); @@ -853,7 +852,7 @@ signals: * }); * var properties = JSON.parse("{ x: 1"); // Invalid JSON string. */ - void unhandledException(const ScriptValuePointer& exception); + void unhandledException(const ScriptValue& exception); // Triggered once before the first call to Script.addEventHandler happens on this ScriptManager // connections assumed to use Qt::DirectConnection; not for use by scripts @@ -885,7 +884,7 @@ protected: // then inside of init() we just have to do "Script.require.resolve = Script._requireResolve;" Q_INVOKABLE QString _requireResolve(const QString& moduleId, const QString& relativeTo = QString()); - QString logException(const ScriptValuePointer& exception); + QString logException(const ScriptValue& exception); void timerFired(); void stopAllTimers(); void stopAllTimersForEntityScript(const EntityItemID& entityID); @@ -894,7 +893,7 @@ protected: void setEntityScriptDetails(const EntityItemID& entityID, const EntityScriptDetails& details); void setParentURL(const QString& parentURL) { _parentURL = parentURL; } - QObject* setupTimerWithInterval(const ScriptValuePointer& function, int intervalMS, bool isSingleShot); + QObject* setupTimerWithInterval(const ScriptValue& function, int intervalMS, bool isSingleShot); void stopTimer(QTimer* timer); QHash _registeredHandlers; @@ -914,7 +913,7 @@ protected: EntityItemID currentEntityIdentifier; // Contains the defining entity script entity id during execution, if any. Empty for interface script execution. QUrl currentSandboxURL; // The toplevel url string for the entity script that loaded the code being executed, else empty. void doWithEnvironment(const EntityItemID& entityID, const QUrl& sandboxURL, std::function operation); - void callWithEnvironment(const EntityItemID& entityID, const QUrl& sandboxURL, ScriptValuePointer function, ScriptValuePointer thisObject, ScriptValueList args); + void callWithEnvironment(const EntityItemID& entityID, const QUrl& sandboxURL, const ScriptValue& function, const ScriptValue& thisObject, const ScriptValueList& args); Context _context; Type _type; diff --git a/libraries/script-engine/src/ScriptValue.cpp b/libraries/script-engine/src/ScriptValue.cpp new file mode 100644 index 0000000000..344d9a6393 --- /dev/null +++ b/libraries/script-engine/src/ScriptValue.cpp @@ -0,0 +1,236 @@ +// +// ScriptValue.cpp +// libraries/script-engine/src +// +// Created by Heather Anderson on 9/2/21. +// Copyright 2021 Vircadia contributors. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "ScriptValue.h" + +#include "ScriptEngineLogging.h" + + +class ScriptValueProxyNull : public ScriptValueProxy { +public: + virtual void release(); + virtual ScriptValueProxy* copy() const; + +public: + virtual ScriptValue call(const ScriptValue& thisObject = ScriptValue(), const ScriptValueList& args = ScriptValueList()); + virtual ScriptValue call(const ScriptValue& thisObject, const ScriptValue& arguments); + virtual ScriptValue construct(const ScriptValueList& args = ScriptValueList()); + virtual ScriptValue construct(const ScriptValue& arguments); + virtual ScriptValue data() const; + virtual ScriptEnginePointer engine() const; + virtual bool equals(const ScriptValue& other) const; + virtual bool isArray() const; + virtual bool isBool() const; + virtual bool isError() const; + virtual bool isFunction() const; + virtual bool isNumber() const; + virtual bool isNull() const; + virtual bool isObject() const; + virtual bool isString() const; + virtual bool isUndefined() const; + virtual bool isValid() const; + virtual bool isVariant() const; + virtual ScriptValueIteratorPointer newIterator() const; + virtual ScriptValue property(const QString& name, + const ScriptValue::ResolveFlags& mode = ScriptValue::ResolvePrototype) const; + virtual ScriptValue property(quint32 arrayIndex, + const ScriptValue::ResolveFlags& mode = ScriptValue::ResolvePrototype) const; + virtual void setData(const ScriptValue& val); + virtual void setProperty(const QString& name, + const ScriptValue& value, + const ScriptValue::PropertyFlags& flags = ScriptValue::KeepExistingFlags); + virtual void setProperty(quint32 arrayIndex, + const ScriptValue& value, + const ScriptValue::PropertyFlags& flags = ScriptValue::KeepExistingFlags); + virtual void setPrototype(const ScriptValue& prototype); + virtual bool strictlyEquals(const ScriptValue& other) const; + + virtual bool toBool() const; + virtual qint32 toInt32() const; + virtual double toInteger() const; + virtual double toNumber() const; + virtual QString toString() const; + virtual quint16 toUInt16() const; + virtual quint32 toUInt32() const; + virtual QVariant toVariant() const; + virtual QObject* toQObject() const; +}; + +static ScriptValueProxyNull SCRIPT_VALUE_NULL; + +ScriptValue::ScriptValue() : _proxy(&SCRIPT_VALUE_NULL) {} + +void ScriptValueProxyNull::release() { + // do nothing, we're a singlet +} + +ScriptValueProxy* ScriptValueProxyNull::copy() const { + // return ourselves, we're a singlet + return const_cast (this); +} + +ScriptValue ScriptValueProxyNull::call(const ScriptValue& thisObject, const ScriptValueList& args) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::call made to empty value"); + return ScriptValue(); +} + +ScriptValue ScriptValueProxyNull::call(const ScriptValue& thisObject, const ScriptValue& arguments) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::call made to empty value"); + return ScriptValue(); +} + +ScriptValue ScriptValueProxyNull::construct(const ScriptValueList& args) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::construct called on empty value"); + return ScriptValue(); +} + +ScriptValue ScriptValueProxyNull::construct(const ScriptValue& arguments) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::construct called on empty value"); + return ScriptValue(); +} + +ScriptValue ScriptValueProxyNull::data() const { + return ScriptValue(); +} + +ScriptEnginePointer ScriptValueProxyNull::engine() const { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::engine called on empty value"); + return ScriptEnginePointer(); +} + +bool ScriptValueProxyNull::equals(const ScriptValue& other) const { + return other.isUndefined(); +} + +bool ScriptValueProxyNull::isArray() const { + return false; +} + +bool ScriptValueProxyNull::isBool() const { + return false; +} + +bool ScriptValueProxyNull::isError() const { + return false; +} + +bool ScriptValueProxyNull::isFunction() const { + return false; +} + +bool ScriptValueProxyNull::isNumber() const { + return false; +} + +bool ScriptValueProxyNull::isNull() const { + return false; +} + +bool ScriptValueProxyNull::isObject() const { + return false; +} + +bool ScriptValueProxyNull::isString() const { + return false; +} + +bool ScriptValueProxyNull::isUndefined() const { + return true; +} + +bool ScriptValueProxyNull::isValid() const { + return false; +} + +bool ScriptValueProxyNull::isVariant() const { + return false; +} + +ScriptValueIteratorPointer ScriptValueProxyNull::newIterator() const { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::newIterator called on empty value"); + return ScriptValueIteratorPointer(); +} + +ScriptValue ScriptValueProxyNull::property(const QString& name, const ScriptValue::ResolveFlags& mode) const { + return ScriptValue(); +} + +ScriptValue ScriptValueProxyNull::property(quint32 arrayIndex, const ScriptValue::ResolveFlags& mode) const { + return ScriptValue(); +} + +void ScriptValueProxyNull::setData(const ScriptValue& val) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::setData called on empty value"); +} + +void ScriptValueProxyNull::setProperty(const QString& name, + const ScriptValue& value, const ScriptValue::PropertyFlags& flags) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::setProperty called on empty value"); +} + +void ScriptValueProxyNull::setProperty(quint32 arrayIndex, + const ScriptValue& value, const ScriptValue::PropertyFlags& flags) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::setProperty called on empty value"); +} + +void ScriptValueProxyNull::setPrototype(const ScriptValue& prototype) { + Q_ASSERT(false); + qCWarning(scriptengine_script, "ScriptValue::setPrototype called on empty value"); +} + +bool ScriptValueProxyNull::strictlyEquals(const ScriptValue& other) const { + return !other.isValid(); +} + +bool ScriptValueProxyNull::toBool() const { + return false; +} + +qint32 ScriptValueProxyNull::toInt32() const { + return 0; +} + +double ScriptValueProxyNull::toInteger() const { + return 0; +} + +double ScriptValueProxyNull::toNumber() const { + return 0; +} + +QString ScriptValueProxyNull::toString() const { + return QString(); +} + +quint16 ScriptValueProxyNull::toUInt16() const { + return 0; +} + +quint32 ScriptValueProxyNull::toUInt32() const { + return 0; +} + +QVariant ScriptValueProxyNull::toVariant() const { + return QVariant(); +} + +QObject* ScriptValueProxyNull::toQObject() const { + return nullptr; +} diff --git a/libraries/script-engine/src/ScriptValue.h b/libraries/script-engine/src/ScriptValue.h index 7b77404546..e2c608b8fc 100644 --- a/libraries/script-engine/src/ScriptValue.h +++ b/libraries/script-engine/src/ScriptValue.h @@ -15,18 +15,19 @@ #ifndef hifi_ScriptValue_h #define hifi_ScriptValue_h +#include #include #include #include #include +#include -class QObject; class ScriptEngine; class ScriptValue; class ScriptValueIterator; +class ScriptValueProxy; using ScriptEnginePointer = QSharedPointer; -using ScriptValuePointer = QSharedPointer; -using ScriptValueList = QList; +using ScriptValueList = QList; using ScriptValueIteratorPointer = QSharedPointer; /// [ScriptInterface] Provides an engine-independent interface for QScriptValue @@ -51,14 +52,22 @@ public: Q_DECLARE_FLAGS(PropertyFlags, PropertyFlag); public: - virtual ScriptValuePointer call(const ScriptValuePointer& thisObject = ScriptValuePointer(), - const ScriptValueList& args = ScriptValueList()) = 0; - virtual ScriptValuePointer call(const ScriptValuePointer& thisObject, const ScriptValuePointer& arguments) = 0; - virtual ScriptValuePointer construct(const ScriptValueList& args = ScriptValueList()) = 0; - virtual ScriptValuePointer construct(const ScriptValuePointer& arguments) = 0; - virtual ScriptValuePointer data() const = 0; - virtual ScriptEnginePointer engine() const = 0; - inline bool equals(const ScriptValuePointer& other) const; + ScriptValue(); + inline ScriptValue(const ScriptValue& src); + inline ~ScriptValue(); + inline ScriptValue(ScriptValueProxy* proxy) : _proxy(proxy) {} + inline ScriptValueProxy* ptr() const { return _proxy; } + inline ScriptValue& operator=(const ScriptValue& other); + +public: + inline ScriptValue call(const ScriptValue& thisObject = ScriptValue(), + const ScriptValueList& args = ScriptValueList()) const; + inline ScriptValue call(const ScriptValue& thisObject, const ScriptValue& arguments) const; + inline ScriptValue construct(const ScriptValueList& args = ScriptValueList()) const; + inline ScriptValue construct(const ScriptValue& arguments) const; + inline ScriptValue data() const; + inline ScriptEnginePointer engine() const; + inline bool equals(const ScriptValue& other) const; inline bool isArray() const; inline bool isBool() const; inline bool isError() const; @@ -70,22 +79,80 @@ public: inline bool isUndefined() const; inline bool isValid() const; inline bool isVariant() const; - virtual ScriptValueIteratorPointer newIterator() = 0; - virtual ScriptValuePointer property(const QString& name, const ResolveFlags& mode = ResolvePrototype) const = 0; - virtual ScriptValuePointer property(quint32 arrayIndex, const ResolveFlags& mode = ResolvePrototype) const = 0; - virtual void setData(const ScriptValuePointer& val) = 0; + inline ScriptValueIteratorPointer newIterator() const; + inline ScriptValue property(const QString& name, const ResolveFlags& mode = ResolvePrototype) const; + inline ScriptValue property(quint32 arrayIndex, const ResolveFlags& mode = ResolvePrototype) const; + inline void setData(const ScriptValue& val); + inline void setProperty(const QString& name, + const ScriptValue& value, + const PropertyFlags& flags = KeepExistingFlags); + inline void setProperty(quint32 arrayIndex, + const ScriptValue& value, + const PropertyFlags& flags = KeepExistingFlags); + template + inline void setProperty(const QString& name, const TYP& value, + const PropertyFlags& flags = KeepExistingFlags); + template + inline void setProperty(quint32 arrayIndex, const TYP& value, + const PropertyFlags& flags = KeepExistingFlags); + inline void setPrototype(const ScriptValue& prototype); + inline bool strictlyEquals(const ScriptValue& other) const; + + inline bool toBool() const; + inline qint32 toInt32() const; + inline double toInteger() const; + inline double toNumber() const; + inline QString toString() const; + inline quint16 toUInt16() const; + inline quint32 toUInt32() const; + inline QVariant toVariant() const; + inline QObject* toQObject() const; + +protected: + ScriptValueProxy* _proxy; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(ScriptValue::PropertyFlags); + +/// [ScriptInterface] Provides an engine-independent interface for QScriptValue +class ScriptValueProxy { +public: + virtual void release() = 0; + virtual ScriptValueProxy* copy() const = 0; + +public: + virtual ScriptValue call(const ScriptValue& thisObject = ScriptValue(), + const ScriptValueList& args = ScriptValueList()) = 0; + virtual ScriptValue call(const ScriptValue& thisObject, const ScriptValue& arguments) = 0; + virtual ScriptValue construct(const ScriptValueList& args = ScriptValueList()) = 0; + virtual ScriptValue construct(const ScriptValue& arguments) = 0; + virtual ScriptValue data() const = 0; + virtual ScriptEnginePointer engine() const = 0; + virtual bool equals(const ScriptValue& other) const = 0; + virtual bool isArray() const = 0; + virtual bool isBool() const = 0; + virtual bool isError() const = 0; + virtual bool isFunction() const = 0; + virtual bool isNumber() const = 0; + virtual bool isNull() const = 0; + virtual bool isObject() const = 0; + virtual bool isString() const = 0; + virtual bool isUndefined() const = 0; + virtual bool isValid() const = 0; + virtual bool isVariant() const = 0; + virtual ScriptValueIteratorPointer newIterator() const = 0; + virtual ScriptValue property(const QString& name, + const ScriptValue::ResolveFlags& mode = ScriptValue::ResolvePrototype) const = 0; + virtual ScriptValue property(quint32 arrayIndex, + const ScriptValue::ResolveFlags& mode = ScriptValue::ResolvePrototype) const = 0; + virtual void setData(const ScriptValue& val) = 0; virtual void setProperty(const QString& name, - const ScriptValuePointer& value, - const PropertyFlags& flags = KeepExistingFlags) = 0; + const ScriptValue& value, + const ScriptValue::PropertyFlags& flags = ScriptValue::KeepExistingFlags) = 0; virtual void setProperty(quint32 arrayIndex, - const ScriptValuePointer& value, - const PropertyFlags& flags = KeepExistingFlags) = 0; - template void setProperty(const QString& name, const TYP& value, - const PropertyFlags& flags = KeepExistingFlags); - template void setProperty(quint32 arrayIndex, const TYP& value, - const PropertyFlags& flags = KeepExistingFlags); - virtual void setPrototype(const ScriptValuePointer& prototype) = 0; - virtual bool strictlyEquals(const ScriptValuePointer& other) const = 0; + const ScriptValue& value, + const ScriptValue::PropertyFlags& flags = ScriptValue::KeepExistingFlags) = 0; + virtual void setPrototype(const ScriptValue& prototype) = 0; + virtual bool strictlyEquals(const ScriptValue& other) const = 0; virtual bool toBool() const = 0; virtual qint32 toInt32() const = 0; @@ -96,105 +163,7 @@ public: virtual quint32 toUInt32() const = 0; virtual QVariant toVariant() const = 0; virtual QObject* toQObject() const = 0; - -protected: - virtual bool equalsInternal(const ScriptValuePointer& other) const = 0; - virtual bool isArrayInternal() const = 0; - virtual bool isBoolInternal() const = 0; - virtual bool isErrorInternal() const = 0; - virtual bool isFunctionInternal() const = 0; - virtual bool isNumberInternal() const = 0; - virtual bool isNullInternal() const = 0; - virtual bool isObjectInternal() const = 0; - virtual bool isStringInternal() const = 0; - virtual bool isUndefinedInternal() const = 0; - virtual bool isValidInternal() const = 0; - virtual bool isVariantInternal() const = 0; }; -Q_DECLARE_OPERATORS_FOR_FLAGS(ScriptValue::PropertyFlags); - -bool ScriptValue::equals(const ScriptValuePointer& other) const { - if (this == NULL || !other) { - return (this == NULL) == !other; - } - return equalsInternal(other); -} - -bool ScriptValue::isArray() const { - assert(this != NULL); - if (this == NULL) return false; - return isArrayInternal(); -} - -bool ScriptValue::isBool() const { - assert(this != NULL); - if (this == NULL) - return false; - return isBoolInternal(); -} - -bool ScriptValue::isError() const { - assert(this != NULL); - if (this == NULL) - return false; - return isErrorInternal(); -} - -bool ScriptValue::isFunction() const { - assert(this != NULL); - if (this == NULL) - return false; - return isFunctionInternal(); -} - -bool ScriptValue::isNumber() const { - assert(this != NULL); - if (this == NULL) - return false; - return isNumberInternal(); -} - -bool ScriptValue::isNull() const { - assert(this != NULL); - if (this == NULL) - return false; - return isNullInternal(); -} - -bool ScriptValue::isObject() const { - assert(this != NULL); - if (this == NULL) - return false; - return isObjectInternal(); -} - -bool ScriptValue::isString() const { - assert(this != NULL); - if (this == NULL) - return false; - return isStringInternal(); -} - -bool ScriptValue::isUndefined() const { - assert(this != NULL); - if (this == NULL) - return true; - return isUndefinedInternal(); -} - -bool ScriptValue::isValid() const { - assert(this != NULL); - if (this == NULL) - return false; - return isValidInternal(); -} - -bool ScriptValue::isVariant() const { - assert(this != NULL); - if (this == NULL) - return false; - return isVariantInternal(); -} template void ScriptValue::setProperty(const QString& name, const TYP& value, const PropertyFlags& flags) { @@ -206,8 +175,158 @@ void ScriptValue::setProperty(quint32 arrayIndex, const TYP& value, const Proper setProperty(arrayIndex, engine()->newValue(value), flags); } -template -T scriptvalue_cast(const ScriptValuePointer& value); +ScriptValue::ScriptValue(const ScriptValue& src) : _proxy(src.ptr()->copy()) { +} + +ScriptValue::~ScriptValue() { + _proxy->release(); +} + +ScriptValue& ScriptValue::operator=(const ScriptValue& other) { + _proxy->release(); + _proxy = other.ptr()->copy(); + return *this; +} + +ScriptValue ScriptValue::call(const ScriptValue& thisObject, const ScriptValueList& args) const { + return _proxy->call(thisObject, args); +} + +ScriptValue ScriptValue::call(const ScriptValue& thisObject, const ScriptValue& arguments) const { + return _proxy->call(thisObject, arguments); +} + +ScriptValue ScriptValue::construct(const ScriptValueList& args) const { + return _proxy->construct(args); +} + +ScriptValue ScriptValue::construct(const ScriptValue& arguments) const { + return _proxy->construct(arguments); +} + +ScriptValue ScriptValue::data() const { + return _proxy->data(); +} + +ScriptEnginePointer ScriptValue::engine() const { + return _proxy->engine(); +} + +bool ScriptValue::equals(const ScriptValue& other) const { + return _proxy->equals(other); +} + +bool ScriptValue::isArray() const { + return _proxy->isArray(); +} + +bool ScriptValue::isBool() const { + return _proxy->isBool(); +} + +bool ScriptValue::isError() const { + return _proxy->isError(); +} + +bool ScriptValue::isFunction() const { + return _proxy->isFunction(); +} + +bool ScriptValue::isNumber() const { + return _proxy->isNumber(); +} + +bool ScriptValue::isNull() const { + return _proxy->isNull(); +} + +bool ScriptValue::isObject() const { + return _proxy->isObject(); +} + +bool ScriptValue::isString() const { + return _proxy->isString(); +} + +bool ScriptValue::isUndefined() const { + return _proxy->isUndefined(); +} + +bool ScriptValue::isValid() const { + return _proxy->isValid(); +} + +bool ScriptValue::isVariant() const { + return _proxy->isVariant(); +} + +ScriptValueIteratorPointer ScriptValue::newIterator() const { + return _proxy->newIterator(); +} + +ScriptValue ScriptValue::property(const QString& name, const ResolveFlags& mode) const { + return _proxy->property(name, mode); +} + +ScriptValue ScriptValue::property(quint32 arrayIndex, const ResolveFlags& mode) const { + return _proxy->property(arrayIndex, mode); +} + +void ScriptValue::setData(const ScriptValue& val) { + return _proxy->setData(val); +} + +void ScriptValue::setProperty(const QString& name, const ScriptValue& value, const PropertyFlags& flags) { + return _proxy->setProperty(name, value, flags); +} + +void ScriptValue::setProperty(quint32 arrayIndex, const ScriptValue& value, const PropertyFlags& flags) { + return _proxy->setProperty(arrayIndex, value, flags); +} + +void ScriptValue::setPrototype(const ScriptValue& prototype) { + return _proxy->setPrototype(prototype); +} + +bool ScriptValue::strictlyEquals(const ScriptValue& other) const { + return _proxy->strictlyEquals(other); +} + +bool ScriptValue::toBool() const { + return _proxy->toBool(); +} + +qint32 ScriptValue::toInt32() const { + return _proxy->toInt32(); +} + +double ScriptValue::toInteger() const { + return _proxy->toInteger(); +} + +double ScriptValue::toNumber() const { + return _proxy->toNumber(); +} + +QString ScriptValue::toString() const { + return _proxy->toString(); +} + +quint16 ScriptValue::toUInt16() const { + return _proxy->toUInt16(); +} + +quint32 ScriptValue::toUInt32() const { + return _proxy->toUInt32(); +} + +QVariant ScriptValue::toVariant() const { + return _proxy->toVariant(); +} + +QObject* ScriptValue::toQObject() const { + return _proxy->toQObject(); +} #endif // hifi_ScriptValue_h diff --git a/libraries/script-engine/src/ScriptValueIterator.h b/libraries/script-engine/src/ScriptValueIterator.h index 2222a457a8..6b383b8ae5 100644 --- a/libraries/script-engine/src/ScriptValueIterator.h +++ b/libraries/script-engine/src/ScriptValueIterator.h @@ -30,7 +30,7 @@ public: virtual bool hasNext() const = 0; virtual QString name() const = 0; virtual void next() = 0; - virtual ScriptValuePointer value() const = 0; + virtual ScriptValue value() const = 0; }; #endif // hifi_ScriptValueIterator_h diff --git a/libraries/script-engine/src/ScriptValueUtils.cpp b/libraries/script-engine/src/ScriptValueUtils.cpp index 6ee0091e09..d183606e86 100644 --- a/libraries/script-engine/src/ScriptValueUtils.cpp +++ b/libraries/script-engine/src/ScriptValueUtils.cpp @@ -28,19 +28,19 @@ #include "ScriptEngineCast.h" #include "ScriptValueIterator.h" -bool isListOfStrings(const ScriptValuePointer& arg) { - if (!arg->isArray()) { +bool isListOfStrings(const ScriptValue& arg) { + if (!arg.isArray()) { return false; } - auto lengthProperty = arg->property("length"); - if (!lengthProperty->isNumber()) { + auto lengthProperty = arg.property("length"); + if (!lengthProperty.isNumber()) { return false; } - int length = lengthProperty->toInt32(); + int length = lengthProperty.toInt32(); for (int i = 0; i < length; i++) { - if (!arg->property(i)->isString()) { + if (!arg.property(i).isString()) { return false; } } @@ -80,9 +80,9 @@ void registerMetaTypes(ScriptEngine* engine) { scriptRegisterSequenceMetaType>(engine); } -ScriptValuePointer vec2ToScriptValue(ScriptEngine* engine, const glm::vec2& vec2) { - auto prototype = engine->globalObject()->property("__hifi_vec2__"); - if (!prototype->property("defined")->toBool()) { +ScriptValue vec2ToScriptValue(ScriptEngine* engine, const glm::vec2& vec2) { + auto prototype = engine->globalObject().property("__hifi_vec2__"); + if (!prototype.property("defined").toBool()) { prototype = engine->evaluate( "__hifi_vec2__ = Object.defineProperties({}, { " "defined: { value: true }," @@ -92,41 +92,41 @@ ScriptValuePointer vec2ToScriptValue(ScriptEngine* engine, const glm::vec2& vec2 "v: { set: function(nv) { return this.y = nv; }, get: function() { return this.y; } }" "})"); } - ScriptValuePointer value = engine->newObject(); - value->setProperty("x", vec2.x); - value->setProperty("y", vec2.y); - value->setPrototype(prototype); + ScriptValue value = engine->newObject(); + value.setProperty("x", vec2.x); + value.setProperty("y", vec2.y); + value.setPrototype(prototype); return value; } -void vec2FromScriptValue(const ScriptValuePointer& object, glm::vec2& vec2) { - if (object->isNumber()) { - vec2 = glm::vec2(object->toVariant().toFloat()); - } else if (object->isArray()) { - QVariantList list = object->toVariant().toList(); +void vec2FromScriptValue(const ScriptValue& object, glm::vec2& vec2) { + if (object.isNumber()) { + vec2 = glm::vec2(object.toVariant().toFloat()); + } else if (object.isArray()) { + QVariantList list = object.toVariant().toList(); if (list.length() == 2) { vec2.x = list[0].toFloat(); vec2.y = list[1].toFloat(); } } else { - ScriptValuePointer x = object->property("x"); - if (!x->isValid()) { - x = object->property("u"); + ScriptValue x = object.property("x"); + if (!x.isValid()) { + x = object.property("u"); } - ScriptValuePointer y = object->property("y"); - if (!y->isValid()) { - y = object->property("v"); + ScriptValue y = object.property("y"); + if (!y.isValid()) { + y = object.property("v"); } - vec2.x = x->toVariant().toFloat(); - vec2.y = y->toVariant().toFloat(); + vec2.x = x.toVariant().toFloat(); + vec2.y = y.toVariant().toFloat(); } } -ScriptValuePointer vec3ToScriptValue(ScriptEngine* engine, const glm::vec3& vec3) { - auto prototype = engine->globalObject()->property("__hifi_vec3__"); - if (!prototype->property("defined")->toBool()) { +ScriptValue vec3ToScriptValue(ScriptEngine* engine, const glm::vec3& vec3) { + auto prototype = engine->globalObject().property("__hifi_vec3__"); + if (!prototype.property("defined").toBool()) { prototype = engine->evaluate( "__hifi_vec3__ = Object.defineProperties({}, { " "defined: { value: true }," @@ -141,17 +141,17 @@ ScriptValuePointer vec3ToScriptValue(ScriptEngine* engine, const glm::vec3& vec3 "blue: { set: function(nv) { return this.z = nv; }, get: function() { return this.z; } }" "})"); } - ScriptValuePointer value = engine->newObject(); - value->setProperty("x", vec3.x); - value->setProperty("y", vec3.y); - value->setProperty("z", vec3.z); - value->setPrototype(prototype); + ScriptValue value = engine->newObject(); + value.setProperty("x", vec3.x); + value.setProperty("y", vec3.y); + value.setProperty("z", vec3.z); + value.setPrototype(prototype); return value; } -ScriptValuePointer vec3ColorToScriptValue(ScriptEngine* engine, const glm::vec3& vec3) { - auto prototype = engine->globalObject()->property("__hifi_vec3_color__"); - if (!prototype->property("defined")->toBool()) { +ScriptValue vec3ColorToScriptValue(ScriptEngine* engine, const glm::vec3& vec3) { + auto prototype = engine->globalObject().property("__hifi_vec3_color__"); + if (!prototype.property("defined").toBool()) { prototype = engine->evaluate( "__hifi_vec3_color__ = Object.defineProperties({}, { " "defined: { value: true }," @@ -166,65 +166,65 @@ ScriptValuePointer vec3ColorToScriptValue(ScriptEngine* engine, const glm::vec3& "z: { set: function(nv) { return this.blue = nv; }, get: function() { return this.blue; } }" "})"); } - ScriptValuePointer value = engine->newObject(); - value->setProperty("red", vec3.x); - value->setProperty("green", vec3.y); - value->setProperty("blue", vec3.z); - value->setPrototype(prototype); + ScriptValue value = engine->newObject(); + value.setProperty("red", vec3.x); + value.setProperty("green", vec3.y); + value.setProperty("blue", vec3.z); + value.setPrototype(prototype); return value; } -void vec3FromScriptValue(const ScriptValuePointer& object, glm::vec3& vec3) { - if (object->isNumber()) { - vec3 = glm::vec3(object->toVariant().toFloat()); - } else if (object->isString()) { - QColor qColor(object->toString()); +void vec3FromScriptValue(const ScriptValue& object, glm::vec3& vec3) { + if (object.isNumber()) { + vec3 = glm::vec3(object.toVariant().toFloat()); + } else if (object.isString()) { + QColor qColor(object.toString()); if (qColor.isValid()) { vec3.x = qColor.red(); vec3.y = qColor.green(); vec3.z = qColor.blue(); } - } else if (object->isArray()) { - QVariantList list = object->toVariant().toList(); + } else if (object.isArray()) { + QVariantList list = object.toVariant().toList(); if (list.length() == 3) { vec3.x = list[0].toFloat(); vec3.y = list[1].toFloat(); vec3.z = list[2].toFloat(); } } else { - ScriptValuePointer x = object->property("x"); - if (!x->isValid()) { - x = object->property("r"); + ScriptValue x = object.property("x"); + if (!x.isValid()) { + x = object.property("r"); } - if (!x->isValid()) { - x = object->property("red"); + if (!x.isValid()) { + x = object.property("red"); } - ScriptValuePointer y = object->property("y"); - if (!y->isValid()) { - y = object->property("g"); + ScriptValue y = object.property("y"); + if (!y.isValid()) { + y = object.property("g"); } - if (!y->isValid()) { - y = object->property("green"); + if (!y.isValid()) { + y = object.property("green"); } - ScriptValuePointer z = object->property("z"); - if (!z->isValid()) { - z = object->property("b"); + ScriptValue z = object.property("z"); + if (!z.isValid()) { + z = object.property("b"); } - if (!z->isValid()) { - z = object->property("blue"); + if (!z.isValid()) { + z = object.property("blue"); } - vec3.x = x->toVariant().toFloat(); - vec3.y = y->toVariant().toFloat(); - vec3.z = z->toVariant().toFloat(); + vec3.x = x.toVariant().toFloat(); + vec3.y = y.toVariant().toFloat(); + vec3.z = z.toVariant().toFloat(); } } -ScriptValuePointer u8vec3ToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3) { - auto prototype = engine->globalObject()->property("__hifi_u8vec3__"); - if (!prototype->property("defined")->toBool()) { +ScriptValue u8vec3ToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3) { + auto prototype = engine->globalObject().property("__hifi_u8vec3__"); + if (!prototype.property("defined").toBool()) { prototype = engine->evaluate( "__hifi_u8vec3__ = Object.defineProperties({}, { " "defined: { value: true }," @@ -239,17 +239,17 @@ ScriptValuePointer u8vec3ToScriptValue(ScriptEngine* engine, const glm::u8vec3& "blue: { set: function(nv) { return this.z = nv; }, get: function() { return this.z; } }" "})"); } - ScriptValuePointer value = engine->newObject(); - value->setProperty("x", vec3.x); - value->setProperty("y", vec3.y); - value->setProperty("z", vec3.z); - value->setPrototype(prototype); + ScriptValue value = engine->newObject(); + value.setProperty("x", vec3.x); + value.setProperty("y", vec3.y); + value.setProperty("z", vec3.z); + value.setPrototype(prototype); return value; } -ScriptValuePointer u8vec3ColorToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3) { - auto prototype = engine->globalObject()->property("__hifi_u8vec3_color__"); - if (!prototype->property("defined")->toBool()) { +ScriptValue u8vec3ColorToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3) { + auto prototype = engine->globalObject().property("__hifi_u8vec3_color__"); + if (!prototype.property("defined").toBool()) { prototype = engine->evaluate( "__hifi_u8vec3_color__ = Object.defineProperties({}, { " "defined: { value: true }," @@ -264,174 +264,174 @@ ScriptValuePointer u8vec3ColorToScriptValue(ScriptEngine* engine, const glm::u8v "z: { set: function(nv) { return this.blue = nv; }, get: function() { return this.blue; } }" "})"); } - ScriptValuePointer value = engine->newObject(); - value->setProperty("red", vec3.x); - value->setProperty("green", vec3.y); - value->setProperty("blue", vec3.z); - value->setPrototype(prototype); + ScriptValue value = engine->newObject(); + value.setProperty("red", vec3.x); + value.setProperty("green", vec3.y); + value.setProperty("blue", vec3.z); + value.setPrototype(prototype); return value; } -void u8vec3FromScriptValue(const ScriptValuePointer& object, glm::u8vec3& vec3) { - if (object->isNumber()) { - vec3 = glm::vec3(object->toVariant().toUInt()); - } else if (object->isString()) { - QColor qColor(object->toString()); +void u8vec3FromScriptValue(const ScriptValue& object, glm::u8vec3& vec3) { + if (object.isNumber()) { + vec3 = glm::vec3(object.toVariant().toUInt()); + } else if (object.isString()) { + QColor qColor(object.toString()); if (qColor.isValid()) { vec3.x = (uint8_t)qColor.red(); vec3.y = (uint8_t)qColor.green(); vec3.z = (uint8_t)qColor.blue(); } - } else if (object->isArray()) { - QVariantList list = object->toVariant().toList(); + } else if (object.isArray()) { + QVariantList list = object.toVariant().toList(); if (list.length() == 3) { vec3.x = list[0].toUInt(); vec3.y = list[1].toUInt(); vec3.z = list[2].toUInt(); } } else { - ScriptValuePointer x = object->property("x"); - if (!x->isValid()) { - x = object->property("r"); + ScriptValue x = object.property("x"); + if (!x.isValid()) { + x = object.property("r"); } - if (!x->isValid()) { - x = object->property("red"); + if (!x.isValid()) { + x = object.property("red"); } - ScriptValuePointer y = object->property("y"); - if (!y->isValid()) { - y = object->property("g"); + ScriptValue y = object.property("y"); + if (!y.isValid()) { + y = object.property("g"); } - if (!y->isValid()) { - y = object->property("green"); + if (!y.isValid()) { + y = object.property("green"); } - ScriptValuePointer z = object->property("z"); - if (!z->isValid()) { - z = object->property("b"); + ScriptValue z = object.property("z"); + if (!z.isValid()) { + z = object.property("b"); } - if (!z->isValid()) { - z = object->property("blue"); + if (!z.isValid()) { + z = object.property("blue"); } - vec3.x = x->toVariant().toUInt(); - vec3.y = y->toVariant().toUInt(); - vec3.z = z->toVariant().toUInt(); + vec3.x = x.toVariant().toUInt(); + vec3.y = y.toVariant().toUInt(); + vec3.z = z.toVariant().toUInt(); } } -ScriptValuePointer vec4toScriptValue(ScriptEngine* engine, const glm::vec4& vec4) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("x", vec4.x); - obj->setProperty("y", vec4.y); - obj->setProperty("z", vec4.z); - obj->setProperty("w", vec4.w); +ScriptValue vec4toScriptValue(ScriptEngine* engine, const glm::vec4& vec4) { + ScriptValue obj = engine->newObject(); + obj.setProperty("x", vec4.x); + obj.setProperty("y", vec4.y); + obj.setProperty("z", vec4.z); + obj.setProperty("w", vec4.w); return obj; } -void vec4FromScriptValue(const ScriptValuePointer& 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(); +void vec4FromScriptValue(const ScriptValue& 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(); } -ScriptValuePointer mat4toScriptValue(ScriptEngine* engine, const glm::mat4& mat4) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("r0c0", mat4[0][0]); - obj->setProperty("r1c0", mat4[0][1]); - obj->setProperty("r2c0", mat4[0][2]); - obj->setProperty("r3c0", mat4[0][3]); - obj->setProperty("r0c1", mat4[1][0]); - obj->setProperty("r1c1", mat4[1][1]); - obj->setProperty("r2c1", mat4[1][2]); - obj->setProperty("r3c1", mat4[1][3]); - obj->setProperty("r0c2", mat4[2][0]); - obj->setProperty("r1c2", mat4[2][1]); - obj->setProperty("r2c2", mat4[2][2]); - obj->setProperty("r3c2", mat4[2][3]); - obj->setProperty("r0c3", mat4[3][0]); - obj->setProperty("r1c3", mat4[3][1]); - obj->setProperty("r2c3", mat4[3][2]); - obj->setProperty("r3c3", mat4[3][3]); +ScriptValue mat4toScriptValue(ScriptEngine* engine, const glm::mat4& mat4) { + ScriptValue obj = engine->newObject(); + obj.setProperty("r0c0", mat4[0][0]); + obj.setProperty("r1c0", mat4[0][1]); + obj.setProperty("r2c0", mat4[0][2]); + obj.setProperty("r3c0", mat4[0][3]); + obj.setProperty("r0c1", mat4[1][0]); + obj.setProperty("r1c1", mat4[1][1]); + obj.setProperty("r2c1", mat4[1][2]); + obj.setProperty("r3c1", mat4[1][3]); + obj.setProperty("r0c2", mat4[2][0]); + obj.setProperty("r1c2", mat4[2][1]); + obj.setProperty("r2c2", mat4[2][2]); + obj.setProperty("r3c2", mat4[2][3]); + obj.setProperty("r0c3", mat4[3][0]); + obj.setProperty("r1c3", mat4[3][1]); + obj.setProperty("r2c3", mat4[3][2]); + obj.setProperty("r3c3", mat4[3][3]); return obj; } -void mat4FromScriptValue(const ScriptValuePointer& object, glm::mat4& mat4) { - mat4[0][0] = object->property("r0c0")->toVariant().toFloat(); - mat4[0][1] = object->property("r1c0")->toVariant().toFloat(); - mat4[0][2] = object->property("r2c0")->toVariant().toFloat(); - mat4[0][3] = object->property("r3c0")->toVariant().toFloat(); - mat4[1][0] = object->property("r0c1")->toVariant().toFloat(); - mat4[1][1] = object->property("r1c1")->toVariant().toFloat(); - mat4[1][2] = object->property("r2c1")->toVariant().toFloat(); - mat4[1][3] = object->property("r3c1")->toVariant().toFloat(); - mat4[2][0] = object->property("r0c2")->toVariant().toFloat(); - mat4[2][1] = object->property("r1c2")->toVariant().toFloat(); - mat4[2][2] = object->property("r2c2")->toVariant().toFloat(); - mat4[2][3] = object->property("r3c2")->toVariant().toFloat(); - mat4[3][0] = object->property("r0c3")->toVariant().toFloat(); - mat4[3][1] = object->property("r1c3")->toVariant().toFloat(); - mat4[3][2] = object->property("r2c3")->toVariant().toFloat(); - mat4[3][3] = object->property("r3c3")->toVariant().toFloat(); +void mat4FromScriptValue(const ScriptValue& object, glm::mat4& mat4) { + mat4[0][0] = object.property("r0c0").toVariant().toFloat(); + mat4[0][1] = object.property("r1c0").toVariant().toFloat(); + mat4[0][2] = object.property("r2c0").toVariant().toFloat(); + mat4[0][3] = object.property("r3c0").toVariant().toFloat(); + mat4[1][0] = object.property("r0c1").toVariant().toFloat(); + mat4[1][1] = object.property("r1c1").toVariant().toFloat(); + mat4[1][2] = object.property("r2c1").toVariant().toFloat(); + mat4[1][3] = object.property("r3c1").toVariant().toFloat(); + mat4[2][0] = object.property("r0c2").toVariant().toFloat(); + mat4[2][1] = object.property("r1c2").toVariant().toFloat(); + mat4[2][2] = object.property("r2c2").toVariant().toFloat(); + mat4[2][3] = object.property("r3c2").toVariant().toFloat(); + mat4[3][0] = object.property("r0c3").toVariant().toFloat(); + mat4[3][1] = object.property("r1c3").toVariant().toFloat(); + mat4[3][2] = object.property("r2c3").toVariant().toFloat(); + mat4[3][3] = object.property("r3c3").toVariant().toFloat(); } -ScriptValuePointer qVectorVec3ColorToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorVec3ColorToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { - array->setProperty(i, vec3ColorToScriptValue(engine, vector.at(i))); + array.setProperty(i, vec3ColorToScriptValue(engine, vector.at(i))); } return array; } -ScriptValuePointer qVectorVec3ToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorVec3ToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { - array->setProperty(i, vec3ToScriptValue(engine, vector.at(i))); + array.setProperty(i, vec3ToScriptValue(engine, vector.at(i))); } return array; } -QVector qVectorVec3FromScriptValue(const ScriptValuePointer& array) { +QVector qVectorVec3FromScriptValue(const ScriptValue& array) { QVector newVector; - int length = array->property("length")->toInteger(); + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { glm::vec3 newVec3 = glm::vec3(); - vec3FromScriptValue(array->property(i), newVec3); + vec3FromScriptValue(array.property(i), newVec3); newVector << newVec3; } return newVector; } -void qVectorVec3FromScriptValue(const ScriptValuePointer& array, QVector& vector) { - int length = array->property("length")->toInteger(); +void qVectorVec3FromScriptValue(const ScriptValue& array, QVector& vector) { + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { glm::vec3 newVec3 = glm::vec3(); - vec3FromScriptValue(array->property(i), newVec3); + vec3FromScriptValue(array.property(i), newVec3); vector << newVec3; } } -ScriptValuePointer quatToScriptValue(ScriptEngine* engine, const glm::quat& quat) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue quatToScriptValue(ScriptEngine* engine, const glm::quat& quat) { + ScriptValue obj = engine->newObject(); if (quat.x != quat.x || quat.y != quat.y || quat.z != quat.z || quat.w != quat.w) { // if quat contains a NaN don't try to convert it return obj; } - obj->setProperty("x", quat.x); - obj->setProperty("y", quat.y); - obj->setProperty("z", quat.z); - obj->setProperty("w", quat.w); + obj.setProperty("x", quat.x); + obj.setProperty("y", quat.y); + obj.setProperty("z", quat.z); + obj.setProperty("w", quat.w); return obj; } -void quatFromScriptValue(const ScriptValuePointer& 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(); +void quatFromScriptValue(const ScriptValue& 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(); // enforce normalized quaternion float length = glm::length(quat); @@ -442,181 +442,181 @@ void quatFromScriptValue(const ScriptValuePointer& object, glm::quat& quat) { } } -ScriptValuePointer qVectorQuatToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorQuatToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { - array->setProperty(i, quatToScriptValue(engine, vector.at(i))); + array.setProperty(i, quatToScriptValue(engine, vector.at(i))); } return array; } -ScriptValuePointer qVectorBoolToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorBoolToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { - array->setProperty(i, vector.at(i)); + array.setProperty(i, vector.at(i)); } return array; } -QVector qVectorFloatFromScriptValue(const ScriptValuePointer& array) { - if (!array->isArray()) { +QVector qVectorFloatFromScriptValue(const ScriptValue& array) { + if (!array.isArray()) { return QVector(); } QVector newVector; - int length = array->property("length")->toInteger(); + int length = array.property("length").toInteger(); newVector.reserve(length); for (int i = 0; i < length; i++) { - if (array->property(i)->isNumber()) { - newVector << array->property(i)->toNumber(); + if (array.property(i).isNumber()) { + newVector << array.property(i).toNumber(); } } return newVector; } -ScriptValuePointer qVectorQUuidToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorQUuidToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { - array->setProperty(i, quuidToScriptValue(engine, vector.at(i))); + array.setProperty(i, quuidToScriptValue(engine, vector.at(i))); } return array; } -void qVectorQUuidFromScriptValue(const ScriptValuePointer& array, QVector& vector) { - int length = array->property("length")->toInteger(); +void qVectorQUuidFromScriptValue(const ScriptValue& array, QVector& vector) { + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { - vector << array->property(i)->toVariant().toUuid(); + vector << array.property(i).toVariant().toUuid(); } } -QVector qVectorQUuidFromScriptValue(const ScriptValuePointer& array) { - if (!array->isArray()) { +QVector qVectorQUuidFromScriptValue(const ScriptValue& array) { + if (!array.isArray()) { return QVector(); } QVector newVector; - int length = array->property("length")->toInteger(); + int length = array.property("length").toInteger(); newVector.reserve(length); for (int i = 0; i < length; i++) { - QString uuidAsString = array->property(i)->toString(); + QString uuidAsString = array.property(i).toString(); QUuid fromString(uuidAsString); newVector << fromString; } return newVector; } -ScriptValuePointer qVectorFloatToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorFloatToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { float num = vector.at(i); - array->setProperty(i, engine->newValue(num)); + array.setProperty(i, engine->newValue(num)); } return array; } -ScriptValuePointer qVectorIntToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorIntToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { int num = vector.at(i); - array->setProperty(i, engine->newValue(num)); + array.setProperty(i, engine->newValue(num)); } return array; } -void qVectorFloatFromScriptValue(const ScriptValuePointer& array, QVector& vector) { - int length = array->property("length")->toInteger(); +void qVectorFloatFromScriptValue(const ScriptValue& array, QVector& vector) { + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { - vector << array->property(i)->toVariant().toFloat(); + vector << array.property(i).toVariant().toFloat(); } } -void qVectorIntFromScriptValue(const ScriptValuePointer& array, QVector& vector) { - int length = array->property("length")->toInteger(); +void qVectorIntFromScriptValue(const ScriptValue& array, QVector& vector) { + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { - vector << array->property(i)->toVariant().toInt(); + vector << array.property(i).toVariant().toInt(); } } -QVector qVectorQuatFromScriptValue(const ScriptValuePointer& array) { +QVector qVectorQuatFromScriptValue(const ScriptValue& array) { QVector newVector; - int length = array->property("length")->toInteger(); + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { glm::quat newQuat = glm::quat(); - quatFromScriptValue(array->property(i), newQuat); + quatFromScriptValue(array.property(i), newQuat); newVector << newQuat; } return newVector; } -void qVectorQuatFromScriptValue(const ScriptValuePointer& array, QVector& vector) { - int length = array->property("length")->toInteger(); +void qVectorQuatFromScriptValue(const ScriptValue& array, QVector& vector) { + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { glm::quat newQuat = glm::quat(); - quatFromScriptValue(array->property(i), newQuat); + quatFromScriptValue(array.property(i), newQuat); vector << newQuat; } } -QVector qVectorBoolFromScriptValue(const ScriptValuePointer& array) { +QVector qVectorBoolFromScriptValue(const ScriptValue& array) { QVector newVector; - int length = array->property("length")->toInteger(); + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { - newVector << array->property(i)->toBool(); + newVector << array.property(i).toBool(); } return newVector; } -void qVectorBoolFromScriptValue(const ScriptValuePointer& array, QVector& vector) { - int length = array->property("length")->toInteger(); +void qVectorBoolFromScriptValue(const ScriptValue& array, QVector& vector) { + int length = array.property("length").toInteger(); for (int i = 0; i < length; i++) { - vector << array->property(i)->toBool(); + vector << array.property(i).toBool(); } } -ScriptValuePointer qRectToScriptValue(ScriptEngine* engine, const QRect& rect) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("x", rect.x()); - obj->setProperty("y", rect.y()); - obj->setProperty("width", rect.width()); - obj->setProperty("height", rect.height()); +ScriptValue qRectToScriptValue(ScriptEngine* engine, const QRect& rect) { + ScriptValue obj = engine->newObject(); + obj.setProperty("x", rect.x()); + obj.setProperty("y", rect.y()); + obj.setProperty("width", rect.width()); + obj.setProperty("height", rect.height()); return obj; } -void qRectFromScriptValue(const ScriptValuePointer& 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()); +void qRectFromScriptValue(const ScriptValue& 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()); } -ScriptValuePointer qRectFToScriptValue(ScriptEngine* engine, const QRectF& rect) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("x", rect.x()); - obj->setProperty("y", rect.y()); - obj->setProperty("width", rect.width()); - obj->setProperty("height", rect.height()); +ScriptValue qRectFToScriptValue(ScriptEngine* engine, const QRectF& rect) { + ScriptValue obj = engine->newObject(); + obj.setProperty("x", rect.x()); + obj.setProperty("y", rect.y()); + obj.setProperty("width", rect.width()); + obj.setProperty("height", rect.height()); return obj; } -void qRectFFromScriptValue(const ScriptValuePointer& object, QRectF& rect) { - rect.setX(object->property("x")->toVariant().toFloat()); - rect.setY(object->property("y")->toVariant().toFloat()); - rect.setWidth(object->property("width")->toVariant().toFloat()); - rect.setHeight(object->property("height")->toVariant().toFloat()); +void qRectFFromScriptValue(const ScriptValue& object, QRectF& rect) { + rect.setX(object.property("x").toVariant().toFloat()); + rect.setY(object.property("y").toVariant().toFloat()); + rect.setWidth(object.property("width").toVariant().toFloat()); + rect.setHeight(object.property("height").toVariant().toFloat()); } -ScriptValuePointer qColorToScriptValue(ScriptEngine* engine, const QColor& color) { - ScriptValuePointer object = engine->newObject(); - object->setProperty("red", color.red()); - object->setProperty("green", color.green()); - object->setProperty("blue", color.blue()); - object->setProperty("alpha", color.alpha()); +ScriptValue qColorToScriptValue(ScriptEngine* engine, const QColor& color) { + ScriptValue object = engine->newObject(); + object.setProperty("red", color.red()); + object.setProperty("green", color.green()); + object.setProperty("blue", color.blue()); + object.setProperty("alpha", color.alpha()); return object; } @@ -629,78 +629,78 @@ ScriptValuePointer qColorToScriptValue(ScriptEngine* engine, const QColor& color * @property {number} z - Z coordinate of the brn corner of the cube. * @property {number} scale - The dimensions of each side of the cube. */ -ScriptValuePointer aaCubeToScriptValue(ScriptEngine* engine, const AACube& aaCube) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue aaCubeToScriptValue(ScriptEngine* engine, const AACube& aaCube) { + ScriptValue obj = engine->newObject(); const glm::vec3& corner = aaCube.getCorner(); - obj->setProperty("x", corner.x); - obj->setProperty("y", corner.y); - obj->setProperty("z", corner.z); - obj->setProperty("scale", aaCube.getScale()); + obj.setProperty("x", corner.x); + obj.setProperty("y", corner.y); + obj.setProperty("z", corner.z); + obj.setProperty("scale", aaCube.getScale()); return obj; } -void aaCubeFromScriptValue(const ScriptValuePointer& object, AACube& aaCube) { +void aaCubeFromScriptValue(const ScriptValue& object, AACube& aaCube) { glm::vec3 corner; - corner.x = object->property("x")->toVariant().toFloat(); - corner.y = object->property("y")->toVariant().toFloat(); - corner.z = object->property("z")->toVariant().toFloat(); - float scale = object->property("scale")->toVariant().toFloat(); + corner.x = object.property("x").toVariant().toFloat(); + corner.y = object.property("y").toVariant().toFloat(); + corner.z = object.property("z").toVariant().toFloat(); + float scale = object.property("scale").toVariant().toFloat(); aaCube.setBox(corner, scale); } -void qColorFromScriptValue(const ScriptValuePointer& object, QColor& color) { - if (object->isNumber()) { - color.setRgb(object->toUInt32()); +void qColorFromScriptValue(const ScriptValue& object, QColor& color) { + if (object.isNumber()) { + color.setRgb(object.toUInt32()); - } else if (object->isString()) { - color.setNamedColor(object->toString()); + } else if (object.isString()) { + color.setNamedColor(object.toString()); } else { - ScriptValuePointer alphaValue = object->property("alpha"); - color.setRgb(object->property("red")->toInt32(), object->property("green")->toInt32(), object->property("blue")->toInt32(), - alphaValue->isNumber() ? alphaValue->toInt32() : 255); + ScriptValue alphaValue = object.property("alpha"); + color.setRgb(object.property("red").toInt32(), object.property("green").toInt32(), object.property("blue").toInt32(), + alphaValue.isNumber() ? alphaValue.toInt32() : 255); } } -ScriptValuePointer qURLToScriptValue(ScriptEngine* engine, const QUrl& url) { +ScriptValue qURLToScriptValue(ScriptEngine* engine, const QUrl& url) { return engine->newValue(url.toString()); } -void qURLFromScriptValue(const ScriptValuePointer& object, QUrl& url) { - url = object->toString(); +void qURLFromScriptValue(const ScriptValue& object, QUrl& url) { + url = object.toString(); } -ScriptValuePointer pickRayToScriptValue(ScriptEngine* engine, const PickRay& pickRay) { - ScriptValuePointer obj = engine->newObject(); - ScriptValuePointer origin = vec3ToScriptValue(engine, pickRay.origin); - obj->setProperty("origin", origin); - ScriptValuePointer direction = vec3ToScriptValue(engine, pickRay.direction); - obj->setProperty("direction", direction); +ScriptValue pickRayToScriptValue(ScriptEngine* engine, const PickRay& pickRay) { + ScriptValue obj = engine->newObject(); + ScriptValue origin = vec3ToScriptValue(engine, pickRay.origin); + obj.setProperty("origin", origin); + ScriptValue direction = vec3ToScriptValue(engine, pickRay.direction); + obj.setProperty("direction", direction); return obj; } -void pickRayFromScriptValue(const ScriptValuePointer& object, PickRay& pickRay) { - ScriptValuePointer originValue = object->property("origin"); - if (originValue->isValid()) { - auto x = originValue->property("x"); - auto y = originValue->property("y"); - auto z = originValue->property("z"); - if (x->isValid() && y->isValid() && z->isValid()) { - pickRay.origin.x = x->toVariant().toFloat(); - pickRay.origin.y = y->toVariant().toFloat(); - pickRay.origin.z = z->toVariant().toFloat(); +void pickRayFromScriptValue(const ScriptValue& object, PickRay& pickRay) { + ScriptValue originValue = object.property("origin"); + if (originValue.isValid()) { + auto x = originValue.property("x"); + auto y = originValue.property("y"); + auto z = originValue.property("z"); + if (x.isValid() && y.isValid() && z.isValid()) { + pickRay.origin.x = x.toVariant().toFloat(); + pickRay.origin.y = y.toVariant().toFloat(); + pickRay.origin.z = z.toVariant().toFloat(); } } - ScriptValuePointer directionValue = object->property("direction"); - if (directionValue->isValid()) { - auto x = directionValue->property("x"); - auto y = directionValue->property("y"); - auto z = directionValue->property("z"); - if (x->isValid() && y->isValid() && z->isValid()) { - pickRay.direction.x = x->toVariant().toFloat(); - pickRay.direction.y = y->toVariant().toFloat(); - pickRay.direction.z = z->toVariant().toFloat(); + ScriptValue directionValue = object.property("direction"); + if (directionValue.isValid()) { + auto x = directionValue.property("x"); + auto y = directionValue.property("y"); + auto z = directionValue.property("z"); + if (x.isValid() && y.isValid() && z.isValid()) { + pickRay.direction.x = x.toVariant().toFloat(); + pickRay.direction.y = y.toVariant().toFloat(); + pickRay.direction.z = z.toVariant().toFloat(); } } } @@ -715,35 +715,35 @@ void pickRayFromScriptValue(const ScriptValuePointer& object, PickRay& pickRay) * @property {Vec3} contactPoint - The point of contact. * @property {Vec3} velocityChange - The change in relative velocity of the two items, in m/s. */ -ScriptValuePointer collisionToScriptValue(ScriptEngine* engine, const Collision& collision) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("type", collision.type); - obj->setProperty("idA", quuidToScriptValue(engine, collision.idA)); - obj->setProperty("idB", quuidToScriptValue(engine, collision.idB)); - obj->setProperty("penetration", vec3ToScriptValue(engine, collision.penetration)); - obj->setProperty("contactPoint", vec3ToScriptValue(engine, collision.contactPoint)); - obj->setProperty("velocityChange", vec3ToScriptValue(engine, collision.velocityChange)); +ScriptValue collisionToScriptValue(ScriptEngine* engine, const Collision& collision) { + ScriptValue obj = engine->newObject(); + obj.setProperty("type", collision.type); + obj.setProperty("idA", quuidToScriptValue(engine, collision.idA)); + obj.setProperty("idB", quuidToScriptValue(engine, collision.idB)); + obj.setProperty("penetration", vec3ToScriptValue(engine, collision.penetration)); + obj.setProperty("contactPoint", vec3ToScriptValue(engine, collision.contactPoint)); + obj.setProperty("velocityChange", vec3ToScriptValue(engine, collision.velocityChange)); return obj; } -void collisionFromScriptValue(const ScriptValuePointer& object, Collision& collision) { +void collisionFromScriptValue(const ScriptValue& object, Collision& collision) { // TODO: implement this when we know what it means to accept collision events from JS } -ScriptValuePointer quuidToScriptValue(ScriptEngine* engine, const QUuid& uuid) { +ScriptValue quuidToScriptValue(ScriptEngine* engine, const QUuid& uuid) { if (uuid.isNull()) { return engine->nullValue(); } - ScriptValuePointer obj(engine->newValue(uuid.toString())); + ScriptValue obj(engine->newValue(uuid.toString())); return obj; } -void quuidFromScriptValue(const ScriptValuePointer& object, QUuid& uuid) { +void quuidFromScriptValue(const ScriptValue& object, QUuid& uuid) { if (object.isNull()) { uuid = QUuid(); return; } - QString uuidAsString = object->toVariant().toString(); + QString uuidAsString = object.toVariant().toString(); QUuid fromString(uuidAsString); uuid = fromString; } @@ -754,16 +754,16 @@ void quuidFromScriptValue(const ScriptValuePointer& object, QUuid& uuid) { * @property {number} height - The height value. * @property {number} width - The width value. */ -ScriptValuePointer qSizeFToScriptValue(ScriptEngine* engine, const QSizeF& qSizeF) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("width", qSizeF.width()); - obj->setProperty("height", qSizeF.height()); +ScriptValue qSizeFToScriptValue(ScriptEngine* engine, const QSizeF& qSizeF) { + ScriptValue obj = engine->newObject(); + obj.setProperty("width", qSizeF.width()); + obj.setProperty("height", qSizeF.height()); return obj; } -void qSizeFFromScriptValue(const ScriptValuePointer& object, QSizeF& qSizeF) { - qSizeF.setWidth(object->property("width")->toVariant().toFloat()); - qSizeF.setHeight(object->property("height")->toVariant().toFloat()); +void qSizeFFromScriptValue(const ScriptValue& object, QSizeF& qSizeF) { + qSizeF.setWidth(object.property("width").toVariant().toFloat()); + qSizeF.setHeight(object.property("height").toVariant().toFloat()); } /**jsdoc @@ -785,47 +785,47 @@ void qSizeFFromScriptValue(const ScriptValuePointer& object, QSizeF& qSizeF) { * @property {boolean} startAutomatically - Not used. * @property {boolean} allowTranslation - Not used. */ -ScriptValuePointer animationDetailsToScriptValue(ScriptEngine* engine, const AnimationDetails& details) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("role", details.role); - obj->setProperty("url", details.url.toString()); - obj->setProperty("fps", details.fps); - obj->setProperty("priority", details.priority); - obj->setProperty("loop", details.loop); - obj->setProperty("hold", details.hold); - obj->setProperty("startAutomatically", details.startAutomatically); - obj->setProperty("firstFrame", details.firstFrame); - obj->setProperty("lastFrame", details.lastFrame); - obj->setProperty("running", details.running); - obj->setProperty("currentFrame", details.currentFrame); - obj->setProperty("allowTranslation", details.allowTranslation); +ScriptValue animationDetailsToScriptValue(ScriptEngine* engine, const AnimationDetails& details) { + ScriptValue obj = engine->newObject(); + obj.setProperty("role", details.role); + obj.setProperty("url", details.url.toString()); + obj.setProperty("fps", details.fps); + obj.setProperty("priority", details.priority); + obj.setProperty("loop", details.loop); + obj.setProperty("hold", details.hold); + obj.setProperty("startAutomatically", details.startAutomatically); + obj.setProperty("firstFrame", details.firstFrame); + obj.setProperty("lastFrame", details.lastFrame); + obj.setProperty("running", details.running); + obj.setProperty("currentFrame", details.currentFrame); + obj.setProperty("allowTranslation", details.allowTranslation); return obj; } -void animationDetailsFromScriptValue(const ScriptValuePointer& object, AnimationDetails& details) { +void animationDetailsFromScriptValue(const ScriptValue& object, AnimationDetails& details) { // nothing for now... } -ScriptValuePointer meshToScriptValue(ScriptEngine* engine, MeshProxy* const& in) { +ScriptValue meshToScriptValue(ScriptEngine* engine, MeshProxy* const& in) { return engine->newQObject(in, ScriptEngine::QtOwnership); } -void meshFromScriptValue(const ScriptValuePointer& value, MeshProxy*& out) { - out = qobject_cast(value->toQObject()); +void meshFromScriptValue(const ScriptValue& value, MeshProxy*& out) { + out = qobject_cast(value.toQObject()); } -ScriptValuePointer meshesToScriptValue(ScriptEngine* engine, const MeshProxyList& in) { +ScriptValue meshesToScriptValue(ScriptEngine* engine, const MeshProxyList& in) { // ScriptValueList result; - ScriptValuePointer result = engine->newArray(); + ScriptValue result = engine->newArray(); int i = 0; - foreach (MeshProxy* const meshProxy, in) { result->setProperty(i++, meshToScriptValue(engine, meshProxy)); } + foreach (MeshProxy* const meshProxy, in) { result.setProperty(i++, meshToScriptValue(engine, meshProxy)); } return result; } -void meshesFromScriptValue(const ScriptValuePointer& value, MeshProxyList& out) { - ScriptValueIteratorPointer itr(value->newIterator()); +void meshesFromScriptValue(const ScriptValue& value, MeshProxyList& out) { + ScriptValueIteratorPointer itr(value.newIterator()); - qDebug() << "in meshesFromScriptValue, value.length =" << value->property("length")->toInt32(); + qDebug() << "in meshesFromScriptValue, value.length =" << value.property("length").toInt32(); while (itr->hasNext()) { itr->next(); @@ -843,67 +843,67 @@ void meshesFromScriptValue(const ScriptValuePointer& value, MeshProxyList& out) * @typedef {object} MeshFace * @property {number[]} vertices - The indexes of the three vertices that make up the face. */ -ScriptValuePointer meshFaceToScriptValue(ScriptEngine* engine, const MeshFace& meshFace) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("vertices", qVectorIntToScriptValue(engine, meshFace.vertexIndices)); +ScriptValue meshFaceToScriptValue(ScriptEngine* engine, const MeshFace& meshFace) { + ScriptValue obj = engine->newObject(); + obj.setProperty("vertices", qVectorIntToScriptValue(engine, meshFace.vertexIndices)); return obj; } -void meshFaceFromScriptValue(const ScriptValuePointer& object, MeshFace& meshFaceResult) { - qVectorIntFromScriptValue(object->property("vertices"), meshFaceResult.vertexIndices); +void meshFaceFromScriptValue(const ScriptValue& object, MeshFace& meshFaceResult) { + qVectorIntFromScriptValue(object.property("vertices"), meshFaceResult.vertexIndices); } -ScriptValuePointer qVectorMeshFaceToScriptValue(ScriptEngine* engine, const QVector& vector) { - ScriptValuePointer array = engine->newArray(); +ScriptValue qVectorMeshFaceToScriptValue(ScriptEngine* engine, const QVector& vector) { + ScriptValue array = engine->newArray(); for (int i = 0; i < vector.size(); i++) { - array->setProperty(i, meshFaceToScriptValue(engine, vector.at(i))); + array.setProperty(i, meshFaceToScriptValue(engine, vector.at(i))); } return array; } -void qVectorMeshFaceFromScriptValue(const ScriptValuePointer& array, QVector& result) { - int length = array->property("length")->toInteger(); +void qVectorMeshFaceFromScriptValue(const ScriptValue& array, QVector& result) { + int length = array.property("length").toInteger(); result.clear(); for (int i = 0; i < length; i++) { MeshFace meshFace = MeshFace(); - meshFaceFromScriptValue(array->property(i), meshFace); + meshFaceFromScriptValue(array.property(i), meshFace); result << meshFace; } } -ScriptValuePointer stencilMaskModeToScriptValue(ScriptEngine* engine, const StencilMaskMode& stencilMode) { +ScriptValue stencilMaskModeToScriptValue(ScriptEngine* engine, const StencilMaskMode& stencilMode) { return engine->newValue((int)stencilMode); } -void stencilMaskModeFromScriptValue(const ScriptValuePointer& object, StencilMaskMode& stencilMode) { - stencilMode = StencilMaskMode(object->toVariant().toInt()); +void stencilMaskModeFromScriptValue(const ScriptValue& object, StencilMaskMode& stencilMode) { + stencilMode = StencilMaskMode(object.toVariant().toInt()); } -void promiseFromScriptValue(const ScriptValuePointer& object, std::shared_ptr& promise) { +void promiseFromScriptValue(const ScriptValue& object, std::shared_ptr& promise) { Q_ASSERT(false); } -ScriptValuePointer promiseToScriptValue(ScriptEngine* engine, const std::shared_ptr& promise) { +ScriptValue promiseToScriptValue(ScriptEngine* engine, const std::shared_ptr& promise) { return engine->newQObject(promise.get()); } -ScriptValuePointer EntityItemIDtoScriptValue(ScriptEngine* engine, const EntityItemID& id) { +ScriptValue EntityItemIDtoScriptValue(ScriptEngine* engine, const EntityItemID& id) { return quuidToScriptValue(engine, id); } -void EntityItemIDfromScriptValue(const ScriptValuePointer &object, EntityItemID& id) { +void EntityItemIDfromScriptValue(const ScriptValue &object, EntityItemID& id) { quuidFromScriptValue(object, id); } -QVector qVectorEntityItemIDFromScriptValue(const ScriptValuePointer& array) { - if (!array->isArray()) { +QVector qVectorEntityItemIDFromScriptValue(const ScriptValue& array) { + if (!array.isArray()) { return QVector(); } QVector newVector; - int length = array->property("length")->toInteger(); + int length = array.property("length").toInteger(); newVector.reserve(length); for (int i = 0; i < length; i++) { - QString uuidAsString = array->property(i)->toString(); + QString uuidAsString = array.property(i).toString(); EntityItemID fromString(uuidAsString); newVector << fromString; } diff --git a/libraries/script-engine/src/ScriptValueUtils.h b/libraries/script-engine/src/ScriptValueUtils.h index 636845916f..b99b014f45 100644 --- a/libraries/script-engine/src/ScriptValueUtils.h +++ b/libraries/script-engine/src/ScriptValueUtils.h @@ -24,7 +24,7 @@ #include "ScriptValue.h" -bool isListOfStrings(const ScriptValuePointer& value); +bool isListOfStrings(const ScriptValue& value); void registerMetaTypes(ScriptEngine* engine); @@ -51,8 +51,8 @@ void registerMetaTypes(ScriptEngine* engine); * @property {number} r2c3 - Row 2, column 3 value. * @property {number} r3c3 - Row 3, column 3 value. */ -ScriptValuePointer mat4toScriptValue(ScriptEngine* engine, const glm::mat4& mat4); -void mat4FromScriptValue(const ScriptValuePointer& object, glm::mat4& mat4); +ScriptValue mat4toScriptValue(ScriptEngine* engine, const glm::mat4& mat4); +void mat4FromScriptValue(const ScriptValue& object, glm::mat4& mat4); /**jsdoc * A 2-dimensional vector. @@ -68,8 +68,8 @@ void mat4FromScriptValue(const ScriptValuePointer& object, glm::mat4& mat4); * var color = Entities.getEntityProperties().materialMappingPos; // { x: 0.7, y: 0.7 } * color.v = 0.8; // { x: 0.7, y: 0.8 } */ -ScriptValuePointer vec2ToScriptValue(ScriptEngine* engine, const glm::vec2& vec2); -void vec2FromScriptValue(const ScriptValuePointer& object, glm::vec2& vec2); +ScriptValue vec2ToScriptValue(ScriptEngine* engine, const glm::vec2& vec2); +void vec2FromScriptValue(const ScriptValue& object, glm::vec2& vec2); /**jsdoc * A 3-dimensional vector. See also the {@link Vec3(0)|Vec3} object. @@ -91,9 +91,9 @@ void vec2FromScriptValue(const ScriptValuePointer& object, glm::vec2& vec2); * Entities.editEntity(, { position: "red"}); // { x: 255, y: 0, z: 0 } * Entities.editEntity(, { position: "#00FF00"}); // { x: 0, y: 255, z: 0 } */ -ScriptValuePointer vec3ToScriptValue(ScriptEngine* engine, const glm::vec3& vec3); -ScriptValuePointer vec3ColorToScriptValue(ScriptEngine* engine, const glm::vec3& vec3); -void vec3FromScriptValue(const ScriptValuePointer& object, glm::vec3& vec3); +ScriptValue vec3ToScriptValue(ScriptEngine* engine, const glm::vec3& vec3); +ScriptValue vec3ColorToScriptValue(ScriptEngine* engine, const glm::vec3& vec3); +void vec3FromScriptValue(const ScriptValue& object, glm::vec3& vec3); /**jsdoc * A color vector. See also the {@link Vec3(0)|Vec3} object. @@ -133,9 +133,9 @@ void vec3FromScriptValue(const ScriptValuePointer& object, glm::vec3& vec3); * Entities.editEntity(, { color: "red"}); // { red: 255, green: 0, blue: 0 } * Entities.editEntity(, { color: "#00FF00"}); // { red: 0, green: 255, blue: 0 } */ -ScriptValuePointer u8vec3ToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3); -ScriptValuePointer u8vec3ColorToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3); -void u8vec3FromScriptValue(const ScriptValuePointer& object, glm::u8vec3& vec3); +ScriptValue u8vec3ToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3); +ScriptValue u8vec3ColorToScriptValue(ScriptEngine* engine, const glm::u8vec3& vec3); +void u8vec3FromScriptValue(const ScriptValue& object, glm::u8vec3& vec3); /**jsdoc * A 4-dimensional vector. @@ -146,12 +146,12 @@ void u8vec3FromScriptValue(const ScriptValuePointer& object, glm::u8vec3& vec3); * @property {number} z - Z-coordinate of the vector. * @property {number} w - W-coordinate of the vector. */ -ScriptValuePointer vec4toScriptValue(ScriptEngine* engine, const glm::vec4& vec4); -void vec4FromScriptValue(const ScriptValuePointer& object, glm::vec4& vec4); +ScriptValue vec4toScriptValue(ScriptEngine* engine, const glm::vec4& vec4); +void vec4FromScriptValue(const ScriptValue& object, glm::vec4& vec4); // Quaternions -ScriptValuePointer quatToScriptValue(ScriptEngine* engine, const glm::quat& quat); -void quatFromScriptValue(const ScriptValuePointer& object, glm::quat& quat); +ScriptValue quatToScriptValue(ScriptEngine* engine, const glm::quat& quat); +void quatFromScriptValue(const ScriptValue& object, glm::quat& quat); /**jsdoc * Defines a rectangular portion of an image or screen, or similar. @@ -162,64 +162,64 @@ void quatFromScriptValue(const ScriptValuePointer& object, glm::quat& quat); * @property {number} height - Height of the rectangle. */ class QRect; -ScriptValuePointer qRectToScriptValue(ScriptEngine* engine, const QRect& rect); -void qRectFromScriptValue(const ScriptValuePointer& object, QRect& rect); +ScriptValue qRectToScriptValue(ScriptEngine* engine, const QRect& rect); +void qRectFromScriptValue(const ScriptValue& object, QRect& rect); class QRectF; -ScriptValuePointer qRectFToScriptValue(ScriptEngine* engine, const QRectF& rect); -void qRectFFromScriptValue(const ScriptValuePointer& object, QRectF& rect); +ScriptValue qRectFToScriptValue(ScriptEngine* engine, const QRectF& rect); +void qRectFFromScriptValue(const ScriptValue& object, QRectF& rect); // QColor class QColor; -ScriptValuePointer qColorToScriptValue(ScriptEngine* engine, const QColor& color); -void qColorFromScriptValue(const ScriptValuePointer& object, QColor& color); +ScriptValue qColorToScriptValue(ScriptEngine* engine, const QColor& color); +void qColorFromScriptValue(const ScriptValue& object, QColor& color); class QUrl; -ScriptValuePointer qURLToScriptValue(ScriptEngine* engine, const QUrl& url); -void qURLFromScriptValue(const ScriptValuePointer& object, QUrl& url); +ScriptValue qURLToScriptValue(ScriptEngine* engine, const QUrl& url); +void qURLFromScriptValue(const ScriptValue& object, QUrl& url); // vector Q_DECLARE_METATYPE(QVector) -ScriptValuePointer qVectorVec3ToScriptValue(ScriptEngine* engine, const QVector& vector); -ScriptValuePointer qVectorVec3ColorToScriptValue(ScriptEngine* engine, const QVector& vector); -void qVectorVec3FromScriptValue(const ScriptValuePointer& array, QVector& vector); -QVector qVectorVec3FromScriptValue(const ScriptValuePointer& array); +ScriptValue qVectorVec3ToScriptValue(ScriptEngine* engine, const QVector& vector); +ScriptValue qVectorVec3ColorToScriptValue(ScriptEngine* engine, const QVector& vector); +void qVectorVec3FromScriptValue(const ScriptValue& array, QVector& vector); +QVector qVectorVec3FromScriptValue(const ScriptValue& array); // vector Q_DECLARE_METATYPE(QVector) -ScriptValuePointer qVectorQuatToScriptValue(ScriptEngine* engine, const QVector& vector); -void qVectorQuatFromScriptValue(const ScriptValuePointer& array, QVector& vector); -QVector qVectorQuatFromScriptValue(const ScriptValuePointer& array); +ScriptValue qVectorQuatToScriptValue(ScriptEngine* engine, const QVector& vector); +void qVectorQuatFromScriptValue(const ScriptValue& array, QVector& vector); +QVector qVectorQuatFromScriptValue(const ScriptValue& array); // vector -ScriptValuePointer qVectorBoolToScriptValue(ScriptEngine* engine, const QVector& vector); -void qVectorBoolFromScriptValue(const ScriptValuePointer& array, QVector& vector); -QVector qVectorBoolFromScriptValue(const ScriptValuePointer& array); +ScriptValue qVectorBoolToScriptValue(ScriptEngine* engine, const QVector& vector); +void qVectorBoolFromScriptValue(const ScriptValue& array, QVector& vector); +QVector qVectorBoolFromScriptValue(const ScriptValue& array); // vector -ScriptValuePointer qVectorFloatToScriptValue(ScriptEngine* engine, const QVector& vector); -void qVectorFloatFromScriptValue(const ScriptValuePointer& array, QVector& vector); -QVector qVectorFloatFromScriptValue(const ScriptValuePointer& array); +ScriptValue qVectorFloatToScriptValue(ScriptEngine* engine, const QVector& vector); +void qVectorFloatFromScriptValue(const ScriptValue& array, QVector& vector); +QVector qVectorFloatFromScriptValue(const ScriptValue& array); // vector -ScriptValuePointer qVectorIntToScriptValue(ScriptEngine* engine, const QVector& vector); -void qVectorIntFromScriptValue(const ScriptValuePointer& array, QVector& vector); +ScriptValue qVectorIntToScriptValue(ScriptEngine* engine, const QVector& vector); +void qVectorIntFromScriptValue(const ScriptValue& array, QVector& vector); -ScriptValuePointer qVectorQUuidToScriptValue(ScriptEngine* engine, const QVector& vector); -void qVectorQUuidFromScriptValue(const ScriptValuePointer& array, QVector& vector); -QVector qVectorQUuidFromScriptValue(const ScriptValuePointer& array); +ScriptValue qVectorQUuidToScriptValue(ScriptEngine* engine, const QVector& vector); +void qVectorQUuidFromScriptValue(const ScriptValue& array, QVector& vector); +QVector qVectorQUuidFromScriptValue(const ScriptValue& array); class AACube; -ScriptValuePointer aaCubeToScriptValue(ScriptEngine* engine, const AACube& aaCube); -void aaCubeFromScriptValue(const ScriptValuePointer& object, AACube& aaCube); +ScriptValue aaCubeToScriptValue(ScriptEngine* engine, const AACube& aaCube); +void aaCubeFromScriptValue(const ScriptValue& object, AACube& aaCube); class PickRay; -ScriptValuePointer pickRayToScriptValue(ScriptEngine* engine, const PickRay& pickRay); -void pickRayFromScriptValue(const ScriptValuePointer& object, PickRay& pickRay); +ScriptValue pickRayToScriptValue(ScriptEngine* engine, const PickRay& pickRay); +void pickRayFromScriptValue(const ScriptValue& object, PickRay& pickRay); class Collision; -ScriptValuePointer collisionToScriptValue(ScriptEngine* engine, const Collision& collision); -void collisionFromScriptValue(const ScriptValuePointer& object, Collision& collision); +ScriptValue collisionToScriptValue(ScriptEngine* engine, const Collision& collision); +void collisionFromScriptValue(const ScriptValue& object, Collision& collision); /**jsdoc * UUIDs (Universally Unique IDentifiers) are used to uniquely identify entities, avatars, and the like. They are represented @@ -228,44 +228,44 @@ void collisionFromScriptValue(const ScriptValuePointer& object, Collision& colli * @typedef {string} Uuid */ //Q_DECLARE_METATYPE(QUuid) // don't need to do this for QUuid since it's already a meta type -ScriptValuePointer quuidToScriptValue(ScriptEngine* engine, const QUuid& uuid); -void quuidFromScriptValue(const ScriptValuePointer& object, QUuid& uuid); +ScriptValue quuidToScriptValue(ScriptEngine* engine, const QUuid& uuid); +void quuidFromScriptValue(const ScriptValue& object, QUuid& uuid); //Q_DECLARE_METATYPE(QSizeF) // Don't need to to this becase it's arleady a meta type class QSizeF; -ScriptValuePointer qSizeFToScriptValue(ScriptEngine* engine, const QSizeF& qSizeF); -void qSizeFFromScriptValue(const ScriptValuePointer& object, QSizeF& qSizeF); +ScriptValue qSizeFToScriptValue(ScriptEngine* engine, const QSizeF& qSizeF); +void qSizeFFromScriptValue(const ScriptValue& object, QSizeF& qSizeF); class AnimationDetails; -ScriptValuePointer animationDetailsToScriptValue(ScriptEngine* engine, const AnimationDetails& event); -void animationDetailsFromScriptValue(const ScriptValuePointer& object, AnimationDetails& event); +ScriptValue animationDetailsToScriptValue(ScriptEngine* engine, const AnimationDetails& event); +void animationDetailsFromScriptValue(const ScriptValue& object, AnimationDetails& event); class MeshProxy; -ScriptValuePointer meshToScriptValue(ScriptEngine* engine, MeshProxy* const& in); -void meshFromScriptValue(const ScriptValuePointer& value, MeshProxy*& out); +ScriptValue meshToScriptValue(ScriptEngine* engine, MeshProxy* const& in); +void meshFromScriptValue(const ScriptValue& value, MeshProxy*& out); class MeshProxyList; -ScriptValuePointer meshesToScriptValue(ScriptEngine* engine, const MeshProxyList& in); -void meshesFromScriptValue(const ScriptValuePointer& value, MeshProxyList& out); +ScriptValue meshesToScriptValue(ScriptEngine* engine, const MeshProxyList& in); +void meshesFromScriptValue(const ScriptValue& value, MeshProxyList& out); class MeshFace; -ScriptValuePointer meshFaceToScriptValue(ScriptEngine* engine, const MeshFace& meshFace); -void meshFaceFromScriptValue(const ScriptValuePointer& object, MeshFace& meshFaceResult); -ScriptValuePointer qVectorMeshFaceToScriptValue(ScriptEngine* engine, const QVector& vector); -void qVectorMeshFaceFromScriptValue(const ScriptValuePointer& array, QVector& result); +ScriptValue meshFaceToScriptValue(ScriptEngine* engine, const MeshFace& meshFace); +void meshFaceFromScriptValue(const ScriptValue& object, MeshFace& meshFaceResult); +ScriptValue qVectorMeshFaceToScriptValue(ScriptEngine* engine, const QVector& vector); +void qVectorMeshFaceFromScriptValue(const ScriptValue& array, QVector& result); enum class StencilMaskMode; -ScriptValuePointer stencilMaskModeToScriptValue(ScriptEngine* engine, const StencilMaskMode& stencilMode); -void stencilMaskModeFromScriptValue(const ScriptValuePointer& object, StencilMaskMode& stencilMode); +ScriptValue stencilMaskModeToScriptValue(ScriptEngine* engine, const StencilMaskMode& stencilMode); +void stencilMaskModeFromScriptValue(const ScriptValue& object, StencilMaskMode& stencilMode); class MiniPromise; -void promiseFromScriptValue(const ScriptValuePointer& object, std::shared_ptr& promise); -ScriptValuePointer promiseToScriptValue(ScriptEngine* engine, const std::shared_ptr& promise); +void promiseFromScriptValue(const ScriptValue& object, std::shared_ptr& promise); +ScriptValue promiseToScriptValue(ScriptEngine* engine, const std::shared_ptr& promise); class EntityItemID; -ScriptValuePointer EntityItemIDtoScriptValue(ScriptEngine* engine, const EntityItemID& properties); -void EntityItemIDfromScriptValue(const ScriptValuePointer& object, EntityItemID& properties); -QVector qVectorEntityItemIDFromScriptValue(const ScriptValuePointer& array); +ScriptValue EntityItemIDtoScriptValue(ScriptEngine* engine, const EntityItemID& properties); +void EntityItemIDfromScriptValue(const ScriptValue& object, EntityItemID& properties); +QVector qVectorEntityItemIDFromScriptValue(const ScriptValue& array); #endif // #define hifi_ScriptValueUtils_h diff --git a/libraries/script-engine/src/Scriptable.h b/libraries/script-engine/src/Scriptable.h index d9e8403e27..39d5974168 100644 --- a/libraries/script-engine/src/Scriptable.h +++ b/libraries/script-engine/src/Scriptable.h @@ -18,20 +18,19 @@ #include #include "ScriptContext.h" +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; using ScriptEnginePointer = QSharedPointer; -using ScriptValuePointer = QSharedPointer; /// [ScriptInterface] Provides an engine-independent interface for QScriptable class Scriptable { public: static inline ScriptEnginePointer engine(); static ScriptContext* context(); - static inline ScriptValuePointer thisObject(); + static inline ScriptValue thisObject(); static inline int argumentCount(); - static inline ScriptValuePointer argument(int index); + static inline ScriptValue argument(int index); static void setContext(ScriptContext* context); }; @@ -42,9 +41,9 @@ ScriptEnginePointer Scriptable::engine() { return scriptContext->engine(); } -ScriptValuePointer Scriptable::thisObject() { +ScriptValue Scriptable::thisObject() { ScriptContext* scriptContext = context(); - if (!scriptContext) return nullptr; + if (!scriptContext) return ScriptValue(); return scriptContext->thisObject(); } @@ -54,9 +53,9 @@ int Scriptable::argumentCount() { return scriptContext->argumentCount(); } -ScriptValuePointer Scriptable::argument(int index) { +ScriptValue Scriptable::argument(int index) { ScriptContext* scriptContext = context(); - if (!scriptContext) return ScriptValuePointer(); + if (!scriptContext) return ScriptValue(); return scriptContext->argument(index); } diff --git a/libraries/script-engine/src/ScriptsModel.h b/libraries/script-engine/src/ScriptsModel.h index fecf857da2..8c8afd41af 100644 --- a/libraries/script-engine/src/ScriptsModel.h +++ b/libraries/script-engine/src/ScriptsModel.h @@ -19,11 +19,8 @@ #include #include #include -#include class TreeNodeFolder; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; enum ScriptOrigin { SCRIPT_ORIGIN_LOCAL, @@ -147,10 +144,10 @@ public: // No JSDoc because the particulars of the parent class is provided in the @class description. int columnCount(const QModelIndex& parent = QModelIndex()) const override; - // Not exposed in the API because no conversion between TreeNodeBase and ScriptValuePointer is provided. + // Not exposed in the API because no conversion between TreeNodeBase and ScriptValue is provided. TreeNodeBase* getTreeNodeFromIndex(const QModelIndex& index) const; - // Not exposed in the API because no conversion between TreeNodeBase and ScriptValuePointer is provided. + // Not exposed in the API because no conversion between TreeNodeBase and ScriptValue is provided. QList getFolderNodes(TreeNodeFolder* parent) const; enum Role { diff --git a/libraries/script-engine/src/SpatialEvent.cpp b/libraries/script-engine/src/SpatialEvent.cpp index 0c5d96db45..bada11b66e 100644 --- a/libraries/script-engine/src/SpatialEvent.cpp +++ b/libraries/script-engine/src/SpatialEvent.cpp @@ -33,17 +33,17 @@ SpatialEvent::SpatialEvent(const SpatialEvent& event) { } -ScriptValuePointer SpatialEvent::toScriptValue(ScriptEngine* engine, const SpatialEvent& event) { - ScriptValuePointer obj = engine->newObject(); +ScriptValue SpatialEvent::toScriptValue(ScriptEngine* engine, const SpatialEvent& event) { + ScriptValue obj = engine->newObject(); - obj->setProperty("locTranslation", vec3ToScriptValue(engine, event.locTranslation) ); - obj->setProperty("locRotation", quatToScriptValue(engine, event.locRotation) ); - obj->setProperty("absTranslation", vec3ToScriptValue(engine, event.absTranslation)); - obj->setProperty("absRotation", quatToScriptValue(engine, event.absRotation)); + obj.setProperty("locTranslation", vec3ToScriptValue(engine, event.locTranslation) ); + obj.setProperty("locRotation", quatToScriptValue(engine, event.locRotation) ); + obj.setProperty("absTranslation", vec3ToScriptValue(engine, event.absTranslation)); + obj.setProperty("absRotation", quatToScriptValue(engine, event.absRotation)); return obj; } -void SpatialEvent::fromScriptValue(const ScriptValuePointer& object,SpatialEvent& event) { +void SpatialEvent::fromScriptValue(const ScriptValue& object,SpatialEvent& event) { // nothing for now... } diff --git a/libraries/script-engine/src/SpatialEvent.h b/libraries/script-engine/src/SpatialEvent.h index 197d5a6a98..be7e5d3320 100644 --- a/libraries/script-engine/src/SpatialEvent.h +++ b/libraries/script-engine/src/SpatialEvent.h @@ -17,11 +17,10 @@ #include #include -#include + +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// [unused] Represents a spatial event to the scripting engine class SpatialEvent { @@ -29,8 +28,8 @@ public: SpatialEvent(); SpatialEvent(const SpatialEvent& other); - static ScriptValuePointer toScriptValue(ScriptEngine* engine, const SpatialEvent& event); - static void fromScriptValue(const ScriptValuePointer& object, SpatialEvent& event); + static ScriptValue toScriptValue(ScriptEngine* engine, const SpatialEvent& event); + static void fromScriptValue(const ScriptValue& object, SpatialEvent& event); glm::vec3 locTranslation; glm::quat locRotation; diff --git a/libraries/script-engine/src/TouchEvent.cpp b/libraries/script-engine/src/TouchEvent.cpp index e85b773ef6..593eb326fc 100644 --- a/libraries/script-engine/src/TouchEvent.cpp +++ b/libraries/script-engine/src/TouchEvent.cpp @@ -204,47 +204,47 @@ void TouchEvent::calculateMetaAttributes(const TouchEvent& other) { * print(JSON.stringify(event)); * }); */ -ScriptValuePointer TouchEvent::toScriptValue(ScriptEngine* engine, const TouchEvent& event) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("x", event.x); - obj->setProperty("y", event.y); - obj->setProperty("isPressed", event.isPressed); - obj->setProperty("isMoved", event.isMoved); - obj->setProperty("isStationary", event.isStationary); - obj->setProperty("isReleased", event.isReleased); - obj->setProperty("isShifted", event.isShifted); - obj->setProperty("isMeta", event.isMeta); - obj->setProperty("isControl", event.isControl); - obj->setProperty("isAlt", event.isAlt); - obj->setProperty("touchPoints", event.touchPoints); +ScriptValue TouchEvent::toScriptValue(ScriptEngine* engine, const TouchEvent& event) { + ScriptValue obj = engine->newObject(); + obj.setProperty("x", event.x); + obj.setProperty("y", event.y); + obj.setProperty("isPressed", event.isPressed); + obj.setProperty("isMoved", event.isMoved); + obj.setProperty("isStationary", event.isStationary); + obj.setProperty("isReleased", event.isReleased); + obj.setProperty("isShifted", event.isShifted); + obj.setProperty("isMeta", event.isMeta); + obj.setProperty("isControl", event.isControl); + obj.setProperty("isAlt", event.isAlt); + obj.setProperty("touchPoints", event.touchPoints); - ScriptValuePointer pointsObj = engine->newArray(); + ScriptValue pointsObj = engine->newArray(); int index = 0; foreach (glm::vec2 point, event.points) { - ScriptValuePointer thisPoint = vec2ToScriptValue(engine, point); - pointsObj->setProperty(index, thisPoint); + ScriptValue thisPoint = vec2ToScriptValue(engine, point); + pointsObj.setProperty(index, thisPoint); index++; } - obj->setProperty("points", pointsObj); - obj->setProperty("radius", event.radius); - obj->setProperty("isPinching", event.isPinching); - obj->setProperty("isPinchOpening", event.isPinchOpening); + obj.setProperty("points", pointsObj); + obj.setProperty("radius", event.radius); + obj.setProperty("isPinching", event.isPinching); + obj.setProperty("isPinchOpening", event.isPinchOpening); - obj->setProperty("angle", event.angle); - obj->setProperty("deltaAngle", event.deltaAngle); - ScriptValuePointer anglesObj = engine->newArray(); + obj.setProperty("angle", event.angle); + obj.setProperty("deltaAngle", event.deltaAngle); + ScriptValue anglesObj = engine->newArray(); index = 0; foreach (float angle, event.angles) { - anglesObj->setProperty(index, angle); + anglesObj.setProperty(index, angle); index++; } - obj->setProperty("angles", anglesObj); + obj.setProperty("angles", anglesObj); - obj->setProperty("isRotating", event.isRotating); - obj->setProperty("rotating", event.rotating); + obj.setProperty("isRotating", event.isRotating); + obj.setProperty("rotating", event.rotating); return obj; } -void TouchEvent::fromScriptValue(const ScriptValuePointer& object, TouchEvent& event) { +void TouchEvent::fromScriptValue(const ScriptValue& object, TouchEvent& event) { // nothing for now... } diff --git a/libraries/script-engine/src/TouchEvent.h b/libraries/script-engine/src/TouchEvent.h index 9183061f4f..80edf53dd2 100644 --- a/libraries/script-engine/src/TouchEvent.h +++ b/libraries/script-engine/src/TouchEvent.h @@ -19,11 +19,10 @@ #include #include -#include + +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// Represents a display or device event to the scripting engine. Exposed as TouchEvent class TouchEvent { @@ -32,8 +31,8 @@ public: TouchEvent(const QTouchEvent& event); TouchEvent(const QTouchEvent& event, const TouchEvent& other); - static ScriptValuePointer toScriptValue(ScriptEngine* engine, const TouchEvent& event); - static void fromScriptValue(const ScriptValuePointer& object, TouchEvent& event); + static ScriptValue toScriptValue(ScriptEngine* engine, const TouchEvent& event); + static void fromScriptValue(const ScriptValue& object, TouchEvent& event); float x; float y; diff --git a/libraries/script-engine/src/VariantMapToScriptValue.cpp b/libraries/script-engine/src/VariantMapToScriptValue.cpp index 1b206e410d..a1a50ed207 100644 --- a/libraries/script-engine/src/VariantMapToScriptValue.cpp +++ b/libraries/script-engine/src/VariantMapToScriptValue.cpp @@ -15,7 +15,7 @@ #include "SharedLogging.h" -ScriptValuePointer variantToScriptValue(QVariant& qValue, ScriptEngine& scriptEngine) { +ScriptValue variantToScriptValue(QVariant& qValue, ScriptEngine& scriptEngine) { switch(qValue.type()) { case QVariant::Bool: return scriptEngine.newValue(qValue.toBool()); @@ -48,29 +48,29 @@ ScriptValuePointer variantToScriptValue(QVariant& qValue, ScriptEngine& scriptEn break; } - return ScriptValuePointer(); + return ScriptValue(); } -ScriptValuePointer variantMapToScriptValue(QVariantMap& variantMap, ScriptEngine& scriptEngine) { - ScriptValuePointer scriptValue = scriptEngine.newObject(); +ScriptValue variantMapToScriptValue(QVariantMap& variantMap, ScriptEngine& scriptEngine) { + ScriptValue scriptValue = scriptEngine.newObject(); for (QVariantMap::const_iterator iter = variantMap.begin(); iter != variantMap.end(); ++iter) { QString key = iter.key(); QVariant qValue = iter.value(); - scriptValue->setProperty(key, variantToScriptValue(qValue, scriptEngine)); + scriptValue.setProperty(key, variantToScriptValue(qValue, scriptEngine)); } return scriptValue; } -ScriptValuePointer variantListToScriptValue(QVariantList& variantList, ScriptEngine& scriptEngine) { +ScriptValue variantListToScriptValue(QVariantList& variantList, ScriptEngine& scriptEngine) { - ScriptValuePointer scriptValue = scriptEngine.newArray(); + ScriptValue scriptValue = scriptEngine.newArray(); for (int i = 0; i < variantList.size(); i++) { - scriptValue->setProperty(i, variantToScriptValue(variantList[i], scriptEngine)); + scriptValue.setProperty(i, variantToScriptValue(variantList[i], scriptEngine)); } return scriptValue; diff --git a/libraries/script-engine/src/VariantMapToScriptValue.h b/libraries/script-engine/src/VariantMapToScriptValue.h index 3093938d37..956f7c2f15 100644 --- a/libraries/script-engine/src/VariantMapToScriptValue.h +++ b/libraries/script-engine/src/VariantMapToScriptValue.h @@ -16,8 +16,8 @@ #include "ScriptValue.h" #include "ScriptEngine.h" -ScriptValuePointer variantToScriptValue(QVariant& qValue, ScriptEngine& scriptEngine); -ScriptValuePointer variantMapToScriptValue(QVariantMap& variantMap, ScriptEngine& scriptEngine); -ScriptValuePointer variantListToScriptValue(QVariantList& variantList, ScriptEngine& scriptEngine); +ScriptValue variantToScriptValue(QVariant& qValue, ScriptEngine& scriptEngine); +ScriptValue variantMapToScriptValue(QVariantMap& variantMap, ScriptEngine& scriptEngine); +ScriptValue variantListToScriptValue(QVariantList& variantList, ScriptEngine& scriptEngine); /// @} diff --git a/libraries/script-engine/src/WebSocketClass.cpp b/libraries/script-engine/src/WebSocketClass.cpp index 78ddd2d474..8bb6e63082 100644 --- a/libraries/script-engine/src/WebSocketClass.cpp +++ b/libraries/script-engine/src/WebSocketClass.cpp @@ -16,6 +16,7 @@ #include "ScriptContext.h" #include "ScriptEngine.h" +#include "ScriptEngineCast.h" #include "ScriptEngineLogging.h" #include "ScriptValue.h" @@ -44,10 +45,10 @@ void WebSocketClass::initialize() { _binaryType = QStringLiteral("arraybuffer"); } -ScriptValuePointer WebSocketClass::constructor(ScriptContext* context, ScriptEngine* engine) { +ScriptValue WebSocketClass::constructor(ScriptContext* context, ScriptEngine* engine) { QString url; if (context->argumentCount() > 0) { - url = context->argument(0)->toString(); + url = context->argument(0).toString(); } return engine->newQObject(new WebSocketClass(engine, url), ScriptEngine::ScriptOwnership); } @@ -56,12 +57,12 @@ WebSocketClass::~WebSocketClass() { _webSocket->deleteLater(); } -void WebSocketClass::send(ScriptValuePointer message) { - if (message->isObject()) { +void WebSocketClass::send(const ScriptValue& message) { + if (message.isObject()) { QByteArray ba = scriptvalue_cast(message); _webSocket->sendBinaryMessage(ba); } else { - _webSocket->sendTextMessage(message->toString()); + _webSocket->sendTextMessage(message.toString()); } } @@ -91,14 +92,14 @@ void WebSocketClass::close(QWebSocketProtocol::CloseCode closeCode, QString reas */ void WebSocketClass::handleOnClose() { bool hasError = (_webSocket->error() != QAbstractSocket::UnknownSocketError); - if (_onCloseEvent->isFunction()) { + if (_onCloseEvent.isFunction()) { ScriptValueList args; - ScriptValuePointer arg = _engine->newObject(); - arg->setProperty("code", hasError ? QWebSocketProtocol::CloseCodeAbnormalDisconnection : _webSocket->closeCode()); - arg->setProperty("reason", _webSocket->closeReason()); - arg->setProperty("wasClean", !hasError); + ScriptValue arg = _engine->newObject(); + arg.setProperty("code", hasError ? QWebSocketProtocol::CloseCodeAbnormalDisconnection : _webSocket->closeCode()); + arg.setProperty("reason", _webSocket->closeReason()); + arg.setProperty("wasClean", !hasError); args << arg; - _onCloseEvent->call(ScriptValuePointer(), args); + _onCloseEvent.call(ScriptValue(), args); } } @@ -154,8 +155,8 @@ void WebSocketClass::handleOnClose() { * @typedef {number} WebSocket.SocketError */ void WebSocketClass::handleOnError(QAbstractSocket::SocketError error) { - if (_onErrorEvent->isFunction()) { - _onErrorEvent->call(); + if (_onErrorEvent.isFunction()) { + _onErrorEvent.call(); } } @@ -170,26 +171,26 @@ void WebSocketClass::handleOnError(QAbstractSocket::SocketError error) { * @property {string} data - The message content. */ void WebSocketClass::handleOnMessage(const QString& message) { - if (_onMessageEvent->isFunction()) { + if (_onMessageEvent.isFunction()) { ScriptValueList args; - ScriptValuePointer arg = _engine->newObject(); - arg->setProperty("data", message); + ScriptValue arg = _engine->newObject(); + arg.setProperty("data", message); args << arg; - _onMessageEvent->call(ScriptValuePointer(), args); + _onMessageEvent.call(ScriptValue(), args); } } void WebSocketClass::handleOnBinaryMessage(const QByteArray& message) { - if (_onMessageEvent->isFunction()) { + if (_onMessageEvent.isFunction()) { ScriptValueList args; - ScriptValuePointer arg = _engine->newObject(); - ScriptValuePointer arrayBuffer = _engine->newArrayBuffer(message); - if (arrayBuffer->isUndefined()) { + ScriptValue arg = _engine->newObject(); + ScriptValue arrayBuffer = _engine->newArrayBuffer(message); + if (arrayBuffer.isUndefined()) { qCWarning(scriptengine) << "WebSocketClass::handleOnBinaryMessage !ArrayBuffer"; } - arg->setProperty("data", arrayBuffer); + arg.setProperty("data", arrayBuffer); args << arg; - _onMessageEvent->call(ScriptValuePointer(), args); + _onMessageEvent.call(ScriptValue(), args); } } @@ -198,31 +199,31 @@ void WebSocketClass::handleOnBinaryMessage(const QByteArray& message) { * @callback WebSocket~onOpenCallback */ void WebSocketClass::handleOnOpen() { - if (_onOpenEvent->isFunction()) { - _onOpenEvent->call(); + if (_onOpenEvent.isFunction()) { + _onOpenEvent.call(); } } -ScriptValuePointer qWSCloseCodeToScriptValue(ScriptEngine* engine, const QWebSocketProtocol::CloseCode &closeCode) { +ScriptValue qWSCloseCodeToScriptValue(ScriptEngine* engine, const QWebSocketProtocol::CloseCode &closeCode) { return engine->newValue(closeCode); } -void qWSCloseCodeFromScriptValue(const ScriptValuePointer &object, QWebSocketProtocol::CloseCode &closeCode) { - closeCode = (QWebSocketProtocol::CloseCode)object->toUInt16(); +void qWSCloseCodeFromScriptValue(const ScriptValue &object, QWebSocketProtocol::CloseCode &closeCode) { + closeCode = (QWebSocketProtocol::CloseCode)object.toUInt16(); } -ScriptValuePointer webSocketToScriptValue(ScriptEngine* engine, WebSocketClass* const &in) { +ScriptValue webSocketToScriptValue(ScriptEngine* engine, WebSocketClass* const &in) { return engine->newQObject(in, ScriptEngine::ScriptOwnership); } -void webSocketFromScriptValue(const ScriptValuePointer &object, WebSocketClass* &out) { - out = qobject_cast(object->toQObject()); +void webSocketFromScriptValue(const ScriptValue &object, WebSocketClass* &out) { + out = qobject_cast(object.toQObject()); } -ScriptValuePointer wscReadyStateToScriptValue(ScriptEngine* engine, const WebSocketClass::ReadyState& readyState) { +ScriptValue wscReadyStateToScriptValue(ScriptEngine* engine, const WebSocketClass::ReadyState& readyState) { return engine->newValue(readyState); } -void wscReadyStateFromScriptValue(const ScriptValuePointer& object, WebSocketClass::ReadyState& readyState) { - readyState = (WebSocketClass::ReadyState)object->toUInt16(); +void wscReadyStateFromScriptValue(const ScriptValue& object, WebSocketClass::ReadyState& readyState) { + readyState = (WebSocketClass::ReadyState)object.toUInt16(); } diff --git a/libraries/script-engine/src/WebSocketClass.h b/libraries/script-engine/src/WebSocketClass.h index a15d5f0969..32c5db87f6 100644 --- a/libraries/script-engine/src/WebSocketClass.h +++ b/libraries/script-engine/src/WebSocketClass.h @@ -17,12 +17,11 @@ #include #include -#include + +#include "ScriptValue.h" class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * Provides a bi-directional, event-driven communication session between the script and another WebSocket connection. It is a @@ -93,10 +92,10 @@ class WebSocketClass : public QObject { Q_PROPERTY(ulong bufferedAmount READ getBufferedAmount) Q_PROPERTY(QString extensions READ getExtensions) - Q_PROPERTY(ScriptValuePointer onclose READ getOnClose WRITE setOnClose) - Q_PROPERTY(ScriptValuePointer onerror READ getOnError WRITE setOnError) - Q_PROPERTY(ScriptValuePointer onmessage READ getOnMessage WRITE setOnMessage) - Q_PROPERTY(ScriptValuePointer onopen READ getOnOpen WRITE setOnOpen) + Q_PROPERTY(ScriptValue onclose READ getOnClose WRITE setOnClose) + Q_PROPERTY(ScriptValue onerror READ getOnError WRITE setOnError) + Q_PROPERTY(ScriptValue onmessage READ getOnMessage WRITE setOnMessage) + Q_PROPERTY(ScriptValue onopen READ getOnOpen WRITE setOnOpen) Q_PROPERTY(QString protocol READ getProtocol) Q_PROPERTY(WebSocketClass::ReadyState readyState READ getReadyState) @@ -112,7 +111,7 @@ public: WebSocketClass(ScriptEngine* engine, QWebSocket* qWebSocket); ~WebSocketClass(); - static ScriptValuePointer constructor(ScriptContext* context, ScriptEngine* engine); + static ScriptValue constructor(ScriptContext* context, ScriptEngine* engine); /*@jsdoc * The state of a WebSocket connection. @@ -173,17 +172,17 @@ public: } } - void setOnClose(ScriptValuePointer eventFunction) { _onCloseEvent = eventFunction; } - ScriptValuePointer getOnClose() { return _onCloseEvent; } + void setOnClose(const ScriptValue& eventFunction) { _onCloseEvent = eventFunction; } + ScriptValue getOnClose() { return _onCloseEvent; } - void setOnError(ScriptValuePointer eventFunction) { _onErrorEvent = eventFunction; } - ScriptValuePointer getOnError() { return _onErrorEvent; } + void setOnError(const ScriptValue& eventFunction) { _onErrorEvent = eventFunction; } + ScriptValue getOnError() { return _onErrorEvent; } - void setOnMessage(ScriptValuePointer eventFunction) { _onMessageEvent = eventFunction; } - ScriptValuePointer getOnMessage() { return _onMessageEvent; } + void setOnMessage(const ScriptValue& eventFunction) { _onMessageEvent = eventFunction; } + ScriptValue getOnMessage() { return _onMessageEvent; } - void setOnOpen(ScriptValuePointer eventFunction) { _onOpenEvent = eventFunction; } - ScriptValuePointer getOnOpen() { return _onOpenEvent; } + void setOnOpen(const ScriptValue& eventFunction) { _onOpenEvent = eventFunction; } + ScriptValue getOnOpen() { return _onOpenEvent; } public slots: @@ -192,7 +191,7 @@ public slots: * @function WebSocket.send * @param {string|object} message - The message to send. If an object, it is converted to a string. */ - void send(ScriptValuePointer message); + void send(const ScriptValue& message); /*@jsdoc * Closes the connection. @@ -232,10 +231,10 @@ private: QWebSocket* _webSocket; ScriptEngine* _engine; - ScriptValuePointer _onCloseEvent; - ScriptValuePointer _onErrorEvent; - ScriptValuePointer _onMessageEvent; - ScriptValuePointer _onOpenEvent; + ScriptValue _onCloseEvent; + ScriptValue _onErrorEvent; + ScriptValue _onMessageEvent; + ScriptValue _onOpenEvent; QString _binaryType; @@ -253,14 +252,14 @@ private slots: Q_DECLARE_METATYPE(QWebSocketProtocol::CloseCode); Q_DECLARE_METATYPE(WebSocketClass::ReadyState); -ScriptValuePointer qWSCloseCodeToScriptValue(ScriptEngine* engine, const QWebSocketProtocol::CloseCode& closeCode); -void qWSCloseCodeFromScriptValue(const ScriptValuePointer& object, QWebSocketProtocol::CloseCode& closeCode); +ScriptValue qWSCloseCodeToScriptValue(ScriptEngine* engine, const QWebSocketProtocol::CloseCode& closeCode); +void qWSCloseCodeFromScriptValue(const ScriptValue& object, QWebSocketProtocol::CloseCode& closeCode); -ScriptValuePointer webSocketToScriptValue(ScriptEngine* engine, WebSocketClass* const &in); -void webSocketFromScriptValue(const ScriptValuePointer &object, WebSocketClass* &out); +ScriptValue webSocketToScriptValue(ScriptEngine* engine, WebSocketClass* const &in); +void webSocketFromScriptValue(const ScriptValue &object, WebSocketClass* &out); -ScriptValuePointer wscReadyStateToScriptValue(ScriptEngine* engine, const WebSocketClass::ReadyState& readyState); -void wscReadyStateFromScriptValue(const ScriptValuePointer& object, WebSocketClass::ReadyState& readyState); +ScriptValue wscReadyStateToScriptValue(ScriptEngine* engine, const WebSocketClass::ReadyState& readyState); +void wscReadyStateFromScriptValue(const ScriptValue& object, WebSocketClass::ReadyState& readyState); #endif // hifi_WebSocketClass_h diff --git a/libraries/script-engine/src/WebSocketServerClass.cpp b/libraries/script-engine/src/WebSocketServerClass.cpp index 17677a1fc6..304219952c 100644 --- a/libraries/script-engine/src/WebSocketServerClass.cpp +++ b/libraries/script-engine/src/WebSocketServerClass.cpp @@ -26,21 +26,21 @@ WebSocketServerClass::WebSocketServerClass(ScriptEngine* engine, const QString& } } -ScriptValuePointer WebSocketServerClass::constructor(ScriptContext* context, ScriptEngine* engine) { +ScriptValue WebSocketServerClass::constructor(ScriptContext* context, ScriptEngine* engine) { // the serverName is used in handshakes QString serverName = QStringLiteral("HighFidelity - Scripted WebSocket Listener"); // port 0 will auto-assign a free port quint16 port = 0; - ScriptValuePointer callee = context->callee(); + ScriptValue callee = context->callee(); if (context->argumentCount() > 0) { - ScriptValuePointer options = context->argument(0); - ScriptValuePointer portOption = options->property(QStringLiteral("port")); - if (portOption->isValid() && portOption->isNumber()) { - port = portOption->toNumber(); + ScriptValue options = context->argument(0); + ScriptValue portOption = options.property(QStringLiteral("port")); + if (portOption.isValid() && portOption.isNumber()) { + port = portOption.toNumber(); } - ScriptValuePointer serverNameOption = options->property(QStringLiteral("serverName")); - if (serverNameOption->isValid() && serverNameOption->isString()) { - serverName = serverNameOption->toString(); + ScriptValue serverNameOption = options.property(QStringLiteral("serverName")); + if (serverNameOption.isValid() && serverNameOption.isString()) { + serverName = serverNameOption.toString(); } } return engine->newQObject(new WebSocketServerClass(engine, serverName, port), ScriptEngine::ScriptOwnership); diff --git a/libraries/script-engine/src/WebSocketServerClass.h b/libraries/script-engine/src/WebSocketServerClass.h index 8063d8e507..8c9098929a 100644 --- a/libraries/script-engine/src/WebSocketServerClass.h +++ b/libraries/script-engine/src/WebSocketServerClass.h @@ -18,12 +18,11 @@ #include #include #include "WebSocketClass.h" -#include + +#include "ScriptValue.h" class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * Manages {@link WebSocket}s in server entity and assignment client scripts. @@ -96,7 +95,7 @@ public: quint16 getPort() { return _webSocketServer.serverPort(); } bool isListening() { return _webSocketServer.isListening(); } - static ScriptValuePointer constructor(ScriptContext* context, ScriptEngine* engine); + static ScriptValue constructor(ScriptContext* context, ScriptEngine* engine); public slots: diff --git a/libraries/script-engine/src/WheelEvent.cpp b/libraries/script-engine/src/WheelEvent.cpp index e6db63cc27..ee2be92bce 100644 --- a/libraries/script-engine/src/WheelEvent.cpp +++ b/libraries/script-engine/src/WheelEvent.cpp @@ -80,22 +80,22 @@ WheelEvent::WheelEvent(const QWheelEvent& event) { * print(JSON.stringify(event)); * }); */ -ScriptValuePointer WheelEvent::toScriptValue(ScriptEngine* engine, const WheelEvent& event) { - ScriptValuePointer obj = engine->newObject(); - obj->setProperty("x", event.x); - obj->setProperty("y", event.y); - obj->setProperty("delta", event.delta); - obj->setProperty("orientation", event.orientation); - obj->setProperty("isLeftButton", event.isLeftButton); - obj->setProperty("isRightButton", event.isRightButton); - obj->setProperty("isMiddleButton", event.isMiddleButton); - obj->setProperty("isShifted", event.isShifted); - obj->setProperty("isMeta", event.isMeta); - obj->setProperty("isControl", event.isControl); - obj->setProperty("isAlt", event.isAlt); +ScriptValue WheelEvent::toScriptValue(ScriptEngine* engine, const WheelEvent& event) { + ScriptValue obj = engine->newObject(); + obj.setProperty("x", event.x); + obj.setProperty("y", event.y); + obj.setProperty("delta", event.delta); + obj.setProperty("orientation", event.orientation); + obj.setProperty("isLeftButton", event.isLeftButton); + obj.setProperty("isRightButton", event.isRightButton); + obj.setProperty("isMiddleButton", event.isMiddleButton); + obj.setProperty("isShifted", event.isShifted); + obj.setProperty("isMeta", event.isMeta); + obj.setProperty("isControl", event.isControl); + obj.setProperty("isAlt", event.isAlt); return obj; } -void WheelEvent::fromScriptValue(const ScriptValuePointer& object, WheelEvent& event) { +void WheelEvent::fromScriptValue(const ScriptValue& object, WheelEvent& event) { // nothing for now... } diff --git a/libraries/script-engine/src/WheelEvent.h b/libraries/script-engine/src/WheelEvent.h index 80f9f0370a..9631c8d627 100644 --- a/libraries/script-engine/src/WheelEvent.h +++ b/libraries/script-engine/src/WheelEvent.h @@ -17,11 +17,10 @@ #include #include -#include + +#include "ScriptValue.h" class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// Represents a mouse wheel event to the scripting engine. Exposed as WheelEvent class WheelEvent { @@ -29,8 +28,8 @@ public: WheelEvent(); WheelEvent(const QWheelEvent& event); - static ScriptValuePointer toScriptValue(ScriptEngine* engine, const WheelEvent& event); - static void fromScriptValue(const ScriptValuePointer& object, WheelEvent& event); + static ScriptValue toScriptValue(ScriptEngine* engine, const WheelEvent& event); + static void fromScriptValue(const ScriptValue& object, WheelEvent& event); int x; int y; diff --git a/libraries/script-engine/src/XMLHttpRequestClass.cpp b/libraries/script-engine/src/XMLHttpRequestClass.cpp index 9585fd0aa1..f62a97fa94 100644 --- a/libraries/script-engine/src/XMLHttpRequestClass.cpp +++ b/libraries/script-engine/src/XMLHttpRequestClass.cpp @@ -25,6 +25,7 @@ #include "ResourceRequestObserver.h" #include "ScriptContext.h" #include "ScriptEngine.h" +#include "ScriptEngineCast.h" #include "ScriptValue.h" Q_DECLARE_METATYPE(QByteArray*) @@ -43,15 +44,15 @@ XMLHttpRequestClass::~XMLHttpRequestClass() { if (_reply) { _reply->deleteLater(); } } -ScriptValuePointer XMLHttpRequestClass::constructor(ScriptContext* context, ScriptEngine* engine) { +ScriptValue XMLHttpRequestClass::constructor(ScriptContext* context, ScriptEngine* engine) { return engine->newQObject(new XMLHttpRequestClass(engine), ScriptEngine::ScriptOwnership); } -ScriptValuePointer XMLHttpRequestClass::getStatus() const { +ScriptValue XMLHttpRequestClass::getStatus() const { if (_reply) { return _engine->newValue(_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()); } - return ScriptValuePointer(0); + return ScriptValue(_engine->newValue(0)); } QString XMLHttpRequestClass::getStatusText() const { @@ -91,7 +92,7 @@ void XMLHttpRequestClass::requestDownloadProgress(qint64 bytesReceived, qint64 b } } -ScriptValuePointer XMLHttpRequestClass::getAllResponseHeaders() const { +ScriptValue XMLHttpRequestClass::getAllResponseHeaders() const { if (_reply) { QList headerList = _reply->rawHeaderPairs(); QByteArray headers; @@ -106,7 +107,7 @@ ScriptValuePointer XMLHttpRequestClass::getAllResponseHeaders() const { return _engine->newValue(""); } -ScriptValuePointer XMLHttpRequestClass::getResponseHeader(const QString& name) const { +ScriptValue XMLHttpRequestClass::getResponseHeader(const QString& name) const { if (_reply && _reply->hasRawHeader(name.toLatin1())) { return _engine->newValue(QString(_reply->rawHeader(name.toLatin1()))); } @@ -120,8 +121,8 @@ ScriptValuePointer XMLHttpRequestClass::getResponseHeader(const QString& name) c void XMLHttpRequestClass::setReadyState(ReadyState readyState) { if (readyState != _readyState) { _readyState = readyState; - if (_onReadyStateChange->isFunction()) { - _onReadyStateChange->call(_onReadyStateChange->engine()->nullValue()); + if (_onReadyStateChange.isFunction()) { + _onReadyStateChange.call(_onReadyStateChange.engine()->nullValue()); } } } @@ -160,14 +161,14 @@ void XMLHttpRequestClass::send() { send(_engine->nullValue()); } -void XMLHttpRequestClass::send(const ScriptValuePointer& data) { +void XMLHttpRequestClass::send(const ScriptValue& data) { if (_readyState == OPENED && !_reply) { if (!data.isNull()) { - if (data->isObject()) { + if (data.isObject()) { _sendData = scriptvalue_cast(data); } else { - _sendData = data->toString().toUtf8(); + _sendData = data.toString().toUtf8(); } } @@ -197,8 +198,8 @@ void XMLHttpRequestClass::doSend() { * @callback XMLHttpRequest~onTimeoutCallback */ void XMLHttpRequestClass::requestTimeout() { - if (_onTimeout->isFunction()) { - _onTimeout->call(_engine->nullValue()); + if (_onTimeout.isFunction()) { + _onTimeout.call(_engine->nullValue()); } abortRequest(); _errorCode = QNetworkReply::TimeoutError; @@ -219,7 +220,7 @@ void XMLHttpRequestClass::requestFinished() { if (_responseType == "json") { _responseData = _engine->evaluate("(" + QString(_rawResponseData.data()) + ")"); - if (_responseData->isError()) { + if (_responseData.isError()) { _engine->clearExceptions(); _responseData = _engine->nullValue(); } diff --git a/libraries/script-engine/src/XMLHttpRequestClass.h b/libraries/script-engine/src/XMLHttpRequestClass.h index 322769400f..cf29b7dbfb 100644 --- a/libraries/script-engine/src/XMLHttpRequestClass.h +++ b/libraries/script-engine/src/XMLHttpRequestClass.h @@ -20,13 +20,11 @@ #include #include #include -#include #include "ScriptEngine.h" +#include "ScriptValue.h" class ScriptContext; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /* XMlHttpRequest object @@ -58,7 +56,7 @@ XMlHttpRequest.open(QString,QString,bool,QString) function XMlHttpRequest.open(QString,QString,bool) function XMlHttpRequest.open(QString,QString) function XMlHttpRequest.send() function -XMlHttpRequest.send(ScriptValuePointer) function +XMlHttpRequest.send(ScriptValue) function XMlHttpRequest.getAllResponseHeaders() function XMlHttpRequest.getResponseHeader(QString) function */ @@ -159,13 +157,13 @@ XMlHttpRequest.getResponseHeader(QString) function /// Provides the XMLHttpRequest scripting interface class XMLHttpRequestClass : public QObject { Q_OBJECT - Q_PROPERTY(ScriptValuePointer response READ getResponse) - Q_PROPERTY(ScriptValuePointer responseText READ getResponseText) + Q_PROPERTY(ScriptValue response READ getResponse) + Q_PROPERTY(ScriptValue responseText READ getResponseText) Q_PROPERTY(QString responseType READ getResponseType WRITE setResponseType) - Q_PROPERTY(ScriptValuePointer status READ getStatus) + Q_PROPERTY(ScriptValue status READ getStatus) Q_PROPERTY(QString statusText READ getStatusText) - Q_PROPERTY(ScriptValuePointer readyState READ getReadyState) - Q_PROPERTY(ScriptValuePointer errorCode READ getError) + Q_PROPERTY(ScriptValue readyState READ getReadyState) + Q_PROPERTY(ScriptValue errorCode READ getError) Q_PROPERTY(int timeout READ getTimeout WRITE setTimeout) Q_PROPERTY(int UNSENT READ getUnsent) @@ -175,8 +173,8 @@ class XMLHttpRequestClass : public QObject { Q_PROPERTY(int DONE READ getDone) // Callbacks - Q_PROPERTY(ScriptValuePointer ontimeout READ getOnTimeout WRITE setOnTimeout) - Q_PROPERTY(ScriptValuePointer onreadystatechange READ getOnReadyStateChange WRITE setOnReadyStateChange) + Q_PROPERTY(ScriptValue ontimeout READ getOnTimeout WRITE setOnTimeout) + Q_PROPERTY(ScriptValue onreadystatechange READ getOnReadyStateChange WRITE setOnReadyStateChange) public: XMLHttpRequestClass(ScriptEngine* engine); ~XMLHttpRequestClass(); @@ -216,23 +214,23 @@ public: int getLoading() const { return LOADING; }; int getDone() const { return DONE; }; - static ScriptValuePointer constructor(ScriptContext* context, ScriptEngine* engine); + static ScriptValue constructor(ScriptContext* context, ScriptEngine* engine); int getTimeout() const { return _timeout; } void setTimeout(int timeout) { _timeout = timeout; } - ScriptValuePointer getResponse() const { return _responseData; } - ScriptValuePointer getResponseText() const { return _engine->newValue(QString(_rawResponseData.data())); } + ScriptValue getResponse() const { return _responseData; } + ScriptValue getResponseText() const { return _engine->newValue(QString(_rawResponseData.data())); } QString getResponseType() const { return _responseType; } void setResponseType(const QString& responseType) { _responseType = responseType; } - ScriptValuePointer getReadyState() const { return _engine->newValue(_readyState); } - ScriptValuePointer getError() const { return _engine->newValue(_errorCode); } - ScriptValuePointer getStatus() const; + ScriptValue getReadyState() const { return _engine->newValue(_readyState); } + ScriptValue getError() const { return _engine->newValue(_errorCode); } + ScriptValue getStatus() const; QString getStatusText() const; - ScriptValuePointer getOnTimeout() const { return _onTimeout; } - void setOnTimeout(ScriptValuePointer function) { _onTimeout = function; } - ScriptValuePointer getOnReadyStateChange() const { return _onReadyStateChange; } - void setOnReadyStateChange(ScriptValuePointer function) { _onReadyStateChange = function; } + ScriptValue getOnTimeout() const { return _onTimeout; } + void setOnTimeout(const ScriptValue& function) { _onTimeout = function; } + ScriptValue getOnReadyStateChange() const { return _onReadyStateChange; } + void setOnReadyStateChange(const ScriptValue& function) { _onReadyStateChange = function; } public slots: @@ -271,14 +269,14 @@ public slots: * @param {*} [data] - The data to send. */ void send(); - void send(const ScriptValuePointer& data); + void send(const ScriptValue& data); /*@jsdoc * Gets the response headers. * @function XMLHttpRequest.getAllResponseHeaders * @returns {string} The response headers, separated by "\n" characters. */ - ScriptValuePointer getAllResponseHeaders() const; + ScriptValue getAllResponseHeaders() const; /*@jsdoc * Gets a response header. @@ -286,7 +284,7 @@ public slots: * @param {string} name - * @returns {string} The response header. */ - ScriptValuePointer getResponseHeader(const QString& name) const; + ScriptValue getResponseHeader(const QString& name) const; signals: @@ -313,9 +311,9 @@ private: QNetworkReply* _reply { nullptr }; QByteArray _sendData; QByteArray _rawResponseData; - ScriptValuePointer _responseData; - ScriptValuePointer _onTimeout; - ScriptValuePointer _onReadyStateChange; + ScriptValue _responseData; + ScriptValue _onTimeout; + ScriptValue _onReadyStateChange; ReadyState _readyState { XMLHttpRequestClass::UNSENT }; /*@jsdoc diff --git a/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.cpp b/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.cpp index 798d93a0ea..75172bed12 100644 --- a/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.cpp +++ b/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.cpp @@ -28,18 +28,18 @@ int ScriptContextQtWrapper::argumentCount() const { return _context->argumentCount(); } -ScriptValuePointer ScriptContextQtWrapper::argument(int index) const { +ScriptValue ScriptContextQtWrapper::argument(int index) const { QScriptValue result = _context->argument(index); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } QStringList ScriptContextQtWrapper::backtrace() const { return _context->backtrace(); } -ScriptValuePointer ScriptContextQtWrapper::callee() const { +ScriptValue ScriptContextQtWrapper::callee() const { QScriptValue result = _context->callee(); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } ScriptEnginePointer ScriptContextQtWrapper::engine() const { @@ -55,23 +55,23 @@ ScriptContextPointer ScriptContextQtWrapper::parentContext() const { return result ? ScriptContextPointer(new ScriptContextQtWrapper(_engine, result)) : ScriptContextPointer(); } -ScriptValuePointer ScriptContextQtWrapper::thisObject() const { +ScriptValue ScriptContextQtWrapper::thisObject() const { QScriptValue result = _context->thisObject(); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -ScriptValuePointer ScriptContextQtWrapper::throwError(const QString& text) { +ScriptValue ScriptContextQtWrapper::throwError(const QString& text) { QScriptValue result = _context->throwError(text); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -ScriptValuePointer ScriptContextQtWrapper::throwValue(const ScriptValuePointer& value) { +ScriptValue ScriptContextQtWrapper::throwValue(const ScriptValue& value) { ScriptValueQtWrapper* unwrapped = ScriptValueQtWrapper::unwrap(value); if (!unwrapped) { return _engine->undefinedValue(); } QScriptValue result = _context->throwValue(unwrapped->toQtValue()); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } diff --git a/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.h b/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.h index b2f7726d85..db542799c8 100644 --- a/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.h +++ b/libraries/script-engine/src/qtscript/ScriptContextQtWrapper.h @@ -15,16 +15,14 @@ #ifndef hifi_ScriptContextQtWrapper_h #define hifi_ScriptContextQtWrapper_h -#include #include #include #include "../ScriptContext.h" +#include "../ScriptValue.h" class QScriptContext; class ScriptEngineQtScript; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /// [QtScript] Implements ScriptContext for QtScript and translates calls for QScriptContextInfo class ScriptContextQtWrapper : public ScriptContext { @@ -35,15 +33,15 @@ public: // construction public: // ScriptContext implementation virtual int argumentCount() const; - virtual ScriptValuePointer argument(int index) const; + virtual ScriptValue argument(int index) const; virtual QStringList backtrace() const; - virtual ScriptValuePointer callee() const; + virtual ScriptValue callee() const; virtual ScriptEnginePointer engine() const; virtual ScriptFunctionContextPointer functionContext() const; virtual ScriptContextPointer parentContext() const; - virtual ScriptValuePointer thisObject() const; - virtual ScriptValuePointer throwError(const QString& text); - virtual ScriptValuePointer throwValue(const ScriptValuePointer& value); + virtual ScriptValue thisObject() const; + virtual ScriptValue throwError(const QString& text); + virtual ScriptValue throwValue(const ScriptValue& value); private: // storage QScriptContext* _context; diff --git a/libraries/script-engine/src/qtscript/ScriptEngineQtScript.cpp b/libraries/script-engine/src/qtscript/ScriptEngineQtScript.cpp index 7700d778d2..f18bf1d010 100644 --- a/libraries/script-engine/src/qtscript/ScriptEngineQtScript.cpp +++ b/libraries/script-engine/src/qtscript/ScriptEngineQtScript.cpp @@ -62,7 +62,7 @@ static const QScriptValue::PropertyFlags READONLY_HIDDEN_PROP_FLAGS { READONLY_P static const bool HIFI_AUTOREFRESH_FILE_SCRIPTS { true }; -Q_DECLARE_METATYPE(ScriptValuePointer); +Q_DECLARE_METATYPE(ScriptValue); Q_DECLARE_METATYPE(QScriptEngine::FunctionSignature) int qfunctionSignatureMetaID = qRegisterMetaType(); @@ -120,26 +120,26 @@ QScriptValue ScriptEngineQtScript::makeError(const QScriptValue& _other, const Q return err; } -ScriptValuePointer ScriptEngineQtScript::makeError(const ScriptValuePointer& _other, const QString& type) { +ScriptValue ScriptEngineQtScript::makeError(const ScriptValue& _other, const QString& type) { if (!IS_THREADSAFE_INVOCATION(thread(), __FUNCTION__)) { return nullValue(); } ScriptValueQtWrapper* unwrapped = ScriptValueQtWrapper::unwrap(_other); QScriptValue other; - if (_other->isString()) { + if (_other.isString()) { other = QScriptEngine::newObject(); - other.setProperty("message", _other->toString()); + other.setProperty("message", _other.toString()); } else if (unwrapped) { other = unwrapped->toQtValue(); } else { - other = QScriptEngine::newVariant(_other->toVariant()); + other = QScriptEngine::newVariant(_other.toVariant()); } QScriptValue result = makeError(other, type); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } // check syntax and when there are issues returns an actual "SyntaxError" with the details -ScriptValuePointer ScriptEngineQtScript::lintScript(const QString& sourceCode, const QString& fileName, const int lineNumber) { +ScriptValue ScriptEngineQtScript::lintScript(const QString& sourceCode, const QString& fileName, const int lineNumber) { if (!IS_THREADSAFE_INVOCATION(thread(), __FUNCTION__)) { return nullValue(); } @@ -158,13 +158,13 @@ ScriptValuePointer ScriptEngineQtScript::lintScript(const QString& sourceCode, c const auto message = QString("[SyntaxError] %1 in %2:%3(%4)").arg(error, fileName, line, column); err.setProperty("formatted", message); } - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(err))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(err))); } return undefinedValue(); } // this pulls from the best available information to create a detailed snapshot of the current exception -ScriptValuePointer ScriptEngineQtScript::cloneUncaughtException(const QString& extraDetail) { +ScriptValue ScriptEngineQtScript::cloneUncaughtException(const QString& extraDetail) { if (!IS_THREADSAFE_INVOCATION(thread(), __FUNCTION__)) { return nullValue(); } @@ -178,17 +178,17 @@ ScriptValuePointer ScriptEngineQtScript::cloneUncaughtException(const QString& e // not sure why Qt does't offer uncaughtExceptionFileName -- but the line number // on its own is often useless/wrong if arbitrarily married to a filename. // when the error object already has this info, it seems to be the most reliable - auto fileName = exception->property("fileName")->toString(); - auto lineNumber = exception->property("lineNumber")->toInt32(); + auto fileName = exception.property("fileName").toString(); + auto lineNumber = exception.property("lineNumber").toInt32(); // the backtrace, on the other hand, seems most reliable taken from uncaughtExceptionBacktrace auto backtrace = uncaughtExceptionBacktrace(); if (backtrace.isEmpty()) { // fallback to the error object - backtrace = exception->property("stack")->toString().split(ScriptManager::SCRIPT_BACKTRACE_SEP); + backtrace = exception.property("stack").toString().split(ScriptManager::SCRIPT_BACKTRACE_SEP); } // the ad hoc "detail" property can be used now to embed additional clues - auto detail = exception->property("detail")->toString(); + auto detail = exception.property("detail").toString(); if (detail.isEmpty()) { detail = extraDetail; } else if (!extraDetail.isEmpty()) { @@ -212,15 +212,15 @@ ScriptValuePointer ScriptEngineQtScript::cloneUncaughtException(const QString& e } } } - err->setProperty("fileName", fileName); - err->setProperty("lineNumber", lineNumber); - err->setProperty("detail", detail); - err->setProperty("stack", backtrace.join(ScriptManager::SCRIPT_BACKTRACE_SEP)); + err.setProperty("fileName", fileName); + err.setProperty("lineNumber", lineNumber); + err.setProperty("detail", detail); + err.setProperty("stack", backtrace.join(ScriptManager::SCRIPT_BACKTRACE_SEP)); #ifdef DEBUG_JS_EXCEPTIONS - err->setProperty("_fileName", exception.property("fileName").toString()); - err->setProperty("_stack", uncaughtExceptionBacktrace().join(SCRIPT_BACKTRACE_SEP)); - err->setProperty("_lineNumber", uncaughtExceptionLineNumber()); + err.setProperty("_fileName", exception.property("fileName").toString()); + err.setProperty("_stack", uncaughtExceptionBacktrace().join(SCRIPT_BACKTRACE_SEP)); + err.setProperty("_lineNumber", uncaughtExceptionLineNumber()); #endif return err; } @@ -237,7 +237,7 @@ bool ScriptEngineQtScript::raiseException(const QScriptValue& exception) { // we are within a pure C++ stack frame (ie: being called directly by other C++ code) // in this case no context information is available so just emit the exception for reporting QScriptValue thrown = makeError(exception); - emit _manager->unhandledException(ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(thrown)))); + emit _manager->unhandledException(ScriptValue(new ScriptValueQtWrapper(this, std::move(thrown)))); } return false; } @@ -383,13 +383,13 @@ static QScriptValue debugPrint(QScriptContext* context, QScriptEngine* engine) { return QScriptValue(); } -static QScriptValue ScriptValueToQScriptValue(QScriptEngine* engine, const ScriptValuePointer& src) { +static QScriptValue ScriptValueToQScriptValue(QScriptEngine* engine, const ScriptValue& src) { return ScriptValueQtWrapper::fullUnwrap(static_cast(engine), src); } -static void ScriptValueFromQScriptValue(const QScriptValue& src, ScriptValuePointer& dest) { +static void ScriptValueFromQScriptValue(const QScriptValue& src, ScriptValue& dest) { ScriptEngineQtScript* engine = static_cast(src.engine()); - dest = ScriptValuePointer(new ScriptValueQtWrapper(engine, src)); + dest = ScriptValue(new ScriptValueQtWrapper(engine, src)); } ScriptEngineQtScript::ScriptEngineQtScript(ScriptManager* scriptManager) : @@ -408,17 +408,17 @@ ScriptEngineQtScript::ScriptEngineQtScript(ScriptManager* scriptManager) : } else { // ... but may not always be available -- so if needed we fallback to the passed exception QScriptValue thrown = makeError(exception); - emit _manager->unhandledException(ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(thrown)))); + emit _manager->unhandledException(ScriptValue(new ScriptValueQtWrapper(this, std::move(thrown)))); } }, Qt::DirectConnection); moveToThread(scriptManager->thread()); } QScriptValue null = QScriptEngine::nullValue(); - _nullValue = ScriptValuePointer(new ScriptValueQtWrapper(const_cast(this), std::move(null))); + _nullValue = ScriptValue(new ScriptValueQtWrapper(const_cast(this), std::move(null))); QScriptValue undefined = QScriptEngine::undefinedValue(); - _undefinedValue = ScriptValuePointer(new ScriptValueQtWrapper(const_cast(this), std::move(undefined))); + _undefinedValue = ScriptValue(new ScriptValueQtWrapper(const_cast(this), std::move(undefined))); QScriptEngine::setProcessEventsInterval(MSECS_PER_SECOND); } @@ -478,14 +478,14 @@ void ScriptEngineQtScript::registerValue(const QString& valueName, QScriptValue QStringList pathToValue = valueName.split("."); int partsToGo = pathToValue.length(); - QScriptValue partObject = globalObject(); + QScriptValue partObject = QScriptEngine::globalObject(); for (const auto& pathPart : pathToValue) { partsToGo--; if (!partObject.property(pathPart).isValid()) { if (partsToGo > 0) { //QObject *object = new QObject; - QScriptValue partValue = newArray(); //newQObject(object, QScriptEngine::ScriptOwnership); + QScriptValue partValue = QScriptEngine::newArray(); //newQObject(object, QScriptEngine::ScriptOwnership); partObject.setProperty(pathPart, partValue); } else { partObject.setProperty(pathPart, value); @@ -554,7 +554,7 @@ void ScriptEngineQtScript::registerFunction(const QString& name, ScriptEngine::F #endif auto scriptFun = newFunction(functionSignature, numArguments); - globalObject()->setProperty(name, scriptFun); + globalObject().setProperty(name, scriptFun); } void ScriptEngineQtScript::registerFunction(const QString& parent, const QString& name, QScriptEngine::FunctionSignature functionSignature, int numArguments) { @@ -594,10 +594,10 @@ void ScriptEngineQtScript::registerFunction(const QString& parent, const QString qCDebug(scriptengine) << "ScriptEngineQtScript::registerFunction() called on thread [" << QThread::currentThread() << "] parent:" << parent << "name:" << name; #endif - auto object = globalObject()->property(parent); - if (object->isValid()) { + auto object = globalObject().property(parent); + if (object.isValid()) { auto scriptFun = newFunction(functionSignature, numArguments); - object->setProperty(name, scriptFun); + object.setProperty(name, scriptFun); } } @@ -656,18 +656,18 @@ void ScriptEngineQtScript::registerGetterSetter(const QString& name, ScriptEngin auto getterFunction = newFunction(getter); if (!parent.isNull() && !parent.isEmpty()) { - auto object = globalObject()->property(parent); - if (object->isValid()) { - object->setProperty(name, setterFunction, ScriptValue::PropertySetter); - object->setProperty(name, getterFunction, ScriptValue::PropertyGetter); + auto object = globalObject().property(parent); + if (object.isValid()) { + object.setProperty(name, setterFunction, ScriptValue::PropertySetter); + object.setProperty(name, getterFunction, ScriptValue::PropertyGetter); } } else { - globalObject()->setProperty(name, setterFunction, ScriptValue::PropertySetter); - globalObject()->setProperty(name, getterFunction, ScriptValue::PropertyGetter); + globalObject().setProperty(name, setterFunction, ScriptValue::PropertySetter); + globalObject().setProperty(name, getterFunction, ScriptValue::PropertyGetter); } } -ScriptValuePointer ScriptEngineQtScript::evaluateInClosure(const ScriptValuePointer& _closure, +ScriptValue ScriptEngineQtScript::evaluateInClosure(const ScriptValue& _closure, const ScriptProgramPointer& _program) { PROFILE_RANGE(script, "evaluateInClosure"); if (!IS_THREADSAFE_INVOCATION(thread(), __FUNCTION__)) { @@ -712,7 +712,7 @@ ScriptValuePointer ScriptEngineQtScript::evaluateInClosure(const ScriptValuePoin #ifdef DEBUG_JS qCDebug(shared) << QString("[%1] evaluateInClosure %2").arg(isEvaluating()).arg(shortName); #endif - ScriptValuePointer result; + ScriptValue result; { auto qResult = QScriptEngine::evaluate(program); @@ -724,7 +724,7 @@ ScriptValuePointer ScriptEngineQtScript::evaluateInClosure(const ScriptValuePoin #endif result = err; } else { - result = ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(qResult))); + result = ScriptValue(new ScriptValueQtWrapper(this, std::move(qResult))); } } #ifdef DEBUG_JS @@ -742,19 +742,19 @@ ScriptValuePointer ScriptEngineQtScript::evaluateInClosure(const ScriptValuePoin return result; } -ScriptValuePointer ScriptEngineQtScript::evaluate(const QString& sourceCode, const QString& fileName) { +ScriptValue ScriptEngineQtScript::evaluate(const QString& sourceCode, const QString& fileName) { if (_manager && _manager->isStopped()) { return undefinedValue(); // bail early } if (QThread::currentThread() != QScriptEngine::thread()) { - ScriptValuePointer result; + ScriptValue result; #ifdef THREAD_DEBUGGING qCDebug(scriptengine) << "*** WARNING *** ScriptEngineQtScript::evaluate() called on wrong thread [" << QThread::currentThread() << "], invoking on correct thread [" << thread() << "] " "sourceCode:" << sourceCode << " fileName:" << fileName; #endif BLOCKING_INVOKE_METHOD(this, "evaluate", - Q_RETURN_ARG(ScriptValuePointer, result), + Q_RETURN_ARG(ScriptValue, result), Q_ARG(const QString&, sourceCode), Q_ARG(const QString&, fileName)); return result; @@ -762,9 +762,9 @@ ScriptValuePointer ScriptEngineQtScript::evaluate(const QString& sourceCode, con // Check syntax auto syntaxError = lintScript(sourceCode, fileName); - if (syntaxError->isError()) { + if (syntaxError.isError()) { if (!isEvaluating()) { - syntaxError->setProperty("detail", "evaluate"); + syntaxError.setProperty("detail", "evaluate"); } raiseException(syntaxError); maybeEmitUncaughtException("lint"); @@ -782,22 +782,22 @@ ScriptValuePointer ScriptEngineQtScript::evaluate(const QString& sourceCode, con QScriptValue result = QScriptEngine::evaluate(program); maybeEmitUncaughtException("evaluate"); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -Q_INVOKABLE ScriptValuePointer ScriptEngineQtScript::evaluate(const ScriptProgramPointer& program) { +Q_INVOKABLE ScriptValue ScriptEngineQtScript::evaluate(const ScriptProgramPointer& program) { if (_manager && _manager->isStopped()) { return undefinedValue(); // bail early } if (QThread::currentThread() != QScriptEngine::thread()) { - ScriptValuePointer result; + ScriptValue result; #ifdef THREAD_DEBUGGING qCDebug(scriptengine) << "*** WARNING *** ScriptEngineQtScript::evaluate() called on wrong thread [" << QThread::currentThread() << "], invoking on correct thread [" << thread() << "] " "sourceCode:" << sourceCode << " fileName:" << fileName; #endif BLOCKING_INVOKE_METHOD(this, "evaluate", - Q_RETURN_ARG(ScriptValuePointer, result), + Q_RETURN_ARG(ScriptValue, result), Q_ARG(const ScriptProgramPointer&, program)); return result; } @@ -822,7 +822,7 @@ Q_INVOKABLE ScriptValuePointer ScriptEngineQtScript::evaluate(const ScriptProgra QScriptValue result = QScriptEngine::evaluate(qProgram); maybeEmitUncaughtException("evaluate"); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } @@ -849,21 +849,21 @@ void ScriptEngineQtScript::print(const QString& message) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ScriptEngine implementation -ScriptValuePointer ScriptEngineQtScript::globalObject() const { +ScriptValue ScriptEngineQtScript::globalObject() const { QScriptValue global = QScriptEngine::globalObject(); // can't cache the value as it may change - return ScriptValuePointer(new ScriptValueQtWrapper(const_cast < ScriptEngineQtScript*>(this), std::move(global))); + return ScriptValue(new ScriptValueQtWrapper(const_cast < ScriptEngineQtScript*>(this), std::move(global))); } ScriptManager* ScriptEngineQtScript::manager() const { return _manager; } -ScriptValuePointer ScriptEngineQtScript::newArray(uint length) { +ScriptValue ScriptEngineQtScript::newArray(uint length) { QScriptValue result = QScriptEngine::newArray(length); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newArrayBuffer(const QByteArray& message) { +ScriptValue ScriptEngineQtScript::newArrayBuffer(const QByteArray& message) { QScriptValue data = QScriptEngine::newVariant(QVariant::fromValue(message)); QScriptValue ctor = QScriptEngine::globalObject().property("ArrayBuffer"); auto array = qscriptvalue_cast(ctor.data()); @@ -871,12 +871,12 @@ ScriptValuePointer ScriptEngineQtScript::newArrayBuffer(const QByteArray& messag return undefinedValue(); } QScriptValue result = QScriptEngine::newObject(array, data); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newObject() { +ScriptValue ScriptEngineQtScript::newObject() { QScriptValue result = QScriptEngine::newObject(); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } ScriptProgramPointer ScriptEngineQtScript::newProgram(const QString& sourceCode, const QString& fileName) { @@ -884,66 +884,66 @@ ScriptProgramPointer ScriptEngineQtScript::newProgram(const QString& sourceCode, return ScriptProgramPointer(new ScriptProgramQtWrapper(this, result)); } -ScriptValuePointer ScriptEngineQtScript::newQObject(QObject* object, +ScriptValue ScriptEngineQtScript::newQObject(QObject* object, ScriptEngine::ValueOwnership ownership, const ScriptEngine::QObjectWrapOptions& options) { QScriptValue result = QScriptEngine::newQObject(object, static_cast(ownership), (QScriptEngine::QObjectWrapOptions)((int)options | DEFAULT_QOBJECT_WRAP_OPTIONS)); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newValue(bool value) { +ScriptValue ScriptEngineQtScript::newValue(bool value) { QScriptValue result(this, value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newValue(int value) { +ScriptValue ScriptEngineQtScript::newValue(int value) { QScriptValue result(this, value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newValue(uint value) { +ScriptValue ScriptEngineQtScript::newValue(uint value) { QScriptValue result(this, value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newValue(double value) { +ScriptValue ScriptEngineQtScript::newValue(double value) { QScriptValue result(this, value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newValue(const QString& value) { +ScriptValue ScriptEngineQtScript::newValue(const QString& value) { QScriptValue result(this, value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newValue(const QLatin1String& value) { +ScriptValue ScriptEngineQtScript::newValue(const QLatin1String& value) { QScriptValue result(this, value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newValue(const char* value) { +ScriptValue ScriptEngineQtScript::newValue(const char* value) { QScriptValue result(this, value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::newVariant(const QVariant& value) { +ScriptValue ScriptEngineQtScript::newVariant(const QVariant& value) { QScriptValue result = QScriptEngine::newVariant(value); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } -ScriptValuePointer ScriptEngineQtScript::nullValue() { +ScriptValue ScriptEngineQtScript::nullValue() { return _nullValue; } -void ScriptEngineQtScript::setDefaultPrototype(int metaTypeId, const ScriptValuePointer& prototype){ +void ScriptEngineQtScript::setDefaultPrototype(int metaTypeId, const ScriptValue& prototype){ ScriptValueQtWrapper* unwrappedPrototype = ScriptValueQtWrapper::unwrap(prototype); if (unwrappedPrototype) { QScriptEngine::setDefaultPrototype(metaTypeId, unwrappedPrototype->toQtValue()); } } -ScriptValuePointer ScriptEngineQtScript::undefinedValue() { +ScriptValue ScriptEngineQtScript::undefinedValue() { return _undefinedValue; } @@ -974,14 +974,14 @@ bool ScriptEngineQtScript::isEvaluating() const { return QScriptEngine::isEvaluating(); } -ScriptValuePointer ScriptEngineQtScript::newFunction(ScriptEngine::FunctionSignature fun, int length) { +ScriptValue ScriptEngineQtScript::newFunction(ScriptEngine::FunctionSignature fun, int length) { auto innerFunc = [](QScriptContext* _context, QScriptEngine* _engine) -> QScriptValue { auto callee = _context->callee(); QVariant funAddr = callee.property("_func").toVariant(); ScriptEngine::FunctionSignature fun = reinterpret_cast(funAddr.toULongLong()); ScriptEngineQtScript* engine = static_cast(_engine); ScriptContextQtWrapper context(engine, _context); - ScriptValuePointer result = fun(&context, engine); + ScriptValue result = fun(&context, engine); ScriptValueQtWrapper* unwrapped = ScriptValueQtWrapper::unwrap(result); return unwrapped ? unwrapped->toQtValue() : QScriptValue(); }; @@ -989,7 +989,7 @@ ScriptValuePointer ScriptEngineQtScript::newFunction(ScriptEngine::FunctionSigna QScriptValue result = QScriptEngine::newFunction(innerFunc, length); auto funAddr = QScriptEngine::newVariant(QVariant(reinterpret_cast(fun))); result.setProperty("_func", funAddr, QScriptValue::PropertyFlags(QScriptValue::ReadOnly + QScriptValue::Undeletable + QScriptValue::SkipInEnumeration)); - return ScriptValuePointer(new ScriptValueQtWrapper(this, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(this, std::move(result))); } void ScriptEngineQtScript::setObjectName(const QString& name) { @@ -1012,9 +1012,9 @@ void ScriptEngineQtScript::setThread(QThread* thread) { moveToThread(thread); } -ScriptValuePointer ScriptEngineQtScript::uncaughtException() const { +ScriptValue ScriptEngineQtScript::uncaughtException() const { QScriptValue result = QScriptEngine::uncaughtException(); - return ScriptValuePointer(new ScriptValueQtWrapper(const_cast(this), std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(const_cast(this), std::move(result))); } QStringList ScriptEngineQtScript::uncaughtExceptionBacktrace() const { @@ -1025,18 +1025,18 @@ int ScriptEngineQtScript::uncaughtExceptionLineNumber() const { return QScriptEngine::uncaughtExceptionLineNumber(); } -bool ScriptEngineQtScript::raiseException(const ScriptValuePointer& exception) { +bool ScriptEngineQtScript::raiseException(const ScriptValue& exception) { ScriptValueQtWrapper* unwrapped = ScriptValueQtWrapper::unwrap(exception); - QScriptValue qException = unwrapped ? unwrapped->toQtValue() : QScriptEngine::newVariant(exception->toVariant()); + QScriptValue qException = unwrapped ? unwrapped->toQtValue() : QScriptEngine::newVariant(exception.toVariant()); return raiseException(qException); } -ScriptValuePointer ScriptEngineQtScript::create(int type, const void* ptr) { +ScriptValue ScriptEngineQtScript::create(int type, const void* ptr) { QScriptValue result = qScriptValueFromValue_helper(this, type, ptr); - return ScriptValuePointer(new ScriptValueQtWrapper(const_cast(this), std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(const_cast(this), std::move(result))); } -bool ScriptEngineQtScript::convert(const ScriptValuePointer& value, int type, void* ptr) { +bool ScriptEngineQtScript::convert(const ScriptValue& value, int type, void* ptr) { ScriptValueQtWrapper* unwrapped = ScriptValueQtWrapper::unwrap(value); if (unwrapped == nullptr) { return false; @@ -1052,13 +1052,13 @@ public: static QScriptValue internalMarshalFunc(QScriptEngine* engine, const void* src) { ScriptEngineQtScript* unwrappedEngine = static_cast(engine); - ScriptValuePointer dest = marshalFunc(unwrappedEngine, src); + ScriptValue dest = marshalFunc(unwrappedEngine, src); return ScriptValueQtWrapper::fullUnwrap(unwrappedEngine, dest); } static void internalDemarshalFunc(const QScriptValue& src, void* dest) { ScriptEngineQtScript* unwrappedEngine = static_cast(src.engine()); - ScriptValuePointer wrappedSrc(new ScriptValueQtWrapper(unwrappedEngine, src)); + ScriptValue wrappedSrc(new ScriptValueQtWrapper(unwrappedEngine, src)); demarshalFunc(wrappedSrc, dest); } }; @@ -1094,7 +1094,7 @@ ScriptEngine::DemarshalFunction CustomTypeInstance::demarshalFunc; void ScriptEngineQtScript::registerCustomType(int type, ScriptEngine::MarshalFunction marshalFunc, ScriptEngine::DemarshalFunction demarshalFunc, - const ScriptValuePointer& prototype) + const ScriptValue& prototype) { QScriptValue unwrapped = ScriptValueQtWrapper::fullUnwrap(this, prototype); QScriptEngine::MarshalFunction internalMarshalFunc; diff --git a/libraries/script-engine/src/qtscript/ScriptEngineQtScript.h b/libraries/script-engine/src/qtscript/ScriptEngineQtScript.h index 1c8d9ce781..61c5dbbf96 100644 --- a/libraries/script-engine/src/qtscript/ScriptEngineQtScript.h +++ b/libraries/script-engine/src/qtscript/ScriptEngineQtScript.h @@ -47,51 +47,51 @@ class ScriptEngineQtScript : public QScriptEngine, public ScriptEngine, public Q public: // ScriptEngine implementation virtual void abortEvaluation(); virtual void clearExceptions(); - virtual ScriptValuePointer cloneUncaughtException(const QString& detail = QString()); + virtual ScriptValue cloneUncaughtException(const QString& detail = QString()); virtual ScriptContext* currentContext() const; - //virtual ScriptValuePointer evaluate(const QString& program, const QString& fileName = QString()); - //virtual ScriptValuePointer evaluate(const ScriptProgramPointer &program); - //virtual ScriptValuePointer evaluateInClosure(const ScriptValuePointer& locals, const ScriptProgramPointer& program); - virtual ScriptValuePointer globalObject() const; + //virtual ScriptValue evaluate(const QString& program, const QString& fileName = QString()); + //virtual ScriptValue evaluate(const ScriptProgramPointer &program); + //virtual ScriptValue evaluateInClosure(const ScriptValue& locals, const ScriptProgramPointer& program); + virtual ScriptValue globalObject() const; virtual bool hasUncaughtException() const; virtual bool isEvaluating() const; - virtual ScriptValuePointer lintScript(const QString& sourceCode, const QString& fileName, const int lineNumber = 1); - virtual ScriptValuePointer makeError(const ScriptValuePointer& other, const QString& type = "Error"); + virtual ScriptValue lintScript(const QString& sourceCode, const QString& fileName, const int lineNumber = 1); + virtual ScriptValue makeError(const ScriptValue& other, const QString& type = "Error"); virtual ScriptManager* manager() const; // if there is a pending exception and we are at the top level (non-recursive) stack frame, this emits and resets it virtual bool maybeEmitUncaughtException(const QString& debugHint = QString()); - virtual ScriptValuePointer newArray(uint length = 0); - virtual ScriptValuePointer newArrayBuffer(const QByteArray& message); - virtual ScriptValuePointer newFunction(ScriptEngine::FunctionSignature fun, int length = 0); - virtual ScriptValuePointer newObject(); + virtual ScriptValue newArray(uint length = 0); + virtual ScriptValue newArrayBuffer(const QByteArray& message); + virtual ScriptValue newFunction(ScriptEngine::FunctionSignature fun, int length = 0); + virtual ScriptValue newObject(); virtual ScriptProgramPointer newProgram(const QString& sourceCode, const QString& fileName); - virtual ScriptValuePointer newQObject(QObject *object, ScriptEngine::ValueOwnership ownership = ScriptEngine::QtOwnership, + virtual ScriptValue newQObject(QObject *object, ScriptEngine::ValueOwnership ownership = ScriptEngine::QtOwnership, const ScriptEngine::QObjectWrapOptions &options = ScriptEngine::QObjectWrapOptions()); - virtual ScriptValuePointer newValue(bool value); - virtual ScriptValuePointer newValue(int value); - virtual ScriptValuePointer newValue(uint value); - virtual ScriptValuePointer newValue(double value); - virtual ScriptValuePointer newValue(const QString& value); - virtual ScriptValuePointer newValue(const QLatin1String& value); - virtual ScriptValuePointer newValue(const char* value); - virtual ScriptValuePointer newVariant(const QVariant& value); - virtual ScriptValuePointer nullValue(); - virtual bool raiseException(const ScriptValuePointer& exception); + virtual ScriptValue newValue(bool value); + virtual ScriptValue newValue(int value); + virtual ScriptValue newValue(uint value); + virtual ScriptValue newValue(double value); + virtual ScriptValue newValue(const QString& value); + virtual ScriptValue newValue(const QLatin1String& value); + virtual ScriptValue newValue(const char* value); + virtual ScriptValue newVariant(const QVariant& value); + virtual ScriptValue nullValue(); + virtual bool raiseException(const ScriptValue& exception); //virtual void registerEnum(const QString& enumName, QMetaEnum newEnum); //Q_INVOKABLE virtual void registerFunction(const QString& name, ScriptEngine::FunctionSignature fun, int numArguments = -1); //Q_INVOKABLE virtual void registerFunction(const QString& parent, const QString& name, ScriptEngine::FunctionSignature fun, int numArguments = -1); //Q_INVOKABLE virtual void registerGetterSetter(const QString& name, ScriptEngine::FunctionSignature getter, ScriptEngine::FunctionSignature setter, const QString& parent = QString("")); //virtual void registerGlobalObject(const QString& name, QObject* object); - virtual void setDefaultPrototype(int metaTypeId, const ScriptValuePointer& prototype); + virtual void setDefaultPrototype(int metaTypeId, const ScriptValue& prototype); virtual void setObjectName(const QString& name); virtual bool setProperty(const char* name, const QVariant& value); virtual void setProcessEventsInterval(int interval); virtual QThread* thread() const; virtual void setThread(QThread* thread); - virtual ScriptValuePointer undefinedValue(); - virtual ScriptValuePointer uncaughtException() const; + virtual ScriptValue undefinedValue(); + virtual ScriptValue uncaughtException() const; virtual QStringList uncaughtExceptionBacktrace() const; virtual int uncaughtExceptionLineNumber() const; @@ -203,10 +203,10 @@ public: * @deprecated This function is deprecated and will be removed. */ /// evaluate some code in the context of the ScriptEngineQtScript and return the result - Q_INVOKABLE virtual ScriptValuePointer evaluate(const QString& program, const QString& fileName); // this is also used by the script tool widget + Q_INVOKABLE virtual ScriptValue evaluate(const QString& program, const QString& fileName); // this is also used by the script tool widget - Q_INVOKABLE virtual ScriptValuePointer evaluate(const ScriptProgramPointer& program); + Q_INVOKABLE virtual ScriptValue evaluate(const ScriptProgramPointer& program); /**jsdoc * @function Script.evaluateInClosure @@ -215,7 +215,7 @@ public: * @returns {object} Object. * @deprecated This function is deprecated and will be removed. */ - Q_INVOKABLE virtual ScriptValuePointer evaluateInClosure(const ScriptValuePointer& locals, const ScriptProgramPointer& program); + Q_INVOKABLE virtual ScriptValue evaluateInClosure(const ScriptValue& locals, const ScriptProgramPointer& program); /**jsdoc * Checks whether the application was compiled as a debug build. @@ -381,10 +381,10 @@ signals: void entityScriptDetailsUpdated(); public: // not for public use, but I don't like how Qt strings this along with private friend functions - virtual ScriptValuePointer create(int type, const void* ptr); - virtual bool convert(const ScriptValuePointer& value, int type, void* ptr); + virtual ScriptValue create(int type, const void* ptr); + virtual bool convert(const ScriptValue& value, int type, void* ptr); virtual void registerCustomType(int type, ScriptEngine::MarshalFunction marshalFunc, - ScriptEngine::DemarshalFunction demarshalFunc, const ScriptValuePointer& prototype); + ScriptEngine::DemarshalFunction demarshalFunc, const ScriptValue& prototype); protected: // like `newFunction`, but allows mapping inline C++ lambdas with captures as callable QScriptValues @@ -408,8 +408,8 @@ protected: QPointer _manager; int _nextCustomType = 0; - ScriptValuePointer _nullValue; - ScriptValuePointer _undefinedValue; + ScriptValue _nullValue; + ScriptValue _undefinedValue; mutable ScriptContextQtPointer _currContext; std::atomic _isRunning { false }; diff --git a/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.cpp b/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.cpp index c56f021f88..ea3a4fe542 100644 --- a/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.cpp +++ b/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.cpp @@ -27,7 +27,7 @@ void ScriptValueIteratorQtWrapper::next() { _value.next(); } -ScriptValuePointer ScriptValueIteratorQtWrapper::value() const { +ScriptValue ScriptValueIteratorQtWrapper::value() const { QScriptValue result = _value.value(); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } diff --git a/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.h b/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.h index 7835e7cfae..9250117df7 100644 --- a/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.h +++ b/libraries/script-engine/src/qtscript/ScriptValueIteratorQtWrapper.h @@ -25,7 +25,7 @@ /// [QtScript] Implements ScriptValueIterator for QtScript and translates calls for QScriptValueIterator class ScriptValueIteratorQtWrapper : public ScriptValueIterator { public: // construction - inline ScriptValueIteratorQtWrapper(ScriptEngineQtScript* engine, const ScriptValuePointer& object) : + inline ScriptValueIteratorQtWrapper(ScriptEngineQtScript* engine, const ScriptValue& object) : _engine(engine), _value(ScriptValueQtWrapper::fullUnwrap(engine, object)) {} inline ScriptValueIteratorQtWrapper(ScriptEngineQtScript* engine, const QScriptValue& object) : _engine(engine), _value(object) {} @@ -35,7 +35,7 @@ public: // ScriptValueIterator implementation virtual bool hasNext() const; virtual QString name() const; virtual void next(); - virtual ScriptValuePointer value() const; + virtual ScriptValue value() const; private: // storage QPointer _engine; diff --git a/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.cpp b/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.cpp index f0d1e4d22b..768ec41246 100644 --- a/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.cpp +++ b/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.cpp @@ -13,73 +13,71 @@ #include "ScriptValueIteratorQtWrapper.h" -ScriptValueQtWrapper* ScriptValueQtWrapper::unwrap(ScriptValuePointer val) { - if (!val) { - return nullptr; - } - - return dynamic_cast(val.data()); +void ScriptValueQtWrapper::release() { + delete this; } -QScriptValue ScriptValueQtWrapper::fullUnwrap(const ScriptValuePointer& value) const { - if (!value) { - return QScriptValue(); - } +ScriptValueProxy* ScriptValueQtWrapper::copy() const { + return new ScriptValueQtWrapper(_engine, _value); +} + +ScriptValueQtWrapper* ScriptValueQtWrapper::unwrap(const ScriptValue& val) { + return dynamic_cast(val.ptr()); +} + +QScriptValue ScriptValueQtWrapper::fullUnwrap(const ScriptValue& value) const { ScriptValueQtWrapper* unwrapped = unwrap(value); if (unwrapped) { return unwrapped->toQtValue(); } - QVariant varValue = value->toVariant(); + QVariant varValue = value.toVariant(); return static_cast(_engine)->newVariant(varValue); } -QScriptValue ScriptValueQtWrapper::fullUnwrap(ScriptEngineQtScript* engine, const ScriptValuePointer& value) { - if (!value) { - return QScriptValue(); - } +QScriptValue ScriptValueQtWrapper::fullUnwrap(ScriptEngineQtScript* engine, const ScriptValue& value) { ScriptValueQtWrapper* unwrapped = unwrap(value); if (unwrapped) { return unwrapped->toQtValue(); } - QVariant varValue = value->toVariant(); + QVariant varValue = value.toVariant(); return static_cast(engine)->newVariant(varValue); } -ScriptValuePointer ScriptValueQtWrapper::call(const ScriptValuePointer& thisObject, const ScriptValueList& args) { +ScriptValue ScriptValueQtWrapper::call(const ScriptValue& thisObject, const ScriptValueList& args) { QScriptValue qThis = fullUnwrap(thisObject); QScriptValueList qArgs; for (ScriptValueList::const_iterator iter = args.begin(); iter != args.end(); ++iter) { qArgs.push_back(fullUnwrap(*iter)); } QScriptValue result = _value.call(qThis, qArgs); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -ScriptValuePointer ScriptValueQtWrapper::call(const ScriptValuePointer& thisObject, const ScriptValuePointer& arguments) { +ScriptValue ScriptValueQtWrapper::call(const ScriptValue& thisObject, const ScriptValue& arguments) { QScriptValue qThis = fullUnwrap(thisObject); QScriptValue qArgs = fullUnwrap(arguments); QScriptValue result = _value.call(qThis, qArgs); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -ScriptValuePointer ScriptValueQtWrapper::construct(const ScriptValueList& args) { +ScriptValue ScriptValueQtWrapper::construct(const ScriptValueList& args) { QScriptValueList qArgs; for (ScriptValueList::const_iterator iter = args.begin(); iter != args.end(); ++iter) { qArgs.push_back(fullUnwrap(*iter)); } QScriptValue result = _value.construct(qArgs); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -ScriptValuePointer ScriptValueQtWrapper::construct(const ScriptValuePointer& arguments) { +ScriptValue ScriptValueQtWrapper::construct(const ScriptValue& arguments) { QScriptValue unwrapped = fullUnwrap(arguments); QScriptValue result = _value.construct(unwrapped); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -ScriptValuePointer ScriptValueQtWrapper::data() const { +ScriptValue ScriptValueQtWrapper::data() const { QScriptValue result = _value.data(); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } ScriptEnginePointer ScriptValueQtWrapper::engine() const { @@ -89,43 +87,43 @@ ScriptEnginePointer ScriptValueQtWrapper::engine() const { return _engine->sharedFromThis(); } -ScriptValueIteratorPointer ScriptValueQtWrapper::newIterator() { +ScriptValueIteratorPointer ScriptValueQtWrapper::newIterator() const { return ScriptValueIteratorPointer(new ScriptValueIteratorQtWrapper(_engine, _value)); } -ScriptValuePointer ScriptValueQtWrapper::property(const QString& name, const ResolveFlags& mode) const { +ScriptValue ScriptValueQtWrapper::property(const QString& name, const ScriptValue::ResolveFlags& mode) const { QScriptValue result = _value.property(name, (QScriptValue::ResolveFlags)(int)mode); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -ScriptValuePointer ScriptValueQtWrapper::property(quint32 arrayIndex, const ResolveFlags& mode) const { +ScriptValue ScriptValueQtWrapper::property(quint32 arrayIndex, const ScriptValue::ResolveFlags& mode) const { QScriptValue result = _value.property(arrayIndex, (QScriptValue::ResolveFlags)(int)mode); - return ScriptValuePointer(new ScriptValueQtWrapper(_engine, std::move(result))); + return ScriptValue(new ScriptValueQtWrapper(_engine, std::move(result))); } -void ScriptValueQtWrapper::setData(const ScriptValuePointer& value) { +void ScriptValueQtWrapper::setData(const ScriptValue& value) { QScriptValue unwrapped = fullUnwrap(value); _value.setData(unwrapped); } -void ScriptValueQtWrapper::setProperty(const QString& name, const ScriptValuePointer& value, const PropertyFlags& flags) { +void ScriptValueQtWrapper::setProperty(const QString& name, const ScriptValue& value, const ScriptValue::PropertyFlags& flags) { QScriptValue unwrapped = fullUnwrap(value); _value.setProperty(name, unwrapped, (QScriptValue::PropertyFlags)(int)flags); } -void ScriptValueQtWrapper::setProperty(quint32 arrayIndex, const ScriptValuePointer& value, const PropertyFlags& flags) { +void ScriptValueQtWrapper::setProperty(quint32 arrayIndex, const ScriptValue& value, const ScriptValue::PropertyFlags& flags) { QScriptValue unwrapped = fullUnwrap(value); _value.setProperty(arrayIndex, unwrapped, (QScriptValue::PropertyFlags)(int)flags); } -void ScriptValueQtWrapper::setPrototype(const ScriptValuePointer& prototype) { +void ScriptValueQtWrapper::setPrototype(const ScriptValue& prototype) { ScriptValueQtWrapper* unwrappedPrototype = unwrap(prototype); if (unwrappedPrototype) { _value.setPrototype(unwrappedPrototype->toQtValue()); } } -bool ScriptValueQtWrapper::strictlyEquals(const ScriptValuePointer& other) const { +bool ScriptValueQtWrapper::strictlyEquals(const ScriptValue& other) const { ScriptValueQtWrapper* unwrappedOther = unwrap(other); return unwrappedOther ? _value.strictlyEquals(unwrappedOther->toQtValue()) : false; } @@ -166,51 +164,51 @@ QObject* ScriptValueQtWrapper::toQObject() const { return _value.toQObject(); } -bool ScriptValueQtWrapper::equalsInternal(const ScriptValuePointer& other) const { +bool ScriptValueQtWrapper::equals(const ScriptValue& other) const { ScriptValueQtWrapper* unwrappedOther = unwrap(other); return unwrappedOther ? _value.equals(unwrappedOther->toQtValue()) : false; } -bool ScriptValueQtWrapper::isArrayInternal() const { +bool ScriptValueQtWrapper::isArray() const { return _value.isArray(); } -bool ScriptValueQtWrapper::isBoolInternal() const { +bool ScriptValueQtWrapper::isBool() const { return _value.isBool(); } -bool ScriptValueQtWrapper::isErrorInternal() const { +bool ScriptValueQtWrapper::isError() const { return _value.isError(); } -bool ScriptValueQtWrapper::isFunctionInternal() const { +bool ScriptValueQtWrapper::isFunction() const { return _value.isFunction(); } -bool ScriptValueQtWrapper::isNumberInternal() const { +bool ScriptValueQtWrapper::isNumber() const { return _value.isNumber(); } -bool ScriptValueQtWrapper::isNullInternal() const { +bool ScriptValueQtWrapper::isNull() const { return _value.isNull(); } -bool ScriptValueQtWrapper::isObjectInternal() const { +bool ScriptValueQtWrapper::isObject() const { return _value.isObject(); } -bool ScriptValueQtWrapper::isStringInternal() const { +bool ScriptValueQtWrapper::isString() const { return _value.isString(); } -bool ScriptValueQtWrapper::isUndefinedInternal() const { +bool ScriptValueQtWrapper::isUndefined() const { return _value.isUndefined(); } -bool ScriptValueQtWrapper::isValidInternal() const { +bool ScriptValueQtWrapper::isValid() const { return _value.isValid(); } -bool ScriptValueQtWrapper::isVariantInternal() const { +bool ScriptValueQtWrapper::isVariant() const { return _value.isVariant(); } diff --git a/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.h b/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.h index d7fa124a5a..363bf71d05 100644 --- a/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.h +++ b/libraries/script-engine/src/qtscript/ScriptValueQtWrapper.h @@ -24,37 +24,54 @@ #include "ScriptEngineQtScript.h" /// [QtScript] Implements ScriptValue for QtScript and translates calls for QScriptValue -class ScriptValueQtWrapper : public ScriptValue { +class ScriptValueQtWrapper : public ScriptValueProxy { public: // construction inline ScriptValueQtWrapper(ScriptEngineQtScript* engine, const QScriptValue& value) : _engine(engine), _value(value) {} inline ScriptValueQtWrapper(ScriptEngineQtScript* engine, QScriptValue&& value) : _engine(engine), _value(std::move(value)) {} - static ScriptValueQtWrapper* unwrap(ScriptValuePointer val); + static ScriptValueQtWrapper* unwrap(const ScriptValue& val); inline const QScriptValue& toQtValue() const { return _value; } - static QScriptValue fullUnwrap(ScriptEngineQtScript* engine, const ScriptValuePointer& value); + static QScriptValue fullUnwrap(ScriptEngineQtScript* engine, const ScriptValue& value); -public: // ScriptValue implementation - virtual ScriptValuePointer call(const ScriptValuePointer& thisObject = ScriptValuePointer(), - const ScriptValueList& args = ScriptValueList()); - virtual ScriptValuePointer call(const ScriptValuePointer& thisObject, const ScriptValuePointer& arguments); - virtual ScriptValuePointer construct(const ScriptValueList& args = ScriptValueList()); - virtual ScriptValuePointer construct(const ScriptValuePointer& arguments); - virtual ScriptValuePointer data() const; +public: + virtual void release(); + virtual ScriptValueProxy* copy() const; + +public: // ScriptValue implementation + virtual ScriptValue call(const ScriptValue& thisObject = ScriptValue(), const ScriptValueList& args = ScriptValueList()); + virtual ScriptValue call(const ScriptValue& thisObject, const ScriptValue& arguments); + virtual ScriptValue construct(const ScriptValueList& args = ScriptValueList()); + virtual ScriptValue construct(const ScriptValue& arguments); + virtual ScriptValue data() const; virtual ScriptEnginePointer engine() const; - virtual ScriptValueIteratorPointer newIterator(); - virtual ScriptValuePointer property(const QString& name, const ResolveFlags& mode = ResolvePrototype) const; - virtual ScriptValuePointer property(quint32 arrayIndex, const ResolveFlags& mode = ResolvePrototype) const; - virtual void setData(const ScriptValuePointer& val); + virtual ScriptValueIteratorPointer newIterator() const; + virtual ScriptValue property(const QString& name, + const ScriptValue::ResolveFlags& mode = ScriptValue::ResolvePrototype) const; + virtual ScriptValue property(quint32 arrayIndex, + const ScriptValue::ResolveFlags& mode = ScriptValue::ResolvePrototype) const; + virtual void setData(const ScriptValue& val); virtual void setProperty(const QString& name, - const ScriptValuePointer& value, - const PropertyFlags& flags = KeepExistingFlags); + const ScriptValue& value, + const ScriptValue::PropertyFlags& flags = ScriptValue::KeepExistingFlags); virtual void setProperty(quint32 arrayIndex, - const ScriptValuePointer& value, - const PropertyFlags& flags = KeepExistingFlags); - virtual void setPrototype(const ScriptValuePointer& prototype); - virtual bool strictlyEquals(const ScriptValuePointer& other) const; + const ScriptValue& value, + const ScriptValue::PropertyFlags& flags = ScriptValue::KeepExistingFlags); + virtual void setPrototype(const ScriptValue& prototype); + virtual bool strictlyEquals(const ScriptValue& other) const; + virtual bool equals(const ScriptValue& other) const; + virtual bool isArray() const; + virtual bool isBool() const; + virtual bool isError() const; + virtual bool isFunction() const; + virtual bool isNumber() const; + virtual bool isNull() const; + virtual bool isObject() const; + virtual bool isString() const; + virtual bool isUndefined() const; + virtual bool isValid() const; + virtual bool isVariant() const; virtual bool toBool() const; virtual qint32 toInt32() const; virtual double toInteger() const; @@ -65,22 +82,8 @@ public: // ScriptValue implementation virtual QVariant toVariant() const; virtual QObject* toQObject() const; -protected: // ScriptValue implementation - virtual bool equalsInternal(const ScriptValuePointer& other) const; - virtual bool isArrayInternal() const; - virtual bool isBoolInternal() const; - virtual bool isErrorInternal() const; - virtual bool isFunctionInternal() const; - virtual bool isNumberInternal() const; - virtual bool isNullInternal() const; - virtual bool isObjectInternal() const; - virtual bool isStringInternal() const; - virtual bool isUndefinedInternal() const; - virtual bool isValidInternal() const; - virtual bool isVariantInternal() const; - private: // helper functions - QScriptValue fullUnwrap(const ScriptValuePointer& value) const; + QScriptValue fullUnwrap(const ScriptValue& value) const; private: // storage QPointer _engine; diff --git a/libraries/ui/src/QmlFragmentClass.cpp b/libraries/ui/src/QmlFragmentClass.cpp index 163d5e2ca7..b0fe278960 100644 --- a/libraries/ui/src/QmlFragmentClass.cpp +++ b/libraries/ui/src/QmlFragmentClass.cpp @@ -17,15 +17,15 @@ #include std::mutex QmlFragmentClass::_mutex; -std::map QmlFragmentClass::_fragments; +std::map QmlFragmentClass::_fragments; QmlFragmentClass::QmlFragmentClass(bool restricted, QString id) : QmlWindowClass(restricted), qml(id) { } // Method called by Qt scripts to create a new bottom menu bar in Android -ScriptValuePointer QmlFragmentClass::internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted) { +ScriptValue QmlFragmentClass::internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted) { #ifndef DISABLE_QML std::lock_guard guard(_mutex); - auto qml = context->argument(0)->toVariant().toMap().value("qml"); + auto qml = context->argument(0).toVariant().toMap().value("qml"); if (qml.isValid()) { // look up tabletId in the map. auto iter = _fragments.find(qml.toString()); @@ -35,7 +35,7 @@ ScriptValuePointer QmlFragmentClass::internal_constructor(ScriptContext* context } } else { qWarning() << "QmlFragmentClass could not build instance " << qml; - return ScriptValuePointer(); + return ScriptValue(); } auto properties = parseArguments(context); @@ -49,11 +49,11 @@ ScriptValuePointer QmlFragmentClass::internal_constructor(ScriptContext* context } auto manager = engine->manager(); connect(manager, &ScriptManager::destroyed, retVal, &QmlWindowClass::deleteLater); - ScriptValuePointer scriptObject = engine->newQObject(retVal); + ScriptValue scriptObject = engine->newQObject(retVal); _fragments[qml.toString()] = scriptObject; return scriptObject; #else - return ScriptValuePointer(); + return ScriptValue(); #endif } diff --git a/libraries/ui/src/QmlFragmentClass.h b/libraries/ui/src/QmlFragmentClass.h index 35399782ea..9c04fe6263 100644 --- a/libraries/ui/src/QmlFragmentClass.h +++ b/libraries/ui/src/QmlFragmentClass.h @@ -10,24 +10,22 @@ #define hifi_ui_QmlFragmentClass_h #include "QmlWindowClass.h" -#include +#include class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class QmlFragmentClass : public QmlWindowClass { Q_OBJECT private: - static ScriptValuePointer internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted); + static ScriptValue internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted); public: - static ScriptValuePointer constructor(ScriptContext* context, ScriptEngine* engine) { + static ScriptValue constructor(ScriptContext* context, ScriptEngine* engine) { return internal_constructor(context, engine, false); } - static ScriptValuePointer restricted_constructor(ScriptContext* context, ScriptEngine* engine ){ + static ScriptValue restricted_constructor(ScriptContext* context, ScriptEngine* engine ){ return internal_constructor(context, engine, true); } @@ -52,7 +50,7 @@ protected: QString qmlSource() const override { return qml; } static std::mutex _mutex; - static std::map _fragments; + static std::map _fragments; private: QString qml; diff --git a/libraries/ui/src/QmlWebWindowClass.cpp b/libraries/ui/src/QmlWebWindowClass.cpp index e86355a344..9fc5ccdf78 100644 --- a/libraries/ui/src/QmlWebWindowClass.cpp +++ b/libraries/ui/src/QmlWebWindowClass.cpp @@ -20,7 +20,7 @@ static const char* const URL_PROPERTY = "source"; static const char* const SCRIPT_PROPERTY = "scriptUrl"; // Method called by Qt scripts to create a new web window in the overlay -ScriptValuePointer QmlWebWindowClass::internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted) { +ScriptValue QmlWebWindowClass::internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted) { auto properties = parseArguments(context); QmlWebWindowClass* retVal = new QmlWebWindowClass(restricted); Q_ASSERT(retVal); diff --git a/libraries/ui/src/QmlWebWindowClass.h b/libraries/ui/src/QmlWebWindowClass.h index da5b73c81d..20dadd98bb 100644 --- a/libraries/ui/src/QmlWebWindowClass.h +++ b/libraries/ui/src/QmlWebWindowClass.h @@ -13,10 +13,10 @@ #include "QmlWindowClass.h" +#include + class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * A OverlayWebWindow displays an HTML window inside Interface. @@ -149,15 +149,15 @@ class QmlWebWindowClass : public QmlWindowClass { Q_PROPERTY(QString url READ getURL CONSTANT) private: - static ScriptValuePointer internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted); + static ScriptValue internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted); public: QmlWebWindowClass(bool restricted) : QmlWindowClass(restricted) {} - static ScriptValuePointer constructor(ScriptContext* context, ScriptEngine* engine) { + static ScriptValue constructor(ScriptContext* context, ScriptEngine* engine) { return internal_constructor(context, engine, false); } - static ScriptValuePointer restricted_constructor(ScriptContext* context, ScriptEngine* engine ){ + static ScriptValue restricted_constructor(ScriptContext* context, ScriptEngine* engine ){ return internal_constructor(context, engine, true); } diff --git a/libraries/ui/src/QmlWindowClass.cpp b/libraries/ui/src/QmlWindowClass.cpp index c0f2e9a51e..f38dd7723d 100644 --- a/libraries/ui/src/QmlWindowClass.cpp +++ b/libraries/ui/src/QmlWindowClass.cpp @@ -43,20 +43,20 @@ QVariantMap QmlWindowClass::parseArguments(ScriptContext* context) { const auto argumentCount = context->argumentCount(); QVariantMap properties; if (argumentCount > 1) { - if (!context->argument(0)->isUndefined()) { - properties[TITLE_PROPERTY] = context->argument(0)->toString(); + if (!context->argument(0).isUndefined()) { + properties[TITLE_PROPERTY] = context->argument(0).toString(); } - if (!context->argument(1)->isUndefined()) { - properties[SOURCE_PROPERTY] = context->argument(1)->toString(); + if (!context->argument(1).isUndefined()) { + properties[SOURCE_PROPERTY] = context->argument(1).toString(); } - if (context->argument(2)->isNumber()) { - properties[WIDTH_PROPERTY] = context->argument(2)->toInt32(); + if (context->argument(2).isNumber()) { + properties[WIDTH_PROPERTY] = context->argument(2).toInt32(); } - if (context->argument(3)->isNumber()) { - properties[HEIGHT_PROPERTY] = context->argument(3)->toInt32(); + if (context->argument(3).isNumber()) { + properties[HEIGHT_PROPERTY] = context->argument(3).toInt32(); } } else { - properties = context->argument(0)->toVariant().toMap(); + properties = context->argument(0).toVariant().toMap(); } QUrl url { properties[SOURCE_PROPERTY].toString() }; @@ -72,7 +72,7 @@ QVariantMap QmlWindowClass::parseArguments(ScriptContext* context) { // Method called by Qt scripts to create a new web window in the overlay -ScriptValuePointer QmlWindowClass::internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted) { +ScriptValue QmlWindowClass::internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted) { auto properties = parseArguments(context); QmlWindowClass* retVal = new QmlWindowClass(restricted); Q_ASSERT(retVal); diff --git a/libraries/ui/src/QmlWindowClass.h b/libraries/ui/src/QmlWindowClass.h index da44aed9fa..5d1111bd5a 100644 --- a/libraries/ui/src/QmlWindowClass.h +++ b/libraries/ui/src/QmlWindowClass.h @@ -11,15 +11,13 @@ #include #include -#include #include #include +#include class ScriptContext; class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; /*@jsdoc * A OverlayWindow displays a QML window inside Interface. @@ -55,13 +53,13 @@ class QmlWindowClass : public QObject { Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged) private: - static ScriptValuePointer internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted); + static ScriptValue internal_constructor(ScriptContext* context, ScriptEngine* engine, bool restricted); public: - static ScriptValuePointer constructor(ScriptContext* context, ScriptEngine* engine) { + static ScriptValue constructor(ScriptContext* context, ScriptEngine* engine) { return internal_constructor(context, engine, false); } - static ScriptValuePointer restricted_constructor(ScriptContext* context, ScriptEngine* engine ){ + static ScriptValue restricted_constructor(ScriptContext* context, ScriptEngine* engine ){ return internal_constructor(context, engine, true); } @@ -348,7 +346,7 @@ protected slots: protected: static QVariantMap parseArguments(ScriptContext* context); - static ScriptValuePointer internalConstructor(ScriptContext* context, ScriptEngine* engine, + static ScriptValue internalConstructor(ScriptContext* context, ScriptEngine* engine, std::function function); virtual QString qmlSource() const { return "QmlWindow.qml"; } diff --git a/libraries/ui/src/ui/QmlWrapper.h b/libraries/ui/src/ui/QmlWrapper.h index b5150f440c..84873472b9 100644 --- a/libraries/ui/src/ui/QmlWrapper.h +++ b/libraries/ui/src/ui/QmlWrapper.h @@ -11,11 +11,10 @@ #include #include -#include + +#include class ScriptEngine; -class ScriptValue; -using ScriptValuePointer = QSharedPointer; class QmlWrapper : public QObject { Q_OBJECT @@ -32,7 +31,7 @@ protected: }; template -ScriptValuePointer wrapperToScriptValue(ScriptEngine* engine, T* const &in) { +ScriptValue wrapperToScriptValue(ScriptEngine* engine, T* const &in) { if (!in) { return engine->undefinedValue(); } @@ -40,8 +39,8 @@ ScriptValuePointer wrapperToScriptValue(ScriptEngine* engine, T* const &in) { } template -void wrapperFromScriptValue(const ScriptValuePointer& value, T* &out) { - out = qobject_cast(value->toQObject()); +void wrapperFromScriptValue(const ScriptValue& value, T* &out) { + out = qobject_cast(value.toQObject()); } #endif \ No newline at end of file diff --git a/libraries/ui/src/ui/ToolbarScriptingInterface.cpp b/libraries/ui/src/ui/ToolbarScriptingInterface.cpp index e23023e137..c2e908f8a4 100644 --- a/libraries/ui/src/ui/ToolbarScriptingInterface.cpp +++ b/libraries/ui/src/ui/ToolbarScriptingInterface.cpp @@ -16,26 +16,26 @@ #include #include "../OffscreenUi.h" -ScriptValuePointer toolbarToScriptValue(ScriptEngine* engine, ToolbarProxy* const &in) { +ScriptValue toolbarToScriptValue(ScriptEngine* engine, ToolbarProxy* const &in) { if (!in) { return engine->undefinedValue(); } return engine->newQObject(in, ScriptEngine::QtOwnership); } -void toolbarFromScriptValue(const ScriptValuePointer& value, ToolbarProxy* &out) { - out = qobject_cast(value->toQObject()); +void toolbarFromScriptValue(const ScriptValue& value, ToolbarProxy* &out) { + out = qobject_cast(value.toQObject()); } -ScriptValuePointer toolbarButtonToScriptValue(ScriptEngine* engine, ToolbarButtonProxy* const &in) { +ScriptValue toolbarButtonToScriptValue(ScriptEngine* engine, ToolbarButtonProxy* const &in) { if (!in) { return engine->undefinedValue(); } return engine->newQObject(in, ScriptEngine::QtOwnership); } -void toolbarButtonFromScriptValue(const ScriptValuePointer& value, ToolbarButtonProxy* &out) { - out = qobject_cast(value->toQObject()); +void toolbarButtonFromScriptValue(const ScriptValue& value, ToolbarButtonProxy* &out) { + out = qobject_cast(value.toQObject()); } diff --git a/plugins/JSAPIExample/src/JSAPIExample.cpp b/plugins/JSAPIExample/src/JSAPIExample.cpp index 205bd83f98..8dec23fd44 100644 --- a/plugins/JSAPIExample/src/JSAPIExample.cpp +++ b/plugins/JSAPIExample/src/JSAPIExample.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -65,7 +66,7 @@ namespace REPLACE_ME_WITH_UNIQUE_NAME { qCWarning(logger) << "registering w/ScriptInitializerMixin..." << scriptInit.data(); scriptInit->registerScriptInitializer([this](ScriptEngine* engine) { auto value = engine->newQObject(this, ScriptEngine::QtOwnership); - engine->globalObject()->setProperty(objectName(), value); + engine->globalObject().setProperty(objectName(), value); // qCDebug(logger) << "setGlobalInstance" << objectName() << engine->property("fileName"); }); // qCInfo(logger) << "plugin loaded" << qApp << toString() << QThread::currentThread(); @@ -73,7 +74,7 @@ namespace REPLACE_ME_WITH_UNIQUE_NAME { // NOTES: everything within the "public slots:" section below will be available from JS via overall plugin QObject // also, to demonstrate future-proofing JS API code, QVariant's are used throughout most of these examples -- - // which still makes them very Qt-specific, but avoids depending directly on deprecated ScriptValuePointer APIs. + // which still makes them very Qt-specific, but avoids depending directly on deprecated ScriptValue APIs. // (as such this plugin class and its methods remain forward-compatible with other engines like QML's QJSEngine) public slots: @@ -160,14 +161,14 @@ namespace REPLACE_ME_WITH_UNIQUE_NAME { * print("all example::* keys", settings.allKeys()); * settings = null; // optional best pratice; allows the object to be reclaimed ASAP by the JS garbage collector */ - ScriptValuePointer getScopedSettings(const QString& scope) { + ScriptValue getScopedSettings(const QString& scope) { auto engine = Scriptable::engine(); if (!engine) { - return ScriptValuePointer(); + return ScriptValue(); } auto manager = engine->manager(); if (!manager) { - return ScriptValuePointer(); + return ScriptValue(); } QString error; auto cppValue = createScopedSettings(scope, manager, error); diff --git a/plugins/hifiNeuron/CMakeLists.txt b/plugins/hifiNeuron/CMakeLists.txt index ad4f78698c..25fd8ff2e5 100644 --- a/plugins/hifiNeuron/CMakeLists.txt +++ b/plugins/hifiNeuron/CMakeLists.txt @@ -11,6 +11,7 @@ if (WIN32) set(TARGET_NAME hifiNeuron) setup_hifi_plugin(Qml) link_hifi_libraries(shared controllers qml ui plugins input-plugins) + include_hifi_library_headers(script-engine) target_neuron() endif() diff --git a/plugins/hifiOsc/CMakeLists.txt b/plugins/hifiOsc/CMakeLists.txt index cb8b437ab6..78514f5888 100644 --- a/plugins/hifiOsc/CMakeLists.txt +++ b/plugins/hifiOsc/CMakeLists.txt @@ -9,6 +9,7 @@ set(TARGET_NAME hifiOsc) setup_hifi_plugin(Qml) link_hifi_libraries(shared controllers ui plugins input-plugins display-plugins) +include_hifi_library_headers(script-engine) target_liblo() diff --git a/plugins/hifiSdl2/CMakeLists.txt b/plugins/hifiSdl2/CMakeLists.txt index 47d382681f..16ce6f51b4 100644 --- a/plugins/hifiSdl2/CMakeLists.txt +++ b/plugins/hifiSdl2/CMakeLists.txt @@ -17,5 +17,6 @@ if (NOT APPLE) endif() setup_hifi_plugin(Qml) link_hifi_libraries(shared controllers ui plugins input-plugins) + include_hifi_library_headers(script-engine) target_sdl2() endif() diff --git a/plugins/oculus/CMakeLists.txt b/plugins/oculus/CMakeLists.txt index 6ddc75e1e5..2eb7fb4825 100644 --- a/plugins/oculus/CMakeLists.txt +++ b/plugins/oculus/CMakeLists.txt @@ -22,6 +22,7 @@ if (WIN32 AND (NOT USE_GLES)) ${PLATFORM_GL_BACKEND} ) include_hifi_library_headers(octree) + include_hifi_library_headers(script-engine) add_dependency_external_projects(LibOVR) find_package(LibOVR REQUIRED)