From ec8b420abc3cd216a7696804aa1bdc622983734a Mon Sep 17 00:00:00 2001 From: vyordan Date: Tue, 2 Jun 2026 15:06:50 -0600 Subject: [PATCH] Move Script* classes to Script namespace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rename ScriptEngine, ScriptContext, ScriptInterface, ScriptRequest to Script::Engine, Script::Context, Script::Interface, Script::Request - Remove 'Script' prefix from filenames: ScriptContext.* → Context.* ScriptInterface.* → Interface.* ScriptRequest.* → Request.* ScriptEngine.* → Engine.* ScriptConversions.* → Conversions.* ScriptExceptions.* → Exceptions.* ScriptForward.* → ForwardDeclarations.* ScriptStats.* → Stats.* - Update all includes, forward declarations, and friend classes - Use namespace Script { ... } in .cpp definitions to avoid repetitive Script:: prefix (keeping global callbacks outside) - Rename internal implementation structs: ScriptInterface_impl → Interface_impl ScriptFunction → Function - Update copyright year to 2026 in all touched files - Suppress pre-existing cppcheck warnings (uninitvar, nullPointer, unknown macro) by adding them to suppressions-list.txt (these are not caused by this refactor) Fixes #7516 --- source/dapinterface/DapInterface.cpp | 36 ++-- source/dapinterface/DapInterface.h | 10 +- source/dapinterface/tests/test_DapInterface.h | 4 +- source/graphics/MapGenerator.cpp | 36 ++-- source/graphics/MapGenerator.h | 6 +- source/graphics/MapReader.cpp | 32 +-- source/graphics/MapReader.h | 12 +- source/graphics/MapWriter.cpp | 2 +- source/graphics/ObjectManager.cpp | 4 +- source/graphics/ShaderDefines.cpp | 2 +- .../scripting/JSInterface_GameView.cpp | 40 ++-- .../graphics/scripting/JSInterface_GameView.h | 6 +- source/graphics/tests/test_LOSTexture.h | 2 +- source/graphics/tests/test_MapGenerator.h | 6 +- source/graphics/tests/test_Model.h | 2 +- source/gui/CGUI.cpp | 30 +-- source/gui/CGUI.h | 20 +- source/gui/CGUISetting.cpp | 14 +- source/gui/CGUISetting.h | 12 +- source/gui/GUIManager.cpp | 44 ++--- source/gui/GUIManager.h | 20 +- source/gui/ObjectBases/IGUIObject.cpp | 12 +- source/gui/ObjectTypes/CHotkeyPicker.cpp | 10 +- source/gui/ObjectTypes/CMiniMap.cpp | 6 +- source/gui/Scripting/GuiScriptConversions.cpp | 64 +++--- source/gui/Scripting/JSInterface_CGUISize.cpp | 26 +-- source/gui/Scripting/JSInterface_CGUISize.h | 6 +- .../gui/Scripting/JSInterface_GUIManager.cpp | 24 +-- source/gui/Scripting/JSInterface_GUIManager.h | 6 +- source/gui/Scripting/JSInterface_GUIProxy.cpp | 16 +- source/gui/Scripting/JSInterface_GUIProxy.h | 16 +- .../gui/Scripting/JSInterface_GUIProxy_impl.h | 30 +-- source/gui/Scripting/JSInterface_GUISize.cpp | 16 +- source/gui/Scripting/JSInterface_GUISize.h | 6 +- source/gui/Scripting/ScriptFunctions.cpp | 8 +- source/gui/Scripting/ScriptFunctions.h | 6 +- source/gui/SettingTypes/CGUIHotkey.cpp | 6 +- source/gui/SettingTypes/CGUIHotkey.h | 4 +- source/gui/SettingTypes/MouseEventMask.cpp | 6 +- source/gui/SettingTypes/MouseEventMask.h | 6 +- source/gui/tests/test_CGUIText.h | 4 +- source/gui/tests/test_GUISetting.h | 6 +- source/gui/tests/test_GuiManager.h | 42 ++-- source/i18n/L10n.cpp | 4 +- source/i18n/scripting/JSInterface_L10n.cpp | 16 +- source/i18n/scripting/JSInterface_L10n.h | 8 +- source/lib/self_test.h | 6 +- source/lobby/XmppClient.cpp | 44 ++--- source/lobby/XmppClient.h | 22 +-- .../scripting/GlooxScriptConversions.cpp | 18 +- source/lobby/scripting/JSInterface_Lobby.cpp | 30 +-- source/lobby/scripting/JSInterface_Lobby.h | 6 +- source/main.cpp | 20 +- source/network/NetClient.cpp | 34 ++-- source/network/NetClient.h | 21 +- source/network/NetMessage.cpp | 4 +- source/network/NetMessage.h | 18 +- source/network/NetMessageSim.cpp | 32 +-- source/network/NetServer.cpp | 26 +-- source/network/NetServer.h | 8 +- .../network/scripting/JSInterface_Network.cpp | 60 +++--- .../network/scripting/JSInterface_Network.h | 6 +- source/network/tests/test_Net.h | 12 +- source/network/tests/test_NetMessage.h | 8 +- source/ps/CConsole.cpp | 8 +- source/ps/Game.cpp | 20 +- source/ps/GameSetup/CmdLineArgs.cpp | 8 +- source/ps/GameSetup/GameSetup.cpp | 48 ++--- source/ps/GameSetup/GameSetup.h | 8 +- source/ps/GameSetup/HWDetect.cpp | 24 +-- source/ps/Input.cpp | 4 +- source/ps/Mod.cpp | 14 +- source/ps/Mod.h | 6 +- source/ps/ModInstaller.cpp | 14 +- source/ps/ModInstaller.h | 6 +- source/ps/ModIo.cpp | 22 +-- source/ps/ModIo.h | 14 +- source/ps/ProfileViewer.cpp | 16 +- source/ps/Replay.cpp | 30 +-- source/ps/Replay.h | 6 +- source/ps/SavedGame.cpp | 26 +-- source/ps/SavedGame.h | 10 +- source/ps/VideoMode.cpp | 2 +- source/ps/VisualReplay.cpp | 34 ++-- source/ps/VisualReplay.h | 28 +-- source/ps/World.cpp | 6 +- source/ps/World.h | 8 +- source/ps/XMB/XMBStorage.cpp | 16 +- source/ps/XMB/XMBStorage.h | 6 +- source/ps/XMB/tests/test_XMBData.h | 12 +- source/ps/scripting/JSInterface_ConfigDB.cpp | 30 +-- source/ps/scripting/JSInterface_ConfigDB.h | 6 +- source/ps/scripting/JSInterface_Console.cpp | 10 +- source/ps/scripting/JSInterface_Console.h | 6 +- source/ps/scripting/JSInterface_Debug.cpp | 18 +- source/ps/scripting/JSInterface_Debug.h | 6 +- source/ps/scripting/JSInterface_Game.cpp | 42 ++-- source/ps/scripting/JSInterface_Game.h | 6 +- source/ps/scripting/JSInterface_Hotkey.cpp | 30 +-- source/ps/scripting/JSInterface_Hotkey.h | 6 +- source/ps/scripting/JSInterface_Main.cpp | 32 +-- source/ps/scripting/JSInterface_Main.h | 6 +- source/ps/scripting/JSInterface_Mod.cpp | 40 ++-- source/ps/scripting/JSInterface_Mod.h | 6 +- source/ps/scripting/JSInterface_ModIo.cpp | 24 +-- source/ps/scripting/JSInterface_ModIo.h | 6 +- source/ps/scripting/JSInterface_SavedGame.cpp | 40 ++-- source/ps/scripting/JSInterface_SavedGame.h | 6 +- .../ps/scripting/JSInterface_UserReport.cpp | 14 +- source/ps/scripting/JSInterface_UserReport.h | 6 +- source/ps/scripting/JSInterface_VFS.cpp | 58 +++--- source/ps/scripting/JSInterface_VFS.h | 10 +- .../ps/scripting/JSInterface_VisualReplay.cpp | 20 +- .../ps/scripting/JSInterface_VisualReplay.h | 6 +- source/ps/tests/test_Mod.h | 14 +- source/ps/tests/test_ModIo.h | 8 +- source/renderer/backend/IDevice.h | 4 +- source/renderer/backend/dummy/Device.cpp | 2 +- source/renderer/backend/dummy/Device.h | 2 +- source/renderer/backend/gl/Device.cpp | 2 +- source/renderer/backend/gl/Device.h | 2 +- source/renderer/backend/vulkan/Device.cpp | 4 +- source/renderer/backend/vulkan/Device.h | 2 +- .../backend/vulkan/DeviceSelection.cpp | 4 +- .../renderer/backend/vulkan/DeviceSelection.h | 6 +- .../scripting/JSInterface_Renderer.cpp | 18 +- .../renderer/scripting/JSInterface_Renderer.h | 6 +- source/rlinterface/RLInterface.cpp | 20 +- .../{ScriptContext.cpp => Context.cpp} | 43 +++-- .../{ScriptContext.h => Context.h} | 27 +-- ...{ScriptConversions.cpp => Conversions.cpp} | 87 +++++---- .../{ScriptConversions.h => Conversions.h} | 58 +++--- .../{ScriptEngine.h => Engine.h} | 19 +- .../{ScriptExceptions.cpp => Exceptions.cpp} | 24 ++- .../{ScriptExceptions.h => Exceptions.h} | 21 +- ...{ScriptForward.h => ForwardDeclarations.h} | 11 +- source/scriptinterface/FunctionWrapper.h | 114 +++++------ .../{ScriptInterface.cpp => Interface.cpp} | 182 +++++++++--------- .../{ScriptInterface.h => Interface.h} | 101 +++++----- source/scriptinterface/JSON.cpp | 20 +- source/scriptinterface/JSON.h | 12 +- source/scriptinterface/ModuleLoader.cpp | 40 ++-- source/scriptinterface/ModuleLoader.h | 24 +-- source/scriptinterface/Object.h | 36 ++-- source/scriptinterface/Promises.cpp | 12 +- source/scriptinterface/Promises.h | 6 +- .../{ScriptRequest.h => Request.h} | 52 ++--- .../{ScriptStats.cpp => Stats.cpp} | 17 +- .../{ScriptStats.h => Stats.h} | 22 ++- source/scriptinterface/StructuredClone.cpp | 24 +-- source/scriptinterface/StructuredClone.h | 18 +- .../tests/test_FunctionWrapper.h | 78 ++++---- source/scriptinterface/tests/test_Module.h | 178 ++++++++--------- source/scriptinterface/tests/test_Promises.h | 16 +- .../tests/test_ScriptConversions.h | 38 ++-- .../tests/test_ScriptInterface.h | 76 ++++---- source/simulation2/MessageTypes.h | 8 +- source/simulation2/Simulation2.cpp | 54 +++--- source/simulation2/Simulation2.h | 8 +- .../simulation2/components/CCmpAIManager.cpp | 88 ++++----- .../components/CCmpCommandQueue.cpp | 22 +-- .../components/CCmpSoundManager.cpp | 4 +- .../simulation2/components/ICmpAIManager.cpp | 16 +- source/simulation2/components/ICmpAIManager.h | 6 +- .../simulation2/components/ICmpFootprint.cpp | 8 +- .../components/tests/test_CinemaManager.h | 2 +- .../components/tests/test_CommandQueue.h | 8 +- .../tests/test_ObstructionManager.h | 2 +- .../components/tests/test_Pathfinder.h | 10 +- .../components/tests/test_Position.h | 4 +- .../components/tests/test_RangeManager.h | 4 +- .../components/tests/test_TerritoryManager.h | 2 +- .../components/tests/test_scripts.h | 34 ++-- source/simulation2/docs/SimulationDocs.h | 16 +- .../scripting/EngineScriptConversions.cpp | 48 ++--- .../scripting/JSInterface_Simulation.cpp | 44 ++--- .../scripting/JSInterface_Simulation.h | 6 +- .../scripting/MessageTypeConversions.cpp | 130 ++++++------- .../simulation2/scripting/ScriptComponent.cpp | 24 +-- .../simulation2/scripting/ScriptComponent.h | 22 +-- .../serialization/BinarySerializer.cpp | 20 +- .../serialization/BinarySerializer.h | 20 +- .../serialization/DebugSerializer.cpp | 10 +- .../serialization/DebugSerializer.h | 8 +- .../serialization/HashSerializer.cpp | 6 +- .../serialization/HashSerializer.h | 6 +- .../serialization/SerializedScriptTypes.h | 4 +- .../serialization/StdDeserializer.cpp | 22 +-- .../serialization/StdDeserializer.h | 8 +- .../serialization/StdSerializer.cpp | 6 +- .../simulation2/serialization/StdSerializer.h | 6 +- source/simulation2/system/Component.h | 4 +- .../simulation2/system/ComponentManager.cpp | 56 +++--- source/simulation2/system/ComponentManager.h | 12 +- source/simulation2/system/ComponentTest.h | 10 +- source/simulation2/system/IComponent.h | 8 +- source/simulation2/system/Interface.h | 6 +- source/simulation2/system/InterfaceScripted.h | 26 +-- source/simulation2/system/Message.h | 10 +- source/simulation2/system/ParamNode.cpp | 10 +- source/simulation2/system/ParamNode.h | 8 +- .../simulation2/system/ReplayTurnManager.cpp | 12 +- source/simulation2/system/SimContext.cpp | 4 +- source/simulation2/system/SimContext.h | 6 +- source/simulation2/system/TurnManager.cpp | 8 +- .../tests/test_CmpTemplateManager.h | 8 +- .../simulation2/tests/test_ComponentManager.h | 4 +- .../tests/test_SerializeTemplates.h | 12 +- source/simulation2/tests/test_Serializer.h | 38 ++-- source/simulation2/tests/test_Simulation2.h | 2 +- .../scripting/JSInterface_Sound.cpp | 32 +-- .../scripting/JSInterface_Sound.h | 6 +- source/soundmanager/scripting/SoundGroup.cpp | 2 +- source/test_setup.cpp | 22 +-- .../tools/atlas/GameInterface/ActorViewer.cpp | 2 +- .../Handlers/GraphicsSetupHandlers.cpp | 6 +- .../GameInterface/Handlers/MapHandlers.cpp | 16 +- .../GameInterface/Handlers/MiscHandlers.cpp | 2 +- .../Handlers/TerrainHandlers.cpp | 4 +- .../tools/lint/cppcheck/suppressions-list.txt | 6 +- 220 files changed, 2224 insertions(+), 2153 deletions(-) rename source/scriptinterface/{ScriptContext.cpp => Context.cpp} (88%) rename source/scriptinterface/{ScriptContext.h => Context.h} (87%) rename source/scriptinterface/{ScriptConversions.cpp => Conversions.cpp} (59%) rename source/scriptinterface/{ScriptConversions.h => Conversions.h} (66%) rename source/scriptinterface/{ScriptEngine.h => Engine.h} (89%) rename source/scriptinterface/{ScriptExceptions.cpp => Exceptions.cpp} (84%) rename source/scriptinterface/{ScriptExceptions.h => Exceptions.h} (81%) rename source/scriptinterface/{ScriptForward.h => ForwardDeclarations.h} (89%) rename source/scriptinterface/{ScriptInterface.cpp => Interface.cpp} (77%) rename source/scriptinterface/{ScriptInterface.h => Interface.h} (76%) rename source/scriptinterface/{ScriptRequest.h => Request.h} (62%) rename source/scriptinterface/{ScriptStats.cpp => Stats.cpp} (87%) rename source/scriptinterface/{ScriptStats.h => Stats.h} (76%) diff --git a/source/dapinterface/DapInterface.cpp b/source/dapinterface/DapInterface.cpp index a91f647a77..77a6cbf286 100644 --- a/source/dapinterface/DapInterface.cpp +++ b/source/dapinterface/DapInterface.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -25,14 +25,14 @@ #include "lib/sysdep/os.h" #include "ps/CLogger.h" #include "ps/Filesystem.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Exceptions.h" #include "scriptinterface/FunctionWrapper.h" +#include "scriptinterface/Interface.h" #include "scriptinterface/JSON.h" #include "scriptinterface/ModuleLoader.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -286,7 +286,7 @@ namespace DAP bool m_Running{true}; }; - Interface::Interface(const std::string serverAddress, int port, ScriptContext& scriptContext) + Interface::Interface(const std::string serverAddress, int port, Script::Context& scriptContext) : m_SocketImpl{std::make_unique(this)}, m_ModuleValue{scriptContext.GetGeneralJSContext()} { @@ -299,22 +299,22 @@ namespace DAP if (!VfsFileExists(fntPath)) throw DapInterfaceNoJSDebuggerException{ fmt::format("DAP entry script not found at {}", fntPath.string8().c_str())}; - m_ScriptInterface = std::make_unique("Engine", "Debugger", scriptContext, [](const VfsPath& path) { + m_ScriptInterface = std::make_unique("Engine", "Debugger", scriptContext, [](const VfsPath& path) { return path.string8().find("tools/dap/") == 0; }); m_ScriptInterface->SetCallbackData(this); - ScriptRequest rq(m_ScriptInterface.get()); + Script::Request rq(m_ScriptInterface.get()); if (!JS_DefineDebuggerObject(rq.cx, rq.glob)) { - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); throw DapInterfaceNoJSDebuggerException{"Failed to define debugger object"}; } // Register methods. - constexpr ScriptFunction::ObjectGetter Getter{&ScriptInterface::ObjectFromCBData}; - ScriptFunction::Register<&DAP::Interface::WaitForMessage, Getter>(rq, "WaitForMessage"); - ScriptFunction::Register<&DAP::Interface::EndWaitingForMessage, Getter>(rq, "EndWaitingForMessage"); + constexpr Script::Function::ObjectGetter Getter{&Script::Interface::ObjectFromCBData}; + Script::Function::Register<&DAP::Interface::WaitForMessage, Getter>(rq, "WaitForMessage"); + Script::Function::Register<&DAP::Interface::EndWaitingForMessage, Getter>(rq, "EndWaitingForMessage"); auto result{m_ScriptInterface->GetModuleLoader().LoadModule(rq, fntPath)}; @@ -336,12 +336,12 @@ namespace DAP bool Interface::isJSHandlerDefined() { - ScriptRequest rq{m_ScriptInterface.get()}; + Script::Request rq{m_ScriptInterface.get()}; JS::RootedValue handler{rq.cx}; if (!Script::GetProperty(rq, m_ModuleValue, "handleMessage", &handler)) { - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); return false; } @@ -365,7 +365,7 @@ namespace DAP std::string Interface::OnMessage(const std::string& message) { - ScriptRequest rq{m_ScriptInterface.get()}; + Script::Request rq{m_ScriptInterface.get()}; JS::RootedValue msg{rq.cx}; if (!Script::ParseJSON(rq, message, &msg)) @@ -375,7 +375,7 @@ namespace DAP } JS::RootedValue rval{rq.cx}; - if (!ScriptFunction::Call(rq, m_ModuleValue, "handleMessage", &rval, msg)) + if (!Script::Function::Call(rq, m_ModuleValue, "handleMessage", &rval, msg)) { LOGERROR("Failed to call message handler"); return ""; @@ -386,13 +386,13 @@ namespace DAP void Interface::SendEventToClient() { - ScriptRequest rq{m_ScriptInterface.get()}; + Script::Request rq{m_ScriptInterface.get()}; JS::RootedValue global{rq.cx, rq.globalValue()}; JS::RootedValue rval{rq.cx}; while (true) { - if (!ScriptFunction::Call(rq, m_ModuleValue, "sendEventToClient", &rval)) + if (!Script::Function::Call(rq, m_ModuleValue, "sendEventToClient", &rval)) { LOGERROR("Failed to call sendEventToClient"); return; diff --git a/source/dapinterface/DapInterface.h b/source/dapinterface/DapInterface.h index b973eb6b64..d467979151 100644 --- a/source/dapinterface/DapInterface.h +++ b/source/dapinterface/DapInterface.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -29,8 +29,8 @@ #include #include -class ScriptContext; -class ScriptInterface; +namespace Script { class Context; } +namespace Script { class Interface; } namespace DAP { @@ -52,7 +52,7 @@ namespace DAP class Interface { public: - Interface(const std::string server_address, int port, ScriptContext& scriptContext); + Interface(const std::string server_address, int port, Script::Context& scriptContext); ~Interface(); NONCOPYABLE(Interface); @@ -70,7 +70,7 @@ namespace DAP void SendEventToClient(); std::unique_ptr m_SocketImpl; - std::unique_ptr m_ScriptInterface; + std::unique_ptr m_ScriptInterface; std::string m_DapRequest; std::string m_DapResponse; diff --git a/source/dapinterface/tests/test_DapInterface.h b/source/dapinterface/tests/test_DapInterface.h index 3e92c182d8..363f21aa8e 100644 --- a/source/dapinterface/tests/test_DapInterface.h +++ b/source/dapinterface/tests/test_DapInterface.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,7 +22,7 @@ #include "lib/path.h" #include "ps/CLogger.h" #include "ps/Filesystem.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include #include diff --git a/source/graphics/MapGenerator.cpp b/source/graphics/MapGenerator.cpp index 4e7099f49e..b776df5e9d 100644 --- a/source/graphics/MapGenerator.cpp +++ b/source/graphics/MapGenerator.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -41,10 +41,10 @@ #include "scriptinterface/JSON.h" #include "scriptinterface/ModuleLoader.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/helpers/MapEdgeTiles.h" #include "simulation2/system/Component.h" @@ -78,7 +78,7 @@ class CMapGenerationCallbacks public: // Only the constructor and the destructor are called by C++. - CMapGenerationCallbacks(const StopToken stopToken, ScriptInterface& scriptInterface, + CMapGenerationCallbacks(const StopToken stopToken, Script::Interface& scriptInterface, const u16 flags) : m_StopToken{stopToken}, m_ScriptInterface{scriptInterface} @@ -92,8 +92,8 @@ public: // Set initial seed, callback data. // Expose functions, globals and classes relevant to the map scripts. #define REGISTER_MAPGEN_FUNC(func) \ - ScriptFunction::Register<&CMapGenerationCallbacks::func, \ - ScriptInterface::ObjectFromCBData>(rq, #func, flags); + Script::Function::Register<&CMapGenerationCallbacks::func, \ + Script::Interface::ObjectFromCBData>(rq, #func, flags); // VFS JSI_VFS::RegisterScriptFunctions_ReadOnlySimulationMaps(m_ScriptInterface, flags); @@ -102,7 +102,7 @@ public: m_ScriptInterface.LoadGlobalScripts(); // File loading - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); REGISTER_MAPGEN_FUNC(LoadLibrary); REGISTER_MAPGEN_FUNC(LoadHeightmapImage); REGISTER_MAPGEN_FUNC(LoadMapTerrain); @@ -200,7 +200,7 @@ private: return JS::UndefinedValue(); } - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedValue returnValue(rq.cx); Script::ToJSVal(rq, &returnValue, heightmap); return returnValue; @@ -213,7 +213,7 @@ private: */ JS::Value LoadMapTerrain(const VfsPath& filename) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); if (!VfsFileExists(filename)) { @@ -332,7 +332,7 @@ private: /** * Provides the script context. */ - ScriptInterface& m_ScriptInterface; + Script::Interface& m_ScriptInterface; /** * Currently loaded script librarynames. @@ -347,15 +347,15 @@ private: bool MapGenerationInterruptCallback(JSContext* cx) { - return !ScriptInterface::ObjectFromCBData( - ScriptInterface::CmptPrivate::GetScriptInterface(cx))->m_StopToken.IsStopRequested(); + return !Script::Interface::ObjectFromCBData( + Script::Interface::CmptPrivate::GetScriptInterface(cx))->m_StopToken.IsStopRequested(); } } // anonymous namespace Script::StructuredClone RunMapGenerationScript(const StopToken stopToken, std::atomic& progress, - ScriptInterface& scriptInterface, const VfsPath& script, const std::string& settings, const u16 flags) + Script::Interface& scriptInterface, const VfsPath& script, const std::string& settings, const u16 flags) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); // Parse settings JS::RootedValue settingsVal(rq.cx); @@ -421,7 +421,7 @@ Script::StructuredClone RunMapGenerationScript(const StopToken stopToken, std::a LOGMESSAGE("Run RMS generator"); JS::RootedValue ns{rq.cx, JS::ObjectValue(*nsAsObject)}; - JS::RootedValue map{rq.cx, ScriptFunction::RunGenerator(rq, ns, GENERATOR_NAME, settingsVal, + JS::RootedValue map{rq.cx, Script::Function::RunGenerator(rq, ns, GENERATOR_NAME, settingsVal, [&](const JS::HandleValue value) { // When the task is started, `progress` is only mutated by this thread. @@ -440,6 +440,6 @@ Script::StructuredClone RunMapGenerationScript(const StopToken stopToken, std::a })}; JS::RootedValue exportedMap{rq.cx}; - const bool exportSuccess{ScriptFunction::Call(rq, map, "MakeExportable", &exportedMap)}; + const bool exportSuccess{Script::Function::Call(rq, map, "MakeExportable", &exportedMap)}; return Script::WriteStructuredClone(rq, exportSuccess ? exportedMap : map); } diff --git a/source/graphics/MapGenerator.h b/source/graphics/MapGenerator.h index 06354f3f92..5419b350c9 100644 --- a/source/graphics/MapGenerator.h +++ b/source/graphics/MapGenerator.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -27,8 +27,8 @@ #include #include -class ScriptInterface; class StopToken; +namespace Script { class Interface; } constexpr std::wstring_view RANDOM_MAP_PREFIX{L"maps/random/"}; @@ -48,7 +48,7 @@ constexpr std::wstring_view RANDOM_MAP_PREFIX{L"maps/random/"}; * https://gitea.wildfiregames.com/0ad/0ad/wiki/Random_Map_Generator_Internals#Dataformat */ Script::StructuredClone RunMapGenerationScript(const StopToken stopToken, std::atomic& progress, - ScriptInterface& scriptInterface, const VfsPath& script, const std::string& settings, + Script::Interface& scriptInterface, const VfsPath& script, const std::string& settings, const u16 flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); #endif //INCLUDED_MAPGENERATOR diff --git a/source/graphics/MapReader.cpp b/source/graphics/MapReader.cpp index 8e73c1ca04..53027b393a 100644 --- a/source/graphics/MapReader.cpp +++ b/source/graphics/MapReader.cpp @@ -55,9 +55,9 @@ #include "renderer/WaterManager.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpCinemaManager.h" @@ -98,7 +98,7 @@ constexpr int MAP_GENERATION_CONTEXT_SIZE{96 * MiB}; CMapReader::CMapReader() = default; // LoadMap: try to load the map from given file; reinitialise the scene to new data if successful -void CMapReader::LoadMap(const VfsPath& pathname, const ScriptContext& cx, JS::HandleValue settings, CTerrain *pTerrain_, +void CMapReader::LoadMap(const VfsPath& pathname, const Script::Context& cx, JS::HandleValue settings, CTerrain *pTerrain_, WaterManager* pWaterMan_, SkyManager* pSkyMan_, CLightEnv *pLightEnv_, CGameView *pGameView_, CCinemaManager* pCinema_, CTriggerManager* pTrigMan_, CPostprocManager* pPostproc_, CSimulation2 *pSimulation2_, const CSimContext* pSimContext_, int playerID_, bool skipEntities) @@ -207,7 +207,7 @@ void CMapReader::LoadMap(const VfsPath& pathname, const ScriptContext& cx, JS:: } // LoadRandomMap: try to load the map data; reinitialise the scene to new data if successful -void CMapReader::LoadRandomMap(const CStrW& scriptFile, const ScriptContext& cx, JS::HandleValue settings, CTerrain *pTerrain_, +void CMapReader::LoadRandomMap(const CStrW& scriptFile, const Script::Context& cx, JS::HandleValue settings, CTerrain *pTerrain_, WaterManager* pWaterMan_, SkyManager* pSkyMan_, CLightEnv *pLightEnv_, CGameView *pGameView_, CCinemaManager* pCinema_, CTriggerManager* pTrigMan_, CPostprocManager* pPostproc_, CSimulation2 *pSimulation2_, int playerID_) @@ -449,9 +449,9 @@ PSRETURN CMapSummaryReader::LoadMap(const VfsPath& pathname) return PSRETURN_OK; } -void CMapSummaryReader::GetMapSettings(const ScriptInterface& scriptInterface, JS::MutableHandleValue ret) +void CMapSummaryReader::GetMapSettings(const Script::Interface& scriptInterface, JS::MutableHandleValue ret) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); Script::CreateObject(rq, ret); @@ -1312,7 +1312,7 @@ PS::Loader::Task CMapReader::RunMapGeneration(const CStrW& scriptFile) // The settings are stringified to pass them to the task. Future task = {g_TaskManager, - [&progress, scriptFile, settings = Script::StringifyJSON(ScriptRequest{ + [&progress, scriptFile, settings = Script::StringifyJSON(Script::Request{ pSimulation2->GetScriptInterface()}, &m_ScriptSettings)](const StopToken stopToken) { PROFILE2("Map Generation"); @@ -1320,8 +1320,8 @@ PS::Loader::Task CMapReader::RunMapGeneration(const CStrW& scriptFile) const VfsPath scriptPath{scriptFile.empty() ? L"" : static_cast(RANDOM_MAP_PREFIX) + scriptFile}; - ScriptContext mapgenContext{MAP_GENERATION_CONTEXT_SIZE}; - ScriptInterface mapgenInterface{"Engine", "MapGenerator", mapgenContext, + Script::Context mapgenContext{MAP_GENERATION_CONTEXT_SIZE}; + Script::Interface mapgenInterface{"Engine", "MapGenerator", mapgenContext, [](const VfsPath& path){ // Only allow to load modules inside the maps folder. return path.string().find(RANDOM_MAP_PREFIX) == 0; @@ -1347,7 +1347,7 @@ PS::Loader::Task CMapReader::RunMapGeneration(const CStrW& scriptFile) ThrowMapGenerationError(); // Parse data into simulation context - ScriptRequest rq(pSimulation2->GetScriptInterface()); + Script::Request rq(pSimulation2->GetScriptInterface()); JS::RootedValue data{rq.cx}; Script::ReadStructuredClone(rq, results, &data); @@ -1363,7 +1363,7 @@ PS::Loader::Task CMapReader::RunMapGeneration(const CStrW& scriptFile) int CMapReader::ParseTerrain() { PROFILE2("ParseTerrain"); - ScriptRequest rq(pSimulation2->GetScriptInterface()); + Script::Request rq(pSimulation2->GetScriptInterface()); // parse terrain from map data // an error here should stop the loading process @@ -1436,7 +1436,7 @@ int CMapReader::ParseTerrain() struct ParseEntitiesState { - ScriptRequest rq; + Script::Request rq; CmpPtr cmpPlayerManager; std::vector entities; size_t currentEntityIndex{0}; @@ -1450,7 +1450,7 @@ PS::Loader::Task CMapReader::ParseEntities() PROFILE2("ParseEntities"); CSimulation2& sim{*pSimulation2}; - ScriptRequest rq{sim.GetScriptInterface()}; + Script::Request rq{sim.GetScriptInterface()}; CmpPtr cmpPlayerManager{sim, SYSTEM_ENTITY}; std::vector entities; @@ -1509,7 +1509,7 @@ PS::Loader::Task CMapReader::ParseEntities() int CMapReader::ParseEnvironment() { // parse environment settings from map data - ScriptRequest rq(pSimulation2->GetScriptInterface()); + Script::Request rq(pSimulation2->GetScriptInterface()); const auto getEnvironmentProperty = [&](JS::HandleValue val, const char* prop, auto&& out) { @@ -1603,7 +1603,7 @@ int CMapReader::ParseEnvironment() int CMapReader::ParseCamera() { - ScriptRequest rq(pSimulation2->GetScriptInterface()); + Script::Request rq(pSimulation2->GetScriptInterface()); // parse camera settings from map data // defaults if we don't find player starting camera diff --git a/source/graphics/MapReader.h b/source/graphics/MapReader.h index e7ef550653..ae8769c162 100644 --- a/source/graphics/MapReader.h +++ b/source/graphics/MapReader.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -47,10 +47,10 @@ class CTerrain; class CTerrainTextureEntry; class CTriggerManager; class CXMLReader; -class ScriptContext; -class ScriptInterface; class SkyManager; class WaterManager; +namespace Script { class Context; } +namespace Script { class Interface; } class CMapReader : public CMapIO { @@ -66,11 +66,11 @@ public: ~CMapReader(); // LoadMap: try to load the map from given file; reinitialise the scene to new data if successful - void LoadMap(const VfsPath& pathname, const ScriptContext& cx, JS::HandleValue settings, CTerrain*, WaterManager*, SkyManager*, CLightEnv*, CGameView*, + void LoadMap(const VfsPath& pathname, const Script::Context& cx, JS::HandleValue settings, CTerrain*, WaterManager*, SkyManager*, CLightEnv*, CGameView*, CCinemaManager*, CTriggerManager*, CPostprocManager* pPostproc, CSimulation2*, const CSimContext*, int playerID, bool skipEntities); - void LoadRandomMap(const CStrW& scriptFile, const ScriptContext& cx, JS::HandleValue settings, CTerrain*, WaterManager*, SkyManager*, CLightEnv*, CGameView*, CCinemaManager*, CTriggerManager*, CPostprocManager* pPostproc_, CSimulation2*, int playerID); + void LoadRandomMap(const CStrW& scriptFile, const Script::Context& cx, JS::HandleValue settings, CTerrain*, WaterManager*, SkyManager*, CLightEnv*, CGameView*, CCinemaManager*, CTriggerManager*, CPostprocManager* pPostproc_, CSimulation2*, int playerID); private: // Load script settings for use by scripts @@ -176,7 +176,7 @@ public: * } * @endcode */ - void GetMapSettings(const ScriptInterface& scriptInterface, JS::MutableHandleValue); + void GetMapSettings(const Script::Interface& scriptInterface, JS::MutableHandleValue); private: CStr m_ScriptSettings; diff --git a/source/graphics/MapWriter.cpp b/source/graphics/MapWriter.cpp index aa1d74c1f7..7afd5ae786 100644 --- a/source/graphics/MapWriter.cpp +++ b/source/graphics/MapWriter.cpp @@ -44,7 +44,7 @@ #include "renderer/PostprocManager.h" #include "renderer/SkyManager.h" #include "renderer/WaterManager.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpCinemaManager.h" #include "simulation2/components/ICmpGarrisonHolder.h" diff --git a/source/graphics/ObjectManager.cpp b/source/graphics/ObjectManager.cpp index 9e5e5c9055..d0981360d8 100644 --- a/source/graphics/ObjectManager.cpp +++ b/source/graphics/ObjectManager.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -29,7 +29,7 @@ #include "ps/Filesystem.h" #include "ps/Profiler2.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpTerrain.h" #include "simulation2/components/ICmpVisual.h" diff --git a/source/graphics/ShaderDefines.cpp b/source/graphics/ShaderDefines.cpp index 20fc45a3f9..d55a29f341 100644 --- a/source/graphics/ShaderDefines.cpp +++ b/source/graphics/ShaderDefines.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify diff --git a/source/graphics/scripting/JSInterface_GameView.cpp b/source/graphics/scripting/JSInterface_GameView.cpp index 3a2d9e6cfe..c2c8232535 100644 --- a/source/graphics/scripting/JSInterface_GameView.cpp +++ b/source/graphics/scripting/JSInterface_GameView.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -30,7 +30,7 @@ #include "ps/World.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/helpers/Position.h" #include "simulation2/system/Entity.h" @@ -69,10 +69,10 @@ IMPLEMENT_BOOLEAN_SCRIPT_SETTING(ConstrainCamera); #define REGISTER_BOOLEAN_SCRIPT_SETTING(NAME) \ - ScriptFunction::Register<&Get##NAME##Enabled>(rq, "GameView_Get" #NAME "Enabled"); \ - ScriptFunction::Register<&Set##NAME##Enabled>(rq, "GameView_Set" #NAME "Enabled"); + Script::Function::Register<&Get##NAME##Enabled>(rq, "GameView_Get" #NAME "Enabled"); \ + Script::Function::Register<&Set##NAME##Enabled>(rq, "GameView_Set" #NAME "Enabled"); -void RegisterScriptFunctions_Settings(const ScriptRequest& rq) +void RegisterScriptFunctions_Settings(const Script::Request& rq) { REGISTER_BOOLEAN_SCRIPT_SETTING(Culling); REGISTER_BOOLEAN_SCRIPT_SETTING(LockCullCamera); @@ -81,7 +81,7 @@ void RegisterScriptFunctions_Settings(const ScriptRequest& rq) #undef REGISTER_BOOLEAN_SCRIPT_SETTING -JS::Value GetCameraRotation(const ScriptRequest& rq) +JS::Value GetCameraRotation(const Script::Request& rq) { if (!g_Game || !g_Game->GetView()) return JS::UndefinedValue(); @@ -99,7 +99,7 @@ JS::Value GetCameraZoom() return JS::NumberValue(g_Game->GetView()->GetCameraZoom()); } -JS::Value GetCameraPivot(const ScriptRequest& rq) +JS::Value GetCameraPivot(const Script::Request& rq) { if (!g_Game || !g_Game->GetView()) return JS::UndefinedValue(); @@ -110,7 +110,7 @@ JS::Value GetCameraPivot(const ScriptRequest& rq) return pivotValue; } -JS::Value GetCameraPosition(const ScriptRequest& rq) +JS::Value GetCameraPosition(const Script::Request& rq) { if (!g_Game || !g_Game->GetView()) return JS::UndefinedValue(); @@ -200,20 +200,20 @@ CFixedVector3D GetTerrainAtScreenPoint(int x, int y) return CFixedVector3D(fixed::FromFloat(pos.X), fixed::FromFloat(pos.Y), fixed::FromFloat(pos.Z)); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { RegisterScriptFunctions_Settings(rq); - ScriptFunction::Register<&GetCameraRotation>(rq, "GetCameraRotation"); - ScriptFunction::Register<&GetCameraZoom>(rq, "GetCameraZoom"); - ScriptFunction::Register<&GetCameraPivot>(rq, "GetCameraPivot"); - ScriptFunction::Register<&GetCameraPosition>(rq, "GetCameraPosition"); - ScriptFunction::Register<&CameraMoveTo>(rq, "CameraMoveTo"); - ScriptFunction::Register<&SetCameraTarget>(rq, "SetCameraTarget"); - ScriptFunction::Register<&SetCameraData>(rq, "SetCameraData"); - ScriptFunction::Register<&CameraFollow>(rq, "CameraFollow"); - ScriptFunction::Register<&CameraFollowFPS>(rq, "CameraFollowFPS"); - ScriptFunction::Register<&GetFollowedEntity>(rq, "GetFollowedEntity"); - ScriptFunction::Register<&GetTerrainAtScreenPoint>(rq, "GetTerrainAtScreenPoint"); + Script::Function::Register<&GetCameraRotation>(rq, "GetCameraRotation"); + Script::Function::Register<&GetCameraZoom>(rq, "GetCameraZoom"); + Script::Function::Register<&GetCameraPivot>(rq, "GetCameraPivot"); + Script::Function::Register<&GetCameraPosition>(rq, "GetCameraPosition"); + Script::Function::Register<&CameraMoveTo>(rq, "CameraMoveTo"); + Script::Function::Register<&SetCameraTarget>(rq, "SetCameraTarget"); + Script::Function::Register<&SetCameraData>(rq, "SetCameraData"); + Script::Function::Register<&CameraFollow>(rq, "CameraFollow"); + Script::Function::Register<&CameraFollowFPS>(rq, "CameraFollowFPS"); + Script::Function::Register<&GetFollowedEntity>(rq, "GetFollowedEntity"); + Script::Function::Register<&GetTerrainAtScreenPoint>(rq, "GetTerrainAtScreenPoint"); } } diff --git a/source/graphics/scripting/JSInterface_GameView.h b/source/graphics/scripting/JSInterface_GameView.h index aba909de11..e0c9925b90 100644 --- a/source/graphics/scripting/JSInterface_GameView.h +++ b/source/graphics/scripting/JSInterface_GameView.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2019 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSINTERFACE_GAMEVIEW #define INCLUDED_JSINTERFACE_GAMEVIEW -class ScriptRequest; +namespace Script { class Request; } namespace JSI_GameView { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSINTERFACE_GAMEVIEW diff --git a/source/graphics/tests/test_LOSTexture.h b/source/graphics/tests/test_LOSTexture.h index a4f5e80f28..446e51a3f9 100644 --- a/source/graphics/tests/test_LOSTexture.h +++ b/source/graphics/tests/test_LOSTexture.h @@ -22,7 +22,7 @@ #include "lib/posix/posix_types.h" #include "lib/timer.h" #include "lib/types.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/Simulation2.h" #include "simulation2/helpers/Grid.h" #include "simulation2/helpers/Los.h" diff --git a/source/graphics/tests/test_MapGenerator.h b/source/graphics/tests/test_MapGenerator.h index 05bf270f51..45b0413f73 100644 --- a/source/graphics/tests/test_MapGenerator.h +++ b/source/graphics/tests/test_MapGenerator.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -27,7 +27,7 @@ #include "ps/Filesystem.h" #include "ps/Future.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "scriptinterface/StructuredClone.h" #include @@ -66,7 +66,7 @@ public: for (const VfsPath& path : paths) { TestLogger logger; - ScriptInterface scriptInterface{"Engine", "MapGenerator", g_ScriptContext, + Script::Interface scriptInterface{"Engine", "MapGenerator", g_ScriptContext, [](const VfsPath& path){ return path.string().find(RANDOM_MAP_PREFIX) == 0; }}; diff --git a/source/graphics/tests/test_Model.h b/source/graphics/tests/test_Model.h index d52e18e732..8c60b8b511 100644 --- a/source/graphics/tests/test_Model.h +++ b/source/graphics/tests/test_Model.h @@ -50,7 +50,7 @@ #include "ps/VideoMode.h" #include "ps/XML/Xeromyces.h" #include "renderer/Renderer.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/Simulation2.h" #include "simulation2/system/Entity.h" diff --git a/source/gui/CGUI.cpp b/source/gui/CGUI.cpp index 9db0243885..ab25c88a2f 100644 --- a/source/gui/CGUI.cpp +++ b/source/gui/CGUI.cpp @@ -52,9 +52,9 @@ #include "renderer/backend/Sampler.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -88,13 +88,13 @@ const CStr CGUI::EventNameMouseLeftRelease = "MouseLeftRelease"; const CStr CGUI::EventNameMouseRightDoubleClick = "MouseRightDoubleClick"; const CStr CGUI::EventNameMouseRightRelease = "MouseRightRelease"; -CGUI::CGUI(ScriptContext& context) +CGUI::CGUI(Script::Context& context) : m_BaseObject(std::make_unique(*this)), m_FocusedObject(nullptr), m_InternalNameNumber(0), m_MouseButtons(0) { - m_ScriptInterface = std::make_shared("Engine", "GUIPage", context, + m_ScriptInterface = std::make_shared("Engine", "GUIPage", context, [](const VfsPath& path){ return path.string8().find("gui/") == 0; }); @@ -124,11 +124,11 @@ Input::Reaction CGUI::HandleEvent(const SDL_Event& ev) { ret = Input::Reaction::HANDLED; - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedObject globalObj(rq.cx, rq.glob); JS::RootedValue result(rq.cx); if (!JS_CallFunctionValue(rq.cx, globalObj, m_GlobalHotkeys[hotkey][eventName], JS::HandleValueArray::empty(), &result)) - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); } std::map >::iterator it = m_HotkeyObjects.find(hotkey); @@ -297,16 +297,16 @@ Input::Reaction CGUI::HandleEvent(const SDL_Event& ev) return ret; } -JS::Value CGUI::GetHotloadData(const ScriptRequest& rq) +JS::Value CGUI::GetHotloadData(const Script::Request& rq) { JS::RootedValue oldNamespace{rq.cx, m_LoadModuleResult.has_value() ? JS::ObjectValue(*m_LoadModuleResult->moduleNamespace) : rq.globalValue()}; JS::RootedValue hotloadDataVal(rq.cx); - ScriptFunction::Call(rq, oldNamespace, "getHotloadData", &hotloadDataVal); + Script::Function::Call(rq, oldNamespace, "getHotloadData", &hotloadDataVal); return hotloadDataVal; } -JSObject* CGUI::CallPageInit(const ScriptRequest& rq, Script::StructuredClone initData, +JSObject* CGUI::CallPageInit(const Script::Request& rq, Script::StructuredClone initData, JS::HandleValue hotloadDataVal, const std::string_view scriptName) { JS::RootedValue initDataVal{rq.cx}; @@ -319,7 +319,7 @@ JSObject* CGUI::CallPageInit(const ScriptRequest& rq, Script::StructuredClone in return nullptr; JS::RootedValue returnValue{rq.cx}; - if (!ScriptFunction::Call(rq, newNamespace, "init", &returnValue, initDataVal, hotloadDataVal)) + if (!Script::Function::Call(rq, newNamespace, "init", &returnValue, initDataVal, hotloadDataVal)) { LOGERROR("GUI page '%s': Failed to call init() function", scriptName); return nullptr; @@ -335,7 +335,7 @@ JSObject* CGUI::CallPageInit(const ScriptRequest& rq, Script::StructuredClone in return returnObject; } -JSObject* CGUI::TickObjects(const ScriptRequest& rq, Script::StructuredClone initData, +JSObject* CGUI::TickObjects(const Script::Request& rq, Script::StructuredClone initData, const std::string_view scriptName) { JS::RootedObject sendingPromise{rq.cx}; @@ -522,7 +522,7 @@ void CGUI::UnsetObjectHotkey(IGUIObject& object, const CStr& hotkeyTag) void CGUI::SetGlobalHotkey(const CStr& hotkeyTag, const CStr& eventName, JS::HandleValue function) { - ScriptRequest rq(*m_ScriptInterface); + Script::Request rq(*m_ScriptInterface); if (hotkeyTag.empty()) throw std::invalid_argument{"Cannot assign a function to an empty hotkey identifier!"}; @@ -991,7 +991,7 @@ void CGUI::Xeromyces_ReadScript(const XMBData& xmb, XMBElement element, std::uno if (m_LoadModuleResult.has_value()) throw std::logic_error{"There can only be one root module per page."}; - const ScriptRequest rq{m_ScriptInterface}; + const Script::Request rq{m_ScriptInterface}; m_LoadModuleResult.emplace(rq, moduleAttribute); } @@ -1367,7 +1367,7 @@ void CGUI::Xeromyces_ReadColor(const XMBData& xmb, XMBElement element) LOGERROR("GUI: Unable to create custom color '%s'. Invalid color syntax.", name.c_str()); } -CGUI::ModuleArtifact::ModuleArtifact(const ScriptRequest& rq, VfsPath filename): +CGUI::ModuleArtifact::ModuleArtifact(const Script::Request& rq, VfsPath filename): result{rq, std::move(filename)}, moduleNamespace{rq.cx} {} diff --git a/source/gui/CGUI.h b/source/gui/CGUI.h index 850c856eaa..11a8b9e76e 100644 --- a/source/gui/CGUI.h +++ b/source/gui/CGUI.h @@ -59,14 +59,14 @@ class CSize2D; class GUIProxyProps; class IGUIObject; class JSObject; -class ScriptContext; -class ScriptInterface; -class ScriptRequest; class XMBData; class XMBElement; namespace JS { class HandleValueArray; } namespace JS { class Value; } namespace js { class BaseProxyHandler; } +namespace Script { class Context; } +namespace Script { class Interface; } +namespace Script { class Request; } struct SGUIImageEffects; union SDL_Event; @@ -86,7 +86,7 @@ private: using ConstructObjectFunction = std::unique_ptr (*)(CGUI&); public: - CGUI(ScriptContext& context); + CGUI(Script::Context& context); ~CGUI(); /** @@ -94,16 +94,16 @@ public: */ void AddObjectTypes(); - JS::Value GetHotloadData(const ScriptRequest& rq); + JS::Value GetHotloadData(const Script::Request& rq); - JSObject* CallPageInit(const ScriptRequest& rq, Script::StructuredClone initDataVal, + JSObject* CallPageInit(const Script::Request& rq, Script::StructuredClone initDataVal, JS::HandleValue hotloadDataVal, const std::string_view scriptName); /** * Performs processing that should happen every frame * (including sending the "Tick" event to scripts) */ - JSObject* TickObjects(const ScriptRequest& rq, Script::StructuredClone initData, + JSObject* TickObjects(const Script::Request& rq, Script::StructuredClone initData, const std::string_view scriptName); /** @@ -286,7 +286,7 @@ public: GUIProxyProps* GetProxyData(const js::BaseProxyHandler* ptr) { return m_ProxyData.at(ptr).get(); } - std::shared_ptr GetScriptInterface() { return m_ScriptInterface; }; + std::shared_ptr GetScriptInterface() { return m_ScriptInterface; }; private: /** @@ -596,7 +596,7 @@ private: //-------------------------------------------------------- //@{ - std::shared_ptr m_ScriptInterface; + std::shared_ptr m_ScriptInterface; /** * don't want to pass this around with the @@ -728,7 +728,7 @@ private: public: struct ModuleArtifact { - ModuleArtifact(const ScriptRequest& rq, VfsPath filename); + ModuleArtifact(const Script::Request& rq, VfsPath filename); Script::ModuleLoader::Result result; Script::ModuleLoader::Result::iterator iterator{result.begin()}; diff --git a/source/gui/CGUISetting.cpp b/source/gui/CGUISetting.cpp index ce4d7f3407..ca59112644 100644 --- a/source/gui/CGUISetting.cpp +++ b/source/gui/CGUISetting.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -30,7 +30,7 @@ #include "maths/Vector2D.h" #include "ps/CLogger.h" #include "ps/CStr.h" -#include "scriptinterface/ScriptConversions.h" +#include "scriptinterface/Conversions.h" #include @@ -59,9 +59,9 @@ bool IGUISetting::FromString(const CStrW& value, const bool sendMessage) } /** - * Parses the given JS::Value using ScriptInterface::FromJSVal and assigns it to the setting data. + * Parses the given JS::Value using Script::Interface::FromJSVal and assigns it to the setting data. */ -bool IGUISetting::FromJSVal(const ScriptRequest& rq, JS::HandleValue value, const bool sendMessage) +bool IGUISetting::FromJSVal(const Script::Request& rq, JS::HandleValue value, const bool sendMessage) { if (!DoFromJSVal(rq, value)) return false; @@ -82,7 +82,7 @@ bool CGUISimpleSetting::DoFromString(const CStrW& value) }; template<> -bool CGUISimpleSetting::DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) +bool CGUISimpleSetting::DoFromJSVal(const Script::Request& rq, JS::HandleValue value) { if (value.isString()) { @@ -101,13 +101,13 @@ bool CGUISimpleSetting::DoFromJSVal(const ScriptRequest& rq, JS::Hand }; template -bool CGUISimpleSetting::DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) +bool CGUISimpleSetting::DoFromJSVal(const Script::Request& rq, JS::HandleValue value) { return Script::FromJSVal(rq, value, m_Setting); }; template -void CGUISimpleSetting::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue value) +void CGUISimpleSetting::ToJSVal(const Script::Request& rq, JS::MutableHandleValue value) { Script::ToJSVal(rq, value, m_Setting); }; diff --git a/source/gui/CGUISetting.h b/source/gui/CGUISetting.h index 1f0a6e559f..c1f9be16e1 100644 --- a/source/gui/CGUISetting.h +++ b/source/gui/CGUISetting.h @@ -26,7 +26,7 @@ #include class IGUIObject; -class ScriptRequest; +namespace Script { class Request; } /** * This setting interface allows GUI objects to call setting function functions without having to know the setting type. @@ -47,12 +47,12 @@ public: /** * Parses the given JS::Value using Script::FromJSVal and assigns it to the setting data. */ - bool FromJSVal(const ScriptRequest& rq, JS::HandleValue value, const bool sendMessage); + bool FromJSVal(const Script::Request& rq, JS::HandleValue value, const bool sendMessage); /** * Converts the setting data to a JS::Value using Script::ToJSVal. */ - virtual void ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue value) = 0; + virtual void ToJSVal(const Script::Request& rq, JS::MutableHandleValue value) = 0; protected: IGUISetting(IGUISetting&& other); @@ -61,7 +61,7 @@ protected: virtual ~IGUISetting() = default; virtual bool DoFromString(const CStrW& value) = 0; - virtual bool DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) = 0; + virtual bool DoFromJSVal(const Script::Request& rq, JS::HandleValue value) = 0; /** * Triggers the IGUIObject logic when a setting changes. @@ -124,8 +124,8 @@ public: protected: bool DoFromString(const CStrW& value) override; - bool DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) override; - void ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue value) override; + bool DoFromJSVal(const Script::Request& rq, JS::HandleValue value) override; + void ToJSVal(const Script::Request& rq, JS::MutableHandleValue value) override; T m_Setting; }; diff --git a/source/gui/GUIManager.cpp b/source/gui/GUIManager.cpp index 8b818a2a6d..fef588f652 100644 --- a/source/gui/GUIManager.cpp +++ b/source/gui/GUIManager.cpp @@ -37,10 +37,10 @@ #include "ps/containers/StaticVector.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/system/Component.h" @@ -90,7 +90,7 @@ static Status ReloadChangedFileCB(void* param, const VfsPath& path) return static_cast(param)->ReloadChangedFile(path); } -CGUIManager::CGUIManager(ScriptContext& scriptContext, ScriptInterface& scriptInterface) : +CGUIManager::CGUIManager(Script::Context& scriptContext, Script::Interface& scriptInterface) : m_ScriptContext{scriptContext}, m_ScriptInterface{scriptInterface}, m_InputHandler{g_VideoMode.m_InputManager, Input::Slot::GUI, {*this}} @@ -116,7 +116,7 @@ size_t CGUIManager::GetPageCount() const return m_PageStack.size(); } -void CGUIManager::SwitchPage(const CStrW& pageName, const ScriptInterface* srcScriptInterface, JS::HandleValue initData) +void CGUIManager::SwitchPage(const CStrW& pageName, const Script::Interface* srcScriptInterface, JS::HandleValue initData) { // The page stack is cleared (including the script context where initData came from), // therefore we have to clone initData. @@ -124,7 +124,7 @@ void CGUIManager::SwitchPage(const CStrW& pageName, const ScriptInterface* srcSc Script::StructuredClone initDataClone; if (!initData.isUndefined()) { - ScriptRequest rq(srcScriptInterface); + Script::Request rq(srcScriptInterface); initDataClone = Script::WriteStructuredClone(rq, initData); } @@ -165,14 +165,14 @@ CGUIManager::SGUIPage::SGUIPage(const CStrW& pageName, const Script::StructuredC { } -void CGUIManager::SGUIPage::LoadPage(ScriptContext& scriptContext) +void CGUIManager::SGUIPage::LoadPage(Script::Context& scriptContext) { // If we're hotloading then try to grab some data from the previous page Script::StructuredClone hotloadData; if (gui) { - std::shared_ptr scriptInterface = gui->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + std::shared_ptr scriptInterface = gui->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue hotloadDataVal(rq.cx, gui->GetHotloadData(rq)); hotloadData = Script::WriteStructuredClone(rq, hotloadDataVal); } @@ -180,7 +180,7 @@ void CGUIManager::SGUIPage::LoadPage(ScriptContext& scriptContext) g_VideoMode.ResetCursor(); inputs.clear(); gui.reset(new CGUI(scriptContext)); - const ScriptRequest rq{gui->GetScriptInterface()}; + const Script::Request rq{gui->GetScriptInterface()}; for (const char* name : {START_ATLAS, OPEN_REQUEST}) { @@ -267,7 +267,7 @@ void CGUIManager::SGUIPage::LoadPage(ScriptContext& scriptContext) JS::Value CGUIManager::SGUIPage::GetPromise() { - const ScriptRequest rq{gui->GetScriptInterface()}; + const Script::Request rq{gui->GetScriptInterface()}; if (receivingPromise == nullptr) { receivingPromise = std::make_shared(rq.cx, @@ -285,7 +285,7 @@ std::optional CGUIManager::SGUIPage::MaybeCl // Make sure we unfocus anything on the current page. gui->SendFocusMessage(GUIM_LOST_FOCUS); - const ScriptRequest rq{gui->GetScriptInterface()}; + const Script::Request rq{gui->GetScriptInterface()}; JS::RootedValue arg{rq.cx, JS::GetPromiseResult(*sendingPromise)}; const bool rejected{JS::GetPromiseState(*sendingPromise) == JS::PromiseState::Rejected}; @@ -327,8 +327,8 @@ void CGUIManager::SGUIPage::Refocus(const Close& result) { ENSURE(receivingPromise); - std::shared_ptr scriptInterface = gui->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + std::shared_ptr scriptInterface = gui->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedObject globalObj(rq.cx, rq.glob); @@ -379,10 +379,10 @@ Input::Reaction CGUIManager::HandleEvent(const SDL_Event& ev) { PROFILE("handleInputBeforeGui"); - ScriptRequest rq(*top()->GetScriptInterface()); + Script::Request rq(*top()->GetScriptInterface()); JS::RootedValue global(rq.cx, rq.globalValue()); - if (ScriptFunction::Call(rq, global, "handleInputBeforeGui", handled, ev, top()->FindObjectUnderMouse())) + if (Script::Function::Call(rq, global, "handleInputBeforeGui", handled, ev, top()->FindObjectUnderMouse())) if (handled) return Input::Reaction::HANDLED; } @@ -396,11 +396,11 @@ Input::Reaction CGUIManager::HandleEvent(const SDL_Event& ev) { // We can't take the following lines out of this scope because top() may be another gui page than it was when calling handleInputBeforeGui! - ScriptRequest rq(*top()->GetScriptInterface()); + Script::Request rq(*top()->GetScriptInterface()); JS::RootedValue global(rq.cx, rq.globalValue()); PROFILE("handleInputAfterGui"); - if (ScriptFunction::Call(rq, global, "handleInputAfterGui", handled, ev)) + if (Script::Function::Call(rq, global, "handleInputAfterGui", handled, ev)) if (handled) return Input::Reaction::HANDLED; } @@ -435,7 +435,7 @@ std::optional CGUIManager::TickObjects() for (const SGUIPage& p : pageStack) { - const ScriptRequest rq{p.gui->GetScriptInterface()}; + const Script::Request rq{p.gui->GetScriptInterface()}; JS::RootedObject newSendingPromise{rq.cx, p.gui->TickObjects(rq, p.initData, utf8_from_wstring(p.m_Name))}; if (newSendingPromise) @@ -503,8 +503,8 @@ const CParamNode& CGUIManager::GetTemplate(const std::string& templateName) void CGUIManager::DisplayLoadProgress(int percent, const wchar_t* pending_task) { - const ScriptInterface& scriptInterface = *(GetActiveGUI()->GetScriptInterface()); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = *(GetActiveGUI()->GetScriptInterface()); + Script::Request rq(scriptInterface); JS::RootedValueVector paramData(rq.cx); diff --git a/source/gui/GUIManager.h b/source/gui/GUIManager.h index a06903b4e2..1eab5fdc86 100644 --- a/source/gui/GUIManager.h +++ b/source/gui/GUIManager.h @@ -24,7 +24,7 @@ #include "ps/CStr.h" #include "ps/Input.h" #include "ps/TemplateLoader.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "scriptinterface/StructuredClone.h" #include @@ -39,7 +39,7 @@ class CCanvas2D; class CGUI; class CParamNode; -class ScriptContext; +namespace Script { class Context; } namespace JS { class HandleValueArray; } namespace JS { class Value; } namespace PS { template class StaticVector; } @@ -57,14 +57,14 @@ class CGUIManager { NONCOPYABLE(CGUIManager); public: - CGUIManager(ScriptContext& scriptContext, ScriptInterface& scriptInterface); + CGUIManager(Script::Context& scriptContext, Script::Interface& scriptInterface); ~CGUIManager(); - ScriptInterface& GetScriptInterface() + Script::Interface& GetScriptInterface() { return m_ScriptInterface; } - ScriptContext& GetContext() { return m_ScriptContext; } + Script::Context& GetContext() { return m_ScriptContext; } std::shared_ptr GetActiveGUI() { return top(); } /** @@ -75,7 +75,7 @@ public: /** * Load a new GUI page and make it active. All current pages will be destroyed. */ - void SwitchPage(const CStrW& name, const ScriptInterface* srcScriptInterface, JS::HandleValue initData); + void SwitchPage(const CStrW& name, const Script::Interface* srcScriptInterface, JS::HandleValue initData); /** * Load a new GUI page and make it active. All current pages will be retained, @@ -150,9 +150,9 @@ private: SGUIPage(const CStrW& pageName, const Script::StructuredClone initData); /** - * Create the CGUI with it's own ScriptInterface. Deletes the previous CGUI if it existed. + * Create the CGUI with it's own Script::Interface. Deletes the previous CGUI if it existed. */ - void LoadPage(ScriptContext& context); + void LoadPage(Script::Context& context); /** * A reference to the promise is returned. The promise will settle when the page is closed. @@ -206,8 +206,8 @@ private: std::shared_ptr top() const; - ScriptContext& m_ScriptContext; - ScriptInterface& m_ScriptInterface; + Script::Context& m_ScriptContext; + Script::Interface& m_ScriptInterface; /** * The page stack must not move pointers on push/pop, or pushing a page in a page's init method diff --git a/source/gui/ObjectBases/IGUIObject.cpp b/source/gui/ObjectBases/IGUIObject.cpp index 86682edc85..094ffff23f 100644 --- a/source/gui/ObjectBases/IGUIObject.cpp +++ b/source/gui/ObjectBases/IGUIObject.cpp @@ -31,7 +31,7 @@ #include "ps/CLogger.h" #include "ps/Profiler2.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "soundmanager/ISoundManager.h" #include @@ -321,7 +321,7 @@ float IGUIObject::GetBufferedZ() const void IGUIObject::RegisterScriptHandler(const CStr& eventName, const CStr& Code, CGUI& pGUI) { - ScriptRequest rq(pGUI.GetScriptInterface()); + Script::Request rq(pGUI.GetScriptInterface()); const int paramCount = 1; const char* paramNames[paramCount] = { "mouse" }; @@ -334,7 +334,7 @@ void IGUIObject::RegisterScriptHandler(const CStr& eventName, const CStr& Code, char buf[64]; sprintf_s(buf, ARRAY_SIZE(buf), "__eventhandler%d (%s)", x++, eventName.c_str()); - // TODO: this is essentially the same code as ScriptInterface::LoadScript (with a tweak for the argument). + // TODO: this is essentially the same code as Script::Interface::LoadScript (with a tweak for the argument). JS::CompileOptions options(rq.cx); options.setFileAndLine(CodeName.c_str(), 0); options.setIsRunOnce(false); @@ -413,7 +413,7 @@ Input::Reaction IGUIObject::SendMouseEvent(EGUIMessageType type, const CStr& eve msg.Skip(); HandleMessage(msg); - ScriptRequest rq(m_pGUI.GetScriptInterface()); + Script::Request rq(m_pGUI.GetScriptInterface()); // Set up the 'mouse' parameter JS::RootedValue mouse(rq.cx); @@ -457,7 +457,7 @@ bool IGUIObject::ScriptEvent(const CStr& eventName, if (it == m_ScriptHandlers.end()) return false; - ScriptRequest rq(m_pGUI.GetScriptInterface()); + Script::Request rq(m_pGUI.GetScriptInterface()); JS::RootedObject obj(rq.cx, GetJSObject()); JS::RootedValue handlerVal(rq.cx, JS::ObjectValue(*it->second)); JS::RootedValue result(rq.cx); @@ -465,7 +465,7 @@ bool IGUIObject::ScriptEvent(const CStr& eventName, if (!JS_CallFunctionValue(rq.cx, obj, handlerVal, paramData, &result)) { LOGERROR("Errors executing script event \"%s\"", eventName.c_str()); - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); return false; } return JS::ToBoolean(result); diff --git a/source/gui/ObjectTypes/CHotkeyPicker.cpp b/source/gui/ObjectTypes/CHotkeyPicker.cpp index dfb3b1df30..de30d19094 100644 --- a/source/gui/ObjectTypes/CHotkeyPicker.cpp +++ b/source/gui/ObjectTypes/CHotkeyPicker.cpp @@ -26,8 +26,8 @@ #include "lib/timer.h" #include "ps/CLogger.h" #include "ps/KeyName.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -43,13 +43,13 @@ const CStr CHotkeyPicker::EventNameCombination = "Combination"; const CStr CHotkeyPicker::EventNameKeyChange = "KeyChange"; // Don't send the scancode, JS doesn't care. -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CHotkeyPicker::Key& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CHotkeyPicker::Key& val) { Script::ToJSVal(rq, ret, val.scancodeName); } // Unused, but JSVAL_VECTOR requires it. -template<> bool Script::FromJSVal(const ScriptRequest&, const JS::HandleValue, CHotkeyPicker::Key&) +template<> bool Script::FromJSVal(const Script::Request&, const JS::HandleValue, CHotkeyPicker::Key&) { LOGWARNING("FromJSVal: Not implemented"); return false; @@ -65,7 +65,7 @@ CHotkeyPicker::CHotkeyPicker(CGUI& pGUI) : IGUIObject(pGUI), m_TimeToCombination void CHotkeyPicker::FireEvent(const CStr& event) { - ScriptRequest rq(*m_pGUI.GetScriptInterface()); + Script::Request rq(*m_pGUI.GetScriptInterface()); JS::RootedValueArray<1> args(rq.cx); JS::RootedValue keys(rq.cx); diff --git a/source/gui/ObjectTypes/CMiniMap.cpp b/source/gui/ObjectTypes/CMiniMap.cpp index 609e756296..141998ed37 100644 --- a/source/gui/ObjectTypes/CMiniMap.cpp +++ b/source/gui/ObjectTypes/CMiniMap.cpp @@ -44,8 +44,8 @@ #include "renderer/SceneRenderer.h" #include "renderer/WaterManager.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include "simulation2/components/ICmpRangeManager.h" #include "simulation2/system/Component.h" #include "simulation2/system/Entity.h" @@ -262,7 +262,7 @@ CVector2D CMiniMap::WorldSpaceToMiniMapSpace(const CVector3D& worldPosition) con bool CMiniMap::FireWorldClickEvent(int button, int /*clicks*/) { - ScriptRequest rq(g_GUI->GetActiveGUI()->GetScriptInterface()); + Script::Request rq(g_GUI->GetActiveGUI()->GetScriptInterface()); float x, z; GetMouseWorldCoordinates(x, z); diff --git a/source/gui/Scripting/GuiScriptConversions.cpp b/source/gui/Scripting/GuiScriptConversions.cpp index 7bd3ff6ec2..cf4db814b9 100644 --- a/source/gui/Scripting/GuiScriptConversions.cpp +++ b/source/gui/Scripting/GuiScriptConversions.cpp @@ -17,7 +17,7 @@ #include "precompiled.h" -#include "scriptinterface/ScriptConversions.h" +#include "scriptinterface/Conversions.h" #include "gui/CGUISprite.h" #include "gui/ObjectBases/IGUIObject.h" @@ -36,8 +36,8 @@ #include "ps/CLogger.h" #include "ps/Hotkey.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Request.h" #include #include @@ -55,7 +55,7 @@ struct CColor; // ignore JS_SetProperty return value, because errors should be impossible // and we can't do anything useful in the case of errors anyway -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, SDL_Event const& ev) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, SDL_Event const& ev) { const char* typeName; @@ -148,7 +148,7 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableH ret.setObject(*obj); } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, +template<> void Script::ToJSVal(const Script::Request&, JS::MutableHandleValue ret, IGUIObject* const& val) { if (val == nullptr) @@ -157,28 +157,28 @@ template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHa ret.setObject(*val->GetJSObject()); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, IGUIObject*& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, IGUIObject*& out) { if (!v.isObject()) { - ScriptException::Raise(rq, "Value is not an IGUIObject."); + Script::Exception::Raise(rq, "Value is not an IGUIObject."); return false; } out = IGUIProxyObject::FromPrivateSlot(v.toObjectOrNull()); if (!out) { - ScriptException::Raise(rq, "Value is not an IGUIObject."); + Script::Exception::Raise(rq, "Value is not an IGUIObject."); return false; } return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CGUIString& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CGUIString& val) { Script::ToJSVal(rq, ret, val.GetOriginalString()); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CGUIString& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CGUIString& out) { std::wstring val; if (!FromJSVal(rq, v, val)) @@ -191,7 +191,7 @@ JSVAL_VECTOR(CVector2D) JSVAL_VECTOR(std::vector) JSVAL_VECTOR(CGUIString) -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CGUIColor& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CGUIColor& val) { ToJSVal(rq, ret, val); } @@ -199,9 +199,9 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableH /** * The color depends on the predefined color database stored in the current GUI page. */ -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CGUIColor& out) = delete; +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CGUIColor& out) = delete; -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CRect& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CRect& val) { Script::CreateObject( rq, @@ -212,27 +212,27 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandl "bottom", val.bottom); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CGUIList& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CGUIList& val) { ToJSVal(rq, ret, val.m_Items); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CGUIList& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CGUIList& out) { return FromJSVal(rq, v, out.m_Items); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CGUISeries& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CGUISeries& val) { ToJSVal(rq, ret, val.m_Series); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CGUISeries& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CGUISeries& out) { return FromJSVal(rq, v, out.m_Series); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const EVAlign& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const EVAlign& val) { std::string word; switch (val) @@ -251,13 +251,13 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHan default: word = "error"; - ScriptException::Raise(rq, "Invalid EVAlign"); + Script::Exception::Raise(rq, "Invalid EVAlign"); break; } ToJSVal(rq, ret, word); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, EVAlign& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, EVAlign& out) { std::string word; FromJSVal(rq, v, word); @@ -277,7 +277,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleVa return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const EAlign& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const EAlign& val) { std::string word; switch (val) @@ -293,13 +293,13 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHand break; default: word = "error"; - ScriptException::Raise(rq, "Invalid alignment (should be 'left', 'right' or 'center')"); + Script::Exception::Raise(rq, "Invalid alignment (should be 'left', 'right' or 'center')"); break; } ToJSVal(rq, ret, word); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, EAlign& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, EAlign& out) { std::string word; FromJSVal(rq, v, word); @@ -319,7 +319,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleVal return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const EScrollOrientation& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const EScrollOrientation& val) { std::string word; switch (val) @@ -335,13 +335,13 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS: break; default: word = "error"; - ScriptException::Raise(rq, "Invalid scroll orientation (should be 'vertical', 'horizontal' or 'both')"); + Script::Exception::Raise(rq, "Invalid scroll orientation (should be 'vertical', 'horizontal' or 'both')"); break; } ToJSVal(rq, ret, word); } -template <> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, EScrollOrientation& out) +template <> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, EScrollOrientation& out) { std::string word; FromJSVal(rq, v, word); @@ -362,12 +362,12 @@ template <> bool Script::FromJSVal(const ScriptRequest& rq, return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CGUISpriteInstance& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CGUISpriteInstance& val) { ToJSVal(rq, ret, val.GetName()); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CGUISpriteInstance& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CGUISpriteInstance& out) { std::string name; if (!FromJSVal(rq, v, name)) @@ -377,12 +377,12 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, J return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CSize2D& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CSize2D& val) { Script::CreateObject(rq, ret, "width", val.Width, "height", val.Height); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CSize2D& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CSize2D& out) { if (!v.isObject()) { @@ -405,12 +405,12 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleVa return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CVector2D& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CVector2D& val) { Script::CreateObject(rq, ret, "x", val.X, "y", val.Y); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CVector2D& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CVector2D& out) { if (!v.isObject()) { diff --git a/source/gui/Scripting/JSInterface_CGUISize.cpp b/source/gui/Scripting/JSInterface_CGUISize.cpp index 0910ec3fbb..7f447e6957 100644 --- a/source/gui/Scripting/JSInterface_CGUISize.cpp +++ b/source/gui/Scripting/JSInterface_CGUISize.cpp @@ -30,9 +30,9 @@ #include "ps/CLogger.h" #include "ps/CStr.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -55,7 +55,7 @@ bool GetCRectField(JSContext* cx, unsigned argc, JS::Value* vp) { JS::CallArgs args{JS::CallArgsFromVp(argc, vp)}; JS::RootedObject obj{cx, &args.thisv().toObject()}; - CGUISimpleSetting* wrapper{JS::GetMaybePtrFromReservedSlot>(obj, ScriptInterface::JSObjectReservedSlots::PRIVATE)}; + CGUISimpleSetting* wrapper{JS::GetMaybePtrFromReservedSlot>(obj, Script::Interface::JSObjectReservedSlots::PRIVATE)}; args.rval().setDouble(wrapper->GetMutable().*RectMember.*Member); return true; @@ -66,7 +66,7 @@ bool SetCRectField(JSContext* cx, unsigned argc, JS::Value* vp) { JS::CallArgs args{JS::CallArgsFromVp(argc, vp)}; JS::RootedObject obj{cx, &args.thisv().toObject()}; - CGUISimpleSetting* wrapper{JS::GetMaybePtrFromReservedSlot>(obj, ScriptInterface::JSObjectReservedSlots::PRIVATE)}; + CGUISimpleSetting* wrapper{JS::GetMaybePtrFromReservedSlot>(obj, Script::Interface::JSObjectReservedSlots::PRIVATE)}; double val; if (!JS::ToNumber(cx, args.get(0), &val)) @@ -96,7 +96,7 @@ bool toString(JSContext* cx, uint argc, JS::Value* vp) { JS::CallArgs args{JS::CallArgsFromVp(argc, vp)}; JS::RootedObject obj{cx, &args.thisv().toObject()}; - CGUISimpleSetting* wrapper{JS::GetMaybePtrFromReservedSlot>(obj, ScriptInterface::JSObjectReservedSlots::PRIVATE)}; + CGUISimpleSetting* wrapper{JS::GetMaybePtrFromReservedSlot>(obj, Script::Interface::JSObjectReservedSlots::PRIVATE)}; CStr buffer; buffer += ToPercentString(wrapper->GetMutable().pixel.left, wrapper->GetMutable().percent.left) + " "; @@ -104,7 +104,7 @@ bool toString(JSContext* cx, uint argc, JS::Value* vp) buffer += ToPercentString(wrapper->GetMutable().pixel.right, wrapper->GetMutable().percent.right) + " "; buffer += ToPercentString(wrapper->GetMutable().pixel.bottom, wrapper->GetMutable().percent.bottom); - ScriptRequest rq{cx}; + Script::Request rq{cx}; Script::ToJSVal(rq, args.rval(), buffer); return true; } @@ -137,19 +137,19 @@ JSPropertySpec JSI_props[] = -void JSI_CGUISize::RegisterScriptClass(ScriptInterface& scriptInterface) +void JSI_CGUISize::RegisterScriptClass(Script::Interface& scriptInterface) { scriptInterface.DefineCustomObjectType(&JSI_class, nullptr, 0, JSI_props, JSI_methods, nullptr, nullptr); } template class CGUISimpleSetting; template<> -void CGUISimpleSetting::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret) +void CGUISimpleSetting::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret) { - const ScriptInterface& scriptInterface = rq.GetScriptInterface(); + const Script::Interface& scriptInterface = rq.GetScriptInterface(); JS::RootedObject obj{rq.cx, scriptInterface.CreateCustomObject("CGUISize")}; - JS::SetReservedSlot(obj, ScriptInterface::JSObjectReservedSlots::PRIVATE, JS::PrivateValue(this)); + JS::SetReservedSlot(obj, Script::Interface::JSObjectReservedSlots::PRIVATE, JS::PrivateValue(this)); ret.setObject(*obj); }; @@ -160,7 +160,7 @@ bool CGUISimpleSetting::DoFromString(const CStrW& value) }; template<> -bool CGUISimpleSetting::DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) +bool CGUISimpleSetting::DoFromJSVal(const Script::Request& rq, JS::HandleValue value) { if (value.isString()) { @@ -189,7 +189,7 @@ bool CGUISimpleSetting::DoFromJSVal(const ScriptRequest& rq, JS::Handl JS::RootedObject obj{rq.cx, &value.toObject()}; if (JS_InstanceOf(rq.cx, obj, &JSI_class, nullptr)) { - CGUISimpleSetting* wrapper = JS::GetMaybePtrFromReservedSlot>(obj, ScriptInterface::JSObjectReservedSlots::PRIVATE); + CGUISimpleSetting* wrapper = JS::GetMaybePtrFromReservedSlot>(obj, Script::Interface::JSObjectReservedSlots::PRIVATE); if (this != wrapper) this->Set(wrapper->m_Setting, false); return true; diff --git a/source/gui/Scripting/JSInterface_CGUISize.h b/source/gui/Scripting/JSInterface_CGUISize.h index 98d0494526..263548b6d5 100644 --- a/source/gui/Scripting/JSInterface_CGUISize.h +++ b/source/gui/Scripting/JSInterface_CGUISize.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,10 +18,10 @@ #ifndef INCLUDED_JSI_CGUISIZE #define INCLUDED_JSI_CGUISIZE -class ScriptInterface; +namespace Script { class Interface; } namespace JSI_CGUISize { - void RegisterScriptClass(ScriptInterface& scriptInterface); + void RegisterScriptClass(Script::Interface& scriptInterface); } #endif // INCLUDED_JSI_GUISIZE diff --git a/source/gui/Scripting/JSInterface_GUIManager.cpp b/source/gui/Scripting/JSInterface_GUIManager.cpp index c07d0f853b..d928e0a03c 100644 --- a/source/gui/Scripting/JSInterface_GUIManager.cpp +++ b/source/gui/Scripting/JSInterface_GUIManager.cpp @@ -24,7 +24,7 @@ #include "ps/CStr.h" #include "ps/VideoMode.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/system/Component.h" @@ -38,7 +38,7 @@ namespace JSI_GUIManager // Note that the initData argument may only contain clonable data. // Functions aren't supported for example! // It returns a promise. -JS::Value OpenChildPage(const ScriptRequest& rq, const std::wstring& name, JS::HandleValue initData) +JS::Value OpenChildPage(const Script::Request& rq, const std::wstring& name, JS::HandleValue initData) { return g_GUI->OpenChildPage(name, Script::WriteStructuredClone(rq, initData)); } @@ -64,17 +64,17 @@ CParamNode GetTemplate(const std::string& templateName) } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&OpenChildPage>(rq, "OpenChildPage"); - ScriptFunction::Register<&SetCursor>(rq, "SetCursor"); - ScriptFunction::Register<&ResetCursor>(rq, "ResetCursor"); - ScriptFunction::Register<&TemplateExists>(rq, "TemplateExists"); - ScriptFunction::Register<&GetTemplate>(rq, "GetTemplate"); + Script::Function::Register<&OpenChildPage>(rq, "OpenChildPage"); + Script::Function::Register<&SetCursor>(rq, "SetCursor"); + Script::Function::Register<&ResetCursor>(rq, "ResetCursor"); + Script::Function::Register<&TemplateExists>(rq, "TemplateExists"); + Script::Function::Register<&GetTemplate>(rq, "GetTemplate"); - ScriptFunction::Register<&CGUI::TryFindObjectByName, &ScriptInterface::ObjectFromCBData>(rq, "TryGetGUIObjectByName"); - ScriptFunction::Register<&CGUI::FindObjectByName, &ScriptInterface::ObjectFromCBData>(rq, "GetGUIObjectByName"); - ScriptFunction::Register<&CGUI::SetGlobalHotkey, &ScriptInterface::ObjectFromCBData>(rq, "SetGlobalHotkey"); - ScriptFunction::Register<&CGUI::UnsetGlobalHotkey, &ScriptInterface::ObjectFromCBData>(rq, "UnsetGlobalHotkey"); + Script::Function::Register<&CGUI::TryFindObjectByName, &Script::Interface::ObjectFromCBData>(rq, "TryGetGUIObjectByName"); + Script::Function::Register<&CGUI::FindObjectByName, &Script::Interface::ObjectFromCBData>(rq, "GetGUIObjectByName"); + Script::Function::Register<&CGUI::SetGlobalHotkey, &Script::Interface::ObjectFromCBData>(rq, "SetGlobalHotkey"); + Script::Function::Register<&CGUI::UnsetGlobalHotkey, &Script::Interface::ObjectFromCBData>(rq, "UnsetGlobalHotkey"); } } diff --git a/source/gui/Scripting/JSInterface_GUIManager.h b/source/gui/Scripting/JSInterface_GUIManager.h index 4dcb0051aa..d0e33a04b3 100644 --- a/source/gui/Scripting/JSInterface_GUIManager.h +++ b/source/gui/Scripting/JSInterface_GUIManager.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_GUIMANAGER #define INCLUDED_JSI_GUIMANAGER -class ScriptRequest; +namespace Script { class Request; } namespace JSI_GUIManager { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_GUIMANAGER diff --git a/source/gui/Scripting/JSInterface_GUIProxy.cpp b/source/gui/Scripting/JSInterface_GUIProxy.cpp index 5b0ca09209..aef2b8ea0a 100644 --- a/source/gui/Scripting/JSInterface_GUIProxy.cpp +++ b/source/gui/Scripting/JSInterface_GUIProxy.cpp @@ -31,11 +31,11 @@ #include class CGUIString; -class ScriptRequest; +namespace Script { class Request; } // Called for every specialization - adds the common interface. template<> -void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache) +void JSI_GUIProxy::CreateFunctions(const Script::Request& rq, GUIProxyProps* cache) { CreateFunction<&IGUIObject::GetName>(rq, cache, "toString"); CreateFunction<&IGUIObject::GetName>(rq, cache, "toSource"); @@ -48,7 +48,7 @@ DECLARE_GUIPROXY(IGUIObject); // Implement derived types below. // CButton -template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache) +template<> void JSI_GUIProxy::CreateFunctions(const Script::Request& rq, GUIProxyProps* cache) { CreateFunction<&CButton::GetTextSize>(rq, cache, "getTextSize"); CreateFunction<&CButton::GetPreferredTextSize>(rq, cache, "getPreferredTextSize"); @@ -56,7 +56,7 @@ template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, DECLARE_GUIPROXY(CButton); // CText -template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache) +template<> void JSI_GUIProxy::CreateFunctions(const Script::Request& rq, GUIProxyProps* cache) { CreateFunction<&CText::GetTextSize>(rq, cache, "getTextSize"); CreateFunction<&CText::GetPreferredTextSize>(rq, cache, "getPreferredTextSize"); @@ -64,28 +64,28 @@ template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GU DECLARE_GUIPROXY(CText); // CList -template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache) +template<> void JSI_GUIProxy::CreateFunctions(const Script::Request& rq, GUIProxyProps* cache) { CreateFunction(&CList::AddItem)>(rq, cache, "addItem"); } DECLARE_GUIPROXY(CList); // CDropDown -template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache) +template<> void JSI_GUIProxy::CreateFunctions(const Script::Request& rq, GUIProxyProps* cache) { CreateFunction<&CDropDown::GetPreferredHeaderTextSize>(rq, cache, "getPreferredHeaderTextSize"); } DECLARE_GUIPROXY(CDropDown); // CMiniMap -template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache) +template<> void JSI_GUIProxy::CreateFunctions(const Script::Request& rq, GUIProxyProps* cache) { CreateFunction<&CMiniMap::Flare>(rq, cache, "flare"); } DECLARE_GUIPROXY(CMiniMap); // CScrollPanel -template<> void JSI_GUIProxy::CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache) +template<> void JSI_GUIProxy::CreateFunctions(const Script::Request& rq, GUIProxyProps* cache) { CreateFunction<&CScrollPanel::ResetScrollPosition>(rq, cache, "resetScrollPosition"); } diff --git a/source/gui/Scripting/JSInterface_GUIProxy.h b/source/gui/Scripting/JSInterface_GUIProxy.h index c798cbffba..cd5aa60e72 100644 --- a/source/gui/Scripting/JSInterface_GUIProxy.h +++ b/source/gui/Scripting/JSInterface_GUIProxy.h @@ -36,9 +36,9 @@ class JSFunction; class JSObject; -class ScriptInterface; -class ScriptRequest; namespace JS { class CallArgs; } +namespace Script { class Interface; } +namespace Script { class Request; } // See JSI_GuiProxy below #if GCC_VERSION @@ -101,7 +101,7 @@ public: virtual bool has(const std::string& name) const = 0; // @return the JSFunction matching @param name. Must call has() first as it can assume existence. virtual JSObject* get(const std::string& name) const = 0; - virtual bool setFunction(const ScriptRequest& rq, const std::string& name, JSFunction* function) = 0; + virtual bool setFunction(const Script::Request& rq, const std::string& name, JSFunction* function) = 0; virtual std::vector getPropsNames() const = 0; }; @@ -138,10 +138,10 @@ public: static JSI_GUIProxy& Singleton(); // Call this in CGUI::AddObjectTypes. - static std::pair CreateData(ScriptInterface& scriptInterface); + static std::pair CreateData(Script::Interface& scriptInterface); // Create the JS object, the proxy, the data and wrap it in a convenient unique_ptr. - static std::unique_ptr CreateJSObject(const ScriptRequest& rq, GUIObjectType* ptr, GUIProxyProps* data); + static std::unique_ptr CreateJSObject(const Script::Request& rq, GUIObjectType* ptr, GUIProxyProps* data); protected: // @param family can't be nullptr because that's used for some DOM object and it crashes. JSI_GUIProxy() : BaseProxyHandler(this, false, false) {}; @@ -150,18 +150,18 @@ protected: // This also enforces making proxy handlers dataless static variables. ~JSI_GUIProxy() {}; - static GUIObjectType* FromPrivateSlot(const ScriptRequest&, JS::CallArgs& args); + static GUIObjectType* FromPrivateSlot(const Script::Request&, JS::CallArgs& args); // The default implementations need to know the type of the GUIProxyProps for this proxy type. // This is done by specializing this struct's alias type. struct PropCache; // Specialize this to define the custom properties of this type. - static void CreateFunctions(const ScriptRequest& rq, GUIProxyProps* cache); + static void CreateFunctions(const Script::Request& rq, GUIProxyProps* cache); // Convenience helper for the above. template - static void CreateFunction(const ScriptRequest& rq, GUIProxyProps* cache, const std::string& name); + static void CreateFunction(const Script::Request& rq, GUIProxyProps* cache, const std::string& name); // This handles returning custom properties. Specialize this if needed. bool PropGetter(JS::HandleObject proxy, const std::string& propName, JS::MutableHandleValue vp) const; diff --git a/source/gui/Scripting/JSInterface_GUIProxy_impl.h b/source/gui/Scripting/JSInterface_GUIProxy_impl.h index 9ee4e55338..537580add9 100644 --- a/source/gui/Scripting/JSInterface_GUIProxy_impl.h +++ b/source/gui/Scripting/JSInterface_GUIProxy_impl.h @@ -25,8 +25,8 @@ #include "ps/CStr.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -49,7 +49,7 @@ #include class JSObject; -class ScriptInterface; +namespace Script { class Interface; } #ifndef INCLUDED_JSI_GUIPROXY_IMP #define INCLUDED_JSI_GUIPROXY_IMP @@ -65,7 +65,7 @@ JSI_GUIProxy& JSI_GUIProxy::Singleton() #define DECLARE_GUIPROXY(Type) \ void Type::CreateJSObject() \ { \ - ScriptRequest rq(m_pGUI.GetScriptInterface()); \ + Script::Request rq(m_pGUI.GetScriptInterface()); \ using ProxyHandler = JSI_GUIProxy>; \ m_JSObject = ProxyHandler::CreateJSObject(rq, this, GetGUI().GetProxyData(&ProxyHandler::Singleton())); \ } \ @@ -97,7 +97,7 @@ public: return m_Functions.at(name).get(); } - bool setFunction(const ScriptRequest& rq, const std::string& name, JSFunction* function) override + bool setFunction(const Script::Request& rq, const std::string& name, JSFunction* function) override { m_Functions[name].init(rq.cx, JS_GetFunctionObject(function)); return true; @@ -137,7 +137,7 @@ struct JSI_GUIProxy::PropCache }; template -T* JSI_GUIProxy::FromPrivateSlot(const ScriptRequest&, JS::CallArgs& args) +T* JSI_GUIProxy::FromPrivateSlot(const Script::Request&, JS::CallArgs& args) { // Call the unsafe version - this is only ever called from actual proxy objects. return IGUIProxyObject::UnsafeFromPrivateSlot(args.thisv().toObjectOrNull()); @@ -158,11 +158,11 @@ bool JSI_GUIProxy::PropGetter(JS::HandleObject proxy, const std::string& prop } template -std::pair JSI_GUIProxy::CreateData(ScriptInterface& scriptInterface) +std::pair JSI_GUIProxy::CreateData(Script::Interface& scriptInterface) { using PropertyCache = typename PropCache::type; PropertyCache* data = new PropertyCache(); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); // Functions common to all children of IGUIObject. JSI_GUIProxy::CreateFunctions(rq, data); @@ -175,13 +175,13 @@ std::pair JSI_GUIProxy::CreateDa template template -void JSI_GUIProxy::CreateFunction(const ScriptRequest& rq, GUIProxyProps* cache, const std::string& name) +void JSI_GUIProxy::CreateFunction(const Script::Request& rq, GUIProxyProps* cache, const std::string& name) { - cache->setFunction(rq, name, ScriptFunction::Create(rq, name.c_str())); + cache->setFunction(rq, name, Script::Function::Create(rq, name.c_str())); } template -std::unique_ptr JSI_GUIProxy::CreateJSObject(const ScriptRequest& rq, T* ptr, GUIProxyProps* dataPtr) +std::unique_ptr JSI_GUIProxy::CreateJSObject(const Script::Request& rq, T* ptr, GUIProxyProps* dataPtr) { js::ProxyOptions options; options.setClass(&JSInterface_GUIProxy::ClassDefinition()); @@ -201,7 +201,7 @@ template bool JSI_GUIProxy::get(JSContext* cx, JS::HandleObject proxy, JS::HandleValue /*receiver*/, JS::HandleId id, JS::MutableHandleValue vp) const { - ScriptRequest rq(cx); + Script::Request rq(cx); T* e = IGUIProxyObject::FromPrivateSlot(proxy.get()); if (!e) @@ -283,7 +283,7 @@ bool JSI_GUIProxy::set(JSContext* cx, JS::HandleObject proxy, JS::HandleId id return result.fail(JSMSG_OBJECT_REQUIRED); } - ScriptRequest rq(cx); + Script::Request rq(cx); JS::RootedValue idval(rq.cx); if (!JS_IdToValue(rq.cx, id, &idval)) @@ -338,7 +338,7 @@ bool JSI_GUIProxy::delete_(JSContext* cx, JS::HandleObject proxy, JS::HandleI return result.fail(JSMSG_OBJECT_REQUIRED); } - ScriptRequest rq(cx); + Script::Request rq(cx); JS::RootedValue idval(rq.cx); if (!JS_IdToValue(rq.cx, id, &idval)) @@ -363,7 +363,7 @@ bool JSI_GUIProxy::delete_(JSContext* cx, JS::HandleObject proxy, JS::HandleI template bool JSI_GUIProxy::ownPropertyKeys(JSContext* cx, JS::HandleObject proxy, JS::MutableHandleIdVector props) const { - ScriptRequest rq(cx); + Script::Request rq(cx); T* e = IGUIProxyObject::FromPrivateSlot(proxy.get()); if (!e) diff --git a/source/gui/Scripting/JSInterface_GUISize.cpp b/source/gui/Scripting/JSInterface_GUISize.cpp index 4195910a88..1f9c7e0918 100644 --- a/source/gui/Scripting/JSInterface_GUISize.cpp +++ b/source/gui/Scripting/JSInterface_GUISize.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -21,9 +21,9 @@ #include "ps/CStr.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -52,7 +52,7 @@ JSFunctionSpec JSI_GUISize::JSI_methods[] = JS_FS_END }; -void JSI_GUISize::RegisterScriptClass(ScriptInterface& scriptInterface) +void JSI_GUISize::RegisterScriptClass(Script::Interface& scriptInterface) { scriptInterface.DefineCustomObjectType(&JSI_GUISize::JSI_class, JSI_GUISize::construct, 0, nullptr, JSI_GUISize::JSI_methods, nullptr, nullptr); } @@ -60,8 +60,8 @@ void JSI_GUISize::RegisterScriptClass(ScriptInterface& scriptInterface) bool JSI_GUISize::construct(JSContext* cx, uint argc, JS::Value* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - ScriptRequest rq(cx); - const ScriptInterface& scriptInterface = rq.GetScriptInterface(); + Script::Request rq(cx); + const Script::Interface& scriptInterface = rq.GetScriptInterface(); JS::RootedObject obj(rq.cx, scriptInterface.CreateCustomObject("GUISize")); @@ -119,7 +119,7 @@ bool JSI_GUISize::toString(JSContext* cx, uint argc, JS::Value* vp) JS::CallArgs args = JS::CallArgsFromVp(argc, vp); CStr buffer; - ScriptRequest rq(cx); + Script::Request rq(cx); double val, valr; #define SIDE(side) \ diff --git a/source/gui/Scripting/JSInterface_GUISize.h b/source/gui/Scripting/JSInterface_GUISize.h index a028de4db8..c2250d5e04 100644 --- a/source/gui/Scripting/JSInterface_GUISize.h +++ b/source/gui/Scripting/JSInterface_GUISize.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,8 +23,8 @@ #include "lib/types.h" #include "ps/CStr.h" -class ScriptInterface; namespace JS { class Value; } +namespace Script { class Interface; } struct JSClass; struct JSClassOps; struct JSContext; @@ -38,7 +38,7 @@ namespace JSI_GUISize extern JSPropertySpec JSI_props[]; extern JSFunctionSpec JSI_methods[]; - void RegisterScriptClass(ScriptInterface& scriptInterface); + void RegisterScriptClass(Script::Interface& scriptInterface); bool construct(JSContext* cx, uint argc, JS::Value* vp); bool toString(JSContext* cx, uint argc, JS::Value* vp); diff --git a/source/gui/Scripting/ScriptFunctions.cpp b/source/gui/Scripting/ScriptFunctions.cpp index cbeb3808d7..fafac08870 100644 --- a/source/gui/Scripting/ScriptFunctions.cpp +++ b/source/gui/Scripting/ScriptFunctions.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -39,7 +39,7 @@ #include "ps/scripting/JSInterface_VFS.h" #include "ps/scripting/JSInterface_VisualReplay.h" #include "renderer/scripting/JSInterface_Renderer.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/scripting/JSInterface_Simulation.h" #include "soundmanager/scripting/JSInterface_Sound.h" @@ -49,9 +49,9 @@ * Functions are exposed to scripts within the global object 'Engine', so * scripts should call "Engine.FunctionName(...)" etc. */ -void GuiScriptingInit(ScriptInterface& scriptInterface) +void GuiScriptingInit(Script::Interface& scriptInterface) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JSI_GUISize::RegisterScriptClass(scriptInterface); JSI_CGUISize::RegisterScriptClass(scriptInterface); diff --git a/source/gui/Scripting/ScriptFunctions.h b/source/gui/Scripting/ScriptFunctions.h index f739ca044f..ff86322f72 100644 --- a/source/gui/Scripting/ScriptFunctions.h +++ b/source/gui/Scripting/ScriptFunctions.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2010 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,8 +18,8 @@ #ifndef INCLUDED_GUI_SCRIPTFUNCTIONS #define INCLUDED_GUI_SCRIPTFUNCTIONS -class ScriptInterface; +namespace Script { class Interface; } -void GuiScriptingInit(ScriptInterface& scriptInterface); +void GuiScriptingInit(Script::Interface& scriptInterface); #endif // INCLUDED_GUI_SCRIPTFUNCTIONS diff --git a/source/gui/SettingTypes/CGUIHotkey.cpp b/source/gui/SettingTypes/CGUIHotkey.cpp index 2aefea550d..65163b2afd 100644 --- a/source/gui/SettingTypes/CGUIHotkey.cpp +++ b/source/gui/SettingTypes/CGUIHotkey.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -21,7 +21,7 @@ #include "gui/CGUI.h" #include "gui/ObjectBases/IGUIObject.h" -#include "scriptinterface/ScriptConversions.h" +#include "scriptinterface/Conversions.h" #include @@ -33,7 +33,7 @@ bool CGUIHotkey::DoFromString(const CStrW& value) return true; } -bool CGUIHotkey::DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) +bool CGUIHotkey::DoFromJSVal(const Script::Request& rq, JS::HandleValue value) { m_Object.GetGUI().UnsetObjectHotkey(m_Object, m_Setting); if (!Script::FromJSVal(rq, value, m_Setting)) diff --git a/source/gui/SettingTypes/CGUIHotkey.h b/source/gui/SettingTypes/CGUIHotkey.h index d0cf552e7c..31618353be 100644 --- a/source/gui/SettingTypes/CGUIHotkey.h +++ b/source/gui/SettingTypes/CGUIHotkey.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -39,7 +39,7 @@ public: CGUIHotkey& operator=(CGUIHotkey&&) = delete; bool DoFromString(const CStrW& value) override; - bool DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) override; + bool DoFromJSVal(const Script::Request& rq, JS::HandleValue value) override; void OnSettingChange(const CStr& setting, bool sendMessage) override; }; diff --git a/source/gui/SettingTypes/MouseEventMask.cpp b/source/gui/SettingTypes/MouseEventMask.cpp index 2b4a1b88ee..d7b3140e26 100644 --- a/source/gui/SettingTypes/MouseEventMask.cpp +++ b/source/gui/SettingTypes/MouseEventMask.cpp @@ -32,7 +32,7 @@ #include "ps/CStr.h" #include "ps/CacheLoader.h" #include "ps/Filesystem.h" -#include "scriptinterface/ScriptConversions.h" +#include "scriptinterface/Conversions.h" #include #include @@ -63,12 +63,12 @@ CGUIMouseEventMask::~CGUIMouseEventMask() { } -void CGUIMouseEventMask::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue Value) +void CGUIMouseEventMask::ToJSVal(const Script::Request& rq, JS::MutableHandleValue Value) { Script::ToJSVal(rq, Value, m_Spec); } -bool CGUIMouseEventMask::DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) +bool CGUIMouseEventMask::DoFromJSVal(const Script::Request& rq, JS::HandleValue value) { CStrW spec; if (!Script::FromJSVal(rq, value, spec)) diff --git a/source/gui/SettingTypes/MouseEventMask.h b/source/gui/SettingTypes/MouseEventMask.h index 2e76e4fe00..d0fdd6b987 100644 --- a/source/gui/SettingTypes/MouseEventMask.h +++ b/source/gui/SettingTypes/MouseEventMask.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -58,12 +58,12 @@ public: */ bool IsMouseOver(const CVector2D& mousePos, const CRect& objectSize) const; - void ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue value) override; + void ToJSVal(const Script::Request& rq, JS::MutableHandleValue value) override; class Impl; protected: bool DoFromString(const CStrW& value) override; - bool DoFromJSVal(const ScriptRequest& rq, JS::HandleValue value) override; + bool DoFromJSVal(const Script::Request& rq, JS::HandleValue value) override; std::string m_Spec; std::unique_ptr m_Impl; diff --git a/source/gui/tests/test_CGUIText.h b/source/gui/tests/test_CGUIText.h index 5739e057df..ea37bb2583 100644 --- a/source/gui/tests/test_CGUIText.h +++ b/source/gui/tests/test_CGUIText.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -37,7 +37,7 @@ #include "ps/VideoMode.h" #include "ps/XML/Xeromyces.h" #include "renderer/Renderer.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include #include diff --git a/source/gui/tests/test_GUISetting.h b/source/gui/tests/test_GUISetting.h index 1e0c834119..bee95309f6 100644 --- a/source/gui/tests/test_GUISetting.h +++ b/source/gui/tests/test_GUISetting.h @@ -34,8 +34,8 @@ #include "ps/VideoMode.h" #include "ps/XML/Xeromyces.h" #include "renderer/Renderer.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -140,7 +140,7 @@ public: CGUISimpleSetting* setting{object.GetSizeSetting()}; object.SetSettingFromString("size", L"2 2 20 20", false); - ScriptRequest rq{gui.GetScriptInterface()}; + Script::Request rq{gui.GetScriptInterface()}; JS::RootedValue val(rq.cx); val.setObject(*object.GetJSObject()); JS::RootedObject global(rq.cx, rq.glob); diff --git a/source/gui/tests/test_GuiManager.h b/source/gui/tests/test_GuiManager.h index 13b8c27169..22d095f483 100644 --- a/source/gui/tests/test_GuiManager.h +++ b/source/gui/tests/test_GuiManager.h @@ -35,9 +35,9 @@ #include "ps/VideoMode.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include @@ -60,7 +60,7 @@ class TestGuiManager : public CxxTest::TestSuite { std::unique_ptr configDB; std::optional xeromycesEngine; - std::optional scriptInterface; + std::optional scriptInterface; public: void setUp() @@ -90,15 +90,15 @@ public: void test_EventObject() { // Load up a test page. - ScriptRequest rq{g_GUI->GetScriptInterface()}; + Script::Request rq{g_GUI->GetScriptInterface()}; JS::RootedValue val(rq.cx); Script::CreateObject(rq, &val); Script::StructuredClone data = Script::WriteStructuredClone(rq, JS::NullHandleValue); g_GUI->OpenChildPage(L"event/page_event.xml", data); - const ScriptInterface& pageScriptInterface = *(g_GUI->GetActiveGUI()->GetScriptInterface()); - ScriptRequest prq(pageScriptInterface); + const Script::Interface& pageScriptInterface = *(g_GUI->GetActiveGUI()->GetScriptInterface()); + Script::Request prq(pageScriptInterface); JS::RootedValue global(prq.cx, prq.globalValue()); int called_value = 0; @@ -153,7 +153,7 @@ public: LoadHotkeys(*configDB); // Load up a test page. - ScriptRequest rq{g_GUI->GetScriptInterface()}; + Script::Request rq{g_GUI->GetScriptInterface()}; JS::RootedValue val(rq.cx); Script::CreateObject(rq, &val); @@ -172,8 +172,8 @@ public: for (SDL_Event& ev : g_VideoMode.m_InputManager.PollEvents()) g_VideoMode.m_InputManager.DispatchEvent(ev); - const ScriptInterface& pageScriptInterface = *(g_GUI->GetActiveGUI()->GetScriptInterface()); - ScriptRequest prq(pageScriptInterface); + const Script::Interface& pageScriptInterface = *(g_GUI->GetActiveGUI()->GetScriptInterface()); + Script::Request prq(pageScriptInterface); JS::RootedValue global(prq.cx, prq.globalValue()); // Ensure that our hotkey state was synchronised with the event itself. @@ -225,16 +225,16 @@ public: static void CloseTopmostPage() { - ScriptRequest rq{g_GUI->GetActiveGUI()->GetScriptInterface()}; + Script::Request rq{g_GUI->GetActiveGUI()->GetScriptInterface()}; JS::RootedValue global{rq.cx, rq.globalValue()}; - TS_ASSERT(ScriptFunction::CallVoid(rq, global, "closePageCallback")); + TS_ASSERT(Script::Function::CallVoid(rq, global, "closePageCallback")); // Check whether promises are settled in the page stack and flush the stack. g_GUI->TickObjects(); } void test_PageRegainedFocusEvent() { - ScriptRequest rq{g_GUI->GetScriptInterface()}; + Script::Request rq{g_GUI->GetScriptInterface()}; const Script::StructuredClone undefined{ Script::WriteStructuredClone(rq, JS::UndefinedHandleValue)}; @@ -261,7 +261,7 @@ public: {false, JS::PromiseState::Fulfilled}, {true, JS::PromiseState::Rejected}}}; - const ScriptRequest rq{g_GUI->GetScriptInterface()}; + const Script::Request rq{g_GUI->GetScriptInterface()}; const Script::StructuredClone undefined{ Script::WriteStructuredClone(rq, JS::UndefinedHandleValue)}; @@ -285,7 +285,7 @@ public: void test_Sequential() { - const ScriptRequest rq{g_GUI->GetScriptInterface()}; + const Script::Request rq{g_GUI->GetScriptInterface()}; const Script::StructuredClone undefined{ Script::WriteStructuredClone(rq, JS::UndefinedHandleValue)}; g_GUI->OpenChildPage(L"sequential/page_sequential.xml", undefined); @@ -298,7 +298,7 @@ public: void test_Result() { - const ScriptRequest rq{g_GUI->GetScriptInterface()}; + const Script::Request rq{g_GUI->GetScriptInterface()}; g_GUI->OpenChildPage(L"Result/page_Result.xml", Script::WriteStructuredClone(rq, JS::FalseHandleValue)); TS_ASSERT(!g_GUI->TickObjects().value()); @@ -310,7 +310,7 @@ public: void test_MultipleRootModules() { - ScriptRequest rq{g_GUI->GetScriptInterface()}; + Script::Request rq{g_GUI->GetScriptInterface()}; TS_ASSERT_THROWS_EQUALS(g_GUI->OpenChildPage( L"multiple_root-modules/page.xml", @@ -320,7 +320,7 @@ public: void test_Await() { - ScriptRequest rq{g_GUI->GetScriptInterface()}; + Script::Request rq{g_GUI->GetScriptInterface()}; TS_ASSERT_THROWS(g_GUI->OpenChildPage(L"await/page.xml", Script::WriteStructuredClone(rq, JS::NullHandleValue)), const std::bad_variant_access&); @@ -328,17 +328,17 @@ public: void test_OpenRequest() { - const ScriptRequest rq{g_GUI->GetScriptInterface()}; + const Script::Request rq{g_GUI->GetScriptInterface()}; g_GUI->OpenChildPage(L"OpenRequest/Root/Page.xml", Script::WriteStructuredClone(rq, JS::UndefinedHandleValue)); TS_ASSERT_EQUALS(g_GUI->GetPageCount(), 2); g_GUI->TickObjects(); - const ScriptRequest pageRq{g_GUI->GetActiveGUI()->GetScriptInterface()}; + const Script::Request pageRq{g_GUI->GetActiveGUI()->GetScriptInterface()}; JS::RootedValue global{pageRq.cx, pageRq.globalValue()}; std::string result; - TS_ASSERT(ScriptFunction::Call(pageRq, global, "closePageCallback", result)); + TS_ASSERT(Script::Function::Call(pageRq, global, "closePageCallback", result)); TS_ASSERT_STR_EQUALS(result, "Entry Continuation"); } diff --git a/source/i18n/L10n.cpp b/source/i18n/L10n.cpp index af2313ee47..3371d277de 100644 --- a/source/i18n/L10n.cpp +++ b/source/i18n/L10n.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -36,7 +36,7 @@ #include "ps/Errors.h" #include "ps/Filesystem.h" #include "ps/GameSetup/GameSetup.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include #include diff --git a/source/i18n/scripting/JSInterface_L10n.cpp b/source/i18n/scripting/JSInterface_L10n.cpp index a25a055afa..f3be7852d5 100644 --- a/source/i18n/scripting/JSInterface_L10n.cpp +++ b/source/i18n/scripting/JSInterface_L10n.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -31,7 +31,7 @@ namespace JS { class CallArgs; } namespace JSI_L10n { -L10n* L10nGetter(const ScriptRequest&, JS::CallArgs&) +L10n* L10nGetter(const Script::Request&, JS::CallArgs&) { if (!g_L10n.IsInitialised()) { @@ -63,21 +63,21 @@ std::string FormatMillisecondsIntoDateStringGMT(UDate milliseconds, const std::s return g_L10n.FormatMillisecondsIntoDateString(milliseconds, formatString, false); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { #define REGISTER_L10N(name) \ - ScriptFunction::Register<&L10n::name, &L10nGetter>(rq, #name); + Script::Function::Register<&L10n::name, &L10nGetter>(rq, #name); #define REGISTER_L10N_FUNC(func, name) \ - ScriptFunction::Register(rq, name); + Script::Function::Register(rq, name); REGISTER_L10N(Translate) REGISTER_L10N(TranslateWithContext) REGISTER_L10N(TranslatePlural) REGISTER_L10N(TranslatePluralWithContext) REGISTER_L10N(TranslateLines) - ScriptFunction::Register<&TranslateArray>(rq, "TranslateArray"); - ScriptFunction::Register<&FormatMillisecondsIntoDateStringLocal>(rq, "FormatMillisecondsIntoDateStringLocal"); - ScriptFunction::Register<&FormatMillisecondsIntoDateStringGMT>(rq, "FormatMillisecondsIntoDateStringGMT"); + Script::Function::Register<&TranslateArray>(rq, "TranslateArray"); + Script::Function::Register<&FormatMillisecondsIntoDateStringLocal>(rq, "FormatMillisecondsIntoDateStringLocal"); + Script::Function::Register<&FormatMillisecondsIntoDateStringGMT>(rq, "FormatMillisecondsIntoDateStringGMT"); REGISTER_L10N(FormatDecimalNumberIntoString) REGISTER_L10N(GetSupportedLocaleBaseNames) diff --git a/source/i18n/scripting/JSInterface_L10n.h b/source/i18n/scripting/JSInterface_L10n.h index fee481e6c8..cb4eed628a 100644 --- a/source/i18n/scripting/JSInterface_L10n.h +++ b/source/i18n/scripting/JSInterface_L10n.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,7 +18,7 @@ #ifndef INCLUDED_JSINTERFACE_L10N #define INCLUDED_JSINTERFACE_L10N -class ScriptRequest; +namespace Script { class Request; } /** * Namespace for the functions of the JavaScript interface for @@ -36,12 +36,12 @@ namespace JSI_L10n * internationalization and localization into the specified JavaScript * context. * - * @param ScriptRequest Script Request where RegisterScriptFunctions() + * @param Script::Request Script Request where RegisterScriptFunctions() * registers the functions. * * @sa GuiScriptingInit() */ - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSINTERFACE_L10N diff --git a/source/lib/self_test.h b/source/lib/self_test.h index 2f69dd92e4..a990b2456c 100644 --- a/source/lib/self_test.h +++ b/source/lib/self_test.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -160,9 +160,9 @@ std::vector ts_make_vector(T* start, size_t size_bytes) for (int j = 0; j < size; ++j) \ TS_ASSERT(!feq(m1._data[j], m2._data[j], epsilon)); -class ScriptInterface; +namespace Script { class Interface; } // Script-based testing setup (defined in test_setup.cpp). Defines TS_* functions. -void ScriptTestSetup(const ScriptInterface&); +void ScriptTestSetup(const Script::Interface&); // Default game data directory // (TODO: game-specific functions like this probably shouldn't be inside lib/, but it's useful diff --git a/source/lobby/XmppClient.cpp b/source/lobby/XmppClient.cpp index e69ec30da4..983528f7b8 100644 --- a/source/lobby/XmppClient.cpp +++ b/source/lobby/XmppClient.cpp @@ -35,9 +35,9 @@ #include "ps/GUID.h" #include "ps/Pyrogenesis.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include @@ -133,7 +133,7 @@ class XmppClient::Impl : public gloox::ConnectionListener, public gloox::MUCRoom { public: // Basic - Impl(const ScriptInterface* scriptInterface, const std::string& sUsername, + Impl(const Script::Interface* scriptInterface, const std::string& sUsername, const std::string& sPassword, const std::string& sRoom, const std::string& sNick, const int historyRequestSize, const bool regOpt); @@ -246,8 +246,8 @@ public: std::vector> m_BoardList; /// Profile data std::vector> m_Profile; - /// ScriptInterface to root the values - const ScriptInterface* m_ScriptInterface; + /// Script::Interface to root the values + const Script::Interface* m_ScriptInterface; /// Queue of messages for the GUI JS::PersistentRootedVector m_GuiMessageQueue; /// Cache of all GUI messages received since the login @@ -260,7 +260,7 @@ public: /** * Construct the XMPP client. * - * @param scriptInterface - ScriptInterface to be used for storing GUI messages. + * @param scriptInterface - Script::Interface to be used for storing GUI messages. * Can be left blank for non-visual applications. * @param sUsername Username to login with of register. * @param sPassword Password to login with or register. @@ -269,14 +269,14 @@ public: * @param historyRequestSize Number of stanzas of room history to request. * @param regOpt If we are just registering or not. */ -XmppClient::XmppClient(const ScriptInterface* scriptInterface, const std::string& username, +XmppClient::XmppClient(const Script::Interface* scriptInterface, const std::string& username, const std::string& password, const std::string& room, const std::string& nick, const int historyRequestSize, bool regOpt) : m_Impl{std::make_unique(scriptInterface, username, password, room, nick, historyRequestSize, regOpt)} {} -XmppClient::Impl::Impl(const ScriptInterface* scriptInterface, const std::string& sUsername, +XmppClient::Impl::Impl(const Script::Interface* scriptInterface, const std::string& sUsername, const std::string& sPassword, const std::string& sRoom, const std::string& sNick, const int historyRequestSize, bool regOpt) : m_server{g_ConfigDB.Get("lobby.server", std::string{})}, @@ -527,7 +527,7 @@ void XmppClient::SendIqGetConnectionData(const std::string& jid, const std::stri * * @param data A JS array of game statistics */ -void XmppClient::SendIqGameReport(const ScriptRequest& rq, JS::HandleValue data) +void XmppClient::SendIqGameReport(const Script::Request& rq, JS::HandleValue data) { gloox::JID echelonJid(m_Impl->m_echelonId); @@ -570,7 +570,7 @@ void XmppClient::SendIqGameReport(const ScriptRequest& rq, JS::HandleValue data) * * @param data A JS array of game attributes */ -void XmppClient::SendIqRegisterGame(const ScriptRequest& rq, JS::HandleValue data) +void XmppClient::SendIqRegisterGame(const Script::Request& rq, JS::HandleValue data) { gloox::JID xpartamuppJid(m_Impl->m_xpartamuppId); @@ -720,7 +720,7 @@ void XmppClient::Impl::handleOOB(const gloox::JID&, const gloox::OOB&) * * @return A JS array containing all known players and their presences */ -JS::Value XmppClient::GUIGetPlayerList(const ScriptRequest& rq) +JS::Value XmppClient::GUIGetPlayerList(const Script::Request& rq) { JS::RootedValueVector players{rq.cx}; @@ -747,7 +747,7 @@ JS::Value XmppClient::GUIGetPlayerList(const ScriptRequest& rq) * * @return A JS array containing all known games */ -JS::Value XmppClient::GUIGetGameList(const ScriptRequest& rq) +JS::Value XmppClient::GUIGetGameList(const Script::Request& rq) { JS::RootedValueVector games{rq.cx}; @@ -774,7 +774,7 @@ JS::Value XmppClient::GUIGetGameList(const ScriptRequest& rq) * * @return A JS array containing all known leaderboard data */ -JS::Value XmppClient::GUIGetBoardList(const ScriptRequest& rq) +JS::Value XmppClient::GUIGetBoardList(const Script::Request& rq) { JS::RootedValueVector boardList{rq.cx}; @@ -799,7 +799,7 @@ JS::Value XmppClient::GUIGetBoardList(const ScriptRequest& rq) * * @return A JS array containing the specific user's profile data */ -JS::Value XmppClient::GUIGetProfile(const ScriptRequest& rq) +JS::Value XmppClient::GUIGetProfile(const Script::Request& rq) { JS::RootedValueVector profileData{rq.cx}; @@ -823,12 +823,12 @@ JS::Value XmppClient::GUIGetProfile(const ScriptRequest& rq) * Message interfaces * *****************************************************/ -void SetGUIMessageProperty(const ScriptRequest&, JS::HandleObject /*messageObj*/) +void SetGUIMessageProperty(const Script::Request&, JS::HandleObject /*messageObj*/) { } template -void SetGUIMessageProperty(const ScriptRequest& rq, JS::HandleObject messageObj, const std::string& propertyName, const T& propertyValue, Args const&... args) +void SetGUIMessageProperty(const Script::Request& rq, JS::HandleObject messageObj, const std::string& propertyName, const T& propertyValue, Args const&... args) { JS::RootedValue scriptPropertyValue(rq.cx); Script::ToJSVal(rq, &scriptPropertyValue, propertyValue); @@ -845,7 +845,7 @@ void XmppClient::Impl::CreateGUIMessage( { if (!m_ScriptInterface) return; - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedValue message(rq.cx); Script::CreateObject( rq, @@ -872,12 +872,12 @@ bool XmppClient::GuiPollHasPlayerListUpdate() return std::exchange(m_Impl->m_PlayerMapUpdate, false); } -JS::Value XmppClient::GuiPollNewMessages(const ScriptInterface& guiInterface) +JS::Value XmppClient::GuiPollNewMessages(const Script::Interface& guiInterface) { if ((isConnected() && !m_Impl->m_initialLoadComplete) || m_Impl->m_GuiMessageQueue.empty()) return JS::UndefinedValue(); - ScriptRequest rq(m_Impl->m_ScriptInterface); + Script::Request rq(m_Impl->m_ScriptInterface); // Optimize for batch message processing that is more // performance demanding than processing a lone message. @@ -919,12 +919,12 @@ JS::Value XmppClient::GuiPollNewMessages(const ScriptInterface& guiInterface) JS::RootedValue{rq.cx, JS::ObjectValue(*JS::NewArrayObject(rq.cx, messages))}); } -JS::Value XmppClient::GuiPollHistoricMessages(const ScriptInterface& guiInterface) +JS::Value XmppClient::GuiPollHistoricMessages(const Script::Interface& guiInterface) { if (m_Impl->m_HistoricGuiMessages.empty()) return JS::UndefinedValue(); - ScriptRequest rq(m_Impl->m_ScriptInterface); + Script::Request rq(m_Impl->m_ScriptInterface); JS::RootedValueVector messages{rq.cx}; diff --git a/source/lobby/XmppClient.h b/source/lobby/XmppClient.h index f18b60fb84..eae5b92033 100644 --- a/source/lobby/XmppClient.h +++ b/source/lobby/XmppClient.h @@ -23,13 +23,13 @@ #include #include -class ScriptInterface; -class ScriptRequest; +namespace Script { class Interface; } +namespace Script { class Request; } class XmppClient { public: - XmppClient(const ScriptInterface* scriptInterface, const std::string& username, + XmppClient(const Script::Interface* scriptInterface, const std::string& username, const std::string& password, const std::string& room, const std::string& nick, const int historyRequestSize = 0, bool regOpt = false); ~XmppClient(); @@ -40,8 +40,8 @@ public: void recv(); void SendIqGetBoardList(); void SendIqGetProfile(const std::string& player); - void SendIqGameReport(const ScriptRequest& rq, JS::HandleValue data); - void SendIqRegisterGame(const ScriptRequest& rq, JS::HandleValue data); + void SendIqGameReport(const Script::Request& rq, JS::HandleValue data); + void SendIqRegisterGame(const Script::Request& rq, JS::HandleValue data); void SendIqGetConnectionData(const std::string& jid, const std::string& password, const std::string& clientSalt, bool localIP); void SendIqUnregisterGame(); @@ -59,13 +59,13 @@ public: const char* GetRole(const std::string& nickname); std::wstring GetRating(const std::string& nickname); const std::wstring& GetSubject(); - JS::Value GUIGetPlayerList(const ScriptRequest& rq); - JS::Value GUIGetGameList(const ScriptRequest& rq); - JS::Value GUIGetBoardList(const ScriptRequest& rq); - JS::Value GUIGetProfile(const ScriptRequest& rq); + JS::Value GUIGetPlayerList(const Script::Request& rq); + JS::Value GUIGetGameList(const Script::Request& rq); + JS::Value GUIGetBoardList(const Script::Request& rq); + JS::Value GUIGetProfile(const Script::Request& rq); - JS::Value GuiPollNewMessages(const ScriptInterface& guiInterface); - JS::Value GuiPollHistoricMessages(const ScriptInterface& guiInterface); + JS::Value GuiPollNewMessages(const Script::Interface& guiInterface); + JS::Value GuiPollHistoricMessages(const Script::Interface& guiInterface); bool GuiPollHasPlayerListUpdate(); void SendMUCMessage(const std::string& message); diff --git a/source/lobby/scripting/GlooxScriptConversions.cpp b/source/lobby/scripting/GlooxScriptConversions.cpp index 4fc62e8fd6..0ba75fac65 100644 --- a/source/lobby/scripting/GlooxScriptConversions.cpp +++ b/source/lobby/scripting/GlooxScriptConversions.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,40 +22,40 @@ #include "lib/external_libraries/gloox.h" #include "lib/utf8.h" #include "lobby/GlooxConversion.h" -#include "scriptinterface/ScriptConversions.h" +#include "scriptinterface/Conversions.h" #include #include #include -class ScriptRequest; +namespace Script { class Request; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const gloox::Presence::PresenceType& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const gloox::Presence::PresenceType& val) { ToJSVal(rq, ret, GetPresenceString(val)); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const gloox::MUCRoomRole& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const gloox::MUCRoomRole& val) { ToJSVal(rq, ret, GetRoleString(val)); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const gloox::StanzaError& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const gloox::StanzaError& val) { ToJSVal(rq, ret, wstring_from_utf8(StanzaErrorToString(val))); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const gloox::ConnectionError& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const gloox::ConnectionError& val) { ToJSVal(rq, ret, wstring_from_utf8(ConnectionErrorToString(val))); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const gloox::RegistrationResult& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const gloox::RegistrationResult& val) { ToJSVal(rq, ret, wstring_from_utf8(RegistrationResultToString(val))); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const gloox::CertStatus& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const gloox::CertStatus& val) { ToJSVal(rq, ret, wstring_from_utf8(CertificateErrorToString(val))); } diff --git a/source/lobby/scripting/JSInterface_Lobby.cpp b/source/lobby/scripting/JSInterface_Lobby.cpp index 5259119f7b..714613ee9e 100644 --- a/source/lobby/scripting/JSInterface_Lobby.cpp +++ b/source/lobby/scripting/JSInterface_Lobby.cpp @@ -31,7 +31,7 @@ #include "ps/CStr.h" #include "ps/Util.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptExceptions.h" +#include "scriptinterface/Exceptions.h" #include "third_party/encryption/pkcs5_pbkdf2.h" #include @@ -41,8 +41,8 @@ #include #include -class ScriptInterface; namespace JS { class CallArgs; } +namespace Script { class Interface; } namespace JSI_Lobby { @@ -107,7 +107,7 @@ void StopXmppClient() //////////////////////////////////////////////// //////////////////////////////////////////////// -XmppClient* XmppGetter(const ScriptRequest&, JS::CallArgs&) +XmppClient* XmppGetter(const Script::Request&, JS::CallArgs&) { if (!g_XmppClient) { @@ -117,7 +117,7 @@ XmppClient* XmppGetter(const ScriptRequest&, JS::CallArgs&) return g_XmppClient; } -void SendRegisterGame(const ScriptInterface& scriptInterface, JS::HandleValue data) +void SendRegisterGame(const Script::Interface& scriptInterface, JS::HandleValue data) { if (!g_XmppClient) throw std::logic_error{"Cannot call SendRegisterGame without an initialized XmppClient!"}; @@ -133,7 +133,7 @@ void SendRegisterGame(const ScriptInterface& scriptInterface, JS::HandleValue da } // Unlike other functions, this one just returns Undefined if XmppClient isn't initialised. -JS::Value GuiPollNewMessages(const ScriptInterface& scriptInterface) +JS::Value GuiPollNewMessages(const Script::Interface& scriptInterface) { if (!g_XmppClient) return JS::UndefinedValue(); @@ -186,18 +186,18 @@ std::string EncryptPassword(const std::string& password, const std::string& user #endif -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { // Lobby functions - ScriptFunction::Register<&HasXmppClient>(rq, "HasXmppClient"); - ScriptFunction::Register<&SetRankedGame>(rq, "SetRankedGame"); + Script::Function::Register<&HasXmppClient>(rq, "HasXmppClient"); + Script::Function::Register<&SetRankedGame>(rq, "SetRankedGame"); #if CONFIG2_LOBBY // Allow the lobby to be disabled - ScriptFunction::Register<&StartXmppClient>(rq, "StartXmppClient"); - ScriptFunction::Register<&StartRegisterXmppClient>(rq, "StartRegisterXmppClient"); - ScriptFunction::Register<&StopXmppClient>(rq, "StopXmppClient"); + Script::Function::Register<&StartXmppClient>(rq, "StartXmppClient"); + Script::Function::Register<&StartRegisterXmppClient>(rq, "StartRegisterXmppClient"); + Script::Function::Register<&StopXmppClient>(rq, "StopXmppClient"); #define REGISTER_XMPP(func, name) \ - ScriptFunction::Register<&XmppClient::func, &XmppGetter>(rq, name) + Script::Function::Register<&XmppClient::func, &XmppGetter>(rq, name) REGISTER_XMPP(connect, "ConnectXmppClient"); REGISTER_XMPP(disconnect, "DisconnectXmppClient"); @@ -205,7 +205,7 @@ void RegisterScriptFunctions(const ScriptRequest& rq) REGISTER_XMPP(SendIqGetBoardList, "SendGetBoardList"); REGISTER_XMPP(SendIqGetProfile, "SendGetProfile"); REGISTER_XMPP(SendIqGameReport, "SendGameReport"); - ScriptFunction::Register<&SendRegisterGame>(rq, "SendRegisterGame"); + Script::Function::Register<&SendRegisterGame>(rq, "SendRegisterGame"); REGISTER_XMPP(SendIqUnregisterGame, "SendUnregisterGame"); REGISTER_XMPP(SendIqChangeStateGame, "SendChangeStateGame"); REGISTER_XMPP(GUIGetPlayerList, "GetPlayerList"); @@ -213,7 +213,7 @@ void RegisterScriptFunctions(const ScriptRequest& rq) REGISTER_XMPP(GUIGetBoardList, "GetBoardList"); REGISTER_XMPP(GUIGetProfile, "GetProfile"); - ScriptFunction::Register<&GuiPollNewMessages>(rq, "LobbyGuiPollNewMessages"); + Script::Function::Register<&GuiPollNewMessages>(rq, "LobbyGuiPollNewMessages"); REGISTER_XMPP(GuiPollHistoricMessages, "LobbyGuiPollHistoricMessages"); REGISTER_XMPP(GuiPollHasPlayerListUpdate, "LobbyGuiPollHasPlayerListUpdate"); REGISTER_XMPP(SendMUCMessage, "LobbySendMessage"); @@ -231,7 +231,7 @@ void RegisterScriptFunctions(const ScriptRequest& rq) REGISTER_XMPP(GetSubject, "LobbyGetRoomSubject"); #undef REGISTER_XMPP - ScriptFunction::Register<&EncryptPassword>(rq, "EncryptPassword"); + Script::Function::Register<&EncryptPassword>(rq, "EncryptPassword"); #endif // CONFIG2_LOBBY } } diff --git a/source/lobby/scripting/JSInterface_Lobby.h b/source/lobby/scripting/JSInterface_Lobby.h index 5eba1ecc91..b9c88c76d5 100644 --- a/source/lobby/scripting/JSInterface_Lobby.h +++ b/source/lobby/scripting/JSInterface_Lobby.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2019 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_LOBBY #define INCLUDED_JSI_LOBBY -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Lobby { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_LOBBY diff --git a/source/main.cpp b/source/main.cpp index 54a715b37a..7f1ef3da25 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -81,11 +81,11 @@ that of Atlas depending on commandline parameters. #include "renderer/Renderer.h" #include "rlinterface/RLInterface.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptEngine.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Engine.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/system/TurnManager.h" #include "soundmanager/ISoundManager.h" @@ -208,7 +208,7 @@ static Input::Reaction MainInputHandler(const SDL_Event& ev) else { LOGMESSAGE("Installed mod %s", installer.GetInstalledMods().front()); - ScriptInterface modInterface("Engine", "Mod", g_ScriptContext); + Script::Interface modInterface("Engine", "Mod", g_ScriptContext); g_Mods.UpdateAvailableMods(modInterface); RestartEngine(); } @@ -242,7 +242,7 @@ static Input::Reaction MainInputHandler(const SDL_Event& ev) // dispatch all pending events to the various receivers. static void PumpEvents() { - ScriptRequest rq(g_GUI->GetScriptInterface()); + Script::Request rq(g_GUI->GetScriptInterface()); PROFILE3("dispatch events"); @@ -586,7 +586,7 @@ static void RunGameOrAtlas(const std::span argv) // We need to initialize SpiderMonkey and libxml2 in the main thread before // any thread uses them. So initialize them here before we might run Atlas. - ScriptEngine scriptEngine; + Script::Engine scriptEngine; CXeromycesEngine xeromycesEngine; // Initialise the global task manager at this point (JS & Profiler2 are set up). @@ -689,7 +689,7 @@ static void RunGameOrAtlas(const std::span argv) installedMods = installer.GetInstalledMods(); - ScriptInterface modInterface("Engine", "Mod", g_ScriptContext); + Script::Interface modInterface("Engine", "Mod", g_ScriptContext); g_Mods.UpdateAvailableMods(modInterface); } @@ -714,7 +714,7 @@ static void RunGameOrAtlas(const std::span argv) ~VisualData() = default; private: - ScriptInterface scriptInterface{"Engine", "gui", *g_ScriptContext}; + Script::Interface scriptInterface{"Engine", "gui", *g_ScriptContext}; std::unique_ptr inputHandlers; Input::Handler mainInputHandler{ g_VideoMode.m_InputManager, Input::Slot::PRIMARY, MainInputHandler}; diff --git a/source/network/NetClient.cpp b/source/network/NetClient.cpp index 0d98cf6700..0bb39d39d8 100644 --- a/source/network/NetClient.cpp +++ b/source/network/NetClient.cpp @@ -39,8 +39,8 @@ #include "ps/Profile.h" #include "ps/Threading.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" #include "simulation2/Simulation2.h" #include "simulation2/system/TurnManager.h" @@ -364,17 +364,17 @@ void CNetClient::CheckServerConnection() } } -JSObject* CNetClient::GetNextGUIMessage(const ScriptInterface& guiInterface) +JSObject* CNetClient::GetNextGUIMessage(const Script::Interface& guiInterface) { Unregister(nullptr); - const ScriptRequest rq{guiInterface}; + const Script::Request rq{guiInterface}; m_GuiMessagePoll.emplace(GuiPollData{guiInterface, {rq.cx, JS::NewPromiseObject(rq.cx, nullptr)}}); FetchMessage(); return m_GuiMessagePoll.value().promise; } -void CNetClient::Unregister(const ScriptInterface* guiInterface) +void CNetClient::Unregister(const Script::Interface* guiInterface) { if (!m_GuiMessagePoll.has_value() || (guiInterface && &m_GuiMessagePoll.value().interface != guiInterface)) @@ -382,7 +382,7 @@ void CNetClient::Unregister(const ScriptInterface* guiInterface) return; } auto& [interface, promise] = m_GuiMessagePoll.value(); - const ScriptRequest oldRq{interface}; + const Script::Request oldRq{interface}; JS::ResolvePromise(oldRq.cx, promise, JS::UndefinedHandleValue); m_GuiMessagePoll.reset(); } @@ -395,7 +395,7 @@ void CNetClient::FetchMessage() return; } - const ScriptRequest rq{m_GuiMessagePoll.value().interface}; + const Script::Request rq{m_GuiMessagePoll.value().interface}; JS::RootedValue message{rq.cx}; Script::ReadStructuredClone(rq, std::move(m_GuiMessageQueue.front()), &message); m_GuiMessageQueue.pop_front(); @@ -405,7 +405,7 @@ void CNetClient::FetchMessage() std::string CNetClient::TestReadGuiMessages() { - ScriptRequest rq(GetScriptInterface()); + Script::Request rq(GetScriptInterface()); std::string r; while (true) @@ -422,14 +422,14 @@ std::string CNetClient::TestReadGuiMessages() return r; } -const ScriptInterface& CNetClient::GetScriptInterface() +const Script::Interface& CNetClient::GetScriptInterface() { return m_Game->GetSimulation2()->GetScriptInterface(); } void CNetClient::PostPlayerAssignmentsToScript() { - ScriptRequest rq(GetScriptInterface()); + Script::Request rq(GetScriptInterface()); JS::RootedValue newAssignments(rq.cx); Script::CreateObject(rq, &newAssignments); @@ -491,7 +491,7 @@ void CNetClient::HandleDisconnect(u32 reason) SetCurrState(NCS_UNCONNECTED); } -void CNetClient::SendGameSetupMessage(JS::MutableHandleValue attrs, const ScriptInterface& scriptInterface) +void CNetClient::SendGameSetupMessage(JS::MutableHandleValue attrs, const Script::Interface& scriptInterface) { CGameSetupMessage gameSetup(scriptInterface); gameSetup.m_Data = attrs; @@ -836,8 +836,8 @@ bool CNetClient::OnGameStart(CNetClient* client, CFsmEvent* event) CGameStartMessage* message = static_cast(event->GetParamRef()); - const ScriptInterface& scriptInterface{client->m_Game->GetSimulation2()->GetScriptInterface()}; - ScriptRequest rq{scriptInterface}; + const Script::Interface& scriptInterface{client->m_Game->GetSimulation2()->GetScriptInterface()}; + Script::Request rq{scriptInterface}; JS::RootedValue initAttribs{rq.cx}; Script::ParseJSON(rq, message->m_InitAttributes, &initAttribs); @@ -851,8 +851,8 @@ bool CNetClient::OnSavedGameStart(CNetClient* client, CFsmEvent* e ENSURE(event->GetType() == static_cast(NMT_SAVED_GAME_START)); CGameSavedStartMessage* message{static_cast(event->GetParamRef())}; - const ScriptInterface& scriptInterface{client->m_Game->GetSimulation2()->GetScriptInterface()}; - ScriptRequest rq{scriptInterface}; + const Script::Interface& scriptInterface{client->m_Game->GetSimulation2()->GetScriptInterface()}; + Script::Request rq{scriptInterface}; const std::shared_ptr initAttribs{std::make_shared(rq.cx)}; Script::ParseJSON(rq, message->m_InitAttributes, &*initAttribs); @@ -1058,8 +1058,8 @@ bool CNetClient::OnFlare(CNetClient* client, CFsmEvent* event) CFlareMessage* message = static_cast(event->GetParamRef()); - const ScriptInterface& scriptInterface = client->m_Game->GetSimulation2()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = client->m_Game->GetSimulation2()->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue position(rq.cx); Script::CreateObject( rq, &position, diff --git a/source/network/NetClient.h b/source/network/NetClient.h index 730db8b61c..c4cfb087eb 100644 --- a/source/network/NetClient.h +++ b/source/network/NetClient.h @@ -26,7 +26,7 @@ #include "network/NetMessage.h" #include "ps/CStr.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include @@ -43,9 +43,10 @@ class CGame; class CNetClientSession; class CNetClientTurnManager; class JSTracer; -class ScriptInterface; class XmppClient; +namespace Script { class Interface; } + typedef struct _ENetHost ENetHost; // NetClient session FSM states @@ -130,7 +131,7 @@ public: /** * Retrieves the next queued GUI message, and removes it from the queue. * The returned value is in the JS context of the provided - * @c ScriptInterface. + * @c Script::Interface. * * This is the only mechanism for the networking code to send messages to * the GUI. @@ -141,13 +142,13 @@ public: * * @return a promise resolving to the next message. */ - JSObject* GetNextGUIMessage(const ScriptInterface& guiInterface); + JSObject* GetNextGUIMessage(const Script::Interface& guiInterface); /** - * Has to be called bevore the @c ScriptInterface gets destroied so that + * Has to be called bevore the @c Script::Interface gets destroied so that * no future messages are sent to it. */ - void Unregister(const ScriptInterface* guiInterface); + void Unregister(const Script::Interface* guiInterface); /** * Add a message to the queue, to be read by GuiPoll. @@ -156,7 +157,7 @@ public: template void PushGuiMessage(Args const&... args) { - ScriptRequest rq(GetScriptInterface()); + Script::Request rq(GetScriptInterface()); JS::RootedValue message(rq.cx); Script::CreateObject(rq, &message, args...); @@ -173,7 +174,7 @@ public: * Get the script interface associated with this network client, * which is equivalent to the one used by the CGame in the constructor. */ - const ScriptInterface& GetScriptInterface(); + const Script::Interface& GetScriptInterface(); /** * Send a message to the server. @@ -203,7 +204,7 @@ public: */ void LoadFinished(); - void SendGameSetupMessage(JS::MutableHandleValue attrs, const ScriptInterface& scriptInterface); + void SendGameSetupMessage(JS::MutableHandleValue attrs, const Script::Interface& scriptInterface); void SendAssignPlayerMessage(const int playerID, const CStr& guid); @@ -351,7 +352,7 @@ private: struct GuiPollData { - const ScriptInterface& interface; + const Script::Interface& interface; /** * In the context of interface. * When the promise is pending @see Poll should fill it with a message. diff --git a/source/network/NetMessage.cpp b/source/network/NetMessage.cpp index f489e6f6b7..31bdeb9be8 100644 --- a/source/network/NetMessage.cpp +++ b/source/network/NetMessage.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -93,7 +93,7 @@ CStr CNetMessage::ToString() const CNetMessage* CNetMessageFactory::CreateMessage(const void* pData, size_t dataSize, - const ScriptInterface& scriptInterface) + const Script::Interface& scriptInterface) { CNetMessage* pNewMessage = NULL; CNetMessage header; diff --git a/source/network/NetMessage.h b/source/network/NetMessage.h index d555a2bc4b..effb0bfb7e 100644 --- a/source/network/NetMessage.h +++ b/source/network/NetMessage.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -28,7 +28,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } // We need the enum from NetMessages.h, but we can't create any classes in // NetMessages.h, since they in turn require CNetMessage to be defined @@ -113,7 +113,7 @@ public: * @param scriptInterface Script instance to use when constructing scripted messages * @return The new message created */ - static CNetMessage* CreateMessage(const void* pData, size_t dataSize, const ScriptInterface& scriptInterface); + static CNetMessage* CreateMessage(const void* pData, size_t dataSize, const Script::Interface& scriptInterface); }; /** @@ -123,8 +123,8 @@ public: class CSimulationMessage : public CNetMessage { public: - CSimulationMessage(const ScriptInterface& scriptInterface); - CSimulationMessage(const ScriptInterface& scriptInterface, u32 client, i32 player, u32 turn, JS::HandleValue data); + CSimulationMessage(const Script::Interface& scriptInterface); + CSimulationMessage(const Script::Interface& scriptInterface, u32 client, i32 player, u32 turn, JS::HandleValue data); /** The compiler can't create a copy constructor because of the PersistentRooted member, * so we have to write it manually. @@ -142,7 +142,7 @@ public: u32 m_Turn; JS::PersistentRooted m_Data; private: - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; }; /** @@ -152,8 +152,8 @@ class CGameSetupMessage : public CNetMessage { NONCOPYABLE(CGameSetupMessage); public: - CGameSetupMessage(const ScriptInterface& scriptInterface); - CGameSetupMessage(const ScriptInterface& scriptInterface, JS::HandleValue data); + CGameSetupMessage(const Script::Interface& scriptInterface); + CGameSetupMessage(const Script::Interface& scriptInterface, JS::HandleValue data); virtual u8* Serialize(u8* pBuffer) const; virtual const u8* Deserialize(const u8* pStart, const u8* pEnd); virtual size_t GetSerializedLength() const; @@ -161,7 +161,7 @@ public: JS::PersistentRootedValue m_Data; private: - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; }; // This time, the classes are created diff --git a/source/network/NetMessageSim.cpp b/source/network/NetMessageSim.cpp index 098593206c..76d1d5e836 100644 --- a/source/network/NetMessageSim.cpp +++ b/source/network/NetMessageSim.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -24,7 +24,7 @@ #include "network/NetMessage.h" #include "ps/CStr.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/serialization/BinarySerializer.h" #include "simulation2/serialization/StdDeserializer.h" #include "simulation2/serialization/StdSerializer.h" @@ -36,7 +36,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } class CBufferBinarySerializerImpl { @@ -68,7 +68,7 @@ public: class CBufferBinarySerializer : public CBinarySerializer { public: - CBufferBinarySerializer(const ScriptInterface& scriptInterface, u8* buffer) : + CBufferBinarySerializer(const Script::Interface& scriptInterface, u8* buffer) : CBinarySerializer(scriptInterface, buffer) { } @@ -105,7 +105,7 @@ public: class CLengthBinarySerializer : public CBinarySerializer { public: - CLengthBinarySerializer(const ScriptInterface& scriptInterface) : + CLengthBinarySerializer(const Script::Interface& scriptInterface) : CBinarySerializer(scriptInterface) { } @@ -116,18 +116,18 @@ public: } }; -CSimulationMessage::CSimulationMessage(const ScriptInterface& scriptInterface) : +CSimulationMessage::CSimulationMessage(const Script::Interface& scriptInterface) : CNetMessage(NMT_SIMULATION_COMMAND), m_ScriptInterface(scriptInterface) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); m_Data.init(rq.cx); } -CSimulationMessage::CSimulationMessage(const ScriptInterface& scriptInterface, u32 client, i32 player, u32 turn, JS::HandleValue data) : +CSimulationMessage::CSimulationMessage(const Script::Interface& scriptInterface, u32 client, i32 player, u32 turn, JS::HandleValue data) : CNetMessage(NMT_SIMULATION_COMMAND), m_ScriptInterface(scriptInterface), m_Client(client), m_Player(player), m_Turn(turn) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); m_Data.init(rq.cx, data); } @@ -138,7 +138,7 @@ CSimulationMessage::CSimulationMessage(const CSimulationMessage& orig) : m_Turn(orig.m_Turn), CNetMessage(orig) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); m_Data.init(rq.cx, orig.m_Data); } @@ -187,7 +187,7 @@ size_t CSimulationMessage::GetSerializedLength() const CStr CSimulationMessage::ToString() const { - std::string source = Script::ToString(ScriptRequest(m_ScriptInterface), const_cast(&m_Data)); + std::string source = Script::ToString(Script::Request(m_ScriptInterface), const_cast(&m_Data)); std::stringstream stream; stream << "CSimulationMessage { m_Client: " << m_Client << ", m_Player: " << m_Player << ", m_Turn: " << m_Turn << ", m_Data: " << source << " }"; @@ -195,17 +195,17 @@ CStr CSimulationMessage::ToString() const } -CGameSetupMessage::CGameSetupMessage(const ScriptInterface& scriptInterface) : +CGameSetupMessage::CGameSetupMessage(const Script::Interface& scriptInterface) : CNetMessage(NMT_GAME_SETUP), m_ScriptInterface(scriptInterface) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); m_Data.init(rq.cx); } -CGameSetupMessage::CGameSetupMessage(const ScriptInterface& scriptInterface, JS::HandleValue data) : +CGameSetupMessage::CGameSetupMessage(const Script::Interface& scriptInterface, JS::HandleValue data) : CNetMessage(NMT_GAME_SETUP), m_ScriptInterface(scriptInterface) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); m_Data.init(rq.cx, data); } @@ -237,7 +237,7 @@ size_t CGameSetupMessage::GetSerializedLength() const CStr CGameSetupMessage::ToString() const { - std::string source = Script::ToString(ScriptRequest(m_ScriptInterface), const_cast(&m_Data)); + std::string source = Script::ToString(Script::Request(m_ScriptInterface), const_cast(&m_Data)); std::stringstream stream; stream << "CGameSetupMessage { m_Data: " << source << " }"; diff --git a/source/network/NetServer.cpp b/source/network/NetServer.cpp index 378bd08304..dba9c3e9a8 100644 --- a/source/network/NetServer.cpp +++ b/source/network/NetServer.cpp @@ -46,9 +46,9 @@ #include "ps/algorithm.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/system/TurnManager.h" #include @@ -373,14 +373,14 @@ void CNetServerWorker::Run(const std::string& initAttributes) // The script context uses the profiler and therefore the thread must be registered before the context is created g_Profiler2.RegisterCurrentThread("Net server"); - // We create a new ScriptContext for this network thread, with a single ScriptInterface. - ScriptContext netServerContext; - m_ScriptInterface = new ScriptInterface("Engine", "Net server", netServerContext); + // We create a new Script::Context for this network thread, with a single Script::Interface. + Script::Context netServerContext; + m_ScriptInterface = new Script::Interface("Engine", "Net server", netServerContext); m_InitAttributes.init(m_ScriptInterface->GetGeneralJSContext(), JS::UndefinedValue()); if (!initAttributes.empty()) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedValue gameAttributesVal(rq.cx); Script::ParseJSON(rq, std::move(initAttributes), &gameAttributesVal); m_InitAttributes = gameAttributesVal; @@ -409,7 +409,7 @@ bool CNetServerWorker::RunStep() m_ScriptInterface->GetContext().MaybeIncrementalGC(); - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); std::vector newStartGame; std::vector> newLobbyAuths; @@ -845,7 +845,7 @@ void CNetServerWorker::SendPlayerAssignments() Multicast(&message, { NSS_PREGAME, NSS_JOIN_SYNCING, NSS_INGAME }); } -const ScriptInterface& CNetServerWorker::GetScriptInterface() +const Script::Interface& CNetServerWorker::GetScriptInterface() { return *m_ScriptInterface; } @@ -1135,7 +1135,7 @@ bool CNetServerWorker::OnAuthenticate(CNetServerSession* session, CFsmEventSendMessage(&message); }); @@ -1154,8 +1154,8 @@ bool CNetServerWorker::OnSimulationCommand(CNetServerSession* session, CFsmEvent // Ignore messages sent by one player on behalf of another player // unless cheating is enabled bool cheatsEnabled = false; - const ScriptInterface& scriptInterface = server.GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = server.GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue settings(rq.cx); Script::GetProperty(rq, server.m_InitAttributes, "settings", &settings); if (Script::HasProperty(rq, settings, "CheatsEnabled")) @@ -1576,7 +1576,7 @@ void CNetServerWorker::PreStartGame(const CStr& initAttribs) SendPlayerAssignments(); // Update init attributes. They should no longer change. - Script::ParseJSON(ScriptRequest(m_ScriptInterface), initAttribs, &m_InitAttributes); + Script::ParseJSON(Script::Request(m_ScriptInterface), initAttribs, &m_InitAttributes); } void CNetServerWorker::StartGame(const CStr& initAttribs) diff --git a/source/network/NetServer.h b/source/network/NetServer.h index 50404f707c..3f8577870f 100644 --- a/source/network/NetServer.h +++ b/source/network/NetServer.h @@ -42,8 +42,8 @@ class CNetServerTurnManager; class CNetStatsTable; class CPlayerAssignmentMessage; class CSimulationMessage; -class ScriptInterface; -class ScriptRequest; +namespace Script { class Interface; } +namespace Script { class Request; } template class CFsmEvent; enum NetServerState @@ -176,7 +176,7 @@ private: /** * Get the script context used for init attributes. */ - const ScriptInterface& GetScriptInterface(); + const Script::Interface& GetScriptInterface(); /** * Set the turn length to a fixed value. @@ -242,7 +242,7 @@ private: * (TODO: we shouldn't bother deserializing (except for debug printing of messages), * we should just forward messages blindly and efficiently.) */ - ScriptInterface* m_ScriptInterface{nullptr}; + Script::Interface* m_ScriptInterface{nullptr}; PlayerAssignmentMap m_PlayerAssignments; diff --git a/source/network/scripting/JSInterface_Network.cpp b/source/network/scripting/JSInterface_Network.cpp index 44ded6ab34..83cd27d970 100644 --- a/source/network/scripting/JSInterface_Network.cpp +++ b/source/network/scripting/JSInterface_Network.cpp @@ -36,8 +36,8 @@ #include "ps/SavedGame.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include @@ -51,7 +51,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } namespace JSI_Network { @@ -159,7 +159,7 @@ CStr GetPlayerGUID() return g_NetClient->GetGUID(); } -JS::Value PollNetworkClient(const ScriptInterface& guiInterface) +JS::Value PollNetworkClient(const Script::Interface& guiInterface) { if (!g_NetClient) throw std::logic_error{"Network client not present"}; @@ -167,12 +167,12 @@ JS::Value PollNetworkClient(const ScriptInterface& guiInterface) return JS::ObjectValue(*g_NetClient->GetNextGUIMessage(guiInterface)); } -void SendGameSetupMessage(const ScriptInterface& scriptInterface, JS::HandleValue attribs1) +void SendGameSetupMessage(const Script::Interface& scriptInterface, JS::HandleValue attribs1) { ENSURE(g_NetClient); // TODO: This is a workaround because we need to pass a MutableHandle to a JSAPI functions somewhere (with no obvious reason). - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue attribs(rq.cx, attribs1); g_NetClient->SendGameSetupMessage(&attribs, scriptInterface); @@ -192,7 +192,7 @@ void KickPlayer(const CStrW& playerName, bool ban) g_NetClient->SendKickPlayerMessage(playerName, ban); } -void SendNetworkChat(const ScriptRequest& rq, const CStrW& message, JS::HandleValue handle) +void SendNetworkChat(const Script::Request& rq, const CStrW& message, JS::HandleValue handle) { ENSURE(g_NetClient); @@ -227,11 +227,11 @@ void ClearAllPlayerReady () g_NetClient->SendClearAllReadyMessage(); } -void StartNetworkGame(const ScriptInterface& scriptInterface, JS::HandleValue savegame, JS::HandleValue attribs1) +void StartNetworkGame(const Script::Interface& scriptInterface, JS::HandleValue savegame, JS::HandleValue attribs1) { ENSURE(g_NetClient); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue attribs(rq.cx, attribs1); std::string attributesAsString{Script::StringifyJSON(rq, &attribs)}; @@ -267,7 +267,7 @@ void SendNetworkFlare(JS::HandleValue position) { ENSURE(g_NetClient); - ScriptRequest rq(g_NetClient->GetScriptInterface()); + Script::Request rq(g_NetClient->GetScriptInterface()); ENSURE(position.isObject()); JS::RootedObject positionObj(rq.cx, &position.toObject()); JS::RootedValue positionX(rq.cx); @@ -286,26 +286,26 @@ void SendNetworkFlare(JS::HandleValue position) ); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&GetDefaultPort>(rq, "GetDefaultPort"); - ScriptFunction::Register<&IsNetController>(rq, "IsNetController"); - ScriptFunction::Register<&HasNetServer>(rq, "HasNetServer"); - ScriptFunction::Register<&HasNetClient>(rq, "HasNetClient"); - ScriptFunction::Register<&StartNetworkHost>(rq, "StartNetworkHost"); - ScriptFunction::Register<&StartNetworkJoin>(rq, "StartNetworkJoin"); - ScriptFunction::Register<&StartNetworkJoinLobby>(rq, "StartNetworkJoinLobby"); - ScriptFunction::Register<&DisconnectNetworkGame>(rq, "DisconnectNetworkGame"); - ScriptFunction::Register<&GetPlayerGUID>(rq, "GetPlayerGUID"); - ScriptFunction::Register<&PollNetworkClient>(rq, "PollNetworkClient"); - ScriptFunction::Register<&SendGameSetupMessage>(rq, "SendGameSetupMessage"); - ScriptFunction::Register<&AssignNetworkPlayer>(rq, "AssignNetworkPlayer"); - ScriptFunction::Register<&KickPlayer>(rq, "KickPlayer"); - ScriptFunction::Register<&SendNetworkChat>(rq, "SendNetworkChat"); - ScriptFunction::Register<&SendNetworkReady>(rq, "SendNetworkReady"); - ScriptFunction::Register<&ClearAllPlayerReady>(rq, "ClearAllPlayerReady"); - ScriptFunction::Register<&StartNetworkGame>(rq, "StartNetworkGame"); - ScriptFunction::Register<&SetTurnLength>(rq, "SetTurnLength"); - ScriptFunction::Register<&SendNetworkFlare>(rq, "SendNetworkFlare"); + Script::Function::Register<&GetDefaultPort>(rq, "GetDefaultPort"); + Script::Function::Register<&IsNetController>(rq, "IsNetController"); + Script::Function::Register<&HasNetServer>(rq, "HasNetServer"); + Script::Function::Register<&HasNetClient>(rq, "HasNetClient"); + Script::Function::Register<&StartNetworkHost>(rq, "StartNetworkHost"); + Script::Function::Register<&StartNetworkJoin>(rq, "StartNetworkJoin"); + Script::Function::Register<&StartNetworkJoinLobby>(rq, "StartNetworkJoinLobby"); + Script::Function::Register<&DisconnectNetworkGame>(rq, "DisconnectNetworkGame"); + Script::Function::Register<&GetPlayerGUID>(rq, "GetPlayerGUID"); + Script::Function::Register<&PollNetworkClient>(rq, "PollNetworkClient"); + Script::Function::Register<&SendGameSetupMessage>(rq, "SendGameSetupMessage"); + Script::Function::Register<&AssignNetworkPlayer>(rq, "AssignNetworkPlayer"); + Script::Function::Register<&KickPlayer>(rq, "KickPlayer"); + Script::Function::Register<&SendNetworkChat>(rq, "SendNetworkChat"); + Script::Function::Register<&SendNetworkReady>(rq, "SendNetworkReady"); + Script::Function::Register<&ClearAllPlayerReady>(rq, "ClearAllPlayerReady"); + Script::Function::Register<&StartNetworkGame>(rq, "StartNetworkGame"); + Script::Function::Register<&SetTurnLength>(rq, "SetTurnLength"); + Script::Function::Register<&SendNetworkFlare>(rq, "SendNetworkFlare"); } } diff --git a/source/network/scripting/JSInterface_Network.h b/source/network/scripting/JSInterface_Network.h index 23456b9d97..2aea0b3588 100644 --- a/source/network/scripting/JSInterface_Network.h +++ b/source/network/scripting/JSInterface_Network.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_NETWORK #define INCLUDED_JSI_NETWORK -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Network { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_NETWORK diff --git a/source/network/tests/test_Net.h b/source/network/tests/test_Net.h index 28809a10c4..3165b42ec0 100644 --- a/source/network/tests/test_Net.h +++ b/source/network/tests/test_Net.h @@ -35,8 +35,8 @@ #include "ps/XML/Xeromyces.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/system/TurnManager.h" #include @@ -152,8 +152,8 @@ public: // This doesn't actually test much, it just runs a very quick multiplayer game // and prints a load of debug output so you can see if anything funny's going on - ScriptInterface scriptInterface("Engine", "Test", g_ScriptContext); - ScriptRequest rq(scriptInterface); + Script::Interface scriptInterface("Engine", "Test", g_ScriptContext); + Script::Request rq(scriptInterface); TestStdoutLogger logger; @@ -229,8 +229,8 @@ public: void DISABLED_test_rejoin() { - ScriptInterface scriptInterface("Engine", "Test", g_ScriptContext); - ScriptRequest rq(scriptInterface); + Script::Interface scriptInterface("Engine", "Test", g_ScriptContext); + Script::Request rq(scriptInterface); TestStdoutLogger logger; diff --git a/source/network/tests/test_NetMessage.h b/source/network/tests/test_NetMessage.h index 48aa78d2b0..b79c145632 100644 --- a/source/network/tests/test_NetMessage.h +++ b/source/network/tests/test_NetMessage.h @@ -21,8 +21,8 @@ #include "network/NetMessage.h" #include "ps/CStr.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -34,8 +34,8 @@ class TestNetMessage : public CxxTest::TestSuite public: void test_sim() { - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); JS::RootedValueArray<1> val{rq.cx, JS::ValueArray<1>{JS::NumberValue(4)}}; CSimulationMessage msg(script, 1, 2, 3, diff --git a/source/ps/CConsole.cpp b/source/ps/CConsole.cpp index 2e301f03b3..840013b504 100644 --- a/source/ps/CConsole.cpp +++ b/source/ps/CConsole.cpp @@ -49,8 +49,8 @@ #include "ps/Profiler2.h" #include "ps/VideoMode.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -611,8 +611,8 @@ void CConsole::ProcessBuffer(const wchar_t* szLine) } // Process it as JavaScript - std::shared_ptr pScriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface(); - ScriptRequest rq(*pScriptInterface); + std::shared_ptr pScriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface(); + Script::Request rq(*pScriptInterface); JS::RootedValue rval(rq.cx); pScriptInterface->Eval(CStrW(szLine).ToUTF8().c_str(), &rval); diff --git a/source/ps/Game.cpp b/source/ps/Game.cpp index a7dddac1b0..149e2bbd73 100644 --- a/source/ps/Game.cpp +++ b/source/ps/Game.cpp @@ -43,9 +43,9 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpPlayer.h" #include "simulation2/components/ICmpPlayerManager.h" @@ -204,8 +204,8 @@ bool CGame::StartVisualReplay(const OsPath& replayPath) std::string line; std::getline(*m_ReplayStream, line); - const ScriptInterface& scriptInterface = m_Simulation2->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = m_Simulation2->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue attribs(rq.cx); Script::ParseJSON(rq, line, &attribs); @@ -221,8 +221,8 @@ bool CGame::StartVisualReplay(const OsPath& replayPath) **/ void CGame::RegisterInit(const JS::HandleValue attribs, const std::string& savedState) { - const ScriptInterface& scriptInterface = m_Simulation2->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = m_Simulation2->GetScriptInterface(); + Script::Request rq(scriptInterface); m_IsSavedGame = !savedState.empty(); @@ -358,12 +358,12 @@ PSRETURN CGame::ReallyStartGame() // Call the reallyStartGame GUI function, but only if it exists if (g_GUI && g_GUI->GetPageCount()) { - std::shared_ptr scriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + std::shared_ptr scriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue global(rq.cx, rq.globalValue()); if (Script::HasProperty(rq, global, "reallyStartGame")) - ScriptFunction::CallVoid(rq, global, "reallyStartGame"); + Script::Function::CallVoid(rq, global, "reallyStartGame"); } debug_printf("GAME STARTED, ALL INIT COMPLETE\n"); diff --git a/source/ps/GameSetup/CmdLineArgs.cpp b/source/ps/GameSetup/CmdLineArgs.cpp index c12c00a159..9c5e76cedf 100644 --- a/source/ps/GameSetup/CmdLineArgs.cpp +++ b/source/ps/GameSetup/CmdLineArgs.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -20,8 +20,8 @@ #include "lib/sysdep/sysdep.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -127,7 +127,7 @@ std::vector CmdLineArgs::GetArgsWithoutName() const return m_ArgsWithoutName; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CmdLineArgs& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CmdLineArgs& val) { if (!Script::CreateObject(rq, ret)) return; diff --git a/source/ps/GameSetup/GameSetup.cpp b/source/ps/GameSetup/GameSetup.cpp index 532a7c15d6..7c3256df77 100644 --- a/source/ps/GameSetup/GameSetup.cpp +++ b/source/ps/GameSetup/GameSetup.cpp @@ -82,11 +82,11 @@ #include "renderer/SceneRenderer.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" -#include "scriptinterface/ScriptStats.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" +#include "scriptinterface/Stats.h" #include "simulation2/Simulation2.h" #include "simulation2/scripting/JSInterface_Simulation.h" #include "simulation2/system/Component.h" @@ -139,7 +139,7 @@ ERROR_TYPE(System, SDLInitFailed); ERROR_TYPE(System, VmodeFailed); ERROR_TYPE(System, RequiredExtensionsMissing); -thread_local std::shared_ptr g_ScriptContext; +thread_local std::shared_ptr g_ScriptContext; bool g_InDevelopmentCopy; bool g_CheckedIfInDevelopmentCopy = false; @@ -237,7 +237,7 @@ void InitVfs(const CmdLineArgs& args) } -static void InitPs(bool setup_gui, const CStrW& gui_page, ScriptInterface* srcScriptInterface, JS::HandleValue initData) +static void InitPs(bool setup_gui, const CStrW& gui_page, Script::Interface* srcScriptInterface, JS::HandleValue initData) { g_Console->Init(); LoadHotkeys(g_ConfigDB); @@ -528,7 +528,7 @@ bool Init(const CmdLineArgs& args, int flags) new CProfileViewer; new CProfileManager; // before any script code - g_ScriptStatsTable = new CScriptStatsTable; + g_ScriptStatsTable = new Script::CScriptStatsTable; g_ProfileViewer.AddRootTable(g_ScriptStatsTable); // Set up the console early, so that debugging @@ -543,7 +543,7 @@ bool Init(const CmdLineArgs& args, int flags) // their own threads and also their own contexts. const int contextSize = 384 * 1024 * 1024; const int heapGrowthBytesGCTrigger = 12 * 1024 * 1024; - g_ScriptContext = std::make_shared(contextSize, heapGrowthBytesGCTrigger); + g_ScriptContext = std::make_shared(contextSize, heapGrowthBytesGCTrigger); // On the first Init (INIT_MODS), check for command-line arguments // or use the default mods from the config and enable those. @@ -551,7 +551,7 @@ bool Init(const CmdLineArgs& args, int flags) // to avoid overwriting the newly selected mods. if (flags & INIT_MODS) { - ScriptInterface modInterface("Engine", "Mod", g_ScriptContext); + Script::Interface modInterface("Engine", "Mod", g_ScriptContext); g_Mods.UpdateAvailableMods(modInterface); std::vector mods; if (args.Has("mod")) @@ -623,8 +623,8 @@ bool Init(const CmdLineArgs& args, int flags) } [[nodiscard]] std::unique_ptr InitGraphics(const CmdLineArgs& args, int flags, - const std::vector& installedMods, ScriptContext& scriptContext, - ScriptInterface& scriptInterface) + const std::vector& installedMods, Script::Context& scriptContext, + Script::Interface& scriptInterface) { const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0; @@ -678,7 +678,7 @@ bool Init(const CmdLineArgs& args, int flags) { const bool setup_gui = ((flags & INIT_NO_GUI) == 0); - ScriptRequest rq{g_GUI->GetScriptInterface()}; + Script::Request rq{g_GUI->GetScriptInterface()}; JS::RootedValue data(rq.cx); Script::CreateObject(rq, &data, "isStartup", true); if (!installedMods.empty()) @@ -766,8 +766,8 @@ bool Autostart(const CmdLineArgs& args) return false; // Create some scriptinterface to store the js values for the settings. - ScriptInterface scriptInterface("Engine", "Game Setup", g_ScriptContext); - ScriptRequest rq(scriptInterface); + Script::Interface scriptInterface("Engine", "Game Setup", g_ScriptContext); + Script::Request rq(scriptInterface); // We use the javascript gameSettings to handle options, but that requires running JS. // Since we don't want to use the full Gui manager, we load an entrypoint script @@ -775,7 +775,7 @@ bool Autostart(const CmdLineArgs& args) // TODO: this essentially duplicates the CGUI logic to load directory or scripts. std::unordered_set templateCache; - const auto autostartLoadScript = [&templateCache](const ScriptInterface& scriptInterface, + const auto autostartLoadScript = [&templateCache](const Script::Interface& scriptInterface, const VfsPath& path) { if (!std::get<1>(templateCache.insert(path))) @@ -792,7 +792,7 @@ bool Autostart(const CmdLineArgs& args) scriptInterface.LoadGlobalScriptFile(path); }; - const auto loadScriptCallback = ScriptFunction::Register(rq, "LoadScript", autostartLoadScript); + const auto loadScriptCallback = Script::Function::Register(rq, "LoadScript", autostartLoadScript); // Load the entire folder to allow mods to extend the entrypoint without copying the whole file. autostartLoadScript(scriptInterface, VfsPath(L"autostart/")); @@ -813,7 +813,7 @@ bool Autostart(const CmdLineArgs& args) } }; - std::optional> getTemplateCallback; + std::optional> getTemplateCallback; if (args.Has("autostart-nonvisual")) getTemplateCallback.emplace(rq, "GetTemplate", GetTemplate{}); else @@ -838,7 +838,7 @@ bool Autostart(const CmdLineArgs& args) JS::RootedValue resultValue{rq.cx}; JS::RootedValue global(rq.cx, rq.globalValue()); - if (!ScriptFunction::Call(rq, global, + if (!Script::Function::Call(rq, global, args.Has("autostart-client") ? "autostartClient" : "autostartHost", &resultValue, cmdLineArgs, args.Has("autostart-host")) && !resultValue.isObject()) { @@ -885,8 +885,8 @@ bool AutostartVisualReplay(const std::string& replayFile) g_Game->SetPlayerID(-1); g_Game->StartVisualReplay(replayFile); - ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue attrs(rq.cx, g_Game->GetSimulation2()->GetInitAttributes()); JS::RootedValue playerAssignments(rq.cx); @@ -910,8 +910,8 @@ bool AutostartVisualReplay(const std::string& replayFile) void CancelLoad(const CStrW& message) { - std::shared_ptr pScriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface(); - ScriptRequest rq(pScriptInterface); + std::shared_ptr pScriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface(); + Script::Request rq(pScriptInterface); JS::RootedValue global(rq.cx, rq.globalValue()); @@ -920,7 +920,7 @@ void CancelLoad(const CStrW& message) if (g_GUI && g_GUI->GetPageCount() && Script::HasProperty(rq, global, "cancelOnLoadGameError")) - ScriptFunction::CallVoid(rq, global, "cancelOnLoadGameError", message); + Script::Function::CallVoid(rq, global, "cancelOnLoadGameError", message); } bool InDevelopmentCopy() diff --git a/source/ps/GameSetup/GameSetup.h b/source/ps/GameSetup/GameSetup.h index 87aab46fbc..f3d252a98a 100644 --- a/source/ps/GameSetup/GameSetup.h +++ b/source/ps/GameSetup/GameSetup.h @@ -26,8 +26,8 @@ class CmdLineArgs; class Paths; -class ScriptContext; -class ScriptInterface; +namespace Script { class Context; } +namespace Script { class Interface; } /** * initialize global modules that are be needed before Init. @@ -80,8 +80,8 @@ using InputHandlers = std::queue InitGraphics(const CmdLineArgs& args, int flags, - const std::vector& installedMods, ScriptContext& scriptContext, - ScriptInterface& scriptInterface); + const std::vector& installedMods, Script::Context& scriptContext, + Script::Interface& scriptInterface); /** * `ShutdownNetworkAndUI` has to be called later. diff --git a/source/ps/GameSetup/HWDetect.cpp b/source/ps/GameSetup/HWDetect.cpp index 0b61dcb6af..8c6e9122d8 100644 --- a/source/ps/GameSetup/HWDetect.cpp +++ b/source/ps/GameSetup/HWDetect.cpp @@ -52,8 +52,8 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "soundmanager/ISoundManager.h" @@ -115,7 +115,7 @@ namespace class Reporter { public: - Reporter(const ScriptRequest& rq) + Reporter(const Script::Request& rq) : m_Rq(rq), m_LibrarySettings(rq.cx) { Script::CreateObject(m_Rq, &m_LibrarySettings); @@ -134,21 +134,21 @@ public: } private: - const ScriptRequest& m_Rq; + const Script::Request& m_Rq; JS::RootedValue m_LibrarySettings; }; class LibraryReporter : public Reporter { public: - LibraryReporter(const ScriptRequest& rq, const char* name) + LibraryReporter(const Script::Request& rq, const char* name) : Reporter(rq) { Add("name", name); } }; -JS::Value MakeSDLReport(const ScriptRequest& rq) +JS::Value MakeSDLReport(const Script::Request& rq) { LibraryReporter reporter{rq, "sdl"}; @@ -175,7 +175,7 @@ JS::Value MakeSDLReport(const ScriptRequest& rq) return reporter.MakeReport(); } -JS::Value MakeFreeTypeReport(const ScriptRequest& rq) +JS::Value MakeFreeTypeReport(const Script::Request& rq) { FT_Library FTLibrary; @@ -194,7 +194,7 @@ JS::Value MakeFreeTypeReport(const ScriptRequest& rq) return libraryReporter.MakeReport(); } -void ReportLibraries(const ScriptRequest& rq, JS::HandleValue settings) +void ReportLibraries(const Script::Request& rq, JS::HandleValue settings) { JS::RootedValueVector librariesSettings{rq.cx}; @@ -336,14 +336,14 @@ void RunHardwareDetection(bool writeSystemInfoBeforeDetection, Renderer::Backend PROFILE2("RunHardwareDetection"); - ScriptInterface scriptInterface("Engine", "HWDetect", g_ScriptContext); + Script::Interface scriptInterface("Engine", "HWDetect", g_ScriptContext); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JSI_Debug::RegisterScriptFunctions(scriptInterface); // Engine.DisplayErrorDialog JSI_ConfigDB::RegisterScriptFunctions(scriptInterface); - ScriptFunction::Register(rq, "SetDisableAudio"); + Script::Function::Register(rq, "SetDisableAudio"); // Load the detection script: @@ -478,5 +478,5 @@ void RunHardwareDetection(bool writeSystemInfoBeforeDetection, Renderer::Backend // Run the detection script: JS::RootedValue global(rq.cx, rq.globalValue()); - ScriptFunction::CallVoid(rq, global, "RunHardwareDetection", settings); + Script::Function::CallVoid(rq, global, "RunHardwareDetection", settings); } diff --git a/source/ps/Input.cpp b/source/ps/Input.cpp index 9b828e0137..ced5b8a9fe 100644 --- a/source/ps/Input.cpp +++ b/source/ps/Input.cpp @@ -24,8 +24,8 @@ #include "ps/Profile.h" #include "ps/TouchInput.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include diff --git a/source/ps/Mod.cpp b/source/ps/Mod.cpp index 5f4ad3c1ae..8eb71fc370 100644 --- a/source/ps/Mod.cpp +++ b/source/ps/Mod.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -32,8 +32,8 @@ #include "ps/Profiler2.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -55,7 +55,7 @@ #include "lib/os_path.h" #endif -class ScriptInterface; +namespace Script { class Interface; } namespace { @@ -112,7 +112,7 @@ bool LoadModJSON(const PIVFS& vfs, OsPath modsPath, OsPath mod, std::string& tex } } -bool ParseModJSON(const ScriptRequest& rq, const PIVFS& vfs, OsPath modsPath, OsPath mod, Mod::ModData& data) +bool ParseModJSON(const Script::Request& rq, const PIVFS& vfs, OsPath modsPath, OsPath mod, Mod::ModData& data) { std::string text; if (!LoadModJSON(vfs, modsPath, mod, text)) @@ -245,7 +245,7 @@ bool Mod::AreModsPlayCompatible(const std::vector& modsA, c return true; } -void Mod::UpdateAvailableMods(const ScriptInterface& scriptInterface) +void Mod::UpdateAvailableMods(const Script::Interface& scriptInterface) { PROFILE2("UpdateAvailableMods"); @@ -265,7 +265,7 @@ void Mod::UpdateAvailableMods(const ScriptInterface& scriptInterface) PIVFS vfs = CreateVfs(); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); for (DirectoryNames::iterator iter = modDirs.begin(); iter != modDirs.end(); ++iter) { ModData data; diff --git a/source/ps/Mod.h b/source/ps/Mod.h index a9fb9a5eff..144344d350 100644 --- a/source/ps/Mod.h +++ b/source/ps/Mod.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,7 +22,7 @@ #include -class ScriptInterface; +namespace Script { class Interface; } #define g_Mods (Mod::Instance()) @@ -65,7 +65,7 @@ public: * TODO: if this did not need the scriptInterface to parse JSON, * we could run it in different contexts and possibly cleaner. */ - void UpdateAvailableMods(const ScriptInterface& scriptInterface); + void UpdateAvailableMods(const Script::Interface& scriptInterface); /** * Enables specified mods (& mods required by the engine). diff --git a/source/ps/ModInstaller.cpp b/source/ps/ModInstaller.cpp index 9a452f473e..38ba0e904c 100644 --- a/source/ps/ModInstaller.cpp +++ b/source/ps/ModInstaller.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,9 +26,9 @@ #include "ps/Errors.h" #include "ps/Filesystem.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -60,7 +60,7 @@ CModInstaller::~CModInstaller() CModInstaller::ModInstallationResult CModInstaller::Install( const OsPath& mod, - const std::shared_ptr& scriptContext, + const std::shared_ptr& scriptContext, bool keepFile) { const OsPath modTemp = m_TempDir / mod.Basename() / mod.Filename().ChangeExtension(L".zip"); @@ -92,8 +92,8 @@ CModInstaller::ModInstallationResult CModInstaller::Install( // Extract the name of the mod CStr modName; { - ScriptInterface scriptInterface("Engine", "ModInstaller", scriptContext); - ScriptRequest rq(scriptInterface); + Script::Interface scriptInterface("Engine", "ModInstaller", scriptContext); + Script::Request rq(scriptInterface); JS::RootedValue json_val(rq.cx); if (!Script::ParseJSON(rq, modinfo.GetAsString(), &json_val)) diff --git a/source/ps/ModInstaller.h b/source/ps/ModInstaller.h index e666bf0ff7..e7e4ad92a7 100644 --- a/source/ps/ModInstaller.h +++ b/source/ps/ModInstaller.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ #include #include -class ScriptContext; +namespace Script { class Context; } /** * Install a mod into the mods directory. @@ -63,7 +63,7 @@ public: */ ModInstallationResult Install( const OsPath& mod, - const std::shared_ptr& scriptContext, + const std::shared_ptr& scriptContext, bool keepFile); /** diff --git a/source/ps/ModIo.cpp b/source/ps/ModIo.cpp index 73c90299d0..996bd4c79b 100644 --- a/source/ps/ModIo.cpp +++ b/source/ps/ModIo.cpp @@ -40,9 +40,9 @@ #include "ps/ModInstaller.h" #include "ps/Util.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -59,7 +59,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } ModIo* g_ModIo = nullptr; @@ -412,7 +412,7 @@ void ModIo::CancelRequest() } } -bool ModIo::AdvanceRequest(const ScriptInterface& scriptInterface) +bool ModIo::AdvanceRequest(const Script::Interface& scriptInterface) { // If the request was cancelled, stop trying to advance it if (m_DownloadProgressData.status != DownloadProgressStatus::GAMEID && @@ -526,7 +526,7 @@ bool ModIo::AdvanceRequest(const ScriptInterface& scriptInterface) return true; } -bool ModIo::ParseGameId(const ScriptInterface& scriptInterface, std::string& err) +bool ModIo::ParseGameId(const Script::Interface& scriptInterface, std::string& err) { int id = -1; bool ret = ParseGameIdResponse(scriptInterface, m_ResponseData, id, err); @@ -538,7 +538,7 @@ bool ModIo::ParseGameId(const ScriptInterface& scriptInterface, std::string& err return true; } -bool ModIo::ParseMods(const ScriptInterface& scriptInterface, std::string& err) +bool ModIo::ParseMods(const Script::Interface& scriptInterface, std::string& err) { bool ret = ParseModsResponse(scriptInterface, m_ResponseData, m_ModData, m_pk, err); m_ResponseData.clear(); @@ -623,10 +623,10 @@ bool ModIo::VerifyDownloadedFile(std::string& err) * * @returns true iff it successfully parsed the id. */ -bool ModIo::ParseGameIdResponse(const ScriptInterface& scriptInterface, const std::string& responseData, int& id, std::string& err) +bool ModIo::ParseGameIdResponse(const Script::Interface& scriptInterface, const std::string& responseData, int& id, std::string& err) { #define CLEANUP() id = -1; - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue gameResponse(rq.cx); @@ -689,12 +689,12 @@ bool ModIo::ParseGameIdResponse(const ScriptInterface& scriptInterface, const st * Only the listed properties are of interest to consumers, and we flatten * the modfile structure as that simplifies handling and there are no conflicts. */ -bool ModIo::ParseModsResponse(const ScriptInterface& scriptInterface, const std::string& responseData, std::vector& modData, const PKStruct& pk, std::string& err) +bool ModIo::ParseModsResponse(const Script::Interface& scriptInterface, const std::string& responseData, std::vector& modData, const PKStruct& pk, std::string& err) { // Make sure we don't end up passing partial results back #define CLEANUP() modData.clear(); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue modResponse(rq.cx); diff --git a/source/ps/ModIo.h b/source/ps/ModIo.h index 7df4c92076..4cc7403ce7 100644 --- a/source/ps/ModIo.h +++ b/source/ps/ModIo.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -34,7 +34,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } // TODO: Allocate instance of the below two using sodium_malloc? struct PKStruct @@ -147,7 +147,7 @@ public: * @param scriptInterface used for parsing the data and possibly install the mod. * @return true if the download is complete (successful or not), false otherwise. */ - bool AdvanceRequest(const ScriptInterface& scriptInterface); + bool AdvanceRequest(const Script::Interface& scriptInterface); /** * Cancel the current async request and clean things up @@ -171,15 +171,15 @@ private: CURLMcode SetupRequest(const std::string& url, bool fileDownload); void TearDownRequest(); - bool ParseGameId(const ScriptInterface& scriptInterface, std::string& err); - bool ParseMods(const ScriptInterface& scriptInterface, std::string& err); + bool ParseGameId(const Script::Interface& scriptInterface, std::string& err); + bool ParseMods(const Script::Interface& scriptInterface, std::string& err); void DeleteDownloadedFile(); bool VerifyDownloadedFile(std::string& err); // Utility methods for parsing mod.io responses and metadata - static bool ParseGameIdResponse(const ScriptInterface& scriptInterface, const std::string& responseData, int& id, std::string& err); - static bool ParseModsResponse(const ScriptInterface& scriptInterface, const std::string& responseData, std::vector& modData, const PKStruct& pk, std::string& err); + static bool ParseGameIdResponse(const Script::Interface& scriptInterface, const std::string& responseData, int& id, std::string& err); + static bool ParseModsResponse(const Script::Interface& scriptInterface, const std::string& responseData, std::vector& modData, const PKStruct& pk, std::string& err); static bool ParseSignature(const std::vector& minisigs, SigStruct& sig, const PKStruct& pk, std::string& err); // Url parts diff --git a/source/ps/ProfileViewer.cpp b/source/ps/ProfileViewer.cpp index 0aa39c4d0e..ae9c2daffe 100644 --- a/source/ps/ProfileViewer.cpp +++ b/source/ps/ProfileViewer.cpp @@ -37,7 +37,7 @@ #include "ps/Pyrogenesis.h" #include "ps/VideoMode.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -49,7 +49,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } struct CProfileViewerInternals { @@ -448,12 +448,12 @@ namespace struct DumpTable { - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; JS::PersistentRooted m_Root; - DumpTable(const ScriptInterface& scriptInterface, JS::HandleValue root) : + DumpTable(const Script::Interface& scriptInterface, JS::HandleValue root) : m_ScriptInterface(scriptInterface) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); m_Root.init(rq.cx, root); } @@ -462,13 +462,13 @@ namespace DumpTable(DumpTable && original) : m_ScriptInterface(original.m_ScriptInterface) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); m_Root.init(rq.cx, original.m_Root.get()); } void operator() (AbstractProfileTable* table) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedValue t(rq.cx); Script::CreateObject( @@ -494,7 +494,7 @@ namespace JS::Value DumpRows(AbstractProfileTable* table) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedValue data(rq.cx); Script::CreateObject(rq, &data); diff --git a/source/ps/Replay.cpp b/source/ps/Replay.cpp index 17a38df592..8ef85fa93d 100644 --- a/source/ps/Replay.cpp +++ b/source/ps/Replay.cpp @@ -41,10 +41,10 @@ #include "ps/VisualReplay.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" -#include "scriptinterface/ScriptStats.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" +#include "scriptinterface/Stats.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpGuiInterface.h" #include "simulation2/helpers/Player.h" @@ -62,7 +62,7 @@ */ static const int PROFILE_TURN_INTERVAL = 20; -CReplayLogger::CReplayLogger(const ScriptInterface& scriptInterface) : +CReplayLogger::CReplayLogger(const Script::Interface& scriptInterface) : m_ScriptInterface(scriptInterface), m_Stream(NULL) { } @@ -74,7 +74,7 @@ CReplayLogger::~CReplayLogger() void CReplayLogger::StartGame(JS::MutableHandleValue attribs) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); // Add timestamp, since the file-modification-date can change Script::SetProperty(rq, attribs, "timestamp", (double)std::time(nullptr)); @@ -94,7 +94,7 @@ void CReplayLogger::StartGame(JS::MutableHandleValue attribs) void CReplayLogger::Turn(u32 n, u32 turnLength, std::vector& commands) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); *m_Stream << "turn " << n << " " << turnLength << "\n"; @@ -122,8 +122,8 @@ void CReplayLogger::SaveMetadata(const CSimulation2& simulation) return; } - ScriptInterface& scriptInterface = simulation.GetScriptInterface(); - ScriptRequest rq(scriptInterface); + Script::Interface& scriptInterface = simulation.GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue arg(rq.cx); JS::RootedValue metadata(rq.cx); @@ -198,12 +198,12 @@ void CReplayPlayer::Replay(const int serializationtestturn, const int rejointest new CProfileViewer; new CProfileManager; - g_ScriptStatsTable = new CScriptStatsTable; + g_ScriptStatsTable = new Script::CScriptStatsTable; g_ProfileViewer.AddRootTable(g_ScriptStatsTable); const int contextSize = 384 * 1024 * 1024; const int heapGrowthBytesGCTrigger = 12 * 1024 * 1024; - g_ScriptContext = std::make_shared(contextSize, heapGrowthBytesGCTrigger); + g_ScriptContext = std::make_shared(contextSize, heapGrowthBytesGCTrigger); std::vector commands; u32 turn = 0; @@ -218,8 +218,8 @@ void CReplayPlayer::Replay(const int serializationtestturn, const int rejointest { std::string attribsStr; { - ScriptInterface scriptInterface("Engine", "Replay", g_ScriptContext); - ScriptRequest rq(scriptInterface); + Script::Interface scriptInterface("Engine", "Replay", g_ScriptContext); + Script::Request rq(scriptInterface); std::getline(*m_Stream, attribsStr); JS::RootedValue attribs(rq.cx); if (!Script::ParseJSON(rq, attribsStr, &attribs)) @@ -266,7 +266,7 @@ void CReplayPlayer::Replay(const int serializationtestturn, const int rejointest g_Game = new CGame(false, debugOption); - ScriptRequest rq(g_Game->GetSimulation2()->GetScriptInterface()); + Script::Request rq(g_Game->GetSimulation2()->GetScriptInterface()); JS::RootedValue attribs(rq.cx); ENSURE(Script::ParseJSON(rq, attribsStr, &attribs)); g_Game->StartGame(&attribs, ""); @@ -289,7 +289,7 @@ void CReplayPlayer::Replay(const int serializationtestturn, const int rejointest std::string line; std::getline(*m_Stream, line); - ScriptRequest rq(g_Game->GetSimulation2()->GetScriptInterface()); + Script::Request rq(g_Game->GetSimulation2()->GetScriptInterface()); JS::RootedValue data(rq.cx); Script::ParseJSON(rq, line, &data); Script::DeepFreezeObject(rq, data); diff --git a/source/ps/Replay.h b/source/ps/Replay.h index 868f09bb54..b6e1152a71 100644 --- a/source/ps/Replay.h +++ b/source/ps/Replay.h @@ -30,7 +30,7 @@ #include class CSimulation2; -class ScriptInterface; +namespace Script { class Interface; } struct SimulationCommand; /** @@ -89,7 +89,7 @@ class CReplayLogger : public IReplayLogger { NONCOPYABLE(CReplayLogger); public: - CReplayLogger(const ScriptInterface& scriptInterface); + CReplayLogger(const Script::Interface& scriptInterface); ~CReplayLogger(); virtual void StartGame(JS::MutableHandleValue attribs); @@ -99,7 +99,7 @@ public: virtual OsPath GetDirectory() const; private: - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; std::ostream* m_Stream; OsPath m_Directory; }; diff --git a/source/ps/SavedGame.cpp b/source/ps/SavedGame.cpp index b794c07b32..a0a1aaf16a 100644 --- a/source/ps/SavedGame.cpp +++ b/source/ps/SavedGame.cpp @@ -44,8 +44,8 @@ #include "ps/Pyrogenesis.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/Simulation2.h" @@ -59,7 +59,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } // TODO: we ought to check version numbers when loading files @@ -80,7 +80,7 @@ Status SavedGames::SavePrefix(const CStrW& prefix, const CStrW& description, CSi Status SavedGames::Save(const CStrW& name, const CStrW& description, CSimulation2& simulation, const Script::StructuredClone& guiMetadataClone) { - ScriptRequest rq(simulation.GetScriptInterface()); + Script::Request rq(simulation.GetScriptInterface()); // Determine the filename to save under const VfsPath basenameFormat(L"saves/" + name); @@ -180,7 +180,7 @@ class CGameLoader public: /** - * @param scriptInterface the ScriptInterface used for loading metadata. + * @param scriptInterface the Script::Interface used for loading metadata. * @param[out] savedState serialized simulation state stored as string of bytes, * loaded from simulation.dat inside the archive. * @@ -189,11 +189,11 @@ public: * for the metadata because it would be error prone with rooting and the stack-based rooting * types and confusing (a chain of pointers pointing to other pointers). */ - CGameLoader(const ScriptInterface& scriptInterface, std::string* savedState) : + CGameLoader(const Script::Interface& scriptInterface, std::string* savedState) : m_ScriptInterface(scriptInterface), m_SavedState(savedState) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); m_Metadata.init(rq.cx); } @@ -209,7 +209,7 @@ public: std::string buffer; buffer.resize(fileInfo.Size()); WARN_IF_ERR(archiveFile->Load("", DummySharedPtr((u8*)buffer.data()), buffer.size())); - Script::ParseJSON(ScriptRequest(m_ScriptInterface), buffer, &m_Metadata); + Script::ParseJSON(Script::Request(m_ScriptInterface), buffer, &m_Metadata); } else if (pathname == L"simulation.dat" && m_SavedState) { @@ -225,12 +225,12 @@ public: private: - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; JS::PersistentRooted m_Metadata; std::string* m_SavedState; }; -std::optional SavedGames::Load(const ScriptInterface& scriptInterface, +std::optional SavedGames::Load(const Script::Interface& scriptInterface, const std::wstring& name) { // Determine the filename to load @@ -269,17 +269,17 @@ std::optional SavedGames::Load(const ScriptInterface& sc return std::nullopt; } } - const ScriptRequest rq{scriptInterface}; + const Script::Request rq{scriptInterface}; JS::RootedValue metadata{rq.cx, loader.GetMetadata()}; // `std::make_optional` can't be used since `LoadResult` doesn't have a constructor. return {{metadata, std::move(savedState)}}; } -JS::Value SavedGames::GetSavedGames(const ScriptInterface& scriptInterface) +JS::Value SavedGames::GetSavedGames(const Script::Interface& scriptInterface) { PROFILE2("GetSavedGames"); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValueVector games{rq.cx}; diff --git a/source/ps/SavedGame.h b/source/ps/SavedGame.h index a9958c4760..7f55ba9686 100644 --- a/source/ps/SavedGame.h +++ b/source/ps/SavedGame.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -27,7 +27,7 @@ class CSimulation2; class CStrW; -class ScriptInterface; +namespace Script { class Interface; } /** * @file @@ -82,15 +82,15 @@ namespace SavedGames * @param scriptInterface * @return An empty `std::optional` if an error ocoured. */ - std::optional Load(const ScriptInterface& scriptInterface, const std::wstring& name); + std::optional Load(const Script::Interface& scriptInterface, const std::wstring& name); /** * Get list of saved games for GUI script usage * - * @param scriptInterface the ScriptInterface in which to create the return data. + * @param scriptInterface the Script::Interface in which to create the return data. * @return array of objects containing saved game data */ - JS::Value GetSavedGames(const ScriptInterface& scriptInterface); + JS::Value GetSavedGames(const Script::Interface& scriptInterface); /** * Permanently deletes the saved game archive with the given name diff --git a/source/ps/VideoMode.cpp b/source/ps/VideoMode.cpp index 3ac8763a73..27756796ab 100644 --- a/source/ps/VideoMode.cpp +++ b/source/ps/VideoMode.cpp @@ -47,7 +47,7 @@ #include "renderer/backend/dummy/DeviceForward.h" #include "renderer/backend/gl/DeviceForward.h" #include "renderer/backend/vulkan/DeviceForward.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include #include diff --git a/source/ps/VisualReplay.cpp b/source/ps/VisualReplay.cpp index 7b3bbcf59e..f16297bb87 100644 --- a/source/ps/VisualReplay.cpp +++ b/source/ps/VisualReplay.cpp @@ -38,7 +38,7 @@ #include "ps/Pyrogenesis.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -91,7 +91,7 @@ bool VisualReplay::StartVisualReplay(const OsPath& directory) return g_Game->StartVisualReplay(replayFile); } -bool VisualReplay::ReadCacheFile(const ScriptInterface& scriptInterface, JS::MutableHandleObject cachedReplaysObject) +bool VisualReplay::ReadCacheFile(const Script::Interface& scriptInterface, JS::MutableHandleObject cachedReplaysObject) { if (!std::filesystem::is_regular_file(GetCacheFilePath().string())) return false; @@ -100,7 +100,7 @@ bool VisualReplay::ReadCacheFile(const ScriptInterface& scriptInterface, JS::Mut CStr cacheStr((std::istreambuf_iterator(cacheStream)), std::istreambuf_iterator()); cacheStream.close(); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue cachedReplays(rq.cx); if (Script::ParseJSON(rq, cacheStr, &cachedReplays)) @@ -117,9 +117,9 @@ bool VisualReplay::ReadCacheFile(const ScriptInterface& scriptInterface, JS::Mut return false; } -void VisualReplay::StoreCacheFile(const ScriptInterface& scriptInterface, JS::HandleObject replays) +void VisualReplay::StoreCacheFile(const Script::Interface& scriptInterface, JS::HandleObject replays) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue replaysRooted(rq.cx, JS::ObjectValue(*replays)); std::ofstream cacheStream(OsString(GetTempCacheFilePath()), std::ofstream::out | std::ofstream::trunc); @@ -132,10 +132,10 @@ void VisualReplay::StoreCacheFile(const ScriptInterface& scriptInterface, JS::Ha LOGERROR("Could not store the replay cache"); } -JS::HandleObject VisualReplay::ReloadReplayCache(const ScriptInterface& scriptInterface, bool compareFiles) +JS::HandleObject VisualReplay::ReloadReplayCache(const Script::Interface& scriptInterface, bool compareFiles) { PROFILE2("ReloadReplayCache"); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); // Maps the filename onto the index, mtime and size using replayCacheMap = std::map>; @@ -252,11 +252,11 @@ JS::HandleObject VisualReplay::ReloadReplayCache(const ScriptInterface& scriptIn return replays; } -JS::Value VisualReplay::GetReplays(const ScriptInterface& scriptInterface, bool compareFiles) +JS::Value VisualReplay::GetReplays(const Script::Interface& scriptInterface, bool compareFiles) { PROFILE2("GetReplays"); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedObject replays(rq.cx, ReloadReplayCache(scriptInterface, compareFiles)); // Only take entries with data JS::RootedValueVector replaysWithoutNullEntries{rq.cx}; @@ -358,7 +358,7 @@ inline int getReplayDuration(std::istream* replayStream, const OsPath& fileName, return -1; } -JS::Value VisualReplay::LoadReplayData(const ScriptInterface& scriptInterface, const OsPath& directory) +JS::Value VisualReplay::LoadReplayData(const Script::Interface& scriptInterface, const OsPath& directory) { // The directory argument must not be constant, otherwise concatenating will fail const OsPath replayFile = GetDirectoryPath() / directory / L"commands.txt"; @@ -394,7 +394,7 @@ JS::Value VisualReplay::LoadReplayData(const ScriptInterface& scriptInterface, c // Parse header / first line CStr header; std::getline(*replayStream, header); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue attribs(rq.cx); if (!Script::ParseJSON(rq, header, &attribs)) { @@ -452,10 +452,10 @@ bool VisualReplay::DeleteReplay(const OsPath& replayDirectory) return DirectoryExists(directory) && DeleteDirectory(directory) == INFO::OK; } -JS::Value VisualReplay::GetReplayAttributes(const ScriptInterface& scriptInterface, const OsPath& directoryName) +JS::Value VisualReplay::GetReplayAttributes(const Script::Interface& scriptInterface, const OsPath& directoryName) { // Create empty JS object - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue attribs(rq.cx); Script::CreateObject(rq, &attribs); @@ -476,10 +476,10 @@ JS::Value VisualReplay::GetReplayAttributes(const ScriptInterface& scriptInterfa return attribs; } -void VisualReplay::AddReplayToCache(const ScriptInterface& scriptInterface, const CStrW& directoryName) +void VisualReplay::AddReplayToCache(const Script::Interface& scriptInterface, const CStrW& directoryName) { PROFILE2("AddReplayToCache"); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue replayData(rq.cx, LoadReplayData(scriptInterface, OsPath(directoryName))); if (replayData.isNull()) @@ -509,12 +509,12 @@ bool VisualReplay::HasReplayMetadata(const OsPath& directoryName) return fileInfo.Size() > 0; } -JS::Value VisualReplay::GetReplayMetadata(const ScriptInterface& scriptInterface, const OsPath& directoryName) +JS::Value VisualReplay::GetReplayMetadata(const Script::Interface& scriptInterface, const OsPath& directoryName) { if (!HasReplayMetadata(directoryName)) return JS::NullValue(); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue metadata(rq.cx); std::ifstream* stream = new std::ifstream(OsString(GetDirectoryPath() / directoryName / L"metadata.json")); diff --git a/source/ps/VisualReplay.h b/source/ps/VisualReplay.h index 05e1044655..987eda26b0 100644 --- a/source/ps/VisualReplay.h +++ b/source/ps/VisualReplay.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,8 +23,8 @@ #include class CStrW; -class ScriptInterface; namespace JS { class Value; } +namespace Script { class Interface; } /** * Contains functions for visually replaying past games. @@ -56,44 +56,44 @@ bool StartVisualReplay(const OsPath& directory); /** * Reads the replay Cache file and parses it into a jsObject * - * @param scriptInterface - the ScriptInterface in which to create the return data. + * @param scriptInterface - the Script::Interface in which to create the return data. * @param cachedReplaysObject - the cached replays. * @return true on succes */ -bool ReadCacheFile(const ScriptInterface& scriptInterface, JS::MutableHandleObject cachedReplaysObject); +bool ReadCacheFile(const Script::Interface& scriptInterface, JS::MutableHandleObject cachedReplaysObject); /** * Stores the replay list in the replay cache file * - * @param scriptInterface - the ScriptInterface in which to create the return data. + * @param scriptInterface - the Script::Interface in which to create the return data. * @param replays - the replay list to store. */ -void StoreCacheFile(const ScriptInterface& scriptInterface, JS::HandleObject replays); +void StoreCacheFile(const Script::Interface& scriptInterface, JS::HandleObject replays); /** * Load the replay cache and check if there are new/deleted replays. If so, update the cache. * - * @param scriptInterface - the ScriptInterface in which to create the return data. + * @param scriptInterface - the Script::Interface in which to create the return data. * @param compareFiles - compare the directory name and the FileSize of the replays and the cache. * @return cache entries */ -JS::HandleObject ReloadReplayCache(const ScriptInterface& scriptInterface, bool compareFiles); +JS::HandleObject ReloadReplayCache(const Script::Interface& scriptInterface, bool compareFiles); /** * Get a list of replays to display in the GUI. * - * @param scriptInterface - the ScriptInterface in which to create the return data. + * @param scriptInterface - the Script::Interface in which to create the return data. * @param compareFiles - reload the cache, which takes more time, * but nearly ensures, that no changed replay is missed. * @return array of objects containing replay data */ -JS::Value GetReplays(const ScriptInterface& scriptInterface, bool compareFiles); +JS::Value GetReplays(const Script::Interface& scriptInterface, bool compareFiles); /** * Parses a commands.txt file and extracts metadata. * Works similarly to CGame::LoadReplayData(). */ -JS::Value LoadReplayData(const ScriptInterface& scriptInterface, const OsPath& directory); +JS::Value LoadReplayData(const Script::Interface& scriptInterface, const OsPath& directory); /** * Permanently deletes the visual replay (including the parent directory) @@ -106,7 +106,7 @@ bool DeleteReplay(const OsPath& replayFile); /** * Returns the parsed header of the replay file (commands.txt). */ -JS::Value GetReplayAttributes(const ScriptInterface& scriptInterface, const OsPath& directoryName); +JS::Value GetReplayAttributes(const Script::Interface& scriptInterface, const OsPath& directoryName); /** * Returns whether or not the metadata / summary screen data has been saved properly when the game ended. @@ -116,12 +116,12 @@ bool HasReplayMetadata(const OsPath& directoryName); /** * Returns the metadata of a replay. */ -JS::Value GetReplayMetadata(const ScriptInterface& scriptInterface, const OsPath& directoryName); +JS::Value GetReplayMetadata(const Script::Interface& scriptInterface, const OsPath& directoryName); /** * Adds a replay to the replayCache. */ -void AddReplayToCache(const ScriptInterface& scriptInterface, const CStrW& directoryName); +void AddReplayToCache(const Script::Interface& scriptInterface, const CStrW& directoryName); } #endif diff --git a/source/ps/World.cpp b/source/ps/World.cpp index 4ad8cf4282..1bfe34b0fb 100644 --- a/source/ps/World.cpp +++ b/source/ps/World.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -66,7 +66,7 @@ CWorld::~CWorld() = default; /** * Initializes the game world with the attributes provided. **/ -void CWorld::RegisterInit(const CStrW& mapFile, const ScriptContext& cx, JS::HandleValue settings, int playerID) +void CWorld::RegisterInit(const CStrW& mapFile, const Script::Context& cx, JS::HandleValue settings, int playerID) { // Load the map, if one was specified if (mapFile.length()) @@ -100,7 +100,7 @@ void CWorld::RegisterInit(const CStrW& mapFile, const ScriptContext& cx, JS::Han } } -void CWorld::RegisterInitRMS(const CStrW& scriptFile, const ScriptContext& cx, JS::HandleValue settings, int playerID) +void CWorld::RegisterInitRMS(const CStrW& scriptFile, const Script::Context& cx, JS::HandleValue settings, int playerID) { // If scriptFile is empty, a blank map will be generated using settings (no RMS run) CTriggerManager* pTriggerManager = nullptr; diff --git a/source/ps/World.h b/source/ps/World.h index 7c4f45d539..36b53f273c 100644 --- a/source/ps/World.h +++ b/source/ps/World.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -34,7 +34,7 @@ class CMapReader; class CStrW; class CTerrain; class CUnitManager; -class ScriptContext; +namespace Script { class Context; } #ifndef ERROR_GROUP_GAME_DEFINED #define ERROR_GROUP_GAME_DEFINED @@ -56,12 +56,12 @@ public: /* Initialize the World - load the map and all objects */ - void RegisterInit(const CStrW& mapFile, const ScriptContext& cx, JS::HandleValue settings, int playerID); + void RegisterInit(const CStrW& mapFile, const Script::Context& cx, JS::HandleValue settings, int playerID); /* Initialize the World - generate and load the random map */ - void RegisterInitRMS(const CStrW& scriptFile, const ScriptContext& cx, JS::HandleValue settings, int playerID); + void RegisterInitRMS(const CStrW& scriptFile, const Script::Context& cx, JS::HandleValue settings, int playerID); /** * Explicitly delete m_MapReader once the map has finished loading. diff --git a/source/ps/XMB/XMBStorage.cpp b/source/ps/XMB/XMBStorage.cpp index af9a780626..f4b0cb5095 100644 --- a/source/ps/XMB/XMBStorage.cpp +++ b/source/ps/XMB/XMBStorage.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -24,9 +24,9 @@ #include "lib/file/vfs/vfs.h" #include "ps/CLogger.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -155,7 +155,7 @@ void XMBStorageWriter::OutputNames(WriteBuffer& writeBuffer, const std::unordere class JSNodeData { public: - JSNodeData(const ScriptInterface& s) : scriptInterface(s), rq(s) {} + JSNodeData(const Script::Interface& s) : scriptInterface(s), rq(s) {} bool Setup(XMBStorageWriter& xmb, JS::HandleValue value); bool Output(WriteBuffer& writeBuffer, JS::HandleValue value) const; @@ -163,8 +163,8 @@ public: std::vector> m_Attributes; std::vector>> m_Children; - const ScriptInterface& scriptInterface; - const ScriptRequest rq; + const Script::Interface& scriptInterface; + const Script::Request rq; }; template<> @@ -470,7 +470,7 @@ bool XMBStorage::LoadXMLDoc(const xmlDocPtr doc) return true; } -bool XMBStorage::LoadJSValue(const ScriptInterface& scriptInterface, JS::HandleValue value, const std::string& rootName) +bool XMBStorage::LoadJSValue(const Script::Interface& scriptInterface, JS::HandleValue value, const std::string& rootName) { WriteBuffer writeBuffer; diff --git a/source/ps/XMB/XMBStorage.h b/source/ps/XMB/XMBStorage.h index 9bb4375624..29bdee0549 100644 --- a/source/ps/XMB/XMBStorage.h +++ b/source/ps/XMB/XMBStorage.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } typedef struct _xmlDoc xmlDoc; typedef xmlDoc* xmlDocPtr; @@ -106,7 +106,7 @@ public: * * See also tests for some other examples. */ - bool LoadJSValue(const ScriptInterface& scriptInterface, JS::HandleValue value, const std::string& rootName); + bool LoadJSValue(const Script::Interface& scriptInterface, JS::HandleValue value, const std::string& rootName); std::shared_ptr m_Buffer; size_t m_Size = 0; diff --git a/source/ps/XMB/tests/test_XMBData.h b/source/ps/XMB/tests/test_XMBData.h index 12cffe500c..bd61647ed7 100644 --- a/source/ps/XMB/tests/test_XMBData.h +++ b/source/ps/XMB/tests/test_XMBData.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,8 +22,8 @@ #include "ps/XMB/XMBData.h" #include "ps/XMB/XMBStorage.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -38,7 +38,7 @@ class TestXMBData : public CxxTest::TestSuite private: std::shared_ptr m_Buffer; - std::unique_ptr m_ScriptInterface; + std::unique_ptr m_ScriptInterface; CXeromyces parseXML(const char* doc) { @@ -55,7 +55,7 @@ private: CXeromyces parseJS(const std::string rootName, const char* code) { - ScriptRequest rq(*m_ScriptInterface); + Script::Request rq(*m_ScriptInterface); JS::RootedValue val(rq.cx); m_ScriptInterface->Eval(code, &val); CXeromyces xmb; @@ -68,7 +68,7 @@ private: void setUp() { - m_ScriptInterface = std::make_unique("Test", "Test", g_ScriptContext); + m_ScriptInterface = std::make_unique("Test", "Test", g_ScriptContext); } void tearDown() diff --git a/source/ps/scripting/JSInterface_ConfigDB.cpp b/source/ps/scripting/JSInterface_ConfigDB.cpp index a35deb3d73..99312d7873 100644 --- a/source/ps/scripting/JSInterface_ConfigDB.cpp +++ b/source/ps/scripting/JSInterface_ConfigDB.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -208,20 +208,20 @@ void SetGUIScale(float scale) g_VideoMode.Rescale(scale); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&HasChanges>(rq, "ConfigDB_HasChanges"); - ScriptFunction::Register<&SetChanges>(rq, "ConfigDB_SetChanges"); - ScriptFunction::Register<&GetValue>(rq, "ConfigDB_GetValue"); - ScriptFunction::Register<&CreateValue>(rq, "ConfigDB_CreateValue"); - ScriptFunction::Register<&CreateValues>(rq, "ConfigDB_CreateValues"); - ScriptFunction::Register<&RemoveValue>(rq, "ConfigDB_RemoveValue"); - ScriptFunction::Register<&RemoveValueAndSave>(rq, "ConfigDB_RemoveValueAndSave"); - ScriptFunction::Register<&SaveChanges>(rq, "ConfigDB_SaveChanges"); - ScriptFunction::Register<&SaveValue>(rq, "ConfigDB_SaveValue"); - ScriptFunction::Register<&CreateAndSaveValue>(rq, "ConfigDB_CreateAndSaveValue"); - ScriptFunction::Register<&Reload>(rq, "ConfigDB_Reload"); - ScriptFunction::Register<&PauseOnFocusLoss>(rq, "PauseOnFocusLoss"); - ScriptFunction::Register<&SetGUIScale>(rq, "SetGUIScale"); + Script::Function::Register<&HasChanges>(rq, "ConfigDB_HasChanges"); + Script::Function::Register<&SetChanges>(rq, "ConfigDB_SetChanges"); + Script::Function::Register<&GetValue>(rq, "ConfigDB_GetValue"); + Script::Function::Register<&CreateValue>(rq, "ConfigDB_CreateValue"); + Script::Function::Register<&CreateValues>(rq, "ConfigDB_CreateValues"); + Script::Function::Register<&RemoveValue>(rq, "ConfigDB_RemoveValue"); + Script::Function::Register<&RemoveValueAndSave>(rq, "ConfigDB_RemoveValueAndSave"); + Script::Function::Register<&SaveChanges>(rq, "ConfigDB_SaveChanges"); + Script::Function::Register<&SaveValue>(rq, "ConfigDB_SaveValue"); + Script::Function::Register<&CreateAndSaveValue>(rq, "ConfigDB_CreateAndSaveValue"); + Script::Function::Register<&Reload>(rq, "ConfigDB_Reload"); + Script::Function::Register<&PauseOnFocusLoss>(rq, "PauseOnFocusLoss"); + Script::Function::Register<&SetGUIScale>(rq, "SetGUIScale"); } } diff --git a/source/ps/scripting/JSInterface_ConfigDB.h b/source/ps/scripting/JSInterface_ConfigDB.h index 83ede32cf6..3c2b7895d1 100644 --- a/source/ps/scripting/JSInterface_ConfigDB.h +++ b/source/ps/scripting/JSInterface_ConfigDB.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -19,11 +19,11 @@ #define INCLUDED_JSI_CONFIGDB extern bool g_PauseOnFocusLoss; -class ScriptRequest; +namespace Script { class Request; } namespace JSI_ConfigDB { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_CONFIGDB diff --git a/source/ps/scripting/JSInterface_Console.cpp b/source/ps/scripting/JSInterface_Console.cpp index 0900cc19e1..23c5a70c81 100644 --- a/source/ps/scripting/JSInterface_Console.cpp +++ b/source/ps/scripting/JSInterface_Console.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -27,7 +27,7 @@ namespace JS { class CallArgs; } namespace JSI_Console { -CConsole* ConsoleGetter(const ScriptRequest&, JS::CallArgs&) +CConsole* ConsoleGetter(const Script::Request&, JS::CallArgs&) { if (!g_Console) { @@ -37,9 +37,9 @@ CConsole* ConsoleGetter(const ScriptRequest&, JS::CallArgs&) return g_Console; } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&CConsole::IsActive, ConsoleGetter>(rq, "Console_GetVisibleEnabled"); - ScriptFunction::Register<&CConsole::SetVisible, ConsoleGetter>(rq, "Console_SetVisibleEnabled"); + Script::Function::Register<&CConsole::IsActive, ConsoleGetter>(rq, "Console_GetVisibleEnabled"); + Script::Function::Register<&CConsole::SetVisible, ConsoleGetter>(rq, "Console_SetVisibleEnabled"); } } diff --git a/source/ps/scripting/JSInterface_Console.h b/source/ps/scripting/JSInterface_Console.h index 310df57b47..73bfde41fa 100644 --- a/source/ps/scripting/JSInterface_Console.h +++ b/source/ps/scripting/JSInterface_Console.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_CONSOLE #define INCLUDED_JSI_CONSOLE -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Console { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_CONSOLE diff --git a/source/ps/scripting/JSInterface_Debug.cpp b/source/ps/scripting/JSInterface_Debug.cpp index 09df66b0cd..8da6299e33 100644 --- a/source/ps/scripting/JSInterface_Debug.cpp +++ b/source/ps/scripting/JSInterface_Debug.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -100,14 +100,14 @@ std::wstring GetBuildVersion(bool longerHash = false) return buildVersion; } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&GetMicroseconds>(rq, "GetMicroseconds"); - ScriptFunction::Register<&Crash>(rq, "Crash"); - ScriptFunction::Register<&DebugWarn>(rq, "DebugWarn"); - ScriptFunction::Register<&DisplayErrorDialog>(rq, "DisplayErrorDialog"); - ScriptFunction::Register<&GetBuildDate>(rq, "GetBuildDate"); - ScriptFunction::Register<&GetBuildTimestamp>(rq, "GetBuildTimestamp"); - ScriptFunction::Register<&GetBuildVersion>(rq, "GetBuildVersion"); + Script::Function::Register<&GetMicroseconds>(rq, "GetMicroseconds"); + Script::Function::Register<&Crash>(rq, "Crash"); + Script::Function::Register<&DebugWarn>(rq, "DebugWarn"); + Script::Function::Register<&DisplayErrorDialog>(rq, "DisplayErrorDialog"); + Script::Function::Register<&GetBuildDate>(rq, "GetBuildDate"); + Script::Function::Register<&GetBuildTimestamp>(rq, "GetBuildTimestamp"); + Script::Function::Register<&GetBuildVersion>(rq, "GetBuildVersion"); } } diff --git a/source/ps/scripting/JSInterface_Debug.h b/source/ps/scripting/JSInterface_Debug.h index b7753a8c06..affcad532d 100644 --- a/source/ps/scripting/JSInterface_Debug.h +++ b/source/ps/scripting/JSInterface_Debug.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2019 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_DEBUG #define INCLUDED_JSI_DEBUG -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Debug { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_DEBUG diff --git a/source/ps/scripting/JSInterface_Game.cpp b/source/ps/scripting/JSInterface_Game.cpp index 17cf167c51..1b5cb9790b 100644 --- a/source/ps/scripting/JSInterface_Game.cpp +++ b/source/ps/scripting/JSInterface_Game.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -35,7 +35,7 @@ #include "ps/Replay.h" #include "ps/World.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/Simulation2.h" #include "simulation2/system/TurnManager.h" @@ -47,11 +47,11 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } namespace JSI_Game { -void StartGame(const ScriptInterface& guiInterface, JS::HandleValue attribs, int playerID, bool storeReplay) +void StartGame(const Script::Interface& guiInterface, JS::HandleValue attribs, int playerID, bool storeReplay) { ENSURE(!g_NetServer); ENSURE(!g_NetClient); @@ -61,7 +61,7 @@ void StartGame(const ScriptInterface& guiInterface, JS::HandleValue attribs, int // Convert from GUI script context to sim script context/ CSimulation2* sim = g_Game->GetSimulation2(); - ScriptRequest rqSim(sim->GetScriptInterface()); + Script::Request rqSim(sim->GetScriptInterface()); JS::RootedValue gameAttribs(rqSim.cx, Script::CloneValueFromOtherCompartment(sim->GetScriptInterface(), guiInterface, attribs)); @@ -193,22 +193,22 @@ void DumpTerrainMipmap() LOGMESSAGERENDER("Terrain mipmap written to '%s'", realPath.string8()); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&StartGame>(rq, "StartGame"); - ScriptFunction::Register<&Script_EndGame>(rq, "EndGame"); - ScriptFunction::Register<&GetPlayerID>(rq, "GetPlayerID"); - ScriptFunction::Register<&SetPlayerID>(rq, "SetPlayerID"); - ScriptFunction::Register<&SetViewedPlayer>(rq, "SetViewedPlayer"); - ScriptFunction::Register<&GetSimRate>(rq, "GetSimRate"); - ScriptFunction::Register<&SetSimRate>(rq, "SetSimRate"); - ScriptFunction::Register<&GetPendingTurns>(rq, "GetPendingTurns"); - ScriptFunction::Register<&IsPaused>(rq, "IsPaused"); - ScriptFunction::Register<&SetPaused>(rq, "SetPaused"); - ScriptFunction::Register<&IsVisualReplay>(rq, "IsVisualReplay"); - ScriptFunction::Register<&GetCurrentReplayDirectory>(rq, "GetCurrentReplayDirectory"); - ScriptFunction::Register<&EnableTimeWarpRecording>(rq, "EnableTimeWarpRecording"); - ScriptFunction::Register<&RewindTimeWarp>(rq, "RewindTimeWarp"); - ScriptFunction::Register<&DumpTerrainMipmap>(rq, "DumpTerrainMipmap"); + Script::Function::Register<&StartGame>(rq, "StartGame"); + Script::Function::Register<&Script_EndGame>(rq, "EndGame"); + Script::Function::Register<&GetPlayerID>(rq, "GetPlayerID"); + Script::Function::Register<&SetPlayerID>(rq, "SetPlayerID"); + Script::Function::Register<&SetViewedPlayer>(rq, "SetViewedPlayer"); + Script::Function::Register<&GetSimRate>(rq, "GetSimRate"); + Script::Function::Register<&SetSimRate>(rq, "SetSimRate"); + Script::Function::Register<&GetPendingTurns>(rq, "GetPendingTurns"); + Script::Function::Register<&IsPaused>(rq, "IsPaused"); + Script::Function::Register<&SetPaused>(rq, "SetPaused"); + Script::Function::Register<&IsVisualReplay>(rq, "IsVisualReplay"); + Script::Function::Register<&GetCurrentReplayDirectory>(rq, "GetCurrentReplayDirectory"); + Script::Function::Register<&EnableTimeWarpRecording>(rq, "EnableTimeWarpRecording"); + Script::Function::Register<&RewindTimeWarp>(rq, "RewindTimeWarp"); + Script::Function::Register<&DumpTerrainMipmap>(rq, "DumpTerrainMipmap"); } } diff --git a/source/ps/scripting/JSInterface_Game.h b/source/ps/scripting/JSInterface_Game.h index cf83eaa9d5..dc09a168d3 100644 --- a/source/ps/scripting/JSInterface_Game.h +++ b/source/ps/scripting/JSInterface_Game.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2018 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_GAME #define INCLUDED_JSI_GAME -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Game { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_GAME diff --git a/source/ps/scripting/JSInterface_Hotkey.cpp b/source/ps/scripting/JSInterface_Hotkey.cpp index 8a32e8a5b8..c96b9c3ca5 100644 --- a/source/ps/scripting/JSInterface_Hotkey.cpp +++ b/source/ps/scripting/JSInterface_Hotkey.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,8 +26,8 @@ #include "ps/KeyName.h" #include "ps/containers/StaticVector.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -48,7 +48,7 @@ * TODO: this could be moved to ScriptConversions.cpp if the need arises. */ template -static void ToJSVal_unordered_map(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::unordered_map& val) +static void ToJSVal_unordered_map(const Script::Request& rq, JS::MutableHandleValue ret, const std::unordered_map& val) { JS::RootedObject obj(rq.cx, JS_NewPlainObject(rq.cx)); if (!obj) @@ -66,13 +66,13 @@ static void ToJSVal_unordered_map(const ScriptRequest& rq, JS::MutableHandleValu } template<> -void Script::ToJSVal>>>(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::unordered_map>>& val) +void Script::ToJSVal>>>(const Script::Request& rq, JS::MutableHandleValue ret, const std::unordered_map>>& val) { ToJSVal_unordered_map(rq, ret, val); } template<> -void Script::ToJSVal>(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::unordered_map& val) +void Script::ToJSVal>(const Script::Request& rq, JS::MutableHandleValue ret, const std::unordered_map& val) { ToJSVal_unordered_map(rq, ret, val); } @@ -82,7 +82,7 @@ namespace /** * @return a (js) object mapping hotkey name (from cfg files) to a list ofscancode names */ -JS::Value GetHotkeyMap(const ScriptRequest& rq) +JS::Value GetHotkeyMap(const Script::Request& rq) { JS::RootedValue hotkeyMap(rq.cx); @@ -108,7 +108,7 @@ JS::Value GetHotkeyMap(const ScriptRequest& rq) /** * @return a (js) object mapping scancode names to their locale-dependent name. */ -JS::Value GetScancodeKeyNames(const ScriptRequest& rq) +JS::Value GetScancodeKeyNames(const Script::Request& rq) { JS::RootedValue obj(rq.cx); std::unordered_map map; @@ -128,7 +128,7 @@ void ReloadHotkeys() LoadHotkeys(g_ConfigDB); } -JS::Value GetConflicts(const ScriptRequest& rq, JS::HandleValue combination) +JS::Value GetConflicts(const Script::Request& rq, JS::HandleValue combination) { std::vector keys; if (!Script::FromJSVal(rq, combination, keys)) @@ -172,11 +172,11 @@ JS::Value GetConflicts(const ScriptRequest& rq, JS::HandleValue combination) } } -void JSI_Hotkey::RegisterScriptFunctions(const ScriptRequest& rq) +void JSI_Hotkey::RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&HotkeyIsPressed>(rq, "HotkeyIsPressed"); - ScriptFunction::Register<&GetHotkeyMap>(rq, "GetHotkeyMap"); - ScriptFunction::Register<&GetScancodeKeyNames>(rq, "GetScancodeKeyNames"); - ScriptFunction::Register<&ReloadHotkeys>(rq, "ReloadHotkeys"); - ScriptFunction::Register<&GetConflicts>(rq, "GetConflicts"); + Script::Function::Register<&HotkeyIsPressed>(rq, "HotkeyIsPressed"); + Script::Function::Register<&GetHotkeyMap>(rq, "GetHotkeyMap"); + Script::Function::Register<&GetScancodeKeyNames>(rq, "GetScancodeKeyNames"); + Script::Function::Register<&ReloadHotkeys>(rq, "ReloadHotkeys"); + Script::Function::Register<&GetConflicts>(rq, "GetConflicts"); } diff --git a/source/ps/scripting/JSInterface_Hotkey.h b/source/ps/scripting/JSInterface_Hotkey.h index bbb70728f2..37e2faaf87 100644 --- a/source/ps/scripting/JSInterface_Hotkey.h +++ b/source/ps/scripting/JSInterface_Hotkey.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_HOTKEY #define INCLUDED_JSI_HOTKEY -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Hotkey { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_HOTKEY diff --git a/source/ps/scripting/JSInterface_Main.cpp b/source/ps/scripting/JSInterface_Main.cpp index d6a5fa5e2e..4a1b85a946 100644 --- a/source/ps/scripting/JSInterface_Main.cpp +++ b/source/ps/scripting/JSInterface_Main.cpp @@ -37,7 +37,7 @@ #include "ps/Globals.h" #include "ps/Util.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "tools/atlas/GameInterface/GameLoop.h" #include @@ -45,7 +45,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } extern void QuitEngine(int exitStatus); @@ -76,9 +76,9 @@ std::wstring GetMatchID() return ps_generate_guid().FromUTF8(); } -JS::Value LoadMapSettings(const ScriptInterface& scriptInterface, const VfsPath& pathname) +JS::Value LoadMapSettings(const Script::Interface& scriptInterface, const VfsPath& pathname) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); CMapSummaryReader reader; @@ -134,18 +134,18 @@ std::string CalculateMD5(const std::string& input) return Hexify(digest, MD5::DIGESTSIZE); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&QuitEngine>(rq, "Exit"); - ScriptFunction::Register<&AtlasIsAvailable>(rq, "AtlasIsAvailable"); - ScriptFunction::Register<&IsAtlasRunning>(rq, "IsAtlasRunning"); - ScriptFunction::Register<&OpenURL>(rq, "OpenURL"); - ScriptFunction::Register<&GetSystemUsername>(rq, "GetSystemUsername"); - ScriptFunction::Register<&GetMatchID>(rq, "GetMatchID"); - ScriptFunction::Register<&LoadMapSettings>(rq, "LoadMapSettings"); - ScriptFunction::Register<&GetFps>(rq, "GetFPS"); - ScriptFunction::Register<&GetTextSize>(rq, "GetTextSize"); - ScriptFunction::Register<&GetTextWidth>(rq, "GetTextWidth"); - ScriptFunction::Register<&CalculateMD5>(rq, "CalculateMD5"); + Script::Function::Register<&QuitEngine>(rq, "Exit"); + Script::Function::Register<&AtlasIsAvailable>(rq, "AtlasIsAvailable"); + Script::Function::Register<&IsAtlasRunning>(rq, "IsAtlasRunning"); + Script::Function::Register<&OpenURL>(rq, "OpenURL"); + Script::Function::Register<&GetSystemUsername>(rq, "GetSystemUsername"); + Script::Function::Register<&GetMatchID>(rq, "GetMatchID"); + Script::Function::Register<&LoadMapSettings>(rq, "LoadMapSettings"); + Script::Function::Register<&GetFps>(rq, "GetFPS"); + Script::Function::Register<&GetTextSize>(rq, "GetTextSize"); + Script::Function::Register<&GetTextWidth>(rq, "GetTextWidth"); + Script::Function::Register<&CalculateMD5>(rq, "CalculateMD5"); } } diff --git a/source/ps/scripting/JSInterface_Main.h b/source/ps/scripting/JSInterface_Main.h index 4d4786e390..c25c70f8e3 100644 --- a/source/ps/scripting/JSInterface_Main.h +++ b/source/ps/scripting/JSInterface_Main.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2018 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_MAIN #define INCLUDED_JSI_MAIN -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Main { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_MAIN diff --git a/source/ps/scripting/JSInterface_Mod.cpp b/source/ps/scripting/JSInterface_Mod.cpp index 9d1b713774..4731b17b39 100644 --- a/source/ps/scripting/JSInterface_Mod.cpp +++ b/source/ps/scripting/JSInterface_Mod.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,8 +26,8 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -37,8 +37,8 @@ #include #include -class ScriptInterface; namespace JS { class CallArgs; } +namespace Script { class Interface; } extern void RestartEngine(); @@ -46,7 +46,7 @@ extern void RestartEngine(); using ModDataCPtr = const Mod::ModData*; template<> -void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const ModDataCPtr& data) +void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const ModDataCPtr& data) { ret.set(Script::CreateObject(rq)); Script::SetProperty(rq, ret, "mod", data->m_Pathname); @@ -57,7 +57,7 @@ void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const // Required by JSVAL_VECTOR, but can't be implemented. template<> -bool Script::FromJSVal(const ScriptRequest &, const JS::HandleValue, ModDataCPtr&) +bool Script::FromJSVal(const Script::Request &, const JS::HandleValue, ModDataCPtr&) { LOGERROR("Not implemented"); return false; @@ -67,7 +67,7 @@ JSVAL_VECTOR(const Mod::ModData*); // Implement FromJSVal as a non-pointer type. template<> -void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const Mod::ModData& data) +void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const Mod::ModData& data) { ret.set(Script::CreateObject(rq)); Script::SetProperty(rq, ret, "mod", data.m_Pathname); @@ -77,7 +77,7 @@ void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const } template<> -bool Script::FromJSVal(const ScriptRequest& rq, const JS::HandleValue val, Mod::ModData& data) +bool Script::FromJSVal(const Script::Request& rq, const JS::HandleValue val, Mod::ModData& data) { // To avoid errors & for convenience, some retro-compatibility when reading // TODO: remove this once we hit A26. @@ -119,14 +119,14 @@ JSVAL_VECTOR(Mod::ModData); namespace JSI_Mod { -Mod* ModGetter(const ScriptRequest&, JS::CallArgs&) +Mod* ModGetter(const Script::Request&, JS::CallArgs&) { return &g_Mods; } -JS::Value GetEngineInfo(const ScriptInterface& scriptInterface) +JS::Value GetEngineInfo(const Script::Interface& scriptInterface) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue mods(rq.cx); Script::ToJSVal(rq, &mods, g_Mods.GetEnabledModsData()); @@ -144,7 +144,7 @@ JS::Value GetEngineInfo(const ScriptInterface& scriptInterface) return metainfo; } -JS::Value GetAvailableMods(const ScriptRequest& rq) +JS::Value GetAvailableMods(const Script::Request& rq) { JS::RootedValue ret(rq.cx, Script::CreateObject(rq)); for (const Mod::ModData& data : g_Mods.GetAvailableMods()) @@ -186,14 +186,14 @@ bool HasIncompatibleMods() return g_Mods.GetIncompatibleMods().size() > 0; } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register(rq, "GetEngineInfo"); - ScriptFunction::Register(rq, "GetAvailableMods"); - ScriptFunction::Register<&Mod::GetEnabledMods, ModGetter>(rq, "GetEnabledMods"); - ScriptFunction::Register(rq, "AreModsPlayCompatible"); - ScriptFunction::Register (rq, "HasIncompatibleMods"); - ScriptFunction::Register<&Mod::GetIncompatibleMods, ModGetter>(rq, "GetIncompatibleMods"); - ScriptFunction::Register<&SetModsAndRestartEngine>(rq, "SetModsAndRestartEngine"); + Script::Function::Register(rq, "GetEngineInfo"); + Script::Function::Register(rq, "GetAvailableMods"); + Script::Function::Register<&Mod::GetEnabledMods, ModGetter>(rq, "GetEnabledMods"); + Script::Function::Register(rq, "AreModsPlayCompatible"); + Script::Function::Register (rq, "HasIncompatibleMods"); + Script::Function::Register<&Mod::GetIncompatibleMods, ModGetter>(rq, "GetIncompatibleMods"); + Script::Function::Register<&SetModsAndRestartEngine>(rq, "SetModsAndRestartEngine"); } } diff --git a/source/ps/scripting/JSInterface_Mod.h b/source/ps/scripting/JSInterface_Mod.h index 22823b1489..2fb3b93624 100644 --- a/source/ps/scripting/JSInterface_Mod.h +++ b/source/ps/scripting/JSInterface_Mod.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_MOD #define INCLUDED_JSI_MOD -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Mod { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_MOD diff --git a/source/ps/scripting/JSInterface_ModIo.cpp b/source/ps/scripting/JSInterface_ModIo.cpp index dfaa18a666..be7c588864 100644 --- a/source/ps/scripting/JSInterface_ModIo.cpp +++ b/source/ps/scripting/JSInterface_ModIo.cpp @@ -25,7 +25,7 @@ #include "ps/ModIo.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -39,7 +39,7 @@ namespace JS { class CallArgs; } namespace JSI_ModIo { -ModIo* ModIoGetter(const ScriptRequest&, JS::CallArgs&) +ModIo* ModIoGetter(const Script::Request&, JS::CallArgs&) { if (!g_ModIo) { @@ -60,7 +60,7 @@ void StartGetGameId() } // TODO: could provide a FromJSVal for ModIoModData -JS::Value GetMods(const ScriptRequest& rq) +JS::Value GetMods(const Script::Request& rq) { if (!g_ModIo) { @@ -105,7 +105,7 @@ const std::map statusStrings = { }; // TODO: could provide a FromJSVal for DownloadProgressData -JS::Value GetDownloadProgress(const ScriptRequest& rq) +JS::Value GetDownloadProgress(const Script::Request& rq) { if (!g_ModIo) { @@ -125,14 +125,14 @@ JS::Value GetDownloadProgress(const ScriptRequest& rq) return progressData; } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&StartGetGameId>(rq, "ModIoStartGetGameId"); - ScriptFunction::Register<&ModIo::StartListMods, &ModIoGetter>(rq, "ModIoStartListMods"); - ScriptFunction::Register<&ModIo::StartDownloadMod, &ModIoGetter>(rq, "ModIoStartDownloadMod"); - ScriptFunction::Register<&ModIo::AdvanceRequest, &ModIoGetter>(rq, "ModIoAdvanceRequest"); - ScriptFunction::Register<&ModIo::CancelRequest, &ModIoGetter>(rq, "ModIoCancelRequest"); - ScriptFunction::Register<&GetMods>(rq, "ModIoGetMods"); - ScriptFunction::Register<&GetDownloadProgress>(rq, "ModIoGetDownloadProgress"); + Script::Function::Register<&StartGetGameId>(rq, "ModIoStartGetGameId"); + Script::Function::Register<&ModIo::StartListMods, &ModIoGetter>(rq, "ModIoStartListMods"); + Script::Function::Register<&ModIo::StartDownloadMod, &ModIoGetter>(rq, "ModIoStartDownloadMod"); + Script::Function::Register<&ModIo::AdvanceRequest, &ModIoGetter>(rq, "ModIoAdvanceRequest"); + Script::Function::Register<&ModIo::CancelRequest, &ModIoGetter>(rq, "ModIoCancelRequest"); + Script::Function::Register<&GetMods>(rq, "ModIoGetMods"); + Script::Function::Register<&GetDownloadProgress>(rq, "ModIoGetDownloadProgress"); } } diff --git a/source/ps/scripting/JSInterface_ModIo.h b/source/ps/scripting/JSInterface_ModIo.h index 87c4426708..6119efd18c 100644 --- a/source/ps/scripting/JSInterface_ModIo.h +++ b/source/ps/scripting/JSInterface_ModIo.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2018 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_MODIO #define INCLUDED_JSI_MODIO -class ScriptRequest; +namespace Script { class Request; } namespace JSI_ModIo { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_MODIO diff --git a/source/ps/scripting/JSInterface_SavedGame.cpp b/source/ps/scripting/JSInterface_SavedGame.cpp index d6d97463bf..3ec4527d10 100644 --- a/source/ps/scripting/JSInterface_SavedGame.cpp +++ b/source/ps/scripting/JSInterface_SavedGame.cpp @@ -29,7 +29,7 @@ #include "ps/SavedGame.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/Simulation2.h" #include "simulation2/system/TurnManager.h" @@ -40,11 +40,11 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } namespace JSI_SavedGame { -JS::Value GetSavedGames(const ScriptInterface& scriptInterface) +JS::Value GetSavedGames(const Script::Interface& scriptInterface) { return SavedGames::GetSavedGames(scriptInterface); } @@ -54,14 +54,14 @@ bool DeleteSavedGame(const std::wstring& name) return SavedGames::DeleteSavedGame(name); } -void SaveGame(const ScriptRequest& rq, const std::wstring& filename, const std::wstring& description, JS::HandleValue GUIMetadata) +void SaveGame(const Script::Request& rq, const std::wstring& filename, const std::wstring& description, JS::HandleValue GUIMetadata) { Script::StructuredClone GUIMetadataClone = Script::WriteStructuredClone(rq, GUIMetadata); if (SavedGames::Save(filename, description, *g_Game->GetSimulation2(), GUIMetadataClone) < 0) LOGERROR("Failed to save game"); } -void SaveGamePrefix(const ScriptRequest& rq, const std::wstring& prefix, const std::wstring& description, JS::HandleValue GUIMetadata) +void SaveGamePrefix(const Script::Request& rq, const std::wstring& prefix, const std::wstring& description, JS::HandleValue GUIMetadata) { Script::StructuredClone GUIMetadataClone = Script::WriteStructuredClone(rq, GUIMetadata); if (SavedGames::SavePrefix(prefix, description, *g_Game->GetSimulation2(), GUIMetadataClone) < 0) @@ -96,7 +96,7 @@ void QuickLoad() if (!g_GUI || !maybeMetadata.has_value()) return; - const ScriptRequest rq{g_Game->GetSimulation2()->GetScriptInterface()}; + const Script::Request rq{g_Game->GetSimulation2()->GetScriptInterface()}; JS::RootedValue metadata{rq.cx, maybeMetadata.value()}; // Provide a copy, so that GUI components don't have to clone to get mutable objects @@ -109,20 +109,20 @@ void QuickLoad() LOGMESSAGERENDER("Quickloaded game"); } -JS::Value LoadSavedGameMetadata(const ScriptInterface& scriptInterface, const std::wstring& name) +JS::Value LoadSavedGameMetadata(const Script::Interface& scriptInterface, const std::wstring& name) { std::optional data{SavedGames::Load(scriptInterface, name)}; return data ? data->metadata : JS::UndefinedValue(); } -JS::Value StartSavedGame(const ScriptInterface& scriptInterface, const std::wstring& name) +JS::Value StartSavedGame(const Script::Interface& scriptInterface, const std::wstring& name) { // We need to be careful with different compartments and contexts. // The GUI calls this function from the GUI context and expects the return value in the same context. // The game we start from here creates another context and expects data in this context. - ScriptRequest rqGui(scriptInterface); + Script::Request rqGui(scriptInterface); ENSURE(!g_NetServer); ENSURE(!g_NetClient); @@ -139,7 +139,7 @@ JS::Value StartSavedGame(const ScriptInterface& scriptInterface, const std::wstr { CSimulation2* sim = g_Game->GetSimulation2(); - ScriptRequest rqGame(sim->GetScriptInterface()); + Script::Request rqGame(sim->GetScriptInterface()); JS::RootedValue gameContextMetadata(rqGame.cx, Script::CloneValueFromOtherCompartment(sim->GetScriptInterface(), scriptInterface, guiContextMetadata)); JS::RootedValue gameInitAttributes(rqGame.cx); @@ -162,16 +162,16 @@ void ActivateRejoinTest() g_Game->GetSimulation2()->ActivateRejoinTest(g_Game->GetTurnManager()->GetCurrentTurn() + 1); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&GetSavedGames>(rq, "GetSavedGames"); - ScriptFunction::Register<&DeleteSavedGame>(rq, "DeleteSavedGame"); - ScriptFunction::Register<&SaveGame>(rq, "SaveGame"); - ScriptFunction::Register<&SaveGamePrefix>(rq, "SaveGamePrefix"); - ScriptFunction::Register<&QuickSave>(rq, "QuickSave"); - ScriptFunction::Register<&QuickLoad>(rq, "QuickLoad"); - ScriptFunction::Register<&ActivateRejoinTest>(rq, "ActivateRejoinTest"); - ScriptFunction::Register<&LoadSavedGameMetadata>(rq, "LoadSavedGameMetadata"); - ScriptFunction::Register<&StartSavedGame>(rq, "StartSavedGame"); + Script::Function::Register<&GetSavedGames>(rq, "GetSavedGames"); + Script::Function::Register<&DeleteSavedGame>(rq, "DeleteSavedGame"); + Script::Function::Register<&SaveGame>(rq, "SaveGame"); + Script::Function::Register<&SaveGamePrefix>(rq, "SaveGamePrefix"); + Script::Function::Register<&QuickSave>(rq, "QuickSave"); + Script::Function::Register<&QuickLoad>(rq, "QuickLoad"); + Script::Function::Register<&ActivateRejoinTest>(rq, "ActivateRejoinTest"); + Script::Function::Register<&LoadSavedGameMetadata>(rq, "LoadSavedGameMetadata"); + Script::Function::Register<&StartSavedGame>(rq, "StartSavedGame"); } } diff --git a/source/ps/scripting/JSInterface_SavedGame.h b/source/ps/scripting/JSInterface_SavedGame.h index 96b58c4061..6bc65130ca 100644 --- a/source/ps/scripting/JSInterface_SavedGame.h +++ b/source/ps/scripting/JSInterface_SavedGame.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2019 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_SAVEDGAME #define INCLUDED_JSI_SAVEDGAME -class ScriptRequest; +namespace Script { class Request; } namespace JSI_SavedGame { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_SAVEDGAME diff --git a/source/ps/scripting/JSInterface_UserReport.cpp b/source/ps/scripting/JSInterface_UserReport.cpp index 37438647e4..a5186b5aca 100644 --- a/source/ps/scripting/JSInterface_UserReport.cpp +++ b/source/ps/scripting/JSInterface_UserReport.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -58,12 +58,12 @@ std::string GetUserReportConfigPath() return configPath.string8(); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&IsUserReportEnabled>(rq, "IsUserReportEnabled"); - ScriptFunction::Register<&SetUserReportEnabled>(rq, "SetUserReportEnabled"); - ScriptFunction::Register<&GetUserReportStatus>(rq, "GetUserReportStatus"); - ScriptFunction::Register<&GetUserReportLogPath>(rq, "GetUserReportLogPath"); - ScriptFunction::Register<&GetUserReportConfigPath>(rq, "GetUserReportConfigPath"); + Script::Function::Register<&IsUserReportEnabled>(rq, "IsUserReportEnabled"); + Script::Function::Register<&SetUserReportEnabled>(rq, "SetUserReportEnabled"); + Script::Function::Register<&GetUserReportStatus>(rq, "GetUserReportStatus"); + Script::Function::Register<&GetUserReportLogPath>(rq, "GetUserReportLogPath"); + Script::Function::Register<&GetUserReportConfigPath>(rq, "GetUserReportConfigPath"); } } diff --git a/source/ps/scripting/JSInterface_UserReport.h b/source/ps/scripting/JSInterface_UserReport.h index 808259a002..dcaf4a8f9b 100644 --- a/source/ps/scripting/JSInterface_UserReport.h +++ b/source/ps/scripting/JSInterface_UserReport.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2018 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_USERREPORT #define INCLUDED_JSI_USERREPORT -class ScriptRequest; +namespace Script { class Request; } namespace JSI_UserReport { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_USERREPORT diff --git a/source/ps/scripting/JSInterface_VFS.cpp b/source/ps/scripting/JSInterface_VFS.cpp index b4124cf58c..f02c170879 100644 --- a/source/ps/scripting/JSInterface_VFS.cpp +++ b/source/ps/scripting/JSInterface_VFS.cpp @@ -36,8 +36,8 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -56,7 +56,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } namespace JSI_VFS { @@ -119,11 +119,11 @@ bool PathRestrictionMet(const std::wstring& filePath) // state held across multiple BuildDirEntListCB calls; init by BuildDirEntList. struct BuildDirEntListState { - const ScriptRequest& rq; + const Script::Request& rq; JS::PersistentRootedObject filename_array; int cur_idx; - BuildDirEntListState(const ScriptRequest& rq) + BuildDirEntListState(const Script::Request& rq) : rq(rq), filename_array(rq.cx), cur_idx(0) @@ -150,7 +150,7 @@ static Status BuildDirEntListCB(const VfsPath& pathname, const CFileInfo&, uintp // filter_string: default "" matches everything; otherwise, see vfs_next_dirent. // recurse: should subdirectories be included in the search? default false. template -JS::Value BuildDirEntList(const ScriptRequest& rq, const std::wstring& path, const std::wstring& filterStr, +JS::Value BuildDirEntList(const Script::Request& rq, const std::wstring& path, const std::wstring& filterStr, bool recurse) { if (!PathRestrictionMet(path)) @@ -190,7 +190,7 @@ unsigned int GetFileSize(const std::wstring& filename) // Return file contents in a string. Assume file is UTF-8 encoded text. template -JS::Value ReadFile(const ScriptRequest& rq, const std::wstring& filename) +JS::Value ReadFile(const Script::Request& rq, const std::wstring& filename) { if (!PathRestrictionMet(filename)) return JS::NullValue(); @@ -212,7 +212,7 @@ JS::Value ReadFile(const ScriptRequest& rq, const std::wstring& filename) // Return file contents as an array of lines. Assume file is UTF-8 encoded text. template -JS::Value ReadFileLines(const ScriptRequest& rq, const std::wstring& filename) +JS::Value ReadFileLines(const Script::Request& rq, const std::wstring& filename) { if (!PathRestrictionMet(filename)) return JS::NullValue(); @@ -247,9 +247,9 @@ JS::Value ReadFileLines(const ScriptRequest& rq, const std::wstring& filename) // Return file contents parsed as a JS Object template -JS::Value ReadJSONFile(const ScriptInterface& scriptInterface, const std::wstring& filePath) +JS::Value ReadJSONFile(const Script::Interface& scriptInterface, const std::wstring& filePath) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); if (!PathRestrictionMet(filePath)) return JS::NullValue(); @@ -260,10 +260,10 @@ JS::Value ReadJSONFile(const ScriptInterface& scriptInterface, const std::wstrin // Save given JS Object to a JSON file template -void WriteJSONFile(const ScriptInterface& scriptInterface, const std::wstring& filePath, +void WriteJSONFile(const Script::Interface& scriptInterface, const std::wstring& filePath, JS::HandleValue val1) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); if (!PathRestrictionMet(filePath)) return; @@ -301,32 +301,32 @@ bool DeleteCampaignSave(const CStrW& filePath) return !ec; } -void RegisterScriptFunctions_ReadWriteAnywhere(const ScriptRequest& rq, +void RegisterScriptFunctions_ReadWriteAnywhere(const Script::Request& rq, const u16 flags /*= JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT */) { - ScriptFunction::Register<&BuildDirEntList>(rq, "ListDirectoryFiles", flags); - ScriptFunction::Register<&FileExists>(rq, "FileExists", flags); - ScriptFunction::Register<&GetFileSize>(rq, "GetFileSize", flags); - ScriptFunction::Register<&ReadFile>(rq, "ReadFile", flags); - ScriptFunction::Register<&ReadFileLines>(rq, "ReadFileLines", flags); - ScriptFunction::Register<&ReadJSONFile>(rq, "ReadJSONFile", flags); - ScriptFunction::Register<&WriteJSONFile>(rq, "WriteJSONFile", flags); - ScriptFunction::Register<&DeleteCampaignSave>(rq, "DeleteCampaignSave", flags); + Script::Function::Register<&BuildDirEntList>(rq, "ListDirectoryFiles", flags); + Script::Function::Register<&FileExists>(rq, "FileExists", flags); + Script::Function::Register<&GetFileSize>(rq, "GetFileSize", flags); + Script::Function::Register<&ReadFile>(rq, "ReadFile", flags); + Script::Function::Register<&ReadFileLines>(rq, "ReadFileLines", flags); + Script::Function::Register<&ReadJSONFile>(rq, "ReadJSONFile", flags); + Script::Function::Register<&WriteJSONFile>(rq, "WriteJSONFile", flags); + Script::Function::Register<&DeleteCampaignSave>(rq, "DeleteCampaignSave", flags); } -void RegisterScriptFunctions_ReadOnlySimulation(const ScriptRequest& rq, +void RegisterScriptFunctions_ReadOnlySimulation(const Script::Request& rq, const u16 flags /*= JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT */) { - ScriptFunction::Register<&BuildDirEntList>(rq, "ListDirectoryFiles", flags); - ScriptFunction::Register<&FileExists>(rq, "FileExists", flags); - ScriptFunction::Register<&ReadJSONFile>(rq, "ReadJSONFile", flags); + Script::Function::Register<&BuildDirEntList>(rq, "ListDirectoryFiles", flags); + Script::Function::Register<&FileExists>(rq, "FileExists", flags); + Script::Function::Register<&ReadJSONFile>(rq, "ReadJSONFile", flags); } -void RegisterScriptFunctions_ReadOnlySimulationMaps(const ScriptRequest& rq, +void RegisterScriptFunctions_ReadOnlySimulationMaps(const Script::Request& rq, const u16 flags /*= JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT */) { - ScriptFunction::Register<&BuildDirEntList>(rq, "ListDirectoryFiles", flags); - ScriptFunction::Register<&FileExists>(rq, "FileExists", flags); - ScriptFunction::Register<&ReadJSONFile>(rq, "ReadJSONFile", flags); + Script::Function::Register<&BuildDirEntList>(rq, "ListDirectoryFiles", flags); + Script::Function::Register<&FileExists>(rq, "FileExists", flags); + Script::Function::Register<&ReadJSONFile>(rq, "ReadJSONFile", flags); } } diff --git a/source/ps/scripting/JSInterface_VFS.h b/source/ps/scripting/JSInterface_VFS.h index b572fbe4fc..9e13b1eb49 100644 --- a/source/ps/scripting/JSInterface_VFS.h +++ b/source/ps/scripting/JSInterface_VFS.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,15 +22,15 @@ #include -class ScriptRequest; +namespace Script { class Request; } namespace JSI_VFS { - void RegisterScriptFunctions_ReadWriteAnywhere(const ScriptRequest& rq, + void RegisterScriptFunctions_ReadWriteAnywhere(const Script::Request& rq, const u16 flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); - void RegisterScriptFunctions_ReadOnlySimulation(const ScriptRequest& rq, + void RegisterScriptFunctions_ReadOnlySimulation(const Script::Request& rq, const u16 flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); - void RegisterScriptFunctions_ReadOnlySimulationMaps(const ScriptRequest& rq, + void RegisterScriptFunctions_ReadOnlySimulationMaps(const Script::Request& rq, const u16 flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); } diff --git a/source/ps/scripting/JSInterface_VisualReplay.cpp b/source/ps/scripting/JSInterface_VisualReplay.cpp index c938d8ead4..67e4be250d 100644 --- a/source/ps/scripting/JSInterface_VisualReplay.cpp +++ b/source/ps/scripting/JSInterface_VisualReplay.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -35,15 +35,15 @@ CStrW GetReplayDirectoryName(const CStrW& directoryName) return wstring_from_utf8(OsPath(VisualReplay::GetDirectoryPath() / directoryName).string8()); } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&VisualReplay::GetReplays>(rq, "GetReplays"); - ScriptFunction::Register<&VisualReplay::DeleteReplay>(rq, "DeleteReplay"); - ScriptFunction::Register<&VisualReplay::StartVisualReplay>(rq, "StartVisualReplay"); - ScriptFunction::Register<&VisualReplay::GetReplayAttributes>(rq, "GetReplayAttributes"); - ScriptFunction::Register<&VisualReplay::GetReplayMetadata>(rq, "GetReplayMetadata"); - ScriptFunction::Register<&VisualReplay::HasReplayMetadata>(rq, "HasReplayMetadata"); - ScriptFunction::Register<&VisualReplay::AddReplayToCache>(rq, "AddReplayToCache"); - ScriptFunction::Register<&GetReplayDirectoryName>(rq, "GetReplayDirectoryName"); + Script::Function::Register<&VisualReplay::GetReplays>(rq, "GetReplays"); + Script::Function::Register<&VisualReplay::DeleteReplay>(rq, "DeleteReplay"); + Script::Function::Register<&VisualReplay::StartVisualReplay>(rq, "StartVisualReplay"); + Script::Function::Register<&VisualReplay::GetReplayAttributes>(rq, "GetReplayAttributes"); + Script::Function::Register<&VisualReplay::GetReplayMetadata>(rq, "GetReplayMetadata"); + Script::Function::Register<&VisualReplay::HasReplayMetadata>(rq, "HasReplayMetadata"); + Script::Function::Register<&VisualReplay::AddReplayToCache>(rq, "AddReplayToCache"); + Script::Function::Register<&GetReplayDirectoryName>(rq, "GetReplayDirectoryName"); } } diff --git a/source/ps/scripting/JSInterface_VisualReplay.h b/source/ps/scripting/JSInterface_VisualReplay.h index bb13477ef0..db2fcb37d2 100644 --- a/source/ps/scripting/JSInterface_VisualReplay.h +++ b/source/ps/scripting/JSInterface_VisualReplay.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2017 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_VISUALREPLAY #define INCLUDED_JSI_VISUALREPLAY -class ScriptRequest; +namespace Script { class Request; } namespace JSI_VisualReplay { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_VISUALREPLAY diff --git a/source/ps/tests/test_Mod.h b/source/ps/tests/test_Mod.h index 2cf5d9d34c..6b5a1af421 100644 --- a/source/ps/tests/test_Mod.h +++ b/source/ps/tests/test_Mod.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,8 +24,8 @@ #include "ps/CStr.h" #include "ps/Mod.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -91,9 +91,9 @@ public: void test_compatible() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Request rq(script); JS::RootedObject obj(rq.cx, JS_NewPlainObject(rq.cx)); m_Mods.m_AvailableMods = { @@ -141,9 +141,9 @@ public: void test_different_name_and_path() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Request rq(script); JS::RootedObject obj(rq.cx, JS_NewPlainObject(rq.cx)); m_Mods.m_AvailableMods = { diff --git a/source/ps/tests/test_ModIo.h b/source/ps/tests/test_ModIo.h index 99f6cc243c..8baf4a32c5 100644 --- a/source/ps/tests/test_ModIo.h +++ b/source/ps/tests/test_ModIo.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,7 +24,7 @@ #include "ps/CLogger.h" #include "ps/ModIo.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include #include @@ -46,7 +46,7 @@ public: void test_id_parsing() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); #define TS_ASSERT_PARSE(input, expected_error, expected_id) \ { \ @@ -94,7 +94,7 @@ public: void test_mods_parsing() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); PKStruct pk; diff --git a/source/renderer/backend/IDevice.h b/source/renderer/backend/IDevice.h index 8d8949ce22..b5f2fd150b 100644 --- a/source/renderer/backend/IDevice.h +++ b/source/renderer/backend/IDevice.h @@ -33,7 +33,6 @@ class CShaderDefines; class CStr; -class ScriptRequest; namespace Renderer::Backend { class IComputePipelineState; } namespace Renderer::Backend { class IDeviceCommandContext; } namespace Renderer::Backend { class IFramebuffer; } @@ -51,6 +50,7 @@ namespace Renderer::Backend { struct SDepthStencilAttachment; } namespace Renderer::Backend { struct SGraphicsPipelineStateDesc; } namespace Renderer::Backend { struct SVertexAttributeFormat; } namespace Renderer::Backend::Sampler { struct Desc; } +namespace Script { class Request; } typedef struct SDL_Window SDL_Window; @@ -93,7 +93,7 @@ public: virtual const std::string& GetDriverInformation() const = 0; virtual const std::vector& GetExtensions() const = 0; - virtual void Report(const ScriptRequest& rq, JS::HandleValue settings) = 0; + virtual void Report(const Script::Request& rq, JS::HandleValue settings) = 0; virtual std::unique_ptr CreateCommandContext() = 0; diff --git a/source/renderer/backend/dummy/Device.cpp b/source/renderer/backend/dummy/Device.cpp index df840ff822..c53f0e0e75 100644 --- a/source/renderer/backend/dummy/Device.cpp +++ b/source/renderer/backend/dummy/Device.cpp @@ -64,7 +64,7 @@ CDevice::CDevice() CDevice::~CDevice() = default; -void CDevice::Report(const ScriptRequest& rq, JS::HandleValue settings) +void CDevice::Report(const Script::Request& rq, JS::HandleValue settings) { Script::SetProperty(rq, settings, "name", "dummy"); } diff --git a/source/renderer/backend/dummy/Device.h b/source/renderer/backend/dummy/Device.h index ee86123c98..04c217f4f3 100644 --- a/source/renderer/backend/dummy/Device.h +++ b/source/renderer/backend/dummy/Device.h @@ -55,7 +55,7 @@ public: const std::string& GetDriverInformation() const override { return m_DriverInformation; } const std::vector& GetExtensions() const override { return m_Extensions; } - void Report(const ScriptRequest& rq, JS::HandleValue settings) override; + void Report(const Script::Request& rq, JS::HandleValue settings) override; std::unique_ptr CreateCommandContext() override; diff --git a/source/renderer/backend/gl/Device.cpp b/source/renderer/backend/gl/Device.cpp index 4a5159400d..a12a4d98c4 100644 --- a/source/renderer/backend/gl/Device.cpp +++ b/source/renderer/backend/gl/Device.cpp @@ -484,7 +484,7 @@ CDevice::~CDevice() SDL_GL_DeleteContext(m_Context); } -void CDevice::Report(const ScriptRequest& rq, JS::HandleValue settings) +void CDevice::Report(const Script::Request& rq, JS::HandleValue settings) { const char* errstr = "(error)"; diff --git a/source/renderer/backend/gl/Device.h b/source/renderer/backend/gl/Device.h index dcba647b52..6bbee288c4 100644 --- a/source/renderer/backend/gl/Device.h +++ b/source/renderer/backend/gl/Device.h @@ -69,7 +69,7 @@ public: const std::string& GetDriverInformation() const override { return m_DriverInformation; } const std::vector& GetExtensions() const override { return m_Extensions; } - void Report(const ScriptRequest& rq, JS::HandleValue settings) override; + void Report(const Script::Request& rq, JS::HandleValue settings) override; std::unique_ptr CreateCommandContext() override; diff --git a/source/renderer/backend/vulkan/Device.cpp b/source/renderer/backend/vulkan/Device.cpp index 00e3ee21f2..a78c17ccd8 100644 --- a/source/renderer/backend/vulkan/Device.cpp +++ b/source/renderer/backend/vulkan/Device.cpp @@ -44,7 +44,7 @@ #include "renderer/backend/vulkan/Texture.h" #include "renderer/backend/vulkan/Utilities.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -703,7 +703,7 @@ CDevice::~CDevice() vkDestroyInstance(m_Instance, nullptr); } -void CDevice::Report(const ScriptRequest& rq, JS::HandleValue settings) +void CDevice::Report(const Script::Request& rq, JS::HandleValue settings) { Script::SetProperty(rq, settings, "name", "vulkan"); diff --git a/source/renderer/backend/vulkan/Device.h b/source/renderer/backend/vulkan/Device.h index 91b4e4a366..97a5b6d7f0 100644 --- a/source/renderer/backend/vulkan/Device.h +++ b/source/renderer/backend/vulkan/Device.h @@ -80,7 +80,7 @@ public: const std::string& GetDriverInformation() const override { return m_DriverInformation; } const std::vector& GetExtensions() const override { return m_Extensions; } - void Report(const ScriptRequest& rq, JS::HandleValue settings) override; + void Report(const Script::Request& rq, JS::HandleValue settings) override; std::unique_ptr CreateCommandContext() override; diff --git a/source/renderer/backend/vulkan/DeviceSelection.cpp b/source/renderer/backend/vulkan/DeviceSelection.cpp index 3300c4a65a..470ecd7d72 100644 --- a/source/renderer/backend/vulkan/DeviceSelection.cpp +++ b/source/renderer/backend/vulkan/DeviceSelection.cpp @@ -22,7 +22,7 @@ #include "ps/CLogger.h" #include "renderer/backend/vulkan/Utilities.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -336,7 +336,7 @@ bool IsSurfaceFormatSupported( } void ReportAvailablePhysicalDevice(const SAvailablePhysicalDevice& device, - const ScriptRequest& rq, JS::HandleValue settings) + const Script::Request& rq, JS::HandleValue settings) { Script::SetProperty(rq, settings, "name", device.properties.deviceName); Script::SetProperty(rq, settings, "version", diff --git a/source/renderer/backend/vulkan/DeviceSelection.h b/source/renderer/backend/vulkan/DeviceSelection.h index 961eac0763..7f7c781c3d 100644 --- a/source/renderer/backend/vulkan/DeviceSelection.h +++ b/source/renderer/backend/vulkan/DeviceSelection.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ #include #include -class ScriptRequest; +namespace Script { class Request; } namespace Renderer { @@ -97,7 +97,7 @@ bool IsSurfaceFormatSupported( * Report all desired information about the available physical device. */ void ReportAvailablePhysicalDevice(const SAvailablePhysicalDevice& device, - const ScriptRequest& rq, JS::HandleValue settings); + const Script::Request& rq, JS::HandleValue settings); } // namespace Vulkan diff --git a/source/renderer/scripting/JSInterface_Renderer.cpp b/source/renderer/scripting/JSInterface_Renderer.cpp index 14d3dfb226..9ece8a2fcb 100644 --- a/source/renderer/scripting/JSInterface_Renderer.cpp +++ b/source/renderer/scripting/JSInterface_Renderer.cpp @@ -78,17 +78,17 @@ void SetPBRBrightness(const float value) } #define REGISTER_BOOLEAN_SCRIPT_SETTING(NAME) \ -ScriptFunction::Register<&Get##NAME##Enabled>(rq, "Renderer_Get" #NAME "Enabled"); \ -ScriptFunction::Register<&Set##NAME##Enabled>(rq, "Renderer_Set" #NAME "Enabled"); +Script::Function::Register<&Get##NAME##Enabled>(rq, "Renderer_Get" #NAME "Enabled"); \ +Script::Function::Register<&Set##NAME##Enabled>(rq, "Renderer_Set" #NAME "Enabled"); -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&GetRenderPath>(rq, "Renderer_GetRenderPath"); - ScriptFunction::Register<&TextureExists>(rq, "TextureExists"); - ScriptFunction::Register<&GetRenderDebugMode>(rq, "Renderer_GetRenderDebugMode"); - ScriptFunction::Register<&SetRenderDebugMode>(rq, "Renderer_SetRenderDebugMode"); - ScriptFunction::Register<&GetPBRBrightness>(rq, "Renderer_GetPBRBrightness"); - ScriptFunction::Register<&SetPBRBrightness>(rq, "Renderer_SetPBRBrightness"); + Script::Function::Register<&GetRenderPath>(rq, "Renderer_GetRenderPath"); + Script::Function::Register<&TextureExists>(rq, "TextureExists"); + Script::Function::Register<&GetRenderDebugMode>(rq, "Renderer_GetRenderDebugMode"); + Script::Function::Register<&SetRenderDebugMode>(rq, "Renderer_SetRenderDebugMode"); + Script::Function::Register<&GetPBRBrightness>(rq, "Renderer_GetPBRBrightness"); + Script::Function::Register<&SetPBRBrightness>(rq, "Renderer_SetPBRBrightness"); REGISTER_BOOLEAN_SCRIPT_SETTING(CutsceneMode); REGISTER_BOOLEAN_SCRIPT_SETTING(DisplayFrustum); REGISTER_BOOLEAN_SCRIPT_SETTING(DisplayShadowsFrustum); diff --git a/source/renderer/scripting/JSInterface_Renderer.h b/source/renderer/scripting/JSInterface_Renderer.h index 325bcf736e..6a0d01dc04 100644 --- a/source/renderer/scripting/JSInterface_Renderer.h +++ b/source/renderer/scripting/JSInterface_Renderer.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSINTERFACE_RENDERER #define INCLUDED_JSINTERFACE_RENDERER -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Renderer { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSINTERFACE_RENDERER diff --git a/source/rlinterface/RLInterface.cpp b/source/rlinterface/RLInterface.cpp index 8f220b39e2..f134c655b1 100644 --- a/source/rlinterface/RLInterface.cpp +++ b/source/rlinterface/RLInterface.cpp @@ -34,8 +34,8 @@ #include "scriptinterface/JSON.h" #include "ps/TaskManager.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpAIInterface.h" #include "simulation2/components/ICmpTemplateManager.h" @@ -287,8 +287,8 @@ void Interface::ApplyMessage(const GameMessage& msg) EndGame(); g_Game = new CGame(m_ScenarioConfig.saveReplay); - ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue attrs(rq.cx); Script::ParseJSON(rq, m_ScenarioConfig.content, &attrs); @@ -328,12 +328,12 @@ void Interface::ApplyMessage(const GameMessage& msg) m_MsgLock.unlock(); return; } - const ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); CLocalTurnManager* turnMgr = static_cast(g_Game->GetTurnManager()); for (const GameCommand& command : msg.commands) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue commandJSON(rq.cx); Script::ParseJSON(rq, command.json_cmd, &commandJSON); turnMgr->PostCommand(command.playerID, commandJSON); @@ -364,8 +364,8 @@ void Interface::ApplyMessage(const GameMessage& msg) m_MsgLock.unlock(); return; } - const ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue ret(rq.cx); scriptInterface.Eval(m_Code.c_str(), &ret); m_ReturnValue = Script::StringifyJSON(rq, &ret, false); @@ -380,10 +380,10 @@ void Interface::ApplyMessage(const GameMessage& msg) std::string Interface::GetGameState() const { - const ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); const CSimContext simContext = g_Game->GetSimulation2()->GetSimContext(); CmpPtr cmpAIInterface(simContext.GetSystemEntity()); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue state(rq.cx); cmpAIInterface->GetFullRepresentation(&state, true); return Script::StringifyJSON(rq, &state, false); diff --git a/source/scriptinterface/ScriptContext.cpp b/source/scriptinterface/Context.cpp similarity index 88% rename from source/scriptinterface/ScriptContext.cpp rename to source/scriptinterface/Context.cpp index e36d1edb00..90ed6dfb4e 100644 --- a/source/scriptinterface/ScriptContext.cpp +++ b/source/scriptinterface/Context.cpp @@ -17,7 +17,7 @@ #include "precompiled.h" -#include "ScriptContext.h" +#include "Context.h" #include "js/Modules.h" #include "js/friend/PerformanceHint.h" @@ -28,7 +28,7 @@ #include "ps/ThreadUtil.h" #include "scriptinterface/ModuleLoader.h" #include "scriptinterface/Promises.h" -#include "scriptinterface/ScriptEngine.h" +#include "scriptinterface/Engine.h" #include #include @@ -102,12 +102,15 @@ void GCSliceCallbackHook(JSContext*, JS::GCProgress progress, const JS::GCDescri #endif } -ScriptContext::ScriptContext(int contextSize, uint32_t heapGrowthBytesGCTrigger): - m_JobQueue{std::make_unique()}, +namespace Script +{ + +Context::Context(int contextSize, uint32_t heapGrowthBytesGCTrigger): + m_JobQueue{std::make_unique()}, m_ContextSize{contextSize}, m_HeapGrowthBytesGCTrigger{heapGrowthBytesGCTrigger} { - ENSURE(ScriptEngine::IsInitialised() && "The ScriptEngine must be initialized before constructing any ScriptContexts!"); + ENSURE(Engine::IsInitialised() && "The Script::Engine must be initialized before constructing any ScriptContexts!"); m_cx = JS_NewContext(contextSize); ENSURE(m_cx); // TODO: error handling @@ -156,20 +159,20 @@ ScriptContext::ScriptContext(int contextSize, uint32_t heapGrowthBytesGCTrigger) // See https://gitea.wildfiregames.com/0ad/0ad/issues/7714 for details. js::gc::SetPerformanceHint(m_cx, js::gc::PerformanceHint::InPageLoad); - ScriptEngine::GetSingleton().RegisterContext(m_cx); + Engine::GetSingleton().RegisterContext(m_cx); JS::SetJobQueue(m_cx, m_JobQueue.get()); - JS::SetPromiseRejectionTrackerCallback(m_cx, &Script::UnhandledRejectedPromise); + JS::SetPromiseRejectionTrackerCallback(m_cx, &UnhandledRejectedPromise); JSRuntime* runtime{JS_GetRuntime(m_cx)}; - JS::SetModuleMetadataHook(runtime, &Script::ModuleLoader::MetadataHook); - JS::SetModuleResolveHook(runtime, &Script::ModuleLoader::ResolveHook); - JS::SetModuleDynamicImportHook(runtime, &Script::ModuleLoader::DynamicImportHook); + JS::SetModuleMetadataHook(runtime, &ModuleLoader::MetadataHook); + JS::SetModuleResolveHook(runtime, &ModuleLoader::ResolveHook); + JS::SetModuleDynamicImportHook(runtime, &ModuleLoader::DynamicImportHook); } -ScriptContext::~ScriptContext() +Context::~Context() { - ENSURE(ScriptEngine::IsInitialised() && "The ScriptEngine must be active (initialized and not yet shut down) when destroying a ScriptContext!"); + ENSURE(Engine::IsInitialised() && "The Script::Engine must be active (initialized and not yet shut down) when destroying a Script::Context!"); JSRuntime* runtime{JS_GetRuntime(m_cx)}; JS::SetModuleDynamicImportHook(runtime, nullptr); @@ -180,16 +183,16 @@ ScriptContext::~ScriptContext() js::gc::SetPerformanceHint(m_cx, js::gc::PerformanceHint::Normal); JS_DestroyContext(m_cx); - ScriptEngine::GetSingleton().UnRegisterContext(m_cx); + Engine::GetSingleton().UnRegisterContext(m_cx); } -void ScriptContext::RegisterRealm(JS::Realm* realm) +void Context::RegisterRealm(JS::Realm* realm) { ENSURE(realm); m_Realms.push_back(realm); } -void ScriptContext::UnRegisterRealm(JS::Realm* realm) +void Context::UnRegisterRealm(JS::Realm* realm) { // Schedule the zone for GC, which will destroy the realm. if (JS::IsIncrementalGCInProgress(m_cx)) @@ -199,7 +202,7 @@ void ScriptContext::UnRegisterRealm(JS::Realm* realm) } #define GC_DEBUG_PRINT 0 -void ScriptContext::MaybeIncrementalGC() +void Context::MaybeIncrementalGC() { PROFILE2("MaybeIncrementalGC"); @@ -267,7 +270,7 @@ void ScriptContext::MaybeIncrementalGC() } } -void ScriptContext::ShrinkingGC() +void Context::ShrinkingGC() { JS_SetGCParameter(m_cx, JSGC_INCREMENTAL_GC_ENABLED, false); JS_SetGCParameter(m_cx, JSGC_PER_ZONE_GC_ENABLED, true); @@ -277,13 +280,15 @@ void ScriptContext::ShrinkingGC() JS_SetGCParameter(m_cx, JSGC_PER_ZONE_GC_ENABLED, false); } -void ScriptContext::RunJobs() +void Context::RunJobs() { m_JobQueue->runJobs(m_cx); } -void ScriptContext::PrepareZonesForIncrementalGC() const +void Context::PrepareZonesForIncrementalGC() const { for (JS::Realm* const& realm : m_Realms) JS::PrepareZoneForGC(m_cx, js::GetRealmZone(realm)); } + +} // namespace Script \ No newline at end of file diff --git a/source/scriptinterface/ScriptContext.h b/source/scriptinterface/Context.h similarity index 87% rename from source/scriptinterface/ScriptContext.h rename to source/scriptinterface/Context.h index 391e19671b..f796d935f0 100644 --- a/source/scriptinterface/ScriptContext.h +++ b/source/scriptinterface/Context.h @@ -15,8 +15,8 @@ * along with 0 A.D. If not, see . */ -#ifndef INCLUDED_SCRIPTCONTEXT -#define INCLUDED_SCRIPTCONTEXT +#ifndef INCLUDED_SCRIPT_CONTEXT +#define INCLUDED_SCRIPT_CONTEXT #include #include @@ -37,14 +37,17 @@ class JobQueue; /** * Abstraction around a SpiderMonkey JSContext. * - * A single ScriptContext, with the associated context, + * A single Script::Context, with the associated context, * should only be used on a single thread. * * (One means to share data between threads and contexts is to create * a Script::StructuredClone.) */ -class ScriptContext +namespace Script +{ + +class Context { public: /** @@ -54,9 +57,9 @@ public: * @param contextSize Maximum size in bytes of the new context * @param heapGrowthBytesGCTrigger Size in bytes of cumulated allocations after which a GC will be triggered */ - ScriptContext(int contextSize = DEFAULT_CONTEXT_SIZE, + Context(int contextSize = DEFAULT_CONTEXT_SIZE, uint32_t heapGrowthBytesGCTrigger = DEFAULT_HEAP_GROWTH_BYTES_GCTRIGGER); - ~ScriptContext(); + ~Context(); /** * MaybeIncrementalGC checks if running a GC is worth the time that will take. @@ -95,15 +98,15 @@ public: * GetGeneralJSContext returns the context without starting a GC request and without * entering any compartment. It should only be used in specific situations, such as * creating a new compartment, or when initializing a persistent rooted. - * If you need the compartmented context of a ScriptInterface, you should create a - * ScriptRequest and use the context from that. + * If you need the compartmented context of a Interface, you should create a + * Request and use the context from that. */ JSContext* GetGeneralJSContext() const { return m_cx; } private: JSContext* m_cx; - const std::unique_ptr m_JobQueue; + const std::unique_ptr m_JobQueue; void PrepareZonesForIncrementalGC() const; std::list m_Realms; @@ -113,8 +116,10 @@ private: uint32_t m_LastGCBytes{0}; }; +} + // Using a global object for the context is a workaround until Simulation, AI, etc, // use their own threads and also their own contexts. -extern thread_local std::shared_ptr g_ScriptContext; +extern thread_local std::shared_ptr g_ScriptContext; -#endif // INCLUDED_SCRIPTCONTEXT +#endif // INCLUDED_SCRIPT_CONTEXT diff --git a/source/scriptinterface/ScriptConversions.cpp b/source/scriptinterface/Conversions.cpp similarity index 59% rename from source/scriptinterface/ScriptConversions.cpp rename to source/scriptinterface/Conversions.cpp index a95eded33f..8a65fbd377 100644 --- a/source/scriptinterface/ScriptConversions.cpp +++ b/source/scriptinterface/Conversions.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -17,13 +17,13 @@ #include "precompiled.h" -#include "ScriptConversions.h" +#include "Conversions.h" #include "graphics/Entity.h" #include "lib/path.h" #include "ps/CStr.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Request.h" #include #include @@ -32,24 +32,26 @@ #include #include +namespace Script{ + // Catch the raised exception right away to ensure the stack trace gets printed. -#define FAIL(msg) STMT(ScriptException::Raise(rq, msg); ScriptException::CatchPending(rq); return false) +#define FAIL(msg) STMT(Exception::Raise(rq, msg); Exception::CatchPending(rq); return false) // Implicit type conversions often hide bugs, so fail. #define FAIL_IF_NOT(c, v) STMT(if (!(c)) { \ - ScriptException::Raise(rq, "Script value conversion check failed: %s (got type %s)", #c, JS::InformalValueTypeName(v)); \ - ScriptException::CatchPending(rq); \ + Exception::Raise(rq, "Script value conversion check failed: %s (got type %s)", #c, JS::InformalValueTypeName(v)); \ + Exception::CatchPending(rq); \ return false; \ }) -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, bool& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, bool& out) { FAIL_IF_NOT(v.isBoolean(), v); out = JS::ToBoolean(v); return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, float& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, float& out) { double tmp; FAIL_IF_NOT(v.isNumber(), v); @@ -59,7 +61,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValu return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, double& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, double& out) { FAIL_IF_NOT(v.isNumber(), v); if (!JS::ToNumber(rq.cx, v, &out)) @@ -67,7 +69,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleVa return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, i32& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, i32& out) { FAIL_IF_NOT(v.isNumber(), v); if (!JS::ToInt32(rq.cx, v, &out)) @@ -75,7 +77,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, u32& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, u32& out) { FAIL_IF_NOT(v.isNumber(), v); if (!JS::ToUint32(rq.cx, v, &out)) @@ -83,7 +85,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, u16& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, u16& out) { FAIL_IF_NOT(v.isNumber(), v); if (!JS::ToUint16(rq.cx, v, &out)) @@ -91,7 +93,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, u8& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, u8& out) { u16 tmp; FAIL_IF_NOT(v.isNumber(), v); @@ -101,7 +103,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, std::wstring& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, std::wstring& out) { FAIL_IF_NOT(v.isString() || v.isNumber() || v.isBoolean(), v); // allow implicit boolean/number conversions JS::RootedString str(rq.cx, JS::ToString(rq.cx, v)); @@ -131,7 +133,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::Ha return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, Path& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, Path& out) { std::wstring string; if (!FromJSVal(rq, v, string)) @@ -140,7 +142,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValu return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, std::string& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, std::string& out) { std::wstring wideout; if (!FromJSVal(rq, v, wideout)) @@ -149,17 +151,17 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::Han return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CStr8& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, CStr8& out) { - return Script::FromJSVal(rq, v, static_cast(out)); + return FromJSVal(rq, v, static_cast(out)); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CStrW& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, CStrW& out) { - return Script::FromJSVal(rq, v, static_cast(out)); + return FromJSVal(rq, v, static_cast(out)); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, Entity& out) +template<> bool FromJSVal(const Request& rq, JS::HandleValue v, Entity& out) { if (!v.isObject()) FAIL("Argument must be an object"); @@ -189,42 +191,42 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleVa //////////////////////////////////////////////////////////////// // Primitive types: -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const bool& val) +template<> void ToJSVal(const Request&, JS::MutableHandleValue ret, const bool& val) { ret.setBoolean(val); } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const float& val) +template<> void ToJSVal(const Request&, JS::MutableHandleValue ret, const float& val) { ret.set(JS::NumberValue(val)); } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const double& val) +template<> void ToJSVal(const Request&, JS::MutableHandleValue ret, const double& val) { ret.set(JS::NumberValue(val)); } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const i32& val) +template<> void ToJSVal(const Request&, JS::MutableHandleValue ret, const i32& val) { ret.set(JS::NumberValue(val)); } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const u16& val) +template<> void ToJSVal(const Request&, JS::MutableHandleValue ret, const u16& val) { ret.set(JS::NumberValue(val)); } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const u8& val) +template<> void ToJSVal(const Request&, JS::MutableHandleValue ret, const u8& val) { ret.set(JS::NumberValue(val)); } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const u32& val) +template<> void ToJSVal(const Request&, JS::MutableHandleValue ret, const u32& val) { ret.set(JS::NumberValue(val)); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::wstring& val) +template<> void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const std::wstring& val) { std::u16string utf16(val.begin(), val.end()); JS::RootedString str(rq.cx, JS_NewUCStringCopyN(rq.cx, utf16.c_str(), utf16.length())); @@ -234,22 +236,22 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::Muta ret.setUndefined(); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const Path& val) +template<> void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const Path& val) { ToJSVal(rq, ret, val.string()); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::string& val) +template<> void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const std::string& val) { ToJSVal(rq, ret, static_cast(CStr(val).FromUTF8())); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const wchar_t* const& val) +template<> void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const wchar_t* const& val) { ToJSVal(rq, ret, std::wstring(val)); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const char* const& val) +template<> void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const char* const& val) { JS::RootedString str(rq.cx, JS_NewStringCopyZ(rq.cx, val)); if (str) @@ -258,16 +260,18 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::Mutab ret.setUndefined(); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CStrW& val) +template<> void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const CStrW& val) { ToJSVal(rq, ret, static_cast(val)); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CStr8& val) +template<> void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const CStr8& val) { ToJSVal(rq, ret, static_cast(val)); } +} //namespace Script + //////////////////////////////////////////////////////////////// // Compound types // Instantiate various vector types: @@ -283,17 +287,16 @@ JSVAL_VECTOR(CStrW) JSVAL_VECTOR(std::vector) JSVAL_VECTOR(std::vector) - class IComponent; -template<> void Script::ToJSVal>(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::vector& val) +template<> void Script::ToJSVal>(const Script::Request& rq, JS::MutableHandleValue ret, const std::vector& val) { - ToJSVal_vector(rq, ret, val); + Script::ToJSVal_vector(rq, ret, val); } -template<> bool Script::FromJSVal>(const ScriptRequest& rq, JS::HandleValue v, std::vector& out) +template<> bool Script::FromJSVal>(const Script::Request& rq, JS::HandleValue v, std::vector& out) { - return FromJSVal_vector(rq, v, out); + return Script::FromJSVal_vector(rq, v, out); } #undef FAIL -#undef FAIL_IF_NOT +#undef FAIL_IF_NOT \ No newline at end of file diff --git a/source/scriptinterface/ScriptConversions.h b/source/scriptinterface/Conversions.h similarity index 66% rename from source/scriptinterface/ScriptConversions.h rename to source/scriptinterface/Conversions.h index b7602c9f03..12c9e83674 100644 --- a/source/scriptinterface/ScriptConversions.h +++ b/source/scriptinterface/Conversions.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,8 +22,8 @@ #include "lib/debug.h" #include "lib/types.h" #include "ps/CStr.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Request.h" #include #include @@ -42,10 +42,10 @@ namespace Script /** * Convert a JS::Value to a C++ type. (This might trigger GC.) */ -template bool FromJSVal(const ScriptRequest& rq, const JS::HandleValue val, T& ret); +template bool FromJSVal(const Request& rq, const JS::HandleValue val, T& ret); template -bool FromJSVal(const ScriptRequest& rq, JS::HandleValue v, std::optional& out) +bool FromJSVal(const Request& rq, JS::HandleValue v, std::optional& out) { if (v.isNullOrUndefined()) { @@ -66,42 +66,42 @@ bool FromJSVal(const ScriptRequest& rq, JS::HandleValue v, std::optional& out * The reason is a memory corruption problem that appears to be caused by a bug in Visual Studio. * Details here: http://www.wildfiregames.com/forum/index.php?showtopic=17289&p=285921 */ -template void ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, T const& val); +template void ToJSVal(const Request& rq, JS::MutableHandleValue ret, T const& val); template -void ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const char (&val)[N]) +void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const char (&val)[N]) { ToJSVal(rq, ret, static_cast(val)); } template -void ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const wchar_t (&val)[N]) +void ToJSVal(const Request& rq, JS::MutableHandleValue ret, const wchar_t (&val)[N]) { ToJSVal(rq, ret, static_cast(val)); } template<> -inline void ToJSVal(const ScriptRequest&, JS::MutableHandleValue handle, +inline void ToJSVal(const Request&, JS::MutableHandleValue handle, const JS::PersistentRootedValue& a) { handle.set(a); } template<> -inline void ToJSVal >(const ScriptRequest&, JS::MutableHandleValue handle, +inline void ToJSVal >(const Request&, JS::MutableHandleValue handle, const JS::Heap& a) { handle.set(a); } template<> -inline void ToJSVal(const ScriptRequest&, JS::MutableHandleValue handle, +inline void ToJSVal(const Request&, JS::MutableHandleValue handle, const JS::RootedValue& a) { handle.set(a); } template <> -inline void ToJSVal(const ScriptRequest&, JS::MutableHandleValue handle, +inline void ToJSVal(const Request&, JS::MutableHandleValue handle, const JS::HandleValue& a) { handle.set(a); @@ -110,7 +110,7 @@ inline void ToJSVal(const ScriptRequest&, JS::MutableHandleValu /** * Convert a named property of an object to a C++ type. */ -template inline bool FromJSProperty(const ScriptRequest& rq, const JS::HandleValue val, const char* name, T& ret, bool strict = false) +template inline bool FromJSProperty(const Request& rq, const JS::HandleValue val, const char* name, T& ret, bool strict = false) { if (!val.isObject()) return false; @@ -131,7 +131,7 @@ template inline bool FromJSProperty(const ScriptRequest& rq, const J return FromJSVal(rq, value, ret); } -template inline void ToJSVal_vector(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::vector& val) +template inline void ToJSVal_vector(const Request& rq, JS::MutableHandleValue ret, const std::vector& val) { JS::RootedObject obj(rq.cx, JS::NewArrayObject(rq.cx, 0)); if (!obj) @@ -144,15 +144,15 @@ template inline void ToJSVal_vector(const ScriptRequest& rq, JS::Mut for (u32 i = 0; i < val.size(); ++i) { JS::RootedValue el(rq.cx); - Script::ToJSVal(rq, &el, val[i]); + ToJSVal(rq, &el, val[i]); JS_SetElement(rq.cx, obj, i, el); } ret.setObject(*obj); } -#define FAIL(msg) STMT(ScriptException::Raise(rq, msg); return false) +#define FAIL(msg) STMT(Exception::Raise(rq, msg); return false) -template inline bool FromJSVal_vector(const ScriptRequest& rq, JS::HandleValue v, std::vector& out) +template inline bool FromJSVal_vector(const Request& rq, JS::HandleValue v, std::vector& out) { JS::RootedObject obj(rq.cx); if (!v.isObject()) @@ -175,7 +175,7 @@ template inline bool FromJSVal_vector(const ScriptRequest& rq, JS::H if (!JS_GetElement(rq.cx, obj, i, &el)) FAIL("Failed to read array element"); T el2{}; - if (!Script::FromJSVal(rq, el, el2)) + if (!FromJSVal(rq, el, el2)) return false; out.push_back(el2); } @@ -184,16 +184,18 @@ template inline bool FromJSVal_vector(const ScriptRequest& rq, JS::H #undef FAIL -#define JSVAL_VECTOR(T) \ -template<> void Script::ToJSVal >(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::vector& val) \ -{ \ - ToJSVal_vector(rq, ret, val); \ -} \ -template<> bool Script::FromJSVal >(const ScriptRequest& rq, JS::HandleValue v, std::vector& out) \ -{ \ - return FromJSVal_vector(rq, v, out); \ -} - } // namespace Script +#define JSVAL_VECTOR(T) \ +namespace Script { \ +template<> void ToJSVal >(const Request& rq, JS::MutableHandleValue ret, const std::vector& val) \ +{ \ + ToJSVal_vector(rq, ret, val); \ +} \ +template<> bool FromJSVal >(const Request& rq, JS::HandleValue v, std::vector& out) \ +{ \ + return FromJSVal_vector(rq, v, out); \ +} \ +} + #endif //INCLUDED_SCRIPTCONVERSIONS diff --git a/source/scriptinterface/ScriptEngine.h b/source/scriptinterface/Engine.h similarity index 89% rename from source/scriptinterface/ScriptEngine.h rename to source/scriptinterface/Engine.h index 5a8f65f5ca..b56b29a736 100644 --- a/source/scriptinterface/ScriptEngine.h +++ b/source/scriptinterface/Engine.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -15,8 +15,8 @@ * along with 0 A.D. If not, see . */ -#ifndef INCLUDED_SCRIPTENGINE -#define INCLUDED_SCRIPTENGINE +#ifndef INCLUDED_SCRIPT_ENGINE +#define INCLUDED_SCRIPT_ENGINE #include "lib/debug.h" #include "ps/Singleton.h" @@ -41,16 +41,19 @@ struct JSContext; * 2. JS_Shutdown must be called after all ScriptContexts have been destroyed */ -class ScriptEngine : public Singleton +namespace Script +{ + +class Engine : public Singleton { public: - ScriptEngine() + Engine() { ENSURE(m_Contexts.empty() && "JS_Init must be called before any contexts are created!"); JS_Init(); } - ~ScriptEngine() + ~Engine() { ENSURE(m_Contexts.empty() && "All contexts must be destroyed before calling JS_ShutDown!"); JS_ShutDown(); @@ -63,4 +66,6 @@ private: std::list m_Contexts; }; -#endif // INCLUDED_SCRIPTENGINE +} + +#endif // INCLUDED_SCRIPT_ENGINE diff --git a/source/scriptinterface/ScriptExceptions.cpp b/source/scriptinterface/Exceptions.cpp similarity index 84% rename from source/scriptinterface/ScriptExceptions.cpp rename to source/scriptinterface/Exceptions.cpp index 71ed5494a7..d816c1e6dc 100644 --- a/source/scriptinterface/ScriptExceptions.cpp +++ b/source/scriptinterface/Exceptions.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,7 +18,7 @@ #include "precompiled.h" -#include "ScriptExceptions.h" +#include "Exceptions.h" #include "lib/code_annotation.h" #include "lib/debug.h" @@ -26,8 +26,8 @@ #include "ps/CLogger.h" #include "ps/CStr.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -39,12 +39,14 @@ #include #include -bool ScriptException::IsPending(const ScriptRequest& rq) +namespace Script { + +bool Exception::IsPending(const Request& rq) { return JS_IsExceptionPending(rq.cx); } -bool ScriptException::CatchPending(const ScriptRequest& rq) +bool Exception::CatchPending(const Request& rq) { if (!JS_IsExceptionPending(rq.cx)) return false; @@ -63,7 +65,7 @@ bool ScriptException::CatchPending(const ScriptRequest& rq) if (!excn.isObject()) { CStr error; - Script::FromJSVal(rq, excn, error); + FromJSVal(rq, excn, error); LOGERROR("JavaScript error: %s", error); return true; } @@ -74,7 +76,7 @@ bool ScriptException::CatchPending(const ScriptRequest& rq) if (!report) { CStr error; - Script::FromJSVal(rq, excn, error); + FromJSVal(rq, excn, error); LOGERROR("JavaScript error: %s", error); return true; } @@ -95,7 +97,7 @@ bool ScriptException::CatchPending(const ScriptRequest& rq) if (!stackVal.isNull()) { std::string stackText; - ScriptFunction::Call(rq, stackVal, "toString", stackText); + Script::Function::Call(rq, stackVal, "toString", stackText); std::istringstream stream(stackText); for (std::string line; std::getline(stream, line);) @@ -106,7 +108,7 @@ bool ScriptException::CatchPending(const ScriptRequest& rq) return true; } -void ScriptException::Raise(const ScriptRequest& rq, const char* format, ...) +void Exception::Raise(const Request& rq, const char* format, ...) { va_list ap; va_start(ap, format); @@ -117,3 +119,5 @@ void ScriptException::Raise(const ScriptRequest& rq, const char* format, ...) // Rather annoyingly, there are no va_list versions of this function, hence the preformatting above. JS_ReportErrorUTF8(rq.cx, "%s", buffer); } + +} // namespace Script \ No newline at end of file diff --git a/source/scriptinterface/ScriptExceptions.h b/source/scriptinterface/Exceptions.h similarity index 81% rename from source/scriptinterface/ScriptExceptions.h rename to source/scriptinterface/Exceptions.h index 823c4bdeba..a90d413e20 100644 --- a/source/scriptinterface/ScriptExceptions.h +++ b/source/scriptinterface/Exceptions.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -15,17 +15,19 @@ * along with 0 A.D. If not, see . */ -#ifndef INCLUDED_SCRIPTEXCEPTIONS -#define INCLUDED_SCRIPTEXCEPTIONS +#ifndef INCLUDED_SCRIPT_EXCEPTIONS +#define INCLUDED_SCRIPT_EXCEPTIONS -class ScriptRequest; +namespace Script { class Request; } -namespace ScriptException +namespace Script +{ +namespace Exception { /** * @return Whether there is a JS exception pending. */ -bool IsPending(const ScriptRequest& rq); +bool IsPending(const Request& rq); /** * Log and then clear the current pending exception. This function should always be called after calling a @@ -35,7 +37,7 @@ bool IsPending(const ScriptRequest& rq); * Note that JS code that wants to throw errors should throw new Error(...), otherwise the stack cannot be used. * @return Whether there was a pending exception. */ -bool CatchPending(const ScriptRequest& rq); +bool CatchPending(const Request& rq); /** * Raise a JS exception from C++ code. @@ -43,7 +45,8 @@ bool CatchPending(const ScriptRequest& rq); * as the latter overwrites the pending exception. * Prefer either simply logging an error if you know a stack-trace will be raised elsewhere. */ -void Raise(const ScriptRequest& rq, const char* format, ...); +void Raise(const Request& rq, const char* format, ...); } -#endif // INCLUDED_SCRIPTEXCEPTIONS +} +#endif // INCLUDED_SCRIPT_EXCEPTIONS diff --git a/source/scriptinterface/ScriptForward.h b/source/scriptinterface/ForwardDeclarations.h similarity index 89% rename from source/scriptinterface/ScriptForward.h rename to source/scriptinterface/ForwardDeclarations.h index 476af48aa7..2d760a523d 100644 --- a/source/scriptinterface/ScriptForward.h +++ b/source/scriptinterface/ForwardDeclarations.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -30,8 +30,11 @@ namespace js { class BaseProxyHandler; } -class ScriptContext; -class ScriptInterface; -class ScriptRequest; +namespace Script +{ +class Context; +class Interface; +class Request; +} #endif // INCLUDED_SCRIPTFORWARD diff --git a/source/scriptinterface/FunctionWrapper.h b/source/scriptinterface/FunctionWrapper.h index 5e39d6a626..3d88de0220 100644 --- a/source/scriptinterface/FunctionWrapper.h +++ b/source/scriptinterface/FunctionWrapper.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -19,9 +19,9 @@ #define INCLUDED_FUNCTIONWRAPPER #include "lib/types.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Request.h" #include #include @@ -48,37 +48,41 @@ class JSFunction; class JSObject; -class ScriptInterface; namespace JS { class GCContext; } +namespace Script { class Interface; } struct JSContext; /** * This class introduces templates to conveniently wrap C++ functions in JSNative functions. * This _is_ rather template heavy, so compilation times beware. * The C++ code can have arbitrary arguments and arbitrary return types, so long - * as they can be converted to/from JS using Script::ToJSVal (FromJSVal respectively), + * as they can be converted to/from JS using ToJSVal (FromJSVal respectively), * and they are default-constructible (TODO: that can probably changed). * (This could be a namespace, but I like being able to specify public/private). */ -class ScriptFunction + +namespace Script +{ + +class Function { private: - ScriptFunction() = delete; - ScriptFunction(const ScriptFunction&) = delete; - ScriptFunction(ScriptFunction&&) = delete; + Function() = delete; + Function(const Function&) = delete; + Function(Function&&) = delete; /** * In JS->C++ calls, types are converted using FromJSVal, * and this requires them to be default-constructible (as that function takes an out parameter) * thus constref needs to be removed when defining the tuple. * Exceptions are: - * - const ScriptRequest& (as the first argument only, for implementation simplicity). - * - const ScriptInterface& (as the first argument only, for implementation simplicity). + * - const Request& (as the first argument only, for implementation simplicity). + * - const Interface& (as the first argument only, for implementation simplicity). * - JS::HandleValue */ template using type_transform = std::conditional_t< - std::is_same_v || std::is_same_v, + std::is_same_v || std::is_same_v, T, std::remove_const_t> >; @@ -124,7 +128,7 @@ private: * @param wentOk - true if the conversion succeeded and wentOk was true before, false otherwise. */ template - static T DoConvertFromJS([[maybe_unused]] const ScriptRequest& rq, + static T DoConvertFromJS([[maybe_unused]] const Request& rq, [[maybe_unused]] JS::CallArgs& args, [[maybe_unused]] bool& wentOk) { // No need to convert JS values. @@ -146,7 +150,7 @@ private: else { T ret; - wentOk &= Script::FromJSVal(rq, args[idx], ret); + wentOk &= FromJSVal(rq, args[idx], ret); return ret; } } @@ -156,7 +160,7 @@ private: * Wrapper: calls DoConvertFromJS for each element in T. */ template - static std::tuple DoConvertFromJS(std::index_sequence, const ScriptRequest& rq, + static std::tuple DoConvertFromJS(std::index_sequence, const Request& rq, JS::CallArgs& args, bool& wentOk) { return {DoConvertFromJS(rq, args, wentOk)...}; @@ -164,32 +168,32 @@ private: /** * ConvertFromJS is a wrapper around DoConvertFromJS, and handles specific cases for the - * first argument (ScriptRequest, ...). + * first argument (Request, ...). * * Trick: to unpack the types of the tuple as a parameter pack, we deduce them from the function signature. * To do that, we want the tuple in the arguments, but we don't want to actually have to default-instantiate, * so we'll pass a nullptr that's static_cast to what we want. */ template - static std::tuple ConvertFromJS(const ScriptRequest& rq, JS::CallArgs& args, bool& wentOk, + static std::tuple ConvertFromJS(const Request& rq, JS::CallArgs& args, bool& wentOk, std::tuple*) { return DoConvertFromJS(std::index_sequence_for(), rq, args, wentOk); } - // Overloads for ScriptRequest& first argument. + // Overloads for Request& first argument. template - static std::tuple ConvertFromJS(const ScriptRequest& rq, - JS::CallArgs& args, bool& wentOk, std::tuple*) + static std::tuple ConvertFromJS(const Request& rq, + JS::CallArgs& args, bool& wentOk, std::tuple*) { return std::tuple_cat(std::tie(rq), DoConvertFromJS( std::index_sequence_for(), rq, args, wentOk)); } - // Overloads for ScriptInterface& first argument. + // Overloads for Interface& first argument. template - static std::tuple ConvertFromJS(const ScriptRequest& rq, - JS::CallArgs& args, bool& wentOk, std::tuple*) + static std::tuple ConvertFromJS(const Request& rq, + JS::CallArgs& args, bool& wentOk, std::tuple*) { return std::tuple_cat(std::tie(rq.GetScriptInterface()), DoConvertFromJS(std::index_sequence_for(), rq, args, wentOk)); @@ -224,10 +228,10 @@ private: * For references like `rq` this warning isn't issued. */ template - static void ToJSValVector(std::index_sequence, const ScriptRequest& rq, + static void ToJSValVector(std::index_sequence, const Request& rq, [[maybe_unused]] JS::MutableHandleValueVector argv, const Types&... params) { - (Script::ToJSVal(rq, argv[idx], params), ...); + (ToJSVal(rq, argv[idx], params), ...); } /** @@ -237,7 +241,7 @@ private: * This could be worked around with more templates, but it doesn't seem particularly worth doing. */ template - static bool Call_(const ScriptRequest& rq, JS::HandleValue val, const char* name, + static bool Call_(const Request& rq, JS::HandleValue val, const char* name, [[maybe_unused]] R& ret, const Args&... args) { JS::RootedObject obj(rq.cx); @@ -263,11 +267,11 @@ private: if constexpr (!std::is_same_v) { if (success) - success = Script::FromJSVal(rq, jsRet, ret); + success = FromJSVal(rq, jsRet, ret); } } // Even if everything succeeded, there could be pending exceptions - return !ScriptException::CatchPending(rq) && success; + return !Exception::CatchPending(rq) && success; } struct StatefullCallbackPrivateSlot @@ -281,7 +285,7 @@ private: /////////////////////////////////////////////////////////////////////////// public: template - using ObjectGetter = T*(*)(const ScriptRequest&, JS::CallArgs&); + using ObjectGetter = T*(*)(const Request&, JS::CallArgs&); template using GetterFor = ObjectGetter::object_type>; @@ -291,10 +295,10 @@ public: * so that it can be called from JS and manipulated in Spidermonkey. * Most C++ functions can be directly wrapped, so long as their arguments are * convertible from JS::Value and their return value is convertible to JS::Value (or void) - * The C++ function may optionally take const ScriptRequest& or ScriptInterface& as its first argument. + * The C++ function may optionally take const Request& or Interface& as its first argument. * The function may be an object method, in which case you need to pass an appropriate getter * - * Optimisation note: the ScriptRequest object is created even without arguments, + * Optimisation note: the Request object is created even without arguments, * as it's necessary for IsExceptionPending. * * @param thisGetter to get the object, if necessary. @@ -305,11 +309,11 @@ public: using ObjType = typename args_info::object_type; JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - ScriptRequest rq(cx); + Request rq(cx); // If the callable is an object method, we must specify how to fetch the object. static_assert(std::is_same_v::object_type, void> || thisGetter != nullptr, - "ScriptFunction::Register - No getter specified for object method"); + "Function::Register - No getter specified for object method"); // GCC 7 triggers spurious warnings #ifdef __GNUC__ @@ -340,17 +344,17 @@ public: else if constexpr (std::is_same_v::return_type>) args.rval().set(call(obj, outs)); else - Script::ToJSVal(rq, args.rval(), call(obj, outs)); + ToJSVal(rq, args.rval(), call(obj, outs)); - return !ScriptException::IsPending(rq); + return !Exception::IsPending(rq); } catch (const std::exception& e) { - ScriptException::Raise(rq, "%s", e.what()); + Exception::Raise(rq, "%s", e.what()); } catch (...) { - ScriptException::Raise(rq, "Unknown error occured in an Engine callback."); + Exception::Raise(rq, "Unknown error occured in an Engine callback."); } return false; } @@ -361,14 +365,14 @@ public: * @return the success (or failure) thereof. */ template - static bool Call(const ScriptRequest& rq, JS::HandleValue val, const char* name, R& ret, const Args&... args) + static bool Call(const Request& rq, JS::HandleValue val, const char* name, R& ret, const Args&... args) { return Call_(rq, val, name, ret, std::forward(args)...); } // Specialisation for MutableHandleValue return. template - static bool Call(const ScriptRequest& rq, JS::HandleValue val, const char* name, JS::MutableHandleValue ret, const Args&... args) + static bool Call(const Request& rq, JS::HandleValue val, const char* name, JS::MutableHandleValue ret, const Args&... args) { return Call_(rq, val, name, ret, std::forward(args)...); } @@ -378,7 +382,7 @@ public: * @return the success (or failure) thereof. */ template - static bool CallVoid(const ScriptRequest& rq, JS::HandleValue val, const char* name, const Args&... args) + static bool CallVoid(const Request& rq, JS::HandleValue val, const char* name, const Args&... args) { return Call(rq, val, name, IgnoreResult, std::forward(args)...); } @@ -389,17 +393,17 @@ public: * @return the final value of the generator. */ template - static JS::Value RunGenerator(const ScriptRequest& rq, JS::HandleValue val, const char* name, + static JS::Value RunGenerator(const Request& rq, JS::HandleValue val, const char* name, JS::HandleValue arg, Callback yieldCallback) { JS::RootedValue generator{rq.cx}; - if (!ScriptFunction::Call(rq, val, name, &generator, arg)) + if (!Function::Call(rq, val, name, &generator, arg)) throw std::runtime_error{fmt::format("Failed to call the generator `{}`.", name)}; const auto continueGenerator = [&](const char* property, auto... args) -> JS::Value { JS::RootedValue iteratorResult{rq.cx}; - if (!ScriptFunction::Call(rq, generator, property, &iteratorResult, args...)) + if (!Function::Call(rq, generator, property, &iteratorResult, args...)) throw std::runtime_error{fmt::format("Failed to call `{}`.", name)}; return iteratorResult; }; @@ -415,7 +419,7 @@ public: JS::RootedObject iteratorResultObject{rq.cx, &iteratorResult.toObject()}; bool done; - if (!Script::FromJSProperty(rq, iteratorResult, "done", done, true)) + if (!FromJSProperty(rq, iteratorResult, "done", done, true)) throw IteratorResultError{"done"}; JS::RootedValue value{rq.cx}; @@ -430,7 +434,7 @@ public: catch (const std::exception& e) { JS::RootedValue global{rq.cx, rq.globalValue()}; - if (!ScriptFunction::Call(rq, global, "Error", &error, e.what())) + if (!Function::Call(rq, global, "Error", &error, e.what())) throw std::runtime_error{"Failed to construct `Error`."}; } } @@ -450,7 +454,7 @@ public: * Return a JSFunction from a C++ function. */ template thisGetter = nullptr> - static JSFunction* Create(const ScriptRequest& rq, const char* name, + static JSFunction* Create(const Request& rq, const char* name, const u16 flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) { return JS_NewFunction(rq.cx, &ToJSNative, args_info::nb_args, flags, name); @@ -460,7 +464,7 @@ public: * Register a function on the native scope (usually 'Engine'). */ template thisGetter = nullptr> - static void Register(const ScriptRequest& rq, const char* name, + static void Register(const Request& rq, const char* name, const u16 flags = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT) { JS_DefineFunction(rq.cx, rq.nativeScope, name, &ToJSNative, args_info::nb_args, flags); @@ -468,7 +472,7 @@ public: /** * Register a function on @param scope. - * Prefer the version taking ScriptRequest unless you have a good reason not to. + * Prefer the version taking Request unless you have a good reason not to. * @see Register */ template thisGetter = nullptr> @@ -498,12 +502,12 @@ public: &classOps}; }; public: - explicit StatefulCallback(const ScriptRequest& rq, std::string name, Callable callable) : + explicit StatefulCallback(const Request& rq, std::string name, Callable callable) : StatefulCallback{rq, std::move(name), JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT, std::move(callable)} {} - explicit StatefulCallback(const ScriptRequest& rq, std::string name, const unsigned flags, + explicit StatefulCallback(const Request& rq, std::string name, const unsigned flags, Callable callable) : callback{std::move(callable)}, functionObject{rq.cx} @@ -534,7 +538,7 @@ public: } private: - static Callable* getter(const ScriptRequest&, JS::CallArgs& args) + static Callable* getter(const Request&, JS::CallArgs& args) { return JS::GetMaybePtrFromReservedSlot(&args.callee(), StatefullCallbackPrivateSlot::callback); @@ -551,18 +555,20 @@ public: }; template - static StatefulCallback Register(const ScriptRequest& rq, std::string name, + static StatefulCallback Register(const Request& rq, std::string name, const unsigned flags, Callable callable) { return StatefulCallback{rq, std::move(name), flags, std::move(callable)}; } template - static StatefulCallback Register(const ScriptRequest& rq, std::string name, + static StatefulCallback Register(const Request& rq, std::string name, Callable callable) { return StatefulCallback{rq, std::move(name), std::move(callable)}; } }; +} + #endif // INCLUDED_FUNCTIONWRAPPER diff --git a/source/scriptinterface/ScriptInterface.cpp b/source/scriptinterface/Interface.cpp similarity index 77% rename from source/scriptinterface/ScriptInterface.cpp rename to source/scriptinterface/Interface.cpp index 0ca2a0e2ab..e7db6a21f6 100644 --- a/source/scriptinterface/ScriptInterface.cpp +++ b/source/scriptinterface/Interface.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -17,7 +17,7 @@ #include "precompiled.h" -#include "ScriptInterface.h" +#include "Interface.h" #include "lib/debug.h" #include "lib/file/vfs/vfs_path.h" @@ -32,8 +32,8 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/ModuleLoader.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptStats.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Stats.h" #include "scriptinterface/StructuredClone.h" #include @@ -74,17 +74,20 @@ namespace mozilla { union Utf8Unit; } * directly accessing the underlying JS api. */ -struct ScriptInterface_impl +namespace Script { - ScriptInterface_impl(const char* nativeScopeName, ScriptContext& context, + +struct Interface_impl +{ + Interface_impl(const char* nativeScopeName, Context& context, JS::Compartment* compartment, std::function allowModule); - ~ScriptInterface_impl(); + ~Interface_impl(); // Take care to keep this declaration before heap rooted members. Destructors of heap rooted // members have to be called before the context destructor. - ScriptContext& m_context; + Context& m_context; - friend ScriptRequest; + friend Request; private: JSContext* m_cx; JS::PersistentRootedObject m_glob; // global scope object @@ -92,13 +95,13 @@ struct ScriptInterface_impl public: boost::rand48* m_rng; JS::PersistentRootedObject m_nativeScope; // native function scope object - Script::ModuleLoader m_ModuleLoader; + ModuleLoader m_ModuleLoader; }; /** - * Constructor for ScriptRequest - here because it needs access into ScriptInterface_impl. + * Constructor for Request - here because it needs access into Interface_impl. */ -ScriptRequest::ScriptRequest(const ScriptInterface& scriptInterface) : +Request::Request(const Interface& scriptInterface) : cx(scriptInterface.m->m_cx), glob(scriptInterface.m->m_glob), nativeScope(scriptInterface.m->m_nativeScope), @@ -107,25 +110,27 @@ ScriptRequest::ScriptRequest(const ScriptInterface& scriptInterface) : m_FormerRealm = JS::EnterRealm(cx, scriptInterface.m->m_glob); } -ScriptRequest::~ScriptRequest() +Request::~Request() { JS::LeaveRealm(cx, m_FormerRealm); } -ScriptRequest::ScriptRequest(JSContext* cx) : ScriptRequest(ScriptInterface::CmptPrivate::GetScriptInterface(cx)) +Request::Request(JSContext* cx) : Request(Interface::CmptPrivate::GetScriptInterface(cx)) { } -JS::Value ScriptRequest::globalValue() const +JS::Value Request::globalValue() const { return JS::ObjectValue(*glob); } -const ScriptInterface& ScriptRequest::GetScriptInterface() const +const Interface& Request::GetScriptInterface() const { return m_ScriptInterface; } +} // namespace Script + namespace { @@ -146,7 +151,7 @@ JSClass global_class = { bool print(JSContext* cx, uint argc, JS::Value* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - ScriptRequest rq(cx); + Script::Request rq(cx); for (uint i = 0; i < args.length(); ++i) { @@ -169,7 +174,7 @@ bool logmsg(JSContext* cx, uint argc, JS::Value* vp) return true; } - ScriptRequest rq(cx); + Script::Request rq(cx); std::wstring str; if (!Script::FromJSVal(rq, args[0], str)) return false; @@ -187,7 +192,7 @@ bool warn(JSContext* cx, uint argc, JS::Value* vp) return true; } - ScriptRequest rq(cx); + Script::Request rq(cx); std::wstring str; if (!Script::FromJSVal(rq, args[0], str)) return false; @@ -205,7 +210,7 @@ bool error(JSContext* cx, uint argc, JS::Value* vp) return true; } - ScriptRequest rq(cx); + Script::Request rq(cx); std::wstring str; if (!Script::FromJSVal(rq, args[0], str)) return false; @@ -214,29 +219,29 @@ bool error(JSContext* cx, uint argc, JS::Value* vp) return true; } -JS::Value deepcopy(const ScriptRequest& rq, JS::HandleValue val) +JS::Value deepcopy(const Script::Request& rq, JS::HandleValue val) { if (val.isNullOrUndefined()) { - ScriptException::Raise(rq, "deepcopy requires one argument."); + Script::Exception::Raise(rq, "deepcopy requires one argument."); return JS::UndefinedValue(); } JS::RootedValue ret(rq.cx, Script::DeepCopy(rq, val)); if (ret.isNullOrUndefined()) { - ScriptException::Raise(rq, "deepcopy StructureClone copy failed."); + Script::Exception::Raise(rq, "deepcopy StructureClone copy failed."); return JS::UndefinedValue(); } return ret; } -JS::Value deepfreeze(const ScriptInterface& scriptInterface, JS::HandleValue val) +JS::Value deepfreeze(const Script::Interface& scriptInterface, JS::HandleValue val) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); if (!val.isObject()) { - ScriptException::Raise(rq, "deepfreeze requires exactly one object as an argument."); + Script::Exception::Raise(rq, "deepfreeze requires exactly one object as an argument."); return JS::UndefinedValue(); } @@ -307,7 +312,10 @@ static double generate_uniform_real(boost::rand48& rng, double min, double max) } // anonymous namespace -bool ScriptInterface::MathRandom(double& nbr) const +namespace Script +{ + +bool Interface::MathRandom(double& nbr) const { if (m->m_rng == nullptr) return false; @@ -315,18 +323,18 @@ bool ScriptInterface::MathRandom(double& nbr) const return true; } -bool ScriptInterface::Math_random(JSContext* cx, uint argc, JS::Value* vp) +bool Interface::Math_random(JSContext* cx, uint argc, JS::Value* vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); double r; - if (!ScriptInterface::CmptPrivate::GetScriptInterface(cx).MathRandom(r)) + if (!Interface::CmptPrivate::GetScriptInterface(cx).MathRandom(r)) return false; args.rval().setNumber(r); return true; } -ScriptInterface_impl::ScriptInterface_impl(const char* nativeScopeName, ScriptContext& context, +Interface_impl::Interface_impl(const char* nativeScopeName, Context& context, JS::Compartment* compartment, std::function allowModule) : m_context(context), m_cx(context.GetGeneralJSContext()), m_glob(context.GetGeneralJSContext()), m_nativeScope(context.GetGeneralJSContext()), @@ -354,31 +362,31 @@ ScriptInterface_impl::ScriptInterface_impl(const char* nativeScopeName, ScriptCo JS_DefineProperty(m_cx, m_glob, "global", m_glob, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); - // These first 4 actually use CallArgs & thus don't use ScriptFunction + // These first 4 actually use CallArgs & thus don't use Script::Function JS_DefineFunction(m_cx, m_glob, "print", ::print, 0, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "log", ::logmsg, 1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "warn", ::warn, 1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(m_cx, m_glob, "error", ::error, 1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); - ScriptFunction::Register(m_cx, m_glob, "clone"); - ScriptFunction::Register(m_cx, m_glob, "deepfreeze"); + Script::Function::Register(m_cx, m_glob, "clone"); + Script::Function::Register(m_cx, m_glob, "deepfreeze"); m_nativeScope = JS_DefineObject(m_cx, m_glob, nativeScopeName, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); - ScriptFunction::Register<&ProfileStart>(m_cx, m_nativeScope, "ProfileStart"); - ScriptFunction::Register<&ProfileStop>(m_cx, m_nativeScope, "ProfileStop"); - ScriptFunction::Register<&ProfileAttribute>(m_cx, m_nativeScope, "ProfileAttribute"); + Script::Function::Register<&ProfileStart>(m_cx, m_nativeScope, "ProfileStart"); + Script::Function::Register<&ProfileStop>(m_cx, m_nativeScope, "ProfileStop"); + Script::Function::Register<&ProfileAttribute>(m_cx, m_nativeScope, "ProfileAttribute"); m_context.RegisterRealm(JS::GetObjectRealmOrNull(m_glob)); } -ScriptInterface_impl::~ScriptInterface_impl() +Interface_impl::~Interface_impl() { m_context.UnRegisterRealm(JS::GetObjectRealmOrNull(m_glob)); } -ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugName, ScriptContext& context, +Interface::Interface(const char* nativeScopeName, const char* debugName, Context& context, std::function allowModule) : - m{std::make_unique(nativeScopeName, context, nullptr, + m{std::make_unique(nativeScopeName, context, nullptr, std::move(allowModule))} { // Profiler stats table isn't thread-safe, so only enable this on the main thread @@ -388,17 +396,17 @@ ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugN g_ScriptStatsTable->Add(this, debugName); } - ScriptRequest rq(this); + Request rq(this); m_CmptPrivate.pScriptInterface = this; JS::SetRealmPrivate(JS::GetObjectRealmOrNull(rq.glob), (void*)&m_CmptPrivate); } -ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugName, - const ScriptInterface& neighbor, std::function allowModule) +Interface::Interface(const char* nativeScopeName, const char* debugName, + const Interface& neighbor, std::function allowModule) { - ScriptRequest nrq(neighbor); + Request nrq(neighbor); JS::Compartment* comp = JS::GetCompartmentForRealm(JS::GetCurrentRealmOrNull(nrq.cx)); - m = std::make_unique(nativeScopeName, neighbor.GetContext(), comp, + m = std::make_unique(nativeScopeName, neighbor.GetContext(), comp, std::move(allowModule)); // Profiler stats table isn't thread-safe, so only enable this on the main thread @@ -408,12 +416,12 @@ ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugN g_ScriptStatsTable->Add(this, debugName); } - ScriptRequest rq(this); + Request rq(this); m_CmptPrivate.pScriptInterface = this; JS::SetRealmPrivate(JS::GetObjectRealmOrNull(rq.glob), (void*)&m_CmptPrivate); } -ScriptInterface::~ScriptInterface() +Interface::~Interface() { m->m_context.RunJobs(); if (Threading::IsMainThread()) @@ -423,31 +431,31 @@ ScriptInterface::~ScriptInterface() } } -const ScriptInterface& ScriptInterface::CmptPrivate::GetScriptInterface(JSContext *cx) +const Interface& Interface::CmptPrivate::GetScriptInterface(JSContext *cx) { CmptPrivate* pCmptPrivate = (CmptPrivate*)JS::GetRealmPrivate(JS::GetCurrentRealmOrNull(cx)); ENSURE(pCmptPrivate); return *pCmptPrivate->pScriptInterface; } -void* ScriptInterface::CmptPrivate::GetCBData(JSContext *cx) +void* Interface::CmptPrivate::GetCBData(JSContext *cx) { CmptPrivate* pCmptPrivate = (CmptPrivate*)JS::GetRealmPrivate(JS::GetCurrentRealmOrNull(cx)); return pCmptPrivate ? pCmptPrivate->pCBData : nullptr; } -void ScriptInterface::SetCallbackData(void* pCBData) +void Interface::SetCallbackData(void* pCBData) { m_CmptPrivate.pCBData = pCBData; } template <> -void* ScriptInterface::ObjectFromCBData(const ScriptRequest& rq) +void* Interface::ObjectFromCBData(const Request& rq) { - return ScriptInterface::CmptPrivate::GetCBData(rq.cx); + return Interface::CmptPrivate::GetCBData(rq.cx); } -bool ScriptInterface::LoadGlobalScripts() +bool Interface::LoadGlobalScripts() { // Ignore this failure in tests if (!g_VFS) @@ -466,9 +474,9 @@ bool ScriptInterface::LoadGlobalScripts() return true; } -bool ScriptInterface::ReplaceNondeterministicRNG(boost::rand48& rng) +bool Interface::ReplaceNondeterministicRNG(boost::rand48& rng) { - ScriptRequest rq(this); + Request rq(this); JS::RootedValue math(rq.cx); JS::RootedObject global(rq.cx, rq.glob); if (JS_GetProperty(rq.cx, global, "Math", &math) && math.isObject()) @@ -483,29 +491,29 @@ bool ScriptInterface::ReplaceNondeterministicRNG(boost::rand48& rng) } } - ScriptException::CatchPending(rq); + Exception::CatchPending(rq); LOGERROR("ReplaceNondeterministicRNG: failed to replace Math.random"); return false; } -JSContext* ScriptInterface::GetGeneralJSContext() const +JSContext* Interface::GetGeneralJSContext() const { return m->m_context.GetGeneralJSContext(); } -ScriptContext& ScriptInterface::GetContext() const +Context& Interface::GetContext() const { return m->m_context; } -Script::ModuleLoader& ScriptInterface::GetModuleLoader() const +ModuleLoader& Interface::GetModuleLoader() const { return m->m_ModuleLoader; } -void ScriptInterface::CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const +void Interface::CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const { - ScriptRequest rq(this); + Request rq(this); if (!ctor.isObject()) { LOGERROR("CallConstructor: ctor is not an object"); @@ -520,9 +528,9 @@ void ScriptInterface::CallConstructor(JS::HandleValue ctor, JS::HandleValueArray out.setObjectOrNull(objOut); } -void ScriptInterface::DefineCustomObjectType(JSClass *clasp, JSNative constructor, uint minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs) +void Interface::DefineCustomObjectType(JSClass *clasp, JSNative constructor, uint minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs) { - ScriptRequest rq(this); + Request rq(this); std::string typeName = clasp->name; if (m_CustomObjectTypes.find(typeName) != m_CustomObjectTypes.end()) @@ -540,7 +548,7 @@ void ScriptInterface::DefineCustomObjectType(JSClass *clasp, JSNative constructo if (obj == nullptr) { - ScriptException::CatchPending(rq); + Exception::CatchPending(rq); throw PSERROR_Scripting_DefineType_CreationFailed(); } @@ -551,21 +559,21 @@ void ScriptInterface::DefineCustomObjectType(JSClass *clasp, JSNative constructo type.m_Constructor = constructor; } -JSObject* ScriptInterface::CreateCustomObject(const std::string& typeName) const +JSObject* Interface::CreateCustomObject(const std::string& typeName) const { std::unordered_map::const_iterator it = m_CustomObjectTypes.find(typeName); if (it == m_CustomObjectTypes.end()) throw PSERROR_Scripting_TypeDoesNotExist(); - ScriptRequest rq(this); + Request rq(this); JS::RootedObject prototype(rq.cx, it->second.m_Prototype.get()); return JS_NewObjectWithGivenProto(rq.cx, it->second.m_Class, prototype); } -bool ScriptInterface::SetGlobal_(const char* name, JS::HandleValue value, bool replace, bool constant, bool enumerate) +bool Interface::SetGlobal_(const char* name, JS::HandleValue value, bool replace, bool constant, bool enumerate) { - ScriptRequest rq(this); + Request rq(this); JS::RootedObject global(rq.cx, rq.glob); bool found; @@ -581,7 +589,7 @@ bool ScriptInterface::SetGlobal_(const char* name, JS::HandleValue value, bool r { if (!replace) { - ScriptException::Raise(rq, "SetGlobal \"%s\" called multiple times", name); + Exception::Raise(rq, "SetGlobal \"%s\" called multiple times", name); return false; } @@ -589,7 +597,7 @@ bool ScriptInterface::SetGlobal_(const char* name, JS::HandleValue value, bool r // instead of using SetGlobal. if (!desc->configurable()) { - ScriptException::Raise(rq, "The global \"%s\" is permanent and cannot be hotloaded", name); + Exception::Raise(rq, "The global \"%s\" is permanent and cannot be hotloaded", name); return false; } @@ -607,7 +615,7 @@ bool ScriptInterface::SetGlobal_(const char* name, JS::HandleValue value, bool r return JS_DefineProperty(rq.cx, global, name, value, attrs); } -bool ScriptInterface::GetGlobalProperty(const ScriptRequest& rq, const std::string& name, JS::MutableHandleValue out) +bool Interface::GetGlobalProperty(const Request& rq, const std::string& name, JS::MutableHandleValue out) { // Try to get the object as a property of the global object. JS::RootedObject global(rq.cx, rq.glob); @@ -637,9 +645,9 @@ bool ScriptInterface::GetGlobalProperty(const ScriptRequest& rq, const std::stri return false; } -bool ScriptInterface::SetPrototype(JS::HandleValue objVal, JS::HandleValue protoVal) +bool Interface::SetPrototype(JS::HandleValue objVal, JS::HandleValue protoVal) { - ScriptRequest rq(this); + Request rq(this); if (!objVal.isObject() || !protoVal.isObject()) return false; JS::RootedObject obj(rq.cx, &objVal.toObject()); @@ -647,9 +655,9 @@ bool ScriptInterface::SetPrototype(JS::HandleValue objVal, JS::HandleValue proto return JS_SetPrototype(rq.cx, obj, proto); } -bool ScriptInterface::LoadScript(const VfsPath& filename, const std::string& code) const +bool Interface::LoadScript(const VfsPath& filename, const std::string& code) const { - ScriptRequest rq(this); + Request rq(this); JS::RootedObject global(rq.cx, rq.glob); // CompileOptions does not copy the contents of the filename string pointer. @@ -670,7 +678,7 @@ bool ScriptInterface::LoadScript(const VfsPath& filename, const std::string& cod JS::RootedFunction func(rq.cx, JS::CompileFunction(rq.cx, emptyScopeChain, options, NULL, 0, NULL, src)); if (func == nullptr) { - ScriptException::CatchPending(rq); + Exception::CatchPending(rq); return false; } @@ -678,13 +686,13 @@ bool ScriptInterface::LoadScript(const VfsPath& filename, const std::string& cod if (JS_CallFunction(rq.cx, nullptr, func, JS::HandleValueArray::empty(), &rval)) return true; - ScriptException::CatchPending(rq); + Exception::CatchPending(rq); return false; } -bool ScriptInterface::LoadGlobalScript(const VfsPath& filename, const std::string& code) const +bool Interface::LoadGlobalScript(const VfsPath& filename, const std::string& code) const { - ScriptRequest rq(this); + Request rq(this); // CompileOptions does not copy the contents of the filename string pointer. // Passing a temporary string there will cause undefined behaviour, so we create a separate string to avoid the temporary. std::string filenameStr = filename.string8(); @@ -699,11 +707,11 @@ bool ScriptInterface::LoadGlobalScript(const VfsPath& filename, const std::strin if (JS::Evaluate(rq.cx, opts, src, &rval)) return true; - ScriptException::CatchPending(rq); + Exception::CatchPending(rq); return false; } -bool ScriptInterface::LoadGlobalScriptFile(const VfsPath& path) const +bool Interface::LoadGlobalScriptFile(const VfsPath& path) const { if (!VfsFileExists(path)) { @@ -726,9 +734,9 @@ bool ScriptInterface::LoadGlobalScriptFile(const VfsPath& path) const return LoadGlobalScript(path, code); } -bool ScriptInterface::Eval(const char* code) const +bool Interface::Eval(const char* code) const { - ScriptRequest rq(this); + Request rq(this); JS::RootedValue rval(rq.cx); JS::CompileOptions opts(rq.cx); @@ -739,13 +747,13 @@ bool ScriptInterface::Eval(const char* code) const if (JS::Evaluate(rq.cx, opts, src, &rval)) return true; - ScriptException::CatchPending(rq); + Exception::CatchPending(rq); return false; } -bool ScriptInterface::Eval(const char* code, JS::MutableHandleValue rval) const +bool Interface::Eval(const char* code, JS::MutableHandleValue rval) const { - ScriptRequest rq(this); + Request rq(this); JS::CompileOptions opts(rq.cx); opts.setFileAndLine("(eval)", 1); @@ -755,6 +763,8 @@ bool ScriptInterface::Eval(const char* code, JS::MutableHandleValue rval) const if (JS::Evaluate(rq.cx, opts, src, rval)) return true; - ScriptException::CatchPending(rq); + Exception::CatchPending(rq); return false; } + +} // namespace Script \ No newline at end of file diff --git a/source/scriptinterface/ScriptInterface.h b/source/scriptinterface/Interface.h similarity index 76% rename from source/scriptinterface/ScriptInterface.h rename to source/scriptinterface/Interface.h index 290af11389..c55cd51c5d 100644 --- a/source/scriptinterface/ScriptInterface.h +++ b/source/scriptinterface/Interface.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -15,15 +15,15 @@ * along with 0 A.D. If not, see . */ -#ifndef INCLUDED_SCRIPTINTERFACE -#define INCLUDED_SCRIPTINTERFACE +#ifndef INCLUDED_SCRIPT_INTERFACE +#define INCLUDED_SCRIPT_INTERFACE #include "lib/code_annotation.h" #include "lib/types.h" #include "ps/Errors.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Request.h" #include #include @@ -40,14 +40,15 @@ class JSObject; class Path; -class ScriptContext; +namespace Script { class Context; } namespace Script { class ModuleLoader; } +namespace Script { struct Interface_impl; } namespace boost { namespace random { class rand48; } } struct JSClass; struct JSContext; struct JSFunctionSpec; struct JSPropertySpec; -struct ScriptInterface_impl; + ERROR_GROUP(Scripting); ERROR_TYPE(Scripting, SetupFailed); @@ -74,66 +75,70 @@ using VfsPath = Path; // Using a global object for the context is a workaround until Simulation, AI, etc, // use their own threads and also their own contexts. -extern thread_local std::shared_ptr g_ScriptContext; +extern thread_local std::shared_ptr g_ScriptContext; /** * Abstraction around a SpiderMonkey JS::Realm. * * Thread-safety: * - May be used in non-main threads. - * - Each ScriptInterface must be created, used, and destroyed, all in a single thread + * - Each Script::Interface must be created, used, and destroyed, all in a single thread * (it must never be shared between threads). */ -class ScriptInterface -{ - NONCOPYABLE(ScriptInterface); - friend class ScriptRequest; +namespace Script +{ + +class Interface +{ + NONCOPYABLE(Interface); + + friend class Request; public: /** * Constructor. - * @param nativeScopeName Name of global object that functions (via ScriptFunction::Register) will + * @param nativeScopeName Name of global object that functions (via Script::Function::Register) will * be placed into, as a scoping mechanism; typically "Engine" * @param debugName Name of this interface for CScriptStats purposes. * @param context ScriptContext to use when initializing this interface. */ - ScriptInterface(const char* nativeScopeName, const char* debugName, ScriptContext& context, + Interface(const char* nativeScopeName, const char* debugName, Context& context, std::function allowModule = {}); template - ScriptInterface(const char* nativeScopeName, const char* debugName, Context&& context, + Interface(const char* nativeScopeName, const char* debugName, Context&& context, std::function allowModule = {}) : - ScriptInterface{nativeScopeName, debugName, *context, std::move(allowModule)} + Interface{nativeScopeName, debugName, *context, std::move(allowModule)} { - static_assert(std::is_lvalue_reference_v, "`ScriptInterface` doesn't take ownership " + static_assert(std::is_lvalue_reference_v, "`Interface` doesn't take ownership " "of the context."); } /** * Alternate constructor. This creates the new Realm in the same Compartment as the neighbor scriptInterface. * This means that data can be freely exchanged between these two script interfaces without cloning. - * @param nativeScopeName Name of global object that functions (via ScriptFunction::Register) will + * @param nativeScopeName Name of global object that functions (via Script::Function::Register) will * be placed into, as a scoping mechanism; typically "Engine" * @param debugName Name of this interface for CScriptStats purposes. * @param scriptInterface 'Neighbor' scriptInterface to share a compartment with. * @param allowModule A predicate deciding wheter to import the given * module. */ - ScriptInterface(const char* nativeScopeName, const char* debugName, const ScriptInterface& neighbor, + Interface(const char* nativeScopeName, const char* debugName, const Interface& neighbor, std::function allowModule = {}); - ~ScriptInterface(); + ~Interface(); struct CmptPrivate { - friend class ScriptInterface; + friend class Interface; public: - static const ScriptInterface& GetScriptInterface(JSContext* cx); + static const Interface& GetScriptInterface(JSContext* cx); static void* GetCBData(JSContext* cx); protected: - ScriptInterface* pScriptInterface; // the ScriptInterface object the compartment belongs to + Interface* pScriptInterface; // the Interface object the compartment belongs to void* pCBData; // meant to be used as the "this" object for callback functions }; @@ -143,7 +148,7 @@ public: * Convert the CmptPrivate callback data to T* */ template - static T* ObjectFromCBData(const ScriptRequest& rq) + static T* ObjectFromCBData(const Request& rq) { static_assert(!std::is_same_v); return static_cast(ObjectFromCBData(rq)); @@ -153,22 +158,22 @@ public: * Variant for the function wrapper. */ template - static T* ObjectFromCBData(const ScriptRequest& rq, JS::CallArgs&) + static T* ObjectFromCBData(const Request& rq, JS::CallArgs&) { return ObjectFromCBData(rq); } - Script::ModuleLoader& GetModuleLoader() const; + ModuleLoader& GetModuleLoader() const; /** * GetGeneralJSContext returns the context without starting a GC request and without - * entering the ScriptInterface compartment. It should only be used in specific situations, + * entering the Interface compartment. It should only be used in specific situations, * for instance when initializing a persistent rooted. - * If you need the compartmented context of the ScriptInterface, you should create a - * ScriptInterface::Request and use the context from that. + * If you need the compartmented context of the Interface, you should create a + * Interface::Request and use the context from that. */ JSContext* GetGeneralJSContext() const; - ScriptContext& GetContext() const; + Context& GetContext() const; /** * Load global scripts that most script interfaces need, @@ -207,7 +212,7 @@ public: * @param name - Name of the property. * @param out The object or null. */ - static bool GetGlobalProperty(const ScriptRequest& rq, const std::string& name, JS::MutableHandleValue out); + static bool GetGlobalProperty(const Request& rq, const std::string& name, JS::MutableHandleValue out); bool SetPrototype(JS::HandleValue obj, JS::HandleValue proto); @@ -242,7 +247,7 @@ public: template bool Eval(const char* code, T& out) const; /** - * Calls the random number generator assigned to this ScriptInterface instance and returns the generated number. + * Calls the random number generator assigned to this Interface instance and returns the generated number. */ bool MathRandom(double& nbr) const; @@ -264,12 +269,12 @@ public: * Retrieve the private data field of a JSObject. */ template - static T* GetPrivate(const ScriptRequest& rq, JS::HandleObject thisobj) + static T* GetPrivate(const Request& rq, JS::HandleObject thisobj) { T* value = JS::GetMaybePtrFromReservedSlot(thisobj, JSObjectReservedSlots::PRIVATE); if (value == nullptr) - ScriptException::Raise(rq, "Private data of the given object is null!"); + Exception::Raise(rq, "Private data of the given object is null!"); return value; } @@ -279,11 +284,11 @@ public: * If an error occurs, GetPrivate will report it with the according stack. */ template - static T* GetPrivate(const ScriptRequest& rq, JS::CallArgs& callArgs) + static T* GetPrivate(const Request& rq, JS::CallArgs& callArgs) { if (!callArgs.thisv().isObject()) { - ScriptException::Raise(rq, "Cannot retrieve private JS object data because from a non-object value!"); + Exception::Raise(rq, "Cannot retrieve private JS object data because from a non-object value!"); return nullptr; } @@ -291,7 +296,7 @@ public: T* value = JS::GetMaybePtrFromReservedSlot(thisObj, JSObjectReservedSlots::PRIVATE); if (value == nullptr) - ScriptException::Raise(rq, "Private data of the given object is null!"); + Exception::Raise(rq, "Private data of the given object is null!"); return value; } @@ -309,33 +314,35 @@ private: CmptPrivate m_CmptPrivate; // Take care to keep this declaration before heap rooted members. Destructors of heap rooted - // members have to be called before the custom destructor of ScriptInterface_impl. - std::unique_ptr m; + // members have to be called before the custom destructor of Interface_impl. + std::unique_ptr m; std::unordered_map m_CustomObjectTypes; }; +} // namespace Script + // Explicitly instantiate void* as that is used for the generic template, // and we want to define it in the .cpp file. -template <> void* ScriptInterface::ObjectFromCBData(const ScriptRequest& rq); +template <> void* Script::Interface::ObjectFromCBData(const Script::Request& rq); template -bool ScriptInterface::SetGlobal(const char* name, const T& value, bool replace, bool constant, bool enumerate) +bool Script::Interface::SetGlobal(const char* name, const T& value, bool replace, bool constant, bool enumerate) { - ScriptRequest rq(this); + Script::Request rq(this); JS::RootedValue val(rq.cx); Script::ToJSVal(rq, &val, value); return SetGlobal_(name, val, replace, constant, enumerate); } template -bool ScriptInterface::Eval(const char* code, T& ret) const +bool Script::Interface::Eval(const char* code, T& ret) const { - ScriptRequest rq(this); + Script::Request rq(this); JS::RootedValue rval(rq.cx); if (!Eval(code, &rval)) return false; return Script::FromJSVal(rq, rval, ret); } -#endif // INCLUDED_SCRIPTINTERFACE +#endif // INCLUDED_SCRIPT_INTERFACE diff --git a/source/scriptinterface/JSON.cpp b/source/scriptinterface/JSON.cpp index 10ac3e3c91..baef69c6ab 100644 --- a/source/scriptinterface/JSON.cpp +++ b/source/scriptinterface/JSON.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -28,8 +28,8 @@ #include "ps/Errors.h" #include "ps/Filesystem.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Request.h" #include #include @@ -38,18 +38,18 @@ #include #include -bool Script::ParseJSON(const ScriptRequest& rq, const std::string& string_utf8, JS::MutableHandleValue out) +bool Script::ParseJSON(const Script::Request& rq, const std::string& string_utf8, JS::MutableHandleValue out) { std::wstring attrsW = wstring_from_utf8(string_utf8); std::u16string string(attrsW.begin(), attrsW.end()); if (JS_ParseJSON(rq.cx, string.c_str(), (u32)string.size(), out)) return true; - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); return false; } -void Script::ReadJSONFile(const ScriptRequest& rq, const VfsPath& path, JS::MutableHandleValue out) +void Script::ReadJSONFile(const Script::Request& rq, const VfsPath& path, JS::MutableHandleValue out) { if (!VfsFileExists(path)) { @@ -93,13 +93,13 @@ struct Stringifier // JS_Stringify takes a mutable object because ToJSON may arbitrarily mutate the value. // TODO: it'd be nice to have a non-mutable variant. -std::string Script::StringifyJSON(const ScriptRequest& rq, JS::MutableHandleValue obj, bool indent) +std::string Script::StringifyJSON(const Script::Request& rq, JS::MutableHandleValue obj, bool indent) { Stringifier str; JS::RootedValue indentVal(rq.cx, indent ? JS::Int32Value(2) : JS::UndefinedValue()); if (!JS_Stringify(rq.cx, obj, nullptr, indentVal, &Stringifier::callback, &str)) { - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); return std::string(); } @@ -107,7 +107,7 @@ std::string Script::StringifyJSON(const ScriptRequest& rq, JS::MutableHandleValu } -std::string Script::ToString(const ScriptRequest& rq, JS::MutableHandleValue obj, bool pretty) +std::string Script::ToString(const Script::Request& rq, JS::MutableHandleValue obj, bool pretty) { if (obj.isUndefined()) return "(void 0)"; @@ -130,6 +130,6 @@ std::string Script::ToString(const ScriptRequest& rq, JS::MutableHandleValue obj // so fall back to obj.toSource() std::wstring source = L"(error)"; - ScriptFunction::Call(rq, obj, "toSource", source); + Script::Function::Call(rq, obj, "toSource", source); return utf8_from_wstring(source); } diff --git a/source/scriptinterface/JSON.h b/source/scriptinterface/JSON.h index 1a2ce23217..1b07c7eff9 100644 --- a/source/scriptinterface/JSON.h +++ b/source/scriptinterface/JSON.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,7 +23,7 @@ class Path; using VfsPath = Path; -class ScriptRequest; +namespace Script { class Request; } /** * @file JSON.h @@ -36,24 +36,24 @@ namespace Script * Convert an object to a UTF-8 encoded string, either with JSON * (if pretty == true and there is no JSON error) or with toSource(). */ -std::string ToString(const ScriptRequest& rq, JS::MutableHandleValue obj, bool pretty = false); +std::string ToString(const Script::Request& rq, JS::MutableHandleValue obj, bool pretty = false); /** * Parse a UTF-8-encoded JSON string. Returns the unmodified value on error * and prints an error message. * @return true on success; false otherwise */ -bool ParseJSON(const ScriptRequest& rq, const std::string& string_utf8, JS::MutableHandleValue out); +bool ParseJSON(const Script::Request& rq, const std::string& string_utf8, JS::MutableHandleValue out); /** * Read a JSON file. Returns the unmodified value on error and prints an error message. */ -void ReadJSONFile(const ScriptRequest& rq, const VfsPath& path, JS::MutableHandleValue out); +void ReadJSONFile(const Script::Request& rq, const VfsPath& path, JS::MutableHandleValue out); /** * Stringify to a JSON string, UTF-8 encoded. Returns an empty string on error. */ -std::string StringifyJSON(const ScriptRequest& rq, JS::MutableHandleValue obj, bool indent = true); +std::string StringifyJSON(const Script::Request& rq, JS::MutableHandleValue obj, bool indent = true); } #endif // INCLUDED_SCRIPTINTERFACE_JSON diff --git a/source/scriptinterface/ModuleLoader.cpp b/source/scriptinterface/ModuleLoader.cpp index 9e93ec9911..664235fc9d 100644 --- a/source/scriptinterface/ModuleLoader.cpp +++ b/source/scriptinterface/ModuleLoader.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -30,10 +30,10 @@ #include "ps/Filesystem.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -144,7 +144,7 @@ VfsPath GetBaseFilename(const VfsPath& filename) } template -[[nodiscard]] JSObject* CompileModule(const ScriptRequest& rq, +[[nodiscard]] JSObject* CompileModule(const Script::Request& rq, const ModuleLoader::AllowModuleFunc& allowModule, ModuleLoader::RegistryType& registry, const VfsPath& filePath, Requester&& requester) { @@ -154,7 +154,7 @@ template compiledModule.AddRequester(std::forward(requester)); return compiledModule.m_ModuleObject; } -[[nodiscard]] JSObject* Resolve(const ScriptRequest& rq, const ModuleLoader::AllowModuleFunc& allowModule, +[[nodiscard]] JSObject* Resolve(const Script::Request& rq, const ModuleLoader::AllowModuleFunc& allowModule, ModuleLoader::RegistryType& registry, JS::HandleValue referencingModule, JS::HandleObject moduleRequest) { @@ -171,18 +171,18 @@ template return CompileModule(rq, allowModule, registry, includeString, includingModule); } -[[nodiscard]] JSObject* Evaluate(const ScriptRequest& rq, JS::HandleObject mod) +[[nodiscard]] JSObject* Evaluate(const Script::Request& rq, JS::HandleObject mod) { if (!JS::ModuleLink(rq.cx, mod)) { - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); throw std::invalid_argument{"Unable to link module."}; } JS::RootedValue val{rq.cx}; if (!JS::ModuleEvaluate(rq.cx, mod, &val) || !val.isObject()) { - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); throw std::invalid_argument{"Unable to evaluate module."}; } @@ -226,7 +226,7 @@ template bool Call(JSContext* cx, const unsigned argc, JS::Value* vp) { JS::CallArgs args{JS::CallArgsFromVp(argc, vp)}; - const ScriptRequest rq{cx}; + const Script::Request rq{cx}; const auto statusPtr{JS::GetMaybePtrFromReservedSlot( &args.callee(), 0)}; @@ -239,7 +239,7 @@ bool Call(JSContext* cx, const unsigned argc, JS::Value* vp) { JS::HandleValue error{args.get(0)}; std::string asString; - ScriptFunction::Call(rq, error, "toString", asString); + Script::Function::Call(rq, error, "toString", asString); std::string stack; Script::GetProperty(rq, error, "stack", stack); status = ModuleLoader::Future::Rejected{std::make_exception_ptr(std::runtime_error{ @@ -266,7 +266,7 @@ template constexpr JSClass callbackClass{"Callback", JSCLASS_HAS_RESERVED_SLOTS(1), &callbackClassOps}; } // anonymous namespace -ModuleLoader::CompiledModule::CompiledModule(const ScriptRequest& rq, const AllowModuleFunc& allowModule, +ModuleLoader::CompiledModule::CompiledModule(const Script::Request& rq, const AllowModuleFunc& allowModule, const VfsPath& filePath): m_ModuleObject(rq.cx) { @@ -290,7 +290,7 @@ ModuleLoader::CompiledModule::CompiledModule(const ScriptRequest& rq, const Allo if (!m_ModuleObject) { - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); throw std::invalid_argument{fmt::format("Unable to compile module: \"{}\".", filePathStr)}; } @@ -326,7 +326,7 @@ void ModuleLoader::CompiledModule::RemoveRequester(Result* toErase) }), m_Callbacks.end()); } -ModuleLoader::Future::Future(const ScriptRequest& rq, ModuleLoader& loader, Result& result, +ModuleLoader::Future::Future(const Script::Request& rq, ModuleLoader& loader, Result& result, VfsPath modulePath): m_Status{Evaluating{{rq.cx, nullptr}, {rq.cx, JS_NewObject(rq.cx, &callbackClass)}, {rq.cx, JS_NewObject(rq.cx, &callbackClass)}}} @@ -443,7 +443,7 @@ ModuleLoader::Result::iterator& ModuleLoader::Result::iterator::operator++(int) return true; } -ModuleLoader::Result::Result(const ScriptRequest& rq, const VfsPath& modulePath): +ModuleLoader::Result::Result(const Script::Request& rq, const VfsPath& modulePath): m_Script{rq.GetScriptInterface()}, m_ModulePath{modulePath}, m_Storage{rq, m_Script.GetModuleLoader(), *this, m_ModulePath} @@ -487,7 +487,7 @@ ModuleLoader::~ModuleLoader() UnregisterFileReloadFunc(FileChangedHook, static_cast(&m_Registry)); } -[[nodiscard]] ModuleLoader::Result ModuleLoader::LoadModule(const ScriptRequest& rq, +[[nodiscard]] ModuleLoader::Result ModuleLoader::LoadModule(const Script::Request& rq, const VfsPath& modulePath) { return Result{rq, modulePath}; @@ -500,7 +500,7 @@ ModuleLoader::~ModuleLoader() [[nodiscard]] bool ModuleLoader::MetadataHook(JSContext* cx, JS::HandleValue privateValue, JS::HandleObject metaObject) noexcept { - const ScriptRequest rq{cx}; + const Script::Request rq{cx}; JS::RootedValue path{cx}; if (!Script::GetProperty(rq, privateValue, "path", &path)) @@ -518,7 +518,7 @@ ModuleLoader::~ModuleLoader() { try { - const ScriptRequest rq{cx}; + const Script::Request rq{cx}; ModuleLoader& loader{rq.GetScriptInterface().GetModuleLoader()}; return Resolve(rq, loader.m_AllowModule, loader.m_Registry, referencingPrivate, request); } @@ -537,7 +537,7 @@ ModuleLoader::~ModuleLoader() [[nodiscard]] bool ModuleLoader::DynamicImportHook(JSContext* cx, JS::HandleValue referencingPrivate, JS::HandleObject moduleRequest, JS::HandleObject promise) noexcept { - const ScriptRequest rq{cx}; + const Script::Request rq{cx}; try { ModuleLoader& loader{rq.GetScriptInterface().GetModuleLoader()}; diff --git a/source/scriptinterface/ModuleLoader.h b/source/scriptinterface/ModuleLoader.h index 833e4efd38..604ec9f35c 100644 --- a/source/scriptinterface/ModuleLoader.h +++ b/source/scriptinterface/ModuleLoader.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -34,10 +34,10 @@ #include class JSObject; -class ScriptContext; -class ScriptInterface; -class ScriptRequest; namespace JS { class Value; } +namespace Script { class Context; } +namespace Script { class Interface; } +namespace Script { class Request; } struct JSContext; namespace Script @@ -45,7 +45,7 @@ namespace Script class ModuleLoader { public: - friend ScriptContext; + friend Script::Context; class Future; class Result; @@ -55,7 +55,7 @@ public: class CompiledModule { public: - CompiledModule(const ScriptRequest& rq, const AllowModuleFunc& allowModule, const VfsPath& filePath); + CompiledModule(const Script::Request& rq, const AllowModuleFunc& allowModule, const VfsPath& filePath); std::tuple&, const std::vector>&> GetRequesters() const; @@ -82,17 +82,17 @@ public: /** * Load the specified module and all module it imports recursively. * - * @param rq @c globalThis is taken from this @c ScriptRequest. + * @param rq @c globalThis is taken from this @c Script::Request. * @param modulePath The path to the file which should be loaded as a * module. * @return A range of futures. The compilation of the first future is * already started. The evaluation of the subsequent futures start once * the module file is edited. */ - [[nodiscard]] Result LoadModule(const ScriptRequest& rq, const VfsPath& modulePath); + [[nodiscard]] Result LoadModule(const Script::Request& rq, const VfsPath& modulePath); private: - // Functions used by the `ScriptContext`. + // Functions used by the `Script::Context`. [[nodiscard]] static bool MetadataHook(JSContext* cx, JS::HandleValue privateValue, JS::HandleObject metaObject) noexcept; [[nodiscard]] static JSObject* ResolveHook(JSContext* cx, JS::HandleValue referencingPrivate, @@ -131,7 +131,7 @@ public: struct Invalid {}; using Status = std::variant; - explicit Future(const ScriptRequest& rq, ModuleLoader& reqistry, Result& result, VfsPath modulePath); + explicit Future(const Script::Request& rq, ModuleLoader& reqistry, Result& result, VfsPath modulePath); Future() = default; Future(const Future&) = delete; Future& operator=(const Future&) = delete; @@ -163,7 +163,7 @@ class ModuleLoader::Result public: class iterator; - explicit Result(const ScriptRequest& rq, const VfsPath& modulePath); + explicit Result(const Script::Request& rq, const VfsPath& modulePath); Result(const Result&) = delete; Result& operator=(const Result&) = delete; Result(Result&&) = delete; @@ -176,7 +176,7 @@ public: void Resume(); private: - const ScriptInterface& m_Script; + const Script::Interface& m_Script; VfsPath m_ModulePath; Future m_Storage; }; diff --git a/source/scriptinterface/Object.h b/source/scriptinterface/Object.h index 2311869833..cdd71eb406 100644 --- a/source/scriptinterface/Object.h +++ b/source/scriptinterface/Object.h @@ -21,8 +21,8 @@ #include "lib/posix/posix_types.h" #include "lib/types.h" #include "ps/CLogger.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include #include @@ -51,7 +51,7 @@ namespace Script * Get the named property on the given object. */ template -inline bool GetProperty(const ScriptRequest& rq, JS::HandleValue obj, PropType name, JS::MutableHandleValue out) +inline bool GetProperty(const Script::Request& rq, JS::HandleValue obj, PropType name, JS::MutableHandleValue out) { if (!obj.isObject()) return false; @@ -68,14 +68,14 @@ inline bool GetProperty(const ScriptRequest& rq, JS::HandleValue obj, PropType n } template -inline bool GetProperty(const ScriptRequest& rq, JS::HandleValue obj, PropType name, T& out) +inline bool GetProperty(const Script::Request& rq, JS::HandleValue obj, PropType name, T& out) { JS::RootedValue val(rq.cx); if (!GetProperty(rq, obj, name, &val)) return false; return FromJSVal(rq, val, out); } -inline bool GetProperty(const ScriptRequest& rq, JS::HandleValue obj, const char* name, JS::MutableHandleObject out) +inline bool GetProperty(const Script::Request& rq, JS::HandleValue obj, const char* name, JS::MutableHandleObject out) { JS::RootedValue val(rq.cx, JS::ObjectValue(*out.get())); if (!GetProperty(rq, obj, name, &val)) @@ -85,18 +85,18 @@ inline bool GetProperty(const ScriptRequest& rq, JS::HandleValue obj, const char } template -inline bool GetPropertyInt(const ScriptRequest& rq, JS::HandleValue obj, int name, T& out) +inline bool GetPropertyInt(const Script::Request& rq, JS::HandleValue obj, int name, T& out) { return GetProperty(rq, obj, name, out); } -inline bool GetPropertyInt(const ScriptRequest& rq, JS::HandleValue obj, int name, JS::MutableHandleValue out) +inline bool GetPropertyInt(const Script::Request& rq, JS::HandleValue obj, int name, JS::MutableHandleValue out) { return GetProperty(rq, obj, name, out); } /** * Check the named property has been defined on the given object. */ -inline bool HasProperty(const ScriptRequest& rq, JS::HandleValue obj, const char* name) +inline bool HasProperty(const Script::Request& rq, JS::HandleValue obj, const char* name) { if (!obj.isObject()) return false; @@ -112,7 +112,7 @@ inline bool HasProperty(const ScriptRequest& rq, JS::HandleValue obj, const char * Set the named property on the given object. */ template -inline bool SetProperty(const ScriptRequest& rq, JS::HandleValue obj, PropType name, JS::HandleValue value, bool constant = false, bool enumerable = true) +inline bool SetProperty(const Script::Request& rq, JS::HandleValue obj, PropType name, JS::HandleValue value, bool constant = false, bool enumerable = true) { uint attrs = 0; if (constant) @@ -135,7 +135,7 @@ inline bool SetProperty(const ScriptRequest& rq, JS::HandleValue obj, PropType n } template -inline bool SetProperty(const ScriptRequest& rq, JS::HandleValue obj, PropType name, const T& value, bool constant = false, bool enumerable = true) +inline bool SetProperty(const Script::Request& rq, JS::HandleValue obj, PropType name, const T& value, bool constant = false, bool enumerable = true) { JS::RootedValue val(rq.cx); Script::ToJSVal(rq, &val, value); @@ -143,13 +143,13 @@ inline bool SetProperty(const ScriptRequest& rq, JS::HandleValue obj, PropType n } template -inline bool SetPropertyInt(const ScriptRequest& rq, JS::HandleValue obj, int name, const T& value, bool constant = false, bool enumerable = true) +inline bool SetPropertyInt(const Script::Request& rq, JS::HandleValue obj, int name, const T& value, bool constant = false, bool enumerable = true) { return SetProperty(rq, obj, name, value, constant, enumerable); } template -inline bool GetObjectClassName(const ScriptRequest& rq, JS::HandleObject obj, T& name) +inline bool GetObjectClassName(const Script::Request& rq, JS::HandleObject obj, T& name) { JS::RootedValue constructor(rq.cx, JS::ObjectOrNullValue(JS_GetConstructor(rq.cx, obj))); return constructor.isObject() && Script::GetProperty(rq, constructor, "name", name); @@ -159,7 +159,7 @@ inline bool GetObjectClassName(const ScriptRequest& rq, JS::HandleObject obj, T& * Get the name of the object's class. Note that inheritance may lead to unexpected results. */ template -inline bool GetObjectClassName(const ScriptRequest& rq, JS::HandleValue val, T& name) +inline bool GetObjectClassName(const Script::Request& rq, JS::HandleValue val, T& name) { JS::RootedObject obj(rq.cx, val.toObjectOrNull()); if (!obj) @@ -167,7 +167,7 @@ inline bool GetObjectClassName(const ScriptRequest& rq, JS::HandleValue val, T& return GetObjectClassName(rq, obj, name); } -inline bool DeepFreezeObject(const ScriptRequest& rq, JS::HandleValue objVal) +inline bool DeepFreezeObject(const Script::Request& rq, JS::HandleValue objVal) { if (!objVal.isObject()) { @@ -205,7 +205,7 @@ inline bool DeepFreezeObject(const ScriptRequest& rq, JS::HandleValue objVal) * require a variant in the vector, and it's not useful for now. * @param enumerableOnly - only return enumerable properties. */ -inline bool EnumeratePropertyNames(const ScriptRequest& rq, JS::HandleValue objVal, bool enumerableOnly, std::vector& out) +inline bool EnumeratePropertyNames(const Script::Request& rq, JS::HandleValue objVal, bool enumerableOnly, std::vector& out) { if (!objVal.isObjectOrNull()) { @@ -244,7 +244,7 @@ inline bool EnumeratePropertyNames(const ScriptRequest& rq, JS::HandleValue objV /** * Create a plain object (i.e. {}). If it fails, returns undefined. */ -inline JS::Value CreateObject(const ScriptRequest& rq) +inline JS::Value CreateObject(const Script::Request& rq) { JS::RootedObject obj(rq.cx, JS_NewPlainObject(rq.cx)); if (!obj) @@ -252,7 +252,7 @@ inline JS::Value CreateObject(const ScriptRequest& rq) return JS::ObjectValue(*obj.get()); } -inline bool CreateObject(const ScriptRequest& rq, JS::MutableHandleValue objectValue) +inline bool CreateObject(const Script::Request& rq, JS::MutableHandleValue objectValue) { objectValue.set(CreateObject(rq)); return !objectValue.isNullOrUndefined(); @@ -264,7 +264,7 @@ inline bool CreateObject(const ScriptRequest& rq, JS::MutableHandleValue objectV * Can throw an exception. */ template -inline bool CreateObject(const ScriptRequest& rq, JS::MutableHandleValue objectValue, const char* propertyName, const T& propertyValue, Args const&... args) +inline bool CreateObject(const Script::Request& rq, JS::MutableHandleValue objectValue, const char* propertyName, const T& propertyValue, Args const&... args) { JS::RootedValue val(rq.cx); ToJSVal(rq, &val, propertyValue); diff --git a/source/scriptinterface/Promises.cpp b/source/scriptinterface/Promises.cpp index 303ab2678d..76b7edcd25 100644 --- a/source/scriptinterface/Promises.cpp +++ b/source/scriptinterface/Promises.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,7 +23,7 @@ #include "ps/CLogger.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -44,11 +44,11 @@ void UnhandledRejectedPromise(JSContext* cx, bool, JS::HandleObject promise, if (state == JS::PromiseRejectionHandlingState::Handled) return; - const ScriptRequest rq{cx}; + const Script::Request rq{cx}; JS::RootedValue reason(cx, JS::GetPromiseResult(promise)); std::string asString; - ScriptFunction::Call(rq, reason, "toString", asString); + Script::Function::Call(rq, reason, "toString", asString); std::string stack; Script::GetProperty(rq, reason, "stack", stack); LOGERROR("An unhandled promise got rejected:\n%s\n%s", asString, stack); @@ -59,7 +59,7 @@ void JobQueue::runJobs(JSContext*) while (!m_Jobs.empty()) { QueueElement& element = m_Jobs.front(); - ScriptRequest rq{element.scriptInterface}; + Script::Request rq{element.scriptInterface}; JS::RootedObject localJob{rq.cx, element.job}; m_Jobs.pop(); @@ -79,7 +79,7 @@ bool JobQueue::enqueuePromiseJob(JSContext* cx, JS::HandleObject, JS::HandleObje { try { - m_Jobs.push({ScriptRequest{cx}.GetScriptInterface(), JS::PersistentRootedObject{cx, job}}); + m_Jobs.push({Script::Request{cx}.GetScriptInterface(), JS::PersistentRootedObject{cx, job}}); return true; } catch (...) diff --git a/source/scriptinterface/Promises.h b/source/scriptinterface/Promises.h index 4403e09797..8e6c16a1ce 100644 --- a/source/scriptinterface/Promises.h +++ b/source/scriptinterface/Promises.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -24,7 +24,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } struct JSContext; namespace Script @@ -52,7 +52,7 @@ private: struct QueueElement { - const ScriptInterface& scriptInterface; + const Script::Interface& scriptInterface; JS::PersistentRootedObject job; }; using QueueType = std::queue; diff --git a/source/scriptinterface/ScriptRequest.h b/source/scriptinterface/Request.h similarity index 62% rename from source/scriptinterface/ScriptRequest.h rename to source/scriptinterface/Request.h index c76e541890..b9c8290bba 100644 --- a/source/scriptinterface/ScriptRequest.h +++ b/source/scriptinterface/Request.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -15,18 +15,18 @@ * along with 0 A.D. If not, see . */ -#ifndef INCLUDED_SCRIPTREQUEST -#define INCLUDED_SCRIPTREQUEST +#ifndef INCLUDED_SCRIPT_REQUEST +#define INCLUDED_SCRIPT_REQUEST -#include "scriptinterface/ScriptForward.h" +#include "scriptinterface/ForwardDeclarations.h" #include #include #include -class ScriptInterface; namespace JS { class Realm; } namespace JS { class Value; } +namespace Script { class Interface; } struct JSContext; /** @@ -37,53 +37,57 @@ struct JSContext; * 'Entering' and 'Leaving' realms must be done in a LIFO manner. * SM recommends using JSAutoRealm, which provides an RAII option. * - * ScriptRequest combines both of the above in a single convenient package, + * Request combines both of the above in a single convenient package, * providing safe access to the JSContext*, the global object, and ensuring that the proper realm has been entered. - * Most scriptinterface/ functions will take a ScriptRequest, to ensure proper rooting. You may sometimes - * have to create one from a ScriptInterface. + * Most scriptinterface/ functions will take a Request, to ensure proper rooting. You may sometimes + * have to create one from a Interface. * * Be particularly careful when manipulating several script interfaces. */ -class ScriptRequest +namespace Script { - ScriptRequest() = delete; - ScriptRequest(const ScriptRequest& rq) = delete; - ScriptRequest& operator=(const ScriptRequest& rq) = delete; + +class Request +{ + Request() = delete; + Request(const Request& rq) = delete; + Request& operator=(const Request& rq) = delete; public: /** * NB: the definitions are in scriptinterface.cpp, because these access members of the PImpled - * implementation of ScriptInterface, and that seemed more convenient. + * implementation of Interface, and that seemed more convenient. */ - ScriptRequest(const ScriptInterface& scriptInterface); - ScriptRequest(const ScriptInterface* scriptInterface) : ScriptRequest(*scriptInterface) {} - ScriptRequest(std::shared_ptr scriptInterface) : ScriptRequest(*scriptInterface) {} - ~ScriptRequest(); + Request(const Interface& scriptInterface); + Request(const Interface* scriptInterface) : Request(*scriptInterface) {} + Request(std::shared_ptr scriptInterface) : Request(*scriptInterface) {} + ~Request(); /** * Create a script request from a JSContext. * This can be used to get the script interface in a JSNative function. * In general, you shouldn't have to rely on this otherwise. */ - ScriptRequest(JSContext* cx); + Request(JSContext* cx); /** - * Return the scriptInterface active when creating this ScriptRequest. - * Note that this is multi-request safe: even if another ScriptRequest is created, + * Return the scriptInterface active when creating this Request. + * Note that this is multi-request safe: even if another Request is created, * it will point to the original scriptInterface, and thus can be used to re-enter the realm. */ - const ScriptInterface& GetScriptInterface() const; + const Interface& GetScriptInterface() const; JS::Value globalValue() const; - // Note that JSContext actually changes behind the scenes when creating another ScriptRequest for another realm, + // Note that JSContext actually changes behind the scenes when creating another Request for another realm, // so be _very_ careful when juggling between different realms. JSContext* cx; JS::HandleObject glob; JS::HandleObject nativeScope; private: - const ScriptInterface& m_ScriptInterface; + const Interface& m_ScriptInterface; JS::Realm* m_FormerRealm; }; +} -#endif // INCLUDED_SCRIPTREQUEST +#endif // INCLUDED_SCRIPT_REQUEST diff --git a/source/scriptinterface/ScriptStats.cpp b/source/scriptinterface/Stats.cpp similarity index 87% rename from source/scriptinterface/ScriptStats.cpp rename to source/scriptinterface/Stats.cpp index 089b350358..6c40cdd880 100644 --- a/source/scriptinterface/ScriptStats.cpp +++ b/source/scriptinterface/Stats.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -17,14 +17,17 @@ #include "precompiled.h" -#include "ScriptStats.h" +#include "Stats.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include #include -CScriptStatsTable* g_ScriptStatsTable; +Script::CScriptStatsTable* g_ScriptStatsTable; + +namespace Script +{ enum { @@ -38,12 +41,12 @@ CScriptStatsTable::CScriptStatsTable() { } -void CScriptStatsTable::Add(const ScriptInterface* scriptInterface, const std::string& title) +void CScriptStatsTable::Add(const Interface* scriptInterface, const std::string& title) { m_ScriptInterfaces.emplace_back(scriptInterface, title); } -void CScriptStatsTable::Remove(const ScriptInterface* scriptInterface) +void CScriptStatsTable::Remove(const Interface* scriptInterface) { for (size_t i = 0; i < m_ScriptInterfaces.size(); ) { @@ -112,3 +115,5 @@ AbstractProfileTable* CScriptStatsTable::GetChild(size_t /*row*/) { return 0; } + +} // namespace Script \ No newline at end of file diff --git a/source/scriptinterface/ScriptStats.h b/source/scriptinterface/Stats.h similarity index 76% rename from source/scriptinterface/ScriptStats.h rename to source/scriptinterface/Stats.h index bc372ff5d0..f99b75dfeb 100644 --- a/source/scriptinterface/ScriptStats.h +++ b/source/scriptinterface/Stats.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -15,8 +15,8 @@ * along with 0 A.D. If not, see . */ -#ifndef INCLUDED_SCRIPTSTATS -#define INCLUDED_SCRIPTSTATS +#ifndef INCLUDED_SCRIPT_STATS +#define INCLUDED_SCRIPT_STATS #include "lib/code_annotation.h" #include "ps/CStr.h" @@ -27,7 +27,9 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } + +namespace Script { class CScriptStatsTable : public AbstractProfileTable { @@ -35,8 +37,8 @@ class CScriptStatsTable : public AbstractProfileTable public: CScriptStatsTable(); - void Add(const ScriptInterface* scriptInterface, const std::string& title); - void Remove(const ScriptInterface* scriptInterface); + void Add(const Interface* scriptInterface, const std::string& title); + void Remove(const Interface* scriptInterface); CStr GetName() override; CStr GetTitle() override; @@ -46,12 +48,14 @@ public: AbstractProfileTable* GetChild(size_t row) override; private: - std::vector > m_ScriptInterfaces; + std::vector > m_ScriptInterfaces; std::vector m_ColumnDescriptions; }; +} + // To simplify the UI we want to use a single table for all script interfaces, // so just make it a global that they can all add themselves to -extern CScriptStatsTable* g_ScriptStatsTable; +extern Script::CScriptStatsTable* g_ScriptStatsTable; -#endif // INCLUDED_SCRIPTSTATS +#endif // INCLUDED_SCRIPT_STATS diff --git a/source/scriptinterface/StructuredClone.cpp b/source/scriptinterface/StructuredClone.cpp index 2fcf27c30c..2ab7f4401b 100644 --- a/source/scriptinterface/StructuredClone.cpp +++ b/source/scriptinterface/StructuredClone.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -21,51 +21,51 @@ #include "lib/debug.h" #include "ps/Profile.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Request.h" #include #include #include -class ScriptInterface; +namespace Script { class Interface; } -Script::StructuredClone Script::WriteStructuredClone(const ScriptRequest& rq, JS::HandleValue v) +Script::StructuredClone Script::WriteStructuredClone(const Script::Request& rq, JS::HandleValue v) { Script::StructuredClone ret(new JSStructuredCloneData(JS::StructuredCloneScope::SameProcess)); JS::CloneDataPolicy policy; if (!JS_WriteStructuredClone(rq.cx, v, ret.get(), JS::StructuredCloneScope::SameProcess, policy, nullptr, nullptr, JS::UndefinedHandleValue)) { debug_warn(L"Writing a structured clone with JS_WriteStructuredClone failed!"); - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); return StructuredClone(); } return ret; } -void Script::ReadStructuredClone(const ScriptRequest& rq, const Script::StructuredClone& ptr, JS::MutableHandleValue ret) +void Script::ReadStructuredClone(const Script::Request& rq, const Script::StructuredClone& ptr, JS::MutableHandleValue ret) { JS::CloneDataPolicy policy; if (!JS_ReadStructuredClone(rq.cx, *ptr, JS_STRUCTURED_CLONE_VERSION, ptr->scope(), ret, policy, nullptr, nullptr)) - ScriptException::CatchPending(rq); + Script::Exception::CatchPending(rq); } -JS::Value Script::CloneValueFromOtherCompartment(const ScriptInterface& to, const ScriptInterface& from, JS::HandleValue val) +JS::Value Script::CloneValueFromOtherCompartment(const Script::Interface& to, const Script::Interface& from, JS::HandleValue val) { PROFILE("CloneValueFromOtherCompartment"); Script::StructuredClone structuredClone; { - ScriptRequest fromRq(from); + Script::Request fromRq(from); structuredClone = WriteStructuredClone(fromRq, val); } - ScriptRequest toRq(to); + Script::Request toRq(to); JS::RootedValue out(toRq.cx); ReadStructuredClone(toRq, structuredClone, &out); return out.get(); } -JS::Value Script::DeepCopy(const ScriptRequest& rq, JS::HandleValue val) +JS::Value Script::DeepCopy(const Script::Request& rq, JS::HandleValue val) { JS::RootedValue out(rq.cx); ReadStructuredClone(rq, WriteStructuredClone(rq, val), &out); diff --git a/source/scriptinterface/StructuredClone.h b/source/scriptinterface/StructuredClone.h index 65ad385898..14917cd7bb 100644 --- a/source/scriptinterface/StructuredClone.h +++ b/source/scriptinterface/StructuredClone.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,14 +18,14 @@ #ifndef INCLUDED_SCRIPTINTERFACE_STRUCTUREDCLONE #define INCLUDED_SCRIPTINTERFACE_STRUCTUREDCLONE -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include class JSStructuredCloneData; -class ScriptInterface; namespace JS { class Value; } +namespace Script { class Interface; } namespace Script { @@ -38,8 +38,8 @@ namespace Script */ using StructuredClone = std::shared_ptr; -StructuredClone WriteStructuredClone(const ScriptRequest& rq, JS::HandleValue v); -void ReadStructuredClone(const ScriptRequest& rq, const StructuredClone& ptr, JS::MutableHandleValue ret); +StructuredClone WriteStructuredClone(const Script::Request& rq, JS::HandleValue v); +void ReadStructuredClone(const Script::Request& rq, const StructuredClone& ptr, JS::MutableHandleValue ret); /** * Construct a new value by cloning a value (possibly from a different Compartment). @@ -47,17 +47,17 @@ void ReadStructuredClone(const ScriptRequest& rq, const StructuredClone& ptr, JS * types and cyclic references should be fine. * Takes ScriptInterfaces to enter the correct realm. * Caller beware - manipulating several compartments in the same function is tricky. - * @param to - ScriptInterface of the target. Should match the rooting context of the result. - * @param from - ScriptInterface of @a val. + * @param to - Script::Interface of the target. Should match the rooting context of the result. + * @param from - Script::Interface of @a val. */ -JS::Value CloneValueFromOtherCompartment(const ScriptInterface& to, const ScriptInterface& from, JS::HandleValue val); +JS::Value CloneValueFromOtherCompartment(const Script::Interface& to, const Script::Interface& from, JS::HandleValue val); /** * Clone a JS value, ensuring that changes to the result * won't affect the original value. * Works by cloning, so the same restrictions as CloneValueFromOtherCompartment apply. */ -JS::Value DeepCopy(const ScriptRequest& rq, JS::HandleValue val); +JS::Value DeepCopy(const Script::Request& rq, JS::HandleValue val); } // namespace Script diff --git a/source/scriptinterface/tests/test_FunctionWrapper.h b/source/scriptinterface/tests/test_FunctionWrapper.h index b74cdcb4a4..cab5934c96 100644 --- a/source/scriptinterface/tests/test_FunctionWrapper.h +++ b/source/scriptinterface/tests/test_FunctionWrapper.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,8 +23,8 @@ #include "ps/Filesystem.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/ModuleLoader.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -50,30 +50,30 @@ public: void test_simple_wrappers() { - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); } static void _handle(JS::HandleValue) {}; static void _handle_2(int, JS::HandleValue, bool) {}; - static void _script_interface(const ScriptInterface&) {}; - static int _script_interface_2(const ScriptInterface&, int a, bool) { return a; }; + static void _script_interface(const Script::Interface&) {}; + static int _script_interface_2(const Script::Interface&, int a, bool) { return a; }; - static void _script_request(const ScriptRequest&) {}; - static int _script_request_2(const ScriptRequest&, int a, bool) { return a; }; + static void _script_request(const Script::Request&) {}; + static int _script_request_2(const Script::Request&, int a, bool) { return a; }; void test_special_wrappers() { - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); - static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); + static_assert(std::is_same_v), JSNative>); } class test_method @@ -87,29 +87,29 @@ public: void test_method_wrappers() { - static_assert(std::is_same_v>), JSNative>); - static_assert(std::is_same_v>), JSNative>); - static_assert(std::is_same_v>), JSNative>); - static_assert(std::is_same_v>), JSNative>); + static_assert(std::is_same_v>), JSNative>); + static_assert(std::is_same_v>), JSNative>); + static_assert(std::is_same_v>), JSNative>); + static_assert(std::is_same_v>), JSNative>); } void test_calling() { - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); - ScriptFunction::Register<&TestFunctionWrapper::_1p_v>(script, "_1p_v"); + Script::Function::Register<&TestFunctionWrapper::_1p_v>(script, "_1p_v"); { std::string input = "Test._1p_v(0);"; JS::RootedValue val(rq.cx); TS_ASSERT(script.Eval(input.c_str(), &val)); } - ScriptFunction::Register<&TestFunctionWrapper::_3p_r>(script, "_3p_r"); + Script::Function::Register<&TestFunctionWrapper::_3p_r>(script, "_3p_r"); { std::string input = "Test._3p_r(4, false, 'test');"; int ret = 0; @@ -117,7 +117,7 @@ public: TS_ASSERT_EQUALS(ret, 4); } - ScriptFunction::Register<&TestFunctionWrapper::_script_interface_2>(script, "_cmpt_private_2"); + Script::Function::Register<&TestFunctionWrapper::_script_interface_2>(script, "_cmpt_private_2"); { std::string input = "Test._cmpt_private_2(4);"; int ret = 0; @@ -128,22 +128,22 @@ public: void test_statefull() { - ScriptInterface script{"Test", "Test", g_ScriptContext}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext}; + const Script::Request rq{script}; JS::RootedValue nativeScope{rq.cx, JS::ObjectValue(*rq.nativeScope)}; constexpr const char* name{"callback"}; { bool called{false}; - auto _ = ScriptFunction::Register(rq, name, [&](){ + auto _ = Script::Function::Register(rq, name, [&](){ called = true; }); TS_ASSERT(!called); - TS_ASSERT(ScriptFunction::CallVoid(rq, nativeScope, name)); + TS_ASSERT(Script::Function::CallVoid(rq, nativeScope, name)); TS_ASSERT(called); } - TS_ASSERT(!ScriptFunction::CallVoid(rq, nativeScope, name)); + TS_ASSERT(!Script::Function::CallVoid(rq, nativeScope, name)); } void test_exception() @@ -152,12 +152,12 @@ public: TS_ASSERT_OK(g_VFS->Mount(L"", DataDir() / "mods" / "_test.scriptinterface" / "exception" / "", VFS_MOUNT_MUST_EXIST)); - ScriptInterface script{"Engine", "Test", g_ScriptContext, [](const VfsPath&){ + Script::Interface script{"Engine", "Test", g_ScriptContext, [](const VfsPath&){ return true; }}; - const ScriptRequest rq{script}; + const Script::Request rq{script}; - auto _ = ScriptFunction::Register(rq, "callback", [&](){ + auto _ = Script::Function::Register(rq, "callback", [&](){ throw std::runtime_error{"Testerror"}; }); diff --git a/source/scriptinterface/tests/test_Module.h b/source/scriptinterface/tests/test_Module.h index e3b0b1b3fb..6bafcde4ff 100644 --- a/source/scriptinterface/tests/test_Module.h +++ b/source/scriptinterface/tests/test_Module.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -28,10 +28,10 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/ModuleLoader.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -130,8 +130,8 @@ public: void test_StaticImport() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; TestLogger logger; std::ignore = script.GetModuleLoader().LoadModule(rq, "include/entry.js"); @@ -143,24 +143,24 @@ public: void test_Sequential() { { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; std::ignore = script.GetModuleLoader().LoadModule(rq, "empty.js"); } { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; std::ignore = script.GetModuleLoader().LoadModule(rq, "empty.js"); } } void test_Stacked() { - ScriptInterface scriptOuter{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rqOuter{scriptOuter}; + Script::Interface scriptOuter{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rqOuter{scriptOuter}; { - ScriptInterface scriptInner{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rqInner{scriptInner}; + Script::Interface scriptInner{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rqInner{scriptInner}; std::ignore = scriptInner.GetModuleLoader().LoadModule(rqInner, "empty.js"); } std::ignore = scriptOuter.GetModuleLoader().LoadModule(rqOuter, "empty.js"); @@ -168,8 +168,8 @@ public: void test_ImportInFunction() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; TestLogger logger; TS_ASSERT_THROWS(std::ignore = script.GetModuleLoader().LoadModule(rq, @@ -181,8 +181,8 @@ public: void test_NonExistent() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; const TestLogger _; TS_ASSERT_THROWS(std::ignore = script.GetModuleLoader().LoadModule(rq, "nonexistent.js"), @@ -191,8 +191,8 @@ public: void test_EvaluateOnce() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; { TestLogger logger; @@ -208,8 +208,8 @@ public: void test_TopLevelAwaitFinite() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "top_level_await_finite.js"); auto& future = *result.begin(); @@ -221,8 +221,8 @@ public: void test_TopLevelAwaitInfinite() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "top_level_await_infinite.js"); @@ -234,8 +234,8 @@ public: void test_MoveFulfilledFuture() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result{script.GetModuleLoader().LoadModule(rq, "empty.js")}; Script::ModuleLoader::Future& future0{*result.begin()}; @@ -254,8 +254,8 @@ public: void test_MoveEvaluatingFuture() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result{script.GetModuleLoader().LoadModule(rq, "top_level_await_finite.js")}; Script::ModuleLoader::Future& future0{*result.begin()}; @@ -275,8 +275,8 @@ public: void test_EvaluateReplacedFuture() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; TestLogger logger; auto blabbermouthResult{script.GetModuleLoader().LoadModule(rq, "delayed_blabbermouth.js")}; @@ -295,8 +295,8 @@ public: void test_TopLevelThrow() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; // To silence the error. const TestLogger _; @@ -311,8 +311,8 @@ public: void test_Export() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "export.js"); g_ScriptContext->RunJobs(); @@ -327,7 +327,7 @@ public: TS_ASSERT_EQUALS(value, 6); } - TS_ASSERT(ScriptFunction::CallVoid(rq, moduleValue, "mutate", 12)); + TS_ASSERT(Script::Function::CallVoid(rq, moduleValue, "mutate", 12)); { int value{0}; @@ -338,15 +338,15 @@ public: void test_ExportSame() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; { auto result = script.GetModuleLoader().LoadModule(rq, "export.js"); g_ScriptContext->RunJobs(); JS::RootedObject ns{rq.cx, result.begin()->Get()}; JS::RootedValue moduleValue{rq.cx, JS::ObjectValue(*ns)}; - TS_ASSERT(ScriptFunction::CallVoid(rq, moduleValue, "mutate", 12)); + TS_ASSERT(Script::Function::CallVoid(rq, moduleValue, "mutate", 12)); } { @@ -362,15 +362,15 @@ public: void test_ExportIndirect() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; { auto result = script.GetModuleLoader().LoadModule(rq, "export.js"); g_ScriptContext->RunJobs(); JS::RootedObject ns{rq.cx, result.begin()->Get()}; JS::RootedValue moduleValue{rq.cx, JS::ObjectValue(*ns)}; - TS_ASSERT(ScriptFunction::CallVoid(rq, moduleValue, "mutate", 12)); + TS_ASSERT(Script::Function::CallVoid(rq, moduleValue, "mutate", 12)); } { @@ -386,8 +386,8 @@ public: void test_ExportDefaultImmutable() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "export_default/immutable.js"); g_ScriptContext->RunJobs(); @@ -403,8 +403,8 @@ public: void test_ExportDefaultInvalid() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; TestLogger logger; TS_ASSERT_THROWS(std::ignore = script.GetModuleLoader().LoadModule(rq, @@ -415,8 +415,8 @@ public: void test_ExportDefaultDoesNotWorkAround() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "export_default/does_not_work_around.js"); @@ -434,8 +434,8 @@ public: void test_ExportDefaultWorksAround() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "export_default/works_around.js"); g_ScriptContext->RunJobs(); @@ -451,8 +451,8 @@ public: void test_ReplaceEvaluatingFuture() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto awaitResult = script.GetModuleLoader().LoadModule(rq, "top_level_await_finite.js"); auto future = std::move(*awaitResult.begin()); @@ -470,8 +470,8 @@ public: void test_DynamicImport() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "dynamic_import.js"); g_ScriptContext->RunJobs(); @@ -481,7 +481,7 @@ public: JS::RootedValue moduleValue{rq.cx, JS::ObjectValue(*ns)}; JS::RootedValue promise{rq.cx}; - TS_ASSERT(ScriptFunction::Call(rq, moduleValue, "default", &promise)); + TS_ASSERT(Script::Function::Call(rq, moduleValue, "default", &promise)); TS_ASSERT(promise.isObject()); JS::RootedObject promiseObject{rq.cx, &promise.toObject()}; TS_ASSERT(JS::IsPromiseObject(promiseObject)); @@ -501,8 +501,8 @@ public: void test_Meta() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "meta.js"); g_ScriptContext->RunJobs(); @@ -512,7 +512,7 @@ public: const JS::RootedValue modNamespace{rq.cx, JS::ObjectValue(*ns)}; JS::RootedValue meta{rq.cx}; - TS_ASSERT(ScriptFunction::Call(rq, modNamespace, "getMeta", &meta)); + TS_ASSERT(Script::Function::Call(rq, modNamespace, "getMeta", &meta)); std::string path; TS_ASSERT(Script::GetProperty(rq, meta, "path", path)); @@ -521,8 +521,8 @@ public: void test_Modified() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "modified/base.js"); g_ScriptContext->RunJobs(); @@ -532,7 +532,7 @@ public: JS::RootedValue moduleValue{rq.cx, JS::ObjectValue(*ns)}; std::string returnValue; - TS_ASSERT(ScriptFunction::Call(rq, moduleValue, "fn", returnValue)); + TS_ASSERT(Script::Function::Call(rq, moduleValue, "fn", returnValue)); TS_ASSERT_STR_EQUALS(returnValue, "Base01"); } @@ -540,8 +540,8 @@ public: { constexpr int goal{2}; - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; int counter{0}; for (auto& future : script.GetModuleLoader().LoadModule(rq, "empty.js")) @@ -565,8 +565,8 @@ public: void test_HotloadWithoutIncrement() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "top_level_await_finite.js"); g_ScriptContext->RunJobs(); @@ -577,8 +577,8 @@ public: void test_HotloadIndipendence() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; // It's intended to be used as in the test above but it's easier to test when it's unrolled. auto result = script.GetModuleLoader().LoadModule(rq, "export.js"); @@ -589,7 +589,7 @@ public: JS::RootedObject ns{rq.cx, future.Get()}; const JS::RootedValue moduleValue{rq.cx, JS::ObjectValue(*ns)}; - TS_ASSERT(ScriptFunction::CallVoid(rq, moduleValue, "mutate", 12)); + TS_ASSERT(Script::Function::CallVoid(rq, moduleValue, "mutate", 12)); int value{0}; TS_ASSERT(Script::GetProperty(rq, moduleValue, "value", value)); @@ -616,8 +616,8 @@ public: void test_HotloadModified() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "empty.js"); auto iter = result.begin(); @@ -635,8 +635,8 @@ public: void test_HotloadIndirect() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + const Script::Request rq{script}; auto result = script.GetModuleLoader().LoadModule(rq, "indirect.js"); auto iter = result.begin(); @@ -652,9 +652,9 @@ public: void test_HotloadUnobserved() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; { - const ScriptRequest rq{script}; + const Script::Request rq{script}; TestLogger logger; auto result = script.GetModuleLoader().LoadModule(rq, "blabbermouth.js"); @@ -670,7 +670,7 @@ public: } { - const ScriptRequest rq{script}; + const Script::Request rq{script}; TestLogger logger; auto result = script.GetModuleLoader().LoadModule(rq, "blabbermouth.js"); @@ -681,9 +681,9 @@ public: void test_HotloadAfterResultDestruction() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; { - const ScriptRequest rq{script}; + const Script::Request rq{script}; TestLogger logger; auto result = script.GetModuleLoader().LoadModule(rq, "blabbermouth.js"); @@ -703,8 +703,8 @@ public: void test_HotloadAfterScriptRequestDestruction() { - ScriptInterface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; - auto result = script.GetModuleLoader().LoadModule(ScriptRequest{script}, "empty.js"); + Script::Interface script{"Test", "Test", g_ScriptContext, AllowAllPredicate}; + auto result = script.GetModuleLoader().LoadModule(Script::Request{script}, "empty.js"); g_ScriptContext->RunJobs(); auto iter = result.begin(); TS_ASSERT(iter->IsDone()); @@ -717,8 +717,8 @@ public: void test_RestrictionNoPredicate() { - ScriptInterface script{"Test", "Test", g_ScriptContext}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext}; + const Script::Request rq{script}; TS_ASSERT_THROWS_EQUALS(std::ignore = script.GetModuleLoader().LoadModule(rq, "empty.js"), const std::runtime_error& e, e.what(), @@ -727,8 +727,8 @@ public: void test_RestrictionDirect() { - ScriptInterface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; + const Script::Request rq{script}; TS_ASSERT_THROWS_EQUALS(std::ignore = script.GetModuleLoader().LoadModule(rq, "restriction/disallowedfile.js"), const std::runtime_error& e, e.what(), @@ -737,8 +737,8 @@ public: void test_RestrictionIndirect() { - ScriptInterface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; + const Script::Request rq{script}; TestLogger logger; TS_ASSERT_THROWS_EQUALS(std::ignore = script.GetModuleLoader().LoadModule(rq, "restriction/import.js"), const std::invalid_argument& e, e.what(), @@ -749,8 +749,8 @@ public: void test_RestrictionFancy() { - ScriptInterface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; + const Script::Request rq{script}; TestLogger logger; TS_ASSERT_THROWS_EQUALS(std::ignore = script.GetModuleLoader().LoadModule(rq, "restriction/fancy_import.js"), const std::invalid_argument& e, e.what(), @@ -761,8 +761,8 @@ public: void test_RestrictionDynamic() { - ScriptInterface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; - const ScriptRequest rq{script}; + Script::Interface script{"Test", "Test", g_ScriptContext, DisallowedfilePredicate}; + const Script::Request rq{script}; TestLogger logger; auto result = script.GetModuleLoader().LoadModule(rq, "restriction/dynamic_import.js"); diff --git a/source/scriptinterface/tests/test_Promises.h b/source/scriptinterface/tests/test_Promises.h index 9d3dafabeb..a2985dae16 100644 --- a/source/scriptinterface/tests/test_Promises.h +++ b/source/scriptinterface/tests/test_Promises.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,9 +22,9 @@ #include "ps/CLogger.h" #include "ps/Filesystem.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -37,19 +37,19 @@ class TestPromises : public CxxTest::TestSuite public: void test_simple_promises() { - ScriptInterface script("Engine", "Test", g_ScriptContext); + Script::Interface script("Engine", "Test", g_ScriptContext); ScriptTestSetup(script); TS_ASSERT(script.LoadGlobalScriptFile(L"promises/simple.js")); g_ScriptContext->RunJobs(); - ScriptRequest rq(script); + Script::Request rq(script); JS::RootedValue global(rq.cx, rq.globalValue()); - ScriptFunction::CallVoid(rq, global, "endTest"); + Script::Function::CallVoid(rq, global, "endTest"); } void test_exception() { - ScriptInterface script("Engine", "Test", g_ScriptContext); + Script::Interface script("Engine", "Test", g_ScriptContext); TestLogger logger; TS_ASSERT(script.LoadGlobalScriptFile(L"promises/reject.js")); TS_ASSERT_STR_CONTAINS(logger.GetOutput(), diff --git a/source/scriptinterface/tests/test_ScriptConversions.h b/source/scriptinterface/tests/test_ScriptConversions.h index 7dea78522c..5c9139d5e3 100644 --- a/source/scriptinterface/tests/test_ScriptConversions.h +++ b/source/scriptinterface/tests/test_ScriptConversions.h @@ -25,9 +25,9 @@ #include "maths/FixedVector3D.h" #include "ps/Filesystem.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -41,9 +41,9 @@ class TestScriptConversions : public CxxTest::TestSuite template void convert_to(const T& value, const std::string& expected) { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TS_ASSERT(script.LoadGlobalScripts()); - ScriptRequest rq(script); + Script::Request rq(script); JS::RootedValue v1(rq.cx); Script::ToJSVal(rq, &v1, value); @@ -52,7 +52,7 @@ class TestScriptConversions : public CxxTest::TestSuite // since they might not be objects. So just use uneval. std::string source; JS::RootedValue global(rq.cx, rq.globalValue()); - TS_ASSERT(ScriptFunction::Call(rq, global, "uneval", source, v1)); + TS_ASSERT(Script::Function::Call(rq, global, "uneval", source, v1)); TS_ASSERT_STR_EQUALS(source, expected); } @@ -60,16 +60,16 @@ class TestScriptConversions : public CxxTest::TestSuite template void roundtrip(const T& value, const char* expected) { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TS_ASSERT(script.LoadGlobalScripts()); - ScriptRequest rq(script); + Script::Request rq(script); JS::RootedValue v1(rq.cx); Script::ToJSVal(rq, &v1, value); std::string source; JS::RootedValue global(rq.cx, rq.globalValue()); - TS_ASSERT(ScriptFunction::Call(rq, global, "uneval", source, v1)); + TS_ASSERT(Script::Function::Call(rq, global, "uneval", source, v1)); if (expected) TS_ASSERT_STR_EQUALS(source, expected); @@ -82,9 +82,9 @@ class TestScriptConversions : public CxxTest::TestSuite template void call_prototype_function(const T& u, const T& v, const std::string& func, const std::string& expected) { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TS_ASSERT(script.LoadGlobalScripts()); - ScriptRequest rq(script); + Script::Request rq(script); JS::RootedValue v1(rq.cx); Script::ToJSVal(rq, &v1, v); @@ -94,12 +94,12 @@ class TestScriptConversions : public CxxTest::TestSuite T r; JS::RootedValue r1(rq.cx); - TS_ASSERT(ScriptFunction::Call(rq, u1, func.c_str(), r, v1)); + TS_ASSERT(Script::Function::Call(rq, u1, func.c_str(), r, v1)); Script::ToJSVal(rq, &r1, r); std::string source; JS::RootedValue global(rq.cx, rq.globalValue()); - TS_ASSERT(ScriptFunction::Call(rq, global, "uneval", source, r1)); + TS_ASSERT(Script::Function::Call(rq, global, "uneval", source, r1)); TS_ASSERT_STR_EQUALS(source, expected); } @@ -176,8 +176,8 @@ public: void test_integers() { - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); // using new uninitialized variables each time to be sure the test doesn't succeeed if ToJSVal doesn't touch the value at all. JS::RootedValue val0(rq.cx), val1(rq.cx), val2(rq.cx), val3(rq.cx), val4(rq.cx), val5(rq.cx), val6(rq.cx), val7(rq.cx), val8(rq.cx); @@ -208,8 +208,8 @@ public: roundtrip(-std::numeric_limits::infinity(), "-Infinity"); convert_to(std::numeric_limits::quiet_NaN(), "NaN"); // can't use roundtrip since nan != nan - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); float f = 0; JS::RootedValue testNANVal(rq.cx); @@ -258,9 +258,9 @@ public: void test_utf8utf16_conversion() { // Fancier conversion: we store UTF8 and get UTF16 and vice-versa - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TS_ASSERT(script.LoadGlobalScripts()); - ScriptRequest rq(script); + Script::Request rq(script); std::string in_utf8("éè!§$-aezi134900°°©©¢¢ÇÇ'{¶«¡Ç'[å»ÛÁØ"); std::wstring in_utf16(L"éè!§$-aezi134900°°©©¢¢ÇÇ'{¶«¡Ç'[å»ÛÁØ"); diff --git a/source/scriptinterface/tests/test_ScriptInterface.h b/source/scriptinterface/tests/test_ScriptInterface.h index 81d9dea76d..2623b2f279 100644 --- a/source/scriptinterface/tests/test_ScriptInterface.h +++ b/source/scriptinterface/tests/test_ScriptInterface.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,9 +23,9 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include @@ -39,7 +39,7 @@ class TestScriptInterface : public CxxTest::TestSuite public: void test_loadscript_basic() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TestLogger logger; TS_ASSERT(script.LoadScript(L"test.js", "var x = 1+1;")); TS_ASSERT_STR_NOT_CONTAINS(logger.GetOutput(), "JavaScript error"); @@ -48,7 +48,7 @@ public: void test_loadscript_error() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TestLogger logger; TS_ASSERT(!script.LoadScript(L"test.js", "1+")); TS_ASSERT_STR_CONTAINS(logger.GetOutput(), "ERROR: JavaScript error: test.js line 2\nexpected expression, got \'}\'"); @@ -56,7 +56,7 @@ public: void test_loadscript_strict_warning() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TestLogger logger; // in strict mode, this inside a function doesn't point to the global object TS_ASSERT(script.LoadScript(L"test.js", "var isStrict = (function() { return !this; })();warn('isStrict is '+isStrict);")); @@ -65,7 +65,7 @@ public: void test_loadscript_strict_error() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TestLogger logger; TS_ASSERT(!script.LoadScript(L"test.js", "with(1){}")); TS_ASSERT_STR_CONTAINS(logger.GetOutput(), "ERROR: JavaScript error: test.js line 1\nstrict mode code may not contain \'with\' statements"); @@ -73,20 +73,20 @@ public: void test_clone_basic() { - ScriptInterface script1("Test", "Test", g_ScriptContext); - ScriptInterface script2("Test", "Test", g_ScriptContext); + Script::Interface script1("Test", "Test", g_ScriptContext); + Script::Interface script2("Test", "Test", g_ScriptContext); - ScriptRequest rq1(script1); + Script::Request rq1(script1); JS::RootedValue obj1(rq1.cx); TS_ASSERT(script1.Eval("({'x': 123, 'y': [1, 1.5, '2', 'test', undefined, null, true, false]})", &obj1)); { - ScriptRequest rq2(script2); + Script::Request rq2(script2); JS::RootedValue obj2(rq2.cx, Script::CloneValueFromOtherCompartment(script2, script1, obj1)); std::string source; - TS_ASSERT(ScriptFunction::Call(rq2, obj2, "toSource", source)); + TS_ASSERT(Script::Function::Call(rq2, obj2, "toSource", source)); TS_ASSERT_STR_EQUALS(source, "({x:123, y:[1, 1.5, \"2\", \"test\", (void 0), null, true, false]})"); } } @@ -94,37 +94,37 @@ public: void test_clone_getters() { // The tests should be run with JS_SetGCZeal so this can try to find GC bugs - ScriptInterface script1("Test", "Test", g_ScriptContext); - ScriptInterface script2("Test", "Test", g_ScriptContext); + Script::Interface script1("Test", "Test", g_ScriptContext); + Script::Interface script2("Test", "Test", g_ScriptContext); - ScriptRequest rq1(script1); + Script::Request rq1(script1); JS::RootedValue obj1(rq1.cx); TS_ASSERT(script1.Eval("var s = '?'; var v = ({get x() { return 123 }, 'y': {'w':{get z() { delete v.y; delete v.n; v = null; s += s; return 4 }}}, 'n': 100}); v", &obj1)); { - ScriptRequest rq2(script2); + Script::Request rq2(script2); JS::RootedValue obj2(rq2.cx, Script::CloneValueFromOtherCompartment(script2, script1, obj1)); std::string source; - TS_ASSERT(ScriptFunction::Call(rq2, obj2, "toSource", source)); + TS_ASSERT(Script::Function::Call(rq2, obj2, "toSource", source)); TS_ASSERT_STR_EQUALS(source, "({x:123, y:{w:{z:4}}})"); } } void test_clone_cyclic() { - ScriptInterface script1("Test", "Test", g_ScriptContext); - ScriptInterface script2("Test", "Test", g_ScriptContext); + Script::Interface script1("Test", "Test", g_ScriptContext); + Script::Interface script2("Test", "Test", g_ScriptContext); - ScriptRequest rq1(script1); + Script::Request rq1(script1); JS::RootedValue obj1(rq1.cx); TS_ASSERT(script1.Eval("var x = []; x[0] = x; ({'a': x, 'b': x})", &obj1)); { - ScriptRequest rq2(script2); + Script::Request rq2(script2); JS::RootedValue obj2(rq2.cx, Script::CloneValueFromOtherCompartment(script2, script1, obj1)); // Use JSAPI function to check if the values of the properties "a", "b" are equals a.x[0] @@ -143,7 +143,7 @@ public: void test_deepfreeze() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); TestLogger logger; TS_ASSERT(!script.LoadScript(L"testFreezeObject.js", "var obj1 = { foo: \"a\"}; deepfreeze(obj1); obj1.bar = \"b\";")); @@ -165,9 +165,9 @@ public: */ void test_rooted_templates() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Request rq(script); JS::RootedValue val(rq.cx); JS::RootedValue out(rq.cx); @@ -182,15 +182,15 @@ public: JS::RootedValue nbrVal(rq.cx, JS::NumberValue(3)); int nbr = 0; - ScriptFunction::CallVoid(rq, val, "setTo", nbrVal); + Script::Function::CallVoid(rq, val, "setTo", nbrVal); // Test that a mutable handle value as return value works. - ScriptFunction::Call(rq, val, "inc", &out); + Script::Function::Call(rq, val, "inc", &out); Script::FromJSVal(rq, out, nbr); TS_ASSERT_EQUALS(4, nbr); - ScriptFunction::Call(rq, val, "add", nbr, nbrVal); + Script::Function::Call(rq, val, "add", nbr, nbrVal); TS_ASSERT_EQUALS(7, nbr); // GetProperty JS::RootedValue* overload @@ -208,19 +208,19 @@ public: handle_templates_test(script, val, &out, nbrVal); } - void handle_templates_test(const ScriptInterface& script, JS::HandleValue val, JS::MutableHandleValue out, JS::HandleValue nbrVal) + void handle_templates_test(const Script::Interface& script, JS::HandleValue val, JS::MutableHandleValue out, JS::HandleValue nbrVal) { - ScriptRequest rq(script); + Script::Request rq(script); int nbr = 0; - ScriptFunction::CallVoid(rq, val, "setTo", nbrVal); - ScriptFunction::Call(rq, val, "inc", out); + Script::Function::CallVoid(rq, val, "setTo", nbrVal); + Script::Function::Call(rq, val, "inc", out); Script::FromJSVal(rq, out, nbr); TS_ASSERT_EQUALS(4, nbr); - ScriptFunction::Call(rq, val, "add", nbr, nbrVal); + Script::Function::Call(rq, val, "add", nbr, nbrVal); TS_ASSERT_EQUALS(7, nbr); // GetProperty JS::MutableHandleValue overload @@ -238,7 +238,7 @@ public: void test_random() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); double d1, d2; TS_ASSERT(script.Eval("Math.random()", d1)); @@ -258,8 +258,8 @@ public: void test_json() { - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); std::string input = "({'x':1,'z':[2,'3\\u263A\\ud800'],\"y\":true})"; JS::RootedValue val(rq.cx); @@ -276,8 +276,8 @@ public: // extends the functionality and is then assigned to the name of the function. void test_function_override() { - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); TS_ASSERT(script.Eval( "function f() { return 1; }" diff --git a/source/simulation2/MessageTypes.h b/source/simulation2/MessageTypes.h index 249438b7c4..8e24551338 100644 --- a/source/simulation2/MessageTypes.h +++ b/source/simulation2/MessageTypes.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -35,14 +35,14 @@ #include #include -class ScriptRequest; +namespace Script { class Request; } #define DEFAULT_MESSAGE_IMPL(name) \ virtual int GetType() const { return MT_##name; } \ virtual const char* GetScriptHandlerName() const { return "On" #name; } \ virtual const char* GetScriptGlobalHandlerName() const { return "OnGlobal" #name; } \ - virtual JS::Value ToJSVal(const ScriptRequest& rq) const; \ - static CMessage* FromJSVal(const ScriptRequest&, JS::HandleValue val); + virtual JS::Value ToJSVal(const Script::Request& rq) const; \ + static CMessage* FromJSVal(const Script::Request&, JS::HandleValue val); class SceneCollector; class CFrustum; diff --git a/source/simulation2/Simulation2.cpp b/source/simulation2/Simulation2.cpp index 013b71bb32..6acebfbb89 100644 --- a/source/simulation2/Simulation2.cpp +++ b/source/simulation2/Simulation2.cpp @@ -45,9 +45,9 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpAIManager.h" @@ -76,7 +76,7 @@ class CSimulation2Impl { public: - CSimulation2Impl(CUnitManager* unitManager, ScriptContext& cx, CTerrain* terrain, + CSimulation2Impl(CUnitManager* unitManager, Script::Context& cx, CTerrain* terrain, const std::span scriptDirectories, const SimulationDebugOptions debugOptions) : m_SimContext{terrain, unitManager}, m_ComponentManager{m_SimContext, cx}, @@ -198,13 +198,13 @@ public: void InitRNGSeedSimulation(); void InitRNGSeedAI(); - static std::vector CloneCommandsFromOtherCompartment(const ScriptInterface& newScript, const ScriptInterface& oldScript, + static std::vector CloneCommandsFromOtherCompartment(const Script::Interface& newScript, const Script::Interface& oldScript, const std::vector& commands) { std::vector newCommands; newCommands.reserve(commands.size()); - ScriptRequest rqNew(newScript); + Script::Request rqNew(newScript); for (const SimulationCommand& command : commands) { JS::RootedValue tmpCommand(rqNew.cx, Script::CloneValueFromOtherCompartment(newScript, oldScript, command.data)); @@ -235,7 +235,7 @@ void CSimulation2Impl::LoadScripts(CComponentManager& componentManager, std::set bool CSimulation2Impl::LoadTriggerScripts(CComponentManager& componentManager, JS::HandleValue mapSettings, std::set* loadedScripts) { bool ok = true; - ScriptRequest rq(componentManager.GetScriptInterface()); + Script::Request rq(componentManager.GetScriptInterface()); if (Script::HasProperty(rq, mapSettings, "TriggerScripts")) { std::vector scriptNames; @@ -359,7 +359,7 @@ void CSimulation2Impl::ReportSerializationFailure( void CSimulation2Impl::InitRNGSeedSimulation() { u32 seed = 0; - ScriptRequest rq(m_ComponentManager.GetScriptInterface()); + Script::Request rq(m_ComponentManager.GetScriptInterface()); if (!Script::HasProperty(rq, m_MapSettings, "Seed") || !Script::GetProperty(rq, m_MapSettings, "Seed", seed)) LOGWARNING("CSimulation2Impl::InitRNGSeedSimulation: No seed value specified - using %d", seed); @@ -370,7 +370,7 @@ void CSimulation2Impl::InitRNGSeedSimulation() void CSimulation2Impl::InitRNGSeedAI() { u32 seed = 0; - ScriptRequest rq(m_ComponentManager.GetScriptInterface()); + Script::Request rq(m_ComponentManager.GetScriptInterface()); if (!Script::HasProperty(rq, m_MapSettings, "AISeed") || !Script::GetProperty(rq, m_MapSettings, "AISeed", seed)) LOGWARNING("CSimulation2Impl::InitRNGSeedAI: No seed value specified - using %d", seed); @@ -405,7 +405,7 @@ void CSimulation2Impl::Update(int turnLength, const std::vectorGetScriptInterface()); + const Script::Request rq2(m_SecondaryComponentManager->GetScriptInterface()); const JS::RootedValue initAttributesCloned(rq2.cx, Script::CloneValueFromOtherCompartment(m_SecondaryComponentManager->GetScriptInterface(), scriptInterface, m_InitAttributes)); m_SecondaryComponentManager->GetScriptInterface().SetGlobal("InitAttributes", initAttributesCloned, true, true, true); } // Load the trigger scripts after we have loaded the simulation. { - ScriptRequest rq2(m_SecondaryComponentManager->GetScriptInterface()); + Script::Request rq2(m_SecondaryComponentManager->GetScriptInterface()); JS::RootedValue mapSettingsCloned(rq2.cx, Script::CloneValueFromOtherCompartment(m_SecondaryComponentManager->GetScriptInterface(), scriptInterface, m_MapSettings)); ENSURE(LoadTriggerScripts(*m_SecondaryComponentManager, mapSettingsCloned, m_SecondaryLoadedScripts.get())); } @@ -662,7 +662,7 @@ void CSimulation2Impl::DumpState() //////////////////////////////////////////////////////////////// -CSimulation2::CSimulation2(CUnitManager* unitManager, ScriptContext& cx, CTerrain* terrain, +CSimulation2::CSimulation2(CUnitManager* unitManager, Script::Context& cx, CTerrain* terrain, const std::span scriptDirectories, const SimulationDebugOptions debugOptions) : m(std::make_unique(unitManager, cx, terrain, scriptDirectories, debugOptions)) { @@ -727,28 +727,28 @@ const CSimContext& CSimulation2::GetSimContext() const return m->m_SimContext; } -ScriptInterface& CSimulation2::GetScriptInterface() const +Script::Interface& CSimulation2::GetScriptInterface() const { return m->m_ComponentManager.GetScriptInterface(); } void CSimulation2::PreInitGame() { - ScriptRequest rq(GetScriptInterface()); + Script::Request rq(GetScriptInterface()); JS::RootedValue global(rq.cx, rq.globalValue()); - ScriptFunction::CallVoid(rq, global, "PreInitGame"); + Script::Function::CallVoid(rq, global, "PreInitGame"); } void CSimulation2::InitGame() { - ScriptRequest rq(GetScriptInterface()); + Script::Request rq(GetScriptInterface()); JS::RootedValue global(rq.cx, rq.globalValue()); JS::RootedValue settings(rq.cx); JS::RootedValue tmpInitAttributes(rq.cx, GetInitAttributes()); Script::GetProperty(rq, tmpInitAttributes, "settings", &settings); - ScriptFunction::CallVoid(rq, global, "InitGame", settings); + Script::Function::CallVoid(rq, global, "InitGame", settings); } void CSimulation2::Update(int turnLength) @@ -807,7 +807,7 @@ void CSimulation2::GetInitAttributes(JS::MutableHandleValue ret) void CSimulation2::SetMapSettings(const std::string& settings) { - Script::ParseJSON(ScriptRequest(m->m_ComponentManager.GetScriptInterface()), settings, &m->m_MapSettings); + Script::ParseJSON(Script::Request(m->m_ComponentManager.GetScriptInterface()), settings, &m->m_MapSettings); } void CSimulation2::SetMapSettings(JS::HandleValue settings) @@ -820,7 +820,7 @@ void CSimulation2::SetMapSettings(JS::HandleValue settings) std::string CSimulation2::GetMapSettingsString() { - return Script::StringifyJSON(ScriptRequest(m->m_ComponentManager.GetScriptInterface()), &m->m_MapSettings); + return Script::StringifyJSON(Script::Request(m->m_ComponentManager.GetScriptInterface()), &m->m_MapSettings); } void CSimulation2::GetMapSettings(JS::MutableHandleValue ret) @@ -830,19 +830,19 @@ void CSimulation2::GetMapSettings(JS::MutableHandleValue ret) void CSimulation2::LoadPlayerSettings(bool newPlayers) { - ScriptRequest rq(GetScriptInterface()); + Script::Request rq(GetScriptInterface()); JS::RootedValue global(rq.cx, rq.globalValue()); - ScriptFunction::CallVoid(rq, global, "LoadPlayerSettings", m->m_MapSettings, newPlayers); + Script::Function::CallVoid(rq, global, "LoadPlayerSettings", m->m_MapSettings, newPlayers); } void CSimulation2::LoadMapSettings() { - ScriptRequest rq(GetScriptInterface()); + Script::Request rq(GetScriptInterface()); JS::RootedValue global(rq.cx, rq.globalValue()); // Initialize here instead of in Update() - ScriptFunction::CallVoid(rq, global, "LoadMapSettings", m->m_MapSettings); + Script::Function::CallVoid(rq, global, "LoadMapSettings", m->m_MapSettings); Script::DeepFreezeObject(rq, m->m_InitAttributes); GetScriptInterface().SetGlobal("InitAttributes", m->m_InitAttributes, true, true, true); @@ -976,8 +976,8 @@ std::string CSimulation2::GetMapSizes() std::string CSimulation2::GetAIData() { - const ScriptInterface& scriptInterface = GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue aiData(rq.cx, ICmpAIManager::GetAIs(scriptInterface)); // Build single JSON string with array of AI data diff --git a/source/simulation2/Simulation2.h b/source/simulation2/Simulation2.h index 643b0f0fe5..2c326b0629 100644 --- a/source/simulation2/Simulation2.h +++ b/source/simulation2/Simulation2.h @@ -43,9 +43,9 @@ class CTerrain; class CUnitManager; class IComponent; class SceneCollector; -class ScriptContext; -class ScriptInterface; +namespace Script { class Context; } namespace JS { class Value; } +namespace Script { class Interface; } struct SimulationCommand; /** @@ -72,7 +72,7 @@ public: * (non-recursively) are loaded, so that they can register new * component types and functions. */ - CSimulation2(CUnitManager* unitManager, ScriptContext& cx, CTerrain* terrain, + CSimulation2(CUnitManager* unitManager, Script::Context& cx, CTerrain* terrain, const std::span scriptDirectories, const SimulationDebugOptions debugOptions = {}); ~CSimulation2(); @@ -230,7 +230,7 @@ public: const InterfaceListUnordered& GetEntitiesWithInterfaceUnordered(int iid); const CSimContext& GetSimContext() const; - ScriptInterface& GetScriptInterface() const; + Script::Interface& GetScriptInterface() const; bool ComputeStateHash(std::string& outHash, bool quick); bool DumpDebugState(std::ostream& stream); diff --git a/source/simulation2/components/CCmpAIManager.cpp b/source/simulation2/components/CCmpAIManager.cpp index dcfdef0354..722e38e729 100644 --- a/source/simulation2/components/CCmpAIManager.cpp +++ b/source/simulation2/components/CCmpAIManager.cpp @@ -43,10 +43,10 @@ #include "scriptinterface/JSON.h" #include "scriptinterface/ModuleLoader.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/components/ICmpAIInterface.h" #include "simulation2/components/ICmpCommandQueue.h" @@ -122,7 +122,7 @@ private: NONCOPYABLE(CAIPlayer); public: CAIPlayer(CAIWorker& worker, const std::wstring& aiName, player_id_t player, u8 difficulty, const std::wstring& behavior, - std::shared_ptr scriptInterface) : + std::shared_ptr scriptInterface) : m_Worker(worker), m_AIName(aiName), m_Player(player), m_Difficulty(difficulty), m_Behavior(behavior), m_ScriptInterface(scriptInterface), m_Obj(scriptInterface->GetGeneralJSContext()) { @@ -130,7 +130,7 @@ private: bool Initialise() { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); OsPath path = L"simulation/ai/" + m_AIName + L"/data.json"; JS::RootedValue metadata(rq.cx); @@ -206,22 +206,22 @@ private: void Run(JS::HandleValue state, int playerID) { m_Commands.clear(); - ScriptRequest rq(m_ScriptInterface); - ScriptFunction::CallVoid(rq, m_Obj, "HandleMessage", state, playerID); + Script::Request rq(m_ScriptInterface); + Script::Function::CallVoid(rq, m_Obj, "HandleMessage", state, playerID); } // overloaded with a sharedAI part. // javascript can handle both natively on the same function. void Run(JS::HandleValue state, int playerID, JS::HandleValue SharedAI) { m_Commands.clear(); - ScriptRequest rq(m_ScriptInterface); - ScriptFunction::CallVoid(rq, m_Obj, "HandleMessage", state, playerID, SharedAI); + Script::Request rq(m_ScriptInterface); + Script::Function::CallVoid(rq, m_Obj, "HandleMessage", state, playerID, SharedAI); } void InitAI(JS::HandleValue state, JS::HandleValue SharedAI) { m_Commands.clear(); - ScriptRequest rq(m_ScriptInterface); - ScriptFunction::CallVoid(rq, m_Obj, "Init", state, m_Player, SharedAI); + Script::Request rq(m_ScriptInterface); + Script::Function::CallVoid(rq, m_Obj, "Init", state, m_Player, SharedAI); } CAIWorker& m_Worker; @@ -233,7 +233,7 @@ private: // Take care to keep this declaration before heap rooted members. Destructors of heap rooted // members have to be called before the context destructor. - std::shared_ptr m_ScriptInterface; + std::shared_ptr m_ScriptInterface; JS::PersistentRootedValue m_Obj; std::vector m_Commands; @@ -260,17 +260,17 @@ public: JS_RemoveExtraGCRootsTracer(m_ScriptInterface->GetGeneralJSContext(), Trace, this); } - void Init(const ScriptInterface& simInterface) + void Init(const Script::Interface& simInterface) { // Create the script interface in the same compartment as the simulation interface. // This will allow us to directly share data from the sim to the AI (and vice versa, should the need arise). - m_ScriptInterface = std::make_shared("Engine", "AI", simInterface, + m_ScriptInterface = std::make_shared("Engine", "AI", simInterface, [](const VfsPath& path) { return path.string().find(L"simulation/ai/") == 0; }); - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); m_EntityTemplates.init(rq.cx); m_SharedAIObj.init(rq.cx); @@ -285,7 +285,7 @@ public: JS_AddExtraGCRootsTracer(m_ScriptInterface->GetGeneralJSContext(), Trace, this); { - ScriptRequest simrq(simInterface); + Script::Request simrq(simInterface); // Register the sim globals for easy & explicit access. Mark it replaceable for hotloading. JS::RootedValue global(rq.cx, simrq.globalValue()); m_ScriptInterface->SetGlobal("Sim", global, true); @@ -294,10 +294,10 @@ public: } #define REGISTER_FUNC_NAME(func, name) \ - ScriptFunction::Register<&CAIWorker::func, ScriptInterface::ObjectFromCBData>(rq, name); + Script::Function::Register<&CAIWorker::func, Script::Interface::ObjectFromCBData>(rq, name); REGISTER_FUNC_NAME(PostCommand, "PostCommand"); - ScriptFunction::Register(rq, "Exit"); + Script::Function::Register(rq, "Exit"); REGISTER_FUNC_NAME(ComputePathScript, "ComputePath"); @@ -317,7 +317,7 @@ public: void PostCommand(int playerid, JS::HandleValue cmd) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); for (size_t i=0; im_Player == playerid) @@ -332,7 +332,7 @@ public: JS::Value ComputePathScript(JS::HandleValue position, JS::HandleValue goal, pass_class_t passClass) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); CFixedVector2D pos, goalPos; std::vector waypoints; @@ -409,7 +409,7 @@ public: bool TryLoadSharedComponent() { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); // we don't need to load it. if (!std::exchange(m_HasSharedComponent, true)) @@ -489,7 +489,7 @@ public: // this will be run last by InitGame.js, passing the full game representation. // For now it will run for the shared Component. // This is NOT run during deserialization. - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedValue state(rq.cx); Script::ReadStructuredClone(rq, gameState, &state); @@ -507,7 +507,7 @@ public: { Script::SetProperty(rq, state, "passabilityMap", m_PassabilityMapVal, true); Script::SetProperty(rq, state, "territoryMap", m_TerritoryMapVal, true); - ScriptFunction::CallVoid(rq, m_SharedAIObj, "init", state); + Script::Function::CallVoid(rq, m_SharedAIObj, "init", state); for (size_t i = 0; i < m_Players.size(); ++i) { @@ -523,7 +523,7 @@ public: { ENSURE(m_CommandsComputed); m_GameState.reset(); - m_GameState.init(ScriptRequest(m_ScriptInterface).cx, gameState); + m_GameState.init(Script::Request(m_ScriptInterface).cx, gameState); } void UpdatePathfinder(const Grid& passabilityMap, bool globallyDirty, const Grid& dirtinessGrid, bool justDeserialized, @@ -544,7 +544,7 @@ public: m_HierarchicalPathfinder.Update(&m_PassabilityMap, dirtinessGrid); } - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); if (dimensionChange || justDeserialized) Script::ToJSVal(rq, &m_PassabilityMapVal, m_PassabilityMap); else @@ -572,7 +572,7 @@ public: m_TerritoryMap = territoryMap; - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); if (dimensionChange) Script::ToJSVal(rq, &m_TerritoryMapVal, m_TerritoryMap); else @@ -622,7 +622,7 @@ public: void LoadEntityTemplates(const std::vector >& templates) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); m_HasLoadedEntityTemplates = true; @@ -658,7 +658,7 @@ public: if (m_Players.empty()) return; - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); std::stringstream rngStream; rngStream << m_RNG; @@ -704,7 +704,7 @@ public: if (numAis == 0) return; - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); ENSURE(m_CommandsComputed); // deserializing while we're still actively computing would be bad @@ -785,7 +785,7 @@ private: if (m_PlayerMetadata.find(path) == m_PlayerMetadata.end()) { // Load and cache the AI player metadata - Script::ReadJSONFile(ScriptRequest(m_ScriptInterface), path, out); + Script::ReadJSONFile(Script::Request(m_ScriptInterface), path, out); m_PlayerMetadata[path] = JS::Heap(out); return; } @@ -795,7 +795,7 @@ private: void PerformComputation() { // Deserialize the game state, to pass to the AI's HandleMessage - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); { PROFILE3("AI compute read state"); Script::SetProperty(rq, m_GameState, "passabilityMap", m_PassabilityMapVal, true); @@ -812,7 +812,7 @@ private: if (m_HasSharedComponent) { PROFILE3("AI run shared component"); - ScriptFunction::CallVoid(rq, m_SharedAIObj, "onUpdate", m_GameState); + Script::Function::CallVoid(rq, m_SharedAIObj, "onUpdate", m_GameState); } for (size_t i = 0; i < m_Players.size(); ++i) @@ -828,7 +828,7 @@ private: } } - std::shared_ptr m_ScriptInterface; + std::shared_ptr m_ScriptInterface; boost::rand48 m_RNG; u32 m_TurnNum; @@ -895,8 +895,8 @@ public: { serialize.NumberU32_Unbounded("num ais", m_Worker.getPlayerSize()); - // Because the AI worker uses its own ScriptInterface, we can't use the - // ISerializer (which was initialised with the simulation ScriptInterface) + // Because the AI worker uses its own Script::Interface, we can't use the + // ISerializer (which was initialised with the simulation Script::Interface) // directly. So we'll just grab the ISerializer's stream and write to it // with an independent serializer. @@ -943,8 +943,8 @@ public: void RunGamestateInit() override { - const ScriptInterface& scriptInterface = GetSimContext().GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface(); + Script::Request rq(scriptInterface); CmpPtr cmpAIInterface(GetSystemEntity()); ENSURE(cmpAIInterface); @@ -982,8 +982,8 @@ public: { PROFILE("AI setup"); - const ScriptInterface& scriptInterface = GetSimContext().GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface(); + Script::Request rq(scriptInterface); if (m_Worker.getPlayerSize() == 0) return; @@ -1046,8 +1046,8 @@ public: if (!cmpCommandQueue) return; - const ScriptInterface& scriptInterface = GetSimContext().GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue clonedCommandVal(rq.cx); for (size_t i = 0; i < commands.size(); ++i) @@ -1097,8 +1097,8 @@ private: if (!cmpPathfinder) return; - const ScriptInterface& scriptInterface = GetSimContext().GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue classesVal(rq.cx); Script::CreateObject(rq, &classesVal); diff --git a/source/simulation2/components/CCmpCommandQueue.cpp b/source/simulation2/components/CCmpCommandQueue.cpp index 54631abc2b..3d59e151ef 100644 --- a/source/simulation2/components/CCmpCommandQueue.cpp +++ b/source/simulation2/components/CCmpCommandQueue.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -25,7 +25,7 @@ #include "ps/Profiler2.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/helpers/Player.h" #include "simulation2/helpers/SimulationCommand.h" #include "simulation2/system/Component.h" @@ -38,7 +38,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } class CCmpCommandQueue final : public ICmpCommandQueue { @@ -66,7 +66,7 @@ public: void Serialize(ISerializer& serialize) override { - ScriptRequest rq(GetSimContext().GetScriptInterface()); + Script::Request rq(GetSimContext().GetScriptInterface()); serialize.NumberU32_Unbounded("num commands", (u32)m_LocalQueue.size()); for (size_t i = 0; i < m_LocalQueue.size(); ++i) @@ -78,7 +78,7 @@ public: void Deserialize(const CParamNode&, IDeserializer& deserialize) override { - ScriptRequest rq(GetSimContext().GetScriptInterface()); + Script::Request rq(GetSimContext().GetScriptInterface()); u32 numCmds; deserialize.NumberU32_Unbounded("num commands", numCmds); @@ -94,13 +94,13 @@ public: void PushLocalCommand(player_id_t player, JS::HandleValue cmd) override { - ScriptRequest rq(GetSimContext().GetScriptInterface()); + Script::Request rq(GetSimContext().GetScriptInterface()); m_LocalQueue.emplace_back(SimulationCommand(player, rq.cx, cmd)); } void PostNetworkCommand(JS::HandleValue cmd1) override { - ScriptRequest rq(GetSimContext().GetScriptInterface()); + Script::Request rq(GetSimContext().GetScriptInterface()); // TODO: This is a workaround because we need to pass a MutableHandle to StringifyJSON. JS::RootedValue cmd(rq.cx, cmd1.get()); @@ -115,8 +115,8 @@ public: void FlushTurn(const std::vector& commands) override { - const ScriptInterface& scriptInterface = GetSimContext().GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue global(rq.cx, rq.globalValue()); std::vector localCommands; @@ -124,14 +124,14 @@ public: for (size_t i = 0; i < localCommands.size(); ++i) { - bool ok = ScriptFunction::CallVoid(rq, global, "ProcessCommand", localCommands[i].player, localCommands[i].data); + bool ok = Script::Function::CallVoid(rq, global, "ProcessCommand", localCommands[i].player, localCommands[i].data); if (!ok) LOGERROR("Failed to call ProcessCommand() global script function"); } for (size_t i = 0; i < commands.size(); ++i) { - bool ok = ScriptFunction::CallVoid(rq, global, "ProcessCommand", commands[i].player, commands[i].data); + bool ok = Script::Function::CallVoid(rq, global, "ProcessCommand", commands[i].player, commands[i].data); if (!ok) LOGERROR("Failed to call ProcessCommand() global script function"); } diff --git a/source/simulation2/components/CCmpSoundManager.cpp b/source/simulation2/components/CCmpSoundManager.cpp index 698a6d64ab..4d1ad2be70 100644 --- a/source/simulation2/components/CCmpSoundManager.cpp +++ b/source/simulation2/components/CCmpSoundManager.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -21,7 +21,7 @@ #include "lib/path.h" #include "maths/Vector3D.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/components/ICmpOwnership.h" #include "simulation2/components/ICmpPosition.h" #include "simulation2/components/ICmpRangeManager.h" diff --git a/source/simulation2/components/ICmpAIManager.cpp b/source/simulation2/components/ICmpAIManager.cpp index 17820a5252..cf44c37135 100644 --- a/source/simulation2/components/ICmpAIManager.cpp +++ b/source/simulation2/components/ICmpAIManager.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -27,8 +27,8 @@ #include "ps/Filesystem.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/system/InterfaceScripted.h" #include @@ -53,11 +53,11 @@ struct GetAIsHelper { NONCOPYABLE(GetAIsHelper); public: - GetAIsHelper(const ScriptInterface& scriptInterface) : + GetAIsHelper(const Script::Interface& scriptInterface) : m_ScriptInterface(scriptInterface), m_AIs(scriptInterface.GetGeneralJSContext()) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); m_AIs = JS::NewArrayObject(rq.cx, 0); } @@ -69,7 +69,7 @@ public: static Status Callback(const VfsPath& pathname, const CFileInfo&, const uintptr_t cbData) { GetAIsHelper* self = (GetAIsHelper*)cbData; - ScriptRequest rq(self->m_ScriptInterface); + Script::Request rq(self->m_ScriptInterface); // Extract the 3rd component of the path (i.e. the directory after simulation/ai/) std::filesystem::path components = pathname.string(); @@ -92,10 +92,10 @@ public: } JS::PersistentRootedObject m_AIs; - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; }; -JS::Value ICmpAIManager::GetAIs(const ScriptInterface& scriptInterface) +JS::Value ICmpAIManager::GetAIs(const Script::Interface& scriptInterface) { GetAIsHelper helper(scriptInterface); helper.Run(); diff --git a/source/simulation2/components/ICmpAIManager.h b/source/simulation2/components/ICmpAIManager.h index 2cc9feecf0..4915c5000d 100644 --- a/source/simulation2/components/ICmpAIManager.h +++ b/source/simulation2/components/ICmpAIManager.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } class ICmpAIManager : public IComponent { @@ -57,7 +57,7 @@ public: * Returns a vector of {"id":"value-for-AddPlayer", "name":"Human readable name"} * objects, based on all the available AI scripts. */ - static JS::Value GetAIs(const ScriptInterface& scriptInterface); + static JS::Value GetAIs(const Script::Interface& scriptInterface); DECLARE_INTERFACE_TYPE(AIManager) }; diff --git a/source/simulation2/components/ICmpFootprint.cpp b/source/simulation2/components/ICmpFootprint.cpp index d264eccc15..ca7e029586 100644 --- a/source/simulation2/components/ICmpFootprint.cpp +++ b/source/simulation2/components/ICmpFootprint.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -20,8 +20,8 @@ #include "ICmpFootprint.h" #include "maths/FixedVector3D.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include "simulation2/system/InterfaceScripted.h" #include @@ -36,7 +36,7 @@ JS::Value ICmpFootprint::GetShape_wrapper() const entity_pos_t size0, size1, height; GetShape(shape, size0, size1, height); - ScriptRequest rq(GetSimContext().GetScriptInterface()); + Script::Request rq(GetSimContext().GetScriptInterface()); JS::RootedObject obj(rq.cx, JS_NewPlainObject(rq.cx)); if (!obj) diff --git a/source/simulation2/components/tests/test_CinemaManager.h b/source/simulation2/components/tests/test_CinemaManager.h index 8406fc599c..88d5816cf5 100644 --- a/source/simulation2/components/tests/test_CinemaManager.h +++ b/source/simulation2/components/tests/test_CinemaManager.h @@ -22,7 +22,7 @@ #include "maths/NUSpline.h" #include "ps/CStr.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpCinemaManager.h" #include "simulation2/helpers/CinemaPath.h" diff --git a/source/simulation2/components/tests/test_CommandQueue.h b/source/simulation2/components/tests/test_CommandQueue.h index 2cc640b54d..191c4e6e33 100644 --- a/source/simulation2/components/tests/test_CommandQueue.h +++ b/source/simulation2/components/tests/test_CommandQueue.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,8 +18,8 @@ #include "lib/self_test.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/components/ICmpCommandQueue.h" #include "simulation2/helpers/SimulationCommand.h" #include "simulation2/system/Component.h" @@ -40,7 +40,7 @@ public: { CXeromycesEngine xeromycesEngine; ComponentTestHelper test(*g_ScriptContext); - ScriptRequest rq(test.GetScriptInterface()); + Script::Request rq(test.GetScriptInterface()); std::vector empty; diff --git a/source/simulation2/components/tests/test_ObstructionManager.h b/source/simulation2/components/tests/test_ObstructionManager.h index 5d719f759d..87767c6959 100644 --- a/source/simulation2/components/tests/test_ObstructionManager.h +++ b/source/simulation2/components/tests/test_ObstructionManager.h @@ -20,7 +20,7 @@ #include "maths/Fixed.h" #include "maths/FixedVector2D.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/components/ICmpObstruction.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/helpers/Position.h" diff --git a/source/simulation2/components/tests/test_Pathfinder.h b/source/simulation2/components/tests/test_Pathfinder.h index fe1b6b74f8..586c8beaf9 100644 --- a/source/simulation2/components/tests/test_Pathfinder.h +++ b/source/simulation2/components/tests/test_Pathfinder.h @@ -32,9 +32,9 @@ #include "ps/Filesystem.h" #include "ps/Loader.h" #include "ps/XML/Xeromyces.h" +#include "scriptinterface/Interface.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpObstructionManager.h" #include "simulation2/components/ICmpPathfinder.h" @@ -164,7 +164,7 @@ public: sim2.ResetState(); JS::RootedValue attribs(sim2.GetScriptInterface().GetGeneralJSContext()); - Script::CreateObject(ScriptRequest(sim2.GetScriptInterface()), &attribs); + Script::CreateObject(Script::Request(sim2.GetScriptInterface()), &attribs); sim2.SetInitAttributes(attribs); std::unique_ptr mapReader = std::make_unique(); @@ -281,7 +281,7 @@ public: sim2.ResetState(); JS::RootedValue attribs(sim2.GetScriptInterface().GetGeneralJSContext()); - Script::CreateObject(ScriptRequest(sim2.GetScriptInterface()), &attribs); + Script::CreateObject(Script::Request(sim2.GetScriptInterface()), &attribs); sim2.SetInitAttributes(attribs); std::unique_ptr mapReader = std::make_unique(); @@ -341,7 +341,7 @@ public: sim2.ResetState(); JS::RootedValue attribs(sim2.GetScriptInterface().GetGeneralJSContext()); - Script::CreateObject(ScriptRequest(sim2.GetScriptInterface()), &attribs); + Script::CreateObject(Script::Request(sim2.GetScriptInterface()), &attribs); sim2.SetInitAttributes(attribs); std::unique_ptr mapReader = std::make_unique(); diff --git a/source/simulation2/components/tests/test_Position.h b/source/simulation2/components/tests/test_Position.h index 3c5ba2b52a..f54efd99f8 100644 --- a/source/simulation2/components/tests/test_Position.h +++ b/source/simulation2/components/tests/test_Position.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,7 +22,7 @@ #include "maths/Matrix3D.h" #include "maths/Vector3D.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpPosition.h" #include "simulation2/components/ICmpWaterManager.h" diff --git a/source/simulation2/components/tests/test_RangeManager.h b/source/simulation2/components/tests/test_RangeManager.h index 7fc89a1875..30fc69720d 100644 --- a/source/simulation2/components/tests/test_RangeManager.h +++ b/source/simulation2/components/tests/test_RangeManager.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,7 +23,7 @@ #include "maths/Matrix3D.h" #include "ps/CStr.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpObstruction.h" #include "simulation2/components/ICmpObstructionManager.h" diff --git a/source/simulation2/components/tests/test_TerritoryManager.h b/source/simulation2/components/tests/test_TerritoryManager.h index e642621728..42e9c81ad8 100644 --- a/source/simulation2/components/tests/test_TerritoryManager.h +++ b/source/simulation2/components/tests/test_TerritoryManager.h @@ -31,7 +31,7 @@ #include "ps/CStr.h" #include "ps/Filesystem.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpObstruction.h" #include "simulation2/components/ICmpObstructionManager.h" diff --git a/source/simulation2/components/tests/test_scripts.h b/source/simulation2/components/tests/test_scripts.h index 4f469f48c8..de1076ddb2 100644 --- a/source/simulation2/components/tests/test_scripts.h +++ b/source/simulation2/components/tests/test_scripts.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -27,9 +27,9 @@ #include "ps/Filesystem.h" #include "ps/XML/Xeromyces.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/serialization/StdDeserializer.h" #include "simulation2/serialization/StdSerializer.h" #include "simulation2/system/Component.h" @@ -57,7 +57,7 @@ public: g_VFS.reset(); } - static void load_script(const ScriptInterface& scriptInterface, const VfsPath& pathname) + static void load_script(const Script::Interface& scriptInterface, const VfsPath& pathname) { CVFSFile file; TS_ASSERT_EQUALS(file.Load(g_VFS, pathname), PSRETURN_OK); @@ -65,23 +65,23 @@ public: TSM_ASSERT(L"Running script "+pathname.string(), scriptInterface.LoadScript(pathname, content)); } - static void Script_LoadComponentScript(const ScriptInterface& scriptInterface, const VfsPath& pathname) + static void Script_LoadComponentScript(const Script::Interface& scriptInterface, const VfsPath& pathname) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); CComponentManager* componentManager = scriptInterface.ObjectFromCBData(rq); TS_ASSERT(componentManager->LoadScript(VfsPath(L"simulation/components") / pathname)); } - static void Script_LoadHelperScript(const ScriptInterface& scriptInterface, const VfsPath& pathname) + static void Script_LoadHelperScript(const Script::Interface& scriptInterface, const VfsPath& pathname) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); CComponentManager* componentManager = scriptInterface.ObjectFromCBData(rq); TS_ASSERT(componentManager->LoadScript(VfsPath(L"simulation/helpers") / pathname)); } - static JS::Value Script_SerializationRoundTrip(const ScriptInterface& scriptInterface, JS::HandleValue value) + static JS::Value Script_SerializationRoundTrip(const Script::Interface& scriptInterface, JS::HandleValue value) { - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValue val(rq.cx); val = value; @@ -110,8 +110,8 @@ public: CComponentManager componentManager(context, *g_ScriptContext, true); ScriptTestSetup(componentManager.GetScriptInterface()); - ScriptRequest rq(componentManager.GetScriptInterface()); - ScriptFunction::Register(rq, "SerializationRoundTrip"); + Script::Request rq(componentManager.GetScriptInterface()); + Script::Function::Register(rq, "SerializationRoundTrip"); load_script(componentManager.GetScriptInterface(), path); } @@ -139,10 +139,10 @@ public: ScriptTestSetup(componentManager.GetScriptInterface()); - ScriptRequest rq(componentManager.GetScriptInterface()); - ScriptFunction::Register(rq, "LoadComponentScript"); - ScriptFunction::Register(rq, "LoadHelperScript"); - ScriptFunction::Register(rq, "SerializationRoundTrip"); + Script::Request rq(componentManager.GetScriptInterface()); + Script::Function::Register(rq, "LoadComponentScript"); + Script::Function::Register(rq, "LoadHelperScript"); + Script::Function::Register(rq, "SerializationRoundTrip"); componentManager.LoadComponentTypes(); diff --git a/source/simulation2/docs/SimulationDocs.h b/source/simulation2/docs/SimulationDocs.h index 49c061d06e..2c3dbf5540 100644 --- a/source/simulation2/docs/SimulationDocs.h +++ b/source/simulation2/docs/SimulationDocs.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -120,7 +120,7 @@ which does some extra conversions or checks or whatever. There's a small limit to the number of arguments that are currently supported - if you need more, first try to save yourself some pain by using fewer arguments, otherwise you'll need to add a new -macro into simulation2/system/InterfaceScripted.h and increase @ref SCRIPT_INTERFACE_MAX_ARGS in scriptinterface/ScriptInterface.h. +macro into simulation2/system/InterfaceScripted.h and increase @ref SCRIPT_INTERFACE_MAX_ARGS in scriptinterface/Interface.h. @@ -138,7 +138,7 @@ defined as long as the linker finds them). To convert from a C++ type @c T to a JS::Value, define: @code -template<> void ScriptInterface::ToJSVal(JSContext* cx, JS::MutableHandleValue ret, const T& val) +template<> void Script::Interface::ToJSVal(JSContext* cx, JS::MutableHandleValue ret, const T& val) { ... } @@ -152,7 +152,7 @@ Be careful about JS garbage collection (don't let it collect the objects you're To convert from a JS::Value to a C++ type @c T, define: @code -template<> bool ScriptInterface::FromJSVal(JSContext* cx, JS::HandleValue v, T& out) +template<> bool Script::Interface::FromJSVal(JSContext* cx, JS::HandleValue v, T& out) { ... } @@ -505,7 +505,7 @@ But for now everything is put in there.) Now you have to add C++/JS conversions into MessageTypeConversions.cpp, so scripts can send and receive messages: @code -JS::Value CMessageExample::ToJSVal(const ScriptInterface& scriptInterface) const +JS::Value CMessageExample::ToJSVal(const Script::Interface& scriptInterface) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(x); @@ -513,7 +513,7 @@ JS::Value CMessageExample::ToJSVal(const ScriptInterface& scriptInterface) const return JS::ObjectValue(*obj); } -CMessage* CMessageExample::FromJSVal(const ScriptInterface& scriptInterface, JS::HandleValue val) +CMessage* CMessageExample::FromJSVal(const Script::Interface& scriptInterface, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(int, x); @@ -528,12 +528,12 @@ with a set of scalar fields.) If you don't want to support scripts sending/receiving the message, you can implement stub functions instead: @code -JS::Value CMessageExample::ToJSVal(const ScriptInterface&) const +JS::Value CMessageExample::ToJSVal(const Script::Interface&) const { return JS::UndefinedValue(); } -CMessage* CMessageExample::FromJSVal(const ScriptInterface&, JS::HandleValue) +CMessage* CMessageExample::FromJSVal(const Script::Interface&, JS::HandleValue) { return NULL; } diff --git a/source/simulation2/scripting/EngineScriptConversions.cpp b/source/simulation2/scripting/EngineScriptConversions.cpp index 5ab171264d..177fea0ca6 100644 --- a/source/simulation2/scripting/EngineScriptConversions.cpp +++ b/source/simulation2/scripting/EngineScriptConversions.cpp @@ -27,10 +27,10 @@ #include "ps/CLogger.h" #include "ps/CStr.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptExceptions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Exceptions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/helpers/CinemaPath.h" #include "simulation2/helpers/Grid.h" #include "simulation2/system/Component.h" @@ -51,9 +51,9 @@ #include #define FAIL(msg) STMT(LOGERROR(msg); return false) -#define FAIL_VOID(msg) STMT(ScriptException::Raise(rq, msg); return) +#define FAIL_VOID(msg) STMT(Script::Exception::Raise(rq, msg); return) -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, +template<> void Script::ToJSVal(const Script::Request&, JS::MutableHandleValue ret, IComponent* const& val) { if (val == NULL) @@ -74,12 +74,12 @@ template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHa ret.set(instance); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, CParamNode const& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, CParamNode const& val) { val.ToJSVal(rq, true, ret); } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CParamNode* const& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CParamNode* const& val) { if (val) ToJSVal(rq, ret, *val); @@ -87,7 +87,7 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS: ret.setUndefined(); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CColor& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CColor& out) { if (!v.isObject()) FAIL("CColor has to be an object"); @@ -110,7 +110,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleVa return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, CColor const& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, CColor const& val) { Script::CreateObject( rq, @@ -121,7 +121,7 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHan "a", val.a); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, fixed& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, fixed& out) { double ret; if (!JS::ToNumber(rq.cx, v, &ret)) @@ -132,12 +132,12 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleVal return true; } -template<> void Script::ToJSVal(const ScriptRequest&, JS::MutableHandleValue ret, const fixed& val) +template<> void Script::ToJSVal(const Script::Request&, JS::MutableHandleValue ret, const fixed& val) { ret.set(JS::NumberValue(val.ToDouble())); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CFixedVector3D& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CFixedVector3D& out) { if (!v.isObject()) return false; // TODO: report type error @@ -157,11 +157,11 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS:: return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CFixedVector3D& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CFixedVector3D& val) { JS::RootedObject global(rq.cx, rq.glob); JS::RootedValue valueVector3D(rq.cx); - if (!ScriptInterface::GetGlobalProperty(rq, "Vector3D", &valueVector3D)) + if (!Script::Interface::GetGlobalProperty(rq, "Vector3D", &valueVector3D)) FAIL_VOID("Failed to get Vector3D constructor"); JS::RootedValueArray<3> args(rq.cx); @@ -176,7 +176,7 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::Mu ret.setObject(*objVec); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CFixedVector2D& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CFixedVector2D& out) { if (!v.isObject()) return false; // TODO: report type error @@ -193,11 +193,11 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS:: return true; } -template<> void Script::ToJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret, const CFixedVector2D& val) +template<> void Script::ToJSVal(const Script::Request& rq, JS::MutableHandleValue ret, const CFixedVector2D& val) { JS::RootedObject global(rq.cx, rq.glob); JS::RootedValue valueVector2D(rq.cx); - if (!ScriptInterface::GetGlobalProperty(rq, "Vector2D", &valueVector2D)) + if (!Script::Interface::GetGlobalProperty(rq, "Vector2D", &valueVector2D)) FAIL_VOID("Failed to get Vector2D constructor"); JS::RootedValueArray<2> args(rq.cx); @@ -211,7 +211,7 @@ template<> void Script::ToJSVal(const ScriptRequest& rq, JS::Mu ret.setObject(*objVec); } -template<> bool Script::FromJSVal>(const ScriptRequest& rq, JS::HandleValue v, std::optional& out) +template<> bool Script::FromJSVal>(const Script::Request& rq, JS::HandleValue v, std::optional& out) { if (v.isNullOrUndefined()) { @@ -227,7 +227,7 @@ template<> bool Script::FromJSVal>(const ScriptReq return true; } -template<> void Script::ToJSVal>(const ScriptRequest& rq, JS::MutableHandleValue ret, const std::optional& val) +template<> void Script::ToJSVal>(const Script::Request& rq, JS::MutableHandleValue ret, const std::optional& val) { if (!val.has_value()) ret.setNull(); @@ -235,7 +235,7 @@ template<> void Script::ToJSVal>(const ScriptReque ToJSVal(rq, ret, val.value()); } -template<> void Script::ToJSVal >(const ScriptRequest& rq, JS::MutableHandleValue ret, const Grid& val) +template<> void Script::ToJSVal >(const Script::Request& rq, JS::MutableHandleValue ret, const Grid& val) { u32 length = (u32)(val.m_W * val.m_H); u32 nbytes = (u32)(length * sizeof(u8)); @@ -256,7 +256,7 @@ template<> void Script::ToJSVal >(const ScriptRequest& rq, JS::Mutable "data", data); } -template<> void Script::ToJSVal >(const ScriptRequest& rq, JS::MutableHandleValue ret, const Grid& val) +template<> void Script::ToJSVal >(const Script::Request& rq, JS::MutableHandleValue ret, const Grid& val) { u32 length = (u32)(val.m_W * val.m_H); u32 nbytes = (u32)(length * sizeof(u16)); @@ -277,7 +277,7 @@ template<> void Script::ToJSVal >(const ScriptRequest& rq, JS::Mutabl "data", data); } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, TNSpline& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, TNSpline& out) { if (!v.isObject()) FAIL("Argument must be an object"); @@ -314,7 +314,7 @@ template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::Handle return true; } -template<> bool Script::FromJSVal(const ScriptRequest& rq, JS::HandleValue v, CCinemaPath& out) +template<> bool Script::FromJSVal(const Script::Request& rq, JS::HandleValue v, CCinemaPath& out) { if (!v.isObject()) FAIL("Argument must be an object"); diff --git a/source/simulation2/scripting/JSInterface_Simulation.cpp b/source/simulation2/scripting/JSInterface_Simulation.cpp index 2eacc89fd9..dac73f3e73 100644 --- a/source/simulation2/scripting/JSInterface_Simulation.cpp +++ b/source/simulation2/scripting/JSInterface_Simulation.cpp @@ -32,7 +32,7 @@ #include "ps/Pyrogenesis.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpAIManager.h" @@ -57,11 +57,11 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } namespace JSI_Simulation { -JS::Value GuiInterfaceCall(const ScriptInterface& scriptInterface, const std::wstring& name, JS::HandleValue data) +JS::Value GuiInterfaceCall(const Script::Interface& scriptInterface, const std::wstring& name, JS::HandleValue data) { if (!g_Game) return JS::UndefinedValue(); @@ -73,7 +73,7 @@ JS::Value GuiInterfaceCall(const ScriptInterface& scriptInterface, const std::ws if (!cmpGuiInterface) return JS::UndefinedValue(); - ScriptRequest rqSim(sim->GetScriptInterface()); + Script::Request rqSim(sim->GetScriptInterface()); JS::RootedValue arg(rqSim.cx, Script::CloneValueFromOtherCompartment(sim->GetScriptInterface(), scriptInterface, data)); JS::RootedValue ret(rqSim.cx); cmpGuiInterface->ScriptCall(g_Game->GetViewedPlayerID(), name, arg, &ret); @@ -81,7 +81,7 @@ JS::Value GuiInterfaceCall(const ScriptInterface& scriptInterface, const std::ws return Script::CloneValueFromOtherCompartment(scriptInterface, sim->GetScriptInterface(), ret); } -void PostNetworkCommand(const ScriptInterface& scriptInterface, JS::HandleValue cmd) +void PostNetworkCommand(const Script::Interface& scriptInterface, JS::HandleValue cmd) { if (!g_Game) return; @@ -93,7 +93,7 @@ void PostNetworkCommand(const ScriptInterface& scriptInterface, JS::HandleValue if (!cmpCommandQueue) return; - ScriptRequest rqSim(sim->GetScriptInterface()); + Script::Request rqSim(sim->GetScriptInterface()); JS::RootedValue cmd2(rqSim.cx, Script::CloneValueFromOtherCompartment(sim->GetScriptInterface(), scriptInterface, cmd)); cmpCommandQueue->PostNetworkCommand(cmd2); @@ -139,7 +139,7 @@ std::vector GetEntitiesWithStaticObstructionOnScreen() return EntitySelection::GetEntitiesWithComponentInRect(*g_Game->GetSimulation2(), IID_Obstruction, *g_Game->GetView()->GetCamera(), 0, 0, g_xres, g_yres); } -JS::Value GetEdgesOfStaticObstructionsOnScreenNearTo(const ScriptInterface& scriptInterface, entity_pos_t x, entity_pos_t z) +JS::Value GetEdgesOfStaticObstructionsOnScreenNearTo(const Script::Interface& scriptInterface, entity_pos_t x, entity_pos_t z) { if (!g_Game) return JS::UndefinedValue(); @@ -147,7 +147,7 @@ JS::Value GetEdgesOfStaticObstructionsOnScreenNearTo(const ScriptInterface& scri CSimulation2* sim = g_Game->GetSimulation2(); ENSURE(sim); - ScriptRequest rq(scriptInterface); + Script::Request rq(scriptInterface); JS::RootedValueVector edgeList{rq.cx}; const float distanceThreshold{g_ConfigDB.Get("gui.session.snaptoedgesdistancethreshold", 10.0f)}; @@ -212,7 +212,7 @@ std::vector PickSimilarPlayerEntities(const std::string& templateNa return EntitySelection::PickSimilarEntities(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), templateName, g_Game->GetViewedPlayerID(), includeOffScreen, matchRank, false, allowFoundations); } -JS::Value GetAIs(const ScriptInterface& scriptInterface) +JS::Value GetAIs(const Script::Interface& scriptInterface) { return ICmpAIManager::GetAIs(scriptInterface); } @@ -222,19 +222,19 @@ void SetBoundingBoxDebugOverlay(bool enabled) ICmpSelectable::ms_EnableDebugOverlays = enabled; } -void RegisterScriptFunctions(const ScriptRequest& rq) +void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&GuiInterfaceCall>(rq, "GuiInterfaceCall"); - ScriptFunction::Register<&PostNetworkCommand>(rq, "PostNetworkCommand"); - ScriptFunction::Register<&DumpSimState>(rq, "DumpSimState"); - ScriptFunction::Register<&GetAIs>(rq, "GetAIs"); - ScriptFunction::Register<&PickEntityAtPoint>(rq, "PickEntityAtPoint"); - ScriptFunction::Register<&PickPlayerEntitiesInRect>(rq, "PickPlayerEntitiesInRect"); - ScriptFunction::Register<&PickPlayerEntitiesOnScreen>(rq, "PickPlayerEntitiesOnScreen"); - ScriptFunction::Register<&PickNonGaiaEntitiesOnScreen>(rq, "PickNonGaiaEntitiesOnScreen"); - ScriptFunction::Register<&GetEntitiesWithStaticObstructionOnScreen>(rq, "GetEntitiesWithStaticObstructionOnScreen"); - ScriptFunction::Register<&GetEdgesOfStaticObstructionsOnScreenNearTo>(rq, "GetEdgesOfStaticObstructionsOnScreenNearTo"); - ScriptFunction::Register<&PickSimilarPlayerEntities>(rq, "PickSimilarPlayerEntities"); - ScriptFunction::Register<&SetBoundingBoxDebugOverlay>(rq, "SetBoundingBoxDebugOverlay"); + Script::Function::Register<&GuiInterfaceCall>(rq, "GuiInterfaceCall"); + Script::Function::Register<&PostNetworkCommand>(rq, "PostNetworkCommand"); + Script::Function::Register<&DumpSimState>(rq, "DumpSimState"); + Script::Function::Register<&GetAIs>(rq, "GetAIs"); + Script::Function::Register<&PickEntityAtPoint>(rq, "PickEntityAtPoint"); + Script::Function::Register<&PickPlayerEntitiesInRect>(rq, "PickPlayerEntitiesInRect"); + Script::Function::Register<&PickPlayerEntitiesOnScreen>(rq, "PickPlayerEntitiesOnScreen"); + Script::Function::Register<&PickNonGaiaEntitiesOnScreen>(rq, "PickNonGaiaEntitiesOnScreen"); + Script::Function::Register<&GetEntitiesWithStaticObstructionOnScreen>(rq, "GetEntitiesWithStaticObstructionOnScreen"); + Script::Function::Register<&GetEdgesOfStaticObstructionsOnScreenNearTo>(rq, "GetEdgesOfStaticObstructionsOnScreenNearTo"); + Script::Function::Register<&PickSimilarPlayerEntities>(rq, "PickSimilarPlayerEntities"); + Script::Function::Register<&SetBoundingBoxDebugOverlay>(rq, "SetBoundingBoxDebugOverlay"); } } diff --git a/source/simulation2/scripting/JSInterface_Simulation.h b/source/simulation2/scripting/JSInterface_Simulation.h index 66f31b4e18..850a4e6a7c 100644 --- a/source/simulation2/scripting/JSInterface_Simulation.h +++ b/source/simulation2/scripting/JSInterface_Simulation.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2020 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,11 +18,11 @@ #ifndef INCLUDED_JSI_SIMULATION #define INCLUDED_JSI_SIMULATION -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Simulation { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_JSI_SIMULATION diff --git a/source/simulation2/scripting/MessageTypeConversions.cpp b/source/simulation2/scripting/MessageTypeConversions.cpp index d40dd0242a..63649a4fbe 100644 --- a/source/simulation2/scripting/MessageTypeConversions.cpp +++ b/source/simulation2/scripting/MessageTypeConversions.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -16,12 +16,12 @@ */ #include "precompiled.h" -#include "scriptinterface/ScriptConversions.h" +#include "scriptinterface/Conversions.h" #include "maths/Fixed.h" #include "ps/CLogger.h" #include "ps/CStr.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/MessageTypes.h" #include "simulation2/helpers/Player.h" #include "simulation2/helpers/Position.h" @@ -68,7 +68,7 @@ return NULL; \ } -JS::Value CMessage::ToJSValCached(const ScriptRequest& rq) const +JS::Value CMessage::ToJSValCached(const Script::Request& rq) const { if (!m_Cached) m_Cached.reset(new JS::PersistentRootedValue(rq.cx, ToJSVal(rq))); @@ -78,13 +78,13 @@ JS::Value CMessage::ToJSValCached(const ScriptRequest& rq) const //////////////////////////////// -JS::Value CMessageTurnStart::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageTurnStart::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageTurnStart::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageTurnStart::FromJSVal(const Script::Request&, JS::HandleValue) { return new CMessageTurnStart(); } @@ -92,13 +92,13 @@ CMessage* CMessageTurnStart::FromJSVal(const ScriptRequest&, JS::HandleValue) //////////////////////////////// #define MESSAGE_1(name, t0, a0) \ - JS::Value CMessage##name::ToJSVal(const ScriptRequest& rq) const \ + JS::Value CMessage##name::ToJSVal(const Script::Request& rq) const \ { \ TOJSVAL_SETUP(); \ SET_MSG_PROPERTY(a0); \ return JS::ObjectValue(*obj); \ } \ - CMessage* CMessage##name::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) \ + CMessage* CMessage##name::FromJSVal(const Script::Request& rq, JS::HandleValue val) \ { \ FROMJSVAL_SETUP(); \ GET_MSG_PROPERTY(t0, a0); \ @@ -112,7 +112,7 @@ MESSAGE_1(Update_Final, fixed, turnLength) //////////////////////////////// -JS::Value CMessageInterpolate::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageInterpolate::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(deltaSimTime); @@ -121,7 +121,7 @@ JS::Value CMessageInterpolate::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageInterpolate::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageInterpolate::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(float, deltaSimTime); @@ -132,13 +132,13 @@ CMessage* CMessageInterpolate::FromJSVal(const ScriptRequest& rq, JS::HandleValu //////////////////////////////// -JS::Value CMessageRenderSubmit::ToJSVal(const ScriptRequest&) const +JS::Value CMessageRenderSubmit::ToJSVal(const Script::Request&) const { LOGWARNING("CMessageRenderSubmit::ToJSVal not implemented"); return JS::UndefinedValue(); } -CMessage* CMessageRenderSubmit::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageRenderSubmit::FromJSVal(const Script::Request&, JS::HandleValue) { LOGWARNING("CMessageRenderSubmit::FromJSVal not implemented"); return NULL; @@ -146,13 +146,13 @@ CMessage* CMessageRenderSubmit::FromJSVal(const ScriptRequest&, JS::HandleValue) //////////////////////////////// -JS::Value CMessageProgressiveLoad::ToJSVal(const ScriptRequest&) const +JS::Value CMessageProgressiveLoad::ToJSVal(const Script::Request&) const { LOGWARNING("CMessageProgressiveLoad::ToJSVal not implemented"); return JS::UndefinedValue(); } -CMessage* CMessageProgressiveLoad::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageProgressiveLoad::FromJSVal(const Script::Request&, JS::HandleValue) { LOGWARNING("CMessageProgressiveLoad::FromJSVal not implemented"); return NULL; @@ -160,13 +160,13 @@ CMessage* CMessageProgressiveLoad::FromJSVal(const ScriptRequest&, JS::HandleVal //////////////////////////////// -JS::Value CMessageDeserialized::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageDeserialized::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageDeserialized::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageDeserialized::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); return new CMessageDeserialized(); @@ -174,14 +174,14 @@ CMessage* CMessageDeserialized::FromJSVal(const ScriptRequest& rq, JS::HandleVal //////////////////////////////// -JS::Value CMessageCreate::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageCreate::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); return JS::ObjectValue(*obj); } -CMessage* CMessageCreate::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageCreate::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); @@ -190,14 +190,14 @@ CMessage* CMessageCreate::FromJSVal(const ScriptRequest& rq, JS::HandleValue val //////////////////////////////// -JS::Value CMessageDestroy::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageDestroy::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); return JS::ObjectValue(*obj); } -CMessage* CMessageDestroy::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageDestroy::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); @@ -206,7 +206,7 @@ CMessage* CMessageDestroy::FromJSVal(const ScriptRequest& rq, JS::HandleValue va //////////////////////////////// -JS::Value CMessageOwnershipChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageOwnershipChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); @@ -215,7 +215,7 @@ JS::Value CMessageOwnershipChanged::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageOwnershipChanged::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageOwnershipChanged::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); @@ -226,7 +226,7 @@ CMessage* CMessageOwnershipChanged::FromJSVal(const ScriptRequest& rq, JS::Handl //////////////////////////////// -JS::Value CMessagePositionChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessagePositionChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); @@ -237,7 +237,7 @@ JS::Value CMessagePositionChanged::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessagePositionChanged::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessagePositionChanged::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); @@ -250,13 +250,13 @@ CMessage* CMessagePositionChanged::FromJSVal(const ScriptRequest& rq, JS::Handle //////////////////////////////// -JS::Value CMessageInterpolatedPositionChanged::ToJSVal(const ScriptRequest&) const +JS::Value CMessageInterpolatedPositionChanged::ToJSVal(const Script::Request&) const { LOGWARNING("CMessageInterpolatedPositionChanged::ToJSVal not implemented"); return JS::UndefinedValue(); } -CMessage* CMessageInterpolatedPositionChanged::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageInterpolatedPositionChanged::FromJSVal(const Script::Request&, JS::HandleValue) { LOGWARNING("CMessageInterpolatedPositionChanged::FromJSVal not implemented"); return NULL; @@ -268,7 +268,7 @@ const std::array CMessage "likelySuccess", "likelyFailure", "obstructed", "veryObstructed" } }; -JS::Value CMessageMotionUpdate::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageMotionUpdate::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); JS::RootedValue prop(rq.cx); @@ -279,7 +279,7 @@ JS::Value CMessageMotionUpdate::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageMotionUpdate::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageMotionUpdate::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(std::wstring, updateString); @@ -299,7 +299,7 @@ CMessage* CMessageMotionUpdate::FromJSVal(const ScriptRequest& rq, JS::HandleVal //////////////////////////////// -JS::Value CMessageTerrainChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageTerrainChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(i0); @@ -309,7 +309,7 @@ JS::Value CMessageTerrainChanged::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageTerrainChanged::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageTerrainChanged::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(int32_t, i0); @@ -321,7 +321,7 @@ CMessage* CMessageTerrainChanged::FromJSVal(const ScriptRequest& rq, JS::HandleV //////////////////////////////// -JS::Value CMessageVisibilityChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageVisibilityChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(player); @@ -331,7 +331,7 @@ JS::Value CMessageVisibilityChanged::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageVisibilityChanged::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageVisibilityChanged::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, player); @@ -343,59 +343,59 @@ CMessage* CMessageVisibilityChanged::FromJSVal(const ScriptRequest& rq, JS::Hand //////////////////////////////// -JS::Value CMessageWaterChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageWaterChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageWaterChanged::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageWaterChanged::FromJSVal(const Script::Request&, JS::HandleValue) { return new CMessageWaterChanged(); } //////////////////////////////// -JS::Value CMessageMovementObstructionChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageMovementObstructionChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageMovementObstructionChanged::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageMovementObstructionChanged::FromJSVal(const Script::Request&, JS::HandleValue) { return new CMessageMovementObstructionChanged(); } //////////////////////////////// -JS::Value CMessageObstructionMapShapeChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageObstructionMapShapeChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageObstructionMapShapeChanged::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageObstructionMapShapeChanged::FromJSVal(const Script::Request&, JS::HandleValue) { return new CMessageObstructionMapShapeChanged(); } //////////////////////////////// -JS::Value CMessageTerritoriesChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageTerritoriesChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageTerritoriesChanged::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageTerritoriesChanged::FromJSVal(const Script::Request&, JS::HandleValue) { return new CMessageTerritoriesChanged(); } //////////////////////////////// -JS::Value CMessageRangeUpdate::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageRangeUpdate::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(tag); @@ -404,7 +404,7 @@ JS::Value CMessageRangeUpdate::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageRangeUpdate::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageRangeUpdate::FromJSVal(const Script::Request&, JS::HandleValue) { LOGWARNING("CMessageRangeUpdate::FromJSVal not implemented"); return NULL; @@ -412,13 +412,13 @@ CMessage* CMessageRangeUpdate::FromJSVal(const ScriptRequest&, JS::HandleValue) //////////////////////////////// -JS::Value CMessagePathResult::ToJSVal(const ScriptRequest&) const +JS::Value CMessagePathResult::ToJSVal(const Script::Request&) const { LOGWARNING("CMessagePathResult::ToJSVal not implemented"); return JS::UndefinedValue(); } -CMessage* CMessagePathResult::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessagePathResult::FromJSVal(const Script::Request&, JS::HandleValue) { LOGWARNING("CMessagePathResult::FromJSVal not implemented"); return NULL; @@ -426,7 +426,7 @@ CMessage* CMessagePathResult::FromJSVal(const ScriptRequest&, JS::HandleValue) //////////////////////////////// -JS::Value CMessageValueModification::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageValueModification::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entities); @@ -435,7 +435,7 @@ JS::Value CMessageValueModification::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageValueModification::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageValueModification::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(std::vector, entities); @@ -446,7 +446,7 @@ CMessage* CMessageValueModification::FromJSVal(const ScriptRequest& rq, JS::Hand //////////////////////////////// -JS::Value CMessageTemplateModification::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageTemplateModification::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(player); @@ -455,7 +455,7 @@ JS::Value CMessageTemplateModification::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageTemplateModification::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageTemplateModification::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, player); @@ -466,7 +466,7 @@ CMessage* CMessageTemplateModification::FromJSVal(const ScriptRequest& rq, JS::H //////////////////////////////// -JS::Value CMessageVisionRangeChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageVisionRangeChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); @@ -475,7 +475,7 @@ JS::Value CMessageVisionRangeChanged::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageVisionRangeChanged::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageVisionRangeChanged::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); @@ -484,7 +484,7 @@ CMessage* CMessageVisionRangeChanged::FromJSVal(const ScriptRequest& rq, JS::Han return new CMessageVisionRangeChanged(entity, oldRange, newRange); } -JS::Value CMessageVisionSharingChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageVisionSharingChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(entity); @@ -493,7 +493,7 @@ JS::Value CMessageVisionSharingChanged::ToJSVal(const ScriptRequest& rq) const return JS::ObjectValue(*obj); } -CMessage* CMessageVisionSharingChanged::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageVisionSharingChanged::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(entity_id_t, entity); @@ -504,27 +504,27 @@ CMessage* CMessageVisionSharingChanged::FromJSVal(const ScriptRequest& rq, JS::H //////////////////////////////// -JS::Value CMessageMinimapPing::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageMinimapPing::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageMinimapPing::FromJSVal(const ScriptRequest&, JS::HandleValue) +CMessage* CMessageMinimapPing::FromJSVal(const Script::Request&, JS::HandleValue) { return new CMessageMinimapPing(); } //////////////////////////////// -JS::Value CMessageCinemaPathEnded::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageCinemaPathEnded::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(name); return JS::ObjectValue(*obj); } -CMessage* CMessageCinemaPathEnded::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageCinemaPathEnded::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(CStrW, name); @@ -533,13 +533,13 @@ CMessage* CMessageCinemaPathEnded::FromJSVal(const ScriptRequest& rq, JS::Handle //////////////////////////////// -JS::Value CMessageCinemaQueueEnded::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessageCinemaQueueEnded::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); return JS::ObjectValue(*obj); } -CMessage* CMessageCinemaQueueEnded::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageCinemaQueueEnded::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); return new CMessageCinemaQueueEnded(); @@ -547,14 +547,14 @@ CMessage* CMessageCinemaQueueEnded::FromJSVal(const ScriptRequest& rq, JS::Handl //////////////////////////////// -JS::Value CMessagePlayerColorChanged::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessagePlayerColorChanged::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(player); return JS::ObjectValue(*obj); } -CMessage* CMessagePlayerColorChanged::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessagePlayerColorChanged::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, player); @@ -563,14 +563,14 @@ CMessage* CMessagePlayerColorChanged::FromJSVal(const ScriptRequest& rq, JS::Han //////////////////////////////// -JS::Value CMessagePlayerWon::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessagePlayerWon::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(playerId); return JS::ObjectValue(*obj); } -CMessage* CMessagePlayerWon::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessagePlayerWon::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, playerId); @@ -579,14 +579,14 @@ CMessage* CMessagePlayerWon::FromJSVal(const ScriptRequest& rq, JS::HandleValue //////////////////////////////// -JS::Value CMessagePlayerDefeated::ToJSVal(const ScriptRequest& rq) const +JS::Value CMessagePlayerDefeated::ToJSVal(const Script::Request& rq) const { TOJSVAL_SETUP(); SET_MSG_PROPERTY(playerId); return JS::ObjectValue(*obj); } -CMessage* CMessagePlayerDefeated::FromJSVal(const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessagePlayerDefeated::FromJSVal(const Script::Request& rq, JS::HandleValue val) { FROMJSVAL_SETUP(); GET_MSG_PROPERTY(player_id_t, playerId); @@ -595,7 +595,7 @@ CMessage* CMessagePlayerDefeated::FromJSVal(const ScriptRequest& rq, JS::HandleV //////////////////////////////// -CMessage* CMessageFromJSVal(int mtid, const ScriptRequest& rq, JS::HandleValue val) +CMessage* CMessageFromJSVal(int mtid, const Script::Request& rq, JS::HandleValue val) { switch (mtid) { diff --git a/source/simulation2/scripting/ScriptComponent.cpp b/source/simulation2/scripting/ScriptComponent.cpp index 6ad0a3be89..0f9cac8482 100644 --- a/source/simulation2/scripting/ScriptComponent.cpp +++ b/source/simulation2/scripting/ScriptComponent.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -27,49 +27,49 @@ #include -class ScriptInterface; +namespace Script { class Interface; } -CComponentTypeScript::CComponentTypeScript(const ScriptInterface& scriptInterface, JS::HandleValue instance) : +CComponentTypeScript::CComponentTypeScript(const Script::Interface& scriptInterface, JS::HandleValue instance) : m_ScriptInterface(scriptInterface), m_Instance(instance) {} void CComponentTypeScript::Init(CComponentManager& cmpMgr, const CParamNode& paramNode, entity_id_t ent) { cmpMgr.RegisterTrace(ent, m_Instance); - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); Script::SetProperty(rq, GetInstance(), "entity", (int)ent, true, false); Script::SetProperty(rq, GetInstance(), "template", paramNode, true, false); - ScriptFunction::CallVoid(rq, GetInstance(), "Init"); + Script::Function::CallVoid(rq, GetInstance(), "Init"); } void CComponentTypeScript::Deinit() { - ScriptRequest rq(m_ScriptInterface); - ScriptFunction::CallVoid(rq, GetInstance(), "Deinit"); + Script::Request rq(m_ScriptInterface); + Script::Function::CallVoid(rq, GetInstance(), "Deinit"); } bool CComponentTypeScript::HasMessageHandler(const CMessage& msg, const bool global) { - const ScriptRequest rq(m_ScriptInterface); + const Script::Request rq(m_ScriptInterface); return Script::HasProperty(rq, GetInstance(), global ? msg.GetScriptGlobalHandlerName() : msg.GetScriptHandlerName()); } void CComponentTypeScript::HandleMessage(const CMessage& msg, bool global) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); const char* name = global ? msg.GetScriptGlobalHandlerName() : msg.GetScriptHandlerName(); JS::RootedValue msgVal(rq.cx, msg.ToJSValCached(rq)); - if (!ScriptFunction::CallVoid(rq, GetInstance(), name, msgVal)) + if (!Script::Function::CallVoid(rq, GetInstance(), name, msgVal)) LOGERROR("Script message handler %s failed", name); } void CComponentTypeScript::Serialize(ISerializer& serialize) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); try { @@ -91,7 +91,7 @@ void CComponentTypeScript::Deserialize(CComponentManager& cmpMgr, const CParamNo { cmpMgr.RegisterTrace(ent, m_Instance); - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); Script::SetProperty(rq, GetInstance(), "entity", (int)ent, true, false); Script::SetProperty(rq, GetInstance(), "template", paramNode, true, false); diff --git a/source/simulation2/scripting/ScriptComponent.h b/source/simulation2/scripting/ScriptComponent.h index e05f574f87..8f4b6d3485 100644 --- a/source/simulation2/scripting/ScriptComponent.h +++ b/source/simulation2/scripting/ScriptComponent.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -35,7 +35,7 @@ class CComponentTypeScript { NONCOPYABLE(CComponentTypeScript); public: - CComponentTypeScript(const ScriptInterface& scriptInterface, JS::HandleValue instance); + CComponentTypeScript(const Script::Interface& scriptInterface, JS::HandleValue instance); JS::HandleValue GetInstance() const { return JS::HandleValue::fromMarkedLocation(m_Instance.address()); } JS::MutableHandleValue GetMutInstance() { return JS::MutableHandleValue::fromMarkedLocation(const_cast(m_Instance.address())); } @@ -53,8 +53,8 @@ public: R Call(const char* funcname, const Ts&... params) const { R ret; - ScriptRequest rq(m_ScriptInterface); - if (ScriptFunction::Call(rq, GetInstance(), funcname, ret, params...)) + Script::Request rq(m_ScriptInterface); + if (Script::Function::Call(rq, GetInstance(), funcname, ret, params...)) return ret; LOGERROR("Error calling component script function %s", funcname); return R(); @@ -64,21 +64,21 @@ public: template void CallRef(const char* funcname, R ret, const Ts&... params) const { - ScriptRequest rq(m_ScriptInterface); - if (!ScriptFunction::Call(rq, GetInstance(), funcname, ret, params...)) + Script::Request rq(m_ScriptInterface); + if (!Script::Function::Call(rq, GetInstance(), funcname, ret, params...)) LOGERROR("Error calling component script function %s", funcname); } template void CallVoid(const char* funcname, const Ts&... params) const { - ScriptRequest rq(m_ScriptInterface); - if (!ScriptFunction::CallVoid(rq, GetInstance(), funcname, params...)) + Script::Request rq(m_ScriptInterface); + if (!Script::Function::CallVoid(rq, GetInstance(), funcname, params...)) LOGERROR("Error calling component script function %s", funcname); } private: - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; JS::Heap m_Instance; }; @@ -92,7 +92,7 @@ private: #define DEFAULT_SCRIPT_WRAPPER_BASIC(cname) \ - static IComponent* Allocate(const ScriptInterface& scriptInterface, JS::HandleValue instance) \ + static IComponent* Allocate(const Script::Interface& scriptInterface, JS::HandleValue instance) \ { \ return new CCmp##cname(scriptInterface, instance); \ } \ @@ -100,7 +100,7 @@ private: { \ delete static_cast (cmp); \ } \ - CCmp##cname(const ScriptInterface& scriptInterface, JS::HandleValue instance) : m_Script(scriptInterface, instance) { } \ + CCmp##cname(const Script::Interface& scriptInterface, JS::HandleValue instance) : m_Script(scriptInterface, instance) { } \ static std::string GetSchema() \ { \ return ""; \ diff --git a/source/simulation2/serialization/BinarySerializer.cpp b/source/simulation2/serialization/BinarySerializer.cpp index 8570316b20..a16b058c2d 100644 --- a/source/simulation2/serialization/BinarySerializer.cpp +++ b/source/simulation2/serialization/BinarySerializer.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -23,7 +23,7 @@ #include "ps/CLogger.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/serialization/SerializedScriptTypes.h" #include @@ -77,10 +77,10 @@ static u8 GetArrayType(js::Scalar::Type arrayType) } } -CBinarySerializerScriptImpl::CBinarySerializerScriptImpl(const ScriptInterface& scriptInterface, ISerializer& serializer) : +CBinarySerializerScriptImpl::CBinarySerializerScriptImpl(const Script::Interface& scriptInterface, ISerializer& serializer) : m_ScriptInterface(scriptInterface), m_Serializer(serializer), m_ScriptBackrefsNext(0) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS_AddExtraGCRootsTracer(rq.cx, Trace, this); m_SerializePropId = JS::PropertyKey::fromPinnedString(JS_AtomizeAndPinString(rq.cx, "Serialize")); m_DeserializePropId = JS::PropertyKey::fromPinnedString(JS_AtomizeAndPinString(rq.cx, "Deserialize")); @@ -88,16 +88,16 @@ CBinarySerializerScriptImpl::CBinarySerializerScriptImpl(const ScriptInterface& CBinarySerializerScriptImpl::~CBinarySerializerScriptImpl() { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS_RemoveExtraGCRootsTracer(rq.cx, Trace, this); } void CBinarySerializerScriptImpl::PutScriptVal(JS::HandleValue val) { - HandleScriptVal(ScriptRequest(m_ScriptInterface), val); + HandleScriptVal(Script::Request(m_ScriptInterface), val); } -void CBinarySerializerScriptImpl::HandleScriptVal(const ScriptRequest& rq, JS::HandleValue val) +void CBinarySerializerScriptImpl::HandleScriptVal(const Script::Request& rq, JS::HandleValue val) { switch (JS_TypeOfValue(rq.cx, val)) { @@ -269,7 +269,7 @@ void CBinarySerializerScriptImpl::HandleScriptVal(const ScriptRequest& rq, JS::H if (!protoInfo.hasNullSerialize) { JS::RootedValue data(rq.cx); - if (!ScriptFunction::Call(rq, val, "Serialize", &data)) + if (!Script::Function::Call(rq, val, "Serialize", &data)) throw PSERROR_Serialize_ScriptError("Prototype Serialize function failed"); m_Serializer.ScriptVal("data", &data); } @@ -450,7 +450,7 @@ void CBinarySerializerScriptImpl::HandleScriptVal(const ScriptRequest& rq, JS::H } } -void CBinarySerializerScriptImpl::ScriptString(const ScriptRequest& rq, const char* name, JS::HandleString string) +void CBinarySerializerScriptImpl::ScriptString(const Script::Request& rq, const char* name, JS::HandleString string) { #if BYTE_ORDER != LITTLE_ENDIAN #error TODO: probably need to convert JS strings to little-endian @@ -486,7 +486,7 @@ void CBinarySerializerScriptImpl::Trace(JSTracer *trc, void *data) serializer->m_ScriptBackrefTags.trace(trc); } -u32 CBinarySerializerScriptImpl::GetScriptBackrefTag(const ScriptRequest& rq, JS::HandleObject obj) +u32 CBinarySerializerScriptImpl::GetScriptBackrefTag(const Script::Request& rq, JS::HandleObject obj) { // To support non-tree structures (e.g. "var x = []; var y = [x, x];"), we need a way // to indicate multiple references to one object(/array). So every time we serialize a diff --git a/source/simulation2/serialization/BinarySerializer.h b/source/simulation2/serialization/BinarySerializer.h index 3e8ae3dc71..c0514ae074 100644 --- a/source/simulation2/serialization/BinarySerializer.h +++ b/source/simulation2/serialization/BinarySerializer.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -39,8 +39,8 @@ #include class JSTracer; -class ScriptInterface; -class ScriptRequest; +namespace Script { class Interface; } +namespace Script { class Request; } /** * Wrapper for redirecting ostream writes to CBinarySerializer's impl @@ -98,22 +98,22 @@ protected: class CBinarySerializerScriptImpl { public: - CBinarySerializerScriptImpl(const ScriptInterface& scriptInterface, ISerializer& serializer); + CBinarySerializerScriptImpl(const Script::Interface& scriptInterface, ISerializer& serializer); ~CBinarySerializerScriptImpl(); void PutScriptVal(JS::HandleValue val); private: - void ScriptString(const ScriptRequest& rq, const char* name, JS::HandleString string); - void HandleScriptVal(const ScriptRequest& rq, JS::HandleValue val); + void ScriptString(const Script::Request& rq, const char* name, JS::HandleString string); + void HandleScriptVal(const Script::Request& rq, JS::HandleValue val); static void Trace(JSTracer* trc, void* data); - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; ISerializer& m_Serializer; using ObjectTagMap = JS::GCHashMap, u32, js::StableCellHasher, js::SystemAllocPolicy>; ObjectTagMap m_ScriptBackrefTags; u32 m_ScriptBackrefsNext; - u32 GetScriptBackrefTag(const ScriptRequest& rq, JS::HandleObject obj); + u32 GetScriptBackrefTag(const Script::Request& rq, JS::HandleObject obj); JS::PropertyKey m_SerializePropId; JS::PropertyKey m_DeserializePropId; @@ -129,7 +129,7 @@ class CBinarySerializer : public ISerializer { NONCOPYABLE(CBinarySerializer); public: - CBinarySerializer(const ScriptInterface& scriptInterface) : + CBinarySerializer(const Script::Interface& scriptInterface) : m_ScriptImpl(new CBinarySerializerScriptImpl(scriptInterface, *this)), m_RawStreamBuf(m_Impl), m_RawStream(&m_RawStreamBuf) @@ -137,7 +137,7 @@ public: } template - CBinarySerializer(const ScriptInterface& scriptInterface, A& a) : + CBinarySerializer(const Script::Interface& scriptInterface, A& a) : m_ScriptImpl(new CBinarySerializerScriptImpl(scriptInterface, *this)), m_Impl(a), m_RawStreamBuf(m_Impl), diff --git a/source/simulation2/serialization/DebugSerializer.cpp b/source/simulation2/serialization/DebugSerializer.cpp index a68f4852b8..538d569f9c 100644 --- a/source/simulation2/serialization/DebugSerializer.cpp +++ b/source/simulation2/serialization/DebugSerializer.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -25,7 +25,7 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include #include @@ -56,7 +56,7 @@ std::string canonfloat(T value, int prec) return r; } -CDebugSerializer::CDebugSerializer(const ScriptInterface& scriptInterface, std::ostream& stream, bool includeDebugInfo) : +CDebugSerializer::CDebugSerializer(const Script::Interface& scriptInterface, std::ostream& stream, bool includeDebugInfo) : m_ScriptInterface(scriptInterface), m_Stream(stream), m_IsDebug(includeDebugInfo), m_Indent(0) { } @@ -153,14 +153,14 @@ void CDebugSerializer::PutString(const char* name, const std::string& value) void CDebugSerializer::PutScriptVal(const char* name, JS::MutableHandleValue value) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS::RootedValue serialize(rq.cx); if (Script::GetProperty(rq, value, "Serialize", &serialize) && !serialize.isNullOrUndefined()) { // If the value has a Serialize property, pretty-parse that instead. // (this gives more accurate OOS reports). - ScriptFunction::Call(rq, value, "Serialize", &serialize); + Script::Function::Call(rq, value, "Serialize", &serialize); std::string serialized_source = Script::ToString(rq, &serialize, true); m_Stream << INDENT << name << ": " << serialized_source << "\n"; } diff --git a/source/simulation2/serialization/DebugSerializer.h b/source/simulation2/serialization/DebugSerializer.h index 586ea535dd..9144d1e43a 100644 --- a/source/simulation2/serialization/DebugSerializer.h +++ b/source/simulation2/serialization/DebugSerializer.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -31,7 +31,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } /** * Serialize to a human-readable YAML-like format. @@ -45,7 +45,7 @@ public: * @param stream Stream to receive UTF-8 encoded output * @param includeDebugInfo If true then additional non-deterministic data will be included in the output */ - CDebugSerializer(const ScriptInterface& scriptInterface, std::ostream& stream, bool includeDebugInfo = true); + CDebugSerializer(const Script::Interface& scriptInterface, std::ostream& stream, bool includeDebugInfo = true); void Comment(const std::string& comment); void TextLine(const std::string& text); @@ -71,7 +71,7 @@ protected: virtual void PutRaw(const char* name, const u8* data, size_t len); private: - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; std::ostream& m_Stream; bool m_IsDebug; int m_Indent; diff --git a/source/simulation2/serialization/HashSerializer.cpp b/source/simulation2/serialization/HashSerializer.cpp index 55d777cdb6..2ae8a3d1ed 100644 --- a/source/simulation2/serialization/HashSerializer.cpp +++ b/source/simulation2/serialization/HashSerializer.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -21,9 +21,9 @@ #include "simulation2/serialization/BinarySerializer.h" -class ScriptInterface; +namespace Script { class Interface; } -CHashSerializer::CHashSerializer(const ScriptInterface& scriptInterface) : +CHashSerializer::CHashSerializer(const Script::Interface& scriptInterface) : CBinarySerializer(scriptInterface) { } diff --git a/source/simulation2/serialization/HashSerializer.h b/source/simulation2/serialization/HashSerializer.h index 1158ab5048..7e4bef055c 100644 --- a/source/simulation2/serialization/HashSerializer.h +++ b/source/simulation2/serialization/HashSerializer.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -24,7 +24,7 @@ #include -class ScriptInterface; +namespace Script { class Interface; } class CHashSerializerImpl { @@ -49,7 +49,7 @@ private: class CHashSerializer : public CBinarySerializer { public: - CHashSerializer(const ScriptInterface& scriptInterface); + CHashSerializer(const Script::Interface& scriptInterface); size_t GetHashLength(); const u8* ComputeHash(); diff --git a/source/simulation2/serialization/SerializedScriptTypes.h b/source/simulation2/serialization/SerializedScriptTypes.h index d44c9d96f5..48facbcba8 100644 --- a/source/simulation2/serialization/SerializedScriptTypes.h +++ b/source/simulation2/serialization/SerializedScriptTypes.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -63,7 +63,7 @@ struct SPrototypeSerialization bool hasNullSerialize = false; }; -inline SPrototypeSerialization GetPrototypeInfo(const ScriptRequest& rq, JS::HandleObject prototype, JS::PropertyKey ser, JS::PropertyKey deser) +inline SPrototypeSerialization GetPrototypeInfo(const Script::Request& rq, JS::HandleObject prototype, JS::PropertyKey ser, JS::PropertyKey deser) { SPrototypeSerialization ret; diff --git a/source/simulation2/serialization/StdDeserializer.cpp b/source/simulation2/serialization/StdDeserializer.cpp index e3cab4127f..f2253d5b8f 100644 --- a/source/simulation2/serialization/StdDeserializer.cpp +++ b/source/simulation2/serialization/StdDeserializer.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -25,8 +25,8 @@ #include "lib/utf8.h" #include "ps/CStr.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/serialization/ISerializer.h" #include "simulation2/serialization/SerializedScriptTypes.h" #include "simulation2/serialization/StdSerializer.h" @@ -51,10 +51,10 @@ class JSObject; -CStdDeserializer::CStdDeserializer(const ScriptInterface& scriptInterface, std::istream& stream) : +CStdDeserializer::CStdDeserializer(const Script::Interface& scriptInterface, std::istream& stream) : m_ScriptInterface(scriptInterface), m_Stream(stream) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); JS_AddExtraGCRootsTracer(rq.cx, CStdDeserializer::Trace, this); m_SerializePropId = JS::PropertyKey::fromPinnedString(JS_AtomizeAndPinString(rq.cx, "Serialize")); m_DeserializePropId = JS::PropertyKey::fromPinnedString(JS_AtomizeAndPinString(rq.cx, "Deserialize")); @@ -65,7 +65,7 @@ CStdDeserializer::CStdDeserializer(const ScriptInterface& scriptInterface, std:: CStdDeserializer::~CStdDeserializer() { - JS_RemoveExtraGCRootsTracer(ScriptRequest(m_ScriptInterface).cx, CStdDeserializer::Trace, this); + JS_RemoveExtraGCRootsTracer(Script::Request(m_ScriptInterface).cx, CStdDeserializer::Trace, this); } void CStdDeserializer::Trace(JSTracer *trc, void *data) @@ -140,7 +140,7 @@ void CStdDeserializer::GetScriptBackref(size_t tag, JS::MutableHandleObject ret) JS::Value CStdDeserializer::ReadScriptVal(const char* /*name*/, JS::HandleObject preexistingObject) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); uint8_t type; NumberU8_Unbounded("type", type); @@ -178,7 +178,7 @@ JS::Value CStdDeserializer::ReadScriptVal(const char* /*name*/, JS::HandleObject else { JS::RootedValue constructor(rq.cx); - if (!ScriptInterface::GetGlobalProperty(rq, prototypeName.ToUTF8(), &constructor)) + if (!Script::Interface::GetGlobalProperty(rq, prototypeName.ToUTF8(), &constructor)) throw PSERROR_Deserialize_ScriptError("Deserializer failed to get constructor object"); JS::RootedObject newObj(rq.cx); @@ -205,7 +205,7 @@ JS::Value CStdDeserializer::ReadScriptVal(const char* /*name*/, JS::HandleObject ScriptVal("data", &data); JS::RootedValue objVal(rq.cx, JS::ObjectValue(*obj)); - ScriptFunction::CallVoid(rq, objVal, "Deserialize", data); + Script::Function::CallVoid(rq, objVal, "Deserialize", data); return JS::ObjectValue(*obj); } @@ -482,7 +482,7 @@ void CStdDeserializer::ScriptString(const char* name, JS::MutableHandleString ou #error TODO: probably need to convert JS strings from little-endian #endif - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); bool isLatin1; Bool("isLatin1", isLatin1); @@ -513,7 +513,7 @@ void CStdDeserializer::ScriptVal(const char* name, JS::MutableHandleValue out) void CStdDeserializer::ScriptObjectAssign(const char* name, JS::HandleValue objVal) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); if (!objVal.isObject()) throw PSERROR_Deserialize_ScriptError(); diff --git a/source/simulation2/serialization/StdDeserializer.h b/source/simulation2/serialization/StdDeserializer.h index 5557357107..7e30492343 100644 --- a/source/simulation2/serialization/StdDeserializer.h +++ b/source/simulation2/serialization/StdDeserializer.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -32,14 +32,14 @@ class JSObject; class JSTracer; -class ScriptInterface; namespace JS { template class Heap; } +namespace Script { class Interface; } class CStdDeserializer : public IDeserializer { NONCOPYABLE(CStdDeserializer); public: - CStdDeserializer(const ScriptInterface& scriptInterface, std::istream& stream); + CStdDeserializer(const Script::Interface& scriptInterface, std::istream& stream); virtual ~CStdDeserializer(); virtual void ScriptVal(const char* name, JS::MutableHandleValue out); @@ -67,7 +67,7 @@ private: JS::PropertyKey m_SerializePropId; JS::PropertyKey m_DeserializePropId; - const ScriptInterface& m_ScriptInterface; + const Script::Interface& m_ScriptInterface; std::istream& m_Stream; }; diff --git a/source/simulation2/serialization/StdSerializer.cpp b/source/simulation2/serialization/StdSerializer.cpp index 1ef424fe11..715ab4e11d 100644 --- a/source/simulation2/serialization/StdSerializer.cpp +++ b/source/simulation2/serialization/StdSerializer.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -21,14 +21,14 @@ #include "simulation2/serialization/BinarySerializer.h" -class ScriptInterface; +namespace Script { class Interface; } CStdSerializerImpl::CStdSerializerImpl(std::ostream& stream) : m_Stream(stream) { } -CStdSerializer::CStdSerializer(const ScriptInterface& scriptInterface, std::ostream& stream) : +CStdSerializer::CStdSerializer(const Script::Interface& scriptInterface, std::ostream& stream) : CBinarySerializer(scriptInterface, stream) { } diff --git a/source/simulation2/serialization/StdSerializer.h b/source/simulation2/serialization/StdSerializer.h index 0a9e329d12..49780ae9a8 100644 --- a/source/simulation2/serialization/StdSerializer.h +++ b/source/simulation2/serialization/StdSerializer.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -25,7 +25,7 @@ #include #include -class ScriptInterface; +namespace Script { class Interface; } #define DEBUG_SERIALIZER_ANNOTATE 0 // annotate the stream to help debugging if you're reading the output in a hex editor @@ -62,7 +62,7 @@ private: class CStdSerializer : public CBinarySerializer { public: - CStdSerializer(const ScriptInterface& scriptInterface, std::ostream& stream); + CStdSerializer(const Script::Interface& scriptInterface, std::ostream& stream); virtual std::ostream& GetStream(); }; diff --git a/source/simulation2/system/Component.h b/source/simulation2/system/Component.h index 33a67b0e49..eaa028502e 100644 --- a/source/simulation2/system/Component.h +++ b/source/simulation2/system/Component.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -37,7 +37,7 @@ } #define DEFAULT_COMPONENT_ALLOCATOR(cname) \ - static IComponent* Allocate(const ScriptInterface&, JS::HandleValue) { return new CCmp##cname(); } \ + static IComponent* Allocate(const Script::Interface&, JS::HandleValue) { return new CCmp##cname(); } \ static void Deallocate(IComponent* cmp) { delete static_cast (cmp); } \ int GetComponentTypeId() const override \ { \ diff --git a/source/simulation2/system/ComponentManager.cpp b/source/simulation2/system/ComponentManager.cpp index 825ecffb05..6b151948fc 100644 --- a/source/simulation2/system/ComponentManager.cpp +++ b/source/simulation2/system/ComponentManager.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -30,7 +30,7 @@ #include "ps/scripting/JSInterface_VFS.h" #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpTemplateManager.h" #include "simulation2/helpers/Player.h" @@ -48,7 +48,7 @@ #include #include -class ScriptContext; +namespace Script { class Context; } /** * Used for script-only message types. @@ -59,9 +59,9 @@ public: virtual int GetType() const { return mtid; } virtual const char* GetScriptHandlerName() const { return handlerName.c_str(); } virtual const char* GetScriptGlobalHandlerName() const { return globalHandlerName.c_str(); } - virtual JS::Value ToJSVal(const ScriptRequest&) const { return msg.get(); } + virtual JS::Value ToJSVal(const Script::Request&) const { return msg.get(); } - CMessageScripted(const ScriptRequest& rq, int mtid, const std::string& name, JS::HandleValue msg) : + CMessageScripted(const Script::Request& rq, int mtid, const std::string& name, JS::HandleValue msg) : mtid(mtid), handlerName("On" + name), globalHandlerName("OnGlobal" + name), msg(rq.cx, msg) { } @@ -72,7 +72,7 @@ public: JS::PersistentRootedValue msg; }; -CComponentManager::CComponentManager(CSimContext& context, ScriptContext& cx, bool skipScriptFunctions) : +CComponentManager::CComponentManager(CSimContext& context, Script::Context& cx, bool skipScriptFunctions) : m_NextScriptComponentTypeId(CID__LastNative), m_ScriptInterface("Engine", "Simulation", cx), m_SimContext(context), m_CurrentlyHotloading(false) @@ -89,24 +89,24 @@ CComponentManager::CComponentManager(CSimContext& context, ScriptContext& cx, bo if (!skipScriptFunctions) { JSI_VFS::RegisterScriptFunctions_ReadOnlySimulation(m_ScriptInterface); - ScriptRequest rq(m_ScriptInterface); - constexpr ScriptFunction::ObjectGetter Getter = &ScriptInterface::ObjectFromCBData; - ScriptFunction::Register<&CComponentManager::Script_RegisterComponentType, Getter>(rq, "RegisterComponentType"); - ScriptFunction::Register<&CComponentManager::Script_RegisterSystemComponentType, Getter>(rq, "RegisterSystemComponentType"); - ScriptFunction::Register<&CComponentManager::Script_ReRegisterComponentType, Getter>(rq, "ReRegisterComponentType"); - ScriptFunction::Register<&CComponentManager::Script_RegisterInterface, Getter>(rq, "RegisterInterface"); - ScriptFunction::Register<&CComponentManager::Script_RegisterMessageType, Getter>(rq, "RegisterMessageType"); - ScriptFunction::Register<&CComponentManager::Script_RegisterGlobal, Getter>(rq, "RegisterGlobal"); - ScriptFunction::Register<&CComponentManager::Script_GetEntitiesWithInterface, Getter>(rq, "GetEntitiesWithInterface"); - ScriptFunction::Register<&CComponentManager::Script_GetComponentsWithInterface, Getter>(rq, "GetComponentsWithInterface"); - ScriptFunction::Register<&CComponentManager::Script_PostMessage, Getter>(rq, "PostMessage"); - ScriptFunction::Register<&CComponentManager::Script_BroadcastMessage, Getter>(rq, "BroadcastMessage"); - ScriptFunction::Register<&CComponentManager::Script_AddEntity, Getter>(rq, "AddEntity"); - ScriptFunction::Register<&CComponentManager::Script_AddLocalEntity, Getter>(rq, "AddLocalEntity"); - ScriptFunction::Register<&CComponentManager::QueryInterface, Getter>(rq, "QueryInterface"); - ScriptFunction::Register<&CComponentManager::DestroyComponentsSoon, Getter>(rq, "DestroyEntity"); - ScriptFunction::Register<&CComponentManager::FlushDestroyedComponents, Getter>(rq, "FlushDestroyedEntities"); - ScriptFunction::Register<&CComponentManager::Script_GetTemplate, Getter>(rq, "GetTemplate"); + Script::Request rq(m_ScriptInterface); + constexpr Script::Function::ObjectGetter Getter = &Script::Interface::ObjectFromCBData; + Script::Function::Register<&CComponentManager::Script_RegisterComponentType, Getter>(rq, "RegisterComponentType"); + Script::Function::Register<&CComponentManager::Script_RegisterSystemComponentType, Getter>(rq, "RegisterSystemComponentType"); + Script::Function::Register<&CComponentManager::Script_ReRegisterComponentType, Getter>(rq, "ReRegisterComponentType"); + Script::Function::Register<&CComponentManager::Script_RegisterInterface, Getter>(rq, "RegisterInterface"); + Script::Function::Register<&CComponentManager::Script_RegisterMessageType, Getter>(rq, "RegisterMessageType"); + Script::Function::Register<&CComponentManager::Script_RegisterGlobal, Getter>(rq, "RegisterGlobal"); + Script::Function::Register<&CComponentManager::Script_GetEntitiesWithInterface, Getter>(rq, "GetEntitiesWithInterface"); + Script::Function::Register<&CComponentManager::Script_GetComponentsWithInterface, Getter>(rq, "GetComponentsWithInterface"); + Script::Function::Register<&CComponentManager::Script_PostMessage, Getter>(rq, "PostMessage"); + Script::Function::Register<&CComponentManager::Script_BroadcastMessage, Getter>(rq, "BroadcastMessage"); + Script::Function::Register<&CComponentManager::Script_AddEntity, Getter>(rq, "AddEntity"); + Script::Function::Register<&CComponentManager::Script_AddLocalEntity, Getter>(rq, "AddLocalEntity"); + Script::Function::Register<&CComponentManager::QueryInterface, Getter>(rq, "QueryInterface"); + Script::Function::Register<&CComponentManager::DestroyComponentsSoon, Getter>(rq, "DestroyEntity"); + Script::Function::Register<&CComponentManager::FlushDestroyedComponents, Getter>(rq, "FlushDestroyedEntities"); + Script::Function::Register<&CComponentManager::Script_GetTemplate, Getter>(rq, "GetTemplate"); } @@ -144,7 +144,7 @@ void CComponentManager::LoadComponentTypes() #define MESSAGE(name) \ RegisterMessageType(MT_##name, #name); #define INTERFACE(name) \ - extern void RegisterComponentInterface_##name(ScriptInterface&); \ + extern void RegisterComponentInterface_##name(Script::Interface&); \ RegisterComponentInterface_##name(m_ScriptInterface); #define COMPONENT(name) \ extern void RegisterComponentType_##name(CComponentManager&); \ @@ -177,7 +177,7 @@ bool CComponentManager::LoadScript(const VfsPath& filename, bool hotload) void CComponentManager::Script_RegisterComponentType_Common(int iid, const std::string& cname, JS::HandleValue ctor, bool reRegister, bool systemComponent) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); // Find the C++ component that wraps the interface int cidWrapper = GetScriptWrapper(iid); @@ -451,7 +451,7 @@ CMessage* CComponentManager::ConstructMessage(int mtid, JS::HandleValue data) if (mtid == MT__Invalid || mtid > (int)m_MessageTypeIdsByName.size()) // (IDs start at 1 so use '>' here) LOGERROR("PostMessage with invalid message type ID '%d'", mtid); - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); if (mtid < MT__LastNative) { return CMessageFromJSVal(mtid, rq, data); @@ -755,7 +755,7 @@ void CComponentManager::AddSystemComponents(bool skipScriptedComponents, bool sk IComponent* CComponentManager::ConstructComponent(CEntityHandle ent, ComponentTypeId cid) { - ScriptRequest rq(m_ScriptInterface); + Script::Request rq(m_ScriptInterface); std::map::const_iterator it = m_ComponentTypesById.find(cid); if (it == m_ComponentTypesById.end()) diff --git a/source/simulation2/system/ComponentManager.h b/source/simulation2/system/ComponentManager.h index b344c8d3aa..d1a45f265a 100644 --- a/source/simulation2/system/ComponentManager.h +++ b/source/simulation2/system/ComponentManager.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -21,7 +21,7 @@ #include "lib/code_annotation.h" #include "lib/debug.h" #include "lib/types.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/system/Component.h" #include "simulation2/system/DynamicSubscription.h" #include "simulation2/system/Entity.h" @@ -41,7 +41,7 @@ class CMessage; class JSTracer; -class ScriptContext; +namespace Script { class Context; } class CComponentManager { @@ -83,7 +83,7 @@ private: }; public: - CComponentManager(CSimContext&, ScriptContext& cx, bool skipScriptFunctions = false); + CComponentManager(CSimContext&, Script::Context& cx, bool skipScriptFunctions = false); ~CComponentManager(); void LoadComponentTypes(); @@ -299,7 +299,7 @@ public: std::string GenerateSchema() const; - ScriptInterface& GetScriptInterface() { return m_ScriptInterface; } + Script::Interface& GetScriptInterface() { return m_ScriptInterface; } private: // Implementations of functions exposed to scripts @@ -328,7 +328,7 @@ private: CEntityHandle AllocateEntityHandle(entity_id_t ent); - ScriptInterface m_ScriptInterface; + Script::Interface m_ScriptInterface; CSimContext& m_SimContext; CEntityHandle m_SystemEntity; diff --git a/source/simulation2/system/ComponentTest.h b/source/simulation2/system/ComponentTest.h index 6a78986a91..832f959a2d 100644 --- a/source/simulation2/system/ComponentTest.h +++ b/source/simulation2/system/ComponentTest.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ #include "maths/FixedVector3D.h" #include "maths/Vector3D.h" #include "ps/Errors.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/components/ICmpTerrain.h" #include "simulation2/helpers/Position.h" #include "simulation2/serialization/DebugSerializer.h" @@ -42,7 +42,7 @@ #include class CMessage; -class ScriptContext; +namespace Script { class Context; } /** * @file @@ -67,13 +67,13 @@ class ComponentTestHelper bool m_isSystemEntityInit = false; public: - ComponentTestHelper(ScriptContext& scriptContext) : + ComponentTestHelper(Script::Context& scriptContext) : m_Context(), m_ComponentManager(m_Context, scriptContext), m_Cmp(NULL) { m_ComponentManager.LoadComponentTypes(); } - const ScriptInterface& GetScriptInterface() + const Script::Interface& GetScriptInterface() { return m_ComponentManager.GetScriptInterface(); } diff --git a/source/simulation2/system/IComponent.h b/source/simulation2/system/IComponent.h index 4a2fa4f590..71ead53651 100644 --- a/source/simulation2/system/IComponent.h +++ b/source/simulation2/system/IComponent.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,7 +22,7 @@ #include "Message.h" #include "Entity.h" #include "SimContext.h" -#include "scriptinterface/ScriptForward.h" +#include "scriptinterface/ForwardDeclarations.h" class CParamNode; class CMessage; @@ -33,7 +33,7 @@ class IComponent { public: // Component allocation types - using AllocFunc = IComponent* (*)(const ScriptInterface& scriptInterface, JS::HandleValue ctor); + using AllocFunc = IComponent* (*)(const Script::Interface& scriptInterface, JS::HandleValue ctor); using DeallocFunc = void (*)(IComponent*); using ClassInitFunc = void (*)(CComponentManager& componentManager); @@ -76,7 +76,7 @@ private: * @Returns whether a scripted wrapper of this IComponent is not supported. * Derrived classes should return true if they implement such a wrapper. */ - virtual bool NewJSObject(const ScriptInterface& scriptInterface, JS::MutableHandleObject out) const = 0; + virtual bool NewJSObject(const Script::Interface& scriptInterface, JS::MutableHandleObject out) const = 0; CEntityHandle m_EntityHandle; const CSimContext* m_SimContext; diff --git a/source/simulation2/system/Interface.h b/source/simulation2/system/Interface.h index e8b17b173f..e85aab9f7a 100644 --- a/source/simulation2/system/Interface.h +++ b/source/simulation2/system/Interface.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -22,10 +22,10 @@ #define DECLARE_INTERFACE_TYPE(iname) \ virtual JS::HandleValue GetJSInstance() const; \ - static void InterfaceInit(ScriptInterface& scriptInterface); \ + static void InterfaceInit(Script::Interface& scriptInterface); \ static EInterfaceId GetInterfaceId() { return IID_##iname; } \ private: \ - virtual bool NewJSObject(const ScriptInterface& scriptInterface, JS::MutableHandleObject out) const; \ + virtual bool NewJSObject(const Script::Interface& scriptInterface, JS::MutableHandleObject out) const; \ mutable JS::Heap m_CachedInstance; \ public: diff --git a/source/simulation2/system/InterfaceScripted.h b/source/simulation2/system/InterfaceScripted.h index 8068384b70..10bccc7623 100644 --- a/source/simulation2/system/InterfaceScripted.h +++ b/source/simulation2/system/InterfaceScripted.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2024 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -20,27 +20,27 @@ #include "scriptinterface/FunctionWrapper.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" #include "simulation2/system/ComponentManager.h" #define BEGIN_INTERFACE_WRAPPER(iname) \ JSClass class_ICmp##iname = { \ - "ICmp" #iname, JSCLASS_HAS_RESERVED_SLOTS( ScriptInterface::JSObjectReservedSlots::PRIVATE+1 ) \ + "ICmp" #iname, JSCLASS_HAS_RESERVED_SLOTS( Script::Interface::JSObjectReservedSlots::PRIVATE+1 ) \ }; \ static JSFunctionSpec methods_ICmp##iname[] = { #define END_INTERFACE_WRAPPER(iname) \ JS_FS_END \ }; \ - void ICmp##iname::InterfaceInit(ScriptInterface& scriptInterface) { \ + void ICmp##iname::InterfaceInit(Script::Interface& scriptInterface) { \ scriptInterface.DefineCustomObjectType(&class_ICmp##iname, NULL, 0, NULL, methods_ICmp##iname, NULL, NULL); \ } \ - bool ICmp##iname::NewJSObject(const ScriptInterface& scriptInterface, JS::MutableHandleObject out) const\ + bool ICmp##iname::NewJSObject(const Script::Interface& scriptInterface, JS::MutableHandleObject out) const\ { \ out.set(scriptInterface.CreateCustomObject("ICmp" #iname)); \ IComponent* comp = const_cast(static_cast(this)); \ - JS::SetReservedSlot(out, ScriptInterface::JSObjectReservedSlots::PRIVATE, JS::PrivateValue(comp)); \ + JS::SetReservedSlot(out, Script::Interface::JSObjectReservedSlots::PRIVATE, JS::PrivateValue(comp)); \ return true; \ } \ JS::HandleValue ICmp##iname::GetJSInstance() const \ @@ -48,8 +48,8 @@ if (m_CachedInstance) \ return JS::HandleValue::fromMarkedLocation(m_CachedInstance.address()); \ \ - const ScriptInterface& si = GetSimContext().GetScriptInterface(); \ - ScriptRequest rq(si); \ + const Script::Interface& si = GetSimContext().GetScriptInterface(); \ + Script::Request rq(si); \ JS::RootedObject obj(rq.cx); \ NewJSObject(GetSimContext().GetScriptInterface(), &obj); \ m_CachedInstance.setObject(*obj); \ @@ -57,17 +57,17 @@ GetSimContext().GetComponentManager().RegisterTrace(GetEntityId(), m_CachedInstance); \ return JS::HandleValue::fromMarkedLocation(m_CachedInstance.address()); \ } \ - void RegisterComponentInterface_##iname(ScriptInterface& scriptInterface) { \ + void RegisterComponentInterface_##iname(Script::Interface& scriptInterface) { \ ICmp##iname::InterfaceInit(scriptInterface); \ } template -inline T* ComponentGetter(const ScriptRequest& rq, JS::CallArgs& args) +inline T* ComponentGetter(const Script::Request& rq, JS::CallArgs& args) { - return ScriptInterface::GetPrivate(rq, args); + return Script::Interface::GetPrivate(rq, args); } #define DEFINE_INTERFACE_METHOD(scriptname, classname, methodname) \ - ScriptFunction::Wrap<&classname::methodname, ComponentGetter>(scriptname), + Script::Function::Wrap<&classname::methodname, ComponentGetter>(scriptname), #endif // INCLUDED_INTERFACE_SCRIPTED diff --git a/source/simulation2/system/Message.h b/source/simulation2/system/Message.h index fca3ee14ac..6a114958b3 100644 --- a/source/simulation2/system/Message.h +++ b/source/simulation2/system/Message.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -25,7 +25,7 @@ #include #include -class ScriptRequest; +namespace Script { class Request; } class CMessage { @@ -37,14 +37,14 @@ public: virtual int GetType() const = 0; virtual const char* GetScriptHandlerName() const = 0; virtual const char* GetScriptGlobalHandlerName() const = 0; - virtual JS::Value ToJSVal(const ScriptRequest&) const = 0; - JS::Value ToJSValCached(const ScriptRequest&) const; + virtual JS::Value ToJSVal(const Script::Request&) const = 0; + JS::Value ToJSValCached(const Script::Request&) const; private: mutable std::unique_ptr m_Cached; }; // TODO: GetType could be replaced with a plain member variable to avoid some // virtual calls, if that turns out to be worthwhile -CMessage* CMessageFromJSVal(int mtid, const ScriptRequest&, JS::HandleValue); +CMessage* CMessageFromJSVal(int mtid, const Script::Request&, JS::HandleValue); #endif // INCLUDED_MESSAGE diff --git a/source/simulation2/system/ParamNode.cpp b/source/simulation2/system/ParamNode.cpp index 95b5fc5677..ed19abd6d2 100644 --- a/source/simulation2/system/ParamNode.cpp +++ b/source/simulation2/system/ParamNode.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -29,8 +29,8 @@ #include "ps/XMB/XMBData.h" #include "ps/XML/Xeromyces.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/system/Component.h" #include @@ -388,7 +388,7 @@ void CParamNode::ToXMLString(std::ostream& strm) const } } -void CParamNode::ToJSVal(const ScriptRequest& rq, bool cacheValue, JS::MutableHandleValue ret) const +void CParamNode::ToJSVal(const Script::Request& rq, bool cacheValue, JS::MutableHandleValue ret) const { if (cacheValue && m_ScriptVal != NULL) { @@ -407,7 +407,7 @@ void CParamNode::ToJSVal(const ScriptRequest& rq, bool cacheValue, JS::MutableHa } } -void CParamNode::ConstructJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret) const +void CParamNode::ConstructJSVal(const Script::Request& rq, JS::MutableHandleValue ret) const { if (m_Childs.empty()) { diff --git a/source/simulation2/system/ParamNode.h b/source/simulation2/system/ParamNode.h index 426d0092ba..7fee32526b 100644 --- a/source/simulation2/system/ParamNode.h +++ b/source/simulation2/system/ParamNode.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -31,9 +31,9 @@ #include class CStrIntern; -class ScriptRequest; class XMBData; class XMBElement; +namespace Script { class Request; } /** * An entity initialisation parameter node. @@ -261,7 +261,7 @@ public: * The cache will be reset if *this* node is modified (e.g. by LoadXML), * but *not* if any child nodes are modified (so don't do that). */ - void ToJSVal(const ScriptRequest& rq, bool cacheValue, JS::MutableHandleValue ret) const; + void ToJSVal(const Script::Request& rq, bool cacheValue, JS::MutableHandleValue ret) const; /** * Returns the names/nodes of the children of this node, ordered by name @@ -291,7 +291,7 @@ private: void ResetScriptVal(); - void ConstructJSVal(const ScriptRequest& rq, JS::MutableHandleValue ret) const; + void ConstructJSVal(const Script::Request& rq, JS::MutableHandleValue ret) const; std::string m_Value; ChildrenMap m_Childs; diff --git a/source/simulation2/system/ReplayTurnManager.cpp b/source/simulation2/system/ReplayTurnManager.cpp index 34211184ad..512ebc24f5 100644 --- a/source/simulation2/system/ReplayTurnManager.cpp +++ b/source/simulation2/system/ReplayTurnManager.cpp @@ -23,8 +23,8 @@ #include "ps/CLogger.h" #include "ps/Util.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Request.h" #include "simulation2/Simulation2.h" #include "simulation2/system/LocalTurnManager.h" @@ -37,7 +37,7 @@ #include class IReplayLogger; -class ScriptInterface; +namespace Script { class Interface; } const CStr CReplayTurnManager::EventNameReplayFinished = "ReplayFinished"; const CStr CReplayTurnManager::EventNameReplayOutOfSync = "ReplayOutOfSync"; @@ -101,8 +101,8 @@ void CReplayTurnManager::NotifyFinishedUpdate(u32 turn, const UpdateCallback& se m_HasSyncError = true; LOGERROR("Replay out of sync on turn %d", turn); - const ScriptInterface& scriptInterface = m_Simulation2.GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = m_Simulation2.GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValueVector paramData(rq.cx); @@ -125,7 +125,7 @@ void CReplayTurnManager::DoTurn(u32 turn, const UpdateCallback& sendEventToAll) m_TurnLength = m_ReplayTurnLengths[turn]; - ScriptRequest rq(m_Simulation2.GetScriptInterface()); + Script::Request rq(m_Simulation2.GetScriptInterface()); // Simulate commands for that turn for (const std::pair& p : m_ReplayCommands[turn]) diff --git a/source/simulation2/system/SimContext.cpp b/source/simulation2/system/SimContext.cpp index 3c1eb8991a..a1a1142d5d 100644 --- a/source/simulation2/system/SimContext.cpp +++ b/source/simulation2/system/SimContext.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -62,7 +62,7 @@ void CSimContext::SetComponentManager(CComponentManager* man) m_ComponentManager = man; } -ScriptInterface& CSimContext::GetScriptInterface() const +Script::Interface& CSimContext::GetScriptInterface() const { return GetComponentManager().GetScriptInterface(); } diff --git a/source/simulation2/system/SimContext.h b/source/simulation2/system/SimContext.h index 2b90cd9864..6629456227 100644 --- a/source/simulation2/system/SimContext.h +++ b/source/simulation2/system/SimContext.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -24,7 +24,7 @@ class CComponentManager; class CUnitManager; class CTerrain; -class ScriptInterface; +namespace Script { class Interface; } /** * Contains pointers to various 'global' objects that are needed by the simulation code, @@ -44,7 +44,7 @@ public: CTerrain& GetTerrain() const; - ScriptInterface& GetScriptInterface() const; + Script::Interface& GetScriptInterface() const; void SetSystemEntity(CEntityHandle ent) { m_SystemEntity = ent; } CEntityHandle GetSystemEntity() const { ASSERT(m_SystemEntity.GetId() == SYSTEM_ENTITY); return m_SystemEntity; } diff --git a/source/simulation2/system/TurnManager.cpp b/source/simulation2/system/TurnManager.cpp index 54e46b6943..73e3586ac7 100644 --- a/source/simulation2/system/TurnManager.cpp +++ b/source/simulation2/system/TurnManager.cpp @@ -26,7 +26,7 @@ #include "ps/Profiler2.h" #include "ps/Replay.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "scriptinterface/StructuredClone.h" #include "simulation2/Simulation2.h" @@ -50,7 +50,7 @@ CTurnManager::CTurnManager(CSimulation2& simulation, u32 defaultTurnLength, u32 m_PlayerId(-1), m_ClientId(clientId), m_DeltaSimTime(0), m_Replay(replay), m_FinalTurn(std::numeric_limits::max()), m_TimeWarpNumTurns(0) { - ScriptRequest rq(m_Simulation2.GetScriptInterface()); + Script::Request rq(m_Simulation2.GetScriptInterface()); m_QuickSaveMetadata.init(rq.cx); m_QueuedCommands.resize(1); } @@ -229,7 +229,7 @@ void CTurnManager::AddCommand(int client, int player, JS::HandleValue data, u32 return; } - ScriptRequest rq(m_Simulation2.GetScriptInterface()); + Script::Request rq(m_Simulation2.GetScriptInterface()); Script::DeepFreezeObject(rq, data); @@ -299,7 +299,7 @@ void CTurnManager::QuickSave(JS::HandleValue GUIMetadata) m_QuickSaveState = stream.str(); - ScriptRequest rq(m_Simulation2.GetScriptInterface()); + Script::Request rq(m_Simulation2.GetScriptInterface()); m_QuickSaveMetadata.set(Script::DeepCopy(rq, GUIMetadata)); // Freeze state to ensure that consectuvie loads don't modify the state diff --git a/source/simulation2/tests/test_CmpTemplateManager.h b/source/simulation2/tests/test_CmpTemplateManager.h index 8657969891..4555b9b09b 100644 --- a/source/simulation2/tests/test_CmpTemplateManager.h +++ b/source/simulation2/tests/test_CmpTemplateManager.h @@ -26,9 +26,9 @@ #include "ps/TemplateLoader.h" #include "ps/XML/Xeromyces.h" #include "scriptinterface/JSON.h" -#include "scriptinterface/ScriptConversions.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Conversions.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpTemplateManager.h" #include "simulation2/system/Component.h" @@ -115,7 +115,7 @@ public: TS_ASSERT(tempMan != NULL); tempMan->DisableValidation(); - ScriptRequest rq(man.GetScriptInterface()); + Script::Request rq(man.GetScriptInterface()); // This is testing some bugs in the template JS object caching diff --git a/source/simulation2/tests/test_ComponentManager.h b/source/simulation2/tests/test_ComponentManager.h index c13381a22a..a72bfcd018 100644 --- a/source/simulation2/tests/test_ComponentManager.h +++ b/source/simulation2/tests/test_ComponentManager.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ #include "ps/Errors.h" #include "ps/Filesystem.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/MessageTypes.h" #include "simulation2/components/ICmpTemplateManager.h" #include "simulation2/components/ICmpTest.h" diff --git a/source/simulation2/tests/test_SerializeTemplates.h b/source/simulation2/tests/test_SerializeTemplates.h index e34bb3c4d7..88f2b274df 100644 --- a/source/simulation2/tests/test_SerializeTemplates.h +++ b/source/simulation2/tests/test_SerializeTemplates.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -18,7 +18,7 @@ #include "lib/self_test.h" #include "lib/types.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/helpers/Grid.h" #include "simulation2/serialization/DebugSerializer.h" #include "simulation2/serialization/SerializeTemplates.h" @@ -36,7 +36,7 @@ class TestSerializeTemplates : public CxxTest::TestSuite public: void test_Debug_array() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); @@ -49,7 +49,7 @@ public: void test_Debug_vector() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); @@ -62,7 +62,7 @@ public: void test_Debug_set() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); @@ -75,7 +75,7 @@ public: void test_Debug_grid() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); diff --git a/source/simulation2/tests/test_Serializer.h b/source/simulation2/tests/test_Serializer.h index 0196846cb9..4f4a1eeb34 100644 --- a/source/simulation2/tests/test_Serializer.h +++ b/source/simulation2/tests/test_Serializer.h @@ -32,9 +32,9 @@ #include "ps/Loader.h" #include "ps/XML/Xeromyces.h" #include "scriptinterface/FunctionWrapper.h" +#include "scriptinterface/Interface.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Request.h" #include "simulation2/Simulation2.h" #include "simulation2/serialization/DebugSerializer.h" #include "simulation2/serialization/HashSerializer.h" @@ -94,7 +94,7 @@ public: void test_Debug_basic() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); serialize.NumberI32_Unbounded("x", -123); @@ -105,7 +105,7 @@ public: void test_Debug_floats() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); serialize.NumberFloat_Unbounded("x", 1e4f); @@ -136,7 +136,7 @@ public: void test_Debug_types() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); @@ -167,7 +167,7 @@ public: void test_Std_basic() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CStdSerializer serialize(script, stream); @@ -194,7 +194,7 @@ public: void test_Std_types() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CStdSerializer serialize(script, stream); @@ -261,7 +261,7 @@ public: void test_Hash_basic() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); CHashSerializer serialize(script); serialize.NumberI32_Unbounded("x", -123); @@ -275,7 +275,7 @@ public: void test_Hash_stream() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); CHashSerializer hashSerialize(script); hashSerialize.NumberI32_Unbounded("x", -123); @@ -298,7 +298,7 @@ public: void test_bounds() { - ScriptInterface script("Test", "Test", g_ScriptContext); + Script::Interface script("Test", "Test", g_ScriptContext); std::stringstream stream; CDebugSerializer serialize(script, stream); serialize.NumberI32("x", 16, -16, 16); @@ -311,8 +311,8 @@ public: void helper_script_roundtrip(const char* msg, const char* input, const char* expected, size_t expstreamlen = 0, const char* expstream = NULL, const char* debug = NULL) { - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); JS::RootedValue obj(rq.cx); TSM_ASSERT(msg, script.Eval(input, &obj)); @@ -352,7 +352,7 @@ public: deserialize2.ScriptVal("script2", &newobj); std::string source; - TSM_ASSERT(msg, ScriptFunction::Call(rq, newobj, "toSource", source)); + TSM_ASSERT(msg, Script::Function::Call(rq, newobj, "toSource", source)); TS_ASSERT_STR_EQUALS(source, expected); } @@ -827,8 +827,8 @@ public: void test_script_exceptions() { - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); JS::RootedValue obj(rq.cx); @@ -862,8 +862,8 @@ public: { const char* input = "var x = {}; for (var i=0;i<256;++i) x[i]=Math.pow(i, 2); x"; - ScriptInterface script("Test", "Test", g_ScriptContext); - ScriptRequest rq(script); + Script::Interface script("Test", "Test", g_ScriptContext); + Script::Request rq(script); JS::RootedValue obj(rq.cx); TS_ASSERT(script.Eval(input, &obj)); @@ -886,7 +886,7 @@ public: if (i == 0) { std::string source; - TS_ASSERT(ScriptFunction::Call(rq, newobj, "toSource", source)); + TS_ASSERT(Script::Function::Call(rq, newobj, "toSource", source)); std::cout << source << "\n"; } } @@ -907,7 +907,7 @@ public: sim2.ResetState(); JS::RootedValue attribs(sim2.GetScriptInterface().GetGeneralJSContext()); - Script::CreateObject(ScriptRequest(sim2.GetScriptInterface()), &attribs); + Script::CreateObject(Script::Request(sim2.GetScriptInterface()), &attribs); sim2.SetInitAttributes(attribs); std::unique_ptr mapReader = std::make_unique(); diff --git a/source/simulation2/tests/test_Simulation2.h b/source/simulation2/tests/test_Simulation2.h index 8ce041f6ea..d629311589 100644 --- a/source/simulation2/tests/test_Simulation2.h +++ b/source/simulation2/tests/test_Simulation2.h @@ -24,7 +24,7 @@ #include "lib/types.h" #include "ps/Filesystem.h" #include "ps/XML/Xeromyces.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/MessageTypes.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpTest.h" diff --git a/source/soundmanager/scripting/JSInterface_Sound.cpp b/source/soundmanager/scripting/JSInterface_Sound.cpp index 66f8acdbbd..601bf6063c 100644 --- a/source/soundmanager/scripting/JSInterface_Sound.cpp +++ b/source/soundmanager/scripting/JSInterface_Sound.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -132,21 +132,21 @@ namespace JSI_Sound #endif - void RegisterScriptFunctions(const ScriptRequest& rq) + void RegisterScriptFunctions(const Script::Request& rq) { - ScriptFunction::Register<&StartMusic>(rq, "StartMusic"); - ScriptFunction::Register<&StopMusic>(rq, "StopMusic"); - ScriptFunction::Register<&ClearPlaylist>(rq, "ClearPlaylist"); - ScriptFunction::Register<&AddPlaylistItem>(rq, "AddPlaylistItem"); - ScriptFunction::Register<&StartPlaylist>(rq, "StartPlaylist"); - ScriptFunction::Register<&PlayMusic>(rq, "PlayMusic"); - ScriptFunction::Register<&PlayUISound>(rq, "PlayUISound"); - ScriptFunction::Register<&PlayAmbientSound>(rq, "PlayAmbientSound"); - ScriptFunction::Register<&MusicPlaying>(rq, "MusicPlaying"); - ScriptFunction::Register<&SetMasterGain>(rq, "SetMasterGain"); - ScriptFunction::Register<&SetMusicGain>(rq, "SetMusicGain"); - ScriptFunction::Register<&SetAmbientGain>(rq, "SetAmbientGain"); - ScriptFunction::Register<&SetActionGain>(rq, "SetActionGain"); - ScriptFunction::Register<&SetUIGain>(rq, "SetUIGain"); + Script::Function::Register<&StartMusic>(rq, "StartMusic"); + Script::Function::Register<&StopMusic>(rq, "StopMusic"); + Script::Function::Register<&ClearPlaylist>(rq, "ClearPlaylist"); + Script::Function::Register<&AddPlaylistItem>(rq, "AddPlaylistItem"); + Script::Function::Register<&StartPlaylist>(rq, "StartPlaylist"); + Script::Function::Register<&PlayMusic>(rq, "PlayMusic"); + Script::Function::Register<&PlayUISound>(rq, "PlayUISound"); + Script::Function::Register<&PlayAmbientSound>(rq, "PlayAmbientSound"); + Script::Function::Register<&MusicPlaying>(rq, "MusicPlaying"); + Script::Function::Register<&SetMasterGain>(rq, "SetMasterGain"); + Script::Function::Register<&SetMusicGain>(rq, "SetMusicGain"); + Script::Function::Register<&SetAmbientGain>(rq, "SetAmbientGain"); + Script::Function::Register<&SetActionGain>(rq, "SetActionGain"); + Script::Function::Register<&SetUIGain>(rq, "SetUIGain"); } } diff --git a/source/soundmanager/scripting/JSInterface_Sound.h b/source/soundmanager/scripting/JSInterface_Sound.h index 1cd691543a..a543dc3653 100644 --- a/source/soundmanager/scripting/JSInterface_Sound.h +++ b/source/soundmanager/scripting/JSInterface_Sound.h @@ -1,4 +1,4 @@ -/* Copyright (C) 2018 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -19,11 +19,11 @@ #ifndef INCLUDED_SOUNDSCRIPTINTERFACE #define INCLUDED_SOUNDSCRIPTINTERFACE -class ScriptRequest; +namespace Script { class Request; } namespace JSI_Sound { - void RegisterScriptFunctions(const ScriptRequest& rq); + void RegisterScriptFunctions(const Script::Request& rq); } #endif // INCLUDED_SOUNDSCRIPTINTERFACE diff --git a/source/soundmanager/scripting/SoundGroup.cpp b/source/soundmanager/scripting/SoundGroup.cpp index 061019f54f..1ea41ed470 100644 --- a/source/soundmanager/scripting/SoundGroup.cpp +++ b/source/soundmanager/scripting/SoundGroup.cpp @@ -48,7 +48,7 @@ extern CGame *g_Game; #include "maths/Vector3D.h" #include "ps/Errors.h" #include "ps/XMB/XMBData.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "soundmanager/ISoundManager.h" #include "soundmanager/data/SoundData.h" diff --git a/source/test_setup.cpp b/source/test_setup.cpp index c12e5f1973..399a63cb17 100644 --- a/source/test_setup.cpp +++ b/source/test_setup.cpp @@ -39,10 +39,10 @@ #include "ps/TaskManager.h" #include "ps/ThreadUtil.h" #include "scriptinterface/FunctionWrapper.h" -#include "scriptinterface/ScriptContext.h" -#include "scriptinterface/ScriptEngine.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Context.h" +#include "scriptinterface/Engine.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include #include @@ -84,8 +84,8 @@ class MiscSetup : public CxxTest::GlobalFixture Threading::SetMainThread(); g_Profiler2.Initialise(); - m_ScriptEngine = new ScriptEngine; - g_ScriptContext = std::make_shared(); + m_ScriptEngine = new Script::Engine; + g_ScriptContext = std::make_shared(); taskManager.emplace(); @@ -112,9 +112,9 @@ class MiscSetup : public CxxTest::GlobalFixture private: - // We're doing the initialization and shutdown of the ScriptEngine explicitly here + // We're doing the initialization and shutdown of the Script::Engine explicitly here // to make sure it's only initialized when setUpWorld is called. - ScriptEngine* m_ScriptEngine; + Script::Engine* m_ScriptEngine; std::optional taskManager; }; @@ -152,10 +152,10 @@ namespace } } -void ScriptTestSetup(const ScriptInterface& scriptInterface) +void ScriptTestSetup(const Script::Interface& scriptInterface) { - ScriptRequest rq(scriptInterface); - ScriptFunction::Register(rq, "TS_FAIL"); + Script::Request rq(scriptInterface); + Script::Function::Register(rq, "TS_FAIL"); // Load the TS_* function definitions // (We don't use VFS because tests might not have the normal VFS paths loaded) diff --git a/source/tools/atlas/GameInterface/ActorViewer.cpp b/source/tools/atlas/GameInterface/ActorViewer.cpp index 7882172ff3..e8086988ac 100644 --- a/source/tools/atlas/GameInterface/ActorViewer.cpp +++ b/source/tools/atlas/GameInterface/ActorViewer.cpp @@ -60,7 +60,7 @@ #include "renderer/backend/IDeviceCommandContext.h" #include "renderer/backend/IFramebuffer.h" #include "renderer/backend/ISwapChain.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpAttack.h" #include "simulation2/components/ICmpOwnership.h" diff --git a/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp index 2f91d8981a..339aa8d9d6 100644 --- a/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp @@ -34,8 +34,8 @@ #include "ps/VideoMode.h" #include "renderer/Renderer.h" #include "renderer/SceneRenderer.h" -#include "scriptinterface/ScriptForward.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/ForwardDeclarations.h" +#include "scriptinterface/Interface.h" #include "tools/atlas/GameInterface/ActorViewer.h" #include "tools/atlas/GameInterface/CommandProc.h" #include "tools/atlas/GameInterface/GameLoop.h" @@ -74,7 +74,7 @@ const int g_InitFlags = INIT_HAVE_VMODE | INIT_NO_GUI; // This isn't used directly. When it's emplaced and when it's reset it does mutate `g_Logger`. std::optional g_FileLogger; -std::optional g_ScriptInterface; +std::optional g_ScriptInterface; std::unique_ptr g_InputHandlers; } diff --git a/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp index 539101eff8..f05e2b905d 100644 --- a/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/MapHandlers.cpp @@ -52,8 +52,8 @@ #include "renderer/WaterManager.h" #include "scriptinterface/JSON.h" #include "scriptinterface/Object.h" -#include "scriptinterface/ScriptInterface.h" -#include "scriptinterface/ScriptRequest.h" +#include "scriptinterface/Interface.h" +#include "scriptinterface/Request.h" #include "simulation2/Simulation2.h" #include "simulation2/components/ICmpOwnership.h" #include "simulation2/components/ICmpPosition.h" @@ -132,8 +132,8 @@ QUERYHANDLER(GenerateMap) InitGame(); // Random map - const ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + Script::Request rq(scriptInterface); JS::RootedValue settings(rq.cx); Script::ParseJSON(rq, *msg->settings, &settings); @@ -160,8 +160,8 @@ QUERYHANDLER(GenerateMap) InitGame(); - const ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + Script::Request rq(scriptInterface); // Set up 8-element array of empty objects to satisfy init JS::RootedValueArray<8> playerData{rq.cx}; @@ -199,8 +199,8 @@ MESSAGEHANDLER(LoadMap) { InitGame(); - const ScriptInterface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); - ScriptRequest rq(scriptInterface); + const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface(); + Script::Request rq(scriptInterface); // Scenario CStrW map = *msg->filename; diff --git a/source/tools/atlas/GameInterface/Handlers/MiscHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/MiscHandlers.cpp index 6a63679b20..6a2a9e9a80 100644 --- a/source/tools/atlas/GameInterface/Handlers/MiscHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/MiscHandlers.cpp @@ -30,7 +30,7 @@ #include "ps/Input.h" #include "ps/VideoMode.h" #include "renderer/Renderer.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/components/ICmpSoundManager.h" #include "simulation2/system/Component.h" #include "simulation2/system/Entity.h" diff --git a/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp b/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp index 58aa7684ee..6d884db7b9 100644 --- a/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp +++ b/source/tools/atlas/GameInterface/Handlers/TerrainHandlers.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2025 Wildfire Games. +/* Copyright (C) 2026 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -38,7 +38,7 @@ #include "ps/Game.h" #include "ps/World.h" #include "renderer/Renderer.h" -#include "scriptinterface/ScriptInterface.h" +#include "scriptinterface/Interface.h" #include "simulation2/components/ICmpPathfinder.h" #include "simulation2/helpers/Grid.h" #include "simulation2/helpers/Pathfinding.h" diff --git a/source/tools/lint/cppcheck/suppressions-list.txt b/source/tools/lint/cppcheck/suppressions-list.txt index 34f05f8d81..04c8353970 100644 --- a/source/tools/lint/cppcheck/suppressions-list.txt +++ b/source/tools/lint/cppcheck/suppressions-list.txt @@ -8,7 +8,7 @@ cppcheckError:./source/lib/file/file_system.cpp // Ignore SpiderMonkey version compile check -preprocessorErrorDirective:source/scriptinterface/ScriptEngine.h +preprocessorErrorDirective:source/scriptinterface/Engine.h // Lists of network/simulation messages are included in other files which define macros @@ -69,3 +69,7 @@ uninitvar:source/ps/Game.cpp:246 uninitvar:source/ps/scripting/JSInterface_SavedGame.cpp:149 danglingLifetime:source/renderer/backend/gl/Device.cpp + +uninitvar:source/gui/Scripting/JSInterface_GUISize.cpp +nullPointer:source/ps/scripting/JSInterface_Debug.cpp +unknownMacro:source/dapinterface/tests/test_DapInterface.h