yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
editor_manager.cc
Go to the documentation of this file.
1// Related header
2#include "editor_manager.h"
3
4// C system headers
5#include <cctype>
6#include <cstdint>
7#include <cstdio>
8#include <cstring>
9#include <ctime>
10
11// C++ standard library headers
12#include <algorithm>
13#include <array>
14#include <chrono>
15#include <cstdlib>
16#include <exception>
17#include <filesystem>
18#include <fstream>
19#include <functional>
20#include <initializer_list>
21#include <iterator>
22#include <map>
23#include <memory>
24#include <optional>
25#include <sstream>
26#include <stdexcept>
27#include <string>
28#include <string_view>
29#include <unordered_map>
30#include <unordered_set>
31#include <utility>
32#include <vector>
33
34#ifdef __APPLE__
35#include <TargetConditionals.h>
36#endif
37
38// Third-party library headers
39#define IMGUI_DEFINE_MATH_OPERATORS
40#include "absl/status/status.h"
41#include "absl/status/statusor.h"
42#include "absl/strings/ascii.h"
43#include "absl/strings/match.h"
44#include "absl/strings/str_format.h"
45#include "absl/strings/str_join.h"
46#include "absl/strings/str_split.h"
47#include "absl/strings/string_view.h"
48#include "imgui/imgui.h"
49#ifdef YAZE_WITH_JSON
50#include "nlohmann/json.hpp"
51#endif
52#ifdef _WIN32
53#include <process.h>
54#else
55#include <unistd.h>
56#endif
57
58// Project headers
59#include "app/application.h"
62#include "app/editor/editor.h"
90#include "app/emu/emulator.h"
96#include "app/gui/core/icons.h"
101#include "app/platform/timing.h"
103#include "core/features.h"
105#include "core/palette_catalog.h"
106#include "core/project.h"
107#include "core/rom_settings.h"
117#include "rom/rom.h"
118#include "rom/rom_diff.h"
119#include "rom/transaction.h"
120#include "startup_flags.h"
121#include "util/file_util.h"
123#include "util/log.h"
124#include "util/macro.h"
125#include "util/rom_hash.h"
126#include "yaze_config.h"
132#include "zelda3/game_data.h"
139#include "zelda3/sprite/sprite.h"
140
141// Conditional platform headers
142#ifdef __EMSCRIPTEN__
146#endif
147
148// Conditional test headers
149#ifdef YAZE_ENABLE_TESTING
155#endif
156#ifdef YAZE_WITH_GRPC
158#endif
159
160// Conditional agent UI headers
161#ifdef YAZE_BUILD_AGENT_UI
163#endif
164
165namespace yaze::editor {
166
167namespace {
168absl::StatusOr<std::map<std::string, std::string>> ProjectBuildEnvironment(
169 const project::YazeProject& project,
170 const std::string& editing_source_path) {
171 if (project.filepath.empty()) {
172 return absl::FailedPreconditionError("Save the project before building");
173 }
174 std::error_code error;
175 const auto project_file =
176 std::filesystem::absolute(project.filepath, error).lexically_normal();
177 if (error) {
178 return absl::FailedPreconditionError(
179 "Cannot resolve the project build context: " + error.message());
180 }
181 const auto absolute = [&project_file](const std::string& value) {
182 if (value.empty()) {
183 return std::string();
184 }
185 const std::filesystem::path path(value);
186 return (path.is_absolute() ? path : project_file.parent_path() / path)
187 .lexically_normal()
188 .string();
189 };
190 std::string save_context_path;
191#if defined(YAZE_WITH_JSON) && !defined(__EMSCRIPTEN__)
192 if (!editing_source_path.empty()) {
194 auto save_context,
195 core::GetNativeSaveContext(editing_source_path, project_file.string()));
196 save_context_path = save_context.path.string();
197 }
198#endif
199 return std::map<std::string, std::string>{
200 {"YAZE_PROJECT_FILE", project_file.string()},
201 {"YAZE_PROJECT_CODE_FOLDER", absolute(project.code_folder)},
202 {"YAZE_PROJECT_ROM", absolute(project.rom_filename)},
203 {"YAZE_NATIVE_SAVE_RECEIPT", project_file.string() + ".native-save.json"},
204 {"YAZE_NATIVE_SAVE_CONTEXT", save_context_path},
205 {"YAZE_LYRA_TERRAIN_FILE", absolute(project.lyra_terrain_file)},
206 {"OOS_LYRA_PROJECT",
207 project.lyra_terrain_file.empty() ? "" : project_file.string()},
208 {"OOS_LYRA_REQUEST", absolute(project.lyra_build_request_file)}};
209}
210
211std::string LastNonEmptyLine(const std::string& text) {
212 std::vector<std::string> lines = absl::StrSplit(text, '\n');
213 for (auto it = lines.rbegin(); it != lines.rend(); ++it) {
214 std::string line = std::string(*it);
215 absl::StripAsciiWhitespace(&line);
216 if (!line.empty()) {
217 return line;
218 }
219 }
220 return "";
221}
222
224 ProjectManagementPanel* project_panel,
225 const ProjectWorkflowStatus& status) {
227 if (status_bar != nullptr) {
228 status_bar->SetBuildStatus(status);
229 }
230 if (project_panel != nullptr) {
231 project_panel->SetBuildStatus(status);
232 }
233}
234
236 ProjectManagementPanel* project_panel,
237 const ProjectWorkflowStatus& status) {
239 if (status_bar != nullptr) {
240 status_bar->SetRunStatus(status);
241 }
242 if (project_panel != nullptr) {
243 project_panel->SetRunStatus(status);
244 }
245}
246
247void AppendWorkflowHistoryEntry(const std::string& kind,
248 const ProjectWorkflowStatus& status,
249 const std::string& output_log) {
251 {.kind = kind,
252 .status = status,
253 .output_log = output_log,
254 .timestamp = std::chrono::system_clock::now()});
255}
256
258 std::unordered_map<std::string, float>* preferences,
259 const std::unordered_map<std::string, float>& drawer_widths) {
260 if (preferences == nullptr) {
261 return;
262 }
263 constexpr std::array<const char*, 9> kDrawerWidthKeys = {
264 "right_sidebar.shared", "agent_chat", "proposals", "settings", "help",
265 "notifications", "properties", "project", "tool_output",
266 };
267 for (const char* key : kDrawerWidthKeys) {
268 preferences->erase(key);
269 }
270 for (const auto& [key, width] : drawer_widths) {
271 preferences->insert_or_assign(key, width);
272 }
273}
274
275std::string StripSessionPrefix(absl::string_view panel_id) {
276 if (panel_id.size() > 2 && panel_id[0] == 's' &&
277 absl::ascii_isdigit(panel_id[1])) {
278 const size_t dot = panel_id.find('.');
279 if (dot != absl::string_view::npos) {
280 return std::string(panel_id.substr(dot + 1));
281 }
282 }
283 return std::string(panel_id);
284}
285
287 namespace fs = std::filesystem;
288
289 std::vector<fs::path> roots;
290 if (const char* home = std::getenv("HOME");
291 home != nullptr && std::strlen(home) > 0) {
292 roots.push_back(fs::path(home) / "src" / "hobby" / "oracle-of-secrets");
293 }
294
295 std::vector<fs::path> candidates;
296 std::unordered_set<std::string> seen;
297 auto add_candidate = [&](const fs::path& path) {
298 std::error_code ec;
299 if (!fs::exists(path, ec) || ec) {
300 return;
301 }
302 std::string ext = path.extension().string();
303 absl::AsciiStrToLower(&ext);
304 if (ext != ".yaze" && ext != ".yazeproj") {
305 return;
306 }
307 const std::string normalized = fs::weakly_canonical(path, ec).string();
308 const std::string key = normalized.empty() ? path.string() : normalized;
309 if (key.empty() || seen.count(key) > 0) {
310 return;
311 }
312 seen.insert(key);
313 candidates.push_back(path);
314 };
315
316 for (const auto& root : roots) {
317 std::error_code ec;
318 if (!fs::exists(root, ec) || ec) {
319 continue;
320 }
321
322 // Priority candidates first.
323 add_candidate(root / "Oracle-of-Secrets.yaze");
324 add_candidate(root / "Oracle of Secrets.yaze");
325 add_candidate(root / "Oracle-of-Secrets.yazeproj");
326 add_candidate(root / "Oracle of Secrets.yazeproj");
327 add_candidate(root / "Roms" / "Oracle of Secrets.yaze");
328
329 // Also detect additional local project files nearby.
330 fs::recursive_directory_iterator it(
331 root, fs::directory_options::skip_permission_denied, ec);
332 fs::recursive_directory_iterator end;
333 if (ec) {
334 continue;
335 }
336 for (; it != end; it.increment(ec)) {
337 if (ec) {
338 ec.clear();
339 continue;
340 }
341 if (it.depth() > 2) {
342 it.disable_recursion_pending();
343 continue;
344 }
345 add_candidate(it->path());
346 }
347 }
348
349 if (candidates.empty()) {
350 return;
351 }
352
354 // Add in reverse so the first candidate remains most recent.
355 for (auto it = candidates.rbegin(); it != candidates.rend(); ++it) {
356 manager.AddFile(it->string());
357 }
358 manager.Save();
359}
360
361} // namespace
362
363std::optional<EditorType> ParseEditorTypeFromString(absl::string_view name) {
364 std::string normalized = std::string(name);
365 absl::StripAsciiWhitespace(&normalized);
366 const std::string lower = absl::AsciiStrToLower(normalized);
367 for (int i = 0; i < static_cast<int>(kEditorTypeCount); ++i) {
368 const auto type = static_cast<EditorType>(i);
369 const std::string name_candidate =
370 absl::AsciiStrToLower(EditorRegistry::GetEditorName(type));
371 const std::string category_candidate =
372 absl::AsciiStrToLower(EditorRegistry::GetEditorCategory(type));
373 if (name_candidate == lower || category_candidate == lower) {
374 return type;
375 }
376 }
377 return std::nullopt;
378}
379
380// Static registry of editors that use the card-based layout system
381// These editors register their cards with WorkspaceWindowManager and manage their
382// own windows They do NOT need the traditional ImGui::Begin/End wrapper - they
383// create cards internally
387
391
392void EditorManager::ApplyLayoutPreset(const std::string& preset_name) {
394}
395
396bool EditorManager::ApplyLayoutProfile(const std::string& profile_id) {
397 if (!layout_manager_) {
398 return false;
399 }
400
401 const size_t session_id = GetCurrentSessionId();
402 const EditorType current_type =
404
405 LayoutProfile applied_profile;
406 if (!layout_manager_->ApplyBuiltInProfile(profile_id, session_id,
407 current_type, &applied_profile)) {
408 return false;
409 }
410
411 if (applied_profile.open_agent_chat && right_drawer_manager_) {
412 right_drawer_manager_->OpenDrawer(
414 const float default_width = RightDrawerManager::GetDefaultDrawerWidth(
416 right_drawer_manager_->SetDrawerWidth(
418 std::max(default_width, 480.0f));
419 }
420
422 absl::StrFormat("Layout Profile: %s", applied_profile.label),
424 return true;
425}
426
428 if (!layout_manager_) {
429 return;
430 }
431 layout_manager_->CaptureTemporarySessionLayout(GetCurrentSessionId());
432 toast_manager_.Show("Captured temporary layout snapshot", ToastType::kInfo);
433}
434
435void EditorManager::RestoreTemporaryLayoutSnapshot(bool clear_after_restore) {
436 if (!layout_manager_) {
437 return;
438 }
439
440 if (layout_manager_->RestoreTemporarySessionLayout(GetCurrentSessionId(),
441 clear_after_restore)) {
442 toast_manager_.Show("Restored temporary layout snapshot",
444 } else {
445 toast_manager_.Show("No temporary layout snapshot available",
447 }
448}
449
451 if (!layout_manager_) {
452 return;
453 }
454 layout_manager_->ClearTemporarySessionLayout();
455 toast_manager_.Show("Cleared temporary layout snapshot", ToastType::kInfo);
456}
457
458bool EditorManager::SaveLayoutSnapshotAs(const std::string& name) {
459 if (!layout_manager_)
460 return false;
461 if (name.empty()) {
462 toast_manager_.Show("Snapshot name cannot be empty", ToastType::kWarning);
463 return false;
464 }
465 const bool ok =
466 layout_manager_->SaveNamedSnapshot(name, GetCurrentSessionId());
467 if (ok) {
468 toast_manager_.Show(absl::StrFormat("Saved snapshot '%s'", name),
470 } else {
471 toast_manager_.Show(absl::StrFormat("Failed to save snapshot '%s'", name),
473 }
474 return ok;
475}
476
477bool EditorManager::RestoreLayoutSnapshot(const std::string& name,
478 bool remove_after_restore) {
479 if (!layout_manager_)
480 return false;
481 const bool ok = layout_manager_->RestoreNamedSnapshot(
482 name, GetCurrentSessionId(), remove_after_restore);
483 if (ok) {
484 toast_manager_.Show(absl::StrFormat("Restored snapshot '%s'", name),
486 } else {
487 toast_manager_.Show(absl::StrFormat("Snapshot '%s' not available", name),
489 }
490 return ok;
491}
492
493bool EditorManager::DeleteLayoutSnapshot(const std::string& name) {
494 if (!layout_manager_)
495 return false;
496 const bool ok = layout_manager_->DeleteNamedSnapshot(name);
497 if (ok) {
498 toast_manager_.Show(absl::StrFormat("Deleted snapshot '%s'", name),
500 }
501 return ok;
502}
503
504std::vector<std::string> EditorManager::ListLayoutSnapshots() const {
505 if (!layout_manager_)
506 return {};
507 return layout_manager_->ListNamedSnapshots(GetCurrentSessionId());
508}
509
511 if (!layout_manager_) {
512 return;
513 }
514
516 layout_manager_->SetProjectLayoutKey(
518 } else {
519 layout_manager_->UseGlobalLayouts();
520 }
521}
522
527
533
535 if (!current_editor_) {
536 toast_manager_.Show("No active editor to reset", ToastType::kWarning);
537 return;
538 }
539 // Choosing defaults ends automatic reapplication of a named layout. Keep
540 // the named layout itself; the recovery snapshot also retains live docking.
542 settings_dirty_ = true;
546}
547
548#ifdef YAZE_BUILD_AGENT_UI
549void EditorManager::ShowAIAgent() {
554 "AI Agent is experimental. It remains available; enable experimental "
555 "features in Settings to acknowledge this warning.",
557 }
558 // Apply saved agent settings from the current project when opening the Agent
559 // UI to respect the user's preferred provider/model.
560 // TODO: Implement LoadAgentSettingsFromProject in AgentChat or AgentEditor
561 agent_ui_->ShowAgent();
564 for (const auto& window_id :
565 LayoutPresets::GetDefaultWindows(EditorType::kAgent)) {
566 window_manager_.OpenWindow(window_id);
567 }
568}
569
570void EditorManager::ShowChatHistory() {
571 agent_ui_->ShowChatHistory();
572}
573
574AgentEditor* EditorManager::GetAgentEditor() {
575 return agent_ui_->GetAgentEditor();
576}
577#endif
578
580 : agent_ui_(std::make_unique<AgentUiController>()),
581 project_manager_(&toast_manager_),
582 rom_file_manager_(&toast_manager_) {
583 std::stringstream ss;
584 ss << YAZE_VERSION_MAJOR << "." << YAZE_VERSION_MINOR << "."
585 << YAZE_VERSION_PATCH;
586 ss >> version_;
587
588 // Initialize Core Context
589 editor_context_ = std::make_unique<GlobalEditorContext>(event_bus_);
592
596
597 // STEP 5: ShortcutConfigurator created later in Initialize() method
598 // It depends on all above coordinators being available
599}
600
603
604 // STEP 1: Initialize PopupManager FIRST
605 popup_manager_ = std::make_unique<PopupManager>(this);
606 popup_manager_->Initialize(); // Registers all popups with PopupID constants
607
608 // STEP 2: Initialize SessionCoordinator (independent of popups)
609 session_coordinator_ = std::make_unique<SessionCoordinator>(
611 session_coordinator_->SetEditorRegistry(&editor_registry_);
612
613 // STEP 3: Initialize MenuOrchestrator (depends on popup_manager_,
614 // session_coordinator_)
615 menu_orchestrator_ = std::make_unique<MenuOrchestrator>(
618
619 // Wire up the window manager for the View menu window listing
620 menu_orchestrator_->SetWindowManager(&window_manager_);
621 menu_orchestrator_->SetStatusBar(&status_bar_);
622 menu_orchestrator_->SetUserSettings(&user_settings_);
623 menu_orchestrator_->SetShortcutManager(&shortcut_manager_);
624
625 session_coordinator_->SetEditorManager(this);
626 session_coordinator_->SetBeforeSessionTransition(
627 [this] { return RetireNativeSaveTransfer("rebound"); });
628 session_coordinator_->SetEventBus(&event_bus_); // Enable event publishing
630 &event_bus_); // Global event bus access
631
632 // Expose UserSettings to cross-editor panels that don't get constructor
633 // injection (e.g. Layout Designer, which reads named_layouts). The
634 // LayoutManager setter happens below once the unique_ptr is constructed.
636
637 // STEP 3.5: Initialize RomLifecycleManager (depends on popup_manager_,
638 // session_coordinator_, rom_file_manager_, toast_manager_)
640 .rom_file_manager = &rom_file_manager_,
641 .session_coordinator = session_coordinator_.get(),
644 .project = &current_project_,
645 });
646
647 // STEP 4: Initialize UICoordinator (depends on popup_manager_,
648 // session_coordinator_, window_manager_)
649 ui_coordinator_ = std::make_unique<UICoordinator>(
653
654 // STEP 4.5: Initialize LayoutManager (DockBuilder layouts for editors)
655 layout_manager_ = std::make_unique<LayoutManager>();
656 layout_manager_->SetWindowManager(&window_manager_);
657 layout_manager_->UseGlobalLayouts();
658 // Expose to cross-editor panels that drive the live dockspace (Layout
659 // Designer). Must land after the unique_ptr is constructed.
663 [this](const std::string& preset_name) {
664 ApplyLayoutPreset(preset_name);
665 });
667 [this](const std::string& preset_name) {
668 ApplyLayoutPreset(preset_name);
669 });
670
671 // STEP 4.6: Initialize RightDrawerManager (right-side sliding drawers)
672 right_drawer_manager_ = std::make_unique<RightDrawerManager>();
673 right_drawer_manager_->SetToastManager(&toast_manager_);
674 right_drawer_manager_->SetProposalDrawer(&proposal_drawer_);
676 right_drawer_manager_->SetShortcutManager(&shortcut_manager_);
677 right_drawer_manager_->SetSettingsPanelProvider([this]() -> SettingsPanel* {
678 // The drawers button and the palette toggle open the Settings drawer
679 // directly; on the Welcome screen there is no session yet. Create an
680 // empty one, as SwitchToEditor does for ROM-less editors (BUG-020).
681 if (session_coordinator_ && GetCurrentEditorSet() == nullptr) {
682 session_coordinator_->CreateNewSession();
683 }
684 auto* editor_set = GetCurrentEditorSet();
685 return editor_set ? editor_set->GetSettingsPanel() : nullptr;
686 });
688 [this](const std::string& prompt) {
689#if defined(YAZE_BUILD_AGENT_UI)
690 auto* agent_editor = agent_ui_->GetAgentEditor();
691 if (!agent_editor) {
692 return;
693 }
694 auto* chat = agent_editor->GetAgentChat();
695 if (!chat) {
696 return;
697 }
698 chat->set_active(true);
699 chat->SendMessage(prompt);
700#else
701 (void)prompt;
702#endif
703 },
704 [this]() {
705#if defined(YAZE_BUILD_AGENT_UI)
707 right_drawer_manager_->OpenDrawer(
709 }
710#endif
711 });
714 right_drawer_manager_->ToggleDrawer(
716 } else {
717 agent_ui_->ShowAgent();
718 }
719 });
720
721 // Initialize ProjectManagementPanel for project/version management
722 project_management_panel_ = std::make_unique<ProjectManagementPanel>();
723 project_management_panel_->SetToastManager(&toast_manager_);
725 [this](const std::string& filepath, const std::string& contents) {
726 return PrepareRawProjectFileSave(filepath, contents);
727 });
729 [this](const std::string& filepath, const std::string& contents) {
730 return CommitRawProjectFileSave(filepath, contents);
731 });
733 std::make_unique<workflow::ProjectWorkflowOutputPanel>());
734 project_management_panel_->SetSwapRomCallback([this]() {
735 // Prompt user to select a new ROM for the project
738 if (!rom_path.empty()) {
739 auto status = SwapProjectRom(rom_path);
740 if (status.ok()) {
741 toast_manager_.Show("Project ROM updated and reloaded.",
743 } else {
744 toast_manager_.Show(absl::StrFormat("Failed to update project ROM: %s",
745 status.message()),
747 }
748 }
749 });
750 project_management_panel_->SetReloadRomCallback([this]() {
753 auto status = ReloadProjectRom();
754 if (!status.ok()) {
756 absl::StrFormat("Failed to reload ROM: %s", status.message()),
758 }
759 }
760 });
761 project_management_panel_->SetSaveProjectCallback([this]() {
762 auto status = SaveProject();
763 if (status.ok()) {
764 toast_manager_.Show("Project saved", ToastType::kSuccess);
765 } else {
767 absl::StrFormat("Failed to save project: %s", status.message()),
769 }
770 return status;
771 });
772 project_management_panel_->SetBrowseFolderCallback(
773 [this](const std::string& type) {
775 if (!folder_path.empty()) {
776 if (type == "code") {
777 current_project_.code_folder = folder_path;
778 // Update assembly editor path
779 if (auto* editor_set = GetCurrentEditorSet()) {
780// iOS: avoid blocking folder enumeration on the UI thread.
781#if !(defined(__APPLE__) && TARGET_OS_IOS == 1)
782 editor_set->OpenAssemblyFolder(folder_path);
783#endif
784 window_manager_.SetFileBrowserPath("Assembly", folder_path);
785 }
786 } else if (type == "assets") {
787 current_project_.assets_folder = folder_path;
788 }
792 }
793 toast_manager_.Show(absl::StrFormat("%s folder set: %s", type.c_str(),
794 folder_path.c_str()),
796 }
797 });
798 project_management_panel_->SetBuildProjectCallback(
799 [this]() { QueueBuildCurrentProject(); });
800 project_management_panel_->SetCancelBuildCallback(
801 [this]() { CancelQueuedProjectBuild(); });
802 project_management_panel_->SetRunProjectCallback(
803 [this]() { (void)RunCurrentProject(); });
805 [this]() { QueueBuildCurrentProject(); });
807 [this]() { (void)RunCurrentProject(); });
809 window_manager_.OpenWindow("workflow.output");
810 window_manager_.MarkWindowRecentlyUsed("workflow.output");
811 });
813 [this]() { CancelQueuedProjectBuild(); });
814 right_drawer_manager_->SetProjectManagementPanel(
816
817 // STEP 4.6.1: Initialize LayoutCoordinator (facade for layout operations)
819 layout_deps.layout_manager = layout_manager_.get();
820 layout_deps.window_manager = &window_manager_;
821 layout_deps.ui_coordinator = ui_coordinator_.get();
822 layout_deps.toast_manager = &toast_manager_;
823 layout_deps.status_bar = &status_bar_;
825 layout_coordinator_.Initialize(layout_deps);
826
827 // STEP 4.6.2: Initialize EditorActivator (editor switching and jump navigation)
828 EditorActivator::Dependencies activator_deps;
829 activator_deps.window_manager = &window_manager_;
830 activator_deps.layout_manager = layout_manager_.get();
831 activator_deps.ui_coordinator = ui_coordinator_.get();
832 activator_deps.right_drawer_manager = right_drawer_manager_.get();
833 activator_deps.toast_manager = &toast_manager_;
834 activator_deps.event_bus = &event_bus_;
835 activator_deps.ensure_editor_assets_loaded = [this](EditorType type) {
836 return EnsureEditorAssetsLoaded(type);
837 };
838 activator_deps.get_current_editor_set = [this]() {
839 return GetCurrentEditorSet();
840 };
841 activator_deps.get_current_session_id = [this]() {
842 return GetCurrentSessionId();
843 };
844 activator_deps.queue_deferred_action = [this](std::function<void()> action) {
845 QueueDeferredAction(std::move(action));
846 };
847 editor_activator_.Initialize(activator_deps);
848
849 // STEP 4.7: Initialize ActivityBar
850 activity_bar_ = std::make_unique<ActivityBar>(
852 [this]() -> bool {
853 if (auto* editor_set = GetCurrentEditorSet()) {
854 if (auto* dungeon_editor = editor_set->GetEditorAs<DungeonEditorV2>(
856 return dungeon_editor->IsWorkbenchWorkflowEnabled();
857 }
858 }
859 return false;
860 },
861 [this](bool enabled) {
862 if (auto* editor_set = GetCurrentEditorSet()) {
863 if (auto* dungeon_editor = editor_set->GetEditorAs<DungeonEditorV2>(
865 dungeon_editor->QueueWorkbenchWorkflowMode(enabled);
866 }
867 }
868 },
869 [this](const std::string& category) {
870 return GetEditorContextSnapshot(category);
871 });
872
873 // Wire per-user sidebar prefs so right-click / drag mutate persisted state.
874 activity_bar_->SetUserSettings(&user_settings_);
875
876 // Populate the MoreActions registry with the default rail entries. External
877 // callers can Register/Unregister further entries at runtime.
878 auto& registry = activity_bar_->actions_registry();
879 registry.Register({"command_palette",
880 "Command Palette",
883 {}});
884 registry.Register({"keyboard_shortcuts",
885 "Keyboard Shortcuts",
888 {}});
889 registry.Register({"open_rom_project",
890 "Open ROM / Project",
892 [this]() { window_manager_.TriggerOpenRom(); },
893 {}});
894 registry.Register({"settings",
895 "Settings",
897 [this]() { window_manager_.TriggerShowSettings(); },
898 {}});
899
900 // WindowHost is the declarative window registration surface used by
901 // editor/runtime systems.
902 window_host_ = std::make_unique<WindowHost>(&window_manager_);
903
904 // Wire up EventBus to WorkspaceWindowManager for action event publishing
906}
907
909 // Auto-register panels from ContentRegistry (Unified Panel System)
910 auto registry_panels = ContentRegistry::Panels::CreateAll();
911 for (auto& panel : registry_panels) {
913 }
914
915 // STEP 4.8: Initialize DashboardPanel
916 dashboard_panel_ = std::make_unique<DashboardPanel>(this);
917
918 if (window_host_) {
919 WindowDefinition dashboard_definition;
920 dashboard_definition.id = "dashboard.main";
921 dashboard_definition.display_name = "Dashboard";
922 dashboard_definition.icon = ICON_MD_DASHBOARD;
923 dashboard_definition.category = "Dashboard";
924 dashboard_definition.window_title = " Dashboard";
925 dashboard_definition.shortcut_hint = "Ctrl+E";
926 dashboard_definition.priority = 0;
927 dashboard_definition.visibility_flag = dashboard_panel_->visibility_flag();
928 dashboard_definition.presentation =
930 window_host_->RegisterWindow(dashboard_definition);
931 } else {
933 {.card_id = "dashboard.main",
934 .display_name = "Dashboard",
935 .window_title = " Dashboard",
936 .icon = ICON_MD_DASHBOARD,
937 .category = "Dashboard",
939 .shortcut_hint = "Ctrl+E",
940 .visibility_flag = dashboard_panel_->visibility_flag(),
941 .priority = 0});
942 }
943}
944
946 // Subscribe to session lifecycle events via EventBus
947 // (replaces SessionObserver pattern)
949 [this](const SessionSwitchedEvent& e) {
950 HandleSessionSwitched(e.new_index, e.session, e.transient);
951 });
952
954 [this](const SessionCreatedEvent& e) {
955 HandleSessionCreated(e.index, e.session);
956 });
957
959 [this](const SessionClosedEvent& e) { HandleSessionClosed(e.index); });
960
962 HandleSessionRomLoaded(e.session_id, e.rom);
963 });
964
965 // Subscribe to FrameGuiBeginEvent for ImGui-safe deferred action processing
966 // This replaces scattered manual processing calls with event-driven execution
968 ui_sync_frame_id_.fetch_add(1, std::memory_order_relaxed);
969
970 // Process LayoutCoordinator's deferred actions
972
973 // Process EditorManager's deferred actions
974 if (!deferred_actions_.empty()) {
975 std::vector<std::function<void()>> actions_to_execute;
976 actions_to_execute.swap(deferred_actions_);
977 const int processed_count = static_cast<int>(actions_to_execute.size());
978 for (auto& action : actions_to_execute) {
979 action();
980 }
981 if (processed_count > 0) {
982 const int remaining = pending_editor_deferred_actions_.fetch_sub(
983 processed_count, std::memory_order_relaxed) -
984 processed_count;
985 if (remaining < 0) {
986 pending_editor_deferred_actions_.store(0, std::memory_order_relaxed);
987 }
988 }
989 }
990 });
991
992 // Subscribe to UIActionRequestEvent for activity bar actions
993 // This replaces direct callbacks from WorkspaceWindowManager
995 [this](const UIActionRequestEvent& e) {
996 HandleUIActionRequest(e.action);
997 });
998
1000 [this](const PanelVisibilityChangedEvent& e) {
1001 if (e.category.empty() ||
1003 return;
1004 }
1005 if (IsTransientPanelVisibilityId(e.base_panel_id)) {
1006 return;
1007 }
1008 if (e.visible && layout_manager_) {
1009 layout_manager_->DockPresetPositionOnPanelOpen(e.session_id,
1010 e.base_panel_id);
1011 }
1012 auto& prefs = user_settings_.prefs();
1013 prefs.panel_visibility_state[e.category][e.base_panel_id] = e.visible;
1014 settings_dirty_ = true;
1016 });
1017}
1018
1020 // ContentRegistry::Context holds non-owning pointers into our members
1021 // (event_bus_, editor_context_, user_settings_, layout_manager_, callbacks).
1022 // Clear them before our members destruct so widgets that read the singleton
1023 // (e.g. Canvas::set_global_scale via Context::event_bus()) don't see
1024 // dangling pointers in tests that instantiate multiple EditorManagers.
1025 // Clear() resets fallback state but intentionally keeps global_context for
1026 // session-close semantics, so null it explicitly here.
1029
1030 // GetResourceLabels() is a process-wide singleton. RefreshResourceLabelProvider
1031 // hands it a pointer to current_project_.hack_manifest, which dangles after
1032 // we destruct. Clear before our members go out of scope.
1035
1036 // ThemeManager is a singleton that outlives us. Clear the theme-changed
1037 // callback so it stops calling back into a destroyed EditorManager via the
1038 // captured `this` pointer. Matters for unit tests that construct and destroy
1039 // multiple EditorManager instances in the same process.
1042
1043 // EventBus subscriptions are automatically cleaned up when event_bus_ is
1044 // destroyed (owned by this class). No manual unsubscription needed.
1045}
1046
1047// ============================================================================
1048// Session Event Handlers (EventBus subscribers)
1049// ============================================================================
1050
1052 auto& provider = zelda3::GetResourceLabels();
1055
1056 auto merge_labels =
1059 for (const auto& [type, labels] : src) {
1060 auto& out = (*dst)[type];
1061 for (const auto& [key, value] : labels) {
1062 out[key] = value;
1063 }
1064 }
1065 };
1066
1067 merged_labels.clear();
1068 std::vector<std::string> source_parts;
1069
1070 // 1) ROM-local labels as baseline for active session.
1071 if (auto* rom = GetCurrentRom();
1072 rom && rom->resource_label() && !rom->resource_label()->labels_.empty()) {
1073 merge_labels(&merged_labels, rom->resource_label()->labels_);
1074 source_parts.push_back("rom");
1075 }
1076
1077 // 2) Project registry labels from the active hack manifest.
1081 merge_labels(
1082 &merged_labels,
1084 source_parts.push_back("registry");
1085 }
1086
1087 // 3) Explicit project labels override all other sources.
1090 merge_labels(&merged_labels, current_project_.resource_labels);
1091 source_parts.push_back("project");
1092 }
1093
1094 auto* label_source = merged_labels.empty() ? &empty_labels : &merged_labels;
1095 std::string source =
1096 source_parts.empty() ? "empty" : absl::StrJoin(source_parts, "+");
1097
1098 provider.SetProjectLabels(label_source);
1099 provider.SetHackManifest(current_project_.project_opened() &&
1102 : nullptr);
1103
1104 const bool prefer_hmagic =
1108 provider.SetPreferHMagicNames(prefer_hmagic);
1109
1110 LOG_DEBUG("EditorManager",
1111 "ResourceLabelProvider refreshed (source=%s, project_open=%s)",
1112 source.c_str(),
1113 current_project_.project_opened() ? "true" : "false");
1114}
1115
1118 return;
1119 }
1120
1121 const auto index =
1123 if (!index.has_value()) {
1125 return;
1126 }
1127
1128 auto* session =
1129 static_cast<RomSession*>(session_coordinator_->GetSession(*index));
1130 if (!session) {
1132 return;
1133 }
1134
1136 if (session->project_context.has_value()) {
1137 session->project_context->feature_flags = session->feature_flags;
1138 }
1140 current_project_.feature_flags = session->feature_flags;
1141 }
1142}
1143
1145 if (!active_project_context_session_id_.has_value() ||
1147 return;
1148 }
1149
1152 const auto index =
1154 if (!index.has_value()) {
1156 return;
1157 }
1158
1159 auto* session =
1160 static_cast<RomSession*>(session_coordinator_->GetSession(*index));
1161 if (!session) {
1163 return;
1164 }
1165
1166 // The singleton can temporarily belong to another session while all editor
1167 // windows are ticked. Only use that value when it still belongs to this
1168 // project owner; otherwise its session-owned copy is authoritative.
1171 }
1172 // These preferences are exposed through global runtime settings, but they
1173 // are project workspace state. Capture them before leaving the session so a
1174 // later SaveProject cannot copy another session's values into this project.
1183 current_project_.feature_flags = session->feature_flags;
1185}
1186
1188 if (!active_project_context_session_id_.has_value() ||
1190 return;
1191 }
1192
1193 const auto index =
1195 if (!index.has_value()) {
1196 return;
1197 }
1198 auto* session =
1199 static_cast<RomSession*>(session_coordinator_->GetSession(*index));
1200 if (!session) {
1201 return;
1202 }
1203
1205 session->project_dirty = project_management_panel_->IsProjectDirty();
1206 }
1207 session->project_file_editor_state = project_file_editor_.CaptureState();
1208}
1209
1211 bool publish_lyra) {
1212 if (!session_coordinator_) {
1213 return absl::OkStatus();
1214 }
1215 auto* session = session_coordinator_->GetActiveRomSession();
1216 if (session == nullptr || !session->editors.HasPendingProjectDraftChanges()) {
1217 return absl::OkStatus();
1218 }
1219 if (!IsCurrentProjectContextOwnedBySession(session->session_id())) {
1220 return absl::FailedPreconditionError(
1221 "Project editor drafts require their project context to be active");
1222 }
1223 return session->editors.PrepareProjectSave(publish_lyra);
1224}
1225
1235
1237 std::optional<size_t> previous_session_id) {
1240 if (previous_session_id.has_value() && session_coordinator_) {
1241 const auto index = ResolveSessionIndexById(*previous_session_id);
1242 if (index.has_value()) {
1243 auto* previous_session =
1244 static_cast<RomSession*>(session_coordinator_->GetSession(*index));
1245 if (previous_session) {
1246 if (session_coordinator_->GetActiveSessionIndex() != *index) {
1247 session_coordinator_->SwitchToSession(*index);
1248 } else {
1249 RestoreProjectContextForSession(previous_session);
1250 }
1251 return;
1252 }
1253 }
1254 }
1255
1259 version_manager_ = nullptr;
1262}
1263
1265 size_t previous_session_count) {
1266 if (!session_coordinator_ ||
1267 session_coordinator_->GetTotalSessionCount() <= previous_session_count) {
1268 return absl::OkStatus();
1269 }
1270 auto* provisional_session = session_coordinator_->GetActiveRomSession();
1271 if (!provisional_session) {
1272 return absl::InternalError(
1273 "A provisional session was created but is not active");
1274 }
1275 return session_coordinator_->DiscardProvisionalSession(
1276 provisional_session->session_id());
1277}
1278
1287
1289 const std::string& filepath, const std::string& contents) {
1291 const bool targets_current = !current_project_.filepath.empty() &&
1293 filepath, current_project_.filepath);
1294 if (!targets_current) {
1295 // Save As to a separate descriptor is the deterministic escape hatch when
1296 // both the structured panel and raw document have edits.
1297 return absl::OkStatus();
1298 }
1299 if (IsCurrentProjectDirty()) {
1300 return absl::FailedPreconditionError(
1301 "Project settings also have unsaved changes; use raw Save As to "
1302 "preserve this draft, then save the project settings");
1303 }
1304
1305 auto* session = session_coordinator_
1306 ? session_coordinator_->GetActiveRomSession()
1307 : nullptr;
1308 if (!session || !session->rom.is_loaded()) {
1309 return absl::FailedPreconditionError(
1310 "No active ROM session for this project file");
1311 }
1312
1313 project::YazeProject parsed_project;
1314 RETURN_IF_ERROR(parsed_project.LoadFromString(contents, filepath));
1315 if (!parsed_project.project_opened()) {
1316 return absl::InvalidArgumentError(
1317 "Raw project file must contain a non-empty project name");
1318 }
1319 if (parsed_project.rom_filename.empty() ||
1321 parsed_project.rom_filename, session->filepath) ||
1323 parsed_project.rom_filename, session->rom.filename()))) {
1324 return absl::FailedPreconditionError(
1325 "Raw project file cannot change the ROM backing file of a loaded "
1326 "session; use Project Management > Swap ROM");
1327 }
1328 return session_coordinator_->CheckBackingFileAvailable(
1329 parsed_project.rom_filename, session->session_id());
1330}
1331
1333 const std::string& filepath, const std::string& contents) {
1334 if (current_project_.filepath.empty() ||
1336 filepath, current_project_.filepath)) {
1337 return absl::OkStatus();
1338 }
1339
1340 auto* session = session_coordinator_
1341 ? session_coordinator_->GetActiveRomSession()
1342 : nullptr;
1343 if (!session) {
1344 return absl::FailedPreconditionError("No active ROM session");
1345 }
1346
1347 project::YazeProject parsed_project;
1348 RETURN_IF_ERROR(parsed_project.LoadFromString(contents, filepath));
1349 current_project_ = std::move(parsed_project);
1351 session->project_dirty = false;
1352 active_project_context_session_id_ = session->session_id();
1353 runtime_feature_flags_session_id_ = session->session_id();
1354 version_manager_ = session->version_manager.get();
1357 project_management_panel_->SetProject(&current_project_, false);
1358 }
1359 return absl::OkStatus();
1360}
1361
1362void EditorManager::RebaseCleanProjectFileDraft(const std::string& filepath) {
1363 if (!session_coordinator_ || filepath.empty()) {
1364 return;
1365 }
1366 auto* session = session_coordinator_->GetActiveRomSession();
1367 if (!session || !session->project_file_editor_state.initialized ||
1368 session->project_file_editor_state.modified) {
1369 return;
1370 }
1371
1372 const bool was_active = project_file_editor_.is_active();
1373 auto status = project_file_editor_.LoadFile(filepath);
1374 if (!status.ok()) {
1375 LOG_WARN("EditorManager", "Failed to rebase raw project editor: %s",
1376 status.message());
1377 return;
1378 }
1380 project_file_editor_.set_active(was_active);
1381 session->project_file_editor_state = project_file_editor_.CaptureState();
1382}
1383
1384absl::StatusOr<const project::YazeProject*>
1386 if (!session_coordinator_) {
1387 return absl::FailedPreconditionError("No session coordinator");
1388 }
1389 auto* session = session_coordinator_->GetActiveRomSession();
1390 if (!session || !session->rom.is_loaded()) {
1391 return absl::FailedPreconditionError("No active ROM session");
1392 }
1393
1395 if (!active_project_context_session_id_.has_value() ||
1396 *active_project_context_session_id_ != session->session_id()) {
1397 return absl::FailedPreconditionError(
1398 "Active ROM session project context is not restored");
1399 }
1401 if (!session->project_context.has_value()) {
1402 return absl::FailedPreconditionError(
1403 "Active ROM session has no project/save context");
1404 }
1405 return &*session->project_context;
1406}
1407
1409 using Action = UIActionRequestEvent::Action;
1410 switch (action) {
1411 case Action::kShowEmulator:
1412 if (ui_coordinator_) {
1413 ui_coordinator_->SetEmulatorVisible(true);
1414 }
1415 break;
1416
1417 case Action::kShowSettings:
1418 // Toggle Settings panel in sidebar
1420 right_drawer_manager_->ToggleDrawer(
1422 } else {
1424 }
1425 break;
1426
1427 case Action::kShowPanelBrowser:
1428 if (ui_coordinator_) {
1429 ui_coordinator_->ShowWindowBrowser();
1430 }
1431 break;
1432
1433 case Action::kShowSearch:
1434 if (ui_coordinator_) {
1435 ui_coordinator_->ShowGlobalSearch();
1436 }
1437 break;
1438
1439 case Action::kShowShortcuts:
1440 if (ui_coordinator_) {
1441 ui_coordinator_->ShowShortcutsBrowser();
1442 }
1443 break;
1444
1445 case Action::kShowCommandPalette:
1446 if (ui_coordinator_) {
1447 ui_coordinator_->ShowCommandPalette();
1448 }
1449 break;
1450
1451 case Action::kShowHelp:
1453 // Toggle Help panel in sidebar
1454 right_drawer_manager_->ToggleDrawer(
1456 } else if (popup_manager_) {
1457 // Fallback to "About" dialog if sidebar not available
1459 }
1460 break;
1461
1462 case Action::kShowAgentChatSidebar:
1464 right_drawer_manager_->OpenDrawer(
1466 } else {
1468 }
1469 break;
1470
1471 case Action::kShowAgentProposalsSidebar:
1473 right_drawer_manager_->OpenDrawer(
1475 }
1476 break;
1477
1478 case Action::kOpenRom: {
1479 auto status = LoadRom();
1480 if (!status.ok()) {
1482 std::string("Open failed: ") + std::string(status.message()),
1484 }
1485 } break;
1486
1487 case Action::kSaveRom:
1488 if (GetCurrentRom() && GetCurrentRom()->is_loaded()) {
1489 auto status = SaveRom();
1490 if (!absl::IsCancelled(status) && !status.ok()) {
1492 std::string("Save failed: ") + std::string(status.message()),
1494 }
1495 }
1496 break;
1497
1498 case Action::kUndo:
1499 if (auto* current_editor = GetCurrentEditor()) {
1500 auto status = current_editor->Undo();
1501 if (!status.ok()) {
1503 std::string("Undo failed: ") + std::string(status.message()),
1505 }
1506 }
1507 break;
1508
1509 case Action::kRedo:
1510 if (auto* current_editor = GetCurrentEditor()) {
1511 auto status = current_editor->Redo();
1512 if (!status.ok()) {
1514 std::string("Redo failed: ") + std::string(status.message()),
1516 }
1517 }
1518 break;
1519
1520 case Action::kResetLayout:
1522 break;
1523 }
1524}
1525
1527 auto& test_manager = test::TestManager::Get();
1528
1529#ifdef YAZE_ENABLE_TESTING
1530 // Register comprehensive test suites
1531 test_manager.RegisterTestSuite(
1532 std::make_unique<test::CoreSystemsTestSuite>());
1533 test_manager.RegisterTestSuite(std::make_unique<test::IntegratedTestSuite>());
1534 test_manager.RegisterTestSuite(
1535 std::make_unique<test::PerformanceTestSuite>());
1536 test_manager.RegisterTestSuite(std::make_unique<test::UITestSuite>());
1537 test_manager.RegisterTestSuite(
1538 std::make_unique<test::RomDependentTestSuite>());
1539
1540 // Register new E2E and ZSCustomOverworld test suites
1541 test_manager.RegisterTestSuite(std::make_unique<test::E2ETestSuite>());
1542 test_manager.RegisterTestSuite(
1543 std::make_unique<test::ZSCustomOverworldTestSuite>());
1544#endif
1545
1546 // Register z3ed AI Agent test suites (requires gRPC)
1547#ifdef YAZE_WITH_GRPC
1549#endif
1550
1551 // Update resource monitoring to track Arena state
1552 test_manager.UpdateResourceStats();
1553}
1554
1556 const std::string& filename) {
1557 renderer_ = renderer;
1559 SeedOracleProjectInRecents();
1560
1561 // Inject the window manager into emulator and workspace_manager
1564
1565 // Point to a blank editor set when no ROM is loaded
1566 // current_editor_set_ = &blank_editor_set_;
1567
1568 // Note: PopupManager is now initialized in constructor before
1569 // MenuOrchestrator This ensures all menu callbacks can safely call
1570 // popup_manager_.Show()
1571
1575
1576 // Apply sidebar state from settings AFTER registering callbacks
1577 // This triggers the callbacks but they should be safe now
1579 /*notify=*/false);
1582 /*notify=*/false);
1584 user_settings_.prefs().sidebar_panel_width, /*notify=*/false);
1587 /*notify=*/false);
1588 {
1589 const bool prefer_dashboard_only =
1591 startup_editor_hint_.empty() && startup_panel_hints_.empty();
1592 if (!prefer_dashboard_only) {
1593 const std::string category = GetPreferredStartupCategory(
1595 if (!category.empty()) {
1596 window_manager_.SetActiveCategory(category, /*notify=*/false);
1598 auto it = user_settings_.prefs().panel_visibility_state.find(category);
1599 if (it != user_settings_.prefs().panel_visibility_state.end()) {
1601 window_manager_.GetActiveSessionId(), it->second);
1602 }
1603 }
1604 }
1605 }
1606
1610 }
1611
1612 // Initialize testing system only when tests are enabled
1613#ifdef YAZE_ENABLE_TESTING
1615#endif
1616
1617 // TestManager will be updated when ROMs are loaded via SetCurrentRom calls
1618
1620
1621 // Open a startup ROM last. The post-load surface reads Settings (Default
1622 // Editor), which InitializeServices() loads; opening earlier used the
1623 // built-in defaults and always showed the editor picker.
1624 if (!filename.empty()) {
1625 // The post-load surface must see --startup_dashboard/--welcome (saved by
1626 // SetStartupLoadHints) and Settings > Test mode now; Application applies
1627 // them only after this returns.
1631 }
1634 }
1635 }
1637 // Scripts and test launches pass --rom_file; they must not wait on the
1638 // load options dialog.
1640 }
1641}
1642
1644 // Register emulator panels early (emulator Initialize might not be called).
1645 const std::vector<WindowDefinition> panel_definitions = {
1646 {.id = "emulator.cpu_debugger",
1647 .display_name = "CPU Debugger",
1648 .icon = ICON_MD_BUG_REPORT,
1649 .category = "Emulator",
1650 .priority = 10,
1652 {.id = "emulator.ppu_viewer",
1653 .display_name = "PPU Viewer",
1655 .category = "Emulator",
1656 .priority = 20,
1657 .presentation = WindowPresentationPolicy::CoreWorkspace()},
1658 {.id = "emulator.memory_viewer",
1659 .display_name = "Memory Viewer",
1660 .icon = ICON_MD_MEMORY,
1661 .category = "Emulator",
1662 .priority = 30,
1664 {.id = "emulator.breakpoints",
1665 .display_name = "Breakpoints",
1666 .icon = ICON_MD_STOP,
1667 .category = "Emulator",
1668 .priority = 40,
1670 {.id = "emulator.performance",
1671 .display_name = "Performance",
1672 .icon = ICON_MD_SPEED,
1673 .category = "Emulator",
1674 .priority = 50,
1676 {.id = "emulator.ai_agent",
1677 .display_name = "AI Agent",
1678 .icon = ICON_MD_SMART_TOY,
1679 .category = "Emulator",
1680 .priority = 60,
1682 {.id = "emulator.save_states",
1683 .display_name = "Save States",
1684 .icon = ICON_MD_SAVE,
1685 .category = "Emulator",
1686 .priority = 70,
1688 "Command palette (placeholder: Coming Soon)")},
1689 {.id = "emulator.keyboard_config",
1690 .display_name = "Keyboard Config",
1691 .icon = ICON_MD_KEYBOARD,
1692 .category = "Emulator",
1693 .priority = 80,
1695 {.id = "emulator.virtual_controller",
1696 .display_name = "Virtual Controller",
1697 .icon = ICON_MD_SPORTS_ESPORTS,
1698 .category = "Emulator",
1699 .priority = 85,
1701 {.id = "emulator.apu_debugger",
1702 .display_name = "APU Debugger",
1703 .icon = ICON_MD_AUDIOTRACK,
1704 .category = "Emulator",
1705 .priority = 90,
1707 {.id = "emulator.audio_mixer",
1708 .display_name = "Audio Mixer",
1709 .icon = ICON_MD_AUDIO_FILE,
1710 .category = "Emulator",
1711 .priority = 100,
1713 {.id = "memory.hex_editor",
1714 .display_name = "Hex Editor",
1715 .icon = ICON_MD_MEMORY,
1716 .category = "Memory",
1717 .window_title = ICON_MD_MEMORY " Hex Editor",
1718 .priority = 10,
1720 .legacy_ids = {"Memory Editor"}},
1721 };
1722
1723 if (window_host_) {
1724 window_host_->RegisterPanels(panel_definitions);
1725 return;
1726 }
1727
1728 for (const auto& definition : panel_definitions) {
1729 WindowDescriptor descriptor;
1730 descriptor.card_id = definition.id;
1731 descriptor.display_name = definition.display_name;
1732 descriptor.window_title = definition.window_title;
1733 descriptor.icon = definition.icon;
1734 descriptor.category = definition.category;
1735 descriptor.shortcut_hint = definition.shortcut_hint;
1736 descriptor.priority = definition.priority;
1737 descriptor.scope = definition.scope;
1738 descriptor.window_lifecycle = definition.window_lifecycle;
1739 descriptor.context_scope = definition.context_scope;
1740 descriptor.presentation = definition.presentation;
1741 descriptor.visibility_flag = definition.visibility_flag;
1742 descriptor.on_show = definition.on_show;
1743 descriptor.on_hide = definition.on_hide;
1744
1745 for (const auto& legacy_id : definition.legacy_ids) {
1746 window_manager_.RegisterPanelAlias(legacy_id, definition.id);
1747 }
1748
1749 window_manager_.RegisterWindow(descriptor);
1750 if (definition.visible_by_default) {
1751 window_manager_.OpenWindow(definition.id);
1752 }
1753 }
1754}
1755
1757 // Initialize project file editor
1759
1760 // Initialize agent UI (no-op when agent UI is disabled)
1764
1765 // Note: Unified gRPC Server is started from Application::Initialize()
1766 // after gRPC infrastructure is properly set up
1767
1768 // Load critical user settings first
1770 if (!status_.ok()) {
1771 LOG_WARN("EditorManager", "Failed to load user settings: %s",
1772 status_.ToString().c_str());
1773 }
1774
1779 if (popup_manager_) {
1781 }
1782 });
1783
1784 // Wire theme persistence. Any successful theme application (selector click,
1785 // command-palette switch, programmatic call) stamps the name into prefs and
1786 // rides the existing debounced-save path. Decouples ThemeManager (singleton
1787 // in app/gui) from UserSettings (editor-layer) — ThemeManager holds only a
1788 // std::function.
1790 [this](const std::string& theme_name) {
1791 user_settings_.prefs().last_theme_name = theme_name;
1792 settings_dirty_ = true;
1794 });
1796 [this](const std::string& locale) {
1797 user_settings_.prefs().language_locale = locale;
1798 settings_dirty_ = true;
1800 });
1801
1802 auto& prefs = user_settings_.prefs();
1803 i18n::LanguageManager::Get().SetLanguage(prefs.language_locale);
1804
1805 // Apply the persisted font selection (defaults to index 0 = Karla).
1806 // Fonts were loaded by the window backend before EditorManager init, so
1807 // ImGui::GetIO().Fonts->Fonts is fully populated here.
1808 ::yaze::SetActiveFontIndex(prefs.font_family_index);
1809
1810 prefs.switch_motion_profile = std::clamp(prefs.switch_motion_profile, 0, 2);
1812 prefs.reduced_motion,
1813 gui::Animator::ClampMotionProfile(prefs.switch_motion_profile));
1814
1816
1818 // Rebuilding dock placement does not invalidate user-sized drawers.
1819 // Migrations that intentionally discard widths clear them in UserSettings.
1820 right_drawer_manager_->RestoreDrawerWidths(
1822 auto normalized_widths = user_settings_.prefs().right_panel_widths;
1823 MergeRightDrawerWidthPreferences(
1824 &normalized_widths, right_drawer_manager_->SerializeDrawerWidths());
1825 if (user_settings_.prefs().right_panel_widths != normalized_widths) {
1826 user_settings_.prefs().right_panel_widths = std::move(normalized_widths);
1827 settings_dirty_ = true;
1829 }
1830 right_drawer_manager_->SetDrawerWidthChangedCallback(
1831 [this](RightDrawerManager::DrawerType, float) {
1832 if (!right_drawer_manager_) {
1833 return;
1834 }
1835 MergeRightDrawerWidthPreferences(
1837 right_drawer_manager_->SerializeDrawerWidths());
1838 settings_dirty_ = true;
1840 });
1841 }
1842 agent_ui_->ApplyUserSettingsDefaults();
1843 // Apply sprite naming preference globally.
1846
1848
1849 // Apply font scale after loading (only if ImGui context exists)
1850 if (ImGui::GetCurrentContext() != nullptr) {
1851 ImGui::GetIO().FontGlobalScale = user_settings_.prefs().font_global_scale;
1852 } else {
1853 LOG_WARN("EditorManager",
1854 "ImGui context not available; skipping FontGlobalScale update");
1855 }
1856
1857 // Restore the user's last theme. Empty (first run) or "Custom Accent"
1858 // (transient generated themes without a matching discovered preset) both
1859 // skip restoration and keep the built-in default (Classic YAZE / YAZE Tre).
1860 const auto& last_theme = user_settings_.prefs().last_theme_name;
1861 if (!last_theme.empty() && last_theme != "Custom Accent") {
1862 gui::ThemeManager::Get().ApplyTheme(last_theme);
1863 }
1864
1865 // Initialize WASM control and session APIs for browser/agent integration
1866#ifdef __EMSCRIPTEN__
1869 LOG_INFO("EditorManager", "WASM Control and Session APIs initialized");
1870#endif
1871}
1872
1876
1878 ui_coordinator_->SetWelcomeScreenVisible(false);
1879 ui_coordinator_->SetWelcomeScreenManuallyClosed(true);
1880 }
1881}
1882
1885 pending_editor_deferred_actions_.load(std::memory_order_relaxed) > 0;
1886}
1887
1893
1895 if (ui_coordinator_) {
1896 ui_coordinator_->SetWelcomeScreenVisible(false);
1897 }
1898
1899 // 1. Never cover an editor the user already has open. Re-enter the same
1900 // editor type so it binds to the newly loaded session.
1901 std::optional<EditorType> target;
1902 if (HasOpenEditor()) {
1903 target = current_editor_->type();
1904 }
1905
1906 // 2. Settings > Editor Behavior > Default Editor.
1907 if (!target.has_value()) {
1909 case 1:
1910 target = EditorType::kOverworld;
1911 break;
1912 case 2:
1913 target = EditorType::kDungeon;
1914 break;
1915 case 3:
1916 target = EditorType::kGraphics;
1917 break;
1918 case 4:
1919 target = EditorType::kMessage;
1920 break;
1921 default:
1922 break;
1923 }
1924 }
1925
1926 // 3. The editor picker, unless it is suppressed (--startup_dashboard=hide
1927 // or Settings > Test mode). Suppressed with no other choice: open the
1928 // most recently used editor, else Dungeon.
1929 if (!target.has_value()) {
1930 if (!ui_coordinator_ || ui_coordinator_->ShouldShowDashboard()) {
1931 if (ui_coordinator_) {
1932 ui_coordinator_->SetEditorSelectionVisible(true);
1933 }
1934 // Suppress panel drawing until the user picks an editor.
1937 return;
1938 }
1939 target =
1940 (dashboard_panel_ ? dashboard_panel_->MostRecentEditor() : std::nullopt)
1941 .value_or(EditorType::kDungeon);
1942 }
1943
1944 if (ui_coordinator_) {
1945 ui_coordinator_->SetStartupSurface(StartupSurface::kEditor);
1946 }
1947 SwitchToEditor(*target, /*force_visible=*/true);
1948}
1949
1951 ShortcutDependencies shortcut_deps;
1952 shortcut_deps.editor_manager = this;
1953 shortcut_deps.editor_registry = &editor_registry_;
1954 shortcut_deps.menu_orchestrator = menu_orchestrator_.get();
1955 shortcut_deps.rom_file_manager = &rom_file_manager_;
1956 shortcut_deps.project_manager = &project_manager_;
1957 shortcut_deps.session_coordinator = session_coordinator_.get();
1958 shortcut_deps.ui_coordinator = ui_coordinator_.get();
1959 shortcut_deps.workspace_manager = &workspace_manager_;
1960 shortcut_deps.popup_manager = popup_manager_.get();
1961 shortcut_deps.toast_manager = &toast_manager_;
1962 shortcut_deps.window_manager = &window_manager_;
1963 shortcut_deps.user_settings = &user_settings_;
1964
1968}
1969
1971 const std::string& editor_name, const std::string& panels_str) {
1972 const bool has_editor = !editor_name.empty();
1973 const bool has_panels = !panels_str.empty();
1974
1975 if (!has_editor && !has_panels) {
1976 return;
1977 }
1978
1979 LOG_INFO("EditorManager",
1980 "Processing startup flags: editor='%s', panels='%s'",
1981 editor_name.c_str(), panels_str.c_str());
1982
1983 std::optional<EditorType> editor_type_to_open =
1984 has_editor ? ParseEditorTypeFromString(editor_name) : std::nullopt;
1985 if (has_editor && !editor_type_to_open.has_value()) {
1986 LOG_WARN("EditorManager", "Unknown editor specified via flag: %s",
1987 editor_name.c_str());
1988 } else if (editor_type_to_open.has_value()) {
1989 // Use EditorActivator to ensure layouts and default panels are initialized
1990 SwitchToEditor(*editor_type_to_open, true, /*from_dialog=*/true);
1991 }
1992
1993 // Open windows via WorkspaceWindowManager - works for any editor type
1994 if (!has_panels) {
1995 return;
1996 }
1997
1998 const size_t session_id = GetCurrentSessionId();
1999 std::string last_known_category = window_manager_.GetActiveCategory();
2000 bool applied_category_from_panel = false;
2001
2002 for (absl::string_view token :
2003 absl::StrSplit(panels_str, ',', absl::SkipWhitespace())) {
2004 if (token.empty()) {
2005 continue;
2006 }
2007 std::string panel_name = std::string(absl::StripAsciiWhitespace(token));
2008 LOG_DEBUG("EditorManager", "Attempting to open panel: '%s'",
2009 panel_name.c_str());
2010
2011 const std::string lower_name = absl::AsciiStrToLower(panel_name);
2012 if (lower_name == "welcome" || lower_name == "welcome_screen") {
2013 if (ui_coordinator_) {
2014 ui_coordinator_->SetWelcomeScreenBehavior(StartupVisibility::kShow);
2015 }
2016 continue;
2017 }
2018 if (lower_name == "dashboard" || lower_name == "dashboard.main" ||
2019 lower_name == "editor_selection") {
2020 if (dashboard_panel_) {
2021 dashboard_panel_->Show();
2022 }
2023 if (ui_coordinator_) {
2024 ui_coordinator_->SetDashboardBehavior(StartupVisibility::kShow);
2025 }
2028 /*notify=*/false);
2029 continue;
2030 }
2031
2032 // Special case: "Room <id>" opens a dungeon room
2033 if (absl::StartsWith(panel_name, "Room ")) {
2034 if (auto* editor_set = GetCurrentEditorSet()) {
2035 try {
2036 int room_id = std::stoi(panel_name.substr(5));
2038 JumpToRoomRequestEvent::Create(room_id, session_id));
2039 } catch (const std::exception& e) {
2040 LOG_WARN("EditorManager", "Invalid room ID format: %s",
2041 panel_name.c_str());
2042 }
2043 }
2044 continue;
2045 }
2046
2047 std::optional<std::string> resolved_panel;
2048 if (window_manager_.GetWindowDescriptor(session_id, panel_name)) {
2049 resolved_panel = panel_name;
2050 } else {
2051 for (const auto& [prefixed_id, descriptor] :
2053 const std::string base_id = StripSessionPrefix(prefixed_id);
2054 const std::string card_lower = absl::AsciiStrToLower(base_id);
2055 const std::string display_lower =
2056 absl::AsciiStrToLower(descriptor.display_name);
2057
2058 if (card_lower == lower_name || display_lower == lower_name) {
2059 resolved_panel = base_id;
2060 break;
2061 }
2062 }
2063 }
2064
2065 if (!resolved_panel.has_value()) {
2066 LOG_WARN("EditorManager",
2067 "Unknown panel '%s' from --open_panels (known count: %zu)",
2068 panel_name.c_str(),
2070 continue;
2071 }
2072
2073 if (window_manager_.OpenWindow(session_id, *resolved_panel)) {
2074 const auto* descriptor =
2075 window_manager_.GetWindowDescriptor(session_id, *resolved_panel);
2076 if (descriptor != nullptr) {
2077 const EditorType type =
2078 EditorRegistry::GetEditorTypeFromCategory(descriptor->category);
2079 const auto ensure_status = EnsureEditorAssetsLoaded(type);
2080 if (!ensure_status.ok()) {
2081 LOG_WARN("EditorManager", "Failed to load assets for panel '%s': %s",
2082 resolved_panel->c_str(), ensure_status.message().data());
2083 }
2084 }
2085 if (descriptor && !applied_category_from_panel &&
2086 descriptor->category != WorkspaceWindowManager::kDashboardCategory) {
2087 window_manager_.SetActiveCategory(descriptor->category);
2088 applied_category_from_panel = true;
2089 } else if (!applied_category_from_panel && descriptor &&
2090 descriptor->category.empty() && !last_known_category.empty()) {
2091 window_manager_.SetActiveCategory(last_known_category);
2092 }
2093 } else {
2094 LOG_WARN("EditorManager", "Failed to show panel '%s'",
2095 resolved_panel->c_str());
2096 }
2097 }
2098}
2099
2106
2114
2116 constexpr int kTargetRevision =
2118 const int previous_revision =
2120 if (!user_settings_.ApplyPanelLayoutDefaultsRevision(kTargetRevision)) {
2121 return;
2122 }
2123
2124 const bool includes_workspace_reset_revision =
2125 previous_revision <
2127 kTargetRevision >=
2130 pending_layout_defaults_reset_ || includes_workspace_reset_revision;
2131 settings_dirty_ = true;
2133
2134 LOG_INFO("EditorManager",
2135 "Applied panel layout defaults migration %d -> %d (%s)",
2136 previous_revision, kTargetRevision,
2137 includes_workspace_reset_revision ? "workspace reset"
2138 : "targeted preferences");
2139}
2140
2142 const std::string& saved_category,
2143 const std::vector<std::string>& available_categories) const {
2144 const std::string preferred =
2145 PreferStartupCategory(saved_category, available_categories);
2146 if (preferred.empty()) {
2147 return preferred;
2148 }
2149
2150 return preferred;
2151}
2152
2156
2158 if (ui_coordinator_) {
2159 ui_coordinator_->SetWelcomeScreenBehavior(welcome_mode_override_);
2160 ui_coordinator_->SetDashboardBehavior(dashboard_mode_override_);
2161 }
2162
2164 const bool sidebar_visible =
2166 window_manager_.SetSidebarVisible(sidebar_visible, /*notify=*/false);
2167 if (ui_coordinator_) {
2168 ui_coordinator_->SetPanelSidebarVisible(sidebar_visible);
2169 }
2170 }
2171
2172 // Force sidebar panel to collapse if Welcome Screen or Dashboard is explicitly shown
2173 // This prevents visual overlap/clutter on startup
2176 window_manager_.SetSidebarExpanded(false, /*notify=*/false);
2177 }
2178
2179 if (dashboard_panel_) {
2181 dashboard_panel_->Hide();
2183 dashboard_panel_->Show();
2184 }
2185 }
2186}
2187
2189 ApplyStartupVisibility(config);
2190 // Handle startup editor and panels
2191 std::string panels_str;
2192 for (size_t i = 0; i < config.open_panels.size(); ++i) {
2193 if (i > 0)
2194 panels_str += ",";
2195 panels_str += config.open_panels[i];
2196 }
2197 OpenEditorAndPanelsFromFlags(config.startup_editor, panels_str);
2198
2199 // Handle jump targets
2200 if (config.jump_to_room >= 0) {
2203 }
2204 if (config.jump_to_map >= 0) {
2205 // The navigation handler loads project assets before validating the target
2206 // against the editor's displayed capacity (including project Lyra maps).
2209 }
2210}
2211
2212absl::Status EditorManager::LoadAssetsForMode(uint64_t loading_handle) {
2213 switch (asset_load_mode_) {
2215 return LoadAssetsLazy(loading_handle);
2218 default:
2219 return LoadAssets(loading_handle);
2220 }
2221}
2222
2224 if (!session) {
2225 return;
2226 }
2227 session->ResetGraphicsDisplay();
2228 session->game_data_loaded = false;
2229 session->editor_initialized.fill(false);
2230 session->editor_assets_loaded.fill(false);
2231}
2232
2234 EditorType type) {
2235 if (!session) {
2236 return;
2237 }
2238 const size_t index = EditorTypeIndex(type);
2239 if (index < session->editor_initialized.size()) {
2240 session->editor_initialized[index] = true;
2241 }
2242}
2243
2245 if (!session) {
2246 return;
2247 }
2248 const size_t index = EditorTypeIndex(type);
2249 if (index < session->editor_assets_loaded.size()) {
2250 session->editor_assets_loaded[index] = true;
2251 }
2252}
2253
2255 EditorType type) {
2256 if (!session || !layout_manager_) {
2257 return;
2258 }
2259
2260 const size_t index = EditorTypeIndex(type);
2262 index >= session->editor_initialized.size() ||
2263 !session->editor_initialized[index] ||
2265 return;
2266 }
2267
2268 const std::string category = EditorRegistry::GetEditorCategory(type);
2269 // Session switching can happen before a lazily loaded editor registers its
2270 // panels. Repeat the persisted visibility pass once those descriptors exist.
2271 const auto visibility_it =
2273 if (visibility_it != user_settings_.prefs().panel_visibility_state.end()) {
2275 visibility_it->second);
2276 }
2277
2278 // Only the active category owns the shared dock tree. A cross-category
2279 // activation will refresh its layout immediately after the category switch.
2280 if (window_manager_.GetActiveCategory() == category &&
2281 layout_manager_->IsLayoutInitialized(type)) {
2283 }
2284}
2285
2291
2293 switch (type) {
2301 return true;
2302 default:
2303 return false;
2304 }
2305}
2306
2310
2312 EditorSet* editor_set) const {
2313 std::unordered_set<EditorType> types;
2314
2315 auto add_type = [&types](EditorType type) {
2316 switch (type) {
2320 case EditorType::kAgent:
2321 return;
2322 default:
2323 types.insert(type);
2324 return;
2325 }
2326 };
2327
2328 auto add_category = [&](const std::string& category) {
2329 if (category.empty() ||
2331 return;
2332 }
2334 };
2335
2336 const size_t session_id = GetCurrentSessionId();
2337 bool used_startup_hints = false;
2338
2339 if (!startup_editor_hint_.empty()) {
2340 if (auto startup_type = ParseEditorTypeFromString(startup_editor_hint_)) {
2341 add_type(*startup_type);
2342 used_startup_hints = true;
2343 }
2344 }
2345
2346 for (const auto& panel_name : startup_panel_hints_) {
2347 if (panel_name.empty()) {
2348 continue;
2349 }
2350
2351 if (const auto* descriptor =
2352 window_manager_.GetWindowDescriptor(session_id, panel_name)) {
2353 add_category(descriptor->category);
2354 used_startup_hints = true;
2355 continue;
2356 }
2357
2358 const std::string lower_name = absl::AsciiStrToLower(panel_name);
2359 for (const auto& [prefixed_id, descriptor] :
2361 const std::string base_id = StripSessionPrefix(prefixed_id);
2362 const std::string card_lower = absl::AsciiStrToLower(base_id);
2363 const std::string display_lower =
2364 absl::AsciiStrToLower(descriptor.display_name);
2365 if (card_lower == lower_name || display_lower == lower_name) {
2366 add_category(descriptor.category);
2367 used_startup_hints = true;
2368 break;
2369 }
2370 }
2371 }
2372
2373 if (used_startup_hints) {
2374 return std::vector<EditorType>(types.begin(), types.end());
2375 }
2376
2378 return {};
2379 }
2380
2381 if (editor_set) {
2382 for (auto* editor : editor_set->active_editors_) {
2383 if (editor != nullptr && *editor->active()) {
2384 add_type(editor->type());
2385 }
2386 }
2387 }
2388
2389 if (current_editor_ != nullptr) {
2390 add_type(current_editor_->type());
2391 }
2392
2393 add_category(window_manager_.GetActiveCategory());
2394
2395 for (const auto& window_id :
2397 if (const auto* descriptor =
2398 window_manager_.GetWindowDescriptor(session_id, window_id)) {
2399 add_category(descriptor->category);
2400 }
2401 }
2402
2403 return std::vector<EditorType>(types.begin(), types.end());
2404}
2405
2407 EditorSet* editor_set) const {
2408 return editor_set ? editor_set->GetEditor(type) : nullptr;
2409}
2410
2412 if (category.empty() ||
2414 return nullptr;
2415 }
2416
2417 auto* editor_set = GetCurrentEditorSet();
2418 if (!editor_set) {
2419 return nullptr;
2420 }
2421
2423 switch (type) {
2424 case EditorType::kAgent:
2425#ifdef YAZE_BUILD_AGENT_UI
2426 return agent_ui_->GetAgentEditor();
2427#else
2428 return nullptr;
2429#endif
2433 return nullptr;
2434 default:
2435 return GetEditorByType(type, editor_set);
2436 }
2437}
2438
2440 const std::string& category) {
2441 EditorContextSnapshot snapshot;
2442 snapshot.category = category;
2443 Editor* editor = ResolveEditorForCategory(category);
2444 if (editor == nullptr) {
2445 return snapshot;
2446 }
2447
2448 snapshot = editor->BuildContextSnapshot();
2449 if (snapshot.category.empty()) {
2450 snapshot.category = category;
2451 }
2452 if (snapshot.semantic_owner.empty()) {
2453 snapshot.semantic_owner = snapshot.category;
2454 }
2455
2456 const EditorExperimentPolicy policy =
2458 snapshot.experiment.experimental = policy.experimental;
2459 snapshot.experiment.acknowledged =
2461 switch (policy.disabled_save_posture) {
2463 snapshot.experiment.save_posture = "Defensive backup";
2464 break;
2466 snapshot.experiment.save_posture = "Guarded / read-only";
2467 break;
2469 default:
2470 snapshot.experiment.save_posture = "Normal";
2471 break;
2472 }
2475 snapshot.diagnostics.push_back({
2476 .id = "experimental_editor",
2478 .message = absl::StrFormat("%s is experimental; save posture: %s",
2479 snapshot.category,
2480 snapshot.experiment.save_posture),
2481 });
2482 }
2483 return snapshot;
2484}
2485
2486void EditorManager::SyncEditorContextForCategory(const std::string& category) {
2487 if (Editor* resolved = ResolveEditorForCategory(category)) {
2488 SetCurrentEditor(resolved);
2489 } else if (!category.empty() &&
2491 LOG_DEBUG("EditorManager", "No editor context available for category '%s'",
2492 category.c_str());
2493 }
2494}
2495
2497 EditorSet* editor_set,
2498 Rom* rom) {
2499 if (!editor_set) {
2500 return absl::FailedPreconditionError("No editor set available");
2501 }
2502
2503 auto* editor = GetEditorByType(type, editor_set);
2504 if (!editor) {
2505 return absl::OkStatus();
2506 }
2507 editor->Initialize();
2508 return absl::OkStatus();
2509}
2510
2512 auto* session = session_coordinator_
2513 ? session_coordinator_->GetActiveRomSession()
2514 : nullptr;
2515 if (!session) {
2516 return absl::FailedPreconditionError("No active session");
2517 }
2518 if (session->game_data_loaded) {
2519 return absl::OkStatus();
2520 }
2521 if (!session->rom.is_loaded()) {
2522 return absl::FailedPreconditionError("ROM not loaded");
2523 }
2524
2525 RETURN_IF_ERROR(zelda3::LoadGameData(session->rom, session->game_data));
2526 session->ReloadGraphicsDisplay();
2527
2528 auto* game_data = &session->game_data;
2529 auto* editor_set = &session->editors;
2530 editor_set->SetGameData(game_data);
2532
2534 session->game_data_loaded = true;
2535
2536 return absl::OkStatus();
2537}
2538
2540 if (type == EditorType::kUnknown) {
2541 return absl::OkStatus();
2542 }
2543
2544 auto* session = session_coordinator_
2545 ? session_coordinator_->GetActiveRomSession()
2546 : nullptr;
2547 if (!session) {
2548 return absl::OkStatus();
2549 }
2550
2551 if (!session->rom.is_loaded()) {
2553 return absl::OkStatus();
2554 }
2555 const size_t index = EditorTypeIndex(type);
2556 if (index >= session->editor_initialized.size()) {
2557 return absl::InvalidArgumentError("Invalid editor type");
2558 }
2559 if (EditorInitRequiresGameData(type)) {
2560 return absl::OkStatus();
2561 }
2562 bool initialized_now = false;
2563 if (!session->editor_initialized[index]) {
2565 InitializeEditorForType(type, &session->editors, &session->rom));
2566 MarkEditorInitialized(session, type);
2567 initialized_now = true;
2568 }
2569 if (initialized_now) {
2570 RestoreEditorLayoutAfterAssets(session, type);
2571 }
2572 return absl::OkStatus();
2573 }
2574
2575 const size_t index = EditorTypeIndex(type);
2576 if (index >= session->editor_initialized.size()) {
2577 return absl::InvalidArgumentError("Invalid editor type");
2578 }
2579
2580 if (EditorInitRequiresGameData(type)) {
2582 }
2583
2584 bool initialized_now = false;
2585 if (!session->editor_initialized[index]) {
2587 InitializeEditorForType(type, &session->editors, &session->rom));
2588 MarkEditorInitialized(session, type);
2589 initialized_now = true;
2590 }
2591
2592 if (EditorRequiresGameData(type)) {
2594 }
2595
2596 bool loaded_now = false;
2597 if (!session->editor_assets_loaded[index]) {
2598 auto* editor = GetEditorByType(type, &session->editors);
2599 if (editor) {
2600 RETURN_IF_ERROR(editor->Load());
2601 }
2602 MarkEditorLoaded(session, type);
2603 loaded_now = true;
2604 }
2605
2606 if (initialized_now || loaded_now) {
2607 RestoreEditorLayoutAfterAssets(session, type);
2608 }
2609
2610 return absl::OkStatus();
2611}
2612
2619
2645 GetCurrentSessionId()})) {
2646 return absl::OkStatus();
2647 }
2648
2649 return LoadRomInternal();
2650}
2651
2652absl::Status EditorManager::LoadAssets(uint64_t passed_handle) {
2653 auto* current_rom = GetCurrentRom();
2654 auto* current_editor_set = GetCurrentEditorSet();
2655 if (!current_rom || !current_editor_set) {
2656 return absl::FailedPreconditionError("No ROM or editor set loaded");
2657 }
2658
2659 auto* current_session = session_coordinator_->GetActiveRomSession();
2660 if (!current_session) {
2661 return absl::FailedPreconditionError("No active ROM session");
2662 }
2663 ResetAssetState(current_session);
2664
2665 auto start_time = std::chrono::steady_clock::now();
2666
2667#ifdef __EMSCRIPTEN__
2668 // Use passed handle if provided, otherwise create new one
2669 auto loading_handle =
2670 passed_handle != 0
2671 ? static_cast<app::platform::WasmLoadingManager::LoadingHandle>(
2672 passed_handle)
2673 : app::platform::WasmLoadingManager::BeginLoading(
2674 "Loading Editor Assets");
2675
2676 // Progress starts at 10% (ROM already loaded), goes to 100%
2677 constexpr float kStartProgress = 0.10f;
2678 constexpr float kEndProgress = 1.0f;
2679 constexpr int kTotalSteps = 11; // Graphics + 8 editors + profiler + finish
2680 int current_step = 0;
2681 auto update_progress = [&](const std::string& message) {
2682 current_step++;
2683 float progress =
2684 kStartProgress + (kEndProgress - kStartProgress) *
2685 (static_cast<float>(current_step) / kTotalSteps);
2686 app::platform::WasmLoadingManager::UpdateProgress(loading_handle, progress);
2687 app::platform::WasmLoadingManager::UpdateMessage(loading_handle, message);
2688 };
2689 // RAII guard to ensure loading indicator is closed even on early return
2690 auto cleanup_loading = [&]() {
2691 app::platform::WasmLoadingManager::EndLoading(loading_handle);
2692 };
2693 struct LoadingGuard {
2694 std::function<void()> cleanup;
2695 bool dismissed = false;
2696 ~LoadingGuard() {
2697 if (!dismissed)
2698 cleanup();
2699 }
2700 void dismiss() { dismissed = true; }
2701 } loading_guard{cleanup_loading};
2702#else
2703 (void)passed_handle; // Unused on non-WASM
2704#endif
2705
2706 // Set renderer for emulator (lazy initialization happens in Run())
2707 if (renderer_) {
2709 }
2710
2711 const auto preload_editor_list = CollectEditorsToPreload(current_editor_set);
2712 const std::unordered_set<EditorType> preload_types(
2713 preload_editor_list.begin(), preload_editor_list.end());
2714
2715 // Initialize only the editors needed for the current startup surface. This
2716 // registers their windows and sets up editor-specific resources before Load().
2717 struct InitStep {
2718 EditorType type;
2719 bool mark_loaded;
2720 };
2721 const InitStep init_steps[] = {
2723 {EditorType::kGraphics, false}, {EditorType::kScreen, false},
2724 {EditorType::kSprite, false}, {EditorType::kPalette, false},
2725 {EditorType::kAssembly, true}, {EditorType::kMusic, false},
2726 {EditorType::kDungeon, false},
2727 };
2728 for (const auto& step : init_steps) {
2729 if (!preload_types.contains(step.type)) {
2730 continue;
2731 }
2732 if (auto* editor = current_editor_set->GetEditor(step.type)) {
2733 editor->Initialize();
2734 MarkEditorInitialized(current_session, step.type);
2735 if (step.mark_loaded) {
2736 MarkEditorLoaded(current_session, step.type);
2737 }
2738 }
2739 }
2740
2741#ifdef __EMSCRIPTEN__
2742 update_progress("Loading graphics sheets...");
2743#endif
2744 // Load all Zelda3-specific data (metadata, palettes, gfx groups, graphics)
2745 gfx::PaletteManager::Get().ReleaseSession(&current_session->game_data);
2747 zelda3::LoadGameData(*current_rom, current_session->game_data));
2748 current_session->game_data_loaded = true;
2749
2750 current_session->ReloadGraphicsDisplay();
2751
2752 // Propagate GameData to editors that already exist; future editors inherit it
2753 // on first construction via EditorSet.
2754 auto* game_data = &current_session->game_data;
2755 current_editor_set->SetGameData(game_data);
2757
2758 struct LoadStep {
2759 EditorType type;
2760 const char* progress_message;
2761 };
2762 const LoadStep load_steps[] = {
2763 {EditorType::kOverworld, "Loading overworld..."},
2764 {EditorType::kDungeon, "Loading dungeons..."},
2765 {EditorType::kScreen, "Loading screen editor..."},
2766 {EditorType::kGraphics, "Loading graphics editor..."},
2767 {EditorType::kSprite, "Loading sprites..."},
2768 {EditorType::kMessage, "Loading messages..."},
2769 {EditorType::kMusic, "Loading music..."},
2770 {EditorType::kPalette, "Loading palettes..."},
2771 };
2772 for (const auto& step : load_steps) {
2773 if (!preload_types.contains(step.type)) {
2774 continue;
2775 }
2776#ifdef __EMSCRIPTEN__
2777 update_progress(step.progress_message);
2778#endif
2779 if (auto* editor = current_editor_set->GetEditor(step.type)) {
2780 RETURN_IF_ERROR(editor->Load());
2781 MarkEditorLoaded(current_session, step.type);
2782 }
2783 }
2784
2785#ifdef __EMSCRIPTEN__
2786 update_progress("Finishing up...");
2787#endif
2788
2789 // Set up RightDrawerManager with session's settings editor
2791 auto* settings = current_editor_set->GetSettingsPanel();
2792 right_drawer_manager_->SetSettingsPanel(settings);
2793 }
2794
2795 // Apply user preferences to status bar
2797
2798 RestoreActiveEditorLayoutAfterAssets(current_session);
2799
2801
2802#ifdef __EMSCRIPTEN__
2803 // Dismiss the guard and manually close - we completed successfully
2804 loading_guard.dismiss();
2805 app::platform::WasmLoadingManager::EndLoading(loading_handle);
2806#endif
2807
2808 auto end_time = std::chrono::steady_clock::now();
2809 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
2810 end_time - start_time);
2811 LOG_DEBUG("EditorManager", "ROM assets loaded in %lld ms", duration.count());
2812
2813 return absl::OkStatus();
2814}
2815
2816absl::Status EditorManager::LoadAssetsLazy(uint64_t passed_handle) {
2817 auto* current_rom = GetCurrentRom();
2818 auto* current_editor_set = GetCurrentEditorSet();
2819 if (!current_rom || !current_editor_set) {
2820 return absl::FailedPreconditionError("No ROM or editor set loaded");
2821 }
2822
2823 auto* current_session = session_coordinator_->GetActiveRomSession();
2824 if (!current_session) {
2825 return absl::FailedPreconditionError("No active ROM session");
2826 }
2827 ResetAssetState(current_session);
2828
2829#ifdef __EMSCRIPTEN__
2830 // Use passed handle if provided, otherwise create new one
2831 auto loading_handle =
2832 passed_handle != 0
2833 ? static_cast<app::platform::WasmLoadingManager::LoadingHandle>(
2834 passed_handle)
2835 : app::platform::WasmLoadingManager::BeginLoading(
2836 "Loading ROM (lazy assets)");
2837 auto cleanup_loading = [&]() {
2838 app::platform::WasmLoadingManager::EndLoading(loading_handle);
2839 };
2840 struct LoadingGuard {
2841 std::function<void()> cleanup;
2842 bool dismissed = false;
2843 ~LoadingGuard() {
2844 if (!dismissed) {
2845 cleanup();
2846 }
2847 }
2848 void dismiss() { dismissed = true; }
2849 } loading_guard{cleanup_loading};
2850#else
2851 (void)passed_handle; // Unused on non-WASM
2852#endif
2853
2854 // Set renderer for emulator (lazy initialization happens in Run())
2855 if (renderer_) {
2857 }
2858
2859 // Wire settings panel to right panel manager for the current session.
2861 auto* settings = current_editor_set->GetSettingsPanel();
2862 right_drawer_manager_->SetSettingsPanel(settings);
2863 }
2864
2865 // Apply user preferences to status bar
2867
2868#ifdef __EMSCRIPTEN__
2869 loading_guard.dismiss();
2870 app::platform::WasmLoadingManager::EndLoading(loading_handle);
2871#endif
2872
2873 LOG_INFO("EditorManager", "Lazy asset mode: editor assets deferred");
2874 return absl::OkStatus();
2875}
2876
2893 const std::optional<std::string>& target_filename) {
2894 return rom_lifecycle_.CheckRomWritePolicy(GetCurrentRom(), target_filename);
2895}
2896
2900
2906
2908 if (!pending_rom_save_.has_value() || !session_coordinator_) {
2909 return false;
2910 }
2911 return pending_rom_save_->session_index == GetCurrentSessionIndex() &&
2912 pending_rom_save_->rom != nullptr &&
2914}
2915
2917 pending_rom_save_.reset();
2919
2920 if (!hide_popups || !popup_manager_) {
2921 return;
2922 }
2923 for (const char* popup :
2926 if (popup_manager_->IsVisible(popup)) {
2927 popup_manager_->Hide(popup);
2928 }
2929 }
2930}
2931
2933 const std::optional<std::string>& save_as_filename) {
2934 auto* rom = GetCurrentRom();
2935 if (!session_coordinator_ || !session_coordinator_->GetActiveRomSession() ||
2936 !rom) {
2937 return absl::FailedPreconditionError("No active ROM session");
2938 }
2939
2942 PendingRomSave{save_as_filename, GetCurrentSessionIndex(), rom};
2943 return absl::OkStatus();
2944}
2945
2946void EditorManager::FinishPendingRomSaveAttempt(const absl::Status& status) {
2947 // A Cancelled status is resumable only while one of this request's explicit
2948 // confirmation dialogs is pending. Every other outcome is terminal and must
2949 // consume all one-shot bypasses so a later Ctrl+S cannot inherit consent.
2950 if (status.ok() || !absl::IsCancelled(status) ||
2953 }
2954}
2955
2957 // An established ROM save owns its confirmation and one-shot exemptions.
2958 if (pending_rom_save_.has_value()) {
2959 return SaveRom();
2960 }
2961 if (!session_coordinator_ || !session_coordinator_->GetActiveRomSession()) {
2962 return absl::FailedPreconditionError("No active ROM session");
2963 }
2964 if (auto* message = static_cast<MessageEditor*>(
2965 GetCurrentEditorSet()->GetExistingEditor(EditorType::kMessage));
2966 message && message->HasUnpublishedMessageSourceChanges()) {
2967 return absl::FailedPreconditionError(
2968 "Expanded message source has unpublished edits; use Preview and "
2969 "Publish in the Message editor before saving");
2970 }
2972 const size_t session_id = GetCurrentSessionId();
2973 RETURN_IF_ERROR(SaveProjectWorkBeforeRomSave(/*allow_dialogs=*/true));
2974 if (GetCurrentSessionId() != session_id) {
2975 return absl::FailedPreconditionError(
2976 "The active session changed while saving project work");
2977 }
2979 return SaveRom();
2980 }
2982}
2983
2985 auto* session = session_coordinator_
2986 ? session_coordinator_->GetActiveRomSession()
2987 : nullptr;
2988 const auto* rom = GetCurrentRom();
2989 if (session == nullptr || !session->native_save_completion_pending ||
2991 rom == nullptr || !rom->is_loaded() || rom->filename().empty()) {
2992 return absl::OkStatus();
2993 }
2995 session->native_save_completion_save_as,
2996 /*rom_written=*/false);
2997}
2998
2999absl::Status EditorManager::SaveProjectWorkBeforeRomSave(bool allow_dialogs) {
3000 // A project-only receipt failure must not block the following ROM save.
3003 const auto status = SaveActiveProjectEditingWork(allow_dialogs);
3005 return status;
3006}
3007
3009 // Do not let an autosave or an unrelated Ctrl+S replace a Save As request
3010 // while one of its confirmation dialogs is still open.
3011 if (pending_rom_save_.has_value()) {
3012 const bool unresolved_confirmation =
3017 if (unresolved_confirmation) {
3018 return absl::CancelledError("Save pending confirmation");
3019 }
3020 // Preserve the established request after programmatic confirmation too.
3021 // Older callers use ConfirmRomWrite(); SaveRom() rather than the popup's
3022 // ResumePendingRomSave() helper.
3023 return ResumePendingRomSave();
3024 }
3025 RETURN_IF_ERROR(StartPendingRomSave(std::nullopt));
3026 auto status = SaveRomInternal(std::nullopt);
3028 return status;
3029}
3030
3031absl::Status EditorManager::SaveRomAs(const std::string& filename) {
3032 if (filename.empty()) {
3033 return absl::InvalidArgumentError("No filename provided for save as");
3034 }
3035 if (pending_rom_save_.has_value() && HasPendingRomSaveConfirmation()) {
3036 return absl::CancelledError("Save pending confirmation");
3037 }
3039 auto status = SaveRomInternal(filename);
3041 return status;
3042}
3043
3045 if (!pending_rom_save_.has_value()) {
3047 return absl::FailedPreconditionError("No pending ROM save to resume");
3048 }
3050 CancelPendingRomSave(/*hide_popups=*/true);
3051 return absl::FailedPreconditionError(
3052 "Pending ROM save belongs to a different session");
3053 }
3054
3055 const auto save_as_filename = pending_rom_save_->save_as_filename;
3056 auto status = SaveRomInternal(save_as_filename);
3058 return status;
3059}
3060
3061std::string EditorManager::ExecuteEditorControl(const std::string& request) {
3062#ifdef YAZE_WITH_JSON
3063 using nlohmann::json;
3065 json response = {{"protocol", "yaze-editor-control/v1"},
3066 {"status", "ok"},
3067 {"http_status", 200}};
3068 response["capabilities"]["commands"] = {"status",
3069 "project.open",
3070 "project.rom.swap",
3071 "dungeon.select",
3072 "proposal.load",
3073 "panel.hide",
3074 "overworld.stencil.apply"};
3075#ifdef _WIN32
3076 const auto pid = _getpid();
3077#else
3078 const auto pid = getpid();
3079#endif
3080 const auto rom_sha256 = [](const Rom& rom) {
3081 return core::ComputeSourceArtifactSha256(std::string_view(
3082 reinterpret_cast<const char*>(rom.data()), rom.size()));
3083 };
3084 auto fail = [&](int code, const std::string& message) {
3085 response["status"] = "error";
3086 response["http_status"] = code;
3087 response["error"] = message;
3088 };
3089 try {
3090 const auto body = json::parse(request);
3091 const std::string command = body.at("command").get<std::string>();
3092 response["command"] = command;
3093 auto path_argument = [&]() -> std::string {
3094 const auto path = body.at("path").get<std::string>();
3095 if (path.empty() || path.find('\0') != std::string::npos ||
3096 !std::filesystem::path(path).is_absolute()) {
3097 throw std::invalid_argument("path must be an absolute local path");
3098 }
3099 return path;
3100 };
3101 auto dungeon_editor = [&]() -> DungeonEditorV2* {
3102 auto* editors = GetCurrentEditorSet();
3103 return editors
3104 ? editors->GetEditorAs<DungeonEditorV2>(EditorType::kDungeon)
3105 : nullptr;
3106 };
3107 const auto hash_argument = [](const json& value) {
3108 const auto hash = value.get<std::string>();
3109 if (hash.size() != 64 ||
3110 !std::all_of(hash.begin(), hash.end(), [](char ch) {
3111 return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f');
3112 })) {
3113 throw std::invalid_argument(
3114 "SHA256 must contain 64 lowercase hexadecimal characters");
3115 }
3116 return hash;
3117 };
3118 // The caller names the exact editor it inspected; any other process,
3119 // session, project, ROM file or ROM bytes refuses the command.
3120 const auto expected_editor_matches = [&](const json& expected) {
3121 for (const auto* field : {"pid", "session_id"}) {
3122 if (!expected.at(field).is_number_integer() || expected.at(field) < 0 ||
3123 (std::string_view(field) == "pid" && expected.at(field) == 0)) {
3124 throw std::invalid_argument(
3125 "expected pid and session_id must be valid nonnegative integers");
3126 }
3127 }
3128 const auto expected_path = [&](const char* field) {
3129 const auto value = expected.at(field).get<std::string>();
3130 if (value.empty() || value.find('\0') != std::string::npos ||
3131 !std::filesystem::path(value).is_absolute()) {
3132 throw std::invalid_argument(std::string("expected ") + field +
3133 " must be an absolute local path");
3134 }
3135 return value;
3136 };
3137 const auto project_path = expected_path("project_path");
3138 const auto current_rom_path = expected_path("rom_path");
3139 const auto current_sha256 = hash_argument(expected.at("rom_sha256"));
3140 const auto* rom = GetCurrentRom();
3141 return current_project_.project_opened() && rom && rom->is_loaded() &&
3142 expected.at("pid") == pid &&
3143 expected.at("session_id") == GetCurrentSessionId() &&
3145 project_path, current_project_.filepath) &&
3147 rom->filename()) &&
3148 current_sha256 == rom_sha256(*rom);
3149 };
3150 if (command == "status") {
3151 // Read-only; usable before a ROM is opened.
3152 } else if (command == "project.open") {
3153 const auto path = path_argument();
3154 const auto extension = std::filesystem::path(path).extension();
3155 if (extension != ".yaze" && extension != ".zsproj" &&
3156 extension != ".yazeproj") {
3157 fail(400, "project.open requires a .yaze, .zsproj or .yazeproj path");
3158 } else if (HasAnySessionPendingUnsavedWork() ||
3160 fail(409, "Project switch blocked: " + DescribeAllPendingUnsavedWork());
3161 } else if (current_project_.filepath != path) {
3162 // No implicit save/discard and no repair/file picker fallback.
3163 const auto status = OpenRomOrProjectInternal(path, false);
3164 if (!status.ok())
3165 fail(422, std::string(status.message()));
3166 }
3167 } else if (command == "project.rom.swap") {
3168 const auto path = path_argument();
3169 const auto candidate_sha256 = hash_argument(body.at("candidate_sha256"));
3170 const bool identity_matches =
3171 expected_editor_matches(body.at("expected"));
3174 fail(409, "ROM swap blocked by pending work or action: " +
3176 } else if (!identity_matches) {
3177 fail(409,
3178 "ROM swap expected identity does not match the active editor");
3179 } else {
3180 const auto status = SwapProjectRom(path, candidate_sha256);
3181 if (!status.ok()) {
3182 fail(absl::IsAborted(status) ? 409 : 422,
3183 std::string(status.message()));
3184 }
3185 }
3186 } else if (command == "overworld.stencil.apply") {
3187 const auto path = path_argument();
3188 const auto stencil_sha256 = hash_argument(body.at("stencil_sha256"));
3189 const bool identity_matches =
3190 expected_editor_matches(body.at("expected"));
3191 std::ifstream file(path, std::ios::binary);
3192 const std::string bytes((std::istreambuf_iterator<char>(file)),
3193 std::istreambuf_iterator<char>());
3194 if (!file.good() && !file.eof()) {
3195 fail(422, "Stencil file could not be read");
3196 } else if (core::ComputeSourceArtifactSha256(bytes) != stencil_sha256) {
3197 fail(409, "Stencil file does not match stencil_sha256");
3198 } else if (HasAnySessionPendingUnsavedWork() ||
3200 fail(409, "Stencil blocked by pending work or action: " +
3202 } else if (!identity_matches) {
3203 fail(409, "Stencil expected identity does not match the active editor");
3204 } else {
3205 const auto stencil = json::parse(bytes);
3206 if (stencil.at("schema").get<std::string>() !=
3207 "yaze.overworld_tile16_stencil.v1") {
3208 throw std::invalid_argument(
3209 "Stencil schema must be yaze.overworld_tile16_stencil.v1");
3210 }
3211 const int map_id = stencil.at("map_id").get<int>();
3212 std::vector<GuardedTileCell> cells;
3213 for (const auto& cell : stencil.at("cells")) {
3214 const auto tile = [&](const char* field) {
3215 const int value = cell.at(field).get<int>();
3216 if (value < 0 || value > 0xFFFF) {
3217 throw std::invalid_argument(std::string("Stencil ") + field +
3218 " must be a Tile16 ID");
3219 }
3220 return static_cast<uint16_t>(value);
3221 };
3222 cells.push_back({cell.at("x").get<int>(), cell.at("y").get<int>(),
3223 tile("expected"), tile("proposed")});
3224 }
3226 auto* editors = GetCurrentEditorSet();
3227 auto* overworld =
3228 editors
3229 ? editors->GetEditorAs<OverworldEditor>(EditorType::kOverworld)
3230 : nullptr;
3231 if (!loaded.ok()) {
3232 fail(422, std::string(loaded.message()));
3233 } else if (!overworld) {
3234 fail(503, "Overworld editor is unavailable");
3235 } else {
3237 const auto changed = overworld->ApplyTile16Stencil(map_id, cells);
3238 if (!changed.ok()) {
3239 fail(absl::IsFailedPrecondition(changed.status()) ? 409 : 422,
3240 std::string(changed.status().message()));
3241 } else {
3242 response["map_id"] = map_id;
3243 response["cells"] = cells.size();
3244 response["cells_changed"] = *changed;
3245 response["stencil_sha256"] = stencil_sha256;
3246 }
3247 }
3248 }
3249 } else if (command == "dungeon.select" || command == "proposal.load") {
3250 int room = -1;
3251 std::string path;
3252 if (command == "dungeon.select") {
3253 if (!body.at("room").is_number_integer()) {
3254 throw std::invalid_argument("room must be an integer from 0 to 295");
3255 }
3256 room = body.at("room").get<int>();
3257 if (room < 0 || room >= 296) {
3258 throw std::invalid_argument("room must be an integer from 0 to 295");
3259 }
3260 } else {
3261 path = path_argument();
3262 }
3263 if (!GetCurrentRom() || !GetCurrentRom()->is_loaded()) {
3264 fail(409, "No ROM loaded");
3265 } else {
3267 if (!loaded.ok()) {
3268 fail(422, std::string(loaded.message()));
3269 } else if (auto* dungeon = dungeon_editor()) {
3271 if (command == "dungeon.select") {
3272 dungeon->add_room(room);
3273 dungeon->FocusRoom(room);
3274 if (dungeon->current_room_id() != room) {
3275 fail(422, "Dungeon room selection did not complete");
3276 }
3277 } else {
3278 const auto status = dungeon->LoadProposalForReview(path);
3279 if (!status.ok())
3280 fail(422, std::string(status.message()));
3281 }
3282 } else {
3283 fail(503, "Dungeon editor is unavailable");
3284 }
3285 }
3286 } else if (command == "panel.hide") {
3287 const auto id = body.at("panel").get<std::string>();
3289 fail(404, "Unknown panel ID for the active session: " + id);
3290 } else {
3292 response["panel"] = id;
3293 response["panel_visible"] = window_manager_.IsWindowOpen(id);
3294 if (response["panel_visible"].get<bool>()) {
3295 fail(409, "Panel did not close");
3296 }
3297 }
3298 } else {
3299 fail(400, "Unknown editor command: " + command);
3300 }
3301 } catch (const std::exception& error) {
3302 fail(400, error.what());
3303 }
3304 // Report the state after completion or rejection, never the requested path.
3305 json state;
3306 state["pid"] = pid;
3307 state["project_path"] = current_project_.filepath;
3308 state["session_id"] = GetCurrentSessionId();
3309 state["session_count"] =
3310 session_coordinator_ ? session_coordinator_->GetTotalSessionCount() : 0;
3311 state["sessions"] = json::array();
3313 for (size_t i = 0; i < session_coordinator_->GetTotalSessionCount(); ++i) {
3314 auto* session =
3315 static_cast<RomSession*>(session_coordinator_->GetSession(i));
3316 const auto* project =
3317 IsCurrentProjectContextOwnedBySession(session->session_id())
3319 : session->project_context.has_value() ? &*session->project_context
3320 : nullptr;
3321 json item = {{"session_id", session->session_id()},
3322 {"active", i == GetCurrentSessionIndex()},
3323 {"loaded", session->rom.is_loaded()},
3324 {"project_path", project ? project->filepath : ""},
3325 {"rom_dirty", session->rom.dirty()},
3326 {"unsaved", SessionHasPendingUnsavedWork(i)}};
3327 item["rom_path"] = session->rom.is_loaded()
3328 ? json(session->rom.filename())
3329 : json(nullptr);
3330 state["sessions"].push_back(std::move(item));
3331 }
3332 }
3333 state["unsaved"] = HasAnySessionPendingUnsavedWork();
3334 state["unsaved_detail"] = DescribeAllPendingUnsavedWork();
3335 state["pending_action"] = HasPendingUnsavedSessionAction();
3336 if (auto* rom = GetCurrentRom(); rom && rom->is_loaded()) {
3337 state["rom_path"] = rom->filename();
3338 state["rom_title"] = rom->title();
3339 state["rom_size"] = rom->size();
3340 state["rom_dirty"] = rom->dirty();
3341 state["rom_sha256"] = rom_sha256(*rom);
3342 } else {
3343 state["rom_path"] = nullptr;
3344 state["rom_sha256"] = nullptr;
3345 }
3346 state["room"] = nullptr;
3347 state["proposal_path"] = nullptr;
3348 if (auto* editors = GetCurrentEditorSet()) {
3349 if (auto* dungeon =
3350 editors->GetEditorAs<DungeonEditorV2>(EditorType::kDungeon)) {
3351 state["room"] = dungeon->current_room_id();
3352 state["proposal_path"] = dungeon->proposal_review_path();
3353 }
3354 }
3355 state["visible_panels"] = json::array();
3356 for (const auto& id :
3358 if (window_manager_.IsWindowOpen(id)) {
3359 state["visible_panels"].push_back(id);
3360 }
3361 }
3362 response["state"] = std::move(state);
3363 return response.dump();
3364#else
3365 return R"({"status":"error","http_status":503,"error":"JSON support unavailable"})";
3366#endif
3367}
3368
3370 const std::string& filename) {
3371 if (!session_coordinator_ || filename.empty() ||
3374 return false;
3375 }
3376 const bool is_project = absl::EndsWith(filename, ".yaze") ||
3377 absl::EndsWith(filename, ".zsproj") ||
3378 absl::EndsWith(filename, ".yazeproj");
3379 const size_t count = session_coordinator_->GetTotalSessionCount();
3380 // Prefer the active owner if an older app left duplicate sessions behind.
3381 for (size_t step = 0; step < count; ++step) {
3382 const size_t index = (GetCurrentSessionIndex() + step) % count;
3383 auto* session =
3384 static_cast<RomSession*>(session_coordinator_->GetSession(index));
3385 if (!session || !session->rom.is_loaded()) {
3386 continue;
3387 }
3388 bool matches = false;
3389 if (is_project) {
3390 const auto* project =
3391 IsCurrentProjectContextOwnedBySession(session->session_id())
3393 : session->project_context.has_value() ? &*session->project_context
3394 : nullptr;
3395 matches = project && project->project_opened() &&
3397 filename, project->filepath);
3398 } else {
3400 filename, session->filepath) ||
3402 filename, session->rom.filename());
3403 }
3404 if (matches) {
3405 // Reuse the loaded buffers and editor drafts. Switching away from another
3406 // dirty session still follows the ordinary unsaved-work guard.
3407 SwitchToSession(index);
3408 return true;
3409 }
3410 }
3411 return false;
3412}
3413
3414absl::Status EditorManager::OpenRomOrProject(const std::string& filename,
3415 LoadOptionsPrompt prompt) {
3416 if (ActivateExistingSessionForOpen(filename)) {
3417 return absl::OkStatus();
3418 }
3421 GetCurrentSessionId(), SIZE_MAX, filename, prompt})) {
3422 return absl::OkStatus();
3423 }
3424
3425 return OpenRomOrProjectInternal(filename, /*allow_dialogs=*/true, prompt);
3426}
3427
3429 const std::string& filename, bool allow_dialogs, LoadOptionsPrompt prompt) {
3430 LOG_INFO("EditorManager", "OpenRomOrProject called with: '%s'",
3431 filename.c_str());
3432 if (filename.empty()) {
3433 LOG_INFO("EditorManager", "Empty filename provided, skipping load.");
3434 return absl::OkStatus();
3435 }
3436 if (ActivateExistingSessionForOpen(filename)) {
3437 return absl::OkStatus();
3438 }
3439
3440#ifdef __EMSCRIPTEN__
3441 // Start loading indicator early for WASM builds
3442 auto loading_handle =
3443 app::platform::WasmLoadingManager::BeginLoading("Loading ROM");
3444 app::platform::WasmLoadingManager::UpdateMessage(loading_handle,
3445 "Reading ROM file...");
3446 // RAII guard to ensure loading indicator is closed even on early return
3447 struct LoadingGuard {
3448 app::platform::WasmLoadingManager::LoadingHandle handle;
3449 bool dismissed = false;
3450 ~LoadingGuard() {
3451 if (!dismissed)
3452 app::platform::WasmLoadingManager::EndLoading(handle);
3453 }
3454 void dismiss() { dismissed = true; }
3455 } loading_guard{loading_handle};
3456#endif
3457
3458 if (absl::EndsWith(filename, ".yaze") ||
3459 absl::EndsWith(filename, ".zsproj") ||
3460 absl::EndsWith(filename, ".yazeproj")) {
3461 // Parse first so a failed project open cannot destroy the active session's
3462 // working context. Detach only when the incoming project is ready.
3463 project::YazeProject incoming_project;
3464 RETURN_IF_ERROR(incoming_project.Open(filename));
3465 if (!incoming_project.rom_filename.empty()) {
3466 RETURN_IF_ERROR(session_coordinator_->CheckBackingFileAvailable(
3467 incoming_project.rom_filename));
3468 }
3469 const std::optional<size_t> previous_session_id =
3472 pending_project_open_previous_session_id_ = previous_session_id;
3474 current_project_ = std::move(incoming_project);
3477
3478 // Automation cannot fall back to a file dialog for a missing/invalid ROM.
3479 auto project_status = LoadProjectWithRom(allow_dialogs);
3480 if (!project_status.ok()) {
3481 RestoreProjectContextAfterFailedOpen(previous_session_id);
3482 }
3483 return project_status;
3484 } else {
3485#ifdef __EMSCRIPTEN__
3486 app::platform::WasmLoadingManager::UpdateProgress(loading_handle, 0.05f);
3487 app::platform::WasmLoadingManager::UpdateMessage(loading_handle,
3488 "Loading ROM data...");
3489#endif
3490 Rom temp_rom;
3491 RETURN_IF_ERROR(session_coordinator_->CheckBackingFileAvailable(filename));
3492 RETURN_IF_ERROR(rom_file_manager_.LoadRom(&temp_rom, filename));
3494
3495 const std::optional<size_t> previous_session_id =
3497 const size_t previous_session_count =
3498 session_coordinator_->GetTotalSessionCount();
3499 auto session_or = session_coordinator_->CreateSessionFromRom(
3500 std::move(temp_rom), filename);
3501 if (!session_or.ok()) {
3502 return session_or.status();
3503 }
3504 RomSession* session = *session_or;
3505
3509
3510 // Apply project feature flags to both session and global singleton
3514 // A choice remembered for this file applies to prompted and unprompted
3515 // opens alike, and has to be live before assets load.
3516 const bool remembered_load_options = allow_dialogs &&
3517 ui_coordinator_ != nullptr &&
3519 // Ask only when nothing is remembered and no project owns the flags.
3520 const bool ask_for_load_options =
3521 prompt == LoadOptionsPrompt::kAsk && allow_dialogs &&
3522 ui_coordinator_ != nullptr && !remembered_load_options &&
3524
3525 // Keep ResourceLabelProvider in sync with the active ROM session before
3526 // editors register room/sprite labels.
3528
3529 // Update test manager with current ROM for ROM-dependent tests (only when
3530 // tests are enabled)
3531#ifdef YAZE_ENABLE_TESTING
3532 LOG_DEBUG("EditorManager", "Setting ROM in TestManager - %p ('%s')",
3533 (void*)GetCurrentRom(),
3534 GetCurrentRom() ? GetCurrentRom()->title().c_str() : "null");
3536#endif
3537
3538 if (auto* editor_set = GetCurrentEditorSet();
3539 editor_set && !current_project_.code_folder.empty()) {
3540 const std::string absolute_code_folder =
3542 // iOS: avoid blocking the main thread during project open / scene updates.
3543 // Large iCloud-backed projects can trigger watchdog termination if we
3544 // eagerly enumerate folders here.
3545#if !(defined(__APPLE__) && TARGET_OS_IOS == 1)
3546 editor_set->OpenAssemblyFolder(absolute_code_folder);
3547#endif
3548 // Also set the sidebar file browser path (refresh happens during UI draw).
3549 window_manager_.SetFileBrowserPath("Assembly", absolute_code_folder);
3550 }
3551
3552#ifdef __EMSCRIPTEN__
3553 app::platform::WasmLoadingManager::UpdateProgress(loading_handle, 0.10f);
3554 app::platform::WasmLoadingManager::UpdateMessage(loading_handle,
3555 "Initializing editors...");
3556 // Pass the loading handle to LoadAssets and dismiss our guard
3557 // LoadAssets will manage closing the indicator when done
3558 loading_guard.dismiss();
3559 auto asset_status = LoadAssetsForMode(loading_handle);
3560#else
3561 auto asset_status = LoadAssetsForMode();
3562#endif
3563 if (!asset_status.ok()) {
3564 auto rollback_status =
3565 DiscardProvisionalSessionCreatedSince(previous_session_count);
3566 RestoreProjectContextAfterFailedOpen(previous_session_id);
3567 if (!rollback_status.ok()) {
3568 return absl::InternalError(
3569 absl::StrFormat("%s; session rollback failed: %s",
3570 asset_status.message(), rollback_status.message()));
3571 }
3572 return asset_status;
3573 }
3574
3575 bool is_first_time_rom_path = false;
3576 if (ask_for_load_options) {
3577 const auto& recent_files =
3579 is_first_time_rom_path =
3580 std::find(recent_files.begin(), recent_files.end(), filename) ==
3581 recent_files.end();
3582 }
3583 FinishRawRomOpen(remembered_load_options, ask_for_load_options,
3584 is_first_time_rom_path);
3586 }
3587 return absl::OkStatus();
3588}
3589
3590absl::Status EditorManager::CreateNewProject(const std::string& template_name) {
3592 return absl::FailedPreconditionError(
3593 "Save or discard pending session work before creating a project");
3594 }
3595
3596 if (!ui_coordinator_) {
3597 return absl::FailedPreconditionError(
3598 "Project creation dialog is not available");
3599 }
3600 ui_coordinator_->OpenNewProjectDialog(
3601 template_name.empty() ? "Vanilla ROM Hack" : template_name);
3602 return absl::OkStatus();
3603}
3604
3606 const std::string& template_name, const std::string& rom_path,
3607 const std::string& project_name, const std::string& project_path) {
3608 if (rom_path.empty() || project_name.empty()) {
3609 return absl::InvalidArgumentError("ROM path and project name are required");
3610 }
3611 if (absl::EndsWith(rom_path, ".yaze") ||
3612 absl::EndsWith(rom_path, ".yazeproj") ||
3613 absl::EndsWith(rom_path, ".zsproj")) {
3614 return absl::InvalidArgumentError(
3615 "New projects require a ROM file, not a project descriptor");
3616 }
3618 return absl::FailedPreconditionError(
3619 "Save or discard pending session work before creating a project");
3620 }
3621
3622 auto* reusable_session = session_coordinator_
3623 ? session_coordinator_->GetActiveRomSession()
3624 : nullptr;
3625 const bool reuse_active_raw_session =
3626 reusable_session && reusable_session->rom.is_loaded() &&
3628 rom_path, reusable_session->rom.filename()) &&
3631 const std::optional<size_t> previous_session_id =
3633 const size_t previous_session_count =
3634 session_coordinator_ ? session_coordinator_->GetTotalSessionCount() : 0;
3636 auto rom_status = project_manager_.SetProjectRom(rom_path);
3637 if (!rom_status.ok()) {
3639 return rom_status;
3640 }
3642 project_name, project_path);
3643 if (!target_status.ok()) {
3645 return target_status;
3646 }
3647
3648 if (reuse_active_raw_session) {
3649 return FinalizeNewProject(project_name, project_path);
3650 }
3651
3655
3656 // The new project, not the load options dialog, owns the flags.
3657 auto open_status = OpenRomOrProjectInternal(rom_path, /*allow_dialogs=*/true,
3659 if (!open_status.ok()) {
3661 RestoreProjectContextAfterFailedOpen(previous_session_id);
3662 return open_status;
3663 }
3664
3665 auto finalize_status = FinalizeNewProject(project_name, project_path);
3666 if (!finalize_status.ok()) {
3667 auto rollback_status =
3668 DiscardProvisionalSessionCreatedSince(previous_session_count);
3669 RestoreProjectContextAfterFailedOpen(previous_session_id);
3670 if (!rollback_status.ok()) {
3671 return absl::InternalError(absl::StrFormat(
3672 "%s; session rollback failed: %s", finalize_status.message(),
3673 rollback_status.message()));
3674 }
3675 }
3676 return finalize_status;
3677}
3678
3680 const std::string& project_name, const std::string& project_path) {
3681 if (!session_coordinator_) {
3682 return absl::FailedPreconditionError("No session coordinator");
3683 }
3684 auto* session = session_coordinator_->GetActiveRomSession();
3685 if (!session || !session->rom.is_loaded()) {
3686 return absl::FailedPreconditionError(
3687 "Load a ROM before finalizing the project");
3688 }
3689
3690 // The ROM-load-options dialog can create a project directly from an
3691 // already-open raw ROM. Start from a clean shell in that path rather than
3692 // reusing ProjectManager state left by an earlier project/import.
3693 const bool created_project_shell = !project_manager_.IsPendingRomSelection();
3694 if (created_project_shell) {
3696 }
3697
3698 auto project_rom_status =
3699 project_manager_.SetProjectRom(session->rom.filename());
3700 if (!project_rom_status.ok()) {
3702 return project_rom_status;
3703 }
3704 auto& pending_project = project_manager_.GetCurrentProject();
3705 if (created_project_shell) {
3706 // ROM-load options apply their selected flags directly to the raw session.
3707 // Guided creation already configured the pending template, including when
3708 // it reuses an existing raw-ROM session.
3709 pending_project.feature_flags = session->feature_flags;
3710 }
3711 pending_project.workspace_settings.font_global_scale =
3713 pending_project.workspace_settings.autosave_enabled =
3715 pending_project.workspace_settings.autosave_interval_secs =
3717 pending_project.workspace_settings.backup_on_save =
3719
3720 auto finalize_status =
3721 project_manager_.FinalizeProjectCreation(project_name, project_path);
3722 if (!finalize_status.ok()) {
3724 return finalize_status;
3725 }
3726
3729 session->project_dirty = false;
3730 active_project_context_session_id_ = session->session_id();
3731 runtime_feature_flags_session_id_ = session->session_id();
3733 if (version_manager_) {
3734 // Creating a project never creates a Git repository; the Initialize Git
3735 // action in Project Management is the opt-in. Adopt one that exists.
3737 current_project_.git_repository = session->project_context->git_repository;
3739 }
3743 return absl::OkStatus();
3744}
3745
3749 GetCurrentSessionId()})) {
3750 return absl::OkStatus();
3751 }
3752
3753 return OpenProjectInternal();
3754}
3755
3757 auto open_project_from_path =
3758 [this](const std::string& file_path) -> absl::Status {
3759 if (file_path.empty()) {
3760 return absl::OkStatus();
3761 }
3762 if (ActivateExistingSessionForOpen(file_path)) {
3763 return absl::OkStatus();
3764 }
3765
3766 project::YazeProject new_project;
3767 RETURN_IF_ERROR(new_project.Open(file_path));
3768
3769 if (!new_project.rom_filename.empty()) {
3770 RETURN_IF_ERROR(session_coordinator_->CheckBackingFileAvailable(
3771 new_project.rom_filename));
3772 }
3773
3774 // Validate project
3775 auto validation_status = new_project.Validate();
3776 if (!validation_status.ok()) {
3777 toast_manager_.Show(absl::StrFormat("Project validation failed: %s",
3778 validation_status.message()),
3780
3781 // Ask user if they want to repair
3782 popup_manager_->Show("Project Repair");
3783 }
3784
3785 const std::optional<size_t> previous_session_id =
3788 pending_project_open_previous_session_id_ = previous_session_id;
3790 current_project_ = std::move(new_project);
3792
3793 auto project_status = LoadProjectWithRom();
3794 if (!project_status.ok()) {
3795 RestoreProjectContextAfterFailedOpen(previous_session_id);
3796 }
3797 return project_status;
3798 };
3799
3800#if defined(__APPLE__) && TARGET_OS_IOS == 1
3801 // On iOS, route project selection through the SwiftUI overlay document picker
3802 // so we get open-in-place + security-scoped access for iCloud Drive bundles.
3803 platform::ios::PostOverlayCommand("open_project");
3804 return absl::OkStatus();
3805#else
3807 return open_project_from_path(file_path);
3808#endif
3809}
3810
3812 const std::string& rom_path) {
3813 RETURN_IF_ERROR(session_coordinator_->CheckBackingFileAvailable(rom_path));
3814
3815 Rom candidate_rom;
3816 RETURN_IF_ERROR(rom_file_manager_.LoadRom(&candidate_rom, rom_path));
3818
3821 .candidate_path = rom_path,
3822 };
3823 return absl::OkStatus();
3824}
3825
3827 const std::string& rom_path,
3828 const std::optional<std::string>& expected_sha256) {
3829 if (rom_path.empty()) {
3830 return absl::InvalidArgumentError("ROM path cannot be empty");
3831 }
3832 if (!session_coordinator_) {
3833 return absl::FailedPreconditionError("No session coordinator");
3834 }
3835 auto* session = session_coordinator_->GetActiveRomSession();
3836 if (!session || !session->rom.is_loaded() ||
3838 return absl::FailedPreconditionError("No active project ROM session");
3839 }
3841 session->editors.HasPendingProjectDraftChanges()) {
3842 return absl::FailedPreconditionError(
3843 "Save or discard ROM or project edits before swapping the project ROM");
3844 }
3846 if (session->project_file_editor_state.initialized &&
3847 session->project_file_editor_state.modified &&
3849 return absl::FailedPreconditionError(
3850 "Preserve the raw project-file draft before swapping ROMs");
3851 }
3852
3853 RETURN_IF_ERROR(session_coordinator_->CheckBackingFileAvailable(
3854 rom_path, session->session_id()));
3855 Rom replacement_rom;
3856 RETURN_IF_ERROR(rom_file_manager_.LoadRom(&replacement_rom, rom_path));
3857 // Bind approval to the bytes that will replace the session, not a separate
3858 // file read that could change before LoadRom. Reject before descriptor Save.
3859 if (expected_sha256 &&
3860 *expected_sha256 !=
3861 core::ComputeSourceArtifactSha256(std::string_view(
3862 reinterpret_cast<const char*>(replacement_rom.data()),
3863 replacement_rom.size()))) {
3864 return absl::AbortedError("Loaded candidate ROM SHA256 does not match");
3865 }
3866
3867 // Save As deliberately leaves the project's collision source untouched.
3868 // Refuse an incompatible copy before saving the descriptor or rebuilding
3869 // live editor models: otherwise neither normal Save nor Build can repair
3870 // the newly mismatched pair. Rebinding never publishes source changes.
3873 &replacement_rom, current_project_.GetAbsolutePath(
3875 }
3877
3878 std::string replacement_path = rom_path;
3883 // The policy proved this is the manifest's exact backing file. Bind its
3884 // canonical path so an accepted alias cannot later fail the write policy
3885 // or be replaced as a separate file by the atomic ROM save.
3886 std::error_code ec;
3887 const auto development_path = std::filesystem::canonical(
3890 ec);
3891 if (ec) {
3892 return absl::FailedPreconditionError(absl::StrFormat(
3893 "Cannot resolve the manifest development ROM before rebinding: %s",
3894 ec.message()));
3895 }
3896 replacement_path = development_path.string();
3897 replacement_rom.set_filename(replacement_path);
3898 }
3899
3900 const std::string old_rom_path = current_project_.rom_filename;
3901 current_project_.rom_filename = replacement_path;
3902 auto save_status = current_project_.Save();
3903 if (!save_status.ok()) {
3904 current_project_.rom_filename = old_rom_path;
3905 return save_status;
3906 }
3907
3909 auto replace_status =
3910 ReplaceActiveSessionRom(std::move(replacement_rom), replacement_path);
3911 if (!replace_status.ok()) {
3912 current_project_.rom_filename = old_rom_path;
3913 auto rollback_status = current_project_.Save();
3916 if (!rollback_status.ok()) {
3917 return absl::InternalError(absl::StrFormat(
3918 "ROM swap failed (%s) and restoring the project descriptor failed "
3919 "(%s)",
3920 replace_status.message(), rollback_status.message()));
3921 }
3922 return replace_status;
3923 }
3924 session->project_dirty = false;
3926 project_management_panel_->SetProjectDirty(false);
3927 }
3930 return absl::OkStatus();
3931}
3932
3934 if (!session_coordinator_) {
3935 return absl::FailedPreconditionError("No session coordinator");
3936 }
3937 auto* session = session_coordinator_->GetActiveRomSession();
3938 if (!session || !session->rom.is_loaded() ||
3941 return absl::FailedPreconditionError("No active project ROM to reload");
3942 }
3944 session->editors.HasPendingProjectDraftChanges()) {
3945 return absl::FailedPreconditionError(
3946 "Save or discard ROM or project edits before reloading from disk");
3947 }
3948
3949 RETURN_IF_ERROR(session_coordinator_->CheckBackingFileAvailable(
3950 current_project_.rom_filename, session->session_id()));
3951 Rom replacement_rom;
3952 RETURN_IF_ERROR(rom_file_manager_.LoadRom(&replacement_rom,
3955 return ReplaceActiveSessionRom(std::move(replacement_rom),
3957}
3958
3961 return absl::FailedPreconditionError(
3962 "Save a Yaze project before creating or opening Lyra terrain");
3963 }
3965 return absl::FailedPreconditionError(
3966 "Lyra terrain requires its project session to be active");
3967 }
3968 auto* rom = GetCurrentRom();
3969 if (!rom || !rom->is_loaded() || !GetCurrentEditorSet()) {
3970 return absl::FailedPreconditionError(
3971 "Load the project's ROM before creating or opening Lyra terrain");
3972 }
3973 return absl::OkStatus();
3974}
3975
3979 auto* overworld = GetCurrentEditorSet()->GetEditorAs<OverworldEditor>(
3981 if (!overworld) {
3982 return absl::NotFoundError("Overworld editor is unavailable");
3983 }
3984 const auto previous_source = current_project_.lyra_terrain_file;
3985 RETURN_IF_ERROR(overworld->CreateLyraTerrain());
3986 if (previous_source != current_project_.lyra_terrain_file ||
3987 overworld->HasPendingProjectDraftChanges()) {
3989 }
3992 return absl::OkStatus();
3993}
3994
3998 options.filters.push_back({"Lyra terrain source", "json"});
4001}
4002
4003absl::Status EditorManager::OpenLyraTerrainFromPath(const std::string& path) {
4004 if (path.empty()) {
4005 return absl::OkStatus();
4006 }
4009 auto* overworld = GetCurrentEditorSet()->GetEditorAs<OverworldEditor>(
4011 if (!overworld) {
4012 return absl::NotFoundError("Overworld editor is unavailable");
4013 }
4014 const auto previous_source = current_project_.lyra_terrain_file;
4015 RETURN_IF_ERROR(overworld->OpenLyraTerrain(path));
4016 if (previous_source != current_project_.lyra_terrain_file) {
4018 }
4021 return absl::OkStatus();
4022}
4023
4027 if (auto* session = session_coordinator_->GetActiveRomSession();
4028 session && session->project_file_editor_state.initialized &&
4029 session->project_file_editor_state.modified &&
4031 return absl::FailedPreconditionError(
4032 "Raw project file also has unsaved changes; use raw Save As to "
4033 "preserve that draft before saving project settings");
4034 }
4035 }
4036 auto* save_session = session_coordinator_
4037 ? session_coordinator_->GetActiveRomSession()
4038 : nullptr;
4039 if (save_session != nullptr && IsPlanningOnlyProjectSave(*save_session)) {
4040 // The plan is a live reference outside the build: its own CAS save is the
4041 // whole Save, leaving the descriptor and native receipt untouched.
4042 return save_session->editors.SavePlanningProjectDraft();
4043 }
4044 // Every other project Save commits build-owned work: the descriptor and
4045 // any terrain/sprite/dungeon drafts. Retire the prior native commit before
4046 // any of those bytes change.
4047 const bool build_owned =
4048 current_project_.project_opened() && save_session != nullptr;
4049 if (build_owned) {
4051 }
4055 return CreateNewProject();
4056 }
4057
4058 ApplyProjectSaveSettings(&current_project_, /*include_recent_files=*/true);
4059
4060 auto status = current_project_.Save();
4061 if (status.ok()) {
4062 if (auto* editors = GetCurrentEditorSet())
4063 editors->ProjectSaveCommitted();
4065 project_management_panel_->SetProjectDirty(false);
4066 }
4068 if (auto* session = session_coordinator_->GetActiveRomSession()) {
4069 session->project_dirty = false;
4070 }
4071 }
4073 }
4075 if (!status.ok() || !build_owned) {
4076 return status;
4077 }
4078 save_session->native_save_completion_pending = true;
4080 return absl::OkStatus();
4081 }
4083}
4084
4086 bool include_recent_files) {
4087 if (!GetCurrentRom() || !GetCurrentEditorSet()) {
4088 return;
4089 }
4091 if (auto* session = session_coordinator_->GetActiveRomSession()) {
4092 project->feature_flags = session->feature_flags;
4093 }
4094 }
4103 if (!include_recent_files) {
4104 return;
4105 }
4107 project->workspace_settings.recent_files.clear();
4108 for (const auto& file : manager.GetRecentFiles()) {
4109 project->workspace_settings.recent_files.push_back(file);
4110 }
4111}
4112
4113// True when a project Save would write the descriptor bytes already on disk,
4114// apart from its timestamp and the recent-files list, which are not build
4115// inputs.
4117 if (current_project_.filepath.empty() ||
4119 return false;
4120 }
4123 ApplyProjectSaveSettings(&candidate, /*include_recent_files=*/false);
4124 candidate.NormalizePathsToAbsolute();
4125 const auto serialized = candidate.SerializeToString();
4126 std::ifstream input(current_project_.filepath, std::ios::binary);
4127 if (!serialized.ok() || !input.is_open()) {
4128 return false;
4129 }
4130 const std::string on_disk((std::istreambuf_iterator<char>(input)),
4131 std::istreambuf_iterator<char>());
4132 return !input.bad() && on_disk == *serialized;
4133}
4134
4144
4147 project_management_panel_->SetProjectDirty(true);
4148 }
4150 if (auto* session = session_coordinator_->GetActiveRomSession()) {
4151 session->project_dirty = true;
4152 }
4153 }
4154}
4155
4157 if (!session_coordinator_) {
4159 project_management_panel_->IsProjectDirty();
4160 }
4161 const auto* session = session_coordinator_->GetActiveRomSession();
4162 return session != nullptr &&
4163 (session->project_dirty ||
4164 session->editors.HasPendingProjectDraftChanges());
4165}
4166
4167absl::Status EditorManager::SaveActiveProjectEditingWork(bool allow_dialogs) {
4168 if (!session_coordinator_) {
4169 return absl::FailedPreconditionError("No session coordinator");
4170 }
4171 auto* session = session_coordinator_->GetActiveRomSession();
4172 if (!session) {
4173 return absl::FailedPreconditionError("No active ROM session");
4174 }
4175
4176 if (auto* graphics = static_cast<GraphicsEditor*>(
4177 session->editors.GetExistingEditor(EditorType::kGraphics))) {
4178 RETURN_IF_ERROR(graphics->SaveScratchAssets());
4179 }
4180
4181 if (session->editors.HasPendingSpriteChanges()) {
4182 auto* sprite = static_cast<SpriteEditor*>(
4183 session->editors.GetExistingEditor(EditorType::kSprite));
4184 RETURN_IF_ERROR(allow_dialogs ? sprite->Save() : sprite->SaveForAutosave());
4185 }
4186
4188 const bool project_dirty = session->project_dirty ||
4189 session->editors.HasPendingProjectDraftChanges();
4190 const bool project_file_dirty =
4191 session->project_file_editor_state.initialized &&
4192 session->project_file_editor_state.modified;
4193
4194 if (project_dirty && project_file_dirty &&
4196 return absl::FailedPreconditionError(
4197 "Project settings and raw project file both have unsaved changes; "
4198 "use raw Save As to preserve the draft, then save project settings");
4199 }
4200
4201 if (project_dirty) {
4203 current_project_.filepath.empty()) {
4204 return absl::FailedPreconditionError(
4205 "Project settings have no project file to save");
4206 }
4208 }
4209
4210 if (project_file_dirty) {
4211 if (project_file_editor_.filepath().empty()) {
4212 return absl::FailedPreconditionError(
4213 "Project file draft has no destination; use Save As first");
4214 }
4216 session->project_file_editor_state = project_file_editor_.CaptureState();
4217 }
4218
4219 return absl::OkStatus();
4220}
4221
4223 if (!session_coordinator_) {
4224 return absl::FailedPreconditionError("No session coordinator");
4225 }
4226 const size_t session_index = GetCurrentSessionIndex();
4227 RETURN_IF_ERROR(SaveProjectWorkBeforeRomSave(/*allow_dialogs=*/false));
4228 const auto* session = session_coordinator_->GetActiveRomSession();
4229 if (session != nullptr && session->backup_restore_pending) {
4230 return absl::CancelledError(
4231 "Staged backup restore requires an explicit Save ROM");
4232 }
4233 if (SessionHasPendingRomWork(session_index)) {
4235 } else {
4237 }
4238 if (SessionHasPendingUnsavedWork(session_index)) {
4239 return absl::FailedPreconditionError(
4240 "Autosave left unsaved project or ROM work");
4241 }
4242 return absl::OkStatus();
4243}
4244
4246 PotItemSaveDecision decision) {
4247 // Map EditorManager enum to RomLifecycleManager enum
4248 auto lifecycle_decision =
4250 static_cast<int>(decision));
4252
4253 if (decision == PotItemSaveDecision::kCancel) {
4255 toast_manager_.Show("Save cancelled", ToastType::kInfo);
4256 return;
4257 }
4258
4259 auto status = ResumePendingRomSave();
4260 if (!absl::IsCancelled(status) && !status.ok()) {
4262 absl::StrFormat("Failed to save ROM: %s", status.message()),
4264 }
4265}
4266
4268 // Get current project name for default filename
4269 std::string default_name = current_project_.project_opened()
4271 : "untitled_project";
4272
4273 auto file_path =
4274 util::FileDialogWrapper::ShowSaveFileDialog(default_name, "yaze");
4275 if (file_path.empty()) {
4276 return absl::OkStatus();
4277 }
4278
4279 return SaveProjectAs(file_path);
4280}
4281
4282absl::Status EditorManager::SaveProjectAs(const std::string& filepath) {
4283 if (filepath.empty()) {
4284 return absl::InvalidArgumentError("Project file path cannot be empty");
4285 }
4287 std::string file_path = filepath;
4288
4289 // Ensure a project extension.
4290 if (!(absl::EndsWith(file_path, ".yaze") ||
4291 absl::EndsWith(file_path, ".yazeproj"))) {
4292 file_path += ".yaze";
4293 }
4295 file_path)) {
4296 return SaveProject();
4297 }
4298 if (auto* editors = GetCurrentEditorSet();
4299 editors && editors->HasPendingPlanningProjectDraftChanges()) {
4300 return absl::FailedPreconditionError(
4301 "Save or discard plan edits before saving the project to another file");
4302 }
4303
4305 if (auto* session = session_coordinator_->GetActiveRomSession();
4306 session && session->project_file_editor_state.initialized &&
4307 session->project_file_editor_state.modified &&
4309 session->project_file_editor_state.filepath, file_path)) {
4310 return absl::FailedPreconditionError(
4311 "Raw project draft targets the selected file; preserve it with "
4312 "raw Save As before overwriting that destination");
4313 }
4314 }
4315
4316 OverworldEditor* lyra_editor = nullptr;
4321 lyra_editor = GetCurrentEditorSet()->GetEditorAs<OverworldEditor>(
4323 if (!lyra_editor || !lyra_editor->lyra_canvas_.loaded()) {
4324 return lyra_editor && !lyra_editor->lyra_canvas_status_.ok()
4325 ? lyra_editor->lyra_canvas_status_
4326 : absl::FailedPreconditionError(
4327 "Project Lyra terrain is unavailable");
4328 }
4329 }
4330 // Dungeon property drafts still join the saved descriptor. Lyra publishes
4331 // directly into its new owner instead of flushing into the original source.
4332 // Refuse the rebind before writing either owner if the previous native
4333 // transfer cannot be durably retired. A failed Save As leaves it retired.
4336 /*publish_lyra=*/lyra_editor == nullptr));
4338
4339 std::string old_filepath = current_project_.filepath;
4340 absl::Status save_status;
4341 if (lyra_editor) {
4342 save_status =
4343 lyra_editor->SaveProjectTerrainAs(&current_project_, file_path);
4344 } else {
4345 current_project_.filepath = file_path;
4346 save_status = current_project_.Save();
4347 }
4348 if (save_status.ok()) {
4349 if (auto* editors = GetCurrentEditorSet())
4350 editors->ProjectSaveCommitted();
4352 project_management_panel_->SetProjectDirty(false);
4353 }
4355 if (auto* session = session_coordinator_->GetActiveRomSession()) {
4356 session->project_dirty = false;
4357 }
4358 }
4360 RebaseCleanProjectFileDraft(file_path);
4361
4362 // Add to recent files
4364 manager.AddFile(file_path);
4365 manager.Save();
4366
4367 const auto catalog_path = core::PaletteCatalog::ResolvePathForProject(
4370 absl::IsInvalidArgument(catalog_path.status())) {
4372 absl::StrFormat(
4373 "Project saved as: %s. Its palette catalog cannot load from this "
4374 "folder. Copy the catalog into the new project folder, then "
4375 "update palette_catalog_file in Edit Project File.",
4376 file_path),
4378 } else {
4379 toast_manager_.Show(absl::StrFormat("Project saved as: %s", file_path),
4381 }
4382 } else {
4383 // Restore old filepath on failure
4384 current_project_.filepath = old_filepath;
4386 absl::StrFormat("Failed to save project: %s", save_status.message()),
4388 }
4389
4391
4392 if (!save_status.ok()) {
4393 return save_status;
4394 }
4395 const auto retirement = RetireNativeSaveTransfer("rebound");
4396 if (!retirement.ok()) {
4397 return absl::FailedPreconditionError(
4398 "Project saved as, but its retired native-save context could not be "
4399 "updated: " +
4400 std::string(retirement.message()));
4401 }
4402 // The new owner's receipt is part of Save As; a failed completion stays
4403 // pending so a Save without new edits retries it.
4404 if (auto* session = session_coordinator_
4405 ? session_coordinator_->GetActiveRomSession()
4406 : nullptr) {
4407 session->native_save_completion_pending = true;
4408 session->native_save_completion_save_as = true;
4409 }
4411}
4412
4413absl::StatusOr<std::string> EditorManager::ResolveProjectBuildCommand() {
4415 return absl::FailedPreconditionError("No project open");
4416 }
4419 return absl::PermissionDeniedError(
4420 "Build Project is disabled by the project's read-only policy");
4421 }
4422
4423 // A Build button can run during the panel's Draw() before the frame-end
4424 // project draft capture. Read the live panel and raw editor state now.
4426 if (auto* editors = GetCurrentEditorSet()) {
4427 const auto* dungeon =
4428 editors->GetEditorAs<DungeonEditorV2>(EditorType::kDungeon);
4429 if (dungeon && dungeon->HasUnpublishedMinecartTrackChanges()) {
4430 return absl::FailedPreconditionError(
4431 "Minecart tracks have unpublished changes. Use Publish Tracks, then "
4432 "save remaining project and ROM changes before Build Project. "
4433 "Undo the track edits if you do not want to publish them.");
4434 }
4435 }
4436 const size_t session_index = GetCurrentSessionIndex();
4437 if (SessionHasPendingUnsavedWork(session_index)) {
4438 return absl::FailedPreconditionError(
4439 absl::StrFormat("Save project and ROM changes before building: %s",
4440 DescribePendingUnsavedWork(session_index)));
4441 }
4442
4443 const Rom* active_rom = GetCurrentRom();
4444 if (active_rom != nullptr && active_rom->is_loaded() &&
4445 !current_project_.rom_filename.empty() &&
4447 active_rom->filename(),
4449 return absl::FailedPreconditionError(absl::StrFormat(
4450 "Build source mismatch: active ROM %s differs from project ROM %s. "
4451 "Use Project Management > Swap ROM to bind the saved copy, or reopen "
4452 "the project's ROM before building.",
4453 active_rom->filename(),
4455 }
4456
4457 std::string command = current_project_.build_script;
4458 if (command.empty() && current_project_.hack_manifest.loaded()) {
4459 const auto& pipeline = current_project_.hack_manifest.build_pipeline();
4460 if (!pipeline.dev_rom.empty() && !current_project_.rom_filename.empty() &&
4462 current_project_.GetAbsolutePath(pipeline.dev_rom),
4464 return absl::FailedPreconditionError(absl::StrFormat(
4465 "Build source mismatch: manifest development ROM %s differs from "
4466 "project ROM %s.",
4467 current_project_.GetAbsolutePath(pipeline.dev_rom),
4469 }
4470 command = pipeline.build_script;
4471 // Manifest build_script is normally a path. Do not parse arbitrary shell
4472 // commands here; only check a single, unquoted file-path token.
4473 if (!command.empty() &&
4474 command.find_first_of(" \t\r\n|&;<>()$`'\"\\") == std::string::npos) {
4475 const std::filesystem::path script_path(command);
4476 if (script_path.is_absolute() || script_path.has_parent_path() ||
4477 script_path.extension() == ".sh") {
4478 const std::string absolute_script =
4480 std::error_code ec;
4481 if (!std::filesystem::is_regular_file(absolute_script, ec)) {
4482 return absl::FailedPreconditionError(absl::StrFormat(
4483 "Manifest build script is unavailable: %s. Configure a build "
4484 "script for this project before building.",
4485 absolute_script));
4486 }
4487 }
4488 }
4489 }
4490 if (command.empty()) {
4491 return absl::NotFoundError("Project does not define a build command");
4492 }
4493 return command;
4494}
4495
4496absl::StatusOr<std::string> EditorManager::ResolveProjectRunTarget() const {
4498 return absl::FailedPreconditionError("No project open");
4499 }
4500
4501 ASSIGN_OR_RETURN(const auto expanded,
4504 if (expanded) {
4505 return *expanded;
4506 }
4507
4508 std::string target;
4511 }
4512 if (target.empty()) {
4514 }
4515 if (target.empty()) {
4516 return absl::NotFoundError("Project does not define a run target ROM");
4517 }
4518 return current_project_.GetAbsolutePath(target);
4519}
4520
4522 const std::string& summary, const std::string& detail,
4523 ProjectWorkflowState state, const std::string& output_tail,
4524 bool can_cancel) const {
4525 return {.visible = true,
4526 .can_cancel = can_cancel,
4527 .label = "Build",
4528 .summary = summary,
4529 .detail = detail,
4530 .output_tail = output_tail,
4531 .state = state};
4532}
4533
4535 const std::string& summary, const std::string& detail,
4536 ProjectWorkflowState state) const {
4537 return {.visible = true,
4538 .label = "Run",
4539 .summary = summary,
4540 .detail = detail,
4541 .state = state};
4542}
4543
4544absl::StatusOr<std::string> EditorManager::RunProjectBuildCommand() {
4545 auto command_or = ResolveProjectBuildCommand();
4546 if (!command_or.ok()) {
4547 return command_or.status();
4548 }
4549
4550 const std::string command = *command_or;
4551 const std::filesystem::path project_root =
4552 std::filesystem::path(current_project_.filepath).parent_path();
4554 auto environment,
4555 ProjectBuildEnvironment(current_project_, NativeSaveEditingSourcePath()));
4557 auto start_status = task.Start(command, project_root.string(), environment);
4558 if (!start_status.ok()) {
4559 return start_status;
4560 }
4561 auto wait_status = task.Wait();
4562 const auto snapshot = task.GetSnapshot();
4563 if (!wait_status.ok()) {
4564 return wait_status;
4565 }
4566 const std::string summary = LastNonEmptyLine(snapshot.output);
4567 return summary.empty() ? command : summary;
4568}
4569
4571 const std::string running_detail =
4572 "Running the configured project build command";
4573 UpdateBuildWorkflowStatus(
4575 MakeBuildStatus("Build running", running_detail,
4576 ProjectWorkflowState::kRunning, "", false));
4577
4578 auto result_or = RunProjectBuildCommand();
4579 if (!result_or.ok()) {
4580 const bool unavailable =
4581 result_or.status().code() == absl::StatusCode::kFailedPrecondition ||
4582 result_or.status().code() == absl::StatusCode::kNotFound;
4583 UpdateBuildWorkflowStatus(
4585 MakeBuildStatus(unavailable ? "Build unavailable" : "Build failed",
4586 std::string(result_or.status().message()),
4589 absl::StrFormat("%s: %s",
4590 unavailable ? "Build unavailable" : "Build failed",
4591 result_or.status().message()),
4593 return result_or.status();
4594 }
4595
4596 const std::string summary = *result_or;
4597 UpdateBuildWorkflowStatus(&status_bar_, project_management_panel_.get(),
4598 MakeBuildStatus("Build succeeded", summary,
4601 summary.empty() ? "Project build completed"
4602 : absl::StrFormat("Project build completed: %s", summary),
4604 LOG_INFO("EditorManager", "Project build completed: %s", summary.c_str());
4605 return absl::OkStatus();
4606}
4607
4610 const auto snapshot = active_project_build_->GetSnapshot();
4611 if (snapshot.running) {
4612 toast_manager_.Show("A project build is already running",
4614 return;
4615 }
4616 }
4617
4618 auto command_or = ResolveProjectBuildCommand();
4619 if (!command_or.ok()) {
4620 UpdateBuildWorkflowStatus(
4622 MakeBuildStatus("Build unavailable",
4623 std::string(command_or.status().message()),
4626 absl::StrFormat("Build unavailable: %s", command_or.status().message()),
4628 return;
4629 }
4630
4631 const std::filesystem::path project_root =
4632 std::filesystem::path(current_project_.filepath).parent_path();
4633 auto environment =
4634 ProjectBuildEnvironment(current_project_, NativeSaveEditingSourcePath());
4635 active_project_build_ = std::make_unique<BackgroundCommandTask>();
4636 auto start_status =
4637 environment.ok() ? active_project_build_->Start(
4638 *command_or, project_root.string(), *environment)
4639 : environment.status();
4640 if (!start_status.ok()) {
4641 UpdateBuildWorkflowStatus(
4643 MakeBuildStatus("Build unavailable",
4644 std::string(start_status.message()),
4647 absl::StrFormat("Build unavailable: %s", start_status.message()),
4649 active_project_build_.reset();
4650 return;
4651 }
4652
4654 UpdateBuildWorkflowStatus(
4656 MakeBuildStatus("Build running",
4657 "Running the configured project build command",
4660 project_management_panel_->SetBuildLogOutput("");
4661 }
4663}
4664
4666 if (!active_project_build_) {
4667 return;
4668 }
4669
4670 const auto snapshot = active_project_build_->GetSnapshot();
4671 if (!snapshot.running) {
4672 return;
4673 }
4674
4675 active_project_build_->Cancel();
4676 UpdateBuildWorkflowStatus(
4678 MakeBuildStatus("Cancelling build", "Stopping the active project build",
4679 ProjectWorkflowState::kRunning, snapshot.output_tail,
4680 false));
4681}
4682
4684 UpdateRunWorkflowStatus(
4686 MakeRunStatus("Run queued",
4687 "Preparing the project output for emulator reload",
4689
4690 auto run_target_or = ResolveProjectRunTarget();
4691 if (!run_target_or.ok()) {
4692 UpdateRunWorkflowStatus(
4694 MakeRunStatus("Run unavailable",
4695 std::string(run_target_or.status().message()),
4697 toast_manager_.Show(absl::StrFormat("Run unavailable: %s",
4698 run_target_or.status().message()),
4700 return run_target_or.status();
4701 }
4702 const std::string run_target = *run_target_or;
4703 if (!std::filesystem::exists(run_target)) {
4704 UpdateRunWorkflowStatus(&status_bar_, project_management_panel_.get(),
4705 MakeRunStatus("Run target missing", run_target,
4707 toast_manager_.Show("Run target ROM not found. Build the project first.",
4709 return absl::NotFoundError("Run target ROM not found");
4710 }
4711
4712#ifdef YAZE_WITH_GRPC
4713 if (auto* emulator_backend = Application::Instance().GetEmulatorBackend()) {
4714 auto load_status = emulator_backend->LoadRom(run_target);
4715 if (load_status.ok()) {
4716 AppendWorkflowHistoryEntry(
4717 "Run",
4718 MakeRunStatus("Reloaded in backend", run_target,
4720 "");
4721 UpdateRunWorkflowStatus(&status_bar_, project_management_panel_.get(),
4722 MakeRunStatus("Reloaded in backend", run_target,
4724 if (ui_coordinator_) {
4725 ui_coordinator_->SetEmulatorVisible(true);
4726 }
4728 absl::StrFormat("Reloaded project output in emulator backend: %s",
4729 run_target),
4731 return absl::OkStatus();
4732 }
4733 }
4734#endif
4735
4736 Rom temp_rom;
4737 auto load_rom_status = rom_file_manager_.LoadRom(&temp_rom, run_target);
4738 if (!load_rom_status.ok()) {
4739 UpdateRunWorkflowStatus(
4741 MakeRunStatus("Run load failed", std::string(load_rom_status.message()),
4743 toast_manager_.Show(absl::StrFormat("Failed to load run target ROM: %s",
4744 load_rom_status.message()),
4746 return load_rom_status;
4747 }
4748
4749 auto reload_status = emulator_.ReloadRuntimeRom(temp_rom.vector());
4750 if (!reload_status.ok()) {
4751 UpdateRunWorkflowStatus(
4753 MakeRunStatus("Reload failed", std::string(reload_status.message()),
4755 toast_manager_.Show(absl::StrFormat("Failed to reload emulator runtime: %s",
4756 reload_status.message()),
4758 return reload_status;
4759 }
4760
4761 if (ui_coordinator_) {
4762 ui_coordinator_->SetEmulatorVisible(true);
4763 }
4764 AppendWorkflowHistoryEntry("Run",
4765 MakeRunStatus("Reloaded in emulator", run_target,
4767 "");
4768 UpdateRunWorkflowStatus(&status_bar_, project_management_panel_.get(),
4769 MakeRunStatus("Reloaded in emulator", run_target,
4772 absl::StrFormat("Reloaded project output in emulator: %s", run_target),
4774 return absl::OkStatus();
4775}
4776
4777absl::Status EditorManager::ImportProject(const std::string& project_path) {
4778 // Delegate to ProjectManager for import logic
4780 // Sync local project reference
4784 if (auto* session = session_coordinator_->GetActiveRomSession()) {
4787 }
4788 }
4791 return absl::OkStatus();
4792}
4793
4796 return absl::FailedPreconditionError("No project is currently open");
4797 }
4798
4801 toast_manager_.Show("Project repaired successfully",
4803
4804 return absl::OkStatus();
4805}
4806
4808 if (auto* editor_set = GetCurrentEditorSet()) {
4809 return editor_set->GetOverworldData();
4810 }
4811 return nullptr;
4812}
4813
4815 if (!rom) {
4816 return absl::InvalidArgumentError("Invalid ROM pointer");
4817 }
4818
4819 // We need to find the session that owns this ROM.
4820 // This is inefficient but SetCurrentRom is rare.
4822 for (size_t i = 0; i < session_coordinator_->GetTotalSessionCount(); ++i) {
4823 auto* session =
4824 static_cast<RomSession*>(session_coordinator_->GetSession(i));
4825 if (session && &session->rom == rom) {
4826 session_coordinator_->SwitchToSession(i);
4827 if (GetCurrentRom() != rom) {
4828 return absl::FailedPreconditionError(
4829 "The requested ROM session could not be activated");
4830 }
4831 // Update test manager with current ROM for ROM-dependent tests
4835 return absl::OkStatus();
4836 }
4837 }
4838 }
4839 // If ROM wasn't found in existing sessions, treat as new session.
4840 // Copying an external ROM object is avoided; instead, fail.
4841 return absl::NotFoundError("ROM not found in existing sessions");
4842}
4843
4848
4849void EditorManager::CaptureCurrentRomIdentity(bool preserve_editing_source) {
4851 if (auto* session = session_coordinator_->GetActiveRomSession()) {
4852 session->CaptureRomIdentity(preserve_editing_source);
4853 }
4854 }
4856}
4857
4863
4864// IsRomHashMismatch() is now inline in editor_manager.h delegating to
4865// rom_lifecycle_.
4866
4867std::vector<RomFileManager::BackupEntry> EditorManager::GetRomBackups() const {
4869}
4870
4872 if (!session_coordinator_) {
4873 return false;
4874 }
4875 const auto* session = session_coordinator_->GetActiveRomSession();
4876 return session != nullptr && session->backup_restore_pending;
4877}
4878
4879absl::Status EditorManager::RestoreRomBackup(const std::string& backup_path) {
4880 auto* rom = GetCurrentRom();
4881 if (!rom) {
4882 return absl::FailedPreconditionError("No ROM loaded");
4883 }
4885 return absl::FailedPreconditionError(
4886 "Save or discard ROM edits before restoring a backup");
4887 }
4888
4889 const std::string original_filename = rom->filename();
4890 const project::ResourceLabelManager original_resource_labels =
4891 *rom->resource_label();
4892 const auto backups = rom_file_manager_.ListBackups(original_filename);
4893 const bool is_managed_backup =
4894 std::any_of(backups.begin(), backups.end(), [&](const auto& backup) {
4895 return SessionCoordinator::PathsReferToSameBackingFile(backup.path,
4896 backup_path);
4897 });
4898 if (!is_managed_backup) {
4899 return absl::InvalidArgumentError(
4900 "Selected file is not a managed backup for the active ROM");
4901 }
4902
4903 // Load the backup away from the live session. Backups may legitimately have
4904 // a different size when they predate a ROM expansion or shrink. Reusing the
4905 // ROM-replacement path restores the prior ROM bytes and backing identity if
4906 // rebuilding assets fails partway through.
4907 Rom restored_rom;
4908 RETURN_IF_ERROR(rom_file_manager_.LoadRom(&restored_rom, backup_path));
4909
4910 if (!original_filename.empty()) {
4911 restored_rom.set_filename(original_filename);
4912 }
4914 // Normal ROM backups do not copy the active `.labels` sidecar. Preserve the
4915 // session's loaded and in-memory resource labels instead of replacing them
4916 // with the usually-empty `<backup>.labels` lookup from LoadFromFile().
4917 *restored_rom.resource_label() = original_resource_labels;
4918 // Restore is intentionally staged in memory. Mark it dirty so closing or
4919 // autosave cannot silently treat the on-disk source as already restored.
4920 restored_rom.set_dirty(true);
4922 ReplaceActiveSessionRom(std::move(restored_rom), original_filename));
4923 auto* restored_session = session_coordinator_->GetActiveRomSession();
4924 if (!restored_session) {
4925 return absl::InternalError(
4926 "ROM backup restored without an active session to stage it");
4927 }
4928 restored_session->backup_restore_pending = true;
4929 return absl::OkStatus();
4930}
4931
4933 if (!session_coordinator_) {
4934 return absl::FailedPreconditionError("No session coordinator");
4935 }
4936 auto* session = session_coordinator_->GetActiveRomSession();
4937 if (!session || !session->rom.is_loaded()) {
4938 return absl::FailedPreconditionError("No ROM loaded");
4939 }
4940 if (!session->backup_restore_pending) {
4941 return absl::FailedPreconditionError("No restored backup is staged");
4942 }
4943
4944 const size_t session_index = GetCurrentSessionIndex();
4945 if (session->editors.HasPendingSpriteChanges() ||
4946 session->editors.HasPendingGraphicsChanges() ||
4947 session->HasPendingGfxGroupChanges() ||
4948 session->editors.HasPendingScreenChanges() ||
4949 HasPendingDungeonChangesForSession(session_index) ||
4950 gfx::PaletteManager::Get().HasUnsavedChanges(&session->game_data)) {
4951 return absl::FailedPreconditionError(
4952 "Resolve pending graphics, screen, dungeon, or palette edits before "
4953 "discarding the restored backup");
4954 }
4955
4956 const std::string backing_path = session->rom.filename();
4957 if (backing_path.empty()) {
4958 return absl::FailedPreconditionError("ROM has no backing file to reload");
4959 }
4960
4961 // Load into scratch storage before touching the live session so file I/O
4962 // failures preserve the staged ROM. Resource labels are session work, not
4963 // part of normal ROM backups, so preserve them across the byte-level discard.
4964 const project::ResourceLabelManager resource_labels =
4965 *session->rom.resource_label();
4966 Rom backing_rom;
4967 RETURN_IF_ERROR(rom_file_manager_.LoadRom(&backing_rom, backing_path));
4968 *backing_rom.resource_label() = resource_labels;
4970 ReplaceActiveSessionRom(std::move(backing_rom), backing_path));
4971
4972 session->backup_restore_pending = false;
4973 session->rom.ClearDirty();
4974 return absl::OkStatus();
4975}
4976
4980
4988
4992
4996
4999 session_coordinator_->CreateNewSession();
5000 // Toast messages are now shown by SessionCoordinator
5001 }
5002}
5003
5006 session_coordinator_->DuplicateCurrentSession();
5007 }
5008}
5009
5011 if (!session_coordinator_) {
5012 return;
5013 }
5014
5015 if (!session_coordinator_->HasMultipleSessions()) {
5016 // Preserve the coordinator's existing warning without offering a
5017 // "Close Without Saving" action that cannot close the final session.
5018 session_coordinator_->CloseCurrentSession();
5019 return;
5020 }
5021
5022 const size_t current_session_id = GetCurrentSessionId();
5025 current_session_id})) {
5026 return;
5027 }
5028
5029 session_coordinator_->CloseCurrentSession();
5031}
5032
5034 if (!CanCloseRom()) {
5035 return;
5036 }
5037 const size_t session_id = GetCurrentSessionId();
5040 session_id})) {
5041 return;
5042 }
5044 {PendingUnsavedSessionAction::Type::kCloseRom, session_id, session_id});
5045}
5046
5048 return session_coordinator_ != nullptr &&
5049 session_coordinator_->GetActiveRomSession() != nullptr;
5050}
5051
5053 if (!session_coordinator_) {
5054 return false;
5055 }
5056 const auto* session = session_coordinator_->GetActiveRomSession();
5057 return session != nullptr && session->rom.is_loaded() &&
5058 !session->rom.filename().empty();
5059}
5060
5062 if (!CanRevertRom()) {
5063 return absl::FailedPreconditionError("No ROM with a backing file is open");
5064 }
5065 const size_t session_id = GetCurrentSessionId();
5068 session_id})) {
5069 return absl::OkStatus(); // Confirmation popup is now showing.
5070 }
5072 toast_manager_.Show("Reverted ROM to the saved file", ToastType::kSuccess);
5073 return absl::OkStatus();
5074}
5075
5077 if (!CanRevertRom()) {
5078 return absl::FailedPreconditionError("No ROM with a backing file is open");
5079 }
5080 auto* session = session_coordinator_->GetActiveRomSession();
5081 // Graphics sheet drafts are held by the Graphics editor and are not rebuilt
5082 // by ReplaceActiveSessionRom. Refuse instead of leaving them stale.
5083 if (session->editors.HasPendingGraphicsChanges()) {
5084 return absl::FailedPreconditionError(
5085 "The Graphics editor has unsaved sheet edits; save or undo them "
5086 "before reverting");
5087 }
5088
5089 const std::string backing_path = session->rom.filename();
5090 // Load into scratch storage first so a read failure leaves the live
5091 // session untouched. Resource labels are session work stored beside the
5092 // ROM, not ROM bytes, so keep the in-memory labels (as
5093 // DiscardPendingRomBackupRestore does).
5094 const project::ResourceLabelManager resource_labels =
5095 *session->rom.resource_label();
5096 Rom backing_rom;
5097 RETURN_IF_ERROR(rom_file_manager_.LoadRom(&backing_rom, backing_path));
5098 *backing_rom.resource_label() = resource_labels;
5100 ReplaceActiveSessionRom(std::move(backing_rom), backing_path));
5101
5102 // ReplaceActiveSessionRom may re-resolve the session pointer's contents but
5103 // not its identity; re-read it defensively.
5104 session = session_coordinator_->GetActiveRomSession();
5105 if (session != nullptr) {
5106 session->backup_restore_pending = false;
5107 session->rom.ClearDirty();
5109 return absl::DataLossError(absl::StrFormat(
5110 "ROM reloaded from disk, but the session still reports %s",
5112 }
5113 }
5114 return absl::OkStatus();
5115}
5116
5118 if (!session_coordinator_ ||
5119 !session_coordinator_->IsValidSessionIndex(index)) {
5120 return;
5121 }
5122
5123 const size_t session_id = session_coordinator_->GetSessionId(index);
5126 session_id})) {
5127 return;
5128 }
5129
5130 session_coordinator_->RemoveSession(index);
5132}
5133
5137 return;
5138 }
5139
5140 quit_ = true;
5141}
5142
5146
5148 size_t session_id) const {
5149 if (!session_coordinator_ || session_id == SIZE_MAX) {
5150 return std::nullopt;
5151 }
5152
5153 for (size_t index = 0; index < session_coordinator_->GetTotalSessionCount();
5154 ++index) {
5155 if (session_coordinator_->GetSessionId(index) == session_id) {
5156 return index;
5157 }
5158 }
5159 return std::nullopt;
5160}
5161
5164 return "";
5165 }
5166
5167 const auto& action = *pending_unsaved_session_action_;
5168 if (action.type == PendingUnsavedSessionAction::Type::kQuit) {
5169 return absl::StrFormat("%s\n\nQuitting now will discard them.",
5171 }
5172
5173 const auto source_index = ResolveSessionIndexById(action.source_session_id);
5174 const std::string session_name =
5175 source_index.has_value()
5176 ? session_coordinator_->GetSessionDisplayName(*source_index)
5177 : "Closed Session";
5178 const std::string work = source_index.has_value()
5179 ? DescribePendingUnsavedWork(*source_index)
5180 : "unsaved work";
5181
5182 switch (action.type) {
5185 return absl::StrFormat(
5186 "Session '%s' has %s. Opening another ROM or project will not save "
5187 "them automatically.",
5188 session_name, work);
5190 return absl::StrFormat(
5191 "Session '%s' has %s. Opening another project will not save them "
5192 "automatically.",
5193 session_name, work);
5195 return absl::StrFormat(
5196 "Session '%s' has %s. Switching sessions will leave them behind in "
5197 "this session.",
5198 session_name, work);
5200 return absl::StrFormat(
5201 "Session '%s' has %s. Closing it now will discard them.",
5202 session_name, work);
5204 return absl::StrFormat(
5205 "Session '%s' has %s. Closing the ROM now will discard them.",
5206 session_name, work);
5208 return absl::StrFormat(
5209 "Session '%s' has %s. Reverting reloads the ROM from disk and "
5210 "discards all unsaved ROM edits. This cannot be undone.",
5211 session_name, work);
5213 break;
5214 }
5215
5216 return "";
5217}
5218
5221 return "Save Work";
5222 }
5223
5224 switch (pending_unsaved_session_action_->type) {
5227 return "Save Work & Open";
5229 return "Save Work & Open Project";
5231 return "Save Work & Switch";
5233 return "Save Work & Close";
5235 return "Save Work & Close ROM";
5237 // Saving and then reloading from disk is a no-op; the popup hides the
5238 // save button when this label is empty.
5239 return "";
5241 return ModifiedSessionCount() == 1 ? "Save Work & Quit"
5242 : "Save Modified Work & Quit";
5243 }
5244
5245 return "Save Work";
5246}
5247
5250 return "Continue";
5251 }
5252
5253 switch (pending_unsaved_session_action_->type) {
5256 return "Open Without Saving";
5258 return "Open Project Without Saving";
5260 return "Switch Without Saving";
5263 return "Close Without Saving";
5265 return "Discard Edits & Revert";
5267 return "Quit Without Saving";
5268 }
5269
5270 return "Continue";
5271}
5272
5275 return;
5276 }
5277
5278 const auto action = *pending_unsaved_session_action_;
5280
5281 if (popup_manager_) {
5283 }
5284
5285 const size_t original_session_id = GetCurrentSessionId();
5286 auto save_modified_session = [this](size_t session_id) -> absl::Status {
5287 const auto session_index = ResolveSessionIndexById(session_id);
5288 if (!session_index.has_value()) {
5289 return absl::FailedPreconditionError(
5290 "The ROM session is no longer available");
5291 }
5292 if (!SessionHasPendingUnsavedWork(*session_index)) {
5293 return absl::OkStatus();
5294 }
5295
5296 session_coordinator_->SwitchToSession(*session_index);
5297 if (GetCurrentSessionId() != session_id) {
5298 return absl::FailedPreconditionError(
5299 "The requested ROM session could not be activated before saving");
5300 }
5302 if (SessionHasPendingRomWork(*session_index)) {
5304 }
5305
5306 // A successful file write does not necessarily mean every pending editor
5307 // domain participated in the save. For example, dungeon palette saving is
5308 // user-configurable. Never execute a destructive follow-up while work that
5309 // the confirmation dialog promised to save is still pending.
5310 if (SessionHasPendingUnsavedWork(*session_index)) {
5311 return absl::FailedPreconditionError(
5312 absl::StrFormat("Save completed, but session still has %s",
5313 DescribePendingUnsavedWork(*session_index)));
5314 }
5315 return absl::OkStatus();
5316 };
5317
5318 absl::Status save_status = absl::OkStatus();
5319 if (action.type == PendingUnsavedSessionAction::Type::kQuit) {
5321 std::vector<size_t> session_ids;
5322 session_ids.reserve(session_coordinator_->GetTotalSessionCount());
5323 for (size_t i = 0; i < session_coordinator_->GetTotalSessionCount();
5324 ++i) {
5325 session_ids.push_back(session_coordinator_->GetSessionId(i));
5326 }
5327 for (const size_t session_id : session_ids) {
5328 save_status = save_modified_session(session_id);
5329 if (!save_status.ok()) {
5330 break;
5331 }
5332 }
5333 }
5334 } else {
5335 save_status = save_modified_session(action.source_session_id);
5336 }
5337
5338 if (!save_status.ok()) {
5339 const bool resumable_confirmation = absl::IsCancelled(save_status) &&
5342 const auto original_session_index =
5343 ResolveSessionIndexById(original_session_id);
5344 if (!resumable_confirmation && original_session_index.has_value()) {
5345 session_coordinator_->SwitchToSession(*original_session_index);
5346 }
5347
5348 if (absl::IsCancelled(save_status)) {
5349 toast_manager_.Show("Save paused. Finish saving, then retry your action.",
5351 } else {
5353 absl::StrFormat("Failed to save before continuing: %s",
5354 save_status.message()),
5356 }
5357 return;
5358 }
5359
5360 // Saving an inactive close target temporarily activates that session. Put
5361 // the original session back before compacting the target index so the same
5362 // stable session remains active after the close.
5364 original_session_id != action.target_session_id) {
5365 const auto original_session_index =
5366 ResolveSessionIndexById(original_session_id);
5367 if (original_session_index.has_value()) {
5368 session_coordinator_->SwitchToSession(*original_session_index);
5369 if (GetCurrentSessionId() != original_session_id) {
5371 "Session saved, but the original ROM session could not be "
5372 "restored. Close was cancelled.",
5374 return;
5375 }
5376 }
5377 }
5378
5380}
5381
5394
5401
5405 const auto source_index = ResolveSessionIndexById(action.source_session_id);
5406 bool has_pending_work = false;
5408 has_pending_work = HasAnySessionPendingUnsavedWork();
5410 // Revert only discards ROM-side work; project drafts survive it.
5411 has_pending_work =
5412 source_index.has_value() && SessionHasPendingRomWork(*source_index);
5413 } else {
5414 has_pending_work =
5415 source_index.has_value() && SessionHasPendingUnsavedWork(*source_index);
5416 }
5417 if (!has_pending_work) {
5418 return true;
5419 }
5420
5421 pending_unsaved_session_action_ = std::move(action);
5422 if (popup_manager_) {
5424 }
5425 return false;
5426}
5427
5429 const PendingUnsavedSessionAction& action) {
5430 switch (action.type) {
5432 auto status = LoadRomInternal();
5433 if (!status.ok()) {
5435 absl::StrFormat("Failed to load ROM: %s", status.message()),
5437 }
5438 break;
5439 }
5441 auto status = OpenRomOrProjectInternal(
5442 action.path, /*allow_dialogs=*/true, action.load_options_prompt);
5443 if (!status.ok()) {
5444 toast_manager_.Show(absl::StrFormat("Failed to open ROM / project: %s",
5445 status.message()),
5447 }
5448 break;
5449 }
5451 auto status = OpenProjectInternal();
5452 if (!status.ok()) {
5454 absl::StrFormat("Failed to open project: %s", status.message()),
5456 }
5457 break;
5458 }
5461 const auto target_index =
5463 if (target_index.has_value()) {
5464 session_coordinator_->SwitchToSession(*target_index);
5465 }
5466 }
5467 break;
5470 const auto target_index =
5472 if (target_index.has_value()) {
5473 session_coordinator_->RemoveSession(*target_index);
5475 }
5476 }
5477 break;
5480 const auto target_index =
5482 if (target_index.has_value()) {
5483 session_coordinator_->CloseSessionAllowingEmpty(*target_index);
5485 }
5486 }
5487 break;
5489 const auto target_index =
5491 if (!target_index.has_value()) {
5492 break;
5493 }
5495 *target_index != session_coordinator_->GetActiveSessionIndex()) {
5496 session_coordinator_->SwitchToSession(*target_index);
5497 }
5498 if (GetCurrentSessionId() != action.target_session_id) {
5500 "Revert cancelled: the requested ROM session could not be "
5501 "activated",
5503 break;
5504 }
5505 auto status = RevertRomToSavedInternal();
5506 if (status.ok()) {
5507 toast_manager_.Show("Reverted ROM to the saved file",
5509 } else {
5511 absl::StrFormat("Revert failed: %s", status.message()),
5512 ToastType::kError, 6.0f);
5513 }
5514 break;
5515 }
5517 quit_ = true;
5518 break;
5519 }
5520}
5521
5522bool EditorManager::SessionHasPendingUnsavedWork(size_t session_index) const {
5523 if (!session_coordinator_ ||
5524 !session_coordinator_->IsValidSessionIndex(session_index)) {
5525 return false;
5526 }
5527
5528 auto* session =
5529 static_cast<RomSession*>(session_coordinator_->GetSession(session_index));
5530 return session != nullptr &&
5531 (SessionHasPendingRomWork(session_index) ||
5532 session->editors.HasPendingSpriteChanges() ||
5533 session->project_dirty ||
5534 session->editors.HasPendingProjectDraftChanges() ||
5535 (session->project_file_editor_state.initialized &&
5536 session->project_file_editor_state.modified));
5537}
5538
5539bool EditorManager::SessionHasPendingRomWork(size_t session_index) const {
5540 if (!session_coordinator_ ||
5541 !session_coordinator_->IsValidSessionIndex(session_index)) {
5542 return false;
5543 }
5544
5545 auto* session =
5546 static_cast<RomSession*>(session_coordinator_->GetSession(session_index));
5547 return session != nullptr &&
5548 ((session->rom.is_loaded() && session->rom.dirty()) ||
5549 session->editors.HasPendingGraphicsChanges() ||
5550 session->HasPendingGfxGroupChanges() ||
5551 session->editors.HasPendingScreenChanges() ||
5552 HasPendingDungeonChangesForSession(session_index) ||
5553 gfx::PaletteManager::Get().HasUnsavedChanges(&session->game_data));
5554}
5555
5559
5561 size_t session_index) const {
5562 if (!session_coordinator_ ||
5563 !session_coordinator_->IsValidSessionIndex(session_index)) {
5564 return false;
5565 }
5566
5567 auto* session =
5568 static_cast<RomSession*>(session_coordinator_->GetSession(session_index));
5569 if (!session) {
5570 return false;
5571 }
5572
5573 if (auto* dungeon_editor =
5574 session->editors.GetEditorAs<DungeonEditorV2>(EditorType::kDungeon)) {
5575 return dungeon_editor->HasPendingDungeonChanges();
5576 }
5577 return false;
5578}
5579
5581 size_t session_index) const {
5582 if (!session_coordinator_ ||
5583 !session_coordinator_->IsValidSessionIndex(session_index)) {
5584 return 0;
5585 }
5586
5587 auto* session =
5588 static_cast<RomSession*>(session_coordinator_->GetSession(session_index));
5589 if (!session) {
5590 return 0;
5591 }
5592
5593 if (auto* dungeon_editor =
5594 session->editors.GetEditorAs<DungeonEditorV2>(EditorType::kDungeon)) {
5595 return dungeon_editor->PendingRoomCount();
5596 }
5597 return 0;
5598}
5599
5601 size_t session_index) const {
5602 if (!session_coordinator_ ||
5603 !session_coordinator_->IsValidSessionIndex(session_index)) {
5604 return 0;
5605 }
5606
5607 auto* session =
5608 static_cast<RomSession*>(session_coordinator_->GetSession(session_index));
5609 return session != nullptr ? gfx::PaletteManager::Get().GetModifiedColorCount(
5610 &session->game_data)
5611 : 0;
5612}
5613
5615 if (!session_coordinator_) {
5616 return 0;
5617 }
5618
5619 int count = 0;
5620 for (size_t i = 0; i < session_coordinator_->GetTotalSessionCount(); ++i) {
5622 ++count;
5623 }
5624 }
5625 return count;
5626}
5627
5629 size_t session_index) const {
5630 if (!session_coordinator_ ||
5631 !session_coordinator_->IsValidSessionIndex(session_index)) {
5632 return "unsaved work";
5633 }
5634
5635 auto* session =
5636 static_cast<RomSession*>(session_coordinator_->GetSession(session_index));
5637 const bool rom_dirty =
5638 session != nullptr && session->rom.is_loaded() && session->rom.dirty();
5639 const bool pending_dungeon_changes =
5641 const bool pending_sprite_changes =
5642 session != nullptr && session->editors.HasPendingSpriteChanges();
5643 const bool pending_graphics_changes =
5644 session != nullptr && session->editors.HasPendingGraphicsChanges();
5645 const bool pending_gfx_group_changes =
5646 session != nullptr && session->HasPendingGfxGroupChanges();
5647 const bool pending_screen_changes =
5648 session != nullptr && session->editors.HasPendingScreenChanges();
5649 const int pending_rooms = PendingDungeonRoomCountForSession(session_index);
5650 const size_t pending_palette_colors =
5652 const bool project_dirty = session != nullptr && session->project_dirty;
5653 const bool project_editor_draft =
5654 session != nullptr && session->editors.HasPendingProjectDraftChanges();
5655 const bool project_file_dirty =
5656 session != nullptr && session->project_file_editor_state.initialized &&
5657 session->project_file_editor_state.modified;
5658
5659 std::vector<std::string> work;
5660 if (pending_rooms > 0) {
5661 work.push_back(absl::StrFormat("%d unapplied dungeon room%s", pending_rooms,
5662 pending_rooms == 1 ? "" : "s"));
5663 } else if (pending_dungeon_changes) {
5664 work.emplace_back("unapplied dungeon metadata");
5665 }
5666 if (pending_palette_colors > 0) {
5667 work.push_back(absl::StrFormat("%zu unapplied palette color%s",
5668 pending_palette_colors,
5669 pending_palette_colors == 1 ? "" : "s"));
5670 }
5671 if (pending_sprite_changes)
5672 work.emplace_back("unsaved sprite assets");
5673 if (pending_graphics_changes) {
5674 work.emplace_back("unapplied graphics sheet edits");
5675 }
5676 if (pending_gfx_group_changes) {
5677 work.emplace_back("unsaved blockset/spriteset (gfx group) edits");
5678 }
5679 if (pending_screen_changes) {
5680 work.emplace_back("unapplied Screen Editor edits");
5681 }
5682 if (rom_dirty) {
5683 work.emplace_back("unsaved ROM-buffer changes");
5684 }
5685 if (project_dirty) {
5686 work.emplace_back("unsaved project settings");
5687 }
5688 if (project_editor_draft) {
5689 work.emplace_back("an uncommitted project editor draft");
5690 }
5691 if (project_file_dirty) {
5692 work.emplace_back("an unsaved project-file draft");
5693 }
5694 return work.empty() ? "unsaved work" : absl::StrJoin(work, " and ");
5695}
5696
5698 size_t session_index) const {
5699 if (!session_coordinator_ ||
5700 !session_coordinator_->IsValidSessionIndex(session_index)) {
5701 return {};
5702 }
5703
5704 auto* session =
5705 static_cast<RomSession*>(session_coordinator_->GetSession(session_index));
5706 const bool rom_dirty =
5707 session != nullptr && session->rom.is_loaded() && session->rom.dirty();
5708 const bool pending_dungeon_changes =
5710 const bool pending_sprite_changes =
5711 session != nullptr && session->editors.HasPendingSpriteChanges();
5712 const bool pending_graphics_changes =
5713 session != nullptr && session->editors.HasPendingGraphicsChanges();
5714 const bool pending_gfx_group_changes =
5715 session != nullptr && session->HasPendingGfxGroupChanges();
5716 const bool pending_screen_changes =
5717 session != nullptr && session->editors.HasPendingScreenChanges();
5718 const int pending_rooms = PendingDungeonRoomCountForSession(session_index);
5719 const size_t pending_palette_colors =
5721 const bool project_dirty = session != nullptr && session->project_dirty;
5722 const bool project_editor_draft =
5723 session != nullptr && session->editors.HasPendingProjectDraftChanges();
5724 const bool project_file_dirty =
5725 session != nullptr && session->project_file_editor_state.initialized &&
5726 session->project_file_editor_state.modified;
5727
5728 std::vector<std::string> tags;
5729 if (pending_rooms > 0) {
5730 tags.push_back("Rooms");
5731 } else if (pending_dungeon_changes) {
5732 tags.push_back("Dungeon");
5733 }
5734 if (pending_palette_colors > 0) {
5735 tags.push_back("Palette");
5736 }
5737 if (pending_sprite_changes)
5738 tags.emplace_back("Sprites");
5739 if (pending_graphics_changes) {
5740 tags.push_back("Gfx");
5741 }
5742 if (pending_gfx_group_changes) {
5743 tags.push_back("GfxGroups");
5744 }
5745 if (pending_screen_changes) {
5746 tags.push_back("Screen");
5747 }
5748 if (rom_dirty) {
5749 tags.push_back("ROM");
5750 }
5751 if (project_dirty || project_editor_draft || project_file_dirty) {
5752 tags.push_back("Project");
5753 }
5754 return absl::StrJoin(tags, "+");
5755}
5756
5758 const int modified_sessions = ModifiedSessionCount();
5759 if (modified_sessions <= 0) {
5760 return "No sessions have unsaved work.";
5761 }
5762
5763 if (modified_sessions == 1 && session_coordinator_) {
5764 for (size_t i = 0; i < session_coordinator_->GetTotalSessionCount(); ++i) {
5766 return absl::StrFormat("Session '%s' has %s.",
5767 session_coordinator_->GetSessionDisplayName(i),
5769 }
5770 }
5771 }
5772
5773 return absl::StrFormat(
5774 "%d sessions have unsaved ROM, graphics, screen, dungeon, palette, or "
5775 "project work.",
5776 modified_sessions);
5777}
5778
5780 return session_coordinator_ ? session_coordinator_->GetActiveSessionIndex()
5781 : 0;
5782}
5783
5785 UiSyncState state;
5786 state.frame_id = ui_sync_frame_id_.load(std::memory_order_relaxed);
5787
5788 int pending_editor =
5789 pending_editor_deferred_actions_.load(std::memory_order_relaxed);
5790 if (pending_editor < 0) {
5791 pending_editor = 0;
5792 }
5793 state.pending_editor_actions = pending_editor;
5794
5795 int pending_layout = layout_coordinator_.PendingDeferredActionCount();
5796 if (pending_layout < 0) {
5797 pending_layout = 0;
5798 }
5799 state.pending_layout_actions = pending_layout;
5801 layout_manager_ ? layout_manager_->IsRebuildRequested() : false;
5802 return state;
5803}
5804
5806 return session_coordinator_ ? session_coordinator_->GetActiveSessionCount()
5807 : 0;
5808}
5809
5811 EditorType type, size_t session_index) const {
5812 const char* base_name = kEditorNames[static_cast<int>(type)];
5813 return session_coordinator_ ? session_coordinator_->GenerateUniqueEditorTitle(
5814 base_name, session_index)
5815 : std::string(base_name);
5816}
5817
5818void EditorManager::SwitchToEditor(EditorType editor_type, bool force_visible,
5819 bool from_dialog) {
5820#ifdef YAZE_BUILD_AGENT_UI
5821 // Agent has its own activation path, including the shared experimental
5822 // warning. Handle it first so one user action cannot emit the warning twice.
5823 if (editor_type == EditorType::kAgent) {
5824 ShowAIAgent();
5825 return;
5826 }
5827#endif
5828
5832 absl::StrFormat(
5833 "%s is experimental. It remains available; enable experimental "
5834 "features in Settings to acknowledge this warning.",
5835 kEditorNames[static_cast<int>(editor_type)]),
5837 }
5838
5839 // Fresh launch has no ROM session, so GetCurrentEditorSet() is null and
5840 // EditorActivator::SwitchToEditor would silently no-op (BUG-020) — that was
5841 // why File->Settings, the "no ROM" welcome buttons, and Tools editors did
5842 // nothing. Create an empty session on demand so ROM-less editors (Settings,
5843 // Assembly, ...) have an editor set to live in. Normal ROM loads create their
5844 // own session, so this only fires when the user reaches an editor first.
5845 if (session_coordinator_ && GetCurrentEditorSet() == nullptr) {
5846 session_coordinator_->CreateNewSession();
5847 }
5848
5849 auto status = EnsureEditorAssetsLoaded(editor_type);
5850 if (!status.ok()) {
5852 absl::StrFormat("Failed to prepare %s: %s",
5853 kEditorNames[static_cast<int>(editor_type)],
5854 status.message()),
5856 }
5857
5859 editor_type != EditorType::kGraphics) {
5860 static_cast<GraphicsEditor*>(current_editor_)->FinishPixelGesture();
5861 }
5862
5863 // Delegate all other editor switching to EditorActivator
5864 editor_activator_.SwitchToEditor(editor_type, force_visible, from_dialog);
5865
5866 switch (editor_type) {
5868 // Show at most one migration tip per editor transition. The next visit
5869 // naturally advances to the more specific Tile16 tip.
5872 }
5873 break;
5876 break;
5879 break;
5880 default:
5881 break;
5882 }
5883}
5884
5886 if (!ui_coordinator_) {
5887 return;
5888 }
5889 ui_coordinator_->SetEditorSelectionVisible(false);
5890 ui_coordinator_->SetStartupSurface(StartupSurface::kEditor);
5891}
5892
5893bool EditorManager::HasDuplicateSession(const std::string& filepath) {
5894 return session_coordinator_ &&
5895 session_coordinator_->HasDuplicateSession(filepath);
5896}
5897
5923 // Menu actions can run before the next Update() frame captures drawer
5924 // edits. Preserve the panel's current dirty bit before rebinding it.
5927 // Update project panel context before showing
5931 project_management_panel_->SetVersionManager(version_manager_);
5933 }
5934 right_drawer_manager_->ToggleDrawer(
5936 }
5937}
5938
5941 auto* session = session_coordinator_
5942 ? session_coordinator_->GetActiveRomSession()
5943 : nullptr;
5944
5945 // Preserve an existing draft for this session. Only load from disk the first
5946 // time this session opens the project-file editor.
5947 if (session && session->project_file_editor_state.initialized &&
5948 !session->project_file_editor_state.modified &&
5949 !current_project_.filepath.empty() &&
5951 session->project_file_editor_state.filepath,
5954 }
5955
5956 if (session && session->project_file_editor_state.initialized) {
5957 project_file_editor_.RestoreState(session->project_file_editor_state,
5959 } else if (!current_project_.filepath.empty()) {
5961 if (!status.ok()) {
5963 absl::StrFormat("Failed to load project file: %s", status.message()),
5965 return;
5966 }
5967 } else {
5969 }
5970 // Set the project pointer for label import functionality
5972 // Activate the editor window
5974 if (session) {
5975 session->project_file_editor_state = project_file_editor_.CaptureState();
5976 }
5977}
5978
5980 size_t session_id) {
5981 if (!editor_set) {
5982 return;
5983 }
5984
5985 EditorDependencies deps;
5986 deps.rom = rom;
5987 deps.session_id = session_id;
5990 deps.popup_manager = popup_manager_.get();
5995 const auto session_index = ResolveSessionIndexById(session_id);
5996 if (session_index.has_value()) {
5997 auto* session = static_cast<RomSession*>(
5998 session_coordinator_->GetSession(*session_index));
5999 if (session) {
6000 deps.game_data = &session->game_data;
6001 if (session->project_context.has_value()) {
6002 deps.project = &*session->project_context;
6003 deps.version_manager = session->version_manager.get();
6004 }
6005 }
6006 }
6007 }
6008 deps.global_context = editor_context_.get();
6009 deps.status_bar = &status_bar_;
6010 deps.renderer = renderer_;
6011 deps.emulator = &emulator_;
6012 deps.custom_data = this;
6013 deps.project_context_provider = [this,
6014 session_id]() -> project::YazeProject* {
6016 : nullptr;
6017 };
6018 deps.gfx_group_workspace = editor_set->gfx_group_workspace();
6019
6020 editor_set->ApplyDependencies(deps);
6021
6022 if (auto* overworld =
6024 overworld->SetProjectContextProvider(
6025 [this, session_id]() -> project::YazeProject* {
6026 return IsCurrentProjectContextOwnedBySession(session_id)
6028 : nullptr;
6029 });
6030 }
6031 if (auto* settings_panel = editor_set->GetSettingsPanel()) {
6032 // Settings edit the same active project that CaptureActiveProjectContext
6033 // persists. Editing the session snapshot directly loses changes when the
6034 // next capture replaces that snapshot with current_project_.
6035 settings_panel->SetProjectContextProvider(
6036 [this, session_id]() -> project::YazeProject* {
6037 return IsCurrentProjectContextOwnedBySession(session_id)
6039 : nullptr;
6040 },
6041 [this, session_id]() -> std::string {
6042 return IsCurrentProjectContextOwnedBySession(session_id)
6044 : std::string();
6045 });
6046 settings_panel->SetOpenMinecartTracksCallback(
6047 [this, session_id]() -> absl::Status {
6048 if (!IsCurrentProjectContextOwnedBySession(session_id)) {
6049 return absl::FailedPreconditionError(
6050 "Minecart Tracks requires its project session to be active.");
6051 }
6053 auto* dungeon = GetCurrentEditorSet()->GetEditorAs<DungeonEditorV2>(
6055 if (dungeon == nullptr) {
6056 return absl::NotFoundError(
6057 "Dungeon editor is unavailable in the active project "
6058 "session.");
6059 }
6060 RETURN_IF_ERROR(dungeon->EnsureMinecartTrackEditorPanel());
6061
6065 return absl::NotFoundError(
6066 "Minecart Tracks could not be opened in the active Dungeon "
6067 "editor.");
6068 }
6069 return absl::OkStatus();
6070 });
6071 }
6072
6073 // If configuring the active session, update the properties panel
6074 if (session_id == GetCurrentSessionId()) {
6076 }
6077}
6078
6079} // namespace yaze::editor
static Application & Instance()
void Publish(const T &event)
Definition event_bus.h:35
HandlerId Subscribe(std::function< void(const T &)> handler)
Definition event_bus.h:22
The Rom class is used to load, save, and modify Rom data. This is a generic SNES ROM container and do...
Definition rom.h:52
project::ResourceLabelManager * resource_label()
Definition rom.h:242
auto filename() const
Definition rom.h:219
void set_dirty(bool dirty)
Definition rom.h:201
const auto & vector() const
Definition rom.h:217
auto data() const
Definition rom.h:213
auto size() const
Definition rom.h:212
bool dirty() const
Definition rom.h:200
auto set_filename(std::string_view name)
Definition rom.h:220
bool is_loaded() const
Definition rom.h:199
auto title() const
Definition rom.h:211
static TimingManager & Get()
Definition timing.h:20
float GetElapsedTime() const
Get total elapsed time since first update.
Definition timing.h:70
static void Initialize(editor::EditorManager *)
static void Initialize(editor::EditorManager *)
static Flags & get()
Definition features.h:122
const ProjectRegistry & project_registry() const
bool HasProjectRegistry() const
bool loaded() const
Check if the manifest has been loaded.
const BuildPipeline & build_pipeline() const
static absl::StatusOr< std::filesystem::path > ResolvePathForProject(const std::string &project_file, const std::string &catalog_file)
Central coordinator for all agent UI components.
absl::Status Start(const std::string &command, const std::string &directory, const std::map< std::string, std::string > &environment={})
DungeonEditorV2 - Simplified dungeon editor using component delegation.
static constexpr const char * kMinecartTrackEditorId
void SwitchToEditor(EditorType type, bool force_visible=false, bool from_dialog=false)
Switch to an editor, optionally forcing visibility.
void Initialize(const Dependencies &deps)
void InitializeEditorLayout(EditorType type)
Initialize the DockBuilder layout for an editor.
void ApplyProjectSaveSettings(project::YazeProject *project, bool include_recent_files)
std::unique_ptr< SessionCoordinator > session_coordinator_
RomLifecycleManager rom_lifecycle_
StartupVisibility welcome_mode_override_
std::unique_ptr< AgentUiController > agent_ui_
void ConfirmPendingUnsavedSessionActionSaveAndContinue()
std::optional< PendingRomSave > pending_rom_save_
std::vector< EditorType > CollectEditorsToPreload(EditorSet *editor_set) const
void SwitchToEditor(EditorType editor_type, bool force_visible=false, bool from_dialog=false) override
std::unique_ptr< GlobalEditorContext > editor_context_
bool MaybeGuardPendingSessionAction(PendingUnsavedSessionAction action)
absl::Status SaveRomAs(const std::string &filename)
bool HasAnySessionPendingUnsavedWork() const
project::YazeProject current_project_
void HandleSessionSwitched(size_t new_index, RomSession *session, bool transient=false)
absl::Status CompletePendingProjectNativeSave()
absl::Status ValidateLyraTerrainProjectContext() const
std::unique_ptr< RightDrawerManager > right_drawer_manager_
void SetCurrentEditor(Editor *editor) override
bool SaveLayoutSnapshotAs(const std::string &name)
absl::Status PrepareRawProjectFileSave(const std::string &filepath, const std::string &contents)
absl::Status LoadAssetsForMode(uint64_t loading_handle=0)
std::string GetPreferredStartupCategory(const std::string &saved_category, const std::vector< std::string > &available_categories) const
absl::StatusOr< std::string > RunProjectBuildCommand()
absl::Status CheckRomWritePolicy(const std::optional< std::string > &target_filename=std::nullopt)
Save the current ROM file.
absl::Status RestoreRomBackup(const std::string &backup_path)
bool SessionHasPendingRomWork(size_t session_index) const
Rom * GetCurrentRom() const override
void CancelPendingRomSave(bool hide_popups=false)
int PendingDungeonRoomCountForSession(size_t session_index) const
bool HasDuplicateSession(const std::string &filepath)
std::unique_ptr< LayoutManager > layout_manager_
std::unique_ptr< DashboardPanel > dashboard_panel_
absl::Status RetireNativeSaveTransfer(const std::string &state, const std::string &editing_source_path="")
void ResetAssetState(RomSession *session)
void ProcessStartupActions(const AppConfig &config)
std::string GenerateUniqueEditorTitle(EditorType type, size_t session_index) const
core::VersionManager * version_manager_
std::vector< editor::RomFileManager::BackupEntry > GetRomBackups() const
std::string CompactPendingUnsavedWorkLabel(size_t session_index) const
std::vector< std::string > ListLayoutSnapshots() const
SharedClipboard shared_clipboard_
bool EditorInitRequiresGameData(EditorType type) const
void SyncEditorContextForCategory(const std::string &category)
void ShowProjectManagement()
Injects dependencies into all editors within an EditorSet.
Editor * ResolveEditorForCategory(const std::string &category)
void FinishRawRomOpen(bool remembered_load_options, bool ask_for_load_options, bool is_first_time_rom_path)
void Initialize(gfx::IRenderer *renderer, const std::string &filename="")
std::optional< size_t > runtime_feature_flags_session_id_
absl::Status FinalizeNewProject(const std::string &project_name, const std::string &project_path=std::string())
std::string DescribeAllPendingUnsavedWork() const
void MarkEditorLoaded(RomSession *session, EditorType type)
absl::Status StartPendingRomSave(const std::optional< std::string > &save_as_filename)
absl::Status CreateNewProjectFromRom(const std::string &template_name, const std::string &rom_path, const std::string &project_name, const std::string &project_path=std::string())
absl::Status CreateNewProject(const std::string &template_name="Basic ROM Hack")
absl::Status RecordCompletedNativeSave(const project::YazeProject &project, const std::string &saved_rom, bool save_as, bool rom_written=true)
void ConfirmPendingUnsavedSessionActionDiscardAndContinue()
absl::Status InitializeEditorForType(EditorType type, EditorSet *editor_set, Rom *rom)
LayoutCoordinator layout_coordinator_
absl::Status LoadAssets(uint64_t loading_handle=0)
std::string GetCurrentRomHash() const
FeatureHintManager feature_hint_manager_
bool HasPendingUnsavedSessionAction() const
void RestoreActiveEditorLayoutAfterAssets(RomSession *session)
auto GetCurrentEditorSet() const -> EditorSet *
std::string DescribePendingUnsavedWork(size_t session_index) const
absl::Status LoadProjectWithRom(bool allow_dialogs=true)
EditorContextSnapshot GetEditorContextSnapshot(const std::string &category)
void FinishPendingRomSaveAttempt(const absl::Status &status)
std::unique_ptr< MenuOrchestrator > menu_orchestrator_
void HandleUIActionRequest(UIActionRequestEvent::Action action)
void ResolvePotItemSaveConfirmation(PotItemSaveDecision decision)
absl::Status CommitRawProjectFileSave(const std::string &filepath, const std::string &contents)
auto GetCurrentEditor() const -> Editor *override
absl::Status OpenRomOrProject(const std::string &filename, LoadOptionsPrompt prompt=LoadOptionsPrompt::kAsk)
void HandleSessionRomLoaded(size_t index, Rom *rom)
ProjectFileEditor project_file_editor_
void ApplyLayoutPreset(const std::string &preset_name)
void RestoreTemporaryLayoutSnapshot(bool clear_after_restore=false)
void ApplyStartupVisibility(const AppConfig &config)
void ExecutePendingUnsavedSessionAction(const PendingUnsavedSessionAction &action)
WorkspaceWindowManager window_manager_
absl::Status SwapProjectRom(const std::string &rom_path, const std::optional< std::string > &expected_sha256=std::nullopt)
size_t PendingPaletteColorCountForSession(size_t session_index) const
absl::Status OpenLyraTerrainFromPath(const std::string &path)
void RestoreEditorLayoutAfterAssets(RomSession *session, EditorType type)
absl::Status SaveRomInternal(const std::optional< std::string > &save_as_filename)
void SetStartupLoadHints(const AppConfig &config)
void RebaseCleanProjectFileDraft(const std::string &filepath)
std::optional< size_t > pending_project_open_previous_session_id_
absl::Status LoadAssetsLazy(uint64_t loading_handle=0)
bool PendingRomSaveMatchesActiveSession() const
void SetAssetLoadMode(AssetLoadMode mode)
void DismissEditorSelection() override
absl::Status DiscardPendingRomBackupRestore()
std::atomic< uint64_t > ui_sync_frame_id_
std::optional< size_t > active_project_context_session_id_
std::string GetPendingUnsavedSessionActionContinueLabel() const
std::string GetPendingUnsavedSessionActionPrompt() const
bool ApplyLayoutProfile(const std::string &profile_id)
Editor * GetEditorByType(EditorType type, EditorSet *editor_set) const
StartupVisibility sidebar_mode_override_
absl::Status LoadRom()
Load a ROM file into a new or existing session.
std::vector< std::string > startup_panel_hints_
std::vector< std::function< void()> > deferred_actions_
bool ActivateExistingSessionForOpen(const std::string &filename)
void OpenEditorAndPanelsFromFlags(const std::string &editor_name, const std::string &panels_str)
StartupVisibility dashboard_mode_override_
void BindProjectContextToSession(RomSession *session, const project::YazeProject &project)
std::optional< size_t > ResolveSessionIndexById(size_t session_id) const
static bool IsPanelBasedEditor(EditorType type)
absl::Status OpenRomOrProjectInternal(const std::string &filename, bool allow_dialogs=true, LoadOptionsPrompt prompt=LoadOptionsPrompt::kAsk)
absl::StatusOr< std::string > ResolveProjectRunTarget() const
absl::Status ImportProject(const std::string &project_path)
size_t GetCurrentSessionId() const
Stable workspace identity; unlike the UI index, it does not compact.
std::string ExecuteEditorControl(const std::string &request)
bool ProjectFileDraftTargetsCurrentProject() const
absl::Status SaveProjectWorkBeforeRomSave(bool allow_dialogs)
ProjectWorkflowStatus MakeRunStatus(const std::string &summary, const std::string &detail, ProjectWorkflowState state) const
void QueueDeferredAction(std::function< void()> action)
absl::Status ValidateProjectRomSelection(const std::string &rom_path)
SelectionPropertiesPanel selection_properties_panel_
bool DeleteLayoutSnapshot(const std::string &name)
absl::Status PrepareActiveProjectEditorDraftsForSave(bool publish_lyra=true)
std::unique_ptr< ActivityBar > activity_bar_
ShortcutManager shortcut_manager_
bool RestoreLayoutSnapshot(const std::string &name, bool remove_after_restore=false)
bool HasPendingDungeonChangesForSession(size_t session_index) const
std::optional< PendingUnsavedSessionAction > pending_unsaved_session_action_
void MarkEditorInitialized(RomSession *session, EditorType type)
bool SessionHasPendingUnsavedWork(size_t session_index) const
absl::Status RevertRomToSavedInternal()
std::unique_ptr< BackgroundCommandTask > active_project_build_
bool IsCurrentProjectContextOwnedBySession(size_t session_id) const
bool IsPlanningOnlyProjectSave(const RomSession &session)
WorkspaceManager workspace_manager_
yaze::zelda3::Overworld * overworld() const
void ConfigureEditorDependencies(EditorSet *editor_set, Rom *rom, size_t session_id)
absl::StatusOr< const project::YazeProject * > PrepareActiveProjectContextForSave()
std::unique_ptr< ProjectManagementPanel > project_management_panel_
std::unique_ptr< workflow::HackWorkflowBackend > hack_workflow_backend_
absl::StatusOr< std::string > ResolveProjectBuildCommand()
void RestoreProjectContextAfterFailedOpen(std::optional< size_t > previous_session_id)
void RemoveSession(size_t index)
absl::Status CheckOracleRomSafetyPreSave(Rom *rom)
UiSyncState GetUiSyncStateSnapshot() const
ProjectWorkflowStatus MakeBuildStatus(const std::string &summary, const std::string &detail, ProjectWorkflowState state, const std::string &output_tail="", bool can_cancel=false) const
absl::Status DiscardProvisionalSessionCreatedSince(size_t previous_session_count)
absl::Status EnsureEditorAssetsLoaded(EditorType type)
std::unique_ptr< PopupManager > popup_manager_
bool RestoreProjectContextForSession(RomSession *session)
void CaptureCurrentRomIdentity(bool preserve_editing_source=false)
std::atomic< int > pending_editor_deferred_actions_
std::unique_ptr< UICoordinator > ui_coordinator_
EditorActivator editor_activator_
absl::Status SetCurrentRom(Rom *rom)
std::string GetPendingUnsavedSessionActionSaveLabel() const
std::optional< PendingProjectRomSelection > pending_project_rom_selection_
std::unique_ptr< WindowHost > window_host_
void HandleSessionCreated(size_t index, RomSession *session)
absl::Status SaveActiveProjectEditingWork(bool allow_dialogs=true)
bool EditorRequiresGameData(EditorType type) const
absl::Status ReplaceActiveSessionRom(Rom &&rom, const std::string &filepath)
static bool UpdateAllowedWithoutLoadedRom(EditorType type)
static EditorType GetEditorTypeFromCategory(const std::string &category)
static bool IsPanelBasedEditor(EditorType type)
static bool ShouldWarnAboutExperimentalEditor(EditorType type, bool experiments_enabled)
static EditorExperimentPolicy GetExperimentPolicy(EditorType type)
static std::string GetEditorName(EditorType type)
static std::string GetEditorCategory(EditorType type)
Contains a complete set of editors for a single ROM instance.
T * GetEditorAs(EditorType type) const
bool HasPendingPlanningProjectDraftChanges() const
bool HasPendingBuildProjectDraftChanges() const
void ApplyDependencies(const EditorDependencies &dependencies)
Editor * GetEditor(EditorType type) const
GfxGroupWorkspaceState * gfx_group_workspace()
SettingsPanel * GetSettingsPanel() const
std::vector< Editor * > active_editors_
Interface for editor classes.
Definition editor.h:252
virtual absl::Status Redo()=0
EditorType type() const
Definition editor.h:355
virtual EditorContextSnapshot BuildContextSnapshot() const
Definition editor.h:344
virtual absl::Status Undo()=0
void SetGuideCallback(std::function< void()> callback)
Opens Help → Coming from ZScream (or equivalent) from actionable tips.
void SetUserSettings(UserSettings *settings)
bool MaybeShow(std::string_view id)
void RegisterBuiltinHints()
Register built-in ZScream migrant tips. Safe to call more than once.
void SetToastManager(ToastManager *toast_manager)
Allows the user to edit graphics sheets from the game or view prototype graphics.
bool RestorePreviousEditorLayout(EditorType type)
void ProcessDeferredActions()
Process all queued deferred actions.
bool HasPreviousEditorLayout(EditorType type) const
void ResetWorkspaceLayout()
Reset the workspace layout to defaults.
void InitializeEditorLayout(EditorType type)
Initialize layout for an editor type on first activation.
void ResetCurrentEditorLayout(EditorType editor_type, size_t session_id)
Reset current editor layout to its default configuration.
int PendingDeferredActionCount() const
Approximate pending deferred layout actions for sync diagnostics.
void ApplyLayoutPreset(const std::string &preset_name, size_t session_id)
Apply a named layout preset.
void Initialize(const Dependencies &deps)
Initialize with all dependencies.
bool HasUnpublishedMessageSourceChanges() const
Main UI class for editing overworld maps in A Link to the Past.
absl::Status SaveProjectTerrainAs(project::YazeProject *project, const std::string &project_path)
absl::Status LoadFile(const std::string &filepath)
Load a project file into the editor.
void SetProject(project::YazeProject *project)
Set the project pointer for label import operations.
ProjectFileEditorState CaptureState() const
void RestoreState(const ProjectFileEditorState &state, project::YazeProject *project)
void set_active(bool active)
Set whether the editor window is active.
absl::Status SaveFile()
Save the current editor contents to disk.
void ResetForProject(project::YazeProject *project)
void SetSaveCompleteCallback(SaveCompleteCallback callback)
void SetToastManager(ToastManager *toast_manager)
Set toast manager for notifications.
const std::string & filepath() const
Get the current filepath.
void SetSaveGuardCallback(SaveGuardCallback callback)
Panel for managing project settings, ROM versions, and snapshots.
void SetBuildStatus(const ProjectWorkflowStatus &status)
void SetRunStatus(const ProjectWorkflowStatus &status)
absl::Status FinalizeProjectCreation(const std::string &project_name, const std::string &project_path)
Complete project creation after ROM is loaded.
absl::Status ValidateProjectCreationTarget(const std::string &project_name, const std::string &project_path=std::string()) const
absl::Status SetProjectRom(const std::string &rom_path)
Set the ROM for the current project.
absl::Status CreateNewProject(const std::string &template_name="")
void CancelPendingProject()
Cancel pending project creation.
bool IsPendingRomSelection() const
Check if project is waiting for ROM selection.
absl::Status ImportProject(const std::string &project_path)
project::YazeProject & GetCurrentProject()
static float GetDefaultDrawerWidth(DrawerType type, EditorType editor=EditorType::kUnknown)
Get the default width for a specific drawer type.
std::vector< BackupEntry > ListBackups(const std::string &rom_filename) const
absl::Status LoadRom(Rom *rom, const std::string &filename)
std::vector< RomFileManager::BackupEntry > GetRomBackups(Rom *rom) const
absl::Status CheckRomWritePolicy(Rom *rom, const std::optional< std::string > &target_filename=std::nullopt)
Enforce project write policy; may set pending_rom_write_confirm.
void ActivateRomIdentity(const RomSession *session)
absl::Status CheckRomOpenPolicy(Rom *rom)
Validate that the loaded ROM is a safe project target to open/edit.
PotItemSaveDecision ResolvePotItemSaveConfirmation(PotItemSaveDecision decision)
const std::vector< core::WriteConflict > & pending_write_conflicts() const
absl::Status CheckOracleRomSafetyPreSave(Rom *rom)
Run Oracle-specific ROM safety preflight before saving.
void ApplyDefaultBackupPolicy(bool enabled, const std::string &folder, int retention_count, bool keep_daily, int keep_daily_days)
Apply default backup policy from user settings.
void SetAgentCallbacks(std::function< void(const std::string &)> send_callback, std::function< void()> focus_callback)
static bool PathsReferToSameBackingFile(const std::string &lhs, const std::string &rhs)
Manages the settings UI displayed in the right sidebar.
Allows the user to edit sprites.
A session-aware status bar displayed at the bottom of the application.
Definition status_bar.h:57
void SetBuildStatus(const ProjectWorkflowStatus &status)
Definition status_bar.h:209
void SetRunStatus(const ProjectWorkflowStatus &status)
Definition status_bar.h:212
void SetEnabled(bool enabled)
Enable or disable the status bar.
Definition status_bar.h:71
void Initialize(GlobalEditorContext *context)
Definition status_bar.cc:91
void SetAgentToggleCallback(std::function< void()> callback)
Definition status_bar.h:219
void Show(const std::string &message, ToastType type=ToastType::kInfo, float ttl_seconds=3.0f, std::string action_label={}, std::function< void()> on_action=nullptr)
bool ApplyPanelLayoutDefaultsRevision(int target_revision)
static constexpr int kLatestPanelLayoutDefaultsRevision
static constexpr int kLastWorkspaceResetPanelLayoutDefaultsRevision
void set_apply_preset_callback(std::function< void(const std::string &)> callback)
void set_apply_preset_callback(std::function< void(const std::string &)> callback)
void set_window_manager(WorkspaceWindowManager *manager)
void set_layout_manager(LayoutManager *manager)
void SetSidebarVisible(bool visible, bool notify=true)
void RestoreVisibilityState(size_t session_id, const std::unordered_map< std::string, bool > &state, bool publish_events=false)
Restore panel visibility state from persistence.
const WindowDescriptor * GetWindowDescriptor(size_t session_id, const std::string &base_window_id) const
std::vector< std::string > GetWindowsInSession(size_t session_id) const
const std::unordered_map< std::string, WindowDescriptor > & GetAllWindowDescriptors() const
Get all panel descriptors (for layout designer, panel browser, etc.)
bool CloseWindow(size_t session_id, const std::string &base_window_id)
void SetActiveCategory(const std::string &category, bool notify=true)
void RegisterRegistryWindowContent(std::unique_ptr< WindowContent > window)
Register a ContentRegistry-managed WindowContent instance.
void RegisterWindowContent(std::unique_ptr< WindowContent > window)
Register a WindowContent instance for central drawing.
static constexpr const char * kDashboardCategory
std::vector< std::string > GetVisibleWindowIds(size_t session_id) const
Get list of currently visible panel IDs for a session.
void RegisterWindow(size_t session_id, const WindowDescriptor &descriptor)
void SetStoredSidePanelWidth(float width, bool notify=false)
bool IsWindowOpen(size_t session_id, const std::string &base_window_id) const
void SetFileBrowserPath(const std::string &category, const std::string &path)
bool OpenWindow(size_t session_id, const std::string &base_window_id)
void SetWindowBrowserCategoryWidth(float width, bool notify=true)
void SetSidebarExpanded(bool expanded, bool notify=true)
void RestorePinnedState(const std::unordered_map< std::string, bool > &state)
Restore pinned panel state from persistence.
void RegisterPanelAlias(const std::string &legacy_base_id, const std::string &canonical_base_id)
Register a legacy panel ID alias that resolves to a canonical ID.
void MarkWindowRecentlyUsed(const std::string &window_id)
void set_window_manager(editor::WorkspaceWindowManager *manager)
Definition emulator.h:51
void set_renderer(gfx::IRenderer *renderer)
Definition emulator.h:100
auto running() const -> bool
Definition emulator.h:61
absl::Status ReloadRuntimeRom(const std::vector< uint8_t > &rom_data)
Definition emulator.cc:265
bool HasPendingTextures() const
Check if there are pending textures to process.
Definition arena.h:92
static Arena & Get()
Definition arena.cc:24
Defines an abstract interface for all rendering operations.
Definition irenderer.h:60
bool HasUnsavedChanges() const
Check if there are ANY unsaved changes.
void Initialize(zelda3::GameData *game_data)
Initialize the palette manager with GameData.
size_t GetModifiedColorCount() const
Get count of modified colors across all groups.
static PaletteManager & Get()
Get the singleton instance.
void ReleaseSession(const zelda3::GameData *game_data)
Forget all palette tracking for a closing or reloaded ROM session.
static PerformanceProfiler & Get()
void PrintSummary() const
Print a summary of all operations to console.
static MotionProfile ClampMotionProfile(int raw_profile)
Definition animator.cc:110
void SetMotionPreferences(bool reduced_motion, MotionProfile profile)
Definition animator.cc:120
void ApplyTheme(const std::string &theme_name)
void SetOnThemeChangedCallback(ThemeChangedCallback callback)
static ThemeManager & Get()
void SetLanguage(const std::string &locale)
static LanguageManager & Get()
void SetOnLanguageChangedCallback(LanguageChangedCallback cb)
static RecentFilesManager & GetInstance()
Definition project.h:632
const std::vector< std::string > & GetRecentFiles() const
Definition project.h:669
void SetCurrentRom(Rom *rom)
static TestManager & Get()
static std::string ShowSaveFileDialog(const std::string &default_name="", const std::string &default_extension="")
ShowSaveFileDialog opens a save file dialog and returns the selected filepath. Uses global feature fl...
static std::string ShowOpenFileDialog()
ShowOpenFileDialog opens a file dialog and returns the selected filepath. Uses global feature flag to...
static std::string ShowOpenFolderDialog()
ShowOpenFolderDialog opens a file dialog and returns the selected folder path. Uses global feature fl...
std::unordered_map< std::string, LabelMap > ProjectLabels
void SetHackManifest(const core::HackManifest *manifest)
Set the hack manifest reference for ASM-defined labels.
void SetProjectLabels(ProjectLabels *labels)
Set the project labels reference (typically from YazeProject)
#define ICON_MD_FOLDER_OPEN
Definition icons.h:813
#define ICON_MD_SETTINGS
Definition icons.h:1699
#define ICON_MD_MEMORY
Definition icons.h:1195
#define ICON_MD_STOP
Definition icons.h:1862
#define ICON_MD_VIDEOGAME_ASSET
Definition icons.h:2076
#define ICON_MD_BUG_REPORT
Definition icons.h:327
#define ICON_MD_SPEED
Definition icons.h:1817
#define ICON_MD_AUDIOTRACK
Definition icons.h:213
#define ICON_MD_KEYBOARD
Definition icons.h:1028
#define ICON_MD_TERMINAL
Definition icons.h:1951
#define ICON_MD_DASHBOARD
Definition icons.h:517
#define ICON_MD_SAVE
Definition icons.h:1644
#define ICON_MD_SPORTS_ESPORTS
Definition icons.h:1826
#define ICON_MD_AUDIO_FILE
Definition icons.h:212
#define ICON_MD_SMART_TOY
Definition icons.h:1781
#define LOG_DEBUG(category, format,...)
Definition log.h:133
#define LOG_WARN(category, format,...)
Definition log.h:138
#define LOG_INFO(category, format,...)
Definition log.h:136
#define PRINT_IF_ERROR(expression)
Definition macro.h:28
#define ASSIGN_OR_RETURN(type_variable_name, expression)
Definition macro.h:62
std::string ComputeSourceArtifactSha256(std::string_view content)
absl::StatusOr< NativeSaveContext > GetNativeSaveContext(const std::string &, const std::string &)
void SetGlobalContext(GlobalEditorContext *ctx)
void SetShowWorkflowOutputCallback(std::function< void()> callback)
void SetEventBus(::yaze::EventBus *bus)
Set the current EventBus instance.
void SetGameData(::yaze::zelda3::GameData *data)
Set the current game data instance.
void AppendWorkflowHistory(const ProjectWorkflowHistoryEntry &entry)
void SetRunProjectWorkflowCallback(std::function< void()> callback)
void SetBuildWorkflowStatus(const ProjectWorkflowStatus &status)
void SetCancelBuildWorkflowCallback(std::function< void()> callback)
void SetLayoutManager(LayoutManager *manager)
void SetBuildWorkflowLog(const std::string &output)
void SetStartBuildWorkflowCallback(std::function< void()> callback)
void SetRunWorkflowStatus(const ProjectWorkflowStatus &status)
void SetHackWorkflowBackend(workflow::HackWorkflowBackend *backend)
void SetUserSettings(UserSettings *settings)
void Clear()
Clear all context state.
std::vector< std::unique_ptr< WindowContent > > CreateAll()
Create new instances of all registered panels.
constexpr const char * kZScreamDungeon
constexpr const char * kZScreamOverworld
constexpr const char * kZScreamTile16
constexpr const char * kZScreamScreenMap
constexpr const char * kAbout
constexpr const char * kComingFromZScream
constexpr const char * kSaveAs
constexpr const char * kWriteConflictWarning
constexpr const char * kDungeonPotItemSaveConfirm
constexpr const char * kUnsavedSessionChanges
constexpr const char * kRomWriteConfirm
void UpdateBuildWorkflowStatus(StatusBar *status_bar, ProjectManagementPanel *project_panel, const ProjectWorkflowStatus &status)
void UpdateRunWorkflowStatus(StatusBar *status_bar, ProjectManagementPanel *project_panel, const ProjectWorkflowStatus &status)
std::string LastNonEmptyLine(const std::string &text)
void MergeRightDrawerWidthPreferences(std::unordered_map< std::string, float > *preferences, const std::unordered_map< std::string, float > &drawer_widths)
absl::StatusOr< std::map< std::string, std::string > > ProjectBuildEnvironment(const project::YazeProject &project, const std::string &editing_source_path)
void AppendWorkflowHistoryEntry(const std::string &kind, const ProjectWorkflowStatus &status, const std::string &output_log)
std::string StripSessionPrefix(absl::string_view panel_id)
std::unique_ptr< HackWorkflowBackend > CreateHackWorkflowBackendForProject(const project::YazeProject *project)
Editors are the view controllers for the application.
std::string PreferStartupCategory(const std::string &saved_category, const std::vector< std::string > &available_categories)
bool IsTransientPanelVisibilityId(absl::string_view panel_id)
std::optional< EditorType > ParseEditorTypeFromString(absl::string_view name)
constexpr std::array< const char *, 15 > kEditorNames
Definition editor.h:232
void ConfigureMenuShortcuts(const ShortcutDependencies &deps, ShortcutManager *shortcut_manager)
void RegisterDefaultEditorFactories(EditorRegistry *registry)
void ConfigurePanelShortcuts(const ShortcutDependencies &deps, ShortcutManager *shortcut_manager)
Final configuration pass: apply user rebinds, then register panel toggle shortcuts.
size_t EditorTypeIndex(EditorType type)
Definition editor.h:242
void ConfigureEditorShortcuts(const ShortcutDependencies &deps, ShortcutManager *shortcut_manager)
constexpr size_t kEditorTypeCount
Definition editor.h:239
absl::Status ValidateRomCollisionSourceBinding(Rom *replacement_rom, const fs::path &json_path)
Animator & GetAnimator()
Definition animator.cc:318
void PostOverlayCommand(const char *command)
void RegisterZ3edTestSuites()
FileDialogOptions MakeRomFileDialogOptions(bool include_all_files)
Definition file_util.cc:127
absl::Status LoadGameData(Rom &rom, GameData &data, const LoadOptions &options)
Loads all Zelda3-specific game data from a generic ROM.
Definition game_data.cc:123
void SetPreferHmagicSpriteNames(bool prefer)
Definition sprite.cc:276
ResourceLabelProvider & GetResourceLabels()
Get the global ResourceLabelProvider instance.
AssetLoadMode
Asset loading mode for editor resources.
void SetActiveFontIndex(int index)
#define RETURN_IF_ERROR(expr)
Definition snes.cc:22
Configuration options for the application startup.
Definition application.h:26
std::string startup_editor
Definition application.h:38
StartupVisibility welcome_mode
Definition application.h:32
std::vector< std::string > open_panels
Definition application.h:40
StartupVisibility sidebar_mode
Definition application.h:34
StartupVisibility dashboard_mode
Definition application.h:33
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > all_resource_labels
std::function< EditorSet *()> get_current_editor_set
std::function< void(std::function< void()>)> queue_deferred_action
std::function< absl::Status(EditorType)> ensure_editor_assets_loaded
std::vector< EditorContextDiagnostic > diagnostics
Unified dependency container for all editor types.
Definition editor.h:170
project::YazeProject * project
Definition editor.h:174
GlobalEditorContext * global_context
Definition editor.h:176
SharedClipboard * shared_clipboard
Definition editor.h:187
std::function< project::YazeProject *()> project_context_provider
Definition editor.h:197
gfx::IRenderer * renderer
Definition editor.h:192
ShortcutManager * shortcut_manager
Definition editor.h:186
core::VersionManager * version_manager
Definition editor.h:175
zelda3::GameData * game_data
Definition editor.h:173
WorkspaceWindowManager * window_manager
Definition editor.h:182
GfxGroupWorkspaceState * gfx_group_workspace
Definition editor.h:179
ExperimentalSavePosture disabled_save_posture
Published after ImGui::NewFrame and dockspace creation.
static JumpToMapRequestEvent Create(int map, size_t session=0)
static JumpToRoomRequestEvent Create(int room, size_t session=0)
All dependencies required by LayoutCoordinator.
Built-in workflow-oriented layout profiles.
Published when panel visibility changes.
Published when a ROM is successfully loaded into a session.
Definition core_events.h:27
Represents a single session, containing a ROM and its associated editors.
core::FeatureFlags::Flags feature_flags
ProjectFileEditorState project_file_editor_state
std::array< bool, kEditorTypeCount > editor_initialized
std::array< bool, kEditorTypeCount > editor_assets_loaded
Published when a session is closed.
Published when a new session is created.
Published when the active session changes.
Definition core_events.h:89
Activity bar or menu action request.
std::unordered_map< std::string, float > right_panel_widths
std::unordered_map< std::string, std::unordered_map< std::string, bool > > panel_visibility_state
std::unordered_map< std::string, bool > pinned_panels
Declarative registration contract for editor windows.
Definition panel_host.h:22
WindowPresentationPolicy presentation
Definition panel_host.h:37
Metadata for a dockable editor window (formerly PanelInfo)
static WindowPresentationPolicy Diagnostic()
static WindowPresentationPolicy CoreWorkspace()
WindowPresentationPolicy WithHost(std::string host_name) const
Returns a copy that names the hosting surface.
static WindowPresentationPolicy OptionalPopOut()
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > labels_
Definition project.h:623
RomWritePolicy write_policy
Definition project.h:229
std::vector< std::string > recent_files
Definition project.h:89
Modern project structure with comprehensive settings consolidation.
Definition project.h:290
absl::Status RepairProject()
Definition project.cc:2639
std::string MakeStorageKey(absl::string_view suffix) const
Definition project.cc:1353
struct yaze::project::YazeProject::MusicPersistence music_persistence
bool project_opened() const
Definition project.h:538
absl::StatusOr< std::string > SerializeToString() const
Definition project.cc:1602
absl::Status LoadFromString(const std::string &content, const std::string &project_path)
Definition project.cc:789
std::string git_repository
Definition project.h:390
core::HackManifest hack_manifest
Definition project.h:376
std::string lyra_terrain_file
Definition project.h:342
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > resource_labels
Definition project.h:369
std::string assets_folder
Definition project.h:315
std::string GetDisplayName() const
Definition project.cc:2673
std::string lyra_build_request_file
Definition project.h:345
WorkspaceSettings workspace_settings
Definition project.h:362
absl::StatusOr< std::optional< std::string > > ResolveExpandedBuildRunTarget(const std::string &editing_source_path) const
Definition project.cc:905
bool IsOracleCompatible() const
Definition project.cc:1223
std::string custom_collision_json
Definition project.h:328
std::string palette_catalog_file
Definition project.h:355
std::string GetAbsolutePath(const std::string &relative_path) const
Definition project.cc:2700
absl::Status Open(const std::string &project_path)
Definition project.cc:623
absl::Status Validate() const
Definition project.cc:2569
core::FeatureFlags::Flags feature_flags
Definition project.h:361
std::vector< FileDialogFilter > filters
Definition file_util.h:18