LCOV - code coverage report
Current view: top level - source/gui/Scripting - JSInterface_GUIProxy.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 10 25 40.0 %
Date: 2026-12-03 01:19:39 Functions: 7 56 12.5 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #ifndef INCLUDED_JSI_GUIPROXY
      19             : #define INCLUDED_JSI_GUIPROXY
      20             : 
      21             : #include "gui/ObjectBases/IGUIObject.h"
      22             : #include "lib/sysdep/compiler.h"
      23             : 
      24             : #include <js/GCVector.h>
      25             : #include <js/Id.h>
      26             : #include <js/PropertyDescriptor.h>
      27             : #include <js/Proxy.h>
      28             : #include <js/RootingAPI.h>
      29             : #include <js/TypeDecls.h>
      30             : #include <js/Value.h>
      31             : #include <memory>
      32             : #include <string>
      33             : #include <string_view>
      34             : #include <utility>
      35             : #include <vector>
      36             : 
      37             : class JSFunction;
      38             : class JSObject;
      39             : namespace JS { class CallArgs; }
      40             : namespace Script { class Interface; }
      41             : namespace Script { class Request; }
      42             : 
      43             : // See JSI_GuiProxy below
      44             : #if GCC_VERSION
      45             : # pragma GCC diagnostic push
      46             : # pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
      47             : #elif MSC_VERSION
      48             : # pragma warning(push, 1)
      49             : # pragma warning(disable: 4265)
      50             : #endif
      51             : 
      52             : /**
      53             :  * JS GUI proxies need to store some private data.
      54             :  * This class is responsible for deleting that data.
      55             :  */
      56          10 : class IGUIProxyObject final
      57             : {
      58             :     template<typename T>
      59             :     friend class JSI_GUIProxy;
      60             :     friend std::unique_ptr<IGUIProxyObject> std::make_unique<IGUIProxyObject>();
      61             : public:
      62          10 :     JSObject* Get() const
      63             :     {
      64           4 :         return m_Object.get();
      65             :     }
      66             : 
      67             :     using PrivateData = IGUIObject*;
      68             : 
      69             :     template<typename T>
      70           0 :     static T* FromPrivateSlot(JSObject* obj)
      71             :     {
      72           0 :         return static_cast<T*>(FromPrivateSlot<IGUIObject>(obj));
      73             :     }
      74             : protected:
      75             :     template<typename T>
      76          15 :     static T* UnsafeFromPrivateSlot(JSObject* obj)
      77             :     {
      78          15 :         return static_cast<T*>(static_cast<PrivateData>(js::GetProxyPrivate(obj).toPrivate()));
      79             :     }
      80             : 
      81           5 :     IGUIProxyObject() = default;
      82             :     IGUIProxyObject(const IGUIProxyObject&) = delete;
      83             :     IGUIProxyObject(IGUIProxyObject&&) = delete;
      84             : 
      85             :     JS::PersistentRootedObject m_Object;
      86             :     PrivateData m_Ptr;
      87             : };
      88             : // Declare the IGUIObject* specialization - it's defined in _impl.h
      89             : template<> IGUIObject* IGUIProxyObject::FromPrivateSlot<IGUIObject>(JSObject*);
      90             : 
      91             : /**
      92             :  * Proxies need to store some data whose lifetime is tied to an interface.
      93             :  * This is the virtual interface of that data.
      94             :  */
      95         133 : class GUIProxyProps
      96             : {
      97             : public:
      98         133 :     virtual ~GUIProxyProps() {};
      99             : 
     100             :     // @return true if @param name exists in this cache.
     101             :     virtual bool has(const std::string& name) const = 0;
     102             :     // @return the JSFunction matching @param name. Must call has() first as it can assume existence.
     103             :     virtual JSObject* get(const std::string& name) const = 0;
     104             :     virtual bool setFunction(const Script::Request& rq, const std::string& name, JSFunction* function) = 0;
     105             :     virtual std::vector<std::string_view> getPropsNames() const = 0;
     106             : };
     107             : 
     108             : /**
     109             :  * Handles the js interface with C++ GUI objects.
     110             :  * Proxy handlers must live for at least as long as the JS runtime
     111             :  * where a proxy object with that handler was created. The reason is that
     112             :  * proxy handlers are called during GC, such as on runtime destruction.
     113             :  * In practical terms, this means "just keep them static and store no data".
     114             :  *
     115             :  * GUI Objects only exist in C++ and have no JS-only properties.
     116             :  * As such, there is no "target" JS object that this proxy could point to,
     117             :  * and thus we should inherit from BaseProxyHandler and not js::Wrapper.
     118             :  *
     119             :  * Proxies can be used with prototypes and almost treated like regular JS objects.
     120             :  * However, the default implementation embarks a lot of code that we don't really need here,
     121             :  * since the only fanciness is that we cache JSFunction* properties.
     122             :  * As such, these GUI proxies don't have one and instead override get/set directly.
     123             :  *
     124             :  * To add a new JSI_GUIProxy, you'll need to:
     125             :  *  - overload CreateJSObject in your class header.
     126             :  *  - change the CGUI::AddObjectTypes method.
     127             :  *  - explicitly instantiate the template & CreateJSObject via DECLARE_GUIPROXY.
     128             :  *
     129             :  */
     130             : template<typename GUIObjectType>
     131             : class JSI_GUIProxy : public js::BaseProxyHandler
     132             : {
     133             :     // Need to friend other specializations so CreateFunctions() can call the IGUIObject version in all codepaths.
     134             :     template<typename T>
     135             :     friend class JSI_GUIProxy;
     136             : public:
     137             :     // For convenience, this is the single instantiated JSI_GUIProxy.
     138             :     static JSI_GUIProxy& Singleton();
     139             : 
     140             :     // Call this in CGUI::AddObjectTypes.
     141             :     static std::pair<const js::BaseProxyHandler*, GUIProxyProps*> CreateData(Script::Interface& scriptInterface);
     142             : 
     143             :     // Create the JS object, the proxy, the data and wrap it in a convenient unique_ptr.
     144             :     static std::unique_ptr<IGUIProxyObject> CreateJSObject(const Script::Request& rq, GUIObjectType* ptr, GUIProxyProps* data);
     145             : protected:
     146             :     // @param family can't be nullptr because that's used for some DOM object and it crashes.
     147           7 :     JSI_GUIProxy() : BaseProxyHandler(this, false, false) {};
     148             : 
     149             :     // Note: SM provides no virtual destructor for baseProxyHandler.
     150             :     // This also enforces making proxy handlers dataless static variables.
     151           7 :     ~JSI_GUIProxy() {};
     152             : 
     153             :     static GUIObjectType* FromPrivateSlot(const Script::Request&, JS::CallArgs& args);
     154             : 
     155             :     // The default implementations need to know the type of the GUIProxyProps for this proxy type.
     156             :     // This is done by specializing this struct's alias type.
     157             :     struct PropCache;
     158             : 
     159             :     // Specialize this to define the custom properties of this type.
     160             :     static void CreateFunctions(const Script::Request& rq, GUIProxyProps* cache);
     161             : 
     162             :     // Convenience helper for the above.
     163             :     template<auto callable>
     164             :     static void CreateFunction(const Script::Request& rq, GUIProxyProps* cache, const std::string& name);
     165             : 
     166             :     // This handles returning custom properties. Specialize this if needed.
     167             :     bool PropGetter(JS::HandleObject proxy, const std::string& propName, JS::MutableHandleValue vp) const;
     168             : protected:
     169             :     // BaseProxyHandler interface below
     170             : 
     171             :     // Handler for `object.x`
     172             :     bool get(JSContext* cx, JS::HandleObject proxy, JS::HandleValue receiver, JS::HandleId id, JS::MutableHandleValue vp) const final;
     173             :     // Handler for `object.x = y;`
     174             :     bool set(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, JS::HandleValue vp,
     175             :                      JS::HandleValue receiver, JS::ObjectOpResult& result) const final;
     176             :     // Handler for `delete object.x;`
     177             :     bool delete_(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, JS::ObjectOpResult& result) const final;
     178             : 
     179             :     // The following methods are not provided by BaseProxyHandler.
     180             :     // We provide defaults that do nothing (some raise JS exceptions).
     181             : 
     182             :     bool getOwnPropertyDescriptor(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc) const final;
     183             : 
     184             :     // Throw an exception is JS code attempts defining a property.
     185           0 :     bool defineProperty(JSContext*, JS::HandleObject /*proxy*/, JS::HandleId,
     186             :         JS::Handle<JS::PropertyDescriptor>, JS::ObjectOpResult& /*result*/) const override
     187             :     {
     188           0 :         return false;
     189             :     }
     190             : 
     191             :     bool ownPropertyKeys(JSContext* cx, JS::HandleObject proxy, JS::MutableHandleIdVector props) const final;
     192             : 
     193             :     // Nothing to enumerate.
     194           0 :     bool enumerate(JSContext*, JS::HandleObject /*proxy*/,
     195             :         JS::MutableHandleIdVector /*props*/) const override
     196             :     {
     197           0 :         return true;
     198             :     }
     199             :     // Throw an exception is JS attempts to query the prototype.
     200           0 :     bool getPrototypeIfOrdinary(JSContext*, JS::HandleObject /*proxy*/, bool* /*isOrdinary*/,
     201             :         JS::MutableHandleObject /*protop*/) const override
     202             :     {
     203           0 :         return false;
     204             :     }
     205             :     // Throw an exception - no prototype to set.
     206           0 :     bool setImmutablePrototype(JSContext*, JS::HandleObject /*proxy*/,
     207             :         bool* /*succeeded*/) const override
     208             :     {
     209           0 :         return false;
     210             :     }
     211             :     // We are not extensible.
     212           0 :     bool preventExtensions(JSContext*, JS::HandleObject /*proxy*/,
     213             :         JS::ObjectOpResult& /*result*/) const override
     214             :     {
     215           0 :         return true;
     216             :     }
     217           0 :     bool isExtensible(JSContext*, JS::HandleObject /*proxy*/, bool* extensible) const override
     218             :     {
     219           0 :         *extensible = false;
     220           0 :         return true;
     221             :     }
     222             : };
     223             : 
     224             : #if GCC_VERSION
     225             : # pragma GCC diagnostic pop
     226             : #elif MSC_VERSION
     227             : # pragma warning(pop)
     228             : #endif
     229             : 
     230             : 
     231             : #endif // INCLUDED_JSI_GUIPROXY

Generated by: LCOV version 1.16