Overte C++ Documentation
ScriptManager Class Reference

Manages a single scripting engine. More...

#include <ScriptManager.h>

Inherits QObject, EntitiesScriptEngineProvider, and std::enable_shared_from_this< ScriptManager >.

Collaboration diagram for ScriptManager:

Public Types

enum  Context {
  CLIENT_SCRIPT , ENTITY_CLIENT_SCRIPT , ENTITY_SERVER_SCRIPT , AGENT_SCRIPT ,
  NETWORKLESS_TEST_SCRIPT
}
 Context of the script. More...
 
enum  Type {
  CLIENT , ENTITY_CLIENT , ENTITY_SERVER , AGENT ,
  AVATAR , NETWORKLESS_TEST
}
 Type of the script. More...
 

Public Slots

void updateMemoryCost (const qint64 &deltaSize)
 Script.updateMemoryCost. More...
 

Signals

void attachDefaultEventHandlers ()
 Triggered once before the first call to Script.addEventHandler happens on this ScriptManager connections assumed to use Qt::DirectConnection. More...
 
void releaseEntityPacketSenderMessages (bool wait)
 Triggered repeatedly in the scripting loop to ensure entity edit messages get processed properly connections assumed to use Qt::DirectConnection. More...
 
Scripting events
void scriptLoaded (const QString &scriptFilename)
 Script.scriptLoaded. More...
 
void errorLoadingScript (const QString &scriptFilename)
 Script.errorLoadingScript. More...
 
void update (float deltaTime)
 Triggered frequently at a system-determined interval. More...
 
void scriptEnding ()
 Triggered when the script is stopping.
 
void finished (const QString &fileNameString, ScriptManagerPointer)
 Script.finished. More...
 
void printedMessage (const QString &message, const QString &scriptName)
 Triggered when the script prints a message to the program log. More...
 
void errorMessage (const QString &message, const QString &scriptName)
 Triggered when the script generates an error. More...
 
void warningMessage (const QString &message, const QString &scriptName)
 Triggered when the script generates a warning. More...
 
void infoMessage (const QString &message, const QString &scriptName)
 Triggered when the script generates an information message. More...
 
void printedEntityMessage (const QString &message, const QString &fileName, int lineNumber, const EntityItemID &entityID, bool isServerScript)
 Triggered when a client side entity script prints a message to the program log. More...
 
void errorEntityMessage (const QString &message, const QString &fileName, int lineNumber, const EntityItemID &entityID, bool isServerScript)
 Triggered when a client side entity script generates an error. More...
 
void warningEntityMessage (const QString &message, const QString &fileName, int lineNumber, const EntityItemID &entityID, bool isServerScript)
 Triggered when a client side entity script generates a warning. More...
 
void infoEntityMessage (const QString &message, const QString &fileName, int lineNumber, const EntityItemID &entityID, bool isServerScript)
 Triggered when a client side entity script generates an information message. More...
 
void runningStateChanged ()
 Triggered when the running state of the script changes, e.g., from running to stopping.
 
void clearDebugWindow ()
 Script.clearDebugWindow. More...
 
void loadScript (const QString &scriptName, bool isUserLoaded)
 Script.loadScript. More...
 
void reloadScript (const QString &scriptName, bool isUserLoaded)
 Script.reloadScript. More...
 
void doneRunning ()
 Triggered when the script has stopped.
 
void entityScriptDetailsUpdated ()
 Emitted when an entity script is added or removed, or when the status of an entity script is updated (goes from RUNNING to ERROR_RUNNING_SCRIPT, for example)
 
void entityScriptPreloadFinished (const EntityItemID &entityID)
 Emitted when an entity script has finished running preload. More...
 
void unhandledException (std::shared_ptr< ScriptException > exception)
 Triggered when a script generates an unhandled exception. More...
 

Public Member Functions

void runInThread ()
 Run the script in a dedicated thread. More...
 
void run ()
 Run the script in the caller's thread, exit when Script.stop() is called. More...
 
QString getFilename () const
 Get the filename of the running script, without the path. More...
 
QString getAbsoluteFilename () const
 Get the filename of the running script, with absolute path. More...
 
ScriptEnginePointer engine ()
 Underlying scripting engine. More...
 
bool isStopped () const
 Whether the ScriptManager is stopped and unable to run scripts. More...
 
void waitTillDoneRunning (bool shutdown=false)
 Stop any evaluating scripts and wait for the scripting thread to finish. More...
 
void removeFromScriptEngines ()
 Removes shared pointer to script engine from the list of all script engines. More...
 
void loadURL (const QUrl &scriptURL, bool reload)
 Load a script from a given URL. More...
 
bool hasValidScriptSuffix (const QString &scriptFileName)
 Determines whether a script filename has the right suffix. More...
 
void setUserLoaded (bool isUserLoaded)
 Set whether this script was user-loaded. More...
 
bool isUserLoaded () const
 Whether the script was user-loaded. More...
 
void setQuitWhenFinished (const bool quitWhenFinished)
 Set whether to quit when finished. More...
 
bool isQuitWhenFinished () const
 Whether to quit when finished. More...
 
void setEmitScriptUpdatesFunction (std::function< bool()> func)
 Set a function that determines whether to emit update events. More...
 
void scriptErrorMessage (const QString &message, const QString &fileName, int lineNumber)
 Logs a script error message and emits an errorMessage event. More...
 
void scriptWarningMessage (const QString &message, const QString &fileName, int lineNumber)
 Logs a script warning message and emits an warningMessage event. More...
 
void scriptInfoMessage (const QString &message, const QString &fileName, int lineNumber)
 Logs a script info message and emits an infoMessage event. More...
 
void scriptPrintedMessage (const QString &message, const QString &fileName, int lineNumber)
 Logs a script printed message and emits an printedMessage event. More...
 
void clearDebugLogWindow ()
 Clears the debug log window. More...
 
int getNumRunningEntityScripts () const
 Get the number of running entity scripts. More...
 
bool getEntityScriptDetails (const EntityItemID &entityID, EntityScriptDetails &details) const
 Retrieves the details about an entity script. More...
 
bool hasEntityScriptDetails (const EntityItemID &entityID) const
 Whether there are script details for a given entity ID. More...
 
void setScriptEngines (QSharedPointer< ScriptEngines > &scriptEngines)
 Set a shared pointer to the ScriptEngines class. More...
 
void forwardHandlerCall (const EntityItemID &entityID, const QString &eventName, const ScriptValueList &eventHanderArgs)
 Call all the registered event handlers on an entity for the specified name. More...
 
void removeAllEventHandlers (const EntityItemID &entityID)
 Remove all event handlers for the specified entityID (i.e. the entity is being removed) More...
 
ScriptValue getReturnValue () const
 Return value of the script that finished running. More...
 
Q_INVOKABLE QString getExternalPath (ExternalResource::Bucket bucket, const QString &path)
 Gets the URL for an asset in an external resource bucket. More...
 
std::shared_ptr< ScriptExceptiongetUncaughtException () const
 Get the uncaught exception from the underlying script engine. More...
 
bool getAbortOnUncaughtException () const
 Whether this engine will abort on an uncaught exception. More...
 
void setAbortOnUncaughtException (bool value)
 Whether to abort on an uncaught exception. More...
 
bool isDoneRunning ()
 Returns true after script finished running and doneRunning signal was called. More...
 
Script support functions

These functions exist to support the scripting API

Q_INVOKABLE void stop (bool marshal=false)
 Stops and unloads the current script. More...
 
Script support methods

These functions exist to support the scripting API

Q_INVOKABLE QString getContext () const
 Gets the context that the script is running in: Interface/avatar, client entity, server entity, or assignment client. More...
 
Q_INVOKABLE bool isClientScript () const
 Checks whether the script is running as an Interface or avatar script. More...
 
Q_INVOKABLE bool isDebugMode () const
 Checks whether the application was compiled as a debug build. More...
 
Q_INVOKABLE bool isEntityClientScript () const
 Checks whether the script is running as a client entity script. More...
 
Q_INVOKABLE bool isEntityServerScript () const
 Checks whether the script is running as a server entity script. More...
 
Q_INVOKABLE bool isAgentScript () const
 Checks whether the script is running as an assignment client script. More...
 
Q_INVOKABLE void registerValue (const QString &valueName, ScriptValue value)
 Registers a global object by name. More...
 
Q_INVOKABLE QString formatException (const ScriptValue &exception, bool includeExtendedDetails)
 Format an exception and return it as a string. More...
 
Q_INVOKABLE void addEventHandler (const EntityItemID &entityID, const QString &eventName, const ScriptValue &handler)
 Adds a function to the list of functions called when a particular event occurs on a particular entity. More...
 
Q_INVOKABLE void removeEventHandler (const EntityItemID &entityID, const QString &eventName, const ScriptValue &handler)
 Removes a function from the list of functions called when an entity event occurs on a particular entity. More...
 
Q_INVOKABLE void load (const QString &loadfile)
 Starts running another script in Interface, if it isn't already running. The script is not automatically loaded next time Interface starts. More...
 
Q_INVOKABLE void include (const QStringList &includeFiles, const ScriptValue &callback=ScriptValue())
 Includes JavaScript from other files in the current script. More...
 
Q_INVOKABLE void include (const QString &includeFile, const ScriptValue &callback=ScriptValue())
 Includes JavaScript from another file in the current script. More...
 
Module support methods
Q_INVOKABLE ScriptValue require (const QString &moduleId)
 Provides access to methods or objects provided in an external JavaScript or JSON file. More...
 
Q_INVOKABLE void resetModuleCache (bool deleteScriptCache=false)
 Resets the module cache. More...
 
ScriptValue currentModule ()
 The current parent module from the running JS script. More...
 
bool registerModuleWithParent (const ScriptValue &module, const ScriptValue &parent)
 Replaces or adds "module" to "parent.children[]" array. More...
 
ScriptValue newModule (const QString &modulePath, const ScriptValue &parent=ScriptValue())
 creates a new JS "module" Object with default metadata properties More...
 
QVariantMap fetchModuleSource (const QString &modulePath, const bool forceDownload=false)
 Synchronously fetch a module's source code. More...
 
ScriptValue instantiateModule (const ScriptValue &module, const QString &sourceCode)
 Evaluate a pending module object using the fetched source code. More...
 
ScriptValue evaluate (const QString &program, const QString &fileName=QString())
 Evaluate a program in the underlying scripting engine. More...
 
Q_INVOKABLE QTimer * setInterval (const ScriptValue &function, int intervalMS)
 Calls a function repeatedly, at a set interval. More...
 
Q_INVOKABLE QTimer * setTimeout (const ScriptValue &function, int timeoutMS)
 Calls a function once, after a delay. More...
 
Q_INVOKABLE void clearInterval (QTimer *timer)
 Stops an interval timer. More...
 
Q_INVOKABLE void clearInterval (QVariantMap timer)
 Stops an interval timer. More...
 
Q_INVOKABLE void clearTimeout (QTimer *timer)
 Stops a timeout timer. More...
 
Q_INVOKABLE void clearTimeout (QVariantMap timer)
 Stops a timeout timer Overloaded version is needed in case the timer has expired. More...
 
Q_INVOKABLE void print (const QString &message)
 Prints a message to the program log. More...
 
Q_INVOKABLE QUrl resolvePath (const QString &path) const
 Resolves a relative path to an absolute path. The relative path is relative to the script's location. More...
 
Q_INVOKABLE QUrl resourcesPath () const
 Gets the path to the resources directory for QML files. More...
 
Q_INVOKABLE void beginProfileRange (const QString &label) const
 Starts timing a section of code in order to send usage data about it to Overte. Shouldn't be used outside of the standard scripts. More...
 
Q_INVOKABLE void endProfileRange (const QString &label) const
 Finishes timing a section of code in order to send usage data about it to Overte. Shouldn't be used outside of the standard scripts. More...
 
Entity Script methods
Q_INVOKABLE bool isEntityScriptRunning (const EntityItemID &entityID)
 Checks whether an entity has an entity script running. More...
 
QVariant cloneEntityScriptDetails (const EntityItemID &entityID)
 Clone the details of an entity script. More...
 
QFuture< QVariant > getLocalEntityScriptDetails (const EntityItemID &entityID) override
 Get the details of a local entity script. More...
 
Q_INVOKABLE void requestGarbageCollection ()
 Manually runs the JavaScript garbage collector which reclaims memory by disposing of objects that are no longer reachable.
 
Q_INVOKABLE void logBacktrace (const QString &title)
 Prints out current backtrace to the log. More...
 
Q_INVOKABLE void loadEntityScript (const EntityItemID &entityID, const QString &entityScript, bool forceRedownload)
 Load an entity script. More...
 
Q_INVOKABLE void unloadEntityScript (const EntityItemID &entityID, bool shouldRemoveFromMap=false)
 Unload an entity script. More...
 
Q_INVOKABLE void unloadAllEntityScripts (bool blockingCall=false)
 Unload all entity scripts. More...
 
Q_INVOKABLE void callEntityScriptMethod (const EntityItemID &entityID, const QString &methodName, const QStringList &params=QStringList(), const QUuid &remoteCallerID=QUuid()) override
 Call a method on an entity script. More...
 
Q_INVOKABLE void callEntityScriptMethod (const EntityItemID &entityID, const QString &methodName, const PointerEvent &event)
 Call a method on an entity script. More...
 
Q_INVOKABLE void callEntityScriptMethod (const EntityItemID &entityID, const QString &methodName, const EntityItemID &otherID, const Collision &collision)
 Call a method on an entity script. More...
 
void setType (Type type)
 Set the script type. More...
 
Type getType ()
 Returns the script type. More...
 
QString getTypeAsString () const
 Returns the type of the script as a string. More...
 
bool isFinished () const
 Whether the script has finished running. More...
 
bool isRunning () const
 Whether the script is running. More...
 
bool isStopping () const
 Whether this ScriptManager is stopping. Once this is true, it stays true. More...
 
void disconnectNonEssentialSignals ()
 Disconnect all signals, except essential ones. More...
 

Protected Member Functions

void init ()
 Initializes the underlying scripting engine. More...
 
Q_INVOKABLE void executeOnScriptThread (std::function< void()> function, const Qt::ConnectionType &type=Qt::QueuedConnection)
 executeOnScriptThread More...
 
Q_INVOKABLE QString _requireResolve (const QString &moduleId, const QString &relativeTo=QString())
 Script._requireResolve. More...
 
QString logException (const ScriptValue &exception)
 Log an exception. More...
 
void updateEntityScriptStatus (const EntityItemID &entityID, const EntityScriptStatus &status, const QString &errorInfo=QString())
 Updates the status of an entity script. More...
 
void setEntityScriptDetails (const EntityItemID &entityID, const EntityScriptDetails &details)
 Set the details for an entity script. More...
 
void setParentURL (const QString &parentURL)
 Set the parent URL, used to resolve relative paths. More...
 
QTimer * setupTimerWithInterval (const ScriptValue &function, int intervalMS, bool isSingleShot)
 Creates a timer with the specified interval. More...
 
void stopTimer (QTimer *timer)
 Stops a timer. More...
 
Q_INVOKABLE void entityScriptContentAvailable (const EntityItemID &entityID, const QString &scriptOrURL, const QString &contents, bool isURL, bool success, const QString &status)
 Script.entityScriptContentAvailable. More...
 
void doWithEnvironment (const EntityItemID &entityID, const QUrl &sandboxURL, std::function< void()> operation)
 Execute operation in the appropriate context for (the possibly empty) entityID. Even if entityID is supplied as currentEntityIdentifier, this still documents the source of the code being executed (e.g., if we ever sandbox different entity scripts, or provide different global values for different entity scripts). More...
 
void callWithEnvironment (const EntityItemID &entityID, const QUrl &sandboxURL, const ScriptValue &function, const ScriptValue &thisObject, const ScriptValueList &args)
 Execute operation in the appropriate context for (the possibly empty) entityID. More...
 

Friends

ScriptManagerPointer newScriptManager (Context context, const QString &scriptContents, const QString &fileNameString)
 Creates a new ScriptManager. More...
 

Detailed Description

Manages a single scripting engine.

This class manages and sets up a single scripting engine to make it execute scripts.

It passes the objects needed to expose the public API, provides console access and error reporting and event management.

This manipulates a single underlying instance of ScriptEngine.

Part of this class' functionality exists only to provide helper functions to the scripts that are run by the scripting engine, and shouldn't be considered part of the C++ API. Those are the functions in the "Script support methods", "Module support methods", "Entity Script methods", and "Scripting signals" sections.

The script-facing interface is in ScriptManagerScriptingInterface and documented in JSDoc as the Script class.

The ScriptManager provides the following functionality to scripts:

  • A math library: Quat, Vec3, Mat4
  • UUID generation: Uuid
  • Filesystem access: File
  • Console access: console, print
  • Resource access: Resource, Asset, Resources, ExternalPaths
  • Scripting system management: Script
  • Module loading: require
  • Web access: XMLHttpRequest, WebSocket
  • Other miscellaneous functionality.

Example:

#include "ScriptManager.h"
// Scripts only stop running when Script.stop() is called.
// In the normal environment this isn't needed, but for things like unit tests we need
// to use it to make the ScriptManager return from run().
QString scriptSource = "print(\"Hello, world!\"); Script.stop(true);";
QString scriptFilename = "test.js";
ScriptManagerPointer sm = newScriptManager(ScriptManager::NETWORKLESS_TEST_SCRIPT, scriptSource, scriptFilename);
connect(sm.get(), &ScriptManager::printedMessage, [](const QString& message, const QString& engineName){
qCDebug(scriptengine) << "Printed message from engine" << engineName << ": " << message;
});
qInfo() << "Running script!";
sm->run();
qInfo() << "Done!"
void printedMessage(const QString &message, const QString &scriptName)
Triggered when the script prints a message to the program log.
@ NETWORKLESS_TEST_SCRIPT
Network-less test system context. This is used for the QTest self-tests, and minimizes the API that i...
Definition: ScriptManager.h:331
friend ScriptManagerPointer newScriptManager(Context context, const QString &scriptContents, const QString &fileNameString)
Creates a new ScriptManager.
Definition: ScriptManager.cpp:251
Note
Technically, the ScriptManager isn't generic enough – it implements things that imitate Node.js for examine in the module loading code, which makes it JS specific. This code should probably be moved into the JS ScriptEngine class instead.

The EntityScript functionality might also benefit from being split off into a separate class, for better organization.

Some more functionality can be shifted to ScriptManagerScriptingInterface, since it only provides services to scripts and isn't called from C++.

Member Enumeration Documentation

◆ Context

Context of the script.

Enumerator
CLIENT_SCRIPT 

Client script. Allowed to access local HTML files on UI created from C++ calls.

ENTITY_CLIENT_SCRIPT 

Entity client script.

ENTITY_SERVER_SCRIPT 

Entity server script.

AGENT_SCRIPT 

Agent script.

NETWORKLESS_TEST_SCRIPT 

Network-less test system context. This is used for the QTest self-tests, and minimizes the API that is made available to the running script. It removes the need for network access, which makes for much faster test execution.

Warning
This is a development-targeted bit of functionality.
This is going to break functionality like loadURL and require

◆ Type

Type of the script.

Enumerator
CLIENT 

Client.

ENTITY_CLIENT 

Entity client Receives the update event.

ENTITY_SERVER 

Entity server Receives the update event.

AGENT 

Agent script.

AVATAR 

Avatar script.

NETWORKLESS_TEST 

Test system script.

This is used for the QTest self-tests, and minimizes the API that is made available to the running script. It removes the need for network access, which makes for much faster test execution.

Warning
This is a development-targeted bit of functionality.

Member Function Documentation

◆ _requireResolve()

QString ScriptManager::_requireResolve ( const QString &  moduleId,
const QString &  relativeTo = QString() 
)
protected

Script._requireResolve.

Note
this is not meant to be called directly, but just to have QMetaObject take care of wiring it up in general; then inside of init() we just have to do "Script.require.resolve = Script._requireResolve;"
Parameters
moduleId
relativeTo
Returns
QString

◆ addEventHandler()

void ScriptManager::addEventHandler ( const EntityItemID entityID,
const QString &  eventName,
const ScriptValue handler 
)

Adds a function to the list of functions called when a particular event occurs on a particular entity.

Parameters
entityIDEntity ID
eventNameName of the event
handlerEvent handler
Note
The same handler can be added multiple times.

◆ attachDefaultEventHandlers

void ScriptManager::attachDefaultEventHandlers ( )
signal

Triggered once before the first call to Script.addEventHandler happens on this ScriptManager connections assumed to use Qt::DirectConnection.

Note
not for use by scripts

◆ beginProfileRange()

void ScriptManager::beginProfileRange ( const QString &  label) const

Starts timing a section of code in order to send usage data about it to Overte. Shouldn't be used outside of the standard scripts.

Parameters
label

◆ callEntityScriptMethod() [1/3]

void ScriptManager::callEntityScriptMethod ( const EntityItemID entityID,
const QString &  methodName,
const EntityItemID otherID,
const Collision &  collision 
)

Call a method on an entity script.

Parameters
entityID
methodName
otherID
collision

◆ callEntityScriptMethod() [2/3]

void ScriptManager::callEntityScriptMethod ( const EntityItemID entityID,
const QString &  methodName,
const PointerEvent event 
)

Call a method on an entity script.

Parameters
entityID
methodName
event

◆ callEntityScriptMethod() [3/3]

void ScriptManager::callEntityScriptMethod ( const EntityItemID entityID,
const QString &  methodName,
const QStringList &  params = QStringList(),
const QUuid &  remoteCallerID = QUuid() 
)
override

Call a method on an entity script.

Parameters
entityID
methodName
params
remoteCallerID

◆ callWithEnvironment()

void ScriptManager::callWithEnvironment ( const EntityItemID entityID,
const QUrl &  sandboxURL,
const ScriptValue function,
const ScriptValue thisObject,
const ScriptValueList &  args 
)
protected

Execute operation in the appropriate context for (the possibly empty) entityID.

This is equivalent to doWithEnvironment(), only with separate arguments for the function, this object and arguments.

This is a convenience function, which performs:

auto operation = [&]() {
function.call(thisObject, args);
};
doWithEnvironment(entityID, sandboxURL, operation);
void doWithEnvironment(const EntityItemID &entityID, const QUrl &sandboxURL, std::function< void()> operation)
Execute operation in the appropriate context for (the possibly empty) entityID. Even if entityID is s...
Definition: ScriptManager.cpp:2543
Parameters
entityIDEntity ID, may be null
sandboxURLSandbox URL
functionFunction to call
thisObject"this" object to use for the call
argsArguments

◆ clearDebugLogWindow()

void ScriptManager::clearDebugLogWindow ( )

Clears the debug log window.

This only emits clearDebugWindow()

◆ clearDebugWindow

void ScriptManager::clearDebugWindow ( )
signal

Script.clearDebugWindow.

◆ clearInterval() [1/2]

Q_INVOKABLE void ScriptManager::clearInterval ( QTimer *  timer)
inline

Stops an interval timer.

Parameters
timerTimer to stop

◆ clearInterval() [2/2]

Q_INVOKABLE void ScriptManager::clearInterval ( QVariantMap  timer)
inline

Stops an interval timer.

Overloaded version is needed in case the timer has expired

Parameters
timerTimer to stop

◆ clearTimeout() [1/2]

Q_INVOKABLE void ScriptManager::clearTimeout ( QTimer *  timer)
inline

Stops a timeout timer.

Parameters
timerTimer to stop

◆ clearTimeout() [2/2]

Q_INVOKABLE void ScriptManager::clearTimeout ( QVariantMap  timer)
inline

Stops a timeout timer Overloaded version is needed in case the timer has expired.

Parameters
timerTimer to stop

◆ cloneEntityScriptDetails()

QVariant ScriptManager::cloneEntityScriptDetails ( const EntityItemID entityID)

Clone the details of an entity script.

Parameters
entityIDEntity ID
Returns
QVariant Copy of the details

◆ currentModule()

ScriptValue ScriptManager::currentModule ( )

The current parent module from the running JS script.

Returns
ScriptValue Module. May be null or empty.

◆ disconnectNonEssentialSignals()

void ScriptManager::disconnectNonEssentialSignals ( )

Disconnect all signals, except essential ones.

This disconnects all signals, except the destroyed() and finished() handlers that are needed for cleanup.

◆ doWithEnvironment()

void ScriptManager::doWithEnvironment ( const EntityItemID entityID,
const QUrl &  sandboxURL,
std::function< void()>  operation 
)
protected

Execute operation in the appropriate context for (the possibly empty) entityID. Even if entityID is supplied as currentEntityIdentifier, this still documents the source of the code being executed (e.g., if we ever sandbox different entity scripts, or provide different global values for different entity scripts).

Parameters
entityIDEntity ID, may be null
sandboxURLSandbox URL
operationOperation to call

◆ endProfileRange()

void ScriptManager::endProfileRange ( const QString &  label) const

Finishes timing a section of code in order to send usage data about it to Overte. Shouldn't be used outside of the standard scripts.

Parameters
label

◆ engine()

ScriptEnginePointer ScriptManager::engine ( )
inline

Underlying scripting engine.

Returns
ScriptEnginePointer Scripting engine

◆ entityScriptContentAvailable()

void ScriptManager::entityScriptContentAvailable ( const EntityItemID entityID,
const QString &  scriptOrURL,
const QString &  contents,
bool  isURL,
bool  success,
const QString &  status 
)
protected

Script.entityScriptContentAvailable.

Parameters
entityID
scriptOrURL
contents
isURL
success
status

◆ entityScriptPreloadFinished

void ScriptManager::entityScriptPreloadFinished ( const EntityItemID entityID)
signal

Emitted when an entity script has finished running preload.

Parameters
entityID

◆ errorEntityMessage

void ScriptManager::errorEntityMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber,
const EntityItemID entityID,
bool  isServerScript 
)
signal

Triggered when a client side entity script generates an error.

Parameters
message
fileNameName of the file in which message was generated.
lineNumberNumber of the line on which message was generated.
entityID
isServerScripttrue if entity script is server-side, false if it is client-side.

◆ errorLoadingScript

void ScriptManager::errorLoadingScript ( const QString &  scriptFilename)
signal

Script.errorLoadingScript.

Parameters
scriptFilename

◆ errorMessage

void ScriptManager::errorMessage ( const QString &  message,
const QString &  scriptName 
)
signal

Triggered when the script generates an error.

Parameters
message
scriptName

◆ evaluate()

ScriptValue ScriptManager::evaluate ( const QString &  program,
const QString &  fileName = QString() 
)

Evaluate a program in the underlying scripting engine.

This simply calls to ScriptEngine::evaluate()

Parameters
programSource of the program
fileNameFilename it was obtained from
Returns
ScriptValue Result of the evaluation

◆ executeOnScriptThread()

void ScriptManager::executeOnScriptThread ( std::function< void()>  function,
const Qt::ConnectionType &  type = Qt::QueuedConnection 
)
protected

executeOnScriptThread

Parameters
function
type

◆ fetchModuleSource()

QVariantMap ScriptManager::fetchModuleSource ( const QString &  modulePath,
const bool  forceDownload = false 
)

Synchronously fetch a module's source code.

The return value is a map containing the following fields:

  • "status" – A string indicating the status of the operation
  • "success" – A true or false value indicating success or failure
  • "url" – The URL of the source. May not be present.
  • "contents" – The contents of the source. May not be present.
Parameters
modulePathPath to the module's source code
forceDownloadForce a redownload even if the source is already in the cache
Returns
QVariantMap The result of the operation

◆ finished

void ScriptManager::finished ( const QString &  fileNameString,
ScriptManagerPointer   
)
signal

Script.finished.

Parameters
fileNameString

◆ formatException()

QString ScriptManager::formatException ( const ScriptValue exception,
bool  includeExtendedDetails 
)

Format an exception and return it as a string.

Parameters
exceptionException object, containing the exception information.
includeExtendedDetailsInclude additional troubleshooting information from the "detail" property, if there's one
Returns
QString A multi-line string containing the formatted exception

◆ forwardHandlerCall()

void ScriptManager::forwardHandlerCall ( const EntityItemID entityID,
const QString &  eventName,
const ScriptValueList &  eventHanderArgs 
)

Call all the registered event handlers on an entity for the specified name.

Look up the handler associated with eventName and entityID. If found, evalute the argGenerator thunk and call the handler with those args

Parameters
entityID
eventName
eventHanderArgs

◆ getAbortOnUncaughtException()

bool ScriptManager::getAbortOnUncaughtException ( ) const
inline

Whether this engine will abort on an uncaught exception.

Warning
This probably should be refactored into a more comprehensive per-script flags system
Returns
true
false

◆ getAbsoluteFilename()

QString ScriptManager::getAbsoluteFilename ( ) const

Get the filename of the running script, with absolute path.

Returns
QString Filename

◆ getContext()

QString ScriptManager::getContext ( ) const

Gets the context that the script is running in: Interface/avatar, client entity, server entity, or assignment client.

Note
This is part of the public JS API
Returns
QString

◆ getEntityScriptDetails()

bool ScriptManager::getEntityScriptDetails ( const EntityItemID entityID,
EntityScriptDetails details 
) const

Retrieves the details about an entity script.

Parameters
entityIDEntity ID
detailsReturned details
Returns
true If the entity ID was found
false If the entity ID wasn't found. details will be unmodified.

◆ getExternalPath()

QString ScriptManager::getExternalPath ( ExternalResource::Bucket  bucket,
const QString &  path 
)

Gets the URL for an asset in an external resource bucket.

Parameters
bucket
path
Returns
Q_INVOKABLE

◆ getFilename()

QString ScriptManager::getFilename ( ) const

Get the filename of the running script, without the path.

Returns
QString Filename

◆ getLocalEntityScriptDetails()

QFuture< QVariant > ScriptManager::getLocalEntityScriptDetails ( const EntityItemID entityID)
override

Get the details of a local entity script.

Same as cloneEntityScriptDetails, only as a QFuture.

Parameters
entityIDEntity ID
Returns
QFuture<QVariant>

◆ getNumRunningEntityScripts()

int ScriptManager::getNumRunningEntityScripts ( ) const

Get the number of running entity scripts.

Returns
int Number of scripts with the status EntityScriptStatus::RUNNING

◆ getReturnValue()

ScriptValue ScriptManager::getReturnValue ( ) const
inline

Return value of the script that finished running.

This should only be used after the script terminates.

Returns
ScriptValue

◆ getType()

Type ScriptManager::getType ( )
inline

Returns the script type.

Returns
Type of this script

◆ getTypeAsString()

QString ScriptManager::getTypeAsString ( ) const

Returns the type of the script as a string.

Returns
QString A string describing the script's type

◆ getUncaughtException()

std::shared_ptr< ScriptException > ScriptManager::getUncaughtException ( ) const

Get the uncaught exception from the underlying script engine.

Returns
std::shared_ptr<ScriptException> Exception

◆ hasEntityScriptDetails()

bool ScriptManager::hasEntityScriptDetails ( const EntityItemID entityID) const

Whether there are script details for a given entity ID.

Parameters
entityIDEntity ID
Returns
true There is an entity script for this entity
false There's no entity script

◆ hasValidScriptSuffix()

bool ScriptManager::hasValidScriptSuffix ( const QString &  scriptFileName)

Determines whether a script filename has the right suffix.

Parameters
scriptFileName
Returns
true When the script has the right file extension (eg, .js)
false Otherwise

◆ include() [1/2]

void ScriptManager::include ( const QString &  includeFile,
const ScriptValue callback = ScriptValue() 
)

Includes JavaScript from another file in the current script.

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.

Parameters
includeFile
callback

◆ include() [2/2]

void ScriptManager::include ( const QStringList &  includeFiles,
const ScriptValue callback = ScriptValue() 
)

Includes JavaScript from other files in the current script.

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.

Parameters
includeFilesList of files to include
callbackCallback to call when the files have finished loading.

◆ infoEntityMessage

void ScriptManager::infoEntityMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber,
const EntityItemID entityID,
bool  isServerScript 
)
signal

Triggered when a client side entity script generates an information message.

Parameters
message
fileNameName of the file in which message was generated.
lineNumberNumber of the line on which message was generated.
entityID
isServerScripttrue if entity script is server-side, false if it is client-side.

◆ infoMessage

void ScriptManager::infoMessage ( const QString &  message,
const QString &  scriptName 
)
signal

Triggered when the script generates an information message.

Parameters
message
scriptName

◆ init()

void ScriptManager::init ( )
protected

Initializes the underlying scripting engine.

This sets up the scripting engine with the default APIs

◆ instantiateModule()

ScriptValue ScriptManager::instantiateModule ( const ScriptValue module,
const QString &  sourceCode 
)

Evaluate a pending module object using the fetched source code.

Parameters
moduleModule object
sourceCodeSource code to evaluate
Returns
ScriptValue The result of evaluating the source code

◆ isAgentScript()

Q_INVOKABLE bool ScriptManager::isAgentScript ( ) const
inline

Checks whether the script is running as an assignment client script.

Returns
bool

◆ isClientScript()

Q_INVOKABLE bool ScriptManager::isClientScript ( ) const
inline

Checks whether the script is running as an Interface or avatar script.

Note
This is part of the public JS API
Returns
bool

◆ isDebugMode()

bool ScriptManager::isDebugMode ( ) const

Checks whether the application was compiled as a debug build.

Note
This is part of the public JS API
Returns
bool

◆ isDoneRunning()

bool ScriptManager::isDoneRunning ( )
inline

Returns true after script finished running and doneRunning signal was called.

Returns
true If the script and doneRunning signal was called
false If the script has not finished running yet

◆ isEntityClientScript()

Q_INVOKABLE bool ScriptManager::isEntityClientScript ( ) const
inline

Checks whether the script is running as a client entity script.

Returns
bool

◆ isEntityScriptRunning()

Q_INVOKABLE bool ScriptManager::isEntityScriptRunning ( const EntityItemID entityID)
inline

Checks whether an entity has an entity script running.

Parameters
entityID
Returns
bool

◆ isEntityServerScript()

Q_INVOKABLE bool ScriptManager::isEntityServerScript ( ) const
inline

Checks whether the script is running as a server entity script.

Returns
bool

◆ isFinished()

bool ScriptManager::isFinished ( ) const
inline

Whether the script has finished running.

The finished status is set by stop()

Returns
true The script has finished
false The script is running

◆ isQuitWhenFinished()

bool ScriptManager::isQuitWhenFinished ( ) const
inline

Whether to quit when finished.

This is read by ScriptEngines

Returns
true
false

◆ isRunning()

bool ScriptManager::isRunning ( ) const
inline

Whether the script is running.

Returns
true The script is running
false The script is not running

◆ isStopped()

bool ScriptManager::isStopped ( ) const

Whether the ScriptManager is stopped and unable to run scripts.

This is always false for NETWORKLESS_TEST_SCRIPT scripts.

Otherwise, it checks whether scriptEngines is set and is not stopped.

Returns
true
false

◆ isStopping()

bool ScriptManager::isStopping ( ) const
inline

Whether this ScriptManager is stopping. Once this is true, it stays true.

Returns
true We are stopping
false We are not stopping

◆ isUserLoaded()

bool ScriptManager::isUserLoaded ( ) const
inline

Whether the script was user-loaded.

This is used by Application to track if a script is user loaded or not.

Note
Consider finding a solution inside of Application so that the ScriptManager class is not polluted by this notion
Returns
true
false

◆ load()

void ScriptManager::load ( const QString &  loadfile)

Starts running another script in Interface, if it isn't already running. The script is not automatically loaded next time Interface starts.

The script is loaded as a stand-alone script.

Parameters
loadfileFile to load
Warning
In practice this seems equivalent to calling loadScript or reloadScript. It reacts to _isReloading in an odd-looking manner. Is this function superfluous?

◆ loadEntityScript()

void ScriptManager::loadEntityScript ( const EntityItemID entityID,
const QString &  entityScript,
bool  forceRedownload 
)

Load an entity script.

Parameters
entityID
entityScript
forceRedownload

◆ loadScript

void ScriptManager::loadScript ( const QString &  scriptName,
bool  isUserLoaded 
)
signal

Script.loadScript.

Parameters
scriptName
isUserLoaded

◆ loadURL()

void ScriptManager::loadURL ( const QUrl &  scriptURL,
bool  reload 
)

Load a script from a given URL.

If the script engine is not already running, this will download the URL and start the process of seting it up to run.

Parameters
scriptURLURL where to load the script from. Can be http, https, atp, or file protocol. The file extension has to pass hasValidScriptSuffix().
reloadLoad the script again even if it's in the cache.
Note
For file:// URLs, only URLs under the default scripts location are allowed.
See also
PathUtils::defaultScriptsLocation

◆ logBacktrace()

void ScriptManager::logBacktrace ( const QString &  title)

Prints out current backtrace to the log.

Parameters
title

◆ logException()

QString ScriptManager::logException ( const ScriptValue exception)
protected

Log an exception.

This both sends an exception to the log as an error message, and returns the formatted text as a string.

Parameters
exceptionException
Returns
QString Exception formatted as a string

◆ newModule()

ScriptValue ScriptManager::newModule ( const QString &  modulePath,
const ScriptValue parent = ScriptValue() 
)

creates a new JS "module" Object with default metadata properties

This imitates what is provided by https://nodejs.org/api/modules.html

Parameters
modulePathFile path to the module
parentParent module
Returns
ScriptValue Created module object

◆ print()

void ScriptManager::print ( const QString &  message)

Prints a message to the program log.

Parameters
message

◆ printedEntityMessage

void ScriptManager::printedEntityMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber,
const EntityItemID entityID,
bool  isServerScript 
)
signal

Triggered when a client side entity script prints a message to the program log.

Parameters
message
fileNameName of the file in which message was generated.
lineNumberNumber of the line on which message was generated.
entityID
isServerScripttrue if entity script is server-side, false if it is client-side.

◆ printedMessage

void ScriptManager::printedMessage ( const QString &  message,
const QString &  scriptName 
)
signal

Triggered when the script prints a message to the program log.

Parameters
message
scriptName

◆ registerModuleWithParent()

bool ScriptManager::registerModuleWithParent ( const ScriptValue module,
const ScriptValue parent 
)

Replaces or adds "module" to "parent.children[]" array.

This is an internal use function used as a part of the 'require' implementation.

Parameters
moduleModule to register
parentParent
Returns
true Registration successful
false Registration failed, if the parent isn't a valid module

◆ registerValue()

void ScriptManager::registerValue ( const QString &  valueName,
ScriptValue  value 
)

Registers a global object by name.

Parameters
valueName
value

◆ releaseEntityPacketSenderMessages

void ScriptManager::releaseEntityPacketSenderMessages ( bool  wait)
signal

Triggered repeatedly in the scripting loop to ensure entity edit messages get processed properly connections assumed to use Qt::DirectConnection.

Note
Not for use by scripts
Parameters
wait

◆ reloadScript

void ScriptManager::reloadScript ( const QString &  scriptName,
bool  isUserLoaded 
)
signal

Script.reloadScript.

Parameters
scriptName
isUserLoaded

◆ removeAllEventHandlers()

void ScriptManager::removeAllEventHandlers ( const EntityItemID entityID)

Remove all event handlers for the specified entityID (i.e. the entity is being removed)

Parameters
entityIDEntity ID

◆ removeEventHandler()

void ScriptManager::removeEventHandler ( const EntityItemID entityID,
const QString &  eventName,
const ScriptValue handler 
)

Removes a function from the list of functions called when an entity event occurs on a particular entity.

Parameters
entityIDEntity ID
eventNameName if the event
handlerEvent handler

◆ removeFromScriptEngines()

void ScriptManager::removeFromScriptEngines ( )

Removes shared pointer to script engine from the list of all script engines.

This allows deletion of the script engine once all shared pointer instances are gone. This function is called for entity script engines when they are being destroyed.

◆ require()

ScriptValue ScriptManager::require ( const QString &  moduleId)

Provides access to methods or objects provided in an external JavaScript or JSON file.

Implements CommonJS/Node.js like require/module support

Parameters
moduleIdModule to load
Returns
ScriptValue

◆ resetModuleCache()

void ScriptManager::resetModuleCache ( bool  deleteScriptCache = false)

Resets the module cache.

Parameters
deleteScriptCache

◆ resolvePath()

QUrl ScriptManager::resolvePath ( const QString &  path) const

Resolves a relative path to an absolute path. The relative path is relative to the script's location.

Parameters
path
Returns
QUrl

◆ resourcesPath()

QUrl ScriptManager::resourcesPath ( ) const

Gets the path to the resources directory for QML files.

Returns
QUrl

◆ run()

void ScriptManager::run ( )

Run the script in the caller's thread, exit when Script.stop() is called.

Most scripts never stop running, so this function will never return for them.

◆ runInThread()

void ScriptManager::runInThread ( )

Run the script in a dedicated thread.

This will have the side effect of evaluating the current script contents and calling run(). Callers will likely want to register the script with external services before calling this.

This function will return immediately, and work will continue on the newly created thread.

Note
Can't be called twice.
The underlying thread is not accessible.

◆ scriptErrorMessage()

void ScriptManager::scriptErrorMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber 
)

Logs a script error message and emits an errorMessage event.

Emits errorMessage()

Parameters
messageMessage to send to the log
fileNameName of the file in which message was generated. Empty string when no file name is available.
lineNumberNumber of the line on which message was generated. -1 if there line number is not available.

◆ scriptInfoMessage()

void ScriptManager::scriptInfoMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber 
)

Logs a script info message and emits an infoMessage event.

Emits infoMessage()

Parameters
messageMessage to send to the log
fileNameName of the file in which message was generated. Empty string when no file name is available.
lineNumberNumber of the line on which message was generated. -1 if there line number is not available.

◆ scriptLoaded

void ScriptManager::scriptLoaded ( const QString &  scriptFilename)
signal

Script.scriptLoaded.

Parameters
scriptFilename

◆ scriptPrintedMessage()

void ScriptManager::scriptPrintedMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber 
)

Logs a script printed message and emits an printedMessage event.

These are messages scripts provide by calling the print function. Emits printedMessage()

Parameters
messageMessage to send to the log
fileNameName of the file in which message was generated. Empty string when no file name is available.
lineNumberNumber of the line on which message was generated. -1 if there line number is not available.

◆ scriptWarningMessage()

void ScriptManager::scriptWarningMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber 
)

Logs a script warning message and emits an warningMessage event.

Emits warningMessage()

Parameters
messageMessage to send to the log
fileNameName of the file in which message was generated. Empty string when no file name is available.
lineNumberNumber of the line on which message was generated. -1 if there line number is not available.

◆ setAbortOnUncaughtException()

void ScriptManager::setAbortOnUncaughtException ( bool  value)
inline

Whether to abort on an uncaught exception.

Warning
This probably should be refactored into a more comprehensive per-script flags system
Parameters
value

◆ setEmitScriptUpdatesFunction()

void ScriptManager::setEmitScriptUpdatesFunction ( std::function< bool()>  func)
inline

Set a function that determines whether to emit update events.

Function func will be called from run() to determine whether update() will be issued. The update() event will be called if func() returns true.

Parameters
funcFunction that determines whether update() events will be issued.

◆ setEntityScriptDetails()

void ScriptManager::setEntityScriptDetails ( const EntityItemID entityID,
const EntityScriptDetails details 
)
protected

Set the details for an entity script.

Parameters
entityIDEntity ID
detailsDetails

◆ setInterval()

QTimer * ScriptManager::setInterval ( const ScriptValue function,
int  intervalMS 
)

Calls a function repeatedly, at a set interval.

Note
This is a JS API service.
Parameters
functionFunction to call
intervalMSInterval at which to call the function, in ms
Returns
QTimer* A pointer to the timer

◆ setParentURL()

void ScriptManager::setParentURL ( const QString &  parentURL)
inlineprotected

Set the parent URL, used to resolve relative paths.

Relative paths are resolved respect of this URL

Parameters
parentURLParent URL

◆ setQuitWhenFinished()

void ScriptManager::setQuitWhenFinished ( const bool  quitWhenFinished)
inline

Set whether to quit when finished.

This is used by ScriptEngines

Parameters
quitWhenFinished

◆ setScriptEngines()

void ScriptManager::setScriptEngines ( QSharedPointer< ScriptEngines > &  scriptEngines)
inline

Set a shared pointer to the ScriptEngines class.

This is used to ask ScriptEngines whether the system is being stopped. Setting this is optional.

isStopped() is implemented by asking ScriptEngines.

Parameters
scriptEnginesScriptEngines class

◆ setTimeout()

QTimer * ScriptManager::setTimeout ( const ScriptValue function,
int  timeoutMS 
)

Calls a function once, after a delay.

Note
This is a JS API service.
Parameters
functionFunction to call
timeoutMSHow long to wait before calling the function, in ms
Returns
QTimer* A pointer to the timer

◆ setType()

void ScriptManager::setType ( Type  type)
inline

Set the script type.

Parameters
typeType of this script

◆ setupTimerWithInterval()

QTimer * ScriptManager::setupTimerWithInterval ( const ScriptValue function,
int  intervalMS,
bool  isSingleShot 
)
protected

Creates a timer with the specified interval.

Parameters
functionFunction to call when the interval elapses
intervalMSInterval in milliseconds
isSingleShotWhether the timer happens continuously or a single time
Returns
QTimer*

◆ setUserLoaded()

void ScriptManager::setUserLoaded ( bool  isUserLoaded)
inline

Set whether this script was user-loaded.

This is used by Application to track if a script is user loaded or not.

Note
Consider finding a solution inside of Application so that the ScriptManager class is not polluted by this notion
Parameters
isUserLoadedScript is user-loaded.

◆ stop()

void ScriptManager::stop ( bool  marshal = false)

Stops and unloads the current script.

Note
This is part of the public scripting API for Agent scripts and local scripts, but not for EntityScripts
Parameters
marshalDeprecated

◆ stopTimer()

void ScriptManager::stopTimer ( QTimer *  timer)
protected

Stops a timer.

Parameters
timerTimer to stop

◆ unhandledException

void ScriptManager::unhandledException ( std::shared_ptr< ScriptException exception)
signal

Triggered when a script generates an unhandled exception.

Parameters
exception

◆ unloadAllEntityScripts()

void ScriptManager::unloadAllEntityScripts ( bool  blockingCall = false)

Unload all entity scripts.

Parameters
blockingCall

◆ unloadEntityScript()

void ScriptManager::unloadEntityScript ( const EntityItemID entityID,
bool  shouldRemoveFromMap = false 
)

Unload an entity script.

Parameters
entityID
shouldRemoveFromMap

◆ update

void ScriptManager::update ( float  deltaTime)
signal

Triggered frequently at a system-determined interval.

Parameters
deltaTime

◆ updateEntityScriptStatus()

void ScriptManager::updateEntityScriptStatus ( const EntityItemID entityID,
const EntityScriptStatus &  status,
const QString &  errorInfo = QString() 
)
protected

Updates the status of an entity script.

Emits entityScriptDetailsUpdated()

Parameters
entityIDEntity ID
statusStatus
errorInfoDescription of the error, if any

◆ updateMemoryCost

void ScriptManager::updateMemoryCost ( const qint64 &  deltaSize)
slot

Script.updateMemoryCost.

Sends a memory cost update to the underlying scripting engine

Parameters
deltaSizeDifference in memory usage

◆ waitTillDoneRunning()

void ScriptManager::waitTillDoneRunning ( bool  shutdown = false)

Stop any evaluating scripts and wait for the scripting thread to finish.

Parameters
shutdownTrue if we are currently shutting down. Setting this to true will allow processing events emitted during the script's shutdown, such as scripts saving settings.
Note
This function has an internal timeout, and will forcefully abort the script if it takes too long.

◆ warningEntityMessage

void ScriptManager::warningEntityMessage ( const QString &  message,
const QString &  fileName,
int  lineNumber,
const EntityItemID entityID,
bool  isServerScript 
)
signal

Triggered when a client side entity script generates a warning.

Parameters
message
fileNameName of the file in which message was generated.
lineNumberNumber of the line on which message was generated.
entityID
isServerScripttrue if entity script is server-side, false if it is client-side.

◆ warningMessage

void ScriptManager::warningMessage ( const QString &  message,
const QString &  scriptName 
)
signal

Triggered when the script generates a warning.

Parameters
message
scriptName

Friends And Related Function Documentation

◆ newScriptManager

ScriptManagerPointer newScriptManager ( Context  context,
const QString &  scriptContents,
const QString &  fileNameString 
)
friend

Creates a new ScriptManager.

Parameters
contextContext in which scripts will run
scriptContentsContents of the script to run
fileNameStringFilename for the script
Returns
ScriptManagerPointer

The documentation for this class was generated from the following files: