Redraw the in-game menu with the game's own interface textures, and bring in the launcher's save import and faster builds.

In-game menu: the settings window, its tabs, rows, buttons and cursor, the performance overlay and the Preparing
shaders box are drawn with the game's interface textures where the RomFS holds them (runtime/ui/menu_skin.cpp,
perf_panel.cpp; plain shapes until they are decoded). Restart joins Continue and Quit, each behind a confirmation;
VSync is an on/off switch; DLSS is listed only on NVIDIA GPUs; the menu sounds are quieter; Picture shape is gone and
the setting descriptions are shorter; edge cases of input, layout and fonts are fixed. tools/menu_preview.py draws the
menu without the game.

Launcher: Import Saves takes a save from the game folder's saves/ folder or one the player picks; downloads fall back
to Windows' own certificate check when Python's refuses a server; updates are faster; the title bar is drawn in the
window and Navi is every icon. tools/make_game.py builds with CLANG64's clang where the launcher installed it, packs
the RomFS beside the lift and the compile, takes a prebuilt runtime, and compiles the game's resources without cmd.exe,
so a user folder with a space in its name builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
chrg6
2026-11-08 03:57:01 -05:00
parent 5b28da3a06
commit 8daedbd806
42 changed files with 4138 additions and 972 deletions

View File

@@ -1,8 +1,9 @@
"""The NX2navi launcher: installs the build tools, builds the game from the player's own dump, starts it and keeps
the port up to date (docs/launcher.md).
Standard library only, plus numpy for drawing the window (launcher/ui/art.py) and zstandard where Python lacks
compression.zstd. tkinter draws the window; everything that does work runs without it (launcher/cli.py).
Standard library only, plus numpy for drawing the window (launcher/ui/art.py), zstandard where Python lacks
compression.zstd, and truststore for Windows' own certificate check (launcher/net.py). tkinter draws the window;
everything that does work runs without it (launcher/cli.py).
"""
NAME = 'NX2navi'

View File

@@ -8,6 +8,7 @@
#include <shellapi.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <propsys.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
@@ -15,6 +16,12 @@
#define PATHN 1024
#define APP_NAME L"NX2navi"
#define UNINSTALL_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\NX2navi"
/* The launcher window's taskbar identity (launcher/winsys.py app_id): a shortcut that carries it is the one the
taskbar groups and pins the window under, with the shortcut's icon. */
#define APP_USER_MODEL_ID L"NX2navi.Launcher"
static const PROPERTYKEY NX_PKEY_AppUserModel_ID = {
{0x9F4C2855, 0x9F79, 0x4B39, {0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3}}, 5};
static const IID NX_IID_IPropertyStore = {0x886d8eeb, 0x8cf2, 0x4446, {0x8d, 0x02, 0xcd, 0xba, 0x1d, 0xbd, 0xcf, 0x99}};
static inline void exe_dir(wchar_t *out, size_t n)
{
@@ -105,6 +112,16 @@ static inline int make_shortcut(const wchar_t *lnk, const wchar_t *target, const
IShellLinkW_SetWorkingDirectory(sl, workdir);
IShellLinkW_SetIconLocation(sl, target, 0);
IShellLinkW_SetDescription(sl, desc);
IPropertyStore *ps = NULL;
if (SUCCEEDED(IShellLinkW_QueryInterface(sl, &NX_IID_IPropertyStore, (void **)&ps))) {
PROPVARIANT pv;
memset(&pv, 0, sizeof pv);
pv.vt = VT_LPWSTR;
pv.pwszVal = (LPWSTR)APP_USER_MODEL_ID;
IPropertyStore_SetValue(ps, &NX_PKEY_AppUserModel_ID, &pv);
IPropertyStore_Commit(ps);
IPropertyStore_Release(ps);
}
if (SUCCEEDED(IShellLinkW_QueryInterface(sl, &IID_IPersistFile, (void **)&pf))) {
ok = SUCCEEDED(IPersistFile_Save(pf, lnk, TRUE));
IPersistFile_Release(pf);

View File

@@ -1,4 +1,4 @@
/* The icon (the Triforce, written by tools/make_launcher.py from launcher/ui/art.py triforce_ico into the build
folder, found through -I) and the manifest of NX2navi.exe and NX2navi-Setup.exe. */
/* The icon (Navi, written by tools/make_launcher.py from launcher/ui/art.py navi_ico into the build folder,
found through -I) and the manifest of NX2navi.exe and NX2navi-Setup.exe. */
1 ICON "nx2navi.ico"
1 24 "app.manifest"

View File

@@ -32,6 +32,16 @@ typedef struct {
static Setup S;
static HWND g_wnd;
/* Navi as launcher/ui/art.py NAVI draws it: W white, g grey, K black, B and L blue, '.' transparent. */
static const char *const NAVI[21] = {
"WWWW..............WWWW", "WggWW............WWggW", "WgggWW..........WWgggW", "WgWggWW........WWggWgW",
"WggWggW........WggWggW", "WgWgWgWW......WWgWgWgW", "WggggWgWKKKKKKWgWggggW", "WWggWggKBBBBBBKggWggWW",
".WggggKKBBLLBBKKggggW.", ".WWggKKBBLLLLBBKKggWW.", "..WWgKBBLLWWLLBBKgWW..", "...WWKBBLWWWWLBBKWW...",
".....KBBLLWWLLBBK.....", ".....KBBBLLLLBBBK.....", ".....WKKBBBBBBKKW.....", "....WWgKKBBBBKKgWW....",
"...WWgggKKKKKKgggWW...", "...WggWgW....WgWggW...", "...WgWggW....WggWgW...", "...WWggWW....WWggWW...",
"....WWWW......WWWW....",
};
static void fail_msg(const wchar_t *fmt, const wchar_t *arg)
{
swprintf(S.error, 512, fmt, arg ? arg : L"");
@@ -258,35 +268,37 @@ static LRESULT CALLBACK wndproc(HWND w, UINT m, WPARAM wp, LPARAM lp)
FillRect(dc, &r, edge);
RECT in = {r.left + 2, r.top + 2, r.right - 2, r.bottom - 2};
FillRect(dc, &in, bg);
/* the Triforce: three gold triangles */
HBRUSH gold = CreateSolidBrush(RGB(0xe8, 0xaf, 0x3d));
HPEN none = CreatePen(PS_NULL, 0, 0);
HGDIOBJ ob = SelectObject(dc, gold), op = SelectObject(dc, none);
int cx = 52, top = 28, s = 44;
POINT t1[3] = {{cx, top}, {cx + s / 4, top + s * 433 / 1000}, {cx - s / 4, top + s * 433 / 1000}};
POINT t2[3] = {{cx - s / 4, top + s * 433 / 1000 + 1}, {cx, top + s * 866 / 1000}, {cx - s / 2, top + s * 866 / 1000}};
POINT t3[3] = {{cx + s / 4, top + s * 433 / 1000 + 1}, {cx + s / 2, top + s * 866 / 1000}, {cx, top + s * 866 / 1000}};
Polygon(dc, t1, 3);
Polygon(dc, t2, 3);
Polygon(dc, t3, 3);
SelectObject(dc, ob);
SelectObject(dc, op);
/* Navi, the launcher's emblem: the artwork's 22 x 21 pixels, 4 x 4 screen pixels each */
for (int y = 0; y < 21; y++)
for (int x = 0; x < 22; x++) {
COLORREF col;
switch (NAVI[y][x]) {
case 'W': col = RGB(255, 255, 255); break;
case 'g': col = RGB(207, 216, 220); break;
case 'K': col = RGB(0, 0, 0); break;
case 'B': col = RGB(2, 136, 209); break;
case 'L': col = RGB(79, 195, 247); break;
default: continue;
}
HBRUSH b = CreateSolidBrush(col);
RECT px = {16 + 4 * x, 18 + 4 * y, 20 + 4 * x, 22 + 4 * y};
FillRect(dc, &px, b);
DeleteObject(b);
}
HFONT big = CreateFontW(-26, 0, 0, 0, FW_SEMIBOLD, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, L"Segoe UI");
HFONT small = CreateFontW(-16, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, L"Segoe UI");
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, RGB(0xf3, 0xec, 0xdc));
HGDIOBJ of = SelectObject(dc, big);
TextOutW(dc, 96, 30, APP_NAME, (int)wcslen(APP_NAME));
TextOutW(dc, 120, 30, APP_NAME, (int)wcslen(APP_NAME));
SelectObject(dc, small);
SetTextColor(dc, RGB(0xe9, 0xdc, 0xc0));
wchar_t line[96];
swprintf(line, 96, L"Installing version %ls\x2026 %llu MB", S.version, (unsigned long long)(S.written >> 20));
TextOutW(dc, 96, 66, line, (int)wcslen(line));
TextOutW(dc, 120, 66, line, (int)wcslen(line));
SelectObject(dc, of);
DeleteObject(big);
DeleteObject(small);
DeleteObject(gold);
DeleteObject(none);
DeleteObject(bg);
DeleteObject(edge);
EndPaint(w, &ps);

View File

@@ -1,17 +1,37 @@
"""HTTPS for the launcher: JSON requests and file downloads that resume, report progress, can be cancelled and are
checked against a sha256. Standard library only (urllib); Windows' own certificate store verifies the servers."""
checked against a sha256. The standard library (urllib), and on Windows the truststore package of the launcher's
Python for Windows' own certificate check.
Two checks can accept a server's certificate, tried in turn by request():
- Python's: OpenSSL with the certificates of Windows' ROOT and CA stores (ssl.create_default_context). It knows only
the certificates already in those stores, while Windows holds few roots and downloads the others the first time a
Windows program needs them. And it takes a stored certificate before the server's copy of the same name and key: a
store that still holds an old, expired cross-signature of the root a server's chain leads to makes it report
"certificate has expired" for a valid chain (repo.msys2.org's chain on a PC whose CA store still holds the
"ISRG Root X2" cross-signature that expired in September 2025).
- Windows': Windows' own chain engine, which Windows programs check servers with (CertGetCertificateChain and
CertVerifyCertificateChainPolicy, through truststore.SSLContext). It weighs every path the stores and the server
allow, prefers a valid one, and downloads a missing root from Windows Update.
A certificate both refuse ends the request with CertificateError: what each check said, whether the PC's clock agrees
with the server's, and what to do."""
import email.utils
import hashlib
import json
import os
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import timezone
from pathlib import Path
from . import NAME
CHUNK = 1 << 20
CLOCK_TOLERANCE = 3600 # seconds between this PC's clock and a server's beyond which this PC's is wrong
class Cancelled(Exception):
@@ -22,26 +42,127 @@ class DownloadError(Exception):
pass
class CertificateError(DownloadError):
"""No certificate check accepts a server's certificate. Asking again gets the same answer, so download() does
not retry it."""
def user_agent(version='dev'):
return f'{NAME}-Launcher/{version}'
_CTX = None
def _under_wine():
try:
import ctypes
return hasattr(ctypes.WinDLL('ntdll'), 'wine_get_version')
except Exception:
return False
def _context():
global _CTX
if _CTX is None:
_CTX = ssl.create_default_context()
return _CTX
def _windows_check():
"""An SSLContext that leaves the certificate to Windows' own verifier, or None off Windows, in a Python without
truststore (a checkout's own Python) and under Wine. Wine's crypt32 accepts a chain that stops at an issuer it
does not know (CERT_TRUST_IS_PARTIAL_CHAIN passes its SSL policy), and its roots are the host's, which Python's
check reads already."""
if os.name != 'nt' or _under_wine():
return None
try:
import truststore
return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
except Exception: # not installed, or crypt32 not reachable through ctypes
return None
_CHECKS = None # [(name, SSLContext)] in the order request() tries them
_ACCEPTED = {} # host -> index into _CHECKS of the check that accepted its certificate last
def _checks():
global _CHECKS
if _CHECKS is None:
checks = [("Python's check", ssl.create_default_context())]
windows = _windows_check()
if windows is not None:
checks.append(("Windows' check", windows))
_CHECKS = checks
return _CHECKS
def request(url, headers=None, timeout=30, version='dev'):
"""The open response to a GET of url. An https URL is tried with each certificate check in turn, first the one
that accepted the host last, until one accepts the server; CertificateError when none does."""
h = {'User-Agent': user_agent(version)}
h.update(headers or {})
req = urllib.request.Request(url, headers=h)
ctx = _context() if url.startswith('https:') else None
return urllib.request.urlopen(req, timeout=timeout, context=ctx)
if not url.startswith('https:'):
return urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout)
host = urllib.parse.urlsplit(url).hostname or ''
checks = _checks()
first = min(_ACCEPTED.get(host, 0), len(checks) - 1)
refused = []
for i in [first] + [i for i in range(len(checks)) if i != first]:
name, ctx = checks[i]
try:
r = urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout, context=ctx)
except urllib.error.URLError as e:
if not isinstance(e.reason, ssl.SSLCertVerificationError):
raise
refused.append((name, e.reason))
continue
_ACCEPTED[host] = i
return r
raise CertificateError(certificate_problem(url, refused, version)) from refused[0][1]
def server_clock(url, timeout=10, version='dev'):
"""The time (epoch seconds) of the Date header a plain-HTTP HEAD request to url answers with, without following a
redirect, or None without an answer. A PC whose clock is wrong cannot check any certificate, so its clock is
compared over HTTP; the answer is not authenticated and only chooses the advice of an error message."""
class Stay(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': user_agent(version)})
try:
with urllib.request.build_opener(Stay).open(req, timeout=timeout) as r:
date = r.headers.get('Date')
except urllib.error.HTTPError as e: # the redirect to https, or any other status: its Date is as good
date = e.headers.get('Date')
e.close()
except Exception: # no answer, whatever the reason (refused, timed out, not HTTP)
return None
if not date:
return None
try:
when = email.utils.parsedate_to_datetime(date)
except (TypeError, ValueError):
return None
return (when if when.tzinfo else when.replace(tzinfo=timezone.utc)).timestamp()
def _said(err):
said = getattr(err, 'verify_message', None) or (str(err.args[-1]) if err.args else type(err).__name__)
return said.strip().rstrip('.')
def _local(t):
return time.strftime('%Y-%m-%d %H:%M', time.localtime(t))
def certificate_problem(url, refused, version='dev'):
"""The message of a CertificateError for url: what each check in refused ([(name, error)]) said, then the advice
that fits this PC's clock."""
host = urllib.parse.urlsplit(url).hostname or url
said = '; '.join(f'{name}: {_said(e)}' for name, e in refused)
text = f'{url}: the certificate of {host} was not accepted ({said}).'
where = 'Windows Settings > Time & language > Date & time' if os.name == 'nt' else "the system's settings"
ours, theirs = time.time(), server_clock(f'http://{host}/', version=version)
if theirs is not None and abs(ours - theirs) > CLOCK_TOLERANCE:
return (f"{text} This PC's clock reads {_local(ours)}, but {host} says it is {_local(theirs)}: set the date, "
f'time and time zone in {where}, then try again.')
clock = (f"This PC's clock agrees with {host}'s." if theirs is not None else
f"Check that this PC's date, time and time zone are right ({where}).")
return (f'{text} {clock} Security software that scans encrypted connections (HTTPS or SSL scanning) or a proxy '
'may be replacing the certificate: let NX2navi through it or turn that scanning off, then try again.')
def get_bytes(url, headers=None, timeout=30, version='dev', limit=64 << 20):
@@ -100,7 +221,7 @@ def download(url, dest, sha256=None, size=None, progress=None, cancel=None, head
if progress:
progress(done, total or done)
break
except Cancelled:
except (Cancelled, CertificateError):
raise
except urllib.error.HTTPError as e:
if e.code == 416 and have: # the part file is complete or longer than the file: start over

221
launcher/saves.py Normal file
View File

@@ -0,0 +1,221 @@
"""Importing a save into the built game, and the saves folder of the game folder.
The game keeps its save in <game>/profile/save/<account>/ (runtime/fs_host.c storage_init). The folder is named after
the local account in <game>/profile/account.uid: 16 bytes, two little-endian 64-bit halves, the low one first; the
name is the high half then the low half, 16 hex digits each (runtime/ov_system.c load_uid). A game that never ran has
no account yet; the import makes one as the game would. Saves are committed through <game>/profile/save-tx/, where
a finished commit (ready-<n>) is newer than save/<account>: an import clears that folder, so the game loads the
imported save.
<game>/saves is the player's side. Import Saves takes a save put there first (its files, or the folder that holds
them); otherwise the player picks a folder. Before the save is replaced it is copied to saves/backup <time>, and a
save taken from saves/ moves to saves/imported <time>, so nothing is lost and nothing is imported twice.
A save folder can come from a Switch save backup (the save's files), an emulator (nested folders named by user and
title ids, gone down while each holds only one folder), another NX2navi game folder or its profile folder (the
account folder inside).
"""
import os
import re
import shutil
import time
from pathlib import Path
README = '''NX2navi saves folder
To import a save, put it here and select Import Saves in the NX2navi launcher (next to Game Folder):
- the files of a Switch save backup, or the folder that holds them
- an emulator's save folder for the game
- the profile folder (or the whole game folder) of another NX2navi install
You can also select Import Saves and choose the folder instead.
Before a save is imported, the game's current save is copied here into a folder named "backup" and the date. An
imported save moves into a folder named "imported" and the date. The game itself keeps its save in profile\\save.
'''
HEX32 = re.compile(r'^[0-9a-fA-F]{32}$')
MAX_FILES, MAX_BYTES = 4000, 1 << 30 # a save is a few files of a few MB; more is a folder picked by mistake
OURS = re.compile(r'^(backup|imported) \d{4}-\d\d-\d\d') # what this module writes into saves/
class SaveError(Exception):
pass
def saves_dir(game):
return Path(game) / 'saves'
def ensure_saves_dir(game):
"""<game>/saves with its README.txt."""
d = saves_dir(game)
d.mkdir(parents=True, exist_ok=True)
readme = d / 'README.txt'
if not readme.is_file():
readme.write_text(README, encoding='utf-8', newline='\r\n')
return d
def account_dir(game):
"""The game's save folder for its local account, making the account as the game does when it has none."""
prof = Path(game) / 'profile'
f = prof / 'account.uid'
data = f.read_bytes() if f.is_file() else b''
if not data:
data = bytes(16)
while data == bytes(16):
data = os.urandom(16)
prof.mkdir(parents=True, exist_ok=True)
tmp = f.with_name('account.uid.tmp')
tmp.write_bytes(data)
os.replace(tmp, f)
if len(data) != 16 or data == bytes(16):
raise SaveError(f'{f} is not an account file of the game')
lo, hi = int.from_bytes(data[:8], 'little'), int.from_bytes(data[8:], 'little')
return prof / 'save' / f'{hi:016x}{lo:016x}'
def _fresh(folder, name):
"""folder/name, or folder/"name (2)" and so on when that is taken (two imports in one second)."""
p, n = folder / name, 2
while p.exists():
p, n = folder / f'{name} ({n})', n + 1
return p
def _entries(folder, skip=()):
return [e for e in Path(folder).iterdir() if e.name not in skip and not e.name.startswith('.')]
def find_save(folder):
"""(source folder, top-level names to leave out) of the save in folder, or (None, ()) when it holds none."""
p = Path(folder)
if not p.is_dir():
return None, ()
for base in (p / 'profile' / 'save', p / 'save'): # another game folder, or its profile folder
if base.is_dir():
accounts = [d for d in base.iterdir() if d.is_dir() and HEX32.match(d.name)]
if accounts:
return max(accounts, key=lambda d: d.stat().st_mtime), ()
for _ in range(8): # nested id folders: go down while the folder holds a single folder and no file
entries = _entries(p)
dirs = [e for e in entries if e.is_dir()]
if len(entries) != 1 or len(dirs) != 1:
break
p = dirs[0]
return (p, ()) if _has_file(p) else (None, ())
def waiting(game):
"""(source, names to leave out) of a save put into <game>/saves, or (None, ())."""
d = saves_dir(game)
if not d.is_dir():
return None, ()
skip = {'README.txt'} | {e.name for e in d.iterdir() if e.is_dir() and OURS.match(e.name)}
entries = _entries(d, skip)
if not entries:
return None, ()
if len(entries) == 1 and entries[0].is_dir():
return find_save(entries[0])
return (d, tuple(sorted(skip))) if any(e.is_file() or _has_file(e) for e in entries) else (None, ())
def _has_file(folder):
return any(files for _, _, files in os.walk(folder))
def _files(src, skip):
"""Relative paths of the files to import; SaveError when there are too many or too large to be a save."""
out, size = [], 0
for root, dirs, files in os.walk(src):
if Path(root) == Path(src):
dirs[:] = [d for d in dirs if d not in skip and not d.startswith('.')]
files = [f for f in files if f not in skip and not f.startswith('.')]
for f in files:
p = Path(root) / f
out.append(p.relative_to(src))
size += p.stat().st_size
if len(out) > MAX_FILES or size > MAX_BYTES:
raise SaveError(f'{src} holds more than a save ({len(out)} files, {size / 1e6:.0f} MB so far); '
'choose the folder with the save\'s files')
if not out:
raise SaveError(f'{src} holds no files')
return out
def _newest(game, account):
"""The folder the game would load now: a finished commit still waiting in save-tx, else the account folder."""
tx = Path(game) / 'profile' / 'save-tx'
ready = []
if tx.is_dir():
for d in tx.iterdir():
m = re.fullmatch(r'ready-(\d+)', d.name)
if m and d.is_dir():
ready.append((int(m.group(1)), d))
if ready:
return max(ready)[1]
return account if account.is_dir() else None
def game_running(game):
"""Windows: ocarina.exe cannot be opened for writing while it runs."""
exe = Path(game) / 'ocarina.exe'
if os.name != 'nt' or not exe.is_file():
return False
try:
with open(exe, 'r+b'):
return False
except PermissionError:
return True
except OSError:
return False
def import_save(game, folder=None, log=print):
"""Make the save in folder (None: the one waiting in <game>/saves) the game's save. Returns {'files', 'source',
'backup'}; backup is the folder the replaced save went to, or None when there was none."""
game = Path(game)
from_saves = folder is None
src, skip = waiting(game) if from_saves else find_save(folder)
if src is None:
raise SaveError('the saves folder holds no save' if from_saves else f'{folder} holds no save files')
prof = (game / 'profile').resolve()
if Path(src).resolve() == prof or prof in Path(src).resolve().parents:
raise SaveError('that is the game\'s own save')
files = _files(src, set(skip))
account = account_dir(game)
saves = ensure_saves_dir(game)
stamp = time.strftime('%Y-%m-%d %H.%M.%S')
backup = None
current = _newest(game, account)
if current is not None and _has_file(current):
backup = _fresh(saves, f'backup {stamp}')
shutil.copytree(current, backup)
tx = game / 'profile' / 'save-tx'
tx.mkdir(parents=True, exist_ok=True)
stage = tx / 'import'
shutil.rmtree(stage, ignore_errors=True)
for rel in files:
(stage / rel).parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(Path(src) / rel, stage / rel)
for d in list(tx.iterdir()): # the journal of the replaced save: the game would load a finished commit first
if d != stage:
shutil.rmtree(d, ignore_errors=True) if d.is_dir() else d.unlink(missing_ok=True)
account.parent.mkdir(parents=True, exist_ok=True)
if account.exists():
gone = tx / 'replaced'
os.replace(account, gone)
shutil.rmtree(gone, ignore_errors=True)
os.replace(stage, account)
if from_saves: # what was put into saves/ moves out whole, so the next import does not take any of it again
done = _fresh(saves, f'imported {stamp}')
done.mkdir()
if Path(src) == saves:
top = sorted({rel.parts[0] for rel in files})
else: # the save sits in a folder that was put there (a game folder, an emulator's id folders)
top = [Path(src).relative_to(saves).parts[0]]
for name in top:
shutil.move(str(saves / name), str(done / name))
log(f'saves: imported {len(files)} files from {src} into {account}' + (f'; the old save is in {backup}' if backup
else ''))
return {'files': len(files), 'source': Path(src), 'backup': backup}

View File

@@ -8,6 +8,10 @@ toolchain.lock.json (make_lock, written by tools/make_launcher.py), so every pla
release was tested with; the repository keeps old package files. A checkout without a lock resolves the newest
packages instead.
Beside it goes the clang of MSYS2's CLANG64 environment (toolchain/msys64/clang64), the same LLVM release built with
profile-guided optimisation: it compiles the lifted code about a fifth faster into the same objects, reading UCRT64's
headers (tools/make_game.py fast_clang). Only clang.exe, the DLLs it loads and its own headers are unpacked.
zbic (GPL-2.0) unpacks the game's compressed program files. The release does not carry it: the launcher downloads the
wheel for its own Python from PyPI and unpacks it into pydeps/, as `pip install zbic` would.
"""
@@ -28,11 +32,17 @@ from . import net
REPO = 'https://repo.msys2.org/mingw/ucrt64/'
MIRRORS = (REPO, 'https://mirror.msys2.org/mingw/ucrt64/')
PREFIX = 'mingw-w64-ucrt-x86_64-'
ROOTS = ('clang', 'gcc', 'sdl3', 'opus', 'libvpx', 'dav1d', 'zstd', 'vulkan-headers', 'vulkan-loader',
'vulkan-memory-allocator')
ROOTS = ('clang', 'gcc', 'lld', 'sdl3', 'opus', 'libvpx', 'dav1d', 'zstd', 'vulkan-headers', 'vulkan-loader',
'vulkan-memory-allocator') # lld: the game links several times faster than with GNU ld
REQUIRED = ('bin/clang.exe', 'bin/clang++.exe', 'bin/SDL3.dll', 'lib/libSDL3.dll.a', 'include/vma')
SKIP_SHARE = ('ucrt64/share/doc/', 'ucrt64/share/man/', 'ucrt64/share/info/', 'ucrt64/share/locale/',
'ucrt64/share/gtk-doc/', 'ucrt64/share/licenses/')
# CLANG64's clang: exactly the packages clang.exe loads DLLs from (not the dependency closure, which adds the linker,
# the LLVM tools and the CLANG64 C runtime the lifted code does not use).
FAST_REPO = 'https://repo.msys2.org/mingw/clang64/'
FAST_MIRRORS = (FAST_REPO, 'https://mirror.msys2.org/mingw/clang64/')
FAST_PREFIX = 'mingw-w64-clang-x86_64-'
FAST_PACKAGES = ('clang', 'clang-libs', 'llvm-libs', 'libc++', 'libffi', 'zlib', 'zstd', 'libxml2', 'libiconv')
ZBIC = ('zbic', '1.0.1.post1')
LOCK_FORMAT = 1
@@ -101,19 +111,37 @@ def resolve(db, roots=ROOTS):
seen.add(n)
order.append(n)
todo += db[n].get('DEPENDS', [])
pkgs = []
for n in order:
d = db[n]
pkgs.append({'name': n, 'version': d['VERSION'][0], 'filename': d['FILENAME'][0],
'sha256': d['SHA256SUM'][0], 'csize': int(d['CSIZE'][0]), 'isize': int(d.get('ISIZE', ['0'])[0])})
return pkgs
return [_pkg(db, n) for n in order]
def make_lock(repo=REPO, roots=ROOTS, version='dev'):
"""The lock a release ships: the resolved package files of the repository's current database."""
def make_lock(repo=REPO, roots=ROOTS, version='dev', fast_repo=None):
"""The lock a release ships: the resolved package files of the repository's current database. With fast_repo
(FAST_REPO), also CLANG64's clang, when that repository has the same clang version as UCRT64's."""
db = parse_db(net.get_bytes(repo + 'ucrt64.db', version=version))
return {'format': LOCK_FORMAT, 'repo': repo, 'roots': list(roots), 'packages': resolve(db, roots),
pkgs = resolve(db, roots)
lock = {'format': LOCK_FORMAT, 'repo': repo, 'roots': list(roots), 'packages': pkgs,
'zbic': {'name': ZBIC[0], 'version': ZBIC[1]}, 'made': time.strftime('%Y-%m-%d')}
if fast_repo:
fdb = parse_db(net.get_bytes(fast_repo + 'clang64.db', version=version))
fast = [_pkg(fdb, FAST_PREFIX + n, env='clang64') for n in FAST_PACKAGES]
mine = next(p['version'] for p in pkgs if p['name'] == PREFIX + 'clang')
if fast[0]['version'] == mine:
lock['packages'] = pkgs + fast
lock['fast_repo'] = fast_repo
else:
lock['fast_skipped'] = f'CLANG64 has clang {fast[0]["version"]}, UCRT64 {mine}'
return lock
def _pkg(db, name, env=None):
if name not in db:
raise ToolchainError(f'the package database has no {name}')
d = db[name]
p = {'name': name, 'version': d['VERSION'][0], 'filename': d['FILENAME'][0], 'sha256': d['SHA256SUM'][0],
'csize': int(d['CSIZE'][0]), 'isize': int(d.get('ISIZE', ['0'])[0])}
if env:
p['env'] = env
return p
def lock_digest(lock):
@@ -150,9 +178,18 @@ def is_current(layout, lock):
return bool(inst) and inst.get('digest') == lock_digest(lock) and not missing_files(layout.msys)
def _extract_package(path, dest):
"""Unpack one .pkg.tar.zst into dest (the msys64 folder): only its ucrt64/ files, without the documentation.
The archive is read as a stream, member by member, so a 350 MB package never sits in memory whole."""
def _wanted(name, env):
"""Whether a package member is unpacked: UCRT64's files without the documentation; of CLANG64's, clang.exe, the
DLLs and clang's own headers."""
if env == 'clang64':
return (name == 'clang64/bin/clang.exe' or (name.startswith('clang64/bin/') and name.endswith('.dll'))
or name.startswith('clang64/lib/clang/'))
return name.startswith('ucrt64/') and not name.startswith(SKIP_SHARE)
def _members(path):
"""The members of a .pkg.tar.zst (or plain tar), read as a stream, member by member, so a 350 MB package never
sits in memory whole. Yields (tarfile, member)."""
with open(path, 'rb') as raw:
zst = raw.read(4) == b'\x28\xb5\x2f\xfd'
raw.seek(0)
@@ -167,9 +204,22 @@ def _extract_package(path, dest):
fileobj = raw
with tarfile.open(fileobj=fileobj, mode='r|*') as t:
for m in t:
name = m.name.lstrip('./')
if name.startswith('ucrt64/') and not name.startswith(SKIP_SHARE):
t.extract(m, dest, filter='data')
yield t, m
def _extract_package(path, dest, env=None):
"""Unpack one package into dest (the msys64 folder): the members _wanted keeps. A wanted hard link needs its
target on disk, and a stream cannot go back for it: a selective unpack (env) first reads the headers for the
targets of the wanted links (CLANG64's clang.exe is one) and unpacks them too."""
want = set()
if env:
for _, m in _members(path):
if m.islnk() and _wanted(m.name.lstrip('./'), env):
want.add(m.linkname.lstrip('./'))
for t, m in _members(path):
name = m.name.lstrip('./')
if name in want or _wanted(name, env):
t.extract(m, dest, filter='data')
def install(layout, lock, progress=None, cancel=None, log=print, version='dev'):
@@ -185,7 +235,9 @@ def install(layout, lock, progress=None, cancel=None, log=print, version='dev'):
for p in need:
dest = layout.pkgs / p['filename']
last_error = None
for mirror in [lock.get('repo', REPO)] + [m for m in MIRRORS if m != lock.get('repo', REPO)]:
first, others = ((lock.get('fast_repo', FAST_REPO), FAST_MIRRORS) if p.get('env') == 'clang64'
else (lock.get('repo', REPO), MIRRORS))
for mirror in [first] + [m for m in others if m != first]:
try:
net.download(mirror + p['filename'], dest, sha256=p['sha256'], size=p['csize'], cancel=cancel,
progress=(lambda d, t, base=done_before: progress and progress('download', base + d, total)),
@@ -210,7 +262,7 @@ def install(layout, lock, progress=None, cancel=None, log=print, version='dev'):
raise net.Cancelled()
if progress:
progress('unpack', i, len(pkgs))
_extract_package(layout.pkgs / p['filename'], staging)
_extract_package(layout.pkgs / p['filename'], staging, p.get('env'))
if progress:
progress('unpack', len(pkgs), len(pkgs))
missing = missing_files(staging / 'ucrt64')

View File

@@ -1,5 +1,6 @@
"""The launcher's window, laid out like the game's options menu (docs/launcher.md, "Look"): a wooden title band with
the Triforce and the name in the game's Cetra Display, a list of rows on the left (a bronze label cell and a dark value cell each), a white
Navi and the name in the game's Cetra Display across the whole top (the window's own title bar: drag it to move the
window, minimise and close at its right end), a list of rows on the left (a bronze label cell and a dark value cell each), a white
glowing cursor on the selected row, filigree dividers between groups and a description box on the right that
explains the selected row.
@@ -25,12 +26,13 @@ import tkinter.font as tkfont
from pathlib import Path
from tkinter import filedialog
from .. import NAME, build, feed, gamefiles, jobs, versions, winsys
from .. import NAME, build, feed, gamefiles, jobs, saves, versions, winsys
from ..context import Context
from . import art
W, H = 1000, 640
BAND = (52, 948, 56) # x0, x1, height
BAND = (0, 1000, 56) # x0, x1, height: the whole top of the window, which is also its title bar
TITLE_BUTTONS = (('min', 908, 954), ('close', 954, 1000)) # x ranges on the band
PANEL = (112, 60, 580) # x0, top, x1
ROWS = (140, 552, 96) # x0, x1, top
LABEL_W = 222 # 54 % of the row
@@ -105,6 +107,7 @@ class App:
self.check_error = ''
self.checked_at = 0.0
self.message = ''
self.save_message = '' # the last Import Saves result, shown in its description
self.dumps = None
self.dump_search = None
self.uninstall_game = False
@@ -112,6 +115,9 @@ class App:
self.cursor_frames, self.cursor_k = [], 0
self.last_second = 0
self.gamepad = winsys.Gamepad()
self.tb_hover = None
self.drag = None
self.ico = None
root.title(NAME)
root.resizable(False, False)
@@ -128,6 +134,8 @@ class App:
self.root.after(150, self.tick)
self.root.after(50, self.poll_gamepad)
self.center()
self.framed = not winsys.frameless(root) # Windows: the band is the title bar
self.root.after(60, self.native_window)
# ---------------------------------------------------------------- scale, icon, fonts
@@ -151,17 +159,27 @@ class App:
self.root.geometry(f'{w}x{h}+{x}+{y}')
def set_icon(self):
"""Navi as the window's icon: Tk's photo icon everywhere, and on Windows the .ico set on the window itself, so
the taskbar button shows Navi rather than Python's icon."""
try:
self.photos['icon'] = art.photo(self.root, art.triforce(64))
self.photos['icon'] = art.photo(self.root, art.navi_icon(64))
self.root.iconphoto(True, self.photos['icon'])
if os.name == 'nt':
ico = self.layout.cache / 'nx2navi.ico'
if not ico.is_file():
ico.write_bytes(art.triforce_ico())
self.root.iconbitmap(default=str(ico))
data = art.navi_ico()
self.ico = self.layout.cache / 'nx2navi.ico'
if not self.ico.is_file() or self.ico.read_bytes() != data:
self.ico.write_bytes(data)
except (tk.TclError, OSError) as e:
self.ctx.log(f'icon: {e}')
def native_window(self):
if self.ico:
winsys.set_window_icon(self.root, self.ico)
try:
self.root.focus_force()
except tk.TclError:
pass
def load_fonts(self):
"""The game's Cetra Display when this PC has decoded it from the player's game (data/cache/fonts), else the
system's interface font."""
@@ -239,23 +257,47 @@ class App:
c.create_image(0, 0, anchor='nw', image=self.sprite('backdrop', lambda: art.backdrop(self.X(W), self.X(H), s)),
tags='static')
bx0, bx1, bh = BAND
c.create_image(self.X(bx0), 0, anchor='nw', tags='static',
image=self.sprite('band', lambda: art.band(self.X(bx1) - self.X(bx0), self.X(bh), s)))
px0, ptop, px1 = PANEL
c.create_image(self.X(px0), self.X(ptop), anchor='nw', tags='static',
image=self.sprite('panel', lambda: art.panel(self.X(px1) - self.X(px0), self.X(H - ptop), s)))
tri = self.sprite('triforce', lambda: art.triforce(self.X(44)))
c.create_image(self.X(bx0), 0, anchor='nw', tags='static',
image=self.sprite('band', lambda: art.band(self.X(bx1) - self.X(bx0), self.X(bh), s)))
k = max(1, int(round(2 * s))) # Navi in whole pixels: two screen pixels per artwork pixel at 100 %
emblem = self.sprite(('navi', k), lambda: art.navi(k))
ew = emblem.width()
title_w = self.f['band'].measure(NAME)
gap = self.X(12)
total = self.X(44) + gap + title_w
x = self.X(W / 2) - total // 2
c.create_image(x, self.X(bh / 2), anchor='w', image=tri, tags='static')
tx = x + self.X(44) + gap
x = self.X(W / 2) - (ew + gap + title_w) // 2
c.create_image(x, self.X(bh / 2), anchor='w', image=emblem, tags='static')
tx = x + ew + gap
c.create_text(tx + 1, self.X(bh / 2) + self.X(2), text=NAME, anchor='w', font=self.f['band'], fill='#1a120a',
tags='static')
c.create_text(tx, self.X(bh / 2), text=NAME, anchor='w', font=self.f['band'], fill=P['band_text'],
tags='static')
c.create_rectangle(0, 0, self.X(W) - 1, self.X(H) - 1, outline='#140e09', tags='static')
c.tag_lower('static')
self.draw_title_buttons()
def draw_title_buttons(self):
"""Minimise and close at the band's right end, lit when the mouse is over them."""
c, X = self.canvas, self.X
c.delete('tb')
bh = X(BAND[2])
for kind, x0, x1 in TITLE_BUTTONS:
if self.tb_hover == kind:
c.create_rectangle(X(x0), 0, X(x1), bh - 1, outline='', tags='tb',
fill=P['close_hover'] if kind == 'close' else P['button_hover'])
size = X(12)
glyph = self.sprite(('glyph', kind, size), lambda kd=kind: art.title_glyph(kd, size, self.s))
c.create_image((X(x0) + X(x1)) // 2, bh // 2, image=glyph, tags='tb')
def title_button_at(self, x, y):
if y >= self.X(BAND[2]):
return None
for kind, x0, x1 in TITLE_BUTTONS:
if self.X(x0) <= x < self.X(x1):
return kind
return None
# ---------------------------------------------------------------- input
@@ -269,6 +311,10 @@ class App:
r.bind(key, fn)
self.canvas.bind('<Motion>', self.on_motion)
self.canvas.bind('<Button-1>', self.on_click)
self.canvas.bind('<B1-Motion>', self.on_drag)
self.canvas.bind('<ButtonRelease-1>', lambda e: setattr(self, 'drag', None))
self.canvas.bind('<Leave>', lambda e: self.set_tb_hover(None))
r.bind('<Alt-F4>', lambda e: self.on_close())
r.protocol('WM_DELETE_WINDOW', self.on_close)
def poll_gamepad(self):
@@ -344,7 +390,18 @@ class App:
return i
return None
def set_tb_hover(self, kind):
if kind != self.tb_hover:
self.tb_hover = kind
self.draw_title_buttons()
def on_drag(self, e):
if self.drag: # moving the window without the system's help (Linux)
dx, dy = self.drag
self.root.geometry(f'+{e.x_root - dx}+{e.y_root - dy}')
def on_motion(self, e):
self.set_tb_hover(self.title_button_at(e.x, e.y))
i = self.hit(e.x, e.y)
if i is not None and i != self.focus:
self.focus = i
@@ -360,6 +417,22 @@ class App:
self.render()
def on_click(self, e):
try:
self.root.focus_force()
except tk.TclError:
pass
kind = self.title_button_at(e.x, e.y)
if kind == 'close':
self.on_close()
return
if kind == 'min':
self.set_tb_hover(None)
winsys.minimize(self.root)
return
if e.y < self.X(BAND[2]): # the band moves the window, like a title bar
if not winsys.start_drag(self.root):
self.drag = (e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y())
return
i = self.hit(e.x, e.y)
if i is None:
return
@@ -597,8 +670,9 @@ class App:
upd,
Row('divider'),
Row('value', 'Game Folder', gd, on=lambda: self.open(gd),
desc=('Open the game folder. Your saves are in its profile folder, the game\'s settings in '
'nx2navi.ini and its logs in logs.',)),
desc=('Open the game folder. The game keeps your save in its profile folder, its settings in '
'nx2navi.ini and its logs in logs. Its saves folder is for saves to import.',)),
self.saves_row(gd),
Row('value', 'Rebuild the Game', rebuild_value, rebuild_style, on=self.start_rebuild,
desc=('Build the game again from the files of the last build. Only what changed is compiled. Use it '
'after changing build tools, or if the game stopped starting.',)),
@@ -606,6 +680,45 @@ class App:
desc=('Updates, the game folder, the logs and uninstalling.',)),
]
def saves_row(self, gd):
"""Import Saves: a save put into the game folder's saves folder, else a folder the player picks."""
ready = False
if gd and Path(gd).is_dir():
try:
saves.ensure_saves_dir(gd)
ready = saves.waiting(gd)[0] is not None
except OSError:
pass
desc = ('Bring in a save from a Switch save backup, an emulator or another NX2navi install. Put it into the '
'saves folder of the game folder and select this row, or select this row and choose its folder.',
'Your current save is copied to the saves folder first.')
if self.save_message:
desc = (self.save_message,) + desc
return Row('value', 'Import Saves', 'From the Saves Folder' if ready else 'Choose a Folder',
'orange_arrow' if ready else 'arrow', on=self.import_saves, desc=desc)
def import_saves(self):
gd = self.settings.get('game_dir')
if not gd or not Path(gd).is_dir():
self.save_message = 'Install the game first.'
elif (self.game_proc and self.game_proc.poll() is None) or saves.game_running(gd):
self.save_message = 'Quit the game first: it keeps its save open while it runs.'
else:
try:
folder = None
if saves.waiting(gd)[0] is None:
folder = filedialog.askdirectory(parent=self.root, title='Choose the folder with the save',
initialdir=str(saves.ensure_saves_dir(gd)), mustexist=True)
if not folder:
return
r = saves.import_save(gd, folder, log=self.ctx.log)
except (saves.SaveError, OSError) as e:
self.save_message = f'The save was not imported: {e}'
else:
self.save_message = (f'Save imported: {r["files"]} files from {r["source"].name}.'
+ (f' Your old save is in saves\\{r["backup"].name}.' if r['backup'] else ''))
self.show('home', self.focus)
def update_desc(self):
r = self.release
nv, mine = versions.display(r.version), versions.display(self.layout.version)
@@ -1083,6 +1196,12 @@ class App:
cw, ch = X(9), X(12)
img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, '#d9ccae'))
c.create_image(x1 - X(16), cy, anchor='e', image=img, tags='dyn')
if r.value: # a value, centred in the cell's room left of the arrow
right = x1 - X(16) - cw - X(10)
avail = right - vx0 - X(16)
vfont = self.fit_font(vfont, r.value, avail, 0.8)
c.create_text((vx0 + right) // 2, cy, text=fit(vfont, r.value, avail), font=vfont,
fill=P['value_text'], tags='dyn')
else:
color = {'normal': P['value_text'], 'dim': P['dim'], 'salmon': P['salmon']}.get(r.style, P['value_text'])
avail = (x1 - vx0) - X(20) - (X(21) if r.check else 0)

View File

@@ -1,8 +1,8 @@
"""The window's pictures, drawn with numpy into RGBA arrays and handed to Tk as PNG data.
Everything is drawn here from shapes and colours: the misty green backdrop, the wooden title band, the bronze label
cells with their mottled texture, the description box, the white glowing cursor, the filigree divider, the Triforce
and the small icons. Tk's canvas draws lines and polygons without antialiasing on Windows, so every curved or soft
cells with their mottled texture, the description box, the white glowing cursor, the filigree divider, Navi and
the small icons. Tk's canvas draws lines and polygons without antialiasing on Windows, so every curved or soft
shape is a picture; flat rectangles and text stay canvas items.
Colours follow the game's options menu (docs/launcher.md, "Look"). Sizes are in logical pixels times the display
@@ -29,7 +29,7 @@ PALETTE = {
'muted': '#d4c6a6', 'dim': '#7d786a', 'off': '#5e5b51', 'on_text': '#fdf4de', 'salmon': '#e88f6c',
'ok': '#a7d68c', 'gold': '#e6b65a', 'band_text': '#f3ecdc', 'status': '#b9a988', 'log_text': '#cfc4ab',
'line': '#54442f', 'dot': '#5d4b36', 'filigree': '#7a6443', 'glow': '#e9ebee',
'tri_top': '#d49f36', 'tri_bottom': '#fcbf44',
'button_hover': '#8a6c3f', 'close_hover': '#b0402c',
}
@@ -57,13 +57,30 @@ def photo(master, img):
return tk.PhotoImage(master=master, data=base64.b64encode(png_bytes(img)).decode('ascii'), format='png')
def dib_icon(img):
"""One .ico entry as a 32-bit bitmap with its AND mask (what every Windows API and Tk read)."""
a = img if img.dtype == np.uint8 else (np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)
n = a.shape[0]
bgra = a[::-1, :, [2, 1, 0, 3]].tobytes() # bottom-up rows
stride = ((n + 31) // 32) * 4
mask = bytearray()
for row in a[::-1]:
bits = bytearray(stride)
for x in range(n):
if row[x, 3] < 128:
bits[x // 8] |= 0x80 >> (x % 8)
mask += bits
head = struct.pack('<IiiHHIIiiII', 40, n, 2 * n, 1, 32, 0, len(bgra) + len(mask), 0, 0, 0, 0)
return head + bgra + bytes(mask)
def ico_bytes(images):
"""A Windows .ico holding PNG-compressed images (one HxWx4 array per size, square)."""
pngs = [png_bytes(im) for im in images]
head = struct.pack('<HHH', 0, 1, len(pngs))
offset = 6 + 16 * len(pngs)
"""A Windows .ico of square HxWx4 images: bitmaps up to 64 pixels, PNG above (as Windows' own icons do)."""
datas = [png_bytes(im) if im.shape[0] > 64 else dib_icon(im) for im in images]
head = struct.pack('<HHH', 0, 1, len(datas))
offset = 6 + 16 * len(datas)
dirs, body = b'', b''
for im, data in zip(images, pngs):
for im, data in zip(images, datas):
n = im.shape[0]
dirs += struct.pack('<BBBBHHII', n % 256, n % 256, 0, 0, 1, 32, len(data), offset + len(body))
body += data
@@ -450,37 +467,94 @@ def filigree(w, s):
return img, h
def triforce(w):
"""The Triforce, w pixels wide: three triangles, each shading from top to bottom, on a transparent ground."""
h = int(round(w * 217 / 250))
k = w / 250.0
tris = [((125, 1), (186.2, 107), (63.8, 107)), ((62.2, 109), (123.4, 215), (1, 215)),
((187.8, 109), (249, 215), (126.6, 215))]
img = new(h, w)
top, bottom = rgb(PALETTE['tri_top']), rgb(PALETTE['tri_bottom'])
for tri in tris:
pts = [(x * k, y * k) for x, y in tri]
mask = polygon_mask(h, w, pts)
y0, y1 = min(p[1] for p in pts), max(p[1] for p in pts)
t = np.clip((np.arange(h, dtype=np.float32) + 0.5 - y0) / max(y1 - y0, 1e-6), 0, 1)[:, None, None]
layer = new(h, w)
layer[..., :3] = top + (bottom - top) * t
layer[..., 3] = mask
over(img, layer)
# Navi, the launcher's emblem and icon: 22 x 21 pixels as the artwork has them. W white (the outline and the
# wings' highlights), g the wings' grey, K the black outline of the body, B and L its two blues, . transparent.
NAVI = (
'WWWW..............WWWW',
'WggWW............WWggW',
'WgggWW..........WWgggW',
'WgWggWW........WWggWgW',
'WggWggW........WggWggW',
'WgWgWgWW......WWgWgWgW',
'WggggWgWKKKKKKWgWggggW',
'WWggWggKBBBBBBKggWggWW',
'.WggggKKBBLLBBKKggggW.',
'.WWggKKBBLLLLBBKKggWW.',
'..WWgKBBLLWWLLBBKgWW..',
'...WWKBBLWWWWLBBKWW...',
'.....KBBLLWWLLBBK.....',
'.....KBBBLLLLBBBK.....',
'.....WKKBBBBBBKKW.....',
'....WWgKKBBBBKKgWW....',
'...WWgggKKKKKKgggWW...',
'...WggWgW....WgWggW...',
'...WgWggW....WggWgW...',
'...WWggWW....WWggWW...',
'....WWWW......WWWW....',
)
NAVI_COLORS = {'W': (255, 255, 255), 'g': (207, 216, 220), 'K': (0, 0, 0), 'B': (2, 136, 209), 'L': (79, 195, 247)}
def navi_pixels():
"""The artwork as a 21 x 22 RGBA uint8 array."""
a = np.zeros((len(NAVI), len(NAVI[0]), 4), dtype=np.uint8)
for y, row in enumerate(NAVI):
for x, ch in enumerate(row):
if ch in NAVI_COLORS:
a[y, x, :3] = NAVI_COLORS[ch]
a[y, x, 3] = 255
return a
def navi(k):
"""Navi with every artwork pixel k x k screen pixels (crisp edges), as a float RGBA array."""
a = np.repeat(np.repeat(navi_pixels(), k, axis=0), k, axis=1)
return a.astype(np.float32) / 255.0
def navi_icon(n):
"""Navi on a transparent n x n square: whole-pixel scaling where the size allows it, an average of a large
rendering below 22 pixels."""
sq = np.zeros((n, n, 4), dtype=np.float32)
rows, cols = len(NAVI), len(NAVI[0])
if n >= cols:
img = navi(n // cols)
else: # premultiplied box average of an 8x rendering, so the edges blend instead of dropping pixels
big = navi(8)
H, W = big.shape[:2]
h, w = max(1, round(rows * n / cols)), n
ys = (np.arange(h + 1) * H / h).astype(int)
xs = (np.arange(w + 1) * W / w).astype(int)
pm = big.copy()
pm[..., :3] *= pm[..., 3:4]
img = np.zeros((h, w, 4), dtype=np.float32)
for y in range(h):
for x in range(w):
img[y, x] = pm[ys[y]:ys[y + 1], xs[x]:xs[x + 1]].mean(axis=(0, 1))
img[..., :3] = np.where(img[..., 3:4] > 0, img[..., :3] / np.maximum(img[..., 3:4], 1e-6), 0)
h, w = img.shape[:2]
over(sq, img, (n - w) // 2, (n - h) // 2)
return sq
def navi_ico():
"""The launcher's icon (NX2navi.exe, the setup, the window, the taskbar) at the sizes Windows asks for."""
return ico_bytes([navi_icon(n) for n in (16, 20, 24, 32, 40, 48, 64, 96, 128, 256)])
def title_glyph(kind, size, s):
"""The minimise bar or the close cross of the band's buttons, in the band's light text colour."""
img = new(size, size)
t = max(1.2, 1.4 * s)
m = size * 0.12
if kind == 'min':
lines = [[(m, size / 2), (size - m, size / 2)]]
else:
lines = [[(m, m), (size - m, size - m)], [(size - m, m), (m, size - m)]]
paint(img, stroke_mask(size, size, lines, t), PALETTE['band_text'])
return img
def triforce_ico():
"""The launcher's icon at the sizes Windows asks for."""
imgs = []
for n in (16, 24, 32, 48, 64, 128, 256):
t = triforce(n)
sq = new(n, n)
over(sq, t, 0, (n - t.shape[0]) // 2)
imgs.append(sq)
return ico_bytes(imgs)
def check_mark(size, s, color=None):
img = new(size, size)
k = size / 24.0

View File

@@ -139,9 +139,15 @@ def states(app):
def uninstall():
app.show('uninstall', 0)
def import_saves():
app.release, app.message = None, ''
app.save_message = ('Save imported: 3 files from 0100F2C0115B6000. Your old save is in '
'saves\\backup 2026-11-08 17.30.12.')
app.show('home', next(i for i, r in enumerate(app.rows_home()) if r.label == 'Import Saves'))
return [('1-first-run', first_run), ('2-installing', installing), ('3-home', home),
('4-update-ready', update_ready), ('5-updating', updating), ('6-settings', settings),
('7-build-failed', failed), ('8-uninstall', uninstall)]
('7-build-failed', failed), ('8-uninstall', uninstall), ('9-import-saves', import_saves)]
def run(app, shots):

View File

@@ -35,6 +35,96 @@ def app_id():
pass
GWL_STYLE, GWL_EXSTYLE = -16, -20
WS_MINIMIZEBOX, WS_SYSMENU = 0x00020000, 0x00080000
WS_EX_APPWINDOW, WS_EX_TOOLWINDOW = 0x00040000, 0x00000080
def _hwnd(root):
"""The Win32 window of a Tk toplevel (the wrapper around Tk's child window)."""
user32 = ctypes.windll.user32
user32.GetParent.restype = ctypes.c_void_p
user32.GetParent.argtypes = [ctypes.c_void_p]
return user32.GetParent(root.winfo_id()) or root.winfo_id()
def _post(hwnd, msg, wparam, lparam):
"""Queue a message for the window instead of sending it. A sent message runs the window's handler inside this
ctypes call, which has released Python's lock; when that handler dispatches Tk events (the move loop of a title
bar drag does), Tk calls back into Python without the lock and Python aborts. A posted message is handled by Tk's
own event loop, where calling back into Python is allowed."""
user32 = ctypes.windll.user32
user32.PostMessageW.restype = ctypes.c_int
user32.PostMessageW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t]
return user32.PostMessageW(hwnd, msg, wparam, lparam)
def frameless(root):
"""Windows: drop the system title bar (the window draws its own), but keep a taskbar button, Alt+Tab, minimise
from the taskbar and Alt+F4. False elsewhere, where the window keeps its frame."""
if os.name != 'nt':
return False
try:
root.overrideredirect(True)
root.update_idletasks()
user32 = ctypes.windll.user32
get, put = user32.GetWindowLongPtrW, user32.SetWindowLongPtrW
get.restype, get.argtypes = ctypes.c_ssize_t, [ctypes.c_void_p, ctypes.c_int]
put.restype, put.argtypes = ctypes.c_ssize_t, [ctypes.c_void_p, ctypes.c_int, ctypes.c_ssize_t]
hwnd = _hwnd(root)
put(hwnd, GWL_EXSTYLE, (get(hwnd, GWL_EXSTYLE) & ~WS_EX_TOOLWINDOW) | WS_EX_APPWINDOW)
put(hwnd, GWL_STYLE, get(hwnd, GWL_STYLE) | WS_MINIMIZEBOX | WS_SYSMENU)
root.withdraw() # the taskbar takes a changed window style only when the window is shown again
root.after(10, root.deiconify)
return True
except (AttributeError, OSError, Exception):
return False
def minimize(root):
"""Tk refuses to iconify a window without a frame, so ask Windows; asynchronously, for the reason in _post."""
if os.name == 'nt':
ctypes.windll.user32.ShowWindowAsync(ctypes.c_void_p(_hwnd(root)), 6) # SW_MINIMIZE
else:
root.iconify()
def start_drag(root):
"""Windows: let the system move the window from the mouse's current press (as on a title bar, with snapping).
False elsewhere: the caller moves the window itself."""
if os.name != 'nt':
return False
try:
ctypes.windll.user32.ReleaseCapture()
return bool(_post(_hwnd(root), 0x00A1, 2, 0)) # WM_NCLBUTTONDOWN, HTCAPTION
except (AttributeError, OSError):
return False
_ICONS = []
def set_window_icon(root, ico):
"""Windows: the window's and the taskbar button's icon, straight from an .ico (the large and the small size)."""
if os.name != 'nt':
return False
try:
user32 = ctypes.windll.user32
user32.LoadImageW.restype = ctypes.c_void_p
user32.LoadImageW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int,
ctypes.c_uint]
hwnd = _hwnd(root)
for which, (mx, my) in ((1, (11, 12)), (0, (49, 50))): # ICON_BIG: SM_CXICON; ICON_SMALL: SM_CXSMICON
h = user32.LoadImageW(None, str(ico), 1, user32.GetSystemMetrics(mx), user32.GetSystemMetrics(my),
0x10) # IMAGE_ICON, LR_LOADFROMFILE
if h:
_ICONS.append(h)
_post(hwnd, 0x0080, which, h) # WM_SETICON
return True
except (AttributeError, OSError):
return False
def register_font(path):
"""Make a font file usable by this process only (Tk then finds it by family name). True on success."""
path = str(path)