Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Architecture of the Mac launcher
The launcher is one SwiftPM package with four targets. The compiler keeps the layers apart: each target may only import the ones above it in this table. A store that imports SwiftUI does not compile.
| Target | Holds | May import |
|---|---|---|
NXCore |
pure logic and services | Foundation |
NXModel |
stores | NXCore, Foundation, Combine |
NXLauncher |
views | NXModel, NXCore, SwiftUI, AppKit |
NX2Apple (app) |
entry point, wiring | all |
The plan and the steps are in LNPANDY/NX2Apple#387. Package.swift is the source of truth for what a target depends on.
Where it stands
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 alet. It holds no logic and no@Publishedstate. The views take the stores they show as parameters.NXCoreholds the value types and static functions that need only Foundation: app and engine update parsing, the language choice and lookup (Localization.swift:Langis a value identified by its code, not an enum, andLang.allis the list of files.LocalizationFiles.swiftreads the texts and each language's name, locale prefixes and order fromfrontend/l10n/*.json. The same files hold the iOS shell's texts underios.ui.andios.host., which the launcher never shows:tools/l10n_shell_catalogs.pygenerates 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) andToolchain(probing Python, the venv, dotnet and Xcode, and the dependency rowsDep).StageandStepStatemoved withBuildProgress. Step 5 added the first services (step 6 addedReleaseSource, see below):ProcessRunner(a protocol, withSystemProcessRunneras the real one),ProcessGroups(the process groups that Stop and quitting end) andGitCheckout(a protocol, withSystemGitCheckout, plusGitRulesfor the decisions that need no git).ProcessRunneris where a build process starts:captureruns to the end and keeps the output,streamhands out lines,startreturns at once and can lead a process group.LauncherStorescreates 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 andopenOnDevice(BuildStore).Toolchain,Diagnostics,OlderTools,Uninstall,EngineLayout.runSyncand 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 aProcessthemselves and move with the step that owns them:EngineInstaller(ditto, inNXCoresince the engine sync store), the administrator prompt inLiveOnboardingDriverand the game start inLiveConsoleDriver. The tools of the device store (DeviceTools,AppSignature,DeviceControl,ShellInstaller) moved ontoProcessRunnerwith the device store, see below. What readsOnboardingDefaults(needsIOSPlatform, the platform choice that asks for a new dependency check) stays in the app target, inLauncherStores, 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 aProcessRunner.ReleaseSourceis the second service (a protocol, withGitHubReleasesas the real one): the latest release and the download.Uninstallmoved toNXCoretoo, because the store holds its plan.AppUpdate.relaunchstill starts its detached shell itself, and the store gets it as a closure. NXCoreTeststestsNXCorealone. It links no other target, so these tests run without SwiftUI. New tests of pure logic go there.NXModelholdsLocalizer:langandt().LauncherStorescreates one, andLauncherViewhands it to every view as an environment object. A view that shows text declares@EnvironmentObject var loc: Localizerand callsloc.t(...). A language change redraws these views and nothing else.NXModelholdsAppUpdateStore: the release check, the staged update, the update sheet, the uninstall plan andappVersion.LauncherStorescreates it with its localizer, runner and release source, and the views that show the update (the launcher's top bar and activity line, the Settings section, the update sheet) observe it.NXModelTeststests it with a fake runner and a fake release source, without SwiftUI.NXModelholdsRepoStore(step 7, repository): the repository path, the status line under it, how far it is behind origin/main, the clone, the update check, the pull, the automatic update when the app opens and the adoption of a ZIP copy.LauncherStorescreates it with itsLocalizerandGitCheckoutand wires four closures: whether a build runs, whether this is a release app (which never clones or pulls), the build log, anddidMove, which starts the engine sync after a clone, a pull or an adoption. The views that show the repository (Settings "Tools", the library's activity line, the setup hint) observe the store.RepoLocationis the narrow protocol (path,isRepo,isGit) for a store that needs only where the repository is.NXCoregot the rules the store needs:RepoLayout(is it a repository, the tools a build needs, which checkout to use at start) and the file-system part ofEngineLayout(marker,root,isCheckout,hasEngineTool). The stale check and the sync ofEngineLayoutstay in the app target with the engine.NXModelholdsEngineSyncStore(step 7, engine sync): the engine selection (channel, engine ID, version, the one kept), the sync of a checkout'sengine/(tools/engine.py sync, its status line and its failure row with Try again, the calls that wait for a running sync) and the engine of the release app (seeding the app's own engine, the check of the selected channel, the install, the channel switch after a confirmation, an engine that waits for the running build).LauncherStorescreates it with its localizer and runner, theRepoStoreas theRepoLocationto read, theDependencyStoreas thePythonLocation(a narrow protocol withpythonPath) and closures: where the build reads its tools from (setRepoPath, an installed engine tree), whether a build runs, the automatic update and the log.RepoStore.didMovestarts its sync. The views that show the engine (Settings "Tools", the sync banner, the failure row's Try again, the launcher's checks after a sync) observe the store.NXCoregot what the store needs: the stale check and the sync ofEngineLayout,EngineUpdater.swift(EngineChannel,EngineSelection,EngineUpdate,EngineInstaller,EngineTransport) andBuildFailureKindwithBuildFailure(the sync's failure row). The classifierBuildFailureClassifiermoved toNXCorewith the build store.NXModelTeststests the store with a fake runner, without SwiftUI.NXModelholdsDependencyStore(step 7, dependencies): the rows of the tools panel (deps,checked, whether the list is expanded), the Python and dotnet paths the check finds, the check (check()) and the installs (install(_:), with the failure kept on the row and a note for it). It is thePythonLocationthatEngineSyncStorereads, andDependencyStatus(checked,allPresent,pythonPath,dotnetPath,deps) is the narrow protocol the build reads.LauncherStorescreates it with its localizer, runner and theRepoStoreas theRepoLocation, and wires closures: the guided setup's platform choice (needsIOS), the App Store (a row with no command, Xcode), the log and the note after a failed install. The views that show the rows (Settings "Tools", the setup hint and the status line of the Builds page) observe the store.NXCoregot what the store needs:DependencyCheck(the list of rows, the Metal row, the dotnet install command,deps-check.txt, the bash command and environment of an install) andMetalPin.NXModelTeststests the store with a fake runner and a fake detection, without SwiftUI. The Python row's venv install (Toolchain.makeVenv) is not tested there, because it reads and writes the real venv folder.NXModelholdsDeviceStore(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 withanswerCopy) and the wait for a cable (shellWaiting,cancelWait). The install runs on a background queue, soaskCopy,setWaitingandwaitCancelledare the blocking bridge it calls.xcrunis an injected value of the store (and ofLauncherStores.init), no longer a loose property that tests assign.LauncherStorescreates 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 injectedletof the build store. The views that show the install target (the Builds page) and the copy card observe the store.NXCoregot what the store needs:ShellCopyPlan,ShellCopyDecisionandShellConnection(ShellInstall.Connectionis an alias),DeviceControl(devicectl for the save transfer) andLockedFlag.ProcessLaunchgot atimeoutand aninput,ProcessResultgottimedOut, andProcessRunnergot 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,DeviceControlandShellInstallerstart their tools through a runner now.NXModelTeststests the store without SwiftUI, andNXCoreTeststests the tools against a fake runner.NXModelholdsBuildStore(step 7, build, the last store): the build inputs (the four rowsSlot, 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 ofstartBuild). It is a class with sixBuildStore+files, because no file may pass 800 lines. It gets what it needs through narrow protocols:RepoLocation,DependencyInstalling(DependencyStatusplus the install the fix buttons run),EngineSyncing(the sync a staleengine/needs) andInstallTarget(the device, the team, the teams the Mac knows and the copy flow).DependencyStore,EngineSyncStoreandDeviceStoreconform. AppKit reaches it as closures: the open, folder and save panels (choosePaths,chooseFolder,chooseSaveLocation), the notice (showNotice), the Finder (revealFolder,openApp) andtargetChanged, whichLauncherStoresanswers with a new dependency check when a Mac-only setup changes target.NXCoregot what it needs:ShellInstall,ShellLibrary,ShellInstallerandBannerCache(the install of the shared app),BuildFailureClassifier,VolumePath, andRomFSArchiveandBuildCommands(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.NXModelTeststests 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 inShellInstallTests.NXModelalso holdsBuildLog: the log text, its tail trimming and the line buffer.BuildStoreholds it in aletand does not publish it, and onlyBuildLogView(inNXLauncher) observes it. A log line redraws the log and no game card.LauncherPerformanceTestswrites 1000 lines during a build and allows 0 cards.NXLauncherholds the views and styles that need onlyNXModel,NXCore, SwiftUI and AppKit (step 8). The styles:LauncherPalette,Typography,LauncherStyles,LauncherDropdown,PadFocusandEmbeddedFonts. The pieces of a card (LauncherCard.swift:CardGroup,CardRow,CardDivider,CardDisclosure,CardPageHeadingandLauncherPageScroll, the scrolling column of a page). One view per card of the Builds page:SetupHintCard,TargetCard,InstallCard,LogCard(withBuildLogView),ActionCard,OutcomeCardandProgressCard, and the cards that belong beside them,ShellCopyCard,BuildFailureCardandEngineSyncBanner. One view per card of the Settings page:ControlsCard,ToolsCardandAppCard. AlsoUpdateSheet, theGameFilesDroptarget,RowScrollerandDockProgress. Each card declares the stores it shows as@ObservedObjectparameters and observes nothing else. A value from another store comes as a value (buildRunning) 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), the diagnostics button and the cache row (ToolsCard). The cache row isShellCacheRow, a view of its own that observes the build store, because Move cache folder runs on the build'srunningflag (#427).AppCard.languageCodeslists the languages of the picker: the files infrontend/l10n, each shown by its own name.NX2Appleholds everything else: the wiring (LauncherStores), the root viewLauncherViewand the views that need an app type, the panels and the drivers.CardPagesis 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) andBuildPageandSettingsPageonly list the cards of their page.FilesCardstays here because it runsKeyCheck, which needs CommonCrypto.LibraryCardobservesGameLibrary. The other views stay because they read an app type:LauncherView,Library,ManageMenuandLaunchOptionsViewreadGameLibrary,LibraryGameorLauncherGamepad,CheatsViewreadsCheatFiles,FrameTimesViewreadsFrameTimes, the console views readConsoleStateand the glyphs readLauncherGamepad,OnboardingViewreadsOnboardingStateand its drivers. They move when those types do.
Access level
Types shared between targets use package, not public. Everything else stays internal. A package struct has no memberwise initializer outside its module, so give it a package init.
Tests use @testable import for the targets they test, which reaches internal too.
Language mode
The package uses swift-tools-version 6.0 and builds every target in Swift 5 mode. NXCore is meant to build in Swift 6 mode so the compiler checks data races there. It does not yet: LauncherWork.counts is global mutable state, and PipeReader captures a non-Sendable closure in a @Sendable one. Fixing these changes signatures that the app uses, so it is its own step. When NXCore builds clean, give it swiftSettings: [.swiftLanguageMode(.v6)] in Package.swift.
Stores
A store is a small ObservableObject that owns its @Published state and is @MainActor. It gets services and other stores through init. It checks the conditions for its own actions. It asks another store for what it needs through a narrow protocol, not the whole store.
Services start processes or touch the file system and have no @Published state. Each one is a protocol with one real implementation, so a test passes in a fake.
Things a store needs from AppKit, such as file pickers and opening Finder, reach it as closures.
A view observes only the stores it shows. A change in one store invalidates only the views that observe it.
The pattern: AppUpdateStore
Sources/NXModel/AppUpdateStore.swift is the reference. A new store follows it:
- Declaration.
@MainActor package final class XStore: ObservableObject. It importsFoundation,CombineandNXCore, never SwiftUI or AppKit. - State. Everything a view shows is
@Published.package private(set)when only the store changes it.package varwhen a view binds it (showUpdateSheet,uninstallPlan) or a test sets it up. inittakes what the store works with. The services as protocols (ProcessRunner,ReleaseSource), theLocalizerfor its text, and the facts of its environment with the real ones as defaults (bundle,version,defaults,runningOS). A test passes in fakes and temporary folders. Another store or the model's flags come as a narrow closure (buildRunning), never as the whole object.- AppKit as closures. Quitting and relaunching reach the store as
terminateandrelaunch. A system notification is forwarded by the app, which calls a method of the store (appWillTerminate()). - Logic stays out. What needs no state (parsing, comparing, deciding what may be installed) is a static function in
NXCore(AppUpdate) with its own tests. The store only calls it and keeps the result. - Actions check their own conditions.
installrefuses while a build runs and for a copy that is not a released one. The view does not decide that. - Async work. The method that starts it sets its state synchronously (
busy = true), runs aTaskon the main actor, hops off it for blocking work (Task.detached) and returns theTask, so a test awaitsstore.checkForUpdate().value. - Tests.
NXModelTests, a@MainActortest class, no SwiftUI. Fakes for the services, aUserDefaultssuite of its own, files in a temporary folder. The tests ofNX2AppleTestsderive fromIsolatedDefaultsTestCase:LauncherStores(defaults: testDefaults)keeps the settings of a test in a suite of its own, and a test that leaves a key in the shared test domain fails. - Wiring.
LauncherStorescreates the store and connects it to the others. Views take it as an@ObservedObjectparameter (or as an environment object, asLocalizer), so a change redraws the views that show it and nothing else.
appVersion
AppUpdateStore.appVersion is the one line that says which release the launcher is: nonisolated package static let appVersion = "x.y.z". build-mac-app.yml checks the tag against it, sync-upstream.yml names the experimental engine after it, tools/try-local builds <appVersion>-local, and RELEASING.md says where to bump it. They read the line with sed, so keep it in that form and in that file. tools/tests/test_app_version.py fails when a reader names a file without the line, or a new reader is not in its list. When the line moves again, move every reader with it.
Where a new feature goes
- Parsing, formatting, classification, anything that is a function of its input:
NXCore, as a value type or a static function, with a test. - Running a process or reading and writing files: a service in
NXCorebehind a protocol. - State that a view shows and changes: a store in
NXModel. - A view:
NXLauncher, observing the stores it shows. A new card is one view there, listed inBuildPageorSettingsPage. A view that needs an app type stays inNX2Apple. - Creating the services and stores and handing them to the views:
NX2Apple, nothing else.
BuildModel is gone. Do not put logic in LauncherStores: it only creates and connects.
File size
No Swift file under frontend/Sources is above 800 lines. SourceSizeTests fails otherwise. No file is above it today, so SourceSizeTests.aboveTheLimit is empty. A file that cannot be split gets an entry there with its size, and it may only shrink. LauncherView.swift was the last one: its Library page (the hero, the collection row and the status line) moved to LauncherView+Library.swift as an extension, and LauncherPage and LibraryFilter moved to LauncherPage.swift. The state stays in LauncherView, so a member the extension reads is internal, not private.
Names that stay
The app is NX2Apple.app, and the target, the sources folder and the tests carry that name. Three names keep the old one, because players would lose data or updates otherwise:
CFBundleIdentifierorg.nxnative.NSPortBuilder. The settings in UserDefaults belong to it, and the updater rejects a bundle with another identifier.CFBundleExecutableNSPortBuilder. The build copies.build/release/NX2AppletoContents/MacOS/NSPortBuilder.- The data folder
~/Library/Application Support/NS Port Builder/with the venv, the artwork andlibrary.json.