From a2843c3fbf7c0917cd6cc2c763be2deb97a2beb8 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Thu, 5 Nov 2026 17:21:32 +0300 Subject: [PATCH] The setup window remembers the base, update, keys and firmware paths along with the install folder A reinstall or a switch to another game version starts with the form filled in. Only absolute paths are stored, never the keys file's contents, and an entry that no longer exists, has the wrong kind or cannot be statted is dropped on load. Follows #715 by DanielSvoboda. Co-Authored-By: Claude Opus 5.5 --- docs/installer.md | 5 +- installer/gui.py | 12 +++-- installer/recent.py | 62 +++++++++++++++++------ tests/installer_gui_test.py | 99 ++++++++++++++++++++++++++++++++++--- 4 files changed, 150 insertions(+), 28 deletions(-) diff --git a/docs/installer.md b/docs/installer.md index 14d6a6e2..790faa88 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -39,8 +39,9 @@ The install folder (`main.c` `portable_paths()` reads this layout; it stays port The player runs a newer installer on the same folder. It reads `totk-install.json`, keeps `romfs/`, `exefs/`, `shared-fonts/`, `profile/` and `totk.ini` after checking their hashes, rebuilds `totk.exe` and re-prepares the shaders. A newer release that changes nothing game-derived skips the rebuild. The window starts with the last install folder -it ran on, kept in `%LOCALAPPDATA%\TotK Recomp\setup.json` (`$XDG_STATE_HOME/totk-recomp/setup.json` elsewhere), so an update -needs no other input. +and the base, update, keys and firmware paths it ran with (paths only, never the keys file's contents), kept in +`%LOCALAPPDATA%\TotK Recomp\setup.json` (`$XDG_STATE_HOME/totk-recomp/setup.json` elsewhere). Entries that no longer exist +stay empty. A reinstall or a switch to another game version starts filled in. Given an update file other than the recorded one (1.1.0, then 1.2.1, then 1.4.3), the installer extracts and builds again from it and keeps `profile/`. Saves carry over both ways between 1.2.1 and 1.4.3: 1.4.3 converts a 1.2.1 save on load, and 1.2.1 diff --git a/installer/gui.py b/installer/gui.py index f04a0f43..d3cbd498 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -116,9 +116,13 @@ class App: self.vars['dest'].set(str(rebuild)) root.after(POLL_MS, self.start) else: - last = recent.load() # an update needs only the folder: refresh_form shows the hint and the recorded language - if last: - self.vars['dest'].set(last) + # recorded sources fill only empty fields; dest goes last, its trace runs refresh_form (update hint and + # recorded language). In update mode filled files are harmless: Extract.current hashes one only when its + # size or mtime differ from the recorded ones. + last = recent.load() + for name in ('base', 'update', 'keys', 'firmware', 'dest'): + if name in last and not self.vars[name].get().strip(): + self.vars[name].set(last[name]) # ---- text ----------------------------------------------------------------------------------------------------- @@ -364,7 +368,7 @@ class App: self.fit() return self.form_error.configure(text='') - recent.save(form.dest) + recent.save(form.dest, {name: getattr(form, name) for name in recent.SOURCES}) # in a repository the Python running this window: the tools' embeddable Python there has no ._pth entry for # the repository, so `-m installer` would not find the package python = Path(sys.executable) if self.layout.dev else self.layout.python diff --git a/installer/recent.py b/installer/recent.py index 7b9e1700..5ebe75cd 100644 --- a/installer/recent.py +++ b/installer/recent.py @@ -1,10 +1,13 @@ -"""The last install folder, in a per-user file, so an update starts with the folder already filled in. +"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game +version starts with the form filled in. - {"format": 1, "dest": ""} + {"format": 1, "dest": ..., "base": ..., "update": ..., "keys": ..., "firmware": ...} + +Absolute paths only. The keys entry is the path of the keys file, never its contents. Windows: %LOCALAPPDATA%\TotK Recomp\setup.json; elsewhere $XDG_STATE_HOME/totk-recomp/setup.json (default ~/.local/state/totk-recomp/setup.json). TOTK_SETUP_RECENT names another file (tests, --selftest). Nothing else is -stored: the language comes from the install's own totk-install.json, and no key or key file path is kept. +stored: the language comes from the install's own totk-install.json. A file of format 0 (only "dest") still loads. """ import json import os @@ -15,6 +18,9 @@ from . import state FORMAT = 1 ENV = 'TOTK_SETUP_RECENT' +FILES = ('base', 'update', 'keys') # recorded when they are files +SOURCES = FILES + ('firmware',) +FIELDS = ('dest',) + SOURCES def path(): @@ -28,25 +34,53 @@ def path(): return Path(base) / 'totk-recomp' / 'setup.json' -def load(): - """The recorded install folder when it still holds totk-install.json, else None. Never raises.""" +def usable(name, value): + """value when it is a non-empty absolute path of the right kind for the field, else None. One stat call per + path, no file is opened or hashed; a path the OS rejects (embedded NUL, unreachable share) counts as missing.""" + if not isinstance(value, str) or not value or not os.path.isabs(value): + return None + try: + p = Path(value) + if name == 'dest': + ok = (p / state.NAME).is_file() + elif name == 'firmware': + ok = p.is_dir() + else: + ok = p.is_file() + except (OSError, ValueError): + return None + return value if ok else None + + +def read(): try: data = json.loads(path().read_text(encoding='utf-8')) - dest = data['dest'] - if not isinstance(dest, str) or not dest: - return None - return dest if (Path(dest) / state.NAME).is_file() else None - except (OSError, ValueError, KeyError, TypeError): - return None + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} -def save(dest): - """Records dest atomically; a failure to write is ignored, the window works without it.""" +def load(): + """The recorded entries that still exist, by field name. Never raises.""" + data = read() + return {name: data[name] for name in FIELDS if usable(name, data.get(name))} + + +def save(dest, sources=None): + """Records dest and the non-empty, existing entries of sources (base, update, keys, firmware); an entry left out + or empty keeps its saved value. Atomic; a failure to write is ignored, the window works without it.""" target = path() tmp = target.with_name(target.name + '.tmp') + data = {name: v for name, v in read().items() if name in FIELDS and isinstance(v, str)} + data['dest'] = os.path.abspath(dest) + for name, value in (sources or {}).items(): + if name in SOURCES and isinstance(value, str) and value.strip(): + value = os.path.abspath(value.strip()) + if usable(name, value): + data[name] = value try: target.parent.mkdir(parents=True, exist_ok=True) - tmp.write_text(json.dumps({'format': FORMAT, 'dest': os.path.abspath(dest)}), encoding='utf-8') + tmp.write_text(json.dumps({'format': FORMAT, **data}), encoding='utf-8') os.replace(tmp, target) except OSError: pass diff --git a/tests/installer_gui_test.py b/tests/installer_gui_test.py index b301421b..16e0cbc1 100644 --- a/tests/installer_gui_test.py +++ b/tests/installer_gui_test.py @@ -22,6 +22,7 @@ import sys import tempfile import time import unittest +import unittest.mock from pathlib import Path from types import SimpleNamespace @@ -397,25 +398,107 @@ class RecentTest(unittest.TestCase): self.assertEqual(recent.path(), self.file) def test_missing_file(self): - self.assertIsNone(recent.load()) + self.assertEqual(recent.load(), {}) + + def installed(self): + (self.dest / statefile.NAME).write_text('{}', encoding='utf-8') + + def files(self): + out = {} + for name in ('base', 'update', 'keys'): + f = self.tmp / (name + '.bin') + f.write_text('x', encoding='utf-8') + out[name] = str(f) + fw = self.tmp / 'fw' + fw.mkdir() + out['firmware'] = str(fw) + return out + + def write(self, **fields): + self.file.parent.mkdir(parents=True, exist_ok=True) + self.file.write_text(json.dumps(fields), encoding='utf-8') def test_folder_without_state(self): recent.save(self.dest) - self.assertIsNone(recent.load()) + self.assertEqual(recent.load(), {}) def test_round_trip(self): - (self.dest / statefile.NAME).write_text('{}', encoding='utf-8') - recent.save(self.dest) - self.assertEqual(json.loads(self.file.read_text(encoding='utf-8')), - {'format': 1, 'dest': os.path.abspath(self.dest)}) - self.assertEqual(recent.load(), os.path.abspath(self.dest)) + self.installed() + src = self.files() + recent.save(self.dest, src) + want = {name: os.path.abspath(v) for name, v in src.items()} + want['dest'] = os.path.abspath(self.dest) + self.assertEqual(json.loads(self.file.read_text(encoding='utf-8')), {'format': 1, **want}) + self.assertEqual(recent.load(), want) self.assertFalse(self.file.with_name('setup.json.tmp').exists()) + def test_empty_field_keeps_saved_value(self): + self.installed() + src = self.files() + recent.save(self.dest, src) + recent.save(self.dest, {'base': '', 'update': ' ', 'keys': src['keys']}) + self.assertEqual(recent.load()['base'], os.path.abspath(src['base'])) + self.assertEqual(recent.load()['firmware'], os.path.abspath(src['firmware'])) + + def test_missing_path_not_saved(self): + self.installed() + recent.save(self.dest, {'base': str(self.tmp / 'gone.xci'), 'firmware': str(self.tmp / 'nofw')}) + self.assertEqual(recent.load(), {'dest': os.path.abspath(self.dest)}) + self.assertNotIn('base', json.loads(self.file.read_text(encoding='utf-8'))) + + def test_vanished_path_dropped_on_load(self): + self.installed() + src = self.files() + recent.save(self.dest, src) + os.remove(src['base']) + self.assertNotIn('base', recent.load()) + self.assertIn('update', recent.load()) + + def test_directory_as_file_dropped(self): + self.installed() + self.write(format=1, dest=str(self.dest), base=str(self.tmp), update=str(self.tmp), keys=str(self.tmp)) + self.assertEqual(recent.load(), {'dest': str(self.dest)}) + + def test_file_as_firmware_dropped(self): + self.installed() + src = self.files() + self.write(format=1, dest=str(self.dest), firmware=src['base']) + self.assertEqual(recent.load(), {'dest': str(self.dest)}) + + def test_dest_file_dropped(self): + f = self.tmp / 'afile' + f.write_text('x', encoding='utf-8') + self.write(format=1, dest=str(f)) + self.assertEqual(recent.load(), {}) + + def test_bad_values_dropped(self): + self.installed() + src = self.files() + self.write(format=1, dest=str(self.dest), base=5, update='', keys='rel/prod.keys', firmware=['x']) + self.assertEqual(recent.load(), {'dest': str(self.dest)}) + self.write(format=1, dest=str(self.dest), base=src['base'] + '\0x', update=None, keys=True) + self.assertEqual(recent.load(), {'dest': str(self.dest)}) + self.write(format=1, dest='relative/dir') + self.assertEqual(recent.load(), {}) + + def test_stat_errors_dropped(self): + self.installed() + src = self.files() + self.write(format=1, dest=str(self.dest), base=src['base']) + for exc in (OSError('share gone'), ValueError('embedded null byte')): + with unittest.mock.patch.object(Path, 'is_file', side_effect=exc): + self.assertEqual(recent.load(), {}) + + def test_old_dest_only_format(self): + self.installed() + self.write(format=0, dest=str(self.dest)) + self.assertEqual(recent.load(), {'dest': str(self.dest)}) + def test_garbage_file(self): self.file.parent.mkdir() for text in ('not json', '[]', '{"dest": 5}', '{"format": 1}'): self.file.write_text(text, encoding='utf-8') - self.assertIsNone(recent.load(), text) + self.assertEqual(recent.load(), {}, text) class SmokeTest(unittest.TestCase):