Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
The iOS shell's texts are lines of the language files, its catalogs are generated (#388)
v0lumehiea2153886ba8
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex d787c918..ca033fc9 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -176,7 +176,7 @@ jobs:- name: Install the signing tool's package (tools/release_manifest.py)run: python -m pip install -r tools/requirements-release.txt- name: Patch, engine and release tool tests- run: python -m unittest -v tools/tests/test_patches.py tools/tests/test_engine.py tools/tests/test_release_manifest.py tools/tests/test_release_notes.py tools/tests/test_app_version.py+ run: python -m unittest -v tools/tests/test_patches.py tools/tests/test_engine.py tools/tests/test_release_manifest.py tools/tests/test_release_notes.py tools/tests/test_app_version.py tools/tests/test_l10n_shell_catalogs.py- name: Dry bump to seedds main (report only)run: python tools/engine.py bump --dry --to main || truediff --git a/AGENTS.md b/AGENTS.mdindex c43365f4..d8cb336a 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 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".+- **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 are in the same files under `ios.ui.` and `ios.host.`, and `python3 tools/l10n_shell_catalogs.py` writes the shell's `Localizable.xcstrings` from them, never edit those by hand). 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-ios/Demo/Gen/Info.plist b/frontend-ios/Demo/Gen/Info.plistindex b0763805..75a15e62 100644--- a/frontend-ios/Demo/Gen/Info.plist+++ b/frontend-ios/Demo/Gen/Info.plist@@ -13,6 +13,9 @@<key>CFBundleLocalizations</key><array><string>en</string>+ <string>de</string>+ <string>fr</string>+ <string>sv</string><string>zh-Hans</string></array><key>CFBundleName</key>diff --git a/frontend-ios/Demo/project.yml b/frontend-ios/Demo/project.ymlindex 8ee07e7d..0e52fe47 100644--- a/frontend-ios/Demo/project.yml+++ b/frontend-ios/Demo/project.yml@@ -34,7 +34,7 @@ targets:info:path: Gen/Info.plistproperties:- CFBundleLocalizations: [en, zh-Hans] # the string catalogs of ShellUI and ShellHost, so iOS offers them to the package bundles+ CFBundleLocalizations: [en, de, fr, sv, zh-Hans] # every file of frontend/l10n (tools/l10n_shell_catalogs.py), so iOS offers them to the package bundlesdependencies:- package: ShellUIproduct: ShellUIdiff --git a/frontend-ios/README.md b/frontend-ios/README.mdindex 825683a4..85066b72 100644--- a/frontend-ios/README.md+++ b/frontend-ios/README.md@@ -100,7 +100,7 @@ Choice rows with 2 to 4 short labels that fit their equal segment (`ChoicePresenController first: the D-pad and stick move a cream focus ring, A activates, B backs out, X opens settings, Y opens controllers. In Cover Flow, left and right move the carousel by one card and the focused card is always the middle one. A hardware keyboard works the same way: arrows, Return, Escape, O for settings and Y for controllers. Touch hides the focus ring and the controller hints until the next press. In Cover Flow the centred card is the button: a tap does what the game needs, a tap on a side card brings it to the middle, a long press opens its settings.-Manrope and its SIL OFL licence are bundled and registered at runtime, with the system font as fallback. Reduce Motion turns the Cover Flow tilt and the slides into plain crossfades. Shell strings are in `Resources/Localizable.xcstrings`.+Manrope and its SIL OFL licence are bundled and registered at runtime, with the system font as fallback. Reduce Motion turns the Cover Flow tilt and the slides into plain crossfades. Shell strings are lines of `frontend/l10n/<code>.json` (`ios.ui.*` for ShellUI, `ios.host.*` for ShellHost), and `Resources/Localizable.xcstrings` of ShellUI and ShellHost is generated from them by `python3 tools/l10n_shell_catalogs.py`. Do not edit the catalogs by hand, see `frontend/README.md`, section "Language".## Demodiff --git a/frontend-ios/Sources/ShellHost/HostText.swift b/frontend-ios/Sources/ShellHost/HostText.swiftindex 59bf6f91..f43eea2e 100644--- a/frontend-ios/Sources/ShellHost/HostText.swift+++ b/frontend-ios/Sources/ShellHost/HostText.swift@@ -1,7 +1,8 @@import Foundationimport ShellUI-/// The host layer's own words, from `Resources/Localizable.xcstrings` (English source, like ShellUI).+/// The host layer's own words, from `Resources/Localizable.xcstrings` (English source, like ShellUI). The catalog is generated from+/// `frontend/l10n/*.json` (`ios.host.*`) by `tools/l10n_shell_catalogs.py`: change a text there, not in the catalog.func hostText(_ key: String.LocalizationValue) -> String {String(localized: key, bundle: .module)}diff --git a/frontend-ios/Tests/ShellUITests/ShellStringsTests.swift b/frontend-ios/Tests/ShellUITests/ShellStringsTests.swiftindex ca319513..6cbc6159 100644--- a/frontend-ios/Tests/ShellUITests/ShellStringsTests.swift+++ b/frontend-ios/Tests/ShellUITests/ShellStringsTests.swift@@ -2,7 +2,8 @@ import Foundationimport Testing@testable import ShellUI-/// Every text of the shell comes in English and in Simplified Chinese, the two languages the interface language can pick.+/// Every text of the shell comes in English and in Simplified Chinese, the two languages that have every key. The catalogs are generated+/// from `frontend/l10n/*.json` (`tools/l10n_shell_catalogs.py`): another language may miss a text and then shows English.@Suite struct ShellStringsTests {private static let languages = ["en", "zh-Hans"]diff --git a/frontend-qt/tests/test_localization_de.py b/frontend-qt/tests/test_localization_de.pyindex 1abf9585..07016e70 100644--- a/frontend-qt/tests/test_localization_de.py+++ b/frontend-qt/tests/test_localization_de.py@@ -16,8 +16,10 @@ from nspb_qt.l10n import TABLE, t # noqa: E402class German(unittest.TestCase):def test_no_german_prose_is_left_in_english(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['de'] == row['en'] and len(row['en']) > 30 and k != 'dep.python.hint']+ # dep.python.hint is a list of package names, the same in every language. ios.* are the iOS shell's texts: the launcher never+ # shows them, and a language without them falls back to English in the shell too (tools/l10n_shell_catalogs.py)+ prose = [k for k, row in TABLE.items() if row['de'] == row['en'] and len(row['en']) > 30 and k != 'dep.python.hint'+ and not k.startswith('ios.')]self.assertEqual(prose, [], 'English text left in the German column')def test_german_has_no_semicolons_and_no_added_product_name(self):diff --git a/frontend-qt/tests/test_localization_keys.py b/frontend-qt/tests/test_localization_keys.pyindex 7b302614..bd793bab 100644--- a/frontend-qt/tests/test_localization_keys.py+++ b/frontend-qt/tests/test_localization_keys.py@@ -3,7 +3,9 @@1. A key that code names in a lookup (`t('key')`, `self.m.t('key')`, `L10n.string("key", ...)`) is in en.json.2. A key that code builds at run time (a prefix and a variable) starts with an entry of `dynamicKeys` infrontend/Tests/l10n-key-rules.json, and every entry has a key in en.json and a place in the sources that builds it.-3. A key of en.json that no source mentions, literally or under a `dynamicKeys` entry, fails, unless it is in `unusedAllowed`.+3. A key of en.json that no source mentions, literally or under a `dynamicKeys` or `catalogKeys` entry, fails, unless it is in+ `unusedAllowed`. `catalogKeys` are the iOS shell's texts (`ios.*`): tools/l10n_shell_catalogs.py writes them into the shell's+ string catalogs, and tools/tests/test_l10n_shell_catalogs.py checks that the catalogs are current.The sources are both front ends, so a key only the Windows launcher or only the Mac launcher uses is used. The Mac launcherruns the same rules in frontend/Tests/NXCoreTests/LocalizationKeyTests.swift.@@ -47,6 +49,7 @@ class LocalizationKeys(unittest.TestCase):cls.keys = {k for k in en if k != '_language'}rules = json.loads(RULES.read_text(encoding='utf-8'))cls.dynamic = [(d['prefix'], d['suffix']) for d in rules['dynamicKeys']]+ cls.catalog = [c['prefix'] for c in rules['catalogKeys']]cls.allowed = {a['key'] for a in rules['unusedAllowed']}cls.rules = rulescls.text = {p: p.read_text(encoding='utf-8') for p in source_files()}@@ -63,7 +66,8 @@ class LocalizationKeys(unittest.TestCase):cls.looked_up.append((path, DYNAMIC.split(body)[0] if built else body, built))def covered(self, key: str) -> bool:- return any(key.startswith(p) and key.endswith(s) and len(key) >= len(p) + len(s) for p, s in self.dynamic)+ return (any(key.startswith(p) and key.endswith(s) and len(key) >= len(p) + len(s) for p, s in self.dynamic)+ or any(key.startswith(p) for p in self.catalog))def test_the_sources_were_found(self):self.assertTrue(any(p.suffix == '.py' for p in self.text), 'no Python sources')@@ -86,6 +90,11 @@ class LocalizationKeys(unittest.TestCase):# Built in a lookup or anywhere else (a Dep's name, a labelKey), so the check is that a string literal starts with itself.assertTrue(any(f'"{prefix}' in t or f"'{prefix}" in t for t in self.text.values()), f'no source has a string that starts with {prefix!r}')+ def test_every_catalog_prefix_has_keys_and_a_reason(self):+ for entry in self.rules['catalogKeys']:+ self.assertTrue(any(k.startswith(entry['prefix']) for k in self.keys), f'catalogKeys {entry["prefix"]!r} has no key in en.json')+ self.assertTrue(entry.get('why', '').strip(), f'catalogKeys {entry["prefix"]!r} has no reason')+def test_no_key_is_unused(self):unused = sorted(k for k in self.keys if k not in self.literals and not self.covered(k) and k not in self.allowed)self.assertEqual(unused, [], 'keys in en.json that no source uses (remove them from every language file, or explain them in unusedAllowed)')diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.mdindex a357c284..ee071821 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`: `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.+- `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 same files hold the iOS shell's texts under `ios.ui.` and `ios.host.`, which the launcher never shows: `tools/l10n_shell_catalogs.py` generates the shell's string catalogs from them), 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.diff --git a/frontend/README.md b/frontend/README.mdindex 850146a4..08bbf632 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -311,7 +311,7 @@ shows), the lowercased locale prefixes that select it (`locales`) and optionally`Sources/NXCore/Localization.swift` keeps only `Lang` (a language is its code, and `Lang.all` is the listof files) and the lookup, and `LocalizationFiles.swift` reads the files once, at the first lookup. A newlanguage 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+change in Swift, and the iOS shell offers it too (below). 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 Frenchmay 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@@ -322,6 +322,19 @@ names must exist, a key en.json has must be used by one of the two front ends, a(`"fail." + kind + ".what"`) needs a line in `frontend/Tests/l10n-key-rules.json` (`dynamicKeys`). A key that is onlykept on purpose goes into `unusedAllowed` there, with the reason. Remove an unused key from every language file.+The iOS shell's texts are in the same files, under `ios.ui.` (ShellUI) and `ios.host.` (ShellHost). The Mac and the+Windows launcher never show them. Xcode needs a string catalog per target, so+`python3 tools/l10n_shell_catalogs.py` writes `frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings` and+`frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings` from the files (the catalogs are not edited by hand).+The Swift code asks for a shell text by its English words (`ShellStrings.text("Done")`), so the catalog's key is the English+text of the JSON key, and each language file that has the JSON key adds a localization (`zh.json` becomes `zh-Hans`, every other+code stays as it is). A new shell text is a line in `en.json` and `zh.json` under the prefix, the same words in the Swift call+and `python3 tools/l10n_shell_catalogs.py`. A new language file shows up in both catalogs with no change in the tool. A language+that has no line for a key shows the English text, as in the launchers. `tools/tests/test_l10n_shell_catalogs.py` fails when a+committed catalog differs from what the files give, and when the app's `CFBundleLocalizations` (the Demo app, `tools/try-local`+and the shell app of the engine, patch 0056) do not list every file, because iOS offers a language to the shell only when the+app declares it. The key checks treat the `ios.*` keys as used (`catalogKeys` in `frontend/Tests/l10n-key-rules.json`).+The app finds the files in `Contents/Resources/l10n` (`build-mac-app.yml` and `tools/try-local` copy thefolder there, the same way as the engine and the bundled tools, not as SwiftPM resources). `swift run` finds`frontend/l10n` by walking up from the executable, and `swift test` takes it from the source path.diff --git a/frontend/Tests/NXCoreTests/LocalizationKeyTests.swift b/frontend/Tests/NXCoreTests/LocalizationKeyTests.swiftindex 4cbfc805..fbe85a98 100644--- a/frontend/Tests/NXCoreTests/LocalizationKeyTests.swift+++ b/frontend/Tests/NXCoreTests/LocalizationKeyTests.swift@@ -6,7 +6,9 @@ import XCTest/// 1. A key that code names in a lookup (`t("key")`, `loc.t("key")`, `L10n.string("key", ...)`, `t('key')` in Python) is in en.json./// 2. A key that code builds at run time (a prefix and a variable) starts with an entry of `dynamicKeys` in/// `frontend/Tests/l10n-key-rules.json`, and every entry has a key in en.json and a place in the sources that builds it.-/// 3. A key of en.json that no source mentions, literally or under a `dynamicKeys` entry, fails, unless it is in `unusedAllowed`.+/// 3. A key of en.json that no source mentions, literally or under a `dynamicKeys` or `catalogKeys` entry, fails, unless it is in+/// `unusedAllowed`. `catalogKeys` are the iOS shell's texts (`ios.*`): `tools/l10n_shell_catalogs.py` writes them into the shell's+/// string catalogs, and `tools/tests/test_l10n_shell_catalogs.py` checks that the catalogs are current.////// The sources are both front ends, so a key only the Windows launcher or only the Mac launcher uses is used. The Qt front end/// runs the same rules in `frontend-qt/tests/test_localization_keys.py`, from the same rules file.@@ -14,7 +16,9 @@ final class LocalizationKeyTests: XCTestCase {private struct Rules: Decodable {struct Dynamic: Decodable { let prefix: String; let suffix: String; let why: String }struct Allowed: Decodable { let key: String; let why: String }+ struct Catalog: Decodable { let prefix: String; let why: String }let dynamicKeys: [Dynamic]+ let catalogKeys: [Catalog]let unusedAllowed: [Allowed]}@@ -29,6 +33,7 @@ final class LocalizationKeyTests: XCTestCase {func covered(_ key: String) -> Bool {rules.dynamicKeys.contains { key.hasPrefix($0.prefix) && key.hasSuffix($0.suffix) && key.count >= $0.prefix.count + $0.suffix.count }+ || rules.catalogKeys.contains { key.hasPrefix($0.prefix) }}}@@ -110,6 +115,14 @@ final class LocalizationKeyTests: XCTestCase {}}+ func testEveryCatalogPrefixHasKeysAndAReason() {+ let scan = Self.scan+ for entry in scan.rules.catalogKeys {+ XCTAssertTrue(scan.keys.contains { $0.hasPrefix(entry.prefix) }, "catalogKeys \(entry.prefix) has no key in en.json")+ XCTAssertFalse(entry.why.trimmingCharacters(in: .whitespaces).isEmpty, "catalogKeys \(entry.prefix) has no reason")+ }+ }+func testNoKeyIsUnused() {let scan = Self.scanlet allowed = Set(scan.rules.unusedAllowed.map(\.key))diff --git a/frontend/Tests/l10n-key-rules.json b/frontend/Tests/l10n-key-rules.jsonindex 4ab97481..1b718481 100644--- a/frontend/Tests/l10n-key-rules.json+++ b/frontend/Tests/l10n-key-rules.json@@ -1,5 +1,5 @@{- "_about": "Read by LocalizationKeyTests.swift (Mac launcher) and frontend-qt/tests/test_localization_keys.py (Qt front end), LNPANDY/NX2Apple#388. A key that code builds at run time (a prefix plus a variable) must start with one of the dynamicKeys, and every entry needs at least one key in frontend/l10n/en.json and one place in the sources that builds it. A key of en.json that no source mentions and no dynamicKeys entry covers fails the tests unless it is in unusedAllowed, with the reason.",+ "_about": "Read by LocalizationKeyTests.swift (Mac launcher) and frontend-qt/tests/test_localization_keys.py (Qt front end), LNPANDY/NX2Apple#388. A key that code builds at run time (a prefix plus a variable) must start with one of the dynamicKeys, and every entry needs at least one key in frontend/l10n/en.json and one place in the sources that builds it. A key of en.json that no source mentions and no dynamicKeys entry covers fails the tests unless it is in unusedAllowed, with the reason. The iOS shell's texts (catalogKeys) are not looked up by key in any source: tools/l10n_shell_catalogs.py writes them into the shell's string catalogs, and tools/tests/test_l10n_shell_catalogs.py checks that those files are current, so a key under a catalogKeys prefix counts as used.","dynamicKeys": [{"prefix": "console.kind.", "suffix": "", "why": "the controller kinds, ConsoleState.swift"},{"prefix": "console.platform.", "suffix": "", "why": "the platforms of a game, ConsoleState.swift"},@@ -34,5 +34,9 @@{"prefix": "onboarding.setup.", "suffix": "", "why": "the Xcode setup tasks of the onboarding, OnboardingState.swift"},{"prefix": "stage.", "suffix": "", "why": "the name of each build stage, BuildProgress.swift"}],+ "catalogKeys": [+ {"prefix": "ios.ui.", "why": "ShellUI, frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings"},+ {"prefix": "ios.host.", "why": "ShellHost, frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings"}+ ],"unusedAllowed": []}diff --git a/frontend/l10n/en.json b/frontend/l10n/en.jsonindex a00c3c4b..e7e49bb9 100644--- a/frontend/l10n/en.json+++ b/frontend/l10n/en.json@@ -542,6 +542,132 @@"free.selected": "%@ selected","free.title": "Free space","install.reveal": "Reveal in Finder",+ "ios.host.additionalContentPacks": "%lld additional content packs",+ "ios.host.appFolder": "This app's folder",+ "ios.host.appFolderEmpty": "This app's folder has no data for this game yet. Copy it to games/%@ in this app's folder in Files.",+ "ios.host.appearsTwice": "%@ appears twice in launcher.json.",+ "ios.host.badChain": "chain \"%@\" is not of the form b-<hex>.",+ "ios.host.badFramework": "framework \"%@\" is not a .framework name.",+ "ios.host.badGameId": "game \"%@\" in launcher.json is not 16 hex digits.",+ "ios.host.badLoader": "loader \"%@\" is neither FR nor FH.",+ "ios.host.badTitleId": "title_id \"%@\" is not 16 hex digits.",+ "ios.host.cantReadGame": "Can't read this game",+ "ios.host.choiceWithoutOptions": "%@ is a choice without [value, label] options.",+ "ios.host.chooseRomfs": "Choose a RomFS folder or romfs.img on this device, an external drive, or iCloud Drive.",+ "ios.host.codeMissing": "Game code missing",+ "ios.host.codeMissingNote": "The game's code is missing from this app. Rebuild and reinstall it.",+ "ios.host.differentVersionNote": "This game was built for a different version of this app. Update the app or rebuild the game in the launcher on your Mac.",+ "ios.host.done": "Done",+ "ios.host.filesDamaged": "Game files damaged",+ "ios.host.filesDamagedNote": "This game's files are damaged. Rebuild the game in the launcher on your Mac.",+ "ios.host.folderNameMismatch": "The folder is named %@ but the manifest says %@.",+ "ios.host.folderNotRemembered": "That folder could not be remembered. Try a different one.",+ "ios.host.folderUnreadable": "The folder you chose before is no longer readable. Please choose it again.",+ "ios.host.launchUnavailable": "Launching is not available yet.",+ "ios.host.launcherMismatch": "launcher.json is for %@, the manifest for %@.",+ "ios.host.launcherSchema": "launcher.json has schema %lld, this app reads schema 1.",+ "ios.host.locationNotRemembered": "That location could not be remembered. Try a different one.",+ "ios.host.locationUnreadable": "The location you picked before is no longer readable (the app was signed differently). Please choose it again.",+ "ios.host.logTruncated": "Only the end of the log is shown.",+ "ios.host.manifestDamagedNote": "This game's manifest is damaged. Rebuild the game in the launcher on your Mac.",+ "ios.host.manifestMissing": "Game manifest missing",+ "ios.host.manifestMissingNote": "This game's manifest is missing. Rebuild the game in the launcher on your Mac.",+ "ios.host.manifestSchema": "game.manifest.json has schema %lld, this app reads schema %lld.",+ "ios.host.manifestUnsupported": "Manifest not supported",+ "ios.host.missingKey": "%@ has no \"%@\"%@.",+ "ios.host.noAdditional": "No additional content",+ "ios.host.noDataInFolder": "No game data for %@ was found in that folder.",+ "ios.host.noLauncherJson": "This game has no launcher.json.",+ "ios.host.noLogYet": "This game has no log yet. It appears after the game has run.",+ "ios.host.noManifestFile": "This game's folder has no game.manifest.json.",+ "ios.host.noModules": "The manifest lists no modules.",+ "ios.host.noUpdateAddress": "No update address is set up for this app.",+ "ios.host.notDmSwitch": "\"%@\" is not a DM_ switch.",+ "ios.host.notInGameFolder": "%@ is not in this game's folder. Install the game again.",+ "ios.host.notValidJson": "%@ is not valid JSON.",+ "ios.host.ok": "OK",+ "ios.host.oneAdditionalContentPack": "1 additional content pack",+ "ios.host.player": "Player %@",+ "ios.host.rangeWithoutLimits": "%@ is a range without min, max and step.",+ "ios.host.settingsDamaged": "Settings list damaged",+ "ios.host.settingsDamagedNote": "This game's settings list is damaged. Rebuild the game in the launcher on your Mac.",+ "ios.host.settingsMissing": "Settings list missing",+ "ios.host.settingsMissingNote": "This game's settings list is missing. Rebuild the game in the launcher on your Mac.",+ "ios.host.settingsUnsupported": "Settings list not supported",+ "ios.host.shellName": "Shell",+ "ios.host.subjectManifest": "The game's manifest",+ "ios.host.subjectSettings": "The settings list",+ "ios.host.unknownGame": "Unknown game",+ "ios.host.unknownKind": "%@ has the unknown kind \"%@\".",+ "ios.host.valueFromSettings": "%@ (from Settings)",+ "ios.host.wrongValueAt": "%@ has a wrong or missing value at \"%@\".",+ "ios.ui.appUpdateNeeded": "App update needed",+ "ios.ui.back": "Back",+ "ios.ui.charging": "Charging",+ "ios.ui.choose": "Choose",+ "ios.ui.chooseEllipsis": "Choose…",+ "ios.ui.chooseFolder": "Choose folder…",+ "ios.ui.chooseGameData": "Choose game data…",+ "ios.ui.chooseGameDataHint": "Choose this game's data to get ready to play.",+ "ios.ui.chooseSameCloudFolder": "Choose the same iCloud Drive folder you use on your Mac.",+ "ios.ui.closeControllers": "Close controllers",+ "ios.ui.cloudFolderNote": "Games without a folder of their own save here. Choose the same iCloud Drive folder you use on your Mac.",+ "ios.ui.cloudSaves": "Cloud saves",+ "ios.ui.connectController": "Connect a controller in Bluetooth settings. Touch controls are always available in the library.",+ "ios.ui.controllers": "Controllers",+ "ios.ui.decrease": "Decrease",+ "ios.ui.details": "Details",+ "ios.ui.done": "Done",+ "ios.ui.doubleTapToSelect": "Double-tap to select",+ "ios.ui.emptyLibraryNote": "Your games will appear here when they are included in this app.",+ "ios.ui.forBugReport": "For a bug report",+ "ios.ui.fromSettings": "From Settings",+ "ios.ui.gameData": "Game data",+ "ios.ui.gameDataNote": "Games look for their data here. Keep one romfs.img per game in any folder inside. Each game is found by the image itself, so the folder names do not matter. Each game can also have a folder of its own.",+ "ios.ui.gameSettings": "Game settings",+ "ios.ui.howToFix": "How to fix",+ "ios.ui.howToUpdate": "How to update",+ "ios.ui.increase": "Increase",+ "ios.ui.installNewerApp": "Install a newer version of this app to play this game.",+ "ios.ui.interface": "Interface",+ "ios.ui.library": "Library",+ "ios.ui.moveBetweenControls": "Move between controls",+ "ios.ui.needsGameData": "Needs game data",+ "ios.ui.needsNewerApp": "This game needs a newer version of this app. Update it with the Mac app on your Mac, then install it on this device again.",+ "ios.ui.noAdditional": "No additional content",+ "ios.ui.noBattery": "No battery level",+ "ios.ui.noControllers": "No controllers connected",+ "ios.ui.noData": "No data selected",+ "ios.ui.noFolder": "No folder chosen",+ "ios.ui.off": "Off",+ "ios.ui.on": "On",+ "ios.ui.onController": "On a controller",+ "ios.ui.overlayNote": "Used by games that have no choice of their own.",+ "ios.ui.performanceOverlay": "Performance overlay",+ "ios.ui.play": "Play",+ "ios.ui.played": "Played %@",+ "ios.ui.playedToday": "Played today",+ "ios.ui.playedYesterday": "Played yesterday",+ "ios.ui.position": "%lld of %lld",+ "ios.ui.readyToPlay": "Ready to play",+ "ios.ui.rebuildNote": "Build this game again on your Mac and install it on this device. The Mac app checks every file while it builds, so the new copy is complete.",+ "ios.ui.recentlyPlayed": "Recently played",+ "ios.ui.remove": "Remove",+ "ios.ui.resetNote": "Brings back the settings this game was tested with.",+ "ios.ui.resetToDefaults": "Reset to tested defaults",+ "ios.ui.select": "Select",+ "ios.ui.settings": "Settings",+ "ios.ui.showLog": "Show log",+ "ios.ui.tagline": "A little room for adventure",+ "ios.ui.titleId": "Title ID %@",+ "ios.ui.turnOff": "Turn off",+ "ios.ui.turnOffCloudSaves": "Turn off cloud saves",+ "ios.ui.unavailable": "Unavailable",+ "ios.ui.updateApp": "Update app",+ "ios.ui.useAppData": "Use app data",+ "ios.ui.useSettingsFolder": "Use Settings folder",+ "ios.ui.version": "Version %@",+ "ios.ui.yourGames": "Your games","key.clear": "Clear","key.code": "Key %ld","key.delete": "Delete",diff --git a/frontend/l10n/zh.json b/frontend/l10n/zh.jsonindex b1ae8c25..687258f1 100644--- a/frontend/l10n/zh.json+++ b/frontend/l10n/zh.json@@ -543,6 +543,132 @@"free.selected": "已选 %@","free.title": "释放空间","install.reveal": "在访达中显示",+ "ios.host.additionalContentPacks": "%lld 个附加内容包",+ "ios.host.appFolder": "本 App 的文件夹",+ "ios.host.appFolderEmpty": "本 App 的文件夹中还没有此游戏的数据。请拷贝到 games/%@,或点「使用应用数据」。",+ "ios.host.appearsTwice": "%@ 在 launcher.json 中出现了两次。",+ "ios.host.badChain": "chain \"%@\" 不符合 b-<十六进制> 格式。",+ "ios.host.badFramework": "framework \"%@\" 不是 .framework 名称。",+ "ios.host.badGameId": "launcher.json 中的 game \"%@\" 不是 16 位十六进制。",+ "ios.host.badLoader": "loader \"%@\" 既不是 FR 也不是 FH。",+ "ios.host.badTitleId": "title_id \"%@\" 不是 16 位十六进制。",+ "ios.host.cantReadGame": "无法读取此游戏",+ "ios.host.choiceWithoutOptions": "%@ 是没有 [value, label] 选项的选择项。",+ "ios.host.chooseRomfs": "在此设备、外置硬盘或 Mac 上选择 RomFS 文件夹或 romfs.img。iOS 启动器会记住该位置。",+ "ios.host.codeMissing": "游戏代码缺失",+ "ios.host.codeMissingNote": "此 App 中缺少游戏代码。请重新构建并安装。",+ "ios.host.differentVersionNote": "此游戏是为本 App 的其它版本构建的。请更新 App 或在 Mac 启动器中重新构建。",+ "ios.host.done": "完成",+ "ios.host.filesDamaged": "游戏文件已损坏",+ "ios.host.filesDamagedNote": "此游戏文件已损坏。请在 Mac 上的启动器中重新构建。",+ "ios.host.folderNameMismatch": "文件夹名为 %@,但清单显示 %@。",+ "ios.host.folderNotRemembered": "无法记住该文件夹。请换一个试试。",+ "ios.host.folderUnreadable": "之前选择的文件夹已无法读取。请重新选择。",+ "ios.host.launchUnavailable": "启动功能尚不可用。",+ "ios.host.launcherMismatch": "launcher.json 属于 %@,而清单属于 %@。",+ "ios.host.launcherSchema": "launcher.json 的 schema 为 %lld,本 App 读取 1。",+ "ios.host.locationNotRemembered": "无法记住该位置。请换一个试试。",+ "ios.host.locationUnreadable": "之前选择的位置已无法读取(App 被重签)。请重新选择。",+ "ios.host.logTruncated": "仅显示日志末尾部分。",+ "ios.host.manifestDamagedNote": "此游戏的清单已损坏。请在 Mac 上的启动器中重新构建。",+ "ios.host.manifestMissing": "游戏清单缺失",+ "ios.host.manifestMissingNote": "此游戏的清单缺失。请在 Mac 上的启动器中重新构建。",+ "ios.host.manifestSchema": "game.manifest.json 的 schema 为 %lld,本 App 读取 %lld。",+ "ios.host.manifestUnsupported": "清单不受支持",+ "ios.host.missingKey": "%@ 缺少 \"%@\"%@。",+ "ios.host.noAdditional": "无附加内容",+ "ios.host.noDataInFolder": "在该文件夹中未找到 %@ 的游戏数据。",+ "ios.host.noLauncherJson": "此游戏没有 launcher.json。",+ "ios.host.noLogYet": "此游戏还没有日志。运行一次后会出现。",+ "ios.host.noManifestFile": "此游戏的文件夹中没有 game.manifest.json。",+ "ios.host.noModules": "清单中未列出任何模块。",+ "ios.host.noUpdateAddress": "此 App 未设置更新地址。",+ "ios.host.notDmSwitch": "\"%@\" 不是 DM_ 开关。",+ "ios.host.notInGameFolder": "%@ 不在此游戏的文件夹中。请重新安装游戏。",+ "ios.host.notValidJson": "%@ 不是有效的 JSON。",+ "ios.host.ok": "好",+ "ios.host.oneAdditionalContentPack": "1 个附加内容包",+ "ios.host.player": "玩家 %@",+ "ios.host.rangeWithoutLimits": "%@ 是缺少 min、max、step 的范围项。",+ "ios.host.settingsDamaged": "设置列表已损坏",+ "ios.host.settingsDamagedNote": "此游戏的设置列表已损坏。请在 Mac 上的启动器中重新构建。",+ "ios.host.settingsMissing": "设置列表缺失",+ "ios.host.settingsMissingNote": "此游戏的设置列表缺失。请在 Mac 上的启动器中重新构建。",+ "ios.host.settingsUnsupported": "设置列表不受支持",+ "ios.host.shellName": "壳",+ "ios.host.subjectManifest": "游戏清单",+ "ios.host.subjectSettings": "设置列表",+ "ios.host.unknownGame": "未知游戏",+ "ios.host.unknownKind": "%@ 的类型 \"%@\" 未知。",+ "ios.host.valueFromSettings": "%@(来自设置)",+ "ios.host.wrongValueAt": "%@ 的 \"%@\" 值错误或缺失。",+ "ios.ui.appUpdateNeeded": "需要更新 App",+ "ios.ui.back": "返回",+ "ios.ui.charging": "充电中",+ "ios.ui.choose": "选择",+ "ios.ui.chooseEllipsis": "选择…",+ "ios.ui.chooseFolder": "选择文件夹…",+ "ios.ui.chooseGameData": "选择游戏数据…",+ "ios.ui.chooseGameDataHint": "选择此游戏的数据以开始游戏。",+ "ios.ui.chooseSameCloudFolder": "选择与 Mac 上相同的 iCloud Drive 文件夹。",+ "ios.ui.closeControllers": "关闭手柄列表",+ "ios.ui.cloudFolderNote": "没有单独指定文件夹的游戏会把存档保存在这里。请选择与 Mac 相同的 iCloud Drive 文件夹。",+ "ios.ui.cloudSaves": "云存档",+ "ios.ui.connectController": "在蓝牙设置中连接手柄。触屏控制始终可用。",+ "ios.ui.controllers": "手柄",+ "ios.ui.decrease": "减小",+ "ios.ui.details": "详情",+ "ios.ui.done": "完成",+ "ios.ui.doubleTapToSelect": "轻点两下以选择",+ "ios.ui.emptyLibraryNote": "游戏加入此 App 后会显示在这里。",+ "ios.ui.forBugReport": "用于问题报告",+ "ios.ui.fromSettings": "来自设置",+ "ios.ui.gameData": "游戏数据",+ "ios.ui.gameDataNote": "游戏会在这里查找游戏数据。请在其中的任意文件夹里为每个游戏放一个 romfs.img。应用会按镜像本身识别游戏,所以文件夹名称不限。每个游戏也可以单独指定文件夹。",+ "ios.ui.gameSettings": "游戏设置",+ "ios.ui.howToFix": "如何修复",+ "ios.ui.howToUpdate": "如何更新",+ "ios.ui.increase": "增大",+ "ios.ui.installNewerApp": "安装本 App 的更新版本以游玩此游戏。",+ "ios.ui.interface": "界面",+ "ios.ui.library": "游戏库",+ "ios.ui.moveBetweenControls": "在控件之间移动",+ "ios.ui.needsGameData": "需要游戏数据",+ "ios.ui.needsNewerApp": "此游戏需要本 App 的更新版本。请在 Mac 应用中更新。",+ "ios.ui.noAdditional": "无附加内容",+ "ios.ui.noBattery": "无电量信息",+ "ios.ui.noControllers": "未连接手柄",+ "ios.ui.noData": "未选择数据",+ "ios.ui.noFolder": "未选择文件夹",+ "ios.ui.off": "关",+ "ios.ui.on": "开",+ "ios.ui.onController": "在手柄上",+ "ios.ui.overlayNote": "游戏未单独设置时使用。",+ "ios.ui.performanceOverlay": "性能浮层",+ "ios.ui.play": "开始",+ "ios.ui.played": "%@ 玩过",+ "ios.ui.playedToday": "今天玩过",+ "ios.ui.playedYesterday": "昨天玩过",+ "ios.ui.position": "第 %lld 个,共 %lld",+ "ios.ui.readyToPlay": "随时可玩",+ "ios.ui.rebuildNote": "在 Mac 上重新构建此游戏并安装到本设备。Mac 应用构建时会检查每个文件,新副本是完整的。",+ "ios.ui.recentlyPlayed": "最近游玩",+ "ios.ui.remove": "移除",+ "ios.ui.resetNote": "恢复此游戏测试时使用的设置。",+ "ios.ui.resetToDefaults": "恢复测试默认值",+ "ios.ui.select": "选择",+ "ios.ui.settings": "设置",+ "ios.ui.showLog": "显示日志",+ "ios.ui.tagline": "给冒险留一点空间",+ "ios.ui.titleId": "Title ID %@",+ "ios.ui.turnOff": "关闭",+ "ios.ui.turnOffCloudSaves": "关闭云存档",+ "ios.ui.unavailable": "不可用",+ "ios.ui.updateApp": "更新 App",+ "ios.ui.useAppData": "使用应用数据",+ "ios.ui.useSettingsFolder": "使用设置中的文件夹",+ "ios.ui.version": "版本 %@",+ "ios.ui.yourGames": "你的游戏","key.clear": "清除","key.code": "按键 %ld","key.delete": "删除",diff --git a/patches/0056-ios-shell-declare-every-language-of-frontend-l10.patch b/patches/0056-ios-shell-declare-every-language-of-frontend-l10.patchnew file mode 100644index 00000000..4150cc45--- /dev/null+++ b/patches/0056-ios-shell-declare-every-language-of-frontend-l10.patch@@ -0,0 +1,26 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Mon, 2 Nov 2026 06:47:05 +0100+Subject: [PATCH] ios shell: declare every language of frontend/l10n in+ CFBundleLocalizations++Upstream-Status: fork-only+Reason: The shell's texts are the language files of the launcher, and iOS offers a language to the package bundles only when the app declares it. The list was en and zh-Hans, so Swedish, German and French devices got English.+Issue: LNPANDY/NX2Apple#388+---+ dm/ios/project-shell.yml | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)++diff --git a/dm/ios/project-shell.yml b/dm/ios/project-shell.yml+index 2f92fc4..0f82937 100644+--- a/dm/ios/project-shell.yml++++ b/dm/ios/project-shell.yml+@@ -48,7 +48,7 @@ targets:+ path: Gen/Info.plist+ properties:+ CFBundleDisplayName: ${DM_SHELL_NAME}+- CFBundleLocalizations: [en, zh-Hans] # ShellUI and ShellHost carry en and zh-Hans catalogs, iOS offers only the declared ones to the package bundles++ CFBundleLocalizations: [en, de, fr, sv, zh-Hans] # one per file of frontend/l10n (tools/l10n_shell_catalogs.py), iOS offers only the declared ones to the package bundles+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)+ CFBundleShortVersionString: $(MARKETING_VERSION)+ UILaunchScreen: {}diff --git a/patches/series b/patches/seriesindex fa77602e..bc25b64e 100644--- a/patches/series+++ b/patches/series@@ -33,3 +33,4 @@0053-runtime-profile-every-site.patch0054-front-mac-start-with-the-pointer-hidden-when-the.patch0055-ios-shell-declare-en-and-zh-hans-in-cfbundleloca.patch+0056-ios-shell-declare-every-language-of-frontend-l10.patchdiff --git a/tools/l10n_shell_catalogs.py b/tools/l10n_shell_catalogs.pynew file mode 100644index 00000000..6528ccd5--- /dev/null+++ b/tools/l10n_shell_catalogs.py@@ -0,0 +1,115 @@+#!/usr/bin/env python3+"""Generate the string catalogs of the iOS shell from the language files (LNPANDY/NX2Apple#388, step 5).++The shell's texts are lines of `frontend/l10n/<code>.json`, next to the launchers' texts, under two prefixes:++ ios.ui.* ShellUI, frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings+ ios.host.* ShellHost, frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings++The Swift code asks for a text by its English words (`ShellStrings.text("Done")`, `Text("Settings")`), which is what an Xcode+string catalog keys on. So the catalog's key is the English text of the JSON key (`%@` and `%lld` stay as they are), and every+language file that has the JSON key adds one localization. The languages are the files of the folder: a new `<code>.json` shows+up here with no change in this tool. A language that lacks a key falls back to English, as in the launchers.++ python3 tools/l10n_shell_catalogs.py # write the catalogs+ python3 tools/l10n_shell_catalogs.py --check # exit 1 when a committed catalog differs from what the files give+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+L10N = ROOT / 'frontend' / 'l10n'+SOURCES = ROOT / 'frontend-ios' / 'Sources'++# JSON key prefix and the target of the catalog it fills. ShellDemo has its own English-only catalog for the demo app.+CATALOGS = {+ 'ShellUI': 'ios.ui.',+ 'ShellHost': 'ios.host.',+}++# The language code of a file and the code Xcode and iOS know it by. Every other code is the same in both.+APPLE_CODES = {'zh': 'zh-Hans'}+SOURCE_LANGUAGE = 'en'+++def apple_code(code: str) -> str:+ return APPLE_CODES.get(code, code)+++def catalog_path(target: str) -> Path:+ return SOURCES / target / 'Resources' / 'Localizable.xcstrings'+++def load_languages(l10n: Path = L10N) -> dict[str, dict[str, str]]:+ """The texts of every language file of the folder, by language code. `_language` is not a text."""+ languages: dict[str, dict[str, str]] = {}+ for path in sorted(l10n.glob('*.json')):+ if path.name.startswith('.'):+ continue+ body = json.loads(path.read_text(encoding='utf-8'))+ languages[path.stem] = {k: v for k, v in body.items() if k != '_language'}+ if SOURCE_LANGUAGE not in languages:+ raise SystemExit(f'{l10n}/{SOURCE_LANGUAGE}.json is missing')+ return languages+++def apple_codes(languages: dict[str, dict[str, str]]) -> list[str]:+ """What the shell app declares as CFBundleLocalizations: every language file, English first, the rest by code."""+ codes = sorted(apple_code(c) for c in languages if c != SOURCE_LANGUAGE)+ return [SOURCE_LANGUAGE, *codes]+++def build(languages: dict[str, dict[str, str]], prefix: str) -> dict:+ """One catalog: the English text of each `prefix*` key is the key, each language that has the JSON key is a localization."""+ english = languages[SOURCE_LANGUAGE]+ strings: dict[str, dict] = {}+ owner: dict[str, str] = {}+ for json_key in sorted(k for k in english if k.startswith(prefix)):+ text = english[json_key]+ if text in owner:+ raise SystemExit(f'{json_key} and {owner[text]} have the same English text {text!r}: one catalog key cannot carry both')+ owner[text] = json_key+ localizations = {}+ for code, texts in languages.items():+ if json_key in texts:+ localizations[apple_code(code)] = {'stringUnit': {'state': 'translated', 'value': texts[json_key]}}+ strings[text] = {'localizations': dict(sorted(localizations.items(), key=lambda item: (item[0] != SOURCE_LANGUAGE, item[0])))}+ return {'sourceLanguage': SOURCE_LANGUAGE, 'strings': strings, 'version': '1.0'}+++def render(catalog: dict) -> str:+ """The text of the file. Keys are sorted, two spaces, no final newline: what the committed catalogs have always had."""+ return json.dumps(catalog, ensure_ascii=False, indent=2, sort_keys=True)+++def expected(l10n: Path = L10N) -> dict[str, str]:+ languages = load_languages(l10n)+ return {target: render(build(languages, prefix)) for target, prefix in CATALOGS.items()}+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split('\n')[0])+ parser.add_argument('--check', action='store_true', help='do not write, exit 1 when a catalog differs')+ args = parser.parse_args(argv)+ stale = []+ for target, text in expected().items():+ path = catalog_path(target)+ current = path.read_text(encoding='utf-8') if path.exists() else None+ if current == text:+ continue+ stale.append(str(path.relative_to(ROOT)))+ if not args.check:+ path.write_text(text, encoding='utf-8')+ print(f'wrote {path.relative_to(ROOT)}')+ if args.check and stale:+ print('out of date, run python3 tools/l10n_shell_catalogs.py: ' + ', '.join(stale), file=sys.stderr)+ return 1+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/tests/test_l10n_shell_catalogs.py b/tools/tests/test_l10n_shell_catalogs.pynew file mode 100644index 00000000..a8c9472f--- /dev/null+++ b/tools/tests/test_l10n_shell_catalogs.py@@ -0,0 +1,140 @@+"""tools/l10n_shell_catalogs.py: the committed string catalogs of the iOS shell are what the language files give (LNPANDY/NX2Apple#388, step 5).++The catalogs are generated, so a hand edit of a catalog or an edit of `frontend/l10n` without the tool fails here. The shell offers every+language that has a file in the folder: the catalogs carry each, and the app declares each as CFBundleLocalizations.+"""+import importlib+import json+import re+import sys+import tempfile+import unittest+from pathlib import Path++TOOLS = Path(__file__).resolve().parents[1]+ROOT = TOOLS.parent+sys.path.insert(0, str(TOOLS))+C = importlib.import_module('l10n_shell_catalogs')++PRINTF = re.compile(r'%(?:\d+\$)?(?:\.\d+)?(?:ll|l)?[@dsf%]')+++def write_language(folder: Path, code: str, texts: dict) -> None:+ body = {'_language': {'name': code, 'locales': [code]}, **texts}+ (folder / f'{code}.json').write_text(json.dumps(body, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')+++class CommittedCatalogs(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.languages = C.load_languages()++ def test_every_committed_catalog_is_what_the_language_files_give(self):+ for target, text in C.expected().items():+ path = C.catalog_path(target)+ self.assertTrue(path.exists(), f'{path} is missing')+ self.assertEqual(path.read_text(encoding='utf-8'), text,+ f'{path.relative_to(ROOT)} is out of date: run python3 tools/l10n_shell_catalogs.py')++ def test_the_check_mode_passes_on_the_committed_files(self):+ self.assertEqual(C.main(['--check']), 0)++ def test_the_catalogs_are_in_xcode_format(self):+ for target in C.CATALOGS:+ catalog = json.loads(C.catalog_path(target).read_text(encoding='utf-8'))+ self.assertEqual(catalog['sourceLanguage'], 'en')+ self.assertEqual(catalog['version'], '1.0')+ self.assertEqual(set(catalog), {'sourceLanguage', 'strings', 'version'})+ self.assertTrue(catalog['strings'])+ for key, entry in catalog['strings'].items():+ self.assertEqual(set(entry), {'localizations'}, key)+ self.assertEqual(entry['localizations']['en']['stringUnit']['value'], key, f'the key is the English text: {key}')+ for code, localization in entry['localizations'].items():+ self.assertEqual(localization['stringUnit']['state'], 'translated', f'{key} {code}')++ def test_format_specifiers_are_kept_in_every_language(self):+ for target in C.CATALOGS:+ for key, entry in json.loads(C.catalog_path(target).read_text(encoding='utf-8'))['strings'].items():+ for code, localization in entry['localizations'].items():+ self.assertEqual(sorted(PRINTF.findall(localization['stringUnit']['value'])), sorted(PRINTF.findall(key)), f'{code}: {key}')++ def test_english_and_chinese_have_every_shell_text(self):+ for target in C.CATALOGS:+ for key, entry in json.loads(C.catalog_path(target).read_text(encoding='utf-8'))['strings'].items():+ self.assertIn('zh-Hans', entry['localizations'], f'{target}: {key} has no Chinese text')++ def test_every_ios_key_belongs_to_a_catalog(self):+ prefixes = tuple(C.CATALOGS.values())+ for code, texts in self.languages.items():+ stray = sorted(k for k in texts if k.startswith('ios.') and not k.startswith(prefixes))+ self.assertEqual(stray, [], f'{code}.json has ios.* keys that no catalog takes')++ def test_the_demo_app_declares_every_language_of_the_files(self):+ codes = C.apple_codes(self.languages)+ project = (ROOT / 'frontend-ios' / 'Demo' / 'project.yml').read_text(encoding='utf-8')+ declared = re.search(r'CFBundleLocalizations:\s*\[([^\]]*)\]', project)+ self.assertIsNotNone(declared, 'Demo/project.yml has no CFBundleLocalizations')+ self.assertEqual([c.strip() for c in declared.group(1).split(',')], codes,+ 'Demo/project.yml: CFBundleLocalizations are the language files, en first')+ plist = (ROOT / 'frontend-ios' / 'Demo' / 'Gen' / 'Info.plist').read_text(encoding='utf-8')+ block = re.search(r'<key>CFBundleLocalizations</key>\s*<array>(.*?)</array>', plist, re.S)+ self.assertEqual(re.findall(r'<string>([^<]*)</string>', block.group(1)), codes, 'Demo/Gen/Info.plist is out of step with project.yml')++ def test_the_shell_app_of_the_engine_declares_every_language_of_the_files(self):+ project = ROOT / 'engine' / 'dm' / 'ios' / 'project-shell.yml'+ if not project.exists():+ self.skipTest('engine/ is not built (python3 tools/engine.py sync)')+ declared = re.search(r'CFBundleLocalizations:\s*\[([^\]]*)\]', project.read_text(encoding='utf-8'))+ self.assertIsNotNone(declared, 'dm/ios/project-shell.yml has no CFBundleLocalizations')+ self.assertEqual([c.strip() for c in declared.group(1).split(',')], C.apple_codes(self.languages),+ 'dm/ios/project-shell.yml: CFBundleLocalizations are the language files, en first (a patch in patches/)')++ def test_try_local_declares_every_language_of_the_files(self):+ text = (TOOLS / 'try-local').read_text(encoding='utf-8')+ declared = re.search(r'<key>CFBundleLocalizations</key><array>(.*?)</array>', text)+ self.assertEqual(sorted(re.findall(r'<string>([^<]*)</string>', declared.group(1))), sorted(C.apple_codes(self.languages)))+++class Generator(unittest.TestCase):+ def folder(self, **languages):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ for code, texts in languages.items():+ write_language(Path(tmp.name), code, texts)+ return Path(tmp.name)++ def test_a_new_language_file_is_in_the_catalog_with_no_change_to_the_tool(self):+ folder = self.folder(en={'ios.ui.done': 'Done', 'a.b': 'x'}, zh={'ios.ui.done': '完成', 'a.b': 'y'}, es={'ios.ui.done': 'Hecho'})+ catalog = C.build(C.load_languages(folder), 'ios.ui.')+ self.assertEqual(list(catalog['strings']), ['Done'], 'only the ios.ui. keys, the key is the English text')+ self.assertEqual(list(catalog['strings']['Done']['localizations']), ['en', 'es', 'zh-Hans'])+ self.assertEqual(catalog['strings']['Done']['localizations']['es']['stringUnit']['value'], 'Hecho')+ self.assertEqual(C.apple_codes(C.load_languages(folder)), ['en', 'es', 'zh-Hans'])++ def test_a_language_without_a_key_has_no_localization_of_it(self):+ folder = self.folder(en={'ios.ui.a': 'A', 'ios.ui.b': 'B'}, zh={'ios.ui.a': 'a', 'ios.ui.b': 'b'}, sv={'ios.ui.a': 'sa'})+ strings = C.build(C.load_languages(folder), 'ios.ui.')['strings']+ self.assertIn('sv', strings['A']['localizations'])+ self.assertNotIn('sv', strings['B']['localizations'])++ def test_format_specifiers_and_quotes_pass_through(self):+ folder = self.folder(en={'ios.ui.n': '"%@" is %lld of %.1f'}, zh={'ios.ui.n': '"%@" 是 %lld / %.1f'})+ strings = C.build(C.load_languages(folder), 'ios.ui.')['strings']+ self.assertEqual(list(strings), ['"%@" is %lld of %.1f'])+ self.assertEqual(strings['"%@" is %lld of %.1f']['localizations']['zh-Hans']['stringUnit']['value'], '"%@" 是 %lld / %.1f')++ def test_two_keys_with_the_same_english_text_in_one_catalog_fail(self):+ folder = self.folder(en={'ios.ui.a': 'Same', 'ios.ui.b': 'Same'}, zh={'ios.ui.a': 'x', 'ios.ui.b': 'y'})+ with self.assertRaises(SystemExit):+ C.build(C.load_languages(folder), 'ios.ui.')++ def test_the_output_is_stable(self):+ folder = self.folder(en={'ios.ui.b': 'B', 'ios.ui.a': 'A'}, zh={'ios.ui.b': 'b', 'ios.ui.a': 'a'})+ first = C.render(C.build(C.load_languages(folder), 'ios.ui.'))+ self.assertEqual(first, C.render(C.build(C.load_languages(folder), 'ios.ui.')))+ self.assertLess(first.index('"A"'), first.index('"B"'))+ self.assertFalse(first.endswith('\n'))+++if __name__ == '__main__':+ unittest.main()