yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
project.cc
Go to the documentation of this file.
1#include "core/project.h"
4
5#include <algorithm>
6#include <atomic>
7#include <cctype>
8#include <cerrno>
9#include <chrono>
10#include <cstdint>
11#include <cstdio>
12#include <filesystem>
13#include <fstream>
14#include <iomanip>
15#include <iterator>
16#include <sstream>
17#include <stdexcept>
18
19#include "absl/strings/match.h"
20#include "absl/strings/numbers.h"
21#include "absl/strings/str_format.h"
22#include "absl/strings/str_join.h"
23#include "absl/strings/str_split.h"
24#include "absl/strings/strip.h"
25#include "app/gui/core/icons.h"
29#include "imgui/imgui.h"
30#include "util/file_util.h"
31#include "util/json.h"
32#include "util/log.h"
33#include "util/macro.h"
34#include "util/platform_paths.h"
35#include "yaze_config.h"
37
38#if defined(YAZE_WITH_Z3DK) && __has_include("z3dk_core/config.h")
39#include "z3dk_core/config.h"
40#endif
41
42#ifdef __EMSCRIPTEN__
44#elif defined(_WIN32)
45#include <windows.h>
46#ifdef ERROR
47#undef ERROR
48#endif
49#else
50#include <unistd.h>
51#endif
52
53// #ifdef YAZE_ENABLE_JSON_PROJECT_FORMAT
54// #include "nlohmann/json.hpp"
55// using json = nlohmann::json;
56// #endif
57
58namespace yaze {
59namespace project {
60
61namespace {
62std::string ToLowerCopy(std::string value) {
63 std::transform(
64 value.begin(), value.end(), value.begin(),
65 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
66 return value;
67}
68
69// Helper functions for parsing key-value pairs
70std::pair<std::string, std::string> ParseKeyValue(const std::string& line) {
71 size_t eq_pos = line.find('=');
72 if (eq_pos == std::string::npos)
73 return {"", ""};
74
75 std::string key = line.substr(0, eq_pos);
76 std::string value = line.substr(eq_pos + 1);
77
78 // Trim whitespace
79 key.erase(0, key.find_first_not_of(" \t"));
80 key.erase(key.find_last_not_of(" \t") + 1);
81 value.erase(0, value.find_first_not_of(" \t"));
82 value.erase(value.find_last_not_of(" \t") + 1);
83
84 return {key, value};
85}
86
87absl::Status ParseProjectInteger(const std::string& value,
88 const std::string& section,
89 const std::string& key, int* output) {
90 int parsed;
91 if (!absl::SimpleAtoi(value, &parsed)) {
92 return absl::InvalidArgumentError(absl::StrFormat(
93 "Invalid integer value for [%s] %s: '%s'", section, key, value));
94 }
95 *output = parsed;
96 return absl::OkStatus();
97}
98
99bool ParseBool(const std::string& value) {
100 return value == "true" || value == "1" || value == "yes";
101}
102
103float ParseFloat(const std::string& value) {
104 try {
105 return std::stof(value);
106 } catch (...) {
107 return 0.0f;
108 }
109}
110
111std::vector<std::string> ParseStringList(const std::string& value) {
112 std::vector<std::string> result;
113 if (value.empty())
114 return result;
115
116 std::vector<std::string> parts = absl::StrSplit(value, ',');
117 for (const auto& part : parts) {
118 std::string trimmed = std::string(part);
119 trimmed.erase(0, trimmed.find_first_not_of(" \t"));
120 trimmed.erase(trimmed.find_last_not_of(" \t") + 1);
121 if (!trimmed.empty()) {
122 result.push_back(trimmed);
123 }
124 }
125 return result;
126}
127
128std::vector<std::string> ParsePositionalStringList(const std::string& value) {
129 std::vector<std::string> result;
130 if (value.empty())
131 return result;
132
133 std::vector<std::string> parts = absl::StrSplit(value, ',');
134 result.reserve(parts.size());
135 for (const auto& part : parts) {
136 std::string trimmed = part;
137 trimmed.erase(0, trimmed.find_first_not_of(" \t"));
138 trimmed.erase(trimmed.find_last_not_of(" \t") + 1);
139 result.push_back(std::move(trimmed));
140 }
141 return result;
142}
143
144std::vector<uint16_t> ParseHexUintList(const std::string& value) {
145 std::vector<uint16_t> result;
146 if (value.empty()) {
147 return result;
148 }
149
150 auto parts = ParseStringList(value);
151 result.reserve(parts.size());
152 for (const auto& part : parts) {
153 std::string token = part;
154 if (token.rfind("0x", 0) == 0 || token.rfind("0X", 0) == 0) {
155 token = token.substr(2);
156 try {
157 result.push_back(static_cast<uint16_t>(std::stoul(token, nullptr, 16)));
158 } catch (...) {
159 // Ignore malformed entries
160 }
161 } else {
162 try {
163 result.push_back(static_cast<uint16_t>(std::stoul(token, nullptr, 10)));
164 } catch (...) {
165 // Ignore malformed entries
166 }
167 }
168 }
169 return result;
170}
171
172std::optional<uint32_t> ParseHexUint32(const std::string& value) {
173 if (value.empty()) {
174 return std::nullopt;
175 }
176 std::string token = value;
177 if (token.rfind("0x", 0) == 0 || token.rfind("0X", 0) == 0) {
178 token = token.substr(2);
179 try {
180 return static_cast<uint32_t>(std::stoul(token, nullptr, 16));
181 } catch (...) {
182 return std::nullopt;
183 }
184 }
185 try {
186 return static_cast<uint32_t>(std::stoul(token, nullptr, 10));
187 } catch (...) {
188 return std::nullopt;
189 }
190}
191
192std::string FormatHexUintList(const std::vector<uint16_t>& values) {
193 return absl::StrJoin(values, ",", [](std::string* out, uint16_t value) {
194 out->append(absl::StrFormat("0x%02X", value));
195 });
196}
197
198// Before 2026-09-25 the gfx group editor keyed blockset, roomset and
199// spriteset labels as "0x" + decimal digits (spriteset 12 -> "0x12", which the
200// label resolver reads as hex 18); the paletteset editor did the same until
201// 2026-09-26. Canonical keys are decimal. On load:
202// existing decimal keys win; "0x" + only decimal digits is that old format and
203// is read as decimal; other hex keys ("0x0C") are read as hex.
205 std::unordered_map<std::string,
206 std::unordered_map<std::string, std::string>>& labels) {
207 auto all_of = [](absl::string_view text, auto predicate) {
208 return !text.empty() && std::all_of(text.begin(), text.end(), predicate);
209 };
210 auto is_decimal = [](char c) {
211 return c >= '0' && c <= '9';
212 };
213 auto is_hex = [](char c) {
214 return std::isxdigit(static_cast<unsigned char>(c)) != 0;
215 };
216 for (const char* type : {"blockset", "roomset", "spriteset", "paletteset"}) {
217 auto found = labels.find(type);
218 if (found == labels.end()) {
219 continue;
220 }
221 std::unordered_map<std::string, std::string> migrated;
222 // Pass 0: canonical decimal keys. Pass 1: old "0x"+decimal. Pass 2: hex.
223 for (int pass = 0; pass < 3; ++pass) {
224 for (const auto& [key, value] : found->second) {
225 absl::string_view digits = key;
226 const bool prefixed = absl::ConsumePrefix(&digits, "0x") ||
227 absl::ConsumePrefix(&digits, "0X");
228 std::string canonical;
229 if (pass == 0 && !prefixed && all_of(digits, is_decimal)) {
230 canonical = std::string(digits);
231 } else if (pass == 1 && prefixed && all_of(digits, is_decimal)) {
232 canonical =
233 std::to_string(std::stoul(std::string(digits), nullptr, 10));
234 } else if (pass == 2 && !all_of(digits, is_decimal)) {
235 // Real hex keys become decimal; anything else is kept as written.
236 canonical =
237 prefixed && all_of(digits, is_hex)
238 ? std::to_string(std::stoul(std::string(digits), nullptr, 16))
239 : key;
240 }
241 if (!canonical.empty()) {
242 migrated.emplace(canonical, value);
243 }
244 }
245 }
246 found->second = std::move(migrated);
247 }
248}
249
250// "0x55:0,1,2;0x54:3" -> {0x55: {0, 1, 2}, 0x54: {3}}
251std::map<uint16_t, std::vector<uint16_t>> ParseHexUintListMap(
252 const std::string& value) {
253 std::map<uint16_t, std::vector<uint16_t>> result;
254 for (absl::string_view entry : absl::StrSplit(value, ';')) {
255 const size_t colon = entry.find(':');
256 if (colon == absl::string_view::npos) {
257 continue;
258 }
259 const auto keys = ParseHexUintList(std::string(entry.substr(0, colon)));
260 if (keys.size() != 1) {
261 continue;
262 }
263 result[keys.front()] =
264 ParseHexUintList(std::string(entry.substr(colon + 1)));
265 }
266 return result;
267}
268
270 const std::map<uint16_t, std::vector<uint16_t>>& values) {
271 return absl::StrJoin(values, ";", [](std::string* out, const auto& entry) {
272 out->append(absl::StrFormat("0x%02X:", entry.first));
273 out->append(absl::StrJoin(entry.second, ","));
274 });
275}
276
277std::string FormatHexUint32(uint32_t value) {
278 return absl::StrFormat("0x%06X", value);
279}
280
281std::string SanitizeStorageKey(absl::string_view input) {
282 std::string key(input);
283 for (char& c : key) {
284 if (!std::isalnum(static_cast<unsigned char>(c))) {
285 c = '_';
286 }
287 }
288 if (key.empty()) {
289 key = "project";
290 }
291 return key;
292}
293
294std::pair<std::string, std::string> ParseDefineToken(const std::string& value) {
295 auto [key, parsed_value] = ParseKeyValue(value);
296 if (key.empty()) {
297 return {value, "1"};
298 }
299 return {key, parsed_value.empty() ? "1" : parsed_value};
300}
301
302std::string ResolveOptionalPath(const std::filesystem::path& base_dir,
303 const std::string& value) {
304 if (value.empty()) {
305 return {};
306 }
307 std::filesystem::path path(value);
308 if (path.is_absolute()) {
309 return path.lexically_normal().string();
310 }
311 return (base_dir / path).lexically_normal().string();
312}
313
314std::string BasenameLower(const std::string& path) {
315 return ToLowerCopy(std::filesystem::path(path).filename().string());
316}
317
319#if defined(_WIN32)
320 return static_cast<uint64_t>(::GetCurrentProcessId());
321#elif defined(__EMSCRIPTEN__)
322 return 0;
323#else
324 return static_cast<uint64_t>(::getpid());
325#endif
326}
327
328std::filesystem::path MakeProjectSaveTempPath(
329 const std::filesystem::path& target_path) {
330 static std::atomic<uint64_t> next_temp_id{0};
331 std::filesystem::path temp_path = target_path;
332 temp_path +=
333 ".tmp." + std::to_string(CurrentProcessIdForProjectSave()) + "." +
334 std::to_string(next_temp_id.fetch_add(1, std::memory_order_relaxed));
335 return temp_path;
336}
337
338void RemoveProjectSaveTempFile(const std::filesystem::path& temp_path) {
339 std::error_code remove_error;
340 std::filesystem::remove(temp_path, remove_error);
341}
342
344 const std::filesystem::path& target_path, absl::string_view contents,
345 bool replace_existing) {
346#ifdef __EMSCRIPTEN__
347 if (!replace_existing) {
348 // MEMFS/IDBFS do not support hard links. Exclusive fopen keeps the existing
349 // synchronous virtual-filesystem workflow without replacing a destination.
350 FILE* file = std::fopen(target_path.c_str(), "wbx");
351 if (file == nullptr) {
352 if (errno == EEXIST) {
353 return absl::AlreadyExistsError(absl::StrFormat(
354 "Project file already exists: %s", target_path.string()));
355 }
356 return absl::InternalError(absl::StrFormat(
357 "Cannot create project file: %s", target_path.string()));
358 }
359 const bool written = std::fwrite(contents.data(), 1, contents.size(),
360 file) == contents.size();
361 const bool closed = std::fclose(file) == 0;
362 if (!written || !closed) {
363 RemoveProjectSaveTempFile(target_path);
364 return absl::InternalError(absl::StrFormat(
365 "Failed to write project file: %s", target_path.string()));
366 }
367 return absl::OkStatus();
368 }
369#endif
370 const std::filesystem::path temp_path = MakeProjectSaveTempPath(target_path);
371#if defined(_WIN32)
372 HANDLE file = CreateFileW(temp_path.c_str(), GENERIC_WRITE, 0, nullptr,
373 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
374 if (file == INVALID_HANDLE_VALUE) {
375 return absl::InvalidArgumentError(absl::StrFormat(
376 "Cannot create temporary project file: %s", temp_path.string()));
377 }
378
379 size_t written_total = 0;
380 while (written_total < contents.size()) {
381 const DWORD chunk = static_cast<DWORD>(
382 std::min<size_t>(contents.size() - written_total, 1024 * 1024));
383 DWORD written = 0;
384 if (!WriteFile(file, contents.data() + written_total, chunk, &written,
385 nullptr) ||
386 written == 0) {
387 CloseHandle(file);
388 RemoveProjectSaveTempFile(temp_path);
389 return absl::InternalError(absl::StrFormat(
390 "Failed to write temporary project file: %s", temp_path.string()));
391 }
392 written_total += written;
393 }
394 if (!FlushFileBuffers(file)) {
395 CloseHandle(file);
396 RemoveProjectSaveTempFile(temp_path);
397 return absl::InternalError(absl::StrFormat(
398 "Failed to write temporary project file: %s", temp_path.string()));
399 }
400 if (!CloseHandle(file)) {
401 RemoveProjectSaveTempFile(temp_path);
402 return absl::InternalError(absl::StrFormat(
403 "Failed to close temporary project file: %s", temp_path.string()));
404 }
405#else
406 // Exclusive creation establishes ownership; never reopen the staging path.
407 FILE* file = std::fopen(temp_path.c_str(), "wbx");
408 if (file == nullptr) {
409 return absl::InvalidArgumentError(absl::StrFormat(
410 "Cannot create temporary project file: %s", temp_path.string()));
411 }
412 const bool written =
413 std::fwrite(contents.data(), 1, contents.size(), file) == contents.size();
414 const bool flushed = std::fflush(file) == 0;
415 const bool closed = std::fclose(file) == 0;
416 if (!written || !flushed) {
417 RemoveProjectSaveTempFile(temp_path);
418 return absl::InternalError(absl::StrFormat(
419 "Failed to write temporary project file: %s", temp_path.string()));
420 }
421 if (!closed) {
422 RemoveProjectSaveTempFile(temp_path);
423 return absl::InternalError(absl::StrFormat(
424 "Failed to close temporary project file: %s", temp_path.string()));
425 }
426#endif
427
428 std::error_code rename_error;
429#if defined(_WIN32)
430 const DWORD move_flags =
431 MOVEFILE_WRITE_THROUGH |
432 (replace_existing ? MOVEFILE_REPLACE_EXISTING : static_cast<DWORD>(0));
433 if (!::MoveFileExW(temp_path.c_str(), target_path.c_str(), move_flags)) {
434 rename_error = std::error_code(static_cast<int>(::GetLastError()),
435 std::system_category());
436 }
437#elif defined(__EMSCRIPTEN__)
438 std::filesystem::rename(temp_path, target_path, rename_error);
439#else
440 if (replace_existing) {
441 std::filesystem::rename(temp_path, target_path, rename_error);
442 } else if (::link(temp_path.c_str(), target_path.c_str()) != 0) {
443 rename_error = std::error_code(errno, std::generic_category());
444 } else {
445 RemoveProjectSaveTempFile(temp_path);
446 }
447#endif
448 if (rename_error) {
449 RemoveProjectSaveTempFile(temp_path);
450 bool target_already_exists = rename_error == std::errc::file_exists;
451#if defined(_WIN32)
452 target_already_exists = target_already_exists ||
453 rename_error.value() == ERROR_FILE_EXISTS ||
454 rename_error.value() == ERROR_ALREADY_EXISTS;
455#endif
456 if (!replace_existing && target_already_exists) {
457 return absl::AlreadyExistsError(absl::StrFormat(
458 "Project file already exists: %s", target_path.string()));
459 }
460 return absl::InternalError(
461 absl::StrFormat("Failed to replace project file %s: %s",
462 target_path.string(), rename_error.message()));
463 }
464
465 return absl::OkStatus();
466}
467} // namespace
468
469absl::Status WriteProjectFileAtomically(absl::string_view target_path,
470 absl::string_view contents,
471 bool replace_existing) {
472 return WriteProjectFileAtomicallyImpl(
473 std::filesystem::path(std::string(target_path)), contents,
474 replace_existing);
475}
476
477std::string RomRoleToString(RomRole role) {
478 switch (role) {
479 case RomRole::kBase:
480 return "base";
482 return "patched";
484 return "release";
485 case RomRole::kDev:
486 default:
487 return "dev";
488 }
489}
490
491RomRole ParseRomRole(absl::string_view value) {
492 std::string lower = ToLowerCopy(std::string(value));
493 if (lower == "base") {
494 return RomRole::kBase;
495 }
496 if (lower == "patched") {
497 return RomRole::kPatched;
498 }
499 if (lower == "release") {
500 return RomRole::kRelease;
501 }
502 return RomRole::kDev;
503}
504
506 switch (policy) {
508 return "allow";
510 return "block";
512 return "read_only";
514 default:
515 return "warn";
516 }
517}
518
519RomWritePolicy ParseRomWritePolicy(absl::string_view value) {
520 std::string lower = ToLowerCopy(std::string(value));
521 if (lower == "allow") {
523 }
524 if (lower == "block") {
526 }
527 if (lower == "read_only") {
529 }
531}
532
533// YazeProject Implementation
535 auto& provider = zelda3::GetResourceLabels();
536 if (provider.hack_manifest() == &hack_manifest) {
537 provider.SetHackManifest(nullptr);
538 }
539 if (provider.GetAllProjectLabels() == &resource_labels) {
540 provider.SetProjectLabels(nullptr);
541 }
542}
543
544absl::Status YazeProject::Create(const std::string& project_name,
545 const std::string& base_path) {
546 name = project_name;
547 filepath = base_path + "/" + project_name + ".yaze";
548
549 // Initialize metadata
550 auto now = std::chrono::system_clock::now();
551 auto time_t = std::chrono::system_clock::to_time_t(now);
552 std::stringstream ss;
553 ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
554
555 metadata.created_date = ss.str();
556 metadata.last_modified = ss.str();
558 metadata.version = "2.0";
559 metadata.created_by = "YAZE";
561
563
564#ifndef __EMSCRIPTEN__
565 // Create project directory structure
566 std::filesystem::path project_dir(base_path + "/" + project_name);
567 std::filesystem::create_directories(project_dir);
568 std::filesystem::create_directories(project_dir / "code");
569 std::filesystem::create_directories(project_dir / "assets");
570 std::filesystem::create_directories(project_dir / "patches");
571 std::filesystem::create_directories(project_dir / "backups");
572 std::filesystem::create_directories(project_dir / "output");
573
574 // Set folder paths
575 code_folder = (project_dir / "code").string();
576 assets_folder = (project_dir / "assets").string();
577 patches_folder = (project_dir / "patches").string();
578 rom_backup_folder = (project_dir / "backups").string();
579 output_folder = (project_dir / "output").string();
580 labels_filename = (project_dir / "labels.txt").string();
581 symbols_filename = (project_dir / "symbols.txt").string();
582#else
583 // WASM: keep paths relative; persistence handled by WasmStorage/IDBFS
584 code_folder = "code";
585 assets_folder = "assets";
586 patches_folder = "patches";
587 rom_backup_folder = "backups";
588 output_folder = "output";
589 labels_filename = "labels.txt";
590 symbols_filename = "symbols.txt";
591#endif
592
593 return Save();
594}
595
596// static
597std::string YazeProject::ResolveBundleRoot(const std::string& path) {
598 if (path.empty()) {
599 return {};
600 }
601
602 // Walk up the path hierarchy looking for a directory whose filename
603 // (extension) is ".yazeproj". The first match from the leaf upward wins.
604 std::error_code ec;
605 auto current = std::filesystem::path(path).lexically_normal();
606
607 for (; !current.empty(); current = current.parent_path()) {
608 if (current.extension() == ".yazeproj") {
609 // Must be an existing directory to count as a valid bundle root.
610 if (std::filesystem::is_directory(current, ec) && !ec) {
611 return current.string();
612 }
613 }
614 // Guard against infinite loop at the filesystem root.
615 if (current == current.parent_path()) {
616 break;
617 }
618 }
619
620 return {};
621}
622
623absl::Status YazeProject::Open(const std::string& project_path) {
624 // Resolve bundle root: if the user opened a file *inside* a .yazeproj
625 // bundle, normalize to the bundle root directory so the existing
626 // .yazeproj handling takes over.
627 std::string resolved_path = project_path;
628 const std::string bundle_root = ResolveBundleRoot(project_path);
629 if (!bundle_root.empty() && bundle_root != project_path) {
630 // The user pointed at a file inside a bundle; redirect to the root.
631 resolved_path = bundle_root;
632 }
633
634#ifndef __EMSCRIPTEN__
635 // Keep the project root stable even when a caller supplies a relative path.
636 // All project-relative files and registry fallbacks must resolve beside the
637 // project, not against whichever working directory happens to be active
638 // later in the session.
639 std::error_code absolute_ec;
640 const auto absolute_path =
641 std::filesystem::absolute(resolved_path, absolute_ec).lexically_normal();
642 if (!absolute_ec) {
643 resolved_path = absolute_path.string();
644 }
645#endif
646
647 filepath = resolved_path;
648
649#ifdef __EMSCRIPTEN__
650 // Prefer persistent storage in WASM builds
651 auto storage_key = MakeStorageKey("project");
652 auto storage_or = platform::WasmStorage::LoadProject(storage_key);
653 if (storage_or.ok()) {
654 return ParseFromString(storage_or.value());
655 }
656#endif
657
658 // Determine format and load accordingly
659 absl::Status load_status;
660 if (resolved_path.ends_with(".yazeproj")) {
662
663 const std::filesystem::path bundle_path(resolved_path);
664 std::error_code ec;
665 if (!std::filesystem::exists(bundle_path, ec) || ec ||
666 !std::filesystem::is_directory(bundle_path, ec) || ec) {
667 return absl::InvalidArgumentError(
668 absl::StrFormat("Project bundle does not exist: %s", resolved_path));
669 }
670
671 // Bundle convention: store the actual project config at the root so both
672 // desktop and iOS can open the same `.yazeproj` directory.
673 const std::filesystem::path project_file = bundle_path / "project.yaze";
674 filepath = project_file.string();
675
676 if (!std::filesystem::exists(project_file, ec) || ec) {
677 // Create a minimal portable project file for the bundle if missing.
679 name = bundle_path.stem().string();
680
681 // Initialize metadata timestamps (Create() normally does this).
682 auto now = std::chrono::system_clock::now();
683 auto time_t = std::chrono::system_clock::to_time_t(now);
684 std::stringstream ss;
685 ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
686 if (metadata.created_date.empty()) {
687 metadata.created_date = ss.str();
688 }
689 metadata.last_modified = ss.str();
690 if (metadata.yaze_version.empty()) {
692 }
693 if (metadata.version.empty()) {
694 metadata.version = "2.0";
695 }
696 if (metadata.created_by.empty()) {
697 metadata.created_by = "YAZE";
698 }
699 if (metadata.project_id.empty()) {
701 }
702
703 // Bundle layout defaults (paths stored as absolute; serializer writes
704 // relative values for portability).
705 const std::filesystem::path rom_candidate = bundle_path / "rom";
706 // Always set the expected bundle ROM path even if the file is not yet
707 // present on disk (e.g. still downloading from iCloud). The load
708 // attempt in LoadProjectWithRom() handles the missing-file case without
709 // corrupting the project by saving a temporary path.
710 rom_filename = rom_candidate.string();
711
712 const std::filesystem::path project_dir = bundle_path / "project";
713 const std::filesystem::path code_dir = bundle_path / "code";
714 if (std::filesystem::exists(project_dir, ec) &&
715 std::filesystem::is_directory(project_dir, ec) && !ec) {
716 code_folder = project_dir.string();
717 } else if (std::filesystem::exists(code_dir, ec) &&
718 std::filesystem::is_directory(code_dir, ec) && !ec) {
719 code_folder = code_dir.string();
720 }
721
722 assets_folder = (bundle_path / "assets").string();
723 patches_folder = (bundle_path / "patches").string();
724 rom_backup_folder = (bundle_path / "backups").string();
725 output_folder = (bundle_path / "output").string();
726 labels_filename = (bundle_path / "labels.txt").string();
727 symbols_filename = (bundle_path / "symbols.txt").string();
728
729 load_status = SaveToYazeFormat();
730 } else {
731 load_status = LoadFromYazeFormat(project_file.string());
732 }
733 } else if (resolved_path.ends_with(".yaze")) {
735
736 // Try to detect if it's JSON format by peeking at first character
737 std::ifstream file(resolved_path);
738 if (file.is_open()) {
739 std::stringstream buffer;
740 buffer << file.rdbuf();
741 std::string content = buffer.str();
742
743#ifdef YAZE_ENABLE_JSON_PROJECT_FORMAT
744 if (!content.empty() && content.front() == '{') {
745 LOG_DEBUG("Project", "Detected JSON format project file");
746 load_status = LoadFromJsonFormat(resolved_path);
747 } else {
748 load_status = ParseFromString(content);
749 }
750#else
751 load_status = ParseFromString(content);
752#endif
753 } else {
754 return absl::InvalidArgumentError(
755 absl::StrFormat("Cannot open project file: %s", resolved_path));
756 }
757 } else if (resolved_path.ends_with(".zsproj")) {
759 load_status = ImportFromZScreamFormat(resolved_path);
760 } else {
761 return absl::InvalidArgumentError("Unsupported project file format");
762 }
763
764 if (!load_status.ok()) {
765 return load_status;
766 }
767
768 // Normalize project-relative paths so downstream code never depends on the
769 // process working directory (important for iOS and portable bundles).
771
772 // Auto-load z3dk project config if discoverable.
774
775 // Auto-load hack manifest if configured or discoverable
777
778 return absl::OkStatus();
779}
780
781absl::Status YazeProject::Save() {
782 return SaveToYazeFormat();
783}
784
785absl::Status YazeProject::SaveNew() {
786 return SaveToYazeFormat(false);
787}
788
789absl::Status YazeProject::LoadFromString(const std::string& content,
790 const std::string& project_path) {
791 if (project_path.empty()) {
792 return absl::InvalidArgumentError("Project file path cannot be empty");
793 }
794
795 *this = YazeProject();
796
797#ifndef __EMSCRIPTEN__
798 std::error_code ec;
799 const auto absolute_path =
800 std::filesystem::absolute(project_path, ec).lexically_normal();
801 filepath =
802 ec ? std::filesystem::path(project_path).lexically_normal().string()
803 : absolute_path.string();
804#else
805 filepath = project_path;
806#endif
808 try {
810 } catch (const std::exception& error) {
811 return absl::InvalidArgumentError(
812 absl::StrFormat("Invalid project file value: %s", error.what()));
813 }
817 return absl::OkStatus();
818}
819
821 const std::string& content) const {
822 YazeProject saved;
823 saved.filepath = filepath;
824 try {
825 RETURN_IF_ERROR(saved.ParseFromString(content));
827 } catch (const std::exception& error) {
828 return absl::InvalidArgumentError(
829 std::string("Invalid saved project bindings: ") + error.what());
830 }
831 ASSIGN_OR_RETURN(const auto live_text, SerializeToString());
832 ASSIGN_OR_RETURN(const auto saved_text, saved.SerializeToString());
833 const auto bindings = [](const std::string& text) {
834 std::map<std::pair<std::string, std::string>, std::string> values;
835 std::istringstream input(text);
836 std::string line, section;
837 while (std::getline(input, line)) {
838 const auto trimmed = absl::StripAsciiWhitespace(line);
839 if (trimmed.empty() || trimmed.front() == '#')
840 continue;
841 if (trimmed.front() == '[' && trimmed.back() == ']') {
842 section = std::string(trimmed.substr(1, trimmed.size() - 2));
843 continue;
844 }
845 // These sections are transient application preferences, not sources.
846 if (section == "workspace" || section == "keybindings" ||
847 section == "editor_visibility" || section == "agent_settings")
848 continue;
849 const auto [key, value] = ParseKeyValue(std::string(trimmed));
850 if (key.empty() || (section == "project" &&
851 (key == "last_modified" || key == "created_date")))
852 continue;
853 values[{section, key}] = value;
854 }
855 return values;
856 };
857 const auto live_bindings = bindings(live_text);
858 const auto saved_bindings = bindings(saved_text);
859 const auto mismatch = [](const auto& key) {
860 return absl::FailedPreconditionError(
861 "Saved project source bindings differ from the active project: [" +
862 key.first + "] " + key.second);
863 };
864 for (const auto& [key, value] : live_bindings) {
865 const auto saved = saved_bindings.find(key);
866 if (saved == saved_bindings.end() || saved->second != value)
867 return mismatch(key);
868 }
869 for (const auto& [key, value] : saved_bindings) {
870 if (live_bindings.find(key) == live_bindings.end())
871 return mismatch(key);
872 }
873 return absl::OkStatus();
874}
875
876namespace {
877#if defined(YAZE_WITH_JSON) && !defined(__EMSCRIPTEN__)
878absl::Status ExpandedRunError(const std::string& message) {
879 return absl::FailedPreconditionError("Expanded run target unavailable: " +
880 message);
881}
882absl::Status ExpandedRunRequire(bool valid, const std::string& message) {
883 return valid ? absl::OkStatus() : ExpandedRunError(message);
884}
885std::string ExpandedRunPathText(const std::filesystem::path& path) {
886 const auto text = path.generic_u8string();
887 return std::string(text.begin(), text.end());
888}
889absl::StatusOr<std::string> ExpandedRunCanonical(const std::string& text) {
890 const auto path = std::filesystem::u8path(text);
891 if (text.empty() || !path.is_absolute()) {
892 return ExpandedRunError("an absolute evidence path is required");
893 }
894 std::error_code error;
895 const auto canonical = std::filesystem::weakly_canonical(path, error);
896 if (error) {
897 return ExpandedRunError("cannot resolve evidence path: " + text);
898 }
899 return ExpandedRunPathText(canonical);
900}
901#endif
902} // namespace
903
904absl::StatusOr<std::optional<std::string>>
906 const std::string& editing_source_path) const {
907 if (lyra_build_request_file.empty()) {
908 return std::optional<std::string>{};
909 }
910#if !defined(YAZE_WITH_JSON) || defined(__EMSCRIPTEN__)
911 return absl::UnimplementedError(
912 "Expanded run target verification requires desktop JSON support");
913#else
914 namespace fs = std::filesystem;
915 if (!project_opened() || native_save_producer_file.empty() ||
917 build_target.empty() || code_folder.empty() ||
918 editing_source_path.empty()) {
919 return ExpandedRunError("complete saved expanded references are required");
920 }
921 try {
922 ASSIGN_OR_RETURN(const auto descriptor, ExpandedRunCanonical(filepath));
923 const auto resolve = [&](const std::string& ref) {
924 return ExpandedRunCanonical(GetAbsolutePath(ref));
925 };
926 ASSIGN_OR_RETURN(const auto rom, resolve(rom_filename));
927 ASSIGN_OR_RETURN(const auto terrain, resolve(lyra_terrain_file));
928 ASSIGN_OR_RETURN(const auto request_path, resolve(lyra_build_request_file));
929 ASSIGN_OR_RETURN(const auto producer_path,
931 ASSIGN_OR_RETURN(const auto future_proof,
933 ASSIGN_OR_RETURN(const auto candidate, resolve(build_target));
934 ASSIGN_OR_RETURN(const auto engine, resolve(code_folder));
936 const auto authority,
937 core::GetNativeSaveContext(editing_source_path, descriptor));
938 const fs::path target = fs::u8path(candidate);
939 const auto relative =
940 target.lexically_relative(fs::u8path(engine) / "Roms");
941 RETURN_IF_ERROR(ExpandedRunRequire(
942 target.filename() == "oos168x.sfc" && !relative.empty() &&
943 !relative.is_absolute() && *relative.begin() != ".." &&
944 !relative.parent_path().empty(),
945 "build_target must name a generation under the project engine"));
946
947 // These are freshness joins for artifacts already authenticated by Oracle's
948 // compiler. They do not reproduce allocation or native-verifier policy.
949 uint64_t remaining = 8ULL * 1024 * 1024 * 1024;
950 std::vector<Json> observed;
951 const auto check_file = [&](const Json& row) -> absl::Status {
952 ASSIGN_OR_RETURN(const auto name,
953 ExpandedRunCanonical(row.at("path").get<std::string>()));
954 const auto path = fs::u8path(name);
955 const auto expected = row.at("sha256").get<std::string>();
956 std::error_code file_error;
957 const auto size = fs::file_size(path, file_error);
958 RETURN_IF_ERROR(ExpandedRunRequire(
959 !file_error && fs::is_regular_file(path, file_error) && !file_error &&
960 fs::u8path(row.at("path").get<std::string>()) == path &&
961 expected.size() == 64 && size <= 1024ULL * 1024 * 1024 &&
962 size <= remaining,
963 "an evidence file is missing, changed, or exceeds its bounds"));
964 remaining -= size;
965 for (const char* key : {"size", "bytes"}) {
966 if (row.contains(key)) {
968 ExpandedRunRequire(row.at(key).is_number_unsigned() &&
969 row.at(key).get<uint64_t>() == size,
970 "an evidence byte count differs"));
971 }
972 }
973 ASSIGN_OR_RETURN(const auto actual,
975 return ExpandedRunRequire(actual == expected,
976 "evidence changed: " + name);
977 };
978 const auto check = [&](const Json& row) -> absl::Status {
979 RETURN_IF_ERROR(ExpandedRunRequire(observed.size() < 8192,
980 "too many evidence bindings"));
981 RETURN_IF_ERROR(check_file(row));
982 observed.push_back(row);
983 return absl::OkStatus();
984 };
985 const auto rows = [&](const Json& values) -> absl::Status {
986 RETURN_IF_ERROR(ExpandedRunRequire(
987 (values.is_array() || values.is_object()) && values.size() <= 4096,
988 "an evidence binding collection is malformed"));
989 for (const auto& row : values)
990 RETURN_IF_ERROR(check(row));
991 return absl::OkStatus();
992 };
993 const auto read_text =
994 [&](const std::string& name) -> absl::StatusOr<std::string> {
995 std::error_code file_error;
996 const auto path = fs::u8path(name);
997 const auto size = fs::file_size(path, file_error);
999 ExpandedRunRequire(!file_error && size <= 16 * 1024 * 1024,
1000 "metadata is missing or too large"));
1001 std::ifstream stream(path, std::ios::binary);
1002 std::string raw(static_cast<size_t>(size), '\0');
1003 stream.read(raw.data(), static_cast<std::streamsize>(raw.size()));
1004 char extra;
1005 RETURN_IF_ERROR(ExpandedRunRequire(
1006 stream.gcount() == static_cast<std::streamsize>(raw.size()) &&
1007 !stream.get(extra) && !stream.bad(),
1008 "metadata changed while reading"));
1009 RETURN_IF_ERROR(check(Json{
1010 {"path", name}, {"sha256", core::ComputeSourceArtifactSha256(raw)}}));
1011 return raw;
1012 };
1013 const auto load = [&](const std::string& name) -> absl::StatusOr<Json> {
1014 ASSIGN_OR_RETURN(const auto raw, read_text(name));
1015 auto document =
1016 Json::parse(raw, [](int depth, Json::parse_event_t, Json&) {
1017 if (depth > 64)
1018 throw std::runtime_error("evidence nesting is too deep");
1019 return true;
1020 });
1021 RETURN_IF_ERROR(ExpandedRunRequire(document.is_object(),
1022 "evidence JSON must be an object"));
1023 return document;
1024 };
1025 const auto same_path = [&](const Json& value,
1026 const std::string& expected) -> absl::Status {
1027 ASSIGN_OR_RETURN(const auto path,
1028 ExpandedRunCanonical(value.get<std::string>()));
1029 return ExpandedRunRequire(path == expected,
1030 "evidence belongs to another path");
1031 };
1032 const auto sibling = [&](const char* name) {
1033 return ExpandedRunPathText(target.parent_path() / name);
1034 };
1035 ASSIGN_OR_RETURN(const auto build, load(sibling("oos168x.build.json")));
1036 RETURN_IF_ERROR(ExpandedRunRequire(
1037 build.at("schema_version") == 1 &&
1038 (build.at("state") == "completed" ||
1039 build.at("state") == "completed_with_gaps") &&
1040 build.at("finish").at("exit_code") == 0 &&
1041 build.at("finish").at("required_gaps") == Json::array(),
1042 "the selected build is incomplete or failed"));
1043 RETURN_IF_ERROR(same_path(build.at("root"), engine));
1044 const auto& artifacts = build.at("artifacts");
1045 for (const char* key :
1046 {"output_rom", "symbols", "lyra_prepare", "lyra_verification"}) {
1048 ExpandedRunRequire(artifacts.at(key).contains("size"),
1049 "a build artifact byte count is absent"));
1050 RETURN_IF_ERROR(check(artifacts.at(key)));
1051 }
1052 RETURN_IF_ERROR(check(build.at("base_rom")));
1053 RETURN_IF_ERROR(same_path(build.at("base_rom").at("path"), rom));
1055 same_path(artifacts.at("output_rom").at("path"), candidate));
1057 ExpandedRunRequire(artifacts.at("output_rom").at("size") == 0x400000,
1058 "the expanded output must be exactly 4 MiB"));
1060 same_path(artifacts.at("symbols").at("path"), sibling("oos168x.sym")));
1061 RETURN_IF_ERROR(same_path(artifacts.at("lyra_verification").at("path"),
1062 sibling("oos168x.lyra-verification.json")));
1064 const auto prepared,
1065 load(artifacts.at("lyra_prepare").at("path").get<std::string>()));
1067 const auto verified,
1068 load(artifacts.at("lyra_verification").at("path").get<std::string>()));
1069 RETURN_IF_ERROR(ExpandedRunRequire(
1070 prepared.at("kind") == "lyra.current_build_prepare.v1" &&
1071 verified.at("kind") == "lyra.current_build_verification.v1" &&
1072 verified.at("compiled_consumers_verified") == true &&
1073 verified.at("prepared_sha256") ==
1074 artifacts.at("lyra_prepare").at("sha256") &&
1075 verified.at("compiled_rom_sha256") ==
1076 artifacts.at("output_rom").at("sha256") &&
1077 verified.at("symbols_sha256") ==
1078 artifacts.at("symbols").at("sha256") &&
1079 verified.at("saved_rom_sha256") ==
1080 build.at("base_rom").at("sha256") &&
1081 prepared.at("saved_rom_sha256") == verified.at("saved_rom_sha256"),
1082 "compiled verification does not bind this build"));
1083 for (const char* flag :
1084 {"selected", "allocation_granted", "producer_enforcement_verified",
1085 "runtime_admission", "ordinary_build_ready"}) {
1086 RETURN_IF_ERROR(ExpandedRunRequire(
1087 prepared.at(flag).is_boolean() && prepared.at(flag).get<bool>(),
1088 "expanded build admission is incomplete"));
1089 }
1091 ExpandedRunRequire(!prepared.contains("runtime_scope"),
1092 "a private preview is not an ordinary run target"));
1093 RETURN_IF_ERROR(same_path(prepared.at("project"), descriptor));
1094 RETURN_IF_ERROR(same_path(prepared.at("base_rom"), rom));
1095 RETURN_IF_ERROR(same_path(prepared.at("request"), request_path));
1096 RETURN_IF_ERROR(rows(prepared.at("inputs")));
1097 const Json* request_binding = nullptr;
1098 for (const auto& row : prepared.at("inputs")) {
1099 ASSIGN_OR_RETURN(const auto path,
1100 ExpandedRunCanonical(row.at("path").get<std::string>()));
1101 if (path == request_path)
1102 request_binding = &row;
1103 }
1105 ExpandedRunRequire(request_binding != nullptr,
1106 "the preparation omits its request binding"));
1107 RETURN_IF_ERROR(check(*request_binding));
1108 ASSIGN_OR_RETURN(const auto request, load(request_path));
1109 const auto& live = request.at("live");
1110 const auto& plan = prepared.at("terrain_plan");
1111 RETURN_IF_ERROR(ExpandedRunRequire(
1112 request.at("kind") == "lyra.current_save_transfer_request.v1" &&
1113 plan.at("target") == request.at("target") &&
1114 plan.at("transfer_id") == request.at("transfer_id") &&
1115 plan.at("generation") == live.at("generation") &&
1116 plan.at("operation_id") == live.at("operation_id") &&
1117 plan.at("save_context") == live.at("save_context"),
1118 "the prepared transfer or saved generation differs"));
1119 RETURN_IF_ERROR(same_path(request.at("target").at("path"), candidate));
1120 RETURN_IF_ERROR(same_path(live.at("project"), descriptor));
1121 RETURN_IF_ERROR(same_path(live.at("producer").at("path"), producer_path));
1122 RETURN_IF_ERROR(same_path(live.at("enforcement_receipt"), future_proof));
1123 RETURN_IF_ERROR(same_path(live.at("inputs").at("rom").at("path"), rom));
1125 same_path(live.at("inputs").at("project").at("path"), descriptor));
1127 same_path(live.at("inputs").at("terrain").at("path"), terrain));
1128 RETURN_IF_ERROR(rows(live.at("inputs")));
1129 RETURN_IF_ERROR(rows(request.at("inputs")));
1130 for (const char* key : {"producer", "save_receipt", "save_context"})
1131 RETURN_IF_ERROR(check(live.at(key)));
1132 for (const char* key : {"observation", "save_snapshot", "producer_snapshot",
1133 "context_snapshot"})
1134 RETURN_IF_ERROR(check(request.at(key)));
1135 const auto& producer = live.at("producer_identity");
1136 RETURN_IF_ERROR(check(producer.at("editor")));
1137 RETURN_IF_ERROR(check(producer.at("verifier")));
1138 RETURN_IF_ERROR(rows(producer.at("source_bindings")));
1139 RETURN_IF_ERROR(check(plan.at("enforcement_receipt")));
1140 if (request.contains("native_verification"))
1141 RETURN_IF_ERROR(check(request.at("native_verification")));
1142 if (plan.at("enforcement_owner") == "oracle.current_builder") {
1143 RETURN_IF_ERROR(ExpandedRunRequire(
1144 plan.at("enforcement_receipt") == request.at("native_verification"),
1145 "the builder enforcement binding differs"));
1146 } else {
1148 ExpandedRunRequire(plan.at("enforcement_owner") == "legacy_producer",
1149 "the enforcement owner is unsupported"));
1151 same_path(plan.at("enforcement_receipt").at("path"), future_proof));
1152 }
1153
1154 const auto receipt_path = descriptor + ".native-save.json";
1156 same_path(live.at("save_receipt").at("path"), receipt_path));
1157 RETURN_IF_ERROR(same_path(live.at("save_context").at("path"),
1158 ExpandedRunPathText(authority.path)));
1159 ASSIGN_OR_RETURN(const auto receipt, load(receipt_path));
1160 ASSIGN_OR_RETURN(const auto context,
1161 load(ExpandedRunPathText(authority.path)));
1162 RETURN_IF_ERROR(ExpandedRunRequire(
1163 receipt.at("kind") == "yaze.native_save.v1" &&
1164 receipt.at("bindings_complete") == true &&
1165 receipt.at("binding_errors") == Json::array() &&
1166 live.at("generation").is_number_unsigned() &&
1167 live.at("generation").get<uint64_t>() > 0 &&
1168 live.at("operation_id").is_string() &&
1169 !live.at("operation_id").get_ref<const std::string&>().empty() &&
1170 receipt.at("generation") == live.at("generation") &&
1171 receipt.at("operation_id") == live.at("operation_id") &&
1172 context.at("kind") == "yaze.native_save_context.v1" &&
1173 context.at("state") == "committed" &&
1174 context.at("native_commit").at("generation") ==
1175 live.at("generation") &&
1176 context.at("native_commit").at("operation_id") ==
1177 live.at("operation_id"),
1178 "native Save completion or current context differs"));
1179 RETURN_IF_ERROR(same_path(receipt.at("receipt_path"), receipt_path));
1180 RETURN_IF_ERROR(same_path(context.at("native_commit").at("receipt_path"),
1181 receipt_path));
1182 RETURN_IF_ERROR(same_path(context.at("editing_source_path"),
1183 authority.editing_source_path));
1184 RETURN_IF_ERROR(same_path(context.at("project_path"), descriptor));
1185 RETURN_IF_ERROR(same_path(context.at("rom_path"), rom));
1186 const Json* saved_producer = nullptr;
1187 for (const auto& row : receipt.at("artifacts")) {
1188 if (row.at("role") == "producer")
1189 saved_producer = &row;
1190 }
1191 RETURN_IF_ERROR(ExpandedRunRequire(
1192 saved_producer != nullptr &&
1193 context.at("producer") == *saved_producer &&
1194 saved_producer->at("sha256") == producer.at("editor").at("sha256"),
1195 "native Save and context producers differ"));
1196 ASSIGN_OR_RETURN(const auto editor_path,
1197 ExpandedRunCanonical(
1198 producer.at("editor").at("path").get<std::string>()));
1199 RETURN_IF_ERROR(same_path(saved_producer->at("path"), editor_path));
1200 ASSIGN_OR_RETURN(const auto saved_descriptor, read_text(descriptor));
1202 for (const auto& binding : observed)
1203 RETURN_IF_ERROR(check_file(binding));
1204 return std::optional<std::string>(candidate);
1205 } catch (const std::exception& error) {
1206 return ExpandedRunError(
1207 std::string("invalid or incomplete build evidence: ") + error.what());
1208 }
1209#endif
1210}
1211absl::Status YazeProject::SaveAs(const std::string& new_path) {
1212 std::string old_filepath = filepath;
1213 filepath = new_path;
1214
1215 auto status = Save();
1216 if (!status.ok()) {
1217 filepath = old_filepath; // Restore on failure
1218 }
1219
1220 return status;
1221}
1222
1224 return hack_manifest.loaded() &&
1225 (hack_manifest.oracle_progression_state().has_value() ||
1226 ToLowerCopy(hack_manifest.hack_name()).find("oracle") !=
1227 std::string::npos);
1228}
1229
1231 const std::string& new_path, const core::LyraTerrainDocument& terrain,
1232 const std::optional<std::string>& expected_source_bytes) {
1233#ifdef __EMSCRIPTEN__
1234 return absl::UnimplementedError(
1235 "Saving an independent Lyra project copy requires filesystem storage");
1236#else
1237 namespace fs = std::filesystem;
1238 if (!project_opened() || lyra_terrain_file.empty() || new_path.empty()) {
1239 return absl::FailedPreconditionError(
1240 "An open project and Lyra terrain are required for Save As");
1241 }
1242 auto read =
1243 [](const fs::path& path) -> absl::StatusOr<std::optional<std::string>> {
1244 std::error_code ec;
1245 if (!fs::exists(path, ec) && !ec) {
1246 return std::nullopt;
1247 }
1248 if (ec || !fs::is_regular_file(path, ec) || ec ||
1249 fs::file_size(path, ec) > 16 * 1024 * 1024 || ec) {
1250 return absl::FailedPreconditionError(
1251 "Project Save As source or destination is not a readable file");
1252 }
1253 std::ifstream stream(path, std::ios::binary);
1254 if (!stream) {
1255 return absl::PermissionDeniedError("Cannot read project Save As file");
1256 }
1257 std::string bytes{std::istreambuf_iterator<char>(stream), {}};
1258 if (stream.bad()) {
1259 return absl::DataLossError(
1260 "Could not finish reading project Save As file");
1261 }
1262 return std::optional<std::string>(std::move(bytes));
1263 };
1264
1265 auto candidate = *this;
1266 // Preserve the original meaning of every relative asset before relocating.
1267 candidate.NormalizePathsToAbsolute();
1268 std::error_code ec;
1269 const fs::path source_project = fs::absolute(candidate.filepath, ec);
1270 if (ec) {
1271 return absl::InvalidArgumentError("Cannot resolve the source project path");
1272 }
1273 const fs::path source_terrain = candidate.lyra_terrain_file;
1274 const fs::path destination = fs::absolute(new_path, ec).lexically_normal();
1275 if (ec) {
1276 return absl::InvalidArgumentError(
1277 "Cannot resolve the project Save As path");
1278 }
1279 fs::path destination_terrain = destination;
1280 destination_terrain.replace_extension(".lyra-terrain.json");
1281 candidate.filepath = destination.string();
1282 candidate.lyra_terrain_file = destination_terrain.string();
1283
1284 const std::vector<fs::path> targets = {destination, destination_terrain};
1285 std::vector<fs::path> read_only_targets = {source_project, source_terrain};
1286 if (!candidate.rom_filename.empty()) {
1287 read_only_targets.push_back(candidate.rom_filename);
1288 }
1289 if (!candidate.lyra_build_request_file.empty()) {
1290 read_only_targets.push_back(candidate.lyra_build_request_file);
1291 }
1292 for (const auto& reference : {candidate.native_save_producer_file,
1293 candidate.native_save_transfer_proof_file,
1294 candidate.native_save_receipt_file}) {
1295 if (!reference.empty()) {
1296 read_only_targets.push_back(reference);
1297 }
1298 }
1300 auto lock,
1302 targets, {"Lyra project", "Lyra project files"}, read_only_targets));
1303 ASSIGN_OR_RETURN(auto original_project, read(source_project));
1304 if (!original_project) {
1305 return absl::NotFoundError("The original project file is missing");
1306 }
1307 ASSIGN_OR_RETURN(auto original_terrain, read(source_terrain));
1308 if (original_terrain != expected_source_bytes) {
1309 return absl::FailedPreconditionError(
1310 "Lyra terrain changed on disk; refusing stale Save As");
1311 }
1312 ASSIGN_OR_RETURN(auto previous_destination, read(destination));
1313 ASSIGN_OR_RETURN(auto previous_terrain, read(destination_terrain));
1314 if (previous_terrain) {
1315 return absl::AlreadyExistsError(
1316 "The destination project already owns Lyra terrain; choose another "
1317 "project name");
1318 }
1319 auto now =
1320 std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
1321 std::stringstream timestamp;
1322 timestamp << std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M:%S");
1323 candidate.metadata.last_modified = timestamp.str();
1324 if (candidate.music_persistence.storage_key.empty()) {
1325 candidate.music_persistence.storage_key = candidate.MakeStorageKey("music");
1326 }
1327 ASSIGN_OR_RETURN(auto descriptor, candidate.SerializeToString());
1328 const std::string terrain_bytes = terrain.Serialize();
1330 *lock,
1331 {{source_project, original_project, *original_project},
1332 {destination, previous_destination, descriptor},
1333 {destination_terrain, std::nullopt, terrain_bytes}},
1334 core::ComputeSourceArtifactSha256(*original_project),
1335 [&]() -> absl::Status {
1336 ASSIGN_OR_RETURN(auto source_after, read(source_terrain));
1337 if (source_after != expected_source_bytes) {
1338 return absl::FailedPreconditionError(
1339 "Lyra terrain changed during Save As");
1340 }
1341 ASSIGN_OR_RETURN(auto saved, read(destination_terrain));
1342 if (!saved) {
1343 return absl::DataLossError("Saved Lyra terrain is missing");
1344 }
1345 return core::LyraTerrainDocument::Parse(*saved, terrain.profile())
1346 .status();
1347 }));
1348 *this = std::move(candidate);
1349 return absl::OkStatus();
1350#endif
1351}
1352
1353std::string YazeProject::MakeStorageKey(absl::string_view suffix) const {
1354 std::string base;
1355 if (!metadata.project_id.empty()) {
1356 base = metadata.project_id;
1357 } else if (!name.empty()) {
1358 base = name;
1359 } else if (!filepath.empty()) {
1360 base = std::filesystem::path(filepath).stem().string();
1361 }
1362 base = SanitizeStorageKey(base);
1363 if (suffix.empty()) {
1364 return base;
1365 }
1366 return absl::StrFormat("%s_%s", base, suffix);
1367}
1368
1369namespace {
1370// A '\r' not followed by '\n' is a classic-Mac line ending. The parser can
1371// normalize CRLF, but a lone CR would split a line somewhere it does not
1372// expect, so both directions refuse it.
1373bool ContainsLoneCarriageReturn(const std::string& content) {
1374 for (size_t i = 0; i < content.size(); ++i) {
1375 if (content[i] == '\r' &&
1376 (i + 1 >= content.size() || content[i + 1] != '\n')) {
1377 return true;
1378 }
1379 }
1380 return false;
1381}
1382
1383constexpr absl::string_view kProjectFileFooter = "# End of YAZE Project File";
1384
1385// Sections ParseFromString models. Everything else is passed through.
1386bool IsKnownProjectSection(absl::string_view name) {
1387 static constexpr absl::string_view kKnown[] = {"project",
1388 "files",
1389 "sprite_assets",
1390 "rom",
1391 "feature_flags",
1392 "workspace",
1393 "dungeon_overlay",
1394 "graphics_sheets",
1395 "atlas",
1396 "planning",
1397 "rom_addresses",
1398 "custom_objects",
1399 "agent_settings",
1400 "build",
1401 "keybindings",
1402 "editor_visibility",
1403 "zscream_compatibility",
1404 "music"};
1405 if (absl::StartsWith(name, "labels_")) {
1406 return true;
1407 }
1408 return std::find(std::begin(kKnown), std::end(kKnown), name) !=
1409 std::end(kKnown);
1410}
1411
1412// Comments SerializeToString writes itself; keeping them would duplicate
1413// them on every save.
1414bool IsGeneratedProjectComment(absl::string_view line, bool before_sections) {
1415 if (line == kProjectFileFooter) {
1416 return true;
1417 }
1418 if (!before_sections) {
1419 return false;
1420 }
1421 return absl::StartsWith(line, "# yaze Project File") ||
1422 absl::StartsWith(line, "# Format Version:") ||
1423 absl::StartsWith(line, "# Generated by YAZE") ||
1424 absl::StartsWith(line, "# Last Modified:");
1425}
1426
1428 ProjectFilePassthrough& passthrough, const std::string& name) {
1429 for (auto& section : passthrough.sections) {
1430 if (section.name == name) {
1431 return section;
1432 }
1433 }
1434 passthrough.sections.push_back({name, false, {}});
1435 return passthrough.sections.back();
1436}
1437
1438bool IsKeyLine(absl::string_view line) {
1439 return !line.empty() && line.front() != '#' &&
1440 line.find('=') != absl::string_view::npos;
1441}
1442
1443// Writes `canonical` (SerializeToString's own output) with the passthrough
1444// lines put back. See ProjectFilePassthrough for the placement rules.
1446 const std::string& canonical, const ProjectFilePassthrough& passthrough) {
1447 if (passthrough.empty()) {
1448 return canonical;
1449 }
1451
1452 struct CanonicalSection {
1453 std::string header;
1454 std::string name;
1455 std::vector<std::string> lines;
1456 };
1457 std::vector<std::string> preamble;
1458 std::vector<CanonicalSection> canonical_sections;
1459 bool has_footer = false;
1460 for (absl::string_view line : absl::StrSplit(canonical, '\n')) {
1461 if (line == kProjectFileFooter) {
1462 has_footer = true;
1463 continue;
1464 }
1465 if (line.size() >= 2 && line.front() == '[' && line.back() == ']') {
1466 canonical_sections.push_back(
1467 {std::string(line),
1468 std::string(line.substr(1, line.size() - 2)),
1469 {}});
1470 continue;
1471 }
1472 if (line.empty()) {
1473 continue;
1474 }
1475 (canonical_sections.empty() ? preamble : canonical_sections.back().lines)
1476 .push_back(std::string(line));
1477 }
1478
1479 auto find_section =
1480 [&](absl::string_view name) -> const ProjectFilePassthrough::Section* {
1481 for (const auto& section : passthrough.sections) {
1482 if (section.name == name) {
1483 return &section;
1484 }
1485 }
1486 return nullptr;
1487 };
1488
1489 std::ostringstream out;
1490 // Every comment and unknown line of `section`, in file order.
1491 auto write_all = [&](const ProjectFilePassthrough::Section& section) {
1492 for (const auto& line : section.lines) {
1493 if (line.kind != Kind::kKnownKey) {
1494 out << line.text << "\n";
1495 }
1496 }
1497 };
1498
1499 for (const auto& line : preamble) {
1500 out << line << "\n";
1501 }
1502 out << "\n";
1503 if (const auto* before = find_section(""); before != nullptr) {
1504 write_all(*before);
1505 if (!before->lines.empty()) {
1506 out << "\n";
1507 }
1508 }
1509
1510 std::vector<const ProjectFilePassthrough::Section*> merged;
1511 for (const auto& section : canonical_sections) {
1512 out << section.header << "\n";
1513 const auto* kept = find_section(section.name);
1514 if (kept == nullptr) {
1515 for (const auto& line : section.lines) {
1516 out << line << "\n";
1517 }
1518 out << "\n";
1519 continue;
1520 }
1521 merged.push_back(kept);
1522
1523 // Comments belong to the next key line after them in the file.
1524 std::vector<std::pair<std::string, std::vector<std::string>>> anchored;
1525 std::vector<std::string> pending;
1526 std::vector<std::pair<std::string, std::vector<std::string>>> unknown;
1527 for (const auto& line : kept->lines) {
1528 if (line.kind == Kind::kComment) {
1529 pending.push_back(line.text);
1530 } else if (line.kind == Kind::kUnknownLine) {
1531 unknown.push_back({line.text, std::move(pending)});
1532 pending.clear();
1533 } else if (!pending.empty()) {
1534 anchored.push_back({line.key, std::move(pending)});
1535 pending.clear();
1536 }
1537 }
1538 std::vector<bool> anchor_written(anchored.size(), false);
1539 for (const auto& line : section.lines) {
1540 if (IsKeyLine(line)) {
1541 const std::string key = ParseKeyValue(line).first;
1542 for (size_t i = 0; i < anchored.size(); ++i) {
1543 if (!anchor_written[i] && anchored[i].first == key) {
1544 for (const auto& comment : anchored[i].second) {
1545 out << comment << "\n";
1546 }
1547 anchor_written[i] = true;
1548 }
1549 }
1550 }
1551 out << line << "\n";
1552 }
1553 for (const auto& [text, comments] : unknown) {
1554 for (const auto& comment : comments) {
1555 out << comment << "\n";
1556 }
1557 out << text << "\n";
1558 }
1559 // Comments whose key this build no longer writes, then trailing ones.
1560 for (size_t i = 0; i < anchored.size(); ++i) {
1561 if (!anchor_written[i]) {
1562 for (const auto& comment : anchored[i].second) {
1563 out << comment << "\n";
1564 }
1565 }
1566 }
1567 for (const auto& comment : pending) {
1568 out << comment << "\n";
1569 }
1570 out << "\n";
1571 }
1572
1573 // Unknown sections, and known sections this build left out (for example
1574 // an emptied [graphics_sheets]) that still carry comments or unknown keys.
1575 for (const auto& section : passthrough.sections) {
1576 if (section.name.empty() ||
1577 std::find(merged.begin(), merged.end(), &section) != merged.end()) {
1578 continue;
1579 }
1580 const bool has_content = std::any_of(
1581 section.lines.begin(), section.lines.end(),
1582 [](const auto& line) { return line.kind != Kind::kKnownKey; });
1583 if (!has_content) {
1584 continue;
1585 }
1586 out << "[" << section.name << "]\n";
1587 write_all(section);
1588 out << "\n";
1589 }
1590
1591 if (has_footer) {
1592 out << kProjectFileFooter << "\n";
1593 }
1594 return out.str();
1595}
1596} // namespace
1597
1598bool IsKnownProjectFileSection(absl::string_view name) {
1599 return IsKnownProjectSection(name);
1600}
1601
1602absl::StatusOr<std::string> YazeProject::SerializeToString() const {
1603 std::ostringstream file;
1604
1605 // Write header comment
1606 file << "# yaze Project File\n";
1607 file << "# Format Version: 2.0\n";
1608 file << "# Generated by YAZE " << metadata.yaze_version << "\n";
1609 file << "# Last Modified: " << metadata.last_modified << "\n\n";
1610
1611 // Project section
1612 file << "[project]\n";
1613 file << "name=" << name << "\n";
1614 file << "description=" << metadata.description << "\n";
1615 file << "author=" << metadata.author << "\n";
1616 file << "license=" << metadata.license << "\n";
1617 file << "version=" << metadata.version << "\n";
1618 file << "created_date=" << metadata.created_date << "\n";
1619 file << "last_modified=" << metadata.last_modified << "\n";
1620 file << "yaze_version=" << metadata.yaze_version << "\n";
1621 file << "created_by=" << metadata.created_by << "\n";
1622 file << "project_id=" << metadata.project_id << "\n";
1623 file << "tags=" << absl::StrJoin(metadata.tags, ",") << "\n\n";
1624
1625 // Files section
1626 file << "[files]\n";
1627 file << "rom_filename=" << GetRelativePath(rom_filename) << "\n";
1628 file << "rom_backup_folder=" << GetRelativePath(rom_backup_folder) << "\n";
1629 file << "code_folder=" << GetRelativePath(code_folder) << "\n";
1630 file << "assets_folder=" << GetRelativePath(assets_folder) << "\n";
1631 file << "patches_folder=" << GetRelativePath(patches_folder) << "\n";
1632 file << "labels_filename=" << GetRelativePath(labels_filename) << "\n";
1633 file << "symbols_filename=" << GetRelativePath(symbols_filename) << "\n";
1634 if (!overworld_graphics_preview.empty()) {
1635 file << "overworld_graphics_preview="
1637 }
1638 if (!dungeon_tile_patterns.empty()) {
1639 file << "dungeon_tile_patterns="
1641 }
1642 if (!cutscene_shots.empty()) {
1643 file << "cutscene_shots="
1645 }
1646 if (!custom_collision_json.empty()) {
1647 file << "custom_collision_json="
1649 }
1650 file << "output_folder=" << GetRelativePath(output_folder) << "\n";
1651 file << "custom_objects_folder=" << GetRelativePath(custom_objects_folder)
1652 << "\n";
1653 file << "palette_catalog_file="
1655 file << "terrain_catalog_file="
1657 file << "lyra_terrain_file="
1659 file << "lyra_build_request_file="
1661 if (!native_save_producer_file.empty()) {
1662 file << "native_save_producer_file="
1664 }
1665 if (!native_save_transfer_proof_file.empty()) {
1666 file << "native_save_transfer_proof_file="
1668 << "\n";
1669 }
1670 if (!native_save_receipt_file.empty()) {
1671 file << "native_save_receipt_file="
1673 }
1674 file << "hack_manifest_file=" << GetRelativePath(hack_manifest_file) << "\n";
1675 file << "sprite_catalog_file="
1677 file << "sprite_source_root="
1679 file << "additional_roms=" << absl::StrJoin(additional_roms, ",") << "\n\n";
1680
1681 file << "[sprite_assets]\n";
1682 for (size_t i = 0; i < sprite_assets.size(); ++i) {
1683 auto asset = sprite_assets[i];
1684 asset.zsm_path = GetRelativePath(GetAbsolutePath(asset.zsm_path));
1685 for (auto& source : asset.graphics_sources) {
1686 if (source.kind == "bin") {
1687 source.path = GetRelativePath(GetAbsolutePath(source.path));
1688 }
1689 }
1690 file << "asset_" << i << "=" << SpriteAssetToJson(asset).dump() << "\n";
1691 }
1692 file << "\n";
1693
1694 // ROM metadata section
1695 file << "[rom]\n";
1696 file << "role=" << RomRoleToString(rom_metadata.role) << "\n";
1697 file << "expected_hash=" << rom_metadata.expected_hash << "\n";
1698 file << "write_policy=" << RomWritePolicyToString(rom_metadata.write_policy)
1699 << "\n\n";
1700
1701 // Feature flags section
1702 file << "[feature_flags]\n";
1703 file << "load_custom_overworld="
1704 << (feature_flags.overworld.kLoadCustomOverworld ? "true" : "false")
1705 << "\n";
1706 file << "apply_zs_custom_overworld_asm="
1708 : "false")
1709 << "\n";
1710 file << "enable_special_world_expansion="
1712 : "false")
1713 << "\n";
1714 file << "save_with_change_queue="
1715 << (feature_flags.kSaveWithChangeQueue ? "true" : "false") << "\n";
1716 file << "save_dungeon_maps="
1717 << (feature_flags.kSaveDungeonMaps ? "true" : "false") << "\n";
1718 file << "save_overworld_maps="
1719 << (feature_flags.overworld.kSaveOverworldMaps ? "true" : "false")
1720 << "\n";
1721 file << "save_overworld_entrances="
1722 << (feature_flags.overworld.kSaveOverworldEntrances ? "true" : "false")
1723 << "\n";
1724 file << "save_overworld_exits="
1725 << (feature_flags.overworld.kSaveOverworldExits ? "true" : "false")
1726 << "\n";
1727 file << "save_overworld_items="
1728 << (feature_flags.overworld.kSaveOverworldItems ? "true" : "false")
1729 << "\n";
1730 file << "save_overworld_sprites="
1731 << (feature_flags.overworld.kSaveOverworldSprites ? "true" : "false")
1732 << "\n";
1733 file << "save_overworld_properties="
1734 << (feature_flags.overworld.kSaveOverworldProperties ? "true" : "false")
1735 << "\n";
1736 file << "save_dungeon_objects="
1737 << (feature_flags.dungeon.kSaveObjects ? "true" : "false") << "\n";
1738 file << "save_dungeon_sprites="
1739 << (feature_flags.dungeon.kSaveSprites ? "true" : "false") << "\n";
1740 file << "save_dungeon_room_headers="
1741 << (feature_flags.dungeon.kSaveRoomHeaders ? "true" : "false") << "\n";
1742 file << "save_dungeon_torches="
1743 << (feature_flags.dungeon.kSaveTorches ? "true" : "false") << "\n";
1744 file << "save_dungeon_pits="
1745 << (feature_flags.dungeon.kSavePits ? "true" : "false") << "\n";
1746 file << "save_dungeon_blocks="
1747 << (feature_flags.dungeon.kSaveBlocks ? "true" : "false") << "\n";
1748 file << "save_dungeon_collision="
1749 << (feature_flags.dungeon.kSaveCollision ? "true" : "false") << "\n";
1750 file << "save_dungeon_water_fill_zones="
1751 << (feature_flags.dungeon.kSaveWaterFillZones ? "true" : "false")
1752 << "\n";
1753 file << "save_dungeon_chests="
1754 << (feature_flags.dungeon.kSaveChests ? "true" : "false") << "\n";
1755 file << "save_dungeon_pot_items="
1756 << (feature_flags.dungeon.kSavePotItems ? "true" : "false") << "\n";
1757 file << "save_dungeon_entrances="
1758 << (feature_flags.dungeon.kSaveEntrances ? "true" : "false") << "\n";
1759 file << "save_dungeon_palettes="
1760 << (feature_flags.dungeon.kSavePalettes ? "true" : "false") << "\n";
1761 file << "save_graphics_sheet="
1762 << (feature_flags.kSaveGraphicsSheet ? "true" : "false") << "\n";
1763 file << "save_all_palettes="
1764 << (feature_flags.kSaveAllPalettes ? "true" : "false") << "\n";
1765 file << "save_gfx_groups="
1766 << (feature_flags.kSaveGfxGroups ? "true" : "false") << "\n";
1767 file << "save_messages=" << (feature_flags.kSaveMessages ? "true" : "false")
1768 << "\n";
1769 file << "enable_custom_objects="
1770 << (feature_flags.kEnableCustomObjects ? "true" : "false") << "\n\n";
1771
1772 // Workspace settings section
1773 file << "[workspace]\n";
1774 file << "font_global_scale=" << workspace_settings.font_global_scale << "\n";
1775 file << "dark_mode=" << (workspace_settings.dark_mode ? "true" : "false")
1776 << "\n";
1777 file << "ui_theme=" << workspace_settings.ui_theme << "\n";
1778 file << "autosave_enabled="
1779 << (workspace_settings.autosave_enabled ? "true" : "false") << "\n";
1780 file << "autosave_interval_secs=" << workspace_settings.autosave_interval_secs
1781 << "\n";
1782 file << "backup_on_save="
1783 << (workspace_settings.backup_on_save ? "true" : "false") << "\n";
1784 file << "backup_retention_count=" << workspace_settings.backup_retention_count
1785 << "\n";
1786 file << "backup_keep_daily="
1787 << (workspace_settings.backup_keep_daily ? "true" : "false") << "\n";
1788 file << "backup_keep_daily_days=" << workspace_settings.backup_keep_daily_days
1789 << "\n";
1790 file << "show_grid=" << (workspace_settings.show_grid ? "true" : "false")
1791 << "\n";
1792 file << "show_collision="
1793 << (workspace_settings.show_collision ? "true" : "false") << "\n";
1794 file << "prefer_hmagic_names="
1795 << (workspace_settings.prefer_hmagic_names ? "true" : "false") << "\n";
1796 file << "last_layout_preset=" << workspace_settings.last_layout_preset
1797 << "\n";
1798 file << "saved_layouts="
1799 << absl::StrJoin(workspace_settings.saved_layouts, ",") << "\n";
1800 file << "recent_files=" << absl::StrJoin(workspace_settings.recent_files, ",")
1801 << "\n\n";
1802
1803 // Dungeon overlay settings section
1804 auto track_tiles = dungeon_overlay.track_tiles;
1805 if (track_tiles.empty()) {
1806 for (uint16_t tile = 0xB0; tile <= 0xBE; ++tile) {
1807 track_tiles.push_back(tile);
1808 }
1809 }
1810 auto track_stop_tiles = dungeon_overlay.track_stop_tiles;
1811 if (track_stop_tiles.empty()) {
1812 track_stop_tiles = {0xB7, 0xB8, 0xB9, 0xBA};
1813 }
1814 auto track_switch_tiles = dungeon_overlay.track_switch_tiles;
1815 if (track_switch_tiles.empty()) {
1816 track_switch_tiles = {0xD0, 0xD1, 0xD2, 0xD3};
1817 }
1818 auto track_object_ids = dungeon_overlay.track_object_ids;
1819 if (track_object_ids.empty()) {
1820 track_object_ids = {0x31};
1821 }
1822 auto minecart_sprite_ids = dungeon_overlay.minecart_sprite_ids;
1823 if (minecart_sprite_ids.empty()) {
1824 minecart_sprite_ids = {0xA3};
1825 }
1826 file << "[dungeon_overlay]\n";
1827 file << "track_tiles=" << FormatHexUintList(track_tiles) << "\n";
1828 file << "track_stop_tiles=" << FormatHexUintList(track_stop_tiles) << "\n";
1829 file << "track_switch_tiles=" << FormatHexUintList(track_switch_tiles)
1830 << "\n";
1831 file << "track_object_ids=" << FormatHexUintList(track_object_ids) << "\n";
1832 file << "minecart_sprite_ids=" << FormatHexUintList(minecart_sprite_ids)
1833 << "\n\n";
1834
1835 if (!graphics_sheets.empty()) {
1836 file << "[graphics_sheets]\n";
1837 file << "reserved_sheets="
1838 << FormatHexUintList(graphics_sheets.reserved_sheets) << "\n";
1839 file << "flagged_sheets="
1840 << FormatHexUintList(graphics_sheets.flagged_sheets) << "\n";
1841 file << "reserved_blocks="
1842 << FormatHexUintListMap(graphics_sheets.reserved_blocks) << "\n\n";
1843 }
1844
1846 file << "[atlas]\n";
1847 file << "annotations=" << absl::StrJoin(atlas.annotations, ",") << "\n";
1848 file << "defaults=" << atlas.defaults << "\n";
1849 file << "symbols=" << atlas.symbols << "\n";
1850 file << "export_folder=" << atlas.export_folder << "\n\n";
1851 }
1852
1854 file << "[planning]\n";
1855 file << "file=" << planning.file << "\n\n";
1856 }
1857
1858 if (!rom_address_overrides.addresses.empty()) {
1859 file << "[rom_addresses]\n";
1860 for (const auto& [key, value] : rom_address_overrides.addresses) {
1861 file << key << "=" << FormatHexUint32(value) << "\n";
1862 }
1863 file << "\n";
1864 }
1865
1866 if (!custom_object_files.empty()) {
1867 file << "[custom_objects]\n";
1868 for (const auto& [object_id, files] : custom_object_files) {
1869 file << absl::StrFormat("object_0x%X", object_id) << "="
1870 << absl::StrJoin(files, ",") << "\n";
1871 }
1872 file << "\n";
1873 }
1874
1875 // AI Agent settings section
1876 file << "[agent_settings]\n";
1877 file << "ai_provider=" << agent_settings.ai_provider << "\n";
1878 file << "ai_model=" << agent_settings.ai_model << "\n";
1879 file << "ollama_host=" << agent_settings.ollama_host << "\n";
1880 file << "gemini_api_key=" << agent_settings.gemini_api_key << "\n";
1881 file << "custom_system_prompt="
1883 << "\n";
1884 file << "use_custom_prompt="
1885 << (agent_settings.use_custom_prompt ? "true" : "false") << "\n";
1886 file << "show_reasoning="
1887 << (agent_settings.show_reasoning ? "true" : "false") << "\n";
1888 file << "verbose=" << (agent_settings.verbose ? "true" : "false") << "\n";
1889 file << "max_tool_iterations=" << agent_settings.max_tool_iterations << "\n";
1890 file << "max_retry_attempts=" << agent_settings.max_retry_attempts << "\n";
1891 file << "temperature=" << agent_settings.temperature << "\n";
1892 file << "top_p=" << agent_settings.top_p << "\n";
1893 file << "max_output_tokens=" << agent_settings.max_output_tokens << "\n";
1894 file << "stream_responses="
1895 << (agent_settings.stream_responses ? "true" : "false") << "\n";
1896 file << "favorite_models="
1897 << absl::StrJoin(agent_settings.favorite_models, ",") << "\n";
1898 file << "model_chain=" << absl::StrJoin(agent_settings.model_chain, ",")
1899 << "\n";
1900 file << "chain_mode=" << agent_settings.chain_mode << "\n";
1901 file << "enable_tool_resources="
1902 << (agent_settings.enable_tool_resources ? "true" : "false") << "\n";
1903 file << "enable_tool_dungeon="
1904 << (agent_settings.enable_tool_dungeon ? "true" : "false") << "\n";
1905 file << "enable_tool_overworld="
1906 << (agent_settings.enable_tool_overworld ? "true" : "false") << "\n";
1907 file << "enable_tool_messages="
1908 << (agent_settings.enable_tool_messages ? "true" : "false") << "\n";
1909 file << "enable_tool_dialogue="
1910 << (agent_settings.enable_tool_dialogue ? "true" : "false") << "\n";
1911 file << "enable_tool_gui="
1912 << (agent_settings.enable_tool_gui ? "true" : "false") << "\n";
1913 file << "enable_tool_music="
1914 << (agent_settings.enable_tool_music ? "true" : "false") << "\n";
1915 file << "enable_tool_sprite="
1916 << (agent_settings.enable_tool_sprite ? "true" : "false") << "\n";
1917 file << "enable_tool_emulator="
1918 << (agent_settings.enable_tool_emulator ? "true" : "false") << "\n";
1919 file << "enable_tool_memory_inspector="
1920 << (agent_settings.enable_tool_memory_inspector ? "true" : "false")
1921 << "\n";
1922 file << "builder_blueprint_path=" << agent_settings.builder_blueprint_path
1923 << "\n\n";
1924
1925 // Custom keybindings section
1927 file << "[keybindings]\n";
1928 for (const auto& [key, value] : workspace_settings.custom_keybindings) {
1929 file << key << "=" << value << "\n";
1930 }
1931 file << "\n";
1932 }
1933
1934 // Editor visibility section
1936 file << "[editor_visibility]\n";
1937 for (const auto& [key, value] : workspace_settings.editor_visibility) {
1938 file << key << "=" << (value ? "true" : "false") << "\n";
1939 }
1940 file << "\n";
1941 }
1942
1943 // Resource labels sections
1944 for (const auto& [type, labels] : resource_labels) {
1945 if (!labels.empty()) {
1946 file << "[labels_" << type << "]\n";
1947 for (const auto& [key, value] : labels) {
1948 file << key << "=" << value << "\n";
1949 }
1950 file << "\n";
1951 }
1952 }
1953
1954 // Build settings section
1955 file << "[build]\n";
1956 file << "build_script=" << build_script << "\n";
1957 file << "output_folder=" << GetRelativePath(output_folder) << "\n";
1958 file << "git_repository=" << git_repository << "\n";
1959 file << "track_changes=" << (track_changes ? "true" : "false") << "\n";
1960 file << "build_configurations=" << absl::StrJoin(build_configurations, ",")
1961 << "\n";
1962 file << "build_target=" << build_target << "\n";
1963 file << "asm_entry_point=" << asm_entry_point << "\n";
1964 file << "asm_sources=" << absl::StrJoin(asm_sources, ",") << "\n";
1965 file << "last_build_hash=" << last_build_hash << "\n";
1966 file << "build_number=" << build_number << "\n\n";
1967
1968 // Music persistence section (for WASM/offline state)
1969 file << "[music]\n";
1970 file << "persist_custom_music="
1971 << (music_persistence.persist_custom_music ? "true" : "false") << "\n";
1972 file << "storage_key=" << music_persistence.storage_key << "\n";
1973 file << "last_saved_at=" << music_persistence.last_saved_at << "\n\n";
1974
1975 // ZScream compatibility section
1976 if (!zscream_project_file.empty()) {
1977 file << "[zscream_compatibility]\n";
1978 file << "original_project_file=" << zscream_project_file << "\n";
1979 for (const auto& [key, value] : zscream_mappings) {
1980 file << key << "=" << value << "\n";
1981 }
1982 file << "\n";
1983 }
1984
1985 file << "# End of YAZE Project File\n";
1986
1987 // Refuse to WRITE what ParseFromString refuses to READ. Values are streamed
1988 // verbatim — metadata.description and resource labels injected from
1989 // hack_manifest.json among them — so a lone CR pasted from an old-Mac
1990 // source would round-trip through Save() and leave the project permanently
1991 // unopenable, with the previous good file already overwritten. Failing here
1992 // keeps that file intact.
1993 std::string serialized =
1994 MergeProjectFilePassthrough(file.str(), file_passthrough);
1995 if (ContainsLoneCarriageReturn(serialized)) {
1996 return absl::InvalidArgumentError(
1997 "Project contains a lone carriage return in a value; refusing to "
1998 "write a descriptor that could not be read back");
1999 }
2000 return serialized;
2001}
2002
2003absl::Status YazeProject::ParseFromString(const std::string& content) {
2004 if (ContainsLoneCarriageReturn(content)) {
2005 return absl::InvalidArgumentError(
2006 "Project file contains unsupported lone carriage returns");
2007 }
2008
2013 sprite_catalog_file.clear();
2014 sprite_source_root.clear();
2015 sprite_assets.clear();
2016 terrain_catalog_file.clear();
2017 lyra_terrain_file.clear();
2022 palette_catalog_file.clear();
2023 dungeon_tile_patterns.clear();
2025 atlas = AtlasSettings{};
2027 std::istringstream stream(content);
2028 std::string line;
2029 std::string current_section;
2030 ProjectFilePassthrough::Section* passthrough_section =
2031 &PassthroughSection(file_passthrough, "");
2032
2033 while (std::getline(stream, line)) {
2034 // std::getline() consumes '\n' but preserves the '\r' in CRLF input.
2035 // Normalize that line ending before comment, section, or value parsing so
2036 // project safety flags have identical behavior across platforms.
2037 if (!line.empty() && line.back() == '\r') {
2038 line.pop_back();
2039 }
2040
2041 if (line.find_first_not_of(" \t") == std::string::npos)
2042 continue;
2043
2044 if (line[0] == '#') {
2045 if (!IsGeneratedProjectComment(line, current_section.empty())) {
2046 passthrough_section->lines.push_back(
2048 }
2049 continue;
2050 }
2051
2052 if (line.front() == '[' && line.back() == ']') {
2053 current_section = line.substr(1, line.length() - 2);
2054 passthrough_section =
2055 &PassthroughSection(file_passthrough, current_section);
2056 passthrough_section->known = IsKnownProjectSection(current_section);
2057 if (current_section == "atlas") {
2058 atlas.section_present = true;
2059 } else if (current_section == "planning") {
2061 }
2062 continue;
2063 }
2064
2065 auto [key, value] = ParseKeyValue(line);
2066 // False when this build does not model the line; it is then kept verbatim
2067 // and written back on save.
2068 bool understood = !key.empty();
2069 if (key.empty()) {
2070 // No "key=value": nothing to parse.
2071 } else if (current_section == "project") {
2072 if (key == "name")
2073 name = value;
2074 else if (key == "description")
2075 metadata.description = value;
2076 else if (key == "author")
2077 metadata.author = value;
2078 else if (key == "license")
2079 metadata.license = value;
2080 else if (key == "version")
2081 metadata.version = value;
2082 else if (key == "created_date")
2083 metadata.created_date = value;
2084 else if (key == "last_modified")
2085 metadata.last_modified = value;
2086 else if (key == "yaze_version")
2087 metadata.yaze_version = value;
2088 else if (key == "created_by")
2089 metadata.created_by = value;
2090 else if (key == "tags")
2091 metadata.tags = ParseStringList(value);
2092 else if (key == "project_id")
2093 metadata.project_id = value;
2094 else
2095 understood = false;
2096 } else if (current_section == "files") {
2097 if (key == "rom_filename")
2098 rom_filename = value;
2099 else if (key == "rom_backup_folder")
2100 rom_backup_folder = value;
2101 else if (key == "code_folder")
2102 code_folder = value;
2103 else if (key == "assets_folder")
2104 assets_folder = value;
2105 else if (key == "patches_folder")
2106 patches_folder = value;
2107 else if (key == "labels_filename")
2108 labels_filename = value;
2109 else if (key == "symbols_filename")
2110 symbols_filename = value;
2111 else if (key == "overworld_graphics_preview")
2113 else if (key == "dungeon_tile_patterns")
2114 dungeon_tile_patterns = value;
2115 else if (key == "cutscene_shots")
2116 cutscene_shots = value;
2117 else if (key == "custom_collision_json")
2118 custom_collision_json = value;
2119 else if (key == "output_folder")
2120 output_folder = value;
2121 else if (key == "custom_objects_folder")
2122 custom_objects_folder = value;
2123 else if (key == "palette_catalog_file")
2124 palette_catalog_file = value;
2125 else if (key == "terrain_catalog_file")
2126 terrain_catalog_file = value;
2127 else if (key == "lyra_terrain_file")
2128 lyra_terrain_file = value;
2129 else if (key == "lyra_build_request_file")
2131 else if (key == "native_save_producer_file")
2133 else if (key == "native_save_transfer_proof_file")
2135 else if (key == "native_save_receipt_file")
2137 else if (key == "hack_manifest_file")
2138 hack_manifest_file = value;
2139 else if (key == "sprite_catalog_file")
2140 sprite_catalog_file = value;
2141 else if (key == "sprite_source_root")
2142 sprite_source_root = value;
2143 else if (key == "additional_roms")
2144 additional_roms = ParseStringList(value);
2145 else
2146 understood = false;
2147 } else if (current_section == "sprite_assets") {
2148 if (key.rfind("asset_", 0) != 0 || value.size() > 65536 ||
2149 sprite_assets.size() >= 4096)
2150 return absl::InvalidArgumentError("Invalid sprite_assets section");
2151 auto asset = ParseSpriteAssetBinding(value);
2152 if (!asset.ok())
2153 return asset.status();
2154 for (const auto& prior : sprite_assets)
2155 if (prior.zsm_path == asset->zsm_path)
2156 return absl::InvalidArgumentError("Duplicate sprite asset path");
2157 sprite_assets.push_back(std::move(*asset));
2158 } else if (current_section == "rom") {
2159 if (key == "role")
2161 else if (key == "expected_hash")
2163 else if (key == "write_policy")
2165 else
2166 understood = false;
2167 } else if (current_section == "feature_flags") {
2168 if (key == "load_custom_overworld")
2169 feature_flags.overworld.kLoadCustomOverworld = ParseBool(value);
2170 else if (key == "apply_zs_custom_overworld_asm")
2172 else if (key == "enable_special_world_expansion")
2174 else if (key == "save_with_change_queue")
2175 feature_flags.kSaveWithChangeQueue = ParseBool(value);
2176 else if (key == "save_dungeon_maps")
2177 feature_flags.kSaveDungeonMaps = ParseBool(value);
2178 else if (key == "save_overworld_maps")
2179 feature_flags.overworld.kSaveOverworldMaps = ParseBool(value);
2180 else if (key == "save_overworld_entrances")
2182 else if (key == "save_overworld_exits")
2183 feature_flags.overworld.kSaveOverworldExits = ParseBool(value);
2184 else if (key == "save_overworld_items")
2185 feature_flags.overworld.kSaveOverworldItems = ParseBool(value);
2186 else if (key == "save_overworld_sprites")
2188 else if (key == "save_overworld_properties")
2190 else if (key == "save_dungeon_objects")
2191 feature_flags.dungeon.kSaveObjects = ParseBool(value);
2192 else if (key == "save_dungeon_sprites")
2193 feature_flags.dungeon.kSaveSprites = ParseBool(value);
2194 else if (key == "save_dungeon_room_headers")
2195 feature_flags.dungeon.kSaveRoomHeaders = ParseBool(value);
2196 else if (key == "save_dungeon_torches")
2197 feature_flags.dungeon.kSaveTorches = ParseBool(value);
2198 else if (key == "save_dungeon_pits")
2199 feature_flags.dungeon.kSavePits = ParseBool(value);
2200 else if (key == "save_dungeon_blocks")
2201 feature_flags.dungeon.kSaveBlocks = ParseBool(value);
2202 else if (key == "save_dungeon_collision")
2203 feature_flags.dungeon.kSaveCollision = ParseBool(value);
2204 else if (key == "save_dungeon_water_fill_zones")
2205 feature_flags.dungeon.kSaveWaterFillZones = ParseBool(value);
2206 else if (key == "save_dungeon_chests")
2207 feature_flags.dungeon.kSaveChests = ParseBool(value);
2208 else if (key == "save_dungeon_pot_items")
2209 feature_flags.dungeon.kSavePotItems = ParseBool(value);
2210 else if (key == "save_dungeon_entrances")
2211 feature_flags.dungeon.kSaveEntrances = ParseBool(value);
2212 else if (key == "save_dungeon_palettes")
2213 feature_flags.dungeon.kSavePalettes = ParseBool(value);
2214 else if (key == "save_graphics_sheet")
2215 feature_flags.kSaveGraphicsSheet = ParseBool(value);
2216 else if (key == "save_all_palettes")
2217 feature_flags.kSaveAllPalettes = ParseBool(value);
2218 else if (key == "save_gfx_groups")
2219 feature_flags.kSaveGfxGroups = ParseBool(value);
2220 else if (key == "save_messages")
2221 feature_flags.kSaveMessages = ParseBool(value);
2222 else if (key == "enable_custom_objects")
2223 feature_flags.kEnableCustomObjects = ParseBool(value);
2224 else
2225 understood = false;
2226 } else if (current_section == "workspace") {
2227 if (key == "font_global_scale")
2228 workspace_settings.font_global_scale = ParseFloat(value);
2229 else if (key == "dark_mode")
2230 workspace_settings.dark_mode = ParseBool(value);
2231 else if (key == "ui_theme")
2233 else if (key == "autosave_enabled")
2234 workspace_settings.autosave_enabled = ParseBool(value);
2235 else if (key == "autosave_interval_secs")
2236 workspace_settings.autosave_interval_secs = ParseFloat(value);
2237 else if (key == "backup_on_save")
2238 workspace_settings.backup_on_save = ParseBool(value);
2239 else if (key == "backup_retention_count") {
2241 ParseProjectInteger(value, current_section, key,
2243 } else if (key == "backup_keep_daily")
2244 workspace_settings.backup_keep_daily = ParseBool(value);
2245 else if (key == "backup_keep_daily_days") {
2247 ParseProjectInteger(value, current_section, key,
2249 } else if (key == "show_grid")
2250 workspace_settings.show_grid = ParseBool(value);
2251 else if (key == "show_collision")
2252 workspace_settings.show_collision = ParseBool(value);
2253 else if (key == "prefer_hmagic_names")
2254 workspace_settings.prefer_hmagic_names = ParseBool(value);
2255 else if (key == "last_layout_preset")
2257 else if (key == "saved_layouts")
2258 workspace_settings.saved_layouts = ParseStringList(value);
2259 else if (key == "recent_files")
2260 workspace_settings.recent_files = ParseStringList(value);
2261 else
2262 understood = false;
2263 } else if (current_section == "dungeon_overlay") {
2264 if (key == "track_tiles")
2265 dungeon_overlay.track_tiles = ParseHexUintList(value);
2266 else if (key == "track_stop_tiles")
2267 dungeon_overlay.track_stop_tiles = ParseHexUintList(value);
2268 else if (key == "track_switch_tiles")
2269 dungeon_overlay.track_switch_tiles = ParseHexUintList(value);
2270 else if (key == "track_object_ids")
2271 dungeon_overlay.track_object_ids = ParseHexUintList(value);
2272 else if (key == "minecart_sprite_ids")
2273 dungeon_overlay.minecart_sprite_ids = ParseHexUintList(value);
2274 else
2275 understood = false;
2276 } else if (current_section == "graphics_sheets") {
2277 if (key == "reserved_sheets")
2278 graphics_sheets.reserved_sheets = ParseHexUintList(value);
2279 else if (key == "flagged_sheets")
2280 graphics_sheets.flagged_sheets = ParseHexUintList(value);
2281 else if (key == "reserved_blocks")
2282 graphics_sheets.reserved_blocks = ParseHexUintListMap(value);
2283 else
2284 understood = false;
2285 } else if (current_section == "atlas") {
2286 if (key == "annotations")
2287 atlas.annotations = ParseStringList(value);
2288 else if (key == "defaults")
2289 atlas.defaults = value.empty() ? "vanilla" : value;
2290 else if (key == "symbols")
2291 atlas.symbols = value;
2292 else if (key == "export_folder")
2293 atlas.export_folder = value;
2294 else
2295 understood = false;
2296 } else if (current_section == "planning") {
2297 if (key == "file")
2298 planning.file = value;
2299 else
2300 understood = false;
2301 } else if (current_section == "rom_addresses") {
2302 auto parsed = ParseHexUint32(value);
2303 if (parsed.has_value()) {
2304 rom_address_overrides.addresses[key] = *parsed;
2305 } else {
2306 understood = false;
2307 }
2308 } else if (current_section == "custom_objects") {
2309 std::string id_token = key;
2310 if (absl::StartsWith(id_token, "object_")) {
2311 id_token = id_token.substr(7);
2312 }
2313 auto parsed = ParseHexUint32(id_token);
2314 if (parsed.has_value()) {
2315 custom_object_files[static_cast<int>(*parsed)] =
2316 ParsePositionalStringList(value);
2317 } else {
2318 understood = false;
2319 }
2320 } else if (current_section == "agent_settings") {
2321 if (key == "ai_provider")
2323 else if (key == "ai_model")
2324 agent_settings.ai_model = value;
2325 else if (key == "ollama_host")
2327 else if (key == "gemini_api_key")
2329 else if (key == "custom_system_prompt")
2331 else if (key == "use_custom_prompt")
2332 agent_settings.use_custom_prompt = ParseBool(value);
2333 else if (key == "show_reasoning")
2334 agent_settings.show_reasoning = ParseBool(value);
2335 else if (key == "verbose")
2336 agent_settings.verbose = ParseBool(value);
2337 else if (key == "max_tool_iterations") {
2338 RETURN_IF_ERROR(ParseProjectInteger(
2339 value, current_section, key, &agent_settings.max_tool_iterations));
2340 } else if (key == "max_retry_attempts") {
2341 RETURN_IF_ERROR(ParseProjectInteger(
2342 value, current_section, key, &agent_settings.max_retry_attempts));
2343 } else if (key == "temperature")
2344 agent_settings.temperature = ParseFloat(value);
2345 else if (key == "top_p")
2346 agent_settings.top_p = ParseFloat(value);
2347 else if (key == "max_output_tokens") {
2348 RETURN_IF_ERROR(ParseProjectInteger(value, current_section, key,
2350 } else if (key == "stream_responses")
2351 agent_settings.stream_responses = ParseBool(value);
2352 else if (key == "favorite_models")
2353 agent_settings.favorite_models = ParseStringList(value);
2354 else if (key == "model_chain")
2355 agent_settings.model_chain = ParseStringList(value);
2356 else if (key == "chain_mode") {
2357 RETURN_IF_ERROR(ParseProjectInteger(value, current_section, key,
2359 } else if (key == "enable_tool_resources")
2360 agent_settings.enable_tool_resources = ParseBool(value);
2361 else if (key == "enable_tool_dungeon")
2362 agent_settings.enable_tool_dungeon = ParseBool(value);
2363 else if (key == "enable_tool_overworld")
2364 agent_settings.enable_tool_overworld = ParseBool(value);
2365 else if (key == "enable_tool_messages")
2366 agent_settings.enable_tool_messages = ParseBool(value);
2367 else if (key == "enable_tool_dialogue")
2368 agent_settings.enable_tool_dialogue = ParseBool(value);
2369 else if (key == "enable_tool_gui")
2370 agent_settings.enable_tool_gui = ParseBool(value);
2371 else if (key == "enable_tool_music")
2372 agent_settings.enable_tool_music = ParseBool(value);
2373 else if (key == "enable_tool_sprite")
2374 agent_settings.enable_tool_sprite = ParseBool(value);
2375 else if (key == "enable_tool_emulator")
2376 agent_settings.enable_tool_emulator = ParseBool(value);
2377 else if (key == "enable_tool_memory_inspector")
2379 else if (key == "builder_blueprint_path")
2381 else
2382 understood = false;
2383 } else if (current_section == "build") {
2384 if (key == "build_script")
2385 build_script = value;
2386 else if (key == "output_folder")
2387 output_folder = value;
2388 else if (key == "git_repository")
2389 git_repository = value;
2390 else if (key == "track_changes")
2391 track_changes = ParseBool(value);
2392 else if (key == "build_configurations")
2393 build_configurations = ParseStringList(value);
2394 else if (key == "build_target")
2395 build_target = value;
2396 else if (key == "asm_entry_point")
2397 asm_entry_point = value;
2398 else if (key == "asm_sources")
2399 asm_sources = ParseStringList(value);
2400 else if (key == "last_build_hash")
2401 last_build_hash = value;
2402 else if (key == "build_number") {
2404 ParseProjectInteger(value, current_section, key, &build_number));
2405 } else
2406 understood = false;
2407 } else if (current_section.rfind("labels_", 0) == 0) {
2408 std::string label_type = current_section.substr(7);
2409 resource_labels[label_type][key] = value;
2410 } else if (current_section == "keybindings") {
2412 } else if (current_section == "editor_visibility") {
2413 workspace_settings.editor_visibility[key] = ParseBool(value);
2414 } else if (current_section == "zscream_compatibility") {
2415 if (key == "original_project_file")
2416 zscream_project_file = value;
2417 else
2418 zscream_mappings[key] = value;
2419 } else if (current_section == "music") {
2420 if (key == "persist_custom_music")
2421 music_persistence.persist_custom_music = ParseBool(value);
2422 else if (key == "storage_key")
2424 else if (key == "last_saved_at")
2426 else
2427 understood = false;
2428 } else {
2429 understood = false; // A section this build does not know.
2430 }
2431 passthrough_section->lines.push_back(
2432 understood
2437 }
2438
2439 MigrateGfxGroupLabelKeys(resource_labels);
2440
2441 if (metadata.project_id.empty()) {
2443 }
2444 if (metadata.created_by.empty()) {
2445 metadata.created_by = "YAZE";
2446 }
2447 if (music_persistence.storage_key.empty()) {
2449 }
2450
2451 return absl::OkStatus();
2452}
2453
2454absl::Status YazeProject::LoadFromYazeFormat(const std::string& project_path) {
2455#ifdef __EMSCRIPTEN__
2456 auto storage_key = MakeStorageKey("project");
2457 auto storage_or = platform::WasmStorage::LoadProject(storage_key);
2458 if (storage_or.ok()) {
2459 return ParseFromString(storage_or.value());
2460 }
2461#endif // __EMSCRIPTEN__
2462
2463 std::ifstream file(project_path);
2464 if (!file.is_open()) {
2465 return absl::InvalidArgumentError(
2466 absl::StrFormat("Cannot open project file: %s", project_path));
2467 }
2468
2469 std::stringstream buffer;
2470 buffer << file.rdbuf();
2471 file.close();
2472 return ParseFromString(buffer.str());
2473}
2474
2475absl::Status YazeProject::SaveToYazeFormat(bool replace_existing) {
2476 // Update last modified timestamp
2477 auto now = std::chrono::system_clock::now();
2478 auto time_t = std::chrono::system_clock::to_time_t(now);
2479 std::stringstream ss;
2480 ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
2481 metadata.last_modified = ss.str();
2482 if (music_persistence.storage_key.empty()) {
2484 }
2485
2486 // Ensure we serialize clean relative paths even if the user edited fields
2487 // into relative form (and avoid relying on cwd when opening later).
2489
2490 ASSIGN_OR_RETURN(auto serialized, SerializeToString());
2491
2492#ifdef __EMSCRIPTEN__
2493 auto storage_status = platform::WasmStorage::SaveProject(
2494 MakeStorageKey("project"), serialized, replace_existing);
2495 if (!storage_status.ok()) {
2496 return storage_status;
2497 }
2498#else
2499 if (!filepath.empty()) {
2501 WriteProjectFileAtomically(filepath, serialized, replace_existing));
2502 }
2503#endif
2504
2505 return absl::OkStatus();
2506}
2507
2509 const std::string& zscream_project_path) {
2510 // Basic ZScream project import (to be expanded based on ZScream format)
2511 zscream_project_file = zscream_project_path;
2513
2514 // Extract project name from path
2515 std::filesystem::path zs_path(zscream_project_path);
2516 name = zs_path.stem().string() + "_imported";
2517
2518 // Set up basic mapping for common fields
2519 zscream_mappings["rom_file"] = "rom_filename";
2520 zscream_mappings["source_code"] = "code_folder";
2521 zscream_mappings["project_name"] = "name";
2522
2524
2525 // TODO: Implement actual ZScream format parsing when format is known
2526 // For now, just create a project structure that can be manually configured
2527
2528 return absl::OkStatus();
2529}
2530
2531absl::Status YazeProject::ExportForZScream(const std::string& target_path) {
2532 // Create a simplified project file that ZScream might understand
2533 std::ofstream file(target_path);
2534 if (!file.is_open()) {
2535 return absl::InvalidArgumentError(
2536 absl::StrFormat("Cannot create ZScream project file: %s", target_path));
2537 }
2538
2539 // Write in a simple format that ZScream might understand
2540 file << "# ZScream Compatible Project File\n";
2541 file << "# Exported from YAZE " << metadata.yaze_version << "\n\n";
2542 file << "name=" << name << "\n";
2543 file << "rom_file=" << rom_filename << "\n";
2544 file << "source_code=" << code_folder << "\n";
2545 file << "description=" << metadata.description << "\n";
2546 file << "author=" << metadata.author << "\n";
2547 file << "created_with=YAZE " << metadata.yaze_version << "\n";
2548
2549 file.close();
2550 return absl::OkStatus();
2551}
2552
2554 // Consolidated loading of all settings from project file
2555 // This replaces scattered config loading throughout the application
2557}
2558
2560 // Consolidated saving of all settings to project file
2561 return SaveToYazeFormat();
2562}
2563
2566 return Save();
2567}
2568
2569absl::Status YazeProject::Validate() const {
2570 std::vector<std::string> errors;
2571
2572 if (name.empty())
2573 errors.push_back("Project name is required");
2574 if (filepath.empty())
2575 errors.push_back("Project file path is required");
2576 if (rom_filename.empty())
2577 errors.push_back("ROM file is required");
2578
2579#ifndef __EMSCRIPTEN__
2580 // Check if files exist
2581 if (!rom_filename.empty() &&
2582 !std::filesystem::exists(GetAbsolutePath(rom_filename))) {
2583 errors.push_back("ROM file does not exist: " + rom_filename);
2584 }
2585
2586 if (!code_folder.empty() &&
2587 !std::filesystem::exists(GetAbsolutePath(code_folder))) {
2588 errors.push_back("Code folder does not exist: " + code_folder);
2589 }
2590
2591 if (!labels_filename.empty() &&
2592 !std::filesystem::exists(GetAbsolutePath(labels_filename))) {
2593 errors.push_back("Labels file does not exist: " + labels_filename);
2594 }
2595
2596 if (!hack_manifest_file.empty()) {
2597 if (!std::filesystem::exists(GetAbsolutePath(hack_manifest_file))) {
2598 errors.push_back("Hack manifest file does not exist: " +
2600 } else if (!hack_manifest.loaded()) {
2601 errors.push_back("Hack manifest file failed to load: " +
2603 }
2604 }
2605#endif // __EMSCRIPTEN__
2606
2607 if (!errors.empty()) {
2608 return absl::InvalidArgumentError(absl::StrJoin(errors, "; "));
2609 }
2610
2611 return absl::OkStatus();
2612}
2613
2614std::vector<std::string> YazeProject::GetMissingFiles() const {
2615 std::vector<std::string> missing;
2616
2617#ifndef __EMSCRIPTEN__
2618 if (!rom_filename.empty() &&
2619 !std::filesystem::exists(GetAbsolutePath(rom_filename))) {
2620 missing.push_back(rom_filename);
2621 }
2622 if (!labels_filename.empty() &&
2623 !std::filesystem::exists(GetAbsolutePath(labels_filename))) {
2624 missing.push_back(labels_filename);
2625 }
2626 if (!symbols_filename.empty() &&
2627 !std::filesystem::exists(GetAbsolutePath(symbols_filename))) {
2628 missing.push_back(symbols_filename);
2629 }
2630 if (!hack_manifest_file.empty() &&
2631 !std::filesystem::exists(GetAbsolutePath(hack_manifest_file))) {
2632 missing.push_back(hack_manifest_file);
2633 }
2634#endif // __EMSCRIPTEN__
2635
2636 return missing;
2637}
2638
2640#ifdef __EMSCRIPTEN__
2641 // In the web build, filesystem layout is virtual; nothing to repair eagerly.
2642 return absl::OkStatus();
2643#else
2644 // Create missing directories
2645 std::vector<std::string> folders = {code_folder, assets_folder,
2648
2649 for (const auto& folder : folders) {
2650 if (!folder.empty()) {
2651 std::filesystem::path abs_path = GetAbsolutePath(folder);
2652 if (!std::filesystem::exists(abs_path)) {
2653 std::filesystem::create_directories(abs_path);
2654 }
2655 }
2656 }
2657
2658 // Create missing files with defaults
2659 if (!labels_filename.empty()) {
2660 std::filesystem::path abs_labels = GetAbsolutePath(labels_filename);
2661 if (!std::filesystem::exists(abs_labels)) {
2662 std::ofstream labels_file(abs_labels);
2663 labels_file << "# yaze Resource Labels\n";
2664 labels_file << "# Format: [type] key=value\n\n";
2665 labels_file.close();
2666 }
2667 }
2668
2669 return absl::OkStatus();
2670#endif
2671}
2672
2673std::string YazeProject::GetDisplayName() const {
2674 if (!metadata.description.empty()) {
2675 return metadata.description;
2676 }
2677 return name.empty() ? "Untitled Project" : name;
2678}
2679
2681 const std::string& absolute_path) const {
2682 if (absolute_path.empty() || filepath.empty())
2683 return absolute_path;
2684
2685 std::filesystem::path project_dir =
2686 std::filesystem::path(filepath).parent_path();
2687 std::filesystem::path abs_path(absolute_path);
2688
2689 try {
2690 std::filesystem::path relative =
2691 std::filesystem::relative(abs_path.lexically_normal(), project_dir);
2692 // Persist relative paths in a platform-neutral format for project files.
2693 return relative.generic_string();
2694 } catch (...) {
2695 // Return normalized absolute path if relative conversion fails.
2696 return abs_path.lexically_normal().generic_string();
2697 }
2698}
2699
2701 const std::string& relative_path) const {
2702 if (relative_path.empty() || filepath.empty())
2703 return relative_path;
2704
2705 std::filesystem::path project_dir =
2706 std::filesystem::path(filepath).parent_path();
2707 std::filesystem::path abs_path(relative_path);
2708 if (abs_path.is_absolute()) {
2709 abs_path = abs_path.lexically_normal();
2710 abs_path.make_preferred();
2711 return abs_path.string();
2712 }
2713 abs_path = (project_dir / abs_path).lexically_normal();
2714 abs_path.make_preferred();
2715
2716 return abs_path.string();
2717}
2718
2720#ifdef __EMSCRIPTEN__
2721 // Web builds rely on a virtual filesystem and often use relative paths.
2722 return;
2723#endif
2724 if (filepath.empty()) {
2725 return;
2726 }
2727
2728 auto normalize = [this](std::string* path) {
2729 if (!path || path->empty()) {
2730 return;
2731 }
2732 *path = GetAbsolutePath(*path);
2733 };
2734
2735 normalize(&rom_filename);
2736 normalize(&rom_backup_folder);
2737 normalize(&code_folder);
2738 normalize(&assets_folder);
2739 normalize(&patches_folder);
2740 normalize(&labels_filename);
2741 normalize(&symbols_filename);
2742 normalize(&custom_objects_folder);
2743 normalize(&hack_manifest_file);
2744 normalize(&sprite_catalog_file);
2745 normalize(&sprite_source_root);
2746 normalize(&overworld_graphics_preview);
2747 normalize(&dungeon_tile_patterns);
2748 normalize(&terrain_catalog_file);
2749 normalize(&lyra_terrain_file);
2750 normalize(&lyra_build_request_file);
2751 normalize(&native_save_producer_file);
2753 normalize(&native_save_receipt_file);
2754 normalize(&palette_catalog_file);
2755 for (auto& asset : sprite_assets) {
2756 normalize(&asset.zsm_path);
2757 for (auto& source : asset.graphics_sources) {
2758 if (source.kind == "bin") {
2759 normalize(&source.path);
2760 }
2761 }
2762 }
2763 normalize(&output_folder);
2764
2765 for (auto& rom_path : additional_roms) {
2766 if (!rom_path.empty()) {
2767 rom_path = GetAbsolutePath(rom_path);
2768 }
2769 }
2770}
2771
2772std::vector<std::string> YazeProject::AtlasAnnotationPaths() const {
2773 std::vector<std::string> paths;
2774 paths.reserve(atlas.annotations.size());
2775 for (const auto& path : atlas.annotations) {
2776 paths.push_back(GetAbsolutePath(path));
2777 }
2778 return paths;
2779}
2780
2783}
2784
2787}
2788
2790 return name.empty() && rom_filename.empty() && code_folder.empty();
2791}
2792
2794 const std::string& project_path) {
2795 // TODO: Implement ZScream format parsing when format specification is
2796 // available For now, create a basic project that can be manually configured
2797
2798 std::filesystem::path zs_path(project_path);
2799 name = zs_path.stem().string() + "_imported";
2800 zscream_project_file = project_path;
2801
2803
2804 return absl::OkStatus();
2805}
2806
2810
2814
2816 absl::string_view artifact_name) const {
2817 std::filesystem::path base_dir;
2818 if (!output_folder.empty()) {
2819 base_dir = output_folder;
2820 } else if (!z3dk_settings.config_path.empty()) {
2821 base_dir = std::filesystem::path(z3dk_settings.config_path).parent_path();
2822 } else if (!code_folder.empty()) {
2823 base_dir = code_folder;
2824 } else if (!filepath.empty()) {
2825 base_dir = std::filesystem::path(filepath).parent_path();
2826 }
2827
2828 if (base_dir.empty()) {
2829 return std::string(artifact_name);
2830 }
2831 return (base_dir / std::string(artifact_name)).lexically_normal().string();
2832}
2833
2836
2837#if defined(YAZE_WITH_Z3DK) && __has_include("z3dk_core/config.h")
2838 std::vector<std::filesystem::path> candidates;
2839 auto add_candidate = [&candidates](const std::filesystem::path& candidate) {
2840 if (candidate.empty()) {
2841 return;
2842 }
2843 auto normalized = candidate.lexically_normal();
2844 if (std::find(candidates.begin(), candidates.end(), normalized) ==
2845 candidates.end()) {
2846 candidates.push_back(normalized);
2847 }
2848 };
2849
2850 if (!code_folder.empty()) {
2851 std::filesystem::path code_path(code_folder);
2852 if (!std::filesystem::is_directory(code_path)) {
2853 code_path = code_path.parent_path();
2854 }
2855 add_candidate(code_path / "z3dk.toml");
2856 }
2857
2858 if (!hack_manifest_file.empty()) {
2859 add_candidate(std::filesystem::path(hack_manifest_file).parent_path() /
2860 "z3dk.toml");
2861 }
2862
2863 if (!filepath.empty()) {
2864 add_candidate(std::filesystem::path(filepath).parent_path() / "z3dk.toml");
2865 }
2866
2867 for (const auto& candidate : candidates) {
2868 if (!std::filesystem::exists(candidate)) {
2869 continue;
2870 }
2871
2872 std::string error;
2873 z3dk::Config config = z3dk::LoadConfigFile(candidate.string(), &error);
2874 if (!error.empty()) {
2875 LOG_WARN("Project", "Failed to parse z3dk config '%s': %s",
2876 candidate.string().c_str(), error.c_str());
2877 continue;
2878 }
2879
2880 const std::filesystem::path base_dir = candidate.parent_path();
2881 z3dk_settings.loaded = true;
2882 z3dk_settings.config_path = candidate.string();
2883 if (config.preset.has_value()) {
2884 z3dk_settings.preset = *config.preset;
2885 }
2886
2887 z3dk_settings.include_paths.reserve(config.include_paths.size());
2888 for (const auto& include_path : config.include_paths) {
2889 z3dk_settings.include_paths.push_back(
2890 ResolveOptionalPath(base_dir, include_path));
2891 }
2892
2893 z3dk_settings.defines.reserve(config.defines.size());
2894 for (const auto& define : config.defines) {
2895 z3dk_settings.defines.push_back(ParseDefineToken(define));
2896 }
2897
2898 z3dk_settings.main_files.reserve(config.main_files.size());
2899 for (const auto& main_file : config.main_files) {
2900 z3dk_settings.main_files.push_back(
2901 ResolveOptionalPath(base_dir, main_file));
2902 }
2903
2904 if (config.std_includes_path.has_value()) {
2906 ResolveOptionalPath(base_dir, *config.std_includes_path);
2907 }
2908 if (config.std_defines_path.has_value()) {
2910 ResolveOptionalPath(base_dir, *config.std_defines_path);
2911 }
2912 if (config.mapper.has_value()) {
2913 z3dk_settings.mapper = *config.mapper;
2914 }
2915 if (config.rom_size.has_value()) {
2916 z3dk_settings.rom_size = *config.rom_size;
2917 }
2918 if (config.symbols_format.has_value()) {
2919 z3dk_settings.symbols_format = *config.symbols_format;
2920 }
2921 z3dk_settings.lsp_log_enabled = config.lsp_log_enabled;
2922 if (config.lsp_log_path.has_value()) {
2924 ResolveOptionalPath(base_dir, *config.lsp_log_path);
2925 }
2926
2927 z3dk_settings.emits.reserve(config.emits.size());
2928 for (const auto& emit_path : config.emits) {
2929 z3dk_settings.emits.push_back(ResolveOptionalPath(base_dir, emit_path));
2930 }
2931
2932 for (const auto& range : config.prohibited_memory_ranges) {
2934 {.start = range.start, .end = range.end, .reason = range.reason});
2935 }
2936
2938 config.warn_unused_symbols.value_or(true);
2940 config.warn_branch_outside_bank.value_or(true);
2941 z3dk_settings.warn_unknown_width = config.warn_unknown_width.value_or(true);
2942 z3dk_settings.warn_org_collision = config.warn_org_collision.value_or(true);
2944 config.warn_unauthorized_hook.value_or(true);
2945 z3dk_settings.warn_stack_balance = config.warn_stack_balance.value_or(true);
2946 z3dk_settings.warn_hook_return = config.warn_hook_return.value_or(true);
2947
2948 if (config.rom_path.has_value()) {
2949 z3dk_settings.rom_path = ResolveOptionalPath(base_dir, *config.rom_path);
2950 }
2951 if (config.symbols_path.has_value()) {
2953 ResolveOptionalPath(base_dir, *config.symbols_path);
2954 }
2955
2956 for (const auto& emit_path : z3dk_settings.emits) {
2957 const std::string basename = BasenameLower(emit_path);
2958 if (basename.ends_with(".mlb") &&
2961 } else if (basename == "sourcemap.json") {
2963 } else if (basename == "annotations.json") {
2965 } else if (basename == "hooks.json") {
2967 } else if (basename == "lint.json") {
2969 }
2970 }
2971
2973 if (!z3dk_settings.symbols_path.empty() &&
2974 BasenameLower(z3dk_settings.symbols_path).ends_with(".mlb")) {
2976 } else {
2978 GetZ3dkArtifactPath("symbols.mlb");
2979 }
2980 }
2983 GetZ3dkArtifactPath("sourcemap.json");
2984 }
2987 GetZ3dkArtifactPath("annotations.json");
2988 }
2991 GetZ3dkArtifactPath("hooks.json");
2992 }
2995 }
2996
2997 LOG_INFO("Project",
2998 "Loaded z3dk config from %s (%zu include paths, %zu defines)",
2999 z3dk_settings.config_path.c_str(),
3001 return;
3002 }
3003#endif
3004}
3005
3007#ifdef __EMSCRIPTEN__
3010 return; // Hack manifests not supported in web builds
3011#endif
3012
3013 // Clear previous state so we never keep a stale manifest across project loads.
3016
3017 std::filesystem::path loaded_manifest_path;
3018 auto load_manifest = [&](const std::filesystem::path& candidate,
3019 bool update_project_setting) -> bool {
3020 if (candidate.empty() || !std::filesystem::exists(candidate)) {
3021 return false;
3022 }
3023 auto status = hack_manifest.LoadFromFile(candidate.string());
3024 if (!status.ok()) {
3025 LOG_WARN("Project", "Failed to load hack manifest %s: %s",
3026 candidate.string().c_str(),
3027 std::string(status.message()).c_str());
3028 return false;
3029 }
3030 loaded_manifest_path = candidate;
3031 if (update_project_setting) {
3032 hack_manifest_file = GetRelativePath(candidate.string());
3033 }
3034 LOG_DEBUG("Project", "Loaded hack manifest: %s",
3035 candidate.string().c_str());
3037 return true;
3038 };
3039
3040 // Priority 1: An explicit hack_manifest_file setting is authoritative. Do
3041 // not silently replace a missing or malformed configured manifest with an
3042 // auto-discovered file; project validation must surface the bad reference.
3043 const bool has_explicit_manifest = !hack_manifest_file.empty();
3044 if (has_explicit_manifest) {
3045 (void)load_manifest(GetAbsolutePath(hack_manifest_file), false);
3046 }
3047
3048 // Priority 2: Auto-discover hack_manifest.json in code_folder.
3049 if (!has_explicit_manifest && !hack_manifest.loaded() &&
3050 !code_folder.empty()) {
3051 auto code_path = GetAbsolutePath(code_folder);
3052 auto candidate = std::filesystem::path(code_path) / "hack_manifest.json";
3053 (void)load_manifest(candidate, true);
3054 }
3055
3056 // Priority 3: Fallback to the project file directory (or its parent).
3057 if (!has_explicit_manifest && !hack_manifest.loaded() && !filepath.empty()) {
3058 const std::filesystem::path project_dir =
3059 std::filesystem::path(filepath).parent_path();
3060 (void)load_manifest(project_dir / "hack_manifest.json", true);
3061 if (!hack_manifest.loaded() && project_dir.has_parent_path()) {
3062 (void)load_manifest(project_dir.parent_path() / "hack_manifest.json",
3063 true);
3064 }
3065 }
3066
3067 if (hack_manifest.loaded()) {
3069 }
3070
3071 auto try_load_registry = [&](const std::filesystem::path& base) -> bool {
3072 if (base.empty()) {
3073 return false;
3074 }
3075 const auto planning = base / "Docs" / "Dev" / "Planning";
3076 if (!std::filesystem::exists(planning)) {
3077 return false;
3078 }
3079 auto status = hack_manifest.LoadProjectRegistry(base.string());
3080 if (!status.ok()) {
3081 LOG_WARN("Project", "Failed to load project registry from %s: %s",
3082 base.string().c_str(), std::string(status.message()).c_str());
3083 return false;
3084 }
3086 };
3087
3088 bool registry_loaded = false;
3089
3090 // Prefer configured code_folder when valid.
3091 if (!code_folder.empty()) {
3092 registry_loaded =
3093 try_load_registry(std::filesystem::path(GetAbsolutePath(code_folder)));
3094 }
3095
3096 // Fallback to the manifest directory if code_folder is stale/misconfigured.
3097 if (!registry_loaded && !loaded_manifest_path.empty()) {
3098 registry_loaded = try_load_registry(loaded_manifest_path.parent_path());
3099 }
3100
3101 // Last fallback: project directory.
3102 if (!registry_loaded && !filepath.empty()) {
3103 registry_loaded =
3104 try_load_registry(std::filesystem::path(filepath).parent_path());
3105 }
3106
3107 if (!registry_loaded) {
3108 if (!hack_manifest.loaded()) {
3109 return;
3110 }
3111 LOG_WARN("Project",
3112 "Hack manifest loaded but project registry was not found "
3113 "(code_folder='%s', manifest='%s')",
3114 code_folder.c_str(), loaded_manifest_path.string().c_str());
3115 return;
3116 }
3117
3118 // Inject all Oracle resource labels into project resource_labels.
3119 size_t injected = 0;
3120 for (const auto& [type_key, labels] :
3122 for (const auto& [id_str, label] : labels) {
3123 resource_labels[type_key][id_str] = label;
3124 ++injected;
3125 }
3126 }
3127 LOG_DEBUG("Project", "Loaded project registry: %zu resource labels injected",
3128 injected);
3129}
3130
3132 sprite_catalog_file.clear();
3133 sprite_source_root.clear();
3134 sprite_assets.clear();
3135 terrain_catalog_file.clear();
3136 lyra_terrain_file.clear();
3141 palette_catalog_file.clear();
3142 dungeon_tile_patterns.clear();
3143 if (metadata.project_id.empty()) {
3145 }
3146
3147 // Initialize default feature flags
3163 // REMOVED: kLogInstructions (deprecated)
3164
3165 // Initialize default workspace settings
3168 workspace_settings.ui_theme = "default";
3170 workspace_settings.autosave_interval_secs = 300.0f; // 5 minutes
3177
3178 // Initialize default dungeon overlay settings (minecart tracks)
3180 for (uint16_t tile = 0xB0; tile <= 0xBE; ++tile) {
3181 dungeon_overlay.track_tiles.push_back(tile);
3182 }
3183 dungeon_overlay.track_stop_tiles = {0xB7, 0xB8, 0xB9, 0xBA};
3184 dungeon_overlay.track_switch_tiles = {0xD0, 0xD1, 0xD2, 0xD3};
3187
3191
3192 // Initialize default build configurations
3193 build_configurations = {"Debug", "Release", "Distribution"};
3194 build_target.clear();
3195 asm_entry_point = "asm/main.asm";
3196 asm_sources = {"asm"};
3197 last_build_hash.clear();
3198 build_number = 0;
3199
3200 track_changes = true;
3201
3205
3206 if (metadata.created_by.empty()) {
3207 metadata.created_by = "YAZE";
3208 }
3209}
3210
3212 auto now = std::chrono::system_clock::now().time_since_epoch();
3213 auto timestamp =
3214 std::chrono::duration_cast<std::chrono::milliseconds>(now).count();
3215 return absl::StrFormat("yaze_project_%lld", timestamp);
3216}
3217
3218// ProjectManager Implementation
3219std::vector<ProjectManager::ProjectTemplate>
3221 std::vector<ProjectTemplate> templates;
3222
3223 // ==========================================================================
3224 // ZSCustomOverworld Templates (Recommended)
3225 // ==========================================================================
3226
3227 // Vanilla ROM Hack - no ZSO
3228 {
3230 t.name = "Vanilla ROM Hack";
3231 t.description =
3232 "Standard ROM editing without custom ASM. Limited to vanilla features.";
3236 false;
3241 templates.push_back(t);
3242 }
3243
3244 // ZSCustomOverworld v2 - Basic expansion
3245 {
3247 t.name = "ZSCustomOverworld v2";
3248 t.description =
3249 "Basic overworld expansion: custom BG colors, main palettes, parent "
3250 "system.";
3251 t.icon = ICON_MD_MAP;
3254 true;
3261 t.template_project.metadata.tags = {"zso_v2", "overworld", "expansion"};
3262 templates.push_back(t);
3263 }
3264
3265 // ZSCustomOverworld v3 - Full features (Recommended)
3266 {
3268 t.name = "ZSCustomOverworld v3 (Recommended)";
3269 t.description =
3270 "Full overworld expansion: wide/tall areas, animated GFX, overlays, "
3271 "all features.";
3275 true;
3285 t.template_project.metadata.tags = {"zso_v3", "overworld", "full",
3286 "recommended"};
3287 templates.push_back(t);
3288 }
3289
3290 // Randomizer Compatible
3291 {
3293 t.name = "Randomizer Compatible";
3294 t.description =
3295 "Compatible with ALttP Randomizer. Minimal custom features to avoid "
3296 "conflicts.";
3300 false;
3304 t.template_project.metadata.tags = {"randomizer", "compatible", "minimal"};
3305 templates.push_back(t);
3306 }
3307
3308 // ==========================================================================
3309 // Editor-Focused Templates
3310 // ==========================================================================
3311
3312 // Dungeon Designer
3313 {
3315 t.name = "Dungeon Designer";
3316 t.description = "Focused on dungeon creation and modification.";
3317 t.icon = ICON_MD_DOMAIN;
3321 "dungeon_default";
3322 t.template_project.metadata.tags = {"dungeons", "rooms", "design"};
3323 templates.push_back(t);
3324 }
3325
3326 // Graphics Pack
3327 {
3329 t.name = "Graphics Pack";
3330 t.description =
3331 "Project focused on graphics, sprites, and visual modifications.";
3338 "graphics_default";
3339 t.template_project.metadata.tags = {"graphics", "sprites", "palettes"};
3340 templates.push_back(t);
3341 }
3342
3343 // Complete Overhaul
3344 {
3346 t.name = "Complete Overhaul";
3347 t.description = "Full-scale ROM hack with all features enabled.";
3348 t.icon = ICON_MD_BUILD;
3351 true;
3361 t.template_project.metadata.tags = {"complete", "overhaul", "full-mod"};
3362 templates.push_back(t);
3363 }
3364
3365 return templates;
3366}
3367
3368absl::StatusOr<YazeProject> ProjectManager::CreateFromTemplate(
3369 const std::string& template_name, const std::string& project_name,
3370 const std::string& base_path) {
3371 YazeProject project;
3372 auto status = project.Create(project_name, base_path);
3373 if (!status.ok()) {
3374 return status;
3375 }
3376
3377 // Customize based on template
3378 if (template_name == "Full Overworld Mod") {
3381 project.metadata.description = "Overworld modification project";
3382 project.metadata.tags = {"overworld", "maps", "graphics"};
3383 } else if (template_name == "Dungeon Designer") {
3384 project.feature_flags.kSaveDungeonMaps = true;
3385 project.workspace_settings.show_grid = true;
3386 project.metadata.description = "Dungeon design and modification project";
3387 project.metadata.tags = {"dungeons", "rooms", "design"};
3388 } else if (template_name == "Graphics Pack") {
3389 project.feature_flags.kSaveGraphicsSheet = true;
3390 project.workspace_settings.show_grid = true;
3391 project.metadata.description = "Graphics and sprite modification project";
3392 project.metadata.tags = {"graphics", "sprites", "palettes"};
3393 } else if (template_name == "Complete Overhaul") {
3396 project.feature_flags.kSaveDungeonMaps = true;
3397 project.feature_flags.kSaveGraphicsSheet = true;
3398 project.metadata.description = "Complete ROM overhaul project";
3399 project.metadata.tags = {"complete", "overhaul", "full-mod"};
3400 }
3401
3402 status = project.Save();
3403 if (!status.ok()) {
3404 return status;
3405 }
3406
3407 return project;
3408}
3409
3411 const std::string& directory) {
3412#ifdef __EMSCRIPTEN__
3413 (void)directory;
3414 return {};
3415#else
3416 std::vector<std::string> projects;
3417
3418 try {
3419 for (const auto& entry : std::filesystem::directory_iterator(directory)) {
3420 if (entry.is_regular_file()) {
3421 std::string filename = entry.path().filename().string();
3422 if (filename.ends_with(".yaze") || filename.ends_with(".zsproj")) {
3423 projects.push_back(entry.path().string());
3424 }
3425 } else if (entry.is_directory()) {
3426 std::string filename = entry.path().filename().string();
3427 if (filename.ends_with(".yazeproj")) {
3428 projects.push_back(entry.path().string());
3429 }
3430 }
3431 }
3432 } catch (const std::filesystem::filesystem_error& e) {
3433 // Directory doesn't exist or can't be accessed
3434 }
3435
3436 return projects;
3437#endif // __EMSCRIPTEN__
3438}
3439
3440absl::Status ProjectManager::BackupProject(const YazeProject& project) {
3441#ifdef __EMSCRIPTEN__
3442 (void)project;
3443 return absl::UnimplementedError(
3444 "Project backups are not supported in the web build");
3445#else
3446 if (project.filepath.empty()) {
3447 return absl::InvalidArgumentError("Project has no file path");
3448 }
3449
3450 std::filesystem::path project_path(project.filepath);
3451 std::filesystem::path backup_dir = project_path.parent_path() / "backups";
3452 std::filesystem::create_directories(backup_dir);
3453
3454 auto now = std::chrono::system_clock::now();
3455 auto time_t = std::chrono::system_clock::to_time_t(now);
3456 std::stringstream ss;
3457 ss << std::put_time(std::localtime(&time_t), "%Y%m%d_%H%M%S");
3458
3459 std::string backup_filename = project.name + "_backup_" + ss.str() + ".yaze";
3460 std::filesystem::path backup_path = backup_dir / backup_filename;
3461
3462 try {
3463 std::filesystem::copy_file(project.filepath, backup_path);
3464 } catch (const std::filesystem::filesystem_error& e) {
3465 return absl::InternalError(
3466 absl::StrFormat("Failed to backup project: %s", e.what()));
3467 }
3468
3469 return absl::OkStatus();
3470#endif
3471}
3472
3474 const YazeProject& project) {
3475 return project.Validate();
3476}
3477
3479 const YazeProject& project) {
3480 std::vector<std::string> recommendations;
3481
3482 if (project.rom_filename.empty()) {
3483 recommendations.push_back("Add a ROM file to begin editing");
3484 }
3485
3486 if (project.code_folder.empty()) {
3487 recommendations.push_back("Set up a code folder for assembly patches");
3488 }
3489
3490 if (project.labels_filename.empty()) {
3491 recommendations.push_back("Create a labels file for better organization");
3492 }
3493
3494 if (project.metadata.description.empty()) {
3495 recommendations.push_back("Add a project description for documentation");
3496 }
3497
3498 if (project.git_repository.empty() && project.track_changes) {
3499 recommendations.push_back(
3500 "Consider setting up version control for your project");
3501 }
3502
3503 auto missing_files = project.GetMissingFiles();
3504 if (!missing_files.empty()) {
3505 recommendations.push_back(
3506 "Some project files are missing - use Project > Repair to fix");
3507 }
3508
3509 return recommendations;
3510}
3511
3512// Compatibility implementations for ResourceLabelManager and related classes
3513bool ResourceLabelManager::LoadLabels(const std::string& filename) {
3514 filename_ = filename;
3515 std::ifstream file(filename);
3516 if (!file.is_open()) {
3517 labels_loaded_ = false;
3518 return false;
3519 }
3520
3521 labels_.clear();
3522 std::string line;
3523 std::string current_type = "";
3524
3525 while (std::getline(file, line)) {
3526 if (line.empty() || line[0] == '#')
3527 continue;
3528
3529 // Check for type headers [type_name]
3530 if (line[0] == '[' && line.back() == ']') {
3531 current_type = line.substr(1, line.length() - 2);
3532 continue;
3533 }
3534
3535 // Parse key=value pairs
3536 size_t eq_pos = line.find('=');
3537 if (eq_pos != std::string::npos && !current_type.empty()) {
3538 std::string key = line.substr(0, eq_pos);
3539 std::string value = line.substr(eq_pos + 1);
3540 labels_[current_type][key] = value;
3541 }
3542 }
3543
3544 file.close();
3545 MigrateGfxGroupLabelKeys(labels_);
3546 labels_loaded_ = true;
3547 return true;
3548}
3549
3551 if (filename_.empty())
3552 return false;
3553
3554 std::ofstream file(filename_);
3555 if (!file.is_open())
3556 return false;
3557
3558 file << "# yaze Resource Labels\n";
3559 file << "# Format: [type] followed by key=value pairs\n\n";
3560
3561 for (const auto& [type, type_labels] : labels_) {
3562 if (!type_labels.empty()) {
3563 file << "[" << type << "]\n";
3564 for (const auto& [key, value] : type_labels) {
3565 file << key << "=" << value << "\n";
3566 }
3567 file << "\n";
3568 }
3569 }
3570
3571 file.close();
3572 return true;
3573}
3574
3576 if (!p_open || !*p_open)
3577 return;
3578
3579 // Basic implementation - can be enhanced later
3580 if (ImGui::Begin("Resource Labels", p_open)) {
3581 ImGui::Text("Resource Labels Manager");
3582 ImGui::Text("Labels loaded: %s", labels_loaded_ ? "Yes" : "No");
3583 ImGui::Text("Total types: %zu", labels_.size());
3584
3585 for (const auto& [type, type_labels] : labels_) {
3586 if (ImGui::TreeNode(type.c_str())) {
3587 ImGui::Text("Labels: %zu", type_labels.size());
3588 for (const auto& [key, value] : type_labels) {
3589 ImGui::Text("%s = %s", key.c_str(), value.c_str());
3590 }
3591 ImGui::TreePop();
3592 }
3593 }
3594 }
3595 ImGui::End();
3596}
3597
3598void ResourceLabelManager::EditLabel(const std::string& type,
3599 const std::string& key,
3600 const std::string& newValue) {
3601 labels_[type][key] = newValue;
3602}
3603
3605 bool selected, const std::string& type, const std::string& key,
3606 const std::string& defaultValue) {
3607 const auto custom_label = GetLabel(type, key);
3608 const auto& label = custom_label.empty() ? defaultValue : custom_label;
3609 if (ImGui::Selectable(
3610 absl::StrFormat("%s: %s", key.c_str(), label.c_str()).c_str(),
3611 selected)) {
3612 // Handle selection
3613 }
3614}
3615
3616std::string ResourceLabelManager::GetLabel(const std::string& type,
3617 const std::string& key) {
3618 auto type_it = labels_.find(type);
3619 if (type_it == labels_.end())
3620 return "";
3621
3622 auto label_it = type_it->second.find(key);
3623 if (label_it == type_it->second.end())
3624 return "";
3625
3626 return label_it->second;
3627}
3628
3630 const std::string& type, const std::string& key,
3631 const std::string& defaultValue) {
3632 auto existing = GetLabel(type, key);
3633 if (!existing.empty())
3634 return existing;
3635
3636 labels_[type][key] = defaultValue;
3637 return defaultValue;
3638}
3639
3640// ============================================================================
3641// Embedded Labels Support
3642// ============================================================================
3643
3645 const std::unordered_map<
3646 std::string, std::unordered_map<std::string, std::string>>& labels) {
3647 try {
3648 // Load all default Zelda3 resource names into resource_labels
3649 // We merge them with existing labels, prioritizing existing overrides?
3650 // Or just overwrite? The previous code was:
3651 // resource_labels = zelda3::Zelda3Labels::ToResourceLabels();
3652 // which implies overwriting. But we want to keep overrides if possible.
3653 // However, this is usually called on load.
3654
3655 // Let's overwrite for now to match previous behavior, assuming overrides
3656 // are loaded afterwards or this is initial setup.
3657 // Actually, if we load project then init embedded labels, we might lose overrides.
3658 // But typically overrides are loaded from the project file *into* resource_labels.
3659 // If we call this, we might clobber them.
3660 // The previous implementation clobbered resource_labels.
3661
3662 // However, if we want to support overrides + embedded, we should merge.
3663 // But `resource_labels` was treated as "overrides" in the old code?
3664 // No, `resource_labels` was the container for loaded labels.
3665
3666 // If I look at `LoadFromYazeFormat`:
3667 // It parses `[labels_type]` into `resource_labels`.
3668
3669 // If `use_embedded_labels` is true, `InitializeEmbeddedLabels` is called?
3670 // I need to check when `InitializeEmbeddedLabels` is called.
3671
3672 resource_labels = labels;
3673 use_embedded_labels = true;
3674
3675 LOG_DEBUG("Project", "Initialized embedded labels:");
3676 LOG_DEBUG("Project", " - %d room names", resource_labels["room"].size());
3677 LOG_DEBUG("Project", " - %d entrance names",
3678 resource_labels["entrance"].size());
3679 LOG_DEBUG("Project", " - %d sprite names",
3680 resource_labels["sprite"].size());
3681 LOG_DEBUG("Project", " - %d overlord names",
3682 resource_labels["overlord"].size());
3683 LOG_DEBUG("Project", " - %d item names", resource_labels["item"].size());
3684 LOG_DEBUG("Project", " - %d music names",
3685 resource_labels["music"].size());
3686 LOG_DEBUG("Project", " - %d graphics names",
3687 resource_labels["graphics"].size());
3688 LOG_DEBUG("Project", " - %d room effect names",
3689 resource_labels["room_effect"].size());
3690 LOG_DEBUG("Project", " - %d room tag names",
3691 resource_labels["room_tag"].size());
3692 LOG_DEBUG("Project", " - %d tile type names",
3693 resource_labels["tile_type"].size());
3694
3695 return absl::OkStatus();
3696 } catch (const std::exception& e) {
3697 return absl::InternalError(
3698 absl::StrCat("Failed to initialize embedded labels: ", e.what()));
3699 }
3700}
3701
3702std::string YazeProject::GetLabel(const std::string& resource_type, int id,
3703 const std::string& default_value) const {
3704 // First check if we have a custom label override
3705 auto type_it = resource_labels.find(resource_type);
3706 if (type_it != resource_labels.end()) {
3707 auto label_it = type_it->second.find(std::to_string(id));
3708 if (label_it != type_it->second.end()) {
3709 return label_it->second;
3710 }
3711 }
3712
3713 return default_value.empty() ? resource_type + "_" + std::to_string(id)
3714 : default_value;
3715}
3716
3717absl::Status YazeProject::ImportLabelsFromZScream(const std::string& filepath) {
3718#ifdef __EMSCRIPTEN__
3719 (void)filepath;
3720 return absl::UnimplementedError(
3721 "File-based label import is not supported in the web build");
3722#else
3723 std::ifstream file(filepath);
3724 if (!file.is_open()) {
3725 return absl::InvalidArgumentError(
3726 absl::StrFormat("Cannot open labels file: %s", filepath));
3727 }
3728
3729 std::stringstream buffer;
3730 buffer << file.rdbuf();
3731 file.close();
3732
3733 return ImportLabelsFromZScreamContent(buffer.str());
3734#endif
3735}
3736
3738 const std::string& content) {
3739 // Initialize the global provider with our labels
3740 auto& provider = zelda3::GetResourceLabels();
3741 provider.SetProjectLabels(&resource_labels);
3742 provider.SetPreferHMagicNames(workspace_settings.prefer_hmagic_names);
3743
3744 // Use the provider to parse ZScream format
3745 auto status = provider.ImportFromZScreamFormat(content);
3746 if (!status.ok()) {
3747 return status;
3748 }
3749
3750 LOG_DEBUG("Project", "Imported ZScream labels:");
3751 LOG_DEBUG("Project", " - %d sprite labels",
3752 resource_labels["sprite"].size());
3753 LOG_DEBUG("Project", " - %d room labels", resource_labels["room"].size());
3754 LOG_DEBUG("Project", " - %d item labels", resource_labels["item"].size());
3755 LOG_DEBUG("Project", " - %d room tag labels",
3756 resource_labels["room_tag"].size());
3757
3758 return absl::OkStatus();
3759}
3760
3762 auto& provider = zelda3::GetResourceLabels();
3763 provider.SetProjectLabels(&resource_labels);
3764 provider.SetPreferHMagicNames(workspace_settings.prefer_hmagic_names);
3765 provider.SetHackManifest(hack_manifest.loaded() ? &hack_manifest : nullptr);
3766
3767 LOG_DEBUG("Project", "Initialized ResourceLabelProvider with project labels");
3768 LOG_DEBUG("Project", " - prefer_hmagic_names: %s",
3769 workspace_settings.prefer_hmagic_names ? "true" : "false");
3770 LOG_DEBUG("Project", " - hack_manifest: %s",
3771 hack_manifest.loaded() ? "loaded" : "not loaded");
3772}
3773
3774// ============================================================================
3775// JSON Format Support (Optional)
3776// ============================================================================
3777
3778#ifdef YAZE_ENABLE_JSON_PROJECT_FORMAT
3779
3780absl::Status YazeProject::LoadFromJsonFormat(const std::string& project_path) {
3785 terrain_catalog_file.clear();
3786 lyra_terrain_file.clear();
3791 palette_catalog_file.clear();
3792 dungeon_tile_patterns.clear();
3793#ifdef __EMSCRIPTEN__
3794 return absl::UnimplementedError(
3795 "JSON project format loading is not supported in the web build");
3796#endif
3797 std::ifstream file(project_path);
3798 if (!file.is_open()) {
3799 return absl::InvalidArgumentError(
3800 absl::StrFormat("Cannot open JSON project file: %s", project_path));
3801 }
3802
3803 try {
3804 Json j;
3805 file >> j;
3806
3807 sprite_catalog_file.clear();
3808 sprite_source_root.clear();
3809 sprite_assets.clear();
3810
3811 // Parse project metadata
3812 if (j.contains("yaze_project")) {
3813 auto& proj = j["yaze_project"];
3814
3815 if (proj.contains("name"))
3816 name = proj["name"].get<std::string>();
3817 if (proj.contains("description"))
3818 metadata.description = proj["description"].get<std::string>();
3819 if (proj.contains("author"))
3820 metadata.author = proj["author"].get<std::string>();
3821 if (proj.contains("version"))
3822 metadata.version = proj["version"].get<std::string>();
3823 if (proj.contains("created"))
3824 metadata.created_date = proj["created"].get<std::string>();
3825 if (proj.contains("modified"))
3826 metadata.last_modified = proj["modified"].get<std::string>();
3827 if (proj.contains("created_by"))
3828 metadata.created_by = proj["created_by"].get<std::string>();
3829
3830 // Files
3831 if (proj.contains("rom_filename"))
3832 rom_filename = proj["rom_filename"].get<std::string>();
3833 if (proj.contains("rom_backup_folder"))
3834 rom_backup_folder = proj["rom_backup_folder"].get<std::string>();
3835 if (proj.contains("code_folder"))
3836 code_folder = proj["code_folder"].get<std::string>();
3837 if (proj.contains("assets_folder"))
3838 assets_folder = proj["assets_folder"].get<std::string>();
3839 if (proj.contains("patches_folder"))
3840 patches_folder = proj["patches_folder"].get<std::string>();
3841 if (proj.contains("labels_filename"))
3842 labels_filename = proj["labels_filename"].get<std::string>();
3843 if (proj.contains("symbols_filename"))
3844 symbols_filename = proj["symbols_filename"].get<std::string>();
3845 if (proj.contains("dungeon_tile_patterns"))
3847 proj["dungeon_tile_patterns"].get<std::string>();
3848 if (proj.contains("palette_catalog_file"))
3849 palette_catalog_file = proj["palette_catalog_file"].get<std::string>();
3850 if (proj.contains("terrain_catalog_file"))
3851 terrain_catalog_file = proj["terrain_catalog_file"].get<std::string>();
3852 if (proj.contains("lyra_terrain_file"))
3853 lyra_terrain_file = proj["lyra_terrain_file"].get<std::string>();
3854 if (proj.contains("lyra_build_request_file"))
3856 proj["lyra_build_request_file"].get<std::string>();
3857 if (proj.contains("native_save_producer_file"))
3859 proj["native_save_producer_file"].get<std::string>();
3860 if (proj.contains("native_save_transfer_proof_file"))
3862 proj["native_save_transfer_proof_file"].get<std::string>();
3863 if (proj.contains("native_save_receipt_file"))
3865 proj["native_save_receipt_file"].get<std::string>();
3866 if (proj.contains("hack_manifest_file"))
3867 hack_manifest_file = proj["hack_manifest_file"].get<std::string>();
3868 if (proj.contains("sprite_catalog_file"))
3869 sprite_catalog_file = proj["sprite_catalog_file"].get<std::string>();
3870 if (proj.contains("sprite_source_root"))
3871 sprite_source_root = proj["sprite_source_root"].get<std::string>();
3872 if (proj.contains("sprite_assets")) {
3873 if (!proj["sprite_assets"].is_array() ||
3874 proj["sprite_assets"].size() > 4096)
3875 return absl::InvalidArgumentError("Invalid sprite_assets array");
3876 for (const auto& value : proj["sprite_assets"]) {
3877 auto asset = SpriteAssetFromJson(value);
3878 if (!asset.ok())
3879 return asset.status();
3880 for (const auto& prior : sprite_assets)
3881 if (prior.zsm_path == asset->zsm_path)
3882 return absl::InvalidArgumentError("Duplicate sprite asset path");
3883 sprite_assets.push_back(std::move(*asset));
3884 }
3885 }
3886
3887 if (proj.contains("rom") && proj["rom"].is_object()) {
3888 auto& rom = proj["rom"];
3889 if (rom.contains("role"))
3890 rom_metadata.role = ParseRomRole(rom["role"].get<std::string>());
3891 if (rom.contains("expected_hash"))
3892 rom_metadata.expected_hash = rom["expected_hash"].get<std::string>();
3893 if (rom.contains("write_policy"))
3895 ParseRomWritePolicy(rom["write_policy"].get<std::string>());
3896 }
3897
3898 // Embedded labels flag
3899 if (proj.contains("use_embedded_labels")) {
3900 use_embedded_labels = proj["use_embedded_labels"].get<bool>();
3901 }
3902
3903 // Feature flags
3904 if (proj.contains("feature_flags")) {
3905 auto& flags = proj["feature_flags"];
3906 // REMOVED: kLogInstructions (deprecated - DisassemblyViewer always
3907 // active)
3908 if (flags.contains("kSaveDungeonMaps"))
3910 flags["kSaveDungeonMaps"].get<bool>();
3911 if (flags.contains("kSaveWithChangeQueue"))
3913 flags["kSaveWithChangeQueue"].get<bool>();
3914 if (flags.contains("kEnableSpecialWorldExpansion"))
3916 flags["kEnableSpecialWorldExpansion"].get<bool>();
3917 if (flags.contains("kSaveOverworldMaps"))
3919 flags["kSaveOverworldMaps"].get<bool>();
3920 if (flags.contains("kSaveOverworldEntrances"))
3922 flags["kSaveOverworldEntrances"].get<bool>();
3923 if (flags.contains("kSaveOverworldExits"))
3925 flags["kSaveOverworldExits"].get<bool>();
3926 if (flags.contains("kSaveOverworldItems"))
3928 flags["kSaveOverworldItems"].get<bool>();
3929 if (flags.contains("kSaveOverworldSprites"))
3931 flags["kSaveOverworldSprites"].get<bool>();
3932 if (flags.contains("kSaveOverworldProperties"))
3934 flags["kSaveOverworldProperties"].get<bool>();
3935 if (flags.contains("kSaveDungeonObjects"))
3937 flags["kSaveDungeonObjects"].get<bool>();
3938 if (flags.contains("kSaveDungeonSprites"))
3940 flags["kSaveDungeonSprites"].get<bool>();
3941 if (flags.contains("kSaveDungeonRoomHeaders"))
3943 flags["kSaveDungeonRoomHeaders"].get<bool>();
3944 if (flags.contains("kSaveDungeonTorches"))
3946 flags["kSaveDungeonTorches"].get<bool>();
3947 if (flags.contains("kSaveDungeonPits"))
3949 flags["kSaveDungeonPits"].get<bool>();
3950 if (flags.contains("kSaveDungeonBlocks"))
3952 flags["kSaveDungeonBlocks"].get<bool>();
3953 if (flags.contains("kSaveDungeonCollision"))
3955 flags["kSaveDungeonCollision"].get<bool>();
3956 if (flags.contains("kSaveDungeonWaterFillZones"))
3958 flags["kSaveDungeonWaterFillZones"].get<bool>();
3959 if (flags.contains("kSaveDungeonChests"))
3961 flags["kSaveDungeonChests"].get<bool>();
3962 if (flags.contains("kSaveDungeonPotItems"))
3964 flags["kSaveDungeonPotItems"].get<bool>();
3965 if (flags.contains("kSaveDungeonEntrances"))
3967 flags["kSaveDungeonEntrances"].get<bool>();
3968 if (flags.contains("kSaveDungeonPalettes"))
3970 flags["kSaveDungeonPalettes"].get<bool>();
3971 if (flags.contains("kSaveGraphicsSheet"))
3973 flags["kSaveGraphicsSheet"].get<bool>();
3974 if (flags.contains("kSaveAllPalettes"))
3976 flags["kSaveAllPalettes"].get<bool>();
3977 if (flags.contains("kSaveGfxGroups"))
3978 feature_flags.kSaveGfxGroups = flags["kSaveGfxGroups"].get<bool>();
3979 if (flags.contains("kSaveMessages"))
3980 feature_flags.kSaveMessages = flags["kSaveMessages"].get<bool>();
3981 }
3982
3983 // Workspace settings
3984 if (proj.contains("workspace_settings")) {
3985 auto& ws = proj["workspace_settings"];
3986 if (ws.contains("auto_save_enabled"))
3988 ws["auto_save_enabled"].get<bool>();
3989 if (ws.contains("auto_save_interval"))
3991 ws["auto_save_interval"].get<float>();
3992 if (ws.contains("backup_on_save"))
3993 workspace_settings.backup_on_save = ws["backup_on_save"].get<bool>();
3994 if (ws.contains("backup_retention_count"))
3996 ws["backup_retention_count"].get<int>();
3997 if (ws.contains("backup_keep_daily"))
3999 ws["backup_keep_daily"].get<bool>();
4000 if (ws.contains("backup_keep_daily_days"))
4002 ws["backup_keep_daily_days"].get<int>();
4003 }
4004
4005 if (proj.contains("rom_addresses") && proj["rom_addresses"].is_object()) {
4007 for (auto it = proj["rom_addresses"].begin();
4008 it != proj["rom_addresses"].end(); ++it) {
4009 if (it.value().is_number_unsigned()) {
4011 it.value().get<uint32_t>();
4012 } else if (it.value().is_string()) {
4013 auto parsed = ParseHexUint32(it.value().get<std::string>());
4014 if (parsed.has_value()) {
4015 rom_address_overrides.addresses[it.key()] = *parsed;
4016 }
4017 }
4018 }
4019 }
4020
4021 if (proj.contains("custom_objects") &&
4022 proj["custom_objects"].is_object()) {
4023 custom_object_files.clear();
4024 for (auto it = proj["custom_objects"].begin();
4025 it != proj["custom_objects"].end(); ++it) {
4026 if (!it.value().is_array())
4027 continue;
4028 auto parsed = ParseHexUint32(it.key());
4029 if (!parsed.has_value()) {
4030 continue;
4031 }
4032 std::vector<std::string> files;
4033 for (const auto& entry : it.value()) {
4034 if (entry.is_string()) {
4035 files.push_back(entry.get<std::string>());
4036 }
4037 }
4038 if (!files.empty()) {
4039 custom_object_files[static_cast<int>(*parsed)] = std::move(files);
4040 }
4041 }
4042 }
4043
4044 if (proj.contains("agent_settings") &&
4045 proj["agent_settings"].is_object()) {
4046 auto& agent = proj["agent_settings"];
4048 agent.value("ai_provider", agent_settings.ai_provider);
4050 agent.value("ai_model", agent_settings.ai_model);
4052 agent.value("ollama_host", agent_settings.ollama_host);
4054 agent.value("gemini_api_key", agent_settings.gemini_api_key);
4056 agent.value("use_custom_prompt", agent_settings.use_custom_prompt);
4058 "custom_system_prompt", agent_settings.custom_system_prompt);
4060 agent.value("show_reasoning", agent_settings.show_reasoning);
4061 agent_settings.verbose = agent.value("verbose", agent_settings.verbose);
4062 agent_settings.max_tool_iterations = agent.value(
4063 "max_tool_iterations", agent_settings.max_tool_iterations);
4064 agent_settings.max_retry_attempts = agent.value(
4065 "max_retry_attempts", agent_settings.max_retry_attempts);
4067 agent.value("temperature", agent_settings.temperature);
4068 agent_settings.top_p = agent.value("top_p", agent_settings.top_p);
4070 agent.value("max_output_tokens", agent_settings.max_output_tokens);
4072 agent.value("stream_responses", agent_settings.stream_responses);
4073 if (agent.contains("favorite_models") &&
4074 agent["favorite_models"].is_array()) {
4076 for (const auto& model : agent["favorite_models"]) {
4077 if (model.is_string())
4079 model.get<std::string>());
4080 }
4081 }
4082 if (agent.contains("model_chain") && agent["model_chain"].is_array()) {
4084 for (const auto& model : agent["model_chain"]) {
4085 if (model.is_string())
4086 agent_settings.model_chain.push_back(model.get<std::string>());
4087 }
4088 }
4090 agent.value("chain_mode", agent_settings.chain_mode);
4092 "enable_tool_resources", agent_settings.enable_tool_resources);
4093 agent_settings.enable_tool_dungeon = agent.value(
4094 "enable_tool_dungeon", agent_settings.enable_tool_dungeon);
4096 "enable_tool_overworld", agent_settings.enable_tool_overworld);
4098 "enable_tool_messages", agent_settings.enable_tool_messages);
4100 "enable_tool_dialogue", agent_settings.enable_tool_dialogue);
4102 agent.value("enable_tool_gui", agent_settings.enable_tool_gui);
4104 agent.value("enable_tool_music", agent_settings.enable_tool_music);
4105 agent_settings.enable_tool_sprite = agent.value(
4106 "enable_tool_sprite", agent_settings.enable_tool_sprite);
4108 "enable_tool_emulator", agent_settings.enable_tool_emulator);
4110 agent.value("enable_tool_memory_inspector",
4113 "builder_blueprint_path", agent_settings.builder_blueprint_path);
4114 }
4115
4116 // Build settings
4117 if (proj.contains("build_script"))
4118 build_script = proj["build_script"].get<std::string>();
4119 if (proj.contains("output_folder"))
4120 output_folder = proj["output_folder"].get<std::string>();
4121 if (proj.contains("git_repository"))
4122 git_repository = proj["git_repository"].get<std::string>();
4123 if (proj.contains("track_changes"))
4124 track_changes = proj["track_changes"].get<bool>();
4125 }
4126
4127 return absl::OkStatus();
4128 } catch (const Json::exception& e) {
4129 return absl::InvalidArgumentError(
4130 absl::StrFormat("JSON parse error: %s", e.what()));
4131 }
4132}
4133
4134absl::Status YazeProject::SaveToJsonFormat() {
4135#ifdef __EMSCRIPTEN__
4136 return absl::UnimplementedError(
4137 "JSON project format saving is not supported in the web build");
4138#endif
4139 Json j;
4140 auto& proj = j["yaze_project"];
4141
4142 // Metadata
4143 proj["version"] = metadata.version;
4144 proj["name"] = name;
4145 proj["author"] = metadata.author;
4146 proj["created_by"] = metadata.created_by;
4147 proj["description"] = metadata.description;
4148 proj["created"] = metadata.created_date;
4149 proj["modified"] = metadata.last_modified;
4150
4151 // Files
4152 proj["rom_filename"] = rom_filename;
4153 proj["rom_backup_folder"] = rom_backup_folder;
4154 proj["code_folder"] = code_folder;
4155 proj["assets_folder"] = assets_folder;
4156 proj["patches_folder"] = patches_folder;
4157 proj["labels_filename"] = labels_filename;
4158 proj["symbols_filename"] = symbols_filename;
4159 proj["dungeon_tile_patterns"] =
4161 proj["palette_catalog_file"] =
4163 proj["terrain_catalog_file"] =
4165 proj["lyra_terrain_file"] =
4167 proj["lyra_build_request_file"] =
4169 if (!native_save_producer_file.empty()) {
4170 proj["native_save_producer_file"] =
4172 }
4173 if (!native_save_transfer_proof_file.empty()) {
4174 proj["native_save_transfer_proof_file"] =
4176 }
4177 if (!native_save_receipt_file.empty()) {
4178 proj["native_save_receipt_file"] =
4180 }
4181 proj["hack_manifest_file"] = hack_manifest_file;
4182 proj["sprite_catalog_file"] =
4184 proj["sprite_source_root"] =
4186 proj["sprite_assets"] = nlohmann::json::array();
4187 for (auto asset : sprite_assets) {
4188 asset.zsm_path = GetRelativePath(GetAbsolutePath(asset.zsm_path));
4189 for (auto& source : asset.graphics_sources) {
4190 if (source.kind == "bin") {
4191 source.path = GetRelativePath(GetAbsolutePath(source.path));
4192 }
4193 }
4194 proj["sprite_assets"].push_back(SpriteAssetToJson(asset));
4195 }
4196 proj["output_folder"] = output_folder;
4197
4198 proj["rom"]["role"] = RomRoleToString(rom_metadata.role);
4199 proj["rom"]["expected_hash"] = rom_metadata.expected_hash;
4200 proj["rom"]["write_policy"] =
4202
4203 // Embedded labels
4204 proj["use_embedded_labels"] = use_embedded_labels;
4205
4206 // Feature flags
4207 // REMOVED: kLogInstructions (deprecated)
4208 proj["feature_flags"]["kSaveDungeonMaps"] = feature_flags.kSaveDungeonMaps;
4209 proj["feature_flags"]["kSaveWithChangeQueue"] =
4211 proj["feature_flags"]["kEnableSpecialWorldExpansion"] =
4213 proj["feature_flags"]["kSaveOverworldMaps"] =
4215 proj["feature_flags"]["kSaveOverworldEntrances"] =
4217 proj["feature_flags"]["kSaveOverworldExits"] =
4219 proj["feature_flags"]["kSaveOverworldItems"] =
4221 proj["feature_flags"]["kSaveOverworldSprites"] =
4223 proj["feature_flags"]["kSaveOverworldProperties"] =
4225 proj["feature_flags"]["kSaveDungeonObjects"] =
4227 proj["feature_flags"]["kSaveDungeonSprites"] =
4229 proj["feature_flags"]["kSaveDungeonRoomHeaders"] =
4231 proj["feature_flags"]["kSaveDungeonTorches"] =
4233 proj["feature_flags"]["kSaveDungeonPits"] = feature_flags.dungeon.kSavePits;
4234 proj["feature_flags"]["kSaveDungeonBlocks"] =
4236 proj["feature_flags"]["kSaveDungeonCollision"] =
4238 proj["feature_flags"]["kSaveDungeonWaterFillZones"] =
4240 proj["feature_flags"]["kSaveDungeonChests"] =
4242 proj["feature_flags"]["kSaveDungeonPotItems"] =
4244 proj["feature_flags"]["kSaveDungeonEntrances"] =
4246 proj["feature_flags"]["kSaveDungeonPalettes"] =
4248 proj["feature_flags"]["kSaveGraphicsSheet"] =
4250 proj["feature_flags"]["kSaveAllPalettes"] = feature_flags.kSaveAllPalettes;
4251 proj["feature_flags"]["kSaveGfxGroups"] = feature_flags.kSaveGfxGroups;
4252 proj["feature_flags"]["kSaveMessages"] = feature_flags.kSaveMessages;
4253
4254 // Workspace settings
4255 proj["workspace_settings"]["auto_save_enabled"] =
4257 proj["workspace_settings"]["auto_save_interval"] =
4259 proj["workspace_settings"]["backup_on_save"] =
4261 proj["workspace_settings"]["backup_retention_count"] =
4263 proj["workspace_settings"]["backup_keep_daily"] =
4265 proj["workspace_settings"]["backup_keep_daily_days"] =
4267
4268 auto& agent = proj["agent_settings"];
4269 agent["ai_provider"] = agent_settings.ai_provider;
4270 agent["ai_model"] = agent_settings.ai_model;
4271 agent["ollama_host"] = agent_settings.ollama_host;
4272 agent["gemini_api_key"] = agent_settings.gemini_api_key;
4273 agent["use_custom_prompt"] = agent_settings.use_custom_prompt;
4274 agent["custom_system_prompt"] = agent_settings.custom_system_prompt;
4275 agent["show_reasoning"] = agent_settings.show_reasoning;
4276 agent["verbose"] = agent_settings.verbose;
4277 agent["max_tool_iterations"] = agent_settings.max_tool_iterations;
4278 agent["max_retry_attempts"] = agent_settings.max_retry_attempts;
4279 agent["temperature"] = agent_settings.temperature;
4280 agent["top_p"] = agent_settings.top_p;
4281 agent["max_output_tokens"] = agent_settings.max_output_tokens;
4282 agent["stream_responses"] = agent_settings.stream_responses;
4283 agent["favorite_models"] = agent_settings.favorite_models;
4284 agent["model_chain"] = agent_settings.model_chain;
4285 agent["chain_mode"] = agent_settings.chain_mode;
4286 agent["enable_tool_resources"] = agent_settings.enable_tool_resources;
4287 agent["enable_tool_dungeon"] = agent_settings.enable_tool_dungeon;
4288 agent["enable_tool_overworld"] = agent_settings.enable_tool_overworld;
4289 agent["enable_tool_messages"] = agent_settings.enable_tool_messages;
4290 agent["enable_tool_dialogue"] = agent_settings.enable_tool_dialogue;
4291 agent["enable_tool_gui"] = agent_settings.enable_tool_gui;
4292 agent["enable_tool_music"] = agent_settings.enable_tool_music;
4293 agent["enable_tool_sprite"] = agent_settings.enable_tool_sprite;
4294 agent["enable_tool_emulator"] = agent_settings.enable_tool_emulator;
4295 agent["enable_tool_memory_inspector"] =
4297 agent["builder_blueprint_path"] = agent_settings.builder_blueprint_path;
4298
4299 if (!rom_address_overrides.addresses.empty()) {
4300 auto& addrs = proj["rom_addresses"];
4301 for (const auto& [key, value] : rom_address_overrides.addresses) {
4302 addrs[key] = value;
4303 }
4304 }
4305
4306 if (!custom_object_files.empty()) {
4307 auto& objs = proj["custom_objects"];
4308 for (const auto& [object_id, files] : custom_object_files) {
4309 objs[absl::StrFormat("0x%X", object_id)] = files;
4310 }
4311 }
4312
4313 // Build settings
4314 proj["build_script"] = build_script;
4315 proj["git_repository"] = git_repository;
4316 proj["track_changes"] = track_changes;
4317
4318 // Write to file
4319 std::ofstream file(filepath);
4320 if (!file.is_open()) {
4321 return absl::InvalidArgumentError(
4322 absl::StrFormat("Cannot write JSON project file: %s", filepath));
4323 }
4324
4325 file << j.dump(2); // Pretty print with 2-space indent
4326 return absl::OkStatus();
4327}
4328
4329#endif // YAZE_ENABLE_JSON_PROJECT_FORMAT
4330
4331// RecentFilesManager implementation
4333 auto config_dir = util::PlatformPaths::GetConfigDirectory();
4334 if (!config_dir.ok()) {
4335 return ""; // Or handle error appropriately
4336 }
4337 return (*config_dir / kRecentFilesFilename).string();
4338}
4339
4341#ifdef __EMSCRIPTEN__
4342 auto status = platform::WasmStorage::SaveProject(
4343 kRecentFilesFilename, absl::StrJoin(recent_files_, "\n"));
4344 if (!status.ok()) {
4345 LOG_WARN("RecentFilesManager", "Could not persist recent files: %s",
4346 status.ToString().c_str());
4347 }
4348 return;
4349#endif
4350 // Ensure config directory exists
4351 auto config_dir_status = util::PlatformPaths::GetConfigDirectory();
4352 if (!config_dir_status.ok()) {
4353 LOG_ERROR("Project", "Failed to get or create config directory: %s",
4354 config_dir_status.status().ToString().c_str());
4355 return;
4356 }
4357
4358 std::string filepath = GetFilePath();
4359 std::ofstream file(filepath);
4360 if (!file.is_open()) {
4361 LOG_WARN("RecentFilesManager", "Could not save recent files to %s",
4362 filepath.c_str());
4363 return;
4364 }
4365
4366 for (const auto& file_path : recent_files_) {
4367 file << file_path << std::endl;
4368 }
4369}
4370
4372#ifdef __EMSCRIPTEN__
4373 auto storage_or = platform::WasmStorage::LoadProject(kRecentFilesFilename);
4374 if (!storage_or.ok()) {
4375 return;
4376 }
4377 recent_files_.clear();
4378 std::istringstream stream(storage_or.value());
4379 std::string line;
4380 while (std::getline(stream, line)) {
4381 if (!line.empty()) {
4382 recent_files_.push_back(line);
4383 }
4384 }
4386 return;
4387#else
4388 std::string filepath = GetFilePath();
4389 std::ifstream file(filepath);
4390 if (!file.is_open()) {
4391 // File doesn't exist yet, which is fine
4392 return;
4393 }
4394
4395 recent_files_.clear();
4396 std::string line;
4397 while (std::getline(file, line)) {
4398 if (!line.empty()) {
4399 recent_files_.push_back(line);
4400 }
4401 }
4403#endif
4404}
4405
4406} // namespace project
4407} // namespace yaze
static Json parse(const std::string &)
Definition json.h:36
static Json array()
Definition json.h:35
T get() const
Definition json.h:49
bool contains(const std::string &) const
Definition json.h:53
void Clear()
Clear any loaded manifest state.
const std::string & hack_name() const
const ProjectRegistry & project_registry() const
bool HasProjectRegistry() const
absl::Status LoadProjectRegistry(const std::string &code_folder)
Load project registry data from the code folder.
std::optional< OracleProgressionState > oracle_progression_state() const
absl::Status LoadFromFile(const std::string &filepath)
Load manifest from a JSON file path.
bool loaded() const
Check if the manifest has been loaded.
const LyraTerrainProfile & profile() const
static absl::StatusOr< LyraTerrainDocument > Parse(std::string_view text, const LyraTerrainProfile &expected_profile)
static std::vector< std::string > FindProjectsInDirectory(const std::string &directory)
Definition project.cc:3410
static absl::Status ValidateProjectStructure(const YazeProject &project)
Definition project.cc:3473
static absl::StatusOr< YazeProject > CreateFromTemplate(const std::string &template_name, const std::string &project_name, const std::string &base_path)
Definition project.cc:3368
static std::vector< std::string > GetRecommendedFixesForProject(const YazeProject &project)
Definition project.cc:3478
static std::vector< ProjectTemplate > GetProjectTemplates()
Definition project.cc:3220
static absl::Status BackupProject(const YazeProject &project)
Definition project.cc:3440
std::string GetFilePath() const
Definition project.cc:4332
std::vector< std::string > recent_files_
Definition project.h:690
static absl::StatusOr< std::filesystem::path > GetConfigDirectory()
Get the user-specific configuration directory for YAZE.
void SetHackManifest(const core::HackManifest *manifest)
Set the hack manifest reference for ASM-defined labels.
struct destination destination
Room transition destination.
#define YAZE_VERSION_STRING
#define ICON_MD_SHUFFLE
Definition icons.h:1738
#define ICON_MD_TERRAIN
Definition icons.h:1952
#define ICON_MD_MAP
Definition icons.h:1173
#define ICON_MD_VIDEOGAME_ASSET
Definition icons.h:2076
#define ICON_MD_DOMAIN
Definition icons.h:603
#define ICON_MD_BUILD
Definition icons.h:328
#define ICON_MD_PALETTE
Definition icons.h:1370
#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 ASSIGN_OR_RETURN(type_variable_name, expression)
Definition macro.h:62
absl::Status PublishSourceArtifacts(const SourceArtifactPublicationLock &lock, std::vector< SourceArtifactUpdate > updates, std::string_view expected_primary_sha256, SourceArtifactReadbackValidator readback_validator)
std::string ComputeSourceArtifactSha256(std::string_view content)
absl::StatusOr< std::string > ComputeSourceArtifactFileSha256(const fs::path &path)
absl::StatusOr< NativeSaveContext > GetNativeSaveContext(const std::string &, const std::string &)
absl::StatusOr< std::unique_ptr< SourceArtifactPublicationLock > > AcquireSourceArtifactPublicationLock(const std::vector< fs::path > &targets, const SourceArtifactPublisherLabels &labels, const std::vector< fs::path > &read_only_targets)
Rom * rom()
Get the current ROM instance.
float ParseFloat(const std::string &value)
Definition project.cc:103
std::string ResolveOptionalPath(const std::filesystem::path &base_dir, const std::string &value)
Definition project.cc:302
void RemoveProjectSaveTempFile(const std::filesystem::path &temp_path)
Definition project.cc:338
bool ContainsLoneCarriageReturn(const std::string &content)
Definition project.cc:1373
std::vector< std::string > ParsePositionalStringList(const std::string &value)
Definition project.cc:128
absl::Status WriteProjectFileAtomicallyImpl(const std::filesystem::path &target_path, absl::string_view contents, bool replace_existing)
Definition project.cc:343
std::vector< uint16_t > ParseHexUintList(const std::string &value)
Definition project.cc:144
std::string ToLowerCopy(std::string value)
Definition project.cc:62
constexpr absl::string_view kProjectFileFooter
Definition project.cc:1383
bool ParseBool(const std::string &value)
Definition project.cc:99
std::pair< std::string, std::string > ParseDefineToken(const std::string &value)
Definition project.cc:294
std::optional< uint32_t > ParseHexUint32(const std::string &value)
Definition project.cc:172
bool IsKnownProjectSection(absl::string_view name)
Definition project.cc:1386
std::string FormatHexUint32(uint32_t value)
Definition project.cc:277
ProjectFilePassthrough::Section & PassthroughSection(ProjectFilePassthrough &passthrough, const std::string &name)
Definition project.cc:1427
absl::Status ParseProjectInteger(const std::string &value, const std::string &section, const std::string &key, int *output)
Definition project.cc:87
std::map< uint16_t, std::vector< uint16_t > > ParseHexUintListMap(const std::string &value)
Definition project.cc:251
std::string FormatHexUintListMap(const std::map< uint16_t, std::vector< uint16_t > > &values)
Definition project.cc:269
bool IsGeneratedProjectComment(absl::string_view line, bool before_sections)
Definition project.cc:1414
std::string SanitizeStorageKey(absl::string_view input)
Definition project.cc:281
std::filesystem::path MakeProjectSaveTempPath(const std::filesystem::path &target_path)
Definition project.cc:328
std::string MergeProjectFilePassthrough(const std::string &canonical, const ProjectFilePassthrough &passthrough)
Definition project.cc:1445
std::string FormatHexUintList(const std::vector< uint16_t > &values)
Definition project.cc:192
void MigrateGfxGroupLabelKeys(std::unordered_map< std::string, std::unordered_map< std::string, std::string > > &labels)
Definition project.cc:204
bool IsKeyLine(absl::string_view line)
Definition project.cc:1438
std::string BasenameLower(const std::string &path)
Definition project.cc:314
std::vector< std::string > ParseStringList(const std::string &value)
Definition project.cc:111
std::string RomRoleToString(RomRole role)
Definition project.cc:477
absl::Status WriteProjectFileAtomically(absl::string_view target_path, absl::string_view contents, bool replace_existing)
Definition project.cc:469
RomRole ParseRomRole(absl::string_view value)
Definition project.cc:491
const std::string kRecentFilesFilename
Definition project.h:627
RomWritePolicy ParseRomWritePolicy(absl::string_view value)
Definition project.cc:519
std::string RomWritePolicyToString(RomWritePolicy policy)
Definition project.cc:505
absl::StatusOr< SpriteAssetBinding > ParseSpriteAssetBinding(const std::string &text)
nlohmann::json SpriteAssetToJson(const SpriteAssetBinding &asset)
absl::StatusOr< SpriteAssetBinding > SpriteAssetFromJson(const nlohmann::json &value)
bool IsKnownProjectFileSection(absl::string_view name)
Definition project.cc:1598
ResourceLabelProvider & GetResourceLabels()
Get the global ResourceLabelProvider instance.
#define RETURN_IF_ERROR(expr)
Definition snes.cc:22
Room transition destination.
Definition zelda.h:448
struct yaze::core::FeatureFlags::Flags::Dungeon dungeon
struct yaze::core::FeatureFlags::Flags::Overworld overworld
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > all_resource_labels
std::unordered_map< std::string, uint32_t > addresses
Atlas map views ([atlas]).
Definition project.h:137
std::vector< std::string > annotations
Definition project.h:140
std::vector< uint16_t > track_object_ids
Definition project.h:104
std::vector< uint16_t > minecart_sprite_ids
Definition project.h:105
std::vector< uint16_t > track_stop_tiles
Definition project.h:100
std::vector< uint16_t > track_tiles
Definition project.h:99
std::vector< uint16_t > track_switch_tiles
Definition project.h:101
std::vector< uint16_t > reserved_sheets
Definition project.h:118
std::map< uint16_t, std::vector< uint16_t > > reserved_blocks
Definition project.h:120
std::vector< uint16_t > flagged_sheets
Definition project.h:119
Planning editor sidecar ([planning]).
Definition project.h:170
Lines of a .yaze file that this build does not model.
Definition project.h:196
std::vector< Section > sections
Definition project.h:208
std::vector< std::string > tags
Definition project.h:47
std::string CreateOrGetLabel(const std::string &type, const std::string &key, const std::string &defaultValue)
Definition project.cc:3629
std::string GetLabel(const std::string &type, const std::string &key)
Definition project.cc:3616
void EditLabel(const std::string &type, const std::string &key, const std::string &newValue)
Definition project.cc:3598
bool LoadLabels(const std::string &filename)
Definition project.cc:3513
void SelectableLabelWithNameEdit(bool selected, const std::string &type, const std::string &key, const std::string &defaultValue)
Definition project.cc:3604
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > labels_
Definition project.h:623
std::string expected_hash
Definition project.h:228
RomWritePolicy write_policy
Definition project.h:229
std::map< std::string, std::string > custom_keybindings
Definition project.h:88
std::vector< std::string > saved_layouts
Definition project.h:69
std::map< std::string, bool > editor_visibility
Definition project.h:90
std::vector< std::string > recent_files
Definition project.h:89
std::vector< std::string > favorite_models
Definition project.h:413
std::vector< std::string > model_chain
Definition project.h:414
Modern project structure with comprehensive settings consolidation.
Definition project.h:290
std::string rom_backup_folder
Definition project.h:309
std::unordered_map< int, std::vector< std::string > > custom_object_files
Definition project.h:358
absl::Status ResetToDefaults()
Definition project.cc:2564
std::string custom_objects_folder
Definition project.h:330
absl::Status RepairProject()
Definition project.cc:2639
std::string MakeStorageKey(absl::string_view suffix) const
Definition project.cc:1353
static std::string ResolveBundleRoot(const std::string &path)
Definition project.cc:597
absl::Status ValidateSavedSourceBindings(const std::string &content) const
Definition project.cc:820
struct yaze::project::YazeProject::MusicPersistence music_persistence
bool project_opened() const
Definition project.h:538
std::string sprite_catalog_file
Definition project.h:334
absl::StatusOr< std::string > SerializeToString() const
Definition project.cc:1602
std::string zscream_project_file
Definition project.h:430
absl::Status ExportForZScream(const std::string &target_path)
Definition project.cc:2531
ProjectMetadata metadata
Definition project.h:302
absl::Status SaveToYazeFormat(bool replace_existing=true)
Definition project.cc:2475
std::string native_save_transfer_proof_file
Definition project.h:351
absl::Status ImportZScreamProject(const std::string &zscream_project_path)
Definition project.cc:2508
absl::Status SaveAllSettings()
Definition project.cc:2559
absl::Status LoadFromString(const std::string &content, const std::string &project_path)
Definition project.cc:789
absl::Status ImportLabelsFromZScreamContent(const std::string &content)
Import labels from ZScream format content directly.
Definition project.cc:3737
std::string git_repository
Definition project.h:390
core::HackManifest hack_manifest
Definition project.h:376
void InitializeResourceLabelProvider()
Initialize the global ResourceLabelProvider with this project's labels.
Definition project.cc:3761
absl::Status ParseFromString(const std::string &content)
Definition project.cc:2003
std::string cutscene_shots
Definition project.h:321
std::vector< std::string > additional_roms
Definition project.h:310
std::string native_save_receipt_file
Definition project.h:352
std::string lyra_terrain_file
Definition project.h:342
std::string terrain_catalog_file
Definition project.h:339
std::string patches_folder
Definition project.h:316
absl::Status LoadFromYazeFormat(const std::string &project_path)
Definition project.cc:2454
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > resource_labels
Definition project.h:369
std::vector< std::string > AtlasAnnotationPaths() const
Definition project.cc:2772
std::string GenerateProjectId() const
Definition project.cc:3211
absl::Status Create(const std::string &project_name, const std::string &base_path)
Definition project.cc:544
std::string assets_folder
Definition project.h:315
GraphicsSheetSettings graphics_sheets
Definition project.h:364
std::string AtlasSymbolsPath() const
Definition project.cc:2781
absl::Status LoadAllSettings()
Definition project.cc:2553
std::string labels_filename
Definition project.h:317
std::vector< std::string > asm_sources
Definition project.h:387
std::string hack_manifest_file
Definition project.h:332
std::string GetDisplayName() const
Definition project.cc:2673
PlanningSettings planning
Definition project.h:366
std::string PlanningFilePath() const
Definition project.cc:2785
std::string native_save_producer_file
Definition project.h:350
std::vector< std::string > GetMissingFiles() const
Definition project.cc:2614
std::string lyra_build_request_file
Definition project.h:345
WorkspaceSettings workspace_settings
Definition project.h:362
std::string GetZ3dkArtifactPath(absl::string_view artifact_name) const
Definition project.cc:2815
std::string output_folder
Definition project.h:383
std::string asm_entry_point
Definition project.h:386
std::string GetRelativePath(const std::string &absolute_path) const
Definition project.cc:2680
std::vector< SpriteAssetBinding > sprite_assets
Definition project.h:336
absl::Status InitializeEmbeddedLabels(const std::unordered_map< std::string, std::unordered_map< std::string, std::string > > &labels)
Definition project.cc:3644
ProjectFilePassthrough file_passthrough
Definition project.h:442
absl::StatusOr< std::optional< std::string > > ResolveExpandedBuildRunTarget(const std::string &editing_source_path) const
Definition project.cc:905
absl::Status SaveAs(const std::string &new_path)
Definition project.cc:1211
absl::Status SaveNew()
Definition project.cc:785
bool IsOracleCompatible() const
Definition project.cc:1223
struct yaze::project::YazeProject::AgentSettings agent_settings
std::string custom_collision_json
Definition project.h:328
DungeonOverlaySettings dungeon_overlay
Definition project.h:363
absl::Status SaveAsWithLyraTerrain(const std::string &new_path, const core::LyraTerrainDocument &terrain, const std::optional< std::string > &expected_source_bytes)
Definition project.cc:1230
std::string palette_catalog_file
Definition project.h:355
absl::Status ImportFromZScreamFormat(const std::string &project_path)
Definition project.cc:2793
std::string GetAbsolutePath(const std::string &relative_path) const
Definition project.cc:2700
std::string overworld_graphics_preview
Definition project.h:323
std::string GetLabel(const std::string &resource_type, int id, const std::string &default_value="") const
Definition project.cc:3702
std::string sprite_source_root
Definition project.h:335
absl::Status Open(const std::string &project_path)
Definition project.cc:623
absl::Status ImportLabelsFromZScream(const std::string &filepath)
Import labels from a ZScream DefaultNames.txt file.
Definition project.cc:3717
std::string last_build_hash
Definition project.h:392
std::map< std::string, std::string > zscream_mappings
Definition project.h:431
std::string dungeon_tile_patterns
Definition project.h:325
absl::Status Validate() const
Definition project.cc:2569
core::FeatureFlags::Flags feature_flags
Definition project.h:361
std::vector< std::string > build_configurations
Definition project.h:384
core::RomAddressOverrides rom_address_overrides
Definition project.h:367
std::string symbols_filename
Definition project.h:318
Z3dkSettings z3dk_settings
Definition project.h:379
std::vector< std::string > include_paths
Definition project.h:250
std::string std_includes_path
Definition project.h:254
std::vector< std::string > main_files
Definition project.h:253
std::vector< std::string > emits
Definition project.h:252
std::vector< std::pair< std::string, std::string > > defines
Definition project.h:251
Z3dkArtifactPaths artifact_paths
Definition project.h:271
std::optional< bool > lsp_log_enabled
Definition project.h:261
std::vector< Z3dkMemoryRange > prohibited_memory_ranges
Definition project.h:260
std::string std_defines_path
Definition project.h:255