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"
29#include "imgui/imgui.h"
35#include "yaze_config.h"
38#if defined(YAZE_WITH_Z3DK) && __has_include("z3dk_core/config.h")
39#include "z3dk_core/config.h"
64 value.begin(), value.end(), value.begin(),
65 [](
unsigned char c) { return static_cast<char>(std::tolower(c)); });
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)
75 std::string key = line.substr(0, eq_pos);
76 std::string value = line.substr(eq_pos + 1);
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);
88 const std::string& section,
89 const std::string& key,
int* output) {
91 if (!absl::SimpleAtoi(value, &parsed)) {
92 return absl::InvalidArgumentError(absl::StrFormat(
93 "Invalid integer value for [%s] %s: '%s'", section, key, value));
96 return absl::OkStatus();
100 return value ==
"true" || value ==
"1" || value ==
"yes";
105 return std::stof(value);
112 std::vector<std::string> result;
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);
129 std::vector<std::string> result;
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));
145 std::vector<uint16_t> result;
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);
157 result.push_back(
static_cast<uint16_t
>(std::stoul(token,
nullptr, 16)));
163 result.push_back(
static_cast<uint16_t
>(std::stoul(token,
nullptr, 10)));
176 std::string token = value;
177 if (token.rfind(
"0x", 0) == 0 || token.rfind(
"0X", 0) == 0) {
178 token = token.substr(2);
180 return static_cast<uint32_t
>(std::stoul(token,
nullptr, 16));
186 return static_cast<uint32_t
>(std::stoul(token,
nullptr, 10));
193 return absl::StrJoin(values,
",", [](std::string* out, uint16_t value) {
194 out->append(absl::StrFormat(
"0x%02X", value));
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);
210 auto is_decimal = [](
char c) {
211 return c >=
'0' && c <=
'9';
213 auto is_hex = [](
char c) {
214 return std::isxdigit(
static_cast<unsigned char>(c)) != 0;
216 for (
const char* type : {
"blockset",
"roomset",
"spriteset",
"paletteset"}) {
217 auto found = labels.find(type);
218 if (found == labels.end()) {
221 std::unordered_map<std::string, std::string> migrated;
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)) {
233 std::to_string(std::stoul(std::string(digits),
nullptr, 10));
234 }
else if (pass == 2 && !all_of(digits, is_decimal)) {
237 prefixed && all_of(digits, is_hex)
238 ? std::to_string(std::stoul(std::string(digits),
nullptr, 16))
241 if (!canonical.empty()) {
242 migrated.emplace(canonical, value);
246 found->second = std::move(migrated);
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) {
260 if (keys.size() != 1) {
263 result[keys.front()] =
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,
","));
278 return absl::StrFormat(
"0x%06X", value);
282 std::string key(input);
283 for (
char& c : key) {
284 if (!std::isalnum(
static_cast<unsigned char>(c))) {
295 auto [key, parsed_value] = ParseKeyValue(value);
299 return {key, parsed_value.empty() ?
"1" : parsed_value};
303 const std::string& value) {
307 std::filesystem::path path(value);
308 if (path.is_absolute()) {
309 return path.lexically_normal().string();
311 return (base_dir / path).lexically_normal().string();
315 return ToLowerCopy(std::filesystem::path(path).filename().
string());
320 return static_cast<uint64_t
>(::GetCurrentProcessId());
321#elif defined(__EMSCRIPTEN__)
324 return static_cast<uint64_t
>(::getpid());
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;
334 std::to_string(next_temp_id.fetch_add(1, std::memory_order_relaxed));
339 std::error_code remove_error;
340 std::filesystem::remove(temp_path, remove_error);
344 const std::filesystem::path& target_path, absl::string_view contents,
345 bool replace_existing) {
347 if (!replace_existing) {
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()));
356 return absl::InternalError(absl::StrFormat(
357 "Cannot create project file: %s", target_path.string()));
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) {
364 return absl::InternalError(absl::StrFormat(
365 "Failed to write project file: %s", target_path.string()));
367 return absl::OkStatus();
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()));
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));
384 if (!WriteFile(file, contents.data() + written_total, chunk, &written,
389 return absl::InternalError(absl::StrFormat(
390 "Failed to write temporary project file: %s", temp_path.string()));
392 written_total += written;
394 if (!FlushFileBuffers(file)) {
397 return absl::InternalError(absl::StrFormat(
398 "Failed to write temporary project file: %s", temp_path.string()));
400 if (!CloseHandle(file)) {
402 return absl::InternalError(absl::StrFormat(
403 "Failed to close temporary project file: %s", temp_path.string()));
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()));
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) {
418 return absl::InternalError(absl::StrFormat(
419 "Failed to write temporary project file: %s", temp_path.string()));
423 return absl::InternalError(absl::StrFormat(
424 "Failed to close temporary project file: %s", temp_path.string()));
428 std::error_code rename_error;
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());
437#elif defined(__EMSCRIPTEN__)
438 std::filesystem::rename(temp_path, target_path, rename_error);
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());
450 bool target_already_exists = rename_error == std::errc::file_exists;
452 target_already_exists = target_already_exists ||
453 rename_error.value() == ERROR_FILE_EXISTS ||
454 rename_error.value() == ERROR_ALREADY_EXISTS;
456 if (!replace_existing && target_already_exists) {
457 return absl::AlreadyExistsError(absl::StrFormat(
458 "Project file already exists: %s", target_path.string()));
460 return absl::InternalError(
461 absl::StrFormat(
"Failed to replace project file %s: %s",
462 target_path.string(), rename_error.message()));
465 return absl::OkStatus();
470 absl::string_view contents,
471 bool replace_existing) {
472 return WriteProjectFileAtomicallyImpl(
473 std::filesystem::path(std::string(target_path)), contents,
492 std::string lower = ToLowerCopy(std::string(value));
493 if (lower ==
"base") {
496 if (lower ==
"patched") {
499 if (lower ==
"release") {
520 std::string lower = ToLowerCopy(std::string(value));
521 if (lower ==
"allow") {
524 if (lower ==
"block") {
527 if (lower ==
"read_only") {
537 provider.SetHackManifest(
nullptr);
540 provider.SetProjectLabels(
nullptr);
545 const std::string& base_path) {
547 filepath = base_path +
"/" + project_name +
".yaze";
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");
564#ifndef __EMSCRIPTEN__
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");
605 auto current = std::filesystem::path(path).lexically_normal();
607 for (; !current.empty(); current = current.parent_path()) {
608 if (current.extension() ==
".yazeproj") {
610 if (std::filesystem::is_directory(current, ec) && !ec) {
611 return current.string();
615 if (current == current.parent_path()) {
627 std::string resolved_path = project_path;
629 if (!bundle_root.empty() && bundle_root != project_path) {
631 resolved_path = bundle_root;
634#ifndef __EMSCRIPTEN__
639 std::error_code absolute_ec;
640 const auto absolute_path =
641 std::filesystem::absolute(resolved_path, absolute_ec).lexically_normal();
643 resolved_path = absolute_path.string();
652 auto storage_or = platform::WasmStorage::LoadProject(storage_key);
653 if (storage_or.ok()) {
659 absl::Status load_status;
660 if (resolved_path.ends_with(
".yazeproj")) {
663 const std::filesystem::path bundle_path(resolved_path);
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));
673 const std::filesystem::path project_file = bundle_path /
"project.yaze";
676 if (!std::filesystem::exists(project_file, ec) || ec) {
679 name = bundle_path.stem().string();
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");
705 const std::filesystem::path rom_candidate = bundle_path /
"rom";
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) {
717 }
else if (std::filesystem::exists(code_dir, ec) &&
718 std::filesystem::is_directory(code_dir, ec) && !ec) {
733 }
else if (resolved_path.ends_with(
".yaze")) {
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();
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);
754 return absl::InvalidArgumentError(
755 absl::StrFormat(
"Cannot open project file: %s", resolved_path));
757 }
else if (resolved_path.ends_with(
".zsproj")) {
761 return absl::InvalidArgumentError(
"Unsupported project file format");
764 if (!load_status.ok()) {
778 return absl::OkStatus();
790 const std::string& project_path) {
791 if (project_path.empty()) {
792 return absl::InvalidArgumentError(
"Project file path cannot be empty");
797#ifndef __EMSCRIPTEN__
799 const auto absolute_path =
800 std::filesystem::absolute(project_path, ec).lexically_normal();
802 ec ? std::filesystem::path(project_path).lexically_normal().string()
803 : absolute_path.string();
810 }
catch (
const std::exception& error) {
811 return absl::InvalidArgumentError(
812 absl::StrFormat(
"Invalid project file value: %s", error.what()));
817 return absl::OkStatus();
821 const std::string& content)
const {
827 }
catch (
const std::exception& error) {
828 return absl::InvalidArgumentError(
829 std::string(
"Invalid saved project bindings: ") + error.what());
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() ==
'#')
841 if (trimmed.front() ==
'[' && trimmed.back() ==
']') {
842 section = std::string(trimmed.substr(1, trimmed.size() - 2));
846 if (section ==
"workspace" || section ==
"keybindings" ||
847 section ==
"editor_visibility" || section ==
"agent_settings")
849 const auto [key, value] = ParseKeyValue(std::string(trimmed));
850 if (key.empty() || (section ==
"project" &&
851 (key ==
"last_modified" || key ==
"created_date")))
853 values[{section, key}] = value;
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);
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);
869 for (
const auto& [key, value] : saved_bindings) {
870 if (live_bindings.find(key) == live_bindings.end())
871 return mismatch(key);
873 return absl::OkStatus();
877#if defined(YAZE_WITH_JSON) && !defined(__EMSCRIPTEN__)
878absl::Status ExpandedRunError(
const std::string& message) {
879 return absl::FailedPreconditionError(
"Expanded run target unavailable: " +
882absl::Status ExpandedRunRequire(
bool valid,
const std::string& message) {
883 return valid ? absl::OkStatus() : ExpandedRunError(message);
885std::string ExpandedRunPathText(
const std::filesystem::path& path) {
886 const auto text = path.generic_u8string();
887 return std::string(text.begin(), text.end());
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");
894 std::error_code error;
895 const auto canonical = std::filesystem::weakly_canonical(path, error);
897 return ExpandedRunError(
"cannot resolve evidence path: " + text);
899 return ExpandedRunPathText(canonical);
904absl::StatusOr<std::optional<std::string>>
906 const std::string& editing_source_path)
const {
908 return std::optional<std::string>{};
910#if !defined(YAZE_WITH_JSON) || defined(__EMSCRIPTEN__)
911 return absl::UnimplementedError(
912 "Expanded run target verification requires desktop JSON support");
914 namespace fs = std::filesystem;
918 editing_source_path.empty()) {
919 return ExpandedRunError(
"complete saved expanded references are required");
923 const auto resolve = [&](
const std::string& ref) {
936 const auto authority,
938 const fs::path target = fs::u8path(candidate);
939 const auto relative =
940 target.lexically_relative(fs::u8path(engine) /
"Roms");
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"));
949 uint64_t remaining = 8ULL * 1024 * 1024 * 1024;
950 std::vector<Json> observed;
951 const auto check_file = [&](
const Json& row) -> absl::Status {
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);
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 &&
963 "an evidence file is missing, changed, or exceeds its bounds"));
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"));
975 return ExpandedRunRequire(actual == expected,
976 "evidence changed: " +
name);
978 const auto check = [&](
const Json& row) -> absl::Status {
980 "too many evidence bindings"));
982 observed.push_back(row);
983 return absl::OkStatus();
985 const auto rows = [&](
const Json& values) -> absl::Status {
987 (values.is_array() || values.is_object()) && values.size() <= 4096,
988 "an evidence binding collection is malformed"));
989 for (
const auto& row : values)
991 return absl::OkStatus();
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()));
1006 stream.gcount() ==
static_cast<std::streamsize
>(raw.size()) &&
1007 !stream.get(extra) && !stream.bad(),
1008 "metadata changed while reading"));
1013 const auto load = [&](
const std::string&
name) -> absl::StatusOr<Json> {
1018 throw std::runtime_error(
"evidence nesting is too deep");
1022 "evidence JSON must be an object"));
1025 const auto same_path = [&](
const Json& value,
1026 const std::string& expected) -> absl::Status {
1028 ExpandedRunCanonical(value.
get<std::string>()));
1029 return ExpandedRunRequire(path == expected,
1030 "evidence belongs to another path");
1032 const auto sibling = [&](
const char*
name) {
1033 return ExpandedRunPathText(target.parent_path() /
name);
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"));
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"));
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>()));
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"}) {
1087 prepared.at(flag).is_boolean() && prepared.at(flag).get<
bool>(),
1088 "expanded build admission is incomplete"));
1091 ExpandedRunRequire(!prepared.contains(
"runtime_scope"),
1092 "a private preview is not an ordinary run target"));
1097 const Json* request_binding =
nullptr;
1098 for (
const auto& row : prepared.at(
"inputs")) {
1100 ExpandedRunCanonical(row.at(
"path").get<std::string>()));
1101 if (path == request_path)
1102 request_binding = &row;
1105 ExpandedRunRequire(request_binding !=
nullptr,
1106 "the preparation omits its request binding"));
1109 const auto& live = request.at(
"live");
1110 const auto& plan = prepared.at(
"terrain_plan");
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));
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));
1130 for (
const char* key : {
"producer",
"save_receipt",
"save_context"})
1132 for (
const char* key : {
"observation",
"save_snapshot",
"producer_snapshot",
1133 "context_snapshot"})
1135 const auto& producer = live.at(
"producer_identity");
1140 if (request.contains(
"native_verification"))
1142 if (plan.at(
"enforcement_owner") ==
"oracle.current_builder") {
1144 plan.at(
"enforcement_receipt") == request.at(
"native_verification"),
1145 "the builder enforcement binding differs"));
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));
1154 const auto receipt_path = descriptor +
".native-save.json";
1156 same_path(live.at(
"save_receipt").at(
"path"), receipt_path));
1158 ExpandedRunPathText(authority.path)));
1161 load(ExpandedRunPathText(authority.path)));
1163 receipt.at(
"kind") ==
"yaze.native_save.v1" &&
1164 receipt.at(
"bindings_complete") ==
true &&
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"));
1180 RETURN_IF_ERROR(same_path(context.at(
"native_commit").at(
"receipt_path"),
1183 authority.editing_source_path));
1186 const Json* saved_producer =
nullptr;
1187 for (
const auto& row : receipt.at(
"artifacts")) {
1188 if (row.at(
"role") ==
"producer")
1189 saved_producer = &row;
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"));
1197 ExpandedRunCanonical(
1198 producer.at(
"editor").at(
"path").get<std::string>()));
1202 for (
const auto& binding : observed)
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());
1212 std::string old_filepath =
filepath;
1215 auto status =
Save();
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");
1237 namespace fs = std::filesystem;
1239 return absl::FailedPreconditionError(
1240 "An open project and Lyra terrain are required for Save As");
1243 [](
const fs::path& path) -> absl::StatusOr<std::optional<std::string>> {
1245 if (!fs::exists(path, ec) && !ec) {
1246 return std::nullopt;
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");
1253 std::ifstream stream(path, std::ios::binary);
1255 return absl::PermissionDeniedError(
"Cannot read project Save As file");
1257 std::string bytes{std::istreambuf_iterator<char>(stream), {}};
1259 return absl::DataLossError(
1260 "Could not finish reading project Save As file");
1262 return std::optional<std::string>(std::move(bytes));
1265 auto candidate = *
this;
1267 candidate.NormalizePathsToAbsolute();
1269 const fs::path source_project = fs::absolute(candidate.filepath, ec);
1271 return absl::InvalidArgumentError(
"Cannot resolve the source project path");
1273 const fs::path source_terrain = candidate.lyra_terrain_file;
1274 const fs::path
destination = fs::absolute(new_path, ec).lexically_normal();
1276 return absl::InvalidArgumentError(
1277 "Cannot resolve the project Save As path");
1280 destination_terrain.replace_extension(
".lyra-terrain.json");
1282 candidate.lyra_terrain_file = destination_terrain.string();
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);
1289 if (!candidate.lyra_build_request_file.empty()) {
1290 read_only_targets.push_back(candidate.lyra_build_request_file);
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);
1302 targets, {
"Lyra project",
"Lyra project files"}, read_only_targets));
1304 if (!original_project) {
1305 return absl::NotFoundError(
"The original project file is missing");
1308 if (original_terrain != expected_source_bytes) {
1309 return absl::FailedPreconditionError(
1310 "Lyra terrain changed on disk; refusing stale Save As");
1314 if (previous_terrain) {
1315 return absl::AlreadyExistsError(
1316 "The destination project already owns Lyra terrain; choose another "
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");
1328 const std::string terrain_bytes = terrain.
Serialize();
1331 {{source_project, original_project, *original_project},
1333 {destination_terrain, std::nullopt, terrain_bytes}},
1335 [&]() -> absl::Status {
1337 if (source_after != expected_source_bytes) {
1338 return absl::FailedPreconditionError(
1339 "Lyra terrain changed during Save As");
1343 return absl::DataLossError(
"Saved Lyra terrain is missing");
1348 *
this = std::move(candidate);
1349 return absl::OkStatus();
1357 }
else if (!
name.empty()) {
1360 base = std::filesystem::path(
filepath).stem().string();
1362 base = SanitizeStorageKey(base);
1363 if (suffix.empty()) {
1366 return absl::StrFormat(
"%s_%s", base, suffix);
1374 for (
size_t i = 0; i < content.size(); ++i) {
1375 if (content[i] ==
'\r' &&
1376 (i + 1 >= content.size() || content[i + 1] !=
'\n')) {
1387 static constexpr absl::string_view kKnown[] = {
"project",
1402 "editor_visibility",
1403 "zscream_compatibility",
1405 if (absl::StartsWith(name,
"labels_")) {
1408 return std::find(std::begin(kKnown), std::end(kKnown), name) !=
1418 if (!before_sections) {
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:");
1429 for (
auto& section : passthrough.
sections) {
1430 if (section.name == name) {
1434 passthrough.
sections.push_back({name,
false, {}});
1435 return passthrough.
sections.back();
1439 return !line.empty() && line.front() !=
'#' &&
1440 line.find(
'=') != absl::string_view::npos;
1447 if (passthrough.
empty()) {
1452 struct CanonicalSection {
1455 std::vector<std::string> lines;
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')) {
1465 if (line.size() >= 2 && line.front() ==
'[' && line.back() ==
']') {
1466 canonical_sections.push_back(
1468 std::string(line.substr(1, line.size() - 2)),
1475 (canonical_sections.empty() ? preamble : canonical_sections.back().lines)
1476 .push_back(std::string(line));
1481 for (
const auto& section : passthrough.
sections) {
1482 if (section.name == name) {
1489 std::ostringstream out;
1492 for (
const auto& line : section.lines) {
1493 if (line.kind != Kind::kKnownKey) {
1494 out << line.text <<
"\n";
1499 for (
const auto& line : preamble) {
1500 out << line <<
"\n";
1503 if (
const auto* before = find_section(
""); before !=
nullptr) {
1505 if (!before->lines.empty()) {
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";
1521 merged.push_back(kept);
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)});
1533 }
else if (!pending.empty()) {
1534 anchored.push_back({line.key, std::move(pending)});
1538 std::vector<bool> anchor_written(anchored.size(),
false);
1539 for (
const auto& line : section.lines) {
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";
1547 anchor_written[i] =
true;
1551 out << line <<
"\n";
1553 for (
const auto& [text, comments] : unknown) {
1554 for (
const auto& comment : comments) {
1555 out << comment <<
"\n";
1557 out << text <<
"\n";
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";
1567 for (
const auto& comment : pending) {
1568 out << comment <<
"\n";
1575 for (
const auto& section : passthrough.
sections) {
1576 if (section.name.empty() ||
1577 std::find(merged.begin(), merged.end(), §ion) != merged.end()) {
1580 const bool has_content = std::any_of(
1581 section.lines.begin(), section.lines.end(),
1582 [](
const auto& line) { return line.kind != Kind::kKnownKey; });
1586 out <<
"[" << section.name <<
"]\n";
1599 return IsKnownProjectSection(name);
1603 std::ostringstream file;
1606 file <<
"# yaze Project File\n";
1607 file <<
"# Format Version: 2.0\n";
1612 file <<
"[project]\n";
1613 file <<
"name=" <<
name <<
"\n";
1623 file <<
"tags=" << absl::StrJoin(
metadata.
tags,
",") <<
"\n\n";
1626 file <<
"[files]\n";
1635 file <<
"overworld_graphics_preview="
1639 file <<
"dungeon_tile_patterns="
1643 file <<
"cutscene_shots="
1647 file <<
"custom_collision_json="
1653 file <<
"palette_catalog_file="
1655 file <<
"terrain_catalog_file="
1657 file <<
"lyra_terrain_file="
1659 file <<
"lyra_build_request_file="
1662 file <<
"native_save_producer_file="
1666 file <<
"native_save_transfer_proof_file="
1671 file <<
"native_save_receipt_file="
1675 file <<
"sprite_catalog_file="
1677 file <<
"sprite_source_root="
1679 file <<
"additional_roms=" << absl::StrJoin(
additional_roms,
",") <<
"\n\n";
1681 file <<
"[sprite_assets]\n";
1685 for (
auto& source : asset.graphics_sources) {
1686 if (source.kind ==
"bin") {
1702 file <<
"[feature_flags]\n";
1703 file <<
"load_custom_overworld="
1706 file <<
"apply_zs_custom_overworld_asm="
1710 file <<
"enable_special_world_expansion="
1714 file <<
"save_with_change_queue="
1716 file <<
"save_dungeon_maps="
1718 file <<
"save_overworld_maps="
1721 file <<
"save_overworld_entrances="
1724 file <<
"save_overworld_exits="
1727 file <<
"save_overworld_items="
1730 file <<
"save_overworld_sprites="
1733 file <<
"save_overworld_properties="
1736 file <<
"save_dungeon_objects="
1738 file <<
"save_dungeon_sprites="
1740 file <<
"save_dungeon_room_headers="
1742 file <<
"save_dungeon_torches="
1744 file <<
"save_dungeon_pits="
1746 file <<
"save_dungeon_blocks="
1748 file <<
"save_dungeon_collision="
1750 file <<
"save_dungeon_water_fill_zones="
1753 file <<
"save_dungeon_chests="
1755 file <<
"save_dungeon_pot_items="
1757 file <<
"save_dungeon_entrances="
1759 file <<
"save_dungeon_palettes="
1761 file <<
"save_graphics_sheet="
1763 file <<
"save_all_palettes="
1765 file <<
"save_gfx_groups="
1769 file <<
"enable_custom_objects="
1773 file <<
"[workspace]\n";
1778 file <<
"autosave_enabled="
1782 file <<
"backup_on_save="
1786 file <<
"backup_keep_daily="
1792 file <<
"show_collision="
1794 file <<
"prefer_hmagic_names="
1798 file <<
"saved_layouts="
1805 if (track_tiles.empty()) {
1806 for (uint16_t tile = 0xB0; tile <= 0xBE; ++tile) {
1807 track_tiles.push_back(tile);
1811 if (track_stop_tiles.empty()) {
1812 track_stop_tiles = {0xB7, 0xB8, 0xB9, 0xBA};
1815 if (track_switch_tiles.empty()) {
1816 track_switch_tiles = {0xD0, 0xD1, 0xD2, 0xD3};
1819 if (track_object_ids.empty()) {
1820 track_object_ids = {0x31};
1823 if (minecart_sprite_ids.empty()) {
1824 minecart_sprite_ids = {0xA3};
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)
1831 file <<
"track_object_ids=" << FormatHexUintList(track_object_ids) <<
"\n";
1832 file <<
"minecart_sprite_ids=" << FormatHexUintList(minecart_sprite_ids)
1836 file <<
"[graphics_sheets]\n";
1837 file <<
"reserved_sheets="
1839 file <<
"flagged_sheets="
1841 file <<
"reserved_blocks="
1846 file <<
"[atlas]\n";
1854 file <<
"[planning]\n";
1859 file <<
"[rom_addresses]\n";
1861 file << key <<
"=" << FormatHexUint32(value) <<
"\n";
1867 file <<
"[custom_objects]\n";
1869 file << absl::StrFormat(
"object_0x%X", object_id) <<
"="
1870 << absl::StrJoin(files,
",") <<
"\n";
1876 file <<
"[agent_settings]\n";
1881 file <<
"custom_system_prompt="
1884 file <<
"use_custom_prompt="
1886 file <<
"show_reasoning="
1894 file <<
"stream_responses="
1896 file <<
"favorite_models="
1901 file <<
"enable_tool_resources="
1903 file <<
"enable_tool_dungeon="
1905 file <<
"enable_tool_overworld="
1907 file <<
"enable_tool_messages="
1909 file <<
"enable_tool_dialogue="
1911 file <<
"enable_tool_gui="
1913 file <<
"enable_tool_music="
1915 file <<
"enable_tool_sprite="
1917 file <<
"enable_tool_emulator="
1919 file <<
"enable_tool_memory_inspector="
1927 file <<
"[keybindings]\n";
1929 file << key <<
"=" << value <<
"\n";
1936 file <<
"[editor_visibility]\n";
1938 file << key <<
"=" << (value ?
"true" :
"false") <<
"\n";
1945 if (!labels.empty()) {
1946 file <<
"[labels_" << type <<
"]\n";
1947 for (
const auto& [key, value] : labels) {
1948 file << key <<
"=" << value <<
"\n";
1955 file <<
"[build]\n";
1959 file <<
"track_changes=" << (
track_changes ?
"true" :
"false") <<
"\n";
1964 file <<
"asm_sources=" << absl::StrJoin(
asm_sources,
",") <<
"\n";
1969 file <<
"[music]\n";
1970 file <<
"persist_custom_music="
1977 file <<
"[zscream_compatibility]\n";
1980 file << key <<
"=" << value <<
"\n";
1985 file <<
"# End of YAZE Project File\n";
1993 std::string serialized =
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");
2004 if (ContainsLoneCarriageReturn(content)) {
2005 return absl::InvalidArgumentError(
2006 "Project file contains unsupported lone carriage returns");
2027 std::istringstream stream(content);
2029 std::string current_section;
2033 while (std::getline(stream, line)) {
2037 if (!line.empty() && line.back() ==
'\r') {
2041 if (line.find_first_not_of(
" \t") == std::string::npos)
2044 if (line[0] ==
'#') {
2045 if (!IsGeneratedProjectComment(line, current_section.empty())) {
2046 passthrough_section->
lines.push_back(
2052 if (line.front() ==
'[' && line.back() ==
']') {
2053 current_section = line.substr(1, line.length() - 2);
2054 passthrough_section =
2056 passthrough_section->
known = IsKnownProjectSection(current_section);
2057 if (current_section ==
"atlas") {
2059 }
else if (current_section ==
"planning") {
2065 auto [key, value] = ParseKeyValue(line);
2068 bool understood = !key.empty();
2071 }
else if (current_section ==
"project") {
2074 else if (key ==
"description")
2076 else if (key ==
"author")
2078 else if (key ==
"license")
2080 else if (key ==
"version")
2082 else if (key ==
"created_date")
2084 else if (key ==
"last_modified")
2086 else if (key ==
"yaze_version")
2088 else if (key ==
"created_by")
2090 else if (key ==
"tags")
2092 else if (key ==
"project_id")
2096 }
else if (current_section ==
"files") {
2097 if (key ==
"rom_filename")
2099 else if (key ==
"rom_backup_folder")
2101 else if (key ==
"code_folder")
2103 else if (key ==
"assets_folder")
2105 else if (key ==
"patches_folder")
2107 else if (key ==
"labels_filename")
2109 else if (key ==
"symbols_filename")
2111 else if (key ==
"overworld_graphics_preview")
2113 else if (key ==
"dungeon_tile_patterns")
2115 else if (key ==
"cutscene_shots")
2117 else if (key ==
"custom_collision_json")
2119 else if (key ==
"output_folder")
2121 else if (key ==
"custom_objects_folder")
2123 else if (key ==
"palette_catalog_file")
2125 else if (key ==
"terrain_catalog_file")
2127 else if (key ==
"lyra_terrain_file")
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")
2139 else if (key ==
"sprite_catalog_file")
2141 else if (key ==
"sprite_source_root")
2143 else if (key ==
"additional_roms")
2147 }
else if (current_section ==
"sprite_assets") {
2148 if (key.rfind(
"asset_", 0) != 0 || value.size() > 65536 ||
2150 return absl::InvalidArgumentError(
"Invalid sprite_assets section");
2153 return asset.status();
2155 if (prior.zsm_path == asset->zsm_path)
2156 return absl::InvalidArgumentError(
"Duplicate sprite asset path");
2158 }
else if (current_section ==
"rom") {
2161 else if (key ==
"expected_hash")
2163 else if (key ==
"write_policy")
2167 }
else if (current_section ==
"feature_flags") {
2168 if (key ==
"load_custom_overworld")
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")
2176 else if (key ==
"save_dungeon_maps")
2178 else if (key ==
"save_overworld_maps")
2180 else if (key ==
"save_overworld_entrances")
2182 else if (key ==
"save_overworld_exits")
2184 else if (key ==
"save_overworld_items")
2186 else if (key ==
"save_overworld_sprites")
2188 else if (key ==
"save_overworld_properties")
2190 else if (key ==
"save_dungeon_objects")
2192 else if (key ==
"save_dungeon_sprites")
2194 else if (key ==
"save_dungeon_room_headers")
2196 else if (key ==
"save_dungeon_torches")
2198 else if (key ==
"save_dungeon_pits")
2200 else if (key ==
"save_dungeon_blocks")
2202 else if (key ==
"save_dungeon_collision")
2204 else if (key ==
"save_dungeon_water_fill_zones")
2206 else if (key ==
"save_dungeon_chests")
2208 else if (key ==
"save_dungeon_pot_items")
2210 else if (key ==
"save_dungeon_entrances")
2212 else if (key ==
"save_dungeon_palettes")
2214 else if (key ==
"save_graphics_sheet")
2216 else if (key ==
"save_all_palettes")
2218 else if (key ==
"save_gfx_groups")
2220 else if (key ==
"save_messages")
2222 else if (key ==
"enable_custom_objects")
2226 }
else if (current_section ==
"workspace") {
2227 if (key ==
"font_global_scale")
2229 else if (key ==
"dark_mode")
2231 else if (key ==
"ui_theme")
2233 else if (key ==
"autosave_enabled")
2235 else if (key ==
"autosave_interval_secs")
2237 else if (key ==
"backup_on_save")
2239 else if (key ==
"backup_retention_count") {
2241 ParseProjectInteger(value, current_section, key,
2243 }
else if (key ==
"backup_keep_daily")
2245 else if (key ==
"backup_keep_daily_days") {
2247 ParseProjectInteger(value, current_section, key,
2249 }
else if (key ==
"show_grid")
2251 else if (key ==
"show_collision")
2253 else if (key ==
"prefer_hmagic_names")
2255 else if (key ==
"last_layout_preset")
2257 else if (key ==
"saved_layouts")
2259 else if (key ==
"recent_files")
2263 }
else if (current_section ==
"dungeon_overlay") {
2264 if (key ==
"track_tiles")
2266 else if (key ==
"track_stop_tiles")
2268 else if (key ==
"track_switch_tiles")
2270 else if (key ==
"track_object_ids")
2272 else if (key ==
"minecart_sprite_ids")
2276 }
else if (current_section ==
"graphics_sheets") {
2277 if (key ==
"reserved_sheets")
2279 else if (key ==
"flagged_sheets")
2281 else if (key ==
"reserved_blocks")
2285 }
else if (current_section ==
"atlas") {
2286 if (key ==
"annotations")
2288 else if (key ==
"defaults")
2290 else if (key ==
"symbols")
2292 else if (key ==
"export_folder")
2296 }
else if (current_section ==
"planning") {
2301 }
else if (current_section ==
"rom_addresses") {
2302 auto parsed = ParseHexUint32(value);
2303 if (parsed.has_value()) {
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);
2313 auto parsed = ParseHexUint32(id_token);
2314 if (parsed.has_value()) {
2316 ParsePositionalStringList(value);
2320 }
else if (current_section ==
"agent_settings") {
2321 if (key ==
"ai_provider")
2323 else if (key ==
"ai_model")
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")
2333 else if (key ==
"show_reasoning")
2335 else if (key ==
"verbose")
2337 else if (key ==
"max_tool_iterations") {
2340 }
else if (key ==
"max_retry_attempts") {
2343 }
else if (key ==
"temperature")
2345 else if (key ==
"top_p")
2347 else if (key ==
"max_output_tokens") {
2350 }
else if (key ==
"stream_responses")
2352 else if (key ==
"favorite_models")
2354 else if (key ==
"model_chain")
2356 else if (key ==
"chain_mode") {
2359 }
else if (key ==
"enable_tool_resources")
2361 else if (key ==
"enable_tool_dungeon")
2363 else if (key ==
"enable_tool_overworld")
2365 else if (key ==
"enable_tool_messages")
2367 else if (key ==
"enable_tool_dialogue")
2369 else if (key ==
"enable_tool_gui")
2371 else if (key ==
"enable_tool_music")
2373 else if (key ==
"enable_tool_sprite")
2375 else if (key ==
"enable_tool_emulator")
2377 else if (key ==
"enable_tool_memory_inspector")
2379 else if (key ==
"builder_blueprint_path")
2383 }
else if (current_section ==
"build") {
2384 if (key ==
"build_script")
2386 else if (key ==
"output_folder")
2388 else if (key ==
"git_repository")
2390 else if (key ==
"track_changes")
2392 else if (key ==
"build_configurations")
2394 else if (key ==
"build_target")
2396 else if (key ==
"asm_entry_point")
2398 else if (key ==
"asm_sources")
2400 else if (key ==
"last_build_hash")
2402 else if (key ==
"build_number") {
2404 ParseProjectInteger(value, current_section, key, &
build_number));
2407 }
else if (current_section.rfind(
"labels_", 0) == 0) {
2408 std::string label_type = current_section.substr(7);
2410 }
else if (current_section ==
"keybindings") {
2412 }
else if (current_section ==
"editor_visibility") {
2414 }
else if (current_section ==
"zscream_compatibility") {
2415 if (key ==
"original_project_file")
2419 }
else if (current_section ==
"music") {
2420 if (key ==
"persist_custom_music")
2422 else if (key ==
"storage_key")
2424 else if (key ==
"last_saved_at")
2431 passthrough_section->
lines.push_back(
2451 return absl::OkStatus();
2455#ifdef __EMSCRIPTEN__
2457 auto storage_or = platform::WasmStorage::LoadProject(storage_key);
2458 if (storage_or.ok()) {
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));
2469 std::stringstream buffer;
2470 buffer << file.rdbuf();
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");
2492#ifdef __EMSCRIPTEN__
2493 auto storage_status = platform::WasmStorage::SaveProject(
2495 if (!storage_status.ok()) {
2496 return storage_status;
2505 return absl::OkStatus();
2509 const std::string& zscream_project_path) {
2515 std::filesystem::path zs_path(zscream_project_path);
2516 name = zs_path.stem().string() +
"_imported";
2528 return absl::OkStatus();
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));
2540 file <<
"# ZScream Compatible Project File\n";
2542 file <<
"name=" <<
name <<
"\n";
2550 return absl::OkStatus();
2570 std::vector<std::string> errors;
2573 errors.push_back(
"Project name is required");
2575 errors.push_back(
"Project file path is required");
2577 errors.push_back(
"ROM file is required");
2579#ifndef __EMSCRIPTEN__
2583 errors.push_back(
"ROM file does not exist: " +
rom_filename);
2588 errors.push_back(
"Code folder does not exist: " +
code_folder);
2598 errors.push_back(
"Hack manifest file does not exist: " +
2601 errors.push_back(
"Hack manifest file failed to load: " +
2607 if (!errors.empty()) {
2608 return absl::InvalidArgumentError(absl::StrJoin(errors,
"; "));
2611 return absl::OkStatus();
2615 std::vector<std::string> missing;
2617#ifndef __EMSCRIPTEN__
2640#ifdef __EMSCRIPTEN__
2642 return absl::OkStatus();
2649 for (
const auto& folder : folders) {
2650 if (!folder.empty()) {
2652 if (!std::filesystem::exists(abs_path)) {
2653 std::filesystem::create_directories(abs_path);
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();
2669 return absl::OkStatus();
2677 return name.empty() ?
"Untitled Project" :
name;
2681 const std::string& absolute_path)
const {
2682 if (absolute_path.empty() ||
filepath.empty())
2683 return absolute_path;
2685 std::filesystem::path project_dir =
2686 std::filesystem::path(
filepath).parent_path();
2687 std::filesystem::path abs_path(absolute_path);
2690 std::filesystem::path relative =
2691 std::filesystem::relative(abs_path.lexically_normal(), project_dir);
2693 return relative.generic_string();
2696 return abs_path.lexically_normal().generic_string();
2701 const std::string& relative_path)
const {
2702 if (relative_path.empty() ||
filepath.empty())
2703 return relative_path;
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();
2713 abs_path = (project_dir / abs_path).lexically_normal();
2714 abs_path.make_preferred();
2716 return abs_path.string();
2720#ifdef __EMSCRIPTEN__
2728 auto normalize = [
this](std::string* path) {
2729 if (!path || path->empty()) {
2756 normalize(&asset.zsm_path);
2757 for (
auto& source : asset.graphics_sources) {
2758 if (source.kind ==
"bin") {
2759 normalize(&source.path);
2766 if (!rom_path.empty()) {
2773 std::vector<std::string> paths;
2794 const std::string& project_path) {
2798 std::filesystem::path zs_path(project_path);
2799 name = zs_path.stem().string() +
"_imported";
2804 return absl::OkStatus();
2816 absl::string_view artifact_name)
const {
2817 std::filesystem::path base_dir;
2825 base_dir = std::filesystem::path(
filepath).parent_path();
2828 if (base_dir.empty()) {
2829 return std::string(artifact_name);
2831 return (base_dir / std::string(artifact_name)).lexically_normal().string();
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()) {
2843 auto normalized = candidate.lexically_normal();
2844 if (std::find(candidates.begin(), candidates.end(), normalized) ==
2846 candidates.push_back(normalized);
2852 if (!std::filesystem::is_directory(code_path)) {
2853 code_path = code_path.parent_path();
2855 add_candidate(code_path /
"z3dk.toml");
2864 add_candidate(std::filesystem::path(
filepath).parent_path() /
"z3dk.toml");
2867 for (
const auto& candidate : candidates) {
2868 if (!std::filesystem::exists(candidate)) {
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());
2880 const std::filesystem::path base_dir = candidate.parent_path();
2883 if (config.preset.has_value()) {
2888 for (
const auto& include_path : config.include_paths) {
2890 ResolveOptionalPath(base_dir, include_path));
2894 for (
const auto& define : config.defines) {
2899 for (
const auto& main_file : config.main_files) {
2901 ResolveOptionalPath(base_dir, main_file));
2904 if (config.std_includes_path.has_value()) {
2906 ResolveOptionalPath(base_dir, *config.std_includes_path);
2908 if (config.std_defines_path.has_value()) {
2910 ResolveOptionalPath(base_dir, *config.std_defines_path);
2912 if (config.mapper.has_value()) {
2915 if (config.rom_size.has_value()) {
2918 if (config.symbols_format.has_value()) {
2922 if (config.lsp_log_path.has_value()) {
2924 ResolveOptionalPath(base_dir, *config.lsp_log_path);
2928 for (
const auto& emit_path : config.emits) {
2932 for (
const auto& range : config.prohibited_memory_ranges) {
2934 {.start = range.start, .end = range.end, .reason = range.reason});
2938 config.warn_unused_symbols.value_or(
true);
2940 config.warn_branch_outside_bank.value_or(
true);
2944 config.warn_unauthorized_hook.value_or(
true);
2948 if (config.rom_path.has_value()) {
2951 if (config.symbols_path.has_value()) {
2953 ResolveOptionalPath(base_dir, *config.symbols_path);
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") {
2998 "Loaded z3dk config from %s (%zu include paths, %zu defines)",
3007#ifdef __EMSCRIPTEN__
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)) {
3025 LOG_WARN(
"Project",
"Failed to load hack manifest %s: %s",
3026 candidate.string().c_str(),
3027 std::string(status.message()).c_str());
3030 loaded_manifest_path = candidate;
3031 if (update_project_setting) {
3034 LOG_DEBUG(
"Project",
"Loaded hack manifest: %s",
3035 candidate.string().c_str());
3044 if (has_explicit_manifest) {
3052 auto candidate = std::filesystem::path(code_path) /
"hack_manifest.json";
3053 (void)load_manifest(candidate,
true);
3058 const std::filesystem::path project_dir =
3059 std::filesystem::path(
filepath).parent_path();
3060 (void)load_manifest(project_dir /
"hack_manifest.json",
true);
3062 (void)load_manifest(project_dir.parent_path() /
"hack_manifest.json",
3071 auto try_load_registry = [&](
const std::filesystem::path& base) ->
bool {
3075 const auto planning = base /
"Docs" /
"Dev" /
"Planning";
3076 if (!std::filesystem::exists(
planning)) {
3081 LOG_WARN(
"Project",
"Failed to load project registry from %s: %s",
3082 base.string().c_str(), std::string(status.message()).c_str());
3088 bool registry_loaded =
false;
3097 if (!registry_loaded && !loaded_manifest_path.empty()) {
3098 registry_loaded = try_load_registry(loaded_manifest_path.parent_path());
3102 if (!registry_loaded && !
filepath.empty()) {
3104 try_load_registry(std::filesystem::path(
filepath).parent_path());
3107 if (!registry_loaded) {
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());
3119 size_t injected = 0;
3120 for (
const auto& [type_key, labels] :
3122 for (
const auto& [id_str, label] : labels) {
3127 LOG_DEBUG(
"Project",
"Loaded project registry: %zu resource labels injected",
3180 for (uint16_t tile = 0xB0; tile <= 0xBE; ++tile) {
3212 auto now = std::chrono::system_clock::now().time_since_epoch();
3214 std::chrono::duration_cast<std::chrono::milliseconds>(now).count();
3215 return absl::StrFormat(
"yaze_project_%lld", timestamp);
3219std::vector<ProjectManager::ProjectTemplate>
3221 std::vector<ProjectTemplate> templates;
3230 t.
name =
"Vanilla ROM Hack";
3232 "Standard ROM editing without custom ASM. Limited to vanilla features.";
3241 templates.push_back(t);
3247 t.
name =
"ZSCustomOverworld v2";
3249 "Basic overworld expansion: custom BG colors, main palettes, parent "
3262 templates.push_back(t);
3268 t.
name =
"ZSCustomOverworld v3 (Recommended)";
3270 "Full overworld expansion: wide/tall areas, animated GFX, overlays, "
3287 templates.push_back(t);
3293 t.
name =
"Randomizer Compatible";
3295 "Compatible with ALttP Randomizer. Minimal custom features to avoid "
3305 templates.push_back(t);
3315 t.
name =
"Dungeon Designer";
3316 t.
description =
"Focused on dungeon creation and modification.";
3323 templates.push_back(t);
3329 t.
name =
"Graphics Pack";
3331 "Project focused on graphics, sprites, and visual modifications.";
3340 templates.push_back(t);
3346 t.
name =
"Complete Overhaul";
3347 t.
description =
"Full-scale ROM hack with all features enabled.";
3362 templates.push_back(t);
3369 const std::string& template_name,
const std::string& project_name,
3370 const std::string& base_path) {
3372 auto status = project.
Create(project_name, base_path);
3378 if (template_name ==
"Full Overworld Mod") {
3382 project.
metadata.
tags = {
"overworld",
"maps",
"graphics"};
3383 }
else if (template_name ==
"Dungeon Designer") {
3387 project.
metadata.
tags = {
"dungeons",
"rooms",
"design"};
3388 }
else if (template_name ==
"Graphics Pack") {
3392 project.
metadata.
tags = {
"graphics",
"sprites",
"palettes"};
3393 }
else if (template_name ==
"Complete Overhaul") {
3399 project.
metadata.
tags = {
"complete",
"overhaul",
"full-mod"};
3402 status = project.
Save();
3411 const std::string& directory) {
3412#ifdef __EMSCRIPTEN__
3416 std::vector<std::string> projects;
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());
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());
3432 }
catch (
const std::filesystem::filesystem_error& e) {
3441#ifdef __EMSCRIPTEN__
3443 return absl::UnimplementedError(
3444 "Project backups are not supported in the web build");
3447 return absl::InvalidArgumentError(
"Project has no file path");
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);
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");
3459 std::string backup_filename = project.
name +
"_backup_" + ss.str() +
".yaze";
3460 std::filesystem::path backup_path = backup_dir / backup_filename;
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()));
3469 return absl::OkStatus();
3480 std::vector<std::string> recommendations;
3483 recommendations.push_back(
"Add a ROM file to begin editing");
3487 recommendations.push_back(
"Set up a code folder for assembly patches");
3491 recommendations.push_back(
"Create a labels file for better organization");
3495 recommendations.push_back(
"Add a project description for documentation");
3499 recommendations.push_back(
3500 "Consider setting up version control for your project");
3504 if (!missing_files.empty()) {
3505 recommendations.push_back(
3506 "Some project files are missing - use Project > Repair to fix");
3509 return recommendations;
3515 std::ifstream file(filename);
3516 if (!file.is_open()) {
3523 std::string current_type =
"";
3525 while (std::getline(file, line)) {
3526 if (line.empty() || line[0] ==
'#')
3530 if (line[0] ==
'[' && line.back() ==
']') {
3531 current_type = line.substr(1, line.length() - 2);
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;
3545 MigrateGfxGroupLabelKeys(
labels_);
3555 if (!file.is_open())
3558 file <<
"# yaze Resource Labels\n";
3559 file <<
"# Format: [type] followed by key=value pairs\n\n";
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";
3576 if (!p_open || !*p_open)
3580 if (ImGui::Begin(
"Resource Labels", p_open)) {
3581 ImGui::Text(
"Resource Labels Manager");
3583 ImGui::Text(
"Total types: %zu",
labels_.size());
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());
3599 const std::string& key,
3600 const std::string& newValue) {
3601 labels_[type][key] = newValue;
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(),
3617 const std::string& key) {
3618 auto type_it =
labels_.find(type);
3622 auto label_it = type_it->second.find(key);
3623 if (label_it == type_it->second.end())
3626 return label_it->second;
3630 const std::string& type,
const std::string& key,
3631 const std::string& defaultValue) {
3632 auto existing =
GetLabel(type, key);
3633 if (!existing.empty())
3636 labels_[type][key] = defaultValue;
3637 return defaultValue;
3645 const std::unordered_map<
3646 std::string, std::unordered_map<std::string, std::string>>& labels) {
3675 LOG_DEBUG(
"Project",
"Initialized embedded labels:");
3677 LOG_DEBUG(
"Project",
" - %d entrance names",
3679 LOG_DEBUG(
"Project",
" - %d sprite names",
3681 LOG_DEBUG(
"Project",
" - %d overlord names",
3684 LOG_DEBUG(
"Project",
" - %d music names",
3686 LOG_DEBUG(
"Project",
" - %d graphics names",
3688 LOG_DEBUG(
"Project",
" - %d room effect names",
3690 LOG_DEBUG(
"Project",
" - %d room tag names",
3692 LOG_DEBUG(
"Project",
" - %d tile type names",
3695 return absl::OkStatus();
3696 }
catch (
const std::exception& e) {
3697 return absl::InternalError(
3698 absl::StrCat(
"Failed to initialize embedded labels: ", e.what()));
3703 const std::string& default_value)
const {
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;
3713 return default_value.empty() ? resource_type +
"_" + std::to_string(
id)
3718#ifdef __EMSCRIPTEN__
3720 return absl::UnimplementedError(
3721 "File-based label import is not supported in the web build");
3724 if (!file.is_open()) {
3725 return absl::InvalidArgumentError(
3726 absl::StrFormat(
"Cannot open labels file: %s",
filepath));
3729 std::stringstream buffer;
3730 buffer << file.rdbuf();
3738 const std::string& content) {
3745 auto status = provider.ImportFromZScreamFormat(content);
3750 LOG_DEBUG(
"Project",
"Imported ZScream labels:");
3751 LOG_DEBUG(
"Project",
" - %d sprite labels",
3755 LOG_DEBUG(
"Project",
" - %d room tag labels",
3758 return absl::OkStatus();
3767 LOG_DEBUG(
"Project",
"Initialized ResourceLabelProvider with project labels");
3768 LOG_DEBUG(
"Project",
" - prefer_hmagic_names: %s",
3770 LOG_DEBUG(
"Project",
" - hack_manifest: %s",
3778#ifdef YAZE_ENABLE_JSON_PROJECT_FORMAT
3780absl::Status YazeProject::LoadFromJsonFormat(
const std::string& project_path) {
3793#ifdef __EMSCRIPTEN__
3794 return absl::UnimplementedError(
3795 "JSON project format loading is not supported in the web build");
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));
3813 auto& proj = j[
"yaze_project"];
3815 if (proj.contains(
"name"))
3816 name = proj[
"name"].
get<std::string>();
3817 if (proj.contains(
"description"))
3819 if (proj.contains(
"author"))
3821 if (proj.contains(
"version"))
3823 if (proj.contains(
"created"))
3825 if (proj.contains(
"modified"))
3827 if (proj.contains(
"created_by"))
3831 if (proj.contains(
"rom_filename"))
3832 rom_filename = proj[
"rom_filename"].get<std::string>();
3833 if (proj.contains(
"rom_backup_folder"))
3835 if (proj.contains(
"code_folder"))
3836 code_folder = proj[
"code_folder"].get<std::string>();
3837 if (proj.contains(
"assets_folder"))
3839 if (proj.contains(
"patches_folder"))
3841 if (proj.contains(
"labels_filename"))
3843 if (proj.contains(
"symbols_filename"))
3845 if (proj.contains(
"dungeon_tile_patterns"))
3847 proj[
"dungeon_tile_patterns"].get<std::string>();
3848 if (proj.contains(
"palette_catalog_file"))
3850 if (proj.contains(
"terrain_catalog_file"))
3852 if (proj.contains(
"lyra_terrain_file"))
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"))
3868 if (proj.contains(
"sprite_catalog_file"))
3870 if (proj.contains(
"sprite_source_root"))
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"]) {
3879 return asset.status();
3881 if (prior.zsm_path == asset->zsm_path)
3882 return absl::InvalidArgumentError(
"Duplicate sprite asset path");
3887 if (proj.contains(
"rom") && proj[
"rom"].is_object()) {
3888 auto&
rom = proj[
"rom"];
3889 if (
rom.contains(
"role"))
3891 if (
rom.contains(
"expected_hash"))
3893 if (
rom.contains(
"write_policy"))
3899 if (proj.contains(
"use_embedded_labels")) {
3904 if (proj.contains(
"feature_flags")) {
3905 auto& flags = proj[
"feature_flags"];
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"))
3979 if (flags.contains(
"kSaveMessages"))
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"))
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>();
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()) {
4014 if (parsed.has_value()) {
4021 if (proj.contains(
"custom_objects") &&
4022 proj[
"custom_objects"].is_object()) {
4024 for (
auto it = proj[
"custom_objects"].begin();
4025 it != proj[
"custom_objects"].end(); ++it) {
4026 if (!it.value().is_array())
4029 if (!parsed.has_value()) {
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>());
4038 if (!files.empty()) {
4044 if (proj.contains(
"agent_settings") &&
4045 proj[
"agent_settings"].is_object()) {
4046 auto& agent = proj[
"agent_settings"];
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>());
4082 if (agent.contains(
"model_chain") && agent[
"model_chain"].is_array()) {
4084 for (
const auto& model : agent[
"model_chain"]) {
4085 if (model.is_string())
4110 agent.value(
"enable_tool_memory_inspector",
4117 if (proj.contains(
"build_script"))
4118 build_script = proj[
"build_script"].get<std::string>();
4119 if (proj.contains(
"output_folder"))
4121 if (proj.contains(
"git_repository"))
4123 if (proj.contains(
"track_changes"))
4127 return absl::OkStatus();
4128 }
catch (
const Json::exception& e) {
4129 return absl::InvalidArgumentError(
4130 absl::StrFormat(
"JSON parse error: %s", e.what()));
4134absl::Status YazeProject::SaveToJsonFormat() {
4135#ifdef __EMSCRIPTEN__
4136 return absl::UnimplementedError(
4137 "JSON project format saving is not supported in the web build");
4140 auto& proj = j[
"yaze_project"];
4144 proj[
"name"] =
name;
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"] =
4170 proj[
"native_save_producer_file"] =
4174 proj[
"native_save_transfer_proof_file"] =
4178 proj[
"native_save_receipt_file"] =
4182 proj[
"sprite_catalog_file"] =
4184 proj[
"sprite_source_root"] =
4186 proj[
"sprite_assets"] = nlohmann::json::array();
4189 for (
auto& source : asset.graphics_sources) {
4190 if (source.kind ==
"bin") {
4200 proj[
"rom"][
"write_policy"] =
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"] =
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"] =
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"] =
4268 auto& agent = proj[
"agent_settings"];
4295 agent[
"enable_tool_memory_inspector"] =
4300 auto& addrs = proj[
"rom_addresses"];
4307 auto& objs = proj[
"custom_objects"];
4309 objs[absl::StrFormat(
"0x%X", object_id)] = files;
4320 if (!file.is_open()) {
4321 return absl::InvalidArgumentError(
4322 absl::StrFormat(
"Cannot write JSON project file: %s",
filepath));
4326 return absl::OkStatus();
4334 if (!config_dir.ok()) {
4341#ifdef __EMSCRIPTEN__
4342 auto status = platform::WasmStorage::SaveProject(
4345 LOG_WARN(
"RecentFilesManager",
"Could not persist recent files: %s",
4346 status.ToString().c_str());
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());
4359 std::ofstream file(filepath);
4360 if (!file.is_open()) {
4361 LOG_WARN(
"RecentFilesManager",
"Could not save recent files to %s",
4367 file << file_path << std::endl;
4372#ifdef __EMSCRIPTEN__
4374 if (!storage_or.ok()) {
4378 std::istringstream stream(storage_or.value());
4380 while (std::getline(stream, line)) {
4381 if (!line.empty()) {
4389 std::ifstream file(filepath);
4390 if (!file.is_open()) {
4397 while (std::getline(file, line)) {
4398 if (!line.empty()) {
static Json parse(const std::string &)
bool contains(const std::string &) const
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.
std::string Serialize() const
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)
static absl::Status ValidateProjectStructure(const YazeProject &project)
static absl::StatusOr< YazeProject > CreateFromTemplate(const std::string &template_name, const std::string &project_name, const std::string &base_path)
static std::vector< std::string > GetRecommendedFixesForProject(const YazeProject &project)
static std::vector< ProjectTemplate > GetProjectTemplates()
static absl::Status BackupProject(const YazeProject &project)
std::string GetFilePath() const
std::vector< std::string > recent_files_
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_VIDEOGAME_ASSET
#define LOG_DEBUG(category, format,...)
#define LOG_ERROR(category, format,...)
#define LOG_WARN(category, format,...)
#define LOG_INFO(category, format,...)
#define ASSIGN_OR_RETURN(type_variable_name, expression)
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)
std::string ResolveOptionalPath(const std::filesystem::path &base_dir, const std::string &value)
void RemoveProjectSaveTempFile(const std::filesystem::path &temp_path)
bool ContainsLoneCarriageReturn(const std::string &content)
std::vector< std::string > ParsePositionalStringList(const std::string &value)
absl::Status WriteProjectFileAtomicallyImpl(const std::filesystem::path &target_path, absl::string_view contents, bool replace_existing)
std::vector< uint16_t > ParseHexUintList(const std::string &value)
std::string ToLowerCopy(std::string value)
constexpr absl::string_view kProjectFileFooter
bool ParseBool(const std::string &value)
std::pair< std::string, std::string > ParseDefineToken(const std::string &value)
std::optional< uint32_t > ParseHexUint32(const std::string &value)
bool IsKnownProjectSection(absl::string_view name)
std::string FormatHexUint32(uint32_t value)
ProjectFilePassthrough::Section & PassthroughSection(ProjectFilePassthrough &passthrough, const std::string &name)
absl::Status ParseProjectInteger(const std::string &value, const std::string §ion, const std::string &key, int *output)
std::map< uint16_t, std::vector< uint16_t > > ParseHexUintListMap(const std::string &value)
std::string FormatHexUintListMap(const std::map< uint16_t, std::vector< uint16_t > > &values)
bool IsGeneratedProjectComment(absl::string_view line, bool before_sections)
std::string SanitizeStorageKey(absl::string_view input)
std::filesystem::path MakeProjectSaveTempPath(const std::filesystem::path &target_path)
std::string MergeProjectFilePassthrough(const std::string &canonical, const ProjectFilePassthrough &passthrough)
uint64_t CurrentProcessIdForProjectSave()
std::string FormatHexUintList(const std::vector< uint16_t > &values)
void MigrateGfxGroupLabelKeys(std::unordered_map< std::string, std::unordered_map< std::string, std::string > > &labels)
bool IsKeyLine(absl::string_view line)
std::string BasenameLower(const std::string &path)
std::vector< std::string > ParseStringList(const std::string &value)
std::string RomRoleToString(RomRole role)
absl::Status WriteProjectFileAtomically(absl::string_view target_path, absl::string_view contents, bool replace_existing)
RomRole ParseRomRole(absl::string_view value)
const std::string kRecentFilesFilename
RomWritePolicy ParseRomWritePolicy(absl::string_view value)
std::string RomWritePolicyToString(RomWritePolicy policy)
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)
ResourceLabelProvider & GetResourceLabels()
Get the global ResourceLabelProvider instance.
#define RETURN_IF_ERROR(expr)
Room transition destination.
bool kSaveOverworldProperties
bool kEnableSpecialWorldExpansion
bool kSaveOverworldSprites
bool kApplyZSCustomOverworldASM
bool kLoadCustomOverworld
bool kSaveOverworldEntrances
bool kEnableCustomObjects
struct yaze::core::FeatureFlags::Flags::Dungeon dungeon
struct yaze::core::FeatureFlags::Flags::Overworld overworld
bool kSaveWithChangeQueue
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]).
std::vector< std::string > annotations
std::string export_folder
std::vector< uint16_t > track_object_ids
std::vector< uint16_t > minecart_sprite_ids
std::vector< uint16_t > track_stop_tiles
std::vector< uint16_t > track_tiles
std::vector< uint16_t > track_switch_tiles
std::vector< uint16_t > reserved_sheets
std::map< uint16_t, std::vector< uint16_t > > reserved_blocks
std::vector< uint16_t > flagged_sheets
Planning editor sidecar ([planning]).
std::vector< Line > lines
Lines of a .yaze file that this build does not model.
std::vector< Section > sections
YazeProject template_project
std::string CreateOrGetLabel(const std::string &type, const std::string &key, const std::string &defaultValue)
void DisplayLabels(bool *p_open)
std::string GetLabel(const std::string &type, const std::string &key)
void EditLabel(const std::string &type, const std::string &key, const std::string &newValue)
bool LoadLabels(const std::string &filename)
void SelectableLabelWithNameEdit(bool selected, const std::string &type, const std::string &key, const std::string &defaultValue)
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > labels_
int backup_keep_daily_days
std::string last_layout_preset
std::map< std::string, std::string > custom_keybindings
int backup_retention_count
std::vector< std::string > saved_layouts
std::map< std::string, bool > editor_visibility
float autosave_interval_secs
std::vector< std::string > recent_files
std::string custom_system_prompt
std::string gemini_api_key
bool enable_tool_emulator
bool enable_tool_memory_inspector
std::vector< std::string > favorite_models
bool enable_tool_resources
bool enable_tool_messages
std::vector< std::string > model_chain
std::string builder_blueprint_path
bool enable_tool_dialogue
bool enable_tool_overworld
std::string last_saved_at
bool persist_custom_music
Modern project structure with comprehensive settings consolidation.
std::string rom_backup_folder
std::unordered_map< int, std::vector< std::string > > custom_object_files
absl::Status ResetToDefaults()
std::string custom_objects_folder
absl::Status RepairProject()
std::string MakeStorageKey(absl::string_view suffix) const
static std::string ResolveBundleRoot(const std::string &path)
absl::Status ValidateSavedSourceBindings(const std::string &content) const
struct yaze::project::YazeProject::MusicPersistence music_persistence
bool project_opened() const
std::string sprite_catalog_file
absl::StatusOr< std::string > SerializeToString() const
std::string zscream_project_file
absl::Status ExportForZScream(const std::string &target_path)
absl::Status SaveToYazeFormat(bool replace_existing=true)
std::string native_save_transfer_proof_file
absl::Status ImportZScreamProject(const std::string &zscream_project_path)
absl::Status SaveAllSettings()
absl::Status LoadFromString(const std::string &content, const std::string &project_path)
void NormalizePathsToAbsolute()
absl::Status ImportLabelsFromZScreamContent(const std::string &content)
Import labels from ZScream format content directly.
std::string git_repository
core::HackManifest hack_manifest
void InitializeResourceLabelProvider()
Initialize the global ResourceLabelProvider with this project's labels.
absl::Status ParseFromString(const std::string &content)
std::string cutscene_shots
std::vector< std::string > additional_roms
std::string native_save_receipt_file
std::string lyra_terrain_file
std::string terrain_catalog_file
std::string patches_folder
absl::Status LoadFromYazeFormat(const std::string &project_path)
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > resource_labels
std::vector< std::string > AtlasAnnotationPaths() const
std::string GenerateProjectId() const
absl::Status Create(const std::string &project_name, const std::string &base_path)
std::string assets_folder
void ReloadHackManifest()
GraphicsSheetSettings graphics_sheets
std::string AtlasSymbolsPath() const
absl::Status LoadAllSettings()
std::string labels_filename
std::vector< std::string > asm_sources
std::string hack_manifest_file
std::string GetDisplayName() const
PlanningSettings planning
std::string PlanningFilePath() const
std::string native_save_producer_file
std::vector< std::string > GetMissingFiles() const
std::string lyra_build_request_file
WorkspaceSettings workspace_settings
std::string GetZ3dkArtifactPath(absl::string_view artifact_name) const
std::string output_folder
std::string asm_entry_point
std::string GetRelativePath(const std::string &absolute_path) const
std::vector< SpriteAssetBinding > sprite_assets
absl::Status InitializeEmbeddedLabels(const std::unordered_map< std::string, std::unordered_map< std::string, std::string > > &labels)
ProjectFilePassthrough file_passthrough
absl::StatusOr< std::optional< std::string > > ResolveExpandedBuildRunTarget(const std::string &editing_source_path) const
absl::Status SaveAs(const std::string &new_path)
bool IsOracleCompatible() const
struct yaze::project::YazeProject::AgentSettings agent_settings
std::string custom_collision_json
DungeonOverlaySettings dungeon_overlay
absl::Status SaveAsWithLyraTerrain(const std::string &new_path, const core::LyraTerrainDocument &terrain, const std::optional< std::string > &expected_source_bytes)
std::string palette_catalog_file
absl::Status ImportFromZScreamFormat(const std::string &project_path)
void InitializeDefaults()
std::string GetAbsolutePath(const std::string &relative_path) const
std::string overworld_graphics_preview
std::string GetLabel(const std::string &resource_type, int id, const std::string &default_value="") const
std::string sprite_source_root
absl::Status Open(const std::string &project_path)
absl::Status ImportLabelsFromZScream(const std::string &filepath)
Import labels from a ZScream DefaultNames.txt file.
std::string last_build_hash
void TryLoadHackManifest()
std::map< std::string, std::string > zscream_mappings
std::string dungeon_tile_patterns
absl::Status Validate() const
core::FeatureFlags::Flags feature_flags
std::vector< std::string > build_configurations
void ReloadZ3dkSettings()
core::RomAddressOverrides rom_address_overrides
std::string symbols_filename
Z3dkSettings z3dk_settings
std::string annotations_json
std::string sourcemap_json
std::vector< std::string > include_paths
std::string std_includes_path
std::vector< std::string > main_files
std::vector< std::string > emits
std::vector< std::pair< std::string, std::string > > defines
std::string symbols_format
Z3dkArtifactPaths artifact_paths
bool warn_branch_outside_bank
std::optional< bool > lsp_log_enabled
bool warn_unauthorized_hook
std::vector< Z3dkMemoryRange > prohibited_memory_ranges
std::string std_defines_path