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 "GUIManager.h"
21 :
22 : #include "gui/CGUI.h"
23 : #include "gui/SGUIMessage.h"
24 : #include "lib/debug.h"
25 : #include "lib/file/vfs/vfs_path.h"
26 : #include "lib/file/vfs/vfs_util.h"
27 : #include "lib/utf8.h"
28 : #include "ps/CLogger.h"
29 : #include "ps/Errors.h"
30 : #include "ps/Filesystem.h"
31 : #include "ps/Profile.h"
32 : #include "ps/Profiler2.h"
33 : #include "ps/VideoMode.h"
34 : #include "ps/XMB/XMBData.h"
35 : #include "ps/XMB/XMBStorage.h"
36 : #include "ps/XML/Xeromyces.h"
37 : #include "ps/containers/StaticVector.h"
38 : #include "scriptinterface/FunctionWrapper.h"
39 : #include "scriptinterface/Object.h"
40 : #include "scriptinterface/Context.h"
41 : #include "scriptinterface/Conversions.h"
42 : #include "scriptinterface/Interface.h"
43 : #include "scriptinterface/Request.h"
44 : #include "scriptinterface/StructuredClone.h"
45 : #include "simulation2/system/Component.h"
46 :
47 : #include <SDL_events.h>
48 : #include <algorithm>
49 : #include <iterator>
50 : #include <js/Equality.h>
51 : #include <js/GCVector.h>
52 : #include <js/Promise.h>
53 : #include <js/RootingAPI.h>
54 : #include <js/String.h>
55 : #include <js/Symbol.h>
56 : #include <js/Value.h>
57 : #include <js/ValueArray.h>
58 : #include <stdexcept>
59 : #include <tuple>
60 : #include <utility>
61 : #include <vector>
62 :
63 : namespace
64 : {
65 :
66 : const CStr EVENT_NAME_GAME_LOAD_PROGRESS = "GameLoadProgress";
67 : const CStr EVENT_NAME_WINDOW_RESIZED = "WindowResized";
68 : constexpr const char* START_ATLAS{"startAtlas"};
69 : constexpr const char* OPEN_REQUEST{"openRequest"};
70 :
71 : } // anonymous namespace
72 :
73 : CGUIManager* g_GUI = nullptr;
74 :
75 : // General TODOs:
76 : //
77 : // A lot of the CGUI data could (and should) be shared between
78 : // multiple pages, instead of treating them as completely independent, to save
79 : // memory and loading time.
80 :
81 : // trampoline: we don't want to make the HandleEvent implementation static
82 7 : Input::Reaction CGUIManager::InputHandler::operator()(const SDL_Event& ev)
83 : {
84 7 : PROFILE("GUI event handler");
85 14 : return gui.HandleEvent(ev);
86 7 : }
87 :
88 0 : static Status ReloadChangedFileCB(void* param, const VfsPath& path)
89 : {
90 0 : return static_cast<CGUIManager*>(param)->ReloadChangedFile(path);
91 : }
92 :
93 10 : CGUIManager::CGUIManager(Script::Context& scriptContext, Script::Interface& scriptInterface) :
94 10 : m_ScriptContext{scriptContext},
95 10 : m_ScriptInterface{scriptInterface},
96 10 : m_InputHandler{g_VideoMode.m_InputManager, Input::Slot::GUI, {*this}}
97 : {
98 10 : m_ScriptInterface.SetCallbackData(this);
99 10 : m_ScriptInterface.LoadGlobalScripts();
100 :
101 20 : if (!g_Xeromyces.AddValidator(g_VFS, "gui_page", "gui/gui_page.rng"))
102 0 : LOGERROR("CGUIManager: failed to load GUI page grammar file 'gui/gui_page.rng'");
103 20 : if (!g_Xeromyces.AddValidator(g_VFS, "gui", "gui/gui.rng"))
104 0 : LOGERROR("CGUIManager: failed to load GUI XML grammar file 'gui/gui.rng'");
105 :
106 10 : RegisterFileReloadFunc(ReloadChangedFileCB, this);
107 10 : }
108 :
109 10 : CGUIManager::~CGUIManager()
110 : {
111 10 : UnregisterFileReloadFunc(ReloadChangedFileCB, this);
112 10 : }
113 :
114 12 : size_t CGUIManager::GetPageCount() const
115 : {
116 12 : return m_PageStack.size();
117 : }
118 :
119 0 : void CGUIManager::SwitchPage(const CStrW& pageName, const Script::Interface* srcScriptInterface, JS::HandleValue initData)
120 : {
121 : // The page stack is cleared (including the script context where initData came from),
122 : // therefore we have to clone initData.
123 :
124 0 : Script::StructuredClone initDataClone;
125 0 : if (!initData.isUndefined())
126 : {
127 0 : Script::Request rq(srcScriptInterface);
128 0 : initDataClone = Script::WriteStructuredClone(rq, initData);
129 0 : }
130 :
131 0 : if (!m_PageStack.empty())
132 : {
133 : // Make sure we unfocus anything on the current page.
134 0 : m_PageStack.back().gui->SendFocusMessage(GUIM_LOST_FOCUS);
135 : m_PageStack.clear();
136 : }
137 :
138 0 : OpenChildPage(pageName, initDataClone);
139 0 : }
140 :
141 18 : JS::Value CGUIManager::OpenChildPage(const CStrW& pageName, Script::StructuredClone initData)
142 : {
143 : // Store the callback handler in the current GUI page before opening the new one
144 18 : JS::RootedValue promise{m_ScriptInterface.GetGeneralJSContext(), [&]
145 : {
146 18 : if (m_PageStack.empty())
147 10 : return JS::UndefinedValue();
148 :
149 8 : CGUI& currentPage = *m_PageStack.back().gui;
150 : // Make sure we unfocus anything on the current page.
151 8 : currentPage.SendFocusMessage(GUIM_LOST_FOCUS);
152 8 : return m_PageStack.back().GetPromise();
153 18 : }()};
154 :
155 : // Emplace the page prior to loading its contents, because that may open
156 : // another GUI page on init which should be emplaced on top of this new page.
157 18 : m_PageStack.emplace_back(pageName, initData);
158 19 : m_PageStack.back().LoadPage(m_ScriptContext);
159 :
160 16 : return promise;
161 16 : }
162 :
163 18 : CGUIManager::SGUIPage::SGUIPage(const CStrW& pageName, const Script::StructuredClone initData)
164 18 : : m_Name(pageName), initData(initData)
165 : {
166 18 : }
167 :
168 18 : void CGUIManager::SGUIPage::LoadPage(Script::Context& scriptContext)
169 : {
170 : // If we're hotloading then try to grab some data from the previous page
171 18 : Script::StructuredClone hotloadData;
172 18 : if (gui)
173 : {
174 0 : std::shared_ptr<Script::Interface> scriptInterface = gui->GetScriptInterface();
175 0 : Script::Request rq(scriptInterface);
176 0 : JS::RootedValue hotloadDataVal(rq.cx, gui->GetHotloadData(rq));
177 0 : hotloadData = Script::WriteStructuredClone(rq, hotloadDataVal);
178 0 : }
179 :
180 18 : g_VideoMode.ResetCursor();
181 18 : inputs.clear();
182 18 : gui.reset(new CGUI(scriptContext));
183 20 : const Script::Request rq{gui->GetScriptInterface()};
184 :
185 54 : for (const char* name : {START_ATLAS, OPEN_REQUEST})
186 : {
187 36 : JS::RootedString jsName{rq.cx, JS_NewStringCopyZ(rq.cx, name)};
188 36 : JS::RootedValue symbol{rq.cx, JS::SymbolValue(JS::NewSymbol(rq.cx, jsName))};
189 36 : JS::RootedValue nativeScope{rq.cx, JS::ObjectValue(*rq.nativeScope)};
190 36 : Script::SetProperty(rq, nativeScope, name, symbol, true);
191 36 : }
192 18 : gui->AddObjectTypes();
193 :
194 72 : VfsPath path = VfsPath("gui") / m_Name;
195 18 : inputs.insert(path);
196 :
197 18 : CXeromyces xero;
198 18 : if (xero.Load(g_VFS, path, "gui_page") != PSRETURN_OK)
199 : // Fail silently (Xeromyces reported the error)
200 : return;
201 :
202 18 : int elmt_page = xero.GetElementID("page");
203 18 : int elmt_include = xero.GetElementID("include");
204 :
205 18 : XMBElement root = xero.GetRoot();
206 :
207 18 : if (root.GetNodeName() != elmt_page)
208 : {
209 2 : LOGERROR("GUI page '{}' must have root element <page>", utf8_from_wstring(m_Name));
210 0 : return;
211 : }
212 :
213 18 : VfsPath rootModule;
214 91 : for (XMBElement node : root.GetChildNodes())
215 : {
216 28 : if (node.GetNodeName() != elmt_include)
217 : {
218 2 : LOGERROR("GUI page '{}' must only have <include> elements inside <page>",
219 : utf8_from_wstring(m_Name));
220 0 : continue;
221 0 : }
222 :
223 28 : CStr8 name = node.GetText();
224 29 : CStrW nameW = node.GetText().FromUTF8();
225 :
226 28 : PROFILE2("load gui xml");
227 28 : PROFILE2_ATTR("name: %s", name.c_str());
228 :
229 28 : if (name.back() == '/')
230 : {
231 0 : VfsPath currentDirectory = VfsPath("gui") / nameW;
232 0 : VfsPaths directories;
233 0 : vfs::GetPathnames(g_VFS, currentDirectory, L"*.xml", directories);
234 0 : for (const VfsPath& directory : directories)
235 0 : gui->LoadXmlFile(directory, inputs);
236 0 : }
237 : else
238 : {
239 113 : VfsPath directory = VfsPath("gui") / nameW;
240 28 : gui->LoadXmlFile(directory, inputs);
241 28 : }
242 83 : }
243 :
244 17 : gui->LoadedXmlFiles();
245 :
246 17 : scriptContext.RunJobs();
247 17 : if (gui->m_LoadModuleResult.has_value())
248 : {
249 1 : gui->m_LoadModuleResult->moduleNamespace = gui->m_LoadModuleResult->iterator->Get();
250 0 : ++gui->m_LoadModuleResult->iterator;
251 : }
252 :
253 16 : JS::RootedValue hotloadDataVal(rq.cx);
254 :
255 16 : if (hotloadData)
256 0 : Script::ReadStructuredClone(rq, hotloadData, &hotloadDataVal);
257 :
258 16 : sendingPromise = std::make_shared<JS::PersistentRootedObject>(rq.cx);
259 : // Assigning to `sendingPromise` isn't possible after `init` has been called because `init` might
260 : // replace this page. So a local copy has to be made.
261 16 : const std::shared_ptr<JS::PersistentRootedObject> localPromise{sendingPromise};
262 :
263 32 : JS::RootedObject returnObject{rq.cx, gui->CallPageInit(rq, initData, hotloadDataVal,
264 32 : utf8_from_wstring(m_Name))};
265 :
266 16 : *localPromise = returnObject ? returnObject : JS::NewPromiseObject(rq.cx, nullptr);
267 70 : }
268 :
269 8 : JS::Value CGUIManager::SGUIPage::GetPromise()
270 : {
271 8 : const Script::Request rq{gui->GetScriptInterface()};
272 8 : if (receivingPromise == nullptr)
273 : {
274 14 : receivingPromise = std::make_shared<JS::PersistentRootedObject>(rq.cx,
275 7 : JS::NewPromiseObject(rq.cx, nullptr));
276 : }
277 :
278 8 : return JS::ObjectValue(**receivingPromise);
279 8 : }
280 :
281 19 : std::optional<CGUIManager::SGUIPage::CloseResult> CGUIManager::SGUIPage::MaybeClose(const bool isRootPage)
282 : {
283 19 : if (JS::GetPromiseState(*sendingPromise) == JS::PromiseState::Pending)
284 7 : return std::nullopt;
285 :
286 : // Make sure we unfocus anything on the current page.
287 12 : gui->SendFocusMessage(GUIM_LOST_FOCUS);
288 :
289 12 : const Script::Request rq{gui->GetScriptInterface()};
290 12 : JS::RootedValue arg{rq.cx, JS::GetPromiseResult(*sendingPromise)};
291 12 : const bool rejected{JS::GetPromiseState(*sendingPromise) == JS::PromiseState::Rejected};
292 :
293 12 : JS::RootedValue nativeScope{rq.cx, JS::ObjectValue(*rq.nativeScope)};
294 12 : if (arg.isObject())
295 : {
296 2 : JS::RootedObject argObject{rq.cx, &arg.toObject()};
297 2 : JS::RootedValue symbol{rq.cx};
298 2 : Script::GetProperty(rq, nativeScope, OPEN_REQUEST, &symbol);
299 2 : JS::RootedId key{rq.cx, JS::PropertyKey::Symbol(symbol.toSymbol())};
300 2 : JS::RootedValue openRequest{rq.cx};
301 4 : if (JS_GetPropertyById(rq.cx, argObject, key, &openRequest) &&
302 3 : Script::HasProperty(rq, openRequest, "page"))
303 : {
304 1 : std::wstring page;
305 1 : Script::GetProperty(rq, openRequest, "page", page);
306 1 : JS::RootedValue openArg{rq.cx};
307 1 : Script::GetProperty(rq, openRequest, "argument", &openArg);
308 1 : return CGUIManager::SGUIPage::OpenRequest{page,
309 1 : Script::WriteStructuredClone(rq, openArg)};
310 2 : }
311 2 : }
312 :
313 11 : if (isRootPage)
314 : {
315 4 : JS::RootedValue symbol{rq.cx};
316 4 : Script::GetProperty(rq, nativeScope, START_ATLAS, &symbol);
317 4 : bool equals;
318 4 : if (!JS::StrictlyEqual(rq.cx, arg, symbol, &equals))
319 0 : throw std::runtime_error{"Error while comparing return value to a symbol."};
320 :
321 4 : if (equals)
322 1 : return CGUIManager::SGUIPage::Close{nullptr, rejected};
323 4 : }
324 10 : return CGUIManager::SGUIPage::Close{Script::WriteStructuredClone(rq, arg), rejected};
325 14 : }
326 :
327 7 : void CGUIManager::SGUIPage::Refocus(const Close& result)
328 : {
329 7 : ENSURE(receivingPromise);
330 :
331 7 : std::shared_ptr<Script::Interface> scriptInterface = gui->GetScriptInterface();
332 14 : Script::Request rq(scriptInterface);
333 :
334 7 : JS::RootedObject globalObj(rq.cx, rq.glob);
335 :
336 7 : JS::RootedObject recv(rq.cx, *std::exchange(receivingPromise, nullptr));
337 :
338 14 : JS::RootedValue argVal(rq.cx);
339 7 : Script::ReadStructuredClone(rq, result.arg, &argVal);
340 :
341 : // This only resolves the promise, it doesn't call the continuation.
342 13 : (result.rejected ? JS::RejectPromise : JS::ResolvePromise)(rq.cx, recv, argVal);
343 :
344 : // We return to a page where some object might have been focused.
345 7 : gui->SendFocusMessage(GUIM_GOT_FOCUS);
346 7 : }
347 :
348 0 : Status CGUIManager::ReloadChangedFile(const VfsPath& path)
349 : {
350 0 : for (SGUIPage& p : m_PageStack)
351 0 : if (p.inputs.find(path) != p.inputs.end())
352 : {
353 0 : LOGMESSAGE("GUI file '{}' changed - reloading page '{}'", path.string8(),
354 : utf8_from_wstring(p.m_Name));
355 0 : p.LoadPage(m_ScriptContext);
356 : // TODO: this can crash if LoadPage runs an init script which modifies the page stack and breaks our iterators
357 : }
358 :
359 0 : return INFO::OK;
360 : }
361 :
362 0 : Status CGUIManager::ReloadAllPages()
363 : {
364 : // TODO: this can crash if LoadPage runs an init script which modifies the page stack and breaks our iterators
365 0 : for (SGUIPage& p : m_PageStack)
366 0 : p.LoadPage(m_ScriptContext);
367 :
368 0 : return INFO::OK;
369 : }
370 :
371 7 : Input::Reaction CGUIManager::HandleEvent(const SDL_Event& ev)
372 : {
373 : // We want scripts to have access to the raw input events, so they can do complex
374 : // processing when necessary (e.g. for unit selection and camera movement).
375 : // Sometimes they'll want to be layered behind the GUI widgets (e.g. to detect mousedowns on the
376 : // visible game area), sometimes they'll want to intercepts events before the GUI (e.g.
377 : // to capture all mouse events until a mouseup after dragging).
378 : // So we call two separate handler functions:
379 :
380 7 : bool handled = false;
381 :
382 7 : {
383 7 : PROFILE("handleInputBeforeGui");
384 14 : Script::Request rq(*top()->GetScriptInterface());
385 :
386 7 : JS::RootedValue global(rq.cx, rq.globalValue());
387 14 : if (Script::Function::Call(rq, global, "handleInputBeforeGui", handled, ev, top()->FindObjectUnderMouse()))
388 7 : if (handled)
389 0 : return Input::Reaction::HANDLED;
390 7 : }
391 :
392 7 : {
393 7 : PROFILE("handle event in native GUI");
394 7 : Input::Reaction r = top()->HandleEvent(ev);
395 7 : if (r != Input::Reaction::PASS)
396 0 : return r;
397 7 : }
398 :
399 7 : {
400 : // We can't take the following lines out of this scope because top() may be another gui page than it was when calling handleInputBeforeGui!
401 14 : Script::Request rq(*top()->GetScriptInterface());
402 7 : JS::RootedValue global(rq.cx, rq.globalValue());
403 :
404 7 : PROFILE("handleInputAfterGui");
405 7 : if (Script::Function::Call(rq, global, "handleInputAfterGui", handled, ev))
406 7 : if (handled)
407 0 : return Input::Reaction::HANDLED;
408 7 : }
409 :
410 7 : return Input::Reaction::PASS;
411 : }
412 :
413 :
414 150 : void CGUIManager::SendEventToAll(const CStr& eventName,
415 : std::optional<JS::HandleValueArray> paramData) const
416 : {
417 150 : const auto pageStack = GetCopyOfFrozenStack();
418 :
419 150 : for (const SGUIPage& p : pageStack)
420 : {
421 0 : if (paramData.has_value())
422 0 : p.gui->SendEventToAll(eventName, paramData.value());
423 : else
424 0 : p.gui->SendEventToAll(eventName);
425 : }
426 150 : }
427 :
428 11 : std::optional<bool> CGUIManager::TickObjects()
429 : {
430 11 : PROFILE3("gui tick");
431 :
432 : // We share the script context with everything else that runs in the same thread.
433 : // This call makes sure we trigger GC regularly even if the simulation is not running.
434 11 : m_ScriptContext.MaybeIncrementalGC();
435 :
436 11 : const auto pageStack = GetCopyOfFrozenStack();
437 :
438 29 : for (const SGUIPage& p : pageStack)
439 : {
440 18 : const Script::Request rq{p.gui->GetScriptInterface()};
441 36 : JS::RootedObject newSendingPromise{rq.cx, p.gui->TickObjects(rq, p.initData,
442 36 : utf8_from_wstring(p.m_Name))};
443 18 : if (newSendingPromise)
444 18 : (*p.sendingPromise) = newSendingPromise;
445 18 : }
446 :
447 11 : m_ScriptContext.RunJobs();
448 :
449 19 : while (!m_PageStack.empty())
450 : {
451 19 : const size_t stackSize{m_PageStack.size()};
452 19 : const std::optional<SGUIPage::CloseResult> result{
453 20 : m_PageStack.back().MaybeClose(stackSize == 1)};
454 19 : if (!result.has_value())
455 : break;
456 12 : ENSURE(m_PageStack.size() == stackSize);
457 12 : m_PageStack.pop_back();
458 12 : if (const SGUIPage::OpenRequest* request{std::get_if<SGUIPage::OpenRequest>(&result.value())})
459 4 : OpenChildPage(request->path, request->arg);
460 11 : else if (const SGUIPage::Close& ret{std::get<SGUIPage::Close>(result.value())};
461 11 : m_PageStack.empty())
462 : {
463 4 : return !ret.arg;
464 : }
465 : else
466 7 : m_PageStack.back().Refocus(ret);
467 :
468 8 : m_ScriptContext.RunJobs();
469 19 : }
470 7 : return std::nullopt;
471 11 : }
472 :
473 0 : void CGUIManager::Draw(CCanvas2D& canvas) const
474 : {
475 0 : PROFILE3("gui");
476 :
477 0 : for (const SGUIPage& p : m_PageStack)
478 0 : p.gui->Draw(canvas);
479 0 : }
480 :
481 0 : void CGUIManager::UpdateResolution()
482 : {
483 0 : const auto pageStack = GetCopyOfFrozenStack();
484 :
485 0 : for (const SGUIPage& p : pageStack)
486 : {
487 0 : p.gui->UpdateResolution();
488 0 : p.gui->SendEventToAll(EVENT_NAME_WINDOW_RESIZED);
489 : }
490 0 : }
491 :
492 0 : bool CGUIManager::TemplateExists(const std::string& templateName) const
493 : {
494 0 : return m_TemplateLoader.TemplateExists(templateName);
495 : }
496 :
497 0 : const CParamNode& CGUIManager::GetTemplate(const std::string& templateName)
498 : {
499 0 : const CParamNode& templateRoot = m_TemplateLoader.GetTemplateFileData(templateName).GetOnlyChild();
500 0 : if (!templateRoot.IsOk())
501 0 : LOGERROR("Invalid template found for '{}'", templateName);
502 :
503 0 : return templateRoot;
504 : }
505 :
506 0 : void CGUIManager::DisplayLoadProgress(int percent, const wchar_t* pending_task)
507 : {
508 0 : const Script::Interface& scriptInterface = *(GetActiveGUI()->GetScriptInterface());
509 0 : Script::Request rq(scriptInterface);
510 :
511 0 : JS::RootedValueVector paramData(rq.cx);
512 :
513 0 : std::ignore = paramData.append(JS::NumberValue(percent));
514 :
515 0 : JS::RootedValue valPendingTask(rq.cx);
516 0 : Script::ToJSVal(rq, &valPendingTask, pending_task);
517 0 : std::ignore = paramData.append(valPendingTask);
518 :
519 0 : SendEventToAll(EVENT_NAME_GAME_LOAD_PROGRESS, paramData);
520 0 : }
521 :
522 : // This returns a shared_ptr to make sure the CGUI doesn't get deallocated
523 : // while we're in the middle of calling a function on it (e.g. if a GUI script
524 : // calls SwitchPage)
525 35 : std::shared_ptr<CGUI> CGUIManager::top() const
526 : {
527 35 : ENSURE(m_PageStack.size());
528 36 : return m_PageStack.back().gui;
529 : }
530 :
531 161 : PS::StaticVector<CGUIManager::SGUIPage, 16> CGUIManager::GetCopyOfFrozenStack() const
532 : {
533 161 : PS::StaticVector<CGUIManager::SGUIPage, 16> stack;
534 161 : std::copy(m_PageStack.begin(), m_PageStack.end(), std::back_inserter(stack));
535 161 : return stack;
536 0 : }
|