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 "CGUI.h"
21 :
22 : #include "graphics/Canvas2D.h"
23 : #include "graphics/Color.h"
24 : #include "gui/CGUISetting.h"
25 : #include "gui/CGUISprite.h"
26 : #include "gui/GUIObjectEventBroadcaster.h"
27 : #include "gui/IGUIScrollBar.h"
28 : #include "gui/ObjectBases/IGUIObject.h"
29 : #include "gui/ObjectTypes/CGUIDummyObject.h"
30 : #include "gui/ObjectTypes/CTooltip.h"
31 : #include "gui/Scripting/JSInterface_GUIProxy.h"
32 : #include "gui/Scripting/ScriptFunctions.h"
33 : #include "gui/SettingTypes/CGUISize.h"
34 : #include "i18n/L10n.h"
35 : #include "lib/bits.h"
36 : #include "lib/debug.h"
37 : #include "lib/external_libraries/libsdl.h"
38 : #include "lib/file/vfs/vfs_util.h"
39 : #include "lib/path.h"
40 : #include "lib/timer.h"
41 : #include "lib/utf8.h"
42 : #include "maths/Size2D.h"
43 : #include "network/NetClient.h"
44 : #include "ps/CLogger.h"
45 : #include "ps/Errors.h"
46 : #include "ps/Filesystem.h"
47 : #include "ps/GameSetup/Config.h"
48 : #include "ps/Hotkey.h"
49 : #include "ps/VideoMode.h"
50 : #include "ps/XMB/XMBData.h"
51 : #include "ps/XML/Xeromyces.h"
52 : #include "ps/algorithm.h"
53 : #include "renderer/backend/Sampler.h"
54 : #include "scriptinterface/FunctionWrapper.h"
55 : #include "scriptinterface/Object.h"
56 : #include "scriptinterface/Exceptions.h"
57 : #include "scriptinterface/Interface.h"
58 : #include "scriptinterface/Request.h"
59 :
60 : #include <algorithm>
61 : #include <js/CallAndConstruct.h>
62 : #include <js/Promise.h>
63 : #include <optional>
64 : #include <SDL_events.h>
65 : #include <SDL_mouse.h>
66 : #include <stdexcept>
67 : #include <string>
68 : #include <tuple>
69 : #include <unordered_map>
70 : #include <unordered_set>
71 : #include <utility>
72 :
73 : const double SELECT_DBLCLICK_RATE = 0.5;
74 : const std::uint32_t MAX_OBJECT_DEPTH = 100; // Max number of nesting for GUI includes. Used to detect recursive inclusion
75 :
76 : const CStr CGUI::EventNameLoad = "Load";
77 : const CStr CGUI::EventNameTick = "Tick";
78 : const CStr CGUI::EventNamePress = "Press";
79 : const CStr CGUI::EventNameKeyDown = "KeyDown";
80 : const CStr CGUI::EventNameRelease = "Release";
81 : const CStr CGUI::EventNameMouseRightPress = "MouseRightPress";
82 : const CStr CGUI::EventNameMouseLeftPress = "MouseLeftPress";
83 : const CStr CGUI::EventNameMouseWheelDown = "MouseWheelDown";
84 : const CStr CGUI::EventNameMouseWheelUp = "MouseWheelUp";
85 : const CStr CGUI::EventNameMouseWheelLeft = "MouseWheelLeft";
86 : const CStr CGUI::EventNameMouseWheelRight = "MouseWheelRight";
87 : const CStr CGUI::EventNameMouseLeftDoubleClick = "MouseLeftDoubleClick";
88 : const CStr CGUI::EventNameMouseLeftRelease = "MouseLeftRelease";
89 : const CStr CGUI::EventNameMouseRightDoubleClick = "MouseRightDoubleClick";
90 : const CStr CGUI::EventNameMouseRightRelease = "MouseRightRelease";
91 :
92 26 : CGUI::CGUI(Script::Context& context)
93 26 : : m_BaseObject(std::make_unique<CGUIDummyObject>(*this)),
94 26 : m_FocusedObject(nullptr),
95 26 : m_InternalNameNumber(0),
96 52 : m_MouseButtons(0)
97 : {
98 26 : m_ScriptInterface = std::make_shared<Script::Interface>("Engine", "GUIPage", context,
99 28 : [](const VfsPath& path){
100 2 : return path.string8().find("gui/") == 0;
101 26 : });
102 26 : m_ScriptInterface->SetCallbackData(this);
103 :
104 26 : GuiScriptingInit(*m_ScriptInterface);
105 26 : m_ScriptInterface->LoadGlobalScripts();
106 26 : }
107 :
108 26 : CGUI::~CGUI()
109 : {
110 26 : if (g_NetClient)
111 0 : g_NetClient->Unregister(m_ScriptInterface.get());
112 54 : }
113 :
114 7 : Input::Reaction CGUI::HandleEvent(const SDL_Event& ev)
115 : {
116 7 : Input::Reaction ret = Input::Reaction::PASS;
117 :
118 7 : if (ev.type == SDL_HOTKEYDOWN || ev.type == SDL_HOTKEYPRESS || ev.type == SDL_HOTKEYUP)
119 : {
120 4 : const char* hotkey = static_cast<const char*>(ev.user.data1);
121 :
122 4 : const CStr& eventName = ev.type == SDL_HOTKEYPRESS ? EventNamePress : ev.type == SDL_HOTKEYDOWN ? EventNameKeyDown : EventNameRelease;
123 :
124 4 : if (m_GlobalHotkeys.find(hotkey) != m_GlobalHotkeys.end() && m_GlobalHotkeys[hotkey].find(eventName) != m_GlobalHotkeys[hotkey].end())
125 : {
126 0 : ret = Input::Reaction::HANDLED;
127 :
128 0 : Script::Request rq(m_ScriptInterface);
129 0 : JS::RootedObject globalObj(rq.cx, rq.glob);
130 0 : JS::RootedValue result(rq.cx);
131 0 : if (!JS_CallFunctionValue(rq.cx, globalObj, m_GlobalHotkeys[hotkey][eventName], JS::HandleValueArray::empty(), &result))
132 0 : Script::Exception::CatchPending(rq);
133 0 : }
134 :
135 4 : std::map<CStr, std::vector<IGUIObject*> >::iterator it = m_HotkeyObjects.find(hotkey);
136 4 : if (it != m_HotkeyObjects.end())
137 0 : for (IGUIObject* const& obj : it->second)
138 : {
139 0 : if (!obj->IsEnabled())
140 0 : continue;
141 0 : if (ev.type == SDL_HOTKEYPRESS)
142 0 : ret = obj->SendEvent(GUIM_PRESSED, EventNamePress);
143 0 : else if (ev.type == SDL_HOTKEYDOWN)
144 0 : ret = obj->SendEvent(GUIM_KEYDOWN, EventNameKeyDown);
145 : else
146 0 : ret = obj->SendEvent(GUIM_RELEASED, EventNameRelease);
147 : }
148 : }
149 :
150 3 : else if (ev.type == SDL_MOUSEMOTION)
151 : {
152 : // Yes the mouse position is stored as float to avoid
153 : // constant conversions when operating in a
154 : // float-based environment.
155 0 : m_MousePos = CVector2D(static_cast<float>(ev.motion.x) / g_VideoMode.GetScale(), static_cast<float>(ev.motion.y) / g_VideoMode.GetScale());
156 :
157 0 : SGUIMessage msg(GUIM_MOUSE_MOTION);
158 0 : m_BaseObject->RecurseObject(&IGUIObject::IsHiddenOrGhostOrOutOfBoundaries, &IGUIObject::HandleMessage, msg);
159 0 : }
160 :
161 : // Update m_MouseButtons. (BUTTONUP is handled later.)
162 3 : else if (ev.type == SDL_MOUSEBUTTONDOWN)
163 : {
164 0 : switch (ev.button.button)
165 : {
166 0 : case SDL_BUTTON_LEFT:
167 0 : case SDL_BUTTON_RIGHT:
168 0 : case SDL_BUTTON_MIDDLE:
169 0 : m_MouseButtons |= Bit<unsigned int>(ev.button.button);
170 0 : break;
171 : default:
172 : break;
173 : }
174 : }
175 :
176 : // Update m_MousePos (for delayed mouse button events)
177 7 : CVector2D oldMousePos = m_MousePos;
178 7 : if (ev.type == SDL_MOUSEBUTTONDOWN || ev.type == SDL_MOUSEBUTTONUP)
179 : {
180 0 : m_MousePos = CVector2D(static_cast<float>(ev.button.x) / g_VideoMode.GetScale(), static_cast<float>(ev.button.y) / g_VideoMode.GetScale());
181 : }
182 :
183 : // Allow the focused object to pre-empt regular GUI events.
184 7 : if (GetFocusedObject())
185 0 : ret = GetFocusedObject()->PreemptEvent(ev);
186 :
187 : // Only one object can be hovered
188 : // pNearest will after this point at the hovered object, possibly nullptr
189 7 : IGUIObject* pNearest = FindObjectUnderMouse();
190 :
191 7 : if (ret == Input::Reaction::PASS)
192 : {
193 : // Now we'll call UpdateMouseOver on *all* objects,
194 : // we'll input the one hovered, and they will each
195 : // update their own data and send messages accordingly
196 7 : m_BaseObject->RecurseObject(&IGUIObject::IsHiddenOrGhostOrOutOfBoundaries, &IGUIObject::UpdateMouseOver, static_cast<IGUIObject* const&>(pNearest));
197 :
198 7 : if (ev.type == SDL_MOUSEBUTTONDOWN)
199 : {
200 0 : switch (ev.button.button)
201 : {
202 0 : case SDL_BUTTON_LEFT:
203 : // Focus the clicked object (or focus none if nothing clicked on)
204 0 : SetFocusedObject(pNearest);
205 :
206 0 : if (pNearest)
207 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_PRESS_LEFT, EventNameMouseLeftPress);
208 : break;
209 :
210 0 : case SDL_BUTTON_RIGHT:
211 0 : if (pNearest)
212 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_PRESS_RIGHT, EventNameMouseRightPress);
213 : break;
214 :
215 : default:
216 : break;
217 : }
218 : }
219 7 : else if (ev.type == SDL_MOUSEWHEEL && pNearest)
220 : {
221 0 : if (ev.wheel.y < 0)
222 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_WHEEL_DOWN, EventNameMouseWheelDown);
223 0 : else if (ev.wheel.y > 0)
224 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_WHEEL_UP, EventNameMouseWheelUp);
225 :
226 0 : if (ev.wheel.x < 0)
227 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_WHEEL_LEFT, EventNameMouseWheelLeft);
228 0 : else if (ev.wheel.x > 0)
229 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_WHEEL_RIGHT, EventNameMouseWheelRight);
230 : }
231 7 : else if (ev.type == SDL_MOUSEBUTTONUP)
232 : {
233 0 : switch (ev.button.button)
234 : {
235 0 : case SDL_BUTTON_LEFT:
236 0 : if (pNearest)
237 : {
238 0 : double timeElapsed = timer_Time() - pNearest->m_LastClickTime[SDL_BUTTON_LEFT];
239 0 : pNearest->m_LastClickTime[SDL_BUTTON_LEFT] = timer_Time();
240 0 : if (timeElapsed < SELECT_DBLCLICK_RATE)
241 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_DBLCLICK_LEFT, EventNameMouseLeftDoubleClick);
242 : else
243 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_RELEASE_LEFT, EventNameMouseLeftRelease);
244 : }
245 : break;
246 0 : case SDL_BUTTON_RIGHT:
247 0 : if (pNearest)
248 : {
249 0 : double timeElapsed = timer_Time() - pNearest->m_LastClickTime[SDL_BUTTON_RIGHT];
250 0 : pNearest->m_LastClickTime[SDL_BUTTON_RIGHT] = timer_Time();
251 0 : if (timeElapsed < SELECT_DBLCLICK_RATE)
252 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_DBLCLICK_RIGHT, EventNameMouseRightDoubleClick);
253 : else
254 0 : ret = pNearest->SendMouseEvent(GUIM_MOUSE_RELEASE_RIGHT, EventNameMouseRightRelease);
255 : }
256 : break;
257 : }
258 :
259 : // Reset all states on all visible objects
260 0 : m_BaseObject->RecurseObject(&IGUIObject::IsHidden, &IGUIObject::ResetStates);
261 :
262 : // Since the hover state will have been reset, we reload it.
263 0 : m_BaseObject->RecurseObject(&IGUIObject::IsHiddenOrGhostOrOutOfBoundaries, &IGUIObject::UpdateMouseOver, static_cast<IGUIObject* const&>(pNearest));
264 : }
265 : }
266 :
267 : // BUTTONUP's effect on m_MouseButtons is handled after
268 : // everything else, so that e.g. 'press' handlers (activated
269 : // on button up) see which mouse button had been pressed.
270 7 : if (ev.type == SDL_MOUSEBUTTONUP)
271 : {
272 0 : switch (ev.button.button)
273 : {
274 0 : case SDL_BUTTON_LEFT:
275 0 : case SDL_BUTTON_RIGHT:
276 0 : case SDL_BUTTON_MIDDLE:
277 0 : m_MouseButtons &= ~Bit<unsigned int>(ev.button.button);
278 0 : break;
279 : default:
280 : break;
281 : }
282 : }
283 :
284 : // Restore m_MousePos (for delayed mouse button events)
285 7 : if (ev.type == SDL_MOUSEBUTTONDOWN || ev.type == SDL_MOUSEBUTTONUP)
286 0 : m_MousePos = oldMousePos;
287 :
288 : // Let GUI items handle keys after everything else, e.g. for input boxes.
289 7 : if (ret == Input::Reaction::PASS && GetFocusedObject())
290 : {
291 0 : if (ev.type == SDL_KEYUP || ev.type == SDL_KEYDOWN ||
292 0 : ev.type == SDL_HOTKEYUP || ev.type == SDL_HOTKEYDOWN ||
293 0 : ev.type == SDL_TEXTINPUT || ev.type == SDL_TEXTEDITING)
294 0 : ret = GetFocusedObject()->ManuallyHandleKeys(ev);
295 : // else will return IN_PASS because we never used the button.
296 : }
297 :
298 7 : return ret;
299 : }
300 :
301 0 : JS::Value CGUI::GetHotloadData(const Script::Request& rq)
302 : {
303 0 : JS::RootedValue oldNamespace{rq.cx, m_LoadModuleResult.has_value() ?
304 0 : JS::ObjectValue(*m_LoadModuleResult->moduleNamespace) : rq.globalValue()};
305 0 : JS::RootedValue hotloadDataVal(rq.cx);
306 0 : Script::Function::Call(rq, oldNamespace, "getHotloadData", &hotloadDataVal);
307 0 : return hotloadDataVal;
308 0 : }
309 :
310 16 : JSObject* CGUI::CallPageInit(const Script::Request& rq, Script::StructuredClone initData,
311 : JS::HandleValue hotloadDataVal, const std::string_view scriptName)
312 : {
313 16 : JS::RootedValue initDataVal{rq.cx};
314 16 : if (initData)
315 16 : Script::ReadStructuredClone(rq, initData, &initDataVal);
316 16 : JS::RootedValue newNamespace{rq.cx, m_LoadModuleResult.has_value() ?
317 16 : JS::ObjectValue(*m_LoadModuleResult->moduleNamespace) : rq.globalValue()};
318 :
319 16 : if (!Script::HasProperty(rq, newNamespace, "init"))
320 : return nullptr;
321 :
322 14 : JS::RootedValue returnValue{rq.cx};
323 14 : if (!Script::Function::Call(rq, newNamespace, "init", &returnValue, initDataVal, hotloadDataVal))
324 : {
325 0 : LOGERROR("GUI page '{}': Failed to call init() function", scriptName);
326 0 : return nullptr;
327 : }
328 :
329 14 : if (!returnValue.isObject())
330 : return nullptr;
331 :
332 14 : JS::RootedObject returnObject{rq.cx, &returnValue.toObject()};
333 14 : if (!JS::IsPromiseObject(returnObject))
334 : return nullptr;
335 :
336 14 : return returnObject;
337 16 : }
338 :
339 18 : JSObject* CGUI::TickObjects(const Script::Request& rq, Script::StructuredClone initData,
340 : const std::string_view scriptName)
341 : {
342 18 : JS::RootedObject sendingPromise{rq.cx};
343 18 : if (m_LoadModuleResult.has_value() && m_LoadModuleResult->iterator->IsDone())
344 : {
345 0 : JS::RootedValue hotloadData{rq.cx, GetHotloadData(rq)};
346 0 : try
347 : {
348 0 : m_LoadModuleResult->moduleNamespace = m_LoadModuleResult->iterator->Get();
349 : }
350 0 : catch(const std::exception& e)
351 : {
352 0 : LOGERROR("{}", e.what());
353 0 : }
354 0 : ++m_LoadModuleResult->iterator;
355 0 : sendingPromise = CallPageInit(rq, initData, hotloadData, scriptName);
356 0 : }
357 :
358 18 : m_BaseObject->RecurseObject(&IGUIObject::IsHiddenOrGhostOrOutOfBoundaries, &IGUIObject::Tick);
359 18 : SendEventToAll(EventNameTick);
360 18 : m_Tooltip.Update(FindObjectUnderMouse(), m_MousePos, *this);
361 18 : return sendingPromise;
362 18 : }
363 :
364 35 : void CGUI::SendEventToAll(const CStr& eventName,
365 : const JS::HandleValueArray paramData /* = JS::HandleValueArray::empty() */)
366 : {
367 35 : std::unordered_map<CStr, std::vector<IGUIObject*>>::iterator it = m_EventObjects.find(eventName);
368 35 : if (it == m_EventObjects.end())
369 33 : return;
370 :
371 2 : std::vector<IGUIObject*> copy = it->second;
372 7 : for (IGUIObject* object : copy)
373 5 : object->ScriptEvent(eventName, paramData);
374 2 : }
375 :
376 0 : void CGUI::Draw(CCanvas2D& canvas)
377 : {
378 0 : CGUIObjectEventBroadcaster::RecurseVisibleObject(m_BaseObject.get(), &IGUIObject::Draw, canvas);
379 0 : }
380 :
381 0 : void CGUI::DrawSprite(const CGUISpriteInstance& Sprite, CCanvas2D& canvas, const CRect& Rect, const CRect& Clipping)
382 : {
383 : // If the sprite doesn't exist (name == ""), don't bother drawing anything
384 0 : if (!Sprite)
385 0 : return;
386 :
387 0 : std::optional<CCanvas2D::ScopedScissor> scopedScissor;
388 0 : if (Clipping != CRect())
389 0 : scopedScissor.emplace(canvas, Clipping);
390 :
391 0 : Sprite.Draw(*this, canvas, Rect, m_Sprites);
392 0 : }
393 :
394 0 : void CGUI::UpdateResolution()
395 : {
396 0 : m_BaseObject->RecurseObject(nullptr, &IGUIObject::HandleSizeChanged);
397 0 : }
398 :
399 4 : std::unique_ptr<IGUIObject> CGUI::ConstructObject(const CStr& str)
400 : {
401 4 : std::map<CStr, ConstructObjectFunction>::iterator it = m_ObjectTypes.find(str);
402 :
403 4 : if (it == m_ObjectTypes.end())
404 0 : return nullptr;
405 :
406 4 : return (*it->second)(*this);
407 : }
408 :
409 4 : void CGUI::AddObject(IGUIObject& parent, std::unique_ptr<IGUIObject> child)
410 : {
411 4 : if (child->m_Name.empty())
412 : {
413 0 : LOGERROR("Can't register an object without name!");
414 0 : return;
415 : }
416 :
417 4 : if (m_pAllObjects.find(child->m_Name) != m_pAllObjects.end())
418 : {
419 0 : LOGERROR("Can't register more than one object of the name {}", child->m_Name);
420 0 : return;
421 : }
422 :
423 4 : parent.RegisterChild(child.get());
424 4 : m_pAllObjects[child->m_Name] = std::move(child);
425 : }
426 :
427 121 : IGUIObject* CGUI::GetBaseObject()
428 : {
429 121 : return m_BaseObject.get();
430 : };
431 :
432 0 : bool CGUI::ObjectExists(const CStr& Name) const
433 : {
434 0 : return m_pAllObjects.find(Name) != m_pAllObjects.end();
435 : }
436 :
437 5 : IGUIObject* CGUI::TryFindObjectByName(const CStr& Name) const
438 : {
439 0 : map_pObjects::const_iterator it = m_pAllObjects.find(Name);
440 :
441 5 : if (it == m_pAllObjects.end())
442 : return nullptr;
443 :
444 5 : return it->second.get();
445 : }
446 :
447 5 : IGUIObject* CGUI::FindObjectByName(const CStr& Name) const
448 : {
449 5 : IGUIObject* obj = TryFindObjectByName(Name);
450 5 : if (obj == nullptr)
451 : {
452 0 : LOGERROR("Failed to get GUI object by name: object '{}' not found. Note: Use "
453 : "'Engine.TryGetGUIObjectByName' to query for potentially non-existent objects instead.",
454 : Name);
455 : }
456 :
457 5 : return obj;
458 : }
459 :
460 32 : IGUIObject* CGUI::FindObjectUnderMouse()
461 : {
462 32 : IGUIObject* pNearest = nullptr;
463 32 : m_BaseObject->RecurseObject(&IGUIObject::IsHiddenOrGhostOrOutOfBoundaries, &IGUIObject::ChooseMouseOverAndClosest, pNearest);
464 32 : return pNearest;
465 : }
466 :
467 2 : CSize2D CGUI::GetWindowSize() const
468 : {
469 2 : return CSize2D{static_cast<float>(g_VideoMode.GetWindowWidth()) / g_VideoMode.GetScale(), static_cast<float>(g_VideoMode.GetWindowHeight()) / g_VideoMode.GetScale() };
470 : }
471 :
472 27 : void CGUI::SendFocusMessage(EGUIMessageType msgType)
473 : {
474 27 : if (m_FocusedObject)
475 : {
476 0 : SGUIMessage msg(msgType);
477 0 : m_FocusedObject->HandleMessage(msg);
478 0 : }
479 27 : }
480 :
481 0 : void CGUI::SetFocusedObject(IGUIObject* pObject)
482 : {
483 0 : if (pObject == m_FocusedObject)
484 : return;
485 :
486 0 : if (m_FocusedObject)
487 : {
488 0 : SGUIMessage msg(GUIM_LOST_FOCUS);
489 0 : m_FocusedObject->HandleMessage(msg);
490 0 : }
491 :
492 0 : m_FocusedObject = pObject;
493 :
494 0 : if (m_FocusedObject)
495 : {
496 0 : SGUIMessage msg(GUIM_GOT_FOCUS);
497 0 : m_FocusedObject->HandleMessage(msg);
498 0 : }
499 : }
500 :
501 4 : void CGUI::SetObjectStyle(IGUIObject& object, const CStr& styleName)
502 : {
503 : // If the style is not recognised (or an empty string) then ApplyStyle will
504 : // emit an error message. Thus we don't need to handle it here.
505 4 : object.ApplyStyle(styleName);
506 4 : }
507 :
508 0 : void CGUI::UnsetObjectStyle(IGUIObject& object)
509 : {
510 0 : SetObjectStyle(object, "default");
511 0 : }
512 :
513 0 : void CGUI::SetObjectHotkey(IGUIObject& object, const CStr& hotkeyTag)
514 : {
515 0 : if (!hotkeyTag.empty())
516 0 : m_HotkeyObjects[hotkeyTag].push_back(&object);
517 0 : }
518 :
519 0 : void CGUI::UnsetObjectHotkey(IGUIObject& object, const CStr& hotkeyTag)
520 : {
521 0 : if (hotkeyTag.empty())
522 : return;
523 :
524 0 : std::vector<IGUIObject*>& assignment = m_HotkeyObjects[hotkeyTag];
525 :
526 0 : assignment.erase(
527 0 : std::remove_if(
528 : assignment.begin(),
529 : assignment.end(),
530 0 : [&object](const IGUIObject* hotkeyObject)
531 0 : { return &object == hotkeyObject; }),
532 0 : assignment.end());
533 : }
534 :
535 0 : void CGUI::SetGlobalHotkey(const CStr& hotkeyTag, const CStr& eventName, JS::HandleValue function)
536 : {
537 0 : Script::Request rq(*m_ScriptInterface);
538 :
539 0 : if (hotkeyTag.empty())
540 0 : throw std::invalid_argument{"Cannot assign a function to an empty hotkey identifier!"};
541 :
542 : // Only support "Press", "Keydown" and "Release" events.
543 0 : if (eventName != EventNamePress && eventName != EventNameKeyDown && eventName != EventNameRelease)
544 0 : throw std::invalid_argument{"Cannot assign a function to an unsupported event!"};
545 :
546 0 : if (!function.isObject() || !JS::IsCallable(&function.toObject()))
547 : {
548 0 : throw std::invalid_argument{fmt::format(
549 0 : "Cannot assign non-function value to global hotkey '{}'", hotkeyTag.c_str())};
550 : }
551 :
552 0 : UnsetGlobalHotkey(hotkeyTag, eventName);
553 0 : m_GlobalHotkeys[hotkeyTag][eventName].init(rq.cx, function);
554 0 : }
555 :
556 0 : void CGUI::UnsetGlobalHotkey(const CStr& hotkeyTag, const CStr& eventName)
557 : {
558 0 : std::map<CStr, std::map<CStr, JS::PersistentRootedValue>>::iterator it = m_GlobalHotkeys.find(hotkeyTag);
559 0 : if (it == m_GlobalHotkeys.end())
560 0 : return;
561 :
562 0 : m_GlobalHotkeys[hotkeyTag].erase(eventName);
563 :
564 0 : if (m_GlobalHotkeys.count(hotkeyTag) == 0)
565 0 : m_GlobalHotkeys.erase(it);
566 : }
567 :
568 0 : const SGUIScrollBarStyle* CGUI::GetScrollBarStyle(const CStr& style) const
569 : {
570 0 : std::map<CStr, const SGUIScrollBarStyle>::const_iterator it = m_ScrollBarStyles.find(style);
571 0 : if (it == m_ScrollBarStyles.end())
572 : return nullptr;
573 :
574 0 : return &it->second;
575 : }
576 :
577 : /**
578 : * @callgraph
579 : */
580 28 : void CGUI::LoadXmlFile(const VfsPath& Filename, std::unordered_set<VfsPath>& Paths)
581 : {
582 28 : Paths.insert(Filename);
583 :
584 28 : CXeromyces xeroFile;
585 28 : if (xeroFile.Load(g_VFS, Filename, "gui") != PSRETURN_OK)
586 : // The error has already been reported by CXeromyces
587 0 : return;
588 :
589 28 : XMBElement node = xeroFile.GetRoot();
590 28 : std::string_view root_name(xeroFile.GetElementStringView(node.GetNodeName()));
591 :
592 28 : if (root_name == "objects")
593 18 : Xeromyces_ReadRootObjects(xeroFile, node, Paths);
594 10 : else if (root_name == "sprites")
595 0 : Xeromyces_ReadRootSprites(xeroFile, node);
596 10 : else if (root_name == "styles")
597 10 : Xeromyces_ReadRootStyles(xeroFile, node);
598 0 : else if (root_name == "setup")
599 0 : Xeromyces_ReadRootSetup(xeroFile, node);
600 : else
601 1 : LOGERROR("CGUI::LoadXmlFile encountered an unknown XML root node type: {}", root_name.data());
602 27 : }
603 :
604 17 : void CGUI::LoadedXmlFiles()
605 : {
606 17 : m_BaseObject->RecurseObject(nullptr, &IGUIObject::HandleSizeChanged);
607 :
608 17 : SGUIMessage msg(GUIM_LOAD);
609 17 : m_BaseObject->RecurseObject(nullptr, &IGUIObject::HandleMessage, msg);
610 :
611 17 : SendEventToAll(EventNameLoad);
612 17 : }
613 :
614 : //===================================================================
615 : // XML Reading Xeromyces Specific Sub-Routines
616 : //===================================================================
617 :
618 18 : void CGUI::Xeromyces_ReadRootObjects(const XMBData& xmb, XMBElement element, std::unordered_set<VfsPath>& Paths)
619 : {
620 18 : int el_script = xmb.GetElementID("script");
621 :
622 18 : std::vector<std::pair<CStr, CStr> > subst;
623 :
624 : // Iterate main children
625 : // they should all be <object> or <script> elements
626 103 : for (XMBElement child : element.GetChildNodes())
627 : {
628 23 : if (child.GetNodeName() == el_script)
629 : // Execute the inline script
630 19 : Xeromyces_ReadScript(xmb, child, Paths);
631 : else
632 : // Read in this whole object into the GUI
633 4 : Xeromyces_ReadObject(xmb, child, *m_BaseObject, subst, Paths, 0);
634 : }
635 18 : }
636 :
637 0 : void CGUI::Xeromyces_ReadRootSprites(const XMBData& xmb, XMBElement element)
638 : {
639 0 : for (XMBElement child : element.GetChildNodes())
640 0 : Xeromyces_ReadSprite(xmb, child);
641 0 : }
642 :
643 10 : void CGUI::Xeromyces_ReadRootStyles(const XMBData& xmb, XMBElement element)
644 : {
645 40 : for (XMBElement child : element.GetChildNodes())
646 10 : Xeromyces_ReadStyle(xmb, child);
647 10 : }
648 :
649 0 : void CGUI::Xeromyces_ReadRootSetup(const XMBData& xmb, XMBElement element)
650 : {
651 0 : for (XMBElement child : element.GetChildNodes())
652 : {
653 0 : std::string_view name(xmb.GetElementStringView(child.GetNodeName()));
654 0 : if (name == "scrollbar")
655 0 : Xeromyces_ReadScrollBarStyle(xmb, child);
656 0 : else if (name == "icon")
657 0 : Xeromyces_ReadIcon(xmb, child);
658 0 : else if (name == "tooltip")
659 0 : Xeromyces_ReadTooltip(xmb, child);
660 0 : else if (name == "color")
661 0 : Xeromyces_ReadColor(xmb, child);
662 : else
663 0 : debug_warn(L"Invalid data - DTD shouldn't allow this");
664 : }
665 0 : }
666 :
667 4 : void CGUI::Xeromyces_ReadObject(const XMBData& xmb, XMBElement element, IGUIObject& parent,
668 : std::vector<std::pair<CStr, CStr> >& NameSubst, std::unordered_set<VfsPath>& Paths,
669 : std::uint32_t nesting_depth)
670 : {
671 4 : XMBAttributeList attributes = element.GetAttributes();
672 :
673 4 : CStr type(attributes.GetNamedItem(xmb.GetAttributeID("type")));
674 4 : if (type.empty())
675 4 : type = "empty";
676 :
677 : // Construct object from specified type
678 : // henceforth, we need to do a rollback before aborting.
679 : // i.e. releasing this object
680 4 : std::unique_ptr<IGUIObject> object = ConstructObject(type);
681 :
682 4 : if (!object)
683 : {
684 0 : LOGERROR("GUI: Unrecognized object type \"{}\"", type);
685 0 : return;
686 : }
687 :
688 : // Cache some IDs for element attribute names, to avoid string comparisons
689 : #define ELMT(x) int elmt_##x = xmb.GetElementID(#x)
690 : #define ATTR(x) int attr_##x = xmb.GetAttributeID(#x)
691 4 : ELMT(object);
692 4 : ELMT(action);
693 4 : ELMT(script);
694 4 : ELMT(repeat);
695 4 : ELMT(translatableAttribute);
696 4 : ELMT(translate);
697 4 : ELMT(attribute);
698 4 : ELMT(keep);
699 4 : ELMT(include);
700 4 : ATTR(style);
701 4 : ATTR(type);
702 4 : ATTR(name);
703 4 : ATTR(z);
704 4 : ATTR(on);
705 4 : ATTR(file);
706 4 : ATTR(directory);
707 4 : ATTR(id);
708 4 : ATTR(context);
709 :
710 : //
711 : // Read Style and set defaults
712 : //
713 : // If the setting "style" is set, try loading that setting.
714 : //
715 : // Always load default (if it's available) first!
716 : //
717 8 : SetObjectStyle(*object, "default");
718 :
719 4 : CStr argStyle(attributes.GetNamedItem(attr_style));
720 4 : if (!argStyle.empty())
721 0 : SetObjectStyle(*object, argStyle);
722 :
723 4 : bool NameSet = false;
724 4 : bool ManuallySetZ = false;
725 :
726 16 : for (XMBAttribute attr : attributes)
727 : {
728 : // If value is "null", then it is equivalent as never being entered
729 4 : if (attr.Value == "null")
730 0 : continue;
731 :
732 : // Ignore "type" and "style", we've already checked it
733 4 : if (attr.Name == attr_type || attr.Name == attr_style)
734 0 : continue;
735 :
736 4 : if (attr.Name == attr_name)
737 : {
738 4 : CStr name(attr.Value);
739 :
740 4 : if (name.starts_with("__"))
741 : {
742 0 : LOGERROR("GUI: Names starting with '__' are reserved for the engine (object: {})",
743 : name);
744 0 : continue;
745 0 : }
746 :
747 4 : for (const std::pair<CStr, CStr>& sub : NameSubst)
748 0 : PS::ReplaceSubrange(name, sub.first, sub.second);
749 :
750 4 : object->SetName(name);
751 4 : NameSet = true;
752 4 : continue;
753 4 : }
754 :
755 0 : if (attr.Name == attr_z)
756 0 : ManuallySetZ = true;
757 :
758 0 : object->SetSettingFromString(xmb.GetAttributeString(attr.Name), attr.Value.FromUTF8(), false);
759 4 : }
760 :
761 : // Check if name isn't set, generate an internal name in that case.
762 4 : if (!NameSet)
763 : {
764 0 : object->SetName(fmt::format("__internal({})", m_InternalNameNumber));
765 0 : ++m_InternalNameNumber;
766 : }
767 :
768 4 : CStrW caption(element.GetText().FromUTF8());
769 4 : if (!caption.empty())
770 0 : object->SetSettingFromString("caption", caption, false);
771 :
772 8 : for (XMBElement child : element.GetChildNodes())
773 : {
774 : // Check what name the elements got
775 0 : int element_name = child.GetNodeName();
776 :
777 0 : if (element_name == elmt_object)
778 : {
779 : // Call this function on the child
780 0 : Xeromyces_ReadObject(xmb, child, *object, NameSubst, Paths, nesting_depth);
781 : }
782 0 : else if (element_name == elmt_action)
783 : {
784 : // Scripted <action> element
785 :
786 : // Check for a 'file' parameter
787 0 : CStrW filename(child.GetAttributes().GetNamedItem(attr_file).FromUTF8());
788 :
789 0 : CStr code;
790 :
791 : // If there is a file, open it and use it as the code
792 0 : if (!filename.empty())
793 : {
794 0 : Paths.insert(filename);
795 0 : CVFSFile scriptfile;
796 0 : if (scriptfile.Load(g_VFS, filename) != PSRETURN_OK)
797 : {
798 0 : LOGERROR("Error opening GUI script action file '{}'",
799 : utf8_from_wstring(filename));
800 0 : continue;
801 0 : }
802 :
803 0 : code = scriptfile.DecodeUTF8(); // assume it's UTF-8
804 0 : }
805 :
806 0 : XMBElementList grandchildren = child.GetChildNodes();
807 0 : if (!grandchildren.empty()) // The <action> element contains <keep> and <translate> tags.
808 0 : for (XMBElement grandchild : grandchildren)
809 : {
810 0 : if (grandchild.GetNodeName() == elmt_translate)
811 0 : code += g_L10n.Translate(grandchild.GetText());
812 0 : else if (grandchild.GetNodeName() == elmt_keep)
813 0 : code += grandchild.GetText();
814 : }
815 : else // It's pure JavaScript code.
816 : // Read the inline code (concatenating to the file code, if both are specified)
817 0 : code += CStr(child.GetText());
818 :
819 0 : CStr eventName = child.GetAttributes().GetNamedItem(attr_on);
820 0 : object->RegisterScriptHandler(eventName, code, *this);
821 0 : }
822 0 : else if (child.GetNodeName() == elmt_script)
823 : {
824 0 : Xeromyces_ReadScript(xmb, child, Paths);
825 : }
826 0 : else if (element_name == elmt_repeat)
827 : {
828 0 : Xeromyces_ReadRepeat(xmb, child, *object, NameSubst, Paths, nesting_depth);
829 : }
830 0 : else if (element_name == elmt_translatableAttribute)
831 : {
832 : // This is an element in the form "<translatableAttribute id="attributeName">attributeValue</translatableAttribute>".
833 0 : CStr attributeName(child.GetAttributes().GetNamedItem(attr_id)); // Read the attribute name.
834 0 : if (attributeName.empty())
835 : {
836 0 : LOGERROR("GUI: 'translatableAttribute' XML element with empty 'id' XML attribute "
837 : "found. (object: {})", object->GetPresentableName());
838 0 : continue;
839 0 : }
840 :
841 0 : CStr value(child.GetText());
842 0 : if (value.empty())
843 0 : continue;
844 :
845 0 : CStr context(child.GetAttributes().GetNamedItem(attr_context)); // Read the context if any.
846 :
847 0 : CStr translatedValue = context.empty() ?
848 0 : g_L10n.Translate(value) :
849 0 : g_L10n.TranslateWithContext(context, value);
850 :
851 0 : object->SetSettingFromString(attributeName, translatedValue.FromUTF8(), false);
852 0 : }
853 0 : else if (element_name == elmt_attribute)
854 : {
855 : // This is an element in the form "<attribute id="attributeName"><keep>Don't translate this part
856 : // </keep><translate>but translate this one.</translate></attribute>".
857 0 : CStr attributeName(child.GetAttributes().GetNamedItem(attr_id)); // Read the attribute name.
858 0 : if (attributeName.empty())
859 : {
860 0 : LOGERROR("GUI: 'attribute' XML element with empty 'id' XML attribute found. "
861 : "(object: {})", object->GetPresentableName());
862 0 : continue;
863 0 : }
864 :
865 0 : CStr translatedValue;
866 :
867 0 : for (XMBElement grandchild : child.GetChildNodes())
868 : {
869 0 : if (grandchild.GetNodeName() == elmt_translate)
870 0 : translatedValue += g_L10n.Translate(grandchild.GetText());
871 0 : else if (grandchild.GetNodeName() == elmt_keep)
872 0 : translatedValue += grandchild.GetText();
873 : }
874 0 : object->SetSettingFromString(attributeName, translatedValue.FromUTF8(), false);
875 0 : }
876 0 : else if (element_name == elmt_include)
877 : {
878 0 : CStrW filename(child.GetAttributes().GetNamedItem(attr_file).FromUTF8());
879 0 : CStrW directory(child.GetAttributes().GetNamedItem(attr_directory).FromUTF8());
880 0 : if (!filename.empty())
881 : {
882 0 : if (!directory.empty())
883 : {
884 0 : LOGWARNING("GUI: Include element found with file name ({}) and directory "
885 : "name ({}). Only the file will be processed.",
886 : utf8_from_wstring(filename), utf8_from_wstring(directory));
887 : }
888 :
889 0 : Paths.insert(filename);
890 :
891 0 : CXeromyces xeroIncluded;
892 0 : if (xeroIncluded.Load(g_VFS, filename, "gui") != PSRETURN_OK)
893 : {
894 0 : LOGERROR("GUI: Error reading included XML: '{}'",
895 : utf8_from_wstring(filename));
896 0 : continue;
897 0 : }
898 :
899 0 : XMBElement node = xeroIncluded.GetRoot();
900 0 : if (node.GetNodeName() != xeroIncluded.GetElementID("object"))
901 : {
902 0 : LOGERROR("GUI: Error reading included XML: '{}', root element must have "
903 : "be of type 'object'.", utf8_from_wstring(filename));
904 0 : continue;
905 0 : }
906 :
907 0 : if (nesting_depth+1 >= MAX_OBJECT_DEPTH)
908 : {
909 0 : LOGERROR("GUI: Too many nested GUI includes. Probably caused by a recursive "
910 : "include attribute. Abort rendering '{}'.",
911 : utf8_from_wstring(filename));
912 0 : continue;
913 0 : }
914 :
915 0 : Xeromyces_ReadObject(xeroIncluded, node, *object, NameSubst, Paths,
916 : nesting_depth + 1);
917 0 : }
918 0 : else if (!directory.empty())
919 : {
920 0 : if (nesting_depth+1 >= MAX_OBJECT_DEPTH)
921 : {
922 0 : LOGERROR("GUI: Too many nested GUI includes. Probably caused by a recursive "
923 : "include attribute. Abort rendering '{}'.",
924 : utf8_from_wstring(directory));
925 0 : continue;
926 0 : }
927 :
928 0 : VfsPaths pathnames;
929 0 : vfs::GetPathnames(g_VFS, directory, L"*.xml", pathnames);
930 0 : for (const VfsPath& path : pathnames)
931 : {
932 : // as opposed to loading scripts, don't care if it's loaded before
933 : // one might use the same parts of the GUI in different situations
934 0 : Paths.insert(path);
935 0 : CXeromyces xeroIncluded;
936 0 : if (xeroIncluded.Load(g_VFS, path, "gui") != PSRETURN_OK)
937 : {
938 0 : LOGERROR("GUI: Error reading included XML: '{}'", path.string8());
939 0 : continue;
940 0 : }
941 :
942 0 : XMBElement node = xeroIncluded.GetRoot();
943 0 : if (node.GetNodeName() != xeroIncluded.GetElementID("object"))
944 : {
945 0 : LOGERROR("GUI: Error reading included XML: '{}', root element must "
946 : "have be of type 'object'.", path.string8());
947 0 : continue;
948 0 : }
949 0 : Xeromyces_ReadObject(xeroIncluded, node, *object, NameSubst, Paths,
950 : nesting_depth + 1);
951 0 : }
952 :
953 0 : }
954 : else
955 0 : LOGERROR("GUI: 'include' XML element must have valid 'file' or 'directory' "
956 : "attribute found. (object {})", object->GetPresentableName());
957 0 : }
958 : else
959 : {
960 : // Try making the object read the tag.
961 0 : if (!object->HandleAdditionalChildren(xmb, child))
962 : {
963 0 : LOGERROR("GUI: (object: {}) Reading unknown children for its type",
964 : object->GetPresentableName().c_str());
965 : }
966 : }
967 : }
968 :
969 4 : object->AdditionalChildrenHandled();
970 :
971 4 : if (!ManuallySetZ)
972 : {
973 : // Set it automatically to 10 plus its parents
974 4 : if (object->m_Absolute)
975 : // If the object is absolute, we'll have to get the parent's Z buffered,
976 : // and add to that!
977 4 : object->m_Z.Set(parent.GetBufferedZ() + 10.f, false);
978 : else
979 : // If the object is relative, then we'll just store Z as "10"
980 0 : object->m_Z.Set(10.f, false);
981 : }
982 :
983 8 : AddObject(parent, std::move(object));
984 4 : }
985 :
986 0 : void CGUI::Xeromyces_ReadRepeat(const XMBData& xmb, XMBElement element, IGUIObject& parent,
987 : std::vector<std::pair<CStr, CStr>>& NameSubst, std::unordered_set<VfsPath>& Paths,
988 : std::uint32_t nesting_depth)
989 : {
990 : #define ELMT(x) int elmt_##x = xmb.GetElementID(#x)
991 : #define ATTR(x) int attr_##x = xmb.GetAttributeID(#x)
992 0 : ELMT(object);
993 0 : ATTR(count);
994 0 : ATTR(var);
995 :
996 0 : XMBAttributeList attributes = element.GetAttributes();
997 :
998 0 : int count = CStr(attributes.GetNamedItem(attr_count)).ToInt();
999 0 : CStr var("["+attributes.GetNamedItem(attr_var)+"]");
1000 0 : if (var.size() < 3)
1001 0 : var = "[n]";
1002 :
1003 0 : for (int n = 0; n < count; ++n)
1004 : {
1005 0 : NameSubst.emplace_back(var, fmt::format("[{}]", n));
1006 :
1007 0 : for (XMBElement child : element.GetChildNodes())
1008 : {
1009 0 : if (child.GetNodeName() == elmt_object)
1010 0 : Xeromyces_ReadObject(xmb, child, parent, NameSubst, Paths, nesting_depth);
1011 : }
1012 0 : NameSubst.pop_back();
1013 : }
1014 0 : }
1015 :
1016 19 : void CGUI::Xeromyces_ReadScript(const XMBData& xmb, XMBElement element, std::unordered_set<VfsPath>& Paths)
1017 : {
1018 : // If there is a "module" attribute, save it so it can be loaded at the end. It isn't saved to `Path`
1019 : // because modules automatically get reloaded.
1020 19 : const std::string moduleAttribute{element.GetAttributes().GetNamedItem(xmb.GetAttributeID("module"))};
1021 19 : if (!moduleAttribute.empty())
1022 : {
1023 3 : if (m_LoadModuleResult.has_value())
1024 1 : throw std::logic_error{"There can only be one root module per page."};
1025 :
1026 2 : const Script::Request rq{m_ScriptInterface};
1027 2 : m_LoadModuleResult.emplace(rq, moduleAttribute);
1028 2 : }
1029 :
1030 : // If there is a "file" attribute, open and execute it
1031 19 : CStrW fileAttr(element.GetAttributes().GetNamedItem(xmb.GetAttributeID("file")).FromUTF8());
1032 18 : if (!fileAttr.empty())
1033 : {
1034 64 : if (!VfsPath(fileAttr).IsDirectory())
1035 : {
1036 48 : Paths.insert(fileAttr);
1037 48 : m_ScriptInterface->LoadGlobalScriptFile(fileAttr);
1038 : }
1039 : else
1040 0 : LOGERROR("GUI: Script path {} is not a file path", fileAttr.ToUTF8());
1041 : }
1042 :
1043 : // If there is a "directory" attribute, read all JS files in that directory
1044 18 : CStrW directoryAttr(element.GetAttributes().GetNamedItem(xmb.GetAttributeID("directory")).FromUTF8());
1045 18 : if (!directoryAttr.empty())
1046 : {
1047 0 : if (VfsPath(directoryAttr).IsDirectory())
1048 : {
1049 0 : VfsPaths pathnames;
1050 0 : vfs::GetPathnames(g_VFS, directoryAttr, L"*.js", pathnames);
1051 0 : for (const VfsPath& path : pathnames)
1052 : {
1053 : // Only load new files (so when the insert succeeds)
1054 0 : if (Paths.insert(path).second)
1055 0 : m_ScriptInterface->LoadGlobalScriptFile(path);
1056 : }
1057 0 : }
1058 : else
1059 0 : LOGERROR("GUI: Script path {} is not a directory path", directoryAttr.ToUTF8());
1060 : }
1061 :
1062 18 : CStr code(element.GetText());
1063 18 : if (!code.empty())
1064 0 : m_ScriptInterface->LoadGlobalScript(L"Some XML file", code);
1065 36 : }
1066 :
1067 0 : void CGUI::Xeromyces_ReadSprite(const XMBData& xmb, XMBElement element)
1068 : {
1069 0 : auto sprite = std::make_unique<CGUISprite>();
1070 :
1071 : // Get name, we know it exists because of DTD requirements
1072 0 : CStr name = element.GetAttributes().GetNamedItem(xmb.GetAttributeID("name"));
1073 :
1074 0 : if (m_Sprites.find(name) != m_Sprites.end())
1075 : {
1076 0 : LOGWARNING("GUI sprite name '{}' used more than once; first definition will be discarded",
1077 : name);
1078 : }
1079 :
1080 : // shared_ptr to link the effect to every image, faster than copy.
1081 0 : std::shared_ptr<SGUIImageEffects> effects;
1082 :
1083 0 : for (XMBElement child : element.GetChildNodes())
1084 : {
1085 0 : std::string_view ElementName(xmb.GetElementStringView(child.GetNodeName()));
1086 0 : if (ElementName == "image")
1087 0 : Xeromyces_ReadImage(xmb, child, *sprite);
1088 0 : else if (ElementName == "effect")
1089 : {
1090 0 : if (effects)
1091 0 : LOGERROR("GUI <sprite> must not have more than one <effect>");
1092 : else
1093 : {
1094 0 : effects = std::make_shared<SGUIImageEffects>();
1095 0 : Xeromyces_ReadEffects(xmb, child, *effects);
1096 : }
1097 : }
1098 : else
1099 0 : debug_warn(L"Invalid data - DTD shouldn't allow this");
1100 : }
1101 :
1102 : // Apply the effects to every image (unless the image overrides it with
1103 : // different effects)
1104 0 : if (effects)
1105 : {
1106 0 : for (const std::unique_ptr<SGUIImage>& image : sprite->m_Images)
1107 0 : if (!image->m_Effects)
1108 0 : image->m_Effects = effects;
1109 : }
1110 :
1111 0 : m_Sprites.erase(name);
1112 0 : m_Sprites.emplace(name, std::move(sprite));
1113 0 : }
1114 :
1115 0 : void CGUI::Xeromyces_ReadImage(const XMBData& xmb, XMBElement element, CGUISprite& parent)
1116 : {
1117 0 : auto image = std::make_unique<SGUIImage>();
1118 :
1119 : // TODO Gee: Setup defaults here (or maybe they are in the SGUIImage ctor)
1120 :
1121 0 : for (XMBAttribute attr : element.GetAttributes())
1122 : {
1123 0 : std::string_view attr_name(xmb.GetAttributeStringView(attr.Name));
1124 0 : CStrW attr_value(attr.Value.FromUTF8());
1125 :
1126 0 : if (attr_name == "texture")
1127 : {
1128 0 : image->m_TextureName = VfsPath("art/textures/ui") / attr_value;
1129 : }
1130 0 : else if (attr_name == "size")
1131 : {
1132 0 : image->m_Size.FromString(attr.Value);
1133 : }
1134 0 : else if (attr_name == "texture_size")
1135 : {
1136 0 : image->m_TextureSize.FromString(attr.Value);
1137 : }
1138 0 : else if (attr_name == "real_texture_placement")
1139 : {
1140 0 : CRect rect;
1141 0 : if (!ParseString<CRect>(this, attr_value, rect))
1142 : {
1143 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name,
1144 : utf8_from_wstring(attr_value));
1145 : }
1146 : else
1147 0 : image->m_TexturePlacementInFile = rect;
1148 : }
1149 0 : else if (attr_name == "fixed_h_aspect_ratio")
1150 : {
1151 0 : float val;
1152 0 : if (!ParseString<float>(this, attr_value, val))
1153 : {
1154 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name,
1155 : utf8_from_wstring(attr_value));
1156 : }
1157 : else
1158 0 : image->m_FixedHAspectRatio = val;
1159 : }
1160 0 : else if (attr_name == "round_coordinates")
1161 : {
1162 0 : bool b;
1163 0 : if (!ParseString<bool>(this, attr_value, b))
1164 : {
1165 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name,
1166 : utf8_from_wstring(attr_value));
1167 : }
1168 : else
1169 0 : image->m_RoundCoordinates = b;
1170 : }
1171 0 : else if (attr_name == "wrap_mode")
1172 : {
1173 0 : if (attr_value == L"repeat")
1174 0 : image->m_AddressMode = Renderer::Backend::Sampler::AddressMode::REPEAT;
1175 0 : else if (attr_value == L"mirrored_repeat")
1176 0 : image->m_AddressMode = Renderer::Backend::Sampler::AddressMode::MIRRORED_REPEAT;
1177 0 : else if (attr_value == L"clamp_to_edge")
1178 0 : image->m_AddressMode = Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE;
1179 : else
1180 : {
1181 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name,
1182 : utf8_from_wstring(attr_value));
1183 : }
1184 : }
1185 0 : else if (attr_name == "backcolor")
1186 : {
1187 0 : if (!ParseString<CGUIColor>(this, attr_value, image->m_BackColor))
1188 : {
1189 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name,
1190 : utf8_from_wstring(attr_value));
1191 : }
1192 : }
1193 : else
1194 0 : debug_warn(L"Invalid data - DTD shouldn't allow this");
1195 0 : }
1196 :
1197 : // Look for effects
1198 0 : for (XMBElement child : element.GetChildNodes())
1199 : {
1200 0 : std::string_view ElementName(xmb.GetElementStringView(child.GetNodeName()));
1201 0 : if (ElementName == "effect")
1202 : {
1203 0 : if (image->m_Effects)
1204 0 : LOGERROR("GUI <image> must not have more than one <effect>");
1205 : else
1206 : {
1207 0 : image->m_Effects = std::make_shared<SGUIImageEffects>();
1208 0 : Xeromyces_ReadEffects(xmb, child, *image->m_Effects);
1209 : }
1210 : }
1211 : else
1212 0 : debug_warn(L"Invalid data - DTD shouldn't allow this");
1213 : }
1214 :
1215 0 : parent.AddImage(std::move(image));
1216 0 : }
1217 :
1218 0 : void CGUI::Xeromyces_ReadEffects(const XMBData& xmb, XMBElement element, SGUIImageEffects& effects)
1219 : {
1220 0 : for (XMBAttribute attr : element.GetAttributes())
1221 : {
1222 0 : std::string_view attr_name(xmb.GetAttributeStringView(attr.Name));
1223 0 : if (attr_name == "add_color")
1224 : {
1225 0 : if (!effects.m_AddColor.ParseString(*this, attr.Value, 0))
1226 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name, attr.Value);
1227 : }
1228 0 : else if (attr_name == "grayscale")
1229 0 : effects.m_Greyscale = true;
1230 : else
1231 0 : debug_warn(L"Invalid data - DTD shouldn't allow this");
1232 0 : }
1233 0 : }
1234 :
1235 10 : void CGUI::Xeromyces_ReadStyle(const XMBData& xmb, XMBElement element)
1236 : {
1237 10 : SGUIStyle style;
1238 10 : CStr name;
1239 :
1240 40 : for (XMBAttribute attr : element.GetAttributes())
1241 : {
1242 10 : std::string_view attr_name(xmb.GetAttributeStringView(attr.Name));
1243 : // The "name" setting is actually the name of the style
1244 : // and not a new default
1245 10 : if (attr_name == "name")
1246 20 : name = attr.Value;
1247 : else
1248 0 : style.m_SettingsDefaults.emplace(std::string(attr_name), attr.Value.FromUTF8());
1249 10 : }
1250 :
1251 10 : m_Styles.erase(name);
1252 10 : m_Styles.emplace(name, std::move(style));
1253 10 : }
1254 :
1255 0 : void CGUI::Xeromyces_ReadScrollBarStyle(const XMBData& xmb, XMBElement element)
1256 : {
1257 0 : SGUIScrollBarStyle scrollbar;
1258 0 : CStr name;
1259 :
1260 : // Setup some defaults.
1261 0 : scrollbar.m_MinimumBarSize = 0.f;
1262 : // Using 1.0e10 as a substitute for infinity
1263 0 : scrollbar.m_MaximumBarSize = 1.0e10;
1264 0 : scrollbar.m_UseEdgeButtons = false;
1265 :
1266 0 : for (XMBAttribute attr : element.GetAttributes())
1267 : {
1268 0 : std::string_view attr_name(xmb.GetAttributeStringView(attr.Name));
1269 0 : CStr attr_value(attr.Value);
1270 :
1271 0 : if (attr_value == "null")
1272 0 : continue;
1273 :
1274 0 : if (attr_name == "name")
1275 0 : name = attr_value;
1276 0 : else if (attr_name == "show_edge_buttons")
1277 : {
1278 0 : bool b;
1279 0 : if (!ParseString<bool>(this, attr_value.FromUTF8(), b))
1280 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name, attr_value);
1281 : else
1282 0 : scrollbar.m_UseEdgeButtons = b;
1283 : }
1284 0 : else if (attr_name == "width")
1285 : {
1286 0 : float f;
1287 0 : if (!ParseString<float>(this, attr_value.FromUTF8(), f))
1288 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name, attr_value);
1289 : else
1290 0 : scrollbar.m_Width = f;
1291 : }
1292 0 : else if (attr_name == "minimum_bar_size")
1293 : {
1294 0 : float f;
1295 0 : if (!ParseString<float>(this, attr_value.FromUTF8(), f))
1296 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name, attr_value);
1297 : else
1298 0 : scrollbar.m_MinimumBarSize = f;
1299 : }
1300 0 : else if (attr_name == "maximum_bar_size")
1301 : {
1302 0 : float f;
1303 0 : if (!ParseString<float>(this, attr_value.FromUTF8(), f))
1304 0 : LOGERROR("GUI: Error parsing '{}' (\"{}\")", attr_name, attr_value);
1305 : else
1306 0 : scrollbar.m_MaximumBarSize = f;
1307 : }
1308 0 : else if (attr_name == "sprite_button_top")
1309 0 : scrollbar.m_SpriteButtonTop = attr_value;
1310 0 : else if (attr_name == "sprite_button_top_pressed")
1311 0 : scrollbar.m_SpriteButtonTopPressed = attr_value;
1312 0 : else if (attr_name == "sprite_button_top_disabled")
1313 0 : scrollbar.m_SpriteButtonTopDisabled = attr_value;
1314 0 : else if (attr_name == "sprite_button_top_over")
1315 0 : scrollbar.m_SpriteButtonTopOver = attr_value;
1316 0 : else if (attr_name == "sprite_button_bottom")
1317 0 : scrollbar.m_SpriteButtonBottom = attr_value;
1318 0 : else if (attr_name == "sprite_button_bottom_pressed")
1319 0 : scrollbar.m_SpriteButtonBottomPressed = attr_value;
1320 0 : else if (attr_name == "sprite_button_bottom_disabled")
1321 0 : scrollbar.m_SpriteButtonBottomDisabled = attr_value;
1322 0 : else if (attr_name == "sprite_button_bottom_over")
1323 0 : scrollbar.m_SpriteButtonBottomOver = attr_value;
1324 0 : else if (attr_name == "sprite_back_vertical")
1325 0 : scrollbar.m_SpriteBackVertical = attr_value;
1326 0 : else if (attr_name == "sprite_slider_vertical")
1327 0 : scrollbar.m_SpriteSliderVertical = attr_value;
1328 0 : else if (attr_name == "sprite_slider_vertical_over")
1329 0 : scrollbar.m_SpriteSliderVerticalOver = attr_value;
1330 0 : else if (attr_name == "sprite_slider_vertical_pressed")
1331 0 : scrollbar.m_SpriteSliderVerticalPressed = attr_value;
1332 0 : else if (attr_name == "sprite_back_horizontal")
1333 0 : scrollbar.m_SpriteBackHorizontal = attr_value;
1334 0 : else if (attr_name == "sprite_slider_horizontal")
1335 0 : scrollbar.m_SpriteSliderHorizontal = attr_value;
1336 0 : else if (attr_name == "sprite_slider_horizontal_over")
1337 0 : scrollbar.m_SpriteSliderHorizontalOver = attr_value;
1338 0 : else if (attr_name == "sprite_slider_horizontal_pressed")
1339 0 : scrollbar.m_SpriteSliderHorizontalPressed = attr_value;
1340 0 : }
1341 :
1342 0 : m_ScrollBarStyles.erase(name);
1343 0 : m_ScrollBarStyles.emplace(name, std::move(scrollbar));
1344 0 : }
1345 :
1346 0 : void CGUI::Xeromyces_ReadIcon(const XMBData& xmb, XMBElement element)
1347 : {
1348 0 : SGUIIcon icon;
1349 0 : CStr name;
1350 :
1351 0 : for (XMBAttribute attr : element.GetAttributes())
1352 : {
1353 0 : std::string_view attr_name(xmb.GetAttributeStringView(attr.Name));
1354 0 : CStr attr_value(attr.Value);
1355 :
1356 0 : if (attr_value == "null")
1357 0 : continue;
1358 :
1359 0 : if (attr_name == "name")
1360 0 : name = attr_value;
1361 0 : else if (attr_name == "sprite")
1362 0 : icon.m_SpriteName = attr_value;
1363 0 : else if (attr_name == "size")
1364 : {
1365 0 : CSize2D size;
1366 0 : if (!ParseString<CSize2D>(this, attr_value.FromUTF8(), size))
1367 0 : LOGERROR("Error parsing '{}' (\"{}\") inside <icon>.", attr_name, attr_value);
1368 : else
1369 0 : icon.m_Size = size;
1370 : }
1371 : else
1372 0 : debug_warn(L"Invalid data - DTD shouldn't allow this");
1373 0 : }
1374 :
1375 0 : m_Icons.erase(name);
1376 0 : m_Icons.emplace(name, std::move(icon));
1377 0 : }
1378 :
1379 0 : void CGUI::ReportMissingIcon(const CStr& name) const
1380 : {
1381 0 : if (m_MissingIconsReported.insert(name).second)
1382 : {
1383 0 : LOGWARNING("Trying to use an icon, imgleft or imgright-tag with an undefined icon (\"{}\").",
1384 : name);
1385 : }
1386 0 : }
1387 :
1388 0 : void CGUI::Xeromyces_ReadTooltip(const XMBData& xmb, XMBElement element)
1389 : {
1390 0 : std::unique_ptr<IGUIObject> object{std::make_unique<CTooltip>(*this)};
1391 :
1392 0 : for (XMBAttribute attr : element.GetAttributes())
1393 : {
1394 0 : std::string_view attr_name(xmb.GetAttributeStringView(attr.Name));
1395 0 : CStr attr_value(attr.Value);
1396 :
1397 0 : if (attr_name == "name")
1398 0 : object->SetName("__tooltip_" + attr_value);
1399 : else
1400 0 : object->SetSettingFromString(std::string(attr_name), attr_value.FromUTF8(), true);
1401 0 : }
1402 :
1403 0 : AddObject(*m_BaseObject, std::move(object));
1404 0 : }
1405 :
1406 0 : void CGUI::Xeromyces_ReadColor(const XMBData& xmb, XMBElement element)
1407 : {
1408 0 : XMBAttributeList attributes = element.GetAttributes();
1409 0 : CStr name = attributes.GetNamedItem(xmb.GetAttributeID("name"));
1410 :
1411 : // Try parsing value
1412 0 : CStr value(element.GetText());
1413 0 : if (value.empty())
1414 0 : return;
1415 :
1416 0 : CColor color;
1417 0 : if (color.ParseString(value))
1418 : {
1419 0 : m_PreDefinedColors.erase(name);
1420 0 : m_PreDefinedColors.emplace(
1421 : std::piecewise_construct,
1422 0 : std::forward_as_tuple(name),
1423 0 : std::forward_as_tuple(color.r, color.g, color.b, color.a));
1424 : }
1425 : else
1426 0 : LOGERROR("GUI: Unable to create custom color '{}'. Invalid color syntax.", name);
1427 0 : }
1428 :
1429 2 : CGUI::ModuleArtifact::ModuleArtifact(const Script::Request& rq, VfsPath filename):
1430 2 : result{rq, std::move(filename)},
1431 2 : moduleNamespace{rq.cx}
1432 2 : {}
|