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 : // This file is included directly into actual implementation files.
19 :
20 : #include "JSInterface_GUIProxy.h"
21 :
22 : #include "gui/CGUI.h"
23 : #include "gui/ObjectBases/IGUIObject.h"
24 : #include "ps/CLogger.h"
25 : #include "ps/CStr.h"
26 : #include "scriptinterface/FunctionWrapper.h"
27 : #include "scriptinterface/Object.h"
28 : #include "scriptinterface/Conversions.h"
29 : #include "scriptinterface/Request.h"
30 :
31 : #include <js/CallAndConstruct.h>
32 : #include <js/CallArgs.h>
33 : #include <js/Class.h>
34 : #include <js/Object.h>
35 : #include <js/Proxy.h>
36 : #include <js/RootingAPI.h>
37 : #include <js/TypeDecls.h>
38 : #include <js/Value.h>
39 : #include <js/friend/ErrorMessages.h>
40 : #include <jsapi.h>
41 : #include <jspubtd.h>
42 : #include <map>
43 : #include <memory>
44 : #include <cstddef>
45 : #include <string>
46 : #include <string_view>
47 : #include <type_traits>
48 : #include <unordered_map>
49 : #include <utility>
50 :
51 : class JSObject;
52 : namespace Script { class Interface; }
53 :
54 : #ifndef INCLUDED_JSI_GUIPROXY_IMP
55 : #define INCLUDED_JSI_GUIPROXY_IMP
56 :
57 : template <typename T>
58 143 : JSI_GUIProxy<T>& JSI_GUIProxy<T>::Singleton()
59 : {
60 143 : static JSI_GUIProxy<T> s;
61 143 : return s;
62 : }
63 :
64 : // Call this for every specialised type. You will need to override IGUIObject::CreateJSObject() in your class interface.
65 : #define DECLARE_GUIPROXY(Type) \
66 : void Type::CreateJSObject() \
67 : { \
68 : Script::Request rq(m_pGUI.GetScriptInterface()); \
69 : using ProxyHandler = JSI_GUIProxy<std::remove_pointer_t<decltype(this)>>; \
70 : m_JSObject = ProxyHandler::CreateJSObject(rq, this, GetGUI().GetProxyData(&ProxyHandler::Singleton())); \
71 : } \
72 : template class JSI_GUIProxy<Type>;
73 :
74 : // Use a common namespace to avoid duplicating the symbols un-necessarily.
75 : namespace JSInterface_GUIProxy
76 : {
77 : // All proxy objects share a class definition.
78 19 : JSClass& ClassDefinition()
79 : {
80 19 : static JSClass c = PROXY_CLASS_DEF("GUIObjectProxy", JSCLASS_HAS_CACHED_PROTO(JSProto_Proxy) | JSCLASS_HAS_RESERVED_SLOTS(1));
81 14 : return c;
82 : }
83 :
84 : // Default implementation of the cache via unordered_map
85 133 : class MapCache : public GUIProxyProps
86 : {
87 : public:
88 133 : virtual ~MapCache() {};
89 :
90 4 : bool has(const std::string& name) const override
91 : {
92 4 : return m_Functions.find(name) != m_Functions.end();
93 : }
94 :
95 1 : JSObject* get(const std::string& name) const override
96 : {
97 1 : return m_Functions.at(name).get();
98 : }
99 :
100 817 : bool setFunction(const Script::Request& rq, const std::string& name, JSFunction* function) override
101 : {
102 817 : m_Functions[name].init(rq.cx, JS_GetFunctionObject(function));
103 817 : return true;
104 : }
105 :
106 0 : std::vector<std::string_view> getPropsNames() const override
107 : {
108 0 : std::vector<std::string_view> result;
109 0 : result.reserve(m_Functions.size());
110 :
111 0 : for (const auto& [key, value] : m_Functions)
112 0 : result.emplace_back(key);
113 :
114 0 : return result;
115 0 : }
116 :
117 : protected:
118 : std::unordered_map<std::string, JS::PersistentRootedObject> m_Functions;
119 : };
120 : }
121 :
122 : template<>
123 14 : IGUIObject* IGUIProxyObject::FromPrivateSlot<IGUIObject>(JSObject* obj)
124 : {
125 0 : if (!obj)
126 : return nullptr;
127 14 : if (JS::GetClass(obj) != &JSInterface_GUIProxy::ClassDefinition())
128 : return nullptr;
129 14 : return UnsafeFromPrivateSlot<IGUIObject>(obj);
130 : }
131 :
132 : // The default propcache is a MapCache.
133 : template<typename T>
134 : struct JSI_GUIProxy<T>::PropCache
135 : {
136 : using type = JSInterface_GUIProxy::MapCache;
137 : };
138 :
139 : template <typename T>
140 1 : T* JSI_GUIProxy<T>::FromPrivateSlot(const Script::Request&, JS::CallArgs& args)
141 : {
142 : // Call the unsafe version - this is only ever called from actual proxy objects.
143 1 : return IGUIProxyObject::UnsafeFromPrivateSlot<T>(args.thisv().toObjectOrNull());
144 : }
145 :
146 : template <typename T>
147 4 : bool JSI_GUIProxy<T>::PropGetter(JS::HandleObject proxy, const std::string& propName, JS::MutableHandleValue vp) const
148 : {
149 : using PropertyCache = typename PropCache::type;
150 : // Since we know at compile time what the type actually is, avoid the virtual call.
151 4 : const PropertyCache* data = static_cast<const PropertyCache*>(static_cast<const GUIProxyProps*>(js::GetProxyReservedSlot(proxy, 0).toPrivate()));
152 4 : if (data->has(propName))
153 : {
154 1 : vp.setObjectOrNull(data->get(propName));
155 1 : return true;
156 : }
157 : return false;
158 : }
159 :
160 : template <typename T>
161 133 : std::pair<const js::BaseProxyHandler*, GUIProxyProps*> JSI_GUIProxy<T>::CreateData(Script::Interface& scriptInterface)
162 : {
163 : using PropertyCache = typename PropCache::type;
164 133 : PropertyCache* data = new PropertyCache();
165 133 : Script::Request rq(scriptInterface);
166 :
167 : // Functions common to all children of IGUIObject.
168 133 : JSI_GUIProxy<IGUIObject>::CreateFunctions(rq, data);
169 :
170 : // Let derived classes register their own interface.
171 : if constexpr (!std::is_same_v<T, IGUIObject>)
172 114 : CreateFunctions(rq, data);
173 133 : return { &Singleton(), data };
174 133 : }
175 :
176 : template<typename T>
177 : template<auto callable>
178 817 : void JSI_GUIProxy<T>::CreateFunction(const Script::Request& rq, GUIProxyProps* cache, const std::string& name)
179 : {
180 817 : cache->setFunction(rq, name, Script::Function::Create<callable, FromPrivateSlot>(rq, name.c_str()));
181 817 : }
182 :
183 : template<typename T>
184 5 : std::unique_ptr<IGUIProxyObject> JSI_GUIProxy<T>::CreateJSObject(const Script::Request& rq, T* ptr, GUIProxyProps* dataPtr)
185 : {
186 5 : js::ProxyOptions options;
187 5 : options.setClass(&JSInterface_GUIProxy::ClassDefinition());
188 :
189 5 : auto ret = std::make_unique<IGUIProxyObject>();
190 5 : ret->m_Ptr = static_cast<IGUIObject*>(ptr);
191 :
192 5 : JS::RootedValue cppObj(rq.cx), data(rq.cx);
193 5 : cppObj.get().setPrivate(ret->m_Ptr);
194 5 : data.get().setPrivate(static_cast<void*>(dataPtr));
195 10 : ret->m_Object.init(rq.cx, js::NewProxyObject(rq.cx, &Singleton(), cppObj, nullptr, options));
196 10 : js::SetProxyReservedSlot(ret->m_Object, 0, data);
197 5 : return ret;
198 5 : }
199 :
200 : template <typename T>
201 4 : bool JSI_GUIProxy<T>::get(JSContext* cx, JS::HandleObject proxy, JS::HandleValue /*receiver*/,
202 : JS::HandleId id, JS::MutableHandleValue vp) const
203 : {
204 4 : Script::Request rq(cx);
205 :
206 4 : T* e = IGUIProxyObject::FromPrivateSlot<T>(proxy.get());
207 4 : if (!e)
208 : return false;
209 :
210 4 : JS::RootedValue idval(rq.cx);
211 4 : if (!JS_IdToValue(rq.cx, id, &idval))
212 : return false;
213 :
214 4 : std::string propName;
215 4 : if (!Script::FromJSVal(rq, idval, propName))
216 : return false;
217 :
218 : // Return function properties. Specializable.
219 4 : if (PropGetter(proxy, propName, vp))
220 : return true;
221 :
222 : // Use onWhatever to access event handlers
223 3 : if (propName.substr(0, 2) == "on")
224 : {
225 0 : CStr eventName(propName.substr(2));
226 0 : std::map<CStr, JS::Heap<JSObject*>>::iterator it = e->m_ScriptHandlers.find(eventName);
227 0 : if (it == e->m_ScriptHandlers.end())
228 0 : vp.setNull();
229 : else
230 0 : vp.setObject(*it->second.get());
231 0 : return true;
232 0 : }
233 :
234 3 : if (propName == "parent")
235 : {
236 0 : IGUIObject* parent = e->GetParent();
237 :
238 0 : if (parent)
239 0 : vp.set(JS::ObjectValue(*parent->GetJSObject()));
240 : else
241 0 : vp.set(JS::NullValue());
242 :
243 0 : return true;
244 : }
245 3 : else if (propName == "children")
246 : {
247 0 : JS::RootedValueVector children{rq.cx};
248 :
249 0 : for (const auto& child : e->m_Children)
250 : {
251 0 : JS::RootedValue rootedChild{rq.cx};
252 0 : Script::ToJSVal(rq, &rootedChild, child);
253 0 : if (!children.append(rootedChild))
254 0 : throw std::runtime_error{"Append failed"};
255 : }
256 0 : vp.set(JS::ObjectValue(*JS::NewArrayObject(rq.cx, children)));
257 0 : return true;
258 0 : }
259 3 : else if (propName == "name")
260 : {
261 0 : Script::ToJSVal(rq, vp, e->GetName());
262 : return true;
263 : }
264 6 : else if (e->SettingExists(propName))
265 : {
266 6 : e->m_Settings[propName]->ToJSVal(rq, vp);
267 3 : return true;
268 : }
269 :
270 0 : LOGERROR("Property '{}' does not exist!", propName);
271 0 : return false;
272 4 : }
273 :
274 :
275 : template <typename T>
276 6 : bool JSI_GUIProxy<T>::set(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, JS::HandleValue vp,
277 : JS::HandleValue /*receiver*/, JS::ObjectOpResult& result) const
278 : {
279 6 : T* e = IGUIProxyObject::FromPrivateSlot<T>(proxy.get());
280 6 : if (!e)
281 : {
282 0 : LOGERROR("C++ GUI Object could not be found");
283 0 : return result.fail(JSMSG_OBJECT_REQUIRED);
284 : }
285 :
286 6 : Script::Request rq(cx);
287 :
288 6 : JS::RootedValue idval(rq.cx);
289 6 : if (!JS_IdToValue(rq.cx, id, &idval))
290 0 : return result.fail(JSMSG_BAD_PROP_ID);
291 :
292 6 : std::string propName;
293 6 : if (!Script::FromJSVal(rq, idval, propName))
294 0 : return result.fail(JSMSG_BAD_PROP_ID);
295 :
296 6 : if (propName == "name")
297 : {
298 0 : std::string value;
299 0 : if (!Script::FromJSVal(rq, vp, value))
300 0 : return result.fail(JSMSG_BAD_PROP_ID);
301 0 : e->SetName(value);
302 0 : return result.succeed();
303 0 : }
304 :
305 6 : JS::RootedObject vpObj(cx);
306 6 : if (vp.isObject())
307 6 : vpObj = &vp.toObject();
308 :
309 : // Use onWhatever to set event handlers
310 6 : if (propName.substr(0, 2) == "on")
311 : {
312 5 : if (vp.isPrimitive() || vp.isNull() || !JS::IsCallable(&vp.toObject()))
313 : {
314 0 : LOGERROR("on- event-handlers must be functions");
315 0 : return result.fail(JSMSG_NOT_FUNCTION);
316 : }
317 :
318 10 : CStr eventName(propName.substr(2));
319 5 : e->SetScriptHandler(eventName, vpObj);
320 :
321 5 : return result.succeed();
322 5 : }
323 :
324 2 : if (e->SettingExists(propName))
325 2 : return e->m_Settings[propName]->FromJSVal(rq, vp, true) ? result.succeed() : result.fail(JSMSG_USER_DEFINED_ERROR);
326 :
327 0 : LOGERROR("Property '{}' does not exist!", propName);
328 0 : return result.fail(JSMSG_BAD_PROP_ID);
329 12 : }
330 :
331 : template<typename T>
332 4 : bool JSI_GUIProxy<T>::delete_(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, JS::ObjectOpResult& result) const
333 : {
334 4 : T* e = IGUIProxyObject::FromPrivateSlot<T>(proxy.get());
335 4 : if (!e)
336 : {
337 0 : LOGERROR("C++ GUI Object could not be found");
338 0 : return result.fail(JSMSG_OBJECT_REQUIRED);
339 : }
340 :
341 4 : Script::Request rq(cx);
342 :
343 4 : JS::RootedValue idval(rq.cx);
344 4 : if (!JS_IdToValue(rq.cx, id, &idval))
345 0 : return result.fail(JSMSG_BAD_PROP_ID);
346 :
347 4 : std::string propName;
348 4 : if (!Script::FromJSVal(rq, idval, propName))
349 0 : return result.fail(JSMSG_BAD_PROP_ID);
350 :
351 : // event handlers
352 4 : if (std::string_view{propName}.substr(0, 2) == "on")
353 : {
354 8 : CStr eventName(propName.substr(2));
355 4 : e->UnsetScriptHandler(eventName);
356 4 : return result.succeed();
357 4 : }
358 :
359 0 : LOGERROR("Only event handlers can be deleted from GUI objects!");
360 0 : return result.fail(JSMSG_BAD_PROP_ID);
361 4 : }
362 :
363 : template<typename T>
364 0 : bool JSI_GUIProxy<T>::ownPropertyKeys(JSContext* cx, JS::HandleObject proxy, JS::MutableHandleIdVector props) const
365 : {
366 0 : Script::Request rq(cx);
367 :
368 0 : T* e = IGUIProxyObject::FromPrivateSlot<T>(proxy.get());
369 0 : if (!e)
370 : return false;
371 :
372 : // Add common properties.
373 : static constexpr std::array<const char*, 3> keys = {
374 : "name",
375 : "parent",
376 : "children"
377 : };
378 :
379 0 : for (const char* key : keys)
380 : {
381 0 : JS::RootedString str(cx, JS_NewStringCopyZ(cx, key));
382 0 : if (!str)
383 : return false;
384 :
385 0 : JS::RootedId id(cx);
386 0 : if (!JS_StringToId(cx, str, &id))
387 : return false;
388 :
389 0 : if (!props.append(id))
390 : return false;
391 : }
392 :
393 : // Add settings.
394 0 : for (const auto& [name, setting] : e->m_Settings)
395 : {
396 0 : JS::RootedString str(cx, JS_NewStringCopyZ(cx, name.c_str()));
397 0 : JS::RootedId id(cx);
398 0 : if (!str || !JS_StringToId(cx, str, &id) || !props.append(id))
399 0 : return false;
400 : }
401 :
402 : // Add script handlers.
403 0 : for (const auto& [name, scriptHandler] : e->m_ScriptHandlers)
404 : {
405 0 : JS::RootedString str(cx, JS_NewStringCopyZ(cx, fmt::format("on{}", name).c_str()));
406 0 : JS::RootedId id(cx);
407 0 : if (!str || !JS_StringToId(cx, str, &id) || !props.append(id))
408 0 : return false;
409 : }
410 :
411 : // Add properties from the cache.
412 : using PropertyCache = typename PropCache::type;
413 0 : const PropertyCache* data = static_cast<const PropertyCache*>(static_cast<const GUIProxyProps*>(js::GetProxyReservedSlot(proxy, 0).toPrivate()));
414 0 : for (const auto& key : data->getPropsNames()) {
415 0 : JS::RootedString str(cx, JS_NewStringCopyZ(cx, key.data()));
416 0 : JS::RootedId id(cx);
417 0 : if (!str || !JS_StringToId(cx, str, &id) || !props.append(id))
418 0 : return false;
419 : }
420 :
421 0 : return true;
422 0 : }
423 :
424 : template<typename T>
425 0 : bool JSI_GUIProxy<T>::getOwnPropertyDescriptor(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc) const
426 : {
427 0 : JS::RootedValue value(cx);
428 :
429 0 : if (!this->get(cx, proxy, JS::UndefinedHandleValue, id, &value))
430 : return false;
431 :
432 0 : if (value.isUndefined())
433 : {
434 0 : desc.set(mozilla::Nothing());
435 0 : return true;
436 : }
437 :
438 0 : desc.set(mozilla::Some(JS::PropertyDescriptor::Data(value, JSPROP_ENUMERATE | JSPROP_READONLY)));
439 0 : return true;
440 0 : }
441 : #endif // INCLUDED_JSI_GUIPROXY_IMP
|