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 29 34.5 %
Date: 2023-01-19 00:18:29 Functions: 16 65 24.6 %

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

Generated by: LCOV version 1.13