Merge the save export and import for bug reports into the test line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
chrg6
2026-11-09 21:11:18 -05:00
26 changed files with 2974 additions and 78 deletions

View File

@@ -1,6 +1,8 @@
// The host's own folder dialog, for menu pages that point at a folder (the Amiibo tab): folder_pick_win.cpp with Win32,
// folder_pick_sdl.c with SDL. The menu has no text entry, so a folder is chosen here or by walking the page's list.
// The host's own folder and file dialogs, for menu pages that point at a folder (the Amiibo tab) or a file (a shared
// save's zip, the Game tab), and the player's Downloads folder: folder_pick_win.cpp with Win32, folder_pick_sdl.c with
// SDL. The menu has no text entry, so a folder is chosen here or by walking the page's list.
#pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
@@ -12,6 +14,10 @@ typedef void (*FolderPickDone)(const char *path, void *ctx);
// Opens the dialog at start (may be relative or missing) and returns at once; done runs later on another thread, once.
// The caller keeps one dialog open at a time.
void folder_pick(const char *start, FolderPickDone done, void *ctx);
// The same for one file: the dialog lists the files whose name ends in "." ext ("zip") and offers all files too.
void file_pick(const char *start, const char *ext, FolderPickDone done, void *ctx);
// The player's Downloads folder (where the system keeps it, also when moved) into out, UTF-8. 0 when there is none.
int folder_downloads(char *out, size_t cap);
#ifdef __cplusplus
}

View File

@@ -1,6 +1,8 @@
// The SDL front end of folder_pick.h: SDL_ShowOpenFolderDialog (the desktop portal, else zenity), started on the window
// thread, which runs SDL's event loop that delivers the portal's answer.
// The SDL front end of folder_pick.h: SDL_ShowOpenFolderDialog and SDL_ShowOpenFileDialog (the desktop portal, else
// zenity), started on the window thread, which runs SDL's event loop that delivers the portal's answer, and SDL's user
// folders.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -12,6 +14,8 @@
typedef struct {
char start[PATH_MAX]; // absolute, or empty: the dialog's own default
char ext[16]; // a file of this extension; empty: a folder
SDL_DialogFileFilter filters[2]; // read by SDL until the answer comes
FolderPickDone done;
void *ctx;
} PickReq;
@@ -26,10 +30,16 @@ static void SDLCALL on_pick(void *userdata, const char *const *list, int filter)
static void show(void *arg) {
PickReq *r = arg;
SDL_ShowOpenFolderDialog(on_pick, r, gfx_window_sdl(), r->start[0] ? r->start : NULL, false);
if (!r->ext[0]) {
SDL_ShowOpenFolderDialog(on_pick, r, gfx_window_sdl(), r->start[0] ? r->start : NULL, false);
return;
}
r->filters[0] = (SDL_DialogFileFilter){r->ext, r->ext}; // the extension is its own name: no text to translate
r->filters[1] = (SDL_DialogFileFilter){"*", "*"};
SDL_ShowOpenFileDialog(on_pick, r, gfx_window_sdl(), r->filters, 2, r->start[0] ? r->start : NULL, false);
}
void folder_pick(const char *start, FolderPickDone done, void *ctx) {
static void pick(const char *start, const char *ext, FolderPickDone done, void *ctx) {
PickReq *r = calloc(1, sizeof *r);
if (!r) {
done(NULL, ctx);
@@ -37,6 +47,21 @@ void folder_pick(const char *start, FolderPickDone done, void *ctx) {
}
r->done = done;
r->ctx = ctx;
if (ext) snprintf(r->ext, sizeof r->ext, "%s", *ext ? ext : "*");
if (start && *start && !realpath(start, r->start)) r->start[0] = 0;
gfx_window_sdl_run(show, r);
}
void folder_pick(const char *start, FolderPickDone done, void *ctx) { pick(start, NULL, done, ctx); }
void file_pick(const char *start, const char *ext, FolderPickDone done, void *ctx) { pick(start, ext, done, ctx); }
int folder_downloads(char *out, size_t cap) {
const char *p = SDL_GetUserFolder(SDL_FOLDER_DOWNLOADS);
size_t n = p ? strlen(p) : 0;
while (n > 1 && p[n - 1] == '/') n--; // SDL ends it with a separator
if (!n || n >= cap) return 0;
memcpy(out, p, n);
out[n] = 0;
return 1;
}

View File

@@ -1,6 +1,8 @@
// The Win32 front end of folder_pick.h: the shell's folder dialog (IFileOpenDialog with FOS_PICKFOLDERS), owned by the
// game window, on a thread of its own so the present thread that draws the menu keeps running.
// The Win32 front end of folder_pick.h: the shell's open dialog (IFileOpenDialog; FOS_PICKFOLDERS for a folder), owned
// by the game window, on a thread of its own so the present thread that draws the menu keeps running, and the shell's
// Downloads folder.
#include <windows.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <stdlib.h>
#include <string>
@@ -14,6 +16,7 @@ extern "C" {
struct PickReq {
std::string start;
std::string ext; // a file of this extension; empty: a folder
FolderPickDone done;
void *ctx;
};
@@ -54,7 +57,14 @@ static void pick_main(void *arg) {
if (SUCCEEDED(hr)) {
FILEOPENDIALOGOPTIONS opt = 0;
d->GetOptions(&opt);
d->SetOptions(opt | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
if (r->ext.empty()) {
d->SetOptions(opt | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
} else {
d->SetOptions(opt | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST);
std::wstring pattern = L"*." + wide(r->ext); // the pattern is its own name: no text to translate
COMDLG_FILTERSPEC types[] = {{pattern.c_str(), pattern.c_str()}, {L"*.*", L"*.*"}};
d->SetFileTypes(2, types);
}
set_start(d, r->start);
hr = d->Show(gfx_window_handle());
IShellItem *item = NULL;
@@ -68,17 +78,38 @@ static void pick_main(void *arg) {
}
d->Release();
}
if (FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_CANCELLED)) rt_log("folder_pick: the folder dialog failed (0x%08lx)", (unsigned long)hr);
if (FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_CANCELLED))
rt_log("folder_pick: the %s dialog failed (0x%08lx)", r->ext.empty() ? "folder" : "file", (unsigned long)hr);
r->done(chosen.empty() ? NULL : chosen.c_str(), r->ctx);
if (SUCCEEDED(co)) CoUninitialize();
delete r;
}
extern "C" void folder_pick(const char *start, FolderPickDone done, void *ctx) {
PickReq *r = new PickReq{start ? start : "", done, ctx};
static void pick(const char *start, const char *ext, FolderPickDone done, void *ctx) {
PickReq *r = new PickReq{start ? start : "", ext ? ext : "", done, ctx};
if (!plat_thread_spawn(pick_main, r, "folder dialog", 0)) {
rt_log("folder_pick: cannot start the dialog thread");
done(NULL, ctx);
delete r;
}
}
extern "C" void folder_pick(const char *start, FolderPickDone done, void *ctx) { pick(start, NULL, done, ctx); }
extern "C" void file_pick(const char *start, const char *ext, FolderPickDone done, void *ctx) {
pick(start, ext && *ext ? ext : "*", done, ctx);
}
extern "C" int folder_downloads(char *out, size_t cap) {
// FOLDERID_Downloads, spelled out so no import library has to carry it
static const GUID downloads = {0x374de290, 0x123f, 0x4565, {0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b}};
PWSTR path = NULL;
int ok = 0;
if (SUCCEEDED(SHGetKnownFolderPath(downloads, 0, NULL, &path)) && path) {
std::string s = utf8(path);
ok = !s.empty() && s.size() < cap;
if (ok) memcpy(out, s.c_str(), s.size() + 1);
}
CoTaskMemFree(path);
return ok;
}

View File

@@ -63,3 +63,16 @@ int fs_save_busy(void); // a save is being wr
// or save data changed in the last 3 s and not committed
void fs_save_flush(void); // wait for a save Commit still running in the background;
// every exit path calls it before the process ends
// A shared save (save_share.c). fs_save_export: visit(ctx, path below the save with '/', bytes, size) for every file of
// the save the game would load next, under the commit lock; visit returns 0 to fail. The number of files (0: no save
// yet), -1 when one could not be read or visit failed.
typedef int (*FsSaveVisit)(void *ctx, const char *rel, const uint8_t *data, size_t n);
int fs_save_export(FsSaveVisit visit, void *ctx);
// The menu's import: count files (relative '/' paths, bytes) become <profile>/save-import, which the next start makes
// the save, backing up the save it replaces; one waiting already is replaced. 0 on success.
int fs_save_import_stage(int count, const char *const *rel, const uint8_t *const *data, const size_t *size);
int fs_save_import_waiting(void); // 1 while an import waits for the next start (0 before
// the first storage use)
int fs_save_import_cancel(void); // drops it; 0 on success
const char *fs_save_import_done(void); // the backup of the save an import replaced at this start,
// "-" when there was none, "" when no import ran

View File

@@ -8,6 +8,8 @@
// <profile>/save-tx/ the save mount's working copy and Commit's staging (section "save
// transactions")
// <profile>/save-backup/<time>/ the three committed saves before the current one
// <profile>/save-import/ a save the menu imported, made the save at the next start (section "a shared
// save")
// <profile>/temp/ emptied at start
// <profile>/cache/<index>/ cache storage
//
@@ -23,6 +25,7 @@
#include "host.h"
#include "platform/platform.h"
#include "romfs_path.h"
#include "save_share.h"
#define NX2NAVI_APPLICATION_ID 0x0400486024dec000ull // the game's title id, as svc.c PROGRAM_ID tells it
#define FILE_BASE 0x200000000ull
@@ -618,6 +621,170 @@ static uint32_t save_commit(void) {
return commit_run();
}
// ---- a shared save (save_share.c): the export reads the newest save, the menu's import waits for the next start
//
// <profile>/save-import/ a save the menu took from a zip: it becomes the save at the next start
// <profile>/save-import.part/ that save while the menu writes it; renamed to save-import when complete
//
// The import cannot replace the save while the game runs: the game holds its progress in memory and writes it back
// at its next save, over the imported files, and the save mount's working copy is made once per mount. So the start
// takes it (import_pending), in storage_init after save_recover and before the game mounts its save: the save the
// game would load is copied to <game folder>/saves/backup <local time> (save_share_backup_dir, where the launcher keeps
// the backups of its imports), then the import becomes a finished commit (ready-<n>) and swaps in as one (swap_in),
// which also moves the replaced save to save-backup. When the copy fails the import waits for the next start.
static char import_done[1100]; // the backup folder of the import this start made the save; "-" with none to back up
static void ready(void);
static void import_pending(void) {
char imp[1100], part[1100];
snprintf(imp, sizeof imp, "%s/save-import", profile);
snprintf(part, sizeof part, "%s/save-import.part", profile);
if (exists(part) && remove_tree(part)) rt_log("host save import: cannot delete the unfinished %s", part);
if (plat_fs_kind(imp) != PLAT_FS_DIR) return;
const char *cur = newest_save();
char backup[1100] = "";
if (exists(cur)) {
int nfiles = 0, linked = 0;
uint64_t bytes = 0;
if (!save_share_backup_dir(backup, sizeof backup) || copy_tree(cur, backup, NULL, 1, &nfiles, &linked, &bytes)) {
rt_log("host save import: cannot copy the current save to %s; the import waits in %s for the next start",
*backup ? backup : "the saves folder", imp);
if (*backup) remove_tree(backup);
return;
}
if (!nfiles) { // an empty account folder: nothing to keep
remove_tree(backup);
*backup = 0;
}
}
char commit[1100];
snprintf(commit, sizeof commit, "%s/ready-%010u", tx_root, ready_seq + 1);
if (move_dir(imp, commit, MOVE_TRIES)) {
rt_log("host save import: cannot move %s into save-tx; it waits for the next start", imp);
return;
}
ready_seq++;
if (*ready_root) remove_tree(ready_root); // the save the backup holds
snprintf(ready_root, sizeof ready_root, "%s", commit);
int waits = swap_in();
snprintf(import_done, sizeof import_done, "%s", *backup ? backup : "-");
rt_log("host save import: the save imported in the menu is the save now%s; the save it replaced is in %s",
waits ? " (it waits in save-tx)" : "", *backup ? backup : "(none: there was no save)");
}
const char *fs_save_import_done(void) {
return plat_cas32(&storage_ready, 0, 0) ? import_done : "";
}
// Visits every file under dir (rel: its path below the save, "" at the top), in name order; links are left out.
// -1 when a file cannot be read.
static int export_tree(const char *dir, const char *rel, FsSaveVisit visit, void *ctx) {
Listing l;
if (list_dir(dir, &l)) return -1;
qsort(l.e, (size_t)l.n, sizeof *l.e, listed_cmp);
int n = 0;
for (int i = 0; i < l.n && n >= 0; i++) {
if (l.e[i].kind == PLAT_FS_LINK) continue;
char *path = join(dir, l.e[i].name);
char *sub = *rel ? join(rel, l.e[i].name) : strdup(l.e[i].name);
need(sub != NULL, "save export path");
if (l.e[i].kind == PLAT_FS_DIR) {
int k = export_tree(path, sub, visit, ctx);
n = k < 0 ? -1 : n + k;
} else {
uint64_t size = 0;
uint8_t *data = plat_file_read(path, &size); // NULL for an empty file as well
if (!data && plat_file_size(path) != 0) n = -1;
else if (!visit(ctx, sub, data ? data : (const uint8_t *)"", (size_t)size)) n = -1;
else n++;
free(data);
}
free(path);
free(sub);
}
listing_free(l.e, l.n);
return n;
}
int fs_save_export(FsSaveVisit visit, void *ctx) {
ready();
// the commit thread holds tx_lock while it swaps a commit in, and the committed save is never written in place
plat_mutex_lock(&tx_lock);
const char *src = newest_save();
int n = exists(src) ? export_tree(src, "", visit, ctx) : 0;
plat_mutex_unlock(&tx_lock);
return n;
}
// Writes one file and flushes it; 0 on success.
static int stage_file(const char *path, const uint8_t *data, size_t n) {
char dir[PATH_CAP];
snprintf(dir, sizeof dir, "%s", path);
char *cut = strrchr(dir, '/');
if (cut) {
*cut = 0;
plat_file_mkdir_p(dir);
}
PlatFile *f = plat_fs_create(path, NULL);
if (!f) return -1;
int ok = 1;
for (size_t at = 0; ok && at < n;) {
uint32_t k = n - at > COPY_CHUNK ? COPY_CHUNK : (uint32_t)(n - at);
ok = plat_file_pwrite(f, data + at, k, at) == k;
at += k;
}
ok = ok && plat_file_fsync(f);
plat_file_close(f);
return ok ? 0 : -1;
}
int fs_save_import_stage(int count, const char *const *rel, const uint8_t *const *data, const size_t *size) {
ready(); // the start's own import_pending has run: this one waits for the next start
char imp[1100], part[1100];
snprintf(imp, sizeof imp, "%s/save-import", profile);
snprintf(part, sizeof part, "%s/save-import.part", profile);
if (remove_tree_retry(part) || plat_fs_mkdir(part)) {
rt_log("host save import: cannot make %s", part);
return -1;
}
for (int i = 0; i < count; i++) {
char *path = join(part, rel[i]);
int bad = strlen(path) >= PATH_CAP || stage_file(path, data[i], size[i]);
free(path);
if (bad) {
rt_log("host save import: cannot write %s into %s", rel[i], part);
remove_tree(part);
return -1;
}
}
plat_fs_sync_dir(part);
if (remove_tree_retry(imp) || move_dir(part, imp, MOVE_TRIES)) {
rt_log("host save import: cannot put the import in place as %s", imp);
remove_tree(part);
return -1;
}
rt_log("host save import: %d files wait in %s for the next start", count, imp);
return 0;
}
int fs_save_import_waiting(void) {
// the menu asks every frame: before the game's first storage use the start's own import_pending has not run, and
// this is no reason to run it on the present thread
if (!plat_cas32(&storage_ready, 0, 0)) return 0;
char imp[1100];
snprintf(imp, sizeof imp, "%s/save-import", profile);
return plat_fs_kind(imp) == PLAT_FS_DIR;
}
int fs_save_import_cancel(void) {
ready();
char imp[1100];
snprintf(imp, sizeof imp, "%s/save-import", profile);
if (remove_tree_retry(imp)) return -1;
rt_log("host save import: the import waiting for the next start was dropped");
return 0;
}
// ---- storage roots
// One game per profile: a second one's start would take the first one's commit in progress for an interrupted one
// and delete it, and both would write into one working copy (save-tx/work), losing or mixing their saves. rt_boot
@@ -653,6 +820,7 @@ static void storage_init(void *param) {
snprintf(new_root, sizeof new_root, "%s/new", tx_root);
snprintf(old_root, sizeof old_root, "%s/old", tx_root);
save_recover(); // before save_root is created: an absent save_root means a commit to complete
import_pending();
make_dirs(save_root);
snprintf(p, sizeof p, "%s/temp", profile);
remove_tree(p);

View File

@@ -884,6 +884,20 @@ static void probe_menu_text(void) {
CHECK(ui_text_defined("zh-Hans", (UiTextId)id), "menu text id %d lacks Simplified Chinese", id);
}
CHECK(!ui_text_defined("en", UI_TEXT_COUNT) && !*ui_text_in("ru", UI_TEXT_COUNT), "an id past the catalog gives text");
// the Saves group's lines are formats of one path or detail (ui/menu.cpp rows_saves): at most one "%s", nothing else
for (int id = UI_MENU_SAVES; id <= UI_MENU_SAVE_E_UNSAFE; id++)
for (size_t i = 0; i < 4; i++) {
static const char *const menu_langs[] = {"en", "ru", "pt-BR", "zh-Hans"};
const char *t = ui_text_in(menu_langs[i], (UiTextId)id);
int conv = 0, other = 0;
for (const char *q = strchr(t, '%'); q; q = strchr(q + 2, '%')) {
if (q[1] == 's') conv++;
else if (q[1] != '%') other++;
if (!q[1]) break;
}
CHECK(conv <= 1 && !other, "saves text %d in %s has %d %%s and %d other conversions", id, menu_langs[i],
conv, other);
}
// other languages fall back to English for the menu, and keep their own keyboard texts
CHECK(!strcmp(ui_text_in("ja", UI_MENU_CONTINUE), ui_text_in("en", UI_MENU_CONTINUE)), "ja menu text is not English");
CHECK(!strcmp(ui_text_in("ru", UI_SWKBD_OK), "ОК") && !strcmp(ui_text_in("de", UI_SWKBD_CANCEL), "Abbrechen") &&

278
runtime/save_share.c Normal file
View File

@@ -0,0 +1,278 @@
// Sharing a save (save_share.h). The zip, as the launcher's launcher/saves.py export_save writes it:
//
// manifest.json {"format": "nx2navi-save", "format_version": 1, "game", "title_id", "game_version", "nx2navi",
// "exported" (UTC), "exported_by", "files", "bug_report"}
// save/... the save's files as the game keeps them (account.sav, option.sav, slot_00/progress.sav, ...)
// bug-report/... with a bug report: this run's log and nx2navi.ini; an import leaves them out
//
// An import accepts a zip whose manifest has this format, a version up to FORMAT_VERSION and the game's title id, whose
// save/ paths stay inside the save, with no links, at most MAX_FILES files and MAX_BYTES, among them a file of this
// game's save (save_file). Every member's CRC-32 is checked before anything is written.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "folder_pick.h"
#include "fs.h"
#include "host.h"
#include "platform/platform.h"
#include "save_share.h"
#include "save_zip.h"
#define FORMAT "nx2navi-save"
#define FORMAT_VERSION 1
#define TITLE_ID "0400486024dec000" // the game's title id (fs_host.c NX2NAVI_APPLICATION_ID)
#define GAME "The Legend of Zelda: Ocarina of Time"
#define MAX_FILES 4000
#define MAX_BYTES (256ull << 20)
#define MAX_ZIP (512ll << 20)
#define MANIFEST_MAX 65536
// The executable's folder, where nx2navi.ini, logs and saves are (cfg.c find_ini, main.c log_open). 0 when unknown.
static int exe_dir(char *out, size_t cap) {
if (!plat_exe_path(out, cap)) return 0;
char *cut = plat_last_sep(out), *slash = strrchr(out, '/');
if (slash > cut) cut = slash;
if (!cut) return 0;
*cut = 0;
return 1;
}
static int lower(int c) { return c >= 'A' && c <= 'Z' ? c + 32 : c; }
static int same_text(const char *a, const char *b) { // ASCII, any case
while (*a && lower((unsigned char)*a) == lower((unsigned char)*b)) a++, b++;
return !*a && !*b;
}
static int ends_with(const char *s, const char *tail) {
size_t n = strlen(s), k = strlen(tail);
return n >= k && same_text(s + n - k, tail);
}
// Key files never go into a zip or out of one, wherever a stray copy sits in a save folder.
static int key_file(const char *rel) { return ends_with(rel, ".keys") || ends_with(rel, ".keys.txt"); }
// A file only this game's save has: what makes the zip's save this game's.
static int save_file(const char *rel) {
if (!strcmp(rel, "account.sav") || !strcmp(rel, "option.sav")) return 1;
return !strncmp(rel, "slot_", 5) && rel[5] >= '0' && rel[5] <= '9' && rel[6] >= '0' && rel[6] <= '9' &&
!strcmp(rel + 7, "/progress.sav");
}
// A relative path that stays inside the save: '/' separators, no empty, "." or ".." part, no drive or backslash.
static int safe_rel(const char *rel) {
if (!*rel || *rel == '/' || strchr(rel, '\\') || strchr(rel, ':')) return 0;
for (const char *p = rel;;) {
const char *slash = strchr(p, '/');
size_t k = slash ? (size_t)(slash - p) : strlen(p);
if (!k || (k == 1 && p[0] == '.') || (k == 2 && p[0] == '.' && p[1] == '.')) return 0;
if (!slash) return 1;
p = slash + 1;
}
}
int save_share_default_dir(char *out, size_t cap) { return folder_downloads(out, cap) || exe_dir(out, cap); }
int save_share_backup_dir(char *out, size_t cap) {
char dir[PLAT_PATH_MAX], saves[PLAT_PATH_MAX + 8];
if (!exe_dir(dir, sizeof dir)) return 0;
snprintf(saves, sizeof saves, "%s/saves", dir);
plat_file_mkdir_p(saves);
struct tm t;
plat_local_time(&t);
char stamp[32];
snprintf(stamp, sizeof stamp, "%04d-%02d-%02d %02d.%02d.%02d", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
for (int k = 1; k < 100; k++) {
int n = k == 1 ? snprintf(out, cap, "%s/backup %s", saves, stamp)
: snprintf(out, cap, "%s/backup %s (%d)", saves, stamp, k);
if (n < 0 || (size_t)n >= cap) break;
if (plat_fs_kind(out) == PLAT_FS_MISSING) return 1;
}
*out = 0;
return 0;
}
// ---- export
typedef struct {
SzWriter w;
int files;
} Export;
static int add_save_file(void *ctx, const char *rel, const uint8_t *data, size_t n) {
Export *e = ctx;
if (key_file(rel)) return 1;
char name[PLAT_PATH_MAX];
if (snprintf(name, sizeof name, "save/%s", rel) >= (int)sizeof name) return 0;
sz_writer_add(&e->w, name, data, n);
e->files++;
return !e->w.failed;
}
static void add_file(Export *e, const char *name, const char *path) {
uint64_t n = 0;
uint8_t *data = path ? plat_file_read(path, &n) : NULL;
if (data) sz_writer_add(&e->w, name, data, (size_t)n);
free(data);
}
SaveShareResult save_share_export(const char *dir, int bug_report, char *path, size_t cap) {
*path = 0;
struct tm t;
plat_local_time(&t);
Export e;
memset(&e, 0, sizeof e);
sz_writer_init(&e.w, t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
int n = fs_save_export(add_save_file, &e);
if (n <= 0 || !e.files || e.w.failed) {
size_t unused;
free(sz_writer_finish(&e.w, &unused));
rt_log("save share: export: %s", n < 0 ? "a save file could not be read" : "the game has no save yet");
return n < 0 ? SAVE_SHARE_READ_FAILED : SAVE_SHARE_NO_SAVE;
}
char base[PLAT_PATH_MAX], file[PLAT_PATH_MAX + 32];
if (bug_report) {
add_file(&e, "bug-report/nx2navi.log", rt_log_path());
if (exe_dir(base, sizeof base)) {
snprintf(file, sizeof file, "%s/nx2navi.ini", base);
add_file(&e, "bug-report/nx2navi.ini", file);
}
}
struct tm u;
plat_gmtime((int64_t)(plat_unix_time_ns() / 1000000000u), &u);
char ver[96], manifest[1024];
sz_json_escape(rt_port_version, ver, sizeof ver);
int mn = snprintf(manifest, sizeof manifest,
"{\n \"format\": \"" FORMAT "\",\n \"format_version\": %d,\n \"game\": \"" GAME "\",\n"
" \"title_id\": \"" TITLE_ID "\",\n \"game_version\": \"%d.%d.%d\",\n \"nx2navi\": \"%s\",\n"
" \"exported\": \"%04d-%02d-%02dT%02d:%02d:%02dZ\",\n \"exported_by\": \"game\",\n"
" \"files\": %d,\n \"bug_report\": %s\n}\n",
FORMAT_VERSION, rt_game_version / 100, rt_game_version / 10 % 10, rt_game_version % 10, ver,
u.tm_year + 1900, u.tm_mon + 1, u.tm_mday, u.tm_hour, u.tm_min, u.tm_sec, e.files,
bug_report ? "true" : "false");
sz_writer_add(&e.w, "manifest.json", manifest, (size_t)mn);
size_t zn = 0;
uint8_t *zip = sz_writer_finish(&e.w, &zn);
if (!zip) {
rt_log("save share: export: out of memory for the zip");
return SAVE_SHARE_WRITE_FAILED;
}
plat_file_mkdir_p(dir);
char stem[64];
snprintf(stem, sizeof stem, "NX2navi-save-%04d-%02d-%02d_%02d-%02d-%02d%s", t.tm_year + 1900, t.tm_mon + 1,
t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, bug_report ? "-bug-report" : "");
int ok = 0;
for (int k = 1; k < 100 && !ok; k++) { // two exports in one second: "(2)" as the launcher names them
int len = k == 1 ? snprintf(path, cap, "%s/%s.zip", dir, stem) : snprintf(path, cap, "%s/%s (%d).zip", dir, stem, k);
if (len < 0 || (size_t)len >= cap) break;
if (plat_fs_kind(path) != PLAT_FS_MISSING) continue;
ok = plat_file_write_atomic(path, zip, zn);
if (!ok) break;
}
free(zip);
if (!ok) {
rt_log("save share: export: cannot write the zip into %s", dir);
*path = 0;
return SAVE_SHARE_WRITE_FAILED;
}
rt_log("save share: exported %d save files%s to %s (%zu bytes)", e.files, bug_report ? " with the log and settings" : "",
path, zn);
return SAVE_SHARE_OK;
}
// ---- import
static const SzEntry *find_member(const SzEntry *e, int count, const char *name) {
for (int i = 0; i < count; i++)
if (!strcmp(e[i].name, name)) return &e[i];
return NULL;
}
// The manifest's verdict on the zip; detail gets its NX2navi version and export date.
static SaveShareResult check_manifest(const uint8_t *zip, size_t n, const SzEntry *e, int count, char *detail,
size_t cap) {
const SzEntry *m = find_member(e, count, "manifest.json");
if (!m || m->usize > MANIFEST_MAX) return SAVE_SHARE_NOT_A_SAVE;
int err;
char *json = (char *)sz_extract(zip, n, m, &err);
if (!json) return err == SZ_E_MEMORY ? SAVE_SHARE_READ_FAILED : SAVE_SHARE_DAMAGED;
char format[32] = "", title[32] = "", ver[64] = "?", when[32] = "?";
long long version = 0;
SaveShareResult r = SAVE_SHARE_OK;
if (!sz_json_str(json, "format", format, sizeof format) || strcmp(format, FORMAT) ||
!sz_json_int(json, "format_version", &version) || version < 1)
r = SAVE_SHARE_NOT_A_SAVE;
else if (version > FORMAT_VERSION)
r = SAVE_SHARE_NEWER;
else if (!sz_json_str(json, "title_id", title, sizeof title) || !same_text(title, TITLE_ID))
r = SAVE_SHARE_OTHER_GAME;
sz_json_str(json, "nx2navi", ver, sizeof ver);
sz_json_str(json, "exported", when, sizeof when);
snprintf(detail, cap, "%s, %.10s", *ver ? ver : "?", when);
free(json);
return r;
}
SaveShareResult save_share_import(const char *zip_path, char *detail, size_t cap) {
*detail = 0;
int64_t size = plat_file_size(zip_path);
if (size < 0) return SAVE_SHARE_READ_FAILED;
if (size > MAX_ZIP) return SAVE_SHARE_UNSAFE;
uint64_t n = 0;
uint8_t *zip = plat_file_read(zip_path, &n);
if (!zip) return size ? SAVE_SHARE_READ_FAILED : SAVE_SHARE_NOT_A_SAVE;
SzEntry *e = NULL;
int count = 0, zr = sz_read_dir(zip, (size_t)n, &e, &count);
SaveShareResult r = zr == SZ_OK ? check_manifest(zip, (size_t)n, e, count, detail, cap)
: zr == SZ_E_NOT_ZIP ? SAVE_SHARE_NOT_A_SAVE
: zr == SZ_E_MEMORY ? SAVE_SHARE_READ_FAILED
: SAVE_SHARE_DAMAGED;
// the save's members: checked all before any is extracted
int files = 0, has_save = 0;
uint64_t bytes = 0;
for (int i = 0; r == SAVE_SHARE_OK && i < count; i++) {
if (strncmp(e[i].name, "save/", 5) || e[i].is_dir) continue;
const char *rel = e[i].name + 5;
if (!safe_rel(rel) || e[i].is_link) r = SAVE_SHARE_UNSAFE;
else if (key_file(rel)) continue;
bytes += e[i].usize;
if (++files > MAX_FILES || bytes > MAX_BYTES) r = SAVE_SHARE_UNSAFE;
has_save |= save_file(rel);
}
if (r == SAVE_SHARE_OK && !has_save) r = SAVE_SHARE_NOT_A_SAVE;
const char **rels = NULL;
uint8_t **data = NULL;
size_t *sizes = NULL;
int k = 0;
if (r == SAVE_SHARE_OK) {
rels = calloc((size_t)files, sizeof *rels);
data = calloc((size_t)files, sizeof *data);
sizes = calloc((size_t)files, sizeof *sizes);
if (!rels || !data || !sizes) r = SAVE_SHARE_READ_FAILED;
}
for (int i = 0; r == SAVE_SHARE_OK && i < count; i++) {
if (strncmp(e[i].name, "save/", 5) || e[i].is_dir || key_file(e[i].name + 5)) continue;
int err;
data[k] = sz_extract(zip, (size_t)n, &e[i], &err);
if (!data[k]) {
r = err == SZ_E_MEMORY ? SAVE_SHARE_READ_FAILED : SAVE_SHARE_DAMAGED;
break;
}
rels[k] = e[i].name + 5;
sizes[k++] = (size_t)e[i].usize;
}
if (r == SAVE_SHARE_OK && fs_save_import_stage(k, rels, (const uint8_t *const *)data, sizes))
r = SAVE_SHARE_WRITE_FAILED;
for (int i = 0; i < k; i++) free(data[i]);
free(rels), free(data), free(sizes), free(e), free(zip);
static const char *const why[] = {"waits for the next start", "", "the zip cannot be read", "its save cannot be put in place",
"not a zip of an NX2navi save", "a save of another game",
"made by a newer NX2navi", "damaged", "paths outside the save, links or too large"};
rt_log("save share: import of %s (NX2navi %s): %s", zip_path, *detail ? detail : "?", why[r]);
return r;
}
int save_share_pending(void) { return fs_save_import_waiting(); }
int save_share_cancel(void) { return fs_save_import_cancel(); }

40
runtime/save_share.h Normal file
View File

@@ -0,0 +1,40 @@
// Sharing a save (save_share.c): the menu's Export writes the save the game would load next into one zip, for a bug
// report or another player, and its Import checks such a zip and leaves its save for the game's next start
// (fs_host.c import_pending). The launcher writes and reads the same zip (launcher/saves.py export_save, import_zip).
#pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
SAVE_SHARE_OK,
SAVE_SHARE_NO_SAVE, // export: the game has not saved yet
SAVE_SHARE_READ_FAILED, // export: a save file could not be read; import: the zip could not be read
SAVE_SHARE_WRITE_FAILED, // export: the zip could not be written; import: its save could not be put in place
SAVE_SHARE_NOT_A_SAVE, // import: not a zip of an NX2navi save (no manifest, another format, no save files)
SAVE_SHARE_OTHER_GAME, // import: the manifest names another game
SAVE_SHARE_NEWER, // import: a newer NX2navi made it, in a format this one does not know
SAVE_SHARE_DAMAGED, // import: a member's data or CRC is wrong
SAVE_SHARE_UNSAFE, // import: a path outside the save, a link, or far more than a save
} SaveShareResult;
// Writes NX2navi-save-<local date>_<time>[-bug-report].zip into dir (made when missing); bug_report adds this run's
// log and nx2navi.ini. path gets the zip's path. Never a key file.
SaveShareResult save_share_export(const char *dir, int bug_report, char *path, size_t cap);
// Checks the zip at zip_path (manifest, game, paths, sizes, CRCs) and stages its save for the next start. detail gets
// "<NX2navi version>, <export date>" from its manifest ("?" for what it lacks).
SaveShareResult save_share_import(const char *zip_path, char *detail, size_t cap);
int save_share_pending(void); // 1 while an import waits for the next start
int save_share_cancel(void); // drops the waiting import; 0 on success
// Where Export writes and Import's file dialog opens: the player's Downloads folder, else the game folder. 0 when
// neither is known.
int save_share_default_dir(char *out, size_t cap);
// A new folder name <game folder>/saves/backup <local date> <time> (with " (2)" and up when taken), the saves folder
// made; the folder itself is not. Where the launcher keeps the backups of its imports. 0 when it cannot be named.
int save_share_backup_dir(char *out, size_t cap);
#ifdef __cplusplus
}
#endif

662
runtime/save_zip.c Normal file
View File

@@ -0,0 +1,662 @@
// The zip file of a shared save (save_zip.h). Little-endian fields as the zip format (PKWARE APPNOTE) lays them out;
// deflate as RFC 1951 defines it.
#include <stdlib.h>
#include <string.h>
#include "save_zip.h"
// ---- CRC-32 (the zip polynomial, reflected), one table built on first use
static uint32_t crc_table[256];
static volatile int crc_ready;
uint32_t sz_crc32(uint32_t crc, const void *data, size_t n) {
if (!crc_ready) { // two threads may build it at once: they write the same values
for (uint32_t i = 0; i < 256; i++) {
uint32_t c = i;
for (int k = 0; k < 8; k++) c = c & 1 ? 0xedb88320u ^ (c >> 1) : c >> 1;
crc_table[i] = c;
}
__atomic_store_n(&crc_ready, 1, __ATOMIC_RELEASE);
}
const uint8_t *p = data;
crc = ~crc;
while (n--) crc = crc_table[(crc ^ *p++) & 0xff] ^ (crc >> 8);
return ~crc;
}
// ---- deflate tables shared by both directions: length codes 257..285 and distance codes 0..29
static const uint16_t len_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27,
31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
static const uint8_t len_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
static const uint16_t dist_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129,
193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
static const uint8_t dist_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
// ---- inflate
typedef struct {
const uint8_t *in;
size_t n, pos;
uint64_t bitbuf;
int bitcnt, bad;
uint8_t *out;
size_t cap, at;
} Inflate;
// need (0..16) bits, the first read in the lowest bit; past the end of the input: 0 and bad set.
static unsigned get_bits(Inflate *s, int need) {
while (s->bitcnt < need) {
if (s->pos >= s->n) {
s->bad = 1;
return 0;
}
s->bitbuf |= (uint64_t)s->in[s->pos++] << s->bitcnt;
s->bitcnt += 8;
}
unsigned v = (unsigned)(s->bitbuf & ((1u << need) - 1));
s->bitbuf >>= need;
s->bitcnt -= need;
return v;
}
// A canonical Huffman code: how many codes of each length, and the symbols in code order.
typedef struct {
uint16_t count[16];
uint16_t symbol[288];
} Huff;
// The code of lengths[0..n) (0: the symbol is unused). 0 when usable: no length is over-subscribed (an incomplete
// code is allowed, as a stream with a single distance code has one; a code it lacks then reads as damaged).
static int huff_build(Huff *h, const uint8_t *lengths, int n) {
uint16_t offs[16];
memset(h->count, 0, sizeof h->count);
for (int i = 0; i < n; i++) h->count[lengths[i]]++;
h->count[0] = 0;
int left = 1;
for (int len = 1; len < 16; len++) {
left = (left << 1) - h->count[len];
if (left < 0) return -1;
}
offs[1] = 0;
for (int len = 1; len < 15; len++) offs[len + 1] = offs[len] + h->count[len];
for (int i = 0; i < n; i++)
if (lengths[i]) h->symbol[offs[lengths[i]]++] = (uint16_t)i;
return 0;
}
// The next symbol of code h, the bits read one at a time (Huffman codes are packed from their first bit); -1 damaged.
static int huff_decode(Inflate *s, const Huff *h) {
int code = 0, first = 0, index = 0;
for (int len = 1; len < 16; len++) {
code |= (int)get_bits(s, 1);
if (s->bad) return -1;
int count = h->count[len];
if (code - first < count) return h->symbol[index + (code - first)];
index += count;
first = (first + count) << 1;
code <<= 1;
}
return -1;
}
// The symbols of one block until its end code.
static int inflate_codes(Inflate *s, const Huff *lit, const Huff *dist) {
for (;;) {
int sym = huff_decode(s, lit);
if (sym < 0) return -1;
if (sym < 256) {
if (s->at >= s->cap) return -1;
s->out[s->at++] = (uint8_t)sym;
continue;
}
if (sym == 256) return 0;
sym -= 257;
if (sym >= 29) return -1;
size_t len = len_base[sym] + get_bits(s, len_extra[sym]);
int d = huff_decode(s, dist);
if (d < 0 || d >= 30) return -1;
size_t back = dist_base[d] + get_bits(s, dist_extra[d]);
if (s->bad || back > s->at || len > s->cap - s->at) return -1;
for (size_t i = 0; i < len; i++, s->at++) s->out[s->at] = s->out[s->at - back]; // overlapping on purpose
}
}
static int inflate_stored(Inflate *s) {
s->bitbuf = 0, s->bitcnt = 0; // the rest of the current byte
if (s->n - s->pos < 4) return -1;
unsigned len = s->in[s->pos] | s->in[s->pos + 1] << 8, nlen = s->in[s->pos + 2] | s->in[s->pos + 3] << 8;
s->pos += 4;
if (len != (~nlen & 0xffffu) || len > s->n - s->pos || len > s->cap - s->at) return -1;
memcpy(s->out + s->at, s->in + s->pos, len);
s->pos += len, s->at += len;
return 0;
}
static int inflate_fixed(Inflate *s) {
static Huff lit, dist;
static volatile int built;
if (!built) { // two threads may build them at once: they write the same values
uint8_t l[288];
int i = 0;
for (; i < 144; i++) l[i] = 8;
for (; i < 256; i++) l[i] = 9;
for (; i < 280; i++) l[i] = 7;
for (; i < 288; i++) l[i] = 8;
huff_build(&lit, l, 288);
for (i = 0; i < 30; i++) l[i] = 5;
huff_build(&dist, l, 30);
__atomic_store_n(&built, 1, __ATOMIC_RELEASE);
}
return inflate_codes(s, &lit, &dist);
}
static int inflate_dynamic(Inflate *s) {
static const uint8_t order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
uint8_t lengths[320];
Huff lit, dist;
int nlen = (int)get_bits(s, 5) + 257, ndist = (int)get_bits(s, 5) + 1, ncode = (int)get_bits(s, 4) + 4;
if (s->bad || nlen > 286 || ndist > 30) return -1;
memset(lengths, 0, sizeof lengths);
for (int i = 0; i < ncode; i++) lengths[order[i]] = (uint8_t)get_bits(s, 3);
if (s->bad || huff_build(&lit, lengths, 19)) return -1; // the code lengths' own code, in lit for now
for (int i = 0; i < nlen + ndist;) {
int sym = huff_decode(s, &lit);
if (sym < 0) return -1;
if (sym < 16) {
lengths[i++] = (uint8_t)sym;
continue;
}
int repeat, value = 0;
if (sym == 16) {
if (!i) return -1;
value = lengths[i - 1];
repeat = 3 + (int)get_bits(s, 2);
} else if (sym == 17) {
repeat = 3 + (int)get_bits(s, 3);
} else {
repeat = 11 + (int)get_bits(s, 7);
}
if (s->bad || i + repeat > nlen + ndist) return -1;
while (repeat--) lengths[i++] = (uint8_t)value;
}
if (!lengths[256]) return -1; // a block without its end code
if (huff_build(&lit, lengths, nlen) || huff_build(&dist, lengths + nlen, ndist)) return -1;
return inflate_codes(s, &lit, &dist);
}
int sz_inflate(const uint8_t *src, size_t n, uint8_t *dst, size_t dst_n) {
Inflate s = {.in = src, .n = n, .out = dst, .cap = dst_n};
for (int last = 0; !last;) {
last = (int)get_bits(&s, 1);
int type = (int)get_bits(&s, 2), r;
if (s.bad) return -1;
if (type == 0) r = inflate_stored(&s);
else if (type == 1) r = inflate_fixed(&s);
else if (type == 2) r = inflate_dynamic(&s);
else r = -1;
if (r || s.bad) return -1;
}
return s.at == dst_n ? 0 : -1;
}
// ---- deflate: greedy LZ77 over a 32 KiB window (hash chains of 3-byte keys), the fixed Huffman codes
typedef struct {
uint8_t *out;
size_t at, cap;
uint64_t bitbuf;
int bitcnt;
} BitOut;
static void put_bits(BitOut *b, uint32_t v, int n) {
b->bitbuf |= (uint64_t)v << b->bitcnt;
b->bitcnt += n;
while (b->bitcnt >= 8) {
if (b->at < b->cap) b->out[b->at] = (uint8_t)b->bitbuf;
b->at++;
b->bitbuf >>= 8;
b->bitcnt -= 8;
}
}
// A Huffman code goes out from its first bit: reversed into the LSB-first stream.
static void put_code(BitOut *b, uint32_t code, int len) {
uint32_t r = 0;
for (int i = 0; i < len; i++) r |= ((code >> i) & 1u) << (len - 1 - i);
put_bits(b, r, len);
}
static void put_literal(BitOut *b, int sym) { // a literal/length symbol in the fixed code
if (sym < 144) put_code(b, 0x30u + (uint32_t)sym, 8);
else if (sym < 256) put_code(b, 0x190u + (uint32_t)(sym - 144), 9);
else if (sym < 280) put_code(b, (uint32_t)(sym - 256), 7);
else put_code(b, 0xc0u + (uint32_t)(sym - 280), 8);
}
static void put_match(BitOut *b, size_t len, size_t back) {
int i = 28;
while (len_base[i] > len) i--;
put_literal(b, 257 + i);
put_bits(b, (uint32_t)(len - len_base[i]), len_extra[i]);
int d = 29;
while (dist_base[d] > back) d--;
put_code(b, (uint32_t)d, 5);
put_bits(b, (uint32_t)(back - dist_base[d]), dist_extra[d]);
}
#define WINDOW 32768u
#define HASH_BITS 15
#define CHAIN 48 // candidates tried per position: logs repeat a lot, saves little
#define MAX_MATCH 258
uint8_t *sz_deflate(const uint8_t *src, size_t n, size_t *out_n) {
BitOut b = {.cap = n + n / 8 + 64}; // a literal takes at most 9 bits
b.out = malloc(b.cap);
int32_t *head = malloc(sizeof(int32_t) << HASH_BITS), *prev = malloc(sizeof(int32_t) * WINDOW);
if (!b.out || !head || !prev) {
free(b.out), free(head), free(prev);
return NULL;
}
for (size_t i = 0; i < (1u << HASH_BITS); i++) head[i] = -1;
put_bits(&b, 1, 1); // the last block
put_bits(&b, 1, 2); // fixed Huffman codes
#define HASH(p) ((((uint32_t)(p)[0] << 10) ^ ((uint32_t)(p)[1] << 5) ^ (p)[2]) & ((1u << HASH_BITS) - 1))
size_t i = 0;
while (i < n) {
size_t best = 0, back = 0;
if (n - i >= 3) {
uint32_t h = HASH(src + i);
int32_t cand = head[h];
size_t limit = n - i < MAX_MATCH ? n - i : MAX_MATCH;
for (int tries = 0; cand >= 0 && i - (size_t)cand <= WINDOW && tries < CHAIN; tries++) {
const uint8_t *a = src + cand, *c = src + i;
if (a[best] == c[best]) { // only a longer match can win
size_t k = 0;
while (k < limit && a[k] == c[k]) k++;
if (k > best) {
best = k, back = i - (size_t)cand;
if (k == limit) break;
}
}
int32_t next = prev[cand & (WINDOW - 1)];
if (next >= cand) break; // an older entry overwritten by a newer one
cand = next;
}
}
size_t step = best >= 3 ? best : 1;
if (best >= 3) put_match(&b, best, back);
else put_literal(&b, src[i]);
for (size_t k = 0; k < step; k++, i++) // every position covered goes into the chains
if (n - i >= 3) {
uint32_t h = HASH(src + i);
prev[i & (WINDOW - 1)] = head[h];
head[h] = (int32_t)i;
}
}
#undef HASH
put_literal(&b, 256);
put_bits(&b, 0, 7); // out to the byte
free(head), free(prev);
if (b.at > b.cap) { // cannot happen with the bound above; kept as the guard put_bits relies on
free(b.out);
return NULL;
}
*out_n = b.at;
return b.out;
}
// ---- writing a zip
static void put16(uint8_t *p, unsigned v) { p[0] = (uint8_t)v, p[1] = (uint8_t)(v >> 8); }
static void put32(uint8_t *p, uint32_t v) { put16(p, v & 0xffff), put16(p + 2, v >> 16); }
static unsigned get16(const uint8_t *p) { return p[0] | p[1] << 8; }
static uint32_t get32(const uint8_t *p) { return get16(p) | (uint32_t)get16(p + 2) << 16; }
static uint8_t *room(SzWriter *w, size_t k) {
if (w->failed) return NULL;
if (w->n + k > 0xffffffffu) { // offsets and sizes are 32-bit without the 64-bit extension
w->failed = 1;
return NULL;
}
if (w->n + k > w->cap) {
size_t cap = w->cap ? w->cap : 1 << 16;
while (cap < w->n + k) cap *= 2;
uint8_t *nb = realloc(w->buf, cap);
if (!nb) {
w->failed = 1;
return NULL;
}
w->buf = nb, w->cap = cap;
}
uint8_t *p = w->buf + w->n;
w->n += k;
return p;
}
void sz_writer_init(SzWriter *w, int year, int month, int day, int hour, int minute, int second) {
memset(w, 0, sizeof *w);
if (year < 1980) year = 1980, month = 1, day = 1, hour = minute = second = 0;
w->dos_time = (uint16_t)(hour << 11 | minute << 5 | second / 2);
w->dos_date = (uint16_t)((year - 1980) << 9 | month << 5 | day);
}
void sz_writer_add(SzWriter *w, const char *name, const void *data, size_t n) {
if (w->failed) return;
size_t name_n = strlen(name);
if (n > 0xffffffffu || name_n >= 0xffff) {
w->failed = 1;
return;
}
if (w->count == w->cap_m) {
int cap = w->cap_m ? w->cap_m * 2 : 32;
SzMember *m = realloc(w->m, (size_t)cap * sizeof *m);
if (!m) {
w->failed = 1;
return;
}
w->m = m, w->cap_m = cap;
}
SzMember *m = &w->m[w->count];
m->name = malloc(name_n + 1);
if (!m->name) {
w->failed = 1;
return;
}
memcpy(m->name, name, name_n + 1);
w->count++;
m->crc = sz_crc32(0, data, n);
m->usize = (uint32_t)n;
size_t packed_n = 0;
uint8_t *packed = n >= 64 ? sz_deflate(data, n, &packed_n) : NULL;
if (packed && packed_n >= n) free(packed), packed = NULL; // stored when deflate does not help
m->method = packed ? 8 : 0;
m->csize = (uint32_t)(packed ? packed_n : n);
m->offset = (uint32_t)w->n;
uint8_t *h = room(w, 30 + name_n);
if (h) {
put32(h, 0x04034b50);
put16(h + 4, 20); // version needed: deflate
put16(h + 6, 0);
put16(h + 8, m->method);
put16(h + 10, w->dos_time);
put16(h + 12, w->dos_date);
put32(h + 14, m->crc);
put32(h + 18, m->csize);
put32(h + 22, m->usize);
put16(h + 26, (unsigned)name_n);
put16(h + 28, 0);
memcpy(h + 30, name, name_n);
}
uint8_t *d = room(w, m->csize);
if (d && m->csize) memcpy(d, packed ? packed : data, m->csize);
free(packed);
}
uint8_t *sz_writer_finish(SzWriter *w, size_t *n) {
size_t cd_at = w->n;
for (int i = 0; i < w->count && !w->failed; i++) {
SzMember *m = &w->m[i];
size_t name_n = strlen(m->name);
uint8_t *c = room(w, 46 + name_n);
if (!c) break;
put32(c, 0x02014b50);
put16(c + 4, 20); // made by: MS-DOS attributes, version 2.0
put16(c + 6, 20);
put16(c + 8, 0);
put16(c + 10, m->method);
put16(c + 12, w->dos_time);
put16(c + 14, w->dos_date);
put32(c + 16, m->crc);
put32(c + 20, m->csize);
put32(c + 24, m->usize);
put16(c + 28, (unsigned)name_n);
put16(c + 30, 0); // extra
put16(c + 32, 0); // comment
put16(c + 34, 0); // disk
put16(c + 36, 0); // internal attributes
put32(c + 38, 0); // external attributes
put32(c + 42, m->offset);
memcpy(c + 46, m->name, name_n);
}
size_t cd_n = w->n - cd_at;
uint8_t *e = w->count < 0xffff ? room(w, 22) : (w->failed = 1, NULL);
if (e) {
put32(e, 0x06054b50);
put16(e + 4, 0);
put16(e + 6, 0);
put16(e + 8, (unsigned)w->count);
put16(e + 10, (unsigned)w->count);
put32(e + 12, (uint32_t)cd_n);
put32(e + 16, (uint32_t)cd_at);
put16(e + 20, 0);
}
for (int i = 0; i < w->count; i++) free(w->m[i].name);
free(w->m);
uint8_t *out = w->failed ? NULL : w->buf;
if (w->failed) free(w->buf);
*n = w->failed ? 0 : w->n;
memset(w, 0, sizeof *w);
return out;
}
// ---- reading a zip
int sz_read_dir(const uint8_t *zip, size_t n, SzEntry **out, int *count) {
*out = NULL, *count = 0;
if (n < 22) return SZ_E_NOT_ZIP;
// the end record: its signature within the last 22 bytes plus the longest comment
size_t e = n - 22, stop = n > 22 + 0xffff ? n - 22 - 0xffff : 0;
while (get32(zip + e) != 0x06054b50 || 22 + get16(zip + e + 20) != n - e) {
if (e == stop) return SZ_E_NOT_ZIP;
e--;
}
unsigned total = get16(zip + e + 10);
uint32_t cd_n = get32(zip + e + 12), cd_at = get32(zip + e + 16);
if (get16(zip + e + 4) || get16(zip + e + 6) || get16(zip + e + 8) != total) return SZ_E_UNSUPPORTED; // spanned
if (total == 0xffff || cd_n == 0xffffffffu || cd_at == 0xffffffffu) return SZ_E_UNSUPPORTED; // the 64-bit zip
if (cd_at > e || cd_n > e - cd_at) return SZ_E_DAMAGED;
SzEntry *list = calloc(total ? total : 1, sizeof *list);
if (!list) return SZ_E_MEMORY;
size_t p = cd_at;
int r = SZ_OK;
for (unsigned i = 0; i < total && r == SZ_OK; i++) {
if (p + 46 > cd_at + cd_n || get32(zip + p) != 0x02014b50) {
r = SZ_E_DAMAGED;
break;
}
const uint8_t *c = zip + p;
unsigned made_by = get16(c + 4), flags = get16(c + 8), name_n = get16(c + 28);
size_t next = p + 46 + name_n + get16(c + 30) + get16(c + 32);
uint32_t ext = get32(c + 38), local = get32(c + 42);
SzEntry *en = &list[i];
en->method = (uint16_t)get16(c + 10);
en->crc = get32(c + 16);
en->csize = get32(c + 20);
en->usize = get32(c + 24);
if (next > cd_at + cd_n) r = SZ_E_DAMAGED;
else if (flags & 1 || (en->method != 0 && en->method != 8) || name_n >= sizeof en->name ||
en->csize == 0xffffffffu || en->usize == 0xffffffffu || local == 0xffffffffu)
r = SZ_E_UNSUPPORTED; // encrypted, another method, a long name, a 64-bit member
if (r) break;
memcpy(en->name, c + 46, name_n);
en->name[name_n] = 0;
if (memchr(en->name, 0, name_n)) {
r = SZ_E_DAMAGED;
break;
}
en->is_dir = name_n && en->name[name_n - 1] == '/';
en->is_link = (made_by >> 8) == 3 && ((ext >> 16) & 0170000) == 0120000; // Unix: S_IFLNK
if (local > cd_at || cd_at - local < 30 || get32(zip + local) != 0x04034b50) {
r = SZ_E_DAMAGED;
break;
}
uint64_t data = (uint64_t)local + 30 + get16(zip + local + 26) + get16(zip + local + 28);
if (data > cd_at || en->csize > cd_at - data) {
r = SZ_E_DAMAGED;
break;
}
en->data = data;
p = next;
}
if (r) {
free(list);
return r;
}
*out = list, *count = (int)total;
return SZ_OK;
}
uint8_t *sz_extract(const uint8_t *zip, size_t n, const SzEntry *e, int *err) {
if (e->data > n || e->csize > n - e->data || e->usize > (uint64_t)SIZE_MAX - 1) {
*err = SZ_E_DAMAGED;
return NULL;
}
uint8_t *out = malloc((size_t)e->usize + 1);
if (!out) {
*err = SZ_E_MEMORY;
return NULL;
}
const uint8_t *src = zip + e->data;
int bad = e->method == 0 ? e->csize != e->usize : sz_inflate(src, (size_t)e->csize, out, (size_t)e->usize) != 0;
if (!bad && e->method == 0) memcpy(out, src, (size_t)e->usize);
if (!bad && sz_crc32(0, out, (size_t)e->usize) != e->crc) bad = 1;
if (bad) {
free(out);
*err = SZ_E_DAMAGED;
return NULL;
}
out[e->usize] = 0;
*err = SZ_OK;
return out;
}
// ---- the manifest's JSON
static const char *ws(const char *p) {
while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
return p;
}
static int hex4(const char *p) {
int v = 0;
for (int i = 0; i < 4; i++) {
char c = p[i];
int d = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
if (d < 0) return -1;
v = v << 4 | d;
}
return v;
}
// The string at p (its opening quote) into out (NULL: skipped); *cut set when it did not fit. The byte after its
// closing quote, NULL when it is not a string.
static const char *json_string(const char *p, char *out, size_t cap, int *cut) {
if (*p++ != '"') return NULL;
size_t k = 0;
for (;;) {
char c = *p++;
if (!c || (unsigned char)c < 0x20) return NULL;
if (c == '"') break;
if (c == '\\') {
char esc = *p++;
switch (esc) {
case '"': case '\\': case '/': c = esc; break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
case 'u': {
int v = hex4(p);
if (v < 0) return NULL;
p += 4;
c = v > 0 && v < 0x80 ? (char)v : '?';
break;
}
default: return NULL;
}
}
if (out && k + 1 < cap) out[k++] = c;
else if (out && cut) *cut = 1;
}
if (out && cap) out[k] = 0;
return p;
}
// Past one value: a string, an object or array (nested), or a number or literal.
static const char *json_skip(const char *p) {
if (*p == '"') return json_string(p, NULL, 0, NULL);
if (*p == '{' || *p == '[') {
int depth = 0;
while (*p) {
if (*p == '"') {
p = json_string(p, NULL, 0, NULL);
if (!p) return NULL;
continue;
}
if (*p == '{' || *p == '[') depth++;
else if ((*p == '}' || *p == ']') && !--depth) return p + 1;
p++;
}
return NULL;
}
const char *s = p;
while (*p && *p != ',' && *p != '}' && *p != ']' && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n') p++;
return p > s ? p : NULL;
}
// The value of key at the top level of the object json, NULL when it has none.
static const char *json_find(const char *json, const char *key) {
const char *p = ws(json);
if (*p++ != '{') return NULL;
for (;;) {
p = ws(p);
char k[128];
int cut = 0;
p = json_string(p, k, sizeof k, &cut);
if (!p) return NULL;
p = ws(p);
if (*p++ != ':') return NULL;
p = ws(p);
if (!cut && !strcmp(k, key)) return p;
p = json_skip(p);
if (!p) return NULL;
p = ws(p);
if (*p++ != ',') return NULL;
}
}
int sz_json_str(const char *json, const char *key, char *out, size_t cap) {
const char *v = json_find(json, key);
return v && *v == '"' && json_string(v, out, cap, NULL) != NULL;
}
int sz_json_int(const char *json, const char *key, long long *out) {
const char *v = json_find(json, key);
if (!v) return 0;
int neg = *v == '-';
v += neg;
if (*v < '0' || *v > '9') return 0;
long long r = 0;
for (; *v >= '0' && *v <= '9'; v++) {
if (r > (0x7fffffffffffffffll - 9) / 10) return 0;
r = r * 10 + (*v - '0');
}
if (*v == '.' || *v == 'e' || *v == 'E') return 0;
*out = neg ? -r : r;
return 1;
}
char *sz_json_escape(const char *s, char *out, size_t cap) {
static const char hex[] = "0123456789abcdef";
size_t k = 0;
for (; *s; s++) {
unsigned char c = (unsigned char)*s;
char tmp[7];
size_t m = 0;
if (c == '"' || c == '\\') tmp[m++] = '\\', tmp[m++] = (char)c;
else if (c < 0x20) tmp[m++] = '\\', tmp[m++] = 'u', tmp[m++] = '0', tmp[m++] = '0', tmp[m++] = hex[c >> 4],
tmp[m++] = hex[c & 15];
else tmp[m++] = (char)c;
if (k + m >= cap) break;
memcpy(out + k, tmp, m);
k += m;
}
if (cap) out[k] = 0;
return out;
}

70
runtime/save_zip.h Normal file
View File

@@ -0,0 +1,70 @@
// The zip file of a shared save (save_share.c; the launcher writes and reads the same file, launcher/saves.py
// export_save): a zip in memory with stored or deflated members, its members read back with their CRC-32 checked, raw
// deflate both ways, and the top-level keys of its manifest.json. Plain C on the C library alone, so
// tests/save_zip_check.py builds it by itself and checks it against Python's zipfile and zlib.
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
uint32_t sz_crc32(uint32_t crc, const void *data, size_t n); // the zip CRC-32; crc 0 to start, the last result to go on
// Raw deflate (RFC 1951) of src[0..n): one block of the fixed Huffman codes over LZ77 matches. A malloc'd buffer of
// *out_n bytes, NULL when out of memory.
uint8_t *sz_deflate(const uint8_t *src, size_t n, size_t *out_n);
// Raw deflate data src[0..n) into exactly dst_n bytes at dst: stored, fixed and dynamic blocks. 0 on success, -1 when
// the data is damaged, ends early or holds another number of bytes.
int sz_inflate(const uint8_t *src, size_t n, uint8_t *dst, size_t dst_n);
// ---- writing: the members go into one buffer as they come, then the central directory after them
typedef struct {
char *name;
uint32_t crc, csize, usize, offset;
uint16_t method;
} SzMember;
typedef struct {
uint8_t *buf;
size_t n, cap;
SzMember *m;
int count, cap_m;
int failed; // out of memory, or past the 4 GiB a zip without its 64-bit extension holds
uint16_t dos_time, dos_date;
} SzWriter;
// Every member gets this local time (the zip's DOS time stamp, two-second steps).
void sz_writer_init(SzWriter *w, int year, int month, int day, int hour, int minute, int second);
// A member: name relative with '/' separators, its bytes deflated when that makes them smaller, else stored.
void sz_writer_add(SzWriter *w, const char *name, const void *data, size_t n);
// The whole archive (*n bytes; the caller frees it), NULL when any add failed. Frees the writer's own memory either way.
uint8_t *sz_writer_finish(SzWriter *w, size_t *n);
// ---- reading
enum { SZ_OK, SZ_E_NOT_ZIP, SZ_E_DAMAGED, SZ_E_UNSUPPORTED, SZ_E_MEMORY };
typedef struct {
char name[256]; // as stored: '/' separators
uint32_t crc;
uint64_t csize, usize, data; // data: the offset of its bytes in the zip
uint16_t method;
int is_dir, is_link; // a folder entry (name ends in '/'); a symbolic link (a Unix mode in its attributes)
} SzEntry;
// The members of the zip zip[0..n) from its central directory: a malloc'd array in *out (the caller frees it) and its
// length in *count. SZ_OK or why not: not a zip, damaged, or what this reader leaves out (encryption, a 64-bit zip, a
// method but stored and deflate, a name of 256 bytes or more).
int sz_read_dir(const uint8_t *zip, size_t n, SzEntry **out, int *count);
// The bytes of member e, checked against its CRC-32: malloc'd with a NUL after them (the caller frees them), NULL with
// *err set to the SZ_E_* reason.
uint8_t *sz_extract(const uint8_t *zip, size_t n, const SzEntry *e, int *err);
// ---- the manifest: a JSON object whose values the reader needs are strings and integers at its top level
// The string value of key into out (cut to cap - 1 bytes; \u escapes outside ASCII become '?'). 1 when found.
int sz_json_str(const char *json, const char *key, char *out, size_t cap);
// The integer value of key. 1 when found and an integer.
int sz_json_int(const char *json, const char *key, long long *out);
// s as the inside of a JSON string ('"', '\' and control characters escaped) into out, cut to fit cap. Returns out.
char *sz_json_escape(const char *s, char *out, size_t cap);
#ifdef __cplusplus
}
#endif

View File

@@ -43,12 +43,14 @@ extern "C" {
#include "amiibo.h"
#include "cheats.h"
#include "cfg.h"
#include "folder_pick.h"
#include "fs.h"
#include "input.h"
#include "input_map.h"
#include "mods.h"
#include "perfmon.h"
#include "platform/platform.h"
#include "save_share.h"
#include "sysinfo.h"
#include "ui/menu.h"
#include "ui_text.h"
@@ -980,6 +982,105 @@ static void tab_screen(float scale) {
opt_end();
}
// ---- the Game tab's Saves group (save_share.c). Export writes the save the game would load next into a zip in the
// player's Downloads folder, for another player or, with this run's log and nx2navi.ini, a bug report. Import takes a
// zip the player picks in the host's file dialog and leaves its save for the next start (fs_host.c import_pending): the
// game holds its progress in memory and would write it back over a save replaced under it. The work runs off the
// present thread (a thread of its own, or the dialog's); the rows wait greyed meanwhile, and the line under them says
// what the last one did, else what an import did at this start.
static PlatMutex g_share_lock = PLAT_MUTEX_INIT;
static std::atomic<int> g_share_busy{0};
static int g_share_text = -1; // the last result's UiTextId, -1 none; a format that takes g_share_arg
static char g_share_arg[PLAT_PATH_MAX + 64];
static bool g_share_warn;
static void share_done(UiTextId text, const char *arg, bool warn) {
plat_mutex_lock(&g_share_lock);
g_share_text = text;
snprintf(g_share_arg, sizeof g_share_arg, "%s", arg ? arg : "");
g_share_warn = warn;
plat_mutex_unlock(&g_share_lock);
g_share_busy.store(0);
}
static void share_export_main(void *arg) {
const int bug_report = (int)(intptr_t)arg;
char dir[PLAT_PATH_MAX], path[PLAT_PATH_MAX + 64];
SaveShareResult r = save_share_default_dir(dir, sizeof dir) ? save_share_export(dir, bug_report, path, sizeof path)
: SAVE_SHARE_WRITE_FAILED;
if (r == SAVE_SHARE_OK) share_done(UI_MENU_SAVE_EXPORTED, path, false);
else share_done(r == SAVE_SHARE_NO_SAVE ? UI_MENU_SAVE_E_NO_SAVE : r == SAVE_SHARE_READ_FAILED ? UI_MENU_SAVE_E_READ_SAVE
: UI_MENU_SAVE_E_WRITE,
dir, true);
}
// The file dialog's answer, on its thread: the import's checks and the copy into the profile run here.
static void share_zip_picked(const char *path, void *ctx) {
(void)ctx;
if (!path) { // cancelled: the last line stays
g_share_busy.store(0);
return;
}
char detail[160];
SaveShareResult r = save_share_import(path, detail, sizeof detail);
UiTextId text;
switch (r) {
case SAVE_SHARE_OK: text = UI_MENU_SAVE_IMPORT_READY; break;
case SAVE_SHARE_READ_FAILED: text = UI_MENU_SAVE_E_READ; break;
case SAVE_SHARE_WRITE_FAILED: text = UI_MENU_SAVE_E_STAGE; break;
case SAVE_SHARE_OTHER_GAME: text = UI_MENU_SAVE_E_OTHER_GAME; break;
case SAVE_SHARE_NEWER: text = UI_MENU_SAVE_E_NEWER; break;
case SAVE_SHARE_DAMAGED: text = UI_MENU_SAVE_E_DAMAGED; break;
case SAVE_SHARE_UNSAFE: text = UI_MENU_SAVE_E_UNSAFE; break;
default: text = UI_MENU_SAVE_E_NOT_SAVE; break;
}
share_done(text, r == SAVE_SHARE_OK ? detail : path, r != SAVE_SHARE_OK);
}
static void rows_saves(void) {
opt_group(UI_MENU_SAVES);
const bool busy = g_share_busy.load() != 0;
int start = 0; // 1 export, 2 export for a bug report, 3 import
if (busy) opt_disable_next(UI_MENU_SAVE_BUSY);
if (opt_button("##save_export", UI_MENU_SAVE_EXPORT, UI_MENU_SAVE_EXPORT_DESC)) start = 1;
if (busy) opt_disable_next(UI_MENU_SAVE_BUSY);
if (opt_button("##save_export_bug", UI_MENU_SAVE_EXPORT_BUG, UI_MENU_SAVE_EXPORT_BUG_DESC)) start = 2;
// a stat per frame while the Game tab shows; the launcher's own import drops a waiting one
const bool waiting = save_share_pending() != 0;
if (busy) opt_disable_next(UI_MENU_SAVE_BUSY);
if (opt_button("##save_import", UI_MENU_SAVE_IMPORT, UI_MENU_SAVE_IMPORT_DESC,
waiting ? menu_text(UI_MENU_SAVE_IMPORT_WAITING) : ""))
start = 3;
if (waiting) {
if (busy) opt_disable_next(UI_MENU_SAVE_BUSY);
if (opt_button("##save_import_cancel", UI_MENU_SAVE_IMPORT_CANCEL, UI_MENU_SAVE_IMPORT_CANCEL_DESC)) {
if (save_share_cancel()) share_done(UI_MENU_SAVE_E_STAGE, "", true);
else share_done(UI_MENU_SAVE_IMPORT_CANCELLED, "", false);
}
}
if (start && !busy) {
g_share_busy.store(1);
if (start == 3) {
char dir[PLAT_PATH_MAX];
file_pick(save_share_default_dir(dir, sizeof dir) ? dir : "", "zip", share_zip_picked, NULL);
} else if (!plat_thread_spawn(share_export_main, (void *)(intptr_t)(start == 2), "save export", 0)) {
share_done(UI_MENU_SAVE_E_READ_SAVE, "", true);
}
}
char line[PLAT_PATH_MAX * 2] = "";
plat_mutex_lock(&g_share_lock);
bool warn = g_share_warn;
if (g_share_text >= 0) snprintf(line, sizeof line, menu_text((UiTextId)g_share_text), g_share_arg);
plat_mutex_unlock(&g_share_lock);
const char *done = fs_save_import_done();
if (!line[0] && *done) {
if (!strcmp(done, "-")) snprintf(line, sizeof line, "%s", menu_text(UI_MENU_SAVE_IMPORTED_NEW));
else snprintf(line, sizeof line, menu_text(UI_MENU_SAVE_IMPORTED), done);
warn = false;
}
if (line[0]) opt_text_str(line, warn);
}
static void tab_game(float scale) {
opt_begin("##game", scale);
row_fps_limit(); // frame_rate.c: Ocarina steps by the clock, so the pacer alone sets its rate
@@ -989,6 +1090,7 @@ static void tab_game(float scale) {
opt_toggle("NX2NAVI_ASSUME_FOCUS", UI_MENU_ASSUME_FOCUS, UI_MENU_ASSUME_FOCUS_DESC);
// discord_rpc.c reads the setting on its own thread and connects or clears the status within half a second
opt_toggle("NX2NAVI_DISCORD_RPC", UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC);
rows_saves();
opt_end();
}

View File

@@ -507,6 +507,37 @@ static const char *const text_en[UI_TEXT_COUNT] = {
"now.",
[UI_MENU_CHEAT_UNSUPPORTED] = "not supported",
[UI_MENU_CHEAT_UNSUPPORTED_DESC] = "This cheat cannot be used with this version of the game:",
[UI_MENU_SAVES] = "Saves",
[UI_MENU_SAVE_EXPORT] = "Export save",
[UI_MENU_SAVE_EXPORT_DESC] = "Writes your save (every slot) into one zip file in your Downloads folder, to give to "
"another player or attach to a bug report. It never holds your keys or game files.",
[UI_MENU_SAVE_EXPORT_BUG] = "Export save for a bug report",
[UI_MENU_SAVE_EXPORT_BUG_DESC] = "The same zip with this run's log and your settings (nx2navi.ini) added, which "
"show what happened and with which settings. Attach it to your bug report.",
[UI_MENU_SAVE_IMPORT] = "Import a save",
[UI_MENU_SAVE_IMPORT_DESC] = "Choose a save someone shared (an NX2navi-save zip). It replaces your save, every slot, "
"at the next start: the game keeps your progress in memory and would write it back "
"over a save replaced now. Your current save is copied to the saves folder first.",
[UI_MENU_SAVE_IMPORT_WAITING] = "at next start",
[UI_MENU_SAVE_IMPORT_CANCEL] = "Cancel the import",
[UI_MENU_SAVE_IMPORT_CANCEL_DESC] = "Keeps your save as it is: the save waiting for the next start is dropped.",
[UI_MENU_SAVE_BUSY] = "working…",
[UI_MENU_SAVE_EXPORTED] = "Saved as %s",
[UI_MENU_SAVE_IMPORT_READY] = "The save (NX2navi %s) loads at the next start: select Restart below. Your current "
"save is copied to the saves folder first.",
[UI_MENU_SAVE_IMPORT_CANCELLED] = "Import cancelled; your save stays as it is.",
[UI_MENU_SAVE_IMPORTED] = "A shared save was imported at this start. Your old save is in %s",
[UI_MENU_SAVE_IMPORTED_NEW] = "A shared save was imported at this start.",
[UI_MENU_SAVE_E_NO_SAVE] = "There is no save to export yet: play until the game saves.",
[UI_MENU_SAVE_E_READ_SAVE] = "A file of your save could not be read; try again in a moment.",
[UI_MENU_SAVE_E_WRITE] = "The zip could not be written into %s.",
[UI_MENU_SAVE_E_READ] = "%s could not be read.",
[UI_MENU_SAVE_E_STAGE] = "The save could not be prepared for the next start; the log says why.",
[UI_MENU_SAVE_E_NOT_SAVE] = "%s is not a save NX2navi exported.",
[UI_MENU_SAVE_E_OTHER_GAME] = "%s is a save of another game.",
[UI_MENU_SAVE_E_NEWER] = "%s was made by a newer NX2navi: update NX2navi first.",
[UI_MENU_SAVE_E_DAMAGED] = "%s is damaged: download it again.",
[UI_MENU_SAVE_E_UNSAFE] = "%s was refused: it holds files outside a save, links, or far more than a save.",
[UI_BOOT_TITLE] = "Preparing shaders",
[UI_BOOT_STARTING] = "Starting", [UI_BOOT_SHADERS] = "Shaders: %lld of %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld of %lld",
[UI_MENU_UPSCALING] = "Upscaling",
@@ -1019,6 +1050,40 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
"его при следующем запуске (несколько минут), или нажмите «Пересобрать игру сейчас».",
[UI_MENU_CHEAT_UNSUPPORTED] = "не поддерживается",
[UI_MENU_CHEAT_UNSUPPORTED_DESC] = "Этот чит нельзя использовать с этой версией игры:",
[UI_MENU_SAVES] = "Сохранения",
[UI_MENU_SAVE_EXPORT] = "Экспорт сохранения",
[UI_MENU_SAVE_EXPORT_DESC] = "Записывает ваше сохранение (все слоты) в один zip-файл в папке «Загрузки», чтобы "
"передать его другому игроку или приложить к сообщению об ошибке. Ключи и файлы игры "
"в него не попадают.",
[UI_MENU_SAVE_EXPORT_BUG] = "Экспорт для сообщения об ошибке",
[UI_MENU_SAVE_EXPORT_BUG_DESC] = "Тот же zip с журналом этого запуска и вашими настройками (nx2navi.ini): по ним "
"видно, что произошло и с какими настройками. Приложите его к сообщению об ошибке.",
[UI_MENU_SAVE_IMPORT] = "Импорт сохранения",
[UI_MENU_SAVE_IMPORT_DESC] = "Выберите сохранение, которым с вами поделились (zip NX2navi-save). Оно заменит ваше "
"сохранение, все слоты, при следующем запуске: игра держит прогресс в памяти и "
"записала бы его поверх сохранения, заменённого сейчас. Текущее сохранение сначала "
"копируется в папку saves.",
[UI_MENU_SAVE_IMPORT_WAITING] = "при следующем запуске",
[UI_MENU_SAVE_IMPORT_CANCEL] = "Отменить импорт",
[UI_MENU_SAVE_IMPORT_CANCEL_DESC] = "Оставляет ваше сохранение как есть: сохранение, ждущее следующего запуска, "
"удаляется.",
[UI_MENU_SAVE_BUSY] = "выполняется…",
[UI_MENU_SAVE_EXPORTED] = "Сохранено: %s",
[UI_MENU_SAVE_IMPORT_READY] = "Сохранение (NX2navi %s) загрузится при следующем запуске: выберите «Перезапустить» "
"внизу. Текущее сохранение сначала копируется в папку saves.",
[UI_MENU_SAVE_IMPORT_CANCELLED] = "Импорт отменён, ваше сохранение не изменилось.",
[UI_MENU_SAVE_IMPORTED] = "При этом запуске импортировано сохранение. Прежнее сохранение лежит в %s",
[UI_MENU_SAVE_IMPORTED_NEW] = "При этом запуске импортировано сохранение.",
[UI_MENU_SAVE_E_NO_SAVE] = "Экспортировать пока нечего: играйте, пока игра не сохранится.",
[UI_MENU_SAVE_E_READ_SAVE] = "Не удалось прочитать файл сохранения; попробуйте ещё раз чуть позже.",
[UI_MENU_SAVE_E_WRITE] = "Не удалось записать zip в %s.",
[UI_MENU_SAVE_E_READ] = "Не удалось прочитать %s.",
[UI_MENU_SAVE_E_STAGE] = "Не удалось подготовить сохранение к следующему запуску; причина указана в журнале.",
[UI_MENU_SAVE_E_NOT_SAVE] = "%s — не сохранение, экспортированное NX2navi.",
[UI_MENU_SAVE_E_OTHER_GAME] = "%s — сохранение другой игры.",
[UI_MENU_SAVE_E_NEWER] = "%s создан более новой версией NX2navi: сначала обновите NX2navi.",
[UI_MENU_SAVE_E_DAMAGED] = "%s повреждён: скачайте его заново.",
[UI_MENU_SAVE_E_UNSAFE] = "%s отклонён: в нём файлы вне сохранения, ссылки или слишком много данных.",
[UI_BOOT_TITLE] = "Подготовка шейдеров",
[UI_BOOT_STARTING] = "Запуск", [UI_BOOT_SHADERS] = "Шейдеры: %lld из %lld", [UI_BOOT_PIPELINES] = "Конвейеры: %lld из %lld",
[UI_MENU_CHEATS_REBUILD] = "Пересобрать игру сейчас",
@@ -1526,6 +1591,40 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
"Recompilar o jogo agora.",
[UI_MENU_CHEAT_UNSUPPORTED] = "não suportado",
[UI_MENU_CHEAT_UNSUPPORTED_DESC] = "Este cheat não pode ser usado com esta versão do jogo:",
[UI_MENU_SAVES] = "Saves",
[UI_MENU_SAVE_EXPORT] = "Exportar save",
[UI_MENU_SAVE_EXPORT_DESC] = "Grava seu save (todos os slots) em um arquivo zip na pasta Downloads, para passar a "
"outro jogador ou anexar a um relato de bug. Ele nunca contém suas chaves nem arquivos "
"do jogo.",
[UI_MENU_SAVE_EXPORT_BUG] = "Exportar para relato de bug",
[UI_MENU_SAVE_EXPORT_BUG_DESC] = "O mesmo zip com o log desta execução e suas configurações (nx2navi.ini), que "
"mostram o que aconteceu e com quais configurações. Anexe-o ao seu relato de bug.",
[UI_MENU_SAVE_IMPORT] = "Importar save",
[UI_MENU_SAVE_IMPORT_DESC] = "Escolha um save que alguém compartilhou (um zip NX2navi-save). Ele substitui seu save, "
"todos os slots, na próxima inicialização: o jogo mantém seu progresso na memória e o "
"gravaria por cima de um save substituído agora. Seu save atual é copiado antes para a "
"pasta saves.",
[UI_MENU_SAVE_IMPORT_WAITING] = "na próxima inicialização",
[UI_MENU_SAVE_IMPORT_CANCEL] = "Cancelar a importação",
[UI_MENU_SAVE_IMPORT_CANCEL_DESC] = "Mantém seu save como está: o save que aguardava a próxima inicialização é "
"descartado.",
[UI_MENU_SAVE_BUSY] = "trabalhando…",
[UI_MENU_SAVE_EXPORTED] = "Salvo como %s",
[UI_MENU_SAVE_IMPORT_READY] = "O save (NX2navi %s) é carregado na próxima inicialização: selecione Reiniciar abaixo. "
"Seu save atual é copiado antes para a pasta saves.",
[UI_MENU_SAVE_IMPORT_CANCELLED] = "Importação cancelada; seu save continua como estava.",
[UI_MENU_SAVE_IMPORTED] = "Um save compartilhado foi importado nesta inicialização. Seu save anterior está em %s",
[UI_MENU_SAVE_IMPORTED_NEW] = "Um save compartilhado foi importado nesta inicialização.",
[UI_MENU_SAVE_E_NO_SAVE] = "Ainda não há save para exportar: jogue até o jogo salvar.",
[UI_MENU_SAVE_E_READ_SAVE] = "Um arquivo do seu save não pôde ser lido; tente de novo daqui a pouco.",
[UI_MENU_SAVE_E_WRITE] = "Não foi possível gravar o zip em %s.",
[UI_MENU_SAVE_E_READ] = "Não foi possível ler %s.",
[UI_MENU_SAVE_E_STAGE] = "Não foi possível preparar o save para a próxima inicialização; o log diz o motivo.",
[UI_MENU_SAVE_E_NOT_SAVE] = "%s não é um save exportado pelo NX2navi.",
[UI_MENU_SAVE_E_OTHER_GAME] = "%s é um save de outro jogo.",
[UI_MENU_SAVE_E_NEWER] = "%s foi feito por um NX2navi mais novo: atualize o NX2navi primeiro.",
[UI_MENU_SAVE_E_DAMAGED] = "%s está danificado: baixe-o de novo.",
[UI_MENU_SAVE_E_UNSAFE] = "%s foi recusado: contém arquivos fora de um save, links ou dados demais.",
[UI_BOOT_TITLE] = "Preparando shaders",
[UI_BOOT_STARTING] = "Iniciando", [UI_BOOT_SHADERS] = "Shaders: %lld de %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld de %lld",
[UI_MENU_CHEATS_REBUILD] = "Recompilar o jogo agora",
@@ -2130,6 +2229,37 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_CHEAT_REBUILD_DESC] = "此金手指修改游戏代码,并且是在游戏构建后新增或修改的。游戏会在下次启动时把它构建进去(几分钟),也可以使用“立即重新构建游戏”。",
[UI_MENU_CHEAT_UNSUPPORTED] = "不支持",
[UI_MENU_CHEAT_UNSUPPORTED_DESC] = "此金手指不能用于此游戏版本:",
[UI_MENU_SAVES] = "存档",
[UI_MENU_SAVE_EXPORT] = "导出存档",
[UI_MENU_SAVE_EXPORT_DESC] = "将你的存档(所有存档位)写入“下载”文件夹中的一个 zip 文件,可分享给其他玩家或附在错误报告中。"
"其中不含你的密钥和游戏文件。",
[UI_MENU_SAVE_EXPORT_BUG] = "导出存档用于错误报告",
[UI_MENU_SAVE_EXPORT_BUG_DESC] = "同样的 zip,另附本次运行的日志和你的设置(nx2navi.ini),可看出发生了什么以及使用了哪些"
"设置。请将其附在错误报告中。",
[UI_MENU_SAVE_IMPORT] = "导入存档",
[UI_MENU_SAVE_IMPORT_DESC] = "选择别人分享的存档(NX2navi-save zip)。它会在下次启动时替换你的存档(所有存档位):游戏"
"把进度保存在内存中,若现在替换,游戏会把进度写回并覆盖它。你当前的存档会先复制到 saves "
"文件夹。",
[UI_MENU_SAVE_IMPORT_WAITING] = "下次启动时",
[UI_MENU_SAVE_IMPORT_CANCEL] = "取消导入",
[UI_MENU_SAVE_IMPORT_CANCEL_DESC] = "保留你的存档不变:丢弃等待下次启动的存档。",
[UI_MENU_SAVE_BUSY] = "处理中…",
[UI_MENU_SAVE_EXPORTED] = "已保存为 %s",
[UI_MENU_SAVE_IMPORT_READY] = "该存档(NX2navi %s)将在下次启动时载入:请选择下方的“重启”。你当前的存档会先复制到 saves "
"文件夹。",
[UI_MENU_SAVE_IMPORT_CANCELLED] = "已取消导入,你的存档保持不变。",
[UI_MENU_SAVE_IMPORTED] = "本次启动时已导入分享的存档。你原来的存档在 %s",
[UI_MENU_SAVE_IMPORTED_NEW] = "本次启动时已导入分享的存档。",
[UI_MENU_SAVE_E_NO_SAVE] = "还没有可导出的存档:请先游玩直到游戏存档。",
[UI_MENU_SAVE_E_READ_SAVE] = "无法读取存档文件;请稍后再试。",
[UI_MENU_SAVE_E_WRITE] = "无法将 zip 写入 %s。",
[UI_MENU_SAVE_E_READ] = "无法读取 %s。",
[UI_MENU_SAVE_E_STAGE] = "无法为下次启动准备存档;原因见日志。",
[UI_MENU_SAVE_E_NOT_SAVE] = "%s 不是 NX2navi 导出的存档。",
[UI_MENU_SAVE_E_OTHER_GAME] = "%s 是其他游戏的存档。",
[UI_MENU_SAVE_E_NEWER] = "%s 由更新版本的 NX2navi 制作:请先更新 NX2navi。",
[UI_MENU_SAVE_E_DAMAGED] = "%s 已损坏:请重新下载。",
[UI_MENU_SAVE_E_UNSAFE] = "%s 被拒绝:其中含有存档以外的文件、链接或过多的数据。",
[UI_BOOT_TITLE] = "正在准备着色器",
[UI_BOOT_STARTING] = "正在启动", [UI_BOOT_SHADERS] = "着色器:%lld / %lld", [UI_BOOT_PIPELINES] = "管线:%lld / %lld",
[UI_MENU_CHEATS_REBUILD] = "立即重新构建游戏",

View File

@@ -243,7 +243,27 @@ typedef enum {
UI_MENU_CHEAT_CODE_DESC, UI_MENU_CHEAT_KEY_DESC /* "%s": the buttons */, UI_MENU_CHEAT_DATA_DESC,
UI_MENU_CHEAT_MASTER, UI_MENU_CHEAT_MASTER_DESC, UI_MENU_CHEAT_RESTORE, UI_MENU_CHEAT_RESTORE_DESC,
UI_MENU_CHEAT_REBUILD, UI_MENU_CHEAT_REBUILD_DESC, UI_MENU_CHEAT_UNSUPPORTED, UI_MENU_CHEAT_UNSUPPORTED_DESC,
UI_MENU_LAST_ID = UI_MENU_CHEAT_UNSUPPORTED_DESC,
// the Game tab's Saves group (ui/menu.cpp rows_saves, save_share.c): export the save into a zip, import a shared
// one at the next start. UI_MENU_SAVE_EXPORTED to UI_MENU_SAVE_E_UNSAFE are printf formats with at most one "%s"
// (a path, or the zip's NX2navi version and date)
UI_MENU_SAVES,
UI_MENU_SAVE_EXPORT, UI_MENU_SAVE_EXPORT_DESC, UI_MENU_SAVE_EXPORT_BUG, UI_MENU_SAVE_EXPORT_BUG_DESC,
UI_MENU_SAVE_IMPORT, UI_MENU_SAVE_IMPORT_DESC,
UI_MENU_SAVE_IMPORT_WAITING, // the import row's value while an import waits for the next start
UI_MENU_SAVE_IMPORT_CANCEL, UI_MENU_SAVE_IMPORT_CANCEL_DESC,
UI_MENU_SAVE_BUSY, // note on the rows while an export or import runs
UI_MENU_SAVE_EXPORTED, // "%s": the zip's path
UI_MENU_SAVE_IMPORT_READY, // "%s": "<NX2navi version>, <export date>" of the zip
UI_MENU_SAVE_IMPORT_CANCELLED,
UI_MENU_SAVE_IMPORTED, // "%s": the folder the replaced save was copied to, at this start
UI_MENU_SAVE_IMPORTED_NEW, // the same with no save to replace
UI_MENU_SAVE_E_NO_SAVE, UI_MENU_SAVE_E_READ_SAVE,
UI_MENU_SAVE_E_WRITE, // "%s": the folder the zip could not be written into
UI_MENU_SAVE_E_READ, // "%s" here and below: the zip
UI_MENU_SAVE_E_STAGE,
UI_MENU_SAVE_E_NOT_SAVE, UI_MENU_SAVE_E_OTHER_GAME, UI_MENU_SAVE_E_NEWER, UI_MENU_SAVE_E_DAMAGED,
UI_MENU_SAVE_E_UNSAFE,
UI_MENU_LAST_ID = UI_MENU_SAVE_E_UNSAFE,
// the boot screen while the boot prewarm prepares shaders and pipelines (boot.c, ui/menu.cpp menu_boot_frame)
UI_BOOT_TITLE, UI_BOOT_STARTING,
UI_BOOT_SHADERS, UI_BOOT_PIPELINES, // printf: "%lld" done, "%lld" total