Import the base tree (MIT, see LICENSE)

This commit is contained in:
Valiantsin Dzerakh
2026-11-04 22:16:41 +03:00
committed by chrg6
commit 0478c13e45
734 changed files with 233953 additions and 0 deletions

11
installer/__init__.py Normal file
View File

@@ -0,0 +1,11 @@
"""The NX2navi installer: builds a playable folder from the player's own game files (docs/installer.md).
python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR] [--root DIR]
[--temp DIR]
Modules: layout (where the bundled tools are, release or repository), events (JSON progress on stdout and the log
file), state (nx2navi-install.json), runner (which steps run: resume and update), steps (the eight steps), ini (nx2navi.ini),
cli (the command line). text/en.json holds the English text of every message id the events carry.
Standard library only, apart from what the extraction tools import (cryptography). Runs on Python 3.14.
"""

5
installer/__main__.py Normal file
View File

@@ -0,0 +1,5 @@
import sys
from installer.cli import main
sys.exit(main())

94
installer/cli.py Normal file
View File

@@ -0,0 +1,94 @@
"""Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR]
[--root DIR] [--temp DIR] [--verify] [--dlss]
A first install needs every option. --firmware names the Switch firmware folder (an unpacked firmware or an emulator's
Contents/registered); the setup extracts the system shared fonts from it when the language is Chinese, Korean or
Traditional Chinese. On a folder with nx2navi-install.json (resume after a cancel or failure, or update with a newer
release) only --dest is needed: --lang defaults to the recorded language, and the game files are needed only when the
extraction has to run again. Prints JSON events on stdout (events.py). Exit code: 0 done, 1 failed, 2 bad command
line, 3 cancelled (Ctrl+C or Ctrl+Break).
--dlss downloads NVIDIA's DLSS library (nvngx_dlss.dll) from NVIDIA's DLSS SDK repository into the install folder on
Windows with an NVIDIA RTX GPU (steps.py, Dlss).
"""
import argparse
import hashlib
import signal
import sys
import time
from pathlib import Path
from . import layout as layouts
from . import state as statefile
from .events import Reporter
from .runner import Context, run_steps
from .steps import all_steps, migrate_state
EXIT = {'ok': 0, 'failed': 1, 'cancelled': 3}
class Parser(argparse.ArgumentParser):
def error(self, message):
Reporter().error('cli.usage', {'detail': message})
sys.exit(2)
# The temp folder inside the install folder when the layout names none (the Linux release); the check step does not
# count it when it requires an empty install folder
TEMP_IN_DEST = '.setup-temp'
def temp_folder(base, dest):
"""One temp folder per install folder, so two installs never share generated files."""
tag = hashlib.sha256(str(dest).lower().encode()).hexdigest()[:8]
return base / f'{dest.name or "root"}-{tag}'
def cancel(signum, frame):
raise KeyboardInterrupt
def main(argv=None):
ap = Parser(prog='python -m installer', description=__doc__.splitlines()[0])
ap.add_argument('--base', type=Path, help='base game, XCI or NSP (or NSZ, XCZ: unpacked first)')
ap.add_argument('--update', type=Path, help='the update NSP or NSZ: 1.1.0, 1.2.1 or 1.4.3')
ap.add_argument('--keys', type=Path, help='prod.keys')
ap.add_argument('--firmware', type=Path, help='Switch firmware folder (Contents/registered) for the shared fonts '
'of Chinese, Korean and Traditional Chinese text')
ap.add_argument('--lang', help='game language, a Switch language code (en-US, en-GB, ja, de, ru, ...)')
ap.add_argument('--dest', type=Path, required=True, help='install folder')
ap.add_argument('--root', type=Path, help='release folder or repository (default: the folder above installer/)')
ap.add_argument('--temp', type=Path, help='temp folder (default: temp/ of the release on Windows, .setup-temp in '
'the install folder on Linux, build/install-temp in a repository)')
ap.add_argument('--verify', action='store_true', help='hash every kept file, also those this release made')
ap.add_argument('--dlss', action='store_true', help="download NVIDIA's nvngx_dlss.dll (NVIDIA RTX SDK license) next "
'to the game, for dlaa and the DLSS modes')
args = ap.parse_args(argv)
# The window cancels with Ctrl+Break to the installer's process group (CREATE_NEW_PROCESS_GROUP), which also reaches
# the tools it runs; Python's default for it ends the process without recording anything.
for name in ('SIGBREAK', 'SIGTERM'):
if hasattr(signal, name):
signal.signal(getattr(signal, name), cancel)
layout = layouts.find(args.root)
dest = args.dest.resolve()
base = args.temp or layout.temp
temp = temp_folder(base.resolve(), dest) if base else dest / TEMP_IN_DEST
log = temp / 'logs' / time.strftime('install-%Y%m%d-%H%M%S.log')
rep = Reporter(log_path=log)
t0 = time.monotonic()
try:
state = statefile.load(dest)
except statefile.StateError as e:
rep.error(e.id, {'path': str(e.path)})
rep.emit('end', result='failed', seconds=0)
return 1
ctx = Context(layout, dest, temp, rep, args, state=state, verify=args.verify)
migrate_state(ctx)
steps = all_steps()
rep.emit('start', release=layout.release, mode=ctx.mode, dev=layout.dev, dest=str(dest), log=str(log),
steps=[s.id for s in steps])
result = run_steps(steps, ctx)
rep.emit('end', result=result, seconds=round(time.monotonic() - t0, 1))
rep.close()
return EXIT[result]

123
installer/events.py Normal file
View File

@@ -0,0 +1,123 @@
"""Progress events: one JSON object per line on stdout for the window and tests, the same in English to a log file.
Every event has "type" and "t" (seconds since the start). Types:
start release, mode (install, resume, update), dest, log, steps (the step ids in order)
step step, state: started | done (seconds) | skipped (reason: current, not_needed)
progress step, phase, and done/total/unit (bytes, chunks, objects, shaders) when the amount is known
space dest, need, free (bytes on the install disk; with the temp folder on the same disk need includes it),
temp, temp_need, temp_free, same_disk
warning id, params
error id, params, step (absent outside a step)
end result: ok | failed | cancelled, seconds
Text is never the payload: ids name a step ("step.<id>"), a phase ("phase.<step>.<phase>") or a message ("<id>"),
and installer/text/en.json holds their English text with {param} placeholders. The log renders events with it.
"""
import json
import os
import sys
import threading
import time
from pathlib import Path
CATALOG = Path(__file__).resolve().parent / 'text' / 'en.json'
PROGRESS_EVERY = 0.5 # seconds between two progress events of one phase
def load_catalog(path=CATALOG):
return json.loads(path.read_text(encoding='utf-8'))
GAME_EXE = 'nx2navi.exe' if os.name == 'nt' else 'nx2navi' # {game_exe} in the catalogs
def render(catalog, id, params=None):
"""The English text of id, or the id itself when the catalog lacks it."""
text = catalog.get(id, id)
try:
return text.format(**{'game_exe': GAME_EXE, **(params or {})})
except (KeyError, IndexError, ValueError):
return f'{text} {params}'
class Reporter:
def __init__(self, out=None, log_path=None):
self.out = out or sys.stdout
self.t0 = time.monotonic()
self.catalog = load_catalog()
self.lock = threading.Lock()
self.log_file = None
self.last_progress = {}
if log_path:
Path(log_path).parent.mkdir(parents=True, exist_ok=True)
self.log_file = open(log_path, 'a', encoding='utf-8', buffering=1)
self.log_path = log_path
def elapsed(self):
return time.monotonic() - self.t0
def log(self, text):
"""A line for the log file only."""
if self.log_file:
with self.lock:
self.log_file.write(f'[{self.elapsed():8.1f}] {text}\n')
def emit(self, type, **fields):
event = {'type': type, 't': round(self.elapsed(), 2), **fields}
with self.lock:
self.out.write(json.dumps(event, ensure_ascii=False) + '\n')
self.out.flush()
self.log(self.describe(event))
return event
def describe(self, e):
c = self.catalog
kind = e['type']
if kind == 'step':
name = render(c, 'step.' + e['step'])
extra = f' ({e["seconds"]:.1f} s)' if 'seconds' in e else f' ({e["reason"]})' if 'reason' in e else ''
return f'{name}: {e["state"]}{extra}'
if kind == 'progress':
text = render(c, f'phase.{e["step"]}.{e["phase"]}')
if e.get('total'):
text += f' {e["done"]}/{e["total"]} {e.get("unit", "")}'.rstrip()
return text
if kind in ('warning', 'error'):
return f'{kind}: {render(c, e["id"], e.get("params"))} [{e["id"]}]'
return json.dumps(e, ensure_ascii=False)
def step(self, step, state, **fields):
return self.emit('step', step=step, state=state, **fields)
def progress(self, step, phase, done=None, total=None, unit=None, force=False):
"""A progress event, at most one per PROGRESS_EVERY per phase unless it is the first or the last."""
now = time.monotonic()
key = (step, phase)
last = self.last_progress.get(key)
final = total is not None and done is not None and done >= total
if last is not None and not final and not force and now - last < PROGRESS_EVERY:
return None
self.last_progress[key] = now
fields = {'step': step, 'phase': phase}
if done is not None:
fields['done'] = done
if total is not None:
fields['total'] = total
if unit:
fields['unit'] = unit
return self.emit('progress', **fields)
def warning(self, id, **params):
return self.emit('warning', id=id, params=params)
def error(self, id, params, step=None):
fields = {'id': id, 'params': params}
if step:
fields['step'] = step
return self.emit('error', **fields)
def close(self):
if self.log_file:
self.log_file.close()
self.log_file = None

679
installer/gui.py Normal file
View File

@@ -0,0 +1,679 @@
"""The installer window: python -m installer.gui
A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the optional firmware
folder, the game language and the install folder, runs `python -m installer ...` as a subprocess and shows its JSON
events. Decisions live in guilogic.py; this file only draws. The window text is in
installer/text/<en|ru|pt-BR|zh-Hans>.json under "ui.*" and "launcher.*" ids.
--selftest [--shots DIR] build every screen in every language and close by itself (PNG per screen with --shots)
--lang en|ru|pt-BR|zh-Hans window language (default: the Windows display language)
--rebuild DIR rebuild the install folder DIR for its mods (nx2navi.exe starts this, build-cache/rebuild.txt):
the run starts at once with that folder, and the game starts again when it succeeds
"""
import argparse
import json
import os
import subprocess
import sys
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, ttk
try:
from PIL import ImageGrab # only the screenshots of --selftest --shots need it; the release has no PIL
except ImportError:
ImageGrab = None
from . import ini
from . import layout as layouts
from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, UI_LANGUAGES, Catalog, Form, Model,
Process, amount, default_game_language, describe_event, parse_line, windows_ui_language)
POLL_MS = 100
GLYPH = {PENDING: '\u25cb', RUNNING: '\u25b6', DONE: '\u2714', SKIPPED: '\u2013', FAILED: '\u2716'}
COLOR = {PENDING: '#808080', RUNNING: '#1a5fb4', DONE: '#26a269', SKIPPED: '#808080', FAILED: '#c01c28'}
PAD = 14
def fix_tcl_paths():
"""The embeddable Python keeps Tcl/Tk next to python.exe (python/tcl); point Tcl at it when it is not found."""
tcl = Path(sys.executable).resolve().parent / 'tcl'
if tcl.is_dir() and 'TCL_LIBRARY' not in os.environ:
for lib, var in (('tcl9.0', 'TCL_LIBRARY'), ('tk9.0', 'TK_LIBRARY')):
if (tcl / lib).is_dir():
os.environ[var] = str(tcl / lib)
class App:
def __init__(self, root, ui_lang, layout, run_args=None, rebuild=None):
self.root, self.layout = root, layout
self.rebuild = rebuild # the install folder of --rebuild, or None
self.cat = Catalog(ui_lang)
self.model = Model()
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', 'firmware', 'dest')}
self.vars['lang'] = tk.StringVar()
self.lang_code = default_game_language(ui_lang)
self.screen = None
self.fitted = None # the (width, height) fit last gave the window
root.title(self.cat('ui.title'))
icon = layout.runtime / 'nx2navi.ico'
png = layout.runtime / 'nx2navi.png' # Tk loads no .ico off Windows; the Linux release converts it
if os.name == 'nt' and icon.is_file():
root.iconbitmap(default=str(icon))
elif png.is_file():
self.icon = tk.PhotoImage(file=str(png))
root.iconphoto(True, self.icon)
root.protocol('WM_DELETE_WINDOW', self.on_close)
self.ui_font = 'Segoe UI' if os.name == 'nt' else 'DejaVu Sans'
self.mono_font = 'Consolas' if os.name == 'nt' else 'DejaVu Sans Mono'
style = ttk.Style(root)
style.configure('Title.TLabel', font=(self.ui_font, 15, 'bold'))
style.configure('Notice.TLabel', background='#fff3cd', foreground='#664d03', padding=8)
style.configure('Err.TLabel', foreground='#c01c28')
style.configure('Version.TLabel', foreground='#808080')
top = ttk.Frame(root, padding=(PAD, PAD, PAD, 0))
top.pack(fill='x')
self.title = self.label(top, 'ui.title', style='Title.TLabel')
self.title.pack(side='left')
version = ttk.Label(top, style='Version.TLabel')
self.bind_text(version, 'text', 'ui.version', version=layout.release)
version.pack(side='left', padx=(10, 0), pady=(6, 0))
sw = ttk.Frame(top)
sw.pack(side='right')
self.ui_var = tk.StringVar(value=self.cat.lang) # the window language code; the box shows its name
labels = [UI_LANGUAGE_LABELS[c] for c in UI_LANGUAGES]
self.ui_box = ttk.Combobox(sw, values=labels, state='readonly', width=max(map(len, labels)) + 1)
self.ui_box.set(UI_LANGUAGE_LABELS[self.cat.lang])
self.ui_box.bind('<<ComboboxSelected>>', self.pick_language)
self.ui_box.pack(side='left')
self.body = ttk.Frame(root, padding=PAD)
self.body.pack(fill='both', expand=True)
self.frames = {'form': self.build_form(), 'run': self.build_run(), 'finish': self.build_finish()}
self.vars['lang'].set(self.lang_label(self.lang_code))
self.vars['dest'].trace_add('write', lambda *_: self.refresh_form())
self.show('form')
if rebuild:
self.bind_text(self.title, 'text', 'ui.rebuild_title')
self.vars['dest'].set(str(rebuild))
root.after(POLL_MS, self.start)
# ---- text -----------------------------------------------------------------------------------------------------
def bind_text(self, widget, option, id, **params):
self.bound.append((widget, option, id, params))
widget.configure(**{option: self.cat(id, **params)})
def label(self, parent, id, **kw):
w = ttk.Label(parent, **kw)
self.bind_text(w, 'text', id)
return w
def button(self, parent, id, command, **kw):
w = ttk.Button(parent, command=command, **kw)
self.bind_text(w, 'text', id)
return w
def retext(self):
self.root.title(self.cat('ui.title'))
for widget, option, id, params in self.bound:
widget.configure(**{option: self.cat(id, **params)})
self.fill_languages()
self.refresh_form()
self.refresh_run()
self.refresh_finish()
self.render_log()
def pick_language(self, _event=None):
self.ui_var.set(UI_LANGUAGES[self.ui_box.current()])
self.switch_language()
def switch_language(self):
self.cat.set_language(self.ui_var.get())
self.ui_box.set(UI_LANGUAGE_LABELS[self.ui_var.get()])
code = self.selected_lang()
self.retext()
self.vars['lang'].set(self.lang_label(code))
self.fit()
def lang_label(self, code):
return self.cat('lang.' + code)
def fill_languages(self):
code = self.selected_lang()
self.lang_box.configure(values=[self.lang_label(c) for c in ini.LANGUAGES])
self.vars['lang'].set(self.lang_label(code))
def selected_lang(self):
"""The game language code behind the combobox text (kept when it is not one of the labels)."""
shown = self.vars['lang'].get()
for code in ini.LANGUAGES:
for lang in UI_LANGUAGES:
if shown == Catalog(lang)('lang.' + code):
return code
return self.lang_code
# ---- screens --------------------------------------------------------------------------------------------------
def show(self, name):
for f in self.frames.values():
f.pack_forget()
self.frames[name].pack(fill='both', expand=True)
self.screen = name
self.fit()
def fit(self):
"""Size the window to its largest screen (an unpacked frame still reports the size its children ask for), so
a screen or language switch neither cuts text nor moves the buttons. The window only grows: opening the log
makes it taller, and a size the user dragged it to stays. Every text change that can add lines calls it again,
or pack takes the missing height from the button bars."""
self.root.update_idletasks()
sizes = [(f.winfo_reqwidth(), f.winfo_reqheight()) for f in self.frames.values()]
chrome = self.root.winfo_reqheight() - self.body.winfo_reqheight() # the title row above the body
w = max(self.root.winfo_reqwidth(), max(s[0] for s in sizes) + 2 * PAD)
h = chrome + max(s[1] for s in sizes) + 2 * PAD
if (w, h) == self.fitted: # refresh_run calls it on every poll: leave the window alone while nothing grew
return
self.fitted = (w, h)
self.root.minsize(w, h)
self.root.geometry(f'{max(w, self.root.winfo_width())}x{max(h, self.root.winfo_height())}')
def notice(self, parent):
w = ttk.Label(parent, style='Notice.TLabel', wraplength=620, justify='left')
self.bind_text(w, 'text', 'ui.notice')
return w
def build_form(self):
f = ttk.Frame(self.body)
bar = ttk.Frame(f) # packed first so pack shrinks the text above it, never the buttons
bar.pack(side='bottom', fill='x', pady=(12, 0))
self.start_button = self.button(bar, 'ui.start', self.start)
self.start_button.pack(side='right')
self.form_intro = self.label(f, 'ui.intro', wraplength=620, justify='left')
self.form_intro.pack(anchor='w', pady=(0, 8))
self.notice(f).pack(fill='x', pady=(0, 10))
grid = ttk.Frame(f)
grid.pack(fill='x')
grid.columnconfigure(1, weight=1)
rows = (('base', 'ui.base', 'ui.pick_game'), ('update', 'ui.update', 'ui.pick_update'),
('keys', 'ui.keys', 'ui.pick_keys'))
self.form_rows = {}
for i, (name, label_id, pick_id) in enumerate(rows):
lab = self.label(grid, label_id)
lab.grid(row=i, column=0, sticky='w', pady=4, padx=(0, 10))
ttk.Entry(grid, textvariable=self.vars[name]).grid(row=i, column=1, sticky='ew', pady=4)
b = self.button(grid, 'ui.browse', lambda n=name, p=pick_id: self.pick_file(n, p))
b.grid(row=i, column=2, padx=(8, 0))
self.form_rows[name] = lab
i = len(rows)
self.label(grid, 'ui.firmware').grid(row=i, column=0, sticky='w', pady=4)
ttk.Entry(grid, textvariable=self.vars['firmware']).grid(row=i, column=1, sticky='ew', pady=4)
self.button(grid, 'ui.browse', self.pick_firmware).grid(row=i, column=2, padx=(8, 0))
i += 1
self.label(grid, 'ui.game_language').grid(row=i, column=0, sticky='w', pady=4)
self.lang_box = ttk.Combobox(grid, textvariable=self.vars['lang'], state='readonly', width=30)
self.lang_box.grid(row=i, column=1, sticky='w', pady=4)
self.lang_touched = False
self.lang_box.bind('<<ComboboxSelected>>', lambda _e: setattr(self, 'lang_touched', True))
self.fill_languages()
self.label(grid, 'ui.dest').grid(row=i + 1, column=0, sticky='w', pady=4)
ttk.Entry(grid, textvariable=self.vars['dest']).grid(row=i + 1, column=1, sticky='ew', pady=4)
self.button(grid, 'ui.browse', self.pick_dest).grid(row=i + 1, column=2, padx=(8, 0))
self.label(f, 'ui.compressed_help', wraplength=620, justify='left').pack(anchor='w', pady=(8, 0))
self.label(f, 'ui.firmware_help', wraplength=620, justify='left').pack(anchor='w', pady=(8, 0))
# On by default and named with its source and licence: the player sees what is downloaded and can untick it
self.dlss_var = tk.BooleanVar(value=True)
dlss = ttk.Checkbutton(f, variable=self.dlss_var)
self.bind_text(dlss, 'text', 'ui.dlss')
dlss.pack(anchor='w', pady=(8, 0))
self.label(f, 'ui.dlss_help', wraplength=620, justify='left').pack(anchor='w', padx=(22, 0))
self.update_hint = ttk.Label(f, wraplength=620, justify='left')
self.update_hint.pack(anchor='w', pady=(8, 0))
self.form_error = ttk.Label(f, style='Err.TLabel', wraplength=620, justify='left')
self.form_error.pack(anchor='w', pady=(8, 0))
self.label(f, 'ui.keys_private', wraplength=620, justify='left').pack(anchor='w', pady=(8, 0))
return f
def build_run(self):
f = ttk.Frame(self.body)
bar = ttk.Frame(f)
bar.pack(side='bottom', fill='x', pady=(8, 0))
self.cancel_button = self.button(bar, 'ui.cancel', self.cancel)
self.cancel_button.pack(side='right')
self.log_toggle = self.button(bar, 'ui.show_log', self.toggle_log)
self.log_toggle.pack(side='left')
self.run_header = ttk.Label(f, font=(self.ui_font, 11, 'bold'))
self.run_header.pack(anchor='w')
self.step_rows = {}
self.steps_box = ttk.Frame(f)
self.steps_box.pack(fill='x', pady=(8, 8))
self.phase_label = ttk.Label(f, wraplength=620, justify='left')
self.phase_label.pack(anchor='w')
self.bar = ttk.Progressbar(f, mode='determinate', maximum=1000)
self.bar.pack(fill='x', pady=(4, 6))
self.space_label = ttk.Label(f, wraplength=620, justify='left')
self.space_label.pack(anchor='w')
self.warn_label = ttk.Label(f, wraplength=620, justify='left', foreground='#9a6700')
self.warn_label.pack(anchor='w')
self.log_frame = ttk.Frame(f)
self.log = tk.Text(self.log_frame, height=10, wrap='word', state='disabled', font=(self.mono_font, 9))
scroll = ttk.Scrollbar(self.log_frame, command=self.log.yview)
self.log.configure(yscrollcommand=scroll.set)
scroll.pack(side='right', fill='y')
self.log.pack(side='left', fill='both', expand=True)
self.log_open = False
return f
def build_finish(self):
f = ttk.Frame(self.body)
bar = ttk.Frame(f)
bar.pack(side='bottom', fill='x', pady=(12, 0))
self.button(bar, 'ui.close', self.on_close).pack(side='right')
self.open_button = self.button(bar, 'ui.open_folder', self.open_folder)
self.open_button.pack(side='right', padx=(0, 8))
self.back_button = self.button(bar, 'ui.back', lambda: self.show('form'))
self.back_button.pack(side='left')
if self.rebuild: # a failed or cancelled rebuild: the game starts with the code it has
self.button(bar, 'ui.start_game', self.start_game).pack(side='right', padx=(0, 8))
self.finish_title = ttk.Label(f, style='Title.TLabel', wraplength=620, justify='left')
self.finish_title.pack(anchor='w')
self.finish_text = ttk.Label(f, wraplength=620, justify='left')
self.finish_text.pack(anchor='w', pady=(8, 8))
self.finish_steps = ttk.Frame(f)
self.finish_steps.pack(fill='x', pady=(0, 8))
self.finish_notice = self.notice(f)
self.finish_notice.pack(fill='x', pady=(8, 0))
return f
# ---- form -----------------------------------------------------------------------------------------------------
def form(self):
return Form(base=self.vars['base'].get(), update=self.vars['update'].get(), keys=self.vars['keys'].get(),
firmware=self.vars['firmware'].get(), lang=self.selected_lang(), dest=self.vars['dest'].get(),
dlss=self.dlss_var.get())
def refresh_form(self):
form = self.form()
state = form.installed_state()
if state is not None:
self.update_hint.configure(text=self.cat('ui.update_mode'))
recorded = ini.canonical_language(state.get('lang'))
if recorded in ini.LANGUAGES and not self.lang_touched:
self.vars['lang'].set(self.lang_label(recorded))
else:
self.update_hint.configure(text='')
self.fit()
def pick_file(self, name, pick_id):
# One filter for every game file: the setup tells an NSZ or XCZ from a plain file by its content (Check.unpack)
types = [(self.cat('ui.type_game'), '*.nsp *.xci *.nsz *.xcz'), (self.cat('ui.type_all'), '*.*')]
if name == 'keys':
types = [(self.cat('ui.type_keys'), '*.keys'), (self.cat('ui.type_all'), '*.*')]
path = filedialog.askopenfilename(title=self.cat(pick_id), filetypes=types)
if path:
self.vars[name].set(os.path.normpath(path))
def pick_firmware(self):
path = filedialog.askdirectory(title=self.cat('ui.pick_firmware'), mustexist=True)
if path:
self.vars['firmware'].set(os.path.normpath(path))
def pick_dest(self):
path = filedialog.askdirectory(title=self.cat('ui.pick_dest'), mustexist=False)
if path:
self.vars['dest'].set(os.path.normpath(path))
# ---- run ------------------------------------------------------------------------------------------------------
def start(self):
form = self.form()
problems = form.problems()
if problems:
self.form_error.configure(text=' '.join(self.cat(p) for p in problems))
self.fit()
return
self.form_error.configure(text='')
# 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
command = form.command(python, root=self.layout.root if self.layout.dev else None,
temp=self.run_args.get('temp'), verify_hashes=self.run_args.get('verify', False))
self.begin(command, self.layout.root)
def begin(self, command, cwd):
self.model = Model()
self.model.dest = self.vars['dest'].get().strip()
self.clear_log()
self.build_step_rows(self.model.steps)
self.cancel_button.configure(state='normal')
self.bound = [b for b in self.bound if b[0] is not self.cancel_button]
self.bind_text(self.cancel_button, 'text', 'ui.cancel')
self.show('run')
self.refresh_run()
self.process = Process(command, cwd=cwd, helper_python=self.layout.python)
self.root.after(POLL_MS, self.poll)
def build_step_rows(self, steps):
for w in self.steps_box.winfo_children():
w.destroy()
self.step_rows = {}
for s in steps:
row = ttk.Frame(self.steps_box)
row.pack(fill='x', pady=1)
glyph = ttk.Label(row, width=3)
glyph.pack(side='left')
name = ttk.Label(row)
name.pack(side='left')
self.step_rows[s] = (glyph, name)
def poll(self):
if self.process is None:
return
try:
while True:
line = self.process.lines.get_nowait()
if line is not None:
self.feed(line)
except Exception:
pass
code = self.process.poll()
self.refresh_run()
if code is None:
self.root.after(POLL_MS, self.poll)
return
self.model.finish(code)
self.process = None
if self.rebuild and self.model.result == 'ok' and not self.closing:
self.start_game()
return
self.refresh_run()
self.refresh_finish()
self.show('finish')
if self.closing:
self.root.destroy()
def feed(self, line):
"""One stdout line of the CLI: an event updates the model and the log, anything else goes to the log as is."""
event = parse_line(line)
if event is None:
if line.strip():
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)
self.log_entries.append(event)
self.append_log(describe_event(self.cat, event))
def refresh_run(self):
m = self.model
for s, (glyph, name) in self.step_rows.items():
state = m.states.get(s, PENDING)
glyph.configure(text=GLYPH[state], foreground=COLOR[state])
name.configure(text=self.cat('step.' + s) + (f' ({self.cat("ui.state_" + state)})'
if state in (SKIPPED, FAILED) else ''),
font=(self.ui_font, 10, 'bold') if state == RUNNING else (self.ui_font, 10))
mode = m.mode or 'install'
self.run_header.configure(text=self.cat('ui.running_' + mode if mode in ('install', 'resume', 'update')
else 'ui.running_install'))
if m.current and m.phase:
text = self.cat(f'phase.{m.current}.{m.phase}')
if m.total:
text += ' ' + amount(self.cat, m.done, m.total, m.unit)
elif m.current:
text = self.cat('step.' + m.current)
else:
text = ''
self.phase_label.configure(text=text)
frac = m.fraction()
if frac is None:
if str(self.bar.cget('mode')) != 'indeterminate':
self.bar.configure(mode='indeterminate')
self.bar.start(15)
else:
if str(self.bar.cget('mode')) == 'indeterminate':
self.bar.stop()
self.bar.configure(mode='determinate')
self.bar.configure(value=frac * 1000)
self.space_label.configure(text=m.need_text(self.cat))
self.warn_label.configure(text='\n'.join(self.cat(i, **p) for i, p in m.warnings))
self.fit() # new step rows and warnings make the screen taller
def toggle_log(self):
self.log_open = not self.log_open
if self.log_open:
self.log_frame.pack(fill='both', expand=True, pady=(8, 0))
else:
self.log_frame.pack_forget()
self.bound = [b for b in self.bound if b[0] is not self.log_toggle]
self.bind_text(self.log_toggle, 'text', 'ui.hide_log' if self.log_open else 'ui.show_log')
self.fit()
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')
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')
self.bound = [b for b in self.bound if b[0] is not self.cancel_button]
self.bind_text(self.cancel_button, 'text', 'ui.cancelling')
self.process.cancel()
def on_close(self):
if self.process:
if not messagebox.askyesno(self.cat('ui.title'), self.cat('ui.confirm_cancel')):
return
self.closing = True
self.cancel()
return
self.root.destroy()
# ---- finish ---------------------------------------------------------------------------------------------------
def refresh_finish(self):
m = self.model
result = m.result or 'ok'
self.finish_title.configure(text=self.cat('ui.result_' + result))
if result == 'ok':
text = self.cat('ui.done_text', dest=m.dest)
elif result == 'cancelled':
text = self.cat('ui.cancelled_text')
else:
err = m.error or ('ui.process_died', {'code': m.exit_code}, None)
text = self.cat(err[0], **err[1])
if m.log_path:
text += '\n\n' + self.cat('ui.log_file', path=m.log_path)
self.finish_text.configure(text=text)
for w in self.finish_steps.winfo_children():
w.destroy()
for s in m.steps:
state = m.states.get(s, PENDING)
ttk.Label(self.finish_steps, text=f'{GLYPH[state]} {self.cat("step." + s)}',
foreground=COLOR[state]).pack(anchor='w')
if result == 'ok':
self.open_button.state(['!disabled'])
else:
self.open_button.state(['disabled' if not Path(m.dest or '.').is_dir() else '!disabled'])
def start_game(self):
"""Starts the game of the install folder and closes the window."""
dest = Path(self.vars['dest'].get().strip())
exe = dest / ('nx2navi.exe' if os.name == 'nt' else 'nx2navi')
flags = subprocess.DETACHED_PROCESS if os.name == 'nt' else 0
if exe.is_file():
subprocess.Popen([str(exe)], cwd=str(dest), creationflags=flags, close_fds=True)
self.root.destroy()
def open_folder(self):
dest = self.model.dest
if dest and Path(dest).is_dir():
if os.name == 'nt':
os.startfile(dest)
else:
subprocess.Popen(['xdg-open', dest], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
# ---- self test ---------------------------------------------------------------------------------------------------
SAMPLE_START = {'type': 'start', 'release': 'selftest', 'mode': 'install', 'dest': 'Z:/selftest/NX2navi', 'log': 'D:\\log.txt',
'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', 'cleanup']}
SAMPLE_RUN = [
SAMPLE_START,
{'type': 'plan', 'run': ['check', 'fonts', 'extract'], 'skip': {}},
{'type': 'step', 'step': 'check', 'state': 'started'},
{'type': 'progress', 'step': 'check', 'phase': 'inputs'},
{'type': 'space', 'dest': 'Z:/selftest/NX2navi', 'need': 36_400_000_000, 'free': 210_000_000_000, 'temp': 'C:\\t',
'temp_need': 0, 'temp_free': 0, 'same_disk': True},
{'type': 'warning', 'id': 'warn.lang_needs_fonts', 'params': {'lang': 'ko'}},
{'type': 'step', 'step': 'check', 'state': 'done', 'seconds': 12.0},
{'type': 'step', 'step': 'extract', 'state': 'started'},
{'type': 'progress', 'step': 'extract', 'phase': 'copy', 'done': 6_000_000_000, 'total': 16_000_000_000,
'unit': 'bytes'},
]
SAMPLE_OK = [SAMPLE_START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'fonts': 'current', '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': 'fonts', 'state': 'skipped', 'reason': 'current'},
{'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')
root.attributes('-topmost', True)
root.update()
x, y, w, h = root.winfo_rootx(), root.winfo_rooty(), root.winfo_width(), root.winfo_height()
ImageGrab.grab(bbox=(x, y, x + w, y + h), all_screens=True).save(path)
def selftest(layout, shots=None):
"""Every screen in every language; the window closes itself. Returns 0 when nothing raised."""
fix_tcl_paths()
root = tk.Tk()
root.geometry('+60+40')
app = App(root, 'en', layout)
steps, mixed = [], []
def shot(name):
root.update()
if shots:
Path(shots).mkdir(parents=True, exist_ok=True)
grab(root, Path(shots) / f'{name}.png')
def run_all():
for lang in UI_LANGUAGES:
app.ui_var.set(lang)
app.switch_language()
tag = lang
app.vars['dest'].set('Z:/selftest/NX2navi')
app.vars['base'].set('Z:/selftest/nx2navi.xci')
app.vars['update'].set('Z:/selftest/nx2navi-1.2.1.nsp')
app.vars['keys'].set('Z:/selftest/prod.keys')
app.show('form')
app.start() # missing files: shows the problems
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:
app.feed(json.dumps(e))
app.log_open = False
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/NX2navi'
app.model.finish(0)
app.refresh_finish()
app.show('finish')
shot(f'finish-ok-{tag}')
app.model = Model()
for e in SAMPLE_RUN[:3] + [{'type': 'error', 'id': 'check.disk_space', 'step': 'check',
'params': {'path': 'Z:/selftest/NX2navi', 'need_gb': 36.4, 'free_gb': 20.1}},
{'type': 'end', 'result': 'failed', 'seconds': 3}]:
app.model.apply(e)
app.model.finish(1)
app.refresh_finish()
shot(f'finish-failed-{tag}')
app.model = Model()
app.model.finish(3)
app.refresh_finish()
shot(f'finish-cancelled-{tag}')
app.toggle_log()
root.destroy()
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) and mixed == [False] else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--selftest', action='store_true')
ap.add_argument('--shots', type=Path)
ap.add_argument('--lang', choices=UI_LANGUAGES)
ap.add_argument('--root', type=Path)
ap.add_argument('--rebuild', type=Path)
args = ap.parse_args(argv)
layout = layouts.find(args.root)
if args.selftest:
return selftest(layout, args.shots)
fix_tcl_paths()
root = tk.Tk()
App(root, args.lang or windows_ui_language(), layout, rebuild=args.rebuild)
root.mainloop()
return 0
if __name__ == '__main__':
sys.exit(main())

405
installer/guilogic.py Normal file
View File

@@ -0,0 +1,405 @@
"""The installer window without Tk: text catalogs, the form, the event model and the CLI subprocess.
gui.py draws; everything it decides lives here so tests/installer_gui_test.py runs it headless.
Catalog text of an id in the window language (installer/text/<lang>.json), English when that lacks it
Form what the player entered; command() and problems() build and check the CLI call
Model folds the CLI's JSON events (events.py) into step states, progress, space, errors and the result
Process runs `python -m installer ...`, cancels it with Ctrl+Break and feeds lines to a queue
"""
import ctypes
import json
import os
import queue
import signal
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
from pathlib import Path
from . import ini
from . import state as statefile
from .events import render
TEXT = Path(__file__).resolve().parent / 'text'
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans')
# what the language switch in the window's corner shows for each
UI_LANGUAGE_LABELS = {'en': 'English', 'ru': 'Русский', 'pt-BR': 'Português (Brasil)', 'zh-Hans': '简体中文'}
STEP_ORDER = ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', '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
LANG_PT_BR = 0x0416 # Portuguese (Brazil), the whole LANGID: Portugal's Portuguese stays English
# Windows LANGIDs that write Simplified Chinese: zh-CN, zh-SG. zh-TW, zh-HK and zh-MO write Traditional Chinese, which
# the window does not have.
LANGIDS_ZH_HANS = (0x0804, 0x1004)
def load_texts(lang):
path = TEXT / f'{lang}.json'
return json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {}
class Catalog:
"""Window text: ids from text/<lang>.json, then text/en.json, then the id itself."""
def __init__(self, lang='en'):
self.english = load_texts('en')
self.set_language(lang)
def set_language(self, lang):
self.lang = lang if lang in UI_LANGUAGES else 'en'
self.texts = load_texts(self.lang)
def has(self, id):
return id in self.texts or id in self.english
def __call__(self, id, **params):
text = self.texts.get(id) or self.english.get(id)
if text is None:
return id
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):
return ', '.join(str(v) for v in value) if isinstance(value, (list, tuple)) else value
def windows_ui_language():
"""The window language for the display language: the Windows one (ui_language_for_langid); elsewhere LC_ALL,
LC_MESSAGES or LANG ('ru', 'pt_BR', 'zh_CN' or 'zh_SG', else English)."""
if os.name != 'nt':
loc = (os.environ.get('LC_ALL') or os.environ.get('LC_MESSAGES') or os.environ.get('LANG') or '').lower()
return ('ru' if loc.startswith('ru') else 'pt-BR' if loc.startswith(('pt_br', 'pt-br'))
else 'zh-Hans' if loc.startswith(('zh_cn', 'zh-cn', 'zh_sg', 'zh-sg', 'zh_hans', 'zh-hans')) else 'en')
try:
langid = ctypes.windll.kernel32.GetUserDefaultUILanguage()
except (AttributeError, OSError):
return 'en'
return ui_language_for_langid(langid)
def ui_language_for_langid(langid):
"""'ru' for a Russian Windows LANGID, 'pt-BR' for Brazilian Portuguese, 'zh-Hans' for a Simplified Chinese one,
else 'en'."""
if langid & 0x3ff == LANG_RU:
return 'ru'
if langid == LANG_PT_BR:
return 'pt-BR'
if langid in LANGIDS_ZH_HANS:
return 'zh-Hans'
return 'en'
def default_game_language(ui):
"""The game language the form starts with. A Chinese window still starts with English: Chinese game text needs
the Switch shared fonts (ini.NEED_SHARED_FONTS), which the setup extracts only from a firmware folder, and the game
stops when they are missing; the player can still pick Chinese."""
return 'ru' if ui == 'ru' else 'en-US'
def gib(n):
"""Bytes as decimal gigabytes with one digit, the unit the check.disk_space message uses."""
return f'{n / 1e9:.1f}'
def amount(cat, done, total, unit):
"""'6.0 / 16.0 GB', '120 / 4000 files'..., the progress of a phase whose size is known."""
if unit == 'bytes':
return cat('ui.amount_bytes', done=gib(done or 0), total=gib(total))
id = f'ui.amount_{unit}'
return cat(id if cat.has(id) else 'ui.amount_other', done=done or 0, total=total, unit=unit or '')
# ---- the form ----------------------------------------------------------------------------------------------------
@dataclass
class Form:
base: str = ''
update: str = ''
keys: str = ''
firmware: str = ''
lang: str = ''
dest: str = ''
dlss: bool = False
def installed_state(self):
"""The recorded state of the install folder (nx2navi-install.json), or None. Never raises."""
if not self.dest.strip():
return None
try:
return statefile.load(Path(self.dest.strip()))
except statefile.StateError:
return None
def update_mode(self):
return self.installed_state() is not None
def problems(self):
"""Ids of the entries that are missing or wrong, in screen order. A folder with nx2navi-install.json needs only
itself; the CLI asks for the game files when it must extract again."""
found = []
update = self.update_mode()
if not self.dest.strip():
found.append('ui.need_dest')
if not update:
for name in ('base', 'update', 'keys'):
value = getattr(self, name).strip()
if not value:
found.append(f'ui.need_{name}')
elif not Path(value).is_file():
found.append(f'ui.missing_{name}')
if self.lang not in ini.LANGUAGES:
found.append('ui.need_lang')
else:
for name in ('base', 'update', 'keys'):
value = getattr(self, name).strip()
if value and not Path(value).is_file():
found.append(f'ui.missing_{name}')
if self.firmware.strip() and not Path(self.firmware.strip()).is_dir():
found.append('ui.missing_firmware')
return found
def command(self, python, root=None, temp=None, verify_hashes=False):
cmd = [str(python), '-m', 'installer']
for flag, value in (('--base', self.base), ('--update', self.update), ('--keys', self.keys),
('--firmware', self.firmware), ('--lang', self.lang), ('--dest', self.dest)):
if value.strip():
cmd += [flag, value.strip()]
if root:
cmd += ['--root', str(root)]
if temp:
cmd += ['--temp', str(temp)]
if verify_hashes:
cmd.append('--verify')
if self.dlss:
cmd.append('--dlss')
return cmd
# ---- events -> state ---------------------------------------------------------------------------------------------
PENDING, RUNNING, DONE, SKIPPED, FAILED = 'pending', 'running', 'done', 'skipped', 'failed'
def parse_line(line):
"""The event dict of a stdout line, or None when it is not a JSON event (a traceback line, noise)."""
line = line.strip()
if not line.startswith('{'):
return None
try:
event = json.loads(line)
except ValueError:
return None
return event if isinstance(event, dict) and isinstance(event.get('type'), str) else None
class Model:
"""What the window shows, folded from events. apply() takes one event; nothing else mutates it."""
def __init__(self):
self.steps = list(STEP_ORDER)
self.states = {s: PENDING for s in self.steps}
self.mode = ''
self.release = ''
self.log_path = ''
self.dest = ''
self.current = None # step id running
self.phase = None
self.done = self.total = None
self.unit = None
self.space = None # the space event
self.warnings = [] # (id, params)
self.error = None # (id, params, step)
self.result = None # ok | failed | cancelled once the end event arrived
self.seconds = None
self.exit_code = None
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', '')
self.log_path, self.dest = e.get('log', ''), e.get('dest', '')
elif kind == 'plan':
for s, reason in (e.get('skip') or {}).items():
if s in self.states and self.states[s] == PENDING:
self.states[s] = SKIPPED
elif kind == 'step':
s, state = e.get('step'), e.get('state')
if s not in self.states:
self.states[s] = PENDING
self.steps.append(s)
if state == 'started':
self.states[s], self.current = RUNNING, s
self.phase = self.done = self.total = self.unit = None
elif state == 'done':
self.states[s] = DONE
self.current = None if self.current == s else self.current
elif state == 'skipped':
self.states[s] = SKIPPED
elif kind == 'progress':
if e.get('step') in self.states and self.states[e['step']] == PENDING:
self.states[e['step']] = RUNNING
self.current = e.get('step', self.current)
self.phase = e.get('phase')
self.done, self.total, self.unit = e.get('done'), e.get('total'), e.get('unit')
elif kind == 'space':
self.space = e
elif kind == 'warning':
self.warnings.append((e.get('id', ''), e.get('params') or {}))
elif kind == 'error':
self.error = (e.get('id', ''), e.get('params') or {}, e.get('step'))
if e.get('step') in self.states:
self.states[e['step']] = FAILED
elif kind == 'end':
self.result = e.get('result')
self.seconds = e.get('seconds')
self.current = None
def fraction(self):
"""0..1 of the current phase, or None when its size is unknown."""
if self.total:
return max(0.0, min(1.0, (self.done or 0) / self.total))
return None
def finish(self, exit_code):
"""The process ended. A missing end event (the process died) counts as failed, or cancelled on exit code 3."""
self.exit_code = exit_code
if self.result is None:
self.result = 'cancelled' if exit_code == 3 else 'failed'
if self.result == 'failed' and self.error is None:
self.error = ('ui.process_died', {'code': exit_code}, self.current)
for s, state in self.states.items():
if state == RUNNING:
self.states[s] = FAILED if self.result == 'failed' else PENDING
def need_text(self, cat):
"""The space line, or '' before the check step reported."""
sp = self.space
if not sp:
return ''
key = 'ui.space_one' if sp.get('same_disk') or not sp.get('temp_need') else 'ui.space_two'
return cat(key, path=sp.get('dest', ''), need=gib(sp.get('need', 0)), free=gib(sp.get('free', 0)),
temp=sp.get('temp', ''), temp_need=gib(sp.get('temp_need', 0)),
temp_free=gib(sp.get('temp_free', 0)))
def describe_event(cat, e):
"""One log line for an event, in the window language."""
kind = e['type']
if kind == 'step':
text = f'{cat("step." + e["step"])}: {cat("ui.state_" + e["state"])}'
if 'seconds' in e:
text += f' ({cat("ui.seconds", n=format(e["seconds"], ".1f"))})'
elif e.get('reason'):
text += f' ({e["reason"]})'
return text
if kind == 'progress':
text = cat(f'phase.{e["step"]}.{e["phase"]}')
if e.get('total'):
text += ' ' + amount(cat, e.get('done'), e['total'], e.get('unit'))
return text
if kind in ('warning', 'error'):
return f'{cat("ui.log_" + kind)}: {cat(e["id"], **(e.get("params") or {}))}'
if kind == 'space':
return cat('ui.log_space', need=gib(e.get('need', 0)), free=gib(e.get('free', 0)))
if kind == 'end':
return f'{cat("ui.log_end")}: {cat("ui.result_" + str(e.get("result")))}'
return ''
# ---- the CLI subprocess ------------------------------------------------------------------------------------------
CREATE_NEW_PROCESS_GROUP = 0x200
CREATE_NO_WINDOW = 0x08000000
_BREAK = """
import ctypes, sys, time
k = ctypes.windll.kernel32
pid = int(sys.argv[1])
k.FreeConsole()
if k.AttachConsole(pid):
k.SetConsoleCtrlHandler(None, True)
k.GenerateConsoleCtrlEvent(1, pid)
time.sleep(1)
k.FreeConsole()
else:
sys.exit(1)
"""
def send_break(proc, python=None):
"""Ctrl+Break to the process group of proc (started with CREATE_NEW_PROCESS_GROUP). The window itself may have no
console (pythonw), so a short helper process attaches to the child's console and sends it. Elsewhere SIGTERM to
proc's session (Process starts it in one of its own), which installer/cli.py handles as Ctrl+Break."""
if os.name != 'nt':
try:
os.killpg(proc.pid, signal.SIGTERM)
return True
except OSError:
return False
helper = [str(python or sys.executable), '-c', _BREAK, str(proc.pid)]
flags = CREATE_NO_WINDOW if os.name == 'nt' else 0
r = subprocess.run(helper, creationflags=flags, capture_output=True)
return r.returncode == 0
class Process:
"""`python -m installer ...` with its stdout lines going to self.lines (a queue).
poll() returns the exit code once the process ended and its output is drained, else None."""
def __init__(self, command, cwd=None, helper_python=None, creationflags=None):
self.command = command
self.helper_python = helper_python
self.lines = queue.Queue()
env = dict(os.environ, PYTHONIOENCODING='utf-8', PYTHONUTF8='1', PYTHONUNBUFFERED='1')
if os.name == 'nt':
flags = (CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW) if creationflags is None else creationflags
group = {'creationflags': flags}
else:
group = {'start_new_session': True}
self.proc = subprocess.Popen(command, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, **group)
self.cancelled_at = None
self.reader = threading.Thread(target=self.read, daemon=True)
self.reader.start()
def read(self):
for raw in iter(self.proc.stdout.readline, b''):
self.lines.put(raw.decode('utf-8', errors='replace'))
self.proc.stdout.close()
def cancel(self):
if self.cancelled_at is None and self.proc.poll() is None:
self.cancelled_at = time.monotonic()
send_break(self.proc, self.helper_python)
def poll(self):
code = self.proc.poll()
if code is not None and not self.reader.is_alive() and self.lines.empty():
return code
return None
def kill(self):
if self.proc.poll() is None:
self.proc.kill()

98
installer/hostcheck.c Normal file
View File

@@ -0,0 +1,98 @@
// Host check of the installer's first step, compiled with the bundled clang at install time: does the CPU run
// -march=x86-64-v3 code (or only x86-64-v2), and does a Vulkan 1.3 device exist. Prints one JSON object on stdout.
// The Vulkan loader is opened at run time, so a machine without one gets "loader": false instead of a failed start.
#include <cpuid.h>
#include <stdio.h>
#include <string.h>
#include <vulkan/vulkan.h>
#ifdef _WIN32
#include <windows.h>
#define open_lib() LoadLibraryA("vulkan-1.dll")
#define lib_sym(l, n) ((void *)GetProcAddress((l), (n)))
#else
#include <dlfcn.h>
#define open_lib() dlopen("libvulkan.so.1", RTLD_NOW)
#define lib_sym(l, n) dlsym((l), (n))
#endif
static void json_string(const char *s) {
putchar('"');
for (; *s; s++) {
if (*s == '"' || *s == '\\') printf("\\%c", *s);
else if ((unsigned char)*s < 0x20) printf("\\u%04x", *s);
else putchar(*s);
}
putchar('"');
}
// The x86-64-v2 level from CPUID: SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CMPXCHG16B and LAHF/SAHF. Every CPU with
// SSE4.2 has the others, but the level is what the v2 build is compiled for, so check them all.
static int x86_64_v2(void) {
unsigned a, b, c, d;
if (!__get_cpuid(1, &a, &b, &c, &d)) return 0;
const unsigned sse3 = 1u << 0, ssse3 = 1u << 9, cx16 = 1u << 13, sse41 = 1u << 19, sse42 = 1u << 20,
popcnt = 1u << 23;
if ((c & (sse3 | ssse3 | cx16 | sse41 | sse42 | popcnt)) != (sse3 | ssse3 | cx16 | sse41 | sse42 | popcnt))
return 0;
if (!__get_cpuid(0x80000001, &a, &b, &c, &d)) return 0;
return (c & (1u << 0)) != 0; // LAHF/SAHF
}
// The x86-64-v3 level from CPUID: AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT and MOVBE, with the OS saving the YMM state.
// Not __builtin_cpu_supports("x86-64-v3"): clang reads that from the C runtime's CPU model, and libgcc before GCC 12
// (the Linux release's sysroot has GCC 10) has no level bits, so it answers false on every CPU.
static int x86_64_v3(void) {
if (!x86_64_v2()) return 0;
unsigned a, b, c, d;
if (!__get_cpuid(1, &a, &b, &c, &d)) return 0;
const unsigned fma = 1u << 12, movbe = 1u << 22, osxsave = 1u << 27, avx = 1u << 28, f16c = 1u << 29;
if ((c & (fma | movbe | osxsave | avx | f16c)) != (fma | movbe | osxsave | avx | f16c)) return 0;
unsigned lo, hi;
__asm__("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
if ((lo & 6) != 6) return 0; // XMM and YMM state enabled by the OS
if (!__get_cpuid_count(7, 0, &a, &b, &c, &d)) return 0;
const unsigned bmi1 = 1u << 3, avx2 = 1u << 5, bmi2 = 1u << 8;
if ((b & (bmi1 | avx2 | bmi2)) != (bmi1 | avx2 | bmi2)) return 0;
if (!__get_cpuid(0x80000001, &a, &b, &c, &d)) return 0;
return (c & (1u << 5)) != 0; // LZCNT (ABM)
}
int main(void) {
printf("{\"x86_64_v2\": %s, \"x86_64_v3\": %s, ", x86_64_v2() ? "true" : "false",
x86_64_v3() ? "true" : "false");
void *lib = open_lib();
PFN_vkGetInstanceProcAddr gipa = lib ? (PFN_vkGetInstanceProcAddr)lib_sym(lib, "vkGetInstanceProcAddr") : NULL;
if (!gipa) {
printf("\"loader\": false, \"devices\": []}\n");
return 0;
}
printf("\"loader\": true, ");
PFN_vkCreateInstance create = (PFN_vkCreateInstance)gipa(NULL, "vkCreateInstance");
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "nx2navi-install",
.apiVersion = VK_API_VERSION_1_3};
VkInstanceCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app};
VkInstance inst = VK_NULL_HANDLE;
VkResult r = create ? create(&ci, NULL, &inst) : VK_ERROR_INITIALIZATION_FAILED;
if (r != VK_SUCCESS) {
printf("\"instance\": %d, \"devices\": []}\n", (int)r);
return 0;
}
PFN_vkEnumeratePhysicalDevices enumerate = (PFN_vkEnumeratePhysicalDevices)gipa(inst, "vkEnumeratePhysicalDevices");
PFN_vkGetPhysicalDeviceProperties props = (PFN_vkGetPhysicalDeviceProperties)gipa(inst, "vkGetPhysicalDeviceProperties");
PFN_vkDestroyInstance destroy = (PFN_vkDestroyInstance)gipa(inst, "vkDestroyInstance");
VkPhysicalDevice devs[16];
uint32_t n = 16;
if (enumerate(inst, &n, devs) < 0) n = 0;
printf("\"instance\": 0, \"devices\": [");
for (uint32_t i = 0; i < n; i++) {
VkPhysicalDeviceProperties p;
props(devs[i], &p);
printf("%s{\"name\": ", i ? ", " : "");
json_string(p.deviceName);
printf(", \"api\": [%u, %u, %u], \"type\": %d}", VK_API_VERSION_MAJOR(p.apiVersion),
VK_API_VERSION_MINOR(p.apiVersion), VK_API_VERSION_PATCH(p.apiVersion), (int)p.deviceType);
}
printf("]}\n");
destroy(inst, NULL);
return 0;
}

78
installer/ini.py Normal file
View File

@@ -0,0 +1,78 @@
"""nx2navi.ini: set the game language and keep everything else (keys and syntax as runtime/cfg.c reads them).
A new file starts from nx2navi.ini.example, whose lines are all commented defaults. The language goes into `lang`
(a Switch language code, runtime/ov_system.c): an active `lang = ...` line is rewritten in place, else the commented
`# lang = ...` line of the example is activated, else the line is added to [language] (created at the end if
missing). Other lines, comments and line order stay as they are.
"""
import os
import re
from pathlib import Path
# runtime/ov_system.c: the codes NX2NAVI_LANG offers. Each language appears once, under the code the game accepts.
LANGUAGES = ('ja', 'en-US', 'en-GB', 'fr', 'fr-CA', 'de', 'it', 'es', 'es-419', 'nl', 'pt', 'pt-BR', 'ru', 'ko',
'zh-Hans', 'zh-Hant')
# Older installer builds wrote these two codes; they are read as the canonical ones and rewritten on the next install.
ALIASES = {'zh-CN': 'zh-Hans', 'zh-TW': 'zh-Hant'}
# Their text falls back to the Switch shared fonts (runtime/ov_system.c), which the fonts step extracts from the
# firmware folder when the player gives one.
NEED_SHARED_FONTS = ('ko', 'zh-Hans', 'zh-Hant')
ACTIVE = re.compile(r'^(\s*)(?:nx2navi_)?lang(\s*=\s*)(.*?)(\s*)$', re.IGNORECASE)
COMMENTED = re.compile(r'^\s*[#;]\s*(?:nx2navi_)?lang\s*=.*$', re.IGNORECASE)
SECTION = re.compile(r'^\s*\[(.*)\]\s*$')
def canonical_language(lang):
"""The code LANGUAGES lists for lang: an alias of an older installer build is mapped, anything else is kept."""
return ALIASES.get(lang, lang)
def set_language(text, lang):
"""text with `lang = <lang>` (an alias written as its canonical code); see the module docstring."""
lang = canonical_language(lang)
lines = text.splitlines()
for i, line in enumerate(lines):
m = ACTIVE.match(line)
if m:
lines[i] = f'{m.group(1)}lang{m.group(2)}{lang}'
return '\n'.join(lines) + '\n'
for i, line in enumerate(lines):
if COMMENTED.match(line):
lines[i] = f'lang = {lang}'
return '\n'.join(lines) + '\n'
for i, line in enumerate(lines):
m = SECTION.match(line)
if m and m.group(1).strip().lower() == 'language':
lines.insert(i + 1, f'lang = {lang}')
return '\n'.join(lines) + '\n'
if lines and lines[-1].strip():
lines.append('')
lines += ['[language]', f'lang = {lang}']
return '\n'.join(lines) + '\n'
def get_language(text):
for line in text.splitlines():
m = ACTIVE.match(line)
if m:
return m.group(3)
return None
def write(dest, lang, example=None):
"""Write dest/nx2navi.ini with lang; an existing file keeps its other lines. Returns the path."""
path = Path(dest) / 'nx2navi.ini'
if path.is_file():
text = path.read_text(encoding='utf-8-sig')
elif example and Path(example).is_file():
text = Path(example).read_text(encoding='utf-8')
else:
text = ''
new = set_language(text, lang)
if path.is_file() and new == text:
return path
tmp = path.with_name('nx2navi.ini.tmp')
tmp.write_text(new, encoding='utf-8', newline='\n')
os.replace(tmp, path)
return path

View File

@@ -0,0 +1,51 @@
/* NX2navi-Setup.exe: starts python\pythonw.exe -m installer.gui with this exe's folder as the working directory.
No console window. The two message strings come from the catalog (installer/text/<lang>.json, ids launcher.title and
launcher.python_missing); tools/make_release.py writes them into launcher_text.h before it compiles this file.
Build: llvm/bin/llvm-windres -I runtime -O coff launcher.rc -o launcher_rc.o, then
llvm/bin/clang -O2 -mwindows launcher.c launcher_rc.o -o NX2navi-Setup.exe */
#include <windows.h>
#include <wchar.h>
#include "launcher_text.h"
#define LANGID_RUSSIAN 0x19 /* primary language id */
#define LANGID_PT_BR 0x0416 /* the whole LANGID: Portugal's Portuguese stays English */
#define PATH_CHARS (MAX_PATH * 2)
/* The language of the window (installer/guilogic.py ui_language_for_langid): Russian, Simplified Chinese (zh-CN and
zh-SG; the Traditional Chinese regions get English, as the window has no Traditional Chinese), else English. */
static void fail(void)
{
LANGID ui = GetUserDefaultUILanguage();
int russian = (ui & 0x3ff) == LANGID_RUSSIAN, brazilian = ui == LANGID_PT_BR;
int chinese = ui == MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) ||
ui == MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SINGAPORE);
MessageBoxW(NULL,
russian ? LAUNCHER_PYTHON_MISSING_RU
: brazilian ? LAUNCHER_PYTHON_MISSING_PT_BR
: chinese ? LAUNCHER_PYTHON_MISSING_ZH_HANS
: LAUNCHER_PYTHON_MISSING_EN,
russian ? LAUNCHER_TITLE_RU : brazilian ? LAUNCHER_TITLE_PT_BR : chinese ? LAUNCHER_TITLE_ZH_HANS
: LAUNCHER_TITLE_EN,
MB_OK | MB_ICONERROR);
}
int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int show)
{
wchar_t folder[PATH_CHARS], python[PATH_CHARS], command[PATH_CHARS + 64];
DWORD n = GetModuleFileNameW(NULL, folder, PATH_CHARS);
STARTUPINFOW si = { sizeof si };
PROCESS_INFORMATION pi;
(void)instance; (void)previous; (void)command_line; (void)show;
if (n == 0 || n >= PATH_CHARS) { fail(); return 1; }
while (n > 0 && folder[n - 1] != L'\\') n--;
folder[n > 0 ? n - 1 : 0] = 0;
if (swprintf(python, PATH_CHARS, L"%ls\\python\\pythonw.exe", folder) < 0 ||
GetFileAttributesW(python) == INVALID_FILE_ATTRIBUTES) { fail(); return 1; }
if (swprintf(command, PATH_CHARS + 64, L"\"%ls\" -m installer.gui", python) < 0) { fail(); return 1; }
if (!CreateProcessW(python, command, NULL, NULL, FALSE, 0, NULL, folder, &si, &pi)) { fail(); return 1; }
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}

View File

@@ -0,0 +1,3 @@
/* The icon of NX2navi-Setup.exe: runtime/nx2navi.ico, the icon of nx2navi.exe. tools/make_release.py compiles this file with
llvm-windres -I runtime and links it with launcher.c. */
1 ICON "nx2navi.ico"

193
installer/layout.py Normal file
View File

@@ -0,0 +1,193 @@
"""Where the installer finds what it runs: the one place that maps the release folder and a repository checkout.
Release (docs/installer.md "Release layout"), root = the unpacked folder:
python/python.exe runs every tool (numpy, lz4, cryptography, compression.zstd); its ._pth puts .., ../tools
and ../recomp on sys.path, so `python -m installer` imports from the release folder
recomp/, tools/ the lifter and the scripts; recomp/patches-<v>.txt, tools/data/expected-v<version>.json for
each supported update (SUPPORTED)
llvm/ llvm-mingw (bin/clang.exe)
runtime/ libnx2navirt.a and libnx2navirt-v2.a (x86-64-v3 / v2), the headers, install-side sources (romfs.c,
patches.c, ov_zstd.c) and nx2navi.ico; runtime/deps/ holds
include/ + lib/ of Vulkan, SDL3, Opus, libvpx and VMA (build_game.py --deps)
bin/ nx2navi_xlate.exe (+ nx2navi_xlate.id), hactool.exe, ninja.exe, SDL3.dll, libopus-0.dll
data/shader_list.tsv the MacNativeGames shader list
data/pgo-<v>.profdata the execution profile the update's code is compiled with (tools/pgo.py; Windows only);
without one the game is built at -O1
nx2navi.ini.example
VERSION the release version, one line
temp/ the default temp folder (created)
Linux release (the AppImage's folder, docs/installer.md "Linux release"): python/bin/python3 (python-build-standalone,
with tkinter), llvm/ with clang, lld and llvm-ar plus llvm/sysroot (the glibc headers and libraries the game links
against), runtime/deps/ with include/ and the static Opus, libvpx and zstd, bin/ without .exe and with libSDL3.so.0.
Dev mode, root = a repository checkout (no python/python.exe): build/py314-embed/py/python.exe (the embeddable
Python the release ships, with the same packages), else this Python; toolchain/llvm-mingw-*/ and toolchain/deps-mingw;
runtime/ as the sources with build/install-rtlib/libnx2navirt.a and libnx2navirt-v2.a (tools/build_game.py --make-runtime-lib
--out build/install-rtlib, once per --cpu); MSYS2 UCRT64 ninja.exe; toolchain/hactool; build/xlate/nx2navi_xlate.exe; the shader list from
refs/MacNativeGames; build/pgo/pgo-<v>.profdata when there is one; build/install-temp. The version is VERSION with -dev and the commit: 0.1.0-dev+973c626. On Linux,
dev mode takes clang, lld and ninja from PATH and the system's libraries (no deps folder, no SDL3 copy).
"""
import os
import shutil
import subprocess
import sys
from dataclasses import dataclass, field
from pathlib import Path
WIN = os.name == 'nt'
EXE = '.exe' if WIN else ''
UCRT = Path(r'C:\msys64\ucrt64\bin')
SUPPORTED = ('1.2.1', '1.4.3', '1.1.0') # updates the installer builds; the check identifies the player's by hash
def version_tag(version):
"""'1.4.3' -> 'v143': the version name of build_game.py, make_romfs_patches.py and the patch tables."""
return 'v' + version.replace('.', '')
@dataclass(frozen=True)
class Layout:
root: Path
dev: bool
release: str
python: Path # runs the tools
tools: Path
recomp: Path
llvm: Path # llvm-mingw tree; on Linux the tree with bin/clang (a release's, or the system's /usr)
deps: Path | None # include/ and lib/ for the link; None: the system's (Linux dev mode)
runtime: Path # runtime headers and install-side sources
runtime_lib: Path # libnx2navirt.a
ninja: Path
hactool: Path
xlate: Path # nx2navi_xlate.exe; a nx2navi_xlate.id beside it is copied too
dlls: tuple = field(default_factory=tuple)
shader_list: Path | None = None # None: dev, read from refs/MacNativeGames through git
ini_example: Path | None = None
temp: Path | None = None
sysroot: Path | None = None # Linux release: what the game links against, instead of the host's
runtime_lib_v2: Path | None = None # libnx2navirt-v2.a: the runtime for CPUs without AVX2 (build_game.py --cpu v2)
pgo_dir: Path | None = None # pgo-<v>.profdata (tools/pgo.py); None: no profiles (Linux)
@property
def clang(self):
return self.llvm / 'bin' / ('clang' + EXE)
def runtime_lib_for(self, cpu):
"""The prebuilt runtime library for cpu (v2 or v3). None in dev mode when it was not built: the runtime is
then compiled from the sources in runtime/ instead."""
lib = self.runtime_lib_v2 if cpu == 'v2' else self.runtime_lib
if lib and lib.is_file():
return lib
return None if self.dev else lib
def pgo(self, version):
"""The execution profile build_game.py --pgo compiles the update's code with, None without one (the game is
then built at -O1)."""
p = self.pgo_dir / f'pgo-{version_tag(version)}.profdata' if self.pgo_dir else None
return p if p and p.is_file() else None
def patches(self, version):
"""The code patch table for recomp/gen.py."""
return self.recomp / f'patches-{version_tag(version)}.txt'
def expected(self, version):
"""The expected hashes of the update."""
return self.tools / 'data' / f'expected-v{version}.json'
def missing(self, cpu='v3'):
"""Paths the steps need that do not exist. cpu picks the runtime library the host will use."""
lib = self.runtime_lib_for(cpu)
need = [self.python, self.tools / 'extract.py', self.tools / 'ncz.py', self.tools / 'build_game.py',
self.tools / 'prepare_shaders.py',
self.tools / 'pack_shader_cache.py', self.tools / 'make_romfs_patches.py', self.tools / 'ultrawide_layout.py',
self.tools / 'button_icons.py',
self.tools / 'vendor' / 'macnativegames' / 'extract_shared_fonts.py',
self.recomp / 'gen.py',
self.clang,
*((self.deps / 'include', self.deps / 'lib') if self.deps else ()), self.runtime, *([lib] if lib else ()),
self.ninja, self.hactool,
self.xlate, *self.dlls, *(f(v) for v in SUPPORTED for f in (self.patches, self.expected))]
if self.shader_list:
need.append(self.shader_list)
if self.sysroot:
need.append(self.sysroot)
return [str(p) for p in need if not p.exists()]
def release_python(root):
return root / 'python' / ('python.exe' if WIN else 'bin/python3')
def is_release(root):
return release_python(root).is_file()
def release_layout(root):
version = root / 'VERSION'
return Layout(
root=root, dev=False,
release=version.read_text(encoding='utf-8').strip() if version.is_file() else 'unknown',
python=release_python(root),
tools=root / 'tools', recomp=root / 'recomp',
llvm=root / 'llvm', deps=root / 'runtime' / 'deps', runtime=root / 'runtime',
runtime_lib=root / 'runtime' / 'libnx2navirt.a',
runtime_lib_v2=root / 'runtime' / 'libnx2navirt-v2.a',
ninja=root / 'bin' / ('ninja' + EXE), hactool=root / 'bin' / ('hactool' + EXE),
xlate=root / 'bin' / ('nx2navi_xlate' + EXE),
dlls=(root / 'bin' / 'SDL3.dll', root / 'bin' / 'libopus-0.dll') if WIN else (root / 'bin' / 'libSDL3.so.0',),
shader_list=root / 'data' / 'shader_list.tsv', ini_example=root / 'nx2navi.ini.example',
pgo_dir=root / 'data' if WIN else None,
# Linux: None, the install folder's .setup-temp (installer/cli.py): the AppImage is mounted read-only, and on
# a Steam Deck /home is often too full for the generated C while the install folder is on the SD card
temp=root / 'temp' if WIN else None,
sysroot=None if WIN else root / 'llvm' / 'sysroot')
def dev_layout(root):
if not WIN:
return dev_layout_posix(root)
commit = subprocess.run(['git', '-C', str(root), 'rev-parse', '--short', 'HEAD'], capture_output=True,
text=True).stdout.strip()
embed = root / 'build' / 'py314-embed' / 'py' / ('python' + EXE)
trees = sorted(p.parent.parent for p in (root / 'toolchain').glob('llvm-mingw-*/llvm-mingw-*/bin/clang' + EXE))
deps = root / 'toolchain' / 'deps-mingw'
semver = (root / 'VERSION').read_text(encoding='utf-8').strip()
return Layout(
root=root, dev=True, release=f'{semver}-dev+{commit or "unknown"}',
python=embed if embed.is_file() else Path(sys.executable),
tools=root / 'tools', recomp=root / 'recomp',
llvm=trees[-1] if trees else root / 'toolchain' / 'llvm-mingw-missing', deps=deps,
runtime=root / 'runtime', runtime_lib=root / 'build' / 'install-rtlib' / 'libnx2navirt.a',
runtime_lib_v2=root / 'build' / 'install-rtlib' / 'libnx2navirt-v2.a',
ninja=UCRT / ('ninja' + EXE), hactool=root / 'toolchain' / 'hactool' / ('hactool' + EXE),
xlate=root / 'build' / 'xlate' / ('nx2navi_xlate' + EXE),
dlls=tuple(sorted((deps / 'bin').glob('*.dll'))),
shader_list=None, ini_example=root / 'nx2navi.ini.example', temp=root / 'build' / 'install-temp',
pgo_dir=root / 'build' / 'pgo')
def dev_commit(root):
return subprocess.run(['git', '-C', str(root), 'rev-parse', '--short', 'HEAD'], capture_output=True,
text=True).stdout.strip()
def dev_layout_posix(root):
clang, ninja = shutil.which('clang'), shutil.which('ninja')
semver = (root / 'VERSION').read_text(encoding='utf-8').strip()
return Layout(
root=root, dev=True, release=f'{semver}-dev+{dev_commit(root) or "unknown"}',
python=Path(sys.executable), tools=root / 'tools', recomp=root / 'recomp',
llvm=Path(clang).parent.parent if clang else root / 'toolchain' / 'clang-missing', deps=None,
runtime=root / 'runtime', runtime_lib=root / 'build' / 'install-rtlib' / 'libnx2navirt.a',
runtime_lib_v2=root / 'build' / 'install-rtlib' / 'libnx2navirt-v2.a',
ninja=Path(ninja) if ninja else root / 'toolchain' / 'ninja-missing',
hactool=root / 'toolchain' / 'hactool' / 'hactool', xlate=root / 'build' / 'xlate' / 'nx2navi_xlate',
shader_list=None, ini_example=root / 'nx2navi.ini.example', temp=root / 'build' / 'install-temp')
def find(root=None):
"""The layout of root (default: the folder above this package)."""
root = Path(root or Path(__file__).resolve().parent.parent).resolve()
return release_layout(root) if is_release(root) else dev_layout(root)

151
installer/runner.py Normal file
View File

@@ -0,0 +1,151 @@
"""Which steps run, in what order, and the bookkeeping around them: fresh install, resume and update are one rule.
Each step has a key: a fingerprint of everything its output depends on, computed before anything runs (a step's key
includes the keys of the steps it reads from, so a change upstream reaches every step below it). A step is skipped
when nx2navi-install.json records it with the same key and its output still matches the record (Step.current, cheap).
Otherwise it runs. A transient step (its output lives in the temp folder and only the next step reads it) runs only
when the next step runs. `always` steps (check, cleanup) run every time.
Update mode is the same rule with a newer release: the extraction's key depends only on the expected hashes, so a
release that changes the lifter or the runtime keeps romfs/ and exefs/ and rebuilds from lift on. Before keeping the
output of a step recorded by another release (or with --verify), the check step calls Step.verify (expensive: the full
RomFS hash); a mismatch makes the step run again.
A failed or cancelled run leaves the finished steps recorded; the next run starts at the first step that is not.
"""
import datetime
import traceback
from . import state as statefile
class InstallError(Exception):
"""A failure with a message id (installer/text/en.json) and its parameters."""
def __init__(self, id, **params):
super().__init__(id)
self.id, self.params = id, params
class Step:
id = ''
transient = False
always = False
def key(self, ctx):
"""Fingerprint of the step's inputs; may read ctx.keys of earlier steps."""
return ''
def current(self, ctx, record):
"""True when the recorded output is still in place (cheap checks only)."""
return True
def verify(self, ctx, record):
"""True when the recorded output passes the full check (hashes); called before keeping another release's
output."""
return True
def run(self, ctx):
"""Do the work. Returns fields to record with the step."""
return {}
class Context:
def __init__(self, layout, dest, temp, reporter, options, state=None, verify=False):
self.layout, self.dest, self.temp, self.reporter, self.options = layout, dest, temp, reporter, options
self.state = state or statefile.empty(layout.release)
self.verify = verify
self.mode = 'install' if state is None else 'resume' if state.get('release') == layout.release else 'update'
self.keys, self.runs, self.reasons, self.steps, self.forced = {}, {}, {}, [], set()
def record(self, step_id):
return self.state['steps'].get(step_id)
def will_run(self, step_id):
return self.runs.get(step_id, False)
def save(self):
self.dest.mkdir(parents=True, exist_ok=True)
statefile.save(self.dest, self.state)
def plan(self, forced=()):
"""Fill keys (once), runs and reasons. forced: step ids that must run."""
if not self.keys:
for s in self.steps:
self.keys[s.id] = s.key(self)
for s in self.steps:
rec = self.record(s.id)
if s.always or s.id in forced:
self.runs[s.id] = True
else:
self.runs[s.id] = not (rec and rec.get('key') == self.keys[s.id] and s.current(self, rec))
self.reasons[s.id] = '' if self.runs[s.id] else 'current'
for i in range(len(self.steps) - 2, -1, -1):
s, after = self.steps[i], self.steps[i + 1]
if s.transient and self.runs[s.id] and not self.runs[after.id]:
self.runs[s.id], self.reasons[s.id] = False, 'not_needed'
self.forced = set(forced)
def verify_kept(self, progress_step):
"""Full check of every kept step output that another release recorded (or of all with --verify). A step that
fails it is planned to run. Returns the ids that failed."""
failed = []
for s in self.steps:
rec = self.record(s.id)
if self.runs[s.id] or self.reasons[s.id] != 'current' or s.always:
continue
if not (self.verify or rec.get('release') != self.layout.release):
continue
if not s.verify(self, rec):
failed.append(s.id)
if failed:
for f in failed:
self.reporter.warning('state.output_changed', step=f)
self.plan(self.forced | set(failed))
return failed
def now_utc():
return datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
def run_steps(steps, ctx):
"""Run the plan. Returns 'ok', 'failed' or 'cancelled'; events and the log say why."""
rep = ctx.reporter
ctx.steps = steps
current = None
try:
ctx.plan()
rep.emit('plan', run=[s.id for s in steps if ctx.runs[s.id]],
skip={s.id: ctx.reasons[s.id] for s in steps if not ctx.runs[s.id]})
for s in steps:
if not ctx.runs[s.id]:
rep.step(s.id, 'skipped', reason=ctx.reasons[s.id])
continue
current = s.id
rep.step(s.id, 'started')
t0 = rep.elapsed()
fields = s.run(ctx) or {}
seconds = round(rep.elapsed() - t0, 1)
if not s.always:
ctx.state['steps'][s.id] = {'key': ctx.keys[s.id], 'release': ctx.layout.release,
'finished': now_utc(), 'seconds': seconds, **fields}
ctx.save() # the first save, after the check, creates the install folder
rep.step(s.id, 'done', seconds=seconds)
current = None
ctx.state['release'] = ctx.layout.release
ctx.save()
return 'ok'
except InstallError as e:
rep.error(e.id, e.params, step=current)
return 'failed'
except statefile.StateError as e:
rep.error(e.id, {'path': str(e.path)}, step=current)
return 'failed'
except KeyboardInterrupt:
rep.log(f'cancelled during {current}')
return 'cancelled'
except Exception as e:
rep.log(traceback.format_exc())
rep.error('internal', {'exception': type(e).__name__, 'detail': str(e)}, step=current)
return 'failed'

54
installer/state.py Normal file
View File

@@ -0,0 +1,54 @@
"""nx2navi-install.json in the install folder: what built it and which steps finished.
{"format": 1, "release": "...", "lang": "en-US",
"inputs": {"base": {"name", "size", "sha256"}, "update": {...}},
"steps": {"<step>": {"key": "<input fingerprint>", "release": "...", "finished": "<UTC time>", "seconds": 12.3,
...the step's own fields}}}
A step's key fingerprints everything its output depends on (runner.py), so a step whose recorded key equals the
current one and whose output still checks out is not run again. The file is replaced atomically after each step.
No key value or keys file content is ever stored.
"""
import json
import os
from pathlib import Path
NAME = 'nx2navi-install.json'
FORMAT = 1
class StateError(Exception):
def __init__(self, id, path):
super().__init__(id)
self.id, self.path = id, path
def empty(release):
return {'format': FORMAT, 'release': release, 'inputs': {}, 'steps': {}}
def load(dest):
"""The state of dest, or None when the folder has none. StateError for an unreadable or newer file."""
path = Path(dest) / NAME
if not path.is_file():
return None
try:
data = json.loads(path.read_text(encoding='utf-8'))
except (OSError, ValueError):
raise StateError('state.unreadable', path) from None
if not isinstance(data, dict) or not isinstance(data.get('steps'), dict):
raise StateError('state.unreadable', path)
if data.get('format', 0) > FORMAT:
raise StateError('state.newer_format', path)
return data
def save(dest, data):
path = Path(dest) / NAME
tmp = path.with_name(NAME + '.tmp')
with open(tmp, 'w', encoding='utf-8', newline='\n') as f:
json.dump(data, f, indent=1, ensure_ascii=False)
f.write('\n')
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)

1267
installer/steps.py Normal file

File diff suppressed because it is too large Load Diff

208
installer/text/en.json Normal file
View File

@@ -0,0 +1,208 @@
{
"step.check": "Checking the computer and the game files",
"step.fonts": "Extracting the system fonts",
"step.extract": "Extracting the game",
"step.lift": "Translating the game code to C",
"step.compile": "Compiling {game_exe}",
"step.prepare": "Preparing the shaders",
"step.dlss": "Downloading NVIDIA DLSS",
"step.cleanup": "Cleaning up",
"phase.check.host": "Checking the processor and the graphics card",
"phase.check.verify": "Checking the files already installed",
"phase.check.verify_romfs": "Checking the installed game data",
"phase.check.inputs": "Opening the game files with the keys",
"phase.check.unpack_base": "Unpacking the compressed base game",
"phase.check.unpack_update": "Unpacking the compressed update",
"phase.check.versions": "Checking the game versions",
"phase.fonts.extract": "Extracting the shared fonts from the firmware",
"phase.fonts.copy": "Copying the shared fonts into the install folder",
"phase.extract.hash_base": "Computing the checksum of the base game",
"phase.extract.hash_update": "Computing the checksum of the update",
"phase.extract.exefs": "Extracting the game code",
"phase.extract.copy": "Copying the game data",
"phase.extract.merge": "Applying the update to the game data",
"phase.extract.diagnose": "Finding which game file is damaged",
"phase.extract.index": "Verifying the game data",
"phase.lift.discover": "Finding the functions",
"phase.lift.emit": "Writing C code",
"phase.compile.compile": "Compiling",
"phase.compile.link": "Linking {game_exe}",
"phase.prepare.romfs_patches": "Writing the 60 fps game data patches",
"phase.prepare.seed": "Reading the shaders from the game data",
"phase.prepare.translate": "Translating the shaders",
"phase.prepare.libraries": "Building the shaders for the graphics driver",
"phase.prepare.pack": "Packing the shader cache into one file",
"phase.dlss.download": "Downloading nvngx_dlss.dll from NVIDIA's DLSS SDK",
"phase.cleanup.ini": "Writing nx2navi.ini",
"phase.cleanup.temp": "Removing temporary files",
"cli.usage": "Invalid command line: {detail}",
"internal": "Unexpected error ({exception}): {detail}",
"state.unreadable": "{path} cannot be read. Choose another folder or delete that file.",
"state.newer_format": "{path} was written by a newer installer. Use that installer or another folder.",
"state.output_changed": "Installed files of step '{step}' changed since they were made; that step runs again.",
"check.release_incomplete": "The installer folder is incomplete; missing: {paths}. Unpack the release again.",
"check.dest_not_folder": "The install location {path} is a file, not a folder.",
"check.dest_not_empty": "The install folder {path} is not empty and holds no earlier installation. Choose an empty folder.",
"check.lang_missing": "Choose the game language.",
"check.lang_unknown": "Unknown language '{lang}'. Known: {known}.",
"check.toolchain_broken": "The bundled compiler does not work: {detail}",
"check.glibc_old": "This system's C library is glibc {version}; the setup's compiler needs {need} or later (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 and newer have it). Updating the system fixes this.",
"check.host_probe_failed": "The computer check did not run (exit code {code}).",
"check.cpu_too_old": "This processor lacks x86-64-v2 (SSE4.2, POPCNT and CMPXCHG16B), the oldest level the game is built for. Intel Nehalem (2008) or AMD Bulldozer (2011) and newer have it.",
"check.vulkan_missing": "No Vulkan driver is installed. Install the latest driver for your graphics card.",
"check.vulkan_no_device": "Vulkan finds no graphics card. Install the latest driver for your graphics card.",
"check.vulkan_too_old": "The game needs a graphics card with Vulkan 1.3; found: {devices}. Update the graphics driver.",
"check.no_display": "Preparing the shaders needs a display. Run the setup from the desktop session, or export DISPLAY=:0 (on a Steam Deck in Game Mode also XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "The game files are needed: choose the base game, the 1.1.0 or 1.2.1 or 1.4.3 update and prod.keys.",
"check.input_missing": "File not found ({input}): {path}",
"check.keys_unreadable": "The keys file cannot be read. Choose a prod.keys file.",
"check.keys_no_header_key": "The keys file has no header_key. Dump prod.keys from your console again.",
"check.keys_wrong": "The keys cannot open the {input} file. Use the prod.keys of your console.",
"check.keys_too_old": "The keys file is too old for the {input} file (needs key generation {generation}). Dump prod.keys from a console with newer firmware.",
"check.not_game_file": "The {input} file is not an XCI, NSP, XCZ or NSZ game file.",
"check.file_unreadable": "The {input} file cannot be read: {detail}",
"check.unpack_failed": "The compressed {input} file could not be unpacked: {detail}",
"check.ticket_personalized": "The {input} file carries a personalized ticket; a common ticket is needed.",
"check.ticket_missing": "The {input} file lacks the ticket its content needs.",
"check.base_not_nx2navi": "The base game file is not The Legend of Zelda: Ocarina of Time ({detail}).",
"check.base_is_update": "The base game file is an update. Choose the base game NSP or XCI (version 1.0.0) here and this file as the update.",
"check.base_combined": "The base game file holds several packages (base game, update or DLC in one file). Choose a base game dump that contains only the game.",
"check.update_not_nsp": "The update must be an NSP or NSZ file.",
"check.update_is_base": "The update file holds a base game. Choose the 1.1.0 or 1.2.1 or 1.4.3 update NSP.",
"check.update_not_nx2navi": "The update file is not a Ocarina of Time update ({detail}).",
"check.exefs_failed": "The game code of the {input} file failed its checks; see {log}.",
"check.input_damaged": "The {input} file is damaged or incomplete: {path} ({detail}). Copy that file again from its source, or dump it again, then run the setup again.",
"check.base_wrong_version": "The base game is not version 1.0.0 ({modules} differ).",
"check.update_wrong_version": "The update is version {found}; this release takes {wanted}.",
"check.disk_space": "Not enough free space for {path}: {need_gb} GB needed, {free_gb} GB free.",
"check.firmware_missing": "The firmware folder {path} does not exist. Choose the firmware's Contents/registered folder.",
"check.firmware_empty": "The firmware folder {path} holds no NCA files. Choose the firmware's Contents/registered folder.",
"check.fonts_keys_needed": "The shared fonts for this language are not installed yet; choose prod.keys so the setup can extract them from the firmware.",
"extract.exefs_mismatch": "The extracted game code does not match version {version} ({modules}).",
"extract.romfs_merge_failed": "Applying the update to the game data failed: {detail}. Details: {log}",
"extract.romfs_mismatch": "The extracted game data does not match version {version} (size {size}, checksum {sha256}...).",
"fonts.failed": "Extracting the shared fonts failed (exit code {code}): {detail}. Details: {log}",
"fonts.incomplete": "The shared font extraction did not write every file ({files}).",
"fonts.copy_failed": "The shared fonts cannot be copied into {path}: {detail}",
"lift.failed": "Translating the game code failed (exit code {code}). Details: {log}",
"compile.failed": "Compiling {game_exe} failed (exit code {code}). Details: {log}",
"compile.exe_in_use": "{path} is in use. Close the game and run the installer again.",
"prepare.xlate_in_use": "{path} is in use. Close the game, end any nx2navi_xlate process left from an earlier run, then run the installer again.",
"prepare.shader_list_missing": "The shader list is missing.",
"prepare.romfs_patches_failed": "Writing the game data patches failed (exit code {code}). Details: {log}",
"prepare.shaders_failed": "Preparing the shaders failed (exit code {code}). Details: {log}",
"cleanup.romfs_unreadable": "The game data in {path} is missing or cannot be read after the install. Restart Windows, then run the installer again on the same folder: it extracts the game data again and keeps the rest.",
"prepare.pack_failed": "Packing the shader cache failed (exit code {code}). Details: {log}",
"cleanup.ini_failed": "nx2navi.ini cannot be written: {detail}",
"warn.lang_needs_fonts": "Text in {lang} needs the Switch system fonts, and none were given. The game will not start in this language until they are added. Choose the firmware folder (Contents/registered), or see \"Switch system fonts\" in docs/installer.md.",
"warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.",
"warn.cheats_skipped": "The cheats of the mods folder that change the game's code could not be built; the game installs without them. Details: {log}",
"warn.exefs_skipped": "The mods' ExeFS patches (.ips, .pchtxt) could not be built; the game installs without them. Details: {log}",
"warn.xbox_prompts_failed": "The Xbox or PC button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
"warn.shaders_skipped": "The graphics driver crashed while building some shaders, so {count} were left out of the preparation. The game builds them when it first needs them, and the driver may crash there too; a driver update may fix it. Details: {log}",
"warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.",
"warn.dlss_kept": "A DLSS library is already in the install folder ({path}); the setup keeps it.",
"warn.dlss_download_failed": "NVIDIA DLSS could not be downloaded from {url}: {detail}. The game runs without it; the next setup run tries again.",
"ui.title": "NX2navi Setup",
"ui.rebuild_title": "Rebuilding the game for your mods",
"ui.start_game": "Start the game",
"ui.version": "version {version}",
"ui.intro": "Builds a playable Ocarina of Time folder from your own game files. This takes a while and runs once.",
"ui.notice": "The folder this setup builds contains the game. It is for your own use only; do not share or upload it.",
"ui.keys_private": "The keys file is read in place. Its contents are never shown, copied or stored.",
"ui.base": "Base game (NSP, XCI, NSZ or XCZ)",
"ui.update": "Update 1.1.0 or 1.2.1 or 1.4.3 (NSP or NSZ)",
"ui.keys": "prod.keys",
"ui.firmware": "Firmware folder (optional)",
"ui.game_language": "Game language",
"ui.dest": "Install folder",
"ui.browse": "Browse...",
"ui.pick_game": "Choose the base game file",
"ui.pick_update": "Choose the 1.1.0 or 1.2.1 or 1.4.3 update file",
"ui.pick_keys": "Choose prod.keys",
"ui.pick_firmware": "Choose the Switch firmware folder (Contents/registered)",
"ui.pick_dest": "Choose the install folder",
"ui.firmware_help": "For Chinese, Korean and Traditional Chinese text: the firmware's Contents/registered folder, for example from Ryujinx or The hardware. The setup copies the Switch system fonts from it into the install folder.",
"ui.dlss": "Download NVIDIA DLSS (nvngx_dlss.dll) for NVIDIA RTX graphics cards",
"ui.dlss_help": "From NVIDIA's DLSS SDK on GitHub, under NVIDIA's RTX SDK license (github.com/NVIDIA/DLSS). It makes the dlaa and DLSS settings work; without it they do nothing.",
"ui.compressed_help": "Compressed NSZ and XCZ files work as they are: the setup unpacks them by itself (until the game data is extracted, that needs as much free space as the unpacked files take).",
"ui.type_game": "Game files (NSP, XCI, NSZ, XCZ)",
"ui.type_keys": "Key files (*.keys)",
"ui.type_all": "All files",
"ui.start": "Start",
"ui.cancel": "Cancel",
"ui.cancelling": "Cancelling...",
"ui.show_log": "Show log",
"ui.hide_log": "Hide log",
"ui.close": "Close",
"ui.back": "Back",
"ui.open_folder": "Open folder",
"ui.update_mode": "This folder holds an earlier installation. The setup continues or updates it; the game files are asked for only if they are needed again.",
"ui.need_dest": "Choose the install folder.",
"ui.need_base": "Choose the base game file.",
"ui.need_update": "Choose the 1.1.0 or 1.2.1 or 1.4.3 update file.",
"ui.need_keys": "Choose the prod.keys file.",
"ui.need_lang": "Choose the game language.",
"ui.missing_base": "The base game file does not exist.",
"ui.missing_update": "The update file does not exist.",
"ui.missing_keys": "The keys file does not exist.",
"ui.missing_firmware": "The firmware folder does not exist.",
"ui.running_install": "Installing",
"ui.running_resume": "Continuing the earlier setup",
"ui.running_update": "Updating the installation",
"ui.state_started": "started",
"ui.state_done": "done",
"ui.state_skipped": "skipped",
"ui.state_pending": "waiting",
"ui.state_running": "running",
"ui.state_failed": "failed",
"ui.log_warning": "Warning",
"ui.log_error": "Error",
"ui.log_space": "Space needed: {need} GB, free: {free} GB",
"ui.log_end": "Finished",
"ui.result_ok": "The game is ready",
"ui.result_failed": "The setup failed",
"ui.result_cancelled": "The setup was cancelled",
"ui.done_text": "Start {game_exe} from {dest}. The setup program and the game files you chose are no longer needed.",
"ui.cancelled_text": "The finished steps are kept. Start the setup again with the same folder to continue.",
"ui.log_file": "Log file: {path}",
"ui.process_died": "The setup stopped unexpectedly (exit code {code}).",
"ui.confirm_cancel": "The setup is running. Cancel it and close the window?",
"ui.space_one": "Free space needed on {path}: {need} GB (free: {free} GB).",
"ui.space_two": "Free space needed on {path}: {need} GB (free: {free} GB); on {temp}: {temp_need} GB (free: {temp_free} GB).",
"ui.amount_bytes": "{done} / {total} GB",
"ui.amount_chunks": "{done} / {total} parts",
"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": "NX2navi Setup",
"launcher.python_missing": "The setup files are incomplete: the python folder next to NX2navi-Setup.exe is missing. Unpack the whole archive again and start NX2navi-Setup.exe from the unpacked folder.",
"lang.ja": "Japanese",
"lang.en-US": "English (US)",
"lang.en-GB": "English (UK)",
"lang.fr": "French",
"lang.fr-CA": "French (Canada)",
"lang.de": "German",
"lang.it": "Italian",
"lang.es": "Spanish",
"lang.es-419": "Spanish (Latin America)",
"lang.nl": "Dutch",
"lang.pt": "Portuguese",
"lang.pt-BR": "Portuguese (Brazil)",
"lang.ru": "Russian",
"lang.ko": "Korean",
"lang.zh-Hans": "Chinese (Simplified)",
"lang.zh-Hant": "Chinese (Traditional)"
}

208
installer/text/pt-BR.json Normal file
View File

@@ -0,0 +1,208 @@
{
"step.check": "Verificando o computador e os arquivos do jogo",
"step.fonts": "Extraindo as fontes do sistema",
"step.extract": "Extraindo o jogo",
"step.lift": "Traduzindo o código do jogo para C",
"step.compile": "Compilando o {game_exe}",
"step.prepare": "Preparando os shaders",
"step.dlss": "Baixando o NVIDIA DLSS",
"step.cleanup": "Finalizando",
"phase.check.host": "Verificando o processador e a placa de vídeo",
"phase.check.verify": "Verificando os arquivos já instalados",
"phase.check.verify_romfs": "Verificando os dados do jogo instalados",
"phase.check.inputs": "Abrindo os arquivos do jogo com as chaves",
"phase.check.unpack_base": "Descompactando o jogo base compactado",
"phase.check.unpack_update": "Descompactando a atualização compactada",
"phase.check.versions": "Verificando as versões do jogo",
"phase.fonts.extract": "Extraindo as fontes compartilhadas do firmware",
"phase.fonts.copy": "Copiando as fontes compartilhadas para a pasta de instalação",
"phase.extract.hash_base": "Calculando o checksum do jogo base",
"phase.extract.hash_update": "Calculando o checksum da atualização",
"phase.extract.exefs": "Extraindo o código do jogo",
"phase.extract.copy": "Copiando os dados do jogo",
"phase.extract.merge": "Aplicando a atualização aos dados do jogo",
"phase.extract.diagnose": "Procurando o arquivo do jogo danificado",
"phase.extract.index": "Verificando os dados do jogo",
"phase.lift.discover": "Encontrando as funções",
"phase.lift.emit": "Gerando o código C",
"phase.compile.compile": "Compilando",
"phase.compile.link": "Ligando o {game_exe}",
"phase.prepare.romfs_patches": "Gravando os patches de 60 fps nos dados do jogo",
"phase.prepare.seed": "Lendo os shaders dos dados do jogo",
"phase.prepare.translate": "Traduzindo os shaders",
"phase.prepare.libraries": "Montando os shaders para o driver de vídeo",
"phase.prepare.pack": "Juntando o cache de shaders num único arquivo",
"phase.dlss.download": "Baixando o nvngx_dlss.dll do DLSS SDK da NVIDIA",
"phase.cleanup.ini": "Gravando o nx2navi.ini",
"phase.cleanup.temp": "Removendo os arquivos temporários",
"cli.usage": "Linha de comando inválida: {detail}",
"internal": "Erro inesperado ({exception}): {detail}",
"state.unreadable": "Não foi possível ler {path}. Escolha outra pasta ou apague esse arquivo.",
"state.newer_format": "{path} foi gravado por um instalador mais novo. Use esse instalador ou outra pasta.",
"state.output_changed": "Os arquivos instalados da etapa '{step}' mudaram desde que foram criados; essa etapa será executada de novo.",
"check.release_incomplete": "A pasta do instalador está incompleta; faltam: {paths}. Extraia o pacote de novo.",
"check.dest_not_folder": "O local de instalação {path} é um arquivo, não uma pasta.",
"check.dest_not_empty": "A pasta de instalação {path} não está vazia e não tem uma instalação anterior. Escolha uma pasta vazia.",
"check.lang_missing": "Escolha o idioma do jogo.",
"check.lang_unknown": "Idioma desconhecido '{lang}'. Conhecidos: {known}.",
"check.toolchain_broken": "O compilador incluído não funciona: {detail}",
"check.glibc_old": "A biblioteca C deste sistema é a glibc {version}; o compilador da instalação precisa da {need} ou mais nova (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e mais novos têm). Atualizar o sistema resolve.",
"check.host_probe_failed": "A verificação do computador não rodou (código de saída {code}).",
"check.cpu_too_old": "Este processador não tem x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), o nível mais antigo para o qual o jogo é compilado. Intel Nehalem (2008) ou AMD Bulldozer (2011) e mais novos têm.",
"check.vulkan_missing": "Nenhum driver Vulkan está instalado. Instale o driver mais recente da sua placa de vídeo.",
"check.vulkan_no_device": "O Vulkan não encontra nenhuma placa de vídeo. Instale o driver mais recente da sua placa de vídeo.",
"check.vulkan_too_old": "O jogo precisa de uma placa de vídeo com Vulkan 1.3; encontrado: {devices}. Atualize o driver de vídeo.",
"check.no_display": "Preparar os shaders exige uma tela. Execute a instalação na sessão da área de trabalho ou use export DISPLAY=:0 (no Steam Deck em Game Mode, também XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Os arquivos do jogo são necessários: escolha o jogo base, a atualização 1.1.0, 1.2.1 ou 1.4.3 e o prod.keys.",
"check.input_missing": "Arquivo não encontrado ({input}): {path}",
"check.keys_unreadable": "Não foi possível ler o arquivo de chaves. Escolha um arquivo prod.keys.",
"check.keys_no_header_key": "O arquivo de chaves não tem header_key. Extraia o prod.keys do seu console de novo.",
"check.keys_wrong": "As chaves não abrem o arquivo de {input}. Use o prod.keys do seu console.",
"check.keys_too_old": "O arquivo de chaves é antigo demais para o arquivo de {input} (precisa da geração de chaves {generation}). Extraia o prod.keys de um console com firmware mais novo.",
"check.not_game_file": "O arquivo de {input} não é um arquivo de jogo XCI, NSP, XCZ ou NSZ.",
"check.file_unreadable": "Não foi possível ler o arquivo de {input}: {detail}",
"check.unpack_failed": "Não foi possível descompactar o arquivo compactado de {input}: {detail}",
"check.ticket_personalized": "O arquivo de {input} tem um ticket personalizado; é preciso um ticket comum.",
"check.ticket_missing": "O arquivo de {input} não tem o ticket de que o conteúdo precisa.",
"check.base_not_nx2navi": "O arquivo do jogo base não é The Legend of Zelda: Ocarina of Time ({detail}).",
"check.base_is_update": "O arquivo do jogo base é uma atualização. Escolha aqui o NSP ou XCI do jogo base (versão 1.0.0) e este arquivo como a atualização.",
"check.base_combined": "O arquivo do jogo base contém vários pacotes (jogo base, atualização ou DLC em um só arquivo). Escolha um dump do jogo base que contenha só o jogo.",
"check.update_not_nsp": "A atualização precisa ser um arquivo NSP ou NSZ.",
"check.update_is_base": "O arquivo de atualização contém um jogo base. Escolha o NSP da atualização 1.1.0, 1.2.1 ou 1.4.3.",
"check.update_not_nx2navi": "O arquivo de atualização não é uma atualização de Ocarina of Time ({detail}).",
"check.exefs_failed": "O código do jogo no arquivo de {input} falhou nas verificações; veja {log}.",
"check.input_damaged": "O arquivo de {input} está danificado ou incompleto: {path} ({detail}). Copie esse arquivo de novo da origem, ou extraia-o de novo, e então execute a instalação outra vez.",
"check.base_wrong_version": "O jogo base não é a versão 1.0.0 ({modules} diferem).",
"check.update_wrong_version": "A atualização é a versão {found}; esta versão do instalador aceita {wanted}.",
"check.disk_space": "Espaço livre insuficiente em {path}: são necessários {need_gb} GB, há {free_gb} GB livres.",
"check.firmware_missing": "A pasta de firmware {path} não existe. Escolha a pasta Contents/registered do firmware.",
"check.firmware_empty": "A pasta de firmware {path} não contém arquivos NCA. Escolha a pasta Contents/registered do firmware.",
"check.fonts_keys_needed": "As fontes compartilhadas deste idioma ainda não estão instaladas; escolha o prod.keys para que a instalação possa extraí-las do firmware.",
"extract.exefs_mismatch": "O código do jogo extraído não corresponde à versão {version} ({modules}).",
"extract.romfs_merge_failed": "Falha ao aplicar a atualização aos dados do jogo: {detail}. Detalhes: {log}",
"extract.romfs_mismatch": "Os dados do jogo extraídos não correspondem à versão {version} (tamanho {size}, checksum {sha256}...).",
"fonts.failed": "A extração das fontes compartilhadas falhou (código de saída {code}): {detail}. Detalhes: {log}",
"fonts.incomplete": "A extração das fontes compartilhadas não gravou todos os arquivos ({files}).",
"fonts.copy_failed": "Não foi possível copiar as fontes compartilhadas para {path}: {detail}",
"lift.failed": "Falha ao traduzir o código do jogo (código de saída {code}). Detalhes: {log}",
"compile.failed": "Falha ao compilar o {game_exe} (código de saída {code}). Detalhes: {log}",
"compile.exe_in_use": "{path} está em uso. Feche o jogo e execute o instalador de novo.",
"prepare.xlate_in_use": "{path} está em uso. Feche o jogo, encerre qualquer processo nx2navi_xlate que tenha sobrado de uma execução anterior e execute o instalador de novo.",
"prepare.shader_list_missing": "A lista de shaders está faltando.",
"prepare.romfs_patches_failed": "Falha ao gravar os patches nos dados do jogo (código de saída {code}). Detalhes: {log}",
"prepare.shaders_failed": "Falha ao preparar os shaders (código de saída {code}). Detalhes: {log}",
"cleanup.romfs_unreadable": "Os dados do jogo em {path} estão faltando ou não podem ser lidos depois da instalação. Reinicie o Windows e execute o instalador de novo na mesma pasta: ele extrai os dados do jogo outra vez e mantém o resto.",
"prepare.pack_failed": "Falha ao juntar o cache de shaders (código de saída {code}). Detalhes: {log}",
"cleanup.ini_failed": "Não foi possível gravar o nx2navi.ini: {detail}",
"warn.lang_needs_fonts": "Textos em {lang} precisam das fontes de sistema do Switch, e nenhuma foi informada. O jogo não inicia neste idioma até que sejam adicionadas. Escolha a pasta do firmware (Contents/registered) ou veja \"Switch system fonts\" em docs/installer.md.",
"warn.cheats_skipped": "Não foi possível compilar os cheats da pasta de mods que alteram o código do jogo; o jogo é instalado sem eles. Detalhes: {log}",
"warn.exefs_skipped": "Não foi possível compilar os patches ExeFS dos mods (.ips, .pchtxt); o jogo é instalado sem eles. Detalhes: {log}",
"warn.npdm_differs": "O main.npdm difere do dump de referência da versão {version}; só os módulos de código são usados.",
"warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox ou do PC (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}",
"warn.shaders_skipped": "O driver gráfico travou ao compilar alguns shaders, então {count} ficaram fora da preparação. O jogo os compila quando precisar deles pela primeira vez, e o driver pode travar ali também; uma atualização do driver pode resolver. Detalhes: {log}",
"warn.kernel_old": "O Linux {version} não tem o rastreamento de escrita de que o jogo depende (6.7 ou mais novo); o jogo pode rodar muito devagar. Atualizar o sistema resolve.",
"warn.dlss_kept": "Já existe uma biblioteca DLSS na pasta de instalação ({path}); a instalação a mantém.",
"warn.dlss_download_failed": "Não foi possível baixar o NVIDIA DLSS de {url}: {detail}. O jogo funciona sem ele; a próxima execução da instalação tenta de novo.",
"ui.title": "Instalação do NX2navi",
"ui.rebuild_title": "Recompilando o jogo para os seus mods",
"ui.start_game": "Iniciar o jogo",
"ui.version": "versão {version}",
"ui.intro": "Monta uma pasta jogável de Ocarina of Time a partir dos seus próprios arquivos do jogo. Isso demora um pouco e só precisa ser feito uma vez.",
"ui.notice": "A pasta que esta instalação monta contém o jogo. Ela é só para seu uso pessoal; não compartilhe nem envie para a internet.",
"ui.keys_private": "O arquivo de chaves é lido no lugar. O conteúdo dele nunca é mostrado, copiado nem guardado.",
"ui.base": "Jogo base (NSP, XCI, NSZ ou XCZ)",
"ui.update": "Atualização 1.1.0, 1.2.1 ou 1.4.3 (NSP ou NSZ)",
"ui.keys": "prod.keys",
"ui.firmware": "Pasta de firmware (opcional)",
"ui.game_language": "Idioma do jogo",
"ui.dest": "Pasta de instalação",
"ui.browse": "Procurar...",
"ui.pick_game": "Escolha o arquivo do jogo base",
"ui.pick_update": "Escolha o arquivo da atualização 1.1.0, 1.2.1 ou 1.4.3",
"ui.pick_keys": "Escolha o prod.keys",
"ui.pick_firmware": "Escolha a pasta de firmware do Switch (Contents/registered)",
"ui.pick_dest": "Escolha a pasta de instalação",
"ui.firmware_help": "Para textos em chinês, coreano e chinês tradicional: a pasta Contents/registered do firmware, por exemplo do Ryujinx ou do The hardware. A instalação copia dela as fontes do sistema do Switch para a pasta de instalação.",
"ui.dlss": "Baixar o NVIDIA DLSS (nvngx_dlss.dll) para placas de vídeo NVIDIA RTX",
"ui.dlss_help": "Do DLSS SDK da NVIDIA no GitHub, sob a licença NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Sem ele as opções dlaa e DLSS não fazem nada.",
"ui.compressed_help": "Arquivos compactados NSZ e XCZ funcionam do jeito que estão: a instalação os descompacta sozinha (para isso, até os dados do jogo serem extraídos, ela precisa de tanto espaço livre quanto ocupam os arquivos descompactados).",
"ui.type_game": "Arquivos de jogo (NSP, XCI, NSZ, XCZ)",
"ui.type_keys": "Arquivos de chaves (*.keys)",
"ui.type_all": "Todos os arquivos",
"ui.start": "Iniciar",
"ui.cancel": "Cancelar",
"ui.cancelling": "Cancelando...",
"ui.show_log": "Mostrar log",
"ui.hide_log": "Ocultar log",
"ui.close": "Fechar",
"ui.back": "Voltar",
"ui.open_folder": "Abrir pasta",
"ui.update_mode": "Esta pasta tem uma instalação anterior. A instalação vai continuar ou atualizá-la; os arquivos do jogo só são pedidos se forem necessários de novo.",
"ui.need_dest": "Escolha a pasta de instalação.",
"ui.need_base": "Escolha o arquivo do jogo base.",
"ui.need_update": "Escolha o arquivo da atualização 1.1.0, 1.2.1 ou 1.4.3.",
"ui.need_keys": "Escolha o arquivo prod.keys.",
"ui.need_lang": "Escolha o idioma do jogo.",
"ui.missing_base": "O arquivo do jogo base não existe.",
"ui.missing_update": "O arquivo de atualização não existe.",
"ui.missing_keys": "O arquivo de chaves não existe.",
"ui.missing_firmware": "A pasta de firmware não existe.",
"ui.running_install": "Instalando",
"ui.running_resume": "Continuando a instalação anterior",
"ui.running_update": "Atualizando a instalação",
"ui.state_started": "iniciada",
"ui.state_done": "concluída",
"ui.state_skipped": "pulada",
"ui.state_pending": "aguardando",
"ui.state_running": "em andamento",
"ui.state_failed": "falhou",
"ui.log_warning": "Aviso",
"ui.log_error": "Erro",
"ui.log_space": "Espaço necessário: {need} GB, livre: {free} GB",
"ui.log_end": "Concluído",
"ui.result_ok": "O jogo está pronto",
"ui.result_failed": "A instalação falhou",
"ui.result_cancelled": "A instalação foi cancelada",
"ui.done_text": "Abra o {game_exe} em {dest}. O programa de instalação e os arquivos do jogo que você escolheu não são mais necessários.",
"ui.cancelled_text": "As etapas concluídas são mantidas. Inicie a instalação de novo com a mesma pasta para continuar.",
"ui.log_file": "Arquivo de log: {path}",
"ui.process_died": "A instalação parou de forma inesperada (código de saída {code}).",
"ui.confirm_cancel": "A instalação está em andamento. Cancelar e fechar a janela?",
"ui.space_one": "Espaço livre necessário em {path}: {need} GB (livre: {free} GB).",
"ui.space_two": "Espaço livre necessário em {path}: {need} GB (livre: {free} GB); em {temp}: {temp_need} GB (livre: {temp_free} GB).",
"ui.amount_bytes": "{done} / {total} GB",
"ui.amount_chunks": "{done} / {total} partes",
"ui.amount_objects": "{done} / {total} arquivos",
"ui.amount_shaders": "{done} / {total} shaders",
"ui.amount_other": "{done} / {total} {unit}",
"ui.seconds": "{n} s",
"param.input.base": "jogo base",
"param.input.update": "atualização",
"param.input.keys": "chaves",
"launcher.title": "Instalação do NX2navi",
"launcher.python_missing": "Os arquivos de instalação estão incompletos: a pasta python ao lado do NX2navi-Setup.exe não existe. Extraia o arquivo compactado inteiro de novo e abra o NX2navi-Setup.exe a partir da pasta extraída.",
"lang.ja": "Japonês",
"lang.en-US": "Inglês (EUA)",
"lang.en-GB": "Inglês (Reino Unido)",
"lang.fr": "Francês",
"lang.fr-CA": "Francês (Canadá)",
"lang.de": "Alemão",
"lang.it": "Italiano",
"lang.es": "Espanhol",
"lang.es-419": "Espanhol (América Latina)",
"lang.nl": "Holandês",
"lang.pt": "Português",
"lang.pt-BR": "Português (Brasil)",
"lang.ru": "Russo",
"lang.ko": "Coreano",
"lang.zh-Hans": "Chinês (Simplificado)",
"lang.zh-Hant": "Chinês (Tradicional)"
}

208
installer/text/ru.json Normal file
View File

@@ -0,0 +1,208 @@
{
"step.check": "Проверка компьютера и игровых файлов",
"step.fonts": "Извлечение системных шрифтов",
"step.extract": "Распаковка игры",
"step.lift": "Перевод кода игры в C",
"step.compile": "Сборка {game_exe}",
"step.prepare": "Подготовка шейдеров",
"step.dlss": "Загрузка NVIDIA DLSS",
"step.cleanup": "Уборка",
"phase.check.host": "Проверка процессора и видеокарты",
"phase.check.verify": "Проверка уже установленных файлов",
"phase.check.verify_romfs": "Проверка установленных данных игры",
"phase.check.inputs": "Открытие игровых файлов с помощью ключей",
"phase.check.unpack_base": "Распаковка сжатой базовой игры",
"phase.check.unpack_update": "Распаковка сжатого обновления",
"phase.check.versions": "Проверка версий игры",
"phase.fonts.extract": "Извлечение общих шрифтов из прошивки",
"phase.fonts.copy": "Копирование общих шрифтов в папку установки",
"phase.extract.hash_base": "Подсчёт контрольной суммы базовой игры",
"phase.extract.hash_update": "Подсчёт контрольной суммы обновления",
"phase.extract.exefs": "Распаковка кода игры",
"phase.extract.copy": "Копирование данных игры",
"phase.extract.merge": "Применение обновления к данным игры",
"phase.extract.diagnose": "Поиск повреждённого файла игры",
"phase.extract.index": "Проверка данных игры",
"phase.lift.discover": "Поиск функций",
"phase.lift.emit": "Запись кода на C",
"phase.compile.compile": "Компиляция",
"phase.compile.link": "Компоновка {game_exe}",
"phase.prepare.romfs_patches": "Запись патчей данных игры для 60 кадров/с",
"phase.prepare.seed": "Чтение шейдеров из данных игры",
"phase.prepare.translate": "Трансляция шейдеров",
"phase.prepare.libraries": "Сборка шейдеров для драйвера видеокарты",
"phase.prepare.pack": "Упаковка кэша шейдеров в один файл",
"phase.dlss.download": "Загрузка nvngx_dlss.dll из DLSS SDK от NVIDIA",
"phase.cleanup.ini": "Запись nx2navi.ini",
"phase.cleanup.temp": "Удаление временных файлов",
"cli.usage": "Неверные параметры командной строки: {detail}",
"internal": "Непредвиденная ошибка ({exception}): {detail}",
"state.unreadable": "Не удаётся прочитать {path}. Выберите другую папку или удалите этот файл.",
"state.newer_format": "Файл {path} создан более новой версией установки. Используйте её или выберите другую папку.",
"state.output_changed": "Установленные файлы шага «{step}» изменились после создания; этот шаг выполнится заново.",
"check.release_incomplete": "Папка установки неполная, не хватает: {paths}. Распакуйте архив заново.",
"check.dest_not_folder": "Место установки {path} — это файл, а не папка.",
"check.dest_not_empty": "Папка установки {path} не пуста и не содержит прежней установки. Выберите пустую папку.",
"check.lang_missing": "Выберите язык игры.",
"check.lang_unknown": "Неизвестный язык «{lang}». Доступные: {known}.",
"check.toolchain_broken": "Встроенный компилятор не работает: {detail}",
"check.glibc_old": "Библиотека C этой системы — glibc {version}; компилятору установщика нужна {need} или новее (она есть в Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 и новее). Обновление системы это исправит.",
"check.host_probe_failed": "Проверка компьютера не выполнилась (код выхода {code}).",
"check.cpu_too_old": "Этому процессору не хватает x86-64-v2 (SSE4.2, POPCNT и CMPXCHG16B) — минимального уровня, под который собрана игра. Он есть у Intel Nehalem (2008) и AMD Bulldozer (2011) и новее.",
"check.vulkan_missing": "Драйвер Vulkan не установлен. Установите свежий драйвер видеокарты.",
"check.vulkan_no_device": "Vulkan не находит видеокарту. Установите свежий драйвер видеокарты.",
"check.vulkan_too_old": "Игре нужна видеокарта с Vulkan 1.3; найдено: {devices}. Обновите драйвер видеокарты.",
"check.no_display": "Для подготовки шейдеров нужен дисплей. Запустите установку из сеанса рабочего стола или выполните export DISPLAY=:0 (на Steam Deck в игровом режиме ещё XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Нужны игровые файлы: выберите базовую игру, обновление 1.1.0 или 1.2.1 или 1.4.3 и prod.keys.",
"check.input_missing": "Файл не найден ({input}): {path}",
"check.keys_unreadable": "Не удаётся прочитать файл ключей. Выберите файл prod.keys.",
"check.keys_no_header_key": "В файле ключей нет header_key. Снова получите prod.keys со своей консоли.",
"check.keys_wrong": "Эти ключи не открывают файл «{input}». Используйте prod.keys со своей консоли.",
"check.keys_too_old": "Файл ключей слишком старый для файла «{input}» (нужно поколение ключей {generation}). Получите prod.keys с консоли с более новой прошивкой.",
"check.not_game_file": "Файл «{input}» не является игровым файлом XCI, NSP, XCZ или NSZ.",
"check.file_unreadable": "Не удаётся прочитать файл «{input}»: {detail}",
"check.unpack_failed": "Не удалось распаковать сжатый файл «{input}»: {detail}",
"check.ticket_personalized": "В файле «{input}» личный тикет; нужен общий тикет.",
"check.ticket_missing": "В файле «{input}» нет тикета, который нужен его содержимому.",
"check.base_not_nx2navi": "Файл базовой игры — не The Legend of Zelda: Ocarina of Time ({detail}).",
"check.base_is_update": "Файл базовой игры — это обновление. Выберите здесь NSP или XCI базовой игры (версия 1.0.0), а этот файл укажите как обновление.",
"check.base_combined": "Файл базовой игры содержит несколько пакетов (игра, обновление или DLC в одном файле). Выберите дамп, в котором только базовая игра.",
"check.update_not_nsp": "Обновление должно быть файлом NSP или NSZ.",
"check.update_is_base": "Файл обновления содержит базовую игру. Выберите NSP с обновлением 1.1.0 или 1.2.1 или 1.4.3.",
"check.update_not_nx2navi": "Файл обновления — не обновление Ocarina of Time ({detail}).",
"check.exefs_failed": "Код игры из файла «{input}» не прошёл проверку; подробности в {log}.",
"check.input_damaged": "Файл «{input}» повреждён или скопирован не полностью: {path} ({detail}). Скопируйте этот файл заново из источника или сделайте дамп ещё раз, затем снова запустите установку.",
"check.base_wrong_version": "Базовая игра не версии 1.0.0 (отличаются модули: {modules}).",
"check.update_wrong_version": "Версия обновления {found}; этот выпуск принимает {wanted}.",
"check.disk_space": "Не хватает свободного места для {path}: нужно {need_gb} ГБ, свободно {free_gb} ГБ.",
"check.firmware_missing": "Папки прошивки {path} нет. Выберите папку Contents/registered прошивки.",
"check.firmware_empty": "В папке прошивки {path} нет файлов NCA. Выберите папку Contents/registered прошивки.",
"check.fonts_keys_needed": "Общие шрифты для этого языка ещё не установлены; выберите prod.keys, чтобы установка извлекла их из прошивки.",
"extract.exefs_mismatch": "Распакованный код игры не соответствует версии {version} ({modules}).",
"extract.romfs_merge_failed": "Не удалось применить обновление к данным игры: {detail}. Подробности: {log}",
"extract.romfs_mismatch": "Распакованные данные игры не соответствуют версии {version} (размер {size}, контрольная сумма {sha256}...).",
"fonts.failed": "Не удалось извлечь общие шрифты (код выхода {code}): {detail}. Подробности: {log}",
"fonts.incomplete": "При извлечении общих шрифтов записаны не все файлы ({files}).",
"fonts.copy_failed": "Не удаётся скопировать общие шрифты в {path}: {detail}",
"lift.failed": "Не удалось перевести код игры (код выхода {code}). Подробности: {log}",
"compile.failed": "Не удалось собрать {game_exe} (код выхода {code}). Подробности: {log}",
"compile.exe_in_use": "Файл {path} занят. Закройте игру и запустите установку снова.",
"prepare.xlate_in_use": "Файл {path} занят. Закройте игру, завершите процесс nx2navi_xlate, оставшийся от прошлого запуска, и запустите установку снова.",
"prepare.shader_list_missing": "Нет списка шейдеров.",
"prepare.romfs_patches_failed": "Не удалось записать патчи данных игры (код выхода {code}). Подробности: {log}",
"prepare.shaders_failed": "Не удалось подготовить шейдеры (код выхода {code}). Подробности: {log}",
"cleanup.romfs_unreadable": "Данные игры в {path} пропали или не читаются после установки. Перезагрузите Windows и запустите установщик снова на ту же папку: он заново распакует данные игры, остальное сохранится.",
"prepare.pack_failed": "Не удалось упаковать кэш шейдеров (код выхода {code}). Подробности: {log}",
"cleanup.ini_failed": "Не удаётся записать nx2navi.ini: {detail}",
"warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch, а они не указаны. Игра не запустится на этом языке, пока их не добавят. Выберите папку прошивки (Contents/registered) или см. раздел «Switch system fonts» в docs/installer.md.",
"warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.",
"warn.cheats_skipped": "Не удалось собрать читы из папки модов, меняющие код игры; игра установится без них. Подробности: {log}",
"warn.exefs_skipped": "Не удалось собрать ExeFS-патчи модов (.ips, .pchtxt); игра установится без них. Подробности: {log}",
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox или PC (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
"warn.shaders_skipped": "Графический драйвер аварийно завершился при сборке части шейдеров, поэтому {count} из них пропущены при подготовке. Игра соберёт их, когда они впервые понадобятся, и драйвер может упасть и там; обновление драйвера может это исправить. Подробности: {log}",
"warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.",
"warn.dlss_kept": "В папке установки уже есть библиотека DLSS ({path}); установка её оставляет.",
"warn.dlss_download_failed": "Не удалось загрузить NVIDIA DLSS с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.",
"ui.title": "Установка NX2navi",
"ui.rebuild_title": "Пересборка игры под ваши моды",
"ui.start_game": "Запустить игру",
"ui.version": "версия {version}",
"ui.intro": "Собирает готовую к запуску папку с Ocarina of Time из ваших игровых файлов. Занимает много времени и выполняется один раз.",
"ui.notice": "Папка, которую создаёт установка, содержит игру. Она предназначена только для личного использования: не передавайте и не выкладывайте её.",
"ui.keys_private": "Файл ключей читается на месте. Его содержимое не показывается, не копируется и не сохраняется.",
"ui.base": "Базовая игра (NSP, XCI, NSZ или XCZ)",
"ui.update": "Обновление 1.1.0 или 1.2.1 или 1.4.3 (NSP или NSZ)",
"ui.keys": "prod.keys",
"ui.firmware": "Папка прошивки (необязательно)",
"ui.game_language": "Язык игры",
"ui.dest": "Папка установки",
"ui.browse": "Обзор...",
"ui.pick_game": "Выберите файл базовой игры",
"ui.pick_update": "Выберите файл обновления 1.1.0 или 1.2.1 или 1.4.3",
"ui.pick_keys": "Выберите prod.keys",
"ui.pick_firmware": "Выберите папку прошивки Switch (Contents/registered)",
"ui.pick_dest": "Выберите папку установки",
"ui.firmware_help": "Для текста на китайском и корейском: папка Contents/registered прошивки, например из Ryujinx или The hardware. Установка скопирует из неё системные шрифты Switch в папку установки.",
"ui.dlss": "Загрузить NVIDIA DLSS (nvngx_dlss.dll) для видеокарт NVIDIA RTX",
"ui.dlss_help": "Из DLSS SDK от NVIDIA на GitHub, по лицензии NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Без него настройки dlaa и DLSS ничего не делают.",
"ui.compressed_help": "Сжатые файлы NSZ и XCZ подходят как есть: установка сама их распакует (для этого, пока извлекаются данные игры, нужно столько свободного места, сколько занимают распакованные файлы).",
"ui.type_game": "Файлы игры (NSP, XCI, NSZ, XCZ)",
"ui.type_keys": "Файлы ключей (*.keys)",
"ui.type_all": "Все файлы",
"ui.start": "Начать",
"ui.cancel": "Отмена",
"ui.cancelling": "Отмена...",
"ui.show_log": "Показать журнал",
"ui.hide_log": "Скрыть журнал",
"ui.close": "Закрыть",
"ui.back": "Назад",
"ui.open_folder": "Открыть папку",
"ui.update_mode": "В этой папке уже есть установка. Программа продолжит или обновит её; файлы игры понадобятся, только если их снова придётся читать.",
"ui.need_dest": "Выберите папку установки.",
"ui.need_base": "Выберите файл базовой игры.",
"ui.need_update": "Выберите файл обновления 1.1.0 или 1.2.1 или 1.4.3.",
"ui.need_keys": "Выберите файл prod.keys.",
"ui.need_lang": "Выберите язык игры.",
"ui.missing_base": "Файл базовой игры не найден.",
"ui.missing_update": "Файл обновления не найден.",
"ui.missing_keys": "Файл ключей не найден.",
"ui.missing_firmware": "Папки прошивки нет.",
"ui.running_install": "Установка",
"ui.running_resume": "Продолжение прерванной установки",
"ui.running_update": "Обновление установки",
"ui.state_started": "начат",
"ui.state_done": "готово",
"ui.state_skipped": "пропущен",
"ui.state_pending": "ожидает",
"ui.state_running": "выполняется",
"ui.state_failed": "ошибка",
"ui.log_warning": "Предупреждение",
"ui.log_error": "Ошибка",
"ui.log_space": "Нужно места: {need} ГБ, свободно: {free} ГБ",
"ui.log_end": "Завершено",
"ui.result_ok": "Игра готова",
"ui.result_failed": "Установка не удалась",
"ui.result_cancelled": "Установка отменена",
"ui.done_text": "Запустите {game_exe} из папки {dest}. Программа установки и выбранные игровые файлы больше не нужны.",
"ui.cancelled_text": "Завершённые шаги сохранены. Чтобы продолжить, снова запустите установку с той же папкой.",
"ui.log_file": "Файл журнала: {path}",
"ui.process_died": "Установка неожиданно остановилась (код выхода {code}).",
"ui.confirm_cancel": "Установка выполняется. Отменить её и закрыть окно?",
"ui.space_one": "Нужно свободного места на {path}: {need} ГБ (свободно: {free} ГБ).",
"ui.space_two": "Нужно свободного места на {path}: {need} ГБ (свободно: {free} ГБ); на {temp}: {temp_need} ГБ (свободно: {temp_free} ГБ).",
"ui.amount_bytes": "{done} / {total} ГБ",
"ui.amount_chunks": "{done} / {total} частей",
"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": "Установка NX2navi",
"launcher.python_missing": "Файлы установки неполные: рядом с NX2navi-Setup.exe нет папки python. Распакуйте архив целиком заново и запустите NX2navi-Setup.exe из распакованной папки.",
"lang.ja": "Японский",
"lang.en-US": "Английский (США)",
"lang.en-GB": "Английский (Великобритания)",
"lang.fr": "Французский",
"lang.fr-CA": "Французский (Канада)",
"lang.de": "Немецкий",
"lang.it": "Итальянский",
"lang.es": "Испанский",
"lang.es-419": "Испанский (Латинская Америка)",
"lang.nl": "Нидерландский",
"lang.pt": "Португальский",
"lang.pt-BR": "Португальский (Бразилия)",
"lang.ru": "Русский",
"lang.ko": "Корейский",
"lang.zh-Hans": "Китайский (упрощённый)",
"lang.zh-Hant": "Китайский (традиционный)"
}

208
installer/text/zh-Hans.json Normal file
View File

@@ -0,0 +1,208 @@
{
"step.check": "检查电脑和游戏文件",
"step.fonts": "正在提取系统字体",
"step.extract": "解包游戏",
"step.lift": "将游戏代码转换为 C 代码",
"step.compile": "编译 {game_exe}",
"step.prepare": "准备着色器",
"step.dlss": "下载 NVIDIA DLSS",
"step.cleanup": "清理",
"phase.check.host": "检查处理器和显卡",
"phase.check.verify": "检查已安装的文件",
"phase.check.verify_romfs": "检查已安装的游戏数据",
"phase.check.inputs": "用密钥打开游戏文件",
"phase.check.unpack_base": "正在解压压缩的游戏本体",
"phase.check.unpack_update": "正在解压压缩的更新",
"phase.check.versions": "检查游戏版本",
"phase.fonts.extract": "正在从固件中提取共享字体",
"phase.fonts.copy": "正在将共享字体复制到安装文件夹",
"phase.extract.hash_base": "计算游戏本体的校验和",
"phase.extract.hash_update": "计算更新的校验和",
"phase.extract.exefs": "解包游戏代码",
"phase.extract.copy": "复制游戏数据",
"phase.extract.merge": "将更新应用到游戏数据",
"phase.extract.diagnose": "查找损坏的游戏文件",
"phase.extract.index": "校验游戏数据",
"phase.lift.discover": "查找函数",
"phase.lift.emit": "生成 C 代码",
"phase.compile.compile": "编译",
"phase.compile.link": "链接 {game_exe}",
"phase.prepare.romfs_patches": "写入 60 帧游戏数据补丁",
"phase.prepare.seed": "从游戏数据中读取着色器",
"phase.prepare.translate": "转译着色器",
"phase.prepare.libraries": "为显卡驱动构建着色器",
"phase.prepare.pack": "将着色器缓存打包成一个文件",
"phase.dlss.download": "从 NVIDIA 的 DLSS SDK 下载 nvngx_dlss.dll",
"phase.cleanup.ini": "写入 nx2navi.ini",
"phase.cleanup.temp": "删除临时文件",
"cli.usage": "命令行无效:{detail}",
"internal": "意外错误({exception}):{detail}",
"state.unreadable": "无法读取 {path}。请选择其他文件夹,或删除该文件。",
"state.newer_format": "{path} 是由更新版本的安装程序写入的。请使用那个安装程序,或选择其他文件夹。",
"state.output_changed": "步骤“{step}”生成的已安装文件在生成后被改动过;该步骤将重新运行。",
"check.release_incomplete": "安装程序文件夹不完整,缺少:{paths}。请重新解压发布包。",
"check.dest_not_folder": "安装位置 {path} 是一个文件,而不是文件夹。",
"check.dest_not_empty": "安装文件夹 {path} 不是空的,其中也没有之前的安装。请选择一个空文件夹。",
"check.lang_missing": "请选择游戏语言。",
"check.lang_unknown": "未知语言“{lang}”。可用语言:{known}。",
"check.toolchain_broken": "自带的编译器无法工作:{detail}",
"check.glibc_old": "此系统的 C 库为 glibc {version};安装程序的编译器需要 {need} 或更新版本(Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 及更新版本都满足)。更新系统即可解决。",
"check.host_probe_failed": "电脑检查未能运行(退出代码 {code})。",
"check.cpu_too_old": "此处理器不支持 x86-64-v2(SSE4.2、POPCNT 和 CMPXCHG16B),这是游戏所需的最低指令集。Intel Nehalem(2008 年)或 AMD Bulldozer(2011 年)及更新的处理器都支持。",
"check.vulkan_missing": "未安装 Vulkan 驱动。请为你的显卡安装最新的驱动程序。",
"check.vulkan_no_device": "Vulkan 找不到显卡。请为你的显卡安装最新的驱动程序。",
"check.vulkan_too_old": "游戏需要支持 Vulkan 1.3 的显卡;检测到:{devices}。请更新显卡驱动程序。",
"check.no_display": "准备着色器需要显示器。请在桌面会话中运行安装程序,或执行 export DISPLAY=:0(Steam Deck 游戏模式下还需 XDG_RUNTIME_DIR=/run/user/1000)。",
"check.inputs_needed": "需要游戏文件:请选择游戏本体、1.1.0、1.2.1 或 1.4.3 更新以及 prod.keys。",
"check.input_missing": "找不到文件({input}):{path}",
"check.keys_unreadable": "无法读取密钥文件。请选择一个 prod.keys 文件。",
"check.keys_no_header_key": "密钥文件中没有 header_key。请从你的主机重新导出 prod.keys。",
"check.keys_wrong": "这些密钥无法打开{input}文件。请使用你自己主机的 prod.keys。",
"check.keys_too_old": "密钥文件对{input}文件来说太旧(需要密钥代数 {generation})。请从固件更新的主机导出 prod.keys。",
"check.not_game_file": "{input}文件不是 XCI、NSP、XCZ 或 NSZ 游戏文件。",
"check.file_unreadable": "无法读取{input}文件:{detail}",
"check.unpack_failed": "无法解压压缩的{input}文件:{detail}",
"check.ticket_personalized": "{input}文件带有个人化票据(personalized ticket);需要通用票据(common ticket)。",
"check.ticket_missing": "{input}文件缺少其内容所需的票据(ticket)。",
"check.base_not_nx2navi": "游戏本体文件不是《塞尔达传说 王国之泪》({detail})。",
"check.base_is_update": "基础游戏文件是一个更新。请在这里选择基础游戏的 NSP 或 XCI(版本 1.0.0),并把此文件选为更新。",
"check.base_combined": "基础游戏文件包含多个内容包(基础游戏、更新或 DLC 合在一个文件中)。请选择只包含游戏本体的基础游戏转储。",
"check.update_not_nsp": "更新必须是 NSP 或 NSZ 文件。",
"check.update_is_base": "更新文件里是游戏本体。请选择 1.1.0、1.2.1 或 1.4.3 的更新 NSP。",
"check.update_not_nx2navi": "更新文件不是《王国之泪》的更新({detail})。",
"check.exefs_failed": "{input}文件的游戏代码未通过检查;详见 {log}。",
"check.input_damaged": "{input}文件已损坏或不完整:{path}({detail})。请从来源重新复制该文件或重新导出,然后再次运行安装程序。",
"check.base_wrong_version": "游戏本体不是 1.0.0 版本({modules} 不一致)。",
"check.update_wrong_version": "更新的版本是 {found};此发布版需要 {wanted}。",
"check.disk_space": "{path} 的可用空间不足:需要 {need_gb} GB,可用 {free_gb} GB。",
"check.firmware_missing": "固件文件夹 {path} 不存在。请选择固件的 Contents/registered 文件夹。",
"check.firmware_empty": "固件文件夹 {path} 中没有 NCA 文件。请选择固件的 Contents/registered 文件夹。",
"check.fonts_keys_needed": "此语言的共享字体尚未安装;请选择 prod.keys,以便安装程序从固件中提取它们。",
"extract.exefs_mismatch": "解包出的游戏代码与 {version} 版本不符({modules})。",
"extract.romfs_merge_failed": "将更新应用到游戏数据失败:{detail}。详情:{log}",
"extract.romfs_mismatch": "解包出的游戏数据与 {version} 版本不符(大小 {size},校验和 {sha256}...)。",
"fonts.failed": "提取共享字体失败(退出代码 {code}):{detail}。详情:{log}",
"fonts.incomplete": "共享字体提取没有写出全部文件({files})。",
"fonts.copy_failed": "无法将共享字体复制到 {path}:{detail}",
"lift.failed": "游戏代码转换失败(退出代码 {code})。详情:{log}",
"compile.failed": "编译 {game_exe} 失败(退出代码 {code})。详情:{log}",
"compile.exe_in_use": "{path} 正在使用中。请关闭游戏后重新运行安装程序。",
"prepare.xlate_in_use": "{path} 正在被占用。请关闭游戏,结束上次残留的 nx2navi_xlate 进程,再重新运行安装程序。",
"prepare.shader_list_missing": "缺少着色器列表。",
"prepare.romfs_patches_failed": "写入游戏数据补丁失败(退出代码 {code})。详情:{log}",
"prepare.shaders_failed": "准备着色器失败(退出代码 {code})。详情:{log}",
"cleanup.romfs_unreadable": "安装完成后,{path} 中的游戏数据缺失或无法读取。请重启 Windows,然后对同一文件夹再次运行安装程序:它会重新提取游戏数据,其余内容保留。",
"prepare.pack_failed": "打包着色器缓存失败(退出代码 {code})。详情:{log}",
"cleanup.ini_failed": "无法写入 nx2navi.ini:{detail}",
"warn.lang_needs_fonts": "{lang}文本需要 Switch 系统字体,但未提供。在添加这些字体之前,游戏无法以该语言启动。请选择固件文件夹(Contents/registered),或参阅 docs/installer.md 中的“Switch system fonts”一节。",
"warn.cheats_skipped": "无法构建 mods 文件夹中修改游戏代码的金手指;游戏将不含它们进行安装。详情:{log}",
"warn.exefs_skipped": "无法构建模组的 ExeFS 补丁(.ips、.pchtxt);游戏将不含它们进行安装。详情:{log}",
"warn.npdm_differs": "main.npdm 与参考的 {version} 导出不同;只使用其中的代码模块。",
"warn.xbox_prompts_failed": "无法准备 Xbox 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
"warn.shaders_skipped": "显卡驱动在编译部分着色器时崩溃,因此有 {count} 个着色器未被预先准备。游戏会在首次需要时编译它们,驱动在那时也可能崩溃;更新驱动可能会解决。详情:{log}",
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
"warn.dlss_download_failed": "无法从 {url} 下载 NVIDIA DLSS:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。",
"ui.title": "NX2navi 安装程序",
"ui.rebuild_title": "正在为你的模组重新构建游戏",
"ui.start_game": "启动游戏",
"ui.version": "版本 {version}",
"ui.intro": "用你自己的游戏文件构建一个可以游玩的《王国之泪》文件夹。耗时较长,只需运行一次。",
"ui.notice": "此安装程序构建的文件夹包含游戏本身,仅供你个人使用;请勿分享或上传。",
"ui.keys_private": "密钥文件只在原位置读取,其内容绝不会被显示、复制或保存。",
"ui.base": "游戏本体(NSP、XCI、NSZ 或 XCZ)",
"ui.update": "1.1.0、1.2.1 或 1.4.3 更新(NSP 或 NSZ)",
"ui.keys": "prod.keys",
"ui.firmware": "固件文件夹(可选)",
"ui.game_language": "游戏语言",
"ui.dest": "安装文件夹",
"ui.browse": "浏览...",
"ui.pick_game": "选择游戏本体文件",
"ui.pick_update": "选择 1.1.0、1.2.1 或 1.4.3 更新文件",
"ui.pick_keys": "选择 prod.keys",
"ui.pick_firmware": "选择 Switch 固件文件夹(Contents/registered)",
"ui.pick_dest": "选择安装文件夹",
"ui.firmware_help": "用于中文、韩文和繁体中文文本:固件的 Contents/registered 文件夹,例如来自 Ryujinx 或 The hardware。安装程序会从中把 Switch 系统字体复制到安装文件夹。",
"ui.dlss": "为 NVIDIA RTX 显卡下载 NVIDIA DLSS(nvngx_dlss.dll)",
"ui.dlss_help": "来自 GitHub 上 NVIDIA 的 DLSS SDK,遵循 NVIDIA RTX SDK 许可(github.com/NVIDIA/DLSS)。没有它,dlaa 和 DLSS 设置不起作用。",
"ui.compressed_help": "压缩的 NSZ 和 XCZ 文件可以直接使用:安装程序会自行解压(在游戏数据提取完成之前,需要与解压后文件大小相同的可用空间)。",
"ui.type_game": "游戏文件(NSP、XCI、NSZ、XCZ)",
"ui.type_keys": "密钥文件(*.keys)",
"ui.type_all": "所有文件",
"ui.start": "开始",
"ui.cancel": "取消",
"ui.cancelling": "正在取消...",
"ui.show_log": "显示日志",
"ui.hide_log": "隐藏日志",
"ui.close": "关闭",
"ui.back": "返回",
"ui.open_folder": "打开文件夹",
"ui.update_mode": "此文件夹中已有之前的安装。安装程序会继续或更新它;只有在需要时才会再次要求提供游戏文件。",
"ui.need_dest": "请选择安装文件夹。",
"ui.need_base": "请选择游戏本体文件。",
"ui.need_update": "请选择 1.1.0、1.2.1 或 1.4.3 更新文件。",
"ui.need_keys": "请选择 prod.keys 文件。",
"ui.need_lang": "请选择游戏语言。",
"ui.missing_base": "游戏本体文件不存在。",
"ui.missing_update": "更新文件不存在。",
"ui.missing_keys": "密钥文件不存在。",
"ui.missing_firmware": "固件文件夹不存在。",
"ui.running_install": "正在安装",
"ui.running_resume": "正在继续之前的安装",
"ui.running_update": "正在更新安装",
"ui.state_started": "已开始",
"ui.state_done": "完成",
"ui.state_skipped": "已跳过",
"ui.state_pending": "等待中",
"ui.state_running": "进行中",
"ui.state_failed": "失败",
"ui.log_warning": "警告",
"ui.log_error": "错误",
"ui.log_space": "所需空间:{need} GB,可用:{free} GB",
"ui.log_end": "已结束",
"ui.result_ok": "游戏已准备就绪",
"ui.result_failed": "安装失败",
"ui.result_cancelled": "安装已取消",
"ui.done_text": "从 {dest} 启动 {game_exe}。安装程序和你选择的游戏文件都不再需要了。",
"ui.cancelled_text": "已完成的步骤会保留。用同一个文件夹再次运行安装程序即可继续。",
"ui.log_file": "日志文件:{path}",
"ui.process_died": "安装程序意外停止(退出代码 {code})。",
"ui.confirm_cancel": "安装正在进行。要取消安装并关闭窗口吗?",
"ui.space_one": "{path} 需要的可用空间:{need} GB(可用:{free} GB)。",
"ui.space_two": "{path} 需要的可用空间:{need} GB(可用:{free} GB);{temp} 需要:{temp_need} GB(可用:{temp_free} GB)。",
"ui.amount_bytes": "{done} / {total} GB",
"ui.amount_chunks": "{done} / {total} 部分",
"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": "NX2navi 安装程序",
"launcher.python_missing": "安装文件不完整:NX2navi-Setup.exe 旁边缺少 python 文件夹。请重新解压整个压缩包,然后从解压出的文件夹中启动 NX2navi-Setup.exe。",
"lang.ja": "日语",
"lang.en-US": "英语(美国)",
"lang.en-GB": "英语(英国)",
"lang.fr": "法语",
"lang.fr-CA": "法语(加拿大)",
"lang.de": "德语",
"lang.it": "意大利语",
"lang.es": "西班牙语",
"lang.es-419": "西班牙语(拉丁美洲)",
"lang.nl": "荷兰语",
"lang.pt": "葡萄牙语",
"lang.pt-BR": "葡萄牙语(巴西)",
"lang.ru": "俄语",
"lang.ko": "韩语",
"lang.zh-Hans": "中文(简体)",
"lang.zh-Hant": "中文(繁体)"
}