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 : #include "precompiled.h"
19 :
20 : #include "IGUIObject.h"
21 :
22 : #include "gui/CGUI.h"
23 : #include "gui/CGUISetting.h"
24 : #include "gui/SGUIStyle.h"
25 : #include "gui/Scripting/JSInterface_GUIProxy.h"
26 : #include "js/Conversions.h"
27 : #include "lib/debug.h"
28 : #include "lib/secure_crt.h"
29 : #include "maths/Size2D.h"
30 : #include "maths/Vector2D.h"
31 : #include "ps/CLogger.h"
32 : #include "ps/Profiler2.h"
33 : #include "scriptinterface/Object.h"
34 : #include "scriptinterface/Interface.h"
35 : #include "soundmanager/ISoundManager.h"
36 :
37 : #include <algorithm>
38 : #include <js/CallAndConstruct.h>
39 : #include <js/ComparisonOperators.h>
40 : #include <js/CompilationAndEvaluation.h>
41 : #include <js/CompileOptions.h>
42 : #include <js/EnvironmentChain.h>
43 : #include <js/GCAPI.h>
44 : #include <js/GCVector.h>
45 : #include <js/SourceText.h>
46 : #include <js/TracingAPI.h>
47 : #include <js/Value.h>
48 : #include <jsapi.h>
49 : #include <string>
50 : #include <string_view>
51 : #include <tuple>
52 : #include <unordered_map>
53 : #include <utility>
54 :
55 : class JSObject;
56 : namespace mozilla { union Utf8Unit; }
57 :
58 : const CStr IGUIObject::EventNameMouseEnter = "MouseEnter";
59 : const CStr IGUIObject::EventNameMouseMove = "MouseMove";
60 : const CStr IGUIObject::EventNameMouseLeave = "MouseLeave";
61 :
62 32 : IGUIObject::IGUIObject(CGUI& pGUI)
63 32 : : m_pGUI(pGUI),
64 32 : m_pParent(),
65 32 : m_MouseHovering(),
66 224 : m_LastClickTime(),
67 32 : m_Enabled(this, "enabled", true),
68 32 : m_Hidden(this, "hidden", false),
69 32 : m_Size(this, "size"),
70 32 : m_Style(this, "style"),
71 32 : m_Hotkey(this, "hotkey"),
72 32 : m_Z(this, "z"),
73 32 : m_Absolute(this, "absolute", true),
74 32 : m_Ghost(this, "ghost", false),
75 32 : m_AspectRatio(this, "aspectratio"),
76 32 : m_Tooltip(this, "tooltip"),
77 96 : m_TooltipStyle(this, "tooltip_style")
78 : {
79 32 : }
80 :
81 32 : IGUIObject::~IGUIObject()
82 : {
83 32 : if (!m_ScriptHandlers.empty())
84 4 : JS_RemoveExtraGCRootsTracer(m_pGUI.GetScriptInterface()->GetGeneralJSContext(), Trace, this);
85 :
86 : // m_Children is deleted along all other GUI Objects in the CGUI destructor
87 38 : }
88 :
89 4 : void IGUIObject::RegisterChild(IGUIObject* child)
90 : {
91 4 : child->SetParent(this);
92 4 : m_Children.push_back(child);
93 4 : }
94 :
95 0 : void IGUIObject::UnregisterChild(IGUIObject* child)
96 : {
97 0 : std::vector<IGUIObject*>::iterator it = std::find(m_Children.begin(), m_Children.end(), child);
98 0 : if (it != m_Children.end())
99 : {
100 0 : (*it)->m_pParent = nullptr;
101 0 : m_Children.erase(it);
102 : }
103 0 : }
104 :
105 353 : void IGUIObject::RegisterSetting(const CStr& Name, IGUISetting* setting)
106 : {
107 353 : if (SettingExists(Name))
108 0 : LOGERROR("The setting '{}' already exists on the object '{}'!", Name, GetPresentableName());
109 : else
110 353 : m_Settings.emplace(Name, setting);
111 353 : }
112 :
113 1 : void IGUIObject::ReregisterSetting(const CStr& Name, IGUISetting* setting)
114 : {
115 1 : if (!SettingExists(Name))
116 0 : LOGERROR("The setting '{}' must already exist on the object '{}'!", Name,
117 : GetPresentableName());
118 : else
119 1 : m_Settings.at(Name) = setting;
120 1 : }
121 :
122 360 : bool IGUIObject::SettingExists(const CStr& Setting) const
123 : {
124 354 : return m_Settings.find(Setting) != m_Settings.end();
125 : }
126 :
127 3 : bool IGUIObject::SetSettingFromString(const CStr& Setting, const CStrW& Value, const bool SendMessage)
128 : {
129 3 : const std::map<CStr, IGUISetting*>::iterator it = m_Settings.find(Setting);
130 3 : if (it == m_Settings.end())
131 : {
132 0 : LOGERROR("GUI object '{}' has no property called '{}', can't set parse and set value '{}'",
133 : GetPresentableName(), Setting, Value.ToUTF8());
134 0 : return false;
135 : }
136 3 : return it->second->FromString(Value, SendMessage);
137 : }
138 :
139 12 : void IGUIObject::SettingChanged(const CStr& Setting, const bool SendMessage)
140 : {
141 12 : if (Setting == "size")
142 : {
143 : // Notify all children that they'll have to re-cache their actual size.
144 6 : RecurseObject(nullptr, &IGUIObject::HandleSizeChanged);
145 : }
146 6 : else if (Setting == "hidden")
147 : {
148 : // Hiding an object requires us to reset it and all children
149 0 : if (m_Hidden)
150 0 : RecurseObject(nullptr, &IGUIObject::ResetStates);
151 : }
152 6 : else if (Setting == "style")
153 0 : m_pGUI.SetObjectStyle(*this, m_Style);
154 :
155 12 : if (SendMessage)
156 : {
157 5 : SGUIMessage msg(GUIM_SETTINGS_UPDATED, Setting);
158 5 : HandleMessage(msg);
159 :
160 : // inform to parents until get to the root object
161 : // for now only size and hidden settings are bubbled up
162 5 : if (GetParent() && (Setting == "size" || Setting == "hidden"))
163 : {
164 0 : EGUIMessageType type = Setting == "size" ? GUIM_CHILD_RESIZED : GUIM_CHILD_TOGGLE_VISIBILITY;
165 0 : SGUIMessage msg(type, GetName());
166 0 : msg.Skip(true);
167 :
168 0 : IGUIObject* parent = GetParent();
169 0 : while (parent)
170 : {
171 0 : parent->HandleMessage(msg);
172 :
173 0 : if (!msg.skipped)
174 : break;
175 :
176 0 : parent = parent->GetParent();
177 : }
178 0 : }
179 5 : }
180 12 : }
181 :
182 0 : bool IGUIObject::IsMouseOver() const
183 : {
184 0 : if (m_VisibleArea)
185 0 : return m_VisibleArea.PointInside(m_pGUI.GetMousePos());
186 :
187 0 : return GetActualSize().PointInside(m_pGUI.GetMousePos());
188 : }
189 :
190 0 : void IGUIObject::UpdateMouseOver(IGUIObject* const& pMouseOver)
191 : {
192 0 : if (pMouseOver == this)
193 : {
194 0 : if (!m_MouseHovering)
195 0 : SendMouseEvent(GUIM_MOUSE_ENTER,EventNameMouseEnter);
196 :
197 0 : m_MouseHovering = true;
198 :
199 0 : SendMouseEvent(GUIM_MOUSE_OVER, EventNameMouseMove);
200 : }
201 : else
202 : {
203 0 : if (m_MouseHovering)
204 : {
205 0 : m_MouseHovering = false;
206 0 : SendMouseEvent(GUIM_MOUSE_LEAVE, EventNameMouseLeave);
207 : }
208 : }
209 0 : }
210 :
211 8 : void IGUIObject::ChooseMouseOverAndClosest(IGUIObject*& pObject)
212 : {
213 8 : if (!IsMouseOver())
214 : return;
215 :
216 : // Check if we've got competition at all
217 0 : if (pObject == nullptr)
218 : {
219 0 : pObject = this;
220 0 : return;
221 : }
222 :
223 : // Or if it's closer
224 0 : if (GetBufferedZ() >= pObject->GetBufferedZ())
225 : {
226 0 : pObject = this;
227 0 : return;
228 : }
229 : }
230 :
231 5 : IGUIObject* IGUIObject::GetParent() const
232 : {
233 : // Important, we're not using GetParent() for these
234 : // checks, that could screw it up
235 5 : if (m_pParent && m_pParent->m_pParent == nullptr)
236 0 : return nullptr;
237 :
238 : return m_pParent;
239 : }
240 :
241 0 : void IGUIObject::ResetStates()
242 : {
243 : // Notify the gui that we aren't hovered anymore
244 0 : UpdateMouseOver(nullptr);
245 0 : }
246 :
247 10 : void IGUIObject::HandleSizeChanged()
248 : {
249 10 : m_CachedActualSizeDirty = true;
250 10 : }
251 :
252 2 : const CRect& IGUIObject::GetActualSize() const
253 : {
254 2 : if (std::exchange(m_CachedActualSizeDirty, false))
255 2 : RecalculateActualSize();
256 :
257 2 : return m_CachedActualSize;
258 : }
259 :
260 2 : void IGUIObject::RecalculateActualSize() const
261 : {
262 : // If absolute="false" and the object has got a parent,
263 : // use its cached size instead of the screen.
264 2 : if (!m_Absolute && m_pParent && !IsRootObject())
265 0 : m_CachedActualSize = m_Size->GetSize(m_pParent->GetActualSize());
266 : else
267 2 : m_CachedActualSize = m_Size->GetSize(CRect(m_pGUI.GetWindowSize()));
268 :
269 : // In a few cases, GUI objects have to resize to fill the screen
270 : // but maintain a constant aspect ratio.
271 : // Adjust the size to be the max possible, centered in the original size:
272 2 : if (m_AspectRatio)
273 : {
274 0 : if (m_CachedActualSize.GetWidth() > m_CachedActualSize.GetHeight() * m_AspectRatio)
275 : {
276 0 : float delta = m_CachedActualSize.GetWidth() - m_CachedActualSize.GetHeight() * m_AspectRatio;
277 0 : m_CachedActualSize.left += delta/2.f;
278 0 : m_CachedActualSize.right -= delta/2.f;
279 : }
280 : else
281 : {
282 0 : float delta = m_CachedActualSize.GetHeight() - m_CachedActualSize.GetWidth() / m_AspectRatio;
283 0 : m_CachedActualSize.bottom -= delta/2.f;
284 0 : m_CachedActualSize.top += delta/2.f;
285 : }
286 : }
287 2 : }
288 :
289 4 : bool IGUIObject::ApplyStyle(const CStr& StyleName)
290 : {
291 4 : if (!m_pGUI.HasStyle(StyleName))
292 : {
293 0 : LOGERROR("IGUIObject: Trying to use style '{}' that doesn't exist.", StyleName);
294 0 : return false;
295 : }
296 :
297 : // The default style may specify settings for any GUI object.
298 : // Other styles are reported if they specify a Setting that does not exist,
299 : // so that the XML author is informed and can correct the style.
300 :
301 4 : for (const std::pair<const CStr, CStrW>& p : m_pGUI.GetStyle(StyleName).m_SettingsDefaults)
302 : {
303 0 : if (SettingExists(p.first))
304 0 : m_Settings.at(p.first)->FromString(p.second, true);
305 0 : else if (StyleName != "default")
306 : {
307 0 : LOGWARNING("GUI object has no setting \"{}\", but the style \"{}\" defines it",
308 : p.first, StyleName);
309 : }
310 : }
311 : return true;
312 : }
313 :
314 4 : float IGUIObject::GetBufferedZ() const
315 : {
316 4 : if (m_Absolute)
317 4 : return m_Z;
318 :
319 0 : if (GetParent())
320 0 : return GetParent()->GetBufferedZ() + m_Z;
321 :
322 : // In philosophy, a parentless object shouldn't be able to have a relative sizing,
323 : // but we'll accept it so that absolute can be used as default without a complaint.
324 : // Also, you could consider those objects children to the screen resolution.
325 0 : return m_Z;
326 : }
327 :
328 0 : void IGUIObject::RegisterScriptHandler(const CStr& eventName, const CStr& Code, CGUI& pGUI)
329 : {
330 0 : Script::Request rq(pGUI.GetScriptInterface());
331 :
332 0 : const int paramCount = 1;
333 0 : const char* paramNames[paramCount] = { "mouse" };
334 :
335 : // Location to report errors from
336 0 : CStr CodeName = GetName() + " " + eventName;
337 :
338 : // Generate a unique name
339 0 : static int x = 0;
340 0 : char buf[64];
341 0 : sprintf_s(buf, ARRAY_SIZE(buf), "__eventhandler%d (%s)", x++, eventName.c_str());
342 :
343 : // TODO: this is essentially the same code as Script::Interface::LoadScript (with a tweak for the argument).
344 0 : JS::CompileOptions options(rq.cx);
345 0 : options.setFileAndLine(CodeName.c_str(), 0);
346 0 : options.setIsRunOnce(false);
347 0 : options.setForceStrictMode();
348 :
349 0 : JS::SourceText<mozilla::Utf8Unit> src;
350 0 : ENSURE(src.init(rq.cx, Code.c_str(), Code.length(), JS::SourceOwnership::Borrowed));
351 0 : JS::EnvironmentChain emptyScopeChain{ rq.cx, JS::SupportUnscopables::No };
352 0 : JS::RootedFunction func(rq.cx, JS::CompileFunction(rq.cx, emptyScopeChain, options, buf, paramCount, paramNames, src));
353 0 : if (func == nullptr)
354 : {
355 0 : LOGERROR("RegisterScriptHandler: Failed to compile the script for {}", eventName);
356 0 : return;
357 : }
358 :
359 0 : JS::RootedObject funcObj(rq.cx, JS_GetFunctionObject(func));
360 0 : SetScriptHandler(eventName, funcObj);
361 0 : }
362 :
363 5 : void IGUIObject::SetScriptHandler(const CStr& eventName, JS::HandleObject Function)
364 : {
365 5 : if (m_ScriptHandlers.empty())
366 8 : JS_AddExtraGCRootsTracer(m_pGUI.GetScriptInterface()->GetGeneralJSContext(), Trace, this);
367 :
368 5 : m_ScriptHandlers[eventName] = JS::Heap<JSObject*>(Function);
369 :
370 5 : if (std::find(m_pGUI.m_EventObjects[eventName].begin(), m_pGUI.m_EventObjects[eventName].end(), this) == m_pGUI.m_EventObjects[eventName].end())
371 4 : m_pGUI.m_EventObjects[eventName].emplace_back(this);
372 5 : }
373 :
374 4 : void IGUIObject::UnsetScriptHandler(const CStr& eventName)
375 : {
376 4 : std::map<CStr, JS::Heap<JSObject*> >::iterator it = m_ScriptHandlers.find(eventName);
377 :
378 4 : if (it == m_ScriptHandlers.end())
379 4 : return;
380 :
381 2 : m_ScriptHandlers.erase(it);
382 :
383 2 : if (m_ScriptHandlers.empty())
384 4 : JS_RemoveExtraGCRootsTracer(m_pGUI.GetScriptInterface()->GetGeneralJSContext(), Trace, this);
385 :
386 2 : std::unordered_map<CStr, std::vector<IGUIObject*>>::iterator it2 = m_pGUI.m_EventObjects.find(eventName);
387 2 : if (it2 == m_pGUI.m_EventObjects.end())
388 : return;
389 :
390 2 : std::vector<IGUIObject*>& handlers = it2->second;
391 2 : handlers.erase(std::remove(handlers.begin(), handlers.end(), this), handlers.end());
392 :
393 2 : if (handlers.empty())
394 0 : m_pGUI.m_EventObjects.erase(it2);
395 : }
396 :
397 0 : Input::Reaction IGUIObject::SendEvent(EGUIMessageType type, const CStr& eventName)
398 : {
399 0 : PROFILE2_EVENT("gui event");
400 0 : PROFILE2_ATTR("type: %s", eventName.c_str());
401 0 : PROFILE2_ATTR("object: %s", m_Name.c_str());
402 :
403 0 : SGUIMessage msg(type);
404 0 : HandleMessage(msg);
405 :
406 0 : ScriptEvent(eventName);
407 :
408 0 : return msg.skipped ? Input::Reaction::PASS : Input::Reaction::HANDLED;
409 0 : }
410 :
411 0 : Input::Reaction IGUIObject::SendMouseEvent(EGUIMessageType type, const CStr& eventName)
412 : {
413 0 : PROFILE2_EVENT("gui mouse event");
414 0 : PROFILE2_ATTR("type: %s", eventName.c_str());
415 0 : PROFILE2_ATTR("object: %s", m_Name.c_str());
416 :
417 0 : SGUIMessage msg(type);
418 0 : if (type == GUIM_MOUSE_WHEEL_UP || type == GUIM_MOUSE_WHEEL_DOWN || type == GUIM_MOUSE_WHEEL_LEFT || type == GUIM_MOUSE_WHEEL_RIGHT)
419 0 : msg.Skip();
420 0 : HandleMessage(msg);
421 :
422 0 : Script::Request rq(m_pGUI.GetScriptInterface());
423 :
424 : // Set up the 'mouse' parameter
425 0 : JS::RootedValue mouse(rq.cx);
426 :
427 0 : const CVector2D& mousePos = m_pGUI.GetMousePos();
428 :
429 0 : std::map<CStr, JS::Heap<JSObject*> >::iterator it = m_ScriptHandlers.find(eventName);
430 0 : if (it != m_ScriptHandlers.end())
431 : {
432 0 : Script::CreateObject(
433 : rq,
434 : &mouse,
435 0 : "x", mousePos.X,
436 0 : "y", mousePos.Y,
437 0 : "buttons", m_pGUI.GetMouseButtons());
438 0 : JS::RootedValueVector paramData(rq.cx);
439 0 : std::ignore = paramData.append(mouse);
440 0 : ScriptEvent(eventName, paramData);
441 :
442 0 : if (type == GUIM_MOUSE_WHEEL_UP || type == GUIM_MOUSE_WHEEL_DOWN || type == GUIM_MOUSE_WHEEL_LEFT || type == GUIM_MOUSE_WHEEL_RIGHT)
443 0 : msg.Skip(false);
444 0 : }
445 :
446 : // inform to parents until get to the root object
447 : // for now only wheel events are inform to parents
448 0 : if ((type == GUIM_MOUSE_WHEEL_UP || type == GUIM_MOUSE_WHEEL_DOWN || type == GUIM_MOUSE_WHEEL_LEFT || type == GUIM_MOUSE_WHEEL_RIGHT) && msg.skipped)
449 : {
450 0 : if (GetParent())
451 0 : msg.Skip(GetParent()->SendMouseEvent(type, eventName) == Input::Reaction::PASS);
452 : else
453 0 : msg.Skip(false);
454 : }
455 :
456 0 : return msg.skipped ? Input::Reaction::PASS : Input::Reaction::HANDLED;
457 0 : }
458 :
459 5 : bool IGUIObject::ScriptEvent(const CStr& eventName,
460 : const JS::HandleValueArray& paramData /* = JS::HandleValueArray::empty() */)
461 : {
462 5 : std::map<CStr, JS::Heap<JSObject*> >::iterator it = m_ScriptHandlers.find(eventName);
463 5 : if (it == m_ScriptHandlers.end())
464 : return false;
465 :
466 4 : Script::Request rq(m_pGUI.GetScriptInterface());
467 4 : JS::RootedObject obj(rq.cx, GetJSObject());
468 4 : JS::RootedValue handlerVal(rq.cx, JS::ObjectValue(*it->second));
469 4 : JS::RootedValue result(rq.cx);
470 :
471 4 : if (!JS_CallFunctionValue(rq.cx, obj, handlerVal, paramData, &result))
472 : {
473 0 : LOGERROR("Errors executing script event \"{}\"", eventName);
474 0 : Script::Exception::CatchPending(rq);
475 : return false;
476 : }
477 8 : return JS::ToBoolean(result);
478 4 : }
479 :
480 10 : JSObject* IGUIObject::GetJSObject()
481 : {
482 : // Cache the object when somebody first asks for it, because otherwise
483 : // we end up doing far too much object allocation.
484 10 : if (!m_JSObject)
485 5 : CreateJSObject();
486 :
487 4 : return m_JSObject->Get();
488 : }
489 :
490 0 : bool IGUIObject::IsEnabled() const
491 : {
492 0 : return m_Enabled;
493 : }
494 :
495 0 : bool IGUIObject::IsHidden() const
496 : {
497 0 : return m_Hidden;
498 : }
499 :
500 16 : bool IGUIObject::IsHiddenOrGhost() const
501 : {
502 16 : return m_Hidden || m_Ghost;
503 : }
504 :
505 0 : void IGUIObject::PlaySound(const CStrW& soundPath) const
506 : {
507 0 : if (g_SoundManager && !soundPath.empty())
508 0 : g_SoundManager->PlayAsUI(soundPath.c_str(), false);
509 0 : }
510 :
511 0 : CStr IGUIObject::GetPresentableName() const
512 : {
513 : // __internal(), must be at least 13 letters to be able to be
514 : // an internal name
515 0 : if (m_Name.length() <= 12)
516 0 : return m_Name;
517 :
518 0 : if (std::string_view{m_Name}.substr(0, 10) == "__internal")
519 0 : return CStr("[unnamed object]");
520 : else
521 0 : return m_Name;
522 : }
523 :
524 0 : void IGUIObject::SetFocus()
525 : {
526 0 : m_pGUI.SetFocusedObject(this);
527 0 : }
528 :
529 0 : void IGUIObject::ReleaseFocus()
530 : {
531 0 : m_pGUI.SetFocusedObject(nullptr);
532 0 : }
533 :
534 0 : bool IGUIObject::IsFocused() const
535 : {
536 0 : return m_pGUI.GetFocusedObject() == this;
537 : }
538 :
539 121 : bool IGUIObject::IsBaseObject() const
540 : {
541 121 : return this == m_pGUI.GetBaseObject();
542 : }
543 :
544 0 : bool IGUIObject::IsRootObject() const
545 : {
546 0 : return m_pParent == m_pGUI.GetBaseObject();
547 : }
548 :
549 0 : void IGUIObject::TraceMember(JSTracer* trc)
550 : {
551 : // Please ensure to adapt the Tracer enabling and disabling in accordance with the GC things traced!
552 :
553 0 : for (std::pair<const CStr, JS::Heap<JSObject*>>& handler : m_ScriptHandlers)
554 0 : JS::TraceEdge(trc, &handler.second, "IGUIObject::m_ScriptHandlers");
555 0 : }
556 :
557 0 : void IGUIObject::DrawInArea(CCanvas2D& canvas, CRect& area)
558 : {
559 0 : bool isInsideBoundaries = false;
560 0 : RecurseObject(nullptr, &IGUIObject::SetIsInsideBoundaries, isInsideBoundaries);
561 0 : if (!area.IntersectWith(GetActualSize()))
562 0 : return;
563 :
564 0 : CRect intersection = area.Intersection(GetActualSize());
565 :
566 0 : m_VisibleArea = intersection;
567 :
568 0 : Draw(canvas);
569 :
570 0 : isInsideBoundaries = true;
571 0 : RecurseObject(nullptr, &IGUIObject::SetIsInsideBoundaries, isInsideBoundaries);
572 : }
573 :
574 16 : bool IGUIObject::IsHiddenOrGhostOrOutOfBoundaries() const {
575 32 : return !m_IsInsideBoundaries || IsHiddenOrGhost();
576 : }
577 :
578 0 : Input::Reaction IGUIObject::PreemptEvent(const SDL_Event&)
579 : {
580 0 : return Input::Reaction::PASS;
581 : }
582 :
583 0 : Input::Reaction IGUIObject::ManuallyHandleKeys(const SDL_Event&)
584 : {
585 0 : return Input::Reaction::PASS;
586 : }
|