Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

The language list comes from the language files (#388)

v0lumehib1f7680be49b
diff --git a/AGENTS.md b/AGENTS.md
index c7631098..c43365f4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,5 +13,5 @@ This is the fork's guide. The engine has its own, upstream's: [engine/AGENTS.md]
- **Merging with admin rights.** An admin merge never goes over a red check. That holds even when @LNPANDY overrides an objection. If a re-review is slow, the other maintainer pings the reviewer and does not merge with admin rights.
- **Mac launcher layers.** `frontend/` is four SwiftPM targets (`NXCore`, `NXModel`, `NXLauncher`, `NX2Apple`) and the compiler enforces which may import which. Read [frontend/ARCHITECTURE.md](frontend/ARCHITECTURE.md) before you add a file to `frontend/Sources`. It says where a new feature goes. `BuildModel` is gone: the stores are in `NXModel` and `LauncherStores` only wires them. No Swift file there is above 800 lines (`SourceSizeTests`), and the larger ones may only shrink.
- **Checks.** `cd frontend && swift build && swift test` for the Mac launcher (its tests read `engine/`, so sync first), `python3 -m unittest discover -s frontend-qt/tests` for the Qt front end, `python3 -m unittest discover tools/tests` for the tools. The engine's own tests run in `engine/` as `tests.yml` does. The pre-commit hook runs `python3 tools/engine.py check` when `patches/` or `.upstream-ref` is staged. The pre-push hook runs the checks above for the files the push changes, `tools/githooks.py` has the list. Fix the failure, do not bypass the hook.
-- **Language and text.** Everything is in English except the Chinese pages (`*.zh-CN.md`) and the launcher's strings. No semicolons in UI strings, READMEs and docs. The launcher's strings are not in Swift or Python code. They are one JSON file per language in `frontend/l10n/`, read by the Mac launcher and the Windows launcher. A new string is a line in `en.json` and `zh.json` (English and Chinese have every key, the other languages may miss one and then show English). The files go into the apps by the build workflows, see `frontend/README.md`, section "Language".
+- **Language and text.** Everything is in English except the Chinese pages (`*.zh-CN.md`) and the launcher's strings. No semicolons in UI strings, READMEs and docs. The launcher's strings are not in Swift or Python code. They are one JSON file per language in `frontend/l10n/`, read by the Mac launcher and the Windows launcher. A new string is a line in `en.json` and `zh.json` (English and Chinese have every key, the other languages may miss one and then show English). The language list is in the files too (the `_language` entry: name, locale prefixes, order). `Lang` is not an enum, so a new language is one new file under `frontend/l10n/` for the Mac and Windows launchers (the iOS shell's texts come in a later step of #388). The files go into the apps by the build workflows, see `frontend/README.md`, section "Language".
- **Release notes.** They follow `.github/release_notes_template.md`, English first, then Chinese, no emojis.
diff --git a/frontend-qt/README.md b/frontend-qt/README.md
index 984fdfca..fcdd5f47 100644
--- a/frontend-qt/README.md
+++ b/frontend-qt/README.md
@@ -17,8 +17,10 @@ written once and runs everywhere Python and Qt do.
| Build logic | runs the Python scripts | runs the same scripts |
The strings are **read** from `../frontend/l10n/<code>.json`, one file per language, so the two front
-ends cannot drift apart: a new string is a line in `en.json` and in `zh.json`. A frozen build carries the
-folder as `l10n` (`build-qt.yml` adds it with `--add-data`).
+ends cannot drift apart: a new string is a line in `en.json` and in `zh.json`. The language list comes
+from the files too (`Lang.all()`, each language's own name and the locale names that select it,
+Windows ones such as `german` included, are in its `_language` entry), so a new language is one new file
+and no change here. A frozen build carries the folder as `l10n` (`build-qt.yml` adds it with `--add-data`).
## Run it
@@ -52,8 +54,8 @@ the bundle's `fonts` folder (`build-qt.yml`). If the file is missing the system
the RomFS archive and reports where the IPA and archive landed.
- `--work-dir` is passed only when the checkout's script declares it (an upstream checkout has
no such option — issue #5).
-- Languages: Chinese, Swedish, German or French on devices in those languages, English elsewhere, and the
- header button switches.
+- Languages: every language that has a file in `frontend/l10n` (today Chinese, Swedish, German and French)
+ on devices in that language, English elsewhere, and the header button cycles through them.
## What is not there yet
diff --git a/frontend-qt/nspb_qt/i18n.py b/frontend-qt/nspb_qt/i18n.py
index a4fe5f54..cc81b722 100644
--- a/frontend-qt/nspb_qt/i18n.py
+++ b/frontend-qt/nspb_qt/i18n.py
@@ -1,40 +1,97 @@
-"""Language choice: Chinese, Swedish, German and French devices use their matching catalog."""
+"""Language choice: a device whose language has a file in `frontend/l10n` uses that catalog, any other uses English.
+
+The languages, their own names and the locale prefixes that select them are read from the files (`l10n.py`),
+so a new language is a new file and no change here.
+"""
from __future__ import annotations
import locale
import os
import re
import sys
-from enum import Enum
+from dataclasses import dataclass
+
+from . import l10n
+
+FALLBACK = 'en' # a device language that has no file gets English
+
+
+def selects(low: str, locale_name: str) -> bool:
+ """Does the lowercased locale `low` belong to the language that lists `locale_name`?
-# "fr" alone or followed by a separator (fr_FR, fr-CA, fr_BE.UTF-8), and not a longer code such as
-# "fry" (Frisian); Windows spells the locale out ("French_France"), matched by name instead.
-_FRENCH = re.compile(r'fr(?![a-z])')
+ A language tag matches by prefix, "fr" alone or followed by a separator (fr_FR, fr-CA, fr_BE.UTF-8) and
+ not a longer code such as "fry" (Frisian). A locale name (Windows spells it out: "French_France",
+ "Chinese (Simplified)_China") is longer than a code and matches anywhere in the text.
+ """
+ if len(locale_name) > 3 and locale_name in low:
+ return True
+ return re.match(re.escape(locale_name) + r'(?![a-z])', low) is not None
-class Lang(Enum):
- ZH = 'zh'
- EN = 'en'
- SV = 'sv'
- DE = 'de'
- FR = 'fr'
+def match(low: str, languages: list[l10n.Language]) -> str | None:
+ """The code of the first language one of whose locales selects `low`, None when none does."""
+ for language in languages:
+ if any(selects(low, name) for name in language.locales):
+ return language.code
+ return None
+
+
+@dataclass(frozen=True)
+class Lang:
+ """A language of the launcher, identified by its code: the name of its file in `frontend/l10n`."""
+ code: str
+
+ @staticmethod
+ def all() -> list[Lang]:
+ """Every language that has a file, in picker order."""
+ return [Lang(language.code) for language in l10n.LANGUAGES]
+
+ @staticmethod
+ def find(code: str) -> Lang | None:
+ return next((lang for lang in Lang.all() if lang.code == code), None)
+
+ @property
+ def _language(self) -> l10n.Language | None:
+ return next((language for language in l10n.LANGUAGES if language.code == self.code), None)
+
+ @property
+ def name(self) -> str:
+ """The language's own name (Svenska, Deutsch), or its code when no file has it."""
+ language = self._language
+ return language.name if language else self.code
@property
- def other(self) -> 'Lang':
- return {Lang.ZH: Lang.EN, Lang.EN: Lang.SV, Lang.SV: Lang.DE, Lang.DE: Lang.FR, Lang.FR: Lang.ZH}[self]
+ def locales(self) -> tuple[str, ...]:
+ language = self._language
+ return language.locales if language else (self.code,)
+
+ @property
+ def other(self) -> Lang:
+ """The next language in the picker's order, after the last the first (the language button cycles)."""
+ everyone = Lang.all()
+ if self not in everyone:
+ return everyone[0] if everyone else self
+ return everyone[(everyone.index(self) + 1) % len(everyone)]
@property
def toggle_label(self) -> str:
- return {Lang.ZH: 'EN', Lang.EN: 'Svenska', Lang.SV: 'Deutsch', Lang.DE: 'Français', Lang.FR: '中文'}[self]
+ """What the language button says: the next language's own name, "EN" for English."""
+ nxt = self.other
+ return 'EN' if nxt.code == FALLBACK else nxt.name
+
+ @staticmethod
+ def detect(tag: str, languages: list[l10n.Language] | None = None) -> Lang:
+ """The language a lowercased locale or language tag selects, else English."""
+ code = match(tag, l10n.LANGUAGES if languages is None else languages)
+ return Lang(code or FALLBACK)
@staticmethod
- def initial() -> 'Lang':
- """Saved choice, else the device language: Chinese, Swedish, German and French (by language
- code or Windows locale name) use their own catalog, everything else is English (the same
- rule the SwiftUI app uses)."""
- saved = os.environ.get('NSPB_LANG', '')
- if saved in ('zh', 'en', 'sv', 'de', 'fr'):
- return Lang(saved)
+ def initial() -> Lang:
+ """Saved choice, else the device language: one that has a file (by language code or Windows locale
+ name) uses its own catalog, everything else is English (the same rule the SwiftUI app uses)."""
+ saved = Lang.find(os.environ.get('NSPB_LANG', ''))
+ if saved:
+ return saved
if sys.platform.startswith('win'):
# Ask Windows first, and always — not only when locale.getlocale() came back empty.
# The **user's** UI language, not the system's: a Chinese Windows install on
@@ -56,16 +113,8 @@ class Lang(Enum):
# the prefix test here and the early return handed that user an English interface.
if ctypes.windll.kernel32.GetLocaleInfoW(lang, 0x00000059, buf, 85):
low = buf.value.strip().lower()
- if low.startswith('zh'):
- return Lang.ZH
- if low.startswith('sv'):
- return Lang.SV
- if re.match(r'de($|[^a-z])', low):
- return Lang.DE
- if _FRENCH.match(low):
- return Lang.FR
- if low: # a real code we do not translate: this device is neither
- return Lang.EN
+ if low: # a real code: its language, or English when we have no file for it
+ return Lang.detect(low)
except Exception:
pass # fall through to the environment
try:
@@ -74,12 +123,5 @@ class Lang(Enum):
tag = ''
tag = tag or os.environ.get('LANG', '') or os.environ.get('LC_ALL', '')
# On Windows the locale name is spelled out ("Chinese (Simplified)_China"), so the prefix
- # test alone misses every Chinese install there; the name contains "Chinese".
- low = tag.lower()
- if low.startswith('zh') or 'chinese' in low:
- return Lang.ZH
- if low.startswith('sv') or 'swedish' in low:
- return Lang.SV
- if re.match(r'de($|[^a-z])', low) or 'german' in low or 'deutsch' in low:
- return Lang.DE
- return Lang.FR if _FRENCH.match(low) or 'french' in low else Lang.EN
+ # test alone misses every Chinese install there; the name is in the file's `locales`.
+ return Lang.detect(tag.lower())
diff --git a/frontend-qt/nspb_qt/l10n.py b/frontend-qt/nspb_qt/l10n.py
index 6e45974f..ddbc164b 100644
--- a/frontend-qt/nspb_qt/l10n.py
+++ b/frontend-qt/nspb_qt/l10n.py
@@ -1,9 +1,12 @@
-"""Localised strings, read from the language files `frontend/l10n/<code>.json` (LNPANDY/NX2Apple#388).
+"""Localised strings and the language list, read from the language files `frontend/l10n/<code>.json` (LNPANDY/NX2Apple#388).
The Mac launcher reads the same files, so both front ends say the same thing. Each file is one flat JSON
-object: the keys are the texts' names, the values the texts, and `_language` (the language's own name and
-its locale prefixes) is not a text. English and Chinese have every key. The other languages may miss keys
-and then show the English text.
+object: the keys are the texts' names, the values the texts, and `_language` is not a text. It holds the
+language's own name (`name`), the lowercased prefixes and Windows locale names that select it (`locales`)
+and optionally where the picker puts it (`order`). English and Chinese have every key. The other languages
+may miss keys and then show the English text.
+
+The languages are the files: a new `<code>.json` is a new language, with no change in the code.
Where the files are, in this order:
NX_L10N_DIR a folder named in the environment, for a try-out
@@ -19,10 +22,22 @@ from __future__ import annotations
import json
import os
import sys
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .i18n import Lang
-from .i18n import Lang
+REQUIRED = ('en', 'zh') # every key is in these two, and English is what a missing text falls back to
-CODES = ('zh', 'en', 'sv', 'de', 'fr') # the order of a TABLE row
+
+@dataclass(frozen=True)
+class Language:
+ """What a file says about its language. Without `_language` the name is the code and so is the only locale."""
+ code: str
+ name: str
+ locales: tuple[str, ...]
+ order: int | None = None
def _directory() -> str | None:
@@ -46,14 +61,39 @@ def _report(message: str) -> None:
print(f'l10n: {message}', file=sys.stderr)
-def load(directory: str | None, report=_report) -> dict[str, dict[str, str]]:
- """Every language's texts by code. A language whose file is missing or broken is left out."""
+def _language(code: str, body: dict) -> Language:
+ entry = body.get('_language')
+ name, locales, order = code, (code,), None
+ if isinstance(entry, dict):
+ if isinstance(entry.get('name'), str) and entry['name']:
+ name = entry['name']
+ given = tuple(s.lower() for s in entry.get('locales', ()) if isinstance(s, str) and s) \
+ if isinstance(entry.get('locales'), list) else ()
+ if given:
+ locales = given
+ if isinstance(entry.get('order'), int) and not isinstance(entry.get('order'), bool):
+ order = entry['order']
+ return Language(code, name, locales, order)
+
+
+def read(directory: str | None, report=_report) -> tuple[list[Language], dict[str, dict[str, str]]]:
+ """Every `*.json` in the folder: the languages in picker order and each one's texts by code.
+
+ A file that is broken is left out. Picker order is `order` where a file has one, then the rest by code.
+ """
if directory is None:
report('no language files found (l10n next to the app or frontend/l10n), the app shows its keys')
- return {}
- out: dict[str, dict[str, str]] = {}
- for code in CODES:
- path = os.path.join(directory, f'{code}.json')
+ return [], {}
+ languages: list[Language] = []
+ catalogs: dict[str, dict[str, str]] = {}
+ try:
+ names = sorted(n for n in os.listdir(directory) if n.endswith('.json') and not n.startswith('.'))
+ except OSError as e:
+ report(f'{directory} cannot be read: {e}')
+ names = []
+ for name in names:
+ code = name[:-5]
+ path = os.path.join(directory, name)
try:
with open(path, encoding='utf-8') as f:
body = json.load(f)
@@ -71,18 +111,30 @@ def load(directory: str | None, report=_report) -> dict[str, dict[str, str]]:
texts[key] = value
else:
report(f'{code}.json: {key} is not a text')
- out[code] = texts
- return out
+ catalogs[code] = texts
+ languages.append(_language(code, body))
+ for code in REQUIRED:
+ if f'{code}.json' not in names:
+ report(f'{code}.json is missing, English and Chinese are needed')
+ languages.sort(key=lambda lang: (lang.order is None, lang.order or 0, lang.code))
+ return languages, catalogs
+
+
+def load(directory: str | None, report=_report) -> dict[str, dict[str, str]]:
+ """Every language's texts by code. A language whose file is missing or broken is left out."""
+ return read(directory, report)[1]
-def _table(catalogs: dict[str, dict[str, str]]) -> dict[str, tuple[str, str, str, str, str]]:
- """key: (Chinese, English, Swedish, German, French). A text a language lacks is the English one."""
+def _table(catalogs: dict[str, dict[str, str]]) -> dict[str, dict[str, str]]:
+ """key: {code: text}, for the languages that have a file. A text a language lacks is the English one."""
english = catalogs.get('en', {})
- return {key: tuple(catalogs.get(code, {}).get(key, text) for code in CODES) # type: ignore[misc]
- for key, text in english.items()}
+ return {key: {code: texts.get(key, text) for code, texts in catalogs.items()} for key, text in english.items()}
-TABLE: dict[str, tuple[str, str, str, str, str]] = _table(load(_directory()))
+LANGUAGES: list[Language]
+CATALOGS: dict[str, dict[str, str]]
+LANGUAGES, CATALOGS = read(_directory())
+TABLE: dict[str, dict[str, str]] = _table(CATALOGS)
def t(key: str, lang: Lang, *args: object) -> str:
@@ -92,7 +144,7 @@ def t(key: str, lang: Lang, *args: object) -> str:
Python's %s, so the placeholder is translated here rather than in every call site.
"""
row = TABLE.get(key)
- s = row[CODES.index(lang.value)] if row else key
+ s = row.get(lang.code, row.get('en', key)) if row else key
if not args:
return s
py = s.replace("%@", "%s") # %d is the same in both; %@ is Swift-only
diff --git a/frontend-qt/tests/test_build_failure.py b/frontend-qt/tests/test_build_failure.py
index 1403660b..54912c22 100644
--- a/frontend-qt/tests/test_build_failure.py
+++ b/frontend-qt/tests/test_build_failure.py
@@ -49,7 +49,7 @@ class BuildFailure(unittest.TestCase):
from nspb_qt.model import Model
from nspb_qt.ui import MainWindow
m = Model()
- m.lang = Lang.EN # these assertions read English whatever the device language is
+ m.lang = Lang('en') # these assertions read English whatever the device language is
w = MainWindow(m)
# Delete while the app exists: PySide destroys leftovers after it at exit and segfaults.
self.addCleanup(self._delete, m, w)
diff --git a/frontend-qt/tests/test_build_failure_hints.py b/frontend-qt/tests/test_build_failure_hints.py
index 08025812..f1232974 100644
--- a/frontend-qt/tests/test_build_failure_hints.py
+++ b/frontend-qt/tests/test_build_failure_hints.py
@@ -121,20 +121,20 @@ class Rows(unittest.TestCase):
bf.NO_TITLE_ID: ['Rename the file', '0100XXXXXXXXXXXX', 'exact package', 'iCloud', 'Show folder'],
bf.DISK_FULL: ['Free up space', '_build']}
for kind, ws in words.items():
- en = TABLE[f'fail.{kind}.next'][1]
+ en = TABLE[f'fail.{kind}.next']['en']
for w in ws:
self.assertIn(w, en, kind)
for key in ('fail.showFolder', 'fail.keys.button', 'fail.diskFull.whatNeeds'):
self.assertIn(key, TABLE)
- self.assertTrue(TABLE[key][2] and TABLE[key][2] != TABLE[key][1], key) # Swedish present
- self.assertTrue(TABLE[key][3] and TABLE[key][3] != TABLE[key][1], key) # German present
+ self.assertTrue(TABLE[key]['sv'] and TABLE[key]['sv'] != TABLE[key]['en'], key) # Swedish present
+ self.assertTrue(TABLE[key]['de'] and TABLE[key]['de'] != TABLE[key]['en'], key) # German present
def test_a_missing_zbic_package_is_its_own_row(self):
log = '[3/9] extract\n' + fixture('zbic.missing')['text'] + '\n'
self.assertEqual(bf.classify(log).kind, bf.ZBIC)
self.assertEqual(bf.classify('[RED] the zbic package decoded it').kind, bf.UNKNOWN)
- self.assertIn('pip install zbic', TABLE['fail.zbic.next'][1])
- self.assertIn('zbic', TABLE['fail.zbic.button'][1])
+ self.assertIn('pip install zbic', TABLE['fail.zbic.next']['en'])
+ self.assertIn('zbic', TABLE['fail.zbic.button']['en'])
def test_the_python_probe_and_the_venv_install_name_zbic(self):
pkg = ROOT / 'frontend-qt/nspb_qt'
@@ -148,7 +148,7 @@ class Rows(unittest.TestCase):
import tempfile
from nspb_qt.model import Model
m = Model()
- m.lang = Lang.EN # these assertions read English whatever the device language is
+ m.lang = Lang('en') # these assertions read English whatever the device language is
with tempfile.TemporaryDirectory() as d:
m.base_path = str(Path(d, 'game.nsp'))
self.assertEqual(m.failure_folder(bf.Failure(bf.NO_TITLE_ID, detail='/x')), d)
@@ -210,7 +210,7 @@ class Strings(unittest.TestCase):
with self.subTest(key=key):
self.assertIn(key, TABLE)
row = TABLE[key]
- zh, en = row[0], row[1] # the table carries more columns (Swedish, German)
+ zh, en = row['zh'], row['en'] # the table carries more columns (Swedish, German)
self.assertTrue(zh and en)
for text in (zh, en):
self.assertNotIn(';', text)
@@ -219,13 +219,13 @@ class Strings(unittest.TestCase):
def test_the_risk_text_states_the_risk_and_that_it_is_one_build(self):
for kind in bf.OVERRIDE_FLAGS:
- en = TABLE[f'fail.{kind}.risk'][1]
+ en = TABLE[f'fail.{kind}.risk']['en']
self.assertIn('untested', en)
self.assertIn('one build', en)
def test_the_hints_say_what_the_task_asks(self):
- self.assertIn('Xcode 27.2 (macOS 26.6 or later)', TABLE['fail.otherMetal.next'][1])
- self.assertIn("32-bit and can't run on Apple silicon", TABLE['fail.a32Program.what'][1])
+ self.assertIn('Xcode 27.2 (macOS 26.6 or later)', TABLE['fail.otherMetal.next']['en'])
+ self.assertIn("32-bit and can't run on Apple silicon", TABLE['fail.a32Program.what']['en'])
try:
@@ -245,7 +245,7 @@ class Window(unittest.TestCase):
from nspb_qt.model import Model
from nspb_qt.ui import MainWindow
m = Model()
- m.lang = Lang.EN # these assertions read English whatever the device language is
+ m.lang = Lang('en') # these assertions read English whatever the device language is
w = MainWindow(m)
# A window left alive is destroyed by PySide after the QApplication at interpreter exit,
# which segfaults. Delete it (and the model) while the app is still there.
diff --git a/frontend-qt/tests/test_i18n_detect.py b/frontend-qt/tests/test_i18n_detect.py
index 2fcf57be..776b4924 100644
--- a/frontend-qt/tests/test_i18n_detect.py
+++ b/frontend-qt/tests/test_i18n_detect.py
@@ -35,38 +35,38 @@ def detect(locale_name: str, platform: str = 'darwin', env: dict | None = None)
class Detect(unittest.TestCase):
def test_language_button_cycles_through_each_available_language(self):
- self.assertEqual(Lang.ZH.other, Lang.EN)
- self.assertEqual(Lang.EN.other, Lang.SV)
- self.assertEqual(Lang.SV.other, Lang.DE)
- self.assertEqual(Lang.DE.other, Lang.FR)
- self.assertEqual(Lang.FR.other, Lang.ZH)
- self.assertEqual(Lang.SV.toggle_label, 'Deutsch')
- self.assertEqual(Lang.DE.toggle_label, 'Français')
- self.assertEqual(Lang.FR.toggle_label, '中文')
+ self.assertEqual(Lang('zh').other, Lang('en'))
+ self.assertEqual(Lang('en').other, Lang('sv'))
+ self.assertEqual(Lang('sv').other, Lang('de'))
+ self.assertEqual(Lang('de').other, Lang('fr'))
+ self.assertEqual(Lang('fr').other, Lang('zh'))
+ self.assertEqual(Lang('sv').toggle_label, 'Deutsch')
+ self.assertEqual(Lang('de').toggle_label, 'Français')
+ self.assertEqual(Lang('fr').toggle_label, '中文')
def test_german_is_recognised_by_tag_and_windows_name(self):
for tag in ('de_DE', 'de-AT', 'de_CH.UTF-8', 'de'):
- self.assertEqual(detect(tag), Lang.DE, tag)
- self.assertEqual(detect('German_Germany', platform='win32'), Lang.DE)
- self.assertEqual(detect('en_US', env={'NSPB_LANG': 'de'}), Lang.DE)
- self.assertEqual(detect('Deutsch (Deutschland)', platform='win32'), Lang.DE)
+ self.assertEqual(detect(tag), Lang('de'), tag)
+ self.assertEqual(detect('German_Germany', platform='win32'), Lang('de'))
+ self.assertEqual(detect('en_US', env={'NSPB_LANG': 'de'}), Lang('de'))
+ self.assertEqual(detect('Deutsch (Deutschland)', platform='win32'), Lang('de'))
for tag in ('dv_MV', 'default'): # not German
- self.assertEqual(detect(tag), Lang.EN, tag)
+ self.assertEqual(detect(tag), Lang('en'), tag)
def test_a_saved_choice_wins(self):
- self.assertEqual(detect('English_United States', env={'NSPB_LANG': 'zh'}), Lang.ZH)
- self.assertEqual(detect('Chinese (Simplified)_China', env={'NSPB_LANG': 'en'}), Lang.EN)
+ self.assertEqual(detect('English_United States', env={'NSPB_LANG': 'zh'}), Lang('zh'))
+ self.assertEqual(detect('Chinese (Simplified)_China', env={'NSPB_LANG': 'en'}), Lang('en'))
def test_the_windows_locale_name_is_recognised(self):
for name in ('Chinese (Simplified)_China', 'Chinese (Traditional)_Taiwan', 'Chinese_China'):
- self.assertEqual(detect(name, platform='win32'), Lang.ZH, name)
+ self.assertEqual(detect(name, platform='win32'), Lang('zh'), name)
for name in ('English_United States', 'Japanese_Japan'):
- self.assertEqual(detect(name, platform='win32'), Lang.EN, name)
+ self.assertEqual(detect(name, platform='win32'), Lang('en'), name)
def test_a_bcp47_tag_still_works(self):
for tag in ('zh_CN', 'zh-Hans', 'zh'):
- self.assertEqual(detect(tag), Lang.ZH, tag)
- self.assertEqual(detect('en_US'), Lang.EN)
+ self.assertEqual(detect(tag), Lang('zh'), tag)
+ self.assertEqual(detect('en_US'), Lang('en'))
def test_windows_is_asked_before_the_environment(self):
"""The API decides on Windows even though locale.getlocale() returned a name — that was the bug."""
@@ -81,7 +81,7 @@ class Detect(unittest.TestCase):
mock.patch.dict(sys.modules, {'ctypes': fake}), \
mock.patch('locale.getlocale', return_value=('English_United States', None)), \
mock.patch.object(sys, 'platform', 'win32'):
- self.assertEqual(Lang.initial(), Lang.ZH)
+ self.assertEqual(Lang.initial(), Lang('zh'))
def win_language(self, kind_value: str, langid: int = 0x04) -> tuple[Lang, list[int]]:
"""Lang.initial() on Windows, with GetLocaleInfoW answering `kind_value`; the kinds it was asked for come back too."""
@@ -108,29 +108,29 @@ class Detect(unittest.TestCase):
self.assertEqual(asked, [0x00000059], "the ISO 639 code is what the prefix test can read")
def test_a_windows_display_name_still_selects_the_language(self):
- for name, want in (('zh', Lang.ZH), ('zh-Hans', Lang.ZH), ('sv', Lang.SV), ('de', Lang.DE), ('de-DE', Lang.DE),
- ('fr', Lang.FR), ('fr-CA', Lang.FR), ('fry', Lang.EN), ('en-US', Lang.EN)):
+ for name, want in (('zh', Lang('zh')), ('zh-Hans', Lang('zh')), ('sv', Lang('sv')), ('de', Lang('de')), ('de-DE', Lang('de')),
+ ('fr', Lang('fr')), ('fr-CA', Lang('fr')), ('fry', Lang('en')), ('en-US', Lang('en'))):
lang, _ = self.win_language(name)
self.assertEqual(lang, want, name)
def test_windows_german_is_asked_for_the_iso_code_and_selects_german(self):
lang, asked = self.win_language('de', langid=0x07) # German primary language id
self.assertEqual(asked, [0x00000059])
- self.assertEqual(lang, Lang.DE)
+ self.assertEqual(lang, Lang('de'))
def test_french_is_recognised(self):
for name in ('fr_FR', 'fr-CA', 'fr_BE.UTF-8', 'French_France', 'French (Canada)_Canada'):
- self.assertEqual(detect(name), Lang.FR, name)
- self.assertEqual(detect('French_France', platform='win32'), Lang.FR)
- self.assertEqual(detect('', env={'LANG': 'fr_FR.UTF-8'}), Lang.FR)
- self.assertEqual(detect('English_United States', env={'NSPB_LANG': 'fr'}), Lang.FR)
+ self.assertEqual(detect(name), Lang('fr'), name)
+ self.assertEqual(detect('French_France', platform='win32'), Lang('fr'))
+ self.assertEqual(detect('', env={'LANG': 'fr_FR.UTF-8'}), Lang('fr'))
+ self.assertEqual(detect('English_United States', env={'NSPB_LANG': 'fr'}), Lang('fr'))
def test_an_empty_locale_falls_through_to_the_environment(self):
- self.assertEqual(detect('', env={'LANG': 'zh_CN.UTF-8'}), Lang.ZH)
- self.assertEqual(detect('', env={'LANG': 'en_US.UTF-8'}), Lang.EN)
+ self.assertEqual(detect('', env={'LANG': 'zh_CN.UTF-8'}), Lang('zh'))
+ self.assertEqual(detect('', env={'LANG': 'en_US.UTF-8'}), Lang('en'))
def test_no_signal_at_all_is_english(self):
- self.assertEqual(detect(''), Lang.EN)
+ self.assertEqual(detect(''), Lang('en'))
if __name__ == '__main__':
diff --git a/frontend-qt/tests/test_language_list.py b/frontend-qt/tests/test_language_list.py
new file mode 100644
index 00000000..f02d9521
--- /dev/null
+++ b/frontend-qt/tests/test_language_list.py
@@ -0,0 +1,123 @@
+"""The language list comes from frontend/l10n (LNPANDY/NX2Apple#388, step 2): the language button, the detection and the names.
+
+The five real files are used, and a sixth language is a temporary `xx.json` in a temporary folder that NX_L10N_DIR names.
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / 'frontend-qt'))
+
+from nspb_qt import l10n # noqa: E402
+from nspb_qt.i18n import Lang # noqa: E402
+
+FILES = ROOT / 'frontend' / 'l10n'
+
+
+def detected_before(low: str) -> str:
+ """The detection of the Windows ISO code and of the environment tag before the files, as it was written."""
+ if low.startswith('zh') or 'chinese' in low:
+ return 'zh'
+ if low.startswith('sv') or 'swedish' in low:
+ return 'sv'
+ if re.match(r'de($|[^a-z])', low) or 'german' in low or 'deutsch' in low:
+ return 'de'
+ return 'fr' if re.match(r'fr(?![a-z])', low) or 'french' in low else 'en'
+
+
+# What the old code was given: BCP-47 and POSIX tags, the Windows locale names, the ISO 639 codes GetLocaleInfoW answers.
+OLD_INPUTS = [
+ '', 'en', 'en_us', 'en-gb', 'english_united states', 'c', 'posix', 'default', 'dv_mv', 'fry', 'fry_nl', 'ja_jp', 'japanese_japan', 'pt_br',
+ 'portuguese_brazil', 'es_es', 'spanish_spain', 'it_it', 'ko_kr', 'da_dk', 'nb_no', 'fi_fi', 'x',
+ 'zh', 'zh_cn', 'zh-hans', 'zh-hant', 'zh_tw.utf-8', 'zh_cn.utf-8', 'chinese', 'chinese_china', 'chinese (simplified)_china',
+ 'chinese (traditional)_taiwan', 'chinese (simplified, prc)', 'chinese_hong kong sar',
+ 'sv', 'sv_se', 'sv-fi', 'sv_se.utf-8', 'swedish_sweden', 'swedish (finland)_finland',
+ 'de', 'de_de', 'de-at', 'de_ch.utf-8', 'german_germany', 'german (switzerland)_switzerland', 'deutsch (deutschland)', 'deutsch', 'dev', 'deu',
+ 'fr', 'fr_fr', 'fr-ca', 'fr_be.utf-8', 'french_france', 'french (canada)_canada', 'french_belgium', 'fra',
+]
+
+
+class PickerList(unittest.TestCase):
+ def test_the_button_cycles_the_five_languages_in_the_order_it_always_had(self):
+ self.assertEqual([lang.code for lang in Lang.all()], ['zh', 'en', 'sv', 'de', 'fr'])
+ self.assertEqual([lang.name for lang in Lang.all()], ['中文', 'English', 'Svenska', 'Deutsch', 'Français'])
+ self.assertEqual([Lang(c).other.code for c in ('zh', 'en', 'sv', 'de', 'fr')], ['en', 'sv', 'de', 'fr', 'zh'])
+ self.assertEqual([Lang(c).toggle_label for c in ('zh', 'en', 'sv', 'de', 'fr')], ['EN', 'Svenska', 'Deutsch', 'Français', '中文'])
+
+ def test_find_knows_a_code_only_when_a_file_has_it(self):
+ self.assertEqual(Lang.find('sv'), Lang('sv'))
+ for code in ('', 'xx', 'SV'):
+ self.assertIsNone(Lang.find(code), code)
+
+ def test_a_language_without_a_file_shows_its_code_and_cycles_to_the_first(self):
+ self.assertEqual(Lang('xx').name, 'xx')
+ self.assertEqual(Lang('xx').other, Lang('zh'))
+
+
+class Detection(unittest.TestCase):
+ def test_every_input_the_old_detection_handled_selects_the_same_language(self):
+ for low in OLD_INPUTS:
+ self.assertEqual(Lang.detect(low).code, detected_before(low), low)
+
+ def test_every_locale_a_file_lists_selects_that_file(self):
+ for lang in Lang.all():
+ for name in lang.locales:
+ self.assertEqual(Lang.detect(name + '_xx' if len(name) <= 3 else name + ' (xx)_xx'), lang, name)
+
+ def test_the_names_the_old_code_matched_are_in_the_files(self):
+ listed = {lang.code: set(lang.locales) for lang in Lang.all()}
+ self.assertTrue({'zh', 'chinese'} <= listed['zh'])
+ self.assertTrue({'sv', 'swedish'} <= listed['sv'])
+ self.assertTrue({'de', 'german', 'deutsch'} <= listed['de'])
+ self.assertTrue({'fr', 'french'} <= listed['fr'])
+
+
+class SixthLanguage(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix='nx-l10n-')
+ self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
+ for f in FILES.glob('*.json'):
+ shutil.copy(f, self.tmp)
+ (Path(self.tmp) / 'xx.json').write_text(
+ json.dumps({'_language': {'name': 'Xenia', 'locales': ['xx', 'xenian']}, 'onboarding.start': 'Go'}), encoding='utf-8')
+
+ def test_it_is_in_the_list_after_the_five_and_a_prefix_selects_it(self):
+ languages, catalogs = l10n.read(self.tmp)
+ self.assertEqual([lang.code for lang in languages], ['zh', 'en', 'sv', 'de', 'fr', 'xx'])
+ self.assertEqual(languages[-1].name, 'Xenia')
+ self.assertEqual(Lang.detect('xx_yy', languages), Lang('xx'))
+ self.assertEqual(Lang.detect('xenian_land', languages), Lang('xx'))
+ self.assertEqual(Lang.detect('de_de', languages), Lang('de'))
+ self.assertEqual(Lang.detect('ja_jp', languages), Lang('en'))
+ self.assertEqual(catalogs['xx'], {'onboarding.start': 'Go'})
+ table = l10n._table(catalogs)
+ self.assertEqual(table['onboarding.start']['xx'], 'Go')
+ self.assertEqual(table['onboarding.later']['xx'], table['onboarding.later']['en'], 'a text it lacks is English')
+
+ def run_in_new_process(self, code: str, **env: str) -> str:
+ """The app's own import, in a process whose NX_L10N_DIR names the temporary folder: no code is changed for the new language."""
+ clean = {k: v for k, v in os.environ.items() if k not in ('NSPB_LANG', 'LANG', 'LC_ALL', 'NX_L10N_DIR')}
+ out = subprocess.run([sys.executable, '-c', 'import sys; sys.path.insert(0, %r)\n%s' % (str(ROOT / 'frontend-qt'), code)],
+ capture_output=True, text=True, env={**clean, 'NX_L10N_DIR': self.tmp, **env}, check=True)
+ return out.stdout.strip()
+
+ def test_the_app_picks_it_up_from_nx_l10n_dir(self):
+ listing = self.run_in_new_process('from nspb_qt.i18n import Lang\nprint([(l.code, l.name) for l in Lang.all()][-1], Lang("fr").other.name)')
+ self.assertEqual(listing, "('xx', 'Xenia') Xenia")
+ self.assertEqual(self.run_in_new_process('from nspb_qt.i18n import Lang\nprint(Lang.initial().code)', NSPB_LANG='xx'), 'xx')
+ device = 'import locale\nlocale.getlocale = lambda *a: ("xx_YY", None) # the device language\nfrom nspb_qt.i18n import Lang\nprint(Lang.initial().code)'
+ self.assertEqual(self.run_in_new_process(device), 'xx')
+ self.assertEqual(self.run_in_new_process('from nspb_qt.l10n import t\nfrom nspb_qt.i18n import Lang\nprint(t("onboarding.start", Lang("xx")))'), 'Go')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/frontend-qt/tests/test_localization_de.py b/frontend-qt/tests/test_localization_de.py
index 4f739751..4644b1e4 100644
--- a/frontend-qt/tests/test_localization_de.py
+++ b/frontend-qt/tests/test_localization_de.py
@@ -18,30 +18,30 @@ PLACEHOLDER = re.compile(r'%(?:\d+\$)?(?:\.\d+)?(?:ll|l)?[@dsf%]')
class German(unittest.TestCase):
def test_every_key_has_german_text_that_is_not_the_english_fallback(self):
# dep.python.hint is a list of package names, the same in every language
- prose = [k for k, row in TABLE.items() if row[3] == row[1] and len(row[1]) > 30 and k != 'dep.python.hint']
+ prose = [k for k, row in TABLE.items() if row['de'] == row['en'] and len(row['en']) > 30 and k != 'dep.python.hint']
self.assertEqual(prose, [], 'English text left in the German column')
- self.assertTrue(all(row[3] for row in TABLE.values()))
+ self.assertTrue(all(row['de'] for row in TABLE.values()))
def test_placeholders_match_english_in_count_and_order(self):
for key, row in TABLE.items():
- self.assertEqual(PLACEHOLDER.findall(row[3]), PLACEHOLDER.findall(row[1]), key)
+ self.assertEqual(PLACEHOLDER.findall(row['de']), PLACEHOLDER.findall(row['en']), key)
def test_german_has_no_semicolons_and_no_added_product_name(self):
for key, row in TABLE.items():
- self.assertNotIn(';', row[3], key)
- self.assertNotIn(';', row[3], key)
- if 'NX2Apple' not in row[1]:
- self.assertNotIn('NX2Apple', row[3], key)
+ self.assertNotIn(';', row['de'], key)
+ self.assertNotIn(';', row['de'], key)
+ if 'NX2Apple' not in row['en']:
+ self.assertNotIn('NX2Apple', row['de'], key)
def test_t_picks_the_german_column(self):
- self.assertEqual(t('settings.language.de', Lang.DE), 'Deutsch')
- self.assertEqual(t('dep.recheck', Lang.DE), 'Erneut prüfen')
- self.assertEqual(t('onboarding.stepCount', Lang.DE, 2, 5), 'Schritt 2 von 5')
- self.assertEqual(t('dep.recheck', Lang.EN), 'Check again')
+ self.assertEqual(t('settings.language.de', Lang('de')), 'Deutsch')
+ self.assertEqual(t('dep.recheck', Lang('de')), 'Erneut prüfen')
+ self.assertEqual(t('onboarding.stepCount', Lang('de'), 2, 5), 'Schritt 2 von 5')
+ self.assertEqual(t('dep.recheck', Lang('en')), 'Check again')
def test_newlines_and_backslashes_of_the_files_are_text(self):
- self.assertIn('\n', t('fail.noTitleID.next', Lang.DE))
- self.assertNotIn('\\\\', t('dep.spirv.hint.win', Lang.DE))
+ self.assertIn('\n', t('fail.noTitleID.next', Lang('de')))
+ self.assertNotIn('\\\\', t('dep.spirv.hint.win', Lang('de')))
if __name__ == '__main__':
diff --git a/frontend-qt/tests/test_localization_fr.py b/frontend-qt/tests/test_localization_fr.py
index 5c056cfb..2e01519b 100644
--- a/frontend-qt/tests/test_localization_fr.py
+++ b/frontend-qt/tests/test_localization_fr.py
@@ -18,14 +18,15 @@ PLACEHOLDER = re.compile(r'%(?:\d+\$)?(?:\.\d+)?l{0,2}[@dfs%]')
class FrenchTable(unittest.TestCase):
def test_every_row_has_french_and_its_placeholders(self):
- for key, (_, en, _, _, fr) in TABLE.items():
+ for key, row in TABLE.items():
+ en, fr = row['en'], row['fr']
self.assertTrue(fr, key)
self.assertEqual(PLACEHOLDER.findall(fr), PLACEHOLDER.findall(en), key)
def test_t_reads_the_french_column(self):
- self.assertEqual(t('onboarding.start', Lang.FR), 'Commencer')
- self.assertEqual(t('settings.language.fr', Lang.FR), 'Français')
- self.assertEqual(t('dep.install.begin', Lang.FR, 'zstd'), 'Installation de zstd…')
+ self.assertEqual(t('onboarding.start', Lang('fr')), 'Commencer')
+ self.assertEqual(t('settings.language.fr', Lang('fr')), 'Français')
+ self.assertEqual(t('dep.install.begin', Lang('fr'), 'zstd'), 'Installation de zstd…')
if __name__ == '__main__':
diff --git a/frontend-qt/tests/test_localization_table.py b/frontend-qt/tests/test_localization_table.py
index a9dd6994..4386928d 100644
--- a/frontend-qt/tests/test_localization_table.py
+++ b/frontend-qt/tests/test_localization_table.py
@@ -18,20 +18,20 @@ from nspb_qt.l10n import TABLE, load, t # noqa: E402
class Files(unittest.TestCase):
def test_the_checkout_has_all_five_languages_and_english_and_chinese_have_every_key(self):
loaded = load(str(ROOT / 'frontend' / 'l10n'))
- self.assertEqual(sorted(loaded), sorted(l10n.CODES))
+ self.assertEqual(sorted(loaded), ['de', 'en', 'fr', 'sv', 'zh'])
self.assertEqual(set(loaded['en']), set(loaded['zh']))
self.assertNotIn('_language', loaded['en'])
self.assertEqual(set(TABLE), set(loaded['en']))
def test_tabs_newlines_and_backslashes_are_the_text_they_mean(self):
- for column, text in enumerate(TABLE['fail.noTitleID.next']):
- self.assertIn('\n', text, column)
- self.assertIn('C:\\VulkanSDK\\', TABLE['dep.spirv.hint.win'][1])
- self.assertNotIn('\\\\', TABLE['dep.spirv.hint.win'][1])
+ for code, text in TABLE['fail.noTitleID.next'].items():
+ self.assertIn('\n', text, code)
+ self.assertIn('C:\\VulkanSDK\\', TABLE['dep.spirv.hint.win']['en'])
+ self.assertNotIn('\\\\', TABLE['dep.spirv.hint.win']['en'])
def test_the_stale_frameworks_texts_are_there(self):
- self.assertEqual(t('stale.go', Lang.DE), 'Fortfahren')
- self.assertEqual(t('stale.go', Lang.ZH), '继续')
+ self.assertEqual(t('stale.go', Lang('de')), 'Fortfahren')
+ self.assertEqual(t('stale.go', Lang('zh')), '继续')
def test_a_language_without_the_key_shows_english_and_an_unknown_key_shows_itself(self):
with tempfile.TemporaryDirectory() as d:
@@ -39,9 +39,8 @@ class Files(unittest.TestCase):
(Path(d) / f'{code}.json').write_text(json.dumps({'_language': {'name': code, 'locales': [code]}, **body}), encoding='utf-8')
reports: list[str] = []
table = l10n._table(load(d, report=reports.append))
- self.assertEqual(table['a'], ('甲', 'A', 'A', 'A', 'A'))
- self.assertEqual(len(reports), 2, reports) # de.json and fr.json are missing
-
+ self.assertEqual(table['a'], {'zh': '甲', 'en': 'A', 'sv': 'A'})
+ self.assertEqual(reports, []) # de and fr have no file, so they are not languages here
def test_nothing_found_or_a_broken_file_reports_and_loads_nothing(self):
reports: list[str] = []
self.assertEqual(load(None, report=reports.append), {})
@@ -50,7 +49,7 @@ class Files(unittest.TestCase):
(Path(d) / 'en.json').write_text('{ not json', encoding='utf-8')
reports.clear()
self.assertEqual(load(d, report=reports.append), {})
- self.assertEqual(len(reports), 5)
+ self.assertEqual(len(reports), 2, reports) # en.json is broken and zh.json is missing
self.assertEqual(l10n._table({}), {})
diff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.py
index 5c2f4c15..fe772cc6 100644
--- a/frontend-qt/tests/test_win.py
+++ b/frontend-qt/tests/test_win.py
@@ -1605,8 +1605,8 @@ class LocalizationTest(unittest.TestCase):
'dep.iossdk', 'dep.iossdk.hint', 'dep.metal', 'dep.metal.hint']
for k in keys:
self.assertIn(k, TABLE, f'{k} missing from the table')
- zh = t(k, Lang.ZH)
- en = t(k, Lang.EN)
+ zh = t(k, Lang('zh'))
+ en = t(k, Lang('en'))
self.assertTrue(zh and zh != k, f'{k} has no Chinese text')
self.assertTrue(en and en != k, f'{k} has no English text')
@@ -1619,7 +1619,7 @@ class LocalizationTest(unittest.TestCase):
'dep.pick.iossdk.invalid', 'dep.fix.network', 'dep.fix.diskspace', 'dep.fix.log']
for k in keys:
self.assertIn(k, TABLE, f'{k} missing from the table')
- zh, en = t(k, Lang.ZH), t(k, Lang.EN)
+ zh, en = t(k, Lang('zh')), t(k, Lang('en'))
self.assertTrue(zh and zh != k and en and en != k, f'{k} is not bilingual')
@@ -1745,9 +1745,9 @@ class VenvWheelsTest(unittest.TestCase):
def test_the_log_row_string_takes_three_args(self) -> None:
from nspb_qt.i18n import Lang
from nspb_qt.l10n import t
- out = t('dep.row.log', Lang.EN, 'python', 'missing', 'C:/x | found')
+ out = t('dep.row.log', Lang('en'), 'python', 'missing', 'C:/x | found')
self.assertEqual(out, 'dependency python: [missing] C:/x | found', 'the report log showed raw %@ placeholders')
- self.assertTrue(t('dep.row.log', Lang.ZH, 'python', 'missing', 'd'), 'Chinese side is filled too')
+ self.assertTrue(t('dep.row.log', Lang('zh'), 'python', 'missing', 'd'), 'Chinese side is filled too')
class MetalPickFlowShapeTest(unittest.TestCase):
diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.md
index 2f00395c..a357c284 100644
--- a/frontend/ARCHITECTURE.md
+++ b/frontend/ARCHITECTURE.md
@@ -16,7 +16,7 @@ The plan and the steps are in [LNPANDY/NX2Apple#387](https://github.com/LNPANDY/
Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. Step 5 added the first services. Step 6 added the first store, `AppUpdateStore`, the reference for the others. Step 7 moved the rest one store per PR: the repository, the engine sync, the dependencies, the devices, then the build. `BuildModel` is gone. Step 8 split `BuilderView` into one view per card and deleted `ContentView.swift`. The window's root view is `LauncherView`.
- `LauncherStores` (app target, `LauncherStores.swift`) is the wiring and nothing else: it creates the services and the stores, connects them and hands them to the views. Every store is a `let`. It holds no logic and no `@Published` state. The views take the stores they show as parameters.
-- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, the language choice and lookup (`Localization.swift`, with `LocalizationFiles.swift` reading the texts from `frontend/l10n/*.json`), the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader. Step 4 added four types: `TitleID` (parse a title ID from a file name, its owner, the update version, the build key), `GameInputs` (classify files into the four rows, row mismatch, allowed file types), `BuildProgress` (stage lines, progress details, durations, the steps of Xcode and the install, failure info) and `Toolchain` (probing Python, the venv, dotnet and Xcode, and the dependency rows `Dep`). `Stage` and `StepState` moved with `BuildProgress`. Step 5 added the first services (step 6 added `ReleaseSource`, see below): `ProcessRunner` (a protocol, with `SystemProcessRunner` as the real one), `ProcessGroups` (the process groups that Stop and quitting end) and `GitCheckout` (a protocol, with `SystemGitCheckout`, plus `GitRules` for the decisions that need no git). `ProcessRunner` is where a build process starts: `capture` runs to the end and keeps the output, `stream` hands out lines, `start` returns at once and can lead a process group. `LauncherStores` creates a runner and a checkout and hands them to the stores that use them: the clone, fetch, pull and adoption of a ZIP copy (`RepoStore`), the build run, the tools of a stage, the archive step and `openOnDevice` (`BuildStore`). `Toolchain`, `Diagnostics`, `OlderTools`, `Uninstall`, `EngineLayout.runSync` and the update staging take a runner or a checkout as a parameter with the real one as default. Tests pass in a fake. These still start a `Process` themselves and move with the step that owns them: `EngineInstaller` (ditto, in `NXCore` since the engine sync store), the administrator prompt in `LiveOnboardingDriver` and the game start in `LiveConsoleDriver`. The tools of the device store (`DeviceTools`, `AppSignature`, `DeviceControl`, `ShellInstaller`) moved onto `ProcessRunner` with the device store, see below. What reads `OnboardingDefaults` (`needsIOSPlatform`, the platform choice that asks for a new dependency check) stays in the app target, in `LauncherStores`, because the guided setup owns those keys.
+- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, the language choice and lookup (`Localization.swift`: `Lang` is a value identified by its code, not an enum, and `Lang.all` is the list of files. `LocalizationFiles.swift` reads the texts and each language's name, locale prefixes and order from `frontend/l10n/*.json`), the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader. Step 4 added four types: `TitleID` (parse a title ID from a file name, its owner, the update version, the build key), `GameInputs` (classify files into the four rows, row mismatch, allowed file types), `BuildProgress` (stage lines, progress details, durations, the steps of Xcode and the install, failure info) and `Toolchain` (probing Python, the venv, dotnet and Xcode, and the dependency rows `Dep`). `Stage` and `StepState` moved with `BuildProgress`. Step 5 added the first services (step 6 added `ReleaseSource`, see below): `ProcessRunner` (a protocol, with `SystemProcessRunner` as the real one), `ProcessGroups` (the process groups that Stop and quitting end) and `GitCheckout` (a protocol, with `SystemGitCheckout`, plus `GitRules` for the decisions that need no git). `ProcessRunner` is where a build process starts: `capture` runs to the end and keeps the output, `stream` hands out lines, `start` returns at once and can lead a process group. `LauncherStores` creates a runner and a checkout and hands them to the stores that use them: the clone, fetch, pull and adoption of a ZIP copy (`RepoStore`), the build run, the tools of a stage, the archive step and `openOnDevice` (`BuildStore`). `Toolchain`, `Diagnostics`, `OlderTools`, `Uninstall`, `EngineLayout.runSync` and the update staging take a runner or a checkout as a parameter with the real one as default. Tests pass in a fake. These still start a `Process` themselves and move with the step that owns them: `EngineInstaller` (ditto, in `NXCore` since the engine sync store), the administrator prompt in `LiveOnboardingDriver` and the game start in `LiveConsoleDriver`. The tools of the device store (`DeviceTools`, `AppSignature`, `DeviceControl`, `ShellInstaller`) moved onto `ProcessRunner` with the device store, see below. What reads `OnboardingDefaults` (`needsIOSPlatform`, the platform choice that asks for a new dependency check) stays in the app target, in `LauncherStores`, because the guided setup owns those keys.
- Step 6 moved the self-update out of `BuildModel`. `AppUpdate` (`NXCore`) now also holds the release parsing (`release(fromJSON:)`, `check(latest:current:)`), the version compare (`isNewer`), the asset names, the staging of a download (`stage`, `StageFailure`) and the install, which clears the quarantine flag through a `ProcessRunner`. `ReleaseSource` is the second service (a protocol, with `GitHubReleases` as the real one): the latest release and the download. `Uninstall` moved to `NXCore` too, because the store holds its plan. `AppUpdate.relaunch` still starts its detached shell itself, and the store gets it as a closure.
- `NXCoreTests` tests `NXCore` alone. It links no other target, so these tests run without SwiftUI. New tests of pure logic go there.
- `NXModel` holds `Localizer`: `lang` and `t()`. `LauncherStores` creates one, and `LauncherView` hands it to every view as an environment object. A view that shows text declares `@EnvironmentObject var loc: Localizer` and calls `loc.t(...)`. A language change redraws these views and nothing else.
@@ -27,7 +27,7 @@ Step 1 of #387 made the targets and moved the files that already fit. Step 2 mov
- `NXModel` holds `DeviceStore` (step 7, devices): the paired devices and their refresh (`devicectl list devices`), the signing teams, whether the listing ran (`checked`), the chosen install device and team (saved in the defaults), and the copy flow of the shared app: the question before the game data goes over (`shellCopy`, answered with `answerCopy`) and the wait for a cable (`shellWaiting`, `cancelWait`). The install runs on a background queue, so `askCopy`, `setWaiting` and `waitCancelled` are the blocking bridge it calls. `xcrun` is an injected value of the store (and of `LauncherStores.init`), no longer a loose property that tests assign. `LauncherStores` creates the store with its runner. The listings are closures with the real ones as default (`listDevices`, `readTeams`), so a test gives the store devices and teams. `LauncherStores.init(xcrun:volumesRoot:)` takes the two values that were loose hooks. `volumesRoot` (where external drives are mounted) is read by the failure classifier, not by a device tool, so it is an injected `let` of the build store. The views that show the install target (the Builds page) and the copy card observe the store. `NXCore` got what the store needs: `ShellCopyPlan`, `ShellCopyDecision` and `ShellConnection` (`ShellInstall.Connection` is an alias), `DeviceControl` (devicectl for the save transfer) and `LockedFlag`. `ProcessLaunch` got a `timeout` and an `input`, `ProcessResult` got `timedOut`, and `ProcessRunner` got one primitive, `streamLines` (merged output as whole lines, a callback when the process has started, an optional process group), with fakes and tests. `DeviceTools`, `AppSignature`, `DeviceControl` and `ShellInstaller` start their tools through a runner now. `NXModelTests` tests the store without SwiftUI, and `NXCoreTests` tests the tools against a fake runner.
- `NXModel` holds `BuildStore` (step 7, build, the last store): the build inputs (the four rows `Slot`, the game folder, the output folder), the target, the stage list and whether a build runs, the handling of the script's JSON events (`ingest`), the run (the script's arguments and environment, stopping, the archive step), the install hand-off (`installShell`, the retry of the game data, the reinstall, the re-sign, the IPA, `openOnDevice`), the failure the card shows (`noteFailure`, `noteInstallFailure`), "Build anyway" and the fix buttons, the stale frameworks question and the files a drop adds. It decides whether a build may start (`canBuild`, and the checks at the top of `startBuild`). It is a class with six `BuildStore+` files, because no file may pass 800 lines. It gets what it needs through narrow protocols: `RepoLocation`, `DependencyInstalling` (`DependencyStatus` plus the install the fix buttons run), `EngineSyncing` (the sync a stale `engine/` needs) and `InstallTarget` (the device, the team, the teams the Mac knows and the copy flow). `DependencyStore`, `EngineSyncStore` and `DeviceStore` conform. AppKit reaches it as closures: the open, folder and save panels (`choosePaths`, `chooseFolder`, `chooseSaveLocation`), the notice (`showNotice`), the Finder (`revealFolder`, `openApp`) and `targetChanged`, which `LauncherStores` answers with a new dependency check when a Mac-only setup changes target. `NXCore` got what it needs: `ShellInstall`, `ShellLibrary`, `ShellInstaller` and `BannerCache` (the install of the shared app), `BuildFailureClassifier`, `VolumePath`, and `RomFSArchive` and `BuildCommands` (the archive stamp, the add-on content copy, the reinstall and IPA commands, the tools' PATH). `ShellCLI` (the terminal install) stays in the app target. `NXModelTests` tests the store with fake stores and a fake runner, without SwiftUI. The build's process start and its output callbacks are tested in the app target through the real build script stand-ins in `ShellInstallTests`.
- `NXModel` also holds `BuildLog`: the log text, its tail trimming and the line buffer. `BuildStore` holds it in a `let` and does not publish it, and only `BuildLogView` (in `NXLauncher`) observes it. A log line redraws the log and no game card. `LauncherPerformanceTests` writes 1000 lines during a build and allows 0 cards.
-- `NXLauncher` holds the views and styles that need only `NXModel`, `NXCore`, SwiftUI and AppKit (step 8). The styles: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`. The pieces of a card (`LauncherCard.swift`: `CardGroup`, `CardRow`, `CardDivider`, `CardDisclosure`, `CardPageHeading` and `LauncherPageScroll`, the scrolling column of a page). One view per card of the Builds page: `SetupHintCard`, `TargetCard`, `InstallCard`, `LogCard` (with `BuildLogView`), `ActionCard`, `OutcomeCard` and `ProgressCard`, and the cards that belong beside them, `ShellCopyCard`, `BuildFailureCard` and `EngineSyncBanner`. One view per card of the Settings page: `ControlsCard`, `ToolsCard` and `AppCard`. Also `UpdateSheet`, the `GameFilesDrop` target, `RowScroller` and `DockProgress`. Each card declares the stores it shows as `@ObservedObject` parameters and observes nothing else. A value from another store comes as a value (`buildRunning`, `shellCachePath`) or a closure, never through another store. What only the app can give a card comes as a binding or a view builder: the switches kept in the app's defaults (`AppCard`, `ControlsCard`) and the diagnostics button (`ToolsCard`). `AppCard.languageCodes` lists the languages of the picker.
+- `NXLauncher` holds the views and styles that need only `NXModel`, `NXCore`, SwiftUI and AppKit (step 8). The styles: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`. The pieces of a card (`LauncherCard.swift`: `CardGroup`, `CardRow`, `CardDivider`, `CardDisclosure`, `CardPageHeading` and `LauncherPageScroll`, the scrolling column of a page). One view per card of the Builds page: `SetupHintCard`, `TargetCard`, `InstallCard`, `LogCard` (with `BuildLogView`), `ActionCard`, `OutcomeCard` and `ProgressCard`, and the cards that belong beside them, `ShellCopyCard`, `BuildFailureCard` and `EngineSyncBanner`. One view per card of the Settings page: `ControlsCard`, `ToolsCard` and `AppCard`. Also `UpdateSheet`, the `GameFilesDrop` target, `RowScroller` and `DockProgress`. Each card declares the stores it shows as `@ObservedObject` parameters and observes nothing else. A value from another store comes as a value (`buildRunning`, `shellCachePath`) or a closure, never through another store. What only the app can give a card comes as a binding or a view builder: the switches kept in the app's defaults (`AppCard`, `ControlsCard`) and the diagnostics button (`ToolsCard`). `AppCard.languageCodes` lists the languages of the picker: the files in `frontend/l10n`, each shown by its own name.
- `NX2Apple` holds everything else: the wiring (`LauncherStores`), the root view `LauncherView` and the views that need an app type, the panels and the drivers. `CardPages` is the scrolling column both settings and builds pages share (it keeps the scroll position, the open log and the open extra rows when someone goes from one page to the other) and `BuildPage` and `SettingsPage` only list the cards of their page. `FilesCard` stays here because it runs `KeyCheck`, which needs CommonCrypto. `LibraryCard` observes `GameLibrary`. The other views stay because they read an app type: `LauncherView`, `Library`, `ManageMenu` and `LaunchOptionsView` read `GameLibrary`, `LibraryGame` or `LauncherGamepad`, `CheatsView` reads `CheatFiles`, `FrameTimesView` reads `FrameTimes`, the console views read `ConsoleState` and the glyphs read `LauncherGamepad`, `OnboardingView` reads `OnboardingState` and its drivers. They move when those types do.
## Access level
diff --git a/frontend/README.md b/frontend/README.md
index 12dcccfe..0d4561e9 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -300,14 +300,18 @@ nothing changes: Homebrew's tools, a system Python or the launcher's venv. To tr
## Language
-The interface follows the system language at every launch: any Chinese variant
-(Simplified, Traditional, Hong Kong, Taiwan) gets Chinese, Swedish gets Swedish, German gets
-German, French gets French, and every other language gets English. Settings > Language overrides
-that. The texts are not in Swift. Every language is one JSON file in `l10n/` (`en.json`, `zh.json`,
-`sv.json`, `de.json`, `fr.json`): a flat object with the keys sorted, UTF-8 text without escapes, and a
-`_language` entry that holds the language's own name and the locale prefixes that select it.
-`Sources/NXCore/Localization.swift` keeps only the language choice and the lookup, and
-`LocalizationFiles.swift` reads the files once, at the first lookup. A new string is a line in
+The interface follows the system language at every launch: a device language that has a file in
+`l10n/` gets that language (any Chinese variant gets Chinese, Swedish gets Swedish, German gets German,
+French gets French) and every other language gets English. Settings > Language overrides
+that. The texts and the language list are not in Swift. Every language is one JSON file in `l10n/`
+(`en.json`, `zh.json`, `sv.json`, `de.json`, `fr.json`): a flat object with the keys sorted, UTF-8 text
+without escapes, and a `_language` entry. It holds the language's own name (`name`, which the picker
+shows), the lowercased locale prefixes that select it (`locales`) and optionally its place in the picker
+(`order`, languages without one come last by code).
+`Sources/NXCore/Localization.swift` keeps only `Lang` (a language is its code, and `Lang.all` is the list
+of files) and the lookup, and `LocalizationFiles.swift` reads the files once, at the first lookup. A new
+language is one new file under `l10n/`: the picker, the device detection and the lookup find it with no
+change in Swift (the iOS shell's own texts are not in the files yet, that is a later step of #388). A new string is a line in
`l10n/en.json` and one in `l10n/zh.json`: English and Chinese have every key. Swedish, German and French
may miss a key and then show the English text, and `GermanLocalizationTests` and
`FrenchLocalizationTests` check the entries they have (placeholders match the English text). The Windows
diff --git a/frontend/Sources/NXCore/Localization.swift b/frontend/Sources/NXCore/Localization.swift
index bba281d1..0cb413ed 100644
--- a/frontend/Sources/NXCore/Localization.swift
+++ b/frontend/Sources/NXCore/Localization.swift
@@ -1,46 +1,61 @@
import Foundation
-// The app's interface language follows the system at every launch: Chinese, Swedish, German and French variants
-// select their matching catalogs; other languages use English. The Settings picker can override
-// that choice without changing the device language.
+// The app's interface language follows the system at every launch: a device language that has a file in `frontend/l10n` selects
+// that catalog and any other uses English. The Settings picker can override that choice without changing the device language.
//
// The texts are not in this file. Every language is one JSON file in `frontend/l10n` (`LocalizationFiles` finds and reads
// them), and English and Chinese have every key, so the two cannot drift apart. The other languages are overlays that use English
// as an explicit safe fallback while they are filled, which lets a new language be added without changing every view first.
-package enum Lang: String, CaseIterable {
- case zh, en, sv, de, fr
+/// A language of the launcher: its code, which is the name of its file in `frontend/l10n` (`sv` is `sv.json`). The list, each
+/// language's own name and the locale prefixes that select it come from the files' `_language` entries, so a new language is a new
+/// file and no code. Chinese and English are the two every key must have, and English is the fallback.
+package struct Lang: Hashable, Sendable {
+ package let code: String
- /// Chinese, Swedish, German and French devices use their matching catalog; every other device gets English.
- package static func device() -> Lang {
- guard let first = Locale.preferredLanguages.first?.lowercased() else { return .en }
- if first.hasPrefix("sv") { return .sv }
- if first.hasPrefix("de") { return .de }
- if first.hasPrefix("fr") { return .fr }
- return first.hasPrefix("zh") ? .zh : .en
+ package init(_ code: String) { self.code = code }
+
+ package static let zh = Lang("zh")
+ package static let en = Lang("en")
+
+ /// Every language that has a file, in picker order.
+ package static let all: [Lang] = infos.map { Lang($0.code) }
+
+ private static let infos: [LocalizationFiles.Language] = LocalizationFiles.languages()
+
+ /// The language with this code, nil when no file has it (an empty or stale stored choice).
+ package static func find(_ code: String) -> Lang? { all.first { $0.code == code } }
+
+ /// The language's own name, which the picker shows. A language without a file shows its code.
+ package var name: String { Self.infos.first { $0.code == code }?.name ?? code }
+
+ /// The language tags and locale names (lowercased) that select it.
+ package var locales: [String] { Self.infos.first { $0.code == code }?.locales ?? [code] }
+
+ /// The first language one of whose locale prefixes starts the first of `preferred`, else English. A pure function of its input, so a
+ /// test can pass in languages that exist only in a temporary folder.
+ package static func detect(preferred: [String], among languages: [LocalizationFiles.Language]) -> Lang {
+ guard let first = preferred.first?.lowercased() else { return .en }
+ return languages.first { $0.locales.contains { first.hasPrefix($0) } }.map { Lang($0.code) } ?? .en
}
+ /// The device language when a file has it, else English.
+ package static func device() -> Lang { detect(preferred: Locale.preferredLanguages, among: infos) }
+
/// What the app starts in: the language picked in Settings, else the device's.
///
/// The picker exists because the device language is not always the one someone wants to read
/// this app in (a Chinese Windows display language on hardware bought abroad, a Mac kept in
/// English by habit). "Follow the system" stays the default; the states are stored as
- /// "" (follow), "zh", "en", "sv", "de" or "fr".
+ /// "" (follow) or a language code ("zh", "en", "sv", "de", "fr", or any other file in `frontend/l10n`).
package static func initial() -> Lang {
- switch UserDefaults.standard.string(forKey: "appLanguage") ?? "" {
- case "zh": return .zh
- case "en": return .en
- case "sv": return .sv
- case "de": return .de
- case "fr": return .fr
- default: return device()
- }
+ find(UserDefaults.standard.string(forKey: "appLanguage") ?? "") ?? device()
}
/// The stored choice, or nil when following the system.
package static var saved: Lang? {
- get { Lang(rawValue: UserDefaults.standard.string(forKey: "appLanguage") ?? "") }
- set { UserDefaults.standard.set(newValue?.rawValue ?? "", forKey: "appLanguage") }
+ get { find(UserDefaults.standard.string(forKey: "appLanguage") ?? "") }
+ set { UserDefaults.standard.set(newValue?.code ?? "", forKey: "appLanguage") }
}
}
@@ -61,7 +76,7 @@ package enum L10n {
/// The text of `key` in `lang`, else the English text, else the key itself (it shows up in the UI rather than a blank control).
package static func string(_ key: String, _ lang: Lang) -> String {
- catalogs[lang.rawValue]?[key] ?? catalogs["en"]?[key] ?? key
+ catalogs[lang.code]?[key] ?? catalogs["en"]?[key] ?? key
}
/// Every key has both languages and none is empty. Logged, never fatal.
diff --git a/frontend/Sources/NXCore/LocalizationFiles.swift b/frontend/Sources/NXCore/LocalizationFiles.swift
index 4ce0d7ef..1df8d8c4 100644
--- a/frontend/Sources/NXCore/LocalizationFiles.swift
+++ b/frontend/Sources/NXCore/LocalizationFiles.swift
@@ -13,7 +13,53 @@ import Foundation
/// A missing or broken file never stops the app. That language has no texts, a lookup falls back to English and then to the key, and
/// the problem is written to standard error once (the files are read once, at the first lookup).
package enum LocalizationFiles {
- package static let codes = ["en", "zh", "sv", "de", "fr"]
+ /// What a file says about its language in `_language`. A file without it still works as a catalog: its name is its code and its
+ /// only locale prefix is its code.
+ package struct Language: Equatable, Sendable {
+ package let code: String
+ /// The language's own name, which the picker shows (Svenska, Deutsch).
+ package let name: String
+ /// The lowercased prefixes that select it: a language tag (`de`, so `de-AT`) or, on Windows, a locale name (`german`).
+ package let locales: [String]
+ /// Where the picker puts it. Languages without one come after those with one, by code.
+ package let order: Int?
+ }
+
+ /// The codes of the language files in `directory`: the names of its `*.json` files, sorted.
+ package static func codes(in directory: URL) -> [String] {
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
+ return names.filter { $0.hasSuffix(".json") && !$0.hasPrefix(".") }.map { String($0.dropLast(5)) }.sorted()
+ }
+
+ /// One file's `_language` entry, with the defaults above for a missing or odd one.
+ package static func language(code: String, in file: URL) -> Language {
+ var name = code
+ var locales = [code]
+ var order: Int?
+ if let data = try? Data(contentsOf: file),
+ let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
+ let entry = object["_language"] as? [String: Any] {
+ if let n = entry["name"] as? String, !n.isEmpty { name = n }
+ let given = (entry["locales"] as? [Any])?.compactMap { ($0 as? String)?.lowercased() }.filter { !$0.isEmpty } ?? []
+ if !given.isEmpty { locales = given }
+ order = entry["order"] as? Int
+ }
+ return Language(code: code, name: name, locales: locales, order: order)
+ }
+
+ /// Every language in `directory` in picker order: those with an `order` by it, then the rest by code.
+ package static func languages(from directory: URL? = directory()) -> [Language] {
+ guard let directory else { return [] }
+ let all = codes(in: directory).map { language(code: $0, in: directory.appendingPathComponent("\($0).json")) }
+ return all.sorted {
+ switch ($0.order, $1.order) {
+ case let (a?, b?) where a != b: return a < b
+ case (_?, nil): return true
+ case (nil, _?): return false
+ default: return $0.code < $1.code
+ }
+ }
+ }
/// The folder with the language files, nil when none of the places has `en.json`.
package static func directory(environment: [String: String] = ProcessInfo.processInfo.environment,
@@ -57,7 +103,7 @@ package enum LocalizationFiles {
return [:]
}
var out: [String: [String: String]] = [:]
- for code in codes {
+ for code in codes(in: directory) {
if let texts = texts(in: directory.appendingPathComponent("\(code).json"), report: report) { out[code] = texts }
}
return out
diff --git a/frontend/Sources/NXLauncher/AppCard.swift b/frontend/Sources/NXLauncher/AppCard.swift
index d61c3c1f..10a45ed7 100644
--- a/frontend/Sources/NXLauncher/AppCard.swift
+++ b/frontend/Sources/NXLauncher/AppCard.swift
@@ -26,21 +26,27 @@ package struct AppCard: View {
self.uninstallPlan = uninstallPlan
}
- /// The language picker's choices in order, "" being the system's. A new language is one more code here and its
- /// "settings.language.<code>" entry, which is its own name (Svenska, Deutsch) in every language.
- package static let languageCodes = ["", "zh", "en", "sv", "de", "fr"]
+ /// The language picker's choices in order, "" being the system's. The rest is the language files in `frontend/l10n`, each shown
+ /// by its own name (`Lang.name`, from `_language`: Svenska, Deutsch), so a new language is a new file and nothing here.
+ package static let languageCodes = languageCodes(among: LocalizationFiles.languages())
+
+ package static func languageCodes(among languages: [LocalizationFiles.Language]) -> [String] { [""] + languages.map(\.code) }
+
+ /// What the picker shows for a choice: "system" follows the UI language, a language shows its own name.
+ private func languageLabel(_ code: String) -> String {
+ code.isEmpty ? loc.t("settings.language.system") : (Lang.find(code)?.name ?? code)
+ }
package var body: some View {
CardGroup(loc.t("section.app"), footnote: updates.status) {
// The interface language: the device default unless someone picks one here. Stored as
- // "" (follow), "zh", "en", "sv", "de" or "fr" so a later system-language change still applies.
+ // "" (follow) or a language code so a later system-language change still applies.
CardRow(loc.t("settings.language"),
- detail: Lang.saved.map { loc.t("settings.language.\($0.rawValue)") }
- ?? loc.t("settings.language.system"), dot: LauncherPalette.ready, help: "") {
+ detail: languageLabel(Lang.saved?.code ?? ""), dot: LauncherPalette.ready, help: "") {
// The launcher's own list, drawn like the buttons beside it and as wide as they are.
- // The language names are in their own language (see "settings.language.*"), only "system" follows the UI.
- LauncherDropdown(options: Self.languageCodes.map { (value: $0, label: loc.t("settings.language." + ($0.isEmpty ? "system" : $0))) },
- selection: Lang.saved.map { $0.rawValue } ?? "", label: loc.t("settings.language"),
+ // The language names are in their own language (from the files), only "system" follows the UI.
+ LauncherDropdown(options: Self.languageCodes.map { (value: $0, label: languageLabel($0)) },
+ selection: Lang.saved?.code ?? "", label: loc.t("settings.language"),
style: .button) { v in
loc.choose(v)
}
@@ -104,7 +110,7 @@ package struct AppCard: View {
/// The interface language one step on (a controller's left / right on the language list).
private func cycleLanguage(_ by: Int) {
let values = Self.languageCodes
- let at = values.firstIndex(of: Lang.saved.map { $0.rawValue } ?? "") ?? 0
+ let at = values.firstIndex(of: Lang.saved?.code ?? "") ?? 0
let v = values[(at + by + values.count) % values.count]
loc.choose(v)
}
diff --git a/frontend/Sources/NXModel/Localizer.swift b/frontend/Sources/NXModel/Localizer.swift
index a98e9121..5801616a 100644
--- a/frontend/Sources/NXModel/Localizer.swift
+++ b/frontend/Sources/NXModel/Localizer.swift
@@ -39,9 +39,9 @@ import NXCore
/// The string for `key` in the current language. An unknown key comes back as itself, so it shows up in the UI.
nonisolated package func t(_ key: String) -> String { L10n.string(key, lang) }
- /// Settings' choice: "" follows the system, else a `Lang` raw value. It is stored, and the language changes now.
+ /// Settings' choice: "" follows the system, else a language code. It is stored, and the language changes now.
package func choose(_ code: String) {
- Lang.saved = Lang(rawValue: code)
+ Lang.saved = Lang.find(code)
lang = Lang.initial()
}
}
diff --git a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift b/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
index d4b73ce6..0f9f2e77 100644
--- a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
@@ -207,7 +207,7 @@ import NXModel
}
try shot(AnyView(LauncherView(stores: LauncherStores(), library: library, performStartupChecks: false, enterConsole: {}, qaPrompt: true)), "prompt-windowed", 1000, 720)
for lang in [Lang.en, .zh] {
- try shot(AnyView(ConsoleConnectionPrompt(lang: lang, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark)), "prompt-\(lang.rawValue)", 900, 500)
+ try shot(AnyView(ConsoleConnectionPrompt(lang: lang, enterConsole: {}, dismissPrompt: {}).environmentObject(PadFocus()).preferredColorScheme(.dark)), "prompt-\(lang.code)", 900, 500)
}
}
diff --git a/frontend/Tests/NX2AppleTests/ConsoleTests.swift b/frontend/Tests/NX2AppleTests/ConsoleTests.swift
index d2804d8f..76dd5f65 100644
--- a/frontend/Tests/NX2AppleTests/ConsoleTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsoleTests.swift
@@ -222,7 +222,7 @@ import NXModel
host.layoutSubtreeIfNeeded()
let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
host.cacheDisplay(in: host.bounds, to: rep)
- try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("desktop-\(Int(width))-\(lang.rawValue).png"))
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("desktop-\(Int(width))-\(lang.code).png"))
window.orderOut(nil)
window.contentView = nil
window.close()
@@ -269,7 +269,7 @@ import NXModel
let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
host.cacheDisplay(in: host.bounds, to: rep)
try XCTUnwrap(rep.representation(using: .png, properties: [:]))
- .write(to: output.appendingPathComponent("\(screen)-\(name)-\(lang.rawValue).png"))
+ .write(to: output.appendingPathComponent("\(screen)-\(name)-\(lang.code).png"))
window.orderOut(nil)
window.contentView = nil
window.close()
diff --git a/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift b/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift
index cc1c85eb..3e183daa 100644
--- a/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift
+++ b/frontend/Tests/NX2AppleTests/FrenchLocalizationTests.swift
@@ -47,7 +47,7 @@ final class FrenchLocalizationTests: XCTestCase {
}
func testFrenchIsSelectedAndReadsItsCatalog() {
- XCTAssertEqual(Lang(rawValue: "fr"), .fr)
+ XCTAssertEqual(Lang.find("fr"), .fr)
XCTAssertEqual(L10n.string("settings.language.fr", .fr), "Français")
XCTAssertEqual(L10n.string("settings.language.fr", .en), "Français", "a language's name is in that language")
XCTAssertEqual(L10n.string("onboarding.start", .fr), "Commencer")
diff --git a/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift b/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift
index ecbf979a..be267d9e 100644
--- a/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift
+++ b/frontend/Tests/NX2AppleTests/GermanLocalizationTests.swift
@@ -69,7 +69,7 @@ final class GermanLocalizationTests: XCTestCase {
XCTAssertEqual(L10n.string("onboarding.later", .de), "Sp\u{e4}ter einrichten")
XCTAssertEqual(L10n.string("dep.recheck", .de), "Erneut pr\u{fc}fen")
XCTAssertEqual(L10n.string("saves.cancel", .de), "Abbrechen")
- XCTAssertEqual(Lang(rawValue: "de"), .de)
+ XCTAssertEqual(Lang.find("de"), .de)
}
func testLanguageNamesExistInEveryLanguage() {
@@ -94,7 +94,7 @@ final class GermanLocalizationTests: XCTestCase {
/// The opt-in capture tests render in English (and Chinese). Set `NX_CAPTURE_LANG=de` (or `sv`, `zh`)
/// to render them all in that language instead, for example into /tmp/de-shots.
enum CaptureLanguage {
- private static var chosen: Lang? { ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang(rawValue: $0) } }
+ private static var chosen: Lang? { ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang.find($0) } }
static func current(_ fallback: Lang) -> Lang { chosen ?? fallback }
static func all(_ fallback: [Lang]) -> [Lang] { chosen.map { [$0] } ?? fallback }
}
diff --git a/frontend/Tests/NX2AppleTests/LanguageListTests.swift b/frontend/Tests/NX2AppleTests/LanguageListTests.swift
new file mode 100644
index 00000000..12086d16
--- /dev/null
+++ b/frontend/Tests/NX2AppleTests/LanguageListTests.swift
@@ -0,0 +1,116 @@
+import XCTest
+@testable import NXCore
+@testable import NXLauncher
+
+/// Swedish, German and French as short names for the tests. The app has no such constants: its languages are the files in `frontend/l10n`.
+extension Lang {
+ static let sv = Lang("sv")
+ static let de = Lang("de")
+ static let fr = Lang("fr")
+}
+
+/// The language list comes from the files (LNPANDY/NX2Apple#388, step 2): the picker, the device detection and the names.
+final class LanguageListTests: XCTestCase {
+ private var temporary: URL!
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-l10n-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }
+
+ /// The folder of the real files, copied, so a test can add a file to it.
+ private func copyOfTheFiles() throws -> URL {
+ let real = try XCTUnwrap(LocalizationFiles.directory())
+ for name in try FileManager.default.contentsOfDirectory(atPath: real.path) {
+ try FileManager.default.copyItem(at: real.appendingPathComponent(name), to: temporary.appendingPathComponent(name))
+ }
+ return temporary
+ }
+
+ func testThePickerListsTheFiveLanguagesByTheirOwnNamesInTheOrderItAlwaysHad() {
+ XCTAssertEqual(AppCard.languageCodes, ["", "zh", "en", "sv", "de", "fr"])
+ XCTAssertEqual(Lang.all.map(\.name), ["\u{4E2D}\u{6587}", "English", "Svenska", "Deutsch", "Fran\u{E7}ais"])
+ XCTAssertEqual(Lang.all, [Lang.zh, .en, .sv, .de, .fr])
+ }
+
+ func testFindKnowsACodeOnlyWhenAFileHasIt() {
+ XCTAssertEqual(Lang.find("sv"), .sv)
+ XCTAssertNil(Lang.find(""))
+ XCTAssertNil(Lang.find("xx"))
+ XCTAssertNil(Lang.find("SV"))
+ }
+
+ /// The detection before the files: the first preferred language, by prefix, Chinese, Swedish, German and French, else English.
+ private func detectedBefore(_ preferred: [String]) -> String {
+ guard let first = preferred.first?.lowercased() else { return "en" }
+ if first.hasPrefix("sv") { return "sv" }
+ if first.hasPrefix("de") { return "de" }
+ if first.hasPrefix("fr") { return "fr" }
+ return first.hasPrefix("zh") ? "zh" : "en"
+ }
+
+ func testTheDeviceLanguageIsPickedAsBefore() {
+ let inputs: [[String]] = [
+ [], ["en-US"], ["en"], ["EN-gb"], ["zh-Hans-CN"], ["zh-Hant-TW"], ["zh-HK"], ["ZH"], ["sv-SE"], ["sv"], ["SV-fi"], ["de-DE"], ["de-AT"],
+ ["de-CH"], ["fr-FR"], ["fr-CA"], ["fr"], ["ja-JP"], ["pt-BR"], ["es-419"], ["it-IT"], ["ko-KR"], ["da-DK"], ["nb-NO"], ["fi-FI"],
+ ["en-US", "zh-Hans"], ["ja-JP", "de-DE"], ["de-DE", "en-US"], ["fr-FR", "sv-SE"], [""], ["x"], ["fry-NL"],
+ ]
+ let languages = LocalizationFiles.languages()
+ for preferred in inputs {
+ XCTAssertEqual(Lang.detect(preferred: preferred, among: languages).code, detectedBefore(preferred), "\(preferred)")
+ }
+ }
+
+ func testEveryFileSelectsItsOwnLanguageByItsCode() {
+ for lang in Lang.all {
+ for locale in lang.locales {
+ XCTAssertEqual(Lang.detect(preferred: [locale + "-XX"], among: LocalizationFiles.languages()), lang, locale)
+ }
+ }
+ }
+
+ func testASixthLanguageIsOneNewFileAndNothingElse() throws {
+ let folder = try copyOfTheFiles()
+ let file = """
+ {
+ "_language": { "name": "Xenia", "locales": ["xx", "xenian"] },
+ "onboarding.start": "Go"
+ }
+ """
+ try Data(file.utf8).write(to: folder.appendingPathComponent("xx.json"))
+ // The folder is found the way the app finds it: from NX_L10N_DIR.
+ XCTAssertEqual(LocalizationFiles.directory(environment: ["NX_L10N_DIR": folder.path])?.path, folder.path)
+ let languages = LocalizationFiles.languages(from: folder)
+ // It is in the picker, after the five that have a place, and shows its own name.
+ XCTAssertEqual(languages.map(\.code), ["zh", "en", "sv", "de", "fr", "xx"])
+ XCTAssertEqual(AppCard.languageCodes(among: languages), ["", "zh", "en", "sv", "de", "fr", "xx"])
+ XCTAssertEqual(languages.last?.name, "Xenia")
+ // The device language selects it by its prefix, and the others still select theirs.
+ XCTAssertEqual(Lang.detect(preferred: ["xx-YY"], among: languages), Lang("xx"))
+ XCTAssertEqual(Lang.detect(preferred: ["xenian"], among: languages), Lang("xx"))
+ XCTAssertEqual(Lang.detect(preferred: ["de-DE"], among: languages), .de)
+ XCTAssertEqual(Lang.detect(preferred: ["ja-JP"], among: languages), .en)
+ // Its texts are read, and a key it lacks is not in its catalog (the lookup then shows English).
+ let catalogs = LocalizationFiles.load(from: folder)
+ XCTAssertEqual(catalogs["xx"]?["onboarding.start"], "Go")
+ XCTAssertNil(catalogs["xx"]?["onboarding.later"])
+ XCTAssertNotNil(catalogs["en"]?["onboarding.later"])
+ XCTAssertEqual(catalogs.keys.sorted(), ["de", "en", "fr", "sv", "xx", "zh"])
+ }
+
+ func testAFileWithoutALanguageEntryStillWorks() throws {
+ try Data("{\"a\": \"b\"}".utf8).write(to: temporary.appendingPathComponent("yy.json"))
+ let found = try XCTUnwrap(LocalizationFiles.languages(from: temporary).first)
+ XCTAssertEqual(found, LocalizationFiles.Language(code: "yy", name: "yy", locales: ["yy"], order: nil))
+ }
+
+ func testLanguagesWithoutAnOrderComeAfterThoseWithOneByCode() throws {
+ for (code, order) in [("bb", "\"order\": 9, "), ("aa", ""), ("cc", ""), ("dd", "\"order\": 1, ")] {
+ let body = "{\"_language\": {\(order)\"name\": \"\(code)\", \"locales\": [\"\(code)\"]}}"
+ try Data(body.utf8).write(to: temporary.appendingPathComponent("\(code).json"))
+ }
+ XCTAssertEqual(LocalizationFiles.languages(from: temporary).map(\.code), ["dd", "bb", "aa", "cc"])
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
index 02a3941c..afd61a3a 100644
--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
@@ -21,17 +21,18 @@ import NXModel
func testThePickerOffersEveryLanguage() {
let offered = Set(AppCard.languageCodes.filter { !$0.isEmpty })
- XCTAssertEqual(offered, Set(Lang.allCases.map(\.rawValue)), "Settings > Language lists the launcher's languages")
+ XCTAssertEqual(offered, Set(Lang.all.map(\.code)), "Settings > Language lists the launcher's languages")
}
func testDropdownChoicesFitBesideTheChevron() throws {
- for code in AppCard.languageCodes {
- let key = "settings.language." + (code.isEmpty ? "system" : code)
- XCTAssertNotNil(L10n.table[key], key)
- for lang in Lang.allCases {
- let text = L10n.string(key, lang)
- XCTAssertLessThanOrEqual(try width(text), LauncherControl.choiceWidth, "\(lang) \(key): \(text)")
- }
+ // The languages show their own names, from the files. Only "system" follows the UI language.
+ for lang in Lang.all {
+ XCTAssertLessThanOrEqual(try width(lang.name), LauncherControl.choiceWidth, "\(lang.code): \(lang.name)")
+ }
+ XCTAssertNotNil(L10n.table["settings.language.system"])
+ for lang in Lang.all {
+ let text = L10n.string("settings.language.system", lang)
+ XCTAssertLessThanOrEqual(try width(text), LauncherControl.choiceWidth, "\(lang.code) system: \(text)")
}
}
@@ -39,7 +40,7 @@ import NXModel
func testLibraryFilterLabelsFitTheirSegment() throws {
let room = (LauncherControl.width - 2 * 3 - 2) / 2 - 2 * 12
for filter in LibraryFilter.allCases {
- for lang in Lang.allCases {
+ for lang in Lang.all {
let text = L10n.string(filter.labelKey, lang)
let font = try XCTUnwrap(Typography.manropeFont(size: 12.5, weight: .bold))
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))
@@ -183,7 +184,7 @@ import NXModel
let saved = keys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
for scenario in scenarios {
- for lang in Lang.allCases {
+ for lang in Lang.all {
let samples = try measure(scenario, lang)
let at = "\(lang), \(scenario.name)"
XCTAssertGreaterThanOrEqual(samples.count, scenario.atLeast, "\(at): the page showed fewer controls than expected")
@@ -271,7 +272,7 @@ import NXModel
try JSONEncoder().encode(Snapshot(games: [game], folder: directory.path)).write(to: file)
let library = GameLibrary(file: file)
let modelStores = LauncherStores(); let model = modelStores.build
- for lang in Lang.allCases {
+ for lang in Lang.all {
model.lang = lang
let samples = Samples()
let view = LaunchOptionsView(m: model, library: library, gameID: game.id).environmentObject(PadFocus()).environmentObject(modelStores.localizer)
diff --git a/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift b/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
index 4ff4dd34..ef78bbad 100644
--- a/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherDropdownTests.swift
@@ -54,8 +54,9 @@ final class LauncherDropdownTests: XCTestCase {
func testEveryLanguageInThePickerHasAName() {
XCTAssertEqual(AppCard.languageCodes.first, "")
for code in AppCard.languageCodes.dropFirst() {
- XCTAssertNotNil(Lang(rawValue: code), code)
- for lang: Lang in [.zh, .en, .sv, .de] { XCTAssertNotEqual(L10n.string("settings.language." + code, lang), "settings.language." + code) }
+ let lang = try? XCTUnwrap(Lang.find(code), code)
+ XCTAssertEqual(lang?.name.isEmpty, false, code)
+ XCTAssertNotEqual(lang?.name, code, "\(code) has a name of its own")
}
}
diff --git a/frontend/Tests/NX2AppleTests/OnboardingTests.swift b/frontend/Tests/NX2AppleTests/OnboardingTests.swift
index c2288cab..38402af0 100644
--- a/frontend/Tests/NX2AppleTests/OnboardingTests.swift
+++ b/frontend/Tests/NX2AppleTests/OnboardingTests.swift
@@ -199,7 +199,7 @@ final class OnboardingTests: XCTestCase {
let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
host.cacheDisplay(in: host.bounds, to: rep)
try XCTUnwrap(rep.representation(using: .png, properties: [:]))
- .write(to: output.appendingPathComponent("\(step.rawValue)-\(lang.rawValue).png"))
+ .write(to: output.appendingPathComponent("\(step.rawValue)-\(lang.code).png"))
window.orderOut(nil)
}
}
@@ -245,7 +245,7 @@ final class OnboardingTests: XCTestCase {
let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
host.cacheDisplay(in: host.bounds, to: rep)
try XCTUnwrap(rep.representation(using: .png, properties: [:]))
- .write(to: output.appendingPathComponent("nvn-hint-\(step.rawValue)-\(lang.rawValue).png"))
+ .write(to: output.appendingPathComponent("nvn-hint-\(step.rawValue)-\(lang.code).png"))
window.orderOut(nil)
}
}
diff --git a/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift
index b1ebf075..c1cd0bdc 100644
--- a/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift
+++ b/frontend/Tests/NX2AppleTests/StaleFrameworksTests.swift
@@ -114,7 +114,7 @@ import NXModel
}
func testAllFiveLanguagesHaveTheTextsAndNoneUsesASemicolon() {
- for lang in Lang.allCases {
+ for lang in Lang.all {
for key in ["stale.title", "stale.message", "stale.go", "stale.stop", "stale.removeFailed"] {
let text = L10n.string(key, lang)
XCTAssertNotEqual(text, key, "\(key) in \(lang)")
@@ -132,7 +132,7 @@ import NXModel
guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
- let lang = ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang(rawValue: $0) } ?? .en
+ let lang = ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang.find($0) } ?? .en
let entries = [StaleFrameworks.Entry(titleID: oldID, name: "Super Mario Odyssey", chain: old, paths: []),
StaleFrameworks.Entry(titleID: newID, name: "Hades", chain: old, paths: [])]
let alert = VStack(spacing: 12) {
@@ -158,7 +158,7 @@ import NXModel
host.layoutSubtreeIfNeeded()
let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
host.cacheDisplay(in: host.bounds, to: rep)
- try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("stale-frameworks-\(lang.rawValue).png"))
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("stale-frameworks-\(lang.code).png"))
window.orderOut(nil)
}
}
diff --git a/frontend/Tests/NXCoreTests/LocalizationFilesTests.swift b/frontend/Tests/NXCoreTests/LocalizationFilesTests.swift
index 3b3252c9..a22a3b73 100644
--- a/frontend/Tests/NXCoreTests/LocalizationFilesTests.swift
+++ b/frontend/Tests/NXCoreTests/LocalizationFilesTests.swift
@@ -21,11 +21,11 @@ final class LocalizationFilesTests: XCTestCase {
func testTheCheckoutHasAllFiveLanguagesWithTheSameKeysInEnglishAndChinese() throws {
let loaded = LocalizationFiles.load()
- for code in LocalizationFiles.codes { XCTAssertFalse(loaded[code]?.isEmpty ?? true, "\(code).json was not read") }
+ for code in ["en", "zh", "sv", "de", "fr"] { XCTAssertFalse(loaded[code]?.isEmpty ?? true, "\(code).json was not read") }
XCTAssertEqual(Set(loaded["en"]!.keys), Set(loaded["zh"]!.keys), "English and Chinese need every key")
XCTAssertNil(loaded["en"]!["_language"], "_language is not a text")
- XCTAssertEqual(L10n.string("stale.go", .de), "Fortfahren")
- XCTAssertEqual(L10n.string("no.such.key", .fr), "no.such.key")
+ XCTAssertEqual(L10n.string("stale.go", Lang("de")), "Fortfahren")
+ XCTAssertEqual(L10n.string("no.such.key", Lang("fr")), "no.such.key")
}
func testEnvironmentFolderComesFirstThenTheAppsResources() throws {
@@ -59,6 +59,7 @@ final class LocalizationFilesTests: XCTestCase {
XCTAssertEqual(loaded["en"], ["a": "A"])
XCTAssertNil(loaded["zh"])
XCTAssertNil(loaded["fr"])
- XCTAssertEqual(reports.count, 5, "n is not a text, zh.json is broken, sv, de and fr are missing: \(reports)")
+ // A language with no file is not a language, so only the two problems are reported.
+ XCTAssertEqual(reports.count, 2, "n is not a text and zh.json is broken: \(reports)")
}
}
diff --git a/frontend/Tests/NXModelTests/BuildStoreTests.swift b/frontend/Tests/NXModelTests/BuildStoreTests.swift
index 42697864..f96b70da 100644
--- a/frontend/Tests/NXModelTests/BuildStoreTests.swift
+++ b/frontend/Tests/NXModelTests/BuildStoreTests.swift
@@ -314,9 +314,9 @@ import XCTest
func testWhatTheStoreWritesItselfIsInTheLanguageOfTheLocalizer() {
let store = makeStore()
- localizer.lang = .de
- XCTAssertEqual(store.lang, .de)
- XCTAssertEqual(store.t("shell.needsDevice"), L10n.string("shell.needsDevice", .de))
+ localizer.lang = Lang("de")
+ XCTAssertEqual(store.lang, Lang("de"))
+ XCTAssertEqual(store.t("shell.needsDevice"), L10n.string("shell.needsDevice", Lang("de")))
}
func testAStoppedBuildWithNothingRunningDoesNothing() {
diff --git a/frontend/l10n/de.json b/frontend/l10n/de.json
index a72f325c..83db653a 100644
--- a/frontend/l10n/de.json
+++ b/frontend/l10n/de.json
@@ -1,6 +1,7 @@
{
"_language": {
"name": "Deutsch",
+ "order": 3,
"locales": [
"de",
"german",
diff --git a/frontend/l10n/en.json b/frontend/l10n/en.json
index 5ccbde57..088ad1a7 100644
--- a/frontend/l10n/en.json
+++ b/frontend/l10n/en.json
@@ -1,6 +1,7 @@
{
"_language": {
"name": "English",
+ "order": 1,
"locales": [
"en"
]
diff --git a/frontend/l10n/fr.json b/frontend/l10n/fr.json
index 3a4fa6a6..145421a5 100644
--- a/frontend/l10n/fr.json
+++ b/frontend/l10n/fr.json
@@ -1,6 +1,7 @@
{
"_language": {
"name": "Français",
+ "order": 4,
"locales": [
"fr",
"french"
diff --git a/frontend/l10n/sv.json b/frontend/l10n/sv.json
index a5f10f2c..0345f8c2 100644
--- a/frontend/l10n/sv.json
+++ b/frontend/l10n/sv.json
@@ -1,6 +1,7 @@
{
"_language": {
"name": "Svenska",
+ "order": 2,
"locales": [
"sv",
"swedish"
diff --git a/frontend/l10n/zh.json b/frontend/l10n/zh.json
index 4d2934b4..702b3bc7 100644
--- a/frontend/l10n/zh.json
+++ b/frontend/l10n/zh.json
@@ -1,6 +1,7 @@
{
"_language": {
"name": "中文",
+ "order": 0,
"locales": [
"zh",
"chinese"