//// ScriptEngine.h// libraries/script-engine/src//// Created by Brad Hefta-Gaub on 12/14/13.// Copyright 2013 High Fidelity, Inc.//// Distributed under the Apache License, Version 2.0.// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html// #ifndef hifi_ScriptEngine_h#define hifi_ScriptEngine_h #include <unordered_map>#include <vector> #include <QtCore/QObject>#include <QtCore/QUrl>#include <QtCore/QSet>#include <QtCore/QWaitCondition>#include <QtCore/QStringList>#include <QMap>#include <QMetaEnum> #include <QtScript/QScriptEngine> #include <AnimationCache.h>#include <AnimVariant.h>#include <AvatarData.h>#include <AvatarHashMap.h>#include <LimitedNodeList.h>#include <EntityItemID.h>#include <EntitiesScriptEngineProvider.h>#include <EntityScriptUtils.h> #include "PointerEvent.h"#include "ArrayBufferClass.h"#include "AssetScriptingInterface.h"#include "AudioScriptingInterface.h"#include "BaseScriptEngine.h"#include "ExternalResource.h"#include "Quat.h"#include "Mat4.h"#include "ScriptCache.h"#include "ScriptUUID.h"#include "Vec3.h"#include "ConsoleScriptingInterface.h"#include "SettingHandle.h"#include "Profile.h" class QScriptEngineDebugger; static const QString NO_SCRIPT(""); static const int SCRIPT_FPS = 60;static const int DEFAULT_MAX_ENTITY_PPS = 9000;static const int DEFAULT_ENTITY_PPS_PER_SCRIPT = 900; class ScriptEngines; Q_DECLARE_METATYPE(ScriptEnginePointer) class CallbackData {public: QScriptValue function; EntityItemID definingEntityIdentifier; QUrl definingSandboxURL;}; class DeferredLoadEntity {public: EntityItemID entityID; QString entityScript; //bool forceRedownload;}; struct EntityScriptContentAvailable { EntityItemID entityID; QString scriptOrURL; QString contents; bool isURL; bool success; QString status;}; typedef std::unordered_map<EntityItemID, EntityScriptContentAvailable> EntityScriptContentAvailableMap; typedef QList<CallbackData> CallbackList;typedef QHash<QString, CallbackList> RegisteredEventHandlers; class EntityScriptDetails {public: EntityScriptStatus status { EntityScriptStatus::PENDING }; // If status indicates an error, this contains a human-readable string giving more information about the error. QString errorInfo { "" }; QString scriptText { "" }; QScriptValue scriptObject { QScriptValue() }; int64_t lastModified { 0 }; QUrl definingSandboxURL { QUrl("about:EntityScript") };}; /**jsdoc * The <code>Script</code> API provides facilities for working with scripts. * * @namespace Script * * @hifi-interface * @hifi-client-entity * @hifi-avatar * @hifi-server-entity * @hifi-assignment-client * * @property {string} context - The context that the script is running in: * <ul> * <li><code>"client"</code>: An Interface or avatar script.</li> * <li><code>"entity_client"</code>: A client entity script.</li> * <li><code>"entity_server"</code>: A server entity script.</li> * <li><code>"agent"</code>: An assignment client script.</li> * </ul> * <em>Read-only.</em> * @property {Script.ResourceBuckets} ExternalPaths - External resource buckets. */class ScriptEngine : public BaseScriptEngine, public EntitiesScriptEngineProvider { Q_OBJECT Q_PROPERTY(QString context READ getContext) Q_PROPERTY(QString type READ getTypeAsString) Q_PROPERTY(QString fileName MEMBER _fileNameString CONSTANT)public: enum Context { CLIENT_SCRIPT, ENTITY_CLIENT_SCRIPT, ENTITY_SERVER_SCRIPT, AGENT_SCRIPT }; enum Type { CLIENT, ENTITY_CLIENT, ENTITY_SERVER, AGENT, AVATAR }; Q_ENUM(Type) static int processLevelMaxRetries; ScriptEngine(Context context, const QString& scriptContents = NO_SCRIPT, const QString& fileNameString = QString("about:ScriptEngine")); ~ScriptEngine(); /// run the script in a dedicated thread. This will have the side effect of evalulating /// the current script contents and calling run(). Callers will likely want to register the script with external /// services before calling this. void runInThread(); void runDebuggable(); /// run the script in the callers thread, exit when stop() is called. void run(); QString getFilename() const; QList<EntityItemID> getListOfEntityScriptIDs(); /**jsdoc * Stops and unloads the current script. * <p><strong>Warning:</strong> If an assignment client script, the script gets restarted after stopping.</p> * @function Script.stop * @param {boolean} [marshal=false] - Marshal. * <p class="important">Deprecated: This parameter is deprecated and will be removed.</p> * @example <caption>Stop a script after 5s.</caption> * Script.setInterval(function () { * print("Hello"); * }, 1000); * * Script.setTimeout(function () { * Script.stop(true); * }, 5000); */ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // NOTE - this is intended to be a public interface for Agent scripts, and local scripts, but not for EntityScripts Q_INVOKABLE void stop(bool marshal = false); // Stop any evaluating scripts and wait for the scripting thread to finish. void waitTillDoneRunning(); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // NOTE - these are NOT intended to be public interfaces available to scripts, the are only Q_INVOKABLE so we can // properly ensure they are only called on the correct thread /**jsdoc * @function Script.registerGlobalObject * @param {string} name - Name. * @param {object} object - Object. * @deprecated This function is deprecated and will be removed. */ /// registers a global object by name Q_INVOKABLE void registerGlobalObject(const QString& name, QObject* object); /**jsdoc * @function Script.registerGetterSetter * @param {string} name - Name. * @param {function} getter - Getter. * @param {function} setter - Setter. * @param {string} [parent=""] - Parent. * @deprecated This function is deprecated and will be removed. */ /// registers a global getter/setter Q_INVOKABLE void registerGetterSetter(const QString& name, QScriptEngine::FunctionSignature getter, QScriptEngine::FunctionSignature setter, const QString& parent = QString("")); /**jsdoc * @function Script.registerFunction * @param {string} name - Name. * @param {function} function - Function. * @param {number} [numArguments=-1] - Number of arguments. * @deprecated This function is deprecated and will be removed. */ /// register a global function Q_INVOKABLE void registerFunction(const QString& name, QScriptEngine::FunctionSignature fun, int numArguments = -1); /**jsdoc * @function Script.registerFunction * @param {string} parent - Parent. * @param {string} name - Name. * @param {function} function - Function. * @param {number} [numArguments=-1] - Number of arguments. * @deprecated This function is deprecated and will be removed. */ /// register a function as a method on a previously registered global object Q_INVOKABLE void registerFunction(const QString& parent, const QString& name, QScriptEngine::FunctionSignature fun, int numArguments = -1); /**jsdoc * @function Script.registerEnum * @param {string} name - Name. * @param {object} enum - Enum. * @deprecated This function is deprecated and will be removed. */ // WARNING: This function must be called after a registerGlobalObject that creates the namespace this enum is located in, or // the globalObject won't function. E.g., if you have a Foo object and a Foo.FooType enum, Foo must be registered first. /// registers a global enum Q_INVOKABLE void registerEnum(const QString& enumName, QMetaEnum newEnum); /**jsdoc * @function Script.registerValue * @param {string} name - Name. * @param {object} value - Value. * @deprecated This function is deprecated and will be removed. */ /// registers a global object by name Q_INVOKABLE void registerValue(const QString& valueName, QScriptValue value); /**jsdoc * @function Script.evaluate * @param {string} program - Program. * @param {string} filename - File name. * @param {number} [lineNumber=-1] - Line number. * @returns {object} Object. * @deprecated This function is deprecated and will be removed. */ /// evaluate some code in the context of the ScriptEngine and return the result Q_INVOKABLE QScriptValue evaluate(const QString& program, const QString& fileName, int lineNumber = 1); // this is also used by the script tool widget /**jsdoc * @function Script.evaluateInClosure * @param {object} locals - Locals. * @param {object} program - Program. * @returns {object} Object. * @deprecated This function is deprecated and will be removed. */ Q_INVOKABLE QScriptValue evaluateInClosure(const QScriptValue& locals, const QScriptProgram& program); /// if the script engine is not already running, this will download the URL and start the process of seting it up /// to run... NOTE - this is used by Application currently to load the url. We don't really want it to be exposed /// to scripts. we may not need this to be invokable void loadURL(const QUrl& scriptURL, bool reload); bool hasValidScriptSuffix(const QString& scriptFileName); /**jsdoc * Gets the context that the script is running in: Interface/avatar, client entity, server entity, or assignment client. * @function Script.getContext * @returns {string} The context that the script is running in: * <ul> * <li><code>"client"</code>: An Interface or avatar script.</li> * <li><code>"entity_client"</code>: A client entity script.</li> * <li><code>"entity_server"</code>: A server entity script.</li> * <li><code>"agent"</code>: An assignment client script.</li> * </ul> */ Q_INVOKABLE QString getContext() const; /**jsdoc * Checks whether the script is running as an Interface or avatar script. * @function Script.isClientScript * @returns {boolean} <code>true</code> if the script is running as an Interface or avatar script, <code>false</code> if it * isn't. */ Q_INVOKABLE bool isClientScript() const { return _context == CLIENT_SCRIPT; } /**jsdoc * Checks whether the application was compiled as a debug build. * @function Script.isDebugMode * @returns {boolean} <code>true</code> if the application was compiled as a debug build, <code>false</code> if it was * compiled as a release build. */ Q_INVOKABLE bool isDebugMode() const; /**jsdoc * Checks whether the script is running as a client entity script. * @function Script.isEntityClientScript * @returns {boolean} <code>true</code> if the script is running as a client entity script, <code>false</code> if it isn't. */ Q_INVOKABLE bool isEntityClientScript() const { return _context == ENTITY_CLIENT_SCRIPT; } /**jsdoc * Checks whether the script is running as a server entity script. * @function Script.isEntityServerScript * @returns {boolean} <code>true</code> if the script is running as a server entity script, <code>false</code> if it isn't. */ Q_INVOKABLE bool isEntityServerScript() const { return _context == ENTITY_SERVER_SCRIPT; } /**jsdoc * Checks whether the script is running as an assignment client script. * @function Script.isAgentScript * @returns {boolean} <code>true</code> if the script is running as an assignment client script, <code>false</code> if it * isn't. */ Q_INVOKABLE bool isAgentScript() const { return _context == AGENT_SCRIPT; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // NOTE - these are intended to be public interfaces available to scripts /**jsdoc * Adds a function to the list of functions called when a particular event occurs on a particular entity. * <p>See also, the {@link Entities} API.</p> * @function Script.addEventHandler * @param {Uuid} entityID - The ID of the entity. * @param {Script.EntityEvent} eventName - The name of the event. * @param {Script~entityEventCallback|Script~pointerEventCallback|Script~collisionEventCallback} handler - The function to * call when the event occurs on the entity. It can be either the name of a function or an in-line definition. * @example <caption>Report when a mouse press occurs on a particular entity.</caption> * var entityID = Entities.addEntity({ * type: "Box", * position: Vec3.sum(MyAvatar.position, Vec3.multiplyQbyV(MyAvatar.orientation, { x: 0, y: 0, z: -5 })), * dimensions: { x: 0.5, y: 0.5, z: 0.5 }, * lifetime: 300 // Delete after 5 minutes. * }); * * function reportMousePress(entityID, event) { * print("Mouse pressed on entity: " + JSON.stringify(event)); * } * * Script.addEventHandler(entityID, "mousePressOnEntity", reportMousePress); */ Q_INVOKABLE void addEventHandler(const EntityItemID& entityID, const QString& eventName, QScriptValue handler); /**jsdoc * Removes a function from the list of functions called when an entity event occurs on a particular entity. * <p>See also, the {@link Entities} API.</p> * @function Script.removeEventHandler * @param {Uuid} entityID - The ID of the entity. * @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, QScriptValue handler); /**jsdoc * Starts running another script in Interface, if it isn't already running. The script is not automatically loaded next * time Interface starts. * <p class="availableIn"><strong>Supported Script Types:</strong> Interface Scripts • Avatar Scripts</p> * <p>See also, {@link ScriptDiscoveryService.loadScript}.</p> * @function Script.load * @param {string} filename - The URL of the script to load. This can be relative to the current script's URL. * @example <caption>Load a script from another script.</caption> * // First file: scriptA.js * print("This is script A"); * * // Second file: scriptB.js * print("This is script B"); * Script.load("scriptA.js"); * * // If you run scriptB.js you should see both scripts in the Running Scripts dialog. * // And you should see the following output: * // This is script B * // This is script A */ Q_INVOKABLE void load(const QString& loadfile); /**jsdoc * Includes JavaScript from other files in the current script. If a callback is specified, the files are loaded and * included asynchronously, otherwise they are included synchronously (i.e., script execution blocks while the files are * included). * @function Script.include * @variation 0 * @param {string[]} filenames - The URLs of the scripts to include. Each can be relative to the current script. * @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, QScriptValue callback = QScriptValue()); /**jsdoc * Includes JavaScript from another file in the current script. If a callback is specified, the file is loaded and included * asynchronously, otherwise it is included synchronously (i.e., script execution blocks while the file is included). * @function Script.include * @param {string} filename - The URL of the script to include. It can be relative to the current script. * @param {function} [callback=null] - The function to call back when the script has been included. It can be either the * name of a function or an in-line definition. * @example <caption>Include a script file asynchronously.</caption> * // First file: scriptA.js * print("This is script A"); * * // Second file: scriptB.js * print("This is script B"); * Script.include("scriptA.js", function () { * print("Script A has been included"); * }); * * // If you run scriptB.js you should see only scriptB.js in the running scripts list. * // And you should see the following output: * // This is script B * // This is script A * // Script A has been included */ Q_INVOKABLE void include(const QString& includeFile, QScriptValue callback = QScriptValue()); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MODULE related methods /**jsdoc * Provides access to methods or objects provided in an external JavaScript or JSON file. * See {@link https://docs.vircadia.dev/script/js-tips.html} for further details. * @function Script.require * @param {string} module - The module to use. May be a JavaScript file, a JSON file, or the name of a system module such * as <code>"appUi"</code> (i.e., the "appUi.js" system module JavaScript file). * @returns {object|array} The value assigned to <code>module.exports</code> in the JavaScript file, or the value defined * in the JSON file. */ Q_INVOKABLE QScriptValue require(const QString& moduleId); /**jsdoc * @function Script.resetModuleCache * @param {boolean} [deleteScriptCache=false] - Delete script cache. * @deprecated This function is deprecated and will be removed. */ Q_INVOKABLE void resetModuleCache(bool deleteScriptCache = false); QScriptValue currentModule(); bool registerModuleWithParent(const QScriptValue& module, const QScriptValue& parent); QScriptValue newModule(const QString& modulePath, const QScriptValue& parent = QScriptValue()); QVariantMap fetchModuleSource(const QString& modulePath, const bool forceDownload = false); QScriptValue instantiateModule(const QScriptValue& module, const QString& sourceCode); /**jsdoc * Calls a function repeatedly, at a set interval. * @function Script.setInterval * @param {function} function - The function to call. This can be either the name of a function or an in-line definition. * @param {number} interval - The interval at which to call the function, in ms. * @returns {object} A handle to the interval timer. This can be used in {@link Script.clearInterval}. * @example <caption>Print a message every second.</caption> * Script.setInterval(function () { * print("Interval timer fired"); * }, 1000); */ Q_INVOKABLE QObject* setInterval(const QScriptValue& function, int intervalMS); /**jsdoc * Calls a function once, after a delay. * @function Script.setTimeout * @param {function} function - The function to call. This can be either the name of a function or an in-line definition. * @param {number} timeout - The delay after which to call the function, in ms. * @returns {object} A handle to the timeout timer. This can be used in {@link Script.clearTimeout}. * @example <caption>Print a message once, after a second.</caption> * Script.setTimeout(function () { * print("Timeout timer fired"); * }, 1000); */ Q_INVOKABLE QObject* setTimeout(const QScriptValue& function, int timeoutMS); /**jsdoc * Stops an interval timer set by {@link Script.setInterval|setInterval}. * @function Script.clearInterval * @param {object} timer - The interval timer to stop. * @example <caption>Stop an interval timer.</caption> * // Print a message every second. * var timer = Script.setInterval(function () { * print("Interval timer fired"); * }, 1000); * * // Stop the timer after 10 seconds. * Script.setTimeout(function () { * print("Stop interval timer"); * Script.clearInterval(timer); * }, 10000); */ Q_INVOKABLE void clearInterval(QObject* timer) { stopTimer(reinterpret_cast<QTimer*>(timer)); } Lines 1–500 of 1012. Load more
// // ScriptEngine.h // libraries/script-engine/src // // Created by Brad Hefta-Gaub on 12/14/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_ScriptEngine_h #define hifi_ScriptEngine_h #include <unordered_map> #include <vector> #include <QtCore/QObject> #include <QtCore/QUrl> #include <QtCore/QSet> #include <QtCore/QWaitCondition> #include <QtCore/QStringList> #include <QMap> #include <QMetaEnum> #include <QtScript/QScriptEngine> #include <AnimationCache.h> #include <AnimVariant.h> #include <AvatarData.h> #include <AvatarHashMap.h> #include <LimitedNodeList.h> #include <EntityItemID.h> #include <EntitiesScriptEngineProvider.h> #include <EntityScriptUtils.h> #include "PointerEvent.h" #include "ArrayBufferClass.h" #include "AssetScriptingInterface.h" #include "AudioScriptingInterface.h" #include "BaseScriptEngine.h" #include "ExternalResource.h" #include "Quat.h" #include "Mat4.h" #include "ScriptCache.h" #include "ScriptUUID.h" #include "Vec3.h" #include "ConsoleScriptingInterface.h" #include "SettingHandle.h" #include "Profile.h" class QScriptEngineDebugger; static const QString NO_SCRIPT(""); static const int SCRIPT_FPS = 60; static const int DEFAULT_MAX_ENTITY_PPS = 9000; static const int DEFAULT_ENTITY_PPS_PER_SCRIPT = 900; class ScriptEngines; Q_DECLARE_METATYPE(ScriptEnginePointer) class CallbackData { public: QScriptValue function; EntityItemID definingEntityIdentifier; QUrl definingSandboxURL; }; class DeferredLoadEntity { public: EntityItemID entityID; QString entityScript; //bool forceRedownload; }; struct EntityScriptContentAvailable { EntityItemID entityID; QString scriptOrURL; QString contents; bool isURL; bool success; QString status; }; typedef std::unordered_map<EntityItemID, EntityScriptContentAvailable> EntityScriptContentAvailableMap; typedef QList<CallbackData> CallbackList; typedef QHash<QString, CallbackList> RegisteredEventHandlers; class EntityScriptDetails { public: EntityScriptStatus status { EntityScriptStatus::PENDING }; // If status indicates an error, this contains a human-readable string giving more information about the error. QString errorInfo { "" }; QString scriptText { "" }; QScriptValue scriptObject { QScriptValue() }; int64_t lastModified { 0 }; QUrl definingSandboxURL { QUrl("about:EntityScript") }; }; /**jsdoc * The <code>Script</code> API provides facilities for working with scripts. * * @namespace Script * * @hifi-interface * @hifi-client-entity * @hifi-avatar * @hifi-server-entity * @hifi-assignment-client * * @property {string} context - The context that the script is running in: * <ul> * <li><code>"client"</code>: An Interface or avatar script.</li> * <li><code>"entity_client"</code>: A client entity script.</li> * <li><code>"entity_server"</code>: A server entity script.</li> * <li><code>"agent"</code>: An assignment client script.</li> * </ul> * <em>Read-only.</em> * @property {Script.ResourceBuckets} ExternalPaths - External resource buckets. */ class ScriptEngine : public BaseScriptEngine, public EntitiesScriptEngineProvider { Q_OBJECT Q_PROPERTY(QString context READ getContext) Q_PROPERTY(QString type READ getTypeAsString) Q_PROPERTY(QString fileName MEMBER _fileNameString CONSTANT) public: enum Context { CLIENT_SCRIPT, ENTITY_CLIENT_SCRIPT, ENTITY_SERVER_SCRIPT, AGENT_SCRIPT }; enum Type { CLIENT, ENTITY_CLIENT, ENTITY_SERVER, AGENT, AVATAR }; Q_ENUM(Type) static int processLevelMaxRetries; ScriptEngine(Context context, const QString& scriptContents = NO_SCRIPT, const QString& fileNameString = QString("about:ScriptEngine")); ~ScriptEngine(); /// run the script in a dedicated thread. This will have the side effect of evalulating /// the current script contents and calling run(). Callers will likely want to register the script with external /// services before calling this. void runInThread(); void runDebuggable(); /// run the script in the callers thread, exit when stop() is called. void run(); QString getFilename() const; QList<EntityItemID> getListOfEntityScriptIDs(); /**jsdoc * Stops and unloads the current script. * <p><strong>Warning:</strong> If an assignment client script, the script gets restarted after stopping.</p> * @function Script.stop * @param {boolean} [marshal=false] - Marshal. * <p class="important">Deprecated: This parameter is deprecated and will be removed.</p> * @example <caption>Stop a script after 5s.</caption> * Script.setInterval(function () { * print("Hello"); * }, 1000); * * Script.setTimeout(function () { * Script.stop(true); * }, 5000); */ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // NOTE - this is intended to be a public interface for Agent scripts, and local scripts, but not for EntityScripts Q_INVOKABLE void stop(bool marshal = false); // Stop any evaluating scripts and wait for the scripting thread to finish. void waitTillDoneRunning(); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // NOTE - these are NOT intended to be public interfaces available to scripts, the are only Q_INVOKABLE so we can // properly ensure they are only called on the correct thread /**jsdoc * @function Script.registerGlobalObject * @param {string} name - Name. * @param {object} object - Object. * @deprecated This function is deprecated and will be removed. */ /// registers a global object by name Q_INVOKABLE void registerGlobalObject(const QString& name, QObject* object); /**jsdoc * @function Script.registerGetterSetter * @param {string} name - Name. * @param {function} getter - Getter. * @param {function} setter - Setter. * @param {string} [parent=""] - Parent. * @deprecated This function is deprecated and will be removed. */ /// registers a global getter/setter Q_INVOKABLE void registerGetterSetter(const QString& name, QScriptEngine::FunctionSignature getter, QScriptEngine::FunctionSignature setter, const QString& parent = QString("")); /**jsdoc * @function Script.registerFunction * @param {string} name - Name. * @param {function} function - Function. * @param {number} [numArguments=-1] - Number of arguments. * @deprecated This function is deprecated and will be removed. */ /// register a global function Q_INVOKABLE void registerFunction(const QString& name, QScriptEngine::FunctionSignature fun, int numArguments = -1); /**jsdoc * @function Script.registerFunction * @param {string} parent - Parent. * @param {string} name - Name. * @param {function} function - Function. * @param {number} [numArguments=-1] - Number of arguments. * @deprecated This function is deprecated and will be removed. */ /// register a function as a method on a previously registered global object Q_INVOKABLE void registerFunction(const QString& parent, const QString& name, QScriptEngine::FunctionSignature fun, int numArguments = -1); /**jsdoc * @function Script.registerEnum * @param {string} name - Name. * @param {object} enum - Enum. * @deprecated This function is deprecated and will be removed. */ // WARNING: This function must be called after a registerGlobalObject that creates the namespace this enum is located in, or // the globalObject won't function. E.g., if you have a Foo object and a Foo.FooType enum, Foo must be registered first. /// registers a global enum Q_INVOKABLE void registerEnum(const QString& enumName, QMetaEnum newEnum); /**jsdoc * @function Script.registerValue * @param {string} name - Name. * @param {object} value - Value. * @deprecated This function is deprecated and will be removed. */ /// registers a global object by name Q_INVOKABLE void registerValue(const QString& valueName, QScriptValue value); /**jsdoc * @function Script.evaluate * @param {string} program - Program. * @param {string} filename - File name. * @param {number} [lineNumber=-1] - Line number. * @returns {object} Object. * @deprecated This function is deprecated and will be removed. */ /// evaluate some code in the context of the ScriptEngine and return the result Q_INVOKABLE QScriptValue evaluate(const QString& program, const QString& fileName, int lineNumber = 1); // this is also used by the script tool widget /**jsdoc * @function Script.evaluateInClosure * @param {object} locals - Locals. * @param {object} program - Program. * @returns {object} Object. * @deprecated This function is deprecated and will be removed. */ Q_INVOKABLE QScriptValue evaluateInClosure(const QScriptValue& locals, const QScriptProgram& program); /// if the script engine is not already running, this will download the URL and start the process of seting it up /// to run... NOTE - this is used by Application currently to load the url. We don't really want it to be exposed /// to scripts. we may not need this to be invokable void loadURL(const QUrl& scriptURL, bool reload); bool hasValidScriptSuffix(const QString& scriptFileName); /**jsdoc * Gets the context that the script is running in: Interface/avatar, client entity, server entity, or assignment client. * @function Script.getContext * @returns {string} The context that the script is running in: * <ul> * <li><code>"client"</code>: An Interface or avatar script.</li> * <li><code>"entity_client"</code>: A client entity script.</li> * <li><code>"entity_server"</code>: A server entity script.</li> * <li><code>"agent"</code>: An assignment client script.</li> * </ul> */ Q_INVOKABLE QString getContext() const; /**jsdoc * Checks whether the script is running as an Interface or avatar script. * @function Script.isClientScript * @returns {boolean} <code>true</code> if the script is running as an Interface or avatar script, <code>false</code> if it * isn't. */ Q_INVOKABLE bool isClientScript() const { return _context == CLIENT_SCRIPT; } /**jsdoc * Checks whether the application was compiled as a debug build. * @function Script.isDebugMode * @returns {boolean} <code>true</code> if the application was compiled as a debug build, <code>false</code> if it was * compiled as a release build. */ Q_INVOKABLE bool isDebugMode() const; /**jsdoc * Checks whether the script is running as a client entity script. * @function Script.isEntityClientScript * @returns {boolean} <code>true</code> if the script is running as a client entity script, <code>false</code> if it isn't. */ Q_INVOKABLE bool isEntityClientScript() const { return _context == ENTITY_CLIENT_SCRIPT; } /**jsdoc * Checks whether the script is running as a server entity script. * @function Script.isEntityServerScript * @returns {boolean} <code>true</code> if the script is running as a server entity script, <code>false</code> if it isn't. */ Q_INVOKABLE bool isEntityServerScript() const { return _context == ENTITY_SERVER_SCRIPT; } /**jsdoc * Checks whether the script is running as an assignment client script. * @function Script.isAgentScript * @returns {boolean} <code>true</code> if the script is running as an assignment client script, <code>false</code> if it * isn't. */ Q_INVOKABLE bool isAgentScript() const { return _context == AGENT_SCRIPT; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // NOTE - these are intended to be public interfaces available to scripts /**jsdoc * Adds a function to the list of functions called when a particular event occurs on a particular entity. * <p>See also, the {@link Entities} API.</p> * @function Script.addEventHandler * @param {Uuid} entityID - The ID of the entity. * @param {Script.EntityEvent} eventName - The name of the event. * @param {Script~entityEventCallback|Script~pointerEventCallback|Script~collisionEventCallback} handler - The function to * call when the event occurs on the entity. It can be either the name of a function or an in-line definition. * @example <caption>Report when a mouse press occurs on a particular entity.</caption> * var entityID = Entities.addEntity({ * type: "Box", * position: Vec3.sum(MyAvatar.position, Vec3.multiplyQbyV(MyAvatar.orientation, { x: 0, y: 0, z: -5 })), * dimensions: { x: 0.5, y: 0.5, z: 0.5 }, * lifetime: 300 // Delete after 5 minutes. * }); * * function reportMousePress(entityID, event) { * print("Mouse pressed on entity: " + JSON.stringify(event)); * } * * Script.addEventHandler(entityID, "mousePressOnEntity", reportMousePress); */ Q_INVOKABLE void addEventHandler(const EntityItemID& entityID, const QString& eventName, QScriptValue handler); /**jsdoc * Removes a function from the list of functions called when an entity event occurs on a particular entity. * <p>See also, the {@link Entities} API.</p> * @function Script.removeEventHandler * @param {Uuid} entityID - The ID of the entity. * @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, QScriptValue handler); /**jsdoc * Starts running another script in Interface, if it isn't already running. The script is not automatically loaded next * time Interface starts. * <p class="availableIn"><strong>Supported Script Types:</strong> Interface Scripts • Avatar Scripts</p> * <p>See also, {@link ScriptDiscoveryService.loadScript}.</p> * @function Script.load * @param {string} filename - The URL of the script to load. This can be relative to the current script's URL. * @example <caption>Load a script from another script.</caption> * // First file: scriptA.js * print("This is script A"); * * // Second file: scriptB.js * print("This is script B"); * Script.load("scriptA.js"); * * // If you run scriptB.js you should see both scripts in the Running Scripts dialog. * // And you should see the following output: * // This is script B * // This is script A */ Q_INVOKABLE void load(const QString& loadfile); /**jsdoc * Includes JavaScript from other files in the current script. If a callback is specified, the files are loaded and * included asynchronously, otherwise they are included synchronously (i.e., script execution blocks while the files are * included). * @function Script.include * @variation 0 * @param {string[]} filenames - The URLs of the scripts to include. Each can be relative to the current script. * @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, QScriptValue callback = QScriptValue()); /**jsdoc * Includes JavaScript from another file in the current script. If a callback is specified, the file is loaded and included * asynchronously, otherwise it is included synchronously (i.e., script execution blocks while the file is included). * @function Script.include * @param {string} filename - The URL of the script to include. It can be relative to the current script. * @param {function} [callback=null] - The function to call back when the script has been included. It can be either the * name of a function or an in-line definition. * @example <caption>Include a script file asynchronously.</caption> * // First file: scriptA.js * print("This is script A"); * * // Second file: scriptB.js * print("This is script B"); * Script.include("scriptA.js", function () { * print("Script A has been included"); * }); * * // If you run scriptB.js you should see only scriptB.js in the running scripts list. * // And you should see the following output: * // This is script B * // This is script A * // Script A has been included */ Q_INVOKABLE void include(const QString& includeFile, QScriptValue callback = QScriptValue()); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MODULE related methods /**jsdoc * Provides access to methods or objects provided in an external JavaScript or JSON file. * See {@link https://docs.vircadia.dev/script/js-tips.html} for further details. * @function Script.require * @param {string} module - The module to use. May be a JavaScript file, a JSON file, or the name of a system module such * as <code>"appUi"</code> (i.e., the "appUi.js" system module JavaScript file). * @returns {object|array} The value assigned to <code>module.exports</code> in the JavaScript file, or the value defined * in the JSON file. */ Q_INVOKABLE QScriptValue require(const QString& moduleId); /**jsdoc * @function Script.resetModuleCache * @param {boolean} [deleteScriptCache=false] - Delete script cache. * @deprecated This function is deprecated and will be removed. */ Q_INVOKABLE void resetModuleCache(bool deleteScriptCache = false); QScriptValue currentModule(); bool registerModuleWithParent(const QScriptValue& module, const QScriptValue& parent); QScriptValue newModule(const QString& modulePath, const QScriptValue& parent = QScriptValue()); QVariantMap fetchModuleSource(const QString& modulePath, const bool forceDownload = false); QScriptValue instantiateModule(const QScriptValue& module, const QString& sourceCode); /**jsdoc * Calls a function repeatedly, at a set interval. * @function Script.setInterval * @param {function} function - The function to call. This can be either the name of a function or an in-line definition. * @param {number} interval - The interval at which to call the function, in ms. * @returns {object} A handle to the interval timer. This can be used in {@link Script.clearInterval}. * @example <caption>Print a message every second.</caption> * Script.setInterval(function () { * print("Interval timer fired"); * }, 1000); */ Q_INVOKABLE QObject* setInterval(const QScriptValue& function, int intervalMS); /**jsdoc * Calls a function once, after a delay. * @function Script.setTimeout * @param {function} function - The function to call. This can be either the name of a function or an in-line definition. * @param {number} timeout - The delay after which to call the function, in ms. * @returns {object} A handle to the timeout timer. This can be used in {@link Script.clearTimeout}. * @example <caption>Print a message once, after a second.</caption> * Script.setTimeout(function () { * print("Timeout timer fired"); * }, 1000); */ Q_INVOKABLE QObject* setTimeout(const QScriptValue& function, int timeoutMS); /**jsdoc * Stops an interval timer set by {@link Script.setInterval|setInterval}. * @function Script.clearInterval * @param {object} timer - The interval timer to stop. * @example <caption>Stop an interval timer.</caption> * // Print a message every second. * var timer = Script.setInterval(function () { * print("Interval timer fired"); * }, 1000); * * // Stop the timer after 10 seconds. * Script.setTimeout(function () { * print("Stop interval timer"); * Script.clearInterval(timer); * }, 10000); */ Q_INVOKABLE void clearInterval(QObject* timer) { stopTimer(reinterpret_cast<QTimer*>(timer)); }