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 : /*
19 : * The base class of an object.
20 : * All objects are derived from this class.
21 : * It's an abstract data type, so it can't be used per se.
22 : * Also contains a Dummy object which is used for completely blank objects.
23 : */
24 :
25 : #ifndef INCLUDED_IGUIOBJECT
26 : #define INCLUDED_IGUIOBJECT
27 :
28 : #include "gui/CGUISetting.h"
29 : #include "gui/SGUIMessage.h"
30 : #include "gui/SettingTypes/CGUIHotkey.h"
31 : #include "gui/SettingTypes/CGUISize.h"
32 : #include "lib/code_annotation.h"
33 : #include "maths/Rect.h"
34 : #include "ps/CStr.h"
35 : #include "ps/Input.h"
36 :
37 : #include <js/RootingAPI.h>
38 : #include <js/TypeDecls.h>
39 : #include <js/ValueArray.h>
40 : #include <map>
41 : #include <memory>
42 : #include <vector>
43 :
44 : class CCanvas2D;
45 : class CGUI;
46 : class IGUIProxyObject;
47 : class JSObject;
48 : class JSTracer;
49 : class XMBData;
50 : class XMBElement;
51 : namespace JS { class HandleValueArray; }
52 :
53 : #define GUI_OBJECT(obj) \
54 : public: \
55 : static std::unique_ptr<IGUIObject> ConstructObject(CGUI& pGUI) \
56 : { return std::make_unique<obj>(pGUI); }
57 :
58 : /**
59 : * GUI object such as a button or an input-box.
60 : * Abstract data type !
61 : */
62 : class IGUIObject
63 : {
64 : friend class CGUI;
65 : friend class CGUIObjectEventBroadcaster;
66 :
67 : // For triggering message update handlers.
68 : friend class IGUISetting;
69 :
70 : // Allow getProperty to access things like GetParent()
71 : template <typename T>
72 : friend class JSI_GUIProxy;
73 :
74 : public:
75 : NONCOPYABLE(IGUIObject);
76 :
77 : // IGUIObjects must not be moved in memory: SpiderMonkey keeps a pointer to
78 : // them in order to trace script handlers during GCs (see Set/UnsetScriptHandlers())
79 : IGUIObject(IGUIObject&&) = delete;
80 : IGUIObject& operator=(IGUIObject&&) = delete;
81 :
82 : IGUIObject(CGUI& pGUI);
83 : virtual ~IGUIObject();
84 :
85 : /**
86 : * This function checks if the mouse is hovering the
87 : * rectangle that the base setting "size" makes.
88 : * Although it is virtual, so one could derive
89 : * an object from CButton, which changes only this
90 : * to checking the circle that "size" makes.
91 : *
92 : * This function also returns true if there is a different
93 : * GUI object shown on top of this one.
94 : */
95 : virtual bool IsMouseOver() const;
96 :
97 : /**
98 : * This function returns true if the mouse is hovering
99 : * over this GUI object and if this GUI object is the
100 : * topmost object in that screen location.
101 : * For example when hovering dropdown list items, the
102 : * buttons beneath the list won't return true here.
103 : */
104 0 : virtual bool IsMouseHovering() const { return m_MouseHovering; }
105 :
106 : //--------------------------------------------------------
107 : /** @name Leaf Functions */
108 : //--------------------------------------------------------
109 : //@{
110 :
111 : /// Get object name, name is unique
112 0 : const CStr& GetName() const { return m_Name; }
113 :
114 : /// Get object name
115 4 : void SetName(const CStr& Name) { m_Name = Name; }
116 :
117 : // Get Presentable name.
118 : // Will change all internally set names to something like "<unnamed object>"
119 : CStr GetPresentableName() const;
120 :
121 : /**
122 : * Return all child objects of the current object.
123 : */
124 0 : const std::vector<IGUIObject*>& GetChildren() const { return m_Children; }
125 :
126 : //@}
127 : //--------------------------------------------------------
128 : /** @name Settings Management */
129 : //--------------------------------------------------------
130 : //@{
131 :
132 : /**
133 : * Registers the given setting with the GUI object.
134 : * Enable XML and JS to modify the given variable.
135 : */
136 : void RegisterSetting(const CStr& Name, IGUISetting* setting);
137 : void ReregisterSetting(const CStr& Name, IGUISetting* setting);
138 :
139 : /**
140 : * Returns whether there is a setting with the given name registered.
141 : *
142 : * @param Setting setting name
143 : * @return True if settings exist.
144 : */
145 : bool SettingExists(const CStr& Setting) const;
146 :
147 : /**
148 : * Set a setting by string, regardless of what type it is.
149 : * Used to parse setting values from XML files.
150 : * For example a CRect(10,10,20,20) is created from "10 10 20 20".
151 : * @return false if the setting does not exist or the conversion fails, otherwise true.
152 : */
153 : bool SetSettingFromString(const CStr& Setting, const CStrW& Value, const bool SendMessage);
154 :
155 : /**
156 : * Returns whether this object is set to be hidden or ghost.
157 : */
158 : bool IsEnabled() const;
159 :
160 : /**
161 : * Returns whether this is object is set to be hidden.
162 : */
163 : bool IsHidden() const;
164 :
165 0 : void SetHidden(bool hidden) { m_Hidden.Set(hidden, true); }
166 :
167 : /**
168 : * Returns whether this object is set to be hidden or ghost.
169 : */
170 : bool IsHiddenOrGhost() const;
171 :
172 : /**
173 : * Retrieves the configured sound filename from the given setting name and plays that once.
174 : */
175 : void PlaySound(const CStrW& soundPath) const;
176 :
177 : /**
178 : * Send event to this GUI object (HandleMessage and ScriptEvent)
179 : *
180 : * @param type Type of GUI message to be handled
181 : * @param eventName String representation of event name
182 : * @return IN_HANDLED if event was handled, or IN_PASS if skipped
183 : */
184 : Input::Reaction SendEvent(EGUIMessageType type, const CStr& eventName);
185 :
186 : /**
187 : * Same as SendEvent, but passes mouse coordinates and button state as an argument.
188 : */
189 : Input::Reaction SendMouseEvent(EGUIMessageType type, const CStr& eventName);
190 :
191 : /**
192 : * All sizes are relative to resolution, and the calculation
193 : * is not wanted in real time, therefore it is cached, update
194 : * the cached size with this function.
195 : */
196 : virtual void HandleSizeChanged();
197 :
198 : /**
199 : * Get the size of the object.
200 : * Besides m_Size it also depends on the parent's size, hence "actual".
201 : */
202 : virtual const CRect& GetActualSize() const;
203 :
204 0 : virtual const CStrW& GetTooltipText() const { return m_Tooltip; }
205 0 : virtual const CStr& GetTooltipStyle() const { return m_TooltipStyle; }
206 :
207 : /**
208 : * Reset internal state of this object.
209 : */
210 : virtual void ResetStates();
211 :
212 : /**
213 : * Set the script handler for a particular object-specific action
214 : *
215 : * @param eventName Name of action
216 : * @param Code Javascript code to execute when the action occurs
217 : * @param pGUI GUI instance to associate the script with
218 : */
219 : void RegisterScriptHandler(const CStr& eventName, const CStr& Code, CGUI& pGUI);
220 :
221 : /**
222 : * Retrieves the JSObject representing this GUI object.
223 : */
224 : JSObject* GetJSObject();
225 :
226 0 : virtual const std::vector<IGUIObject*>& GetVisibleChildren() const { return m_Children; }
227 0 : void SetIsInsideBoundaries(bool& isInsideBoundaries) { m_IsInsideBoundaries = isInsideBoundaries; }
228 : bool IsHiddenOrGhostOrOutOfBoundaries() const;
229 :
230 : //@}
231 : protected:
232 : //--------------------------------------------------------
233 : /** @name Called by CGUI and friends
234 : *
235 : * Methods that the CGUI will call using
236 : * its friendship, these should not
237 : * be called by user.
238 : * TODO: this comment is old and the following interface should be cleaned up.
239 : */
240 : //--------------------------------------------------------
241 : //@{
242 :
243 : public:
244 :
245 : /**
246 : * Called on every GUI tick unless the object or one of its parent is hidden/ghost.
247 : */
248 8 : virtual void Tick() {};
249 :
250 : /**
251 : * This function is called with different messages
252 : * for instance when the mouse enters the object.
253 : *
254 : * @param Message GUI Message
255 : */
256 9 : virtual void HandleMessage(SGUIMessage&) {}
257 :
258 : /**
259 : * Calls an IGUIObject member function recursively on this object and its children.
260 : * Aborts recursion at IGUIObjects that have the isRestricted function return true.
261 : * The arguments of the callback function must be references.
262 : */
263 : template<typename... Args>
264 121 : void RecurseObject(bool(IGUIObject::*isRestricted)() const, void(IGUIObject::*callbackFunction)(Args... args), Args&&... args)
265 : {
266 121 : if (!IsBaseObject())
267 : {
268 30 : if (isRestricted && (this->*isRestricted)())
269 : return;
270 :
271 30 : (this->*callbackFunction)(args...);
272 : }
273 :
274 145 : for (IGUIObject* const& obj : m_Children)
275 24 : obj->RecurseObject(isRestricted, callbackFunction, args...);
276 : }
277 :
278 : virtual void DrawInArea(CCanvas2D& canvas, CRect& area);
279 :
280 : protected:
281 : /**
282 : * Draws the object.
283 : */
284 : virtual void Draw(CCanvas2D& canvas) = 0;
285 :
286 : /**
287 : * Some objects need to be able to pre-emptively process SDL_Event.
288 : *
289 : * Only the object with focus will have this function called.
290 : *
291 : * Returns either IN_PASS or IN_HANDLED. If IN_HANDLED, then
292 : * the event won't be passed on and processed by other handlers.
293 : */
294 : virtual Input::Reaction PreemptEvent(const SDL_Event&);
295 :
296 : /**
297 : * Some objects need to handle the text-related SDL_Event manually.
298 : * For instance the input box.
299 : *
300 : * Only the object with focus will have this function called.
301 : *
302 : * Returns either IN_PASS or IN_HANDLED. If IN_HANDLED, then
303 : * the key won't be passed on and processed by other handlers.
304 : * This is used for keys that the GUI uses.
305 : */
306 : virtual Input::Reaction ManuallyHandleKeys(const SDL_Event&);
307 :
308 : /**
309 : * Applies the given style to the object.
310 : *
311 : * Returns false if the style is not recognised (and thus has
312 : * not been applied).
313 : */
314 : bool ApplyStyle(const CStr& StyleName);
315 :
316 : /**
317 : * Returns not the Z value, but the actual buffered Z value, i.e. if it's
318 : * defined relative, then it will check its parent's Z value and add
319 : * the relativity.
320 : *
321 : * @return Actual Z value on the screen.
322 : */
323 : virtual float GetBufferedZ() const;
324 :
325 : /**
326 : * Add an object to the hierarchy.
327 : */
328 : void RegisterChild(IGUIObject* child);
329 :
330 : /**
331 : * Remove an object from the hierarchy.
332 : */
333 : void UnregisterChild(IGUIObject* child);
334 :
335 : /**
336 : * Set parent of this object
337 : */
338 4 : void SetParent(IGUIObject* pParent) { m_pParent = pParent; }
339 :
340 : public:
341 :
342 8 : CGUI& GetGUI() { return m_pGUI; }
343 : const CGUI& GetGUI() const { return m_pGUI; }
344 :
345 : /**
346 : * Take focus!
347 : */
348 : void SetFocus();
349 :
350 : /**
351 : * Release focus.
352 : */
353 : void ReleaseFocus();
354 :
355 : protected:
356 : /**
357 : * Check if object is focused.
358 : */
359 : bool IsFocused() const;
360 :
361 : /**
362 : * <b>NOTE!</b> This will not just return m_pParent, when that is
363 : * need use it! There is one exception to it, when the parent is
364 : * the top-node (the object that isn't a real object), this
365 : * will return nullptr, so that the top-node's children are
366 : * seemingly parentless.
367 : *
368 : * @return Pointer to parent
369 : */
370 : IGUIObject* GetParent() const;
371 :
372 : /**
373 : * Handle additional children to the \<object\>-tag. In IGUIObject, this function does
374 : * nothing. In CList and CDropDown, it handles the \<item\>, used to build the data.
375 : *
376 : * Returning false means the object doesn't recognize the child. Should be reported.
377 : * Notice 'false' is default, because an object not using this function, should not
378 : * have any additional children (and this function should never be called).
379 : */
380 0 : virtual bool HandleAdditionalChildren(const XMBData& /*file*/, const XMBElement& /*child*/)
381 : {
382 0 : return false;
383 : }
384 :
385 : /**
386 : * Allow the GUI object to process after all child items were handled.
387 : * Useful to avoid iterator invalidation with push_back calls.
388 : */
389 4 : virtual void AdditionalChildrenHandled() {}
390 :
391 : /**
392 : * Execute the script for a particular action.
393 : * Does nothing if no script has been registered for that action.
394 : *
395 : * @param eventName Name of action
396 : * @param paramData JS::HandleValueArray arguments to pass to the event.
397 : *
398 : * @return True if the script returned something truthy.
399 : */
400 : bool ScriptEvent(const CStr& eventName,
401 0 : const JS::HandleValueArray& paramData = JS::HandleValueArray::empty());
402 :
403 : /**
404 : * Assigns a JS function to the event name.
405 : */
406 : void SetScriptHandler(const CStr& eventName, JS::HandleObject Function);
407 :
408 : /**
409 : * Deletes an event handler assigned to the given name, if such a handler exists.
410 : */
411 : void UnsetScriptHandler(const CStr& eventName);
412 :
413 : /**
414 : * Inputes the object that is currently hovered, this function
415 : * updates this object accordingly (i.e. if it's the object
416 : * being inputted one thing happens, and not, another).
417 : *
418 : * @param pMouseOver Object that is currently hovered, can be nullptr too!
419 : */
420 : void UpdateMouseOver(IGUIObject* const& pMouseOver);
421 :
422 : /**
423 : * Recompute the actual (absolute) size from scratch again and cache it.
424 : */
425 : virtual void RecalculateActualSize() const;
426 :
427 : //@}
428 : private:
429 : //--------------------------------------------------------
430 : /** @name Internal functions */
431 : //--------------------------------------------------------
432 : //@{
433 :
434 : /**
435 : * Creates the JS object representing this page upon first use.
436 : * This function (and its derived versions) are defined in the GUIProxy implementation file for convenience.
437 : */
438 : virtual void CreateJSObject();
439 :
440 : /**
441 : * Updates some internal data depending on the setting changed.
442 : */
443 : void SettingChanged(const CStr& Setting, const bool SendMessage);
444 :
445 : /**
446 : * Inputs a reference pointer, checks if the new inputted object
447 : * if hovered, if so, then check if this's Z value is greater
448 : * than the inputted object... If so then the object is closer
449 : * and we'll replace the pointer with this.
450 : * Also Notice input can be nullptr, which means the Z value demand
451 : * is out. NOTICE you can't input nullptr as const so you'll have
452 : * to set an object to nullptr.
453 : *
454 : * @param pObject Object pointer, can be either the old one, or
455 : * the new one.
456 : */
457 : void ChooseMouseOverAndClosest(IGUIObject*& pObject);
458 :
459 : /**
460 : * Returns whether this is the object all other objects are descendants of.
461 : */
462 : bool IsBaseObject() const;
463 :
464 : /**
465 : * Returns whether this object is a child of the base object.
466 : */
467 : bool IsRootObject() const;
468 :
469 0 : static void Trace(JSTracer* trc, void* data)
470 : {
471 0 : reinterpret_cast<IGUIObject*>(data)->TraceMember(trc);
472 0 : }
473 :
474 : void TraceMember(JSTracer* trc);
475 :
476 : // Variables
477 : protected:
478 : static const CStr EventNameMouseEnter;
479 : static const CStr EventNameMouseMove;
480 : static const CStr EventNameMouseLeave;
481 :
482 : // Name of object
483 : CStr m_Name;
484 :
485 : // Constructed on the heap, will be destroyed along with the the CGUI
486 : std::vector<IGUIObject*> m_Children;
487 :
488 : // Pointer to parent
489 : IGUIObject* m_pParent;
490 :
491 : //This represents the last click time for each mouse button
492 : double m_LastClickTime[6];
493 :
494 : /**
495 : * This variable is true if the mouse is hovering this object and
496 : * this object is the topmost object shown in this location.
497 : */
498 : bool m_MouseHovering;
499 :
500 : /**
501 : * Settings pool, all an object's settings are located here
502 : */
503 : std::map<CStr, IGUISetting*> m_Settings;
504 :
505 : // An object can't function stand alone
506 : CGUI& m_pGUI;
507 :
508 : // Internal storage for registered script handlers.
509 : std::map<CStr, JS::Heap<JSObject*> > m_ScriptHandlers;
510 :
511 : // Cached JSObject representing this GUI object.
512 : std::unique_ptr<IGUIProxyObject> m_JSObject;
513 :
514 : CRect m_VisibleArea;
515 : bool m_IsInsideBoundaries = true;
516 :
517 : /**
518 : * The actual size (usually) depends on the size of the parent.
519 : * And to avoid recomputing all the time, it is cached here.
520 : * Do not read from this directly, it is not guaranteed to be up-to-date,
521 : * call GetActualSize() insead.
522 : */
523 : mutable CRect m_CachedActualSize;
524 :
525 : /**
526 : * Whether m_CacheActualSize is not up-to-date and will have to be recomputed
527 : * when accessing it the next time.
528 : */
529 : mutable bool m_CachedActualSizeDirty = true;
530 :
531 : CGUISimpleSetting<bool> m_Enabled;
532 : CGUISimpleSetting<bool> m_Hidden;
533 : CGUISimpleSetting<CGUISize> m_Size;
534 : CGUISimpleSetting<CStr> m_Style;
535 : CGUIHotkey m_Hotkey;
536 : CGUISimpleSetting<float> m_Z;
537 : CGUISimpleSetting<bool> m_Absolute;
538 : CGUISimpleSetting<bool> m_Ghost;
539 : CGUISimpleSetting<float> m_AspectRatio;
540 : CGUISimpleSetting<CStrW> m_Tooltip;
541 : CGUISimpleSetting<CStr> m_TooltipStyle;
542 : };
543 :
544 : #endif // INCLUDED_IGUIOBJECT
|