From 2d8a93f8231123c11b03106530df7a722f129e4c Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sat, 24 Oct 2026 09:27:39 +0300 Subject: [PATCH] Re-render the window log from the kept events on a language switch, show language, step and input names instead of codes, reset the model on a new run and feed the selftest's ok screen a complete run Co-Authored-By: Claude Opus 5.5 --- installer/gui.py | 61 +++++++++++++++++++++++++++++-------- installer/guilogic.py | 21 +++++++++++-- installer/text/en.json | 4 +++ installer/text/ru.json | 6 +++- tests/installer_gui_test.py | 46 ++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 15 deletions(-) diff --git a/installer/gui.py b/installer/gui.py index 776af85c..ac031400 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -48,6 +48,7 @@ class App: self.process = None self.closing = False self.run_args = run_args or {} # extra CLI options for tests: temp, verify + self.log_entries = [] # events and raw lines of the run, rendered by render_log self.bound = [] # (widget, option, id, params) retranslated on a language switch self.vars = {n: tk.StringVar() for n in ('base', 'update', 'keys', 'dest')} self.vars['lang'] = tk.StringVar() @@ -103,6 +104,7 @@ class App: self.refresh_form() self.refresh_run() self.refresh_finish() + self.render_log() def switch_language(self): self.cat.set_language(self.ui_var.get()) @@ -326,15 +328,15 @@ class App: event = parse_line(line) if event is None: if line.strip(): - self.add_log(line.rstrip()) + self.log_entries.append(line.rstrip()) + self.append_log(line.rstrip()) return before = list(self.model.steps) self.model.apply(event) if self.model.steps != before: self.build_step_rows(self.model.steps) - text = describe_event(self.cat, event) - if text: - self.add_log(text) + self.log_entries.append(event) + self.append_log(describe_event(self.cat, event)) def refresh_run(self): m = self.model @@ -379,16 +381,27 @@ class App: self.bind_text(self.log_toggle, 'text', 'ui.hide_log' if self.log_open else 'ui.show_log') def clear_log(self): + self.log_entries = [] + self.render_log() + + def render_log(self): + """The whole log from the kept events in the current language (raw CLI lines stay as they are).""" self.log.configure(state='normal') self.log.delete('1.0', 'end') - self.log.configure(state='disabled') - - def add_log(self, text): - self.log.configure(state='normal') - self.log.insert('end', text + '\n') + for entry in self.log_entries: + text = entry if isinstance(entry, str) else describe_event(self.cat, entry) + if text: + self.log.insert('end', text + '\n') self.log.see('end') self.log.configure(state='disabled') + def append_log(self, text): + if text: + self.log.configure(state='normal') + self.log.insert('end', text + '\n') + self.log.see('end') + self.log.configure(state='disabled') + def cancel(self): if self.process: self.cancel_button.configure(state='disabled') @@ -457,6 +470,19 @@ SAMPLE_RUN = [ ] +SAMPLE_OK = [SAMPLE_START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'lift': 'current', 'compile': 'current', + 'prepare': 'current', 'cleanup': 'not_needed'}}, + {'type': 'step', 'step': 'check', 'state': 'started'}, + {'type': 'step', 'step': 'check', 'state': 'done', 'seconds': 1.0}, + {'type': 'step', 'step': 'extract', 'state': 'started'}, + {'type': 'step', 'step': 'extract', 'state': 'done', 'seconds': 1.0}, + {'type': 'step', 'step': 'lift', 'state': 'skipped', 'reason': 'current'}, + {'type': 'step', 'step': 'compile', 'state': 'skipped', 'reason': 'current'}, + {'type': 'step', 'step': 'prepare', 'state': 'skipped', 'reason': 'current'}, + {'type': 'step', 'step': 'cleanup', 'state': 'done', 'seconds': 0.1}, + {'type': 'end', 'result': 'ok', 'seconds': 3}] + + def grab(root, path): if ImageGrab is None: raise SystemExit('--shots needs Pillow') @@ -472,7 +498,7 @@ def selftest(layout, shots=None): root = tk.Tk() root.geometry('720x640+60+40') app = App(root, 'en', layout) - steps = [] + steps, mixed = [], [] def shot(name): root.update() @@ -494,6 +520,7 @@ def selftest(layout, shots=None): steps.append(app.form_error.cget('text')) shot(f'form-{tag}') app.model = Model() + app.clear_log() app.build_step_rows(app.model.steps) app.show('run') for e in SAMPLE_RUN: @@ -502,8 +529,18 @@ def selftest(layout, shots=None): app.toggle_log() app.refresh_run() shot(f'run-{tag}') + if lang == 'en': # the log follows the window language: no English line may remain after the switch + app.ui_var.set('ru') + app.switch_language() + text = app.log.get('1.0', 'end') + mixed.append('Checking' in text or 'Extracting' not in text and 'Распаковка' not in text) + app.ui_var.set('en') + app.switch_language() + app.model = Model() + for e in SAMPLE_OK: + app.model.apply(e) + app.model.dest = 'Z:/selftest/TotK' app.model.finish(0) - app.model.result = 'ok' app.refresh_finish() app.show('finish') shot(f'finish-ok-{tag}') @@ -525,7 +562,7 @@ def selftest(layout, shots=None): root.after(200, run_all) root.after(60000, root.destroy) # never leaves a window open root.mainloop() - return 0 if len(steps) == len(UI_LANGUAGES) and all(steps) else 1 + return 0 if len(steps) == len(UI_LANGUAGES) and all(steps) and mixed == [False] else 1 def main(argv=None): diff --git a/installer/guilogic.py b/installer/guilogic.py index 8e29c99e..7d517024 100644 --- a/installer/guilogic.py +++ b/installer/guilogic.py @@ -25,6 +25,8 @@ from .events import render TEXT = Path(__file__).resolve().parent / 'text' UI_LANGUAGES = ('en', 'ru') STEP_ORDER = ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup') +# message parameter -> catalog id prefix of the names that replace its raw values +PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'} LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID @@ -51,7 +53,21 @@ class Catalog: text = self.texts.get(id) or self.english.get(id) if text is None: return id - return render({id: text}, id, {k: flat(v) for k, v in params.items()}) + return render({id: text}, id, {k: self.param(k, v) for k, v in params.items()}) + + def param(self, name, value): + """A message parameter as the player should read it: language codes, step ids and input names become the + catalog's names (the ones the pickers and the step list show); the rest stays as it is.""" + prefix = PARAM_NAMES.get(name) + if prefix: + if isinstance(value, (list, tuple)): + return ', '.join(self.param(name, v) for v in value) + ident = prefix + str(value) + if self.has(ident): + return self(ident) + if name == 'known': + return ', '.join(self(prefix + c) if self.has(prefix + c) else c for c in str(value).split(', ')) + return flat(value) def flat(value): @@ -185,6 +201,7 @@ class Model: def apply(self, e): kind = e['type'] if kind == 'start': + self.__init__() # a new run: nothing of an earlier one stays self.steps = list(e.get('steps') or STEP_ORDER) self.states = {s: PENDING for s in self.steps} self.mode, self.release = e.get('mode', ''), e.get('release', '') @@ -259,7 +276,7 @@ def describe_event(cat, e): if kind == 'step': text = f'{cat("step." + e["step"])}: {cat("ui.state_" + e["state"])}' if 'seconds' in e: - text += f' ({e["seconds"]:.1f} s)' + text += f' ({cat("ui.seconds", n=format(e["seconds"], ".1f"))})' elif e.get('reason'): text += f' ({e["reason"]})' return text diff --git a/installer/text/en.json b/installer/text/en.json index 4cd5435e..bdf5b0fd 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -141,6 +141,10 @@ "ui.amount_objects": "{done} / {total} files", "ui.amount_shaders": "{done} / {total} shaders", "ui.amount_other": "{done} / {total} {unit}", + "ui.seconds": "{n} s", + "param.input.base": "base game", + "param.input.update": "update", + "param.input.keys": "keys", "launcher.title": "TotK Setup", "launcher.python_missing": "The setup files are incomplete: the python folder next to TotK-Setup.exe is missing. Unpack the whole archive again and start TotK-Setup.exe from the unpacked folder.", diff --git a/installer/text/ru.json b/installer/text/ru.json index f24077f5..f045ea6d 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -75,7 +75,7 @@ "prepare.shaders_failed": "Не удалось подготовить шейдеры (код выхода {code}). Подробности: {log}", "cleanup.ini_failed": "Не удаётся записать totk.ini: {detail}", - "warn.lang_needs_fonts": "Тексту на языке {lang} нужны системные шрифты Switch, которые установка не извлекает; часть текста может не отображаться.", + "warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch, которые установка не извлекает; часть текста может не отображаться.", "warn.npdm_differs": "main.npdm отличается от эталонного дампа 1.2.1; используются только модули с кодом.", "ui.title": "Установка TotK", @@ -141,6 +141,10 @@ "ui.amount_objects": "{done} / {total} файлов", "ui.amount_shaders": "{done} / {total} шейдеров", "ui.amount_other": "{done} / {total} {unit}", + "ui.seconds": "{n} с", + "param.input.base": "базовая игра", + "param.input.update": "обновление", + "param.input.keys": "ключи", "launcher.title": "Установка TotK", "launcher.python_missing": "Файлы установки неполные: рядом с TotK-Setup.exe нет папки python. Распакуйте архив целиком заново и запустите TotK-Setup.exe из распакованной папки.", diff --git a/tests/installer_gui_test.py b/tests/installer_gui_test.py index 5691cf56..beb33a0f 100644 --- a/tests/installer_gui_test.py +++ b/tests/installer_gui_test.py @@ -130,6 +130,40 @@ class ModelTest(unittest.TestCase): self.assertEqual(m.states['check'], PENDING) +class RunStatesTest(unittest.TestCase): + OK = [START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'lift': 'current', 'compile': 'current', + 'prepare': 'current', 'cleanup': 'not_needed'}}, + {'type': 'step', 'step': 'check', 'state': 'started'}, {'type': 'step', 'step': 'check', 'state': 'done'}, + {'type': 'step', 'step': 'extract', 'state': 'started'}, {'type': 'step', 'step': 'extract', 'state': 'done'}, + {'type': 'step', 'step': 'lift', 'state': 'skipped'}, {'type': 'step', 'step': 'compile', 'state': 'skipped'}, + {'type': 'step', 'step': 'prepare', 'state': 'skipped'}, {'type': 'step', 'step': 'cleanup', 'state': 'done'}, + {'type': 'end', 'result': 'ok', 'seconds': 1}] + FAILED = [START, {'type': 'step', 'step': 'check', 'state': 'started'}, {'type': 'step', 'step': 'check', 'state': 'done'}, + {'type': 'step', 'step': 'extract', 'state': 'started'}, + {'type': 'error', 'id': 'extract.romfs_mismatch', 'step': 'extract', 'params': {}}, + {'type': 'warning', 'id': 'warn.lang_needs_fonts', 'params': {'lang': 'ko'}}, + {'type': 'end', 'result': 'failed', 'seconds': 1}] + + def test_ok_run_has_only_done_and_skipped_steps(self): + m = fold(*self.OK) + m.finish(0) + self.assertEqual(m.result, 'ok') + self.assertIsNone(m.error) + self.assertEqual({m.states[s] for s in m.steps}, {DONE, SKIPPED}) + + def test_a_new_run_keeps_nothing_of_the_failed_one(self): + m = fold(*self.FAILED) + m.finish(1) + self.assertEqual(m.states['extract'], FAILED) + for e in self.OK: # the same model object fed a second run (the window makes a new one, but even then) + m.apply(e) + m.finish(0) + self.assertEqual({m.states[s] for s in m.steps}, {DONE, SKIPPED}) + self.assertIsNone(m.error) + self.assertEqual(m.warnings, []) + self.assertEqual(m.result, 'ok') + + class FormTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -210,6 +244,18 @@ class CatalogTest(unittest.TestCase): cat.set_language(lang) self.assertEqual([i for i in ids if not cat.has(i)], []) + def test_codes_become_names(self): + for lang, korean in (('en', 'Korean'), ('ru', 'Корейский')): + cat = Catalog(lang) + self.assertIn(korean, cat('warn.lang_needs_fonts', lang='ko')) + self.assertNotIn(' ko ', cat('warn.lang_needs_fonts', lang='ko')) + self.assertNotIn('extract', cat('state.output_changed', step='extract')) + for word in ('base', 'update', 'keys'): + self.assertIn(cat('param.input.' + word), cat('check.keys_wrong', input=word)) + self.assertNotIn('en-US', cat('check.lang_unknown', lang='xx', known='ja, en-US')) + self.assertEqual(Catalog('en')('check.lang_unknown', lang='xx', known='ja, en-US'), + "Unknown language 'xx'. Known: Japanese, English (US).") + def test_fallback_and_params(self): cat = Catalog('ru') self.assertIn('36.4', cat('ui.log_space', need='36.4', free='1.0'))