yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
message_editor.cc
Go to the documentation of this file.
1#include "message_editor.h"
2#include "util/i18n/tr.h"
3
4#include <algorithm>
5#include <cmath>
6#include <cstdio>
7#include <cstring>
8#include <filesystem>
9#include <fstream>
10#include <iterator>
11#include <limits>
12#include <string>
13#include <unordered_map>
14#include <vector>
15
16#include "absl/status/status.h"
17#include "absl/strings/match.h"
18#include "absl/strings/str_cat.h"
19#include "absl/strings/str_format.h"
26#include "app/gfx/core/bitmap.h"
35#include "app/gui/core/icons.h"
36#include "app/gui/core/input.h"
38#include "app/gui/core/style.h"
42#include "imgui.h"
43#include "imgui/imgui_internal.h"
44#include "imgui/misc/cpp/imgui_stdlib.h"
45#include "rom/rom.h"
46#include "rom/snes.h"
47#include "rom/transaction.h"
48#include "rom/write_fence.h"
49#include "util/file_util.h"
50#include "util/hex.h"
51#include "util/log.h"
52
53namespace yaze {
54namespace editor {
55
56using ImGui::BeginChild;
57using ImGui::BeginTable;
58using ImGui::Button;
59using ImGui::EndChild;
60using ImGui::EndTable;
61using ImGui::InputTextMultiline;
62using ImGui::PopID;
63using ImGui::PushID;
64using ImGui::SameLine;
65using ImGui::Separator;
66using ImGui::TableHeadersRow;
67using ImGui::TableNextColumn;
68using ImGui::TableSetupColumn;
69using ImGui::Text;
70using ImGui::TextWrapped;
71
72constexpr ImGuiTableFlags kMessageTableFlags = ImGuiTableFlags_Hideable |
73 ImGuiTableFlags_Borders |
74 ImGuiTableFlags_Resizable;
75
79 // The backing texture contains hidden message lines, not the viewport.
83 dirty_state_ = {};
88 // Register panels with WorkspaceWindowManager (dependency injection)
90 return;
91
92 auto* window_manager = dependencies_.window_manager;
93 const size_t session_id = dependencies_.session_id;
94
95 // Register WindowContent implementations (they provide both metadata and drawing)
96 window_manager->RegisterWindowContent(
97 std::make_unique<MessageListPanel>([this]() { DrawMessageList(); }));
98 window_manager->RegisterWindowContent(
99 std::make_unique<MessageEditorPanel>([this]() { DrawCurrentMessage(); }));
100 window_manager->RegisterWindowContent(
101 std::make_unique<FontAtlasPanel>([this]() {
104 }));
105 window_manager->RegisterWindowContent(
106 std::make_unique<DictionaryPanel>([this]() { DrawMessageTools(); }));
107
108 // Show message list by default
109 window_manager->OpenWindow(session_id, "message.message_list");
110
111 for (int i = 0; i < kWidthArraySize; i++) {
113 }
114
116 const int message_read_limit = static_cast<int>(
117 std::min(static_cast<size_t>(rom()->size()),
118 static_cast<size_t>(std::numeric_limits<int>::max())));
120 ReadAllTextData(rom()->mutable_data(), kTextData, message_read_limit);
121 LOG_INFO("MessageEditor", "Loaded %zu messages from ROM",
122 list_of_texts_.size());
123
128 }
132
134
135 if (!list_of_texts_.empty()) {
136 // Prefer a complete dialogue over the menu fragments at the start of a
137 // typical ROM. Keep the historical fallback for unusual message sets.
138 size_t default_idx = list_of_texts_.size() > 1 ? 1 : 0;
139 for (size_t i = 0; i < list_of_texts_.size(); ++i) {
140 const int id = list_of_texts_[i].ID;
141 if (id >= 0 && static_cast<size_t>(id) < parsed_messages_.size() &&
143 default_idx = i;
144 break;
145 }
146 }
147 current_message_ = list_of_texts_[default_idx];
151 current_parse_errors_.clear();
154 } else {
155 LOG_ERROR("MessageEditor", "No messages found in ROM!");
156 }
157}
158
159bool MessageEditor::OpenMessageById(int display_id) {
160 // Do not discard an invalid in-progress draft by navigating away. The user
161 // can correct it or undo it before selecting another message.
162 if (!current_parse_errors_.empty()) {
163 return false;
164 }
165
166 const int vanilla_count = static_cast<int>(list_of_texts_.size());
167 const int expanded_base_id = expanded_message_base_id_;
168
169 int expanded_count = static_cast<int>(expanded_messages_.size());
170 auto resolved = ResolveMessageDisplayId(display_id, vanilla_count,
171 expanded_base_id, expanded_count);
172
173 // Projects without a canonical source can inspect expanded ROM messages on
174 // navigation. A missing project source must remain an explicit source error.
175 if (!resolved.has_value() && expanded_count == 0 &&
176 !HasMessageSourceLayout() && display_id >= expanded_base_id && rom_ &&
177 rom_->is_loaded()) {
178 const auto range = ExpandedInspectionRange();
179 const int start = range.first;
180 const int end = range.second;
181 const size_t rom_size = rom_->size();
182 if (start >= 0 && end >= start && static_cast<size_t>(end) < rom_size) {
183 const auto status = LoadExpandedMessagesFromRom();
184 if (!status.ok()) {
185 LOG_DEBUG("MessageEditor",
186 "OpenMessageById: expanded load skipped/failed: %s",
187 std::string(status.message()).c_str());
188 }
189 expanded_count = static_cast<int>(expanded_messages_.size());
190 resolved = ResolveMessageDisplayId(display_id, vanilla_count,
191 expanded_base_id, expanded_count);
192 } else {
193 LOG_DEBUG("MessageEditor",
194 "OpenMessageById: expanded region out of bounds (0x%X-0x%X, "
195 "rom=0x%zX)",
196 start, end, rom_size);
197 }
198 }
199
200 if (!resolved.has_value()) {
201 return false;
202 }
203
205 const size_t session_id = dependencies_.session_id;
207 "message.message_list");
209 "message.message_editor");
210 }
211
212 if (!resolved->is_expanded) {
213 const int idx = resolved->index;
214 if (idx < 0 || idx >= vanilla_count) {
215 return false;
216 }
217
218 const auto& message = list_of_texts_[idx];
219 current_message_ = message;
220 current_message_index_ = message.ID;
222
223 const int parsed_idx = resolved->display_id;
224 if (parsed_idx >= 0 &&
225 parsed_idx < static_cast<int>(parsed_messages_.size())) {
227 } else {
228 message_text_box_.text.clear();
229 }
230
231 current_parse_errors_.clear();
233 editor_cursor_ = 0;
234 find_has_match_ = false;
239 return true;
240 }
241
242 // Expanded message.
243 const int idx = resolved->index;
244 if (idx < 0 || idx >= expanded_count) {
245 return false;
246 }
247
248 const auto& message = expanded_messages_[idx];
249 current_message_ = message;
250 current_message_index_ = message.ID;
252
253 const int parsed_idx = resolved->display_id;
254 if (parsed_idx >= 0 &&
255 parsed_idx < static_cast<int>(parsed_messages_.size())) {
257 } else {
258 message_text_box_.text.clear();
259 }
260
261 current_parse_errors_.clear();
263 editor_cursor_ = 0;
264 find_has_match_ = false;
269 return true;
270}
271
273 int base_id = static_cast<int>(list_of_texts_.size());
275 const auto& layout = dependencies_.project->hack_manifest.message_layout();
276 if (layout.first_expanded_id != 0) {
277 base_id = static_cast<int>(layout.first_expanded_id);
278 }
279 }
280
281 // Never allow the expanded base to precede the vanilla message count; this
282 // prevents truncating/overlapping IDs when the manifest is missing/mistyped.
283 base_id = std::max(base_id, static_cast<int>(list_of_texts_.size()));
284 return base_id;
285}
286
287absl::Status MessageEditor::Load() {
288 gfx::ScopedTimer timer("MessageEditor::Load");
290 return absl::OkStatus();
291 }
293 // Loading assets may be requested again during Save or editor activation.
294 // Never replace an existing draft (including an explicit ROM inspection).
295 if (!expanded_messages_.empty() || !source_loaded_canonical_sha_.empty()) {
296 return absl::OkStatus();
297 }
298 const auto status = LoadCanonicalExpandedSource();
299 if (!status.ok()) {
300 message_bundle_status_ = absl::StrFormat(
301 "Expanded source unavailable: %s. Vanilla dialogue remains available.",
302 status.message());
304 }
305 // Source errors belong in the Message editor; they must not prevent opening
306 // the project or editing its independent vanilla messages.
307 return absl::OkStatus();
308}
309
310absl::Status MessageEditor::Update() {
311 // Panels are drawn by WorkspaceWindowManager. Shortcuts stay here so they
312 // run once per frame, and only while a message window actually has focus.
314 return absl::OkStatus();
315}
316
321
322namespace {
323
325 int* cursor = nullptr;
326 int* select_start = nullptr;
327 int* select_end = nullptr;
328};
329
330int MessageInputCallback(ImGuiInputTextCallbackData* data) {
331 auto* state = static_cast<MessageInputState*>(data->UserData);
332 if (state == nullptr) {
333 return 0;
334 }
335 if (state->select_start != nullptr && state->select_end != nullptr &&
336 *state->select_start >= 0) {
337 const int start = *state->select_start;
338 const int end = std::max(start, *state->select_end);
339 data->CursorPos = std::min(end, data->BufTextLen);
340 data->SelectionStart = std::min(start, data->BufTextLen);
341 data->SelectionEnd = data->CursorPos;
342 *state->select_start = -1;
343 *state->select_end = -1;
344 }
345 if (state->cursor != nullptr) {
346 *state->cursor = data->CursorPos;
347 }
348 return 0;
349}
350
352 ImGuiContext* context = ImGui::GetCurrentContext();
353 if (context == nullptr || context->NavWindow == nullptr) {
354 return false;
355 }
356 ImGuiWindow* root = context->NavWindow->RootWindow != nullptr
357 ? context->NavWindow->RootWindow
358 : context->NavWindow;
359 return root->Name != nullptr &&
360 std::strstr(root->Name, "message.message") != nullptr;
361}
362
363} // namespace
364
366 if (!MessageSurfaceFocused()) {
367 return;
368 }
369 const ImGuiIO& io = ImGui::GetIO();
370 if (io.KeyAlt && !io.KeyCtrl && !io.KeyShift &&
371 ImGui::IsKeyPressed(ImGuiKey_UpArrow, false)) {
373 }
374 if (io.KeyAlt && !io.KeyCtrl && !io.KeyShift &&
375 ImGui::IsKeyPressed(ImGuiKey_DownArrow, false)) {
377 }
378 if (!io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_F3, false)) {
379 if (!find_panel_open_) {
380 find_panel_open_ = true;
381 find_focus_search_ = true;
382 }
383 AdvanceFind(!io.KeyShift);
384 }
385}
386
388 if (status_bar == nullptr) {
389 return;
390 }
391 const char* bank = current_message_is_expanded_ ? "Expanded" : "Vanilla";
392 status_bar->SetCustomSegment(
393 "Message",
394 absl::StrFormat("%s $%04X", bank, CurrentDisplayId() & 0xFFFF));
395 status_bar->SetCustomSegment(
396 "Size", absl::StrFormat("%zu B", current_message_.Data.size()));
397 status_bar->SetCustomSegment(
398 "Lines", absl::StrFormat("%d", message_preview_.text_line + 1));
399 const int shown = static_cast<int>(CollectMessageRows(true).size());
400 const int total = static_cast<int>(CollectMessageRows(false).size());
401 if (!list_filter_.empty() || list_bank_filter_ != 0) {
402 status_bar->SetCustomSegment("Shown",
403 absl::StrFormat("%d/%d", shown, total));
404 }
405 if (!current_parse_errors_.empty()) {
406 status_bar->SetEditorMode("Parse error");
409 status_bar->SetEditorMode("Unsaved");
410 } else {
411 status_bar->SetEditorMode("Dialogue");
412 }
413}
414
421
422std::string_view MessageEditor::ContentsForDisplayId(int display_id) const {
423 if (display_id < 0 ||
424 display_id >= static_cast<int>(parsed_messages_.size())) {
425 return {};
426 }
427 return parsed_messages_[display_id];
428}
429
430std::vector<MessageEditor::MessageRow> MessageEditor::CollectMessageRows(
431 bool apply_filter) const {
432 std::vector<MessageRow> rows;
433 rows.reserve(list_of_texts_.size() + expanded_messages_.size());
434 const auto bank = static_cast<MessageBankFilter>(list_bank_filter_);
435 const auto consider = [&](int display_id, bool expanded, uint32_t address) {
436 if (apply_filter &&
437 !MessageListQueryMatches(display_id, address,
438 ContentsForDisplayId(display_id), expanded,
439 bank, list_filter_)) {
440 return;
441 }
442 rows.push_back(MessageRow{display_id, expanded, address});
443 };
444 for (const auto& message : list_of_texts_) {
445 consider(message.ID, false, static_cast<uint32_t>(message.Address));
446 }
447 for (const auto& message : expanded_messages_) {
448 consider(expanded_message_base_id_ + message.ID, true,
449 static_cast<uint32_t>(message.Address));
450 }
451 return rows;
452}
453
454void MessageEditor::InsertTokenAtCursor(const std::string& token) {
455 if (token.empty()) {
456 return;
457 }
458 auto& text = message_text_box_.text;
459 const int pos = std::clamp(editor_cursor_, 0, static_cast<int>(text.size()));
460 text.insert(static_cast<size_t>(pos), token);
461 editor_cursor_ = pos + static_cast<int>(token.size());
464 ImGui::ClearActiveID();
466}
467
469 if (delta == 0) {
470 return;
471 }
472 if (!current_parse_errors_.empty()) {
473 replace_status_ = "Resolve parse errors before switching messages";
475 find_panel_open_ = true;
476 return;
477 }
478 const std::vector<MessageRow> rows = CollectMessageRows(true);
479 if (rows.empty()) {
480 return;
481 }
482 int current = 0;
483 const int current_id = CurrentDisplayId();
484 for (int i = 0; i < static_cast<int>(rows.size()); ++i) {
485 if (rows[i].display_id == current_id &&
486 rows[i].expanded == current_message_is_expanded_) {
487 current = i;
488 break;
489 }
490 }
491 const int next =
492 std::clamp(current + delta, 0, static_cast<int>(rows.size()) - 1);
493 if (next == current) {
494 return;
495 }
497 OpenMessageById(rows[next].display_id);
498}
499
500bool MessageEditor::ActivateFindMatch(const MessageRow& row, size_t offset,
501 bool wrapped) {
502 const bool same = row.display_id == CurrentDisplayId() &&
504 if (!same) {
505 if (!current_parse_errors_.empty()) {
506 replace_status_ = "Resolve parse errors before leaving this message";
508 return false;
509 }
511 if (!OpenMessageById(row.display_id)) {
512 replace_status_ = "Could not open the matching message";
514 return false;
515 }
516 }
517 find_match_start_ = offset;
518 find_has_match_ = true;
519 const int end = static_cast<int>(offset + search_text_.size());
520 pending_selection_start_ = static_cast<int>(offset);
522 editor_cursor_ = end;
524 replace_status_ = absl::StrFormat("Match in $%04X%s", row.display_id & 0xFFFF,
525 wrapped ? " (wrapped)" : "");
526 replace_status_error_ = false;
527 return true;
528}
529
530bool MessageEditor::AdvanceFind(bool forward) {
531 if (search_text_.empty()) {
532 replace_status_ = "Enter text to search";
534 return false;
535 }
536 const std::vector<MessageRow> rows = CollectMessageRows(false);
537 if (rows.empty()) {
538 replace_status_ = "No messages to search";
540 return false;
541 }
542
543 int start = 0;
544 const int current_id = CurrentDisplayId();
545 for (int i = 0; i < static_cast<int>(rows.size()); ++i) {
546 if (rows[i].display_id == current_id &&
547 rows[i].expanded == current_message_is_expanded_) {
548 start = i;
549 break;
550 }
551 }
552
553 const int count = static_cast<int>(rows.size());
554 const size_t cursor = static_cast<size_t>(std::clamp(
555 editor_cursor_, 0, static_cast<int>(message_text_box_.text.size())));
556 const size_t forward_from = find_has_match_ ? find_match_start_ + 1 : cursor;
557 const size_t backward_before = find_has_match_ ? find_match_start_ : cursor;
558
559 auto match_at = [&](int row_index, size_t bound,
560 bool from_start) -> std::optional<size_t> {
561 const std::string_view text =
562 ContentsForDisplayId(rows[row_index].display_id);
563 if (forward) {
564 return FindNextTextMatch(text, search_text_, from_start ? 0 : bound,
566 }
567 const size_t before = from_start ? std::string::npos : bound;
570 };
571
572 if (auto found =
573 match_at(start, forward ? forward_from : backward_before, false)) {
574 return ActivateFindMatch(rows[start], *found, false);
575 }
576 for (int step = 1; step < count; ++step) {
577 const int row_index =
578 forward ? (start + step) % count : (start - step + count) % count;
579 if (auto found = match_at(row_index, 0, true)) {
580 return ActivateFindMatch(rows[row_index], *found, false);
581 }
582 }
583 // Forward wrap only matters once the cursor has moved past the start.
584 // Backward wrap also covers "previous" from the first match, which should
585 // land on the last match in this message.
586 const bool can_wrap = forward ? forward_from > 0 : true;
587 if (can_wrap) {
588 if (auto found = match_at(start, 0, true)) {
589 return ActivateFindMatch(rows[start], *found, true);
590 }
591 }
592 replace_status_ = "No matches";
594 return false;
595}
596
598 MessageData scratch;
599 const std::string optimized = scratch.OptimizeMessageForDictionary(
601 if (optimized == message_text_box_.text) {
602 replace_status_ = "Dictionary optimize made no changes";
603 replace_status_error_ = false;
604 find_panel_open_ = true;
605 return;
606 }
607 const auto parsed = ParseMessageToDataWithDiagnostics(optimized);
608 if (!parsed.ok()) {
609 replace_status_ = "Dictionary optimize produced invalid text";
611 find_panel_open_ = true;
612 return;
613 }
614 message_text_box_.text = optimized;
617 editor_cursor_ = 0;
618 ImGui::ClearActiveID();
621 replace_status_ = "Applied dictionary compression";
622 replace_status_error_ = false;
623 find_panel_open_ = true;
624}
625
627 if (!find_panel_open_) {
628 return;
629 }
630 ImGui::PushID("FindReplace");
631 if (find_focus_search_) {
632 ImGui::SetKeyboardFocusHere();
633 find_focus_search_ = false;
634 }
635 const float half =
636 std::max(80.0f, ImGui::GetContentRegionAvail().x * 0.5f - 8.0f);
637 ImGui::SetNextItemWidth(half);
638 if (ImGui::InputTextWithHint("##find", "Find in dialogue", &search_text_)) {
639 find_has_match_ = false;
640 }
641 ImGui::SameLine();
642 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
643 ImGui::InputTextWithHint("##replace", "Replace with", &replace_text_);
644
645 if (ImGui::Button(tr("Find Next"))) {
646 AdvanceFind(true);
647 }
648 ImGui::SameLine();
649 if (ImGui::Button(tr("Previous"))) {
650 AdvanceFind(false);
651 }
652 ImGui::SameLine();
653 if (ImGui::Button(tr("Find All"))) {
654 if (search_text_.empty()) {
655 replace_status_ = "Enter text to search";
657 } else {
660 const int matches = static_cast<int>(CollectMessageRows(true).size());
661 replace_status_ = absl::StrFormat("List filtered to %d message%s",
662 matches, matches == 1 ? "" : "s");
663 replace_status_error_ = matches == 0;
667 "message.message_list");
668 }
669 }
670 }
671 ImGui::SameLine();
672 if (ImGui::Button(tr("Replace"))) {
673 const int count = ReplaceCurrentMatch();
674 if (count > 0) {
675 replace_status_ = "Replaced 1 occurrence";
676 replace_status_error_ = false;
677 } else if (search_text_.empty()) {
678 replace_status_ = "Enter text to search";
680 } else {
681 replace_status_ = "No match found in current message";
683 }
684 }
685 ImGui::SameLine();
686 if (ImGui::Button(tr("Replace All"))) {
687 int count = ReplaceAllMatches();
688 if (count >= 0) {
689 replace_status_ = absl::StrFormat("Replaced %d occurrence%s", count,
690 count == 1 ? "" : "s");
691 replace_status_error_ = count == 0;
692 }
693 }
694 ImGui::SameLine();
695 if (ImGui::SmallButton(tr("Close"))) {
696 find_panel_open_ = false;
697 }
698
699 ImGui::Checkbox(tr("Case Sensitive"), &case_sensitive_);
700 if (ImGui::IsItemHovered()) {
701 ImGui::SetTooltip("Applies to Find Next, Previous, and Replace.");
702 }
703 ImGui::SameLine();
704 ImGui::Checkbox(tr("Whole Word"), &match_whole_word_);
705 if (ImGui::IsItemHovered()) {
706 ImGui::SetTooltip("Match only when both sides are not letters or digits.");
707 }
708 if (!replace_status_.empty()) {
709 const ImVec4 color =
711 ImGui::TextColored(color, "%s", replace_status_.c_str());
712 }
713 ImGui::PopID();
714}
715
717 if (baseline_messages_.size() >= parsed_messages_.size()) {
718 return;
719 }
720 baseline_messages_.insert(
721 baseline_messages_.end(),
722 parsed_messages_.begin() +
723 static_cast<std::ptrdiff_t>(baseline_messages_.size()),
724 parsed_messages_.end());
725}
726
728 const int display_id = CurrentDisplayId();
729 if (display_id < 0 ||
730 display_id >= static_cast<int>(baseline_messages_.size())) {
731 return {};
732 }
733 return baseline_messages_[display_id];
734}
735
737 if (!current_parse_errors_.empty()) {
738 return;
739 }
740 const int display_id = CurrentDisplayId();
741 if (display_id < 0) {
742 return;
743 }
744 if (display_id >= static_cast<int>(baseline_messages_.size())) {
745 baseline_messages_.resize(static_cast<size_t>(display_id) + 1);
746 }
749}
750
752 const std::string reference = CurrentReferenceText();
753 if (reference != reference_view_text_) {
754 reference_view_text_ = reference;
755 }
756 const bool edited = reference_view_text_ != message_text_box_.text;
757 const bool show_reference =
758 !reference_view_text_.empty() &&
760 const float label_h = ImGui::GetFrameHeightWithSpacing();
761 const float text_h = std::max(48.0f, height - label_h);
762
763 auto draw_editor = [&](float editor_height) {
764 MessageInputState input_state{&editor_cursor_, &pending_selection_start_,
766 if (InputTextMultiline("##MessageEditor", &message_text_box_.text,
767 ImVec2(-1.0f, editor_height),
768 ImGuiInputTextFlags_CallbackAlways,
769 MessageInputCallback, &input_state)) {
771 }
772 if (ImGui::IsItemDeactivatedAfterEdit()) {
774 }
775 };
776
777 if (!show_reference) {
778 draw_editor(-1.0f);
779 return;
780 }
781
782 const bool side_by_side = ImGui::GetContentRegionAvail().x >= 640.0f;
783 if (side_by_side &&
784 ImGui::BeginTable("##DialogueColumns", 2, ImGuiTableFlags_Resizable,
785 ImVec2(0.0f, height))) {
786 ImGui::TableSetupColumn(gui::ColumnLabel(tr("Loaded"), "loaded").c_str(),
787 ImGuiTableColumnFlags_WidthStretch, 0.45f);
788 ImGui::TableSetupColumn(gui::ColumnLabel(tr("Editing"), "editing").c_str(),
789 ImGuiTableColumnFlags_WidthStretch, 0.55f);
790 ImGui::TableHeadersRow();
791 ImGui::TableNextRow();
792 ImGui::TableNextColumn();
793 ImGui::InputTextMultiline("##MessageReference", &reference_view_text_,
794 ImVec2(-1.0f, text_h),
795 ImGuiInputTextFlags_ReadOnly);
796 ImGui::TableNextColumn();
797 draw_editor(text_h);
798 ImGui::EndTable();
799 return;
800 }
801
802 ImGui::TextDisabled(tr("Loaded"));
803 const float reference_h = std::clamp(height * 0.34f, 64.0f, 140.0f);
804 ImGui::InputTextMultiline("##MessageReference", &reference_view_text_,
805 ImVec2(-1.0f, reference_h),
806 ImGuiInputTextFlags_ReadOnly);
807 ImGui::TextDisabled(tr("Editing"));
808 draw_editor(std::max(48.0f, height - reference_h - label_h * 2.0f));
809}
810
812 const auto* project = dependencies_.project;
813 return project != nullptr && project->hack_manifest.loaded() &&
815}
816
820
824
825std::pair<int, int> MessageEditor::ExpandedInspectionRange() const {
826 const int fallback_start = GetExpandedTextDataStart();
827 const int fallback_end = GetExpandedTextDataEnd();
828 const auto* project = dependencies_.project;
829 if (project == nullptr || !project->hack_manifest.loaded()) {
830 return {fallback_start, fallback_end};
831 }
832 const auto& layout = project->hack_manifest.message_layout();
833 if (layout.data_start == 0 || layout.data_end < layout.data_start) {
834 return {fallback_start, fallback_end};
835 }
836 const int start = static_cast<int>(SnesToPc(layout.data_start));
837 const int end = static_cast<int>(SnesToPc(layout.data_end));
838 if (end < start) {
839 return {fallback_start, fallback_end};
840 }
841 return {start, end};
842}
843
845 if (source_sync_ready_) {
847 "The draft changed after preview. Preview again before publishing.";
849 }
850 source_sync_ready_ = false;
851 source_sync_changed_ = false;
854}
855
856absl::StatusOr<std::filesystem::path>
859 return absl::FailedPreconditionError(
860 "The project hack manifest does not define messages.source");
861 }
862 const auto& configured = dependencies_.project->hack_manifest.message_layout()
863 .source->canonical_bundle_path;
864 const std::filesystem::path relative(configured);
865 if (relative.empty() || relative.is_absolute() || relative.has_root_name()) {
866 return absl::InvalidArgumentError(
867 "Canonical message bundle must be a project-relative path");
868 }
869 std::error_code error;
870 const std::filesystem::path descriptor =
871 std::filesystem::absolute(dependencies_.project->filepath, error);
872 if (error) {
873 return absl::FailedPreconditionError(
874 absl::StrFormat("Cannot resolve project descriptor %s: %s",
875 dependencies_.project->filepath, error.message()));
876 }
877 const std::filesystem::path root =
878 std::filesystem::canonical(descriptor.parent_path(), error);
879 if (error) {
880 return absl::FailedPreconditionError(
881 absl::StrFormat("Cannot resolve project root for %s: %s",
882 dependencies_.project->filepath, error.message()));
883 }
884 const std::filesystem::path joined = (root / relative).lexically_normal();
885 const std::filesystem::path from_root = joined.lexically_relative(root);
886 if (from_root.empty() || from_root.is_absolute() ||
887 *from_root.begin() == "..") {
888 return absl::InvalidArgumentError(
889 "Canonical message bundle must stay inside the project root");
890 }
891 return joined;
892}
893
894absl::StatusOr<std::string> MessageEditor::HashFileSha256(
895 const std::filesystem::path& path) const {
896 std::ifstream input(path, std::ios::binary);
897 if (!input.is_open()) {
898 return absl::NotFoundError(absl::StrFormat(
899 "Cannot read canonical message bundle: %s", path.string()));
900 }
901 const std::string content((std::istreambuf_iterator<char>(input)),
902 std::istreambuf_iterator<char>());
903 if (!input.good() && !input.eof()) {
904 return absl::InternalError(absl::StrFormat(
905 "Cannot read canonical message bundle: %s", path.string()));
906 }
907 return ComputeMessageSourceSha256(content);
908}
909
910bool MessageEditor::IsCanonicalBundlePath(const std::string& path) const {
911 const auto canonical_or = ResolveCanonicalBundlePath();
912 if (!canonical_or.ok() || path.empty()) {
913 return false;
914 }
915 std::error_code error;
916 const auto incoming = std::filesystem::weakly_canonical(path, error);
917 if (error) {
918 return false;
919 }
920 const auto target =
921 std::filesystem::weakly_canonical(canonical_or.value(), error);
922 return !error && incoming == target;
923}
924
945
964
966 std::error_code error;
967 std::filesystem::path directory = std::filesystem::temp_directory_path(error);
968 if (error) {
969 directory = std::filesystem::current_path(error);
970 }
971 return (directory / absl::StrFormat("yaze-message-source-sync-%zu.json",
973 .string();
974}
975
977 source_sync_ready_ = false;
978 source_sync_changed_ = false;
981 source_sync_summary_.clear();
982 if (!current_parse_errors_.empty()) {
983 source_sync_status_ = "Resolve parse errors before previewing source";
985 return;
986 }
987 if (expanded_messages_.empty()) {
988 source_sync_status_ = "Load expanded messages before publishing source";
990 return;
991 }
992 if (!HasMessageSourceLayout()) {
994 "The project hack manifest does not define messages.source";
996 return;
997 }
998 if (source_loaded_canonical_sha_.empty()) {
1000 "Load the canonical expanded bundle before previewing publication";
1002 return;
1003 }
1004
1005 const auto canonical_sha_or = [&]() -> absl::StatusOr<std::string> {
1006 const auto path_or = ResolveCanonicalBundlePath();
1007 if (!path_or.ok()) {
1008 return path_or.status();
1009 }
1010 return HashFileSha256(path_or.value());
1011 }();
1012 if (!canonical_sha_or.ok()) {
1013 source_sync_status_ = std::string(canonical_sha_or.status().message());
1015 return;
1016 }
1017 if (canonical_sha_or.value() != source_loaded_canonical_sha_) {
1019 "Canonical source changed on disk after it was loaded. Reload the "
1020 "canonical bundle before preview. This draft was not published.";
1022 return;
1023 }
1024
1025 const std::string incoming_path = MessageSourceIncomingPath();
1026 const auto write_status =
1028 if (!write_status.ok()) {
1029 source_sync_status_ = absl::StrFormat(
1030 "Could not write the preview bundle: %s", write_status.message());
1032 return;
1033 }
1034 const auto draft_sha_or =
1035 HashFileSha256(std::filesystem::path(incoming_path));
1036 if (!draft_sha_or.ok()) {
1037 source_sync_status_ = std::string(draft_sha_or.status().message());
1039 return;
1040 }
1041
1042 auto result_or = SyncMessageSource(*dependencies_.project, incoming_path,
1044 if (!result_or.ok()) {
1045 source_sync_status_ = std::string(result_or.status().message());
1047 return;
1048 }
1049
1050 const MessageSourceSyncResult& result = *result_or;
1051 source_sync_ready_ = true;
1054 source_sync_draft_sha_ = draft_sha_or.value();
1055 source_sync_summary_ = absl::StrFormat(
1056 "%s. %d update%s, %zu / %zu bytes. SHA %s",
1057 result.changed ? "Source would change" : "Source already matches",
1058 result.incoming_updates, result.incoming_updates == 1 ? "" : "s",
1059 result.encoded_size, result.capacity,
1060 result.proposed_source_sha256.substr(
1061 0, std::min<size_t>(12, result.proposed_source_sha256.size())));
1064}
1065
1068 source_sync_draft_sha_.empty()) {
1069 source_sync_status_ = "Preview the publication before writing it";
1071 return;
1072 }
1073 if (!current_parse_errors_.empty() || expanded_messages_.empty() ||
1075 source_sync_status_ = "Publication is no longer valid";
1077 source_sync_ready_ = false;
1078 source_sync_draft_sha_.clear();
1079 return;
1080 }
1081
1082 const std::string incoming_path = MessageSourceIncomingPath();
1083 const auto write_status =
1085 if (!write_status.ok()) {
1086 source_sync_status_ = absl::StrFormat(
1087 "Could not write the publication bundle: %s", write_status.message());
1089 return;
1090 }
1091 const auto draft_sha_or =
1092 HashFileSha256(std::filesystem::path(incoming_path));
1093 if (!draft_sha_or.ok() || draft_sha_or.value() != source_sync_draft_sha_) {
1094 source_sync_ready_ = false;
1095 source_sync_draft_sha_.clear();
1097 "The draft changed after preview. Preview again before publishing. "
1098 "Nothing was written.";
1100 return;
1101 }
1102
1103 const auto canonical_path_or = ResolveCanonicalBundlePath();
1104 const auto canonical_sha_or =
1105 canonical_path_or.ok()
1106 ? HashFileSha256(canonical_path_or.value())
1107 : absl::StatusOr<std::string>(canonical_path_or.status());
1108 if (!canonical_sha_or.ok() ||
1109 canonical_sha_or.value() != source_sync_sha_before_ ||
1110 canonical_sha_or.value() != source_loaded_canonical_sha_) {
1111 source_sync_ready_ = false;
1112 source_sync_draft_sha_.clear();
1114 "Canonical source changed after preview. Reload the canonical bundle "
1115 "and preview again. This draft was not published.";
1117 return;
1118 }
1119
1121 options.write = true;
1123 auto result_or =
1124 SyncMessageSource(*dependencies_.project, incoming_path, options);
1125 source_sync_ready_ = false;
1126 source_sync_draft_sha_.clear();
1127 if (!result_or.ok()) {
1128 source_sync_status_ = std::string(result_or.status().message());
1130 return;
1131 }
1133 source_loaded_canonical_sha_ = result_or->proposed_source_sha256;
1134 source_sync_changed_ = false;
1136 result_or->wrote ? "Published the canonical bundle and ASM include. "
1137 "Rebuild before the patched ROM shows this text."
1138 : "Canonical source already matched; nothing written";
1141 absl::StrFormat("%s\n%s", result_or->canonical_bundle_path.string(),
1142 result_or->generated_asm_include_path.string());
1143}
1144
1148 ImGui::BeginDisabled(expanded_messages_.empty() ||
1149 !current_parse_errors_.empty());
1150 if (ImGui::Button(tr("Preview Publication"))) {
1152 }
1153 state.preview_disabled =
1154 (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled) != 0;
1155 ImGui::EndDisabled();
1156 ImGui::SameLine();
1157 ImGui::BeginDisabled(!source_sync_ready_ || !source_sync_changed_);
1158 if (ImGui::Button(tr("Publish"))) {
1159 ImGui::OpenPopup("Publish message source###PublishMessageSource");
1160 }
1161 state.publish_disabled =
1162 (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled) != 0;
1163 ImGui::EndDisabled();
1164 return state;
1165}
1166
1168 ImGui::Separator();
1170 if (!HasMessageSourceLayout()) {
1171 ImGui::TextWrapped(
1172 "%s",
1173 tr("Load a project whose hack manifest defines messages.source to "
1174 "publish expanded dialogue as a canonical bundle and ASM include."));
1175 return;
1176 }
1177
1178 const auto& source =
1180 ImGui::TextDisabled("%s", source.canonical_bundle_path.c_str());
1181 ImGui::TextDisabled("%s", source.generated_asm_include_path.c_str());
1182 ImGui::TextWrapped(
1183 "%s",
1184 tr("Preview checks capacity and the current source SHA without writing. "
1185 "Publish updates the bundle and generated include, not the ROM."));
1186
1188
1189 if (ImGui::BeginPopupModal("Publish message source###PublishMessageSource",
1190 nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
1191 ImGui::TextWrapped(
1192 "%s", tr("Write the expanded messages into the canonical bundle and "
1193 "generated ASM include. The ROM is not modified."));
1194 if (!source_sync_summary_.empty()) {
1195 ImGui::TextWrapped("%s", source_sync_summary_.c_str());
1196 }
1197 if (ImGui::Button(tr("Publish now"))) {
1199 ImGui::CloseCurrentPopup();
1200 }
1201 ImGui::SameLine();
1202 if (ImGui::Button(tr("Cancel"))) {
1203 ImGui::CloseCurrentPopup();
1204 }
1205 ImGui::EndPopup();
1206 }
1207
1208 if (!source_sync_status_.empty()) {
1209 const ImVec4 color = source_sync_status_error_ ? gui::GetErrorColor()
1211 ImGui::TextWrapped("%s", source_sync_status_.c_str());
1212 }
1213}
1214
1216 const bool can_navigate = current_parse_errors_.empty();
1217 ImGui::BeginDisabled(!can_navigate);
1218 if (ImGui::Button(ICON_MD_NAVIGATE_BEFORE "##prev_message")) {
1220 }
1221 gui::AutoRegisterLastItem("button", "MessagePrev");
1222 ImGui::EndDisabled();
1223 if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
1224 ImGui::SetTooltip("Previous message (Alt+Up)");
1225 }
1226 ImGui::SameLine();
1227 ImGui::BeginDisabled(!can_navigate);
1228 if (ImGui::Button(ICON_MD_NAVIGATE_NEXT "##next_message")) {
1230 }
1231 gui::AutoRegisterLastItem("button", "MessageNext");
1232 ImGui::EndDisabled();
1233 if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
1234 ImGui::SetTooltip("Next message (Alt+Down)");
1235 }
1236
1237 ImGui::SameLine();
1238 ImGui::Text("$%04X", CurrentDisplayId() & 0xFFFF);
1239 ImGui::SameLine();
1241 current_message_is_expanded_ ? tr("Expanded") : tr("Vanilla"),
1244 ImGui::SameLine();
1245 ImGui::TextDisabled("%s", util::HexLong(current_message_.Address).c_str());
1246 ImGui::SameLine();
1247 ImGui::TextDisabled("%zu B", current_message_.Data.size());
1248
1249 ImGui::SameLine();
1250 const std::string reference_now = CurrentReferenceText();
1251 if (!reference_now.empty() && reference_now != message_text_box_.text) {
1253 ImGui::SameLine();
1254 }
1255 const bool reference_visible =
1256 !reference_now.empty() &&
1258 reference_now != message_text_box_.text));
1259 if (ImGui::Button(reference_visible ? tr("Hide reference")
1260 : tr("Show reference"))) {
1261 show_reference_ = !reference_visible;
1263 }
1264 if (ImGui::IsItemHovered()) {
1265 ImGui::SetTooltip("Show the text from when this message was loaded.");
1266 }
1267 ImGui::SameLine();
1268 ImGui::BeginDisabled(reference_now == message_text_box_.text ||
1269 !current_parse_errors_.empty());
1270 if (ImGui::Button(tr("Accept"))) {
1272 }
1273 ImGui::EndDisabled();
1274 if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
1275 ImGui::SetTooltip(
1276 "Make the current draft the loaded reference for this message.");
1277 }
1278 ImGui::SameLine();
1279 if (ImGui::Button(ICON_MD_SEARCH "##toggle_find")) {
1282 }
1283 if (ImGui::IsItemHovered()) {
1284 ImGui::SetTooltip("Find and replace (F3 finds the next match)");
1285 }
1286 ImGui::SameLine();
1287 if (ImGui::Button(tr("Optimize"))) {
1289 }
1290 if (ImGui::IsItemHovered()) {
1291 ImGui::SetTooltip(
1292 "Replace dictionary phrases in this message with [D:XX] tokens.");
1293 }
1294}
1295
1297 gui::LayoutHelpers::BeginToolbar("##MessageListTools");
1299 const std::string path = util::FileDialogWrapper::ShowOpenFileDialog();
1300 if (!path.empty()) {
1302 }
1303 }
1304 if (ImGui::IsItemHovered()) {
1305 ImGui::SetTooltip("Import message bundle");
1306 }
1307 ImGui::SameLine();
1309 const std::string path = util::FileDialogWrapper::ShowSaveFileDialog();
1310 if (!path.empty()) {
1311 auto status =
1313 if (!status.ok()) {
1315 absl::StrFormat("Export failed: %s", status.message());
1317 } else {
1318 message_bundle_status_ = absl::StrFormat("Exported bundle: %s", path);
1320 }
1321 }
1322 }
1323 if (ImGui::IsItemHovered()) {
1324 ImGui::SetTooltip("Export message bundle");
1325 }
1327
1328 const float filter_row_width = ImGui::GetContentRegionAvail().x;
1329 const bool stack_filters = filter_row_width < 260.0f;
1330 const float bank_filter_width = std::min(110.0f, filter_row_width);
1331 ImGui::SetNextItemWidth(
1332 stack_filters ? filter_row_width
1333 : std::max(1.0f, filter_row_width - bank_filter_width -
1334 ImGui::GetStyle().ItemSpacing.x));
1335 ImGui::InputTextWithHint("##message_filter", "Filter by text, ID, or address",
1336 &list_filter_);
1337 if (!stack_filters) {
1338 ImGui::SameLine();
1339 }
1340 ImGui::SetNextItemWidth(bank_filter_width);
1341 ImGui::Combo("##message_bank", &list_bank_filter_,
1342 "All\0Vanilla\0Expanded\0");
1343
1344 if (!message_bundle_status_.empty()) {
1345 const ImVec4 color = message_bundle_status_error_ ? gui::GetErrorColor()
1347 ImGui::PushStyleColor(ImGuiCol_Text, color);
1348 ImGui::TextWrapped("%s", message_bundle_status_.c_str());
1349 ImGui::PopStyleColor();
1350 }
1351
1352 const std::vector<MessageRow> rows = CollectMessageRows(true);
1353 const int total = static_cast<int>(CollectMessageRows(false).size());
1354 ImGui::TextDisabled("%d / %d", static_cast<int>(rows.size()), total);
1355
1356 if (list_of_texts_.empty() && expanded_messages_.empty()) {
1358 "Load a ROM to edit dialogue.",
1359 nullptr, nullptr, true});
1360 return;
1361 }
1362 if (rows.empty()) {
1364 empty.icon = ICON_MD_SEARCH;
1365 empty.title = "No matches";
1366 empty.detail = "No messages match this filter.";
1367 empty.action_label = "Clear filter";
1368 empty.compact = true;
1369 empty.on_action = [this]() {
1370 list_filter_.clear();
1372 };
1373 gui::DrawEmptyState(empty);
1374 return;
1375 }
1376
1377 constexpr ImGuiTableFlags kListFlags =
1378 ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders |
1379 ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg |
1380 ImGuiTableFlags_ScrollY;
1381 if (!BeginTable("##MessagesTable", 4, kListFlags, ImVec2(0, 0))) {
1382 return;
1383 }
1384 TableSetupColumn("ID", ImGuiTableColumnFlags_WidthFixed, 64);
1385 const ImGuiTableColumnFlags bank_flags =
1386 ImGuiTableColumnFlags_WidthFixed |
1387 (expanded_messages_.empty() ? ImGuiTableColumnFlags_DefaultHide : 0);
1388 TableSetupColumn("Bank", bank_flags, 84);
1389 TableSetupColumn("Contents", ImGuiTableColumnFlags_WidthStretch);
1390 TableSetupColumn(
1391 "Address",
1392 ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide, 90);
1393 TableHeadersRow();
1394
1395 const int current_id = CurrentDisplayId();
1396 int target_row = -1;
1397 for (int i = 0; i < static_cast<int>(rows.size()); ++i) {
1398 if (rows[i].display_id == current_id &&
1399 rows[i].expanded == current_message_is_expanded_) {
1400 target_row = i;
1401 break;
1402 }
1403 }
1404
1405 if (scroll_list_to_selection_ && target_row < 0) {
1407 }
1408 ImGuiListClipper clipper;
1409 clipper.Begin(static_cast<int>(rows.size()));
1410 if (scroll_list_to_selection_ && target_row >= 0) {
1411 clipper.IncludeItemByIndex(target_row);
1412 }
1413 while (clipper.Step()) {
1414 for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; ++row) {
1415 const MessageRow& message = rows[row];
1416 const bool selected = row == target_row;
1417 ImGui::TableNextRow();
1418 TableNextColumn();
1419 // Scope every interactive cell, including repeated bank badges, by the
1420 // message identity so filtering does not transfer IDs between rows.
1421 ImGui::PushID(message.expanded ? "expanded" : "vanilla");
1422 ImGui::PushID(message.display_id);
1423 char id_label[16];
1424 std::snprintf(id_label, sizeof(id_label), "$%04X",
1425 message.display_id & 0xFFFF);
1426 if (ImGui::Selectable(id_label, selected,
1427 ImGuiSelectableFlags_SpanAllColumns |
1428 ImGuiSelectableFlags_AllowOverlap)) {
1429 if (!selected && !current_parse_errors_.empty()) {
1430 replace_status_ = "Resolve parse errors before switching messages";
1431 replace_status_error_ = true;
1432 find_panel_open_ = true;
1433 } else if (!selected) {
1435 OpenMessageById(message.display_id);
1436 }
1437 }
1438 gui::ItemContextMenu(nullptr, [this, display_id = message.display_id,
1439 address = message.address]() {
1440 std::vector<gui::MenuItemSpec> items;
1441 auto open_item = gui::MenuItemSpec::Conditional(
1442 "Open Message",
1443 [this, display_id]() {
1444 FinalizePendingUndo();
1445 OpenMessageById(display_id);
1446 },
1447 [this]() { return current_parse_errors_.empty(); });
1448 open_item.icon = ICON_MD_ARROW_FORWARD;
1449 open_item.separator_after = true;
1450 items.push_back(std::move(open_item));
1451 items.push_back(gui::CopyToClipboardItem("Copy Message ID",
1452 util::HexWord(display_id)));
1453 if (display_id >= 0 &&
1454 display_id < static_cast<int>(parsed_messages_.size())) {
1455 items.push_back(gui::CopyToClipboardItem(
1456 "Copy Text", parsed_messages_[display_id]));
1457 }
1458 items.push_back(
1459 gui::CopyToClipboardItem("Copy Address", util::HexLong(address)));
1460 return items;
1461 });
1462 if (selected && scroll_list_to_selection_) {
1463 ImGui::SetScrollHereY(0.25f);
1465 }
1466 TableNextColumn();
1467 if (message.expanded) {
1469 } else {
1470 ImGui::TextDisabled("%s", tr("Vanilla"));
1471 }
1472
1473 TableNextColumn();
1474 const std::string preview =
1475 MessageListPreview(ContentsForDisplayId(message.display_id));
1476 ImGui::TextUnformatted(preview.c_str());
1477
1478 TableNextColumn();
1479 ImGui::TextUnformatted(util::HexLong(message.address).c_str());
1480 ImGui::PopID();
1481 ImGui::PopID();
1482 }
1483 }
1484 EndTable();
1485}
1486
1487void MessageEditor::DrawMessageStructure() {
1488 if (!ImGui::CollapsingHeader(tr("Message Structure"),
1489 ImGuiTreeNodeFlags_DefaultOpen)) {
1490 return;
1491 }
1492 ImGui::Text(tr("Lines: %d"), message_preview_.text_line + 1);
1493
1494 int scroll_count = 0;
1495 int current_line_chars = 0;
1496 int line_num = 0;
1497 const ImVec4 line_color = gui::GetSuccessColor();
1498
1499 for (size_t i = 0; i < current_message_.Data.size(); i++) {
1500 const uint8_t byte = current_message_.Data[i];
1501 if (byte == kScrollVertical) {
1502 scroll_count++;
1503 ImGui::TextColored(gui::GetInfoColor(),
1504 tr(" [V] Scroll at byte %zu (line %d, %d chars)"), i,
1505 line_num, current_line_chars);
1506 current_line_chars = 0;
1507 line_num++;
1508 } else if (byte == kLine1) {
1509 ImGui::TextColored(line_color, tr(" [1] Line 1 at byte %zu"), i);
1510 current_line_chars = 0;
1511 line_num = 0;
1512 } else if (byte == kLine2) {
1513 ImGui::TextColored(line_color, tr(" [2] Line 2 at byte %zu"), i);
1514 current_line_chars = 0;
1515 line_num = 1;
1516 } else if (byte == kLine3) {
1517 ImGui::TextColored(line_color, tr(" [3] Line 3 at byte %zu"), i);
1518 current_line_chars = 0;
1519 line_num = 2;
1520 } else if (byte < 100) {
1521 current_line_chars++;
1522 }
1523 }
1524
1525 if (scroll_count == 0) {
1526 ImGui::TextDisabled(tr("No scroll breaks in this message"));
1527 } else {
1528 ImGui::Text(tr("Total scroll breaks: %d"), scroll_count);
1529 }
1530
1531 ImGui::Separator();
1532 ImGui::TextDisabled(tr("Line width budget (max ~170px):"));
1533 const int estimated_line_width = current_line_chars * 8;
1534 const float width_ratio = static_cast<float>(estimated_line_width) / 170.0f;
1535 const ImVec4 width_color = (width_ratio > 1.0f) ? gui::GetErrorColor()
1536 : (width_ratio > 0.85f) ? gui::GetWarningColor()
1538 ImGui::TextColored(width_color, tr("Last line: ~%dpx / 170px (%d chars)"),
1539 estimated_line_width, current_line_chars);
1540}
1541
1542void MessageEditor::DrawCurrentMessage() {
1543 DrawMessageHeader();
1544 DrawFindBar();
1545
1546 const float available = ImGui::GetContentRegionAvail().y;
1547 const float max_editor = std::max(96.0f, available - 160.0f);
1548 editor_pane_height_ = std::clamp(editor_pane_height_, 96.0f, max_editor);
1549
1550 if (ImGui::BeginChild("##MessageTextPane", ImVec2(0, editor_pane_height_),
1551 true)) {
1552 DrawDialogueTextPane(ImGui::GetContentRegionAvail().y);
1553 }
1554 ImGui::EndChild();
1555
1556 ImGui::InvisibleButton("##message_editor_split", ImVec2(-1.0f, 6.0f));
1557 if (ImGui::IsItemHovered() || ImGui::IsItemActive()) {
1558 ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);
1559 }
1560 if (ImGui::IsItemActive()) {
1561 editor_pane_height_ += ImGui::GetIO().MouseDelta.y;
1562 }
1563
1564 if (!current_parse_errors_.empty() || !current_parse_warnings_.empty()) {
1565 if (ImGui::BeginChild("##MessageDiagnostics", ImVec2(0, 72), true)) {
1566 if (!current_parse_errors_.empty()) {
1567 ImGui::TextColored(gui::GetErrorColor(), tr("Message parse errors"));
1568 for (const auto& error : current_parse_errors_) {
1569 ImGui::BulletText("%s", error.c_str());
1570 }
1571 }
1572 if (!current_parse_warnings_.empty()) {
1573 ImGui::TextColored(gui::GetWarningColor(),
1574 tr("Message parse warnings"));
1575 for (const auto& warning : current_parse_warnings_) {
1576 ImGui::BulletText("%s", warning.c_str());
1577 }
1578 }
1579 }
1580 ImGui::EndChild();
1581 }
1582 const auto line_warnings = ValidateMessageLineWidths(message_text_box_.text);
1583 if (!line_warnings.empty()) {
1584 ImGui::TextColored(gui::GetWarningColor(), tr("Line width warnings"));
1585 for (const auto& warning : line_warnings) {
1586 ImGui::BulletText("%s", warning.c_str());
1587 }
1588 }
1589
1590 gui::MemoryEditorPopup("Message Data", current_message_.Data);
1591
1592 if (ImGui::BeginChild("##MessagePreview", ImVec2(0, 0), true)) {
1593 EnsureFontTexturesReady();
1594 Text(tr("Message Preview"));
1595 ImGui::SameLine();
1596 if (Button(tr("View Palette"))) {
1597 ImGui::OpenPopup("Palette");
1598 }
1599 if (ImGui::BeginPopup("Palette")) {
1600 gui::DisplayPalette(font_preview_colors_, true);
1601 ImGui::EndPopup();
1602 }
1603 ImGui::SameLine();
1604 bool show_preview_grid = current_font_gfx16_canvas_.GetConfig().enable_grid;
1605 if (ImGui::Checkbox(tr("Grid"), &show_preview_grid)) {
1606 current_font_gfx16_canvas_.SetGridEnabled(show_preview_grid);
1607 }
1608
1610 const float available_width = ImGui::GetContentRegionAvail().x;
1611 const float scale =
1612 std::max(1.0f, std::floor(std::max(1.0f, available_width - 4.0f) /
1613 static_cast<float>(kCurrentMessageWidth)));
1614 const ImVec2 preview_size(kCurrentMessageWidth * scale,
1615 3.0f * 16.0f * scale);
1616 BeginChild("CurrentGfxFont", ImVec2(0, preview_size.y + 4.0f), true,
1617 ImGuiWindowFlags_NoScrollWithMouse);
1618 current_font_gfx16_canvas_.GetConfig().role =
1620 const float zoom = current_font_gfx16_canvas_.GetGlobalScale();
1621 // Context-menu zoom can update the config before the legacy canvas scale.
1622 current_font_gfx16_canvas_.set_global_scale(zoom);
1623 const ImVec2 frame_size(preview_size.x * zoom, preview_size.y * zoom);
1624 const float inset = std::max(
1625 0.0f, (ImGui::GetContentRegionAvail().x - frame_size.x) * 0.5f);
1626 ImGui::SetCursorPosX(ImGui::GetCursorPosX() + inset);
1627 // The viewport claims the wheel before the parent can scroll it.
1628 current_font_gfx16_canvas_.DrawBackground(preview_size, frame_size);
1629 const bool preview_hovered = ImGui::IsItemHovered();
1631 current_font_gfx16_canvas_.DrawContextMenu();
1632
1633 const int last_visible_line =
1634 std::min(std::max(0, message_preview_.text_line - 2),
1635 kCurrentMessageHeight / 16 - 3);
1636 message_preview_.shown_lines =
1637 std::clamp(message_preview_.shown_lines, 0, last_visible_line);
1638 if (preview_hovered) {
1639 const float wheel = ImGui::GetIO().MouseWheel;
1640 if (wheel > 0 && message_preview_.shown_lines > 0) {
1641 message_preview_.shown_lines--;
1642 } else if (wheel < 0 &&
1643 message_preview_.shown_lines < last_visible_line) {
1644 message_preview_.shown_lines++;
1645 }
1646 ImGui::SetTooltip("Scroll the preview with the mouse wheel");
1647 }
1648
1649 const ImVec2 frame_origin = current_font_gfx16_canvas_.zero_point();
1650 const ImVec2 scroll = current_font_gfx16_canvas_.scrolling();
1651 const ImVec2 preview_origin(frame_origin.x + scroll.x,
1652 frame_origin.y + scroll.y);
1653 ImDrawList* preview_draw_list = ImGui::GetWindowDrawList();
1654 preview_draw_list->PushClipRect(
1655 frame_origin,
1656 ImVec2(frame_origin.x + frame_size.x, frame_origin.y + frame_size.y),
1657 true);
1658 preview_draw_list->AddRectFilled(preview_origin,
1659 ImVec2(preview_origin.x + frame_size.x,
1660 preview_origin.y + frame_size.y),
1661 IM_COL32(0, 0, 0, 255));
1662 current_font_gfx16_canvas_.DrawBitmap(
1663 current_font_gfx16_bitmap_, scroll, frame_size,
1664 ImVec2(0, message_preview_.shown_lines * 16.0f),
1665 ImVec2(static_cast<float>(kCurrentMessageWidth), 3.0f * 16.0f));
1666
1667 if (current_font_gfx16_canvas_.GetConfig().enable_grid) {
1668 ImDrawList* overlay_draw_list = ImGui::GetWindowDrawList();
1669 const float line_height = 16.0f;
1670 const ImU32 marker_color =
1671 ImGui::ColorConvertFloat4ToU32(gui::GetInfoColor());
1672 for (int marker_line : message_preview_.scroll_marker_lines) {
1673 const float src_y =
1674 (marker_line - message_preview_.shown_lines) * line_height;
1675 const float y = preview_origin.y + src_y * scale * zoom;
1676 if (y >= frame_origin.y && y <= frame_origin.y + frame_size.y) {
1677 overlay_draw_list->AddLine(ImVec2(preview_origin.x, y),
1678 ImVec2(preview_origin.x + frame_size.x, y),
1679 marker_color, 1.5f);
1680 overlay_draw_list->AddText(
1681 ImVec2(preview_origin.x + frame_size.x - 20, y - 6), marker_color,
1682 "[V]");
1683 }
1684 }
1685 }
1686 preview_draw_list->PopClipRect();
1687
1688 if (current_font_gfx16_canvas_.GetConfig().enable_grid) {
1689 current_font_gfx16_canvas_.DrawGrid();
1690 }
1691 current_font_gfx16_canvas_.DrawOverlay();
1692 EndChild();
1693 DrawMessageStructure();
1694 }
1695 ImGui::EndChild();
1696}
1697
1698void MessageEditor::DrawExpandedMessageSettings() {
1699 ImGui::Separator();
1700 gui::SectionHeader(ICON_MD_LIBRARY_ADD, tr("Expanded Messages"),
1702
1703 if (HasMessageSourceLayout()) {
1704 ImGui::TextWrapped(
1705 "%s",
1706 tr("Expanded dialogue loads automatically from the project bundle. "
1707 "Reload it after resolving a source error. Inspecting the built ROM "
1708 "uses the "
1709 "manifest data range and does not replace the canonical source."));
1710 if (ImGui::Button(tr("Load canonical source"))) {
1711 const auto status = LoadCanonicalExpandedSource();
1712 if (!status.ok()) {
1713 message_bundle_status_ = std::string(status.message());
1714 message_bundle_status_error_ = true;
1715 }
1716 }
1717 ImGui::SameLine();
1718 }
1719 if (ImGui::Button(HasMessageSourceLayout() ? tr("Inspect built ROM")
1720 : tr("Load from ROM"))) {
1721 auto status = LoadExpandedMessagesFromRom();
1722 if (!status.ok()) {
1723 LOG_WARN("MessageEditor", "Load from ROM: %s",
1724 std::string(status.message()).c_str());
1725 message_bundle_status_ =
1726 absl::StrFormat("Load from ROM failed: %s", status.message());
1727 message_bundle_status_error_ = true;
1728 }
1729 }
1730 ImGui::SameLine();
1731 if (ImGui::Button(tr("Load from File"))) {
1733 if (!path.empty()) {
1734 const auto status = LoadExpandedMessagesFromBin(path);
1735 if (!status.ok()) {
1736 message_bundle_status_ = std::string(status.message());
1737 message_bundle_status_error_ = true;
1738 if (auto* popup_manager = dependencies_.popup_manager) {
1739 popup_manager->Show("Error");
1740 }
1741 }
1742 }
1743 }
1744
1745 if (expanded_messages_.empty()) {
1746 ImGui::TextDisabled(
1747 tr("No expanded bank loaded. Vanilla dialogue is still editable."));
1748 return;
1749 }
1750
1751 ImGui::Text(tr("Source: %s"), expanded_message_path_.c_str());
1752 ImGui::Text(tr("Messages: %lu"), expanded_messages_.size());
1753
1754 const auto inspection_range = ExpandedInspectionRange();
1755 const int capacity = inspection_range.second - inspection_range.first + 1;
1756 const int used = CalculateExpandedBankUsage();
1757 const int remaining = capacity - used;
1758 const float usage_ratio =
1759 capacity > 0 ? static_cast<float>(used) / static_cast<float>(capacity)
1760 : 1.0f;
1761 const ImVec4 capacity_color = (usage_ratio < 0.75f) ? gui::GetSuccessColor()
1762 : (usage_ratio < 0.90f) ? gui::GetWarningColor()
1764 {
1765 gui::StyleColorGuard capacity_style(ImGuiCol_PlotHistogram, capacity_color);
1766 char capacity_label[64];
1767 std::snprintf(capacity_label, sizeof(capacity_label), "%d / %d bytes", used,
1768 capacity);
1769 ImGui::ProgressBar(std::clamp(usage_ratio, 0.0f, 1.0f), ImVec2(-1, 0),
1770 capacity_label);
1771 }
1772 ImGui::TextDisabled(tr("%d bytes free"), remaining);
1773
1774 if (ImGui::Button(tr("Add New Message"))) {
1775 MessageData new_message;
1776 new_message.ID = expanded_messages_.back().ID + 1;
1777 new_message.Address =
1778 expanded_messages_.back().Address +
1779 static_cast<int>(expanded_messages_.back().Data.size());
1780 expanded_messages_.push_back(new_message);
1781 MarkDomainDirty(SaveDomain::kExpandedMessages);
1782 const int display_id = expanded_message_base_id_ + new_message.ID;
1783 if (display_id >= 0 &&
1784 static_cast<size_t>(display_id) >= parsed_messages_.size()) {
1785 parsed_messages_.resize(display_id + 1);
1786 }
1787 if (current_parse_errors_.empty()) {
1788 FinalizePendingUndo();
1789 OpenMessageById(display_id);
1790 }
1791 }
1792 ImGui::SameLine();
1793 if (ImGui::Button(tr("Export to JSON"))) {
1795 if (!path.empty()) {
1796 PRINT_IF_ERROR(ExportMessagesToJson(path, expanded_messages_));
1797 }
1798 }
1799
1800 DrawMessageSourceSync();
1801}
1802
1803void MessageEditor::DrawTokenInserter(const std::vector<TextElement>& elements,
1804 std::string& filter, bool use_parameter) {
1805 ImGui::SetNextItemWidth(-1);
1806 ImGui::InputTextWithHint("##token_filter", "Filter tokens", &filter);
1807 if (!BeginTable("##TokenInserter", 2, kMessageTableFlags, ImVec2(0, 0))) {
1808 return;
1809 }
1810 TableSetupColumn("Token", ImGuiTableColumnFlags_WidthFixed, 110);
1811 TableSetupColumn("Description", ImGuiTableColumnFlags_WidthStretch);
1812 TableHeadersRow();
1813 for (const auto& text_element : elements) {
1814 if (!filter.empty() &&
1815 !ContainsCaseInsensitive(text_element.GenericToken, filter) &&
1816 !ContainsCaseInsensitive(text_element.Description, filter)) {
1817 continue;
1818 }
1819 ImGui::TableNextRow();
1820 TableNextColumn();
1821 ImGui::PushID(text_element.ID);
1822 const std::string token =
1823 use_parameter ? text_element.GetParamToken(command_parameter_)
1824 : text_element.GenericToken;
1825 if (ImGui::Selectable(text_element.GenericToken.c_str(), false,
1826 ImGuiSelectableFlags_SpanAllColumns)) {
1827 InsertTokenAtCursor(token);
1828 }
1829 if (ImGui::IsItemHovered()) {
1830 ImGui::SetTooltip("Insert %s", token.c_str());
1831 }
1832 ImGui::PopID();
1833 TableNextColumn();
1834 TextWrapped("%s", text_element.Description.c_str());
1835 }
1836 EndTable();
1837}
1838
1839void MessageEditor::DrawTextCommands() {
1840 gui::InputHexByte("Command Parameter", &command_parameter_);
1841 if (ImGui::IsItemHovered()) {
1842 ImGui::SetTooltip("Argument byte for commands such as [W:02] or [SPD:00].");
1843 }
1844 DrawTokenInserter(TextCommands, command_filter_, true);
1845}
1846
1847void MessageEditor::DrawSpecialCharacters() {
1848 DrawTokenInserter(SpecialChars, symbol_filter_, false);
1849}
1850
1851void MessageEditor::DrawDictionary() {
1852 ImGui::SetNextItemWidth(-1);
1853 ImGui::InputTextWithHint("##dictionary_filter", "Filter dictionary",
1854 &dictionary_filter_);
1855 std::vector<int> visible;
1856 visible.reserve(message_preview_.all_dictionaries_.size());
1857 for (int i = 0;
1858 i < static_cast<int>(message_preview_.all_dictionaries_.size()); ++i) {
1859 const auto& dictionary = message_preview_.all_dictionaries_[i];
1860 if (!dictionary_filter_.empty() &&
1861 !ContainsCaseInsensitive(dictionary.Contents, dictionary_filter_) &&
1862 !ContainsCaseInsensitive(dictionary.Token, dictionary_filter_)) {
1863 continue;
1864 }
1865 visible.push_back(i);
1866 }
1867 if (visible.empty()) {
1868 ImGui::TextDisabled(tr("No dictionary entries match."));
1869 return;
1870 }
1871 if (!BeginTable("##Dictionary", 3,
1872 kMessageTableFlags | ImGuiTableFlags_ScrollY, ImVec2(0, 0))) {
1873 return;
1874 }
1875 TableSetupColumn("Token", ImGuiTableColumnFlags_WidthFixed, 72);
1876 TableSetupColumn("Text", ImGuiTableColumnFlags_WidthStretch);
1877 TableSetupColumn("Len", ImGuiTableColumnFlags_WidthFixed, 40);
1878 TableHeadersRow();
1879
1880 ImGuiListClipper clipper;
1881 clipper.Begin(static_cast<int>(visible.size()));
1882 while (clipper.Step()) {
1883 for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; ++row) {
1884 const auto& dictionary = message_preview_.all_dictionaries_[visible[row]];
1885 ImGui::TableNextRow();
1886 TableNextColumn();
1887 ImGui::PushID(dictionary.ID);
1888 if (ImGui::Selectable(dictionary.Token.c_str(), false,
1889 ImGuiSelectableFlags_SpanAllColumns)) {
1890 InsertTokenAtCursor(dictionary.Token);
1891 }
1892 if (ImGui::IsItemHovered()) {
1893 ImGui::SetTooltip("Insert %s", dictionary.Token.c_str());
1894 }
1895 ImGui::PopID();
1896 TableNextColumn();
1897 Text("%s", dictionary.Contents.c_str());
1898 TableNextColumn();
1899 Text("%d", dictionary.Length);
1900 }
1901 }
1902 EndTable();
1903}
1904
1905void MessageEditor::DrawMessageTools() {
1906 if (!ImGui::BeginTabBar("##MessageTools")) {
1907 return;
1908 }
1909 if (ImGui::BeginTabItem(tr("Commands"))) {
1910 DrawTextCommands();
1911 ImGui::EndTabItem();
1912 }
1913 if (ImGui::BeginTabItem(tr("Symbols"))) {
1914 DrawSpecialCharacters();
1915 ImGui::EndTabItem();
1916 }
1917 if (ImGui::BeginTabItem(tr("Dictionary"))) {
1918 DrawDictionary();
1919 ImGui::EndTabItem();
1920 }
1921 ImGui::EndTabBar();
1922}
1923void MessageEditor::UpdateCurrentMessageFromText(const std::string& text) {
1924 PushUndoSnapshot();
1925
1926 MarkDomainDirty(current_message_is_expanded_ ? SaveDomain::kExpandedMessages
1927 : SaveDomain::kVanillaMessages);
1928
1929 auto parse_result = ParseMessageToDataWithDiagnostics(text);
1930 current_parse_errors_ = parse_result.errors;
1931 current_parse_warnings_ = parse_result.warnings;
1932 if (!parse_result.ok()) {
1933 return;
1934 }
1935
1936 std::string raw_text = text;
1937 raw_text.erase(std::remove(raw_text.begin(), raw_text.end(), '\n'),
1938 raw_text.end());
1939
1940 current_message_.RawString = raw_text;
1941 current_message_.ContentsParsed = text;
1942 current_message_.Data = std::move(parse_result.bytes);
1943
1944 int parsed_index = current_message_index_;
1945 if (current_message_is_expanded_) {
1946 parsed_index = expanded_message_base_id_ + current_message_index_;
1947 }
1948
1949 if (parsed_index >= 0) {
1950 if (static_cast<size_t>(parsed_index) >= parsed_messages_.size()) {
1951 parsed_messages_.resize(parsed_index + 1);
1952 }
1953 parsed_messages_[parsed_index] = text;
1954 }
1955
1956 if (current_message_is_expanded_) {
1957 if (current_message_index_ >= 0 &&
1958 current_message_index_ < static_cast<int>(expanded_messages_.size())) {
1959 expanded_messages_[current_message_index_] = current_message_;
1960 }
1961 } else {
1962 if (current_message_index_ >= 0 &&
1963 current_message_index_ < static_cast<int>(list_of_texts_.size())) {
1964 list_of_texts_[current_message_index_] = current_message_;
1965 }
1966 }
1967
1968 DrawMessagePreview();
1969}
1970
1971void MessageEditor::ImportMessageBundleFromFile(const std::string& path) {
1972 message_bundle_status_.clear();
1973 message_bundle_status_error_ = false;
1974
1975 auto entries_or = LoadMessageBundleFromJson(path);
1976 if (!entries_or.ok()) {
1977 message_bundle_status_ =
1978 absl::StrFormat("Import failed: %s", entries_or.status().message());
1979 message_bundle_status_error_ = true;
1980 return;
1981 }
1982
1983 const ExpandedDraftSnapshot snapshot = CaptureExpandedDraft();
1984 const bool rom_dirty_before = rom_ && rom_->dirty();
1985 const bool importing_canonical = IsCanonicalBundlePath(path);
1986 std::string canonical_sha;
1987 if (importing_canonical) {
1988 const auto sha_or = HashFileSha256(std::filesystem::path(path));
1989 if (!sha_or.ok()) {
1990 message_bundle_status_ = std::string(sha_or.status().message());
1991 message_bundle_status_error_ = true;
1992 return;
1993 }
1994 canonical_sha = sha_or.value();
1995 }
1996
1997 int applied = 0;
1998 int errors = 0;
1999 int warnings = 0;
2000 int duplicate_errors = 0;
2001 int parse_error_entries = 0;
2002 int vanilla_updated = 0;
2003 int expanded_updated = 0;
2004 int expanded_created = 0;
2005 bool expanded_modified = false;
2006 std::vector<std::string> issue_samples;
2007
2008 auto add_issue_sample = [&issue_samples](const std::string& issue) {
2009 constexpr size_t kMaxIssueSamples = 4;
2010 if (issue_samples.size() < kMaxIssueSamples) {
2011 issue_samples.push_back(issue);
2012 }
2013 };
2014
2015 auto make_entry_key = [](const MessageBundleEntry& entry) {
2016 return absl::StrFormat("%s:%d", MessageBankToString(entry.bank), entry.id);
2017 };
2018
2019 std::unordered_map<std::string, int> seen_entries;
2020
2021 auto entries = entries_or.value();
2022 for (const auto& entry : entries) {
2023 const std::string entry_key = make_entry_key(entry);
2024 if (seen_entries.find(entry_key) != seen_entries.end()) {
2025 errors++;
2026 duplicate_errors++;
2027 add_issue_sample(absl::StrFormat("Duplicate entry for %s", entry_key));
2028 continue;
2029 }
2030 seen_entries.emplace(entry_key, 1);
2031
2032 auto parse_result = ParseMessageToDataWithDiagnostics(entry.text);
2033 auto line_warnings = ValidateMessageLineWidths(entry.text);
2034 warnings += static_cast<int>(parse_result.warnings.size());
2035 warnings += static_cast<int>(line_warnings.size());
2036
2037 if (!parse_result.ok()) {
2038 errors++;
2039 parse_error_entries++;
2040 if (!parse_result.errors.empty()) {
2041 add_issue_sample(absl::StrFormat("Parse error for %s: %s", entry_key,
2042 parse_result.errors.front()));
2043 } else {
2044 add_issue_sample(absl::StrFormat("Parse error for %s", entry_key));
2045 }
2046 continue;
2047 }
2048
2049 if (entry.bank == MessageBank::kVanilla) {
2050 if (entry.id < 0 || entry.id >= static_cast<int>(list_of_texts_.size())) {
2051 errors++;
2052 add_issue_sample(
2053 absl::StrFormat("Vanilla ID out of range: %d", entry.id));
2054 continue;
2055 }
2056 auto& message = list_of_texts_[entry.id];
2057 message.RawString = entry.text;
2058 message.ContentsParsed = entry.text;
2059 message.Data = parse_result.bytes;
2060 message.DataParsed = parse_result.bytes;
2061 if (entry.id >= 0 &&
2062 entry.id < static_cast<int>(parsed_messages_.size())) {
2063 parsed_messages_[entry.id] = entry.text;
2064 }
2065 vanilla_updated++;
2066 applied++;
2067 } else {
2068 if (entry.id < 0) {
2069 errors++;
2070 add_issue_sample(
2071 absl::StrFormat("Expanded ID out of range: %d", entry.id));
2072 continue;
2073 }
2074 if (entry.id >= static_cast<int>(expanded_messages_.size())) {
2075 const int old_size = static_cast<int>(expanded_messages_.size());
2076 const int target_size = entry.id + 1;
2077 expanded_messages_.resize(target_size);
2078 for (int i = old_size; i < target_size; ++i) {
2079 expanded_messages_[i].ID = i;
2080 }
2081 expanded_created += target_size - old_size;
2082 }
2083 auto& message = expanded_messages_[entry.id];
2084 message.RawString = entry.text;
2085 message.ContentsParsed = entry.text;
2086 message.Data = parse_result.bytes;
2087 message.DataParsed = parse_result.bytes;
2088 const int parsed_index = expanded_message_base_id_ + entry.id;
2089 if (parsed_index >= 0) {
2090 if (static_cast<size_t>(parsed_index) >= parsed_messages_.size()) {
2091 parsed_messages_.resize(parsed_index + 1);
2092 }
2093 parsed_messages_[parsed_index] = entry.text;
2094 }
2095 expanded_modified = true;
2096 expanded_updated++;
2097 applied++;
2098 }
2099 }
2100
2101 if (expanded_modified) {
2102 int pos = ExpandedInspectionRange().first;
2103 for (auto& message : expanded_messages_) {
2104 message.Address = pos;
2105 pos += static_cast<int>(message.Data.size()) + 1;
2106 }
2107 }
2108
2109 if (errors > 0) {
2110 message_bundle_status_ = absl::StrFormat(
2111 "Import finished with %d errors (%d applied: vanilla %d updated, "
2112 "expanded %d updated/%d created; %d warnings, %d duplicates, %d "
2113 "parse failures).",
2114 errors, applied, vanilla_updated, expanded_updated, expanded_created,
2115 warnings, duplicate_errors, parse_error_entries);
2116 if (!issue_samples.empty()) {
2117 message_bundle_status_ = absl::StrFormat(
2118 "%s Example: %s", message_bundle_status_, issue_samples.front());
2119 }
2120 message_bundle_status_error_ = true;
2121 } else {
2122 message_bundle_status_ = absl::StrFormat(
2123 "Imported %d messages (vanilla %d updated, expanded %d updated/%d "
2124 "created, %d warnings).",
2125 applied, vanilla_updated, expanded_updated, expanded_created, warnings);
2126 }
2127 if (errors > 0) {
2128 RestoreExpandedDraft(snapshot);
2129 if (rom_) {
2130 rom_->set_dirty(rom_dirty_before);
2131 }
2132 return;
2133 }
2134 int current_display_id = current_message_index_;
2135 if (current_message_is_expanded_) {
2136 current_display_id = expanded_message_base_id_ + current_message_index_;
2137 }
2138 if (current_display_id >= 0) {
2139 OpenMessageById(current_display_id);
2140 }
2141 if (vanilla_updated > 0) {
2142 MarkDomainDirty(SaveDomain::kVanillaMessages);
2143 }
2144 if (expanded_modified) {
2145 if (importing_canonical) {
2146 source_loaded_canonical_sha_ = canonical_sha;
2147 dirty_state_.expanded_messages = false;
2148 InvalidateSourcePreview();
2149 expanded_message_path_ = path;
2150 } else {
2151 source_loaded_canonical_sha_.clear();
2152 MarkDomainDirty(SaveDomain::kExpandedMessages);
2153 }
2154 }
2155}
2156
2157void MessageEditor::DrawMessagePreview() {
2158 // Render the message to the preview bitmap
2159 message_preview_.DrawMessagePreview(current_message_);
2160
2161 // Validate preview data before updating
2162 if (message_preview_.current_preview_data_.empty()) {
2163 LOG_WARN("MessageEditor", "Preview data is empty, skipping bitmap update");
2164 return;
2165 }
2166
2167 if (current_font_gfx16_bitmap_.is_active()) {
2168 // CRITICAL: Use set_data() to properly update both data_ AND surface_
2169 // mutable_data() returns a reference but doesn't update the surface!
2170 current_font_gfx16_bitmap_.set_data(message_preview_.current_preview_data_);
2171
2172 if (current_font_gfx16_bitmap_.palette().empty() &&
2173 !font_preview_colors_.empty()) {
2174 current_font_gfx16_bitmap_.SetPalette(font_preview_colors_);
2175 }
2176
2177 // Validate surface was updated
2178 if (!current_font_gfx16_bitmap_.surface()) {
2179 LOG_ERROR("MessageEditor", "Bitmap surface is null after set_data()");
2180 return;
2181 }
2182
2183 // Queue texture update (or create if missing) so changes are visible
2184 const auto command = current_font_gfx16_bitmap_.texture()
2187 gfx::Arena::Get().QueueTextureCommand(command, &current_font_gfx16_bitmap_);
2188
2189 LOG_DEBUG(
2190 "MessageEditor",
2191 "Updated message preview bitmap (size: %zu) and queued texture update",
2192 message_preview_.current_preview_data_.size());
2193 } else {
2194 // Create bitmap and queue texture creation with 8-bit indexed depth
2195 current_font_gfx16_bitmap_.Create(kCurrentMessageWidth,
2197 message_preview_.current_preview_data_);
2198 current_font_gfx16_bitmap_.SetPalette(font_preview_colors_);
2200 gfx::Arena::TextureCommandType::CREATE, &current_font_gfx16_bitmap_);
2201
2202 LOG_INFO("MessageEditor",
2203 "Created message preview bitmap (%dx%d) with 8-bit depth and "
2204 "queued texture creation",
2206 }
2207}
2208
2209absl::Status MessageEditor::Save() {
2210 if (!rom_ || !rom_->is_loaded()) {
2211 return absl::FailedPreconditionError("ROM not loaded");
2212 }
2213 if (!current_parse_errors_.empty()) {
2214 return absl::FailedPreconditionError(absl::StrFormat(
2215 "Current message has parse errors: %s", current_parse_errors_.front()));
2216 }
2217
2218 return SaveDirtyDomains(/*include_font_widths=*/true,
2219 /*include_vanilla_messages=*/true,
2220 /*include_expanded_messages=*/true);
2221}
2222
2223absl::StatusOr<MessageEditor::SavePlan> MessageEditor::BuildSavePlan(
2224 bool include_font_widths, bool include_vanilla_messages,
2225 bool include_expanded_messages) const {
2226 if (!rom_ || !rom_->is_loaded()) {
2227 return absl::FailedPreconditionError("ROM not loaded");
2228 }
2229
2230 SavePlan plan;
2231
2232 if (include_font_widths && dirty_state_.font_widths) {
2233 plan.saves_font_widths = true;
2234 plan.writes.push_back(
2235 {SaveDomain::kFontWidths, kCharactersWidth,
2236 std::vector<uint8_t>(message_preview_.width_array.begin(),
2237 message_preview_.width_array.end())});
2238 }
2239
2240 if (include_vanilla_messages && dirty_state_.vanilla_messages) {
2241 std::optional<size_t> expected_message_count;
2242 if (dependencies_.project &&
2243 dependencies_.project->hack_manifest.loaded()) {
2244 const int manifest_count =
2245 dependencies_.project->hack_manifest.message_layout().vanilla_count;
2246 if (manifest_count > 0) {
2247 expected_message_count = static_cast<size_t>(manifest_count);
2248 }
2249 }
2251 const VanillaMessageSavePlan vanilla_plan,
2252 BuildVanillaMessageSavePlan(list_of_texts_, expected_message_count));
2253
2254 plan.saves_vanilla_messages = true;
2255 for (const auto& write : vanilla_plan.writes()) {
2256 plan.writes.push_back(
2257 {SaveDomain::kVanillaMessages, write.start(), write.bytes()});
2258 }
2259 }
2260
2261 if (include_expanded_messages && dirty_state_.expanded_messages &&
2262 !expanded_messages_.empty()) {
2263 const auto range = ExpandedInspectionRange();
2264 const int start = range.first;
2265 const int end = range.second;
2266 if (start < 0 || end < start) {
2267 return absl::InvalidArgumentError("Invalid expanded message region");
2268 }
2269 if (static_cast<uint64_t>(start) >= rom_->size() ||
2270 static_cast<uint64_t>(end) >= rom_->size()) {
2271 return absl::OutOfRangeError(
2272 "Expanded message region is outside the ROM");
2273 }
2274
2275 const int64_t capacity = static_cast<int64_t>(end) - start + 1;
2276 std::vector<uint8_t> bytes;
2277 bytes.reserve(static_cast<size_t>(capacity));
2278 plan.expanded_message_addresses.reserve(expanded_messages_.size());
2279
2280 for (size_t index = 0; index < expanded_messages_.size(); ++index) {
2281 const auto& message = expanded_messages_[index];
2282 auto parsed = ParseMessageToDataWithDiagnostics(message.RawString);
2283 if (!parsed.ok()) {
2284 return absl::InvalidArgumentError(
2285 absl::StrFormat("Expanded message %d is invalid: %s",
2286 static_cast<int>(index), parsed.errors.front()));
2287 }
2288 if (message.RawString.find("[BANK]") != std::string::npos) {
2289 return absl::InvalidArgumentError(absl::StrFormat(
2290 "Expanded message %d contains [BANK], which is only valid in the "
2291 "vanilla message stream",
2292 static_cast<int>(index)));
2293 }
2294
2295 const int64_t needed = static_cast<int64_t>(parsed.bytes.size()) + 1;
2296 if (static_cast<int64_t>(bytes.size()) + needed + 1 > capacity) {
2297 return absl::ResourceExhaustedError(absl::StrFormat(
2298 "Expanded message data exceeds bank boundary "
2299 "(at message %d, used=%d, needed=%d, capacity=%d, end=0x%06X)",
2300 static_cast<int>(index), static_cast<int>(bytes.size()),
2301 static_cast<int>(needed), static_cast<int>(capacity), end));
2302 }
2303
2304 plan.expanded_message_addresses.push_back(start +
2305 static_cast<int>(bytes.size()));
2306 bytes.insert(bytes.end(), parsed.bytes.begin(), parsed.bytes.end());
2307 bytes.push_back(kMessageTerminator);
2308 }
2309 bytes.push_back(0xFF);
2310
2311 plan.saves_expanded_messages = true;
2312 plan.writes.push_back({SaveDomain::kExpandedMessages,
2313 static_cast<uint32_t>(start), std::move(bytes)});
2314 }
2315
2316 for (const auto& write : plan.writes) {
2317 const uint64_t end =
2318 static_cast<uint64_t>(write.start) + write.bytes.size();
2319 if (end > rom_->size() || end > std::numeric_limits<uint32_t>::max()) {
2320 return absl::OutOfRangeError(absl::StrFormat(
2321 "Message save range [0x%06X, 0x%06llX) is outside the ROM",
2322 write.start, static_cast<unsigned long long>(end)));
2323 }
2324 }
2325
2326 return plan;
2327}
2328
2329absl::Status MessageEditor::ValidateSavePlan(const SavePlan& plan) const {
2330 if (!dependencies_.project ||
2331 !dependencies_.project->hack_manifest.loaded() || plan.writes.empty()) {
2332 return absl::OkStatus();
2333 }
2334
2335 std::vector<std::pair<uint32_t, uint32_t>> ranges;
2336 ranges.reserve(plan.writes.size());
2337 for (const auto& write : plan.writes) {
2338 ranges.emplace_back(write.start, write.end());
2339 }
2340
2341 const auto& yaze_project = *dependencies_.project;
2342 if (yaze_project.rom_metadata.write_policy ==
2345 absl::StrContains(yaze_project.hack_manifest.hack_name(),
2346 "Oracle of Secrets")) {
2347 return absl::PermissionDeniedError(kOracleExpandedRomWriteRefusal);
2348 }
2349
2350 const auto status = ValidateHackManifestSaveConflicts(
2351 yaze_project.hack_manifest, yaze_project.rom_metadata.write_policy,
2352 ranges, "message data", "MessageEditor", dependencies_.toast_manager);
2353 return status;
2354}
2355
2356absl::Status MessageEditor::ApplySavePlan(const SavePlan& plan) {
2357 if (plan.writes.empty()) {
2358 return absl::OkStatus();
2359 }
2360
2362 for (const auto& write : plan.writes) {
2363 const char* label = "MessageData";
2364 switch (write.domain) {
2365 case SaveDomain::kFontWidths:
2366 label = "MessageFontWidths";
2367 break;
2368 case SaveDomain::kVanillaMessages:
2369 label = "VanillaMessageBank";
2370 break;
2371 case SaveDomain::kExpandedMessages:
2372 label = "ExpandedMessageBank";
2373 break;
2374 }
2375 RETURN_IF_ERROR(fence.Allow(write.start, write.end(), label));
2376 }
2377
2378 ScopedRomTransaction transaction(*rom_);
2379 yaze::rom::ScopedWriteFence fence_scope(rom_, &fence);
2380 for (const auto& write : plan.writes) {
2382 rom_->WriteVector(static_cast<int>(write.start), write.bytes));
2383 }
2384 transaction.Commit();
2385
2386 if (plan.saves_expanded_messages) {
2387 for (size_t index = 0; index < expanded_messages_.size() &&
2388 index < plan.expanded_message_addresses.size();
2389 ++index) {
2390 expanded_messages_[index].Address =
2391 plan.expanded_message_addresses[index];
2392 }
2393 SyncCurrentExpandedMessageAddress();
2394 }
2395
2396 return absl::OkStatus();
2397}
2398
2399absl::Status MessageEditor::SaveDirtyDomains(bool include_font_widths,
2400 bool include_vanilla_messages,
2401 bool include_expanded_messages) {
2402 ASSIGN_OR_RETURN(const SavePlan plan,
2403 BuildSavePlan(include_font_widths, include_vanilla_messages,
2404 include_expanded_messages));
2405 RETURN_IF_ERROR(ValidateSavePlan(plan));
2406 RETURN_IF_ERROR(ApplySavePlan(plan));
2407 RecordSavedDomains(plan);
2408 return absl::OkStatus();
2409}
2410
2411absl::Status MessageEditor::SaveExpandedMessages() {
2412 return SaveDirtyDomains(/*include_font_widths=*/false,
2413 /*include_vanilla_messages=*/false,
2414 /*include_expanded_messages=*/true);
2415}
2416
2417absl::Status MessageEditor::BeginSaveTransaction() {
2418 if (save_transaction_active_) {
2419 return absl::FailedPreconditionError(
2420 "Message save transaction is already active");
2421 }
2422 transaction_dirty_snapshot_ = dirty_state_;
2423 transaction_saved_domains_ = {};
2424 transaction_expanded_address_snapshot_.clear();
2425 transaction_expanded_address_snapshot_.reserve(expanded_messages_.size());
2426 for (const auto& message : expanded_messages_) {
2427 transaction_expanded_address_snapshot_.push_back(message.Address);
2428 }
2429 save_transaction_active_ = true;
2430 return absl::OkStatus();
2431}
2432
2433void MessageEditor::RollbackSaveTransaction() {
2434 if (!save_transaction_active_) {
2435 return;
2436 }
2437 dirty_state_ = transaction_dirty_snapshot_;
2438 for (size_t index = 0; index < expanded_messages_.size() &&
2439 index < transaction_expanded_address_snapshot_.size();
2440 ++index) {
2441 expanded_messages_[index].Address =
2442 transaction_expanded_address_snapshot_[index];
2443 }
2444 SyncCurrentExpandedMessageAddress();
2445 transaction_dirty_snapshot_ = {};
2446 transaction_saved_domains_ = {};
2447 transaction_expanded_address_snapshot_.clear();
2448 save_transaction_active_ = false;
2449}
2450
2451void MessageEditor::CommitSaveTransaction() {
2452 if (!save_transaction_active_) {
2453 return;
2454 }
2455 ClearSavedDomains(transaction_saved_domains_);
2456 transaction_dirty_snapshot_ = {};
2457 transaction_saved_domains_ = {};
2458 transaction_expanded_address_snapshot_.clear();
2459 save_transaction_active_ = false;
2460}
2461
2462void MessageEditor::MarkDomainDirty(SaveDomain domain) {
2463 bool* dirty = nullptr;
2464 bool* transaction_saved = nullptr;
2465 switch (domain) {
2466 case SaveDomain::kFontWidths:
2467 dirty = &dirty_state_.font_widths;
2468 transaction_saved = &transaction_saved_domains_.font_widths;
2469 break;
2470 case SaveDomain::kVanillaMessages:
2471 dirty = &dirty_state_.vanilla_messages;
2472 transaction_saved = &transaction_saved_domains_.vanilla_messages;
2473 break;
2474 case SaveDomain::kExpandedMessages:
2475 dirty = &dirty_state_.expanded_messages;
2476 transaction_saved = &transaction_saved_domains_.expanded_messages;
2477 break;
2478 }
2479 *dirty = true;
2480 if (save_transaction_active_) {
2481 *transaction_saved = false;
2482 }
2483 if (domain == SaveDomain::kExpandedMessages) {
2484 InvalidateSourcePreview();
2485 }
2486 if (rom_ && !(domain == SaveDomain::kExpandedMessages &&
2487 ExpandedEditsAreSourceOwned())) {
2488 rom_->set_dirty(true);
2489 }
2490}
2491
2492void MessageEditor::RecordSavedDomains(const SavePlan& plan) {
2495 if (!save_transaction_active_) {
2496 ClearSavedDomains(saved);
2497 return;
2498 }
2499 transaction_saved_domains_.font_widths |= saved.font_widths;
2500 transaction_saved_domains_.vanilla_messages |= saved.vanilla_messages;
2501 transaction_saved_domains_.expanded_messages |= saved.expanded_messages;
2502}
2503
2504void MessageEditor::ClearSavedDomains(const DirtyState& saved) {
2505 if (saved.font_widths) {
2506 dirty_state_.font_widths = false;
2507 }
2508 if (saved.vanilla_messages) {
2509 dirty_state_.vanilla_messages = false;
2510 }
2511 if (saved.expanded_messages) {
2512 dirty_state_.expanded_messages = false;
2513 }
2514}
2515
2516void MessageEditor::SyncCurrentExpandedMessageAddress() {
2517 if (!current_message_is_expanded_ || current_message_index_ < 0 ||
2518 current_message_index_ >= static_cast<int>(expanded_messages_.size())) {
2519 return;
2520 }
2521 current_message_.Address = expanded_messages_[current_message_index_].Address;
2522}
2523
2524absl::Status MessageEditor::LoadCanonicalExpandedSource() {
2525 if (!HasMessageSourceLayout()) {
2526 return absl::FailedPreconditionError(
2527 "The project hack manifest does not define messages.source");
2528 }
2529 if (dirty_state_.expanded_messages || dirty_state_.vanilla_messages ||
2530 dirty_state_.font_widths || pending_undo_before_.has_value() ||
2531 !current_parse_errors_.empty()) {
2532 return absl::FailedPreconditionError(
2533 "The Message editor has pending edits; canonical source was not "
2534 "loaded");
2535 }
2536 auto source_or = LoadMessageSource(*dependencies_.project);
2537 if (!source_or.ok()) {
2538 return source_or.status();
2539 }
2540 // Commit only after the complete source bank validates. This does not import
2541 // vanilla messages, set ROM dirty, write a preview, or publish source files.
2542 expanded_message_base_id_ = source_or->first_expanded_id;
2543 expanded_messages_ = std::move(source_or->messages);
2544 expanded_message_path_ = source_or->canonical_bundle_path.string();
2545 source_loaded_canonical_sha_ = std::move(source_or->source_sha256);
2546 parsed_messages_.resize(expanded_message_base_id_ +
2547 expanded_messages_.size());
2548 for (const auto& message : expanded_messages_) {
2549 parsed_messages_[expanded_message_base_id_ + message.ID] =
2550 message.RawString;
2551 }
2552 InvalidateSourcePreview();
2553 NoteLoadedMessages();
2554 message_bundle_status_ =
2555 absl::StrFormat("Loaded %zu expanded messages from project source: %s",
2556 expanded_messages_.size(), expanded_message_path_);
2557 message_bundle_status_error_ = false;
2558 if (current_message_is_expanded_) {
2559 OpenMessageById(expanded_message_base_id_ + current_message_index_);
2560 }
2561 return absl::OkStatus();
2562}
2563
2564absl::Status MessageEditor::LoadExpandedMessagesFromBin(
2565 const std::string& path) {
2566 const ExpandedDraftSnapshot snapshot = CaptureExpandedDraft();
2567 const bool rom_dirty_before = rom_ && rom_->dirty();
2568 expanded_message_base_id_ = ResolveExpandedMessageBaseId();
2569 parsed_messages_.resize(
2570 static_cast<size_t>(std::max(expanded_message_base_id_, 0)));
2571 expanded_messages_.clear();
2572 std::vector<std::string> parsed_expanded;
2573 std::string mutable_path = path;
2574 const auto status =
2575 LoadExpandedMessages(mutable_path, parsed_expanded, expanded_messages_,
2576 message_preview_.all_dictionaries_);
2577 if (!status.ok() || expanded_messages_.empty()) {
2578 RestoreExpandedDraft(snapshot);
2579 if (rom_) {
2580 rom_->set_dirty(rom_dirty_before);
2581 }
2582 if (!status.ok()) {
2583 return status;
2584 }
2585 return absl::NotFoundError("No expanded messages found in file");
2586 }
2587 parsed_messages_.insert(parsed_messages_.end(), parsed_expanded.begin(),
2588 parsed_expanded.end());
2589 expanded_message_path_ = path;
2590 source_loaded_canonical_sha_.clear();
2591 NoteLoadedMessages();
2592 MarkDomainDirty(SaveDomain::kExpandedMessages);
2593 return absl::OkStatus();
2594}
2595
2596absl::Status MessageEditor::LoadExpandedMessagesFromRom() {
2597 if (!rom_ || !rom_->is_loaded()) {
2598 return absl::FailedPreconditionError("ROM not loaded");
2599 }
2600
2601 const ExpandedDraftSnapshot snapshot = CaptureExpandedDraft();
2602 const bool rom_dirty_before = rom_ && rom_->dirty();
2603 const auto range = ExpandedInspectionRange();
2604 const int end = std::min(range.second, static_cast<int>(rom_->size()) - 1);
2605 auto loaded = ReadExpandedTextData(rom_->mutable_data(), range.first, end);
2606 if (loaded.empty()) {
2607 RestoreExpandedDraft(snapshot);
2608 if (rom_) {
2609 rom_->set_dirty(rom_dirty_before);
2610 }
2611 return absl::NotFoundError(
2612 "No expanded messages found in ROM at the manifest data range");
2613 }
2614
2615 expanded_message_base_id_ = ResolveExpandedMessageBaseId();
2616 parsed_messages_.resize(
2617 static_cast<size_t>(std::max(expanded_message_base_id_, 0)));
2618 expanded_messages_ = std::move(loaded);
2619 auto parsed_expanded =
2620 ParseMessageData(expanded_messages_, message_preview_.all_dictionaries_);
2621 for (const auto& msg : expanded_messages_) {
2622 if (msg.ID >= 0 && msg.ID < static_cast<int>(parsed_expanded.size())) {
2623 parsed_messages_.push_back(parsed_expanded[msg.ID]);
2624 }
2625 }
2626
2627 expanded_message_path_ = "(ROM inspection)";
2628 source_loaded_canonical_sha_.clear();
2629 dirty_state_.expanded_messages = false;
2630 InvalidateSourcePreview();
2631 NoteLoadedMessages();
2632 return absl::OkStatus();
2633}
2634
2635int MessageEditor::CalculateExpandedBankUsage() const {
2636 if (expanded_messages_.empty())
2637 return 0;
2638 int total = 0;
2639 for (const auto& msg : expanded_messages_) {
2640 total += static_cast<int>(msg.Data.size()) + 1; // +1 for 0x7F
2641 }
2642 total += 1; // +1 for final 0xFF
2643 return total;
2644}
2645
2646absl::Status MessageEditor::Cut() {
2647 // Ensure that text is currently selected in the text box.
2648 if (!message_text_box_.text.empty()) {
2649 // Cut the selected text in the control and paste it into the Clipboard.
2650 message_text_box_.Cut();
2651 }
2652 return absl::OkStatus();
2653}
2654
2655absl::Status MessageEditor::Paste() {
2656 // Determine if there is any text in the Clipboard to paste into the
2657 if (ImGui::GetClipboardText() != nullptr) {
2658 // Paste the text from the Clipboard into the text box.
2659 message_text_box_.Paste();
2660 }
2661 return absl::OkStatus();
2662}
2663
2664absl::Status MessageEditor::Copy() {
2665 // Ensure that text is selected in the text box.
2666 if (message_text_box_.selection_length > 0) {
2667 // Copy the selected text to the Clipboard.
2668 message_text_box_.Copy();
2669 }
2670 return absl::OkStatus();
2671}
2672
2673void MessageEditor::PushUndoSnapshot() {
2674 if (pending_undo_before_.has_value()) {
2675 // If we're still editing the same message, keep the existing "before"
2676 // snapshot so the entire edit session becomes a single undo step.
2677 if (pending_undo_before_->message_index == current_message_index_ &&
2678 pending_undo_before_->is_expanded == current_message_is_expanded_) {
2679 return;
2680 }
2681 FinalizePendingUndo();
2682 }
2683
2684 // Capture current state as "before"
2685 int parsed_index = current_message_index_;
2686 if (current_message_is_expanded_) {
2687 parsed_index = expanded_message_base_id_ + current_message_index_;
2688 }
2689 std::string text;
2690 if (parsed_index >= 0 &&
2691 parsed_index < static_cast<int>(parsed_messages_.size())) {
2692 text = parsed_messages_[parsed_index];
2693 }
2694 pending_undo_before_ =
2695 MessageSnapshot{current_message_, text, current_message_index_,
2696 current_message_is_expanded_};
2697}
2698
2699void MessageEditor::FinalizePendingUndo() {
2700 if (!pending_undo_before_.has_value())
2701 return;
2702
2703 // The "after" snapshot must correspond to the same message as the pending
2704 // "before", even if the user navigated to a different message in the UI.
2705 const int message_index = pending_undo_before_->message_index;
2706 const bool is_expanded = pending_undo_before_->is_expanded;
2707
2708 MessageData after_message;
2709 if (is_expanded) {
2710 if (message_index < 0 ||
2711 message_index >= static_cast<int>(expanded_messages_.size())) {
2712 pending_undo_before_.reset();
2713 return;
2714 }
2715 after_message = expanded_messages_[message_index];
2716 } else {
2717 if (message_index < 0 ||
2718 message_index >= static_cast<int>(list_of_texts_.size())) {
2719 pending_undo_before_.reset();
2720 return;
2721 }
2722 after_message = list_of_texts_[message_index];
2723 }
2724
2725 int parsed_index = message_index;
2726 if (is_expanded) {
2727 parsed_index = expanded_message_base_id_ + message_index;
2728 }
2729 std::string text;
2730 if (parsed_index >= 0 &&
2731 parsed_index < static_cast<int>(parsed_messages_.size())) {
2732 text = parsed_messages_[parsed_index];
2733 }
2734 MessageSnapshot after{std::move(after_message), std::move(text),
2735 message_index, is_expanded};
2736
2737 undo_manager_.Push(std::make_unique<MessageEditAction>(
2738 std::move(*pending_undo_before_), std::move(after),
2739 [this](const MessageSnapshot& s) { ApplySnapshot(s); }));
2740 pending_undo_before_.reset();
2741}
2742
2743void MessageEditor::ApplySnapshot(const MessageSnapshot& snapshot) {
2744 current_message_ = snapshot.message;
2745 current_message_index_ = snapshot.message_index;
2746 current_message_is_expanded_ = snapshot.is_expanded;
2747 message_text_box_.text = snapshot.parsed_text;
2748 const auto diagnostics =
2750 current_parse_errors_ = diagnostics.errors;
2751 current_parse_warnings_ = diagnostics.warnings;
2752
2753 int parsed_index = snapshot.message_index;
2754 if (snapshot.is_expanded) {
2755 parsed_index = expanded_message_base_id_ + snapshot.message_index;
2756 }
2757 if (parsed_index >= 0 &&
2758 parsed_index < static_cast<int>(parsed_messages_.size())) {
2759 parsed_messages_[parsed_index] = snapshot.parsed_text;
2760 }
2761
2762 if (snapshot.is_expanded) {
2763 if (snapshot.message_index >= 0 &&
2764 snapshot.message_index < static_cast<int>(expanded_messages_.size())) {
2765 expanded_messages_[snapshot.message_index] = snapshot.message;
2766 }
2767 } else {
2768 if (snapshot.message_index >= 0 &&
2769 snapshot.message_index < static_cast<int>(list_of_texts_.size())) {
2770 list_of_texts_[snapshot.message_index] = snapshot.message;
2771 }
2772 }
2773
2774 MarkDomainDirty(snapshot.is_expanded ? SaveDomain::kExpandedMessages
2775 : SaveDomain::kVanillaMessages);
2776 DrawMessagePreview();
2777}
2778
2779absl::Status MessageEditor::Undo() {
2780 FinalizePendingUndo();
2781 return undo_manager_.Undo();
2782}
2783
2784absl::Status MessageEditor::Redo() {
2785 return undo_manager_.Redo();
2786}
2787
2788void MessageEditor::Delete() {
2789 // Determine if any text is selected in the TextBox control.
2790 if (message_text_box_.selection_length == 0) {
2791 // clear all of the text in the textbox.
2792 message_text_box_.clear();
2793 }
2794}
2795
2796void MessageEditor::SelectAll() {
2797 // Determine if any text is selected in the TextBox control.
2798 if (message_text_box_.selection_length == 0) {
2799 // Select all text in the text box.
2800 message_text_box_.SelectAll();
2801
2802 // Move the cursor to the text box.
2803 message_text_box_.Focus();
2804 }
2805}
2806
2807absl::Status MessageEditor::Find() {
2808 // Edit > Find is a one-shot menu action. The bar itself is drawn every
2809 // frame from the message editor panel so it stays open across frames.
2810 find_panel_open_ = true;
2811 find_focus_search_ = true;
2812 if (dependencies_.window_manager) {
2813 dependencies_.window_manager->OpenWindow(dependencies_.session_id,
2814 "message.message_editor");
2815 }
2816 return absl::OkStatus();
2817}
2818
2819int MessageEditor::ReplaceCurrentMatch() {
2820 if (search_text_.empty()) {
2821 return 0;
2822 }
2823
2824 std::string& text = message_text_box_.text;
2825 const size_t cursor = static_cast<size_t>(
2826 std::clamp(editor_cursor_, 0, static_cast<int>(text.size())));
2827 const size_t from = find_has_match_ ? find_match_start_ : cursor;
2828 auto match = FindNextTextMatch(text, search_text_, from, case_sensitive_,
2829 match_whole_word_);
2830 if (!match && from > 0) {
2831 match = FindNextTextMatch(text, search_text_, 0, case_sensitive_,
2832 match_whole_word_);
2833 }
2834 if (!match) {
2835 return 0;
2836 }
2837
2838 text.replace(*match, search_text_.size(), replace_text_);
2839 pending_selection_start_ = static_cast<int>(*match);
2840 pending_selection_end_ =
2841 pending_selection_start_ + static_cast<int>(replace_text_.size());
2842 editor_cursor_ = pending_selection_end_;
2843 find_has_match_ = false;
2844 ImGui::ClearActiveID();
2845 UpdateCurrentMessageFromText(text);
2846 FinalizePendingUndo();
2847 return 1;
2848}
2849
2850int MessageEditor::ReplaceAllMatches() {
2851 if (search_text_.empty()) {
2852 return 0;
2853 }
2854 if (!current_parse_errors_.empty()) {
2855 replace_status_ =
2856 "Replace All blocked: resolve the current message parse errors first";
2857 replace_status_error_ = true;
2858 return -1;
2859 }
2860
2861 auto replace_in_text = [&](std::string& text) -> int {
2862 int count = 0;
2863 std::string search = search_text_;
2864
2865 if (!case_sensitive_) {
2866 std::transform(search.begin(), search.end(), search.begin(), ::tolower);
2867 }
2868
2869 size_t pos = 0;
2870 while (pos < text.size()) {
2871 std::string source = text;
2872 if (!case_sensitive_) {
2873 std::transform(source.begin(), source.end(), source.begin(), ::tolower);
2874 }
2875
2876 size_t found = source.find(search, pos);
2877 if (found == std::string::npos)
2878 break;
2879
2880 if (match_whole_word_) {
2881 bool start_ok = (found == 0 || !std::isalnum(source[found - 1]));
2882 bool end_ok = (found + search.size() >= source.size() ||
2883 !std::isalnum(source[found + search.size()]));
2884 if (!start_ok || !end_ok) {
2885 pos = found + 1;
2886 continue;
2887 }
2888 }
2889
2890 text.replace(found, search_text_.size(), replace_text_);
2891 pos = found + replace_text_.size();
2892 count++;
2893 }
2894 return count;
2895 };
2896
2897 struct PlannedReplacement {
2898 int message_index;
2899 bool is_expanded;
2900 std::string text;
2901 int count;
2902 };
2903 std::vector<PlannedReplacement> plan;
2904
2905 const auto plan_replacements = [&](const std::vector<MessageData>& messages,
2906 bool is_expanded) -> bool {
2907 for (size_t i = 0; i < messages.size(); ++i) {
2908 const int parsed_index =
2909 (is_expanded ? expanded_message_base_id_ : 0) + static_cast<int>(i);
2910 if (parsed_index < 0 ||
2911 parsed_index >= static_cast<int>(parsed_messages_.size())) {
2912 continue;
2913 }
2914
2915 std::string text = parsed_messages_[parsed_index];
2916 const int count = replace_in_text(text);
2917 if (count == 0) {
2918 continue;
2919 }
2920
2921 const auto parsed = ParseMessageToDataWithDiagnostics(text);
2922 if (!parsed.ok() ||
2923 (is_expanded && text.find("[BANK]") != std::string::npos)) {
2924 const std::string error =
2925 !parsed.ok() ? parsed.errors.front()
2926 : "[BANK] is not valid in expanded messages";
2927 replace_status_ = absl::StrFormat(
2928 "Replace All aborted at %s message %d: %s",
2929 is_expanded ? "expanded" : "vanilla", static_cast<int>(i), error);
2930 replace_status_error_ = true;
2931 return false;
2932 }
2933
2934 plan.push_back(
2935 {static_cast<int>(i), is_expanded, std::move(text), count});
2936 }
2937 return true;
2938 };
2939
2940 // Validate the complete batch before changing any message or undo state.
2941 if (!plan_replacements(list_of_texts_, false) ||
2942 !plan_replacements(expanded_messages_, true)) {
2943 return -1;
2944 }
2945
2946 const int previous_index = current_message_index_;
2947 const bool previous_expanded = current_message_is_expanded_;
2948 int total_replacements = 0;
2949
2950 for (const auto& replacement : plan) {
2951 current_message_ = replacement.is_expanded
2952 ? expanded_messages_[replacement.message_index]
2953 : list_of_texts_[replacement.message_index];
2954 current_message_index_ = replacement.message_index;
2955 current_message_is_expanded_ = replacement.is_expanded;
2956 message_text_box_.text = replacement.text;
2957 UpdateCurrentMessageFromText(replacement.text);
2958 FinalizePendingUndo();
2959 total_replacements += replacement.count;
2960 }
2961
2962 current_message_index_ = previous_index;
2963 current_message_is_expanded_ = previous_expanded;
2964
2965 // Refresh the current message's text box from updated data
2966 int current_parsed_idx = current_message_index_;
2967 if (current_message_is_expanded_) {
2968 current_parsed_idx = expanded_message_base_id_ + current_message_index_;
2969 }
2970 if (current_parsed_idx >= 0 &&
2971 current_parsed_idx < static_cast<int>(parsed_messages_.size())) {
2972 message_text_box_.text = parsed_messages_[current_parsed_idx];
2973 }
2974
2975 // Refresh current_message_ to reflect replacements
2976 if (current_message_is_expanded_) {
2977 if (current_message_index_ >= 0 &&
2978 current_message_index_ < static_cast<int>(expanded_messages_.size())) {
2979 current_message_ = expanded_messages_[current_message_index_];
2980 }
2981 } else {
2982 if (current_message_index_ >= 0 &&
2983 current_message_index_ < static_cast<int>(list_of_texts_.size())) {
2984 current_message_ = list_of_texts_[current_message_index_];
2985 }
2986 }
2987
2988 const auto current_diagnostics =
2989 ParseMessageToDataWithDiagnostics(message_text_box_.text);
2990 current_parse_errors_ = current_diagnostics.errors;
2991 current_parse_warnings_ = current_diagnostics.warnings;
2992
2993 return total_replacements;
2994}
2995
2996} // namespace editor
2997} // namespace yaze
auto data() const
Definition rom.h:213
auto size() const
Definition rom.h:212
bool is_loaded() const
Definition rom.h:199
const MessageLayout & message_layout() const
bool loaded() const
Check if the manifest has been loaded.
virtual void SetGameData(zelda3::GameData *game_data)
Definition editor.h:262
project::YazeProject * project() const
Definition editor.h:370
zelda3::GameData * game_data() const
Definition editor.h:369
EditorDependencies dependencies_
Definition editor.h:382
MessageSourcePublishButtons DrawMessageSourcePublishButtons()
std::vector< std::string > baseline_messages_
void RestoreExpandedDraft(const ExpandedDraftSnapshot &snapshot)
std::vector< std::string > parsed_messages_
std::vector< MessageData > expanded_messages_
void ContributeStatus(StatusBar *status_bar) override
absl::Status Update() override
bool IsCanonicalBundlePath(const std::string &path) const
absl::Status LoadExpandedMessagesFromRom()
void DrawDialogueTextPane(float height)
void UpdateCurrentMessageFromText(const std::string &text)
std::vector< int > transaction_expanded_address_snapshot_
bool AdvanceFind(bool forward)
ExpandedDraftSnapshot CaptureExpandedDraft() const
bool HasUnpublishedMessageSourceChanges() const
absl::StatusOr< std::filesystem::path > ResolveCanonicalBundlePath() const
std::vector< std::string > current_parse_errors_
absl::Status Load() override
std::string MessageSourceIncomingPath() const
absl::StatusOr< std::string > HashFileSha256(const std::filesystem::path &path) const
std::vector< std::string > current_parse_warnings_
std::pair< int, int > ExpandedInspectionRange() const
absl::Status LoadCanonicalExpandedSource()
void InsertTokenAtCursor(const std::string &token)
std::vector< MessageRow > CollectMessageRows(bool apply_filter) const
bool ActivateFindMatch(const MessageRow &row, size_t offset, bool wrapped)
std::string_view ContentsForDisplayId(int display_id) const
std::vector< MessageData > list_of_texts_
std::string CurrentReferenceText() const
bool OpenMessageById(int display_id)
gfx::SnesPalette font_preview_colors_
void SelectAdjacentMessage(int delta)
void ImportMessageBundleFromFile(const std::string &path)
void SetGameData(zelda3::GameData *game_data) override
A session-aware status bar displayed at the bottom of the application.
Definition status_bar.h:57
void SetCustomSegment(const std::string &key, const std::string &value)
Set a custom segment with key-value pair.
void SetEditorMode(const std::string &mode)
Set the current editor mode or tool.
const std::vector< VanillaMessageWrite > & writes() const
bool OpenWindow(size_t session_id, const std::string &base_window_id)
void QueueTextureCommand(TextureCommandType type, Bitmap *bitmap)
Definition arena.cc:39
static Arena & Get()
Definition arena.cc:24
SnesPalette * mutable_palette()
Definition bitmap.h:394
RAII timer for automatic timing management.
CanvasConfig & GetConfig()
Definition canvas.h:243
void SetGridEnabled(bool enabled)
Definition canvas.h:393
static void BeginToolbar(const char *label)
static bool ToolbarButton(const char *label, const ImVec2 &size=ImVec2(0, 0))
RAII guard for ImGui style colors.
Definition style_guard.h:29
absl::Status Allow(uint32_t start, uint32_t end, std::string_view label)
Definition write_fence.h:32
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...
#define ICON_MD_CHAT
Definition icons.h:394
#define ICON_MD_SEARCH
Definition icons.h:1673
#define ICON_MD_NAVIGATE_BEFORE
Definition icons.h:1274
#define ICON_MD_ARROW_FORWARD
Definition icons.h:184
#define ICON_MD_PUBLISH
Definition icons.h:1526
#define ICON_MD_LIBRARY_ADD
Definition icons.h:1077
#define ICON_MD_UPLOAD
Definition icons.h:2048
#define ICON_MD_DOWNLOAD
Definition icons.h:618
#define ICON_MD_NAVIGATE_NEXT
Definition icons.h:1275
#define LOG_DEBUG(category, format,...)
Definition log.h:133
#define LOG_ERROR(category, format,...)
Definition log.h:140
#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
int MessageInputCallback(ImGuiInputTextCallbackData *data)
constexpr int kCharactersWidth
int GetExpandedTextDataStart()
constexpr uint8_t kScrollVertical
absl::StatusOr< MessageSourceSnapshot > LoadMessageSource(const project::YazeProject &project)
std::optional< ResolvedMessageId > ResolveMessageDisplayId(int display_id, int vanilla_count, int expanded_base_id, int expanded_count)
absl::Status ValidateHackManifestSaveConflicts(const core::HackManifest &manifest, project::RomWritePolicy write_policy, const std::vector< std::pair< uint32_t, uint32_t > > &ranges, absl::string_view save_scope, const char *log_tag, ToastManager *toast_manager)
absl::Status LoadExpandedMessages(std::string &expanded_message_path, std::vector< std::string > &parsed_messages, std::vector< MessageData > &expanded_messages, std::vector< DictionaryEntry > &dictionary)
constexpr uint8_t kLine1
constexpr int kTextData
std::string MessageBankToString(MessageBank bank)
constexpr int kCurrentMessageWidth
constexpr int kCurrentMessageHeight
constexpr uint8_t kLine2
bool HasMultilineMessageProse(std::string_view text)
absl::StatusOr< std::vector< MessageBundleEntry > > LoadMessageBundleFromJson(const std::string &path)
std::string ComputeMessageSourceSha256(std::string_view content)
std::string MessageListPreview(std::string_view text, size_t max_chars)
std::vector< MessageData > ReadAllTextData(uint8_t *rom, int pos, int max_pos, bool allow_bank_switch)
std::vector< std::string > ParseMessageData(std::vector< MessageData > &message_data, const std::vector< DictionaryEntry > &dictionary_entries)
constexpr uint8_t kMessageTerminator
std::vector< DictionaryEntry > BuildDictionaryEntries(Rom *rom)
absl::Status ExportMessagesToJson(const std::string &path, const std::vector< MessageData > &messages)
constexpr uint8_t kWidthArraySize
absl::Status ExportMessageBundleToJson(const std::string &path, const std::vector< MessageData > &vanilla, const std::vector< MessageData > &expanded)
constexpr ImGuiTableFlags kMessageTableFlags
absl::StatusOr< VanillaMessageSavePlan > BuildVanillaMessageSavePlan(const std::vector< MessageData > &messages, std::optional< size_t > expected_message_count)
constexpr char kOracleExpandedRomWriteRefusal[]
std::vector< MessageData > ReadExpandedTextData(uint8_t *rom, int pos)
MessageParseResult ParseMessageToDataWithDiagnostics(std::string_view str)
int GetExpandedTextDataEnd()
absl::StatusOr< MessageSourceSyncResult > SyncMessageSource(const project::YazeProject &project, const fs::path &incoming_bundle_path, const MessageSourceSyncOptions &options)
std::optional< size_t > FindNextTextMatch(std::string_view text, std::string_view needle, size_t start, bool case_sensitive, bool whole_word)
std::optional< size_t > FindPreviousTextMatch(std::string_view text, std::string_view needle, size_t before, bool case_sensitive, bool whole_word)
std::vector< std::string > ValidateMessageLineWidths(const std::string &message)
bool MessageListQueryMatches(int display_id, uint32_t address, std::string_view contents, bool expanded, MessageBankFilter bank, std::string_view query)
constexpr uint8_t kLine3
std::string ColumnLabel(absl::string_view text, absl::string_view stable_id)
void BeginPadding(int i)
Definition style.cc:299
ImVec4 GetSuccessColor()
Definition ui_helpers.cc:49
void AutoRegisterLastItem(const std::string &widget_type, const std::string &explicit_label, const std::string &description)
Automatically register the last ImGui item.
void MemoryEditorPopup(const std::string &label, std::span< uint8_t > memory)
Definition input.cc:815
void SectionHeader(const char *icon, const char *label, const ImVec4 &color)
void EndPadding()
Definition style.cc:303
bool ItemContextMenu(const char *id, const std::function< std::vector< MenuItemSpec >()> &build, ImGuiPopupFlags flags)
Right-click menu for the last submitted ImGui item.
bool DrawEmptyState(const EmptyStateOptions &options)
Draw a centered empty-state block.
ImVec4 GetErrorColor()
Definition ui_helpers.cc:59
ImVec4 GetWarningColor()
Definition ui_helpers.cc:54
IMGUI_API bool DisplayPalette(gfx::SnesPalette &palette, bool loaded)
Definition color.cc:263
MenuItemSpec CopyToClipboardItem(const std::string &label, const std::string &text)
ImVec4 GetInfoColor()
Definition ui_helpers.cc:64
bool InputHexByte(const char *label, uint8_t *data, float input_width, bool no_step)
Definition input.cc:483
void StatusBadge(const char *text, ButtonType type)
std::string HexWord(uint16_t word, HexStringParams params)
Definition hex.cc:44
std::string HexLong(uint32_t dword, HexStringParams params)
Definition hex.cc:55
uint32_t SnesToPc(uint32_t addr) noexcept
Definition snes.h:8
#define RETURN_IF_ERROR(expr)
Definition snes.cc:22
std::optional< Source > source
project::YazeProject * project
Definition editor.h:174
WorkspaceWindowManager * window_manager
Definition editor.h:182
std::vector< uint8_t > Data
std::string OptimizeMessageForDictionary(std::string_view message_string, const std::vector< DictionaryEntry > &dictionary)
std::vector< PlannedWrite > writes
std::array< uint8_t, kWidthArraySize > width_array
std::vector< DictionaryEntry > all_dictionaries_
Shared empty / disabled panel presentation.
Definition empty_state.h:15
std::function< void()> on_action
Definition empty_state.h:20
bool compact
Tighter vertical rhythm for drawers / inspectors.
Definition empty_state.h:22
std::string text
Definition style.h:50
core::HackManifest hack_manifest
Definition project.h:376
Automatic widget registration helpers for ImGui Test Engine integration.