diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..cf0b9af7 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +buy_me_a_coffee: bium diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a324f58..9e09cb62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,11 @@ jobs: run: python3 -m unittest discover -s Tests/PublicationChecks - name: Swift tests run: swift test + - name: Application regressions without UI + run: | + for check in Tests/CatalogAppChecks/run_*.py; do + python3 "$check" || exit 1 + done - name: Release compilation run: swift build -c release --product NXLibrary - name: Package and verify development app diff --git a/AGENTS.md b/AGENTS.md index 8ed89916..ffc78f24 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,22 @@ -# NX Library — agent guidance +# Arcane — agent guidance -A personal macOS SwiftUI front-end for upstream [nxnative](https://github.com/seedds/nxnative). Read `README.md` and `docs/architecture.md` before changing behavior. +A personal macOS SwiftUI front-end for upstream [nxnative](https://github.com/seedds/nxnative). Before changing behavior, read in this order: this file, `docs/architecture.md` (how each area works), `docs/conventions.md` (where new code goes and how it is built), `docs/flows.md` (end-to-end paths), the area's own document if it has one (for example `docs/steam.md`), then the files through `docs/file-map.md`. + +## Documentation + +The documentation is how the next session understands the structure. Keep it exact. + +- **Build on the existing structure.** Every new piece follows a recipe in `docs/conventions.md` and its named example. If no recipe fits, propose one to the maintainer; once approved, add it to `conventions.md` before or with the code. Never invent a second way to do something the codebase already does. +- **Same commit, same truth.** A change updates, in the same commit: + - its row in `docs/file-map.md`, placed in its area section, and the total; + - its area in `docs/architecture.md` (or the area's own document); + - `docs/flows.md`, if a flow changed; + - `docs/validation.md`, if something new awaits validation or the maintainer confirmed something. +- **Present tense only.** `architecture.md`, `conventions.md`, `flows.md` and area documents describe what the code does now. Put history in `CHANGELOG.md`, dated notes (`docs/upstream-upgrades/`, `docs/reviews/`) or git. Keep the *why* of a choice next to it in one sentence. Move measurements and probe evidence to a dated note in `docs/reviews/` and link it. +- **One validation list.** Validation status lives only in `docs/validation.md`. A row becomes validated only on the maintainer's confirmation. +- **No appended sections.** New features go into the section of their area, never into a dated section at the end of a guide or of the file map. If an area grows a document of its own, add it to the reading order above. +- **Designs and plans stay private.** Design notes, plans, research, product ideas and future intentions live in `docs/private/` (git-ignored) and are never moved into the repository. Public documents state current behavior and the one-sentence *why*; they never name private files or reveal planned features, sources, product or business ideas. +- **Readable docs.** Use short paragraphs, lists and tables; avoid single lines of thousands of characters. Name real types and files. Verify every claim against the code before writing it. ## Non-negotiables @@ -39,7 +55,7 @@ Every re-pin is a product decision, not just a hash change. Before changing the 2. Read the engine's current `scripts/build_ipa_from_nsp.py -h`, `docs/env_switches.tsv`, `dm/games/*/README.md`, and the changed docs. 3. Classify each change: shader/pipeline, host/runtime, input/display/audio, game profiles, build/extraction, CLI/env, docs/tests. 4. For each user-visible capability decide **UI**, **backend only**, or **not adopted**, and say why. -5. Wire any new engine flag that maps to an existing NX Library control. Example: nxnative 4f24ce6 added `--allow-other-metal`; it must be passed when the app's untested-toolchain override is on. +5. Wire any new engine flag that maps to an existing Arcane control. Example: nxnative 4f24ce6 added `--allow-other-metal`; it must be passed when the app's untested-toolchain override is on. 6. If the engine's README `pip install` line names a new package, add its wheel (and its dependencies) to `runtime.lock`, rebuild with `scripts/bundle_runtime.sh`, and update `NOTICE`; a GPL package also ships its source in `Runtime/sources/`. `EngineRuntimeRequirementsTests` fails until it is there. 7. If the engine's `dm/gfx/tools/dmsh_chain.lock` certifies a new Metal compiler, add it to `ToolchainRequirements.current.metalAssets` with Apple's asset build from `xcodebuild -showComponent MetalToolchain -json` (`buildVersion`), so the Setup check can download exactly that compiler. Raise `minimumXcode` when the new compiler needs it. 8. Re-pin only after tests, the compatibility gate, a certified build, and a smoke launch. Update `README.md` and the design spec. @@ -47,7 +63,7 @@ Every re-pin is a product decision, not just a hash change. Before changing the Never follow `main` automatically. A commit that is newer is not automatically a commit that is tested with this Mac's toolchain. -The only exception is the player's own choice in **Settings → Engine → Newest engine**: it moves the checkout to upstream `main` on request, turns the untested override on and records builds as untested, and is refused when `main` certifies a different Metal compiler. Setup keeps installing the pinned commit and never treats that choice as an error. Do not add any automatic path to `main`. +The only exception is the player's own choice in **Settings → Setup and engine → Newest engine**: it moves the checkout to upstream `main` on request, turns the untested override on and records builds as untested, and is refused when `main` certifies a different Metal compiler. Setup keeps installing the pinned commit and never treats that choice as an error. Do not add any automatic path to `main`. ## Branches @@ -60,11 +76,11 @@ The user performs interactive app and game checks. Never use computer-use tools ```bash DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test bash scripts/build_app.sh -codesign --verify --deep --strict "$HOME/Applications/NXLibrary Dev.app" +codesign --verify --deep --strict "$HOME/Applications/Arcane Dev.app" ``` -Development builds install as **NX Library Dev** (`~/Applications/NXLibrary Dev.app`), the maintainer's only test copy. Never build over, replace or test in the released `~/Applications/NX Library.app`; it is the copy installed from GitHub and updates itself. +Development builds install as **Arcane Dev** (`~/Applications/Arcane Dev.app`), the maintainer's only test copy. Never build over, replace or test in the released copy (`~/Applications/NX Library.app`, which becomes `Arcane.app` when a release that carries the new name quits); it is the copy installed from GitHub and updates itself. -Then verify the gate in **Settings → Engine**, build one real game, and launch it to a visible screen. Do not claim a build or game is working from compilation alone. +Then verify the gate in **Settings → Setup and engine**, build one real game, and launch it to a visible screen. Do not claim a build or game is working from compilation alone. Releases go through `scripts/release.sh` only: it refuses a dirty tree, so commit or stash local changes first. Never publish (`--publish`) without the user asking. diff --git a/CHANGELOG.md b/CHANGELOG.md index ceccdbf9..747ef71f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,63 @@ # Changelog -User-visible changes to NX Library are recorded here. Entries are grouped by release, with the newest first. Engine changes also have their own [upgrade notes](docs/upstream-upgrades/README.md). +User-visible changes to Arcane (formerly NX Library) are recorded here. Entries are grouped by release, with the newest first. Engine changes also have their own [upgrade notes](docs/upstream-upgrades/README.md). + +## 0.2.0 — 2026-11-18 + +See the [validation checklist](docs/validation.md) for the state of manual checks. + +### Added + +- Add installed Steam games for Mac to the shared Spotlight and Collection catalog alongside nxnative games. Arcane watches Steam install manifests to reflect downloads and installed games, and shows playtime and achievements when available. +- Steam game pages show **More like this** below About and Details, with related Steam games first and a fallback to matching Switch titles in your library. +- Steam achievements have a controller-friendly view with filters, sorting, public rarity, crystal tiers and an animated Arcane for unlocking every achievement. +- Shared game details show critic scores from Wikidata and optional IGDB. The metadata picker offers field-by-field suggestions from IGDB, LaunchBox and TheGamesDB. +- **Settings → About → Support Arcane** opens the project's optional Buy Me a Coffee page in your browser. + +### Changed + +- **Updated nxnative to `461a5f9f`.** The upstream update includes shader and texture fixes, audio output-route fixes, more game profiles and improvements in package discovery and pipeline preparation. The required Metal compiler is still `32023.922`. The new engine applies to games built with this pin. + +- **New app icon.** Arcane's icon is now a crystal inside a glass sphere, framed by navy and plum ink strokes on light paper. The Light, Dark and Mono choices in **App icon** follow it. +- The shell keeps the same background renderer when opening Settings and returning home, preserving its frame and motion clock. +- Changing the theme updates the shared background and its shades even when the wallpaper and selected card stay the same. + +- **Arcane** keeps the original blue moonlight as the default. Optional **Arcane Crystal** and **Arcane Flow** draw fine light threads bending in slow travelling waves, with faint ambient light and no broad beams or glass planes. Pink and cyan stay local, with very small colour changes over three minutes. Both are rendered live, with soft particles and the shared motion controls; no pictures or video. The existing theme identity and preferences stay compatible. + +- The app opens on the moving backdrop and brings the first Spotlight library in with growing tiles and a gradual game background. The welcome and Setup share that backdrop during the entrance; fullscreen waits for the window to be drawn. **Entrance animation** replaces the old Intro animation label while keeping its saved value and boot sound. The separate intro and preparation message are removed. The entrance always plays to its end: keys, clicks, the wheel and the controller wait for it, and the top bar and button hints come in last. +- Native alerts and file pickers take priority over controller actions as well as the keyboard and menu commands, so actions do not reach the library or an Arcane dialog underneath. +- The remembered **Game files** folder is kept for the picker without scanning it at launch. Choosing a folder or files in Add game starts the source scan; library refresh continues to discover installed apps. +- The app is now called **Arcane** in every visible place: window, menus, Settings, About and texts in all six languages. Your library, settings and data stay where they are. The development copy is Arcane Dev. +- Settings are grouped into **General**, **Library**, **Porting** and **System**. Launch screen, Surprise me, session card and hidden games are in Library → Games; keys, cloud saves and build caches have their own Porting pages; Rumble sits with the other new-game defaults; Console is in System. Every setting keeps its value. +- Players coming from NX Library see **Welcome to Arcane** once: the new name, what's new, and an offer to add Steam games for Mac when Steam is found and still off. +- A first launch starts from what is already on the Mac: installed Steam games for Mac and games you already ported, each with a count. Choose whether Steam joins the library, then open it; **Porting** leads to the setup for converting Switch games. Nothing changes on disk until you open the library. +- After an update, the app file becomes **Arcane.app** the next time you quit, in the same folder; the Dock keeps opening it. It stays as it is when the folder is read-only or an Arcane.app is already there. + +### Fixed + +- Steam receives Play once Arcane submits the launch cover, so a fast Space change can stay behind the waiting screen. +- The waiting screen stays up when a cold Steam launch pauses during its startup interstitials. +- Steam can finish opening windows behind the waiting screen without Arcane repeatedly hiding them and switching macOS Spaces. +- The waiting screen leaves the bottom-right corner free of app branding. +- Spotlight loads installed mods and the lower game page when the page opens. Moving on the game row skips the Details calculations. Spotlight and Collection save the last selected game in the background. +- Open library remains available during the initial scan, so an unresponsive folder cannot hold up first launch. Leaving cancels the request; sources can be added later in Settings. + +- Updating the app preserves existing copies beside it, including files named `(new)` or `(old)`. Each update uses its own staging directory; a failed Trash operation keeps the previous app. +- If an older copy changes the legacy library after migration, **Keep Arcane’s library** preserves the current games and sources and archives both versions before continuing. The libraries are not merged. + +- Spotlight reuses decoded game artwork on its first frame after returning from Settings, preserving personal picks and Steam icons. The Mods card keeps its prepared cover across navigation instead of briefly returning to its empty background. +- Porting shows **Preparing the first launch** during the engine's prewarm phase instead of estimating it from an older build's finishing time. A prewarm warning explains that missing pipelines are prepared when the game first starts. +- NUP discovery keeps a selected program separate from its application and DLC identities. Rebuilds explicitly select that program when the engine supports it; older NUP records keep program zero. +- Local save backups include additional users and their registry. Restoring an older backup preserves other local users; interrupted replacements and interrupted recovery retain verified backups and unexpected external changes. Cloud sync remains limited to the primary user and device save. + +- First launch keeps the Steam switch choice after quitting during Porting and uses the saved Steam folder for discovery and activation. An incomplete Steam read offers **Retry** instead of saying no games were found. +- Notification permission is requested when a porting starts, rather than when opening the library. +- Scrolling a game page can keep focus on its achievements card; Game Details is disabled while another panel owns input. +- Achievement requests made before Steam is configured are retried when its source becomes available. +- The achievements list keeps following the selected row after quickly closing and reopening the screen. Validated in Dev by the maintainer on 16 November. +- Automatic logo searches use the game's Switch or Switch 2 platform. +- Steam libraries that return after a scan join file watching on the next scan, even when their paths have not changed. Event paths under `/var` and `/tmp` are recognized consistently. +- Steam achievement and playtime readers reject unsafe or changing files through the shared bounded reader. ## 0.1.4.3 — 2026-11-12 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ab190b2c..a5d12727 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,8 @@ # Contributing NX Library is an early macOS front-end for a pinned upstream nxnative. -Start with [README](README.md), [architecture](docs/architecture.md) and -[AGENTS.md](AGENTS.md). +Start with [README](README.md), [AGENTS.md](AGENTS.md), +[architecture](docs/architecture.md) and [conventions](docs/conventions.md). Keep changes small and preserve Play for existing apps. Never patch the user's nxnative checkout, silently follow upstream main, or bypass the compatibility diff --git a/NOTICE b/NOTICE index ff09feb2..d742d814 100644 --- a/NOTICE +++ b/NOTICE @@ -7,7 +7,7 @@ The MIT permission notice is reproduced for each project below. -------------------------------------------------------------------------------- nxnative https://github.com/seedds/nxnative -Pinned engine commit: 2716f78f01e90a9f9bbf0d09e7a798903525962f +Pinned engine commit: 461a5f9f95fc9fc40a690bb2a82eb23f1f03bdca MIT License @@ -95,6 +95,16 @@ No Nintendo games, keys, logos, fonts, sounds, or other Nintendo assets are included in this repository. NX Library is not affiliated with, endorsed by, or sponsored by Nintendo. +The Steam logo (Resources/Brands/SteamLogo.png, the inverse logo from Valve's +Steam brand guidelines, unaltered) marks Steam games in the library. +©2026 Valve Corporation. Steam and the Steam logo are trademarks and/or +registered trademarks of Valve Corporation in the U.S. and/or other countries. +NX Library is not affiliated with, endorsed by, or sponsored by Valve. + +The Buy Me a Coffee cup (Resources/Brands/BuyMeACoffee.png) is from the +official brand kit (https://buymeacoffee.com/brand) and identifies the external +support page. The artwork belongs to Buy Me a Coffee. + -------------------------------------------------------------------------------- Bundled media (Material Icons, Selene sounds and palettes): see Resources/Selene/NOTICE.txt and diff --git a/README.md b/README.md index 3b9dcf90..b1ad810f 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@

- NX Library app icon - NX Library + Arcane's crystal-in-glass app icon + Arcane

A home for your games on Mac.

- Organise your library, build your own Switch dumps with nxnative,
- and launch the resulting Mac apps from one place. + Browse and launch games from one Mac library, with controller navigation,
+ game artwork and activity. Bring together installed Steam games for Mac and games you’ve ported.

@@ -20,57 +20,52 @@

Download · Get started · - User guide · + User guide · Troubleshooting · Changelog · - Next steps · Development

- + + -![NX Library Spotlight with a selected game, artwork, play history and library navigation](docs/media/spotlight.webp) +![Arcane Spotlight with a selected game, artwork, play history and library navigation](docs/media/spotlight.webp)

Your library, together.
Games, artwork and activity in Spotlight.

### New Latest highlights -- **Mods in a few clicks.** A store of GameBanana mods that work with your games, by category and by game. Press **Install** and the mod is on at the next launch, with no rebuild. Mods you already have work too: drop them in, turn them on, choose their order. -- **A lighter, smoother Ocarina of Time.** The updated engine reduces repeated startup work and first-draw stalls, uses less memory and fixes lighting and fog. Supported games offer up to 120 fps after rebuilding. -- **A recap when you stop playing.** Quit a game and you are back in your library, with a card showing how long you played this time and in total. -- **Your icon in the Dock.** Choose whether a game icon stays inside NX Library or also appears in Finder and the Dock, even after a rebuild. -- **Builds on your external drive.** Keep your games on an external drive and the whole build stays there, so the Mac's own disk needs no free space. +- **One library for your Mac games.** Add installed Steam games for Mac alongside games ported with nxnative. Browse in Spotlight or Collection and launch from either view. +- **Steam achievements.** See playtime, achievement rarity and crystal tiers when available. Complete every achievement in a game to reveal the animated Arcane. +- **An interface built for browsing.** Navigate with a controller, keyboard or mouse, and personalise your library with artwork, themes and live backgrounds. +- **NX Library is now Arcane.** Your library, preferences and save backups carry over. Settings are grouped into General, Library, Porting and System. Every release is in the [changelog](CHANGELOG.md). ## Overview -NX Library is an independent SwiftUI frontend for the external [nxnative](https://github.com/seedds/nxnative) toolchain. It brings your installed game apps, local build workflow and game options into a modern Mac-native library inspired by [Selene](https://github.com/mattxslv/Selene). +Arcane is an independent game library and launcher for Apple silicon Macs. It brings installed Steam games for Mac and games ported with nxnative into the same interface, inspired by [Selene](https://github.com/mattxslv/Selene). The integrated porting workflow uses [nxnative](https://github.com/seedds/nxnative) to build compatible Mac apps from your own Switch game files. | Area | What you can do | |---|---| | **Library** | Browse Spotlight and Collection, search, favourite, hide and reorder games. | -| **Local builds** | Select your own sources, review updates and DLC, follow progress and retry a failed installation. | +| **Steam** | Launch installed games for Mac and browse playtime, achievements and related games. | | **Game options** | Keep each title's launch settings, artwork and metadata together. | -| **Saves** | Back up local progress, preview imports and restore a previous copy. | -| **Mods** | Install GameBanana mods that work with the engine, or add your own, and choose what is on for the next launch. | -| **Cheats** | Import matching cheat files and choose what is enabled for the next launch. | | **Personalisation** | Choose palettes, wallpapers, live backgrounds, interface sounds and controller prompts. | +| **Porting** | Build compatible Switch titles with nxnative, review updates and DLC, and follow build progress. | +| **Ported games** | Manage compatible mods and cheats, back up local saves and preview save imports. | Game files, keys and firmware are not provided. See [Legal and third-party notices](#legal-and-third-party-notices). ### Project status -**0.1.4.3 alpha.** Download the packaged app from [Releases](https://github.com/Bium23/NxLibrary/releases/latest), or [build it from source](#building-from-source). +Arcane is in alpha. Get the latest published build from [Releases](https://github.com/Bium23/NxLibrary/releases/latest), or [build this version from source](#building-from-source). Automated checks cover the application code, publication inputs, compilation and development-app packaging. They do not certify game compatibility. Changes are recorded in the [changelog](CHANGELOG.md), and the current checks are available under [Actions](https://github.com/Bium23/NxLibrary/actions/workflows/ci.yml). -The engine is pinned to `8a5c5e7e`: builds no longer need .NET, rendering and shader fixes across many games, newly playable titles such as Red Dead Redemption, TUNIC, Metroid Prime 4: Beyond and PRAGMATA, and safer stopping of builds and cloud-save downloads, using Xcode 27.2 / Metal 32023.922. See the [engine upgrade notes](docs/upstream-upgrades/README.md). +Porting uses nxnative commit `461a5f9f` with Xcode 27.2 and Metal 32023.922. Porting Setup retrieves that commit. Installed game apps use the engine they were built with. See the [engine upgrade notes](docs/upstream-upgrades/README.md). ## Getting started @@ -78,10 +73,11 @@ The engine is pinned to `8a5c5e7e`: builds no longer need .NET, rendering and sh | Requirement | Details | |---|---| -| **Mac** | Apple silicon, macOS 13 or later. | -| **Xcode** | 27.2 or later, with the Metal compiler certified for the pinned engine. | -| **Engine** | nxnative at the pinned commit. Setup can prepare the checkout; an existing folder can be chosen in **Settings → Engine**. | -| **Your files** | Your own supported game sources and keys, with the rights and permissions needed to use them. | +| **Arcane library** | Apple silicon, macOS 13 or later. Steam and each game can require a newer macOS version. | +| **Porting and nxnative game apps** | macOS 26.6 or later for the Mac hosts built by the pinned engine. This is separate from Arcane's own minimum. | +| **Xcode for porting** | 27.2 or later, with the Metal compiler certified for the pinned engine. Browsing the library and using Steam do not require Xcode. | +| **Porting engine** | nxnative at the pinned commit. Setup can prepare the checkout. To select an existing folder, use **Settings → Porting → Setup and engine**. | +| **Porting inputs** | Your own supported game sources and keys, with the rights and permissions needed to use them. | A packaged app includes Python and its required packages, `zstd` and `glslangValidator`. Homebrew is used to prepare that runtime during development; it is not needed to use a packaged copy. A source build without the bundled runtime uses the engine's virtual environment and tools on `PATH`. @@ -95,7 +91,7 @@ cd NxLibrary bash scripts/bundle_runtime.sh bash scripts/build_app.sh -open "$HOME/Applications/NXLibrary.app" +open "$HOME/Applications/Arcane Dev.app" ~~~ Run `bundle_runtime.sh` once, and again when `runtime.lock` changes. `build_app.sh` prepares, signs and verifies the app before installing it atomically in `~/Applications`. @@ -105,18 +101,18 @@ Build options, runtime dependencies, debug builds and release packaging are docu ### Installing a packaged release 1. Download the DMG from [Releases](https://github.com/Bium23/NxLibrary/releases/latest). -2. Open it and drag **NX Library** to Applications. -3. Open the app and complete Setup. +2. Open it and drag **Arcane** to Applications. +3. Open Arcane, choose which detected sources to use, and select **Open library**. The current alpha is ad-hoc signed and not notarised. If macOS blocks first opening, use **System Settings → Privacy & Security → Open Anyway** only for a copy you built or obtained from a source you trust. -Packaged releases check this repository for app updates; no GitHub account is needed. Choose **Update** to download, verify, install and reopen NX Library while keeping your library and preferences. Automatic checks run at most once every 24 hours; **NX Library → Check for Updates…** in the macOS menu bar and **Settings → About → Check now** check immediately. Both open the same app-style dialog, with scrollable release notes and a visible result even when no update is available. Updates wait while a build, a running game or a save operation requires the app. Development builds can check public releases manually but never replace themselves. +Packaged releases check this repository for app updates; no GitHub account is needed. Choose **Update** to download, verify, install and reopen Arcane while keeping your library and preferences. Automatic checks run at most once every 24 hours; **Arcane → Check for Updates…** in the macOS menu bar and **Settings → About → Check now** check immediately. Both open the same app-style dialog, with scrollable release notes and a visible result even when no update is available. Updates wait while a build, a running game or a save operation requires the app. Development builds can check public releases manually but never replace themselves. ### First-run setup -Setup has two steps, **Get ready** and **Your games**. +On first launch, Arcane looks for installed Steam games for Mac and previously ported apps. Choose whether to include Steam and select **Open library**. Use **Settings → Library → Sources** to change your Steam source or refresh it later. Choose **Porting** on the first screen to set up local game builds with nxnative. -**Get ready** shows the engine, build tools and keys. **Install all** handles the supported steps: the engine checkout and the certified Metal compiler. The engine's tools are native, so .NET is no longer needed. Xcode itself comes from the App Store; its licence and any system prompts remain your responsibility. Choose **Continue** to proceed; incomplete build requirements can be finished later, and existing game apps remain playable. +**Get ready** shows the engine, build tools and keys. **Install all** prepares the engine checkout and certified Metal compiler. Install Xcode from the App Store and follow its licence and system prompts. Choose **Continue** to proceed. Build requirements can be completed later, and existing game apps remain playable. **Your games** shows **Game apps**: where to keep existing nxnative games (`.app`) and install new builds. It checks the selected folder before reporting an empty library. Use **Change** to choose another folder, **Choose game file** for NSP, XCI, NSZ or XCZ, or **Choose a folder instead** for a source folder, including supported extracted inputs. A single detected title opens the existing build review; multiple titles require a choice. Selecting sources never starts a build by itself. Cancelling the picker stays on this page. @@ -124,31 +120,33 @@ If games are found, **Open library** takes you to them. **Skip for now** enters The default Game apps folder is `~/Applications`; first use can prepare this default without an extra picker. Remembered or custom unavailable folders are never recreated automatically. Changing folders does not move installed apps, and a rebuild updates an existing app in its current location. A read-only folder still allows discovery and Play; installing new builds needs write access. -Discovery includes subfolders of Game apps. It stays inside the chosen folders, skips app contents and limits how far it searches. Search limits and unreadable folders are explained beside **Settings → Library → Scan game apps**, without interrupting launch. Existing library entries are kept. If several builds of a title are found, the registered app is retained while it exists; a newly discovered title uses the most recently modified build. +Discovery includes subfolders of **Game apps**, skips app contents and limits the search depth. **Settings → Porting → Library → Scan game apps** reports search limits and unreadable folders. If several builds of a title are found, Arcane keeps the registered app while it exists. For a newly discovered title, it uses the most recently modified build. -**Game files** is a separate optional folder preference in **Settings → Library**. Selecting individual files for a porting does not replace that preference or scan their siblings. Both folder choices can be changed in Settings later. +**Game files** is a separate optional folder preference in **Settings → Porting → Library**. Selecting individual files leaves that preference in place. Both folder choices can be changed later. -Import your `prod.keys` when prompted. NX Library keeps a private copy with mode `0600` and leaves the original file unchanged. Key values are not displayed or logged. +Import your `prod.keys` when prompted. Arcane keeps a private copy with mode `0600` and leaves the original file unchanged. Key values are not displayed or logged. -Reopen both setup steps from **Settings → Start-up → Open Setup** whenever needed; this keeps your library and completion state. NX Library never runs `sudo`, accepts the Xcode licence for you or changes `xcode-select`. +Reopen both setup steps from **Settings → Porting → Setup and engine → Open Setup** whenever needed; this keeps your library and completion state. Arcane never runs `sudo`, accepts the Xcode licence for you or changes `xcode-select`. -Already have a built nxnative game app? Use **Settings → Library → Scan game apps → Scan**. The same action finds existing builds and refreshes the library. Play remains available without the original sources; rebuilding requires attaching them again. +To discover existing nxnative game apps, choose **Settings → Porting → Library → Scan game apps → Scan**. Play works with the installed app. To rebuild it, attach the original sources. -If an installed app is moved or removed, its library entry stays with a blurred, locked tile and **App not found**. Restore it to its folder or change **Game apps**, then refresh the library. NX Library does not search elsewhere for it. Missing build inputs show **Game files not found** when there is no app to play. An existing app still plays when its source files are missing; only rebuilding is unavailable. To reconnect a game's moved inputs, use **Game Options → Edit details → Attach sources…**. +If an installed app is moved or removed, its library entry stays with a blurred, locked tile and **App not found**. Restore it to its folder or change **Game apps**, then refresh the library. Arcane does not search elsewhere for it. Missing build inputs show **Game files not found** when there is no app to play. An existing app still plays when its source files are missing; only rebuilding is unavailable. To reconnect a game's moved inputs, use **Game Options → Edit details → Attach sources…**. -## Using NX Library +## Using Arcane ### Your library -**Spotlight** places your games in a row of square tiles, with Play, Options and Favourite beside the selected title. Scroll down for descriptions, screenshots, activity and build information. **Collection** offers a cover-based view. +**Spotlight** places your games in a row of square tiles, with Play, Options and Favourite beside the selected title. **Collection** offers a cover-based view. Both use the same library and support a controller, keyboard or mouse. -![Game details with screenshots, a description, play activity and build information](docs/media/game-details.webp) +![A game page with screenshots, a description and play activity](docs/media/game-details.webp) -

A closer look at each game.
Artwork, play history and build details in one place.

+

A closer look at each game.
Artwork, details and play history in one place.

-Use **Find a game** for search, **Game Options** for title-specific actions, and the menu for themes, Settings and running-game controls. Hidden games can be restored under **Settings → Games → Hidden games**. +Scroll down for screenshots, the game description and **More like this** when matching titles are in your library. Steam games can show playtime and an **Achievements** card with rarity, unlocked items and crystal tiers. The animated Arcane appears when every achievement is unlocked. -When you quit a game, NX Library comes back to the front, unless you had moved to another app or another game is still open. A **session card** in the top right shows how long you played this time and in total; sessions under 10 seconds show none. Turn it off in **Settings → Games → Session card**. +Use **Find a game** for search, **Game Options** for title-specific actions, and the menu for themes, Settings and running-game controls. Hidden games can be restored under **Settings → Library → Games → Hidden games**. + +When you quit a game, Arcane comes back to the front, unless you had moved to another app or another game is still open. A **session card** in the top right shows how long you played this time and in total; sessions under 10 seconds show none. Turn it off in **Settings → Library → Games → Session card**. ![The quick menu open over Spotlight, with Theme selected](docs/media/quick-menu.webp) @@ -156,14 +154,28 @@ When you quit a game, NX Library comes back to the front, unless you had moved t ### Language and region -The unreleased hotfix adds **English, Italiano, Français, Deutsch, Español and Português (Brasil)**. **Settings → Start-up → Language & region** follows the Mac automatically or lets you choose the app language and region separately. Changes apply immediately and are remembered. The **Regional formats** setting controls only date, number and size formats; **Game options → Language** continues to control each game independently. +Arcane is available in **English, Italiano, Français, Deutsch, Español and Português (Brasil)**. **Settings → Start-up → Language & region** follows the Mac automatically or lets you choose the app language and region separately. Changes apply immediately and are remembered. **Regional formats** controls dates, numbers and sizes. **Game options → Language** controls each supported game's language. Choose a language directly from its list. Known catalog genres are translated locally, without changing the saved metadata. Descriptions from Nlib are requested in the app language when supported, with cached descriptions shared between regions using the same language. Switching language reuses available artwork and credits; when those are fresh, only the localized description is requested. English remains available when a translated description cannot be found; descriptions, mod text and release notes from external sources are not automatically translated. Personal names, metadata choices, artwork and game settings are preserved. +### Critic scores + +The last row in **Details** shows five stars, the original score out of 100 and its source. Public ratings via Wikidata work without a key; games without a verified match or usable score show **Rating unavailable**. Critic scores take priority. When neither IGDB nor Wikidata supplies one, a configured IGDB connection can show its community average, clearly labelled **User score · Users · IGDB**. Community and critic scores are never mixed. + +Optional **Settings → Online services → IGDB** accepts your own Twitch application's **Client ID** and **Client Secret**. The dialog includes five short setup steps and a direct link to register an application. **Check and save** verifies access before keeping the credentials in a private file on this Mac. The secret is hidden, and credentials are separate from ordinary settings and the Dev-profile import. **Remove** returns to the keyless source. With IGDB configured, its critic average takes priority, followed by public critic scores via Wikidata and finally the explicitly labelled IGDB user average. Cached scores remain available offline. The same general settings page contains the SteamGridDB key for game artwork; API connections are optional. + +The same optional connection adds **IGDB** proposals to **Game options → Edit details → Change metadata** for Switch, Switch 2 and Steam games. Preview descriptions, genres, developers, publishers and platform-specific release dates, then choose each field individually. Automatic and manual choices remain available. Saved proposals work offline, and IGDB descriptions keep their original language. + +**LaunchBox** and **TheGamesDB** also provide optional proposals without an API key, based on the game's title and platform. The picker explains missing or ambiguous data and allows a retry. Native Mac entries take priority, and PC alternatives are labelled. + +Use the dialog's **Developer portal** and **Setup guide** links to create your credentials. + ### Add or rebuild a game +Use this workflow for games you want to port with nxnative. Arcane discovers installed Steam games through **Settings → Library → Sources**. + 1. Open **Add game** and choose or drop a supported file or folder. -2. Review the detected base game, update and DLC. Supported source formats are NSP, XCI, NSZ and XCZ. +2. Review the detected base game, update and DLC. Arcane accepts NSP, XCI, NSZ, XCZ and Switch 2 NUP packages, plus supported source folders. 3. Check the destination, disk estimate and game options. 4. Choose **Add and port** to build, or **Add to library only** to keep the entry for later. @@ -181,47 +193,43 @@ A rebuild of a running game waits to replace its app until it closes. If compila | Where | Scope | When it applies | |---|---|---| -| **Settings → Games → New games** | Starting values for titles added later. | When a new title is added. Existing titles keep their choices. | +| **Settings → Porting → New games** | Starting values for titles added later. | When a new title is added. Existing titles keep their choices. | | **Game Options → Next launch** | The selected game. | Its next launch. | | **Game Options → Use new game defaults** | Copies the current defaults into that game once. | Its next launch. | | **Add game → Review** | The title being added or rebuilt. | That operation, including its saved language. | -| **Settings → Games → Cloud saves** | Library-wide preference, subject to advanced game configuration overrides. | Reapplied before each launch, including when Off. | +| **Settings → Porting → Cloud saves** | Library-wide preference, subject to advanced game configuration overrides. | Reapplied before each launch, including when Off. | | **Settings → Look** | The library's presentation. | The app interface; game artwork and launch-screen style have their own controls. | -Options include fullscreen, FPS target, docked mode, language, rumble, render scale, MetalFX upscaling and Metal HUD. **MetalFX upscaling** enlarges the finished picture, HUD included, to your window or screen. **Game's upscaler**, offered only by games that upscale their own picture inside the frame (such as Donkey Kong Bananza), keeps the game's own upscaler or swaps it for MetalFX's, which takes much less GPU time; both can be on. Some controls depend on the installed build's capabilities. A control being available does not guarantee that every game supports its effect. +For games built with nxnative, options can include fullscreen, FPS target, docked mode, language, rumble, render scale, MetalFX upscaling and Metal HUD. **MetalFX upscaling** enlarges the finished picture, including the HUD, to your window or screen. **Game's upscaler** is offered for games that upscale inside the frame, such as Donkey Kong Bananza. Available options depend on the installed build and game. -Settings includes **Search** and **Changed**. Group resets retain the cloud-sync choice and selected sources folder. Descriptions explain the scope; information buttons provide additional detail. - -![Settings with categories, Start-up preferences and access to Setup](docs/media/settings.webp) - -

Settings by area.
Find library, appearance, controller and start-up preferences.

+Arcane groups Settings into **General**, **Library**, **Porting** and **System**. Use **Search** to find a setting and **Changed** to review values you’ve adjusted. Group resets retain the cloud-sync choice and selected sources folder. ### Saves: back up, import, restore -Open **Game Options → Saves**, directly below Cheats. Keep the game closed during backup, import or restore. +For a ported game, open **Game Options → Saves**. Keep the game closed during backup, import or restore. | Button | What it does | |---|---| | **Open folder** | Opens the current local save in Finder. | -| **Back up now** | Creates a dated, verified copy of account and device saves. | +| **Back up now** | Creates a dated, verified copy of all local users, their registry and the device save. | | **Save type** | Selects the import destination. **User save** is the usual choice; **Device save** is for a separate device save. | -| **Import save…** | Previews an exported save folder or a dated NX Library backup before replacing anything. | +| **Import save…** | Previews an exported save folder or a dated Arcane backup before replacing anything. | | **Refresh** | Reads save and backup information again. If recovery is needed, offers **Retry recovery**. | | **Backup folder** | Opens this game's backups in Finder. The row shows the latest backup's date and time. | -**To import:** choose the folder, review the centred **From → To** preview, then confirm. NX Library backs up existing progress first and verifies the result. A successful import shows **Imported successfully**, which disappears after three seconds. +**To import:** choose the folder, review the centred **From → To** preview, then confirm. Arcane backs up existing progress first and verifies the result. A successful import shows **Imported successfully**, which disappears after three seconds. -For Ryujinx, choose the numbered game folder under `bis/user/save/`. A folder selected inside that tree is recognised too; NX Library checks its title metadata and imports the complete committed save, including all slots. For other exports, choose the folder containing the complete save. +For Ryujinx, choose the numbered game folder under `bis/user/save/`. A folder selected inside that tree is recognised too; Arcane checks its title metadata and imports the complete committed save, including all slots. For other exports, choose the folder containing the complete save. -**To restore:** choose a dated backup folder through **Import save…**. A restore reinstates both recorded destinations, including whether either one was absent. An ordinary import replaces the selected destination. +**To restore:** choose a dated backup folder through **Import save…**. A current backup restores the complete local user group, including missing destinations. Older backups restore only the primary user and device save, preserving additional users. An ordinary folder import replaces only the selected primary-user or device destination. -**Cloud sync and backups have different purposes.** Cloud sync can replace local files, so import and restore require it to be off in the effective configuration. A backup is a dated copy you manage in Finder. Save compatibility still depends on the game, platform and version; recognising the folder does not guarantee compatibility. +**Cloud sync and backups have different purposes.** Cloud sync can replace local files, so import and restore require it to be off in the effective configuration. Cloud sync covers only the primary user and device save; additional local users are protected by local backups, not by cloud sync. A backup is a dated copy you manage in Finder. Save compatibility still depends on the game, platform and version; recognising the folder does not guarantee compatibility. Interrupted replacements must recover before Play. The Saves panel reports what is blocking an operation and keeps the backup folder accessible. ### Cheats -Open **Game Options → Cheats**, then choose or drop a matching cheat file. NX Library checks the title/build information; newly imported cheats start off. Enable the master switch and the individual cheats you want, then launch the game. +For a ported game, open **Game Options → Cheats**, then choose or drop a matching cheat file. Arcane checks the title and build information. Newly imported cheats start off. Enable the master switch and the individual cheats you want, then launch the game. Changes apply at the next Play and are written only while the game is closed. An older or unrecognised engine build may require **Rebuild**. The engine's in-game panel, `⌘⇧C`, reads the same files. @@ -229,6 +237,8 @@ Cheats change values while you play, for one game version only. New items, looks ### Mods +Arcane manages file mods for games ported with nxnative. + - **Mod store.** The **Mods** card in Spotlight opens a store of the GameBanana mods that work with your games: a featured banner, the most popular, a row per category and a row per game, sorted by Popular, Most liked, Newest or Recently updated. Hide the card in **Settings → Spotlight**. - **A game's Mods band.** Each game page lists its GameBanana mods and the ones you installed. Open a mod for its images, author, version and requirements, then press **Install**; **Update** appears when the author replaces the file. If the game's GameBanana page is uncertain, the band asks once, and **Wrong game?** picks another. - **Your own mods.** File mods (a folder with `romfs` inside) go into the game's mods folder. Turn them on in the band or in **Game Options → Mods**; the order decides which mod wins when two change the same file. **Remove** moves a mod to the Trash. @@ -241,8 +251,8 @@ Mods apply at the next launch, without a rebuild. The engine reads file mods onl ### Artwork, themes and sound -- **Game Options → Edit details** changes one game's artwork or metadata. Manual artwork choices take priority over automatic images. After choosing an Icon in **Change artwork**, choose **Only here** to keep it inside NX Library or **Use on the Mac** to show it in Finder and the Dock too. This choice is available for every game, including apps with no original icon, and survives restarts and rebuilds. **Only here** restores the original app icon (or its absence) if a custom one was already applied. **Automatic** removes the personal image and uses the game's own icon, then available online artwork, while keeping your location choice. On the Icon tab, **Icon location** changes **Only here** / **Use on the Mac** at any time, including with Automatic selected. If no image is found, the app keeps the standard macOS icon and remains playable; Change artwork explains that no icon is available. The finished build log records the separate icon result. -- **Menu → Theme** chooses palettes and wallpapers. Background choices include local images, muted looping videos and optional online sources; source credits appear in the picker. +- **Game Options → Edit details** changes one game's artwork or metadata. Manual artwork choices take priority over automatic images. After choosing an Icon in **Change artwork**, choose **Only here** to keep it inside Arcane or **Use on the Mac** to show it in Finder and the Dock too. This choice is available for every game, including apps with no original icon, and survives restarts and rebuilds. **Only here** restores the original app icon (or its absence) if a custom one was already applied. **Automatic** removes the personal image and uses the game's own icon, then available online artwork, while keeping your location choice. On the Icon tab, **Icon location** changes **Only here** / **Use on the Mac** at any time, including with Automatic selected. If no image is found, the app keeps the standard macOS icon and remains playable; Change artwork explains that no icon is available. The finished build log records the separate icon result. +- **Menu → Theme** opens colors first, then backgrounds. **Arcane** keeps the original blue moonlight as the default. Optional **Arcane Crystal** and **Arcane Flow** offer fine moving light threads, with barely visible ambient light. Background choices include local images, muted looping videos and optional online sources; source credits appear in the picker. - **Settings → Look** controls wallpaper placement, sizing, brightness, game backgrounds, Reduce Motion and the Color/Monochrome app icon. - **Settings → Sound & music** controls interface cues and volume. Four interface sounds are bundled; additional sounds and wallpapers can be imported from a Selene theme folder you own. @@ -285,7 +295,8 @@ Prompts follow the connected controller and supported system remapping. **Settin | What you see | What to do | |---|---| -| **Play works, Rebuild is blocked** | Open **Settings → Engine** and inspect the gate. Existing apps and new builds have separate requirements. | +| **A Steam game is missing** | Open **Settings → Library → Sources**, verify the Steam folder, then choose **Refresh Steam**. Arcane lists supported titles installed as Mac apps. | +| **Play works, Rebuild is blocked** | Open **Settings → Porting → Setup and engine** and check Compatibility. Existing apps and new builds have separate requirements. | | **Sources detached / missing** | Use **Attach Sources…** or locate the original files. The installed app remains usable. | | **Ready build waiting to install** | Close the running game or finish the save operation, then retry the installation if prompted. | | **Import is unavailable** | Close the game, finish any active operation and follow the cloud-sync or recovery action shown in Saves. | @@ -297,8 +308,8 @@ Before reporting a problem, review copied diagnostics and remove anything person ### Compatibility and limitations -- NX Library uses a manually pinned engine and checks its commit, working tree, CLI contract and Metal compiler before new builds. It does not follow upstream `main` automatically. **Settings → Engine → Newest engine** lets you choose `main` yourself before NX Library has tested it: an orange dot marks it, builds are recorded as untested, **Update** moves to a newer `main` when there is one, **Back to tested** returns to the pinned engine, and it is not offered when `main` needs a different Metal compiler. -- The current engine is `8a5c5e7e` and certifies Metal `32023.922`. **Build anyway with an untested toolchain** requires explicit confirmation and marks the resulting build as untested. A successful launch does not turn it into a certified combination. +- Arcane uses a manually pinned engine and checks its commit, working tree, CLI contract and Metal compiler before new builds. It does not follow upstream `main` automatically. **Settings → Setup and engine → Newest engine** lets you choose `main` yourself before Arcane has tested it: an orange dot marks it, builds are recorded as untested, **Update** moves to a newer `main` when there is one, **Back to tested** returns to the pinned engine, and it is not offered when `main` needs a different Metal compiler. +- The current engine is `461a5f9f` and certifies Metal `32023.922`. **Build anyway with an untested toolchain** requires explicit confirmation and marks the resulting build as untested. A successful launch does not turn it into a certified combination. - Game compatibility depends on nxnative, the game version and the toolchain. - Output follows the window/display; native 1440p/4K internal rendering is not supported. Render scale is 50–100% where the build supports it. MetalFX is spatial upscaling. - Builds run one at a time. iOS/IPA output, automatic engine updates and notarisation are not currently provided. @@ -309,56 +320,50 @@ The [upgrade notes](docs/upstream-upgrades/README.md) record each engine review App data lives in `~/Library/Application Support/NXLibrary/`. Local game data uses `~/Library/Application Support/nxnative//`, with mods in its `mods` folder. Backups are stored under `NXLibrary/SaveBackups/<title ID>/`. -**Settings → Storage → By game** shows app, build cache and log sizes for every library entry, including hidden games, with the largest caches first. **Delete cache** permanently removes only the chosen game's build cache after confirmation. Its app, original game files, saves and logs stay in place; the next rebuild may take longer. Shared caches are identified, and their confirmation explains the effect on the other entries. Connect unavailable drives or check folder access, then choose **Recalculate**. Sizes describe file contents; actual space recovered can differ, and shared folders count once in totals. This addition is unreleased; the maintainer confirmed it works in Dev. +**Settings → Porting → Storage** shows app, build cache and log sizes for every library entry, including hidden games, with the largest caches first. **Delete cache** permanently removes only the chosen game's build cache after confirmation. Its app, original game files, saves and logs stay in place. The next rebuild may take longer. Shared cache confirmations list the other affected entries. Connect unavailable drives or check folder access, then choose **Recalculate**. Storage can also clear all build caches or logs and open the shared backups folder. Cleanup runs without blocking navigation and is unavailable during a build or app update. **Remove Sources & Build Cache deletes the selected original source files**, while retaining the installed app and saves. Read that confirmation carefully; it differs from clearing a cache. -## Next steps - -- **Simpler Settings** — Keep everyday options easy to find, with advanced controls grouped within each category. -- **In-app bug reporting** — Make it easier to report a problem directly from NX Library. -- **Broader game discovery** — Discover and launch games from Steam, CrossOver and the Mac App Store, alongside nxnative apps. -- **Community translations** — Review and extend the initial six interface languages. -- **Better controller support** — Refine controller settings and offer more flexible button mapping. -- **Continued polish** — Fix bugs and improve navigation, feedback and visual details throughout the app. - -More to come as NX Library evolves. - ## Documentation and development | Document | Contents | |---|---| | [Changelog](CHANGELOG.md) | User-visible changes and release history. | | [Development guide](docs/development.md) | Runtime preparation, debug builds, tests, packaging and releases. | -| [Screenshots and demo](docs/media/README.md) | Screenshot inventory, placement and the upcoming video. | +| [Screenshots and demo](docs/media/README.md) | Media inventory and display guidance. | | [Contributing](CONTRIBUTING.md) | Change and verification guidelines. | | [Security](SECURITY.md) | Private vulnerability reporting and handling sensitive files. | -| [Technical guide](docs/architecture.md) | Current architecture and feature flows, in Italian. | +| [Technical guide](docs/architecture.md) | How each area works today, in Italian. | +| [How to build](docs/conventions.md) | Where new code goes and the recipes to follow, in Italian. | +| [Flows](docs/flows.md) | End-to-end flows with diagrams, in Italian. | | [File catalog](docs/file-map.md) | Responsibility of every project file, in Italian. | +| [Steam](docs/steam.md) | Steam integration: files read, game states, launch, playtime, achievements, limits; in Italian. | | [Engine upgrade notes](docs/upstream-upgrades/README.md) | Pin changes and their evidence. | +If you’d like to support Arcane’s development and maintenance, you can [buy me a coffee](https://buymeacoffee.com/bium). + ## Credits and licences -NX Library is MIT licensed. It uses upstream [nxnative](https://github.com/seedds/nxnative). It began from the MIT nxnative_Launcher codebase, which has been rewritten since; that repository is no longer available and its notice stays in [NOTICE](NOTICE). Adaptations from [NX2Apple](https://github.com/LNPANDY/NX2Apple) cover key checks, failure explanations, diagnostics and updates. +Arcane is MIT licensed. It uses upstream [nxnative](https://github.com/seedds/nxnative). It began from the MIT nxnative_Launcher codebase, which has been rewritten since; that repository is no longer available and its notice stays in [NOTICE](NOTICE). Adaptations from [NX2Apple](https://github.com/LNPANDY/NX2Apple) cover key checks, failure explanations, diagnostics and updates. The interface draws from the MIT [Selene](https://github.com/mattxslv/Selene) theme. Bundled fonts, sounds, palettes and runtime components retain their own licences; see [NOTICE](NOTICE), [media notices](Resources/Selene/NOTICE.txt) and [palette notices](Resources/Selene/NOTICE-palettes.txt). -The app icon is original artwork created by the owner with AI. Its [master and generation notes](Resources/IconArtwork.md) are included. +The app icon uses original artwork. The [master and generation notes](Resources/IconArtwork.md) are included. ## Legal and third-party notices -**Project scope.** NX Library is an independent macOS frontend for organising and launching game applications. Its current nxnative integration also provides guided setup and local builds using the external nxnative toolchain. +**Project scope.** Arcane is an independent macOS game library and launcher. It supports installed Steam games for Mac and provides guided setup and local game builds through nxnative. **Games and keys.** The project does not provide games, firmware, cryptographic keys or downloadable game packages. Users must supply their own game files and keys and have the rights and permissions required to use them. Do not submit these files through issues, pull requests or support requests. -**Local processing and external services.** Game preparation uses locally supplied files and keys. NX Library checks encrypted game headers using the supplied keys and invokes nxnative to perform the build. Setup, updates and optional artwork features may contact third-party services. +**Local processing and external services.** Game preparation uses locally supplied files and keys. Arcane checks encrypted game headers using the supplied keys and invokes nxnative to perform the build. Setup, updates and optional artwork features may contact third-party services. **Permitted use.** Owning a game or console does not necessarily authorise every form of copying, decryption or conversion. Applicable rules vary by jurisdiction. This project does not grant permission to circumvent technological protections or infringe third-party rights. Do not use it to distribute game files, keys or generated packages without the necessary authorisation. -**Third-party software and content.** NX Library does not distribute proprietary Nintendo game code, game assets, firmware or cryptographic keys. Open-source dependencies and bundled resources remain subject to their respective licences and notices. Artwork retrieved from external services remains subject to its owners’ rights and the applicable service terms. +**Third-party software and content.** Arcane does not distribute proprietary Nintendo game code, game assets, firmware or cryptographic keys. Open-source dependencies and bundled resources remain subject to their respective licences and notices. Artwork retrieved from external services remains subject to its owners’ rights and the applicable service terms. -**Trademarks.** NX Library is not affiliated with, sponsored by or endorsed by Nintendo or any other game publisher or platform provider. Product names, game titles and trademarks belong to their respective owners. +**Trademarks.** Arcane is not affiliated with, sponsored by or endorsed by Nintendo or any other game publisher or platform provider. Product names, game titles and trademarks belong to their respective owners. **Rights concerns.** If you believe material distributed by this project infringes your rights, contact the maintainer with the relevant material, your rights claim and sufficient information to assess it. Substantiated concerns will be reviewed promptly and addressed as appropriate. -**No warranty.** NX Library is provided “as is”, without warranty, as described in LICENSE. Third-party components are governed by their own licences. See NOTICE for acknowledgements. +**No warranty.** Arcane is provided “as is”, without warranty, as described in LICENSE. Third-party components are governed by their own licences. See NOTICE for acknowledgements. diff --git a/Resources/AppIcon-Dark.png b/Resources/AppIcon-Dark.png index 613d2d8b..622086db 100644 Binary files a/Resources/AppIcon-Dark.png and b/Resources/AppIcon-Dark.png differ diff --git a/Resources/AppIcon-Light.png b/Resources/AppIcon-Light.png index 613d2d8b..622086db 100644 Binary files a/Resources/AppIcon-Light.png and b/Resources/AppIcon-Light.png differ diff --git a/Resources/AppIcon-Mono.png b/Resources/AppIcon-Mono.png index 64ae59fd..7cd7c72d 100644 Binary files a/Resources/AppIcon-Mono.png and b/Resources/AppIcon-Mono.png differ diff --git a/Resources/AppIcon.icns b/Resources/AppIcon.icns index a9e450bd..ff75936c 100644 Binary files a/Resources/AppIcon.icns and b/Resources/AppIcon.icns differ diff --git a/Resources/Brands/BuyMeACoffee.png b/Resources/Brands/BuyMeACoffee.png new file mode 100644 index 00000000..c18f321f Binary files /dev/null and b/Resources/Brands/BuyMeACoffee.png differ diff --git a/Resources/Brands/SteamLogo.png b/Resources/Brands/SteamLogo.png new file mode 100644 index 00000000..26d085c9 Binary files /dev/null and b/Resources/Brands/SteamLogo.png differ diff --git a/Resources/IconArtwork.md b/Resources/IconArtwork.md index f0deb638..6a3e7c53 100644 --- a/Resources/IconArtwork.md +++ b/Resources/IconArtwork.md @@ -1,27 +1,13 @@ # App icon artwork -The owner confirmed on 2026-11-01 that the original reference artwork was -created by them with AI. This master and the variants below are derived from -that owner-provided reference. - -`IconArtwork.png` is the full-bleed 1024 × 1024 square master, edited with -built-in imagegen on 2026-11-02 from the user's selected diagonal controller -artwork. The source is opaque and has no pre-rendered icon frame, transparent -padding, rounded corners, rim or external shadow. - -Design brief / final generation prompt: preserve the diagonal outlined blue -upper-left and coral lower-right controller shapes, their large controls, -four small buttons each and delicate trailing ribbons. Make the neutral -charcoal background just slightly darker than the previous version (roughly -#232426); extend it to all four square edges. Center the complete symbol -with balanced padding. No text, monogram, extra objects or icon mockup. - -Symmetry refinement (2026-11-02, built-in imagegen): align the four small -circles in each section into matching 2 × 2 grids, with equal row/column -spacing and matching diameters between blue and coral. Balance each group -and its large circle within its section, with corresponding placement -reversed between sections. Preserve the charcoal background, colored outlines -and trailing ribbons. +The owner created the original artwork with AI and provided it on +2026-11-18 as a WebP image, converted here to PNG without resizing. +`IconArtwork.png` is that full-bleed 1254 × 1254 square master: a violet, +rose and blue crystal inside a clear glass sphere, framed by a navy and a +plum ink brush stroke on light paper, with a plum ink wave inside the +sphere. The source is opaque and has +no pre-rendered icon frame, transparent padding, rounded corners, rim or +external shadow. Regenerate the Finder icon and Dock appearance resources on macOS: @@ -34,8 +20,9 @@ The generator applies the macOS silhouette to the full-bleed source: an restrained shadow. It downsamples this master into all ten standard iconset representations (16–1024 pixels), packages `AppIcon.icns`, and writes the 1024-pixel Light, Dark and Monochrome Dock resources. Light and Dark share -the charcoal tile. Monochrome preserves the geometry and alpha with a -grayscale color-space conversion. +the same tile. Monochrome preserves the geometry and alpha with a +grayscale color-space conversion. The committed resources are exactly what +this command produces from the master. Inspect the installed app in Finder and the Dock after quitting and reopening it; the running app can retain its previous icon until it restarts. diff --git a/Resources/IconArtwork.png b/Resources/IconArtwork.png index 5a2663e3..b8bf1a04 100644 Binary files a/Resources/IconArtwork.png and b/Resources/IconArtwork.png differ diff --git a/Resources/Selene/palettes.json b/Resources/Selene/palettes.json index 4fecb44e..42351852 100644 --- a/Resources/Selene/palettes.json +++ b/Resources/Selene/palettes.json @@ -451,7 +451,7 @@ }, { "id": "selene", - "name": "Default", + "name": "Arcane", "mode": "dark", "focus": 16777215, "onFocus": 1118481, @@ -573,5 +573,57 @@ } ] } + }, + { + "id": "arcane-flow", + "name": "Arcane Flow", + "mode": "dark", + "focus": 16777215, + "onFocus": 1118481, + "ink": 16777215, + "scrim": 0, + "glass": 1316895, + "glyph": 10275839, + "success": 4054148, + "base": { + "kind": "radial", + "stops": [ + { + "color": 790819, + "location": 0.0 + }, + { + "color": 395282, + "location": 1.0 + } + ] + }, + "moonlight": "flow" + }, + { + "id": "arcane-crystal", + "name": "Arcane Crystal", + "mode": "dark", + "focus": 16777215, + "onFocus": 1118481, + "ink": 16777215, + "scrim": 0, + "glass": 1316895, + "glyph": 10275839, + "success": 4054148, + "base": { + "kind": "radial", + "stops": [ + { + "color": 790819, + "location": 0.0 + }, + { + "color": 395282, + "location": 1.0 + } + ] + }, + "moonlight": "arcane" } ] diff --git a/Sources/NXLibrary/AppDelegate.swift b/Sources/NXLibrary/AppDelegate.swift index 586d85f3..83afc752 100644 --- a/Sources/NXLibrary/AppDelegate.swift +++ b/Sources/NXLibrary/AppDelegate.swift @@ -1,10 +1,38 @@ import AppKit +import NXLibraryCore +import OSLog final class AppDelegate: NSObject, NSApplicationDelegate { + private static let log = Logger(subsystem: "local.nxlibrary", category: "rename") + /// Set by the shell: true while a build, an update or a save operation still needs this bundle's path. + @MainActor static var isBusy: () -> Bool = { false } + /// Set when a helper will reopen this bundle at its current path after the app quits. + @MainActor static var relaunchScheduled = false + /// The profile's store outlives the last window so it can finish a selection write when quitting. + @MainActor static var settingsStore: AppSettingsStore? + func applicationWillFinishLaunching(_ notification: Notification) { SeleneFonts.register() } + /// A release copy still called "NX Library.app" takes its current name on its way out + /// (`AppBundleRename`); a failure is logged and never holds up quitting. + func applicationWillTerminate(_ notification: Notification) { + Self.settingsStore?.flushPendingSelection() + let bundle = Bundle.main.bundleURL + guard let target = AppBundleRename.target( + bundleURL: bundle, + isRelease: AppUpdate.installability(bundle) != .developer, + isTranslocated: bundle.standardizedFileURL.path.contains("/AppTranslocation/"), + isBusy: Self.relaunchScheduled || Self.isBusy() + ) else { return } + do { + try AppBundleRename.perform(bundleURL: bundle, to: target) + } catch { + Self.log.error("Renaming the app to \(target.lastPathComponent, privacy: .public) failed: \(error.localizedDescription, privacy: .public)") + } + } + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } diff --git a/Sources/NXLibrary/Models/NXLibraryError.swift b/Sources/NXLibrary/Models/NXLibraryError.swift index 110139a9..496ee5ea 100644 --- a/Sources/NXLibrary/Models/NXLibraryError.swift +++ b/Sources/NXLibrary/Models/NXLibraryError.swift @@ -27,7 +27,7 @@ public enum NXLibraryError: Error, LocalizedError { case .missingKeys: return L10n.text("prod.keys is missing. Import it in Settings.") case .engineMissing: - return L10n.text("The nxnative checkout was not found. Choose it in Settings → Engine.") + return L10n.text("The nxnative checkout was not found. Choose it in Settings → Setup and engine.") case .environmentBlocked(let detail): return L10n.format("The build environment is incomplete: %@", [String(describing: (detail))]) case .incompatibleToolchain(let detail): diff --git a/Sources/NXLibrary/Models/PlayedGame.swift b/Sources/NXLibrary/Models/PlayedGame.swift new file mode 100644 index 00000000..a90f0c76 --- /dev/null +++ b/Sources/NXLibrary/Models/PlayedGame.swift @@ -0,0 +1,23 @@ +import Foundation +import NXLibraryCore + +/// A game the launch screen and the session card show: an nxnative build or a Steam game. Both read the same +/// way; only where their art comes from differs (`GameArtLoader`). +enum PlayedGame: Equatable { + case nxnative(PortedGame) + case steam(CatalogGame) + + var id: UUID { + switch self { + case .nxnative(let game): return game.id + case .steam(let game): return game.id + } + } + + var name: String { + switch self { + case .nxnative(let game): return game.name + case .steam(let game): return game.name + } + } +} diff --git a/Sources/NXLibrary/NXLibraryApp.swift b/Sources/NXLibrary/NXLibraryApp.swift index 7cc83717..92af1ac2 100644 --- a/Sources/NXLibrary/NXLibraryApp.swift +++ b/Sources/NXLibrary/NXLibraryApp.swift @@ -14,8 +14,10 @@ extension Notification.Name { static let nxCollectionGamepadAction = Notification.Name("NXCollectionGamepadAction") static let nxGameOptionsGamepadAction = Notification.Name("NXGameOptionsGamepadAction") static let nxSetupCheckGamepadAction = Notification.Name("NXSetupCheckGamepadAction") + static let nxArcaneWelcomeGamepadAction = Notification.Name("NXArcaneWelcomeGamepadAction") static let nxThemePickerGamepadAction = Notification.Name("NXThemePickerGamepadAction") static let nxLibraryOpenSettings = Notification.Name("NXLibraryOpenSettings") + static let nxLibraryRetryCatalogSave = Notification.Name("NXLibraryRetryCatalogSave") static let nxLibraryOpenConsole = Notification.Name("NXLibraryOpenConsole") static let nxLibraryOpenLibrary = Notification.Name("NXLibraryOpenLibrary") static let nxLibraryOpenAddGame = Notification.Name("NXLibraryOpenAddGame") @@ -28,18 +30,9 @@ struct NXLibraryApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate @FocusedValue(\.nxMenuAvailability) private var availability @ObservedObject private var localization = AppLocalization.shared - private let settingsStore: AppSettingsStore - - init() { - let store = AppSettingsStore() - settingsStore = store - // Publish the initial locale before SwiftUI starts constructing the window graph. - AppLocalization.shared.configure(store.settings) - } - var body: some Scene { - Window("NX Library", id: "main") { - MainView(settingsStore: settingsStore) + Window(AppIdentity.name, id: "main") { + DevelopmentStartupView() } .windowStyle(.hiddenTitleBar) .defaultSize(width: 1440, height: 900) @@ -50,6 +43,12 @@ struct NXLibraryApp: App { .keyboardShortcut("n", modifiers: [.command]) .disabled(availability?.general != true) } + CommandGroup(after: .newItem) { + if availability?.catalogRecovery == true { + Button(L10n.text("Retry saving library")) { NativeMenuCommands.shared.post(.nxLibraryRetryCatalogSave) } + .keyboardShortcut("s", modifiers: [.command]) + } + } CommandGroup(after: .appInfo) { Button(L10n.text("Check for Updates…")) { NativeMenuCommands.shared.post(.nxLibraryCheckAppUpdates) } .disabled(availability?.general != true) diff --git a/Sources/NXLibrary/Services/AppUpdater.swift b/Sources/NXLibrary/Services/AppUpdater.swift index cd29c44b..4ae0a944 100644 --- a/Sources/NXLibrary/Services/AppUpdater.swift +++ b/Sources/NXLibrary/Services/AppUpdater.swift @@ -22,7 +22,7 @@ final class AppUpdater: ObservableObject { private let repository: String? private let runningVersion: String - private let defaults = UserDefaults.standard + private let defaults = AppData.preferences private var downloadSession: URLSession? private var lastRelease: AppUpdate.Release? private var shouldOfferResult = false @@ -231,9 +231,9 @@ final class AppUpdater: ObservableObject { let staged = unpacked.appendingPathComponent("NXLibrary.app") if let problem = AppUpdate.bundleProblem(staged, expectedID: expectedID, version: release.version, runningOS: runningOS) { if case .needsNewerMacOS(let minimum) = problem { - return .failure(.init(message: L10n.format("NX Library %@ needs macOS %@ or later; nothing was changed.", [String(describing: (release.version)), String(describing: (minimum))]))) + return .failure(.init(message: L10n.format("Arcane %@ needs macOS %@ or later; nothing was changed.", [String(describing: (release.version)), String(describing: (minimum))]))) } - return .failure(.init(message: L10n.format("The download is not a valid NX Library %@; nothing was changed.", [String(describing: (release.version))]))) + return .failure(.init(message: L10n.format("The download is not a valid Arcane %@; nothing was changed.", [String(describing: (release.version))]))) } guard AppUpdate.validCodeSignature(staged) else { return .failure(.init(message: L10n.text("The app signature could not be verified; nothing was changed."))) @@ -259,12 +259,13 @@ final class AppUpdater: ObservableObject { switch result { case .success(let placed): if AppUpdate.relaunch(placed) { + AppDelegate.relaunchScheduled = true NSApp.terminate(nil) } else { - self.state = .failed("NX Library \(release.version) is installed; open it again to finish.") + self.state = .failed("Arcane \(release.version) is installed; open it again to finish.") } case .failure: - self.fail("NX Library could not be replaced; the current version is unchanged.") + self.fail("Arcane could not be replaced; the current version is unchanged.") } } } @@ -276,8 +277,7 @@ final class AppUpdater: ObservableObject { } private static func workFolder() -> URL { - FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] - .appendingPathComponent("NXLibrary/Temp/Update") + AppData.supportRoot.appendingPathComponent("Temp/Update") } nonisolated private static func run(_ tool: String, _ arguments: [String]) -> Bool { diff --git a/Sources/NXLibrary/Services/GameControllerService.swift b/Sources/NXLibrary/Services/GameControllerService.swift index 70c83733..9f6186b4 100644 --- a/Sources/NXLibrary/Services/GameControllerService.swift +++ b/Sources/NXLibrary/Services/GameControllerService.swift @@ -19,7 +19,7 @@ public final class GameControllerService: ObservableObject { @Published public var deadzone: Float = 0.35 { didSet { let clamped = min(max(deadzone, 0.10), 0.80) - UserDefaults.standard.set(Double(clamped), forKey: deadzoneKey) + AppData.preferences.set(Double(clamped), forKey: deadzoneKey) } } @@ -28,8 +28,8 @@ public final class GameControllerService: ObservableObject { private var lastNavTime: TimeInterval = 0 private init() { - if UserDefaults.standard.object(forKey: deadzoneKey) != nil { - deadzone = min(max(Float(UserDefaults.standard.double(forKey: deadzoneKey)), 0.10), 0.80) + if AppData.preferences.object(forKey: deadzoneKey) != nil { + deadzone = min(max(Float(AppData.preferences.double(forKey: deadzoneKey)), 0.10), 0.80) } setupObservers() refreshControllers() diff --git a/Sources/NXLibrary/Services/LaunchReadinessProbe.swift b/Sources/NXLibrary/Services/LaunchReadinessProbe.swift index 01037251..78e47449 100644 --- a/Sources/NXLibrary/Services/LaunchReadinessProbe.swift +++ b/Sources/NXLibrary/Services/LaunchReadinessProbe.swift @@ -9,17 +9,29 @@ final class LaunchReadinessProbe { /// True once a window of `bundleID` at least 320×240 and visible is on screen; /// false on timeout or cancellation. func waitUntilVisible(bundleID: String, timeout: TimeInterval = 60) async -> Bool { + await waitUntil(timeout: timeout) { Self.hasVisibleWindow(bundleID: bundleID) } + } + + /// The same for one process: a Steam game, which Steam starts and NX Library knows by its pid. + func waitUntilVisible(pid: pid_t, timeout: TimeInterval = 60) async -> Bool { + await waitUntil(timeout: timeout) { Self.hasVisibleWindow(pids: [pid]) } + } + + private func waitUntil(timeout: TimeInterval, _ visible: () -> Bool) async -> Bool { let deadline = Date().addingTimeInterval(timeout) while Date() < deadline, !Task.isCancelled { - if Self.hasVisibleWindow(bundleID: bundleID) { return true } + if visible() { return true } try? await Task.sleep(nanoseconds: interval) } return false } static func hasVisibleWindow(bundleID: String) -> Bool { - let pids = Set(NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) - .map(\.processIdentifier)) + hasVisibleWindow(pids: Set(NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) + .map(\.processIdentifier))) + } + + static func hasVisibleWindow(pids: Set<pid_t>) -> Bool { guard !pids.isEmpty, let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { diff --git a/Sources/NXLibrary/Services/LibraryWindow.swift b/Sources/NXLibrary/Services/LibraryWindow.swift new file mode 100644 index 00000000..a9934270 --- /dev/null +++ b/Sources/NXLibrary/Services/LibraryWindow.swift @@ -0,0 +1,31 @@ +import AppKit + +/// NX Library's main window back in front after a game quits, for nxnative and Steam games alike. +@MainActor +enum LibraryWindow { + /// macOS often makes NX Library the active app by itself as a game quits, but leaves the screen on the desktop + /// while NX Library's full-screen window stays in its own Space: activating alone shows nothing. So the main + /// window is also brought forward, which takes macOS to its Space. `ignoringOtherApps: true` covers the case + /// where macOS put another app (Steam, for one) in front instead. Checked once more after the Space switch; + /// never over an app `isGame` names. + static func comeForward(unlessFront isGame: @escaping @MainActor (NSRunningApplication) -> Bool) { + bringForward(mainWindow) + Task { @MainActor in + try? await Task.sleep(nanoseconds: 600_000_000) + let window = mainWindow + guard !NSApp.isActive || window?.isOnActiveSpace == false else { return } + if let front = NSWorkspace.shared.frontmostApplication, isGame(front) { return } + bringForward(window) + } + } + + /// NX Library's main window: the visible one that can be main (not a panel or the menu bar's). + private static var mainWindow: NSWindow? { + NSApp.mainWindow ?? NSApp.windows.first { $0.isVisible && $0.canBecomeMain } + } + + private static func bringForward(_ window: NSWindow?) { + NSApp.activate(ignoringOtherApps: true) + window?.makeKeyAndOrderFront(nil) + } +} diff --git a/Sources/NXLibrary/Services/NativeMenuCommands.swift b/Sources/NXLibrary/Services/NativeMenuCommands.swift index 0a0f1853..228cc79b 100644 --- a/Sources/NXLibrary/Services/NativeMenuCommands.swift +++ b/Sources/NXLibrary/Services/NativeMenuCommands.swift @@ -6,6 +6,7 @@ struct NativeMenuAvailability { var play = false var details = false var options = false + var catalogRecovery = false } private struct NativeMenuAvailabilityKey: FocusedValueKey { diff --git a/Sources/NXLibrary/Services/NotificationService.swift b/Sources/NXLibrary/Services/NotificationService.swift index c428483e..27582568 100644 --- a/Sources/NXLibrary/Services/NotificationService.swift +++ b/Sources/NXLibrary/Services/NotificationService.swift @@ -2,6 +2,7 @@ import Foundation import UserNotifications import AppKit import NXLibraryCore +import os extension Notification.Name { /// A porting notification was clicked; userInfo carries "gameID" and "outcome" ("ready" or "failed"). @@ -11,6 +12,7 @@ extension Notification.Name { /// Sends the end-of-porting notification (`PortingNotice` decides when) and routes its click. public final class NotificationService: NSObject, UNUserNotificationCenterDelegate { public static let shared = NotificationService() + private static let log = Logger(subsystem: "local.nxlibrary", category: "notifications") private override init() { super.init() @@ -20,7 +22,7 @@ public final class NotificationService: NSObject, UNUserNotificationCenterDelega public func requestAuthorization() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { _, error in if let error = error { - print("[NotificationService] Authorization error: \(error.localizedDescription)") + Self.log.error("Notification authorization failed: \(error.localizedDescription, privacy: .public)") } } } @@ -36,7 +38,7 @@ public final class NotificationService: NSObject, UNUserNotificationCenterDelega let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil) UNUserNotificationCenter.current().add(request) { error in if let error = error { - print("[NotificationService] Failed to schedule notification: \(error)") + Self.log.error("Scheduling a notification failed: \(error.localizedDescription, privacy: .public)") } } } diff --git a/Sources/NXLibrary/Services/OnlineBackgroundService.swift b/Sources/NXLibrary/Services/OnlineBackgroundService.swift index 90ca9372..8f2219b8 100644 --- a/Sources/NXLibrary/Services/OnlineBackgroundService.swift +++ b/Sources/NXLibrary/Services/OnlineBackgroundService.swift @@ -9,7 +9,7 @@ import NXLibraryCore actor OnlineBackgroundService { static let shared = OnlineBackgroundService() - static let userAgent = "NXLibrary/0.1 (personal macOS app)" + static let userAgent = AppIdentity.userAgent() private static let spacing: [BackgroundSourceID: TimeInterval] = [.wallhaven: 60.0 / 45, .danbooru: 1, .motionbgs: 1, .steam: 1] private let session: URLSession diff --git a/Sources/NXLibrary/Services/RunningGameMonitor.swift b/Sources/NXLibrary/Services/RunningGameMonitor.swift index 6136fafc..f79ab983 100644 --- a/Sources/NXLibrary/Services/RunningGameMonitor.swift +++ b/Sources/NXLibrary/Services/RunningGameMonitor.swift @@ -142,7 +142,8 @@ final class RunningGameMonitor: ObservableObject { var comesForward = false for bundleID in ended { let others = libraryBundleIDs.intersection(tracker.running).subtracting(ended) - if focus.gameEnded(bundleID, othersRunning: !others.isEmpty) { comesForward = true } + let othersRunning = !others.isEmpty || SteamPlayCoordinator.shared.hasRunningGame + if focus.gameEnded(bundleID, othersRunning: othersRunning) { comesForward = true } for session in sessions?.end(bundleID: bundleID) ?? [] { guard let game = games.first(where: { $0.id == session.gameID }), let summary = SessionSummary(session: session, game: game, @@ -158,6 +159,11 @@ final class RunningGameMonitor: ObservableObject { private var libraryBundleIDs: Set<String> { Set(games.compactMap(\.effectiveBundleId)) } + /// The app is one of the library's nxnative games. + func isLibraryGame(_ app: NSRunningApplication) -> Bool { + app.bundleIdentifier.map(libraryBundleIDs.contains) == true + } + /// A library game in front is noted; another app that is still in front a second later, while that game runs, /// means the player left the game (an app macOS brings forward as a game quits does not count). private func activated(_ bundleID: String?) { @@ -174,33 +180,14 @@ final class RunningGameMonitor: ObservableObject { } } - /// NX Library back in front after the game in front quit. macOS often makes NX Library the active app by itself - /// as the game quits, but leaves the screen on the desktop while NX Library's full-screen window stays in its own - /// Space: activating alone shows nothing. So the main window is also brought forward, which takes macOS to its - /// Space. `ignoringOtherApps: true` covers the case where macOS put another app in front instead. Checked once - /// more after the Space switch; never over a library game. + /// NX Library back in front after the game in front quit (`LibraryWindow`), never over a library game. private func comeForward() { - Self.bringForward(Self.mainWindow) - Task { @MainActor [weak self] in - try? await Task.sleep(nanoseconds: 600_000_000) - let window = Self.mainWindow - guard let self, !NSApp.isActive || window?.isOnActiveSpace == false else { return } - if let front = NSWorkspace.shared.frontmostApplication?.bundleIdentifier, - self.libraryBundleIDs.contains(front) { return } - Self.bringForward(window) + LibraryWindow.comeForward { [weak self] app in + self?.isLibraryGame(app) == true + || SteamPlayCoordinator.shared.isRunningGame(pid: app.processIdentifier) } } - /// NX Library's main window: the visible one that can be main (not a panel or the menu bar's). - private static var mainWindow: NSWindow? { - NSApp.mainWindow ?? NSApp.windows.first { $0.isVisible && $0.canBecomeMain } - } - - private static func bringForward(_ window: NSWindow?) { - NSApp.activate(ignoringOtherApps: true) - window?.makeKeyAndOrderFront(nil) - } - private func recompute() { let ids = RunningGames.matchingIDs(in: games, runningBundleIDs: tracker?.running ?? []) if ids != runningGameIDs { runningGameIDs = ids } diff --git a/Sources/NXLibrary/Services/SteamAchievementsStore.swift b/Sources/NXLibrary/Services/SteamAchievementsStore.swift new file mode 100644 index 00000000..4df58f04 --- /dev/null +++ b/Sources/NXLibrary/Services/SteamAchievementsStore.swift @@ -0,0 +1,139 @@ +import Foundation +import NXLibraryCore + +/// The achievements of the Steam games shown, for the page's card and the Achievements screen. +/// Steam's cache is read off the main thread (`SteamAchievementReader.read`) when a game is selected, +/// when the Achievements screen opens and after a Steam session ends; Steam's public rarity follows +/// (`SteamMetadataService.achievementPercents`). Nothing is written to Steam's files, logged or kept +/// beyond the summaries in memory; the rarity and icons are cached by `SteamMetadataService`. +@MainActor +final class SteamAchievementsStore: ObservableObject { + static let shared = SteamAchievementsStore() + + /// By AppID. Missing: not read yet, no achievements, or nothing for the signed-in account. + @Published private(set) var summaries: [UInt32: AchievementSummary] = [:] + + private var root: URL? + private var language: String? + /// Bumped whenever the folder or the language changes, so a read started before is dropped. + private var generation = 0 + private var reading: Set<UInt32> = [] + private var readAgain: Set<UInt32> = [] + /// The game read last (the one on screen): the folder changing and a session ending read it again. + private var current: UInt32? + /// Games with a summary, oldest first; only the last `kept` stay, so going back to one shows it at once. + private var order: [UInt32] = [] + private static let kept = 16 + /// The last reading of each game, rebuilt into a summary when the rarity arrives. + private var latest: [UInt32: [SteamAchievement]] = [:] + /// The rarity last fetched for each game kept (`SteamMetadataService` keeps it on disk too). + private var percents: [UInt32: [String: Double]] = [:] + private var followUp: Task<Void, Never>? + + /// The Steam source's folder while it is enabled. + func setSources(_ sources: [CatalogSourceConfiguration]) { + let folder = sources.first { $0.integration == .steam && $0.isEnabled }?.rootURL + guard folder != root else { return } + root = folder + reset() + // Same game, another folder: read again what was shown. + reloadCurrent() + } + + /// Reads one game's achievements; one read per AppID at a time, a request meanwhile reads again after it. + func load(appID: UInt32, language: String) { + if language != self.language { + self.language = language + reset() + } + current = appID + guard let root else { + summaries = [:] + return + } + guard !reading.contains(appID) else { + readAgain.insert(appID) + return + } + reading.insert(appID) + let ticket = generation + Task.detached(priority: .utility) { + let achievements = (try? SteamAchievementReader.read(root: root, appID: appID, language: language)) ?? nil + await MainActor.run { [weak self] in self?.finish(appID, achievements, ticket: ticket) } + } + } + + /// Steam writes the unlock times as the game quits or a little later: read now and once more in a minute. + /// Only the game on screen: another one is read again when it is selected. + func sessionEnded() { + reloadCurrent() + followUp?.cancel() + followUp = Task { [weak self] in + try? await Task.sleep(nanoseconds: 60_000_000_000) + guard !Task.isCancelled else { return } + self?.reloadCurrent() + } + } + + func stop() { + followUp?.cancel(); followUp = nil + reset() + current = nil + } + + private func reloadCurrent() { + guard let language, let current else { return } + load(appID: current, language: language) + } + + private func reset() { + generation += 1 + reading = [] + readAgain = [] + latest = [:] + percents = [:] + order = [] + summaries = [:] + } + + private func finish(_ appID: UInt32, _ achievements: [SteamAchievement]?, ticket: Int) { + guard ticket == generation else { return } + reading.remove(appID) + defer { + if readAgain.remove(appID) != nil, let language { load(appID: appID, language: language) } + } + guard let achievements, !achievements.isEmpty else { + forget(appID) + return + } + // The counts first, with the rarity known so far; Steam's (or its cache's) answer follows. + keep(appID) + latest[appID] = achievements + summaries[appID] = AchievementSummary(achievements: achievements, percents: percents[appID] ?? [:]) + Task { [weak self] in + guard let fetched = await SteamMetadataService.shared.achievementPercents(appID: appID) else { return } + self?.apply(fetched, appID: appID, ticket: ticket) + } + } + + private func keep(_ appID: UInt32) { + order.removeAll { $0 == appID } + order.append(appID) + while order.count > Self.kept { forget(order[0]) } + } + + private func forget(_ appID: UInt32) { + order.removeAll { $0 == appID } + latest[appID] = nil + percents[appID] = nil + summaries[appID] = nil + } + + private func apply(_ fetched: [String: Double], appID: UInt32, ticket: Int) { + // The newest reading, which may have finished while Steam answered; a game forgotten since stays forgotten. + guard ticket == generation, let achievements = latest[appID] else { return } + percents[appID] = fetched + let summary = AchievementSummary(achievements: achievements, percents: fetched) + if summaries[appID] != summary { summaries[appID] = summary } + } +} diff --git a/Sources/NXLibrary/Services/SteamPlayCoordinator.swift b/Sources/NXLibrary/Services/SteamPlayCoordinator.swift new file mode 100644 index 00000000..c6628c5f --- /dev/null +++ b/Sources/NXLibrary/Services/SteamPlayCoordinator.swift @@ -0,0 +1,574 @@ +import AppKit +import Combine +import NXLibraryCore + +/// Play for Steam games and their real sessions (`SteamPlayState`). Play sends `steam://run/<AppID>` +/// to the registered Steam client only; it never opens the game's app itself. The process list is +/// read on launches, quits and the app list changing, and every 30 s for waits and heartbeats: the +/// installation's own app starts a session, its exit ends it, Steam staying open does not count. +/// The catalog is not written here; only `PlaySessionStore` is. +/// +/// Play shows the launch screen (`launchScreen`) while the game is on its way, as for an nxnative game. The screen +/// has its own window over every app (`LaunchCoverWindow`), so Steam coming forward, or macOS changing Space, +/// happens behind it and NX Library never takes the front back. The screen leaves once the game's window is up (the +/// game is brought forward), when Play ends, as soon as Steam's log says the launch waits on a question for the +/// player (`SteamLaunchQuestionWatch`), or past the wait's patience (`SteamBackgroundLaunch`: 15 s with Steam open, +/// 45 s when Play starts it); in those last two cases Steam is brought forward and the head says to check it. +/// +/// With "Keep Steam in the background", a Steam that Play starts opens with `-silent -nofriendsui`. +/// The launch cover handles visibility during startup. A Steam that was out of view before Play goes back +/// out of view when the game ends in front. +/// +/// When a game whose Play was pressed here quits while it was the app in front and no other library game is +/// open, NX Library comes back to the front (`SteamReturnFocus`, `LibraryWindow`); a game started from Steam +/// leaves the player in Steam. +@MainActor +final class SteamPlayCoordinator: ObservableObject { + static let shared = SteamPlayCoordinator() + nonisolated static let steamBundleID = "com.valvesoftware.steam" + private static let tick: TimeInterval = 30 + + @Published private(set) var states: [UUID: SteamPlayState] = [:] + /// Waits past their patience: Steam is back in view and may need the player. + @Published private(set) var late: Set<UUID> = [] + /// The launch screen of the game whose Play was pressed here; `ready` makes it leave. + struct LaunchScreen: Equatable { + let gameID: UUID + var ready = false + } + @Published private(set) var launchScreen: LaunchScreen? + /// The latest Steam session that ended, for the session card (as `RunningGameMonitor.endedSession`). + @Published private(set) var endedSession: SessionSummary? + + private var games: [CatalogGame] = [] + private var steamEnabled = false + private var sessions: PlaySessionStore? + private var settings: AppSettingsStore? + /// Background launches in progress, with whether Steam was in view before Play. + private var backgrounds: [UUID: Bool] = [:] + private var tokens: [NSObjectProtocol] = [] + /// Each running app's paths as the system gives them and resolved, by pid: resolved once while it lives. + private var canonicalProcesses: [Int32: (observed: NativeProcessObservation, canonical: NativeProcessObservation)] = [:] + private var listObservation: NSKeyValueObservation? + private var timer: Timer? + private var returnFocus = SteamReturnFocus() + /// When the coordinator began watching: a game launched before then is not a new start for Spotlight. + private var watchingSince = Date.distantPast + private var hideAgain: Task<Void, Never>? + /// Each wait's patience, set when Play hands the game to Steam. + private var patience: [UUID: TimeInterval] = [:] + /// Waits for the started game's window, for the launch screen. + private var readiness: Task<Void, Never>? + private struct PendingHandOff { + let gameID: UUID + let generation: Int + let token = UUID() + let send: () -> Void + } + private var pendingHandOff: PendingHandOff? + private var handOffDeadline: Task<Void, Never>? + /// The normal path is a callback from the ordered panel. Keep Play usable when there is no panel. + private static let coverWait: UInt64 = 1_000_000_000 + /// The library's nxnative games, set by the shell: one that is open keeps NX Library from coming forward. + weak var nativeGames: RunningGameMonitor? + /// Whether a launch screen (any game's) is on screen, set by the shell: Play waits until it has gone. + var isLaunchScreenShowing: () -> Bool = { false } + /// Steam's folder while the Steam source is enabled: its log says when a launch waits on the player. + private var steamRoot: URL? + /// The game Play last handed to Steam, read in Steam's log for a question while it is on its way + /// (`questionTimer`), off the main thread and one look at a time. + private var questionWatch: (gameID: UUID, watch: SteamLaunchQuestionWatch)? + private var questionTimer: Timer? + private var questionLooking = false + /// Bumps with each new watch, so a look still reading for an older one is dropped. + private var questionGeneration = 0 + private static let questionLook: TimeInterval = 0.5 + + /// A Steam game's own app is running. + var hasRunningGame: Bool { states.values.contains { if case .running = $0.phase { return true }; return false } } + + func isRunningGame(pid: Int32) -> Bool { + states.values.contains { $0.phase == .running(pid: pid) } + } + + func phase(of game: CatalogGame) -> SteamPlayState.Phase { states[game.id]?.phase ?? .idle } + func isRunning(_ game: CatalogGame) -> Bool { if case .running = phase(of: game) { return true }; return false } + /// One available, recognized installation in an enabled source: what Play needs. + func canPlay(_ game: CatalogGame) -> Bool { + CatalogGamePresentation(game: game, sourceEnabled: steamEnabled).launchTarget != nil + } + + /// Steam is still installing it: the first pill and A open Steam's Downloads instead of Play. + func isDownloading(_ game: CatalogGame) -> Bool { + CatalogGamePresentation(game: game, sourceEnabled: steamEnabled).isDownloading + } + + /// Opens Steam on its Downloads page; nothing without Valve's client. + func openDownloads() { + guard let client = Self.steamClientURL else { return } + NSWorkspace.shared.open([SteamPlayState.downloadsURL], withApplicationAt: client, + configuration: NSWorkspace.OpenConfiguration()) + } + + /// The A hint for a Steam game, matching the Play pill; none while Play cannot do anything. + func hint(for game: CatalogGame) -> [HintItem] { + switch phase(of: game) { + case .running: return [HintItem(.a, L10n.text("Resume"))] + case .starting: return [HintItem(.a, L10n.text("Cancel"))] + case .failed: return [HintItem(.a, L10n.text("Try again"))] + case .idle: + if isDownloading(game) { return Self.steamClientURL != nil ? [HintItem(.a, L10n.text("Steam downloads"))] : [] } + return canPlay(game) ? [HintItem(.a, L10n.text("Play"))] : [] + } + } + + /// The pill and A press: waiting cancels, anything else plays (or brings a running game forward). + func press(_ game: CatalogGame) { + // One launch at a time: the launch screen covers the library, and input reaching it changes nothing. + guard !isLaunchScreenShowing() else { return } + if case .idle = phase(of: game), isDownloading(game) { openDownloads(); return } + if case .starting = phase(of: game) { cancel(game) } else { play(game) } + } + + /// Steam is coming back for the player: the game is late and Steam may be asking for something. + func mayNeedSteam(_ game: CatalogGame) -> Bool { late.contains(game.id) } + + func start(sessions: PlaySessionStore, settings: AppSettingsStore) { + guard tokens.isEmpty else { return } + self.sessions = sessions + self.settings = settings + watchingSince = Date() + let center = NSWorkspace.shared.notificationCenter + // Launches and quits arrive through the `runningApplications` observation below, once each. + // Steam can bring itself forward while it processes steam://run. + tokens = [NSWorkspace.didActivateApplicationNotification, NSWorkspace.didUnhideApplicationNotification].map { name in + center.addObserver(forName: name, object: nil, queue: .main) { [weak self] note in + let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication + let pid = app?.processIdentifier + let isSteam = app?.bundleIdentifier == Self.steamBundleID + Task { @MainActor in + // Steam may be coming forward to ask something: look in its log at once. + if isSteam { self?.lookForQuestion() } + if name == NSWorkspace.didActivateApplicationNotification { self?.activated(pid: pid, isSteam: isSteam) } + } + } + } + listObservation = NSWorkspace.shared.observe(\.runningApplications) { [weak self] _, _ in + Task { @MainActor in self?.refresh() } + } + timer = Timer.scheduledTimer(withTimeInterval: Self.tick, repeats: true) { [weak self] _ in + Task { @MainActor in self?.refresh(heartbeat: true) } + } + refresh() + } + + func stop() { + let center = NSWorkspace.shared.notificationCenter + for token in tokens { center.removeObserver(token) } + tokens = [] + listObservation?.invalidate(); listObservation = nil + timer?.invalidate(); timer = nil + // A later start re-reads the processes: `RunningGameMonitor.start` closes open Steam sessions + // at their last heartbeat, and a game still running must start a new one, not stay "running". + states = [:] + canonicalProcesses = [:] + returnFocus = SteamReturnFocus() + hideAgain?.cancel(); hideAgain = nil + readiness?.cancel(); readiness = nil + handOffDeadline?.cancel(); handOffDeadline = nil + pendingHandOff = nil + stopWatchingQuestions() + // A screen still up leaves the usual way before the wait is forgotten. + if launchScreen?.ready == false { launchScreen?.ready = true } + launchScreen = nil + patience = [:] + sessions = nil + settings = nil + if backgrounds.values.contains(true) { Self.showSteam() } + backgrounds = [:] + late = [] + } + + /// The catalog changed. A game no longer in it keeps its session until its process ends. + func setGames(_ all: [CatalogGame], sources: [CatalogSourceConfiguration]) { + games = all.filter { $0.integration == .steam } + steamEnabled = sources.contains { $0.integration == .steam && $0.isEnabled } + steamRoot = sources.first { $0.integration == .steam && $0.isEnabled }?.rootURL + refresh() + } + + /// The registered handler of steam:// URLs, when it is Valve's Steam client. + static var steamClientURL: URL? { + guard let probe = URL(string: "steam://"), + let handler = NSWorkspace.shared.urlForApplication(toOpen: probe), + Bundle(url: handler)?.bundleIdentifier == steamBundleID else { return nil } + return handler + } + + func play(_ game: CatalogGame) { + // A game that quit since the last notification is not resumed: read the processes first. + refresh() + let presentation = CatalogGamePresentation(game: game, sourceEnabled: steamEnabled) + let client = Self.steamClientURL + var state = states[game.id] ?? SteamPlayState() + let request = state.requestPlay(target: presentation.launchTarget, clientAvailable: client != nil, now: Date()) + states[game.id] = state + switch request { + case .resume(let pid): + if let app = NSRunningApplication(processIdentifier: pid) { RunningGameMonitor.activate(app) } + case .handOff(let url, let generation): + guard let client else { return } + returnFocus.playPressed(game.id) + hideAgain?.cancel(); hideAgain = nil + // Steam gets the request in the background: NX Library stays in front until the game's + // own window appears, instead of Steam's library flashing up in between. + let configuration = NSWorkspace.OpenConfiguration() + configuration.activates = false + let id = game.id + let background = settings?.settings.steamInBackground ?? false + let steam = Self.steamApplication + // Launch arguments reach only a Steam that this request starts. + configuration.arguments = SteamBackgroundLaunch.arguments(enabled: background, steamRunning: steam != nil) + late.remove(id) + let wait = SteamBackgroundLaunch.patience(steamWasRunning: steam != nil) + patience[id] = wait + readiness?.cancel(); readiness = nil + prepareHandOff(for: id, generation: generation) { [weak self] in + guard let self else { return } + self.watchQuestions(for: game) + Timer.scheduledTimer(withTimeInterval: wait + 0.5, repeats: false) { [weak self] _ in + Task { @MainActor in self?.followBackground() } + } + if background { + self.backgrounds[id] = self.backgrounds[id] ?? (steam.map { !$0.isHidden } ?? false) + } + self.followBackground() + NSWorkspace.shared.open([url], withApplicationAt: client, configuration: configuration) { [weak self] _, error in + let accepted = error == nil + Task { @MainActor in self?.finishHandOff(id, accepted: accepted, generation: generation) } + } + } + case .wait, .refuse: + break + } + } + + private func prepareHandOff(for id: UUID, generation: Int, send: @escaping () -> Void) { + let request = PendingHandOff(gameID: id, generation: generation, send: send) + pendingHandOff = request + handOffDeadline?.cancel() + handOffDeadline = Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: Self.coverWait) + guard !Task.isCancelled, let self, self.pendingHandOff?.token == request.token else { return } + self.submitHandOff(for: id, reason: "cover deadline") + } + LaunchCoverTrace.event("Steam Play waiting for cover") + launchScreen = LaunchScreen(gameID: id) + } + + func launchCoverPrepared(for id: UUID) { + submitHandOff(for: id, reason: "cover prepared") + } + + private func submitHandOff(for id: UUID, reason: String) { + guard let request = pendingHandOff, request.gameID == id else { return } + pendingHandOff = nil + handOffDeadline?.cancel(); handOffDeadline = nil + guard let state = states[id], state.generation == request.generation, case .starting = state.phase else { return } + LaunchCoverTrace.event("Steam hand-off: \(reason)") + request.send() + } + + /// Stop waiting, or dismiss a failure. A game already running is not touched. + func cancel(_ game: CatalogGame) { + guard var state = states[game.id] else { return } + if pendingHandOff?.gameID == game.id { + pendingHandOff = nil + handOffDeadline?.cancel(); handOffDeadline = nil + } + state.cancel(); states[game.id] = state + if !isRunning(game) { returnFocus.playAbandoned(game.id) } + followBackground() + } + + private func finishHandOff(_ id: UUID, accepted: Bool, generation: Int) { + guard var state = states[id] else { return } + state.handoffFinished(accepted: accepted, generation: generation) + states[id] = state + refresh() + } + + private func refresh(heartbeat: Bool = false) { + // Before `start` there is no session store: a game seen now would turn "running" with no session. + guard sessions != nil else { return } + // The list drops an app when it quits (no `isTerminated` round trip to LaunchServices per app), and a pid's + // paths are resolved once while it lives. + var resolved: [Int32: NativeProcessObservation] = [:] + let processes = NSWorkspace.shared.runningApplications.map { app -> NativeProcessObservation in + let pid = app.processIdentifier + let observed = NativeProcessObservation(pid: pid, bundleURL: app.bundleURL, executableURL: app.executableURL) + let process = canonicalProcesses[pid].flatMap { $0.observed == observed ? $0.canonical : nil } ?? observed.canonical() + canonicalProcesses[pid] = (observed, process) + resolved[pid] = process + return process + } + canonicalProcesses = canonicalProcesses.filter { resolved[$0.key] != nil } + let now = Date() + var next = states + var ended: [UUID] = [] + let followed = Set(games.map(\.id)).union(states.keys) + for id in followed { + let game = games.first { $0.id == id } + let app = game?.steamGame?.firstAvailableInstallation?.primaryApplication + var state = next[id] ?? SteamPlayState() + switch state.observe(processes, application: app, now: now) { + case .started(let pid): + if let appID = game?.steamGame?.appID { + // A game already running when NX Library began watching (a relaunch) keeps its Spotlight place. + let launched = NSRunningApplication(processIdentifier: pid)?.launchDate + let isNew = launched.map { $0 >= watchingSince } ?? true + sessions?.start(gameID: id, sourceID: "steam-\(appID)", announces: isNew) + } + // The game may have come forward before its process was seen. + if NSWorkspace.shared.frontmostApplication?.processIdentifier == pid { returnFocus.gameCameForward(id) } + case .ended: + for session in sessions?.end(gameID: id) ?? [] { + guard let game, let sessions, + let summary = SessionSummary(session: session, game: game, + total: sessions.totalDuration(for: id)) else { continue } + endedSession = summary + } + ended.append(id) + case nil: + if heartbeat, case .running = state.phase { sessions?.heartbeat(for: id) } + } + if case .failed = state.phase { returnFocus.playAbandoned(id) } + if state.phase == .idle, game == nil { next[id] = nil } else { next[id] = state } + } + if next != states { states = next } + // Quits are judged once every game's state is known, so two games quitting together see each other gone. + if !ended.isEmpty { + SteamPlaytimeCoordinator.shared.sessionEnded() + SteamAchievementsStore.shared.sessionEnded() + } + for id in ended { gameEnded(id) } + followBackground() + } + + // MARK: - Back to NX Library + + /// NX Library comes back for a game played from it that was in front with no other library game open. A Steam + /// that was out of view before Play goes back out of view, unless the player had left the game (for Steam + /// itself, say). + private func gameEnded(_ id: UUID) { + let othersRunning = nativeGames?.runningGameIDs.isEmpty == false || hasRunningGame + let ending = returnFocus.gameEnded(id, othersRunning: othersRunning) + if ending.returnsToLibrary { comeBack() } + if ending.wasInFront, settings?.settings.steamInBackground == true, backgrounds[id] == false { hideSteamAgain() } + } + + /// A Steam game came to the front, or another app stayed in front a second later while it ran: the player left + /// the game (an app macOS brings forward as a game quits does not count). Steam coming forward while the launch + /// screen waits is left alone: the screen's own window stays over it. + private func activated(pid: Int32?, isSteam: Bool) { + if let pid, let id = states.first(where: { $0.value.phase == .running(pid: pid) })?.key { + returnFocus.gameCameForward(id) + return + } + guard let game = returnFocus.gameInFront, case .running(let gamePID) = phase(ofID: game) else { return } + Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: 1_000_000_000) + guard let self, self.phase(ofID: game) == .running(pid: gamePID), + NSWorkspace.shared.frontmostApplication?.processIdentifier != gamePID else { return } + self.returnFocus.otherAppStayedForward(whileRunning: game) + } + } + + private func phase(ofID id: UUID) -> SteamPlayState.Phase { states[id]?.phase ?? .idle } + + private func comeBack() { + LibraryWindow.comeForward { [weak self] app in + guard let self else { return false } + return self.isRunningGame(pid: app.processIdentifier) || self.nativeGames?.isLibraryGame(app) == true + } + } + + // MARK: - Keep Steam in the background + + private static var steamApplication: NSRunningApplication? { + NSRunningApplication.runningApplications(withBundleIdentifier: steamBundleID).first { !$0.isTerminated } + } + + /// A Steam that was out of view before Play goes back out of view once the game quits: now, and once more + /// when Steam shows its own window a moment later. Steam putting itself in front as the game quits is Steam's + /// doing, not the player's, so it is hidden even then. A new Play or `stop` cancels the second look. + private func hideSteamAgain() { + let hide = { + guard let steam = Self.steamApplication, !steam.isHidden else { return } + steam.hide() + } + hide() + hideAgain?.cancel() + hideAgain = Task { @MainActor in + try? await Task.sleep(nanoseconds: 2_000_000_000) + guard !Task.isCancelled else { return } + hide() + } + } + + private static func showSteam() { + // Shown, not brought forward: NX Library or the game keeps the focus. + if let steam = steamApplication, steam.isHidden { steam.unhide() } + } + + // MARK: - Launch screen + + /// The launch screen for `gameID` closed (it faded, the player dismissed it, or it never showed). One the player + /// dismissed while the game was still on its way may have covered a Space change to Steam: NX Library comes + /// forward, unless a game is in front. Applied after the current publish: a value set while `launchScreen` is + /// being published is overwritten by it. + func launchScreenClosed(_ gameID: UUID) { + DispatchQueue.main.async { [weak self] in + guard let self, let screen = self.launchScreen, screen.gameID == gameID else { return } + self.launchScreen = nil + self.submitHandOff(for: gameID, reason: "cover dismissed") + self.readiness?.cancel(); self.readiness = nil + if !screen.ready, !NSApp.isActive || NSApp.mainWindow?.isOnActiveSpace == false { self.comeBack() } + } + } + + /// Reads Steam's log for a question about `game`'s launch for as long as it is on its way, launch screen or not. + private func watchQuestions(for game: CatalogGame) { + stopWatchingQuestions() + guard let appID = game.steamGame?.appID, let steamRoot else { return } + questionWatch = (game.id, SteamLaunchQuestionWatch(appID: appID, steamRoot: steamRoot)) + questionTimer = Timer.scheduledTimer(withTimeInterval: Self.questionLook, repeats: true) { [weak self] _ in + Task { @MainActor in self?.lookForQuestion() } + } + lookForQuestion() + } + + private func stopWatchingQuestions() { + questionTimer?.invalidate(); questionTimer = nil + questionWatch = nil + questionGeneration += 1 + } + + /// Reads Steam's log off the main thread (the first look takes up to a megabyte). + private func lookForQuestion() { + guard let watching = questionWatch else { return } + guard case .starting = phase(ofID: watching.gameID) else { return stopWatchingQuestions() } + guard !questionLooking else { return } + questionLooking = true + let generation = questionGeneration + Task.detached(priority: .userInitiated) { [weak self] in + var watch = watching.watch + let asks = watch.look(now: Date()) + await self?.looked(watch, asks: asks, generation: generation) + } + } + + /// Steam waits on the player for the game on its way: Steam is handed the wait at once. + private func looked(_ watch: SteamLaunchQuestionWatch, asks: Bool, generation: Int) { + questionLooking = false + guard generation == questionGeneration, let gameID = questionWatch?.gameID else { return } + questionWatch = (gameID, watch) + guard asks, case .starting = phase(ofID: gameID) else { return } + stopWatchingQuestions() + handToSteam(gameID, reason: "Steam is waiting for a response") + } + + /// Steam may need the player for this wait: it stops being kept away, is shown, and the head says to check it. + /// While the game's launch screen waits, Steam is also brought forward and the screen leaves; a player who + /// dismissed the screen is left where they are. + private func handToSteam(_ id: UUID, reason: String) { + late.insert(id) + backgrounds[id] = nil + Self.showSteam() + guard var screen = launchScreen, screen.gameID == id, !screen.ready else { return } + LaunchCoverTrace.event("Cover yields to Steam: \(reason)") + if let steam = Self.steamApplication { RunningGameMonitor.activate(steam) } + screen.ready = true + launchScreen = screen + } + + /// Moves the launch screen on: the game started (it leaves once the window is up), Steam is late (Steam is + /// shown and, while the player waits in NX Library, brought forward) or Play ended. + private func followLaunchScreen(now: Date) { + guard var screen = launchScreen, !screen.ready else { return } + let id = screen.gameID + let phase = phase(ofID: id) + switch SteamBackgroundLaunch.launchScreen(phase: phase, now: now, + patience: patience[id] ?? SteamBackgroundLaunch.attentionDelay) { + case .waiting: + return + case .gameStarted: + if case .running(let pid) = phase { watchWindow(of: id, pid: pid) } + return + case .late: + handToSteam(id, reason: "launch wait reached its limit") + return + case .over: + break + } + screen.ready = true + launchScreen = screen + } + + /// Once the started game's window is on screen, the game comes forward and the launch screen leaves; after + /// 60 s without a window the screen leaves anyway, as for an nxnative game. + private func watchWindow(of id: UUID, pid: Int32) { + guard readiness == nil else { return } + // Every process of the game's app counts, as for an nxnative game: its window may belong to another one. + let bundleID = NSRunningApplication(processIdentifier: pid)?.bundleIdentifier + readiness = Task { @MainActor [weak self] in + let visible = if let bundleID { + await LaunchReadinessProbe().waitUntilVisible(bundleID: bundleID) + } else { + await LaunchReadinessProbe().waitUntilVisible(pid: pid) + } + guard !Task.isCancelled, let self, self.launchScreen?.gameID == id else { return } + if visible { + SoundEffectService.shared.play(.gameReady) + if let app = NSRunningApplication(processIdentifier: pid) { RunningGameMonitor.activate(app) } + } + self.launchScreen?.ready = true + self.readiness = nil + } + } + + /// Shows Steam when a launch is late and restores previously visible Steam when Play is over. + /// The launch cover handles the wait. Hiding Steam here would compete with Steam reopening its own + /// windows and repeatedly switch between the desktop and the fullscreen library. + private func followBackground(now: Date = Date()) { + for (id, wasVisible) in backgrounds { + let phase = states[id]?.phase ?? .idle + switch phase { + case .starting: + let wait = patience[id] ?? SteamBackgroundLaunch.attentionDelay + if SteamBackgroundLaunch.mayNeedPlayer(phase: phase, now: now, patience: wait) { + backgrounds[id] = nil + late.insert(id) + Self.showSteam() + } + case .running: + break + case .idle, .failed: + backgrounds[id] = nil + if wasVisible { Self.showSteam() } + } + } + let waiting = Set(states.compactMap { id, state -> UUID? in + if case .starting = state.phase { return id } else { return nil } + }) + // Any wait Play started here is late past its patience, whether or not Steam is kept in the background or + // the launch screen is still up: the head then says to check Steam. + for (id, wait) in patience + where SteamBackgroundLaunch.mayNeedPlayer(phase: phase(ofID: id), now: now, patience: wait) { + late.insert(id) + } + if !late.isSubset(of: waiting) { late.formIntersection(waiting) } + patience = patience.filter { waiting.contains($0.key) || launchScreen?.gameID == $0.key } + followLaunchScreen(now: now) + } +} diff --git a/Sources/NXLibrary/Services/SteamPlaytimeCoordinator.swift b/Sources/NXLibrary/Services/SteamPlaytimeCoordinator.swift new file mode 100644 index 00000000..32432b85 --- /dev/null +++ b/Sources/NXLibrary/Services/SteamPlaytimeCoordinator.swift @@ -0,0 +1,91 @@ +import Foundation +import NXLibraryCore + +/// Steam's own playtime for the catalog's Steam games, handed to `PlaySessionStore` as external totals. +/// Steam's file is read off the main thread (`SteamPlaytimeReading.take`) when the catalog or its sources +/// change, when NX Library becomes active and after a Steam session ends, and parsed only when its +/// modification date moved. `SteamPlaytimeReadQueue` keeps one read at a time; `SteamPlaytimeSync` decides +/// what each reading does. Baselines are written off the main thread, in order. Steam's files are never written. +@MainActor +final class SteamPlaytimeCoordinator { + static let shared = SteamPlaytimeCoordinator() + + private var sessions: PlaySessionStore? + private var games: [CatalogGame] = [] + private var root: URL? + private var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines( + fileURL: AppData.supportRoot.appendingPathComponent("integrations/steam/playtime-baselines.json"))) + private var queue = SteamPlaytimeReadQueue() + private let saving = DispatchQueue(label: "NXLibrary.SteamPlaytime.save", qos: .utility) + private var followUp: Task<Void, Never>? + + /// Before any Steam session can start, so trimming already knows each game's last value. + func start(sessions: PlaySessionStore) { + self.sessions = sessions + sessions.setTrimReferences(sync.baselines.references(for: games)) + refresh() + } + + func stop() { + sessions = nil + queue.stop() + followUp?.cancel(); followUp = nil + } + + /// Steam games only, and the Steam source's folder while it is enabled. + func setGames(_ all: [CatalogGame], sources: [CatalogSourceConfiguration]) { + games = all.filter { $0.integration == .steam } + let folder = sources.first { $0.integration == .steam && $0.isEnabled }?.rootURL + if folder != root { + root = folder + sync.resetStamp() + queue.invalidate() + } + sessions?.setTrimReferences(sync.baselines.references(for: games)) + refresh() + } + + /// Steam may write its new total as the game quits or a little later: read now and once more in a minute. + func sessionEnded() { + refresh() + followUp?.cancel() + followUp = Task { [weak self] in + try? await Task.sleep(nanoseconds: 60_000_000_000) + guard !Task.isCancelled else { return } + self?.refresh() + } + } + + func refresh() { + guard let sessions else { return } + guard let root else { + sessions.setExternal([:]) + return + } + guard let ticket = queue.request() else { return } + let known = sync.stamp + Task.detached(priority: .utility) { + let result = SteamPlaytimeReading.take(root: root, known: known) + await MainActor.run { [weak self] in self?.finish(result, ticket: ticket) } + } + } + + private func finish(_ result: SteamPlaytimeReading, ticket: Int) { + let step = queue.finish(ticket) + if step.apply, let sessions { + let outcome = sync.handle(result, games: games, shownTotal: { sessions.totalDuration(for: $0, with: $1) }, now: Date()) + switch outcome { + case .clear: + sessions.setExternal([:]) + case .publish(let totals, let save): + if save { + let baselines = sync.baselines + saving.async { try? baselines.save() } + } + sessions.setExternal(totals) + } + sessions.setTrimReferences(sync.baselines.references(for: games)) + } + if step.readAgain { refresh() } + } +} diff --git a/Sources/NXLibrary/ViewModels/AchievementsScreenModel.swift b/Sources/NXLibrary/ViewModels/AchievementsScreenModel.swift new file mode 100644 index 00000000..0c3673a6 --- /dev/null +++ b/Sources/NXLibrary/ViewModels/AchievementsScreenModel.swift @@ -0,0 +1,167 @@ +import SwiftUI +import NXLibraryCore + +/// The open Achievements screen: its selection and its list's scroll. A reference Spotlight keeps while the +/// screen is open, so a step or a scroll redraws the screen (or just its list), never the page beneath. +@MainActor +final class AchievementsScreenModel: ObservableObject { + @Published private(set) var state: AchievementsScreenState + let scroll = ListScroll() + + /// The list's geometry in points and the room kept clear above and below the focused row, from the view. + private var layout: GridListLayout? + private var above: CGFloat = 0 + private var below: CGFloat = 0 + private var animates = true + /// The wheel moved the list since the last arrow or click: only then can the focus be out of view. + private var wheeled = false + + init(ids: [String]) { + state = AchievementsScreenState(ids: ids) + } + + enum Outcome { case ignored, moved, filtered, ordered, opened, closedDetail, close } + + /// The arrows move through the list, LB/RB switch the filter, Y the order, A opens the focused achievement, B closes; + /// with the detail open, the arrows step it through the list and A or B close it. The host swallows the rest. + func handle(_ action: GamepadAction, summary: AchievementSummary) -> Outcome { + if state.isDetailOpen { + switch action { + case .navigateUp, .navigateLeft: return move(.up) ? .moved : .ignored + case .navigateDown, .navigateRight: return move(.down) ? .moved : .ignored + case .confirm, .cancel: + closeDetail() + return .closedDetail + default: return .ignored + } + } + switch action { + case .confirm: return openDetail() ? .opened : .ignored + case .contextAction: + cycleOrder(summary: summary) + return .ordered + case .navigateLeft: return move(.left) ? .moved : .ignored + case .navigateRight: return move(.right) ? .moved : .ignored + case .navigateUp: return move(.up) ? .moved : .ignored + case .navigateDown: return move(.down) ? .moved : .ignored + case .tabPrevious, .tabNext: + shiftFilter(by: action == .tabPrevious ? -1 : 1, summary: summary) + return .filtered + case .cancel: return .close + default: return .ignored + } + } + + /// The list's size, from the view whenever it or the canvas changes. + func setLayout(_ layout: GridListLayout, visible: CGFloat, above: CGFloat, below: CGFloat, animates: Bool) { + self.layout = layout + self.above = above + self.below = below + self.animates = animates + scroll.setLayout(content: layout.contentHeight(count: state.count), visible: visible) + } + + /// After the wheel the focused row may be out of view: the first arrow brings the focus to the nearest + /// row in view instead of moving on from one the player can't see. + @discardableResult + func move(_ direction: AchievementsScreenState.MoveDirection) -> Bool { + var next = state + let afterWheel = wheeled + wheeled = false + if afterWheel, let layout, let nearest = layout.nearestVisible(index: next.index, count: next.count, + offset: scroll.state.offset, visible: scroll.state.visible, + above: above, below: below) { + next.index = nearest + } else if !next.move(direction) { + return false + } + state = next + reveal() + return true + } + + /// The focused achievement's detail, over the list. + @discardableResult + func openDetail() -> Bool { + var next = state + guard next.openDetail() else { return false } + state = next + return true + } + + func closeDetail() { + var next = state + next.closeDetail() + state = next + } + + /// The wheel or the trackpad (positive shows more below); the list stays still under an open detail. + func wheel(by delta: CGFloat, animated: Bool) { + guard !state.isDetailOpen else { return } + if scroll.scroll(by: delta, animated: animated) { wheeled = true } + } + + /// A click on a row. + func focus(_ index: Int) { + wheeled = false + guard index != state.index, (0..<state.count).contains(index) else { return } + var next = state + next.index = index + state = next + reveal() + } + + func setFilter(_ filter: AchievementFilter, summary: AchievementSummary) { + var next = state + next.setFilter(filter, ids: summary.rows(filter, order: next.order).map(\.id)) + filterChanged(next) + } + + func shiftFilter(by delta: Int, summary: AchievementSummary) { + var next = state + let order = next.order + next.shiftFilter(by: delta) { summary.rows($0, order: order).map(\.id) } + filterChanged(next) + } + + /// Y: the next order, from the top. + func cycleOrder(summary: AchievementSummary) { + var next = state + let filter = next.filter + next.cycleOrder { summary.rows(filter, order: $0).map(\.id) } + filterChanged(next) + } + + /// A re-read while the screen is open: the selection stays on its achievement, and the list follows it when + /// a new order moved it (a fresh unlock goes to the top); it was left out of view until the next arrow jumped there. + func setIDs(_ ids: [String]) { + var next = state + next.setIDs(ids) + guard next != state else { return } + let moved = next.index != state.index + state = next + relayout() + if moved { + wheeled = false + reveal() + } + } + + /// A new filter or order opens at its top, at once: a glide across a different list would show rows that are gone. + private func filterChanged(_ next: AchievementsScreenState) { + wheeled = false + state = next + scroll.reset() + relayout() + } + + private func relayout() { + guard let layout else { return } + scroll.setLayout(content: layout.contentHeight(count: state.count), visible: scroll.state.visible) + } + + private func reveal() { + guard let layout, state.count > 0 else { return } + scroll.reveal(layout.revealSpan(of: state.index, above: above, below: below), animated: animates) + } +} diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift b/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift index eab4b3ea..788e3944 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift @@ -11,7 +11,7 @@ extension AppViewModel { static let appIconWriter = AppIconWriter() static let automaticIconArtwork = ArtworkStore() - private func iconKey(_ game: PortedGame) -> String { game.titleId ?? game.uniqueKey } + private func iconKey(_ game: PortedGame) -> String { personalizationKey(for: game) } /// Resolve the image independently of whether the player wants it applied to the Mac app. func automaticIconURL(for game: PortedGame) async -> URL? { @@ -69,6 +69,7 @@ extension AppViewModel { /// The pop-up's answer: show the player's Icon on the app too, or keep the game's own. public func setUsesPickedAppIcon(_ use: Bool, for game: PortedGame) { + guard authorizeDevelopmentOperation(.icon, game: game) else { return } updateAppIconState(game) { $0.usesPickedAppIcon = use $0.appIconOnMac = use @@ -79,6 +80,7 @@ extension AppViewModel { /// Automatic removes the personal image without changing the player's destination choice. public func appIconPickChanged(for game: PortedGame, removed: Bool) { + guard authorizeDevelopmentOperation(.icon, game: game) else { return } updateAppIconState(game) { if removed { $0.useAutomaticAppIcon() } $0.appIconPending = true @@ -89,6 +91,7 @@ extension AppViewModel { /// After a library scan: an app whose icon differs from what the rule wants (a pick chosen while the app was /// elsewhere or missing, an app moved or built again, a change lost to a crash) is put right. public func reconcileAppIcons() { + guard !AppData.profile.isDevelopment else { return } for game in libraryGames where !game.appIconPending && !appIconsInFlight.contains(game.id) { guard let app = installedApp(game) else { continue } let writer = Self.appIconWriter @@ -107,6 +110,7 @@ extension AppViewModel { /// the same app is being signed runs again once that finishes, so the last choice wins. public func syncPendingAppIcons() { for game in libraryGames where game.appIconPending { + guard developmentOperations.permits(.icon, gameID: game.id) else { continue } guard !appIconsInFlight.contains(game.id) else { appIconRerun.insert(game.id) continue @@ -178,15 +182,8 @@ extension AppViewModel { } private func updateAppIconState(_ game: PortedGame, _ change: (inout PortedGame) -> Void) { - guard var library = try? libraryStore.load(), - let index = library.games.firstIndex(where: { $0.id == game.id }) else { return } - change(&library.games[index]) - guard (try? libraryStore.save(library)) != nil else { return } - if let shown = libraryGames.firstIndex(where: { $0.id == game.id }) { - libraryGames[shown].usesPickedAppIcon = library.games[index].usesPickedAppIcon - libraryGames[shown].appIconOnMac = library.games[index].appIconOnMac - libraryGames[shown].appIconPending = library.games[index].appIconPending - } + do { applyCatalog(try catalogRepository.updateNXNative(id: game.id, change)) } + catch { reportCatalogFailure(error) } } /// Finder and the Dock read icons through Launch Services, which caches them by the bundle's date. diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+Catalog.swift b/Sources/NXLibrary/ViewModels/AppViewModel+Catalog.swift new file mode 100644 index 00000000..1bd41ba9 --- /dev/null +++ b/Sources/NXLibrary/ViewModels/AppViewModel+Catalog.swift @@ -0,0 +1,51 @@ +import NXLibraryCore + +extension AppViewModel { + func personalizationKey(for game: PortedGame) -> String { personalizations.nxnativeKey(for: game) } + + /// One reported failure, with a reload action instead of saving displayed + /// rows over an unreadable or newer catalog. Build retries keep their result. + func reportCatalogFailure(_ error: Error) { + logs.append(LogEntry(level: .error, message: error.localizedDescription)) + showSettingsNotice(title: L10n.text("Library not saved"), message: error.localizedDescription, + retry: { [weak self] in self?.reloadCatalog() }) + } + + func reloadCatalog() { + do { applyCatalog(try catalogRepository.load()) } + catch { reportCatalogFailure(error) } + } + + @discardableResult + func persistBuildOutcome(_ game: PortedGame, retrying: Bool = false) -> Bool { + if retrying { + guard !isBuilding, catalogBuildRecoveries[game.id] == game else { + reportCatalogFailure(CatalogStoreError.staleRevision) + return false + } + } else { catalogBuildRecoveries.retain(game) } + do { + applyCatalog(try catalogRepository.recordNXNativeBuild(game)) + catalogBuildRecoveries.acknowledge(id: game.id, matching: game) + return true + } catch { + logs.append(LogEntry(level: .error, message: error.localizedDescription)) + if game.pendingInstall != nil { + presentInstallFailure(for: game, error: error.localizedDescription) + return false + } + showSettingsNotice(title: L10n.text("Library not saved"), + message: L10n.text("The build result is kept for this session. Free space if needed, then retry saving before closing Arcane."), + retry: { [weak self] in _ = self?.persistBuildOutcome(game, retrying: true) }) + return false + } + } + + func retrySavingBuildResults() { + guard !isBuilding else { return } + for result in catalogBuildRecoveries.values { + if !persistBuildOutcome(result, retrying: true) { break } + } + } + +} diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift b/Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift index 85290498..a1da9993 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift @@ -96,7 +96,7 @@ extension AppViewModel { } let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize ?? 0 guard size <= CheatFile.maxBytes else { return .refused("The file is larger than 4 MB, so it is not a cheat file.") } - guard let data = try? Data(contentsOf: url) else { return .refused(L10n.text("NX Library could not read the file.")) } + guard let data = try? Data(contentsOf: url) else { return .refused(L10n.text("Arcane could not read the file.")) } return CheatInstall.decide(fileName: url.lastPathComponent, data: data, titleIDInPath: titleIDInPath, buildID: buildID, titleID: titleID) } diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift b/Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift index 1633b826..f79d0663 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift @@ -13,9 +13,10 @@ extension AppViewModel { return libraryGames.first { $0.id == id && !$0.isHidden } } guard router?.route == .collection else { return nil } - let games = librarySelection.query.apply(to: libraryGames, history: playSessionStore ?? NoPlayHistory()) + let games = librarySelection.query.applyCatalog(to: visibleCatalogGames, history: playSessionStore ?? NoPlayHistory()) guard !games.isEmpty else { return nil } - return games.first { $0.id == librarySelection.selectedGameID } ?? games.first + let selected = games.first { $0.id == librarySelection.selectedGameID } ?? games.first + return selected?.nxnativeGame } public func revealSaveFolder(_ url: URL) { diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift b/Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift index 2c3417f3..ec799c6c 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift @@ -10,10 +10,11 @@ extension AppViewModel { guard let titleID = CheatLocator.titleID(appURL: game.url, fallback: game.titleId) else { return nil } let support = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support") return ModStore(supportFolder: support.appendingPathComponent("nxnative/\(titleID)"), - recordsFile: support.appendingPathComponent("NXLibrary/mods/\(titleID).json"), + recordsFile: AppData.supportRoot.appendingPathComponent("mods/\(titleID).json"), titleID: titleID, canWrite: { RunningGameMonitor.runningApplication(for: game) == nil }, - trash: { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) }) + trash: { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) }, + allowsAutomaticMaintenance: !AppData.profile.isDevelopment) } func modsRowValue(for game: PortedGame) -> String { diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+NewestEngine.swift b/Sources/NXLibrary/ViewModels/AppViewModel+NewestEngine.swift index 6c556688..e81ce854 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+NewestEngine.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+NewestEngine.swift @@ -1,7 +1,7 @@ import Foundation import NXLibraryCore -/// Settings → Engine, Newest engine: the player may build with nxnative main before NX Library has tested it. +/// Settings → Setup and engine, Newest engine: the player may build with nxnative main before NX Library has tested it. /// Never automatic (AGENTS.md): only these two actions move the checkout away from, or back to, the tested pin. extension AppViewModel { /// The commit the gate expects and builds record: the player's newest engine, else the tested pin. diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+PendingInstall.swift b/Sources/NXLibrary/ViewModels/AppViewModel+PendingInstall.swift index dea49566..6964b6e2 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+PendingInstall.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+PendingInstall.swift @@ -4,55 +4,71 @@ import NXLibraryCore /// Builds that finished while their game was running (`PendingInstall`): installed once the game is no longer /// running, when a game quits, at launch of NX Library and before the game is played again. extension AppViewModel { - func installPendingBuilds(only gameID: UUID? = nil) { + @discardableResult + func authorizeDevelopmentOperation(_ kind: DevelopmentOperationStore.Kind, game: PortedGame) -> Bool { + do { try developmentOperations.authorize(kind, gameID: game.id); return true } + catch { + logs.append(LogEntry(level: .error, message: error.localizedDescription)) + showSettingsNotice(title: L10n.text("Options not saved"), message: L10n.text("Your changes could not be saved. Try again.")) + return false + } + } + + func installPendingBuilds(only gameID: UUID? = nil, automatic: Bool = true) { recoverSavesAtStartup() - guard libraryGames.contains(where: { $0.pendingInstall != nil }) else { return } - var library = (try? libraryStore.load()) ?? LibraryFile(games: libraryGames) - var changed = false - for index in library.games.indices { - guard gameID == nil || library.games[index].id == gameID else { continue } - // An explicit retry can still use the in-memory ready build if the - // previous catalog write failed (for example, a full disk). - if gameID != nil, library.games[index].pendingInstall == nil { - library.games[index].pendingInstall = libraryGames.first { $0.id == gameID }?.pendingInstall - } - guard library.games[index].pendingInstall != nil else { continue } - let name = library.games[index].name - guard RunningGameMonitor.runningApplication(for: library.games[index]) == nil else { continue } - guard let release = acquireSaveInstallLease(for: library.games[index]) else { continue } - defer { release() } + let candidates = Set(libraryGames.filter { $0.pendingInstall != nil }.map(\.id)) + .union(catalogBuildRecoveries.values.filter { $0.pendingInstall != nil }.map(\.id)) + for id in candidates { + guard gameID == nil || id == gameID else { continue } + if automatic && (!developmentOperations.permits(.build, gameID: id) || catalogBuildRecoveries[id] != nil) { continue } + let recoveryGeneration = catalogBuildRecoveries[id] + var outcome: PortedGame? + var release: (() -> Void)? + defer { release?() } do { - switch try PendingInstaller.install(&library.games[index]) { - case .installed: - logs.append(LogEntry(level: .success, message: L10n.format("Installed the new build of %@.", [String(describing: (name))]))) - library.games[index].appIconPending = true - if let path = library.games[index].lastBuild?.logPath, !path.isEmpty { - appIconBuildLogs[library.games[index].id] = URL(fileURLWithPath: path) + let catalog = try catalogRepository.updateNXNative(id: id) { game in + guard let candidate = try catalogBuildRecoveries.pendingCandidate(persisted: game, explicitRetry: !automatic) else { return } + game = candidate + guard game.pendingInstall != nil else { + if recoveryGeneration != nil { outcome = game } + return + } + if !automatic { + guard authorizeDevelopmentOperation(.build, game: game), + authorizeDevelopmentOperation(.icon, game: game) else { return } } - if gameWithInstallFailure?.id == library.games[index].id { gameWithInstallFailure = nil } - if canRetryReadyInstall, lastBuildGameID == library.games[index].id { - buildState = .succeeded - buildSuccessPath = library.games[index].url.path - buildError = nil - lastError = nil - currentStageName = "Build completed" - portingProgress?.finish(success: true) + guard RunningGameMonitor.runningApplication(for: game) == nil else { return } + guard let lease = acquireSaveInstallLease(for: game) else { return } + release = lease + switch try PendingInstaller.install(&game) { + case .installed: + _ = authorizeDevelopmentOperation(.icon, game: game) + game.appIconPending = true + logs.append(LogEntry(level: .success, message: L10n.format("Installed the new build of %@.", [game.name]))) + if let path = game.lastBuild?.logPath, !path.isEmpty { appIconBuildLogs[id] = URL(fileURLWithPath: path) } + case .gone: + logs.append(LogEntry(level: .warning, message: L10n.format("The new build of %@ that waited for the game to quit is gone. Port it again.", [game.name]))) + case nil: return } - case .gone: - logs.append(LogEntry(level: .warning, - message: L10n.format("The new build of %@ that waited for the game to quit is gone. Port it again.", [String(describing: (name))]))) - case nil: - continue + outcome = game + } + applyCatalog(catalog) + guard let outcome else { continue } + catalogBuildRecoveries.acknowledge(id: id, matching: recoveryGeneration) + if gameWithInstallFailure?.id == id { gameWithInstallFailure = nil } + if buildHeldGameID == id { buildHeldGameID = nil } + if lastBuildGameID == id, outcome.pendingInstall == nil, outcome.status == .built { + buildState = .succeeded; buildSuccessPath = outcome.url.path + buildError = nil; lastError = nil; currentStageName = "Build completed" + portingProgress?.finish(success: true) } - changed = true - if buildHeldGameID == library.games[index].id { buildHeldGameID = nil } } catch { - presentInstallFailure(for: library.games[index], error: error.localizedDescription) + if let outcome { _ = persistBuildOutcome(outcome) } + else if let game = libraryGames.first(where: { $0.id == id }) { + presentInstallFailure(for: game, error: error.localizedDescription) + } else { reportCatalogFailure(error) } } } - guard changed else { return } - do { try libraryStore.save(library) } catch { reportLibrarySaveFailure(error) } - loadLibrary() } func presentInstallFailure(for game: PortedGame, error: String) { @@ -64,7 +80,7 @@ extension AppViewModel { func retryFailedInstallation() { guard let game = gameWithInstallFailure else { return } gameWithInstallFailure = nil - installPendingBuilds(only: game.id) + installPendingBuilds(only: game.id, automatic: false) } /// The game as it is after its waiting build went in; the caller has checked it is not running. diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+Porting.swift b/Sources/NXLibrary/ViewModels/AppViewModel+Porting.swift index c9bc4a2b..d0455a68 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+Porting.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+Porting.swift @@ -58,7 +58,7 @@ extension AppViewModel { case .openEngineSettings: router.openSettings(.engine) case .openSetup: reopenSetup() case .importKeys: selectProdKeysFile() - case .openStorage: router.openSettings(.storage) + case .openStorage: router.openSettings(.portingStorage) case .none: break } } diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+Saves.swift b/Sources/NXLibrary/ViewModels/AppViewModel+Saves.swift index 4839cff1..abea0161 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+Saves.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+Saves.swift @@ -12,7 +12,7 @@ extension AppViewModel { } var saveBackupRoot: URL { - FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/NXLibrary/SaveBackups") + AppData.supportRoot.appendingPathComponent("SaveBackups") } func saveContext(for game: PortedGame) throws -> SaveContext { guard let id = game.titleId else { throw SaveFailure.invalidTitleID } @@ -71,6 +71,8 @@ extension AppViewModel { } /// Only app-owned journals for known games; no startup walk through save contents. func recoverSavesAtStartup() { + // Imported launcher records do not authorize repair of a real game save. + guard !AppData.profile.isDevelopment else { return } for game in libraryGames { guard let location = try? defaultSaveLocation(for: game), SaveTransaction.needsRecovery(location: location), RunningGameMonitor.runningApplication(for: game) == nil, diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+Sources.swift b/Sources/NXLibrary/ViewModels/AppViewModel+Sources.swift new file mode 100644 index 00000000..2f88aa7a --- /dev/null +++ b/Sources/NXLibrary/ViewModels/AppViewModel+Sources.swift @@ -0,0 +1,28 @@ +import AppKit +import NXLibraryCore + +extension AppViewModel { + var visibleCatalogGames: [CatalogGame] { + CatalogLibraryProjection.visible(games: catalogGames, sources: catalogSourceConfigurations) + } + func setCatalogFavorite(_ game: CatalogGame) { + do { applyCatalog(try catalogRepository.toggleFavorite(for: game.id)) } + catch { reportCatalogFailure(error) } + } + @discardableResult + func setCatalogHidden(_ hidden: Bool, game: CatalogGame) -> Bool { + do { applyCatalog(try catalogRepository.setHidden(hidden, for: game.id)); return true } + catch { reportCatalogFailure(error); return false } + } + var currentFocusedCatalogGame: CatalogGame? { + let id: UUID? + switch router?.route { + case .detail(let value): id = value + case .library: id = spotlight.selectedGameID + case .collection: id = librarySelection.selectedGameID + default: id = nil + } + guard let id else { return nil } + return visibleCatalogGames.first { $0.id == id } + } +} diff --git a/Sources/NXLibrary/ViewModels/AppViewModel.swift b/Sources/NXLibrary/ViewModels/AppViewModel.swift index b1d4250c..2d5a1e5f 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel.swift @@ -34,7 +34,7 @@ public final class AppViewModel: ObservableObject { } } @Published var settingsNoticeFocus = 0 - /// A SteamGridDB API key is saved (Settings → Look → SteamGridDB), so Change artwork searches it. + /// A SteamGridDB API key is saved (Settings → Online services → SteamGridDB), so Change artwork searches it. @Published var hasSteamGridDBKey = SteamGridDBKey().load() != nil @Published var isEditingSteamGridDBKey = false @Published var isUpdatingApp = false @@ -58,6 +58,7 @@ public final class AppViewModel: ObservableObject { static let allowUntestedToolchain = "NXLibrary_AllowUntestedToolchain" static let setupCompleted = "NXLibrary_SetupCompleted" static let setupPage = "NXLibrary_SetupPage" + static let setupSteamChoice = "NXLibrary_SetupSteamChoice" /// A chosen engine folder other than ~/nxnative. static let savedEngineFolder = "NXLibrary_EngineFolder" static let newestEngineChoice = "NXLibrary_NewestEngineChoice" @@ -74,7 +75,7 @@ public final class AppViewModel: ObservableObject { @Published public var prodKeysPath: String = "" { didSet { if !prodKeysPath.isEmpty { - UserDefaults.standard.set(prodKeysPath, forKey: StorageKeys.savedProdKeysPath) + AppData.preferences.set(prodKeysPath, forKey: StorageKeys.savedProdKeysPath) } } } @@ -86,7 +87,7 @@ public final class AppViewModel: ObservableObject { didSet { if let folder = selectedGameFolder { if !keepsRememberedGameFolder { - UserDefaults.standard.set(folder.path, forKey: StorageKeys.savedGameFolder) + AppData.preferences.set(folder.path, forKey: StorageKeys.savedGameFolder) } if !restoringGameFolder { selectedPackageURLs = nil @@ -94,7 +95,7 @@ public final class AppViewModel: ObservableObject { } } else { if !keepsRememberedGameFolder { - UserDefaults.standard.removeObject(forKey: StorageKeys.savedGameFolder) + AppData.preferences.removeObject(forKey: StorageKeys.savedGameFolder) } scanGeneration = UUID() selectedPackageURLs = nil @@ -112,7 +113,7 @@ public final class AppViewModel: ObservableObject { private var selectedPackageURLs: [URL]? /// The global source-folder preference is independent of the current Add Game draft. public var gameFilesFolder: URL? { - guard let path = UserDefaults.standard.string(forKey: StorageKeys.savedGameFolder), + guard let path = AppData.preferences.string(forKey: StorageKeys.savedGameFolder), !path.isEmpty, path != "/" else { return nil } return URL(fileURLWithPath: path) } @@ -148,6 +149,14 @@ public final class AppViewModel: ObservableObject { var reviewsFailureOnAddGame = false /// The update dialog is up (set by the shell); screens leave input to it. var isUpdateOfferOpen = false + /// "Welcome to Arcane" is on screen, until its fade has ended: screens' own keyboard monitors let Return and + /// the arrows go to it, and Spotlight holds its entrance until it has gone. + @Published var isWelcomeOpen = false + /// The window is still taking its launch mode (Start in fullscreen): Spotlight's entrance waits for it, so the + /// fullscreen transition never cuts the flight (`StartupWindowObserver`, at most 4 s from attachment). + @Published var isWindowSettling = true + /// A home screen (Spotlight or Collection) has shown since launch: Spotlight's entrance plays only on the first. + var homeSeen = false @Published public var isScanningGameFolder: Bool = false @Published public var scanError: String? = nil @@ -231,7 +240,8 @@ public final class AppViewModel: ObservableObject { let capabilities = engineSourceCapabilities return SourceSelection.supported(sources, titleSelection: capabilities.titleSelection, extractedFolders: capabilities.extractedFolders, - nupContainers: capabilities.nupContainers) + nupContainers: capabilities.nupContainers, + nupPrograms: capabilities.nupPrograms) } public var formattedSelectedSourcesSize: String { @@ -284,22 +294,33 @@ public final class AppViewModel: ObservableObject { @Published public var dropErrorMessage: String? = nil // MARK: - Library - @Published public var libraryGames: [PortedGame] = [] + @Published public private(set) var libraryGames: [PortedGame] = [] + @Published public private(set) var catalogGames: [CatalogGame] = [] + @Published public private(set) var catalogSourceConfigurations: [CatalogSourceConfiguration] = [] + @Published private(set) var personalizations = CatalogPersonalizations.empty + /// Finished file operations whose catalog save must still be retried. + @Published var catalogBuildRecoveries = CatalogBuildRecoveries() @Published public var libraryFolder: URL? { didSet { if let folder = libraryFolder { - UserDefaults.standard.set(folder.path, forKey: StorageKeys.savedLibraryFolder) + AppData.preferences.set(folder.path, forKey: StorageKeys.savedLibraryFolder) } } } /// First use asks where to find existing games and install new ones; later visits keep that choice. public var requiresGameAppsFolderChoice: Bool { - !setupCompleted && UserDefaults.standard.string(forKey: StorageKeys.savedLibraryFolder) == nil + !setupCompleted && AppData.preferences.string(forKey: StorageKeys.savedLibraryFolder) == nil } @Published public var isScanningLibrary: Bool = false /// Non-blocking scan details shown beside Library refresh, never an automatic launch dialog. @Published public var libraryScanWarnings: [String] = [] @Published public var gameForSettingsSheet: PortedGame? = nil + /// The Steam game whose Options are open (`SteamOptionsView`); never open with `gameForSettingsSheet`. + @Published var steamOptionsGame: CatalogGame? = nil + /// Any game's Options are open: the screens underneath stop reading input. + var isGameOptionsOpen: Bool { gameForSettingsSheet != nil || steamOptionsGame != nil } + /// The game whose Options are open, for the panels' own key monitors. + var optionsGameID: UUID? { gameForSettingsSheet?.id ?? steamOptionsGame?.id } /// Where the open Game options came from; decides its rows (Move is Spotlight-only). @Published public var gameOptionsOrigin: GameOptionsOrigin = .collection /// Game options opens straight on its Mods panel (the Details page's Mods band). @@ -333,11 +354,16 @@ public final class AppViewModel: ObservableObject { lazy var setupModel = SetupCheckModel(viewModel: self) @Published public private(set) var firstRunSetup = FirstRunSetup() { didSet { - UserDefaults.standard.set(firstRunSetup.isCompleted, forKey: StorageKeys.setupCompleted) + AppData.preferences.set(firstRunSetup.isCompleted, forKey: StorageKeys.setupCompleted) if let page = firstRunSetup.pageToRemember { - UserDefaults.standard.set(page, forKey: StorageKeys.setupPage) + AppData.preferences.set(page, forKey: StorageKeys.setupPage) } else { - UserDefaults.standard.removeObject(forKey: StorageKeys.setupPage) + AppData.preferences.removeObject(forKey: StorageKeys.setupPage) + } + if let choice = firstRunSetup.steamChoiceToRemember { + AppData.preferences.set(choice, forKey: StorageKeys.setupSteamChoice) + } else { + AppData.preferences.removeObject(forKey: StorageKeys.setupSteamChoice) } } } @@ -351,16 +377,16 @@ public final class AppViewModel: ObservableObject { @Published public var lastBuildGameID: UUID? = nil @Published public var allowUntestedToolchain: Bool = false { didSet { - UserDefaults.standard.set(allowUntestedToolchain, forKey: StorageKeys.allowUntestedToolchain) + AppData.preferences.set(allowUntestedToolchain, forKey: StorageKeys.allowUntestedToolchain) } } - /// The newest nxnative the player chose in Settings → Engine; nil while the tested engine is in use. + /// The newest nxnative the player chose in Settings → Setup and engine; nil while the tested engine is in use. @Published public internal(set) var newestEngineChoice: NewestEngineChoice? = nil { didSet { if let choice = newestEngineChoice, let data = try? JSONEncoder().encode(choice) { - UserDefaults.standard.set(data, forKey: StorageKeys.newestEngineChoice) + AppData.preferences.set(data, forKey: StorageKeys.newestEngineChoice) } else { - UserDefaults.standard.removeObject(forKey: StorageKeys.newestEngineChoice) + AppData.preferences.removeObject(forKey: StorageKeys.newestEngineChoice) } } } @@ -387,6 +413,8 @@ public final class AppViewModel: ObservableObject { @Published public var portingProgress: PortingProgress? = nil /// The game ported last in this session leads Spotlight's row until quit. @Published public var frontGameID: UUID? = nil + /// The Steam games seen downloading this session lead the row after it, until quit. + @Published public private(set) var sessionDownloads = SessionDownloads() /// Spotlight's Delete on a failed porting asks first. @Published public var gameToRemove: PortedGame? = nil @Published var removeGameFocus: SeleneConfirmButton = .cancel @@ -404,12 +432,13 @@ public final class AppViewModel: ObservableObject { var canRetryReadyInstall: Bool { buildState == .failed && portingFailureReason == nil - && libraryGames.contains { $0.id == lastBuildGameID && $0.pendingInstall != nil } + && (libraryGames.contains { $0.id == lastBuildGameID && $0.pendingInstall != nil } + || catalogBuildRecoveries.values.contains { $0.id == lastBuildGameID && $0.pendingInstall != nil }) } @Published public var buildWizardStep: Int = 1 // 1: Select Game, 2: Configure & Output, 3: Porting @Published public var iconAppearanceMode: AppIconAppearanceMode = .auto { didSet { - UserDefaults.standard.set(iconAppearanceMode.rawValue, forKey: StorageKeys.savedIconAppearanceMode) + AppData.preferences.set(iconAppearanceMode.rawValue, forKey: StorageKeys.savedIconAppearanceMode) updateDockIcon() } } @@ -426,7 +455,7 @@ public final class AppViewModel: ObservableObject { @Published public private(set) var boxArtIndexVersion = 0 @Published public var launchingGameId: UUID? = nil /// The launch screen: shown on Play, `isReady` once the game's window is up (or the probe gave up). - @Published public var launchOverlay: LaunchOverlayState? = nil { + @Published var launchOverlay: LaunchOverlayState? = nil { didSet { SoundEffectService.shared.isQuieted = launchOverlay != nil && (settingsStore?.settings.quietLaunch ?? true) @@ -456,16 +485,16 @@ public final class AppViewModel: ObservableObject { .resolve(runtime: .locate(), repo: URL(fileURLWithPath: nxnativePath)) } - public let pinnedEngineCommit = "8a5c5e7e1ee606c650fe1aef6959a83009b6a2fc" - private let core = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary") - lazy var libraryStore = LibraryStore(directory: core) + public let pinnedEngineCommit = "461a5f9f95fc9fc40a690bb2a82eb23f1f03bdca" + private let core = AppData.supportRoot + let catalogRepository: CatalogRepository lazy var keyStore = KeyStore(directory: core.appendingPathComponent("keys")) /// Sizes of built apps are remembered between launches, so a scan walks only new or rebuilt apps. private lazy var importService = ImportService(sizeCache: AppSizeCache(file: core.appendingPathComponent("app-sizes.json"))) private let launchService = LaunchService() private lazy var upstreamChecker = UpstreamChecker() private lazy var storeMetadataService = NintendoStoreMetadataService() + let developmentOperations = DevelopmentOperationStore() private var metadataLocaleGeneration = UUID() private var localizedMetadataRefresh: Task<Void, Never>? private let upstreamCacheKey = "NXLibrary_UpstreamStatus" @@ -473,6 +502,7 @@ public final class AppViewModel: ObservableObject { private let sourceCatalog = SourceCatalog() private lazy var workspaceManager = WorkspaceManager(root: core.appendingPathComponent("workspaces")) private var scanGeneration = UUID() + private var libraryRescanRequested = false private var buildService: BuildService? private var buildPreviousStatus: GameStatus? private var activeBuildToolchain: ToolchainInfo? @@ -485,8 +515,10 @@ public final class AppViewModel: ObservableObject { private var pipelinePollGeneration = UUID() private var isPollingPipelineArchive = false - public init(settingsStore: AppSettingsStore = AppSettingsStore()) { + public init(settingsStore: AppSettingsStore, catalog: CatalogDocument, repository: CatalogRepository) { + self.catalogRepository = repository self.settingsStore = settingsStore + applyCatalog(catalog) saveGate.onActivityChange = { [weak self] in DispatchQueue.main.async { guard let self else { return } @@ -494,9 +526,10 @@ public final class AppViewModel: ObservableObject { } } let startup = settingsStore.settings - let didCompleteSetup = UserDefaults.standard.bool(forKey: StorageKeys.setupCompleted) + let didCompleteSetup = AppData.preferences.bool(forKey: StorageKeys.setupCompleted) self.firstRunSetup = FirstRunSetup(completed: didCompleteSetup, - savedPage: UserDefaults.standard.string(forKey: StorageKeys.setupPage)) + savedPage: AppData.preferences.string(forKey: StorageKeys.setupPage), + savedSteamChoice: AppData.preferences.object(forKey: StorageKeys.setupSteamChoice) as? Bool) self.showSetupCheck = !didCompleteSetup // 1. Resolve safe root directory (anchored to SSD / Bundle, NEVER "/") @@ -505,52 +538,47 @@ public final class AppViewModel: ObservableObject { // The launcher's old ~/Games default is not a Mac-app library. let oldGamesDefault = root.appendingPathComponent("Games").standardized.path - if let savedLib = UserDefaults.standard.string(forKey: StorageKeys.savedLibraryFolder), + if let savedLib = AppData.preferences.string(forKey: StorageKeys.savedLibraryFolder), savedLib != oldGamesDefault, !savedLib.isEmpty, savedLib != "/" { self.libraryFolder = URL(fileURLWithPath: savedLib) } else { self.libraryFolder = root.appendingPathComponent("Applications") - UserDefaults.standard.removeObject(forKey: StorageKeys.savedLibraryFolder) + AppData.preferences.removeObject(forKey: StorageKeys.savedLibraryFolder) } // Restore user preferences - if let savedMode = UserDefaults.standard.string(forKey: StorageKeys.savedIconAppearanceMode), + if let savedMode = AppData.preferences.string(forKey: StorageKeys.savedIconAppearanceMode), let mode = AppIconAppearanceMode(rawValue: savedMode) { self.iconAppearanceMode = mode == .mono ? .mono : .auto } - if UserDefaults.standard.object(forKey: StorageKeys.allowUntestedToolchain) != nil { - self.allowUntestedToolchain = UserDefaults.standard.bool(forKey: StorageKeys.allowUntestedToolchain) + if AppData.preferences.object(forKey: StorageKeys.allowUntestedToolchain) != nil { + self.allowUntestedToolchain = AppData.preferences.bool(forKey: StorageKeys.allowUntestedToolchain) } - if let data = UserDefaults.standard.data(forKey: StorageKeys.newestEngineChoice) { + if let data = AppData.preferences.data(forKey: StorageKeys.newestEngineChoice) { self.newestEngineChoice = try? JSONDecoder().decode(NewestEngineChoice.self, from: data) } - restoreBuildInputs() - if startup.checkEngineAtLaunch || !didCompleteSetup { refreshCompatibility() } + restoreBuildInputs(automatic: true) + if !AppData.profile.isDevelopment && (startup.checkEngineAtLaunch || !didCompleteSetup) { refreshCompatibility() } - // Restore saved game folder if it exists - if let savedGamePath = UserDefaults.standard.string(forKey: StorageKeys.savedGameFolder) { - if !savedGamePath.isEmpty, savedGamePath != "/" { - restoringGameFolder = !startup.refreshLibraryAtLaunch - self.selectedGameFolder = URL(fileURLWithPath: savedGamePath) - restoringGameFolder = false - } - } + // Keep Game files as a picker preference, not an active Add game draft. + // Assigning selectedGameFolder scans it; launch refresh only concerns installed apps. - restoreLibraryFromDisk() + recoverSavesAtStartup() if !setupCompleted && firstRunSetup.page == .games { prepareInitialGameAppsFolder() } - if startup.refreshLibraryAtLaunch || (!setupCompleted && firstRunSetup.page == .games) { loadLibrary() } - if let data = UserDefaults.standard.data(forKey: upstreamCacheKey), + if startup.refreshLibraryAtLaunch || (!setupCompleted && firstRunSetup.page == .games) { scanLibrary(using: catalog) } + if let data = AppData.preferences.data(forKey: upstreamCacheKey), let cached = try? JSONDecoder().decode(UpstreamStatus.self, from: data), cached.baseCommit == pinnedEngineCommit { self.upstreamState = .loaded(cached) } updateDockIcon() - - NotificationService.shared.requestAuthorization() + // Register notification-click routing at launch without asking for permission. + _ = NotificationService.shared + let held = PendingInstaller.keptFolders(libraryGames) - let staging = BuildScratch.tempFolders( - core: core, appFolders: [gameAppsFolder] + libraryGames.map { $0.url.deletingLastPathComponent() }) + let staging = AppData.profile.automaticStagingFolders( + appFolders: [gameAppsFolder] + libraryGames.map { $0.url.deletingLastPathComponent() }) DispatchQueue.global(qos: .utility).async { [weak self] in self?.sweepStaleBuildTemp(in: staging, keeping: held) } @@ -601,12 +629,12 @@ public final class AppViewModel: ObservableObject { refreshCompatibility() } - private func restoreBuildInputs(customRyujinxDir: String? = nil) { + private func restoreBuildInputs(customRyujinxDir: String? = nil, automatic: Bool = false) { let nxResult = SystemDetector.shared.detectNxnativeDirectory( - saved: UserDefaults.standard.string(forKey: StorageKeys.savedEngineFolder)) + saved: AppData.preferences.string(forKey: StorageKeys.savedEngineFolder)) self.nxnativePath = nxResult.path self.isNxnativeValid = nxResult.isValid - ensureKeysImported(customRyujinxDir: customRyujinxDir) + if !automatic || !AppData.profile.isDevelopment { ensureKeysImported(customRyujinxDir: customRyujinxDir) } } /// With launch checks off, inspecting a build screen performs the check on demand. @@ -624,7 +652,7 @@ public final class AppViewModel: ObservableObject { keySummary = summary isProdKeysValid = summary.hasHeaderKey prodKeysPath = keyStore.keyURL.path - prodKeysSource = "NX Library" + prodKeysSource = AppIdentity.name } catch { keySummary = nil isProdKeysValid = false @@ -634,7 +662,7 @@ public final class AppViewModel: ObservableObject { } return } - let saved = UserDefaults.standard.string(forKey: StorageKeys.savedProdKeysPath) + let saved = AppData.preferences.string(forKey: StorageKeys.savedProdKeysPath) let detected = SystemDetector.shared.detectProdKeys(additionalSearchDir: customRyujinxDir) let candidate = [saved, detected?.path].compactMap { $0 }.first { !$0.isEmpty && fm.fileExists(atPath: $0) @@ -747,7 +775,7 @@ public final class AppViewModel: ObservableObject { let status = try await checker.check(from: base) self.upstreamState = .loaded(status) if let data = try? JSONEncoder().encode(status) { - UserDefaults.standard.set(data, forKey: self.upstreamCacheKey) + AppData.preferences.set(data, forKey: self.upstreamCacheKey) } self.checkNewestEngineReadiness(status) } catch { @@ -833,7 +861,7 @@ public final class AppViewModel: ObservableObject { /// Keeps the fetched metadata and shows it with the player's choices (`MetadataPicks`) over it. private func setStoreMetadata(_ metadata: NintendoStoreMetadata, for game: PortedGame) { storeMetadataOriginals[game.id] = metadata - let shown = MetadataPicks.shared.applied(to: metadata, titleID: game.titleId ?? game.uniqueKey) + let shown = MetadataPicks.shared.applied(to: metadata, titleID: personalizationKey(for: game)) storeMetadata[game.id] = screenshotFallback.filled(shown) } @@ -867,7 +895,7 @@ public final class AppViewModel: ObservableObject { /// Keeps the player's value for a field, or (nil) goes back to the store's. public func pickMetadata(_ value: String?, field: MetadataField, for game: PortedGame) { - let key = game.titleId ?? game.uniqueKey + let key = personalizationKey(for: game) if let value { MetadataPicks.shared.set(value, titleID: key, field: field) } else { MetadataPicks.shared.remove(titleID: key, field: field) } if let original = storeMetadataOriginals[game.id] { setStoreMetadata(original, for: game) } @@ -917,7 +945,10 @@ public final class AppViewModel: ObservableObject { return error.localizedDescription } - func resolvedDeveloperDir() -> URL { + func resolvedDeveloperDir() -> URL { Self.resolveDeveloperDir() } + + /// Reads no state of the view model, so it can run off the main thread (it runs `xcode-select`). + static func resolveDeveloperDir() -> URL { let fm = FileManager.default // An explicit DEVELOPER_DIR always wins. if let env = ProcessInfo.processInfo.environment["DEVELOPER_DIR"], @@ -968,23 +999,46 @@ public final class AppViewModel: ObservableObject { public func advanceSetupToGames() { guard showSetupCheck else { return } if !setupCompleted { prepareInitialGameAppsFolder() } - loadLibrary() + importExistingBuilds() firstRunSetup.advance() } public func returnToSetupRequirements() { firstRunSetup.goBack() } + /// The Porting card on the first launch's `found` page. + public func openPortingFromFound() { + guard showSetupCheck, !setupCompleted else { return } + firstRunSetup.openPorting() + } + + /// The Steam switch on `found`; the shell applies it when the first launch finishes. + public func chooseSteamOnFound(_ on: Bool) { firstRunSetup.chooseSteam(on) } + + /// Back from the requirements to `found`, during the first launch only. + public func returnToFound() { firstRunSetup.returnToFound() } + + /// Open library on `found`. Ported apps already in the Game apps folder join the library, which + /// turns the Switch source on; without them it stays off until the player chooses Porting. + public func finishFromFound(importPorted: Bool) { + guard showSetupCheck, !setupCompleted else { return } + if importPorted { + prepareInitialGameAppsFolder() + importExistingBuilds() + } + completeSetup() + } + private func prepareInitialGameAppsFolder() { do { try GameAppDestination.prepareInitialFolder(gameAppsFolder, - hasExplicitChoice: UserDefaults.standard.string(forKey: StorageKeys.savedLibraryFolder) != nil) + hasExplicitChoice: AppData.preferences.string(forKey: StorageKeys.savedLibraryFolder) != nil) } catch { logs.append(LogEntry(level: .warning, message: L10n.format("Could not prepare the default Game apps folder: %@", [String(describing: (error.localizedDescription))]))) } } public func completeSetup() { - UserDefaults.standard.set(gameAppsFolder.path, forKey: StorageKeys.savedLibraryFolder) + AppData.preferences.set(gameAppsFolder.path, forKey: StorageKeys.savedLibraryFolder) firstRunSetup.finish() showSetupCheck = false logs.append(LogEntry(level: .success, message: L10n.text("Setup completed."))) @@ -1124,46 +1178,59 @@ public final class AppViewModel: ObservableObject { loadLibrary() } - private func restoreLibraryFromDisk() { - do { - libraryGames = try libraryStore.load().games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } - recoverSavesAtStartup() - } catch { - lastError = error.localizedDescription - logs.append(LogEntry(level: .error, message: L10n.format("Could not read the library: %@", [String(describing: (error.localizedDescription))]))) + func applyCatalog(_ document: CatalogDocument) { + catalogGames = document.games + // Published only when a game is new, so a rescan that changes nothing redraws nothing for it. + var downloads = sessionDownloads + if downloads.note(document.games) { sessionDownloads = downloads } + catalogSourceConfigurations = document.sources + personalizations = CatalogPersonalizations(document: document) + libraryGames = document.nxnativeGames.sorted { + $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } } public func loadLibrary() { + guard !isScanningLibrary else { libraryRescanRequested = true; return } + libraryRescanRequested = false + do { + let current = try catalogRepository.load() + applyCatalog(current) + scanLibrary(using: current) + } catch { reportCatalogFailure(error) } + } + + /// Startup consumes its already-validated document, without a second + /// fallible read before publishing the shell or starting runtime hooks. + private func scanLibrary(using current: CatalogDocument) { guard !isScanningLibrary else { return } + let choosingSwitch = !setupCompleted && firstRunSetup.page == .games + guard current.source(.nxnative)?.isEnabled == true || choosingSwitch else { return } + let existing = current.nxnativeGames isScanningLibrary = true - // At launch the saved library shows at once; the folder scan below then brings in new and changed apps. - if libraryGames.isEmpty, let stored = try? libraryStore.load(), !stored.games.isEmpty { - libraryGames = stored.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } - } let fm = FileManager.default let directories = [gameAppsFolder] - let store = libraryStore let importer = importService let folderSnapshot = libraryFolder?.standardizedFileURL DispatchQueue.global(qos: .userInitiated).async { [weak self] in - let loaded = (try? store.load()) ?? LibraryFile() let scanned = importer.scan(directories: directories) let scanWarnings = importer.scanWarnings - let selected = importer.appsForLibrary(scanned: scanned, existing: loaded.games) + let selected = importer.appsForLibrary(scanned: scanned, existing: existing) let importedGames = selected.map { importer.makeGame(from: $0) } DispatchQueue.main.async { guard let self else { return } - // A folder chosen during the startup scan gets its own scan before results appear. guard self.libraryFolder?.standardizedFileURL == folderSnapshot else { self.isScanningLibrary = false self.loadLibrary() return } + defer { + self.isScanningLibrary = false + if self.libraryRescanRequested { + self.libraryRescanRequested = false + self.loadLibrary() + } + } self.importedApps = selected var scannedByTitle: [String: ImportedApp] = [:] for app in selected { @@ -1171,52 +1238,40 @@ public final class AppViewModel: ObservableObject { scannedByTitle[titleId.uppercased()] = app } } - var library = loaded do { - library = try store.merge(scanned: importedGames) - } catch { - self.lastError = error.localizedDescription - self.logs.append(LogEntry(level: .error, - message: L10n.format("Could not update the library: %@", [String(describing: (error.localizedDescription))]))) - } - for index in library.games.indices { - let scannedApp = library.games[index].titleId - .flatMap { scannedByTitle[$0.uppercased()] } - if let scannedApp, !fm.fileExists(atPath: library.games[index].url.path), - fm.fileExists(atPath: scannedApp.appURL.path) { - library.games[index].url = scannedApp.appURL - } - if let scannedApp, fm.fileExists(atPath: scannedApp.appURL.path) { - library.games[index].sizeBytes = scannedApp.sizeBytes - library.games[index].versionString = scannedApp.version - ?? library.games[index].versionString - library.games[index].bundleId = scannedApp.bundleId - ?? library.games[index].bundleId + let catalog = try self.catalogRepository.mergeNXNative(scanned: importedGames, enableSource: choosingSwitch, observedFrom: existing) { games, acceptedIDs in + for index in games.indices where acceptedIDs.contains(games[index].id) { + let scannedApp = games[index].titleId + .flatMap { scannedByTitle[$0.uppercased()] } + if let scannedApp, !fm.fileExists(atPath: games[index].url.path), + fm.fileExists(atPath: scannedApp.appURL.path) { + games[index].url = scannedApp.appURL + } + if let scannedApp, fm.fileExists(atPath: scannedApp.appURL.path) { + games[index].sizeBytes = scannedApp.sizeBytes + games[index].versionString = scannedApp.version + ?? games[index].versionString + games[index].bundleId = scannedApp.bundleId + ?? games[index].bundleId + } + let appExists = fm.fileExists(atPath: games[index].url.path) + let sourcesExist = GameResourceState.sourcesAvailable(for: games[index], fileManager: fm) + games[index].status = GameResourceState.reconciledStatus( + for: games[index], appExists: appExists, sourcesAvailable: sourcesExist) + } } - let appExists = fm.fileExists(atPath: library.games[index].url.path) - let sourcesExist = GameResourceState.sourcesAvailable(for: library.games[index], fileManager: fm) - library.games[index].status = GameResourceState.reconciledStatus( - for: library.games[index], appExists: appExists, sourcesAvailable: sourcesExist) - } - do { try store.save(library) } catch { self.reportLibrarySaveFailure(error) } - self.libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + self.applyCatalog(catalog) + self.reconcileAppIcons() + } catch { self.reportCatalogFailure(error) } self.libraryScanWarnings = scanWarnings - self.isScanningLibrary = false - // Paths are known again: icons chosen while an app was elsewhere, or left half done, go on now. - self.reconcileAppIcons() - if !scanWarnings.isEmpty { - for warning in scanWarnings { - self.logs.append(LogEntry(level: .warning, message: warning)) - } - } + for warning in scanWarnings { self.logs.append(LogEntry(level: .warning, message: warning)) } } } } public func importExistingBuilds() { - loadLibrary() + do { applyCatalog(try catalogRepository.configureSource(.nxnative, enabled: true, root: nil)); loadLibrary() } + catch { reportCatalogFailure(error) } } /// Attach source files to an already-imported app. The app URL, version and @@ -1304,7 +1359,8 @@ public final class AppViewModel: ObservableObject { } public func launchGame(_ game: PortedGame) { - guard launchingGameId == nil else { return } + // One launch at a time: the launch screen covers the library, and input reaching it changes nothing. + guard launchingGameId == nil, launchOverlay == nil else { return } // A running game is brought forward, never started a second time. if let running = RunningGameMonitor.runningApplication(for: game) { RunningGameMonitor.activate(running) @@ -1359,7 +1415,7 @@ public final class AppViewModel: ObservableObject { return } launchingGameId = game.id - launchOverlay = LaunchOverlayState(game: game) + launchOverlay = LaunchOverlayState(game: .nxnative(game)) SoundEffectService.shared.play(.launch) // A saved-choices build reads the game's own store; only an older build takes env.txt and the environment. @@ -1393,6 +1449,9 @@ public final class AppViewModel: ObservableObject { } } + // Play can come straight from the row. Reconcile removed mod folders before the game reads its overlay. + if let store = modStore(for: game) { _ = performModChange { try store.sync() } } + launchService.launch(appURL: game.url, environment: gameSettings == nil ? config.toEnvironmentDict() : [:]) { [weak self] success, error in DispatchQueue.main.async { @@ -1453,9 +1512,18 @@ public final class AppViewModel: ObservableObject { public func openGameOptions(_ game: PortedGame, from origin: GameOptionsOrigin, opensMods: Bool = false) { gameOptionsOrigin = origin gameOptionsOpensMods = opensMods + steamOptionsGame = nil gameForSettingsSheet = game } + /// Opens a Steam game's Options, remembering the screen it was opened from. + func openSteamOptions(_ game: CatalogGame, from origin: GameOptionsOrigin) { + guard game.integration == .steam else { return } + gameOptionsOrigin = origin + gameForSettingsSheet = nil + steamOptionsGame = game + } + /// Flips the favorite heart and saves the library. public func toggleFavorite(_ game: PortedGame) { updateStoredGame(game) { $0.isFavorite.toggle() } @@ -1506,18 +1574,8 @@ public final class AppViewModel: ObservableObject { /// Applies one change to the stored game and saves the library, the same way for every flag. private func updateStoredGame(_ game: PortedGame, _ change: (inout PortedGame) -> Void) { - guard var library = try? libraryStore.load(), - let index = library.games.firstIndex(where: { $0.id == game.id }) else { return } - change(&library.games[index]) - do { - try libraryStore.save(library) - } catch { - alertMessage = error.localizedDescription - return - } - libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + do { applyCatalog(try catalogRepository.updateNXNative(id: game.id, change)) } + catch { reportCatalogFailure(error) } } /// Opens the Close Game confirmation for a running game (Spotlight and Details). @@ -1554,17 +1612,17 @@ public final class AppViewModel: ObservableObject { /// Seeded once from the newest porting log when nothing is stored yet. public var lastPortingFinishSeconds: Double? { get { - let stored = UserDefaults.standard.double(forKey: StorageKeys.lastPortingFinishSeconds) + let stored = AppData.preferences.double(forKey: StorageKeys.lastPortingFinishSeconds) if stored > 0 { return stored } guard !didSeedFinishSeconds else { return nil } didSeedFinishSeconds = true guard let seeded = Self.finishSecondsFromNewestLog(in: core.appendingPathComponent("logs")) else { return nil } - UserDefaults.standard.set(seeded, forKey: StorageKeys.lastPortingFinishSeconds) + AppData.preferences.set(seeded, forKey: StorageKeys.lastPortingFinishSeconds) return seeded } - set { UserDefaults.standard.set(newValue ?? 0, forKey: StorageKeys.lastPortingFinishSeconds) } + set { AppData.preferences.set(newValue ?? 0, forKey: StorageKeys.lastPortingFinishSeconds) } } private static func finishSecondsFromNewestLog(in directory: URL) -> Double? { @@ -1583,20 +1641,14 @@ public final class AppViewModel: ObservableObject { /// A library that could not be written: what the player sees would be gone at the next start, so say so once /// (in the log every time) instead of losing it in silence. func reportLibrarySaveFailure(_ error: Error) { - let message = L10n.text("NX Library could not save your library, so recent changes may be lost when it quits: ") + let message = L10n.text("Arcane could not save your library, so recent changes may be lost when it quits: ") + error.localizedDescription logs.append(LogEntry(level: .error, message: message)) if alertMessage == nil { alertMessage = message } } private func updateStoredStatus(_ status: GameStatus, for game: PortedGame) { - guard var library = try? libraryStore.load(), - let index = library.games.firstIndex(where: { $0.id == game.id }) else { return } - library.games[index].status = status - do { try libraryStore.save(library) } catch { reportLibrarySaveFailure(error) } - libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + updateStoredGame(game) { $0.status = status } } public func loadRuntimeConfig(for game: PortedGame) -> GameRuntimeConfig { @@ -1701,14 +1753,16 @@ public final class AppViewModel: ObservableObject { return } let fm = FileManager.default - guard var library = try? libraryStore.load(), - let index = library.games.firstIndex(where: { $0.id == game.id }) else { + let current: CatalogDocument + do { current = try catalogRepository.load() } + catch { reportCatalogFailure(error); return } + guard current.nxnativeGames.contains(where: { $0.id == game.id }) else { alertMessage = L10n.format("Could not load the library entry for %@.", [game.name]) return } let appPath = game.url.standardizedFileURL.path - let otherGames = library.games.filter { $0.id != game.id } + let otherGames = current.nxnativeGames.filter { $0.id != game.id } var removedCount = 0 var removedBytes: Int64 = 0 var failures: [String] = [] @@ -1757,7 +1811,7 @@ public final class AppViewModel: ObservableObject { } } - var updated = library.games[index] + var updated = current.nxnativeGames.first { $0.id == game.id }! updated.sources = updated.sources.filter { source in var isDir: ObjCBool = false return fm.fileExists(atPath: source.url.path, isDirectory: &isDir) @@ -1772,19 +1826,18 @@ public final class AppViewModel: ObservableObject { if updated.sources.isEmpty { updated.status = .builtSourcesMissing } - library.games[index] = updated - do { - try libraryStore.save(library) + applyCatalog(try catalogRepository.updateNXNative(id: game.id) { stored in + stored.sources = updated.sources + stored.workspacePath = updated.workspacePath + stored.buildCachePath = updated.buildCachePath + stored.status = updated.status + }) } catch { alertMessage = L10n.format("The sources were removed, but the library could not be saved: %@", [error.localizedDescription]) logs.append(LogEntry(level: .error, message: alertMessage!)) return } - libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } - let removed = L10n.count("Removed %lld source files (%@).", removedCount, arguments: [Self.formatBytes(removedBytes)]) + (removedWorkspace ? " " + L10n.text("The build cache was also removed.") : "") if failures.isEmpty { @@ -1844,12 +1897,9 @@ public final class AppViewModel: ObservableObject { } } - var library = try libraryStore.load() - library.games.removeAll { $0.id == game.id } - try libraryStore.save(library) - libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + applyCatalog(try catalogRepository.updateNXNativeGames { games in + games.removeAll { $0.id == game.id } + }) if deleteBundle { logs.append(LogEntry(level: .warning, message: L10n.format("Game app deleted: %@%@", [String(describing: (game.name)), String(describing: (removedWorkspace ? "; staged workspace removed" : ""))]))) @@ -2032,7 +2082,7 @@ public final class AppViewModel: ObservableObject { titleId: String(format: "%016llX", source.titleId), versionString: source.version.map { "v\($0)" }, sizeBytes: source.sizeBytes, sourceLayout: source.layout, - requiresTitleSelection: source.requiresTitleSelection + requiresTitleSelection: source.requiresTitleSelection, nupProgram: source.nupProgram ) } ) @@ -2056,9 +2106,9 @@ public final class AppViewModel: ObservableObject { } // Remembered, so launch and every check use it; ~/nxnative itself needs nothing stored. if let saved = EngineLocation.savedValue(for: url, home: SystemDetector.shared.resolveRootDirectory()) { - UserDefaults.standard.set(saved, forKey: StorageKeys.savedEngineFolder) + AppData.preferences.set(saved, forKey: StorageKeys.savedEngineFolder) } else { - UserDefaults.standard.removeObject(forKey: StorageKeys.savedEngineFolder) + AppData.preferences.removeObject(forKey: StorageKeys.savedEngineFolder) } self.nxnativePath = url.path self.isNxnativeValid = true @@ -2072,7 +2122,7 @@ public final class AppViewModel: ObservableObject { panel.canChooseFiles = false panel.canChooseDirectories = true panel.allowsMultipleSelection = false - panel.directoryURL = selectedGameFolder + panel.directoryURL = selectedGameFolder ?? gameFilesFolder panel.prompt = "Choose folder" panel.message = GameFoldersCopy.sourcesPickerMessage(extractedFolders: engineSourceCapabilities.extractedFolders) @@ -2388,18 +2438,16 @@ public final class AppViewModel: ObservableObject { titleId: String(format: "%016llX", $0.titleId), versionString: $0.version.map(String.init), sizeBytes: $0.sizeBytes, isSymlink: folder == nil, sourceLayout: $0.layout, - requiresTitleSelection: $0.requiresTitleSelection) + requiresTitleSelection: $0.requiresTitleSelection, nupProgram: $0.nupProgram) } game.workspacePath = workspace.directory.path game.buildCachePath = workspace.buildCache.path game.status = .notBuilt game.settings = pendingRuntimeConfig - let library = try libraryStore.merge(scanned: [game], replacingSources: true) - libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } - return library.games.first(where: { $0.titleId == titleId }) ?? game + let catalog = try catalogRepository.mergeNXNative(scanned: [game], replacingSources: true, enableSource: true) + applyCatalog(catalog) + return catalog.nxnativeGames.first(where: { $0.titleId == titleId }) ?? game } public func startBuild(for game: PortedGame, extraArguments: [String] = []) { @@ -2436,6 +2484,9 @@ public final class AppViewModel: ObservableObject { guard supportsSources(target.sources) else { throw NXLibraryError.environmentBlocked(L10n.text("These sources need an engine with extracted-folder or multi-title support.")) } + guard SourceSelection.matchesNUPProgram(target.sources, titleID: titleId) else { + throw NXLibraryError.environmentBlocked(L10n.text("The selected NUP program no longer matches this game. Choose the source again.")) + } if requiresKeys { guard isProdKeysValid, FileManager.default.fileExists(atPath: keyStore.keyURL.path) else { throw NXLibraryError.missingKeys @@ -2479,14 +2530,12 @@ public final class AppViewModel: ObservableObject { metalVersion: environmentStatus.metalVersion, xcodeVersion: environmentStatus.xcodeVersion, verified: certified, note: certified ? "Certified toolchain" - : usesNewestEngine ? "Newest engine, not yet tested by NX Library" + : usesNewestEngine ? "Newest engine, not yet tested by Arcane" : "Untested toolchain (explicit override)") - let merged = try libraryStore.merge(scanned: [target]) - libraryGames = merged.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } - guard let stored = merged.games.first(where: { $0.titleId == titleId }) else { + let merged = try catalogRepository.mergeNXNative(scanned: [target], enableSource: true) + applyCatalog(merged) + guard let stored = merged.nxnativeGames.first(where: { $0.titleId == titleId }) else { throw NXLibraryError.missingSources } target = stored @@ -2529,15 +2578,12 @@ public final class AppViewModel: ObservableObject { target.buildCachePath = workspace.buildCache.path } - if var library = try? libraryStore.load(), - let index = library.games.firstIndex(where: { $0.id == target.id }) { - library.games[index].workspacePath = target.workspacePath - library.games[index].buildCachePath = target.buildCachePath - do { try libraryStore.save(library) } catch { reportLibrarySaveFailure(error) } - libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } - } + do { + applyCatalog(try catalogRepository.updateNXNative(id: target.id) { + $0.workspacePath = target.workspacePath + $0.buildCachePath = target.buildCachePath + }) + } catch { reportCatalogFailure(error); throw error } let requiredDisk = SourceSelection.uniqueSize(target.sources) * 2 + 10_000_000_000 var measured = Set<UInt64>() @@ -2558,7 +2604,7 @@ public final class AppViewModel: ObservableObject { let toolchain = engineToolchain guard FileManager.default.isExecutableFile(atPath: toolchain.python.path) else { throw NXLibraryError.environmentBlocked(toolchain.isBundled - ? L10n.text("the bundled Python is missing; reinstall NX Library") + ? L10n.text("the bundled Python is missing; reinstall Arcane") : L10n.text("the nxnative venv Python is missing")) } @@ -2580,6 +2626,8 @@ public final class AppViewModel: ObservableObject { bundleId: target.bundleId ?? "org.nxnative.\(titleId.lowercased())", language: loadRuntimeConfig(for: target).languageForBuild, titleId: engineSourceCapabilities.titleSelection ? titleId : nil, + programIndex: SourceSelection.programIndex(for: target.sources, titleID: titleId, + nupPrograms: engineSourceCapabilities.nupPrograms), packageVersion: engineSourceCapabilities.titleSelection ? SourceSelection.packageVersion(for: target.sources, stagedSelection: !workspace.links.isEmpty) : nil, allowUntestedToolchain: allowUntestedToolchain, @@ -2595,6 +2643,8 @@ public final class AppViewModel: ObservableObject { isPollingPipelineArchive = false buildWizardStep = 3 isBuilding = true + // The request belongs to an accepted porting, never to startup or Steam-only use. + NotificationService.shared.requestAuthorization() isCancellingBuild = false buildState = .running buildError = nil @@ -2681,7 +2731,7 @@ public final class AppViewModel: ObservableObject { return } if canRetryReadyInstall { - installPendingBuilds(only: id) + installPendingBuilds(only: id, automatic: false) return } startBuild(for: game) @@ -2829,9 +2879,9 @@ public final class AppViewModel: ObservableObject { if result.heldApp == nil { try? FileManager.default.removeItem(at: tempDir) } buildTempDirectory = nil - var library = (try? libraryStore.load()) ?? LibraryFile(games: libraryGames) - if let index = library.games.firstIndex(where: { $0.id == gameID }) { - var game = library.games[index] + // Displayed state can retain a finished result for an explicit retry, + // but is never serialized as a replacement catalog. + if var game = libraryGames.first(where: { $0.id == gameID }) { let toolchain = activeBuildToolchain ?? ToolchainInfo(engineCommit: activeEngineCommit, verified: false) let verified = toolchain.verified let record = BuildRecord( @@ -2848,6 +2898,8 @@ public final class AppViewModel: ObservableObject { ) if result.success || result.installationFailed { + _ = authorizeDevelopmentOperation(.build, game: game) + _ = authorizeDevelopmentOperation(.icon, game: game) if let held = result.heldApp { PendingInstaller.hold(PendingInstall(tempApp: held, finalApp: finalApp, record: record, toolchain: toolchain), for: &game) @@ -2914,21 +2966,7 @@ public final class AppViewModel: ObservableObject { notifyPortingEnded(game, success: false) } - library.games[index] = game - var saved = true - do { - try libraryStore.save(library) - } catch { - saved = false - if game.pendingInstall != nil { - presentInstallFailure(for: game, error: error.localizedDescription) - } else { - logs.append(LogEntry(level: .error, message: L10n.format("Could not save the library: %@", [String(describing: (error.localizedDescription))]))) - } - } - libraryGames = library.games.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + let saved = persistBuildOutcome(game) if result.success && saved { if result.heldApp == nil { appIconBuildLogs[gameID] = result.logURL } loadLibrary() @@ -3005,7 +3043,7 @@ public final class AppViewModel: ObservableObject { } return DetectedSource(url: item.url, kind: item.kind, titleId: titleId, version: version, sizeBytes: item.sizeBytes, layout: item.layout, - requiresTitleSelection: item.requiresTitleSelection == true) + requiresTitleSelection: item.requiresTitleSelection == true, nupProgram: item.nupProgram) } guard let titleId = game.titleId.flatMap({ UInt64($0, radix: 16) }) else { throw NXLibraryError.missingTitleId @@ -3027,7 +3065,7 @@ public final class AppViewModel: ObservableObject { } return DetectedSource(url: file.url, kind: file.type, titleId: titleId, version: version, sizeBytes: file.sizeBytes, layout: file.layout, - requiresTitleSelection: file.requiresTitleSelection == true) + requiresTitleSelection: file.requiresTitleSelection == true, nupProgram: file.nupProgram) } private func finalAppURL(for game: PortedGame) -> URL { diff --git a/Sources/NXLibrary/ViewModels/GameBananaServices.swift b/Sources/NXLibrary/ViewModels/GameBananaServices.swift index 14e3ec89..d53a991e 100644 --- a/Sources/NXLibrary/ViewModels/GameBananaServices.swift +++ b/Sources/NXLibrary/ViewModels/GameBananaServices.swift @@ -16,8 +16,8 @@ final class GameBananaServices: @unchecked Sendable { let fm = FileManager.default let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" userAgent = GameBananaClient.userAgent(version: version) - let caches = fm.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("NXLibrary/gamebanana") - let support = fm.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/NXLibrary/gamebanana") + let caches = AppData.cacheRoot.appendingPathComponent("gamebanana") + let support = AppData.supportRoot.appendingPathComponent("gamebanana") client = GameBananaClient(cacheFolder: caches.appendingPathComponent("api"), userAgent: userAgent) images = GameBananaImageCache(folder: caches.appendingPathComponent("images"), userAgent: userAgent) matches = GameBananaMatchStore(file: support.appendingPathComponent("matches.json")) diff --git a/Sources/NXLibrary/ViewModels/IGDBSettings.swift b/Sources/NXLibrary/ViewModels/IGDBSettings.swift new file mode 100644 index 00000000..97bb6d1e --- /dev/null +++ b/Sources/NXLibrary/ViewModels/IGDBSettings.swift @@ -0,0 +1,35 @@ +import Foundation +import Combine +import NXLibraryCore + +/// Optional provider settings, separate from the catalog coordinator. Never publishes credentials. +@MainActor final class IGDBSettings: ObservableObject { + static let shared = IGDBSettings() + @Published private(set) var isConfigured: Bool + @Published private(set) var revision = UUID() + @Published var isEditing = false + @Published private(set) var isRemoving = false + @Published private(set) var message: String? + private let store = IGDBCredentialsStore() + private init() { isConfigured = store.load() != nil } + var credentials: IGDBCredentials? { store.load() } + + func save(_ credentials: IGDBCredentials) async throws { + try await IGDBRatingService.shared.check(credentials) + try Task.checkCancellation() + await IGDBRatingService.shared.invalidate() + try Task.checkCancellation() + try store.save(credentials) + message = nil; isConfigured = true; revision = UUID() + } + func remove() async { + guard !isRemoving else { return } + isRemoving = true + defer { isRemoving = false } + do { + try store.remove() + await IGDBRatingService.shared.invalidate() + message = nil; isConfigured = false; revision = UUID() + } catch { message = IGDBError.notSaved.localizedDescription } + } +} diff --git a/Sources/NXLibrary/ViewModels/ListScroll.swift b/Sources/NXLibrary/ViewModels/ListScroll.swift new file mode 100644 index 00000000..44236d7c --- /dev/null +++ b/Sources/NXLibrary/ViewModels/ListScroll.swift @@ -0,0 +1,48 @@ +import SwiftUI +import NXLibraryCore + +/// A list's own scroll offset (`TextScroll`), the way Selene moves every column: the view shifts its rows by +/// `-state.offset` and draws the lines in view. No scroll view under it, so the wheel and the controller share +/// one offset and one glide, and a step never runs against a scroll still in flight. +@MainActor +final class ListScroll: ObservableObject { + @Published private(set) var state = TextScroll() + + /// The mod panel's glide: critically damped, so quick notches and held arrows carry on without a bounce. + static let glide = DetailScroll.glide + + func setLayout(content: CGFloat, visible: CGFloat) { + var next = state + next.setLayout(content: content, visible: visible) + if next != state { state = next } + } + + /// The wheel (positive shows more below); whether it moved. + @discardableResult + func scroll(by delta: CGFloat, animated: Bool) -> Bool { + var next = state + guard next.scroll(by: delta) else { return false } + commit(next, animated: animated) + return true + } + + /// Moves as little as it can to show `span` whole; whether it moved. + @discardableResult + func reveal(_ span: ClosedRange<CGFloat>, animated: Bool) -> Bool { + var next = state + guard next.reveal(span) else { return false } + commit(next, animated: animated) + return true + } + + func reset() { + guard state.offset != 0 else { return } + var next = state + next.reset() + state = next + } + + private func commit(_ next: TextScroll, animated: Bool) { + if animated { withAnimation(Self.glide) { state = next } } else { state = next } + } +} diff --git a/Sources/NXLibrary/ViewModels/ModStoreHost.swift b/Sources/NXLibrary/ViewModels/ModStoreHost.swift index b866e345..5a51c6f2 100644 --- a/Sources/NXLibrary/ViewModels/ModStoreHost.swift +++ b/Sources/NXLibrary/ViewModels/ModStoreHost.swift @@ -27,6 +27,9 @@ final class ModStoreHost: ObservableObject { /// The cover being decoded before it is shown. private var nextCover: [URL] = [] private var coverTask: Task<Void, Never>? + private var coverTitleIDs: Set<String>? + private var coverRequestID = UUID() + private var recordsGeneration = UUID() private static let log = Logger(subsystem: "local.nxlibrary", category: "gamebanana") private var gamesByTitle: [String: PortedGame] = [:] @@ -38,8 +41,7 @@ final class ModStoreHost: ObservableObject { init() { let services = GameBananaServices.shared - let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] - .appendingPathComponent("NXLibrary/gamebanana/store") + let caches = AppData.cacheRoot.appendingPathComponent("gamebanana/store") snapshots = ModCatalogSnapshots(folder: caches) catalog = ModStoreModel(client: services.client, matches: services.matches, snapshots: snapshots) // After the catalog has published its new value; held while the page moves. @@ -78,6 +80,8 @@ final class ModStoreHost: ObservableObject { /// The card is selected: the store reads its snapshots and refreshes in the background. `games` are your games, /// last played first. func open(_ games: [PortedGame], viewModel: AppViewModel) { + recordsGeneration = UUID() + records = [:] self.viewModel = viewModel var byTitle: [String: PortedGame] = [:] var list: [ModStoreGame] = [] @@ -94,28 +98,42 @@ final class ModStoreHost: ObservableObject { self.reloadRecords(all: true) } catalog.open(list) + reloadRecords(all: true) } /// The card's cover before the store has looked: the art the store will pick, from the snapshots on disk of /// `titleIDs` (your games), read off the main thread. No request. func loadCover(titleIDs: Set<String>) { - guard cover.isEmpty, nextCover.isEmpty else { return } + let wanted = Set(titleIDs.map { $0.uppercased() }) + if coverTitleIDs != wanted { + coverTask?.cancel() + coverTitleIDs = wanted + cover = [] + nextCover = [] + } + let requestID = UUID() + coverRequestID = requestID let snapshots = self.snapshots let matches = GameBananaServices.shared.matches - let wanted = Set(titleIDs.map { $0.uppercased() }) Task { [weak self] in let urls = await Task.detached(priority: .utility) { () -> [URL] in let games = snapshots.loadAll(matches: matches).filter { wanted.contains($0.titleID) } .map { ModCatalogGame(titleID: $0.titleID, name: $0.gameName, mods: $0.mods) } return ModStoreLayout.coverArt(games: games) }.value - guard let self, self.cover.isEmpty else { return } + guard let self, self.coverTitleIDs == wanted, self.coverRequestID == requestID else { return } self.show(cover: urls) } } /// Shows `urls` on the card once all of them are decoded, so the mosaic changes in one crossfade. private func show(cover urls: [URL]) { + if urls.isEmpty { + coverTask?.cancel() + nextCover = [] + cover = [] + return + } guard !urls.isEmpty, urls != nextCover else { return } coverTask?.cancel() guard urls != cover else { nextCover = []; return } @@ -131,6 +149,7 @@ final class ModStoreHost: ObservableObject { /// Another card or a game is selected: requests and downloads stop, the panel closes. func close() { guard catalog.phase != .idle || panel.isPanelOpen else { return } + recordsGeneration = UUID() panel.stop() catalog.close() pending?.cancel() @@ -149,7 +168,11 @@ final class ModStoreHost: ObservableObject { let mods = catalog.games.reduce(0) { $0 + $1.mods.count } let nextCounts = (mods, catalog.games.count, catalog.refreshing || catalog.phase == .loading) if nextCounts != counts { counts = nextCounts } - show(cover: ModStoreLayout.coverArt(games: catalog.games)) + // Closing/loading clears the catalog temporarily, not the prepared cover. + if !catalog.games.isEmpty || catalog.phase == .ready { + coverRequestID = UUID() // The live catalog supersedes an older snapshot still being read. + show(cover: ModStoreLayout.coverArt(games: catalog.games)) + } reloadRecords(all: false) prewarm() Self.log.notice("store rebuild \(self.sections.count, privacy: .public) sections \(mods, privacy: .public) mods in \(Int(Date().timeIntervalSince(start) * 1000), privacy: .public) ms") @@ -157,6 +180,7 @@ final class ModStoreHost: ObservableObject { /// Reads the records of games not read yet (`all`: every game, after an install) off the main thread. private func reloadRecords(all: Bool) { + if all { recordsGeneration = UUID() } guard let viewModel else { return } let stores = catalog.games.compactMap { game -> (String, ModStore)? in guard all || records[game.titleID] == nil, let ported = gamesByTitle[game.titleID], @@ -165,11 +189,12 @@ final class ModStoreHost: ObservableObject { } guard !stores.isEmpty else { return } let box = UncheckedBox(stores) + let generation = recordsGeneration Task { [weak self] in let read = await Task.detached(priority: .utility) { () -> [String: [Int: ModRecord]] in Dictionary(box.value.map { ($0.0, $0.1.gameBananaRecords()) }, uniquingKeysWith: { first, _ in first }) }.value - guard let self else { return } + guard let self, self.recordsGeneration == generation else { return } var next = self.records next.merge(read) { _, new in new } if next != self.records { self.records = next } diff --git a/Sources/NXLibrary/ViewModels/ModsBandHost.swift b/Sources/NXLibrary/ViewModels/ModsBandHost.swift index 2b5ede1a..bd84ae3e 100644 --- a/Sources/NXLibrary/ViewModels/ModsBandHost.swift +++ b/Sources/NXLibrary/ViewModels/ModsBandHost.swift @@ -80,6 +80,15 @@ final class ModsBandHost: ObservableObject { detail = nil } + /// Drops the previous game's band while Spotlight browses the row. Opening a page loads its own band. + func clearGame() { + guard game != nil else { return } + stop() + game = nil + localMods = nil + records = [:] + } + // MARK: - Tiles and panels /// A tile: installed mods and Manage open Game options → Mods (`openMods`); a GameBanana mod opens its detail; diff --git a/Sources/NXLibrary/ViewModels/SetupCheckModel.swift b/Sources/NXLibrary/ViewModels/SetupCheckModel.swift index 7426cfa1..9d682285 100644 --- a/Sources/NXLibrary/ViewModels/SetupCheckModel.swift +++ b/Sources/NXLibrary/ViewModels/SetupCheckModel.swift @@ -30,9 +30,9 @@ final class SetupCheckModel: ObservableObject { // MARK: - Checking - private static func makeProbe(_ viewModel: AppViewModel, runner: CommandRunning) -> SetupProbe { + private static func makeProbe(_ viewModel: AppViewModel, runner: CommandRunning, developerDir: URL) -> SetupProbe { SetupProbe(runner: runner, toolchain: viewModel.engineToolchain, - developerDir: viewModel.resolvedDeveloperDir(), + developerDir: developerDir, engineFolder: URL(fileURLWithPath: viewModel.nxnativePath), pinnedCommit: viewModel.pinnedEngineCommit, certifiedMetal: viewModel.requiredMetalVersion ?? requirements.fallbackMetal, @@ -46,12 +46,19 @@ final class SetupCheckModel: ObservableObject { func refresh() { guard !probing else { return } probing = true - let probe = Self.makeProbe(viewModel, runner: runner) + // Every recheck (4 s) asks xcode-select again, off the main thread; the probe reads the view model on main. queue.async { [weak self] in - let facts = probe.facts() + let developerDir = AppViewModel.resolveDeveloperDir() DispatchQueue.main.async { - self?.probing = false - self?.apply(facts) + guard let self else { return } + let probe = Self.makeProbe(self.viewModel, runner: self.runner, developerDir: developerDir) + self.queue.async { [weak self] in + let facts = probe.facts() + DispatchQueue.main.async { + self?.probing = false + self?.apply(facts) + } + } } } } @@ -86,11 +93,11 @@ final class SetupCheckModel: ObservableObject { } func rememberStates() { - var states = UserDefaults.standard.dictionary(forKey: Self.lastStatesKey) as? [String: String] ?? [:] + var states = AppData.preferences.dictionary(forKey: Self.lastStatesKey) as? [String: String] ?? [:] for item in items where item.state != .working { states[item.id.rawValue] = item.state.rawValue } - UserDefaults.standard.set(states, forKey: Self.lastStatesKey) + AppData.preferences.set(states, forKey: Self.lastStatesKey) } /// At launch, after setup: opens the Setup check when something that was ready @@ -98,13 +105,15 @@ final class SetupCheckModel: ObservableObject { static func checkAtLaunch(viewModel: AppViewModel) { guard viewModel.setupCompleted else { return } let enginePath = viewModel.nxnativePath - let probe = makeProbe(viewModel, runner: SystemCommandRunner()) DispatchQueue.global(qos: .utility).async { + // xcode-select runs here, not on the main thread at launch; the probe reads the view model on main. + let developerDir = AppViewModel.resolveDeveloperDir() + let probe = DispatchQueue.main.sync { makeProbe(viewModel, runner: SystemCommandRunner(), developerDir: developerDir) } let current = SetupCheck.items(from: probe.facts()) DispatchQueue.main.async { guard !viewModel.isBuilding, !viewModel.isUpdatingApp, viewModel.nxnativePath == enginePath else { return } - let stored = UserDefaults.standard.dictionary(forKey: lastStatesKey) as? [String: String] ?? [:] + let stored = AppData.preferences.dictionary(forKey: lastStatesKey) as? [String: String] ?? [:] var previous: [SetupItemID: SetupState] = [:] for (key, value) in stored { if let id = SetupItemID(rawValue: key), let state = SetupState(rawValue: value) { previous[id] = state } @@ -112,7 +121,7 @@ final class SetupCheckModel: ObservableObject { if SetupCheck.shouldReopen(previous: previous, current: current) { viewModel.showSetupCheck = true } else { - UserDefaults.standard.set( + AppData.preferences.set( Dictionary(uniqueKeysWithValues: current.map { ($0.id.rawValue, $0.state.rawValue) }), forKey: lastStatesKey) } @@ -260,7 +269,7 @@ final class SetupCheckModel: ObservableObject { .flatMap { MetalVersion.parse($0.stdout) } if let now, now != certified { final = CommandResult(status: 1, stdout: final.stdout, - stderr: "This Xcode uses Metal \(now); builds wait for an NX Library update tested with it.") + stderr: "This Xcode uses Metal \(now); builds wait for an Arcane update tested with it.") } } DispatchQueue.main.async { @@ -299,7 +308,7 @@ final class SetupCheckModel: ObservableObject { } } - /// The newest engine's card: A returns to the tested engine, the same action as Settings → Engine. + /// The newest engine's card: A returns to the tested engine, the same action as Settings → Setup and engine. private func backToTestedEngine(_ completion: @escaping (Bool) -> Void) { setOverride(.engine, .working("SWITCHING…", detail: L10n.text("Returning to the tested engine…"))) viewModel.useTestedEngine() diff --git a/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift b/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift index e9ade799..86a5ad1a 100644 --- a/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift +++ b/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift @@ -322,9 +322,10 @@ struct AddGameStepThreeView: View { } if let path = viewModel.buildSuccessPath { - return [ + let needsSave = viewModel.lastBuildGameID.map { viewModel.catalogBuildRecoveries[$0] != nil } ?? false + var actions = [ StepAction(id: "play", title: L10n.text("Play"), - systemImage: "play.fill", kind: .primary, + systemImage: "play.fill", kind: needsSave ? .secondary : .primary, isEnabled: FileManager.default.fileExists(atPath: path)) { play(path: path) }, @@ -349,6 +350,13 @@ struct AddGameStepThreeView: View { viewModel.openOutputInFinder() } ] + if needsSave { + actions.insert(StepAction(id: "saveLibrary", title: L10n.text("Retry saving library"), + systemImage: "arrow.clockwise", kind: .primary, isEnabled: !viewModel.isBuilding) { + viewModel.retrySavingBuildResults() + }, at: 0) + } + return actions } if viewModel.buildError != nil || viewModel.buildState == .cancelled { diff --git a/Sources/NXLibrary/Views/AddGame/AddGameView.swift b/Sources/NXLibrary/Views/AddGame/AddGameView.swift index a38d6a20..98166272 100644 --- a/Sources/NXLibrary/Views/AddGame/AddGameView.swift +++ b/Sources/NXLibrary/Views/AddGame/AddGameView.swift @@ -332,6 +332,7 @@ public struct AddGameView: View { viewModel.gameToRemove == nil, viewModel.gameWithInstallFailure == nil, !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, viewModel.alertMessage == nil, viewModel.settingsNotice == nil, let window = event.window, !window.isSheet, diff --git a/Sources/NXLibrary/Views/Catalog/CatalogNativeArtwork.swift b/Sources/NXLibrary/Views/Catalog/CatalogNativeArtwork.swift new file mode 100644 index 00000000..6f02736d --- /dev/null +++ b/Sources/NXLibrary/Views/Catalog/CatalogNativeArtwork.swift @@ -0,0 +1,24 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// Native-app artwork for non-nxnative entries, in the tile's layout role: a square +/// shows the app's own icon (or the player's pick), a portrait the cover. It never +/// asks Nintendo artwork services or writes the installed app. +struct CatalogNativeArtwork: View { + let game: CatalogGame + var role: LibraryArtworkRole = .cover + /// The art's look (black and white while Steam installs the game). + var look: PortingTileLook = .normal + var cornerRadius: CGFloat = 12 + @Environment(\.seleneCanvas) private var canvas + var body: some View { + // No source label on the art: the page's Platform says Steam (maintainer's call, 15 Nov 2026). + ZStack { + SeleneTheme.glassSolid + SteamArtwork(game: game, slot: role.slot) + } + .portingLook(look, cornerRadius: canvas.u(cornerRadius)) + .accessibilityLabel(game.name) + } +} diff --git a/Sources/NXLibrary/Views/Catalog/CatalogSteamInfo.swift b/Sources/NXLibrary/Views/Catalog/CatalogSteamInfo.swift new file mode 100644 index 00000000..8f520653 --- /dev/null +++ b/Sources/NXLibrary/Views/Catalog/CatalogSteamInfo.swift @@ -0,0 +1,186 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// A Steam game's head in the same Selene layout as an nxnative one: the shared +/// logo area, the Play/Options/favorite positions, the stats line and (in Collection) the genre +/// chips. Play follows `SteamPlayCoordinator`: Resume while the game runs, Cancel while +/// waiting for Steam, Try again after a failure, with a one-line note above the pills. +/// Options opens `SteamOptionsView`. +struct CatalogSteamInfo: View { + let game: CatalogGame + let totalPlaytime: TimeInterval + let lastPlayed: Date? + /// Collection shows no pills, like its nxnative column. + var collection = false + var focused: Int? = nil + var onAction: (Int) -> Void = { _ in } + var onHover: (Int) -> Void = { _ in } + @Environment(\.seleneCanvas) private var canvas + @Environment(\.seleneReduceMotion) private var reduceMotion + @Environment(\.nxAppLocale) private var localization + @ObservedObject private var fields = SteamPersonalizations.shared.metadata + @ObservedObject private var picks = SteamPersonalizations.shared.artwork + @ObservedObject private var facts = SteamGameFacts.shared + @ObservedObject private var player = SteamPlayCoordinator.shared + @ObservedObject private var logos = SteamLogoCache.shared + private var metadata: SteamMetadata? { facts.metadata(for: game) } + @State private var shown = true + @State private var restShown = true + @State private var slid = true + + private var presentation: LibraryPresentation { + let key = game.personalizationReference.key + var overrides: [MetadataField: String] = [:] + for field in MetadataField.allCases { overrides[field] = fields.value(titleID: key, field: field) } + return LibraryPresentation(game: game, steamMetadata: metadata, overrides: overrides, + totalPlaytime: totalPlaytime, lastPlayed: lastPlayed) + } + private var currentLogoKey: String { "\(game.id)|\(picks.revision)" } + + var body: some View { + let presentation = presentation + VStack(alignment: .leading, spacing: 0) { + // Spotlight moves only the logo and fades the rest in after it; Collection moves the whole column + // (`SpotlightGameInfoView`, `CollectionInfoView`). + GameLogoArea(title: game.name, logo: logos.logo(for: currentLogoKey), collection: collection) + .offset(x: collection || slid ? 0 : canvas.u(SpotlightGameInfoView.logoSlideDistance)) + .opacity(collection || shown ? 1 : 0) + rest(presentation) + .opacity(collection || restShown ? 1 : 0) + } + .frame(width: collection ? nil : canvas.u(900), alignment: .leading) + .frame(maxWidth: collection ? .infinity : nil, alignment: .topLeading) + .opacity(!collection || shown ? 1 : 0) + .offset(x: !collection || slid ? 0 : canvas.u(CollectionInfoView.slideDistance)) + .onAppear { reveal() } + .onChange(of: game.id) { _ in reveal() } + .task(id: "\(game.id)|\(localization.language.rawValue)") { + await facts.load(game, language: localization.language) + } + .task(id: currentLogoKey) { + await logos.load(game, key: currentLogoKey, picks: picks) + } + } + + @ViewBuilder + private func rest(_ presentation: LibraryPresentation) -> some View { + VStack(alignment: .leading, spacing: 0) { + if let note = playNote { + Text(note) + .seleneFont(19, .semibold) + .foregroundColor(SeleneTheme.ink75) + .padding(.leading, canvas.u(collection ? 0 : 4)) + .padding(.top, canvas.u(20)) + } + if !collection { + GamePrimaryActions(primaryTitle: primaryTitle, + isFavorite: game.isFavorite, focused: focused, + primaryEnabled: primaryEnabled, + primaryWaveDots: primaryWaveDots, + onAction: onAction, onHover: onHover) + .padding(.leading, canvas.u(2)).padding(.top, canvas.u(18)) + } + SeleneStatsRow(presentation: presentation) + .padding(.leading, canvas.u(collection ? 0 : 4)).padding(.top, canvas.u(collection ? 28 : 26)) + // Spotlight places the genres in their own block under the head, as for nxnative games. + if collection, !presentation.genres.isEmpty { + SpotlightGenreChips(genres: presentation.genres).padding(.top, canvas.u(20)) + } + } + } + + private var phase: SteamPlayState.Phase { player.phase(of: game) } + private var primaryEnabled: Bool { + if case .idle = phase { return downloading ? SteamPlayCoordinator.steamClientURL != nil : player.canPlay(game) } + return true + } + + /// Steam is still installing the game: "Downloading" with the dots, as a Switch game's "Porting", in place of + /// Play; it opens Steam's Downloads. + private var downloading: Bool { player.isDownloading(game) } + + /// The pill says the download is under way, with the porting pill's dots, only while it can open Steam. + private var primaryWaveDots: Bool { + guard case .idle = phase, downloading else { return false } + return SteamPlayCoordinator.steamClientURL != nil + } + + private var primaryTitle: String { + switch phase { + case .running: return L10n.text("Resume") + case .starting: return L10n.text("Cancel") + case .failed: return L10n.text("Try again") + case .idle: + if downloading { return L10n.text("Downloading") } + return player.canPlay(game) ? L10n.text("Play") : L10n.text("Unavailable") + } + } + + private var playNote: String? { + switch phase { + case .starting: + return player.mayNeedSteam(game) ? L10n.text("Steam may need you. Check Steam, the game starts after.") + : L10n.text("Waiting for Steam to start the game…") + case .failed(.clientMissing): return L10n.text("Steam is not installed on this Mac.") + case .failed(.handoffRejected): return L10n.text("Steam did not receive the request. Try again.") + case .failed(.notStarted): return L10n.text("The game did not start. Check Steam, then try again.") + case .failed(.unavailable): return L10n.text("Refresh the Steam source or check the installation in Steam.") + case .idle: + // The pill and the tile already say it; only a missing Steam needs a word. + if downloading { + return SteamPlayCoordinator.steamClientURL != nil ? nil : L10n.text("Steam is not installed on this Mac.") + } + return player.canPlay(game) ? nil : L10n.text("Refresh the Steam source or check the installation in Steam.") + case .running: return nil + } + } + + /// The nxnative head's arrival, motion for motion: in Spotlight the logo holds, then fades and slides while + /// the pills and stats fade in after it; in Collection the whole column fades and slides. Reduce motion + /// keeps the fades and drops the slides. + private func reveal() { + var reset = Transaction() + reset.disablesAnimations = true + withTransaction(reset) { shown = false; restShown = false; slid = reduceMotion } + DispatchQueue.main.async { + if collection { + withAnimation(CollectionInfoView.fade) { shown = true; restShown = true } + if !reduceMotion { withAnimation(CollectionInfoView.slide) { slid = true } } + } else { + withAnimation(SpotlightGameInfoView.logoFade) { shown = true } + withAnimation(SpotlightGameInfoView.restMotion) { restShown = true } + if !reduceMotion { withAnimation(SpotlightGameInfoView.logoSlide) { slid = true } } + } + } + } +} + +/// Decoded Steam logos, kept like nxnative ones (`GameArtLoader`): a game seen before shows its logo from the +/// first frame of its arrival, and a logo that lands later fades in over its title. +@MainActor +final class SteamLogoCache: ObservableObject { + static let shared = SteamLogoCache() + private let logos = NSCache<NSString, NSImage>() + /// Bumped (animated) when a logo lands, so heads reading it redraw. + @Published private var tick = 0 + + func logo(for key: String) -> NSImage? { + _ = tick + return logos.object(forKey: key as NSString) + } + + /// `key` names the game and the player's picks revision, so a new pick loads again. + func load(_ game: CatalogGame, key: String, picks: SteamPersonalizationStore) async { + guard logos.object(forKey: key as NSString) == nil else { return } + let request = SteamArtworkRequest(game: game, role: .logo) + var url = request.localURL(picks: picks) + if url == nil, let id = request.appID { url = await SteamMetadataService.shared.image(appID: id, slot: .logo) } + guard !Task.isCancelled, let url else { return } + // Decoded off the main thread like an nxnative logo: a lazily decoded file cost the frame that drew it. + let image = await GameArtLoader.decodeLogo(at: url) + guard !Task.isCancelled, let image else { return } + logos.setObject(image, forKey: key as NSString) + withAnimation(.easeOut(duration: 0.3)) { tick += 1 } + } +} diff --git a/Sources/NXLibrary/Views/Catalog/SteamArtwork.swift b/Sources/NXLibrary/Views/Catalog/SteamArtwork.swift new file mode 100644 index 00000000..fd3f140c --- /dev/null +++ b/Sources/NXLibrary/Views/Catalog/SteamArtwork.swift @@ -0,0 +1,115 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// Same source-qualified personal picks as metadata; downloaded art never writes +/// into Steam or its app bundles. Task identity includes locale-independent URL. +struct SteamArtwork: View { + let game: CatalogGame + let slot: ArtworkSlot + var remote: URL? = nil + @State private var image: NSImage? + @State private var loadedKey = "" + /// The installed app's own icon, the cover/icon fallback: read once per bundle, not on every redraw. + @State private var appIcon: NSImage? + @State private var appIconPath: String? + /// The first look-up has ended (art found or not): a tile is ready for Spotlight's entrance. + @State private var settled = false + @Environment(\.seleneCanvas) private var canvas + @ObservedObject private var picks = SteamPersonalizations.shared.artwork + private var installedApp: CatalogNativeApplication? { + game.steamGame?.firstAvailableInstallation?.primaryApplication + } + private var appBuildID: String? { game.steamGame?.firstAvailableInstallation?.buildID } + private var appIconRequestKey: String { "\(installedApp?.url.path ?? "")|\(appBuildID ?? "")" } + /// The installed app's path is part of it: an installation that moves brings its icon along. + private var key: String { + "\(game.id)|\(slot.rawValue)|\(remote?.absoluteString ?? "")|\(picks.revision)|\(appIconRequestKey)" + } + private var role: LibraryArtworkRole { LibraryArtworkRole.allCases.first { $0.slot == slot } ?? .hero } + + private var displayedImage: NSImage? { + if loadedKey == key, let image { return image } + return TileArtMemo.shared.object(forKey: "steam|\(key)" as NSString) + } + + private var displayedAppIcon: NSImage? { + guard let app = installedApp else { return nil } + if appIconPath == appIconRequestKey, let appIcon { return appIcon } + return SteamAppIconCache.cachedIcon(at: app.url, buildID: appBuildID) + } + + var body: some View { + ZStack { + if let image = displayedImage { + Image(nsImage: image).resizable().aspectRatio(contentMode: slot == .logo ? .fit : .fill) + } else if slot == .cover || slot == .icon { + if let appIcon = displayedAppIcon { + Image(nsImage: appIcon).resizable().scaledToFit().padding(canvas.u(16)) + } else if installedApp == nil, slot == .icon { + // No app yet (Steam still installing it): the store art is on its way; a generic controller + // under the download mark only looked broken. + Color.clear + } else { Image(systemName: "gamecontroller.fill").resizable().scaledToFit().padding(canvas.u(30)) } + } else { Color.clear } + } + .clipped() + .preference(key: TileArtPendingKey.self, value: settled ? 0 : 1) + .task(id: key) { + defer { if !settled { settled = true } } + let expected = key + if slot == .cover || slot == .icon { + appIcon = installedApp.map { SteamAppIconCache.icon(at: $0.url, buildID: appBuildID) } + appIconPath = appIconRequestKey + } + guard let id = game.steamGame?.appID else { return } + let request = SteamArtworkRequest(game: game, role: role) + let url: URL? + if remote == nil, let local = request.localURL(picks: picks) { url = local } + // A square is always an icon, never store art cropped to a square: with no app yet (Steam still + // installing the game), LaunchBox's Square, else nothing. + else if remote == nil, request.wantsAutomaticIcon { + url = await AppViewModel.automaticIconArtwork.automaticSteamIcon(titleID: game.personalizationReference.key, + names: [game.name]) + } else if role == .square { url = nil } + else { url = await SteamMetadataService.shared.image(appID: id, slot: slot, remote: remote) } + guard !Task.isCancelled else { return } + // Decoded off the main thread at the size its nxnative twin uses: a lazily decoded file cost the + // first frame that drew it 40–60 ms. + let decoded: NSImage? = if let url { await GameArtLoader.decode(at: url, maxPixelSize: slot.decodedSize) } else { nil } + guard !Task.isCancelled else { return } + if let decoded { TileArtMemo.store(decoded, for: "steam|\(expected)" as NSString) } + else { TileArtMemo.shared.removeObject(forKey: "steam|\(expected)" as NSString) } + image = decoded; loadedKey = expected + } + + .accessibilityLabel(game.name) + } +} + +/// Installed apps' own icons by bundle path, shared by every tile that shows one. +@MainActor +private enum SteamAppIconCache { + private static let icons = NSCache<NSString, NSImage>() + private static func key(_ url: URL, _ buildID: String?) -> NSString { "\(url.path)|\(buildID ?? "")" as NSString } + static func cachedIcon(at url: URL, buildID: String?) -> NSImage? { icons.object(forKey: key(url, buildID)) } + static func icon(at url: URL, buildID: String?) -> NSImage { + if let icon = cachedIcon(at: url, buildID: buildID) { return icon } + let icon = NSWorkspace.shared.icon(forFile: url.path) + icons.setObject(icon, forKey: key(url, buildID)) + return icon + } +} + +private extension ArtworkSlot { + /// The nxnative sizes: tiles' icons 512 px (`SpotlightTileArtwork`), box covers 900 (`SwitchBoxArtCover`), + /// logos and heroes as `GameArtLoader`. + var decodedSize: Int { + switch self { + case .icon: return 512 + case .cover: return 900 + case .logo: return 1600 + case .background: return 2560 + } + } +} diff --git a/Sources/NXLibrary/Views/Catalog/SteamGamePage.swift b/Sources/NXLibrary/Views/Catalog/SteamGamePage.swift new file mode 100644 index 00000000..a2760053 --- /dev/null +++ b/Sources/NXLibrary/Views/Catalog/SteamGamePage.swift @@ -0,0 +1,39 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// Steam store facts for the games on screen, one copy shared by Spotlight and Collection, +/// so the head, the page and the input counts read the same answer. Facts are per AppID +/// and language; a reply for a game or language no longer asked for is dropped. +@MainActor +final class SteamGameFacts: ObservableObject { + static let shared = SteamGameFacts() + @Published private(set) var facts: [UInt32: SteamMetadata] = [:] + /// AppIDs whose answer (facts or none) is in for the current language. + @Published private(set) var known: Set<UInt32> = [] + private var language = "" + /// When an AppID last came back without facts: asked again after a minute, not on every draw. + private var missedAt: [UInt32: Date] = [:] + private static let retryAfter: TimeInterval = 60 + + func metadata(for game: CatalogGame) -> SteamMetadata? { + game.steamGame.flatMap { facts[$0.appID] } + } + + func isKnown(_ game: CatalogGame) -> Bool { + game.steamGame.map { known.contains($0.appID) } ?? true + } + + func load(_ game: CatalogGame, language app: AppLanguage) async { + guard let appID = game.steamGame?.appID else { return } + let language = SteamMetadata.language(app) + if language != self.language { self.language = language; facts = [:]; known = []; missedAt = [:] } + // An answer without facts (offline, store busy) is retried later; facts once found are kept. + let retry = facts[appID] == nil && missedAt[appID].map { Date().timeIntervalSince($0) > Self.retryAfter } == true + guard !known.contains(appID) || retry else { return } + let result = await SteamMetadataService.shared.metadata(appID: appID, language: language) + guard !Task.isCancelled, language == self.language else { return } + if let result { facts[appID] = result; missedAt[appID] = nil } else { missedAt[appID] = Date() } + known.insert(appID) + } +} diff --git a/Sources/NXLibrary/Views/Catalog/SteamPersonalizations.swift b/Sources/NXLibrary/Views/Catalog/SteamPersonalizations.swift new file mode 100644 index 00000000..543a06e0 --- /dev/null +++ b/Sources/NXLibrary/Views/Catalog/SteamPersonalizations.swift @@ -0,0 +1,11 @@ +import SwiftUI +import AppKit +import UniformTypeIdentifiers +import NXLibraryCore + +@MainActor +final class SteamPersonalizations { + static let shared = SteamPersonalizations() + let metadata = SteamPersonalizationStore(directory: AppData.supportRoot.appendingPathComponent("integrations/steam/personal")) + var artwork: SteamPersonalizationStore { metadata } +} diff --git a/Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift b/Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift index 6e593d03..6c7aefd4 100644 --- a/Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift +++ b/Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift @@ -10,7 +10,7 @@ struct CollectionCoverRow: View { @Environment(\.seleneCanvas) private var canvas @Environment(\.seleneReduceMotion) private var reduceMotion - let games: [PortedGame] + let games: [CatalogGame] let selectedID: UUID? let artwork: ArtworkStore let boxArt: BoxArtService @@ -21,8 +21,8 @@ struct CollectionCoverRow: View { let needsMetadata: (PortedGame) -> Void /// The porting look of a game's cover (`PortingTileLook`). var tileLook: (PortedGame) -> PortingTileLook = { _ in .normal } - let onSelect: (PortedGame) -> Void - let onActivate: (PortedGame) -> Void + let onSelect: (CatalogGame) -> Void + let onActivate: (CatalogGame) -> Void /// The first cover lines up with Spotlight's 80 margin (Selene's list had 14). private static let startInset: CGFloat = 80 @@ -43,6 +43,8 @@ struct CollectionCoverRow: View { .transition(.identity) } } + // Covers made, and art arriving, during the slide ride it with the rest (`GlideGroup`). + .modifier(GlideGroup()) // The camera: the one slide of the whole row. .offset(x: canvas.u(-CGFloat(offset) * CollectionRow.pitch)) .frame(maxWidth: .infinity, alignment: .topLeading) @@ -59,19 +61,30 @@ struct CollectionCoverRow: View { tilesAcross: Int((canvas.size.width / pitch).rounded(.up))) } - private func cover(_ game: PortedGame, selected: Bool) -> some View { + private func cover(_ game: CatalogGame, selected: Bool) -> some View { let w = canvas.u(CollectionRow.coverWidth), h = canvas.u(CollectionRow.coverHeight) let face = RoundedRectangle(cornerRadius: canvas.u(12), style: .continuous) return ZStack { - SwitchBoxArtCover(game: game, width: w, height: h, officialName: officialName(game), + Group { + if let native = game.nxnativeGame { + SwitchBoxArtCover(game: native, width: w, height: h, officialName: officialName(native), boxArt: boxArt, artwork: artwork, indexVersion: boxArtIndexVersion) - .portingLook(tileLook(game), cornerRadius: canvas.u(12)) + .portingLook(tileLook(native), cornerRadius: canvas.u(12)) .frame(width: w, height: h) .clipShape(face) // One picture that grows and slides whole: a drawn cover's title, a lock or build progress would // otherwise snap to the pixel grid on their own at every step and shake against the cover. .drawingGroup() .shadow(color: .black.opacity(0.55), radius: canvas.u(9)) + } else { + CatalogNativeArtwork(game: game, look: PortingTileLook.make(catalog: game)) + .frame(width: w, height: h) + .clipShape(face) + } + } + if game.nxnativeGame == nil { + PortingDownloadMark(look: PortingTileLook.make(catalog: game), width: w, height: h) + } SeleneShine(cornerRadius: canvas.u(12), active: selected) .frame(width: w, height: h) SeleneTileRing(cornerRadius: canvas.u(18), active: selected) @@ -86,6 +99,6 @@ struct CollectionCoverRow: View { .accessibilityElement(children: .ignore) .accessibilityLabel(game.name) .accessibilityAddTraits(selected ? [.isButton, .isSelected] : .isButton) - .task(id: game.id) { needsMetadata(game) } + .task(id: game.id) { if let native = game.nxnativeGame { needsMetadata(native) } } } } diff --git a/Sources/NXLibrary/Views/Collection/CollectionView+Input.swift b/Sources/NXLibrary/Views/Collection/CollectionView+Input.swift index cf14e99d..2c938940 100644 --- a/Sources/NXLibrary/Views/Collection/CollectionView+Input.swift +++ b/Sources/NXLibrary/Views/Collection/CollectionView+Input.swift @@ -6,18 +6,18 @@ import NXLibraryCore extension CollectionView { func handle(_ action: GamepadAction) { var moved = false - let all = viewModel.libraryGames + let all = viewModel.visibleCatalogGames switch action { case .navigateLeft, .navigateRight: let before = viewModel.librarySelection.selectedGameID - viewModel.librarySelection.move(by: action == .navigateLeft ? -1 : 1, + viewModel.librarySelection.moveCatalog(by: action == .navigateLeft ? -1 : 1, in: all, history: playSessions) moved = viewModel.librarySelection.selectedGameID != before case .navigateUp, .navigateDown: break case .jumpToStart, .jumpToEnd: let before = viewModel.librarySelection.selectedGameID - viewModel.librarySelection.jump(toEnd: action == .jumpToEnd, in: all, history: playSessions) + viewModel.librarySelection.jumpCatalog(toEnd: action == .jumpToEnd, in: all, history: playSessions) moved = viewModel.librarySelection.selectedGameID != before case .tabPrevious: setFilter(filter.shifted(by: -1)) @@ -26,15 +26,21 @@ extension CollectionView { case .rightStickPress: setFilter(filter.cycled()) case .confirm: - if let game = selectedGame { - play(game) + if let record = selectedCatalogGame { + activateCatalog(record) } else if !hasAnyGame, !viewModel.isScanningLibrary { SoundEffectService.shared.play(.click) router.openAddGame() } case .secondaryAction: - if let game = selectedGame { router.showDetail(game.id) } + // A Steam game's details are its Spotlight page; Collection has no Details screen for it. + if let game = selectedCatalogGame, game.integration != .steam { router.showDetail(game.id) } case .contextAction: + if let steam = selectedCatalogGame, steam.integration == .steam { + SoundEffectService.shared.play(.click) + viewModel.openSteamOptions(steam, from: .collection) + return + } if let game = selectedGame { viewModel.openGameOptions(game, from: .collection) } case .cancel: router.showLibrary() // B goes home, like Selene's library. @@ -50,6 +56,12 @@ extension CollectionView { if moved { SoundEffectService.shared.play(.focus) } } + func activateCatalog(_ record: CatalogGame) { + if let native = record.nxnativeGame { play(native) } + else if record.integration == .steam { SoundEffectService.shared.play(.click); SteamPlayCoordinator.shared.press(record) } + else { SoundEffectService.shared.play(.click); router.showDetail(record.id) } + } + /// A on a cover: plays, or opens Details when the game is not built (Spotlight's rule). func play(_ game: PortedGame) { SoundEffectService.shared.play(.click) @@ -70,13 +82,13 @@ extension CollectionView { guard !router.isMenuPresented, !NativeMenuCommands.shared.isTracking, !router.isSearchPresented, - !router.isIntroShowing, router.route == .collection, viewModel.alertMessage == nil, viewModel.settingsNotice == nil, - viewModel.gameForSettingsSheet == nil, + !viewModel.isGameOptionsOpen, viewModel.gameToClose == nil, viewModel.gameToRemove == nil, !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, !viewModel.showSetupCheck, !router.isScreenshotViewerOpen, let window = event.window, diff --git a/Sources/NXLibrary/Views/Collection/CollectionView.swift b/Sources/NXLibrary/Views/Collection/CollectionView.swift index 303ab998..abb22036 100644 --- a/Sources/NXLibrary/Views/Collection/CollectionView.swift +++ b/Sources/NXLibrary/Views/Collection/CollectionView.swift @@ -20,6 +20,8 @@ public struct CollectionView: View { @StateObject var art = SeleneHeroArt() /// Art the player picks redraws the hero and logo (their task keys carry its revision). @ObservedObject var picks = ArtworkPicks.shared + /// Steam Play phases drive the A hint. + @ObservedObject var steamPlayer = SteamPlayCoordinator.shared @State var keyMonitor: Any? public init(viewModel: AppViewModel, router: AppRouter, settings: AppSettingsStore, @@ -36,18 +38,19 @@ public struct CollectionView: View { /// The filter is shared with Spotlight. var filter: LibraryFilter { viewModel.librarySelection.query.filter } - var games: [PortedGame] { - viewModel.librarySelection.query.apply(to: viewModel.libraryGames, history: playSessions) + var games: [CatalogGame] { + viewModel.librarySelection.query.applyCatalog(to: viewModel.visibleCatalogGames, history: playSessions) } - var hasAnyGame: Bool { viewModel.libraryGames.contains { !$0.isHidden } } + var hasAnyGame: Bool { !viewModel.visibleCatalogGames.isEmpty } - func selectedGame(in games: [PortedGame]) -> PortedGame? { + func selectedGame(in games: [CatalogGame]) -> PortedGame? { guard let id = viewModel.librarySelection.selectedGameID else { return nil } - return games.first { $0.id == id } + return games.first { $0.id == id }?.nxnativeGame } var selectedGame: PortedGame? { selectedGame(in: games) } + var selectedCatalogGame: CatalogGame? { games.first { $0.id == viewModel.librarySelection.selectedGameID } } // MARK: - Body @@ -67,11 +70,14 @@ public struct CollectionView: View { }, stage: { stage(games: games, game: game) }) .onAppear(perform: appear) + // A launch on Collection: Spotlight's entrance belongs to the first home only (`SpotlightView+Entrance`). + .onAppear { viewModel.homeSeen = true } .onDisappear(perform: removeKeyMonitor) - .onChange(of: viewModel.libraryGames) { _ in + .onChange(of: viewModel.catalogGames) { _ in viewModel.preloadCachedStoreMetadata() reconcile() } + .onChange(of: viewModel.catalogSourceConfigurations) { _ in reconcile() } .onChange(of: filter) { _ in reconcile() } .onChange(of: viewModel.librarySelection.selectedGameID) { _ in selectionChanged() } .onReceive(NotificationCenter.default.publisher(for: .nxCollectionGamepadAction)) { note in @@ -87,10 +93,11 @@ public struct CollectionView: View { .onChange(of: playSessions.sessions.count) { _ in reconcile() } .onChange(of: viewModel.isScanningLibrary) { _ in reconcile() } .task(id: art.heroTaskKey(game, metadata: game.flatMap { viewModel.storeMetadata[$0.id] })) { await loadHero(game) } + .task(id: art.steamHeroTaskKey(selectedCatalogGame)) { await art.loadSteamHero(game: selectedCatalogGame, current: { selectedCatalogGame?.id }, artwork: artwork) } .task(id: art.logoTaskKey(game, metadata: game.flatMap { viewModel.storeMetadata[$0.id] })) { await loadLogo(game) } } - private func stage(games: [PortedGame], game: PortedGame?) -> some View { + private func stage(games: [CatalogGame], game: PortedGame?) -> some View { ZStack(alignment: .topLeading) { SpotlightTopBar(filter: filter, showClock: settings.settings.showClock, onSelect: { setFilter($0) }) @@ -105,6 +112,12 @@ public struct CollectionView: View { // Spotlight's left margin; the logo starts just under the top bar. .frame(width: canvas.u(1100), alignment: .topLeading) .offset(x: canvas.u(80), y: canvas.u(110)) + } else if let record = selectedCatalogGame, record.integration == .steam { + CatalogSteamInfo(game: record, totalPlaytime: playSessions.totalDuration(for: record.id), + lastPlayed: playSessions.lastPlayed(for: record.id), collection: true) + .id(record.id) + .frame(width: canvas.u(1100), alignment: .topLeading) + .offset(x: canvas.u(80), y: canvas.u(110)) } if games.isEmpty { @@ -121,7 +134,7 @@ public struct CollectionView: View { needsMetadata: { viewModel.loadStoreMetadata(for: $0) }, tileLook: viewModel.portingTileLook, onSelect: { select($0.id) }, - onActivate: { select($0.id); play($0) }) + onActivate: { record in select(record.id); activateCatalog(record) }) .offset(y: canvas.u(576)) } } @@ -160,6 +173,10 @@ public struct CollectionView: View { // MARK: - Hints private func contextHints(_ game: PortedGame?) -> [HintItem] { + if let steam = selectedCatalogGame, steam.integration == .steam { + return SteamPlayCoordinator.shared.hint(for: steam) + + [HintItem(.y, L10n.text("Game options")), HintItem(.rs, L10n.text("Filter"))] + } guard let game else { if viewModel.isScanningLibrary { return [] } return hasAnyGame ? [HintItem(.rs, L10n.text("Filter"))] : [HintItem(.a, L10n.text("Add game"))] @@ -189,8 +206,8 @@ public struct CollectionView: View { /// Keeps the selection inside the filtered list, in the same frame as any change to it. func reconcile() { var state = viewModel.librarySelection - state.reconcile(with: viewModel.libraryGames, history: playSessions, - preferredGameID: settings.settings.restoreLastGame ? settings.settings.lastSelectedGameID : nil) + state.reconcileCatalog(with: viewModel.visibleCatalogGames, history: playSessions, + preferredGameID: settings.settings.restoreLastGame ? settings.lastSelectedGameID : nil) if state != viewModel.librarySelection { viewModel.librarySelection = state } } @@ -206,21 +223,23 @@ public struct CollectionView: View { } private func selectionChanged() { - guard let game = selectedGame else { return } - if settings.settings.lastSelectedGameID != game.id { settings.settings.lastSelectedGameID = game.id } - viewModel.loadStoreMetadata(for: game) + let game = selectedGame + if let id = game?.id ?? selectedCatalogGame?.id { settings.rememberLastSelectedGame(id) } + if let game { viewModel.loadStoreMetadata(for: game) } } // MARK: - Art private func loadHero(_ game: PortedGame?) async { + // On a Steam game the nxnative art stays until the Steam hero replaces it, so the change is one crossfade. await art.loadHero(game: game, current: { selectedGame?.id }, - metadata: game.flatMap { viewModel.storeMetadata[$0.id] }, artwork: artwork) + metadata: game.flatMap { viewModel.storeMetadata[$0.id] }, artwork: artwork, personalizations: viewModel.personalizations, + keepsWithoutGame: selectedCatalogGame?.integration == .steam) } private func loadLogo(_ game: PortedGame?) async { await art.loadLogo(game: game, metadata: game.flatMap { viewModel.storeMetadata[$0.id] }, - artwork: artwork) + artwork: artwork, personalizations: viewModel.personalizations) } } @@ -267,36 +286,20 @@ struct CollectionInfoView: View { } .frame(maxWidth: .infinity, alignment: .topLeading) .opacity(shown ? 1 : 0) - .offset(x: slid ? 0 : canvas.u(-24)) + .offset(x: slid ? 0 : canvas.u(Self.slideDistance)) .onAppear { reveal() } } private var logoArea: some View { - ZStack(alignment: .bottomLeading) { - if let logo { - Image(nsImage: logo) - .resizable() - .interpolation(.high) - .aspectRatio(contentMode: .fit) - .frame(maxWidth: canvas.u(700), maxHeight: canvas.u(240), alignment: .bottomLeading) - .shadow(color: .black.opacity(0.35), radius: canvas.u(8)) - } else { - Text(game.name) - .seleneFont(56) - .foregroundColor(SeleneTheme.ink) - .multilineTextAlignment(.leading) - .lineLimit(3) - .frame(maxHeight: canvas.u(220)) - .shadow(color: .black.opacity(0.45), radius: canvas.u(6)) - } - } - .frame(maxWidth: .infinity, alignment: .leading) - .frame(height: canvas.u(250), alignment: .bottomLeading) - .accessibilityElement(children: .ignore) - .accessibilityLabel(game.name) - .accessibilityAddTraits(.isHeader) + GameLogoArea(title: game.name, logo: logo, collection: true) } + /// The whole column's fade and slide after a change. A Steam game's column uses the same. + /// Quicker than Spotlight's head (a grid is browsed fast) but with its curve, easing out like `logoFade`. + static let fade = Animation.easeOut(duration: 0.3).delay(0.12) + static let slide = SeleneTheme.cubicOut(0.3).delay(0.12) + static let slideDistance: CGFloat = -24 + /// The fade always runs; the slide is movement and drops under reduce motion. private func reveal() { var reset = Transaction() @@ -306,9 +309,9 @@ struct CollectionInfoView: View { slid = reduceMotion } DispatchQueue.main.async { - withAnimation(.linear(duration: 0.3).delay(0.12)) { shown = true } + withAnimation(Self.fade) { shown = true } if !reduceMotion { - withAnimation(SeleneTheme.cubicOut(0.3).delay(0.12)) { slid = true } + withAnimation(Self.slide) { slid = true } } } } diff --git a/Sources/NXLibrary/Views/Components/AppUpdateDialog.swift b/Sources/NXLibrary/Views/Components/AppUpdateDialog.swift index 06501731..7ea93c9d 100644 --- a/Sources/NXLibrary/Views/Components/AppUpdateDialog.swift +++ b/Sources/NXLibrary/Views/Components/AppUpdateDialog.swift @@ -18,7 +18,7 @@ struct AppUpdateDialog: View { switch updater.state { case .checking: return L10n.text("Checking for updates") case .upToDate: return L10n.text("You’re up to date") - case .available(let release): return L10n.format("NX Library %@", [String(describing: (release.version))]) + case .available(let release): return L10n.format("Arcane %@", [String(describing: (release.version))]) case .downloading: return L10n.text("Downloading update") case .verifying: return L10n.text("Verifying update") case .installing: return L10n.text("Installing update") @@ -29,23 +29,23 @@ struct AppUpdateDialog: View { private var message: String { switch updater.state { case .checking: return L10n.text("Looking for a new release…") - case .upToDate: return L10n.format("You have NX Library %@. No newer release is available.", [String(describing: (updater.currentVersion))]) + case .upToDate: return L10n.format("You have Arcane %@. No newer release is available.", [String(describing: (updater.currentVersion))]) case .available: var lines = [L10n.format("You have %@.", [String(describing: (updater.currentVersion))])] if updater.installation == .developer { lines.append(L10n.text("This development copy can check releases. Install a packaged release to use automatic updates.")) } else if updater.installation == .readOnly { - lines.append(L10n.text("Move NX Library to Applications before updating.")) + lines.append(L10n.text("Move Arcane to Applications before updating.")) } else if let reason = blockedReason { lines.append(L10n.text(reason)) - } else { lines.append(L10n.text("NX Library restarts to finish.")) } + } else { lines.append(L10n.text("Arcane restarts to finish.")) } return (lines + requirementNotes).joined(separator: "\n\n") case .downloading(let progress): return L10n.format("%@%% · Download continues if you close this dialog.", [String(describing: (Int((progress * 100).rounded())))]) case .verifying: return L10n.text("Checking the download before installing.") - case .installing: return L10n.text("NX Library will reopen automatically.") + case .installing: return L10n.text("Arcane will reopen automatically.") case .failed(let message): return message case .developer: return L10n.text("This development copy can check releases but cannot replace itself.") - case .readOnly: return L10n.text("Move NX Library to Applications before updating.") + case .readOnly: return L10n.text("Move Arcane to Applications before updating.") default: return L10n.text("Updates are currently unavailable.") } } diff --git a/Sources/NXLibrary/Views/Components/GameIconProvider.swift b/Sources/NXLibrary/Views/Components/GameIconProvider.swift index d8bd9f88..f23a4cb8 100644 --- a/Sources/NXLibrary/Views/Components/GameIconProvider.swift +++ b/Sources/NXLibrary/Views/Components/GameIconProvider.swift @@ -38,11 +38,19 @@ public enum GameIconProvider { } private static let artCache = NSCache<NSString, NSImage>() + /// Games with no square art, by where it was looked for: a tile redraws often, and a game with no icon would + /// otherwise read its app and workspace from disk on every draw. Building the game moves it to its app, a new key. + private static let artMisses = NSCache<NSString, NSNull>() + + private static func missKey(_ game: PortedGame) -> NSString { + "\(game.uniqueKey)|\(game.url.path)|\(game.workspacePath ?? "")" as NSString + } /// The app's icon changed (`AppIconWriter`): read it again. public static func forget(_ game: PortedGame) { cache.removeObject(forKey: game.uniqueKey as NSString) artCache.removeObject(forKey: game.uniqueKey as NSString) + artMisses.removeObject(forKey: missKey(game)) } /// The game's own square icon art, full bleed: the built app's icon file @@ -51,6 +59,8 @@ public enum GameIconProvider { public static func squareArt(for game: PortedGame) -> NSImage? { let key = game.uniqueKey as NSString if let cached = artCache.object(forKey: key) { return cached } + let miss = missKey(game) + if artMisses.object(forKey: miss) != nil { return nil } var image: NSImage? let appURL = game.url @@ -63,7 +73,7 @@ public enum GameIconProvider { image = NSImage(contentsOf: URL(fileURLWithPath: workspace) .appendingPathComponent("\(titleId)_build/extract/v0/icon.jpg")) } - if let image { artCache.setObject(image, forKey: key) } + if let image { artCache.setObject(image, forKey: key) } else { artMisses.setObject(NSNull(), forKey: miss) } return image } } diff --git a/Sources/NXLibrary/Views/Components/GameLogoArea.swift b/Sources/NXLibrary/Views/Components/GameLogoArea.swift new file mode 100644 index 00000000..c8ec6466 --- /dev/null +++ b/Sources/NXLibrary/Views/Components/GameLogoArea.swift @@ -0,0 +1,47 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// Shared geometry preserves the established Spotlight and Collection layouts. +/// Provider loading and settings stay outside this purely visual component. +struct GameLogoArea: View { + let title: String + let logo: NSImage? + var collection = false + @Environment(\.seleneCanvas) private var canvas + var body: some View { + Group { + if collection { collectionArea } + else { spotlightArea } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(title).accessibilityAddTraits(.isHeader) + } + private var spotlightArea: some View { + ZStack(alignment: .bottomLeading) { + if let logo { + Image(nsImage: logo).resizable().interpolation(.high).aspectRatio(contentMode: .fit) + .frame(width: canvas.u(700), height: canvas.u(240), alignment: .bottomLeading) + .shadow(color: .black.opacity(0.35), radius: canvas.u(8)) + .transition(.opacity) + } else { + Text(title).seleneFont(56).foregroundColor(SeleneTheme.ink).lineLimit(1).truncationMode(.tail) + .shadow(color: .black.opacity(0.45), radius: canvas.u(6)) + } + }.frame(width: canvas.u(900), height: canvas.u(195), alignment: .bottomLeading) + } + private var collectionArea: some View { + ZStack(alignment: .bottomLeading) { + if let logo { + Image(nsImage: logo).resizable().interpolation(.high).aspectRatio(contentMode: .fit) + .frame(maxWidth: canvas.u(700), maxHeight: canvas.u(240), alignment: .bottomLeading) + .shadow(color: .black.opacity(0.35), radius: canvas.u(8)) + } else { + Text(title).seleneFont(56).foregroundColor(SeleneTheme.ink).multilineTextAlignment(.leading) + .lineLimit(3).frame(maxHeight: canvas.u(220)) + .shadow(color: .black.opacity(0.45), radius: canvas.u(6)) + } + }.frame(maxWidth: .infinity, alignment: .leading) + .frame(height: canvas.u(250), alignment: .bottomLeading) + } +} diff --git a/Sources/NXLibrary/Views/Components/GamePrimaryActions.swift b/Sources/NXLibrary/Views/Components/GamePrimaryActions.swift new file mode 100644 index 00000000..81c0d86a --- /dev/null +++ b/Sources/NXLibrary/Views/Components/GamePrimaryActions.swift @@ -0,0 +1,30 @@ +import SwiftUI +import NXLibraryCore + +/// Play/Options/favorite visual and input targets are identical across sources. +struct GamePrimaryActions: View { + let primaryTitle: String + var secondaryTitle = "Options" + let isFavorite: Bool + let focused: Int? + var primaryEnabled = true + /// The wave dots after the first title, as the porting pill shows them (a Steam game still downloading). + var primaryWaveDots = false + let onAction: (Int) -> Void + var onHover: (Int) -> Void = { _ in } + @Environment(\.seleneCanvas) private var canvas + var body: some View { + HStack(spacing: canvas.u(14)) { + pill(0, SelenePillButton(title: primaryTitle, height: 52, focused: focused == 0, + enabled: primaryEnabled, waveDots: primaryWaveDots) { onAction(0) }) + pill(1, SelenePillButton(title: secondaryTitle, height: 52, focused: focused == 1) { onAction(1) }) + pill(2, SelenePillButton(title: nil, icon: isFavorite ? .favorite : .favoriteBorder, + iconSize: 20, minWidth: 52, height: 52, horizontalPadding: 0, + focused: focused == 2) { onAction(2) }) + .accessibilityLabel(isFavorite ? L10n.text("Remove from favorites") : L10n.text("Add to favorites")) + } + } + private func pill<V: View>(_ index: Int, _ view: V) -> some View { + view.frame(height: canvas.u(60)).onHover { if $0 { onHover(index) } } + } +} diff --git a/Sources/NXLibrary/Views/Components/GlideGroup.swift b/Sources/NXLibrary/Views/Components/GlideGroup.swift new file mode 100644 index 00000000..cc5de156 --- /dev/null +++ b/Sources/NXLibrary/Views/Components/GlideGroup.swift @@ -0,0 +1,26 @@ +import SwiftUI + +/// Moves a block as one while something above it glides. +/// +/// SwiftUI hands an animated offset down to each leaf view (text, image, star), and a leaf animates its whole +/// frame with the animation of the latest change that touches it. A change made in another animation during a +/// glide (a fade, a fan, an image arriving) re-times those leaves, and they run ahead of or behind the rest: +/// Spotlight's page, on the first descent from the row, under the fades of its own blocks (maintainer's report, +/// 16 Nov 2026). +/// +/// A geometry group resolves the glide once for the block and passes each leaf a still position inside it. +/// It needs macOS 14; on macOS 13 the block glides as before. +struct GlideGroup: ViewModifier { + static var available: Bool { + if #available(macOS 14.0, *) { return true } + return false + } + + func body(content: Content) -> some View { + if #available(macOS 14.0, *) { + content.geometryGroup() + } else { + content + } + } +} diff --git a/Sources/NXLibrary/Views/Components/IGDBCredentialsDialog.swift b/Sources/NXLibrary/Views/Components/IGDBCredentialsDialog.swift new file mode 100644 index 00000000..22a91337 --- /dev/null +++ b/Sources/NXLibrary/Views/Components/IGDBCredentialsDialog.swift @@ -0,0 +1,128 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// Only the player's Save action sends their own application credentials to Twitch/IGDB. +struct IGDBCredentialsDialog: View { + @ObservedObject var model: IGDBSettings + let onClose: () -> Void + @Environment(\.seleneCanvas) private var canvas + @State private var clientID = "" + @State private var secret = "" + @State private var message: String? + @State private var checking = false + @State private var focus: SeleneConfirmButton = .confirm + @State private var task: Task<Void, Never>? + private enum Field: Hashable { case client, secret } + @FocusState private var field: Field? + + var body: some View { + ZStack { + SeleneTheme.scrim45.ignoresSafeArea().contentShape(Rectangle()).onTapGesture(perform: close) + SeleneConfirmDialog(title: "IGDB", message: L10n.text("Use your Twitch application credentials for critic scores. They stay on this Mac and are sent only to Twitch and IGDB."), + confirmTitle: checking ? L10n.text("Checking…") : L10n.text("Check and save"), + confirmEnabled: !checking && draft != nil, + focus: $focus, onCancel: close, onConfirm: save) { + VStack(alignment: .leading, spacing: canvas.u(14)) { + setupSteps + VStack(alignment: .leading, spacing: canvas.u(6)) { + Text(L10n.text("Client ID")).seleneFont(14).foregroundColor(SeleneTheme.ink60) + TextField(L10n.text("Client ID"), text: $clientID) + .focused($field, equals: .client).onSubmit { field = .secret } + } + .disabled(checking) + VStack(alignment: .leading, spacing: canvas.u(6)) { + Text(L10n.text("Client Secret")).seleneFont(14).foregroundColor(SeleneTheme.ink60) + SecureField(L10n.text("Client Secret"), text: $secret) + .focused($field, equals: .secret).onSubmit(save) + } + .disabled(checking) + if let message { + Text(message).seleneFont(14).foregroundColor(SeleneTheme.danger) + .fixedSize(horizontal: false, vertical: true) + } + HStack { + Button(L10n.text("Developer portal")) { + NSWorkspace.shared.open(URL(string: "https://dev.twitch.tv/console/apps/create")!) + } + Spacer(minLength: 0) + Button(L10n.text("Setup guide")) { + NSWorkspace.shared.open(URL(string: "https://api-docs.igdb.com/#account-creation")!) + } + } + .buttonStyle(.plain).seleneFont(14).foregroundColor(SeleneTheme.focus) + } + .textFieldStyle(.plain) + .font(.system(size: max(13, canvas.u(17)), design: .monospaced)) + .foregroundColor(SeleneTheme.ink) + .padding(canvas.u(16)) + .background(RoundedRectangle(cornerRadius: canvas.u(12)).fill(SeleneTheme.glassLight)) + .padding(.top, canvas.u(24)) + } + } + .onAppear { + if let current = model.credentials { clientID = current.clientID; secret = current.clientSecret } + field = .client + } + .onDisappear { task?.cancel(); secret = "" } + .onExitCommand(perform: close) + .onReceive(NotificationCenter.default.publisher(for: .nxSettingsGamepadAction)) { note in + guard let action = note.object as? GamepadAction else { return } + switch action { + case .navigateUp: field = .client + case .navigateDown: field = .secret + case .navigateLeft: focus = .cancel + case .navigateRight: focus = .confirm + case .confirm: focus == .cancel ? close() : save() + case .cancel: close() + default: break + } + } + } + private var setupSteps: some View { + let steps = [ + L10n.text("Open the developer portal: Applications → Register Your Application."), + L10n.text("Choose a unique name. OAuth Redirect URLs: http://localhost → Add."), + L10n.text("Category: Application Integration. Client Type: Confidential."), + L10n.text("Create → Manage → New Secret."), + L10n.text("Paste Client ID and Client Secret below, then Check and save.") + ] + return VStack(alignment: .leading, spacing: canvas.u(7)) { + ForEach(Array(steps.enumerated()), id: \.offset) { index, text in + HStack(alignment: .top, spacing: canvas.u(9)) { + Text("\(index + 1).") + .foregroundColor(SeleneTheme.ink60) + .frame(width: canvas.u(18), alignment: .leading) + Text(text).foregroundColor(SeleneTheme.ink90) + } + } + Text(L10n.text("Twitch requires a verified email and two-factor authentication.")) + .foregroundColor(SeleneTheme.ink60) + .padding(.top, canvas.u(3)) + } + .seleneFont(14) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + .padding(.bottom, canvas.u(6)) + } + private var draft: IGDBCredentials? { IGDBCredentials(clientID: clientID, clientSecret: secret) } + private func close() { task?.cancel(); secret = ""; onClose() } + private func save() { + guard !checking else { return } + guard let credentials = draft else { message = IGDBError.invalidCredentials.localizedDescription; return } + checking = true; message = nil + task = Task { @MainActor in + do { + try await model.save(credentials) + guard !Task.isCancelled else { return } + SoundEffectService.shared.play(.click) + close() + } catch { + guard !Task.isCancelled else { return } + checking = false + message = (error as? IGDBError ?? .unreachable).localizedDescription + SoundEffectService.shared.play(.error) + } + } + } +} diff --git a/Sources/NXLibrary/Views/Components/PortingArtLook.swift b/Sources/NXLibrary/Views/Components/PortingArtLook.swift index f1cc16cb..79350ffb 100644 --- a/Sources/NXLibrary/Views/Components/PortingArtLook.swift +++ b/Sources/NXLibrary/Views/Components/PortingArtLook.swift @@ -6,7 +6,8 @@ import NXLibraryCore /// the shaders compile, a thin "k/n" bar with the stage and its step in small type /// sits on the softly blurred art; then the percentage fades in, small, with a slow /// pastel sheen. A failed porting with no app keeps the art black and white, -/// lightly blurred, under a lock. +/// lightly blurred, under a lock; a Steam game still installing looks the same with +/// "Downloading" under a thin download mark that pulses (`PortingDownloadMark`). /// /// The art is drawn once: a grey layer in `.saturation` blend takes the colour out /// above the fill line. The sheen moves only while compiling, and stands still @@ -49,7 +50,7 @@ struct PortingArtLook: ViewModifier { private var fill: Double { switch look { case .normal: return 1 - case .preparing, .locked: return 0 + case .preparing, .locked, .downloading: return 0 case .filling(let value): return min(max(value, 0), 1) } } @@ -58,13 +59,13 @@ struct PortingArtLook: ViewModifier { private var blur: CGFloat { switch look { case .preparing: return 0.02 - case .locked: return 0.012 + case .locked, .downloading: return 0.012 case .normal, .filling: return 0 } } /// What sits on the art; animating between them is the slow dissolve. - private enum Stage: Equatable { case none, steps, percent, lock } + private enum Stage: Equatable { case none, steps, percent, lock, download } private var stage: Stage { switch look { @@ -72,6 +73,7 @@ struct PortingArtLook: ViewModifier { case .preparing: return .steps case .filling: return .percent case .locked: return .lock + case .downloading: return .download } } @@ -108,6 +110,10 @@ struct PortingArtLook: ViewModifier { .shadow(color: .black.opacity(0.55), radius: side * 0.04) .transition(.opacity) } + if stage == .download { + downloading(side: side) + .transition(.opacity) + } } } .allowsHitTesting(false) @@ -151,6 +157,33 @@ struct PortingArtLook: ViewModifier { } } + /// Steam is still installing the game: the word in small type under the mark, which the tile draws outside its + /// flattened picture (`PortingDownloadMark`) so it can pulse. + private func downloading(side: CGFloat) -> some View { + ZStack { + // A soft shade, as under the porting steps, so the white reads on light art too. + Color.black.opacity(0.32) + downloadMark(side: side) + } + } + + /// The download mark and its word, as fractions of the side, centred together on the tile: the circle (its + /// symbol's point size; the drawn ring is about as wide) sits this far above the centre, the word's middle this + /// far below, a small gap between them. + static let downloadMarkSize: CGFloat = 0.18 + static let downloadMarkLift: CGFloat = 0.055 + static let downloadWordDrop: CGFloat = 0.1 + + private func downloadMark(side: CGFloat) -> some View { + Text(L10n.text("Downloading")) + .font(.system(size: side * 0.06, weight: .medium)) + .foregroundColor(.white.opacity(0.85)) + .lineLimit(1) + .frame(width: side * 0.84) + .shadow(color: .black.opacity(0.55), radius: side * 0.04) + .offset(y: side * Self.downloadWordDrop) + } + /// Soft pastels, never vivid; the blue kept faint: pink, peach, butter, mint, mist, lavender. private static let pastels: [Color] = [0xF4CFDA, 0xF6E0C8, 0xF3EECB, 0xD3EBDD, 0xD8E6F2, 0xE2DAF2] .map { Color(hex: $0) } @@ -184,3 +217,26 @@ extension View { modifier(PortingArtLook(look: look, cornerRadius: cornerRadius)) } } + +/// A downloading game's mark, pulsing in brightness over the word "Downloading". A Core Animation view cannot be +/// drawn inside a tile flattened with `drawingGroup` (SwiftUI shows a placeholder instead), so the tile places +/// this over its face, outside the flattened picture, as it does its shine. Nothing for any other look. +struct PortingDownloadMark: View { + let look: PortingTileLook + let width: CGFloat + let height: CGFloat + + @Environment(\.seleneReduceMotion) private var reduceMotion + + var body: some View { + if look == .downloading { + let side = min(width, height) + DownloadMarkLayers(size: side * PortingArtLook.downloadMarkSize, still: reduceMotion) + .frame(width: side * 0.3, height: side * 0.3) + .offset(y: -side * PortingArtLook.downloadMarkLift) + .frame(width: width, height: height) + .allowsHitTesting(false) + .transition(.opacity) + } + } +} diff --git a/Sources/NXLibrary/Views/Components/ScreenshotViewer.swift b/Sources/NXLibrary/Views/Components/ScreenshotViewer.swift index c4f662b3..ea987249 100644 --- a/Sources/NXLibrary/Views/Components/ScreenshotViewer.swift +++ b/Sources/NXLibrary/Views/Components/ScreenshotViewer.swift @@ -63,7 +63,7 @@ struct ScreenshotViewer: View { Spacer(minLength: 0) SeleneHintsBar(left: [HintItem(.b, L10n.text("Back"))], right: [HintItem(.lb, "‹"), HintItem(.rb, "›")], - bottom: 40, leftInset: 18) + bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) } } .frame(maxWidth: .infinity, maxHeight: .infinity) diff --git a/Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift b/Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift index 7a49f47e..73807478 100644 --- a/Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift +++ b/Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift @@ -7,8 +7,10 @@ import NXLibraryCore struct SeleneBottomScrim: View { @Environment(\.seleneCanvas) private var canvas - /// Where the home screens set their hints, in Selene units from the window's bottom edge. - static let hintsBottom: CGFloat = 16 + /// Shared by all screens: halfway between the original Home (16) and Settings (48) positions. + static let hintsBottom: CGFloat = 32 + /// Clear space for the 30-unit badges, two-line home hints and breathing room above them. + static let contentClearance: CGFloat = hintsBottom + 52 var body: some View { VStack(spacing: 0) { diff --git a/Sources/NXLibrary/Views/Components/SeleneExpandableText.swift b/Sources/NXLibrary/Views/Components/SeleneExpandableText.swift new file mode 100644 index 00000000..4c8d6bd9 --- /dev/null +++ b/Sources/NXLibrary/Views/Components/SeleneExpandableText.swift @@ -0,0 +1,42 @@ +import SwiftUI + +/// Keeps both text layouts alive while revealing the full description. Swapping +/// the string itself makes a long option row change height in a single frame. +struct SeleneExpandableText: View { + let text: String + let preview: String + let expanded: Bool + + var body: some View { + SeleneTextRevealLayout(expanded: expanded) { + Text(preview).opacity(expanded ? 0 : 1) + Text(text).opacity(expanded ? 1 : 0) + } + .clipped() + } +} + +/// Resolve the destination geometry immediately and let SwiftUI animate its +/// frames. Interpolating the layout's measurements would make scrollTo read a +/// moving target, particularly when the row above is simultaneously collapsing. +/// Both text children always receive their final width and unconstrained height. +private struct SeleneTextRevealLayout: Layout { + let expanded: Bool + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let width = proposal.width.flatMap { $0.isFinite ? $0 : nil } + let textProposal = ProposedViewSize(width: width, height: nil) + guard subviews.count == 2 else { return .zero } + let preview = subviews[0].sizeThatFits(textProposal) + let full = subviews[1].sizeThatFits(textProposal) + return CGSize(width: width ?? max(preview.width, full.width), + height: expanded ? full.height : preview.height) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + for text in subviews { + text.place(at: bounds.origin, anchor: .topLeading, + proposal: ProposedViewSize(width: bounds.width, height: nil)) + } + } +} diff --git a/Sources/NXLibrary/Views/Components/SeleneHintsBar.swift b/Sources/NXLibrary/Views/Components/SeleneHintsBar.swift index 6b80adc9..f82cd984 100644 --- a/Sources/NXLibrary/Views/Components/SeleneHintsBar.swift +++ b/Sources/NXLibrary/Views/Components/SeleneHintsBar.swift @@ -40,10 +40,10 @@ struct SeleneHintsBar: View { var left: [HintItem] = [] var right: [HintItem] = [] - /// Distance from the bottom edge in Selene units: 48 (Ui.cs:267); the home screens use Selene's 40. - var bottom: CGFloat = 48 + /// Every screen uses the same bottom inset. + var bottom: CGFloat = SeleneBottomScrim.hintsBottom /// Extra inset before the left group (Spotlight's prompts carry Selene's 18 margin). - var leftInset: CGFloat = 0 + var leftInset: CGFloat = 18 /// Labels each right slot can show on this screen, left to right. A slot is /// as wide as its longest label, and a missing item keeps its slot, so the /// prompts never shift as the focus moves. diff --git a/Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift b/Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift index ab6d872d..386eef5c 100644 --- a/Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift +++ b/Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift @@ -14,6 +14,8 @@ struct SeleneHomeChrome<Backdrop: View, Stage: View>: View { var rightReserve: [[String]] = [] /// An overlay with its own hints is up (`AppRouter.overlayHasHints`). var hintsHidden = false + /// Spotlight's entrance holds them until everything else has landed; the change brings its own fade. + var hintsHeld = false @ViewBuilder var backdrop: () -> Backdrop @ViewBuilder var stage: () -> Stage @@ -31,6 +33,8 @@ struct SeleneHomeChrome<Backdrop: View, Stage: View>: View { rightReserve: rightReserve) } .seleneOverlaidHints(hintsHidden) + .opacity(hintsHeld ? 0 : 1) + .allowsHitTesting(!hintsHeld) .frame(width: canvas.size.width, height: canvas.size.height) } .frame(width: canvas.size.width, height: canvas.size.height, alignment: .topLeading) @@ -51,7 +55,7 @@ extension AppRouter { /// so the screen's step aside instead of showing through. @MainActor func overlayHasHints(_ viewModel: AppViewModel) -> Bool { - isMenuPresented || isSearchPresented || viewModel.gameForSettingsSheet != nil || route.isOverlay + isMenuPresented || isSearchPresented || viewModel.isGameOptionsOpen || route.isOverlay } } diff --git a/Sources/NXLibrary/Views/Components/SeleneOptionRow.swift b/Sources/NXLibrary/Views/Components/SeleneOptionRow.swift index e004c4c6..cbfd5534 100644 --- a/Sources/NXLibrary/Views/Components/SeleneOptionRow.swift +++ b/Sources/NXLibrary/Views/Components/SeleneOptionRow.swift @@ -11,6 +11,8 @@ struct SeleneOptionRow<Trailing: View>: View { var destructive = false /// False draws the row dim (ink60 text and icon), as Selene's disabled pills do. It still takes focus. var enabled = true + /// Opt-in focus expansion; other option screens keep their existing layout. + var aboutPreview: String? = nil @ViewBuilder var trailing: () -> Trailing var body: some View { @@ -24,7 +26,13 @@ struct SeleneOptionRow<Trailing: View>: View { .seleneFont(21, .medium) .foregroundColor(destructive ? SeleneTheme.danger : (enabled ? SeleneTheme.ink : SeleneTheme.ink60)) if let about { - Text(about) + Group { + if let aboutPreview { + SeleneExpandableText(text: about, preview: aboutPreview, expanded: focused) + } else { + Text(about) + } + } .seleneFont(15) .foregroundColor(SeleneTheme.ink60) .fixedSize(horizontal: false, vertical: true) diff --git a/Sources/NXLibrary/Views/Components/SelenePillButton.swift b/Sources/NXLibrary/Views/Components/SelenePillButton.swift index bcde129e..b41942be 100644 --- a/Sources/NXLibrary/Views/Components/SelenePillButton.swift +++ b/Sources/NXLibrary/Views/Components/SelenePillButton.swift @@ -5,6 +5,7 @@ import NXLibraryCore struct SelenePillButton: View { @Environment(\.seleneCanvas) private var canvas @Environment(\.seleneReduceMotion) private var reduceMotion + @Environment(\.nxAppLocale) private var localization let title: String? var icon: MaterialIcon? = nil @@ -28,7 +29,10 @@ struct SelenePillButton: View { MaterialIconView(icon, size: iconSize) } if let title { - Text(L10n.text(title)).seleneFont(21) + // A pill's title stays on one line: the pill grows instead. + Text(L10n.text(title, context: localization)).seleneFont(21) + .lineLimit(1) + .fixedSize() } if waveDots { WaveDots() diff --git a/Sources/NXLibrary/Views/Components/SeleneStatsRow.swift b/Sources/NXLibrary/Views/Components/SeleneStatsRow.swift index 94a94d24..138ba8ba 100644 --- a/Sources/NXLibrary/Views/Components/SeleneStatsRow.swift +++ b/Sources/NXLibrary/Views/Components/SeleneStatsRow.swift @@ -1,7 +1,7 @@ import SwiftUI import NXLibraryCore -/// One stat in the row: a label over a value, or the platform (icon and name). +/// One stat in the row: a label over a value, or the platform (icon and name; Steam's logo alone). struct SeleneStat: Identifiable { enum Value { case text(String) @@ -25,6 +25,7 @@ struct SeleneStat: Identifiable { /// passes its own items and a 28 gap. The caller places it. struct SeleneStatsRow: View { @Environment(\.seleneCanvas) private var canvas + @Environment(\.displayScale) private var displayScale let items: [SeleneStat] /// Space either side of each rule, in Selene units. @@ -59,7 +60,6 @@ struct SeleneStatsRow: View { .shadow(color: .black.opacity(0.45), radius: canvas.u(4)) } - @ViewBuilder private func stat(_ item: SeleneStat) -> some View { VStack(alignment: .leading, spacing: canvas.u(2)) { // Line boxes of Selene's Segoe UI 12 / 21 (16 and 28), so the strip lands 34 below. @@ -71,6 +71,8 @@ struct SeleneStatsRow: View { switch item.value { case .text(let text): value(text) + case .platform(let console) where console == SteamPlatformLogo.platformName: + steamLogo case .platform(let console): HStack(spacing: canvas.u(9)) { SwitchPlatformIcon() @@ -85,6 +87,15 @@ struct SeleneStatsRow: View { .accessibilityElement(children: .combine) } + /// Valve's logo alone in the value's place: as tall as the value line, or the guidelines' on-screen minimum. + /// A taller logo (a 1x display, a small window) starts at the line's top and runs into the space below the row, + /// never up into the label, and the row stays as tall as for any other game. The label above sits closer than + /// the crank's clear space: the label was the player's choice. + private var steamLogo: some View { + SteamPlatformLogo(height: SteamPlatformLogo.height(canvas.u(28), displayScale: displayScale)) + .frame(height: canvas.u(28), alignment: .topLeading) + } + private func value(_ text: String) -> some View { Text(text).seleneFont(21, .semibold).foregroundColor(SeleneTheme.ink) } diff --git a/Sources/NXLibrary/Views/Components/SessionCard.swift b/Sources/NXLibrary/Views/Components/SessionCard.swift index 6e2a1ce7..4198a012 100644 --- a/Sources/NXLibrary/Views/Components/SessionCard.swift +++ b/Sources/NXLibrary/Views/Components/SessionCard.swift @@ -51,9 +51,10 @@ final class SessionCardPresenter: ObservableObject { /// Selene's session card: "Session ended", the game's name and this session · total on the left, the logo on the /// right, the game's art faint behind. 640 × 128 units, top right; it takes no input. struct SessionCardView: View { + @Environment(\.catalogPersonalizations) private var personalizations @Environment(\.seleneCanvas) private var canvas let summary: SessionSummary - let game: PortedGame? + let game: PlayedGame? let metadata: NintendoStoreMetadata? let artwork: ArtworkStore @@ -143,11 +144,11 @@ struct SessionCardView: View { hero = GameArtLoader.shared.cachedHero(for: game) logo = GameArtLoader.shared.cachedLogo(for: game) if hero == nil { - let loaded = await GameArtLoader.shared.hero(for: game, metadata: metadata, artwork: artwork) + let loaded = await GameArtLoader.shared.hero(for: game, metadata: metadata, artwork: artwork, personalizations: personalizations) withAnimation(.easeOut(duration: 0.3)) { hero = loaded } } if logo == nil { - let loaded = await GameArtLoader.shared.logo(for: game, metadata: metadata, artwork: artwork) + let loaded = await GameArtLoader.shared.logo(for: game, metadata: metadata, artwork: artwork, personalizations: personalizations) withAnimation(.easeOut(duration: 0.3)) { logo = loaded } } } @@ -159,7 +160,8 @@ struct SessionCardLayer: View { @Environment(\.seleneCanvas) private var canvas @Environment(\.seleneReduceMotion) private var reduceMotion @ObservedObject var presenter: SessionCardPresenter - let games: [PortedGame] + /// The ended session's game, nxnative or Steam. + let game: (UUID) -> PlayedGame? let metadata: [UUID: NintendoStoreMetadata] let artwork: ArtworkStore @@ -167,7 +169,7 @@ struct SessionCardLayer: View { ZStack(alignment: .topTrailing) { if let summary = presenter.shown { SessionCardView(summary: summary, - game: games.first { $0.id == summary.gameID }, + game: game(summary.gameID), metadata: metadata[summary.gameID], artwork: artwork) .id(summary.id) diff --git a/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift b/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift index 4697cb40..f27da0f6 100644 --- a/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift +++ b/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift @@ -9,6 +9,7 @@ import NXLibraryCore /// generic icon. Crossfades when fetched art arrives. /// The caller applies the corner radius. struct SpotlightTileArtwork: View { + @Environment(\.catalogPersonalizations) private var personalizations let game: PortedGame /// Side length in points, already scaled by the caller. let side: CGFloat @@ -20,11 +21,29 @@ struct SpotlightTileArtwork: View { @ObservedObject private var picks = ArtworkPicks.shared @State private var better: NSImage? @State private var picked: NSImage? + @State private var loadedPickKey: NSString? + /// The first look-up has ended (art found or not): the tile is ready for Spotlight's entrance. + @State private var settled = false + + private var automaticKey: NSString { "nxnative|\(game.id)" as NSString } + + private func pickKey(_ url: URL) -> NSString { + "nxnative|pick|\(url.path)|\(picks.revision)" as NSString + } + + /// Read the warm cache while constructing the view, before its task runs. + private var pickedImage: NSImage? { + guard let url = picks.url(titleID: personalizations.nxnativeKey(for: game), slot: .icon) else { return nil } + let key = pickKey(url) + return TileArtMemo.shared.object(forKey: key) ?? (loadedPickKey == key ? picked : nil) + } + + private var automaticImage: NSImage? { better ?? TileArtMemo.shared.object(forKey: automaticKey) } var body: some View { ZStack { SeleneTheme.glassSolid - if let picked { + if let picked = pickedImage { Image(nsImage: picked) .resizable() .interpolation(.high) @@ -34,7 +53,7 @@ struct SpotlightTileArtwork: View { .resizable() .interpolation(.high) .aspectRatio(contentMode: .fill) - } else if let better { + } else if let better = automaticImage { Image(nsImage: better) .resizable() .aspectRatio(contentMode: .fill) @@ -47,21 +66,31 @@ struct SpotlightTileArtwork: View { } .frame(width: side, height: side) .clipped() + .preference(key: TileArtPendingKey.self, value: settled ? 0 : 1) .task(id: "\(game.id)|\(picks.revision)") { - if let url = picks.url(titleID: game.titleId ?? game.uniqueKey, slot: .icon) { - picked = await GameArtLoader.decode(at: url, maxPixelSize: 512) + defer { if !settled { settled = true } } + if let url = picks.url(titleID: personalizations.nxnativeKey(for: game), slot: .icon) { + let key = pickKey(url) + let decoded: NSImage? + if let cached = TileArtMemo.shared.object(forKey: key) { decoded = cached } + else { decoded = await GameArtLoader.decode(at: url, maxPixelSize: 512) } + guard !Task.isCancelled else { return } + if let decoded { TileArtMemo.store(decoded, for: key) } + picked = decoded + loadedPickKey = key return } picked = nil + loadedPickKey = nil guard !ownIconFirst || GameIconProvider.squareArt(for: game) == nil else { return } - let key = game.id.uuidString as NSString + let key = automaticKey if let memo = TileArtMemo.shared.object(forKey: key) { better = memo return } let loaded = await loadIcon() guard !Task.isCancelled, let loaded else { return } - TileArtMemo.shared.setObject(loaded, forKey: key) + TileArtMemo.store(loaded, for: key) withAnimation(.easeInOut(duration: 0.2)) { better = loaded } } } @@ -73,11 +102,23 @@ struct SpotlightTileArtwork: View { } } +/// How many tiles below are still looking up their first art; Spotlight's entrance waits for none (or 1 s). +struct TileArtPendingKey: PreferenceKey { + static let defaultValue = 0 + static func reduce(value: inout Int, nextValue: () -> Int) { value += nextValue() } +} + /// Decoded tile art, so a tile that scrolls back into the row paints at once. -private enum TileArtMemo { +enum TileArtMemo { static let shared: NSCache<NSString, NSImage> = { let cache = NSCache<NSString, NSImage>() cache.countLimit = 200 + cache.totalCostLimit = 160 * 1024 * 1024 return cache }() + + static func store(_ image: NSImage, for key: NSString) { + let pixels = image.representations.first.map { $0.pixelsWide * $0.pixelsHigh } ?? 0 + shared.setObject(image, forKey: key, cost: max(pixels, 1) * 4) + } } diff --git a/Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift b/Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift index 2d60dd9b..d7f2e523 100644 --- a/Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift +++ b/Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift @@ -3,7 +3,7 @@ import AppKit import NXLibraryCore /// Adds the player's SteamGridDB API key: pasted, checked with SteamGridDB, then kept on this Mac. Shown from -/// Settings → Look and from Change artwork. Return saves, Esc cancels; on a controller A chooses the focused pill, +/// Settings → Online services and from Change artwork. Return saves, Esc cancels; on a controller A chooses the focused pill, /// Left/Right move between them and B cancels. The owner stops its own input while the dialog is open. struct SteamGridDBKeyDialog: View { @ObservedObject var viewModel: AppViewModel diff --git a/Sources/NXLibrary/Views/Components/SteamPlatformLogo.swift b/Sources/NXLibrary/Views/Components/SteamPlatformLogo.swift new file mode 100644 index 00000000..f33170cc --- /dev/null +++ b/Sources/NXLibrary/Views/Components/SteamPlatformLogo.swift @@ -0,0 +1,40 @@ +import AppKit +import SwiftUI + +/// Valve's Steam logo, the inverse (white) artwork from the Steam brand guidelines, unaltered: it stands alone, +/// with its ® mark, at least 50 pixels tall on screen. Valve's attribution is in NOTICE and in Settings › About. +/// Without the artwork in the bundle the platform is written out instead, as a stat value. +struct SteamPlatformLogo: View { + static let platformName = "Steam" + /// The guidelines' on-screen minimum, in pixels. + static let minimumPixels: CGFloat = 50 + + @Environment(\.displayScale) private var displayScale + + /// The height asked for, raised to the on-screen minimum on this display. + let height: CGFloat + + static func height(_ wanted: CGFloat, displayScale: CGFloat) -> CGFloat { + max(wanted, minimumPixels / max(displayScale, 1)) + } + + private static let artwork: NSImage? = Bundle.main.url(forResource: "SteamLogo", withExtension: "png", + subdirectory: "Brands").flatMap(NSImage.init(contentsOf:)) + + var body: some View { + Group { + if let artwork = Self.artwork { + Image(nsImage: artwork) + .resizable() + .interpolation(.high) + .aspectRatio(contentMode: .fit) + .frame(height: Self.height(height, displayScale: displayScale)) + .accessibilityLabel(Text(verbatim: Self.platformName)) + } else { + Text(Self.platformName) + .seleneFont(21, .semibold) + .foregroundColor(SeleneTheme.ink) + } + } + } +} diff --git a/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift b/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift index 3040f9eb..d5833f04 100644 --- a/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift +++ b/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift @@ -8,6 +8,7 @@ import NXLibraryCore /// is found, or when GameTDB has none, a composed cover: the blurred Title DB /// banner, the game's icon and its name. The caller applies the corner radius. struct SwitchBoxArtCover: View { + @Environment(\.catalogPersonalizations) private var personalizations let game: PortedGame let width: CGFloat let height: CGFloat @@ -81,7 +82,7 @@ struct SwitchBoxArtCover: View { [game.name] + (officialName.map { [$0] } ?? []) } - private var titleID: String { game.titleId ?? game.uniqueKey } + private var titleID: String { personalizations.nxnativeKey(for: game) } private var coverKey: String { "\(game.id)|\(officialName ?? "")|\(indexVersion)|\(picks.revision)" } diff --git a/Sources/NXLibrary/Views/Components/TileMotionLayers.swift b/Sources/NXLibrary/Views/Components/TileMotionLayers.swift index d893e6fe..dc4bde38 100644 --- a/Sources/NXLibrary/Views/Components/TileMotionLayers.swift +++ b/Sources/NXLibrary/Views/Components/TileMotionLayers.swift @@ -269,3 +269,94 @@ final class TileShineLayerView: TileMotionLayerView { forKey: "sweep.end") } } + +/// A downloading Steam game's mark (a thin arrow in a circle) pulsing in brightness (`TileMotion.downloadMarkOpacity`) +/// in the render server like the selected tile's glow: smooth at the screen's rate, nothing for the app between +/// frames. Every downloading tile follows the same clock, so several pulse together. Full and still with Reduce motion. +struct DownloadMarkLayers: NSViewRepresentable { + /// The symbol's point size. + let size: CGFloat + let still: Bool + + func makeNSView(context: Context) -> DownloadMarkLayerView { DownloadMarkLayerView(size: size, still: still) } + + func updateNSView(_ view: DownloadMarkLayerView, context: Context) { + view.size = size + view.still = still + } +} + +final class DownloadMarkLayerView: TileMotionLayerView { + var size: CGFloat { didSet { if size != oldValue { needsLayout = true } } } + var still: Bool { + didSet { + guard still != oldValue else { return } + mark.removeAllAnimations() + Self.withoutActions { mark.opacity = 1 } + startLoops() + } + } + + private let mark = CALayer() + /// The point size and scale the symbol was last drawn at. + private var drawn: (size: CGFloat, scale: CGFloat)? + + init(size: CGFloat, still: Bool) { + self.size = size + self.still = still + super.init() + // The shadow the lock and the word wear, so the white reads on light art too. + mark.shadowColor = NSColor.black.cgColor + mark.shadowOpacity = 0.45 + mark.shadowOffset = .zero + root.addSublayer(mark) + } + + required init?(coder: NSCoder) { nil } + + override func arrange(scale: CGFloat) { + // A selected tile grows a little: drawn a third finer than the screen, the symbol stays sharp when it does. + let detail = scale * 1.35 + if drawn?.size != size || drawn?.scale != detail, let image = Self.symbol(size: size) { + mark.contents = Self.bitmap(image, scale: detail) + mark.bounds = CGRect(origin: .zero, size: image.size) + mark.contentsScale = detail + mark.shadowRadius = size * 0.14 + drawn = (size, detail) + } + mark.position = CGPoint(x: bounds.midX, y: bounds.midY) + } + + /// The symbol drawn once, at `scale` pixels per point. + private static func bitmap(_ image: NSImage, scale: CGFloat) -> CGImage? { + let width = Int((image.size.width * scale).rounded(.up)), height = Int((image.size.height * scale).rounded(.up)) + guard width > 0, height > 0, + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } + context.scaleBy(x: scale, y: scale) + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false) + image.draw(in: CGRect(origin: .zero, size: image.size)) + NSGraphicsContext.restoreGraphicsState() + return context.makeImage() + } + + private static func symbol(size: CGFloat) -> NSImage? { + guard size > 0 else { return nil } + let config = NSImage.SymbolConfiguration(pointSize: size, weight: .light) + .applying(.init(paletteColors: [NSColor.white.withAlphaComponent(0.92)])) + return NSImage(systemSymbolName: "arrow.down.circle", accessibilityDescription: nil)? + .withSymbolConfiguration(config) + } + + override func startLoops() { + guard !still, window != nil, mark.animation(forKey: "pulse") == nil else { return } + let now = Date().timeIntervalSinceReferenceDate + let pulse = TileMotion.loop(period: TileMotion.downloadPeriod, steps: 84) { TileMotion.downloadMarkOpacity(at: $0) } + mark.add(Self.loop("opacity", values: pulse.values.map { NSNumber(value: $0) }, keyTimes: pulse.keyTimes, + period: TileMotion.downloadPeriod, + phase: TileMotion.phase(period: TileMotion.downloadPeriod, at: now)), + forKey: "pulse") + } +} diff --git a/Sources/NXLibrary/Views/Console/ConsoleView.swift b/Sources/NXLibrary/Views/Console/ConsoleView.swift index 7539ed8d..989b397d 100644 --- a/Sources/NXLibrary/Views/Console/ConsoleView.swift +++ b/Sources/NXLibrary/Views/Console/ConsoleView.swift @@ -509,6 +509,7 @@ public struct ConsoleView: View { keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in guard router.route == .console, !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, !NativeMenuCommands.shared.isTracking, !router.isMenuPresented, viewModel.gameToClose == nil, diff --git a/Sources/NXLibrary/Views/ControlsView.swift b/Sources/NXLibrary/Views/ControlsView.swift index cb082504..0aad422c 100644 --- a/Sources/NXLibrary/Views/ControlsView.swift +++ b/Sources/NXLibrary/Views/ControlsView.swift @@ -60,7 +60,7 @@ public struct ControlsView: View { Text(L10n.text("Controls")) .seleneFont(40) .foregroundColor(SeleneTheme.ink) - Text(inGame ? L10n.text("Default game inputs. Older builds may differ.") : L10n.text("Navigate NX Library.")) + Text(inGame ? L10n.text("Default game inputs. Older builds may differ.") : L10n.text("Navigate Arcane.")) .seleneFont(19) .foregroundColor(SeleneTheme.ink60) .padding(.bottom, canvas.u(18)) diff --git a/Sources/NXLibrary/Views/Detail/AchievementIcon.swift b/Sources/NXLibrary/Views/Detail/AchievementIcon.swift new file mode 100644 index 00000000..9fb4db85 --- /dev/null +++ b/Sources/NXLibrary/Views/Detail/AchievementIcon.swift @@ -0,0 +1,80 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// An achievement's icon from Steam's CDN, cached by `SteamMetadataService.achievementIcon`. A neutral square +/// stands in until it arrives, and stays when it cannot be loaded (offline, unknown file). +/// Decoded icons are kept in memory: the Achievements list draws only the rows near the window and makes them +/// again as they scroll back, and each came back as the grey square fading to its icon, a flicker in the glide. +struct AchievementIcon: View { + @Environment(\.seleneCanvas) private var canvas + + let appID: UInt32 + let file: String? + /// Canvas units. + let size: CGFloat + /// Locked: Steam's gray icon, dimmed a little more on the page. + var dimmed = false + /// A secret not unlocked yet (`AchievementRow.isMasked`): blurred past reading, under the app's lock, as a + /// failed port's art (maintainer's idea, 16 Nov 2026). The lock stays bright on a dimmed icon. + var secret = false + + /// The file whose icon arrived while this view was on screen: only redraws it, the image is in `memory`. + @State private var loaded: String? + + /// Every icon decoded this session, by game and file; the system may let some go under memory pressure. + @MainActor private static let memory: NSCache<NSString, NSImage> = { + let cache = NSCache<NSString, NSImage>() + cache.countLimit = 400 + return cache + }() + + private static func key(_ appID: UInt32, _ file: String) -> NSString { "\(appID)/\(file)" as NSString } + + var body: some View { + let shape = RoundedRectangle(cornerRadius: canvas.u(size * 0.16), style: .continuous) + // Read so the arrival redraws this view; the image itself comes from `memory`. + let _ = loaded + let image = file.flatMap { Self.memory.object(forKey: Self.key(appID, $0)) } + ZStack { + shape.fill(SeleneTheme.ink15) + if let image { + Image(nsImage: image) + .resizable() + .interpolation(.high) + .aspectRatio(contentMode: .fill) + .blur(radius: secret ? canvas.u(size * 0.09) : 0, opaque: true) + .transition(.opacity) + } + } + .frame(width: canvas.u(size), height: canvas.u(size)) + .clipShape(shape) + .opacity(dimmed ? 0.5 : 1) + .overlay { + if secret { + MaterialIconView(.lock, size: max(16, size * 0.36)) + .foregroundColor(.white.opacity(0.9)) + .shadow(color: .black.opacity(0.55), radius: canvas.u(size * 0.05)) + } + } + .accessibilityHidden(true) + .task(id: file) { + guard let file, Self.memory.object(forKey: Self.key(appID, file)) == nil, + let url = await SteamMetadataService.shared.achievementIcon(appID: appID, file: file), + !Task.isCancelled else { return } + // Read and decoded off the main thread; at most 2 MiB, already validated as an image. + guard let decoded = await Task.detached(priority: .utility, operation: { Self.decode(url) }).value else { return } + Self.memory.setObject(decoded, forKey: Self.key(appID, file)) + guard !Task.isCancelled else { return } + withAnimation(SeleneTheme.quick) { loaded = file } + } + } + + /// The file's pixels decoded now, not at the first draw: NSImage(contentsOf:) leaves that to the main thread. + private nonisolated static func decode(_ url: URL) -> NSImage? { + guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), + let cgImage = CGImageSourceCreateImageAtIndex(source, 0, [kCGImageSourceShouldCacheImmediately: true] as CFDictionary) + else { return nil } + return NSImage(cgImage: cgImage, size: NSSize(width: cgImage.width, height: cgImage.height)) + } +} diff --git a/Sources/NXLibrary/Views/Detail/BuildSourcesPanel.swift b/Sources/NXLibrary/Views/Detail/BuildSourcesPanel.swift deleted file mode 100644 index 7f0d9ac9..00000000 --- a/Sources/NXLibrary/Views/Detail/BuildSourcesPanel.swift +++ /dev/null @@ -1,219 +0,0 @@ -import SwiftUI -import NXLibraryCore - -/// One action in Build & Sources: a Selene row. `enabled` dims the title; the -/// row still takes focus and a click (the page decides what a press does). -struct BuildSourcesRow: Identifiable { - let id: String - let title: String - var enabled: Bool = true - let action: () -> Void -} - -/// Band 2's left column (Selene's "Your captures" slot, spec §5.4): the sources -/// status with the engine and toolchain, the app's version, size and file, and -/// the page's actions as a grid of small buttons, three to a row: Left and Right -/// move within a row, Up and Down between rows (see `DetailsFocus`). Narrower -/// than `wide` (Spotlight's column beside About this game), the status and the -/// app's file take two lines each. -struct BuildSourcesPanel: View { - @Environment(\.seleneCanvas) private var canvas - - let presentation: GameDetailPresentation - /// The app's file name, shown with the version and size. - let appFileName: String - /// The Metal gate refuses new builds: the status line says where to fix it. - let buildBlocked: Bool - /// The gate's line for the refusal (ToolchainGateCopy); a newer Metal compiler reads calm, not orange. - var blockedHint: ToolchainGateCopy.Summary? = nil - let rows: [BuildSourcesRow] - /// The focused row, nil when the band has no focus. - let focusedRow: Int? - let onHoverRow: (Int) -> Void - let onPressRow: (Int) -> Void - /// The panel's width in canvas units. - var width: CGFloat = Self.width - - static let width: CGFloat = 1100 - /// Spotlight's column: three buttons and their gaps. - static let narrowWidth: CGFloat = 520 - static let columns = SpotlightState.actionColumns - static let cellWidth: CGFloat = 168 - - private var wide: Bool { width >= 800 } - - var body: some View { - VStack(alignment: .leading, spacing: 0) { - header - status - Text(wide ? L10n.format("Version %@ · %@ · %@", [String(describing: (presentation.version)), String(describing: (presentation.size)), String(describing: (appFileName))]) - : L10n.format("Version %@ · %@", [String(describing: (presentation.version)), String(describing: (presentation.size))])) - .seleneFont(15) - .foregroundColor(SeleneTheme.ink60) - .lineLimit(1) - .truncationMode(.middle) - .padding(.top, canvas.u(4)) - .padding(.leading, canvas.u(2)) - if !wide { - Text(appFileName) - .seleneFont(15) - .foregroundColor(SeleneTheme.ink60) - .lineLimit(1) - .truncationMode(.middle) - .padding(.leading, canvas.u(2)) - } - if presentation.sourcesDetached { - Text(presentation.canPlay - ? L10n.text("Game files are missing or not attached. Play is available; attach them to rebuild.") - : L10n.text("Game files are missing or not attached. Attach them to build.")) - .seleneFont(15) - .foregroundColor(SeleneTheme.ink60) - .padding(.top, canvas.u(4)) - .padding(.leading, canvas.u(2)) - } - grid - .padding(.top, canvas.u(14)) - } - .frame(width: canvas.u(width), alignment: .topLeading) - } - - private var header: some View { - HStack(spacing: canvas.u(8)) { - Text(L10n.text("Build & Sources")) - .seleneFont(21, .semibold) - .foregroundColor(SeleneTheme.ink) - SeleneInfoTip(L10n.text("NX Library uses symlinks to your game ROM files to build the macOS native binary. Rebuilding uses your current engine pin and settings, and preserves your game saves. ") - + (presentation.sourcesDetached - ? L10n.text("The sources are detached: attach them again to rebuild.") - : L10n.text("The original sources are attached. Rebuild writes a new app and keeps the previous one if it fails."))) - } - .padding(.top, canvas.u(2)) - .padding(.bottom, canvas.u(14)) - .padding(.leading, canvas.u(2)) - } - - @ViewBuilder private var status: some View { - if wide { - HStack(spacing: canvas.u(14)) { - sourcesStatus - engineStatus - blockedStatus - } - .padding(.leading, canvas.u(2)) - } else { - VStack(alignment: .leading, spacing: canvas.u(4)) { - sourcesStatus - HStack(spacing: canvas.u(14)) { engineStatus } - blockedStatus - } - .padding(.leading, canvas.u(2)) - } - } - - private var sourcesStatus: some View { - HStack(spacing: canvas.u(7)) { - Circle() - .fill(presentation.sourcesDetached ? SeleneTheme.untested : SeleneTheme.success) - .frame(width: canvas.u(9), height: canvas.u(9)) - Text(presentation.sourcesDetached ? L10n.text("Sources detached") : L10n.text("Sources attached")) - .seleneFont(15, .medium) - .foregroundColor(presentation.sourcesDetached - ? SeleneTheme.untested.opacity(0.9) - : SeleneTheme.success.opacity(0.9)) - } - } - - /// The engine and the toolchain. - @ViewBuilder private var engineStatus: some View { - Text(L10n.format("Engine %@", [String(describing: (presentation.engineCommitShort))])) - .seleneFont(15, .semibold) - .monospacedDigit() - .foregroundColor(SeleneTheme.ink82) - Text(presentation.toolchainVerified ? L10n.text("Certified") : L10n.text("Untested toolchain")) - .seleneFont(15, .medium) - .foregroundColor(presentation.toolchainVerified - ? SeleneTheme.success.opacity(0.85) - : SeleneTheme.untested.opacity(0.9)) - } - - @ViewBuilder private var blockedStatus: some View { - if buildBlocked { - Text(blockedHint.flatMap { $0.buildHint.isEmpty ? nil : $0.buildHint } ?? L10n.text("Build blocked — Settings → Engine")) - .seleneFont(15, .semibold) - .foregroundColor(blockedHint?.tone == .info ? SeleneTheme.ink82 : SeleneTheme.untested) - } - } - - /// Small tool buttons, three to a row (`SpotlightState.actionColumns`): squarer - /// and quieter than Play and Options above, so they read as secondary. - private var grid: some View { - VStack(alignment: .leading, spacing: canvas.u(8)) { - ForEach(Array(stride(from: 0, to: rows.count, by: Self.columns)), id: \.self) { first in - HStack(spacing: canvas.u(8)) { - ForEach(first..<min(first + Self.columns, rows.count), id: \.self) { index in - cell(rows[index], index: index) - } - } - } - } - } - - private func cell(_ row: BuildSourcesRow, index: Int) -> some View { - let radius = canvas.u(7) - let shape = RoundedRectangle(cornerRadius: radius, style: .continuous) - return Button { onPressRow(index) } label: { - Text(row.title) - .seleneFont(14, .medium) - .foregroundColor(row.enabled ? SeleneTheme.ink90 : SeleneTheme.ink60) - .lineLimit(1) - .minimumScaleFactor(0.8) - .padding(.horizontal, canvas.u(10)) - .frame(width: canvas.u(Self.cellWidth), height: canvas.u(32)) - .background(shape.fill(SeleneTheme.glass)) - .overlay(shape.strokeBorder(SeleneTheme.ink15, lineWidth: max(1, canvas.u(1)))) - .contentShape(shape) - .seleneRowFocus(focusedRow == index, radius: radius) - } - .buttonStyle(.plain) - .onHover { if $0 { onHoverRow(index) } } - .accessibilityLabel(row.title) - } -} - -extension BuildSourcesRow { - /// Build & Sources' actions for a game, in grid order. Store links and the - /// Nintendo search appear only when they have a target. Shared by Details and Spotlight. - @MainActor - static func rows(for game: PortedGame, presentation p: GameDetailPresentation, buildBlocked: Bool, - viewModel: AppViewModel, rebuild: @escaping () -> Void) -> [BuildSourcesRow] { - var rows: [BuildSourcesRow] = [ - BuildSourcesRow(id: "attach", title: L10n.text("Attach sources…")) { - viewModel.locateSources(for: game) - }, - BuildSourcesRow(id: "rebuild", title: L10n.text("Rebuild"), enabled: p.canRebuild && !buildBlocked) { - rebuild() - }, - BuildSourcesRow(id: "log", title: L10n.text("Open log")) { - viewModel.revealLog(for: game) - }, - BuildSourcesRow(id: "save", title: L10n.text("Open save folder")) { - viewModel.revealSaveFolder(URL(fileURLWithPath: p.savePath)) - }, - BuildSourcesRow(id: "app", title: L10n.text("Reveal app in Finder")) { - viewModel.revealInFinder(url: game.url) - } - ] - if let store = p.storeURL { - rows.append(BuildSourcesRow(id: "store", title: L10n.text("Store page")) { viewModel.openURL(store) }) - } - if let hltb = p.hltbURL { - rows.append(BuildSourcesRow(id: "hltb", title: L10n.text("HowLongToBeat")) { viewModel.openURL(hltb) }) - } - if p.description.isEmpty, let search = viewModel.nintendoStoreSearchURL(for: game) { - rows.append(BuildSourcesRow(id: "search", title: L10n.text("Search Nintendo Store")) { - viewModel.openURL(search) - }) - } - return rows - } -} diff --git a/Sources/NXLibrary/Views/Detail/CriticRatingValue.swift b/Sources/NXLibrary/Views/Detail/CriticRatingValue.swift new file mode 100644 index 00000000..25db8d72 --- /dev/null +++ b/Sources/NXLibrary/Views/Detail/CriticRatingValue.swift @@ -0,0 +1,68 @@ +import SwiftUI +import NXLibraryCore + +/// A read-only value in Details, not a new card or a personal-vote control. +struct CriticRatingValue: View { + @Environment(\.seleneCanvas) private var canvas + @Environment(\.nxAppLocale) private var localization + let result: CriticRatingResult? + + var body: some View { + Group { + if let rating = result?.rating { + HStack(alignment: .center, spacing: canvas.u(8)) { + HStack(spacing: canvas.u(2)) { + ForEach(Array(rating.starFills.enumerated()), id: \.offset) { _, fill in + Image(systemName: "star.fill") + .foregroundColor(SeleneTheme.ink.opacity(0.18)) + .overlay(alignment: .leading) { + Image(systemName: "star.fill") + .foregroundColor(SeleneTheme.ink90) + .mask(alignment: .leading) { + GeometryReader { geometry in + Rectangle().frame(width: geometry.size.width * fill) + } + } + } + } + } + .font(.system(size: canvas.u(13), weight: .regular)) + .fixedSize() + .accessibilityHidden(true) + Text(rating.number(locale: localization.formatLocale)) + .seleneFont(15, .semibold) + .foregroundColor(SeleneTheme.ink90) + .monospacedDigit() + .fixedSize() + Text(rating.attribution(context: localization)) + .seleneFont(11) + .foregroundColor(SeleneTheme.ink60) + .lineLimit(1) + .truncationMode(.tail) + } + .help(provenance(rating)) + .accessibilityElement(children: .ignore) + .accessibilityLabel(provenance(rating)) + } else { + Text(result == nil ? L10n.text("Loading…") : L10n.text("Rating unavailable")) + .seleneFont(15) + .foregroundColor(SeleneTheme.ink60) + } + } + } + + private func provenance(_ rating: CriticRating) -> String { + var lines = [L10n.text(rating.labelKey), rating.number(locale: localization.formatLocale), + rating.attribution(context: localization), + rating.platforms.isEmpty ? L10n.text("Platform not specified") + : (rating.platforms.contains("Q14116") ? "macOS" + : (rating.platforms.contains("Q122761124") ? "Nintendo Switch 2" : "Nintendo Switch"))] + if let count = rating.reviewCount { + lines.append(L10n.format(rating.isCommunity ? "User ratings: %d" : "Critic reviews: %d", [count])) + } + if let date = rating.scoreDate { lines.append(String(date.dropFirst(date.hasPrefix("+") ? 1 : 0).prefix(10))) } + if result?.isStale == true { lines.append(L10n.text("Saved rating · refresh unavailable")) } + lines.append(rating.sourceURL.absoluteString) + return lines.joined(separator: " · ") + } +} diff --git a/Sources/NXLibrary/Views/Detail/DetailsAchievementsCard.swift b/Sources/NXLibrary/Views/Detail/DetailsAchievementsCard.swift new file mode 100644 index 00000000..b0898bb9 --- /dev/null +++ b/Sources/NXLibrary/Views/Detail/DetailsAchievementsCard.swift @@ -0,0 +1,170 @@ +import SwiftUI +import NXLibraryCore + +/// A Steam game's achievements at the top of the page's right column, above the source's panel and beside +/// About this game (layout "A", maintainer's choice, 16 Nov 2026): the best crystal earned large on the left, beside it +/// "3/41" over the completion (complete: "Arcane" over "All achievements"), the last three unlocked icons on the right +/// and a thin bar under them while incomplete, in a light, nearly transparent panel with a thin outline, the surface +/// of the panel's buttons without their dark fill (maintainer's choice, 15 Nov 2026). Focused, Selene's ring sits on the panel's edge. +/// Shown only when the game has achievements and Steam's files read. A or a click opens the Achievements screen; +/// under the pointer or the controller's focus it says so (maintainer's choice, 15 Nov 2026): the crystal comes to +/// colour, the line under the headline gives way to "View all", the three icons fan out and brighten, and +/// the panel lightens. Details, not a button, does none of it. +/// With Reduce motion the text and light change without movement. +struct DetailsAchievementsCard: View { + @Environment(\.seleneCanvas) private var canvas + @Environment(\.seleneReduceMotion) private var reduceMotion + @State private var hovered = false + + /// What the card shows: set from hover and focus inside its own animation, so only the fan, the text swap + /// and the light animate (an `.animation` on the card would catch every other change in the same update). + @State private var active = false + /// The fan and the text's slide move only where the card can move as one block (`GlideGroup`); + /// elsewhere, as with Reduce motion, only the text and the light change. + private var moves: Bool { !reduceMotion && GlideGroup.available } + private var fanned: Bool { active && moves } + /// Slow and soft, and never past its target (a spring overshot); interrupted, it blends towards the new end. + private var reveal: Animation { !moves ? SeleneTheme.quick : .timingCurve(0.22, 1, 0.36, 1, duration: 0.45) } + + let summary: AchievementSummary + let appID: UInt32 + let focused: Bool + let onOpen: () -> Void + + /// The column's width (`DetailsPanel.narrowWidth`). + static let width = DetailsPanel.narrowWidth + private static let radius: CGFloat = SeleneTheme.contentRadius + + var body: some View { + let shape = RoundedRectangle(cornerRadius: canvas.u(Self.radius), style: .continuous) + VStack(alignment: .leading, spacing: 0) { + DetailsBandTitle(text: L10n.text("Achievements")) + VStack(alignment: .leading, spacing: canvas.u(16)) { + HStack(alignment: .center, spacing: canvas.u(16)) { + if let tier = summary.bestTier { crystal(tier) } + VStack(alignment: .leading, spacing: canvas.u(4)) { + headline + ZStack(alignment: .leading) { + Text(complete ? L10n.text("All achievements") + : L10n.format("%d%% complete", [summary.percentComplete])) + .foregroundColor(SeleneTheme.ink60) + .monospacedDigit() + .opacity(active ? 0 : 1) + .offset(y: fanned ? -canvas.u(5) : 0) + Text(L10n.text("View all")) + .foregroundColor(SeleneTheme.ink) + .opacity(active ? 1 : 0) + .offset(y: active || !moves ? 0 : canvas.u(5)) + } + .seleneFont(14, .semibold) + } + .lineLimit(1) + Spacer(minLength: 0) + icons + } + if !complete { + AchievementProgressBar(fraction: summary.total > 0 ? Double(summary.unlocked) / Double(summary.total) : 0, + height: 5, track: SeleneTheme.ink25) + } + } + .padding(.horizontal, canvas.u(18)) + .padding(.vertical, canvas.u(16)) + .frame(width: canvas.u(Self.width), alignment: .leading) + // Match the option 3 mockup: a transparent tint, without a second layer of material blur. + .background(shape.fill(SeleneTheme.ink.opacity(active ? 0.10 : 0.05))) + .overlay(shape.strokeBorder(SeleneTheme.ink.opacity(active ? 0.32 : 0.16), lineWidth: max(1, canvas.u(1)))) + .contentShape(shape) + .onHover { hovered = $0 } + .onAppear { active = hovered || focused } + .onChange(of: hovered || focused) { wanted in + withAnimation(reveal) { active = wanted } + } + .seleneRowFocus(focused, radius: canvas.u(Self.radius)) + .onTapGesture(perform: onOpen) + .accessibilityElement(children: .ignore) + .accessibilityLabel(L10n.format("Achievements: %d of %d", [summary.unlocked, summary.total])) + .accessibilityAddTraits(.isButton) + .accessibilityAction { onOpen() } + } + // The fan runs in its own, faster animation: without the group its leaves took the page's glide with it + // and ran ahead of the panel, out of its box. + .modifier(GlideGroup()) + } +} + +extension DetailsAchievementsCard { + /// Every achievement unlocked: the card names the reward instead of counting (layout "A", 16 Nov 2026). + private var complete: Bool { summary.isComplete } + + /// Complete, the tier's name ("Arcane"); otherwise "3/41", the unlocked count bright and the total dimmer. + private var headline: some View { + Group { + if complete { + Text(AchievementTier.arcane.displayName()).foregroundColor(SeleneTheme.ink) + } else { + Text("\(summary.unlocked)").foregroundColor(SeleneTheme.ink) + + Text("/\(summary.total)").foregroundColor(SeleneTheme.ink60) + } + } + .seleneFont(22, .bold) + .monospacedDigit() + } + + /// The best crystal earned (`AchievementSummary.bestTier`), large at the card's left (maintainer's choice, + /// 16 Nov 2026): black and white at rest, fully opaque so it doesn't read as a locked tier, in colour when the + /// card is hovered or focused, with the fan. The Arcane orb a size up: it fills less of its square. + /// Arcane is the maintainer's looping video (16 Nov 2026), which greys, lights, scales and plays itself in + /// Core Animation; without it (a damaged bundle) the still orb does the same in SwiftUI. + @ViewBuilder + private func crystal(_ tier: AchievementTier) -> some View { + if let video = tier.videoURL { + ArcaneOrbVideo(url: video, active: active, moves: moves) + .frame(width: canvas.u(76), height: canvas.u(76)) + .accessibilityHidden(true) + } else { + TierCrystal(tier: tier, size: tier == .arcane ? 76 : 64) + .saturation(active ? 1 : 0) + .opacity(active ? 1 : 0.88) + .scaleEffect(fanned ? 1.06 : 1) + } + } + + /// The last three unlocked icons. Active, they fan out like a held hand of cards: the outer ones tilt + /// and drop a little, the gaps open, and all three brighten. + private var icons: some View { + let count = summary.recentIcons.count + let middle = Double(max(count - 1, 0)) / 2 + return HStack(spacing: canvas.u(fanned ? 12 : 8)) { + ForEach(Array(summary.recentIcons.enumerated()), id: \.offset) { index, row in + let side = Double(index) - middle + AchievementIcon(appID: appID, file: row.icon, size: 44, dimmed: summary.unlocked == 0, secret: row.isMasked) + .opacity(active ? 1 : 0.88) + .scaleEffect(fanned ? 1.04 : 1) + .rotationEffect(.degrees(fanned ? side * 5 : 0), anchor: .bottom) + .offset(y: fanned ? canvas.u(CGFloat(abs(side)) * 2) : 0) + .zIndex(-abs(side)) + } + } + } +} + +/// A thin completion bar in the focus colour on a faint track. +struct AchievementProgressBar: View { + @Environment(\.seleneCanvas) private var canvas + let fraction: Double + /// Canvas units: the page's open block uses a finer bar than the screen. + var height: CGFloat = 6 + var track: Color = SeleneTheme.ink15 + + var body: some View { + GeometryReader { proxy in + ZStack(alignment: .leading) { + Capsule().fill(track) + Capsule().fill(SeleneTheme.focus) + .frame(width: proxy.size.width * min(max(fraction, 0), 1)) + } + } + .frame(height: canvas.u(height)) + .accessibilityHidden(true) + } +} diff --git a/Sources/NXLibrary/Views/Detail/DetailsBands.swift b/Sources/NXLibrary/Views/Detail/DetailsBands.swift index 26df9168..de1b2cc8 100644 --- a/Sources/NXLibrary/Views/Detail/DetailsBands.swift +++ b/Sources/NXLibrary/Views/Detail/DetailsBands.swift @@ -48,58 +48,13 @@ struct DetailsScreenshotsBand: View { } } -/// Your activity, the right column of band 2 (Selene's SeleneDetailsBand2b): -/// play time and last played over this week and the rank among your games. -/// The rank is hidden until the game has play time. -struct DetailsActivityColumn: View { - @Environment(\.seleneCanvas) private var canvas - - let presentation: GameDetailPresentation - - static let width: CGFloat = 510 - - var body: some View { - VStack(alignment: .leading, spacing: 0) { - DetailsBandTitle(text: L10n.text("Your activity")) - VStack(alignment: .leading, spacing: canvas.u(14)) { - HStack(alignment: .top, spacing: canvas.u(24)) { - cell(L10n.text("PLAY TIME"), presentation.playtime) - cell("LAST PLAYED", presentation.lastPlayed) - } - HStack(alignment: .top, spacing: canvas.u(24)) { - cell(L10n.text("THIS WEEK"), presentation.thisWeek) - if let rank = presentation.rank { - cell(L10n.text("RANK"), rank) - } - } - } - } - .frame(width: canvas.u(Self.width), alignment: .topLeading) - } - - private func cell(_ label: String, _ value: String) -> some View { - VStack(alignment: .leading, spacing: canvas.u(2)) { - Text(L10n.text(label)) - .seleneFont(12, .semibold) - .foregroundColor(SeleneTheme.ink60) - Text(value) - .seleneFont(21, .semibold) - .foregroundColor(SeleneTheme.ink) - .lineLimit(1) - } - .frame(maxWidth: .infinity, alignment: .leading) - .accessibilityElement(children: .combine) - } -} - -/// Band 3: more games from your own library (`MoreLikeThis`), Switch box -/// covers of 173 × 280 (`SwitchBoxArtCover`). A click focuses, a double -/// click opens the game on Spotlight. +/// More games from your own library (`MoreLikeThis`), in portrait covers of 173 × 280. +/// A click focuses, a double click opens the game on Spotlight. struct DetailsMoreBand: View { @Environment(\.seleneCanvas) private var canvas @Environment(\.seleneReduceMotion) private var reduceMotion - let games: [PortedGame] + let games: [CatalogGame] let focusedIndex: Int? let artwork: ArtworkStore let boxArt: BoxArtService @@ -124,12 +79,11 @@ struct DetailsMoreBand: View { } } - private func tile(_ game: PortedGame, index: Int, focused: Bool) -> some View { + private func tile(_ game: CatalogGame, index: Int, focused: Bool) -> some View { let w = canvas.u(Self.width), h = canvas.u(Self.height) let face = RoundedRectangle(cornerRadius: canvas.u(14), style: .continuous) return ZStack { - SwitchBoxArtCover(game: game, width: w, height: h, officialName: officialName(game), - boxArt: boxArt, artwork: artwork, indexVersion: boxArtIndexVersion) + cover(game, width: w, height: h) .clipShape(face) SeleneTileRing(cornerRadius: canvas.u(21), active: focused) .frame(width: w + canvas.u(14), height: h + canvas.u(14)) @@ -145,9 +99,20 @@ struct DetailsMoreBand: View { .accessibilityLabel(game.name) .accessibilityAddTraits(focused ? [.isButton, .isSelected] : .isButton) } + + @ViewBuilder + private func cover(_ game: CatalogGame, width: CGFloat, height: CGFloat) -> some View { + if let native = game.nxnativeGame { + SwitchBoxArtCover(game: native, width: width, height: height, officialName: officialName(native), + boxArt: boxArt, artwork: artwork, indexVersion: boxArtIndexVersion) + } else { + CatalogNativeArtwork(game: game) + .frame(width: width, height: height) + } + } } -/// The game's mods, between Build & Sources and More like this. Left to right (`ModsBandLayout`): installed mods (`ModStore`, at most 5) with their state, +/// The game's mods, between Details and More like this. Left to right (`ModsBandLayout`): installed mods (`ModStore`, at most 5) with their state, /// Manage mods, the GameBanana mods that work (image, name, author, Installed / Update), then status tiles (Retry, the /// "Is this the right game?" candidates, Wrong game?…). The row slides so the focused tile stays on screen. A click /// focuses a tile; a double click (or A) opens it. diff --git a/Sources/NXLibrary/Views/Detail/DetailsPanel.swift b/Sources/NXLibrary/Views/Detail/DetailsPanel.swift new file mode 100644 index 00000000..c390c1cb --- /dev/null +++ b/Sources/NXLibrary/Views/Detail/DetailsPanel.swift @@ -0,0 +1,234 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// One available link under the Details panel. +struct DetailsLink: Identifiable { + let id: String + let title: String + let action: () -> Void +} + +extension DetailsLink { + /// Every source's links, in grid order, each only when it has a target. Technical actions + /// (Rebuild, sources, log, saves) live in Options. + @MainActor + static func links(app: URL?, store: URL?, hltb: URL?, viewModel: AppViewModel) -> [DetailsLink] { + var links: [DetailsLink] = [] + if let app { + links.append(DetailsLink(id: "app", title: L10n.text("Reveal in Finder")) { viewModel.revealInFinder(url: app) }) + } + if let store { + links.append(DetailsLink(id: "store", title: L10n.text("Store page")) { viewModel.openURL(store) }) + } + if let hltb { + links.append(DetailsLink(id: "hltb", title: L10n.text("HowLongToBeat")) { viewModel.openURL(hltb) }) + } + return links + } + + /// The app's folder by its Finder name ("Applications"); never the path. Read once per folder. + @MainActor + static func folderName(of app: URL) -> String? { + folderNames.name(for: app.deletingLastPathComponent()) + } + + /// The Steam library's volume by its localized name ("Macintosh HD"). Read once per library. + @MainActor + static func volumeName(of game: CatalogGame) -> String? { + guard let library = game.steamGame?.firstAvailableInstallation?.libraryURL + else { return nil } + return volumeNames.name(for: library) + } + + @MainActor private static let folderNames = DisplayNameCache { folder in + let name = FileManager.default.displayName(atPath: folder.path) + return name.isEmpty ? nil : name + } + + @MainActor private static let volumeNames = DisplayNameCache { library in + (try? library.resourceValues(forKeys: [.volumeLocalizedNameKey]))?.volumeLocalizedName + } +} + +/// A game's Details in the page's right column, the same for every source (maintainer's choice, +/// 15 Nov 2026): what a player cares about as label → value rows with small grey icons, and the links under them. +/// The rows sit on the page with a hairline between them, no panel (maintainer's choice "3", 16 Nov 2026): only +/// what can be pressed — the achievements card and the links — has a surface. Rows without a value are not shown; +/// with none at all only the title and the links remain, and with no links either nothing does. No build, engine or sources state: that is +/// Options' business, and problems that stop the player show in Play's own note. +struct DetailsPanel: View { + @Environment(\.seleneCanvas) private var canvas + + let facts: [DetailsFact] + let links: [DetailsLink] + /// The focused link, nil when the band has no focus. + let focusedLink: Int? + let onHoverLink: (Int) -> Void + let onPressLink: (Int) -> Void + /// The panel's width in canvas units. + var width: CGFloat = Self.narrowWidth + /// Public identity of the game whose critic score belongs below Installed in. + var ratingQuery: CriticRatingQuery? = nil + @State private var loadedRatingQuery: CriticRatingQuery? + @State private var ratingResult: CriticRatingResult? + @ObservedObject private var igdb = IGDBSettings.shared + @State private var loadedRatingRevision: UUID? + private struct RatingTask: Hashable { let query: CriticRatingQuery?; let revision: UUID } + + /// Spotlight's column beside About this game: three links and their gaps. + static let narrowWidth: CGFloat = 520 + /// The Switch Details page's band: the rows in two columns. + static let wideWidth: CGFloat = 1100 + private static let columnGap: CGFloat = 40 + + private var wide: Bool { width >= 800 } + + var body: some View { + // With nothing to show, no title alone on the page. + Group { + if !facts.isEmpty || !links.isEmpty || ratingQuery != nil { content } + } + .task(id: RatingTask(query: ratingQuery, revision: igdb.revision)) { + loadedRatingQuery = nil + loadedRatingRevision = nil + ratingResult = nil + guard let query = ratingQuery else { return } + let revision = igdb.revision + let credentials = igdb.credentials + do { try await Task.sleep(nanoseconds: 300_000_000) } + catch { return } + let result = await CriticRatingService.shared.preferred(query, credentials: credentials) + guard !Task.isCancelled, revision == igdb.revision else { return } + loadedRatingQuery = query + loadedRatingRevision = revision + ratingResult = result + } + } + + private var content: some View { + VStack(alignment: .leading, spacing: 0) { + DetailsBandTitle(text: "Details") + if !facts.isEmpty || ratingQuery != nil { + panel.padding(.bottom, canvas.u(14)) + } + SeleneActionGrid(rows: links, focusedRow: focusedLink, onHoverRow: onHoverLink, onPressRow: onPressLink) + } + .frame(width: canvas.u(width), alignment: .topLeading) + } + + private var panel: some View { + let split = wide ? (facts.count + (ratingQuery == nil ? 0 : 1) + 1) / 2 : facts.count + let columnWidth = wide ? (width - Self.columnGap) / 2 : width + return HStack(alignment: .top, spacing: canvas.u(Self.columnGap)) { + column(Array(facts.prefix(split)), width: columnWidth, includeRating: !wide) + if wide { column(Array(facts.dropFirst(split)), width: columnWidth, includeRating: true) } + } + .frame(width: canvas.u(width), alignment: .leading) + .accessibilityElement(children: .contain) + .accessibilityLabel(L10n.text("Details")) + } + + /// The rows with a hairline between them, none above the first or under the last. + private func column(_ facts: [DetailsFact], width: CGFloat, includeRating: Bool) -> some View { + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(facts.enumerated()), id: \.element.id) { index, fact in + if index > 0 { + Rectangle().fill(SeleneTheme.ink15).frame(height: max(1, canvas.u(1))) + } + row(fact).padding(.vertical, canvas.u(9)) + } + if includeRating, ratingQuery != nil { + if !facts.isEmpty { + Rectangle().fill(SeleneTheme.ink15).frame(height: max(1, canvas.u(1))) + } + HStack(alignment: .firstTextBaseline, spacing: 0) { + label(symbol: "star", text: L10n.text(currentRatingResult?.rating?.labelKey ?? "Critic score")) + CriticRatingValue(result: currentRatingResult) + Spacer(minLength: 0) + } + .padding(.vertical, canvas.u(9)) + } + } + .frame(width: canvas.u(width), alignment: .topLeading) + } + + private var currentRatingResult: CriticRatingResult? { + loadedRatingQuery == ratingQuery && loadedRatingRevision == igdb.revision ? ratingResult : nil + } + + private func row(_ fact: DetailsFact) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 0) { + label(symbol: fact.symbol, text: fact.label) + Text(fact.value) + .seleneFont(15, .semibold) + .foregroundColor(SeleneTheme.ink.opacity(0.92)) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 0) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel("\(fact.label): \(fact.value)") + } + + private func label(symbol: String, text: String) -> some View { + HStack(alignment: .firstTextBaseline, spacing: canvas.u(10)) { + Image(systemName: symbol) + .font(.system(size: canvas.u(14), weight: .regular)) + .foregroundColor(SeleneTheme.ink.opacity(0.55)) + .frame(width: canvas.u(18)) + Text(text) + .seleneFont(15) + .foregroundColor(SeleneTheme.ink60) + .lineLimit(1) + .minimumScaleFactor(0.85) + } + .frame(width: canvas.u(182), alignment: .leading) + } +} + +/// Small link buttons, three to a row (`SpotlightState.actionColumns`): squarer and quieter than +/// Play and Options above, so they read as secondary. Shared by every source's page, so Left/Right +/// and Up/Down move the same way (`DetailsFocus`). +struct SeleneActionGrid: View { + @Environment(\.seleneCanvas) private var canvas + let rows: [DetailsLink] + let focusedRow: Int? + let onHoverRow: (Int) -> Void + let onPressRow: (Int) -> Void + static let columns = SpotlightState.actionColumns + static let cellWidth: CGFloat = 168 + + var body: some View { + VStack(alignment: .leading, spacing: canvas.u(8)) { + ForEach(Array(stride(from: 0, to: rows.count, by: Self.columns)), id: \.self) { first in + HStack(spacing: canvas.u(8)) { + ForEach(first..<min(first + Self.columns, rows.count), id: \.self) { index in + cell(rows[index], index: index) + } + } + } + } + } + + private func cell(_ row: DetailsLink, index: Int) -> some View { + let radius = canvas.u(7) + let shape = RoundedRectangle(cornerRadius: radius, style: .continuous) + return Button { onPressRow(index) } label: { + Text(row.title) + .seleneFont(14, .medium) + .foregroundColor(SeleneTheme.ink90) + .lineLimit(1) + .minimumScaleFactor(0.8) + .padding(.horizontal, canvas.u(10)) + .frame(width: canvas.u(Self.cellWidth), height: canvas.u(32)) + .background(shape.fill(SeleneTheme.glass)) + .overlay(shape.strokeBorder(SeleneTheme.ink15, lineWidth: max(1, canvas.u(1)))) + .contentShape(shape) + .seleneRowFocus(focusedRow == index, radius: radius) + } + .buttonStyle(.plain) + .onHover { if $0 { onHoverRow(index) } } + .accessibilityLabel(row.title) + } +} diff --git a/Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift b/Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift index 042b5d95..aa599a7f 100644 --- a/Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift +++ b/Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift @@ -98,7 +98,7 @@ extension GameDetailView { viewModel.toggleFavorite(game) } - /// Hover moves the action focus only while Build & Sources is in focus. + /// Hover moves the action focus only while Details is in focus. func hoverRow(_ index: Int) { guard focus.zone == DetailsFocus.actionsZone, focus.action != index else { return } var next = focus @@ -106,7 +106,7 @@ extension GameDetailView { if next != focus { focus = next } } - /// Press on a row: when Build & Sources is in focus it runs the row (the + /// Press on a row: when Details is in focus it runs the row (the /// row's own path explains a refusal, e.g. the Metal gate); otherwise the /// press first brings that band into focus. func pressRow(_ index: Int) { @@ -115,7 +115,7 @@ extension GameDetailView { return } hoverRow(index) - let rows = currentModel.rows + let rows = currentModel.links guard index < rows.count else { return } rows[index].action() } @@ -130,8 +130,8 @@ extension GameDetailView { case DetailsFocus.modsZone: activateModsTile(focus.mod) case DetailsFocus.actionsZone: - guard focus.action < model.rows.count else { return } - model.rows[focus.action].action() + guard focus.action < model.links.count else { return } + model.links[focus.action].action() case DetailsFocus.moreZone: guard focus.more < model.more.count else { return } selectOnSpotlight(model.more[focus.more]) @@ -191,6 +191,9 @@ extension GameDetailView { /// Re-reads the mods folder (and the overlay). func reloadMods() { modsHost.reload(game, viewModel: viewModel) } + /// Game options (its Cheats panel), a rebuild or a hand edit in Finder can change it. + func reloadCheats() { cheatsOn = viewModel.cheatsOn(for: game) } + /// GameBanana's mods for this game. func startGameBanana() { modsHost.startOnline(game, viewModel: viewModel) } @@ -209,7 +212,7 @@ extension GameDetailView { func openViewer(at index: Int) { let urls = currentModel.screenshots guard !urls.isEmpty else { return } - viewer = ViewerContext(titleID: game.titleId ?? game.uniqueKey, urls: urls, + viewer = ViewerContext(titleID: viewModel.personalizationKey(for: game), urls: urls, state: ScreenshotViewerState(count: urls.count, start: index)) SoundEffectService.shared.play(.click) } @@ -246,10 +249,11 @@ extension GameDetailView { !NativeMenuCommands.shared.isTracking, case .detail(let id) = router.route, id == game.id, viewModel.alertMessage == nil, viewModel.settingsNotice == nil, - viewModel.gameForSettingsSheet == nil, + !viewModel.isGameOptionsOpen, viewModel.gameToClose == nil, viewModel.gameToRemove == nil, !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, !viewModel.showSetupCheck, let window = event.window, !window.isSheet, diff --git a/Sources/NXLibrary/Views/Detail/GameDetailView.swift b/Sources/NXLibrary/Views/Detail/GameDetailView.swift index d5d1a2b7..0bcb3ac3 100644 --- a/Sources/NXLibrary/Views/Detail/GameDetailView.swift +++ b/Sources/NXLibrary/Views/Detail/GameDetailView.swift @@ -10,7 +10,7 @@ final class DetailsModelCache { /// The Details page (spec §5.4, Selene GameDetails + DetailsStage). The top /// block sits on the stage; Down glides the page up into the bands, which -/// are Screenshots (720), Build & Sources with Your activity, Mods (for a game +/// are Screenshots (720), Details, Mods (for a game /// with a title ID) and More like this, one band pitch (230) apart. A band below the one in focus peeks in, blurred, until /// it is focused. Input lives in GameDetailView+Input.swift. struct GameDetailView: View { @@ -36,6 +36,8 @@ struct GameDetailView: View { @State var keyMonitor: Any? @State var wheel = DetailsWheel() @State var cache = DetailsModelCache() + /// "Cheats on" under the title, read from the app's files where they can change (`reloadCheats`), never per draw. + @State var cheatsOn = false /// The Mods band: the game's mods (read when the page appears and when Game options or the app comes back), /// GameBanana's, and their panels. Shared with Spotlight's page. @StateObject var modsHost = ModsBandHost() @@ -51,7 +53,8 @@ struct GameDetailView: View { /// Everything one render needs, computed once per body. struct Model { let presentation: GameDetailPresentation - let rows: [BuildSourcesRow] + let facts: [DetailsFact] + let links: [DetailsLink] let screenshots: [URL] let screenshotsKnown: Bool let more: [PortedGame] @@ -71,13 +74,14 @@ struct GameDetailView: View { let urls = Array((metadata?.screenshotURLs ?? []).prefix(SpotlightScreenshotStrip.maxCount)) let more = moreGames let blocked = toolchainBlocked - let rows = actionRows(p, buildBlocked: blocked) - return Model(presentation: p, rows: rows, screenshots: urls, + let links = DetailsLink.links(app: game.url, store: p.storeURL, hltb: p.hltbURL, viewModel: viewModel) + let facts = DetailsFacts.switchGame(game, metadata: metadata, folderName: DetailsLink.folderName(of: game.url)) + return Model(presentation: p, facts: facts, links: links, screenshots: urls, screenshotsKnown: screenshotsKnown, more: more, mods: modsHost.localMods, bands: DetailsFocus.Bands(screenshots: urls.count, mods: modsHost.tiles.count, - actions: rows.count, more: more.count), + actions: links.count, more: more.count), buildBlocked: blocked, primaryEnabled: p.canPlay || (p.canRebuild && !blocked)) } @@ -121,12 +125,6 @@ struct GameDetailView: View { return metadata != nil || viewModel.storeMetadataErrors[game.id] != nil } - /// Build & Sources' actions, in grid order. - func actionRows(_ p: GameDetailPresentation, buildBlocked: Bool) -> [BuildSourcesRow] { - BuildSourcesRow.rows(for: game, presentation: p, buildBlocked: buildBlocked, - viewModel: viewModel, rebuild: { rebuild() }) - } - // MARK: - Body var body: some View { @@ -141,6 +139,18 @@ struct GameDetailView: View { .frame(width: canvas.stageSize.width, height: canvas.stageSize.height, alignment: .topLeading) .clipped() .offset(x: canvas.stageOrigin.x, y: canvas.stageOrigin.y) + .frame(width: canvas.size.width, height: canvas.size.height, alignment: .topLeading) + .mask(pageMask) + .contentShape(Path(CGRect(x: 0, y: 0, width: canvas.size.width, + height: max(0, canvas.size.height - canvas.u(SeleneBottomScrim.contentClearance))))) + // Anchor to the window, like Settings and Home, rather than the centred 16:9 stage. + VStack(spacing: 0) { + Spacer(minLength: 0) + SeleneHintsBar(left: [HintItem(.b, L10n.text("Back"), action: { router.back() })], + right: [HintItem(.y, L10n.text("Options")), HintItem(.a, L10n.text("Select"))], + bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) + } + .seleneOverlaidHints(router.overlayHasHints(viewModel)) } .overlay(viewerOverlay) .overlay(ModsBandOverlay(host: modsHost, find: modsHost.find, game: game)) @@ -157,14 +167,18 @@ struct GameDetailView: View { } .onChange(of: viewer != nil) { router.isScreenshotViewerOpen = $0 } .onChange(of: model.bands) { _ in settleFocus(model.bands) } - // Game options (its Mods panel) closing, or NX Library coming back from Finder, re-reads the mods. - .onChange(of: viewModel.gameForSettingsSheet == nil) { closed in if closed { reloadMods() } } - .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in reloadMods() } + // Game options (its Mods or Cheats panel) closing, or Arcane coming back from Finder, re-reads mods and cheats. + .onChange(of: !viewModel.isGameOptionsOpen) { closed in if closed { reloadMods(); reloadCheats() } } + .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in + reloadMods() + reloadCheats() + } // The key monitor captures this view's value: reinstall it when the game changes. .onChange(of: game) { _ in removeKeyMonitor() installKeyMonitor() reloadMods() + reloadCheats() startGameBanana() } .onReceive(NotificationCenter.default.publisher(for: .nxDetailGamepadAction)) { note in @@ -172,42 +186,47 @@ struct GameDetailView: View { if let action = note.object as? GamepadAction { handle(action) } } .task(id: art.heroTaskKey(game, metadata: metadata)) { - await art.loadHero(game: game, current: { game.id }, metadata: metadata, artwork: artwork) + await art.loadHero(game: game, current: { game.id }, metadata: metadata, artwork: artwork, personalizations: viewModel.personalizations) } .task(id: art.logoTaskKey(game, metadata: metadata)) { - await art.loadLogo(game: game, metadata: metadata, artwork: artwork) + await art.loadLogo(game: game, metadata: metadata, artwork: artwork, personalizations: viewModel.personalizations) } } // MARK: - Stage private func stage(_ model: Model) -> some View { - ZStack(alignment: .topLeading) { - page(model) - .offset(y: canvas.u(pageShift)) - // The glide is movement: reduce motion makes it instant. - .animation(reduceMotion ? nil : SeleneTheme.cubicOut(0.32), value: pageShift) + page(model) + // Art arriving during the glide rides it with the rest (`GlideGroup`). + .modifier(GlideGroup()) + .offset(y: canvas.u(pageShift)) + // The glide is movement: reduce motion makes it instant. + .animation(reduceMotion ? nil : SeleneTheme.cubicOut(0.32), value: pageShift) + } - VStack(spacing: 0) { - Spacer(minLength: 0) - SeleneHintsBar(left: [HintItem(.b, L10n.text("Back"), action: { router.back() })], - right: [HintItem(.y, L10n.text("Options")), HintItem(.a, L10n.text("Select"))], - bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) - } - .seleneOverlaidHints(router.overlayHasHints(viewModel)) + private var pageMask: some View { + VStack(spacing: 0) { + Color.black + LinearGradient(colors: [.black, .clear], startPoint: .top, endPoint: .bottom) + .frame(height: canvas.u(16)) + Color.clear.frame(height: canvas.u(SeleneBottomScrim.contentClearance)) } } /// Selene's band pitch (230), and 100 more for the tall last band so its covers clear the hints. The Mods band, - /// when there is one, sits between Build & Sources and More like this and pushes More like this one pitch down, + /// when there is one, sits between Details and More like this and pushes More like this one pitch down, /// plus one tile row for each row of its grid after the first; focused, it rises by those rows too, so its last /// row rests where a one-row band would. var pageShift: CGFloat { let mods = modsBandShift + // These fixed band positions were laid out for a 16-unit footer inset. Move a focused band up + // by the same amount as the hints, retaining its gap above them and the spacing between bands. + let footerLift = max(0, SeleneBottomScrim.hintsBottom - 16) switch focus.zone { - case DetailsFocus.actionsZone: return -230 - case DetailsFocus.modsZone: return -460 - modsGridExtra - case DetailsFocus.moreZone: return -560 - mods + case DetailsFocus.screenshotsZone: return -footerLift + case DetailsFocus.actionsZone: return -230 - footerLift + case DetailsFocus.modsZone: return -460 - modsGridExtra - footerLift + case DetailsFocus.moreZone: return -560 - mods - footerLift default: return 0 } } @@ -223,7 +242,7 @@ struct GameDetailView: View { DetailsTopBlock(game: game, logo: art.logo(for: game), presentation: model.presentation, isRunning: runningGames.isRunning(game), - cheatsOn: viewModel.cheatsOn(for: game), + cheatsOn: cheatsOn, focusedPill: focus.zone == DetailsFocus.topZone ? focus.pill : nil, primaryEnabled: model.primaryEnabled, expanded: $expanded, @@ -239,7 +258,7 @@ struct GameDetailView: View { band(zone: DetailsFocus.screenshotsZone) { DetailsScreenshotsBand( - titleID: game.titleId ?? game.uniqueKey, + titleID: viewModel.personalizationKey(for: game), urls: model.screenshots, source: metadata?.screenshotSource, known: model.screenshotsKnown, @@ -271,17 +290,15 @@ struct GameDetailView: View { band(zone: DetailsFocus.actionsZone) { HStack(alignment: .top, spacing: 0) { - BuildSourcesPanel( - presentation: model.presentation, - appFileName: game.url.lastPathComponent, - buildBlocked: model.buildBlocked && model.presentation.canRebuild, - blockedHint: viewModel.toolchainGateSummary, - rows: model.rows, - focusedRow: focus.zone == DetailsFocus.actionsZone ? focus.action : nil, - onHoverRow: { hoverRow($0) }, - onPressRow: { pressRow($0) }) + DetailsPanel( + facts: model.facts, + links: model.links, + focusedLink: focus.zone == DetailsFocus.actionsZone ? focus.action : nil, + onHoverLink: { hoverRow($0) }, + onPressLink: { pressRow($0) }, + width: DetailsPanel.wideWidth, + ratingQuery: CriticRatingQuery(game: game, name: metadata?.name)) Spacer(minLength: 0) - DetailsActivityColumn(presentation: model.presentation) } .frame(width: canvas.u(1700), alignment: .topLeading) } @@ -290,7 +307,7 @@ struct GameDetailView: View { if !model.more.isEmpty { band(zone: DetailsFocus.moreZone) { DetailsMoreBand( - games: model.more, + games: model.more.map(CatalogGame.init(nxnative:)), focusedIndex: focus.zone == DetailsFocus.moreZone ? focus.more : nil, artwork: artwork, boxArt: viewModel.boxArt, @@ -338,6 +355,7 @@ struct GameDetailView: View { router.isSearchPresented = false viewModel.loadStoreMetadata(for: game) reloadMods() + reloadCheats() startGameBanana() focus = DetailsFocus() settleFocus(model.bands) diff --git a/Sources/NXLibrary/Views/Detail/ModDetailPanel.swift b/Sources/NXLibrary/Views/Detail/ModDetailPanel.swift index 15a235be..81e817c9 100644 --- a/Sources/NXLibrary/Views/Detail/ModDetailPanel.swift +++ b/Sources/NXLibrary/Views/Detail/ModDetailPanel.swift @@ -84,6 +84,7 @@ struct ModDetailPanel: View { .background(GeometryReader { proxy in Color.clear.preference(key: ContentHeightKey.self, value: proxy.size.height) }) + .modifier(GlideGroup()) .offset(y: -state.offset) } // Where there is more, the edge fades; the sides leave room for a row's focus ring. diff --git a/Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift b/Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift index d37e4afb..7fed976c 100644 --- a/Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift +++ b/Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift @@ -10,6 +10,8 @@ import NXLibraryCore /// Title DB, the Nintendo store and the online sources (`OnlineArtwork`: stores, databases, /// wikis, Wallhaven) offer, with its size in pixels, and From file…. /// A choice is kept in `ArtworkPicks` and never overwritten by automatic art; Automatic takes it back. +/// A Steam game (`PersonalizationSubject`) gets Steam's own art for its AppID instead of the Switch +/// sources, keeps its choices in the Steam personal store and has no Mac app icon step. /// /// Browsing a source replaces the grid with that source's images for the open tab, as the Theme screen browses /// wallpaper sites: a search prefilled with the game's name, each image credited with its kind or author and its @@ -20,10 +22,11 @@ import NXLibraryCore /// A click chooses. struct ChangeArtworkView: View { @ObservedObject var viewModel: AppViewModel - let game: PortedGame + let subject: PersonalizationSubject let onClose: () -> Void @ObservedObject private var picks = ArtworkPicks.shared + @ObservedObject private var steamPicks = SteamPersonalizations.shared.artwork @State private var slot: ArtworkSlot = .cover /// The focused tile; while browsing, -1 is the search field. @State private var focus = 0 @@ -74,12 +77,14 @@ struct ChangeArtworkView: View { case automatic, yourPick, iconLocation, art(Found), browse(ArtworkBrowseSource), file } - private var titleKey: String { game.titleId ?? game.uniqueKey } - private var hasPick: Bool { picks.url(titleID: titleKey, slot: slot) != nil } - private var switch2: Bool { game.titleId?.hasPrefix("04") == true } + private var hasPick: Bool { subject.artworkURL(slot) != nil } + private var pickRevision: Int { picks.revision &+ steamPicks.revision } + private var switch2: Bool { subject.titleId?.hasPrefix("04") == true } + /// The installed nxnative game: only it has a Mac app icon to change. + private var macApp: PortedGame? { subject.ported } private var gameNames: [String] { - let metadata = viewModel.storeMetadata[game.id] - return [game.name, metadata?.name, titleDB?.name].compactMap { $0 } + let metadata = viewModel.storeMetadata[subject.id] + return [subject.name, metadata?.name, titleDB?.name].compactMap { $0 } .reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } } } @@ -87,7 +92,7 @@ struct ChangeArtworkView: View { if browsing != nil { return (browseItems[slot] ?? []).map(Tile.art) } // The sources to browse come right after Automatic (and Your pick), so a search is one move away and never // waits for the found images to load; From file… ends the grid. - return [.automatic] + (hasPick ? [.yourPick] : []) + (slot == .icon ? [.iconLocation] : []) + ArtworkBrowseSource.allCases.map(Tile.browse) + return [.automatic] + (hasPick ? [.yourPick] : []) + (slot == .icon && macApp != nil ? [.iconLocation] : []) + ArtworkBrowseSource.allCases.map(Tile.browse) + (found[slot] ?? []).map(Tile.art) + [.file] } @@ -123,7 +128,7 @@ struct ChangeArtworkView: View { .seleneFont(15, .semibold) .foregroundColor(SeleneTheme.ink60) .padding(.leading, canvas.u(8)) - Text(game.name) + Text(subject.name) .seleneFont(40) .foregroundColor(SeleneTheme.ink) .lineLimit(1) @@ -167,8 +172,8 @@ struct ChangeArtworkView: View { } } } - .task(id: "\(slot.rawValue)|\(picks.revision)") { await loadPickPreview() } - .task(id: "icon|\(slot.rawValue)|\(picks.revision)") { await loadAutomaticIcon() } + .task(id: "\(slot.rawValue)|\(pickRevision)") { await loadPickPreview() } + .task(id: "icon|\(slot.rawValue)|\(pickRevision)") { await loadAutomaticIcon() } .overlay { if askAppIcon { ZStack { @@ -188,22 +193,22 @@ struct ChangeArtworkView: View { } private var appIconMessage: String { - let running = RunningGameMonitor.runningApplication(for: game) != nil - return L10n.text("Only here changes the image inside NX Library. Use on the Mac also shows it in Finder and the Dock. Automatic uses the game's own icon, then an online image if available. Changing the image keeps this location choice.") + let running = macApp.map { RunningGameMonitor.runningApplication(for: $0) != nil } ?? false + return L10n.text("Only here changes the image inside Arcane. Use on the Mac also shows it in Finder and the Dock. Automatic uses the game's own icon, then an online image if available. Changing the image keeps this location choice.") + (running ? L10n.text(" It changes when the game quits.") : L10n.text(" A large game takes about a minute.")) } private func answerAppIcon(_ use: Bool) { SoundEffectService.shared.play(.click) askAppIcon = false - viewModel.setUsesPickedAppIcon(use, for: game) + if let macApp { viewModel.setUsesPickedAppIcon(use, for: macApp) } } /// Ask for every game, including NUPs, dumps and games not built yet. private func iconPicked() { - guard slot == .icon else { return } + guard slot == .icon, let macApp else { return } editingIconLocation = false - appIconFocus = viewModel.usesIconOnMac(for: game) ? .confirm : .cancel + appIconFocus = viewModel.usesIconOnMac(for: macApp) ? .confirm : .cancel askAppIcon = true } @@ -275,8 +280,8 @@ struct ChangeArtworkView: View { /// On the Icon tab, how the game app's own icon change stands: signing a large app takes about a minute. private var appIconStatus: String? { - guard slot == .icon else { return nil } - let progress = viewModel.appIconProgress[game.id] + guard slot == .icon, macApp != nil else { return nil } + let progress = viewModel.appIconProgress[subject.id] if let progress { switch progress { case .searching, .updating, .failed: return progress.message @@ -294,7 +299,7 @@ struct ChangeArtworkView: View { if downloading { return L10n.format("Downloading the full image from %@…", [String(describing: (source.title))]) } guard let result = browseResult else { return L10n.format("Searching %@ for “%@”…", [String(describing: (source.title)), String(describing: (browseQuery))]) } guard result.page != nil else { - return L10n.format("%@ has no %@ called “%@”", [String(describing: (source.title)), String(describing: (source == .launchBox ? L10n.text("Switch game") : "game")), String(describing: (browseQuery))]) + return L10n.format("%@ has no %@ called “%@”", [String(describing: (source.title)), String(describing: (source == .launchBox && subject.steam == nil ? L10n.text("Switch game") : "game")), String(describing: (browseQuery))]) } if browseLoading.contains(slot) && (browseItems[slot] ?? []).isEmpty { return L10n.text("Loading…") } if (browseItems[slot] ?? []).isEmpty { @@ -418,11 +423,16 @@ struct ChangeArtworkView: View { Image(nsImage: image) .resizable() .interpolation(.high) - .aspectRatio(contentMode: slot == .logo ? .fit : .fill) + .aspectRatio(contentMode: fits(image) ? .fit : .fill) .padding(slot == .logo ? canvas.u(18) : 0) } - private func glyphFace(_ icon: MaterialIcon) -> some View { + /// Logos, and banners much wider than the tile (Steam's library hero), show whole instead of cropped. + private func fits(_ image: NSImage) -> Bool { + slot == .logo || (slot == .background && image.size.width > image.size.height * 2.2) + } + + private func glyphFace(_ icon: MaterialIcon) -> some View { MaterialIconView(icon, size: 44) .foregroundColor(SeleneTheme.ink60) .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -432,6 +442,7 @@ struct ChangeArtworkView: View { switch tile { case .automatic: switch slot { + case _ where subject.steam != nil: return (L10n.text("Automatic"), steamAutomatic) case .cover: return (L10n.text("Automatic"), L10n.text("GameTDB, or a composed cover")) case .background: return (L10n.text("Automatic"), L10n.text("The game's own art, then Title DB")) case .icon: return (L10n.text("Automatic"), L10n.text("The game's own icon, then Title DB")) @@ -440,7 +451,7 @@ struct ChangeArtworkView: View { case .yourPick: return (L10n.text("Your pick"), L10n.text("Saved on this Mac")) case .iconLocation: - return (L10n.text("Icon location"), viewModel.usesIconOnMac(for: game) ? L10n.text("Use on the Mac") : "Only here") + return (L10n.text("Icon location"), macApp.map(viewModel.usesIconOnMac) == true ? L10n.text("Use on the Mac") : "Only here") case .art(let item): return (item.art.candidate.source, item.art.resolution) case .browse(let source): @@ -451,6 +462,16 @@ struct ChangeArtworkView: View { } } + /// What Automatic shows for a Steam game in this tab. + private var steamAutomatic: String { + switch slot { + case .cover: return L10n.text("Steam’s library cover") + case .background: return L10n.text("Screen-shaped art, then Steam") + case .icon: return L10n.text("The Mac app’s own icon") + case .logo: return L10n.text("Steam’s logo") + } + } + private func isCurrent(_ tile: Tile) -> Bool { switch tile { case .automatic: return !hasPick @@ -466,27 +487,34 @@ struct ChangeArtworkView: View { guard found[slot] == nil, !searching.contains(slot) else { return } searching.insert(slot) defer { searching.remove(slot) } - if !titleDBLoaded, let titleId = game.titleId { + if !titleDBLoaded, let titleId = subject.titleId { titleDB = await TitleDBInfo.fetch(titleID: titleId) titleDBLoaded = true } - let metadata = viewModel.storeMetadata[game.id] + let metadata = viewModel.storeMetadata[subject.id] let names = gameNames - let entries = slot == .cover ? await viewModel.boxArt.pickerEntries(names: names) : [] - if online == nil { online = await OnlineArtwork.find(names: names) } - let candidates = ArtworkCandidates.list(for: slot, entries: entries, titleDB: titleDB, + var candidates: [ArtworkCandidate] + found[slot] = [] + if let steam = subject.steam, let appID = subject.steamAppID { + // Steam's own art for this AppID shows at once; the online sources take seconds and follow it. + let screenshots = SteamGameFacts.shared.metadata(for: steam)?.screenshots ?? [] + let own = ArtworkCandidates.steamList(for: slot, appID: appID, screenshots: screenshots) + await collect(own, slot: slot, from: 0) + guard !Task.isCancelled else { found[slot] = nil; return } + if online == nil { online = await OnlineArtwork.find(names: names, platform: .mac) } + candidates = ArtworkCandidates.steamList(for: slot, appID: appID, screenshots: screenshots, online: online ?? []) + await collect(Array(candidates.dropFirst(own.count)), slot: slot, from: own.count) + } else { + let entries = slot == .cover ? await viewModel.boxArt.pickerEntries(names: names) : [] + if online == nil { online = await OnlineArtwork.find(names: names, platform: switch2 ? .switch2 : .switch) } + candidates = ArtworkCandidates.list(for: slot, entries: entries, titleDB: titleDB, storeHeader: metadata?.headerImageURL, storeImage: metadata?.imageURL, storeLogo: metadata?.logoURL, online: online ?? []) - found[slot] = [] - for await item in Self.previews(of: candidates) { - var list = found[slot] ?? [] - list.append(item) - list.sort { $0.order < $1.order } - found[slot] = list + await collect(candidates, slot: slot, from: 0) } if slot == .icon, !Task.isCancelled, - let titleID = game.titleId, - let url = await AppViewModel.automaticIconArtwork.automaticIcon(titleID: titleID, name: game.name), + let titleID = subject.titleId, + let url = await AppViewModel.automaticIconArtwork.automaticIcon(titleID: titleID, name: subject.name), AppViewModel.automaticIconArtwork.automaticIconSource(titleID: titleID) == "Switch Icon Showdown", let data = try? Data(contentsOf: url), let size = ArtworkCandidates.pixelSize(of: data), let preview = await GameArtLoader.decode(at: url, maxPixelSize: 600), !Task.isCancelled { @@ -498,6 +526,16 @@ struct ChangeArtworkView: View { if Task.isCancelled { found[slot] = nil } } + /// Adds the candidates' previews to the slot as they arrive, in list order after `offset`. + private func collect(_ candidates: [ArtworkCandidate], slot: ArtworkSlot, from offset: Int) async { + for await item in Self.previews(of: candidates) { + var list = found[slot] ?? [] + list.append(Found(order: item.order + offset, art: item.art, preview: item.preview)) + list.sort { $0.order < $1.order } + found[slot] = list + } + } + /// Downloads each candidate's preview at once and yields those that are images, as they arrive. private static func previews(of candidates: [ArtworkCandidate]) -> AsyncStream<Found> { AsyncStream { continuation in @@ -531,7 +569,7 @@ struct ChangeArtworkView: View { let round = browseRound if browseResult == nil { let key = source.needsKey ? SteamGridDBKey().load() : nil - let result = await source.search(browseQuery, gameNames: gameNames, switch2: switch2, key: key) + let result = await source.search(browseQuery, gameNames: gameNames, switch2: switch2, computer: subject.steam != nil, key: key) guard round == browseRound, browsing == source, !Task.isCancelled else { return } browseResult = result } @@ -551,7 +589,7 @@ struct ChangeArtworkView: View { } private func loadPickPreview() async { - guard let url = picks.url(titleID: titleKey, slot: slot) else { + guard let url = subject.artworkURL(slot) else { pickPreview = nil return } @@ -561,7 +599,10 @@ struct ChangeArtworkView: View { private func loadAutomaticIcon() async { guard slot == .icon else { return } automaticIconChecked = false - let url = await viewModel.automaticIconURL(for: game) + let url: URL? + if let macApp { url = await viewModel.automaticIconURL(for: macApp) } + else if let steam = subject.steam { url = SteamArtworkRequest(game: steam, role: .square).automaticLocalURL } + else { url = nil } let preview: NSImage? if let url { preview = await GameArtLoader.decode(at: url, maxPixelSize: 600) } else { preview = nil } @@ -588,12 +629,19 @@ struct ChangeArtworkView: View { switch tile { case .automatic: guard hasPick || slot == .icon else { return } - if hasPick { picks.remove(titleID: titleKey, slot: slot) } + if hasPick { + do { try subject.removeArtwork(slot) } catch { + message = error.localizedDescription + SoundEffectService.shared.play(.error) + return + } + } applied() - if slot == .icon { viewModel.appIconPickChanged(for: game, removed: true) } + if slot == .icon, let macApp { viewModel.appIconPickChanged(for: macApp, removed: true) } case .iconLocation: + guard let macApp else { return } editingIconLocation = true - appIconFocus = viewModel.usesIconOnMac(for: game) ? .confirm : .cancel + appIconFocus = viewModel.usesIconOnMac(for: macApp) ? .confirm : .cancel askAppIcon = true SoundEffectService.shared.play(.click) case .yourPick: @@ -636,7 +684,7 @@ struct ChangeArtworkView: View { private func save(_ data: Data) { do { - try picks.save(data, titleID: titleKey, slot: slot) + try subject.saveArtwork(data, slot: slot) applied() // The check moves to Your pick, second in the grid. focus = 1 @@ -649,7 +697,7 @@ struct ChangeArtworkView: View { /// Screens reload their art from the new revision; decoded copies of the old art go. private func applied() { - GameArtLoader.shared.forget(game) + if let macApp { GameArtLoader.shared.forget(macApp) } SoundEffectService.shared.play(.click) } @@ -658,7 +706,7 @@ struct ChangeArtworkView: View { panel.allowedContentTypes = [.png, .jpeg, .heic, .webP, .image] panel.allowsMultipleSelection = false panel.canChooseDirectories = false - panel.message = L10n.format("Choose a %@ for %@.", [String(describing: (slot.title.lowercased())), String(describing: (game.name))]) + panel.message = L10n.format("Choose a %@ for %@.", [String(describing: (slot.title.lowercased())), String(describing: (subject.name))]) guard panel.runModal() == .OK, let url = panel.url else { return } guard let data = try? Data(contentsOf: url) else { message = L10n.text("That file could not be read.") @@ -672,17 +720,17 @@ struct ChangeArtworkView: View { private func openBrowse(_ source: ArtworkBrowseSource) { browsing = source - browseDraft = game.name - browseQuery = game.name + browseDraft = subject.name + browseQuery = subject.name startBrowseSearch() } private func submitSearch() { let text = browseDraft.trimmingCharacters(in: .whitespacesAndNewlines) - if text.isEmpty { browseDraft = game.name } + if text.isEmpty { browseDraft = subject.name } fieldFocused = false SoundEffectService.shared.play(.click) - let query = text.isEmpty ? game.name : text + let query = text.isEmpty ? subject.name : text guard query != browseQuery || browseResult?.page == nil else { focus = tiles.isEmpty ? -1 : 0 return @@ -790,7 +838,7 @@ struct ChangeArtworkView: View { case .cancel: askAppIcon = false // Back dismisses the location question. A newly chosen image still follows the saved scope. - if !editingIconLocation { viewModel.appIconPickChanged(for: game, removed: false) } + if !editingIconLocation, let macApp { viewModel.appIconPickChanged(for: macApp, removed: false) } SoundEffectService.shared.play(.focus) default: break } @@ -815,7 +863,7 @@ struct ChangeArtworkView: View { private func installKeyMonitor() { guard keyMonitor == nil else { return } keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in - guard viewModel.gameForSettingsSheet?.id == game.id, !viewModel.isEditingSteamGridDBKey, + guard viewModel.optionsGameID == subject.id, !viewModel.isEditingSteamGridDBKey, let window = event.window, !window.isSheet, window.attachedSheet == nil, NSApp.modalWindow == nil, !(window.firstResponder is NSText) else { return event } guard event.modifierFlags.intersection([.command, .control, .option]).isEmpty else { return event } diff --git a/Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift b/Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift index 1f2f5fb9..2d8d297e 100644 --- a/Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift +++ b/Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift @@ -4,22 +4,34 @@ import NXLibraryCore /// Game options → Edit details → Change metadata: field by field (description, /// genres, developer, publisher, release date), Automatic (the store's value, as -/// NX Library reads it), what Title DB and GameTDB offer instead, or the player's +/// NX Library reads it), platform-appropriate public databases and optional IGDB, or the player's /// own text. A choice is kept in `MetadataPicks` and laid over the store's data. +/// A Steam game's Automatic is the Steam store's text; it has no Switch databases to offer, +/// and its choices go to the Steam personal store. /// /// Input: Up/Down move, L/R (Q/E, or Left/Right) change the field, A chooses, /// B (or Esc) returns to Game options. A click chooses. struct ChangeMetadataView: View { @ObservedObject var viewModel: AppViewModel - let game: PortedGame + let subject: PersonalizationSubject let onClose: () -> Void @ObservedObject private var picks = MetadataPicks.shared + @ObservedObject private var steamPicks = SteamPersonalizations.shared.metadata + @ObservedObject private var steamFacts = SteamGameFacts.shared + @ObservedObject private var igdb = IGDBSettings.shared + @State private var igdbResult: IGDBMetadataResult? + @State private var igdbSearching = false + @State private var igdbAttempt = 0 + @State private var databaseResults: [MetadataDatabase: DatabaseMetadataResult] = [:] + @State private var databaseSearching: Set<MetadataDatabase> = [] + @State private var databaseAttempts: [MetadataDatabase: Int] = [:] + @State private var failure: String? @State private var field: MetadataField = .description @State private var focus = 0 @State private var titleDB: TitleDBInfo? @State private var gameTDB: [GameTDBEntry] = [] - @State private var searching = true + @State private var searching: Bool @State private var keyMonitor: Any? @State private var editing = false @State private var draft = "" @@ -32,25 +44,87 @@ struct ChangeMetadataView: View { enum Row: Equatable { case automatic case yourPick(String) - case option(MetadataOption) + case source(Source, Int) + case retry(Source) case write } + enum Source: CaseIterable, Hashable { + case titleDB, gameTDB, igdb, launchBox, theGamesDB + var name: String { + switch self { + case .titleDB: return "Title DB" + case .gameTDB: return "GameTDB" + case .igdb: return "IGDB" + case .launchBox: return "LaunchBox" + case .theGamesDB: return "TheGamesDB" + } + } + var database: MetadataDatabase? { + switch self { case .launchBox: return .launchBox; case .theGamesDB: return .theGamesDB; default: return nil } + } + } + private struct IGDBLookup: Hashable { + let query: CriticRatingQuery + let revision: UUID + let attempt: Int + } + private struct DatabaseLookup: Hashable { let query: CriticRatingQuery; let attempt: Int } + + init(viewModel: AppViewModel, subject: PersonalizationSubject, onClose: @escaping () -> Void) { + self.viewModel = viewModel + self.subject = subject + self.onClose = onClose + // Steam games have no Switch databases to search. + _searching = State(initialValue: subject.ported != nil) + } - private var titleKey: String { game.titleId ?? game.uniqueKey } - private var pick: String? { picks.value(titleID: titleKey, field: field) } - private var store: NintendoStoreMetadata? { viewModel.storeMetadataAsFetched(for: game) } + private var pick: String? { + _ = picks.revision; _ = steamPicks.revision + return subject.metadataPick(field) + } + private var store: NintendoStoreMetadata? { subject.ported.flatMap(viewModel.storeMetadataAsFetched) } + private var igdbQuery: CriticRatingQuery { + if let game = subject.ported { return CriticRatingQuery(game: game, name: store?.name) } + return CriticRatingQuery(name: subject.steam?.steamGame?.name ?? subject.name, platform: .mac, steamAppID: subject.steamAppID) + } + private var databaseQuery: CriticRatingQuery { + let query = igdbQuery + return CriticRatingQuery(name: igdbResult?.metadata?.name ?? query.name, platform: query.platform, steamAppID: query.steamAppID) + } + private var sources: [Source] { + igdbQuery.platform == .mac ? [.igdb, .launchBox, .theGamesDB] : Source.allCases + } - /// Automatic is the store's value, so the store's option is not listed again. - private var options: [MetadataOption] { - MetadataOptions.list(for: field, store: store, titleDB: titleDB, gameTDB: gameTDB) - .filter { $0.source != "Nintendo store" } + /// What Automatic shows: the Nintendo or Steam store's value. + private var automaticValue: String? { + if let steam = subject.steam { return steamFacts.metadata(for: steam)?.value(field) } + return MetadataOptions.list(for: field, store: store, titleDB: nil, gameTDB: []).first?.value + } + + private func options(_ source: Source) -> [MetadataOption] { + switch source { + case .titleDB: return MetadataOptions.list(for: field, store: nil, titleDB: titleDB, gameTDB: []) + case .gameTDB: return MetadataOptions.list(for: field, store: nil, titleDB: nil, gameTDB: gameTDB) + case .igdb: return igdbResult?.metadata?.option(for: field).map { [$0] } ?? [] + case .launchBox, .theGamesDB: + guard let database = source.database else { return [] } + return databaseResults[database]?.preview?.option(for: field).map { [$0] } ?? [] + } + } + private func option(_ row: Row) -> MetadataOption? { + guard case .source(let source, let index) = row else { return nil } + let values = options(source) + return values.indices.contains(index) ? values[index] : nil } private var rows: [Row] { - let options = self.options var rows: [Row] = [.automatic] - if let pick, !options.contains(where: { $0.value == pick }) { rows.append(.yourPick(pick)) } - return rows + options.map(Row.option) + [.write] + if let pick { rows.append(.yourPick(pick)) } + for source in sources { + rows += (0..<max(1, options(source).count)).map { .source(source, $0) } + if (canRetry(source) && !options(source).isEmpty) || (isSearching(source) && attempts(source) > 0) { rows.append(.retry(source)) } + } + return rows + [.write] } // MARK: - Body @@ -69,16 +143,18 @@ struct ChangeMetadataView: View { .seleneFont(15, .semibold) .foregroundColor(SeleneTheme.ink60) .padding(.leading, canvas.u(8)) - Text(game.name) + Text(subject.name) .seleneFont(40) .foregroundColor(SeleneTheme.ink) .lineLimit(1) .padding(.leading, canvas.u(6)) .padding(.bottom, canvas.u(14)) tabs - Text(searching ? L10n.text("Looking on Title DB and GameTDB…") : " ") + Text(failure ?? sourceStatus) .seleneFont(14) .foregroundColor(SeleneTheme.ink60) + .lineLimit(1) + .help(failure ?? sourceStatus) .padding(.leading, canvas.u(10)) .padding(.vertical, canvas.u(10)) list(rows) @@ -90,7 +166,7 @@ struct ChangeMetadataView: View { .contentShape(Rectangle()) SeleneHintsBar(left: [HintItem(.b, L10n.text("Back"), action: close)], - right: [HintItem(.lb, L10n.text("Previous")), HintItem(.rb, L10n.text("Next")), HintItem(.a, L10n.text("Choose"))], + right: rightHints, bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) } .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -104,6 +180,24 @@ struct ChangeMetadataView: View { handleGamepad(action) } .task { await search() } + .task(id: IGDBLookup(query: igdbQuery, revision: igdb.revision, attempt: igdbAttempt)) { await searchIGDB() } + .task(id: DatabaseLookup(query: databaseQuery, attempt: databaseAttempts[.launchBox, default: 0])) { await searchDatabase(.launchBox) } + .task(id: DatabaseLookup(query: databaseQuery, attempt: databaseAttempts[.theGamesDB, default: 0])) { await searchDatabase(.theGamesDB) } + } + + private var rightHints: [HintItem] { + var hints = [HintItem(.lb, L10n.text("Previous")), HintItem(.rb, L10n.text("Next"))] + if rows.indices.contains(focus), enabled(rows[focus]) { + let row = rows[focus] + let retrying: Bool + switch row { + case .retry: retrying = true + case .source(let source, _): retrying = option(row) == nil && canRetry(source) + default: retrying = false + } + hints.append(HintItem(.a, L10n.text(retrying ? "Retry" : "Choose"))) + } + return hints } private var tabs: some View { @@ -139,18 +233,23 @@ struct ChangeMetadataView: View { } .padding(.top, canvas.u(6)) .padding(.bottom, canvas.u(24)) + // Expansion and focus scrolling share one curve; the text itself + // stays laid out at its final width throughout the transition. + .animation(reduceMotion ? nil : SeleneTheme.quick, value: focus) } .scrollIndicators(.hidden) .onChange(of: focus) { index in - withAnimation(reduceMotion ? nil : SeleneTheme.quick) { proxy.scrollTo(index, anchor: .center) } + // A description can exceed the viewport: reveal its beginning, + // rather than centring it with the heading already off screen. + withAnimation(reduceMotion ? nil : SeleneTheme.quick) { proxy.scrollTo(index, anchor: .top) } } } } private func rowView(_ row: Row, focused: Bool) -> some View { let text = describe(row) - return SeleneOptionRow(icon: icon(row), title: text.title, about: excerpt(text.value, full: focused), - focused: focused) { + return SeleneOptionRow(icon: icon(row), title: text.title, about: text.value, + focused: focused, enabled: enabled(row), aboutPreview: excerpt(text.value)) { if isCurrent(row) { MaterialIconView(.check, size: 26).foregroundColor(SeleneTheme.focus) } @@ -162,21 +261,30 @@ struct ChangeMetadataView: View { private func icon(_ row: Row) -> MaterialIcon? { switch row { - case .automatic: return .restore + case .automatic, .retry: return .restore case .yourPick, .write: return .edit - case .option: return .info + case .source: return .info } } private func describe(_ row: Row) -> (title: String, value: String?) { switch row { case .automatic: - let value = MetadataOptions.list(for: field, store: store, titleDB: nil, gameTDB: []).first?.value - return (L10n.text("Automatic"), value.map { L10n.format("Nintendo store: %@", [displayValue($0)]) } ?? L10n.text("Nothing from the store yet.")) + let format = subject.steam != nil ? "Steam: %@" : "Nintendo store: %@" + return (L10n.text("Automatic"), automaticValue.map { L10n.format(format, [displayValue($0)]) } ?? L10n.text("Nothing from the store yet.")) case .yourPick(let value): - return (L10n.text("Your own"), displayValue(value)) - case .option(let option): - return (option.source, displayValue(option.value)) + return (L10n.text("Your choice"), displayValue(value)) + case .source(let source, _): + if let option = option(row) { + let same = automaticValue?.trimmingCharacters(in: .whitespacesAndNewlines).caseInsensitiveCompare(option.value) == .orderedSame + var value = same ? L10n.text("Same as Automatic") : displayValue(option.value) + if isStale(source) { value = L10n.text("Saved copy") + " · " + value } + return (option.source, value) + } + let platform = source.database.flatMap { databaseResults[$0]?.preview?.platform } + return (platform.map { "\(source.name) · \($0)" } ?? source.name, sourceMessage(source)) + case .retry(let source): + return (L10n.format("Retry %@", [source.name]), L10n.text("Other sources and your saved choices remain available.")) case .write: return (L10n.text("Write your own…"), L10n.format("Type the %@ yourself.", [String(describing: (field.title.lowercased()))])) } @@ -187,8 +295,8 @@ struct ChangeMetadataView: View { } /// Long descriptions show in full only on the focused row. - private func excerpt(_ value: String?, full: Bool) -> String? { - guard let value, !full, value.count > 240 else { return value } + private func excerpt(_ value: String?) -> String? { + guard let value, value.count > 240 else { return nil } return String(value.prefix(240)).trimmingCharacters(in: .whitespaces) + "…" } @@ -196,20 +304,105 @@ struct ChangeMetadataView: View { switch row { case .automatic: return pick == nil case .yourPick: return true - case .option(let option): return option.value == pick - case .write: return false + case .source: return false // The stored value is shown once in Your choice; sources are alternatives. + case .write, .retry: return false } } // MARK: - Loading private func search() async { + guard subject.ported != nil else { return } defer { searching = false } - if let titleId = game.titleId { titleDB = await TitleDBInfo.fetch(titleID: titleId) } - let names = [game.name, store?.name, titleDB?.name].compactMap { $0 } + if let titleId = subject.titleId { + let result = await TitleDBInfo.fetch(titleID: titleId) + guard !Task.isCancelled else { return } + preservingFocus { titleDB = result } + } + let names = [subject.name, store?.name, titleDB?.name].compactMap { $0 } // Only exact titles: a look-alike game's synopsis would be the wrong game's. let all = await viewModel.boxArt.pickerEntries(names: names) - gameTDB = all.filter { entry in names.contains { GameTDB.normalize($0) == GameTDB.normalize(entry.title) } } + guard !Task.isCancelled else { return } + preservingFocus { + gameTDB = all.filter { entry in names.contains { GameTDB.normalize($0) == GameTDB.normalize(entry.title) } } + } + } + + private var sourceStatus: String { + if searching || igdbSearching || !databaseSearching.isEmpty { return L10n.text("Looking for metadata…") } + return field == .description ? L10n.text("Descriptions are shown in the source’s original language.") + : L10n.text("Choose a source for each field.") + } + private func isSearching(_ source: Source) -> Bool { + if let database = source.database { return databaseSearching.contains(database) } + return source == .igdb ? igdbSearching : searching + } + private func isStale(_ source: Source) -> Bool { + if let database = source.database { return databaseResults[database]?.isStale == true } + return source == .igdb && igdbResult?.isStale == true + } + private func attempts(_ source: Source) -> Int { + source.database.map { databaseAttempts[$0, default: 0] } ?? (source == .igdb ? igdbAttempt : 0) + } + private func canRetry(_ source: Source) -> Bool { + guard !isSearching(source) else { return false } + if let database = source.database { return databaseResults[database]?.issue == .unavailable } + return source == .igdb && igdbResult?.issue == .unavailable + } + private func enabled(_ row: Row) -> Bool { + switch row { + case .source(let source, _): return option(row) != nil || canRetry(source) + case .retry(let source): return !isSearching(source) + default: return true + } + } + private func sourceMessage(_ source: Source) -> String { + if isSearching(source) { return L10n.text("Looking for metadata…") } + if canRetry(source) { return L10n.text("Unavailable · choose this row to retry.") } + if let database = source.database { + guard let result = databaseResults[database] else { return L10n.text("Loading…") } + if result.issue == .ambiguous { return L10n.text("No unique match for this edition.") } + if result.issue == .notFound { return L10n.text("No matching game for this platform.") } + } else if source == .igdb { + if !igdb.isConfigured { return L10n.text("IGDB is optional · connect it in Settings → Online services.") } + if igdbResult == nil { return L10n.text("Loading…") } + if igdbResult?.issue == .ambiguous { return L10n.text("No unique match for this edition.") } + if igdbResult?.issue == .notFound { return L10n.text("No matching game for this platform.") } + } + return L10n.text("No data for this field.") + } + private func searchDatabase(_ database: MetadataDatabase) async { + let query = databaseQuery + preservingFocus { databaseResults[database] = nil; databaseSearching.insert(database) } + let result = await DatabaseMetadataService.shared(database).load(query, forceRefresh: databaseAttempts[database, default: 0] > 0) + guard !Task.isCancelled, query == databaseQuery else { return } + preservingFocus { databaseResults[database] = result; databaseSearching.remove(database) } + } + + private func searchIGDB() async { + let query = igdbQuery, revision = igdb.revision + let credentials = igdb.credentials + preservingFocus { igdbResult = nil; igdbSearching = credentials != nil } + guard let credentials else { return } + let result = await IGDBMetadataService.shared.load(query, credentials: credentials) + guard !Task.isCancelled, revision == igdb.revision, query == igdbQuery else { return } + preservingFocus { igdbResult = result; igdbSearching = false } + } + + /// Source results must not move the user's selection to a different action. + private func preservingFocus(_ update: () throws -> Void) rethrows { + let before = rows + let selected = before.indices.contains(focus) ? before[focus] : nil + try update() + let after = rows + if let selected, let index = after.firstIndex(of: selected) { focus = index } + else if case .yourPick(let value) = selected, + let index = after.firstIndex(where: { option($0)?.value == value }) { + focus = index + } else if case .retry(let source) = selected, + let index = after.firstIndex(of: .source(source, 0)) { + focus = index + } else { focus = 0 } } // MARK: - Choosing @@ -218,24 +411,47 @@ struct ChangeMetadataView: View { switch row { case .automatic: guard pick != nil else { return } - viewModel.pickMetadata(nil, field: field, for: game) + save(nil) case .yourPick: break - case .option(let option): - viewModel.pickMetadata(option.value, field: field, for: game) + case .source(let source, _): + if let option = option(row) { save(option.value) } + else if canRetry(source) { retry(source) } + else { return } + case .retry(let source): + guard !isSearching(source) else { return } + retry(source) case .write: - draft = pick ?? MetadataOptions.list(for: field, store: store, titleDB: nil, gameTDB: []).first?.value ?? "" + draft = pick ?? automaticValue ?? "" editorFocus = .cancel editing = true } SoundEffectService.shared.play(.click) } + private func retry(_ source: Source) { + if let database = source.database { + databaseSearching.insert(database); databaseAttempts[database, default: 0] += 1 + } else if source == .igdb { igdbSearching = true; igdbAttempt += 1 } + } + + /// Keeps the value (nil: the store's), reporting a save that failed instead of showing it as chosen. + private func save(_ value: String?) { + do { + try preservingFocus { try subject.pickMetadata(value, field: field, viewModel: viewModel) } + failure = nil + } + catch { + failure = error.localizedDescription + SoundEffectService.shared.play(.error) + } + } + private var editor: some View { ZStack { SeleneTheme.scrim45.ignoresSafeArea().contentShape(Rectangle()) .onTapGesture { editing = false } - SeleneConfirmDialog(title: field.title, message: game.name, confirmTitle: L10n.text("Save"), + SeleneConfirmDialog(title: field.title, message: subject.name, confirmTitle: L10n.text("Save"), focus: $editorFocus, onCancel: { editing = false }, onConfirm: saveDraft) { VStack(alignment: .leading, spacing: canvas.u(12)) { if field == .description { @@ -267,7 +483,7 @@ struct ChangeMetadataView: View { private func saveDraft() { let text = draft.trimmingCharacters(in: .whitespacesAndNewlines) - viewModel.pickMetadata(text.isEmpty ? nil : text, field: field, for: game) + save(text.isEmpty ? nil : text) editing = false SoundEffectService.shared.play(.click) } @@ -331,7 +547,7 @@ struct ChangeMetadataView: View { private func installKeyMonitor() { guard keyMonitor == nil else { return } keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in - guard viewModel.gameForSettingsSheet?.id == game.id, viewModel.settingsNotice == nil, + guard viewModel.optionsGameID == subject.id, viewModel.settingsNotice == nil, let window = event.window, !window.isSheet, window.attachedSheet == nil, NSApp.modalWindow == nil else { return event } if editing { diff --git a/Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift b/Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift index 8f5ef8f4..7a6af074 100644 --- a/Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift +++ b/Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift @@ -452,7 +452,7 @@ struct CheatsPanel: View { default: return } guard let data = try? Data(contentsOf: found[index].url) else { - refuse(L10n.text("NX Library could not read the file.")) + refuse(L10n.text("Arcane could not read the file.")) return } askConfirm(.install(data: data, file: file, unnamed: unnamed, replacing: cheatState?.file != nil)) diff --git a/Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift b/Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift index 1f1e0bfc..77804a02 100644 --- a/Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift +++ b/Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift @@ -12,6 +12,27 @@ import NXLibraryCore /// pointer alone never moves the focus; the wheel or trackpad scrolls the list /// freely and, once it stops, the focus moves to the nearest row in view without /// moving the list. A click activates. +/// What Game options reads from the game's files when it opens. The view holds it as a `@StateObject`, built once +/// per opening: the view's own initializer runs on every redraw of the shell and must not read files there. +final class GameOptionsFiles: ObservableObject { + /// It parses the game's launcher file, which the rows must not do on every draw. + let supportsRenderScale: Bool + @Published var config: GameRuntimeConfig + /// The build's settings and their values, for a build with saved choices; nil for an older build (`config`). + @Published var snapshot: GameSettingsSnapshot? + /// The Cheats row's value: read when Game options opens and when the panel closes, not on every draw. + @Published var cheatsValue: String + @Published var modsValue: String + + init(viewModel: AppViewModel, game: PortedGame) { + supportsRenderScale = viewModel.supportsSetting("DM_RENDER_SCALE", for: game) + config = viewModel.loadRuntimeConfig(for: game) + snapshot = viewModel.settingsSnapshot(for: game) + cheatsValue = viewModel.cheatRowValue(for: game) + modsValue = viewModel.modsRowValue(for: game) + } +} + struct GameOptionsView: View { @ObservedObject var viewModel: AppViewModel let game: PortedGame @@ -19,12 +40,16 @@ struct GameOptionsView: View { let onClose: () -> Void let onShowBuild: () -> Void let onMove: () -> Void - /// Read once: it parses the game's launcher file, which the rows must not do on every draw. - private let supportsRenderScale: Bool - - @State private var config: GameRuntimeConfig - /// The build's settings and their values, for a build with saved choices; nil for an older build (`config`). - @State private var snapshot: GameSettingsSnapshot? + @StateObject private var files: GameOptionsFiles + private var supportsRenderScale: Bool { files.supportsRenderScale } + private var config: GameRuntimeConfig { + get { files.config } + nonmutating set { files.config = newValue } + } + private var snapshot: GameSettingsSnapshot? { + get { files.snapshot } + nonmutating set { files.snapshot = newValue } + } @State private var level: GameOptionsLevel = .main /// The focused row by identity; nil means the top row of the level. @State private var pickedRow: GameOptionsRow? @@ -38,10 +63,15 @@ struct GameOptionsView: View { @State private var savesOpen = false /// The Mods panel, likewise. @State private var modsOpen: Bool - @State private var modsValue: String + private var modsValue: String { + get { files.modsValue } + nonmutating set { files.modsValue = newValue } + } @State private var moreOpen = false - /// The Cheats row's value: read from disk when Game options opens and when the panel closes, not on every draw. - @State private var cheatsValue: String + private var cheatsValue: String { + get { files.cheatsValue } + nonmutating set { files.cheatsValue = newValue } + } /// A panel over the list has the input. private var panelOpen: Bool { artworkOpen || metadataOpen || cheatsOpen || modsOpen || savesOpen || moreOpen } @State private var confirmFocus: SeleneConfirmButton = .cancel @@ -68,11 +98,8 @@ struct GameOptionsView: View { self.onClose = onClose self.onShowBuild = onShowBuild self.onMove = onMove - supportsRenderScale = viewModel.supportsSetting("DM_RENDER_SCALE", for: game) - _config = State(initialValue: viewModel.loadRuntimeConfig(for: game)) - _snapshot = State(initialValue: viewModel.settingsSnapshot(for: game)) - _cheatsValue = State(initialValue: viewModel.cheatRowValue(for: game)) - _modsValue = State(initialValue: viewModel.modsRowValue(for: game)) + // The autoclosure runs only when Game options opens, not on the shell's later redraws. + _files = StateObject(wrappedValue: GameOptionsFiles(viewModel: viewModel, game: game)) _modsOpen = State(initialValue: opensMods) } @@ -93,6 +120,8 @@ struct GameOptionsView: View { toolchainBlocked: viewModel.isCheckingEnvironment || (viewModel.compatibilityReport != nil && !viewModel.canPassToolchainGate), toolchainHint: viewModel.isCheckingEnvironment ? L10n.text("Checking environment") : viewModel.toolchainGateSummary?.buildHint, hasStorePage: viewModel.storeMetadata[game.id]?.storeURL != nil, + offersStoreSearch: (viewModel.storeMetadata[game.id]?.description ?? "").isEmpty + && viewModel.nintendoStoreSearchURL(for: game) != nil, gameName: game.name, appPath: game.url.path, canDeleteBundle: game.canDeleteAppBundle(), @@ -136,13 +165,13 @@ struct GameOptionsView: View { .allowsHitTesting(!panelOpen) if artworkOpen { - ChangeArtworkView(viewModel: viewModel, game: current) { artworkOpen = false } + ChangeArtworkView(viewModel: viewModel, subject: PersonalizationSubject(current, viewModel: viewModel)) { artworkOpen = false } .transition(.opacity) .zIndex(2) } if metadataOpen { - ChangeMetadataView(viewModel: viewModel, game: current) { metadataOpen = false } + ChangeMetadataView(viewModel: viewModel, subject: PersonalizationSubject(current, viewModel: viewModel)) { metadataOpen = false } .transition(.opacity) .zIndex(2) } @@ -508,6 +537,7 @@ struct GameOptionsView: View { keyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .scrollWheel]) { event in guard viewModel.gameForSettingsSheet?.id == game.id, !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, !NativeMenuCommands.shared.isTracking, !panelOpen, viewModel.gameToClose == nil, @@ -791,6 +821,10 @@ struct GameOptionsView: View { guard let url = viewModel.storeMetadata[game.id]?.storeURL else { return } SoundEffectService.shared.play(.click) viewModel.openURL(url) + case .searchStore: + guard let url = viewModel.nintendoStoreSearchURL(for: current) else { return } + SoundEffectService.shared.play(.click) + viewModel.openURL(url) case .attachSources: SoundEffectService.shared.play(.click) viewModel.locateSources(for: current) diff --git a/Sources/NXLibrary/Views/GameOptions/PersonalizationSubject.swift b/Sources/NXLibrary/Views/GameOptions/PersonalizationSubject.swift new file mode 100644 index 00000000..fd7355c6 --- /dev/null +++ b/Sources/NXLibrary/Views/GameOptions/PersonalizationSubject.swift @@ -0,0 +1,77 @@ +import Foundation +import NXLibraryCore + +/// The game Change artwork and Change metadata personalize, whatever its source. nxnative +/// games keep their picks in `ArtworkPicks`/`MetadataPicks` and their Mac app icon flow; +/// Steam games keep theirs in `SteamPersonalizationStore` and never touch the installed app. +@MainActor +struct PersonalizationSubject { + let id: UUID + let name: String + /// The picks' key: the nxnative personalization key, or "steam-<appid>". + let key: String + /// The nxnative game, for Switch sources (Title DB, GameTDB, Nintendo store) and the app icon. + let ported: PortedGame? + /// The Steam game, for Steam's own art and store facts. + let steam: CatalogGame? + + init(_ game: PortedGame, viewModel: AppViewModel) { + id = game.id; name = game.name; key = viewModel.personalizationKey(for: game) + ported = game; steam = nil + } + + init(steam game: CatalogGame) { + id = game.id; name = game.name; key = game.personalizationReference.key + ported = nil; steam = game + } + + var titleId: String? { ported?.titleId } + var steamAppID: UInt32? { steam?.steamGame?.appID } + + private var steamArt: SteamPersonalizationStore { SteamPersonalizations.shared.artwork } + private var steamFields: SteamPersonalizationStore { SteamPersonalizations.shared.metadata } + + // MARK: Artwork picks + + func artworkURL(_ slot: ArtworkSlot) -> URL? { + steam != nil ? steamArt.url(titleID: key, slot: slot) : ArtworkPicks.shared.url(titleID: key, slot: slot) + } + + func saveArtwork(_ data: Data, slot: ArtworkSlot) throws { + if steam != nil { try steamArt.save(fields: [:], images: [slot: data], automatic: [], titleID: key) } + else { _ = try ArtworkPicks.shared.save(data, titleID: key, slot: slot) } + } + + func removeArtwork(_ slot: ArtworkSlot) throws { + if steam != nil { try steamArt.save(fields: [:], images: [:], automatic: [slot], titleID: key) } + else { ArtworkPicks.shared.remove(titleID: key, slot: slot) } + } + + // MARK: Metadata picks + + func metadataPick(_ field: MetadataField) -> String? { + steam != nil ? steamFields.value(titleID: key, field: field) : MetadataPicks.shared.value(titleID: key, field: field) + } + + /// Keeps the player's value, or (nil) goes back to the store's. + func pickMetadata(_ value: String?, field: MetadataField, viewModel: AppViewModel) throws { + if steam != nil { try steamFields.save(fields: [field: value ?? ""], images: [:], automatic: [], titleID: key) } + else if let ported { viewModel.pickMetadata(value, field: field, for: ported) } + } +} + +extension SteamMetadata { + /// The store's value for a Change metadata field, as one line (genres comma-separated). + func value(_ field: MetadataField) -> String? { + let text: String? + switch field { + case .description: text = description + case .genres: text = genres.joined(separator: ", ") + case .developer: text = developers.joined(separator: ", ") + case .publisher: text = publishers.joined(separator: ", ") + case .releaseDate: text = releaseDate + } + let trimmed = text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed + } +} diff --git a/Sources/NXLibrary/Views/GameOptions/SavesPanel.swift b/Sources/NXLibrary/Views/GameOptions/SavesPanel.swift index 5e8438ec..0dd13f7c 100644 --- a/Sources/NXLibrary/Views/GameOptions/SavesPanel.swift +++ b/Sources/NXLibrary/Views/GameOptions/SavesPanel.swift @@ -148,7 +148,7 @@ struct SavesPanel: View { private func subtitle(_ row: Row) -> String { switch row { case .open: return L10n.text("Open the current save in Finder.") - case .backup: return L10n.text("Keep a copy of your current progress.") + case .backup: return L10n.text("Back up all local users and the device save.") case .target: return L10n.text("Destination for imports only.") case .add: return L10n.text("Choose a save folder to import.") case .refresh: return L10n.text("Check saves and backups again.") @@ -194,14 +194,14 @@ struct SavesPanel: View { confirmTitle: L10n.text("Restore"), focus: $confirmFocus, onCancel: { if !model.busy { model.cancelPreview() } }, onConfirm: { if !model.busy { model.confirmRestore() } }).disabled(model.busy) } else if cloudPrompt { - SeleneConfirmDialog(title: L10n.text("Cloud saves on"), message: cloudHelp.message, confirmTitle: cloudHelp.button, + SeleneConfirmDialog(title: L10n.text("Cloud saves on"), message: cloudHelp.message + "\n\n" + SavePresentation.cloudNotice, confirmTitle: cloudHelp.button, focus: $confirmFocus, onCancel: { cloudPrompt = false }, onConfirm: resolveCloud) } } private var cloudHelp: (message: String, button: String) { switch model.context?.cloudReason { - case "NX Library → Settings → Games": return (L10n.text("Turn off Cloud saves in Settings → Games to import or restore."), "Settings") + case "Arcane → Settings → Cloud saves": return (L10n.text("Turn off Cloud saves in Settings → Cloud saves to import or restore."), "Settings") case "the game's env.txt", "the app's env.txt": return (L10n.text("Turn off cloud sync in this configuration file first."), L10n.text("Show file")) case "the game's Cloud saves settings": return (L10n.text("Turn off Cloud saves in the game's own settings first."), "OK") default: return (L10n.text("Turn off cloud sync in the launch environment first."), "OK") @@ -210,9 +210,9 @@ struct SavesPanel: View { private func resolveCloud() { cloudPrompt = false switch model.context?.cloudReason { - case "NX Library → Settings → Games": + case "Arcane → Settings → Cloud saves": viewModel.gameForSettingsSheet = nil - viewModel.router?.openSettings(.games) + viewModel.router?.openSettings(.cloudSaves) case "the game's env.txt": if let context = model.context { NSWorkspace.shared.activateFileViewerSelecting([context.location.root.appendingPathComponent("env.txt")]) } case "the app's env.txt": NSWorkspace.shared.activateFileViewerSelecting([game.url.appendingPathComponent("Contents/Resources/dm/env.txt")]) diff --git a/Sources/NXLibrary/Views/GameOptions/SteamOptionsView.swift b/Sources/NXLibrary/Views/GameOptions/SteamOptionsView.swift new file mode 100644 index 00000000..7d8be4a8 --- /dev/null +++ b/Sources/NXLibrary/Views/GameOptions/SteamOptionsView.swift @@ -0,0 +1,278 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// A Steam game's Options, in Game options' look and input: the same dimmed screen, +/// centred column, glass rows and hints. Rows and copy come from `SteamOptionsPresentation`; +/// Edit details opens the shared Change artwork and Change metadata panels on the Steam +/// game's own picks. Every row acts on the record it was opened for, re-read from the catalog. +/// +/// Input: Up/Down move (clamped), A activates, B (or Esc) leaves Edit details, then closes; +/// X and Menu close. A click activates; a click on the dimmed area steps back. +struct SteamOptionsView: View { + @ObservedObject var viewModel: AppViewModel + let game: CatalogGame + let origin: GameOptionsOrigin + let onClose: () -> Void + let onMove: () -> Void + + @ObservedObject private var player = SteamPlayCoordinator.shared + @State private var level: GameOptionsLevel = .main + @State private var pickedRow: GameOptionsRow? + @State private var artworkOpen = false + @State private var metadataOpen = false + @State private var keyMonitor: Any? + + @Environment(\.seleneCanvas) private var canvas + @Environment(\.seleneReduceMotion) private var reduceMotion + + /// The record as the catalog holds it now: Favorite and Hidden change it while open. + private var current: CatalogGame { + viewModel.catalogGames.first { $0.id == game.id } ?? game + } + + private var application: CatalogNativeApplication? { + current.steamGame?.firstAvailableInstallation?.primaryApplication + } + + private var presentation: SteamOptionsPresentation { + SteamOptionsPresentation(canPlay: player.canPlay(current), hasApp: application != nil) + } + + private var rows: [GameOptionsRow] { presentation.focusableRows(level: level, origin: origin) } + + private var focusedRow: GameOptionsRow? { + let rows = self.rows + return GameOptionsFocus(row: pickedRow, in: rows).row(in: rows) + } + + private var panelOpen: Bool { artworkOpen || metadataOpen } + + var body: some View { + let p = presentation + return ZStack { + SeleneTheme.scrim45 + .ignoresSafeArea() + .contentShape(Rectangle()) + .onTapGesture { back() } + + VStack(spacing: 0) { + column(p) + SeleneHintsBar(left: [HintItem(.b, L10n.text("Back"))], right: [HintItem(.a, L10n.text("Select"))], + bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .opacity(panelOpen ? 0 : 1) + .allowsHitTesting(!panelOpen) + + if artworkOpen { + ChangeArtworkView(viewModel: viewModel, subject: PersonalizationSubject(steam: current)) { artworkOpen = false } + .transition(.opacity) + .zIndex(2) + } + if metadataOpen { + ChangeMetadataView(viewModel: viewModel, subject: PersonalizationSubject(steam: current)) { metadataOpen = false } + .transition(.opacity) + .zIndex(2) + } + } + .animation(reduceMotion ? nil : SeleneTheme.quick, value: panelOpen) + .onAppear(perform: installKeyMonitor) + .onDisappear(perform: removeKeyMonitor) + .onReceive(NotificationCenter.default.publisher(for: .nxGameOptionsGamepadAction)) { note in + guard let action = note.object as? GamepadAction else { return } + handleGamepad(action) + } + .task(id: game.id) { + // Change metadata's Automatic is the store's text; ask for it before the panel opens. + await SteamGameFacts.shared.load(current, language: L10n.context.language) + } + } + + private func column(_ p: SteamOptionsPresentation) -> some View { + let focused = focusedRow + return VStack(alignment: .leading, spacing: 0) { + Text(L10n.text("GAME OPTIONS")) + .seleneFont(15, .semibold) + .foregroundColor(SeleneTheme.ink60) + .padding(.leading, canvas.u(8)) + Text(current.name) + .seleneFont(40) + .foregroundColor(SeleneTheme.ink) + .lineLimit(1) + .padding(.leading, canvas.u(6)) + .padding(.bottom, canvas.u(14)) + VStack(spacing: canvas.u(8)) { + ForEach(Array(p.entries(level: level, origin: origin).enumerated()), id: \.offset) { _, entry in + entryView(entry, p, focused: focused) + } + } + .padding(.top, canvas.u(6)) + .id(level) + } + .frame(width: canvas.u(1040), alignment: .leading) + .frame(maxHeight: .infinity, alignment: .top) + .padding(.top, canvas.u(90)) + .padding(.bottom, canvas.u(110)) + .contentShape(Rectangle()) + } + + @ViewBuilder + private func entryView(_ entry: GameOptionsEntry, _ p: SteamOptionsPresentation, focused: GameOptionsRow?) -> some View { + switch entry { + case .row(let row): + SeleneOptionRow(icon: row.icon, title: row.title, about: p.about(row), focused: focused == row, + destructive: false, enabled: !p.isDimmed(row)) { + trailing(row) + } + .contentShape(Rectangle()) + .onTapGesture { activate(row) } + .accessibilityElement(children: .ignore) + .accessibilityLabel(row.title) + .accessibilityHint(p.about(row) ?? "") + .accessibilityValue(row.isToggle ? (toggleValue(row) ? "On" : "Off") : "") + .accessibilityAddTraits(.isButton) + .accessibilityAction { activate(row) } + case .heading(let text): + Text(L10n.text(text)) + .seleneFont(17, .semibold) + .foregroundColor(SeleneTheme.ink75) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.leading, canvas.u(26)) + .padding(.top, canvas.u(16)) + case .note, .gap: + EmptyView() + } + } + + @ViewBuilder + private func trailing(_ row: GameOptionsRow) -> some View { + if row.isToggle { + SeleneSwitch(isOn: .constant(toggleValue(row))).allowsHitTesting(false) + } else if row.opensSubmenu { + MaterialIconView(.chevron, size: 24).foregroundColor(SeleneTheme.ink60) + } else { + EmptyView() + } + } + + private func toggleValue(_ row: GameOptionsRow) -> Bool { + switch row { + case .favorite: return current.isFavorite + case .hidden: return current.isHidden + default: return false + } + } + + // MARK: - Actions + + private func activate(_ row: GameOptionsRow) { + pickedRow = row + perform(row) + } + + private func perform(_ row: GameOptionsRow) { + let game = current + switch row { + case .play: + guard presentation.canPlay else { SoundEffectService.shared.play(.error); return } + SoundEffectService.shared.play(.click) + onClose() + SteamPlayCoordinator.shared.press(game) + case .editDetails: + SoundEffectService.shared.play(.click) + pickedRow = presentation.focusableRows(level: .editDetails, origin: origin).first + level = .editDetails + case .move: + SoundEffectService.shared.play(.click) + onMove() + case .favorite: + SoundEffectService.shared.play(.click) + viewModel.setCatalogFavorite(game) + case .hidden: + SoundEffectService.shared.play(.click) + let hiding = !game.isHidden + // Close only once the hidden flag is saved: a failed save leaves the game listed. + if viewModel.setCatalogHidden(hiding, game: game), hiding { onClose() } + case .showInFinder: + guard let application else { SoundEffectService.shared.play(.error); return } + SoundEffectService.shared.play(.click) + viewModel.revealInFinder(url: application.url) + case .changeArtwork: + SoundEffectService.shared.play(.click) + artworkOpen = true + case .changeMetadata: + SoundEffectService.shared.play(.click) + metadataOpen = true + case .storePage: + guard let appID = game.steamGame?.appID, let url = URL(string: "https://store.steampowered.com/app/\(appID)/") else { return } + SoundEffectService.shared.play(.click) + viewModel.openURL(url) + default: + break + } + } + + // MARK: - Input + + private func moveFocus(by delta: Int) { + let rows = self.rows + let previous = focusedRow + var focus = GameOptionsFocus(row: pickedRow, in: rows) + focus.move(by: delta, count: rows.count) + pickedRow = focus.row(in: rows) + if focusedRow != previous { SoundEffectService.shared.play(.focus) } + } + + private func back() { + guard !panelOpen else { return } + if level == .editDetails { + level = .main + pickedRow = .editDetails + SoundEffectService.shared.play(.focus) + } else { + onClose() + } + } + + private func handleGamepad(_ action: GamepadAction) { + // Change artwork and Change metadata read the same notifications while open. + guard !panelOpen else { return } + switch action { + case .navigateUp: moveFocus(by: -1) + case .navigateDown: moveFocus(by: 1) + case .confirm: if let row = focusedRow { perform(row) } + case .cancel: back() + case .secondaryAction, .menu: onClose() + default: break + } + } + + private func installKeyMonitor() { + guard keyMonitor == nil else { return } + keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in + guard viewModel.optionsGameID == game.id, + !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, + !NativeMenuCommands.shared.isTracking, + !panelOpen, + viewModel.alertMessage == nil, viewModel.settingsNotice == nil, + let window = event.window, !window.isSheet, window.attachedSheet == nil, + NSApp.modalWindow == nil, !(window.firstResponder is NSText) else { return event } + guard event.modifierFlags.intersection([.command, .control, .option]).isEmpty else { return event } + switch event.keyCode { + case 126: moveFocus(by: -1) + case 125: moveFocus(by: 1) + case 36, 76, 49: if let row = focusedRow { perform(row) } + case 53: back() + default: return event + } + return nil + } + } + + private func removeKeyMonitor() { + if let keyMonitor { NSEvent.removeMonitor(keyMonitor) } + keyMonitor = nil + } +} diff --git a/Sources/NXLibrary/Views/Launch/DevelopmentStartupView.swift b/Sources/NXLibrary/Views/Launch/DevelopmentStartupView.swift new file mode 100644 index 00000000..fa98183a --- /dev/null +++ b/Sources/NXLibrary/Views/Launch/DevelopmentStartupView.swift @@ -0,0 +1,149 @@ +import AppKit +import SwiftUI +import NXLibraryCore +import os + +@MainActor +final class DevelopmentStartup: ObservableObject { + @Published private(set) var shell: AppShellState? + @Published private(set) var failure: String? + @Published private(set) var working = false + @Published private(set) var recovery: CatalogRecoveryCandidate? + @Published private(set) var legacyConflict: CatalogLegacyConflictCandidate? + private let logger = Logger(subsystem: "local.nxlibrary", category: "Startup") + + func prepare() async { + guard shell == nil, !working else { return } + working = true + failure = nil + recovery = nil + legacyConflict = nil + var profileReady = false + do { + // Services and SwiftUI StateObjects are created only after the profile transaction finishes. + if AppData.profile.isDevelopment, + NSRunningApplication.runningApplications(withBundleIdentifier: "local.nxlibrary") + .contains(where: { $0.processIdentifier != ProcessInfo.processInfo.processIdentifier }) { + throw DevelopmentStartupFailure.otherCopyRunning + } + try await Task.detached(priority: .userInitiated) { try AppData.prepare() }.value + profileReady = true + let catalog = try await Task.detached(priority: .userInitiated) { + try CatalogStore(directory: AppData.supportRoot).loadOrMigrate() + }.value + logger.notice("Launcher data ready; preparing shell models") + let store = AppSettingsStore() + // Complete model/AppKit startup outside the render that inserts MainView. + shell = AppShellState(settings: store, catalog: catalog, repository: CatalogRepository(store: CatalogStore(directory: AppData.supportRoot))) + logger.notice("Shell models ready") + } catch { + logger.error("Launcher preparation failed") + failure = error.localizedDescription + if profileReady { + recovery = try? await Task.detached(priority: .userInitiated) { + try CatalogStore(directory: AppData.supportRoot).recoveryCandidate() + }.value + legacyConflict = try? await Task.detached(priority: .userInitiated) { + try CatalogStore(directory: AppData.supportRoot).legacyConflictCandidate() + }.value + } + } + working = false + } + + func restoreBackup() async { + guard !working, let candidate = recovery else { return } + working = true + do { + _ = try await Task.detached(priority: .userInitiated) { + try CatalogStore(directory: AppData.supportRoot).restoreBackup(candidate) + }.value + working = false + await prepare() + } catch { + failure = error.localizedDescription + recovery = nil + working = false + } + } + + func keepCurrentLibrary() async { + guard !working, let candidate = legacyConflict else { return } + working = true + do { + _ = try await Task.detached(priority: .userInitiated) { + try CatalogStore(directory: AppData.supportRoot).keepCurrentLibrary(candidate) + }.value + working = false + await prepare() + } catch { + failure = error.localizedDescription + legacyConflict = nil + working = false + } + } + +} + +private enum DevelopmentStartupFailure: LocalizedError { + case otherCopyRunning + var errorDescription: String? { + L10n.text("Close the other Arcane copy, then try again. Your original library has not been changed.", context: AppLocale(language: .automatic, region: nil)) + } +} + +/// Bootstrap has no app stores, themes or game-operation hooks until its profile is ready. +struct DevelopmentStartupView: View { + @StateObject private var startup = DevelopmentStartup() + private let context = AppLocale(language: .automatic, region: nil) + var body: some View { + Group { + if let shell = startup.shell { + MainView(state: shell) + .onAppear { + Logger(subsystem: "local.nxlibrary", category: "Startup").notice("Library view appeared") + } + } else if let failure = startup.failure { + VStack(spacing: 20) { + if startup.working { ProgressView().controlSize(.large) } + Text(L10n.text("Library unavailable", context: context)) + .font(.system(size: 28, weight: .semibold)) + Text(failure) + .font(.system(size: 17)).multilineTextAlignment(.center) + if startup.legacyConflict != nil { + Text(L10n.text("Keep the games and sources in Arcane. The older app's changes will be archived separately, without merging the libraries.", context: context)) + .font(.system(size: 15)).multilineTextAlignment(.center) + Button(L10n.text("Keep Arcane's library", context: context)) { + Task { await startup.keepCurrentLibrary() } + }.keyboardShortcut("k", modifiers: [.command, .shift]) + .disabled(startup.working) + } + if let candidate = startup.recovery { + Button(L10n.count("Restore backup (%lld games)", candidate.gameCount, context: context)) { + Task { await startup.restoreBackup() } + }.keyboardShortcut("r", modifiers: [.command, .shift]) + .disabled(startup.working) + } + HStack(spacing: 24) { + Button(L10n.text("Close", context: context)) { NSApplication.shared.terminate(nil) } + .keyboardShortcut(.cancelAction) + Button(L10n.text("Open library folder", context: context)) { NSWorkspace.shared.open(AppData.supportRoot) } + .keyboardShortcut("o", modifiers: [.command]) + Button(L10n.text("Retry", context: context)) { Task { await startup.prepare() } } + .keyboardShortcut(.defaultAction) + }.disabled(startup.working) + } + .foregroundColor(.white) + .padding(48).frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Color(red: 0.08, green: 0.09, blue: 0.12)) + .onAppear { LaunchReveal.show() } + } else { + // While the profile is prepared (a fraction of a second) the window is still transparent + // (`LaunchReveal`) and stays on the scrim, with no words or spinner. + SeleneTheme.scrim.ignoresSafeArea() + } + } + .background(LaunchRevealHold()) + .task { await startup.prepare() } + } +} diff --git a/Sources/NXLibrary/Views/Launch/IntroView.swift b/Sources/NXLibrary/Views/Launch/IntroView.swift deleted file mode 100644 index a1be8b3c..00000000 --- a/Sources/NXLibrary/Views/Launch/IntroView.swift +++ /dev/null @@ -1,69 +0,0 @@ -import SwiftUI -import AppKit -import NXLibraryCore - -extension Notification.Name { - static let nxIntroSkip = Notification.Name("NXIntroSkip") -} - -/// The cold-launch intro: the backdrop's flow with the boot cue, held briefly, then faded out over the library. -/// No icon and no wordmark for now; a designed opening animation may replace it later. -/// Any key, click or controller input skips it. -struct IntroView: View { - let settings: AppSettingsStore - let reduceMotion: Bool - let onFinish: () -> Void - - @State private var leaving = false - @State private var finished = false - @State private var keyMonitor: Any? - - var body: some View { - ZStack { - SeleneBackdrop() - } - .accessibilityElement() - .accessibilityLabel(L10n.text("NX Library")) - .opacity(leaving ? 0 : 1) - .ignoresSafeArea() - .contentShape(Rectangle()) - .onTapGesture { skip() } - .onAppear(perform: start) - .onDisappear(perform: removeKeyMonitor) - .onReceive(NotificationCenter.default.publisher(for: .nxIntroSkip)) { _ in skip() } - .task { - do { try await Task.sleep(nanoseconds: 1_400_000_000) } catch { return } - fadeOut() - } - .task(id: leaving) { - guard leaving else { return } - do { try await Task.sleep(nanoseconds: reduceMotion ? 150_000_000 : 400_000_000) } catch { return } - guard !finished else { return } - finished = true - removeKeyMonitor() - onFinish() - } - } - - private func start() { - keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { _ in - skip() - return nil - } - SoundEffectService.shared.bind(to: settings) - SoundEffectService.shared.play(.boot) - } - - /// Input during the intro ends it at once with the closing fade. - func skip() { fadeOut() } - - private func fadeOut() { - guard !leaving else { return } - withAnimation(.easeIn(duration: reduceMotion ? 0.15 : 0.4)) { leaving = true } - } - - private func removeKeyMonitor() { - if let keyMonitor { NSEvent.removeMonitor(keyMonitor) } - keyMonitor = nil - } -} diff --git a/Sources/NXLibrary/Views/Launch/LaunchCoverWindow.swift b/Sources/NXLibrary/Views/Launch/LaunchCoverWindow.swift new file mode 100644 index 00000000..ba251727 --- /dev/null +++ b/Sources/NXLibrary/Views/Launch/LaunchCoverWindow.swift @@ -0,0 +1,111 @@ +import AppKit +import NXLibraryCore +import QuartzCore +import os +import SwiftUI + +/// The launch screen's own window, as Selene's launch cover: borderless and see-through (the screen fades in over +/// the library), over every app, the Dock and the menu bar, on whichever Space is in front, and never activated. The +/// game starts behind it, and Steam coming forward or macOS changing Space happens behind it, so NX Library never has +/// to take the front back. Shown on the screen of the window that hosts it while `state` is set; the content's +/// own fade-out runs before `state` clears. +struct LaunchCoverWindow<Content: View>: NSViewRepresentable { + let state: LaunchOverlayState? + let onPrepared: (UUID) -> Void + @ViewBuilder let content: (LaunchOverlayState) -> Content + + func makeCoordinator() -> Cover { Cover() } + + func makeNSView(context: Context) -> NSView { NSView() } + + func updateNSView(_ view: NSView, context: Context) { + if let state { + context.coordinator.show(AnyView(content(state)), for: state.game.id, on: view.window?.screen ?? NSScreen.main, + prepared: onPrepared) + } else { + context.coordinator.close() + } + } + + static func dismantleNSView(_ view: NSView, coordinator: Cover) { coordinator.close() } + + @MainActor + final class Cover { + private var panel: LaunchCoverPanel? + private var host: LaunchCoverHostingView? + private var gameID: UUID? + + func show(_ content: AnyView, for id: UUID, on screen: NSScreen?, prepared: @escaping (UUID) -> Void) { + guard let screen else { return } + if gameID == id, let panel, let host { + host.rootView = content + if panel.frame != screen.frame { panel.setFrame(screen.frame, display: true) } + return + } + close() + let panel = LaunchCoverPanel(frame: screen.frame) + let host = LaunchCoverHostingView(rootView: content) + panel.contentView = host + self.panel = panel + self.host = host + gameID = id + panel.orderFrontRegardless() + // Leave SwiftUI's representable update before committing the panel. Steam can change Space as soon as + // it receives Play, so send the hand-off only after submitting the ordered cover to the window server. + DispatchQueue.main.async { [weak self, weak panel, weak host] in + guard let self, let panel, let host, self.panel === panel, panel.isVisible else { return } + host.layoutSubtreeIfNeeded() + panel.displayIfNeeded() + CATransaction.flush() + LaunchCoverTrace.event("Cover submitted, active Space: \(panel.isOnActiveSpace)") + prepared(id) + } + } + + func close() { + panel?.orderOut(nil) + panel?.contentView = nil + panel = nil + host = nil + gameID = nil + } + } +} + +/// Local development diagnostics for the cover hand-off, without game or account identifiers. +enum LaunchCoverTrace { + private static let log = Logger(subsystem: "local.nxlibrary.development", category: "launch-cover") + + static func event(_ message: String) { + guard AppData.profile.isDevelopment else { return } + log.notice("\(message, privacy: .public)") + } +} + +/// A click on the screen dismisses it at once: the first click counts although NX Library may not be active. +final class LaunchCoverHostingView: NSHostingView<AnyView> { + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } +} + +final class LaunchCoverPanel: NSPanel { + init(frame: NSRect) { + super.init(contentRect: frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false) + // Over the Dock and the menu bar (on the desktop Space Steam may take the screen to). + level = .statusBar + // Every Space, full-screen ones included, and left in place by Mission Control. When a game opens full screen + // the screen rides along into the game's Space and covers it until the game draws, instead of the desktop + // picture showing there: the maintainer's choice over a screen that stays on NX Library's Space. + collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle] + // A panel hides when its app is not active by default; NX Library rarely is while a game starts. + hidesOnDeactivate = false + isOpaque = false + backgroundColor = .clear + hasShadow = false + isMovable = false + isReleasedWhenClosed = false + animationBehavior = .none + } + + override var canBecomeKey: Bool { false } + override var canBecomeMain: Bool { false } +} diff --git a/Sources/NXLibrary/Views/Launch/LaunchMotion.swift b/Sources/NXLibrary/Views/Launch/LaunchMotion.swift new file mode 100644 index 00000000..6e017b5b --- /dev/null +++ b/Sources/NXLibrary/Views/Launch/LaunchMotion.swift @@ -0,0 +1,175 @@ +import AppKit +import SwiftUI + +/// The launch screen's motion, as Selene's: the game's art drifts slowly closer for as long as the game takes, and +/// its logo comes in once, fading while it rises gently into place, then stands still. Core Animation plays both +/// in the render server while the game or Steam starts. With Reduce Motion the art stands still and the logo fades in. +enum LaunchMotion { + /// Selene's ease-outs: sine for the fades and the drift, quintic for the rise. + static let sineOut = CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1) + static let quinticOut = CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1) + + /// The screen's own fade in; the logo starts a moment after it. + static let screenFade: TimeInterval = 0.36 + static let logoDelay: CFTimeInterval = 0.06 + static let logoFade: CFTimeInterval = 0.75 + static let logoRise: CFTimeInterval = 1.0 + /// How far below its place the logo starts, in canvas units. + static let riseDistance: CGFloat = 30 + + static let artFrom: CGFloat = 1.04 + static let artTo: CGFloat = 1.12 + static let artDrift: CFTimeInterval = 20 +} + +/// The launch screen's game logo: fitted in its bounds, with a soft shadow, coming in once (`LaunchMotion`). The +/// view is larger than the logo by `margin` on every side, so its shadow is not cut. +struct LaunchLogo: NSViewRepresentable { + let image: NSImage + let shadowRadius: CGFloat + /// How far below its place the logo starts, in points. + let rise: CGFloat + /// When the entrance may start (`CACurrentMediaTime`); a logo that arrives later comes in at once. + let startsAt: CFTimeInterval + let reduceMotion: Bool + + /// Room around the logo for its shadow. + static func margin(shadowRadius: CGFloat) -> CGFloat { shadowRadius * 2 } + + /// The logo's size fitted in `bounds`, as SwiftUI's `aspectRatio(contentMode: .fit)` gives it. + static func fitted(_ size: CGSize, in bounds: CGSize) -> CGSize { + guard size.width > 0, size.height > 0 else { return .zero } + let scale = min(bounds.width / size.width, bounds.height / size.height) + return CGSize(width: size.width * scale, height: size.height * scale) + } + + func makeNSView(context: Context) -> LaunchLogoLayerView { + LaunchLogoLayerView(image: image, shadowRadius: shadowRadius, rise: rise, startsAt: startsAt, reduceMotion: reduceMotion) + } + + func updateNSView(_ view: LaunchLogoLayerView, context: Context) { + view.update(image: image, shadowRadius: shadowRadius) + } +} + +final class LaunchLogoLayerView: TileMotionLayerView { + private let logo = CALayer() + private var image: NSImage + private var shadowRadius: CGFloat + private let rise: CGFloat + private let startsAt: CFTimeInterval + private let reduceMotion: Bool + private var entered = false + + init(image: NSImage, shadowRadius: CGFloat, rise: CGFloat, startsAt: CFTimeInterval, reduceMotion: Bool) { + self.image = image + self.shadowRadius = shadowRadius + self.rise = rise + self.startsAt = startsAt + self.reduceMotion = reduceMotion + super.init() + logo.contentsGravity = .resizeAspect + logo.contents = image + // Selene's shadow: black at 55%, no offset. + logo.shadowColor = NSColor.black.cgColor + logo.shadowOpacity = 0.55 + logo.shadowOffset = .zero + root.addSublayer(logo) + } + + required init?(coder: NSCoder) { nil } + + func update(image: NSImage, shadowRadius: CGFloat) { + if image !== self.image { self.image = image; logo.contents = image } + if shadowRadius != self.shadowRadius { self.shadowRadius = shadowRadius; needsLayout = true } + } + + override func arrange(scale: CGFloat) { + let margin = LaunchLogo.margin(shadowRadius: shadowRadius) + logo.frame = bounds.insetBy(dx: margin, dy: margin) + logo.contentsScale = scale + logo.shadowRadius = shadowRadius + } + + /// Once, the first time the logo reaches a window. + override func startLoops() { + guard !entered else { return } + entered = true + let begin = logo.convertTime(max(startsAt, CACurrentMediaTime()), from: nil) + let fade = CABasicAnimation(keyPath: "opacity") + fade.fromValue = Float(0) + fade.toValue = Float(1) + fade.duration = LaunchMotion.logoFade + fade.timingFunction = LaunchMotion.sineOut + fade.beginTime = begin + fade.fillMode = .backwards + logo.add(fade, forKey: "fade") + guard !reduceMotion else { return } + // Below its place: the view is flipped, so its layers' y axis runs down. + let lift = CABasicAnimation(keyPath: "transform.translation.y") + lift.fromValue = rise + lift.toValue = CGFloat(0) + lift.duration = LaunchMotion.logoRise + lift.timingFunction = LaunchMotion.quinticOut + lift.beginTime = begin + lift.fillMode = .backwards + logo.add(lift, forKey: "rise") + } +} + +/// The launch screen's art, filling the screen and drifting slowly closer while the game starts (`LaunchMotion`). +struct LaunchArt: NSViewRepresentable { + let image: NSImage + /// The player's Launch motion setting, off with Reduce Motion too. + let moves: Bool + + func makeNSView(context: Context) -> LaunchArtLayerView { LaunchArtLayerView(image: image, moves: moves) } + + func updateNSView(_ view: LaunchArtLayerView, context: Context) { view.update(image: image) } +} + +final class LaunchArtLayerView: TileMotionLayerView { + private let art = CALayer() + private var image: NSImage + private let moves: Bool + private var drifting = false + + init(image: NSImage, moves: Bool) { + self.image = image + self.moves = moves + super.init() + root.masksToBounds = true + art.contentsGravity = .resizeAspectFill + art.contents = image + if moves { + // The drift's end, held once it is over. + art.transform = CATransform3DMakeScale(LaunchMotion.artTo, LaunchMotion.artTo, 1) + } + root.addSublayer(art) + } + + required init?(coder: NSCoder) { nil } + + func update(image: NSImage) { + if image !== self.image { self.image = image; art.contents = image } + } + + override func arrange(scale: CGFloat) { + // Bounds and position, not frame: the frame of a scaled layer is its scaled box. + art.bounds = CGRect(origin: .zero, size: bounds.size) + art.position = CGPoint(x: bounds.midX, y: bounds.midY) + art.contentsScale = scale + } + + /// Once, the first time the art reaches a window. + override func startLoops() { + guard moves, !drifting else { return } + drifting = true + let drift = CABasicAnimation(keyPath: "transform.scale") + drift.fromValue = LaunchMotion.artFrom + drift.toValue = LaunchMotion.artTo + drift.duration = LaunchMotion.artDrift + drift.timingFunction = LaunchMotion.sineOut + art.add(drift, forKey: "drift") + } +} diff --git a/Sources/NXLibrary/Views/Launch/LaunchReveal.swift b/Sources/NXLibrary/Views/Launch/LaunchReveal.swift new file mode 100644 index 00000000..3febeb03 --- /dev/null +++ b/Sources/NXLibrary/Views/Launch/LaunchReveal.swift @@ -0,0 +1,68 @@ +import AppKit +import SwiftUI + +/// The app's window stays transparent from its first frame until the moonlight has shown one, then fades in, and +/// only then may it go full screen. Without the wait the window opened black and macOS animated its fullscreen +/// transition from a picture of that black window, because the moonlight draws its first frame on its own thread a +/// moment after the library appears. `limit` bounds the wait (a wallpaper with no moonlight, an error screen). +@MainActor +enum LaunchReveal { + static let limit: TimeInterval = 1 + static let fade: TimeInterval = 0.25 + private static weak var window: NSWindow? + private static var held = false + private static var shown = false + private static var done = false + private static var waiting: [() -> Void] = [] + + /// Once per launch, on the window's first appearance. + static func hold(_ window: NSWindow) { + guard !held, !shown else { return } + held = true + self.window = window + window.alphaValue = 0 + DispatchQueue.main.asyncAfter(deadline: .now() + limit) { show() } + } + + /// The first moonlight frame of this launch is on screen. + static func moonlightShown() { show() } + + /// The window fades in once its first frame is ready, or its bounded wait ends. + static func show() { + guard !shown else { return } + shown = true + guard let window, held else { return finish() } + NSAnimationContext.runAnimationGroup({ context in + context.duration = fade + window.animator().alphaValue = 1 + }, completionHandler: { Task { @MainActor in finish() } }) + } + + /// Runs `action` once the window has faded in (at once when it already has). + static func whenShown(_ action: @escaping () -> Void) { + if done { return action() } + waiting.append(action) + } + + private static func finish() { + window?.alphaValue = 1 + done = true + let actions = waiting + waiting = [] + actions.forEach { $0() } + } +} + +/// Holds the window it lands in transparent until `LaunchReveal` shows it. +struct LaunchRevealHold: NSViewRepresentable { + func makeNSView(context: Context) -> LaunchRevealHoldView { LaunchRevealHoldView() } + func updateNSView(_ view: LaunchRevealHoldView, context: Context) {} +} + +final class LaunchRevealHoldView: NSView { + override func hitTest(_ point: NSPoint) -> NSView? { nil } + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + if let window { MainActor.assumeIsolated { LaunchReveal.hold(window) } } + } +} diff --git a/Sources/NXLibrary/Views/Launch/LaunchScreenView.swift b/Sources/NXLibrary/Views/Launch/LaunchScreenView.swift index 4de871f8..c8fb7289 100644 --- a/Sources/NXLibrary/Views/Launch/LaunchScreenView.swift +++ b/Sources/NXLibrary/Views/Launch/LaunchScreenView.swift @@ -2,18 +2,21 @@ import SwiftUI import AppKit import NXLibraryCore -public struct LaunchOverlayState: Equatable { - public let game: PortedGame - public var isReady = false +/// The launch screen of a game Play started here, nxnative or Steam. +struct LaunchOverlayState: Equatable { + let game: PlayedGame + var isReady = false - public init(game: PortedGame, isReady: Bool = false) { + init(game: PlayedGame, isReady: Bool = false) { self.game = game self.isReady = isReady } } -/// Selene's launch screen: art and logo while the game starts, then fade to black and out -/// once the game's window is on screen (`LaunchReadinessProbe`). +/// Selene's launch screen: art drifting closer and the logo coming in once (`LaunchMotion`) while the game starts, +/// then fade to black and out once the game's window is on screen (`LaunchReadinessProbe`). Shown in its own +/// window over every app (`LaunchCoverWindow`). A Steam game's screen also leaves when Steam is +/// late or Play ends (`SteamPlayCoordinator.launchScreen`). struct LaunchScreenView: View { let state: LaunchOverlayState @ObservedObject var viewModel: AppViewModel @@ -25,12 +28,15 @@ struct LaunchScreenView: View { @State private var hero: NSImage? @State private var logo: NSImage? @State private var shown = false - @State private var drift = false + /// When the screen appeared, for the logo's entrance after the screen's fade. + @State private var appearedAt: CFTimeInterval = 0 @State private var blackout = false @State private var leaving = false - @State private var breathe = false - private var game: PortedGame { state.game } + private var game: PlayedGame { state.game } + + /// The longest the screen stays: past a Steam cold start (45 s), the game's start and the 60 s window probe. + static let ceiling: TimeInterval = 120 private var shadeOpacity: Double { switch settings.launchShade { @@ -53,7 +59,6 @@ struct LaunchScreenView: View { centrePiece Color.black.opacity(blackout ? 1 : 0) } - .overlay(alignment: .bottomTrailing) { mark } .ignoresSafeArea() .opacity(shown && !leaving ? 1 : 0) .contentShape(Rectangle()) @@ -65,17 +70,18 @@ struct LaunchScreenView: View { if ready { finish() } } .task(id: game.id) { await loadArt() } + .task(id: game.id) { + // The screen covers every app: whatever happens to the launch, it never stays up for good. + try? await Task.sleep(nanoseconds: UInt64(Self.ceiling * 1_000_000_000)) + if !Task.isCancelled { finish() } + } } private var art: some View { GeometryReader { geo in if let hero { - Image(nsImage: hero) - .resizable() - .aspectRatio(contentMode: .fill) + LaunchArt(image: hero, moves: settings.launchMotion && !reduceMotion) .frame(width: geo.size.width, height: geo.size.height) - .scaleEffect(drift ? 1.06 : 1.0) - .clipped() .transition(.opacity) } Color.black.opacity(shadeOpacity) @@ -88,11 +94,14 @@ struct LaunchScreenView: View { EmptyView() case .artAndLogo, .logoOnBlack: if let logo { - Image(nsImage: logo) - .resizable() - .aspectRatio(contentMode: .fit) - .frame(maxWidth: canvas.u(720), maxHeight: canvas.u(320)) - .shadow(color: .black.opacity(0.5), radius: canvas.u(18)) + // Selene's size: at most half the width and 38% of the height; the view adds room for the shadow. + let size = LaunchLogo.fitted(logo.size, in: CGSize(width: canvas.u(960), height: canvas.u(410))) + let margin = LaunchLogo.margin(shadowRadius: canvas.u(18)) + LaunchLogo(image: logo, shadowRadius: canvas.u(18), rise: canvas.u(LaunchMotion.riseDistance), + startsAt: appearedAt + LaunchMotion.screenFade + LaunchMotion.logoDelay, + reduceMotion: reduceMotion) + .frame(width: size.width + margin * 2, height: size.height + margin * 2) + .accessibilityHidden(true) } else { title } @@ -109,29 +118,13 @@ struct LaunchScreenView: View { .padding(.horizontal, canvas.u(120)) } - private var mark: some View { - Image(nsImage: NSApplication.shared.applicationIconImage) - .resizable() - .interpolation(.high) - .frame(width: canvas.u(56), height: canvas.u(56)) - .opacity(breathe ? 1 : 0.45) - .padding(.trailing, canvas.u(64)) - .padding(.bottom, canvas.u(56)) - .accessibilityHidden(true) - } - private func appear() { + LaunchCoverTrace.event("Screen content appeared") + appearedAt = CACurrentMediaTime() hero = GameArtLoader.shared.cachedHero(for: game) logo = GameArtLoader.shared.cachedLogo(for: game) - withAnimation(.easeOut(duration: 0.25)) { shown = true } - if settings.launchMotion && !reduceMotion { - withAnimation(.linear(duration: 20)) { drift = true } - } - if !reduceMotion { - withAnimation(.easeInOut(duration: 1.6).repeatForever(autoreverses: true)) { breathe = true } - } else { - breathe = true - } + withAnimation(.easeOut(duration: LaunchMotion.screenFade)) { shown = true } + if state.isReady { finish() } } private func finish() { @@ -152,13 +145,14 @@ struct LaunchScreenView: View { let metadata = viewModel.storeMetadata[game.id] if hero == nil, showsArt { let loaded = await GameArtLoader.shared.hero( - for: game, metadata: metadata, artwork: artwork) + for: game, metadata: metadata, artwork: artwork, personalizations: viewModel.personalizations) withAnimation(.easeOut(duration: 0.3)) { hero = loaded } } if logo == nil, settings.launchStyle != .minimal, settings.launchStyle != .artOnly { let loaded = await GameArtLoader.shared.logo( - for: game, metadata: metadata, artwork: artwork) - withAnimation(.easeOut(duration: 0.3)) { logo = loaded } + for: game, metadata: metadata, artwork: artwork, personalizations: viewModel.personalizations) + // The logo comes in by itself (`LaunchLogo`). + logo = loaded } } } diff --git a/Sources/NXLibrary/Views/MainView.swift b/Sources/NXLibrary/Views/MainView.swift index 4b285b9f..0a4fe7d8 100644 --- a/Sources/NXLibrary/Views/MainView.swift +++ b/Sources/NXLibrary/Views/MainView.swift @@ -2,11 +2,11 @@ import SwiftUI import NXLibraryCore public struct MainView: View { - private let settingsStore: AppSettingsStore + private let state: AppShellState - public init(settingsStore: AppSettingsStore) { - self.settingsStore = settingsStore + @MainActor init(state: AppShellState) { + self.state = state } - public var body: some View { AppShellView(settingsStore: settingsStore) } + public var body: some View { AppShellView(state: state) } } diff --git a/Sources/NXLibrary/Views/Search/FindGameView.swift b/Sources/NXLibrary/Views/Search/FindGameView.swift index f1723b31..7d7d23c9 100644 --- a/Sources/NXLibrary/Views/Search/FindGameView.swift +++ b/Sources/NXLibrary/Views/Search/FindGameView.swift @@ -26,10 +26,10 @@ struct FindGameView: View { private static let columns = 6 private static let limit = 12 - private var results: [PortedGame] { + private var results: [CatalogGame] { guard !query.trimmingCharacters(in: .whitespaces).isEmpty else { return [] } let all = LibraryQuery(filter: .all, searchText: query) - .apply(to: viewModel.libraryGames, history: playSessions) + .applyCatalog(to: viewModel.visibleCatalogGames, history: playSessions) return Array(all.prefix(Self.limit)) } @@ -60,6 +60,7 @@ struct FindGameView: View { } .onDisappear(perform: removeKeyMonitor) .onChange(of: query) { _ in focused = nil } + .onChange(of: results.map(\.id)) { _ in focused = nil } .onReceive(NotificationCenter.default.publisher(for: .nxFindGameGamepadAction)) { note in guard let action = note.object as? GamepadAction else { return } handle(action) @@ -105,9 +106,12 @@ struct FindGameView: View { } } - private func tile(_ game: PortedGame, selected: Bool) -> some View { + private func tile(_ game: CatalogGame, selected: Bool) -> some View { VStack(spacing: canvas.u(10)) { - SpotlightTileArtwork(game: game, side: canvas.u(160), artwork: artwork) + Group { + if let native = game.nxnativeGame { SpotlightTileArtwork(game: native, side: canvas.u(160), artwork: artwork) } + else { CatalogNativeArtwork(game: game, role: .square) } + } .frame(width: canvas.u(160), height: canvas.u(160)) .clipShape(RoundedRectangle(cornerRadius: canvas.u(12), style: .continuous)) .overlay(SeleneTileRing(cornerRadius: canvas.u(12), active: selected)) @@ -166,7 +170,7 @@ struct FindGameView: View { SoundEffectService.shared.play(.focus) } - private func pick(_ game: PortedGame?) { + private func pick(_ game: CatalogGame?) { guard let game else { return } SoundEffectService.shared.play(.click) router.isSearchPresented = false diff --git a/Sources/NXLibrary/Views/Settings/SettingsAPISection.swift b/Sources/NXLibrary/Views/Settings/SettingsAPISection.swift new file mode 100644 index 00000000..5c38b0d6 --- /dev/null +++ b/Sources/NXLibrary/Views/Settings/SettingsAPISection.swift @@ -0,0 +1,61 @@ +import SwiftUI +import NXLibraryCore + +/// General, optional connections; moving them here leaves stored credentials and provider behaviour intact. +struct SettingsAPISection: View { + @ObservedObject var viewModel: AppViewModel + let onActions: ([SettingsRowAction]) -> Void + @Environment(\.seleneCanvas) private var canvas + @ObservedObject private var igdb = IGDBSettings.shared + + var body: some View { + VStack(alignment: .leading, spacing: canvas.u(8)) { + Text(L10n.text("Connect optional services to enrich your library with ratings and artwork. Public sources remain available without API keys.")) + .seleneFont(16) + .foregroundColor(SeleneTheme.ink60) + .fixedSize(horizontal: false, vertical: true) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.bottom, canvas.u(8)) + + SettingsSubheading(L10n.text("Ratings")) + SeleneRow("IGDB", subtitle: igdb.message ?? (igdb.isConfigured + ? "IGDB connected · Wikidata is the fallback" + : "Optional critic scores with your own credentials")) { + HStack(spacing: canvas.u(18)) { + Button(L10n.text(igdb.isConfigured ? "Edit credentials" : "Connect")) { igdb.isEditing = true } + .foregroundColor(SeleneTheme.glyph) + if igdb.isConfigured { + Button(L10n.text("Remove")) { Task { await igdb.remove() } } + .foregroundColor(SeleneTheme.ink60).disabled(igdb.isRemoving) + } + } + .buttonStyle(.plain).seleneFont(15, .semibold) + } + + SettingsSubheading(L10n.text("Artwork")) + SeleneButtonRow("SteamGridDB", + subtitle: viewModel.hasSteamGridDBKey + ? "Key saved · covers, backgrounds, logos and icons in Change artwork" + : "Add your free API key to find art in Change artwork", + buttonTitle: viewModel.hasSteamGridDBKey ? "Remove key" : "Add key") { + steamGridDBAction() + } + } + .onAppear(perform: publishActions) + .onChange(of: igdb.revision) { _ in publishActions() } + } + private func steamGridDBAction() { + if viewModel.hasSteamGridDBKey { viewModel.removeSteamGridDBKey() } + else { viewModel.isEditingSteamGridDBKey = true } + } + private func publishActions() { + onActions([ + .init(id: "IGDB", title: "IGDB", + secondary: igdb.isConfigured ? (title: "Remove", activate: { Task { await igdb.remove() }; return }) : nil) { + igdb.isEditing = true + }, + .init(id: "SteamGridDB", title: "SteamGridDB") { steamGridDBAction() } + ]) + } +} diff --git a/Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift b/Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift index 8613a66d..4cf6fd7d 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift @@ -6,9 +6,14 @@ struct SettingsAboutSection: View { @ObservedObject var viewModel: AppViewModel @EnvironmentObject private var updater: AppUpdater @Environment(\.seleneFocusedRowID) private var focusedRowTitle + @Environment(\.seleneCanvas) private var canvas + @Environment(\.nxAppLocale) private var localization let onActions: ([SettingsRowAction]) -> Void @State private var didCopyDiagnostics = false + private static let supportTitle = "Support Arcane" + private static let supportArtwork = Bundle.main.url(forResource: "BuyMeACoffee", withExtension: "png", + subdirectory: "Brands").flatMap(NSImage.init(contentsOf:)) private let credits: [(name: String, role: String, url: String)] = [ ("seedds", "nxnative engine, NVN/Metal host and ARM64 rewriter", "https://github.com/seedds/nxnative"), @@ -19,22 +24,24 @@ struct SettingsAboutSection: View { ("Khronos Group", L10n.text("SPIRV-Cross Metal Shading Language compiler"), "https://github.com/KhronosGroup/SPIRV-Cross"), ("GameTDB", L10n.text("Switch box covers"), "https://www.gametdb.com"), ("Title DB", L10n.text("Game names, icons and banners"), "https://github.com/blawar/titledb"), - ("LaunchBox Games Database", L10n.text("Box covers, logos, backgrounds and square art in Change artwork"), "https://gamesdb.launchbox-app.com"), + ("LaunchBox Games Database", L10n.text("Community metadata and game artwork"), "https://gamesdb.launchbox-app.com"), + ("TheGamesDB", L10n.text("Community metadata and game artwork"), "https://thegamesdb.net"), ("SteamGridDB", L10n.text("Community covers, backgrounds, logos and icons, with your API key"), "https://www.steamgriddb.com"), + ("IGDB", L10n.text("Critic scores with your own credentials"), "https://www.igdb.com"), ("NX2Apple", L10n.text("Key check, failure explanations and diagnostics, adapted (MIT)"), "https://github.com/LNPANDY/NX2Apple") ] var body: some View { VStack(spacing: 12) { - SelenePanel(L10n.text("NX Library")) { - Text(L10n.text("A personal macOS front-end for building and launching your own Switch games with nxnative.")) + SelenePanel(AppIdentity.name) { + Text(L10n.text("A free, open-source game library and launcher for Mac. Play installed games and port compatible Switch titles with nxnative.")) .seleneFont(16) .foregroundColor(SeleneTheme.ink90) .fixedSize(horizontal: false, vertical: true) Text(L10n.format("Version %@ · Build %@ · Engine %@", [String(describing: (version)), String(describing: (buildDate)), String(describing: (seleneShort(viewModel.pinnedEngineCommit)))])) .seleneFont(13, .regular, design: .monospaced) .foregroundColor(SeleneTheme.ink60) - Text(L10n.text("Play time is tracked only for launches from NX Library. Not affiliated with Nintendo.")) + Text(L10n.text("Play time is tracked only for launches from Arcane. Not affiliated with Nintendo.")) .seleneFont(13) .foregroundColor(SeleneTheme.ink60) updateRow @@ -55,6 +62,8 @@ struct SettingsAboutSection: View { .accessibilityHint(L10n.text("A report for an issue: versions, setup and the last porting. No keys.")) } + supportButton + SelenePanel(L10n.text("Credits")) { LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) { ForEach(credits, id: \.name) { credit in @@ -108,7 +117,7 @@ struct SettingsAboutSection: View { .padding(6) .seleneRowFocus(focusedRowTitle == "Selene") .id("selene-row-Selene") - Text(L10n.text("Selene is a Playnite theme for Windows. No Selene name, logo, wallpaper, avatar or sound is used as NX Library branding; this is a visual adaptation in SwiftUI.")) + Text(L10n.text("Selene is a Playnite theme for Windows. No Selene name, logo, wallpaper, avatar or sound is used as Arcane branding; this is a visual adaptation in SwiftUI.")) .seleneFont(13) .foregroundColor(SeleneTheme.ink60) .fixedSize(horizontal: false, vertical: true) @@ -125,7 +134,7 @@ struct SettingsAboutSection: View { } SelenePanel(L10n.text("Licenses")) { - Text(L10n.text("NX Library is personal software released under the MIT license. nxnative, Ryujinx, SPIR-V Cross, LibHac and the other dependencies retain their own licenses through the engine.")) + Text(L10n.text("Arcane is personal software released under the MIT license. nxnative, Ryujinx, SPIR-V Cross, LibHac and the other dependencies retain their own licenses through the engine.")) .seleneFont(15) .foregroundColor(SeleneTheme.ink90) .fixedSize(horizontal: false, vertical: true) @@ -148,6 +157,14 @@ struct SettingsAboutSection: View { Text(L10n.text("This app is not affiliated with Nintendo.")) .seleneFont(13, .semibold) .foregroundColor(SeleneTheme.ink60) + Text(L10n.text("This app is not affiliated with Valve.")) + .seleneFont(13, .semibold) + .foregroundColor(SeleneTheme.ink60) + // Valve's attribution for the Steam logo, in Valve's own wording for each language. + Text(L10n.text("©2026 Valve Corporation. Steam and the Steam logo are trademarks and/or registered trademarks of Valve Corporation in the U.S. and/or other countries.")) + .seleneFont(13) + .foregroundColor(SeleneTheme.ink60) + .fixedSize(horizontal: false, vertical: true) } } .onAppear(perform: publishActions) @@ -159,6 +176,42 @@ struct SettingsAboutSection: View { .onChange(of: viewModel.runningGameCount) { _ in publishActions() } } + private var supportButton: some View { + Button(action: openSupportPage) { + SelenePanel { + HStack(spacing: canvas.u(14)) { + if let artwork = Self.supportArtwork { + Image(nsImage: artwork) + .resizable() + .interpolation(.high) + .scaledToFit() + .frame(width: canvas.u(44), height: canvas.u(44)) + .clipShape(RoundedRectangle(cornerRadius: canvas.u(9), style: .continuous)) + .accessibilityHidden(true) + } + VStack(alignment: .leading, spacing: canvas.u(4)) { + Text(L10n.text(Self.supportTitle, context: localization)) + .seleneFont(19, .semibold) + .foregroundColor(SeleneTheme.ink) + Text(L10n.text("Optional contributions support development and maintenance.", context: localization)) + .seleneFont(14) + .foregroundColor(SeleneTheme.ink75) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: canvas.u(8)) + Image(systemName: "arrow.up.right") + .seleneFont(16, .semibold) + .foregroundColor(SeleneTheme.glyph) + .accessibilityHidden(true) + } + } + .contentShape(RoundedRectangle(cornerRadius: SeleneTheme.cardRadius, style: .continuous)) + } + .buttonStyle(.plain) + .seleneRowFocus(focusedRowTitle == Self.supportTitle, radius: SeleneTheme.cardRadius) + .id("selene-row-\(Self.supportTitle)") + } + private func copyDiagnostics() { viewModel.copyDiagnostics() didCopyDiagnostics = true @@ -171,6 +224,7 @@ struct SettingsAboutSection: View { isEnabled: action.enabled, activate: action.perform) } actions.append(.init(id: "diagnostics", title: "Copy diagnostics", activate: copyDiagnostics)) + actions.append(.init(id: "support", title: Self.supportTitle, activate: openSupportPage)) actions += credits.map { credit in SettingsRowAction(id: "credit-\(credit.name)", title: credit.name) { if let url = URL(string: credit.url) { NSWorkspace.shared.open(url) } @@ -217,10 +271,10 @@ struct SettingsAboutSection: View { switch updater.state { case .hidden: return "" case .developer: return L10n.text("Development copy · manual checks only") - case .readOnly: return L10n.text("Move NX Library to Applications to update") + case .readOnly: return L10n.text("Move Arcane to Applications to update") case .idle: return L10n.text("Updates not checked yet") case .checking: return "Checking for updates…" - case .upToDate: return L10n.text("NX Library is up to date") + case .upToDate: return L10n.text("Arcane is up to date") case .available(let release): let xcode = AppUpdate.neededXcode(release.requirements, installedXcode: viewModel.environmentStatus?.xcodeVersion) .map { L10n.format(" · new portings need Xcode %@", [String(describing: ($0))]) } ?? "" @@ -262,6 +316,12 @@ struct SettingsAboutSection: View { return "local" } + private func openSupportPage() { + if let url = URL(string: "https://buymeacoffee.com/bium") { + NSWorkspace.shared.open(url) + } + } + private func openProjectDocs() { let docs = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Developer/NXLibrary/docs") diff --git a/Sources/NXLibrary/Views/Settings/SettingsCloudSavesSection.swift b/Sources/NXLibrary/Views/Settings/SettingsCloudSavesSection.swift new file mode 100644 index 00000000..ae04196a --- /dev/null +++ b/Sources/NXLibrary/Views/Settings/SettingsCloudSavesSection.swift @@ -0,0 +1,43 @@ +import SwiftUI +import NXLibraryCore + +/// Porting → Cloud saves: one save-sync choice for every ported game, applied at its next launch. +struct SettingsCloudSavesSection: View { + @ObservedObject var viewModel: AppViewModel + @ObservedObject var settings: AppSettingsStore + let onActions: ([SettingsRowAction]) -> Void + @Environment(\.seleneCanvas) private var canvas + + private var cloudSaves: CloudSaves { settings.settings.cloudSaves } + + private var pickedFolderSubtitle: String { + let picked = settings.settings.cloudSavesPickedFolder + return picked.isEmpty ? L10n.text("None chosen yet.") : (picked as NSString).abbreviatingWithTildeInPath + } + + private func stepCloudSaves(_ step: Int) { + viewModel.setCloudSaves(cloudSaves.stepped(step, picked: settings.settings.cloudSavesPickedFolder)) + } + + var body: some View { + VStack(spacing: canvas.u(8)) { + SeleneCycleRow("Cloud saves", + subtitle: "All games · Next launch", + info: "Applied before each game starts, including Off. Custom save-sync overrides are reported in Saves. Cloud sync covers only the primary user and device save.", + value: cloudSaves.title, cycle: stepCloudSaves) + + SeleneButtonRow("Cloud saves folder", + subtitle: pickedFolderSubtitle, + buttonTitle: "Choose…") { viewModel.chooseCloudSavesFolder() } + + } + .onAppear(perform: publishActions) + } + + private func publishActions() { + onActions([ + .value("cloudSaves", "Cloud saves", cycle: stepCloudSaves), + .init(id: "cloudSavesFolder", title: "Cloud saves folder") { viewModel.chooseCloudSavesFolder() } + ]) + } +} diff --git a/Sources/NXLibrary/Views/Settings/SettingsConsoleSection.swift b/Sources/NXLibrary/Views/Settings/SettingsConsoleSection.swift new file mode 100644 index 00000000..631db995 --- /dev/null +++ b/Sources/NXLibrary/Views/Settings/SettingsConsoleSection.swift @@ -0,0 +1,21 @@ +import SwiftUI +import NXLibraryCore + +/// System → Console: the build and launch logs, to filter, search and copy. +struct SettingsConsoleSection: View { + let onActions: ([SettingsRowAction]) -> Void + let onOpenConsole: () -> Void + + var body: some View { + VStack(spacing: 9) { + SeleneButtonRow("Console", + subtitle: "Filter, search and copy build and launch logs.", + buttonTitle: "Open") { + onOpenConsole() + } + } + .onAppear { + onActions([.init(id: "console", title: "Console") { onOpenConsole() }]) + } + } +} diff --git a/Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift b/Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift index 6df76127..b2e95aac 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift @@ -47,24 +47,6 @@ struct SettingsControllersSection: View { .frame(width: 38, alignment: .trailing) } } - - SettingsSubheading(L10n.text("New games")) - - SeleneToggleRow("Rumble", - subtitle: "Controller vibration", - isOn: $settings.settings.gameDefaults.rumble) - - SeleneRow("Rumble strength", - subtitle: "Vibration strength", - info: "Default haptic feedback multiplier (0: muted, 1: subtle, 2: standard, 3: intense) passed to game builds supporting macOS controller haptics.") { - Stepper(value: $settings.settings.gameDefaults.rumbleGain, in: 0...3) { - Text("\(settings.settings.gameDefaults.rumbleGain)") - .seleneFont(15, .semibold, design: .monospaced) - .foregroundColor(SeleneTheme.glyph) - .frame(width: 20, alignment: .trailing) - } - .fixedSize() - } } .onAppear(perform: publishActions) .onChange(of: controller.deadzone) { _ in publishActions() } @@ -80,13 +62,6 @@ struct SettingsControllersSection: View { }, .value("deadzone", "Stick navigation deadzone") { step in controller.deadzone = min(0.80, max(0.10, controller.deadzone + 0.05 * Float(step))) - }, - .init(id: "rumble", title: "Rumble") { - settings.settings.gameDefaults.rumble.toggle() - }, - .value("gain", "Rumble strength") { step in - let gain = settings.settings.gameDefaults.rumbleGain + step - settings.settings.gameDefaults.rumbleGain = min(3, max(0, gain)) } ]) } diff --git a/Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift b/Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift index 9aa5762c..d262bbe4 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift @@ -3,6 +3,7 @@ import NXLibraryCore struct SettingsEngineSection: View { @ObservedObject var viewModel: AppViewModel + @ObservedObject var settings: AppSettingsStore let onActions: ([SettingsRowAction]) -> Void @Environment(\.seleneFocusedRowID) private var focusedRowTitle @@ -98,6 +99,11 @@ struct SettingsEngineSection: View { } .seleneRowFocus(focusedRowTitle == "Compatibility", radius: SeleneTheme.cardRadius) + SeleneToggleRow("Check engine at launch", + subtitle: "Verify the pinned engine commit and toolchain when the app starts.", + info: "Checks the nxnative checkout against the certified engine commit and confirms your installed Metal compiler matches the lock file before builds are attempted.", + isOn: $settings.settings.checkEngineAtLaunch) + SeleneRow("Untested toolchain override", subtitle: overrideSubtitle, info: "Permits building games when the toolchain differs from the certified engine and Metal combination shown above. Passes --allow-other-metal to nxnative. Builds are recorded as unverified.") { @@ -130,52 +136,12 @@ struct SettingsEngineSection: View { } } - SelenePanel(L10n.text("prod.keys"), - info: L10n.text("Nintendo Switch cryptographic keys required to decrypt game packages (NSP/XCI). NX Library stores a private copy with mode 0600 permissions; key values are never displayed or logged.")) { - HStack(spacing: 8) { - Image(systemName: viewModel.isProdKeysValid ? "checkmark.circle.fill" : "xmark.octagon.fill") - .seleneFont(15, .bold) - .foregroundColor(viewModel.isProdKeysValid ? SeleneTheme.success : SeleneTheme.danger) - Text(viewModel.isProdKeysValid ? L10n.text("Keys imported") : L10n.text("No prod.keys imported")) - .seleneFont(15, .semibold) - .foregroundColor(SeleneTheme.ink) - Spacer() - Text(viewModel.isProdKeysValid && !viewModel.prodKeysPath.isEmpty - ? viewModel.prodKeysPath : L10n.text("Choose your file once")) - .seleneFont(13, .regular, design: .monospaced) - .foregroundColor(SeleneTheme.ink60) - .lineLimit(1) - .truncationMode(.middle) - } - - if let summary = viewModel.keySummary { - Text(L10n.format("header_key present · %@ application key generations", [String(describing: (summary.applicationKeyGenerations.count))])) - .seleneFont(13, .regular, design: .monospaced) - .foregroundColor(SeleneTheme.success) - } - - HStack(spacing: 14) { - Button(viewModel.isProdKeysValid ? L10n.text("Replace Key...") : L10n.text("Import Key...")) { - viewModel.selectProdKeysFile() - } - .buttonStyle(.plain) - .seleneFont(14, .semibold) - .foregroundColor(SeleneTheme.glyph) - .disabled(configurationLocked) - Button(L10n.text("Detect Ryujinx...")) { viewModel.selectRyujinxFolder() } - .buttonStyle(.plain) - .seleneFont(14, .semibold) - .foregroundColor(SeleneTheme.glyph) - .disabled(configurationLocked) - Spacer() - } - - Text(L10n.text("The original file is untouched. The stored copy is mode 0600 and key values are never shown or logged.")) - .seleneFont(13) - .foregroundColor(SeleneTheme.ink60) - .fixedSize(horizontal: false, vertical: true) + SeleneButtonRow("Setup", + subtitle: "Open the Setup check: what Arcane needs and what is ready.", + buttonTitle: "Open Setup") { + viewModel.reopenSetup() } - .seleneRowFocus(focusedRowTitle == "prod.keys", radius: SeleneTheme.cardRadius) + .disabled(configurationLocked) } .onAppear { viewModel.prepareBuildEnvironmentIfNeeded() @@ -250,7 +216,7 @@ struct SettingsEngineSection: View { private var upstreamSubtitle: String { switch viewModel.upstreamState { case .idle: - return L10n.text("See how this NX Library's engine compares with seedds/nxnative main.") + return L10n.text("See how this version's engine compares with seedds/nxnative main.") case .checking: return L10n.text("Asking GitHub for the latest commits...") case .loaded(let status): @@ -491,7 +457,7 @@ struct SettingsEngineSection: View { private func runtimeDetail(_ environment: EnvironmentStatus) -> String { guard let python = environment.pythonURL else { return "missing" } if viewModel.engineToolchain.isBundled { - return BundledRuntime.locate()?.versionSummary() ?? L10n.text("Included in NX Library") + return BundledRuntime.locate()?.versionSummary() ?? L10n.text("Included in Arcane") } return L10n.format("Developer build: %@", [String(describing: (python.path))]) } @@ -539,6 +505,9 @@ struct SettingsEngineSection: View { .init(id: "recheck", title: "Compatibility", isEnabled: !configurationLocked) { viewModel.detectEnvironment() }, + .init(id: "engineAtLaunch", title: "Check engine at launch") { + settings.settings.checkEngineAtLaunch.toggle() + }, .init(id: "override", title: "Untested toolchain override", isEnabled: canChangeOverride) { if viewModel.allowUntestedToolchain { @@ -565,8 +534,8 @@ struct SettingsEngineSection: View { viewModel.openUpstreamCompare() }) } - actions.append(.init(id: "keys", title: "prod.keys", isEnabled: !configurationLocked) { - viewModel.selectProdKeysFile() + actions.append(.init(id: "setup", title: "Setup", isEnabled: !configurationLocked) { + viewModel.reopenSetup() }) onActions(actions) } diff --git a/Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift b/Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift index 25632ee9..3129b868 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift @@ -1,6 +1,7 @@ import SwiftUI import NXLibraryCore +/// Porting → New games: the defaults copied into each new ported game, rumble included. struct SettingsGamesSection: View { @ObservedObject var viewModel: AppViewModel @ObservedObject var settings: AppSettingsStore @@ -16,95 +17,8 @@ struct SettingsGamesSection: View { return options } - /// Games hidden from Game options, by name (the library keeps them sorted). - private var hiddenGames: [PortedGame] { - viewModel.libraryGames.filter(\.isHidden) - } - - private func unhide(_ game: PortedGame) { - SoundEffectService.shared.play(.click) - viewModel.toggleHidden(game) - } - - private var surprisePoolTitle: String { - switch settings.settings.surprisePool { - case .installed: return "Installed" - case .notPlayed: return "Not played yet" - case .all: return "All games" - } - } - - private var cloudSaves: CloudSaves { settings.settings.cloudSaves } - - private var pickedFolderSubtitle: String { - let picked = settings.settings.cloudSavesPickedFolder - return picked.isEmpty ? L10n.text("None chosen yet.") : (picked as NSString).abbreviatingWithTildeInPath - } - - private func stepCloudSaves(_ step: Int) { - viewModel.setCloudSaves(cloudSaves.stepped(step, picked: settings.settings.cloudSavesPickedFolder)) - } - var body: some View { VStack(spacing: canvas.u(8)) { - SettingsSubheading(L10n.text("All games")) - - SeleneCycleRow("Launch screen style", - subtitle: "Artwork layout", - value: settings.settings.launchStyle.title) { step in - settings.settings.launchStyle = settings.settings.launchStyle.stepped(step) - } - - SeleneToggleRow("Launch screen motion", - subtitle: "Artwork drift", - isOn: $settings.settings.launchMotion) - - SeleneCycleRow("Launch screen shade", - subtitle: "Launch brightness", - value: settings.settings.launchShade.title) { step in - settings.settings.launchShade = settings.settings.launchShade.stepped(step) - } - - SeleneToggleRow("Session card", - subtitle: "Your playtime when a game closes", - info: "When you close a game, a card shows how long you played this time and in total. Sessions under 10 seconds show none.", - isOn: $settings.settings.showsSessionCard) - - SeleneCycleRow("Surprise me pool", - subtitle: "Which games Surprise me picks from.", - value: surprisePoolTitle) { step in - settings.settings.surprisePool = settings.settings.surprisePool.stepped(step) - } - - SettingsSubheading(L10n.text("Cloud saves")) - - SeleneCycleRow("Cloud saves", - subtitle: "All games · Next launch", - info: "Applied before each game starts, including Off. Reset group keeps cloud sync and its folder. Custom save-sync overrides are reported in Saves.", - value: cloudSaves.title, cycle: stepCloudSaves) - - SeleneButtonRow("Cloud saves folder", - subtitle: pickedFolderSubtitle, - buttonTitle: "Choose…") { viewModel.chooseCloudSavesFolder() } - - SettingsSubheading(L10n.text("Hidden games")) - - if hiddenGames.isEmpty { - Text(L10n.text("No hidden games. Hide one from its Game options; it comes back here.")) - .seleneFont(15) - .foregroundColor(SeleneTheme.ink60) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.leading, canvas.u(26)) - } else { - ForEach(hiddenGames) { game in - SeleneButtonRow(game.name, id: "hidden-\(game.id)", - subtitle: "Out of Spotlight, Collection, Surprise me and search.", verbatimTitle: true, - buttonTitle: "Show") { unhide(game) } - } - } - - SettingsSubheading(L10n.text("New games")) - SeleneToggleRow("Fullscreen", subtitle: "Launch mode", isOn: $settings.settings.gameDefaults.fullscreen) @@ -156,42 +70,35 @@ struct SettingsGamesSection: View { } } + SeleneToggleRow("Rumble", + subtitle: "Vibration in new ported games", + isOn: $settings.settings.gameDefaults.rumble) + + SeleneRow("Rumble strength", + subtitle: "Vibration strength", + info: "Default haptic feedback multiplier (0: muted, 1: subtle, 2: standard, 3: intense) passed to game builds supporting macOS controller haptics.") { + Stepper(value: $settings.settings.gameDefaults.rumbleGain, in: 0...3) { + Text("\(settings.settings.gameDefaults.rumbleGain)") + .seleneFont(15, .semibold, design: .monospaced) + .foregroundColor(SeleneTheme.glyph) + .frame(width: 20, alignment: .trailing) + } + .fixedSize() + } } .onAppear(perform: publishActions) - .onChange(of: hiddenGames.map(\.id)) { _ in publishActions() } } private func publishActions() { - // Same order as the rows: cloud saves and the hidden games sit between - // Surprise me and the defaults. - let cloud: [SettingsRowAction] = [ - .value("cloudSaves", "Cloud saves", cycle: stepCloudSaves), - .init(id: "cloudSavesFolder", title: "Cloud saves folder") { viewModel.chooseCloudSavesFolder() } - ] - let hidden = hiddenGames.map { game in - SettingsRowAction(id: "hidden-\(game.id)", title: game.name, rowID: "hidden-\(game.id)") { unhide(game) } - } - onActions(launchActions + cloud + hidden + defaultActions) - } - - private var launchActions: [SettingsRowAction] { - [ - .value("launchStyle", "Launch screen style") { step in - settings.settings.launchStyle = settings.settings.launchStyle.stepped(step) - }, - .init(id: "launchMotion", title: L10n.text("Launch screen motion"), rowID: "Launch screen motion") { - settings.settings.launchMotion.toggle() - }, - .value("launchShade", "Launch screen shade") { step in - settings.settings.launchShade = settings.settings.launchShade.stepped(step) + onActions(defaultActions + [ + .init(id: "rumble", title: "Rumble") { + settings.settings.gameDefaults.rumble.toggle() }, - .init(id: "showsSessionCard", title: L10n.text("Session card"), rowID: "Session card") { - settings.settings.showsSessionCard.toggle() - }, - .value("surprisePool", "Surprise me pool") { step in - settings.settings.surprisePool = settings.settings.surprisePool.stepped(step) + .value("gain", "Rumble strength") { step in + let gain = settings.settings.gameDefaults.rumbleGain + step + settings.settings.gameDefaults.rumbleGain = min(3, max(0, gain)) } - ] + ]) } private var defaultActions: [SettingsRowAction] { diff --git a/Sources/NXLibrary/Views/Settings/SettingsKeysSection.swift b/Sources/NXLibrary/Views/Settings/SettingsKeysSection.swift new file mode 100644 index 00000000..6c0aa912 --- /dev/null +++ b/Sources/NXLibrary/Views/Settings/SettingsKeysSection.swift @@ -0,0 +1,72 @@ +import SwiftUI +import NXLibraryCore + +/// Porting → Keys: the private copy of prod.keys that new portings need. +struct SettingsKeysSection: View { + @ObservedObject var viewModel: AppViewModel + let onActions: ([SettingsRowAction]) -> Void + + @Environment(\.seleneFocusedRowID) private var focusedRowTitle + private var configurationLocked: Bool { viewModel.isBuilding || viewModel.isUpdatingApp } + + var body: some View { + VStack(spacing: 9) { + SelenePanel(L10n.text("prod.keys"), + info: L10n.text("Nintendo Switch cryptographic keys required to decrypt game packages (NSP/XCI). Arcane stores a private copy with mode 0600 permissions; key values are never displayed or logged.")) { + HStack(spacing: 8) { + Image(systemName: viewModel.isProdKeysValid ? "checkmark.circle.fill" : "xmark.octagon.fill") + .seleneFont(15, .bold) + .foregroundColor(viewModel.isProdKeysValid ? SeleneTheme.success : SeleneTheme.danger) + Text(viewModel.isProdKeysValid ? L10n.text("Keys imported") : L10n.text("No prod.keys imported")) + .seleneFont(15, .semibold) + .foregroundColor(SeleneTheme.ink) + Spacer() + Text(viewModel.isProdKeysValid && !viewModel.prodKeysPath.isEmpty + ? viewModel.prodKeysPath : L10n.text("Choose your file once")) + .seleneFont(13, .regular, design: .monospaced) + .foregroundColor(SeleneTheme.ink60) + .lineLimit(1) + .truncationMode(.middle) + } + + if let summary = viewModel.keySummary { + Text(L10n.format("header_key present · %@ application key generations", [String(describing: (summary.applicationKeyGenerations.count))])) + .seleneFont(13, .regular, design: .monospaced) + .foregroundColor(SeleneTheme.success) + } + + HStack(spacing: 14) { + Button(viewModel.isProdKeysValid ? L10n.text("Replace Key...") : L10n.text("Import Key...")) { + viewModel.selectProdKeysFile() + } + .buttonStyle(.plain) + .seleneFont(14, .semibold) + .foregroundColor(SeleneTheme.glyph) + .disabled(configurationLocked) + Button(L10n.text("Detect Ryujinx...")) { viewModel.selectRyujinxFolder() } + .buttonStyle(.plain) + .seleneFont(14, .semibold) + .foregroundColor(SeleneTheme.glyph) + .disabled(configurationLocked) + Spacer() + } + + Text(L10n.text("The original file is untouched. The stored copy is mode 0600 and key values are never shown or logged.")) + .seleneFont(13) + .foregroundColor(SeleneTheme.ink60) + .fixedSize(horizontal: false, vertical: true) + } + .seleneRowFocus(focusedRowTitle == "prod.keys", radius: SeleneTheme.cardRadius) + } + .onAppear(perform: publishActions) + .onChange(of: configurationLocked) { _ in publishActions() } + } + + private func publishActions() { + onActions([ + .init(id: "keys", title: "prod.keys", isEnabled: !configurationLocked) { + viewModel.selectProdKeysFile() + } + ]) + } +} diff --git a/Sources/NXLibrary/Views/Settings/SettingsLibraryGamesSection.swift b/Sources/NXLibrary/Views/Settings/SettingsLibraryGamesSection.swift new file mode 100644 index 00000000..8b61de6a --- /dev/null +++ b/Sources/NXLibrary/Views/Settings/SettingsLibraryGamesSection.swift @@ -0,0 +1,107 @@ +import SwiftUI +import NXLibraryCore + +/// Library → Games: how every game launches and closes, Surprise me and the hidden games. +struct SettingsLibraryGamesSection: View { + @ObservedObject var viewModel: AppViewModel + @ObservedObject var settings: AppSettingsStore + let onActions: ([SettingsRowAction]) -> Void + @Environment(\.seleneCanvas) private var canvas + + /// Games hidden from Game options, by name (the library keeps them sorted). + private var hiddenGames: [PortedGame] { + viewModel.libraryGames.filter(\.isHidden) + } + + private func unhide(_ game: PortedGame) { + SoundEffectService.shared.play(.click) + viewModel.toggleHidden(game) + } + + private var surprisePoolTitle: String { + switch settings.settings.surprisePool { + case .installed: return "Installed" + case .notPlayed: return "Not played yet" + case .all: return "All games" + } + } + + var body: some View { + VStack(spacing: canvas.u(8)) { + SettingsSubheading(L10n.text("All games")) + + SeleneCycleRow("Launch screen style", + subtitle: "Artwork layout", + value: settings.settings.launchStyle.title) { step in + settings.settings.launchStyle = settings.settings.launchStyle.stepped(step) + } + + SeleneToggleRow("Launch screen motion", + subtitle: "Artwork drift", + isOn: $settings.settings.launchMotion) + + SeleneCycleRow("Launch screen shade", + subtitle: "Launch brightness", + value: settings.settings.launchShade.title) { step in + settings.settings.launchShade = settings.settings.launchShade.stepped(step) + } + + SeleneToggleRow("Session card", + subtitle: "Your playtime when a game closes", + info: "When you close a game, a card shows how long you played this time and in total. Sessions under 10 seconds show none.", + isOn: $settings.settings.showsSessionCard) + + SeleneCycleRow("Surprise me pool", + subtitle: "Which games Surprise me picks from.", + value: surprisePoolTitle) { step in + settings.settings.surprisePool = settings.settings.surprisePool.stepped(step) + } + + SettingsSubheading(L10n.text("Hidden games")) + + if hiddenGames.isEmpty { + Text(L10n.text("No hidden games. Hide one from its Game options; it comes back here.")) + .seleneFont(15) + .foregroundColor(SeleneTheme.ink60) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.leading, canvas.u(26)) + } else { + ForEach(hiddenGames) { game in + SeleneButtonRow(game.name, id: "hidden-\(game.id)", + subtitle: "Out of Spotlight, Collection, Surprise me and search.", verbatimTitle: true, + buttonTitle: "Show") { unhide(game) } + } + } + + } + .onAppear(perform: publishActions) + .onChange(of: hiddenGames.map(\.id)) { _ in publishActions() } + } + + private func publishActions() { + let hidden = hiddenGames.map { game in + SettingsRowAction(id: "hidden-\(game.id)", title: game.name, rowID: "hidden-\(game.id)") { unhide(game) } + } + onActions(launchActions + hidden) + } + + private var launchActions: [SettingsRowAction] { + [ + .value("launchStyle", "Launch screen style") { step in + settings.settings.launchStyle = settings.settings.launchStyle.stepped(step) + }, + .init(id: "launchMotion", title: L10n.text("Launch screen motion"), rowID: "Launch screen motion") { + settings.settings.launchMotion.toggle() + }, + .value("launchShade", "Launch screen shade") { step in + settings.settings.launchShade = settings.settings.launchShade.stepped(step) + }, + .init(id: "showsSessionCard", title: L10n.text("Session card"), rowID: "Session card") { + settings.settings.showsSessionCard.toggle() + }, + .value("surprisePool", "Surprise me pool") { step in + settings.settings.surprisePool = settings.settings.surprisePool.stepped(step) + } + ] + } +} diff --git a/Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift b/Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift index c2a239e9..e9d4a9be 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift @@ -1,15 +1,12 @@ import SwiftUI +import AppKit import NXLibraryCore struct SettingsLibrarySection: View { @ObservedObject var viewModel: AppViewModel @ObservedObject var settings: AppSettingsStore - @ObservedObject var artwork: ArtworkStore let onActions: ([SettingsRowAction]) -> Void - @State private var metadataBytes: Int64 = 0 - @State private var artworkBytes: Int64 = 0 - var body: some View { VStack(spacing: 9) { SeleneRow(GameFoldersCopy.appsTitle, @@ -65,7 +62,7 @@ struct SettingsLibrarySection: View { ? "Scanning game apps…" : "Find existing nxnative builds and refresh the library.", info: "Checks Game apps and its subfolders. Existing library entries are kept; no apps are moved. Source files are optional for Play.", buttonTitle: "Scan") { - viewModel.refreshLibrary() + viewModel.importExistingBuilds() } .disabled(viewModel.isScanningLibrary) @@ -83,32 +80,20 @@ struct SettingsLibrarySection: View { .padding(.vertical, 8) } + SeleneToggleRow("Refresh library at launch", + subtitle: "Rescan the app library for new or removed builds.", + isOn: $settings.settings.refreshLibraryAtLaunch) + SeleneToggleRow("Notify when a porting ends", - subtitle: "A notification when a porting finishes while NX Library is in the background.", + subtitle: "A notification when a porting finishes while Arcane is in the background.", isOn: $settings.settings.notifyPortingEnds) - SeleneValueRow("Metadata cache", - subtitle: "Nintendo Store descriptions, genres and links.", - info: "Locally cached game metadata such as title IDs, publisher names, release dates, and category tags fetched during library scans.", - value: seleneBytes(metadataBytes), - actionTitle: "Clear") { - viewModel.clearMetadataCache() - metadataBytes = viewModel.metadataCacheSize() - } - - SeleneValueRow("Artwork cache", - subtitle: "Hero and cover art downloaded for this library.", - info: "High-resolution game box art and hero wallpapers cached locally from the Nintendo Store catalog.", - value: seleneBytes(artworkBytes), - actionTitle: "Clear") { - artwork.clear() - artworkBytes = artwork.cacheSize() + SeleneButtonRow("Box covers", + subtitle: "GameTDB covers", + buttonTitle: "Open GameTDB") { + NSWorkspace.shared.open(GameTDB.siteURL) } } - .task { - metadataBytes = viewModel.metadataCacheSize() - artworkBytes = artwork.cacheSize() - } .onAppear(perform: publishActions) .onChange(of: viewModel.isScanningLibrary) { _ in publishActions() } } @@ -122,18 +107,16 @@ struct SettingsLibrarySection: View { viewModel.selectGameFolder() }, .init(id: "refresh", title: "Scan game apps", isEnabled: !viewModel.isScanningLibrary) { - viewModel.refreshLibrary() + viewModel.importExistingBuilds() + }, + .init(id: "refreshAtLaunch", title: "Refresh library at launch") { + settings.settings.refreshLibraryAtLaunch.toggle() }, .init(id: "notify", title: "Notify when a porting ends") { settings.settings.notifyPortingEnds.toggle() }, - .init(id: "metadataClear", title: "Metadata cache") { - viewModel.clearMetadataCache() - metadataBytes = viewModel.metadataCacheSize() - }, - .init(id: "artworkClear", title: "Artwork cache") { - artwork.clear() - artworkBytes = artwork.cacheSize() + .init(id: "covers", title: "Box covers") { + NSWorkspace.shared.open(GameTDB.siteURL) } ]) } diff --git a/Sources/NXLibrary/Views/Settings/SettingsLookSection.swift b/Sources/NXLibrary/Views/Settings/SettingsLookSection.swift index da99dd01..5edbf0f8 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsLookSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsLookSection.swift @@ -114,29 +114,10 @@ struct SettingsLookSection: View { subtitle: "Dock & app", value: viewModel.iconAppearanceMode.label) { stepIcon($0) } - SettingsSubheading(L10n.text("Artwork")) - - SeleneButtonRow("Box covers", - subtitle: "GameTDB covers", - buttonTitle: "Open GameTDB") { - NSWorkspace.shared.open(GameTDB.siteURL) - } - - SeleneButtonRow("SteamGridDB", - subtitle: viewModel.hasSteamGridDBKey - ? "Key saved · covers, backgrounds, logos and icons in Change artwork" - : "Add your free API key to find art in Change artwork", - buttonTitle: viewModel.hasSteamGridDBKey ? "Remove key" : "Add key") { - steamGridDBAction() - } } .onAppear(perform: publishActions) } - private func steamGridDBAction() { - if viewModel.hasSteamGridDBKey { viewModel.removeSteamGridDBKey() } else { viewModel.isEditingSteamGridDBKey = true } - } - private func publishActions() { onActions([ .value("theme", "Color theme") { stepTheme($0) }, @@ -160,11 +141,7 @@ struct SettingsLookSection: View { .init(id: "motion", title: "Reduce motion") { settings.settings.reduceMotion.toggle() }, - .value("icon", "App icon") { stepIcon($0) }, - .init(id: "covers", title: "Box covers") { - NSWorkspace.shared.open(GameTDB.siteURL) - }, - .init(id: "SteamGridDB", title: "SteamGridDB") { steamGridDBAction() } + .value("icon", "App icon") { stepIcon($0) } ]) } } diff --git a/Sources/NXLibrary/Views/Settings/SettingsPortingStorageSection.swift b/Sources/NXLibrary/Views/Settings/SettingsPortingStorageSection.swift new file mode 100644 index 00000000..549b9a08 --- /dev/null +++ b/Sources/NXLibrary/Views/Settings/SettingsPortingStorageSection.swift @@ -0,0 +1,104 @@ +import SwiftUI +import NXLibraryCore + +/// Porting → Storage: the build caches of each game and of all games, largest first. +struct SettingsPortingStorageSection: View { + @ObservedObject var viewModel: AppViewModel + let onActions: ([SettingsRowAction]) -> Void + + var body: some View { + VStack(spacing: 9) { + Text(L10n.text("Largest build caches first. Sizes describe file contents; the space recovered can differ. Shared folders count once in totals.")) + .seleneFont(15).foregroundColor(SeleneTheme.ink60) + .frame(maxWidth: .infinity, alignment: .leading) + if let snapshot = viewModel.storageSnapshot { + if snapshot.games.isEmpty { + Text(L10n.text("Add a game to see its storage here.")).seleneFont(15).foregroundColor(SeleneTheme.ink60) + } + ForEach(snapshot.games) { game in + SeleneButtonRow(game.name, id: game.rowID, + subtitle: gameSummary(game), verbatimTitle: true, + buttonTitle: "Delete cache") { + confirmCacheCleanup(game) + } + .disabled(!viewModel.canCleanStorage || !game.canDeleteCache) + } + } + + + SettingsSubheading(L10n.text("All games")) + + SeleneButtonRow("Build caches", + subtitle: viewModel.isBuilding + ? "Available after the active build finishes or is cancelled." + : "Extracted build caches for every library game. Apps, sources and saves are untouched.", + info: "Intermediate files created during shader translation and staging in the app-owned workspace. Deleting them frees disk space; your built games and saves will not be touched.", + buttonTitle: "Delete all") { + confirmAllCachesCleanup() + } + .disabled(!viewModel.canCleanStorage || (viewModel.storageUsage?.cacheBytes ?? 0) == 0) + } + .task { viewModel.refreshStorageUsage() } + .onAppear(perform: publishActions) + .onChange(of: viewModel.isBuilding) { building in + publishActions() + if !building { viewModel.refreshStorageUsage() } + } + .onChange(of: viewModel.isCleaningStorage) { _ in publishActions() } + .onChange(of: viewModel.isUpdatingApp) { _ in publishActions() } + .onChange(of: viewModel.storageSnapshot) { _ in publishActions() } + .onChange(of: viewModel.storageUsage?.cacheBytes) { _ in publishActions() } + } + + private func sizeText(_ size: StorageSize, missing: String) -> String { + switch size { + case .bytes(let bytes): return seleneBytes(bytes) + case .missing: return missing + case .unavailable: return L10n.text("Unavailable") + } + } + + private func gameSummary(_ game: GameStorageUsage) -> String { + var text = L10n.format("App: %@ · Cache: %@ · Logs: %@", [String(describing: (sizeText(game.app, missing: L10n.text("Not found")))), String(describing: (sizeText(game.cache, missing: "None"))), String(describing: (sizeText(game.logs, missing: "None")))]) + if !game.sharedCacheWith.isEmpty { + text += L10n.format("\nCache shared with %@.", [String(describing: (game.sharedCacheWith.joined(separator: ", ")))]) + } + return text + } + + private func confirmCacheCleanup(_ usage: GameStorageUsage) { + guard viewModel.canCleanStorage, usage.canDeleteCache, + let game = viewModel.libraryGames.first(where: { $0.id == usage.id }) else { return } + var message = L10n.format("Delete %@ of build cache for %@? This permanently removes extracted and compiled build files. The next rebuild may take longer. The game app, original game files, saves and logs are kept.", [String(describing: (seleneBytes(usage.cache.knownBytes ?? 0))), String(describing: (game.name))]) + if !usage.sharedCacheWith.isEmpty { + message += L10n.format(" This cache is also used by %@; their next rebuilds may take longer too.", [String(describing: (usage.sharedCacheWith.joined(separator: ", ")))]) + } + viewModel.showSettingsNotice(title: L10n.text("Delete this game's cache?"), message: message, + actionTitle: L10n.text("Delete cache"), cancelTitle: L10n.text("Cancel")) { + viewModel.deleteCaches(for: game) + } + } + + private func confirmAllCachesCleanup() { + let amount = seleneBytes(viewModel.storageUsage?.cacheBytes ?? 0) + let message = L10n.format("Permanently remove %@ of build caches for all games? Future rebuilds may take longer. Your games, original game files, saves and logs will be kept. Unavailable folders will be left alone.", [String(describing: (amount))]) + viewModel.showSettingsNotice(title: L10n.text("Delete build caches?"), message: message, + actionTitle: L10n.text("Delete"), cancelTitle: L10n.text("Cancel")) { + viewModel.deleteCaches() + } + } + + private func publishActions() { + var actions: [SettingsRowAction] = (viewModel.storageSnapshot?.games ?? []).map { game in + SettingsRowAction(id: game.rowID, title: game.name, rowID: game.rowID, + isEnabled: viewModel.canCleanStorage && game.canDeleteCache) { + confirmCacheCleanup(game) + } + } + actions.append(.init(id: "deleteCaches", title: "Build caches", + isEnabled: viewModel.canCleanStorage && (viewModel.storageUsage?.cacheBytes ?? 0) > 0) { + confirmAllCachesCleanup() + }) + onActions(actions) + } +} diff --git a/Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift b/Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift index c65d73f3..af88c572 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift @@ -6,6 +6,9 @@ struct SettingsSearchSection: View { @ObservedObject var settings: AppSettingsStore let onOpenGroup: (SettingsSection) -> Void let onSubmit: () -> Void + /// Bumped when the player opens the field (A or Right from the sidebar). Selecting Search never + /// takes the keys by itself: Up/Down keep moving through the sidebar. + let fieldRequest: Int let onActions: ([SettingsRowAction]) -> Void @Environment(\.seleneCanvas) private var canvas @@ -43,10 +46,8 @@ struct SettingsSearchSection: View { } SettingsDescriptorList(rows: results, onOpenGroup: onOpenGroup) } - .onAppear { - fieldFocused = true - publishActions() - } + .onAppear(perform: publishActions) + .onChange(of: fieldRequest) { _ in fieldFocused = true } .onChange(of: query) { _ in publishActions() } } @@ -103,7 +104,7 @@ struct SettingsDescriptorList: View { let onOpenGroup: (SettingsSection) -> Void @Environment(\.seleneCanvas) private var canvas - static func title(_ row: SettingDescriptor) -> String { "\(row.group.title) · \(L10n.text(row.title))" } + static func title(_ row: SettingDescriptor) -> String { "\(row.group.place) · \(L10n.text(row.title))" } static func actions(_ rows: [SettingDescriptor], onOpenGroup: @escaping (SettingsSection) -> Void) -> [SettingsRowAction] { diff --git a/Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift b/Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift index 84ac9ed4..0dafc8d0 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift @@ -12,18 +12,19 @@ struct SettingsSectionContent: View { let onOpenConsole: () -> Void let onOpenGroup: (SettingsSection) -> Void let onSearchSubmit: () -> Void + let searchFieldRequest: Int let onActions: ([SettingsRowAction]) -> Void var body: some View { switch section { case .search: SettingsSearchSection(settings: settings, onOpenGroup: onOpenGroup, - onSubmit: onSearchSubmit, onActions: onActions) + onSubmit: onSearchSubmit, fieldRequest: searchFieldRequest, onActions: onActions) case .changed: SettingsChangedSection(settings: settings, viewModel: viewModel, onOpenGroup: onOpenGroup, onActions: onActions) case .startUp: - SettingsStartUpSection(viewModel: viewModel, settings: settings, onActions: onActions, onChooseLanguage: onChooseLanguage, onChooseRegion: onChooseRegion) + SettingsStartUpSection(settings: settings, onActions: onActions, onChooseLanguage: onChooseLanguage, onChooseRegion: onChooseRegion) case .navigation: SettingsNavigationSection(settings: settings, onActions: onActions) case .spotlight: @@ -32,19 +33,31 @@ struct SettingsSectionContent: View { SettingsSoundSection(settings: settings, onActions: onActions) case .look: SettingsLookSection(viewModel: viewModel, settings: settings, onActions: onActions) + case .apiServices: + SettingsAPISection(viewModel: viewModel, onActions: onActions) + case .libraryGames: + SettingsLibraryGamesSection(viewModel: viewModel, settings: settings, onActions: onActions) case .games: SettingsGamesSection(viewModel: viewModel, settings: settings, onActions: onActions) + case .cloudSaves: + SettingsCloudSavesSection(viewModel: viewModel, settings: settings, onActions: onActions) case .controllers: SettingsControllersSection(settings: settings, onActions: onActions, onViewControls: onViewControls) case .library: - SettingsLibrarySection(viewModel: viewModel, settings: settings, - artwork: artwork, onActions: onActions) + SettingsLibrarySection(viewModel: viewModel, settings: settings, onActions: onActions) + case .sources: + SettingsSourcesSection(viewModel: viewModel, settings: settings, onActions: onActions) case .storage: - SettingsStorageSection(viewModel: viewModel, artwork: artwork, - onActions: onActions, onOpenConsole: onOpenConsole) + SettingsStorageSection(viewModel: viewModel, artwork: artwork, onActions: onActions) + case .portingStorage: + SettingsPortingStorageSection(viewModel: viewModel, onActions: onActions) case .engine: - SettingsEngineSection(viewModel: viewModel, onActions: onActions) + SettingsEngineSection(viewModel: viewModel, settings: settings, onActions: onActions) + case .keys: + SettingsKeysSection(viewModel: viewModel, onActions: onActions) + case .console: + SettingsConsoleSection(onActions: onActions, onOpenConsole: onOpenConsole) case .about: SettingsAboutSection(viewModel: viewModel, onActions: onActions) } @@ -59,7 +72,7 @@ struct SettingsSubheading: View { init(_ title: String) { self.title = title } var body: some View { - Text(title) + Text(L10n.text(title)) .seleneFont(17, .semibold) .foregroundColor(SeleneTheme.glyph) .padding(.top, canvas.u(18)) diff --git a/Sources/NXLibrary/Views/Settings/SettingsSidebar.swift b/Sources/NXLibrary/Views/Settings/SettingsSidebar.swift index dafa7330..20bee102 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsSidebar.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsSidebar.swift @@ -2,7 +2,7 @@ import SwiftUI import AppKit import NXLibraryCore -/// Left column of Settings: app mark, name and version, then the groups (Selene `SettingsScreen.cs`). +/// Left column of Settings: app mark, name and version, then the sections under their group headings. struct SettingsSidebar: View { @Binding var selection: SettingsSection var isFocused: Bool = false @@ -17,26 +17,34 @@ struct SettingsSidebar: View { VStack(alignment: .leading, spacing: 0) { header .padding(.bottom, canvas.u(26)) - ScrollView { - groups + // The groups can be taller than the window: the selected section is always scrolled into view, + // at once like a macOS sidebar. An animated scroll started in the same frame as the new section's + // content and stuttered. + ScrollViewReader { proxy in + ScrollView { + groups + } + .scrollIndicators(.hidden) + .onAppear { proxy.scrollTo(selection) } + .onChange(of: selection) { section in proxy.scrollTo(section) } } - .scrollIndicators(.hidden) } } + /// App-wide groups, then one per platform (`SettingsSidebarGroup`); a heading is a label, not a stop. private var groups: some View { VStack(alignment: .leading, spacing: canvas.u(6)) { - ForEach(SettingsSection.allCases) { section in - groupRow(section) - if section == .changed { - Rectangle() - .fill(SeleneTheme.ink.opacity(0.16)) - .frame(height: max(1, canvas.u(1))) + ForEach(SettingsSidebarGroup.all) { group in + if let heading = group.title(in: context) { + Text(heading) + .seleneFont(15, .semibold) + .foregroundColor(SeleneTheme.ink60) .padding(.leading, canvas.u(20)) - .padding(.top, canvas.u(8)) - .padding(.trailing, canvas.u(44)) - .padding(.bottom, canvas.u(14)) + .padding(.top, canvas.u(18)) + .padding(.bottom, canvas.u(2)) + .accessibilityAddTraits(.isHeader) } + ForEach(group.sections) { section in groupRow(section).id(section) } } } } @@ -49,7 +57,7 @@ struct SettingsSidebar: View { .frame(width: canvas.u(48), height: canvas.u(48)) .accessibilityHidden(true) VStack(alignment: .leading, spacing: canvas.u(2)) { - Text(L10n.text("NX Library")) + Text(AppIdentity.name) .seleneFont(28, .semibold) .foregroundColor(SeleneTheme.ink) Text(version) diff --git a/Sources/NXLibrary/Views/Settings/SettingsSourcesSection.swift b/Sources/NXLibrary/Views/Settings/SettingsSourcesSection.swift new file mode 100644 index 00000000..86df24f0 --- /dev/null +++ b/Sources/NXLibrary/Views/Settings/SettingsSourcesSection.swift @@ -0,0 +1,112 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +@MainActor +struct SettingsSourcesSection: View { + @ObservedObject var viewModel: AppViewModel + @ObservedObject var settings: AppSettingsStore + @EnvironmentObject private var sources: CatalogSourcesModel + @Environment(\.nxAppLocale) private var localization + let onActions: ([SettingsRowAction]) -> Void + + private var defaultRoot: URL { CatalogSourcesModel.defaultSteamRoot } + private var hidden: [CatalogGame] { viewModel.catalogGames.filter { $0.integration == .steam && $0.isHidden } } + private var review: [CatalogGame] { + viewModel.catalogGames.filter { !$0.isHidden && $0.steamGame?.needsReview == true } + } + private var statusText: String { + switch sources.status { + case .disabled: return L10n.text("Enable Steam to find its installed Mac games.", context: localization) + case .idle: return L10n.text("Ready to check Steam.", context: localization) + case .scanning: return L10n.text("Checking Steam libraries…", context: localization) + case .ready: return L10n.count("%lld Steam installations found", sources.observedGameCount, context: localization) + case .partial: return L10n.text("Some installations could not be checked. Your library has been kept.", context: localization) + case .cancelled: return L10n.text("Scan stopped. Refresh when you are ready.", context: localization) + case .failed: return L10n.text("Steam could not be refreshed. Your library has been kept.", context: localization) + } + } + var body: some View { + VStack(spacing: 9) { + SeleneToggleRow("Steam", subtitle: "Find installed native Mac games in your Steam libraries.", + info: "Your Steam files stay where they are. Disabling this source keeps its games and personal choices.", + isOn: Binding(get: { sources.configuration.isEnabled }, set: { enabled in + sources.configure(enabled: enabled, root: sources.configuration.rootURL ?? defaultRoot) + })) + SeleneButtonRow("Refresh Steam", subtitle: statusText, + buttonTitle: sources.status == .scanning ? "Cancel" : "Refresh") { + if sources.status == .scanning { sources.cancel() } else { sources.refresh() } + }.disabled(!sources.configuration.isEnabled) + SeleneValueRow("Steam folder", subtitle: "Choose the Steam folder containing steamapps.", + value: (sources.configuration.rootURL ?? defaultRoot).path, actionTitle: "Change", action: chooseFolder) + SettingsSubheading("Play") + SeleneToggleRow("Keep Steam in the background", + subtitle: "Steam starts quietly when possible and comes forward if it needs you.", + info: "When Play opens Steam, it starts quietly. The waiting screen stays visible while the game starts. Steam comes forward if it needs input or the game takes too long.", + isOn: $settings.settings.steamInBackground) + if let error = sources.errorMessage { + Text(error).seleneFont(14).foregroundColor(SeleneTheme.danger) + .fixedSize(horizontal: false, vertical: true).frame(maxWidth: .infinity, alignment: .leading).padding(24) + } + if sources.reviewCount > 0 { + Text(L10n.count("%lld Steam games need review", sources.reviewCount, context: localization)) + .seleneFont(15).foregroundColor(SeleneTheme.ink60).padding(.vertical, 10) + } + if !review.isEmpty { + SettingsSubheading("Review installations") + Text(L10n.text("Check these installations in Steam, then refresh this source. Only recognized native Mac games appear in the library.", context: localization)) + .seleneFont(14).foregroundColor(SeleneTheme.ink60).fixedSize(horizontal: false, vertical: true) + ForEach(review) { game in + SeleneRow(game.name, id: "review-\(game.id)", subtitle: "Needs review", verbatimTitle: true) { + Button(L10n.text("Reveal", context: localization)) { reveal(game) }.buttonStyle(.plain).foregroundColor(SeleneTheme.glyph) + } + } + } + if !hidden.isEmpty { + SettingsSubheading("Hidden Steam games") + ForEach(hidden) { game in + SeleneRow(game.name, id: "hidden-\(game.id)", subtitle: "Hidden from the library", verbatimTitle: true) { + Button(L10n.text("Show", context: localization)) { viewModel.setCatalogHidden(false, game: game) } + .buttonStyle(.plain).foregroundColor(SeleneTheme.glyph) + } + } + } + } + .onAppear(perform: publishActions) + .onChange(of: sources.status) { _ in publishActions() } + .onChange(of: sources.configuration) { _ in publishActions() } + .onChange(of: viewModel.catalogGames) { _ in publishActions() } + } + private func chooseFolder() { + let panel = NSOpenPanel() + panel.canChooseFiles = false; panel.canChooseDirectories = true; panel.allowsMultipleSelection = false + panel.directoryURL = sources.configuration.rootURL ?? defaultRoot + panel.message = L10n.text("Choose the Steam folder containing steamapps.", context: localization) + guard panel.runModal() == .OK, let chosen = panel.url else { return } + let root = chosen.resolvingSymlinksInPath().standardizedFileURL + let apps = root.appendingPathComponent("steamapps").resolvingSymlinksInPath().standardizedFileURL + var directory: ObjCBool = false + guard apps.path.hasPrefix(root.path + "/"), FileManager.default.fileExists(atPath: apps.path, isDirectory: &directory), directory.boolValue else { + viewModel.showSettingsNotice(title: L10n.text("Steam folder", context: localization), message: L10n.text("Choose the Steam folder containing steamapps.", context: localization)) + return + } + sources.configure(enabled: sources.configuration.isEnabled, root: root) + } + private func reveal(_ game: CatalogGame) { + guard let location = game.steamGame?.installations.first?.contentURL else { return } + NSWorkspace.shared.activateFileViewerSelecting([location]) + } + private func publishActions() { + var rows: [SettingsRowAction] = [ + .init(id: "steamSource", title: "Steam") { sources.configure(enabled: !sources.configuration.isEnabled, root: sources.configuration.rootURL ?? defaultRoot) }, + .init(id: "steamRefresh", title: "Refresh Steam", isEnabled: sources.configuration.isEnabled) { + if sources.status == .scanning { sources.cancel() } else { sources.refresh() } + }, + .init(id: "steamFolder", title: "Steam folder", activate: chooseFolder), + .init(id: "steamInBackground", title: "Keep Steam in the background") { settings.settings.steamInBackground.toggle() } + ] + rows += review.map { game in .init(id: "review-\(game.id)", title: game.name, rowID: "review-\(game.id)") { reveal(game) } } + rows += hidden.map { game in .init(id: "hidden-\(game.id)", title: game.name, rowID: "hidden-\(game.id)") { viewModel.setCatalogHidden(false, game: game) } } + onActions(rows) + } +} diff --git a/Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift b/Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift index 31a57588..0d6ca7f9 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift @@ -2,7 +2,6 @@ import SwiftUI import NXLibraryCore struct SettingsStartUpSection: View { - @ObservedObject var viewModel: AppViewModel @ObservedObject var settings: AppSettingsStore let onActions: ([SettingsRowAction]) -> Void let onChooseLanguage: () -> Void @@ -17,13 +16,6 @@ struct SettingsStartUpSection: View { } } - private var readiness: Bool { - viewModel.isProdKeysValid - && viewModel.isNxnativeValid - && viewModel.environmentStatus?.canBuild == true - && viewModel.canPassToolchainGate - } - var body: some View { VStack(spacing: canvas.u(8)) { SettingsSubheading(L10n.text("Language & region")) @@ -37,7 +29,7 @@ struct SettingsStartUpSection: View { } ?? L10n.text("Automatic (Mac)"), action: onChooseRegion) SeleneCycleRow("Start on", - subtitle: "The screen NX Library opens on.", + subtitle: "The screen Arcane opens on.", value: startOnTitle) { step in settings.settings.startOn = settings.settings.startOn.stepped(step) } @@ -50,75 +42,19 @@ struct SettingsStartUpSection: View { subtitle: "Applies at the next launch.", isOn: $settings.settings.startInFullscreen) - SeleneToggleRow("Check engine at launch", - subtitle: "Verify the pinned engine commit and toolchain when the app starts.", - info: "Checks the nxnative checkout against the certified engine commit and confirms your installed Metal compiler matches the lock file before builds are attempted.", - isOn: $settings.settings.checkEngineAtLaunch) - - SeleneToggleRow("Refresh library at launch", - subtitle: "Rescan the app library for new or removed builds.", - isOn: $settings.settings.refreshLibraryAtLaunch) - SeleneToggleRow("Check for app updates", - subtitle: "Look for a newer NX Library release at launch, at most once a day.", + subtitle: "Look for a newer Arcane release at launch, at most once a day.", isOn: $settings.settings.checkAppUpdatesAtLaunch) - SeleneToggleRow("Intro animation", - subtitle: "Plays a short opening with the boot sound when the app opens.", + SeleneToggleRow("Entrance animation", + subtitle: "The library's tiles fly in with the boot sound when the app opens.", isOn: $settings.settings.introAnimation) - - SettingsSubheading(L10n.text("Setup")) - - SeleneButtonRow("Setup", - subtitle: "Open the Setup check: what NX Library needs and what is ready.", - buttonTitle: "Open Setup") { - viewModel.reopenSetup() - } - .disabled(viewModel.isBuilding || viewModel.isUpdatingApp) - - SeleneButtonRow("Environment", - subtitle: "Re-run the environment and compatibility checks.", - buttonTitle: "Re-check") { - viewModel.detectEnvironment() - } - .disabled(viewModel.isBuilding || viewModel.isUpdatingApp) - - SelenePanel(L10n.text("Readiness"), - info: L10n.text("Summarizes the 4 essential gates: valid prod.keys, cloned nxnative repository, Python build environment, and certified Metal compiler version.")) { - HStack(spacing: 9) { - Circle() - .fill(readiness ? SeleneTheme.success : SeleneTheme.untested) - .frame(width: 8, height: 8) - Text(viewModel.isCheckingEnvironment ? L10n.text("Checking…") - : viewModel.environmentStatus == nil && viewModel.setupCompleted ? L10n.text("Not checked") - : readiness ? L10n.text("Ready to build and play") : L10n.text("Setup needed or builds blocked")) - .seleneFont(16, .semibold) - .foregroundColor(SeleneTheme.ink) - Spacer() - } - - Text(readinessLine) - .seleneFont(13, .regular, design: .monospaced) - .foregroundColor(SeleneTheme.ink60) - .fixedSize(horizontal: false, vertical: true) - } } .onAppear(perform: publishActions) - .onChange(of: viewModel.isBuilding) { _ in publishActions() } - .onChange(of: viewModel.isUpdatingApp) { _ in publishActions() } .onChange(of: settings.settings.appLanguage) { _ in publishActions() } .onChange(of: settings.settings.appRegion) { _ in publishActions() } } - private var readinessLine: String { - let engine = seleneShort(viewModel.pinnedEngineCommit) - let metal = viewModel.installedMetalVersion ?? L10n.text("Metal unknown") - let xcode = viewModel.environmentStatus?.xcodeVersion ?? L10n.text("Xcode unknown") - let python = viewModel.environmentStatus?.pythonURL == nil ? L10n.text("Python missing") - : viewModel.engineToolchain.isBundled ? L10n.text("Python included") : L10n.text("Python venv ready") - return L10n.format("Engine %@ · %@ · %@ · %@", [String(describing: (engine)), String(describing: (metal)), String(describing: (xcode)), String(describing: (python))]) - } - private func publishActions() { onActions([ .init(id: "appLanguage", title: "App language", activate: onChooseLanguage), @@ -132,23 +68,11 @@ struct SettingsStartUpSection: View { .init(id: "startupFullscreen", title: "Start in fullscreen") { settings.settings.startInFullscreen.toggle() }, - .init(id: "engine", title: "Check engine at launch") { - settings.settings.checkEngineAtLaunch.toggle() - }, - .init(id: "refresh", title: "Refresh library at launch") { - settings.settings.refreshLibraryAtLaunch.toggle() - }, .init(id: "appUpdates", title: "Check for app updates") { settings.settings.checkAppUpdatesAtLaunch.toggle() }, - .init(id: "intro", title: "Intro animation") { + .init(id: "intro", title: "Entrance animation") { settings.settings.introAnimation.toggle() - }, - .init(id: "setup", title: "Setup", isEnabled: !viewModel.isBuilding && !viewModel.isUpdatingApp) { - viewModel.reopenSetup() - }, - .init(id: "recheck", title: "Environment", isEnabled: !viewModel.isBuilding && !viewModel.isUpdatingApp) { - viewModel.detectEnvironment() } ]) } diff --git a/Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift b/Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift index a62e1c58..ab56fd0a 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift @@ -5,16 +5,10 @@ struct SettingsStorageSection: View { @ObservedObject var viewModel: AppViewModel @ObservedObject var artwork: ArtworkStore let onActions: ([SettingsRowAction]) -> Void - let onOpenConsole: () -> Void @State private var metadataBytes: Int64 = 0 @State private var artworkBytes: Int64 = 0 - private enum CleanupKind: String, Identifiable { - case caches, logs - var id: String { rawValue } - } - var body: some View { VStack(spacing: 9) { SelenePanel(L10n.text("Storage")) { @@ -60,40 +54,10 @@ struct SettingsStorageSection: View { .accessibilityLabel(message) } - SettingsSubheading(L10n.text("By game")) - Text(L10n.text("Largest build caches first. Sizes describe file contents; the space recovered can differ. Shared folders count once in totals.")) - .seleneFont(15).foregroundColor(SeleneTheme.ink60) - .frame(maxWidth: .infinity, alignment: .leading) - if let snapshot = viewModel.storageSnapshot { - if snapshot.games.isEmpty { - Text(L10n.text("Add a game to see its storage here.")).seleneFont(15).foregroundColor(SeleneTheme.ink60) - } - ForEach(snapshot.games) { game in - SeleneButtonRow(game.name, id: game.rowID, - subtitle: gameSummary(game), verbatimTitle: true, - buttonTitle: "Delete cache") { - confirmCacheCleanup(game) - } - .disabled(!viewModel.canCleanStorage || !game.canDeleteCache) - } - } - - SettingsSubheading(L10n.text("All games")) - - SeleneButtonRow("Build caches", - subtitle: viewModel.isBuilding - ? "Available after the active build finishes or is cancelled." - : "Extracted build caches for every library game. Apps, sources and saves are untouched.", - info: "Intermediate files created during shader translation and staging in the app-owned workspace. Deleting them frees disk space; your built games and saves will not be touched.", - buttonTitle: "Delete all") { - confirmCleanup(.caches) - } - .disabled(!viewModel.canCleanStorage || (viewModel.storageUsage?.cacheBytes ?? 0) == 0) - SeleneButtonRow("Logs", subtitle: "Build and launch logs. Apps, sources and saves are untouched.", buttonTitle: "Delete") { - confirmCleanup(.logs) + confirmLogsCleanup() } .disabled(!viewModel.canCleanStorage) @@ -120,11 +84,6 @@ struct SettingsStorageSection: View { viewModel.showAllSaveBackups() } - SeleneButtonRow("Console", - subtitle: "Filter, search and copy build and launch logs.", - buttonTitle: "Open") { - onOpenConsole() - } } .task { viewModel.refreshStorageUsage() @@ -144,48 +103,12 @@ struct SettingsStorageSection: View { .onChange(of: viewModel.libraryFolder) { _ in viewModel.refreshStorageUsage() } } - private func sizeText(_ size: StorageSize, missing: String) -> String { - switch size { - case .bytes(let bytes): return seleneBytes(bytes) - case .missing: return missing - case .unavailable: return L10n.text("Unavailable") - } - } - - private func gameSummary(_ game: GameStorageUsage) -> String { - var text = L10n.format("App: %@ · Cache: %@ · Logs: %@", [String(describing: (sizeText(game.app, missing: L10n.text("Not found")))), String(describing: (sizeText(game.cache, missing: "None"))), String(describing: (sizeText(game.logs, missing: "None")))]) - if !game.sharedCacheWith.isEmpty { - text += L10n.format("\nCache shared with %@.", [String(describing: (game.sharedCacheWith.joined(separator: ", ")))]) - } - return text - } - - private func confirmCacheCleanup(_ usage: GameStorageUsage) { - guard viewModel.canCleanStorage, usage.canDeleteCache, - let game = viewModel.libraryGames.first(where: { $0.id == usage.id }) else { return } - var message = L10n.format("Delete %@ of build cache for %@? This permanently removes extracted and compiled build files. The next rebuild may take longer. The game app, original game files, saves and logs are kept.", [String(describing: (seleneBytes(usage.cache.knownBytes ?? 0))), String(describing: (game.name))]) - if !usage.sharedCacheWith.isEmpty { - message += L10n.format(" This cache is also used by %@; their next rebuilds may take longer too.", [String(describing: (usage.sharedCacheWith.joined(separator: ", ")))]) - } - viewModel.showSettingsNotice(title: L10n.text("Delete this game's cache?"), message: message, - actionTitle: L10n.text("Delete cache"), cancelTitle: L10n.text("Cancel")) { - viewModel.deleteCaches(for: game) - } - } - - private func confirmCleanup(_ kind: CleanupKind) { - let amount = kind == .logs - ? seleneBytes(viewModel.storageUsage?.logsBytes ?? 0) - : seleneBytes(viewModel.storageUsage?.cacheBytes ?? 0) - let message = kind == .logs - ? L10n.format("Remove %@ of logs for all games? Your games, sources and saves will be kept.", [String(describing: (amount))]) - : L10n.format("Permanently remove %@ of build caches for all games? Future rebuilds may take longer. Your games, original game files, saves and logs will be kept. Unavailable folders will be left alone.", [String(describing: (amount))]) - viewModel.showSettingsNotice(title: kind == .logs ? L10n.text("Delete logs?") : L10n.text("Delete build caches?"), + private func confirmLogsCleanup() { + let amount = seleneBytes(viewModel.storageUsage?.logsBytes ?? 0) + let message = L10n.format("Remove %@ of logs for all games? Your games, sources and saves will be kept.", [String(describing: (amount))]) + viewModel.showSettingsNotice(title: L10n.text("Delete logs?"), message: message, actionTitle: L10n.text("Delete"), cancelTitle: L10n.text("Cancel")) { - switch kind { - case .caches: viewModel.deleteCaches() - case .logs: viewModel.deleteLogs() - } + viewModel.deleteLogs() } } @@ -211,18 +134,9 @@ struct SettingsStorageSection: View { viewModel.refreshStorageUsage() } ] - actions += (viewModel.storageSnapshot?.games ?? []).map { game in - SettingsRowAction(id: game.rowID, title: game.name, rowID: game.rowID, - isEnabled: viewModel.canCleanStorage && game.canDeleteCache) { - confirmCacheCleanup(game) - } - } actions += [ - .init(id: "deleteCaches", title: "Build caches", isEnabled: viewModel.canCleanStorage && (viewModel.storageUsage?.cacheBytes ?? 0) > 0) { - confirmCleanup(.caches) - }, .init(id: "deleteLogs", title: "Logs", isEnabled: viewModel.canCleanStorage) { - confirmCleanup(.logs) + confirmLogsCleanup() }, .init(id: "metadataClear", title: "Metadata cache") { viewModel.clearMetadataCache() @@ -234,9 +148,6 @@ struct SettingsStorageSection: View { }, .init(id: "backups", title: "Save backups") { viewModel.showAllSaveBackups() - }, - .init(id: "console", title: "Console") { - onOpenConsole() } ] onActions(actions) diff --git a/Sources/NXLibrary/Views/Settings/SettingsView.swift b/Sources/NXLibrary/Views/Settings/SettingsView.swift index 02b481d0..39116b0f 100644 --- a/Sources/NXLibrary/Views/Settings/SettingsView.swift +++ b/Sources/NXLibrary/Views/Settings/SettingsView.swift @@ -1,6 +1,7 @@ import SwiftUI import AppKit import NXLibraryCore +import os enum SettingsFocusArea { case sidebar, rows } @@ -12,6 +13,8 @@ public struct SettingsView: View { @ObservedObject var router: AppRouter @ObservedObject var artwork: ArtworkStore + /// Opens the Search field when the player asks for it (`enterSection`). + @State private var searchFieldRequest = 0 @State private var section: SettingsSection @State private var showingControls = false @State private var localePicker: LocalePickerMode? @@ -36,6 +39,7 @@ public struct SettingsView: View { } /// A palette change redraws the whole screen; selection and focus live here and survive it. @ObservedObject private var theme = ThemeStore.shared + @ObservedObject private var igdb = IGDBSettings.shared @Environment(\.nxAppLocale) private var localization public init(initialSection: SettingsSection, @@ -78,7 +82,14 @@ public struct SettingsView: View { } .background(SeleneBackdrop().environment(\.seleneBackdropStyle, settingsBackdropStyle)) .onAppear(perform: installKeyMonitor) + .onAppear { + if AppData.profile.isDevelopment { + Logger(subsystem: "local.nxlibrary.development", category: "backdrop-transition") + .notice("Settings appeared, window settling: \(viewModel.isWindowSettling, privacy: .public)") + } + } .onDisappear(perform: removeKeyMonitor) + .onDisappear { igdb.isEditing = false } .onChange(of: section) { _ in rowActions = [] rowFocus = FocusIndex() @@ -99,11 +110,18 @@ public struct SettingsView: View { } } } + .overlay { + if igdb.isEditing { + IGDBCredentialsDialog(model: igdb) { igdb.isEditing = false } + } + } + .opacity(showingControls ? 0.001 : 1) + .allowsHitTesting(!showingControls) .overlay { if showingControls { ControlsView(canHandleInput: { !router.isMenuPresented && !viewModel.showSetupCheck - && !viewModel.isUpdateOfferOpen && !NativeMenuCommands.shared.isTracking + && !viewModel.isUpdateOfferOpen && !viewModel.isWelcomeOpen && !NativeMenuCommands.shared.isTracking && viewModel.settingsNotice == nil && viewModel.gameWithInstallFailure == nil }) { showingControls = false } } @@ -112,7 +130,7 @@ public struct SettingsView: View { if let mode = localePicker { LocalePicker(mode: mode, settings: settings, canHandleInput: { !router.isMenuPresented && !NativeMenuCommands.shared.isTracking - && !viewModel.showSetupCheck && !viewModel.isUpdateOfferOpen + && !viewModel.showSetupCheck && !viewModel.isUpdateOfferOpen && !viewModel.isWelcomeOpen && viewModel.settingsNotice == nil && NSApp.modalWindow == nil }) { localePicker = nil } } @@ -124,7 +142,7 @@ public struct SettingsView: View { ScrollViewReader { proxy in ScrollView { VStack(alignment: .leading, spacing: canvas.u(8)) { - Text(section.title) + Text(section.place) .seleneFont(15, .semibold) .foregroundColor(SeleneTheme.ink.opacity(0.55)) .padding(.bottom, canvas.u(6)) @@ -139,6 +157,7 @@ public struct SettingsView: View { onOpenConsole: { router.openConsole() }, onOpenGroup: openGroup, onSearchSubmit: enterRows, + searchFieldRequest: searchFieldRequest, onActions: updateActions ) } @@ -170,7 +189,7 @@ public struct SettingsView: View { hints.append(HintItem(.x, L10n.text("Reset group")) { resetSection() }) } if focusArea == .sidebar { - hints.append(HintItem(.a, L10n.text("Open")) { enterRows() }) + hints.append(HintItem(.a, L10n.text("Open")) { enterSection() }) } else if focusedRow?.cycle != nil { hints.append(HintItem(.a, L10n.text("Change"))) } else { @@ -201,6 +220,17 @@ public struct SettingsView: View { SoundEffectService.shared.play(.click) } + /// A or Right on the sidebar. Search opens its field; every other section enters its rows. + private func enterSection() { + guard focusArea == .sidebar else { return } + if section == .search { + searchFieldRequest += 1 + SoundEffectService.shared.play(.focus) + } else { + enterRows() + } + } + private func enterRows() { guard focusArea == .sidebar, !rowActions.isEmpty else { return } focusArea = .rows @@ -213,83 +243,28 @@ public struct SettingsView: View { SoundEffectService.shared.play(.focus) } - private var canResetSection: Bool { - switch section { - case .startUp, .navigation, .spotlight, .soundMusic, .look, .games, .controllers, .library: - return true - case .search, .changed, .engine, .storage, .about: - return false - } - } + private var canResetSection: Bool { SettingsReset.canReset(section) } + /// `SettingsReset` puts the section's `AppSettings` back in one assignment; the preferences + /// kept outside it are reset here. private func resetSection() { guard canResetSection else { return } let defaults = AppSettings() - var next = settings.settings switch section { - case .startUp: - next.appLanguage = defaults.appLanguage - next.appRegion = defaults.appRegion - next.startOn = defaults.startOn - next.restoreLastGame = defaults.restoreLastGame - next.startInFullscreen = defaults.startInFullscreen - next.checkEngineAtLaunch = defaults.checkEngineAtLaunch - next.refreshLibraryAtLaunch = defaults.refreshLibraryAtLaunch - next.checkAppUpdatesAtLaunch = defaults.checkAppUpdatesAtLaunch - next.introAnimation = defaults.introAnimation - case .navigation: - next.showButtonHints = defaults.showButtonHints - next.buttonNames = defaults.buttonNames - next.viewButtonSwitches = defaults.viewButtonSwitches - case .spotlight: - next.visibleSpotlightCards = defaults.visibleSpotlightCards - next.startingTab = defaults.startingTab - next.spotlightOrder = defaults.spotlightOrder - case .soundMusic: - next.interfaceSounds = defaults.interfaceSounds - next.soundVolume = defaults.soundVolume - next.quietLaunch = defaults.quietLaunch case .look: - next.colorThemeID = defaults.colorThemeID ThemeStore.shared.apply(id: defaults.colorThemeID) - next.wallpaperID = defaults.wallpaperID - next.settingsWallpaperID = defaults.settingsWallpaperID - next.keepWallpaperOnGames = defaults.keepWallpaperOnGames - next.backgroundSizing = defaults.backgroundSizing - next.wallpaperBrightness = defaults.wallpaperBrightness - next.backgroundShade = defaults.backgroundShade - next.readableText = defaults.readableText - next.animatedBackground = defaults.animatedBackground - next.showClock = defaults.showClock - next.reduceMotion = defaults.reduceMotion viewModel.iconAppearanceMode = .auto - case .games: - resetNotice = L10n.text("Cloud sync kept") - next.launchStyle = defaults.launchStyle - next.launchMotion = defaults.launchMotion - next.launchShade = defaults.launchShade - next.showsSessionCard = defaults.showsSessionCard - next.surprisePool = defaults.surprisePool - let rumble = next.gameDefaults.rumble - let gain = next.gameDefaults.rumbleGain - next.gameDefaults = defaults.gameDefaults - // Rumble lives under Controllers. - next.gameDefaults.rumble = rumble - next.gameDefaults.rumbleGain = gain case .controllers: GameControllerService.shared.deadzone = 0.35 - next.gameDefaults.rumble = defaults.gameDefaults.rumble - next.gameDefaults.rumbleGain = defaults.gameDefaults.rumbleGain case .library: resetNotice = L10n.text("Sources folder kept") - next.notifyPortingEnds = defaults.notifyPortingEnds viewModel.libraryFolder = URL(fileURLWithPath: viewModel.defaultInstallPath) .appendingPathComponent("Applications") viewModel.loadLibrary() - case .search, .changed, .engine, .storage, .about: + default: break } - settings.settings = next + settings.settings = SettingsReset.reset(section, in: settings.settings) SoundEffectService.shared.play(.focus) } @@ -307,7 +282,7 @@ public struct SettingsView: View { private func moveSideways(_ delta: Int) { switch focusArea { case .sidebar: - if delta > 0 { enterRows() } + if delta > 0 { enterSection() } case .rows: if let cycle = focusedRow?.cycle, focusedRow?.isEnabled == true { cycle(delta) @@ -333,10 +308,11 @@ public struct SettingsView: View { keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in guard case .settings = router.route, !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, !NativeMenuCommands.shared.isTracking, !router.isMenuPresented, !viewModel.showSetupCheck, - !showingControls, localePicker == nil, !viewModel.isEditingSteamGridDBKey, + !showingControls, localePicker == nil, !viewModel.isEditingSteamGridDBKey, !igdb.isEditing, viewModel.alertMessage == nil, viewModel.settingsNotice == nil, viewModel.gameWithInstallFailure == nil, let window = event.window, @@ -370,7 +346,6 @@ public struct SettingsView: View { if typing { return event } action = .confirm case 53: - if typing { window.makeFirstResponder(nil) } action = .cancel case 7: // X if typing { return event } @@ -390,7 +365,7 @@ public struct SettingsView: View { private func handleGamepad(_ action: GamepadAction) { // The key dialog takes the controller while it is open. - if viewModel.isEditingSteamGridDBKey { return } + if viewModel.isEditingSteamGridDBKey || igdb.isEditing { return } if localePicker != nil { NotificationCenter.default.post(name: .nxLocalePickerGamepadAction, object: action) return @@ -406,7 +381,7 @@ public struct SettingsView: View { case .navigateRight: moveSideways(1) case .confirm: if focusArea == .sidebar { - enterRows() + enterSection() } else if let row = focusedRow, row.isEnabled { SoundEffectService.shared.play(.click) row.press(button: rowButton) @@ -422,8 +397,12 @@ public struct SettingsView: View { } } + /// B or Esc: steps back one level. Typing in Search, it closes the field and stays on Search. private func handleBack() { - if focusArea == .rows { + if let window = NSApp.keyWindow, window.firstResponder is NSText { + window.makeFirstResponder(nil) + SoundEffectService.shared.play(.focus) + } else if focusArea == .rows { leaveRows() } else { router.back() diff --git a/Sources/NXLibrary/Views/Setup/ArcaneWelcomeView+Input.swift b/Sources/NXLibrary/Views/Setup/ArcaneWelcomeView+Input.swift new file mode 100644 index 00000000..dd997df2 --- /dev/null +++ b/Sources/NXLibrary/Views/Setup/ArcaneWelcomeView+Input.swift @@ -0,0 +1,47 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +extension ArcaneWelcomeView { + /// Controller actions and the mapped keys while the welcome is up: arrows between Add, Not now and + /// Open library, A on the one in focus, B or Esc closes. + func handle(_ action: GamepadAction) { + guard NSApp.modalWindow == nil else { return } + switch action { + case .navigateLeft: move(to: focus.moved(.left, offer: offer)) + case .navigateRight: move(to: focus.moved(.right, offer: offer)) + case .navigateUp: move(to: focus.moved(.up, offer: offer)) + case .navigateDown: move(to: focus.moved(.down, offer: offer)) + case .confirm: activate(focus) + case .cancel: + SoundEffectService.shared.play(.back) + onExit(.back) + default: break + } + } + + func move(to next: ArcaneWelcome.Focus) { + guard focus != next else { return } + focus = next + moved = true + SoundEffectService.shared.play(.focus) + } + + func activate(_ target: ArcaneWelcome.Focus) { + guard NSApp.modalWindow == nil else { return } + switch target { + case .add where offer != nil: + SoundEffectService.shared.play(.click) + onAddSteam() + offerAnswered = true + case .notNow where offer != nil: + SoundEffectService.shared.play(.click) + offerAnswered = true + case .openLibrary: + SoundEffectService.shared.play(.click) + onExit(.openLibrary) + default: + SoundEffectService.shared.play(.error) + } + } +} diff --git a/Sources/NXLibrary/Views/Setup/ArcaneWelcomeView.swift b/Sources/NXLibrary/Views/Setup/ArcaneWelcomeView.swift new file mode 100644 index 00000000..9b356d98 --- /dev/null +++ b/Sources/NXLibrary/Views/Setup/ArcaneWelcomeView.swift @@ -0,0 +1,124 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// "Welcome to Arcane", once, for players who update from NX Library: the new name, what's new, Steam +/// when it is found and still off (Add / Not now) and Open library. Every exit marks it shown. +struct ArcaneWelcomeView: View { + @Environment(\.seleneCanvas) var canvas + @Environment(\.seleneReduceMotion) var reduceMotion + /// Whether the Steam source is already on; then nothing is read and nothing is offered. + let steamEnabled: Bool + let steamRoot: URL + let appsFolder: URL + let onAddSteam: () -> Void + let onExit: (ArcaneWelcome.Exit) -> Void + + @StateObject var reader = FirstRunFindingsReader() + @State var focus: ArcaneWelcome.Focus = .openLibrary + @State var moved = false + /// Add or Not now was chosen: the offer row leaves. + @State var offerAnswered = false + + var offer: ArcaneWelcome.Offer? { + guard !offerAnswered else { return nil } + return ArcaneWelcome.offer(steamEnabled: steamEnabled, steamGameCount: reader.findings?.steamGameCount) + } + + private static let news: [(MaterialIcon, String)] = [ + (.gamepad, "Steam games for Mac in the same library"), + (.trophy, "Achievements, with rarity and crystal trophies"), + (.star, "Critic scores and metadata from more sources"), + (.settings, "Settings regrouped: General, Library, Porting, System") + ] + + var body: some View { + ZStack { + SeleneBackdrop() + VStack(spacing: 0) { + Text(L10n.text("Welcome to Arcane")).seleneFont(46, .semibold).foregroundColor(SeleneTheme.ink) + .multilineTextAlignment(.center) + Text(L10n.format("%@ has a new name: your games and settings are right where you left them.", + [AppIdentity.formerName])) + .seleneFont(19).foregroundColor(SeleneTheme.ink75) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, canvas.u(10)) + + newsCard.padding(.top, canvas.u(30)) + if let offer { offerRow(offer).padding(.top, canvas.u(12)).transition(.opacity) } + + SelenePillButton(title: L10n.text("Open library"), minWidth: 220, + focused: focus == .openLibrary) { activate(.openLibrary) } + .onHover { if $0 { move(to: .openLibrary) } } + .padding(.top, canvas.u(30)) + } + .frame(width: canvas.u(900)) + .offset(y: canvas.u(-20)) + .animation(reduceMotion ? nil : SeleneTheme.standard, value: offer) + + VStack { + Spacer(minLength: 0) + SeleneHintsBar(right: [HintItem(.a, L10n.text("Select")), HintItem(.b, L10n.text("Close"))], + bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) + } + } + .frame(width: canvas.size.width, height: canvas.size.height) + .onAppear { + guard !steamEnabled else { return } + reader.start(steamRoot: steamRoot, appsFolder: appsFolder) + } + .onDisappear { reader.cancel() } + .onChange(of: offer) { next in + // The offer arrives after the read: it takes the first focus unless the player already moved. + if next != nil, !moved { focus = ArcaneWelcome.Focus.initial(offer: next) } + if next == nil, focus != .openLibrary { focus = .openLibrary } + } + .onReceive(NotificationCenter.default.publisher(for: .nxArcaneWelcomeGamepadAction)) { note in + guard let action = note.object as? GamepadAction else { return } + handle(action) + } + } + + private var newsCard: some View { + VStack(alignment: .leading, spacing: canvas.u(14)) { + Text(L10n.text("What's new")).seleneFont(17, .semibold).foregroundColor(SeleneTheme.ink60) + ForEach(Self.news, id: \.1) { icon, line in + HStack(spacing: canvas.u(14)) { + MaterialIconView(icon, size: 22).foregroundColor(SeleneTheme.ink75) + Text(L10n.text(line)).seleneFont(19).foregroundColor(SeleneTheme.ink) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + } + } + } + .padding(canvas.u(26)) + .frame(maxWidth: .infinity, alignment: .leading) + .background(SeleneTheme.glass.opacity(0.75)) + .clipShape(RoundedRectangle(cornerRadius: canvas.u(18), style: .continuous)) + } + + private func offerRow(_ offer: ArcaneWelcome.Offer) -> some View { + let count: Int + switch offer { case .steam(let gameCount): count = gameCount } + return HStack(spacing: canvas.u(16)) { + MaterialIconView(.gamepad, size: 26).foregroundColor(SeleneTheme.ink75) + VStack(alignment: .leading, spacing: canvas.u(4)) { + Text(L10n.count("Found %lld Steam games", count)).seleneFont(20, .semibold).foregroundColor(SeleneTheme.ink) + Text(L10n.text("Adding them doesn't change Steam's files.")).seleneFont(16).foregroundColor(SeleneTheme.ink60) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: 0) + SelenePillButton(title: L10n.text("Add"), minWidth: 120, height: 50, focused: focus == .add) { activate(.add) } + .onHover { if $0 { move(to: .add) } } + SelenePillButton(title: L10n.text("Not now"), minWidth: 120, height: 50, focused: focus == .notNow) { + activate(.notNow) + } + .onHover { if $0 { move(to: .notNow) } } + } + .padding(.horizontal, canvas.u(26)) + .padding(.vertical, canvas.u(18)) + .background(SeleneTheme.glass.opacity(0.75)) + .clipShape(RoundedRectangle(cornerRadius: canvas.u(18), style: .continuous)) + } +} diff --git a/Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift b/Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift new file mode 100644 index 00000000..51ed0adf --- /dev/null +++ b/Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift @@ -0,0 +1,45 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +extension FoundGamesSetupView { + /// Controller actions and the mapped keys while `found` is up: Up/Down between the rows, A on the one in focus. + func handle(_ action: GamepadAction) { + guard viewModel.showSetupCheck, viewModel.firstRunSetup.page == .found, + NSApp.modalWindow == nil, viewModel.alertMessage == nil else { return } + switch action { + case .navigateUp: move(to: focus.movedOnFound(.up, hasSteam: hasSteam)) + case .navigateDown: move(to: focus.movedOnFound(.down, hasSteam: hasSteam)) + case .confirm: activate(focus) + default: break + } + } + + func move(to next: FirstRunSetup.Focus) { + guard focus != next else { return } + focus = next + SoundEffectService.shared.play(.focus) + } + + func activate(_ target: FirstRunSetup.Focus) { + guard viewModel.showSetupCheck, viewModel.firstRunSetup.page == .found, NSApp.modalWindow == nil else { return } + move(to: target) + switch target { + case .steamToggle where findings?.steamReadFailed == true: + SoundEffectService.shared.play(.click) + reader.start(steamRoot: steamRoot, appsFolder: viewModel.gameAppsFolder) + case .steamToggle where steamCount != nil: + viewModel.chooseSteamOnFound(!steamOn) + SoundEffectService.shared.play(.key) + case .portingCard: + SoundEffectService.shared.play(.click) + viewModel.openPortingFromFound() + case .openLibrary: + reader.cancel() + SoundEffectService.shared.play(.click) + onOpenLibrary(portedCount > 0) + default: + SoundEffectService.shared.play(.error) + } + } +} diff --git a/Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift b/Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift new file mode 100644 index 00000000..30943670 --- /dev/null +++ b/Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift @@ -0,0 +1,110 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// The first launch's first page: what is already on the Mac (Steam, ported apps), the Porting card and +/// Open library. It reads without changing anything; the switches apply only on Open library. +struct FoundGamesSetupView: View { + @Environment(\.seleneCanvas) var canvas + @Environment(\.seleneReduceMotion) var reduceMotion + @ObservedObject var viewModel: AppViewModel + let steamRoot: URL + /// The Steam switch lives in `FirstRunSetup`, so it survives the Porting path; the shell applies it. + let onOpenLibrary: (_ importPorted: Bool) -> Void + + @StateObject var reader = FirstRunFindingsReader() + @State var focus: FirstRunSetup.Focus = .initialOnFound + + var findings: FirstRunFindings? { reader.findings } + var steamCount: Int? { findings?.steamGameCount } + var hasSteam: Bool { steamCount != nil || findings?.steamReadFailed == true } + var portedCount: Int { findings?.portedAppCount ?? 0 } + var isReading: Bool { findings == nil } + var steamOn: Bool { viewModel.firstRunSetup.steamChoice ?? true } + + private var title: String { + if isReading { return L10n.text("Looking at your Mac…") } + return findings?.isEmpty == true ? L10n.text("No games found") : L10n.text("Here's what's on your Mac") + } + + private var subtitle: String { + if isReading { return L10n.text("Arcane reads Steam and your Game apps folder without changing anything. You can open the library now and add sources later in Settings.") } + return findings?.isEmpty == true + ? L10n.text("Steam and ported apps aren't here yet. Add them later from Settings → Sources or with Porting.") + : L10n.text("Arcane looked without changing anything. Choose what goes in your library.") + } + + var body: some View { + ZStack { + SeleneBackdrop() + VStack(spacing: 0) { + Text(title).seleneFont(46, .semibold).foregroundColor(SeleneTheme.ink) + .multilineTextAlignment(.center) + Text(subtitle).seleneFont(19).foregroundColor(SeleneTheme.ink75) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, canvas.u(10)) + + VStack(spacing: canvas.u(12)) { + if let steamCount { + SetupCardRow(title: "Steam", + detail: L10n.count("%lld installed Mac games", steamCount), + icon: .store, trailing: .toggle(steamOn), + focused: focus == .steamToggle, + onHover: { move(to: .steamToggle) }) { activate(.steamToggle) } + } else if findings?.steamReadFailed == true { + SetupCardRow(title: "Steam", + detail: L10n.text("Steam couldn't be read completely. Try again or continue and check Settings → Sources later."), + icon: .store, trailing: .text(L10n.text("Retry")), + focused: focus == .steamToggle, + onHover: { move(to: .steamToggle) }) { activate(.steamToggle) } + } + if portedCount > 0 { + SetupCardRow(title: L10n.format("Already ported: %@", [String(portedCount)]), + detail: L10n.text("They're in your library."), + icon: .check, trailing: .none, height: 84, focused: false) {} + .allowsHitTesting(false) + } + SetupCardRow(title: AppIdentity.portingName, + detail: L10n.text("Bring the Nintendo Switch games you own to the Mac."), + note: L10n.text("Arcane is not affiliated with Nintendo."), + icon: .build, focused: focus == .portingCard, + onHover: { move(to: .portingCard) }) { activate(.portingCard) } + } + .padding(.top, canvas.u(32)) + + SelenePillButton(title: L10n.text("Open library"), minWidth: 220, + focused: focus == .openLibrary) { + activate(.openLibrary) + } + .onHover { if $0 { move(to: .openLibrary) } } + .padding(.top, canvas.u(30)) + } + .frame(width: canvas.u(960)) + .offset(y: canvas.u(-20)) + .animation(reduceMotion ? nil : SeleneTheme.standard, value: findings) + + VStack { + Spacer(minLength: 0) + SeleneHintsBar(right: [HintItem(.a, L10n.text("Select"))], + bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) + } + } + .frame(width: canvas.size.width, height: canvas.size.height) + .onAppear { + reader.start(steamRoot: steamRoot, appsFolder: viewModel.gameAppsFolder) + } + .onDisappear { reader.cancel() } + .onChange(of: findings) { found in + if found != nil, !hasSteam, focus == .steamToggle { move(to: .openLibrary) } + // The switch starts on; that is the choice until the player turns it off. + if found?.steamGameCount != nil, viewModel.firstRunSetup.steamChoice == nil { + viewModel.chooseSteamOnFound(true) + } + } + .onReceive(NotificationCenter.default.publisher(for: .nxSetupCheckGamepadAction)) { note in + guard let action = note.object as? GamepadAction else { return } + handle(action) + } + } +} diff --git a/Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift b/Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift index f49c6b54..e59d50a4 100644 --- a/Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift +++ b/Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift @@ -15,7 +15,7 @@ extension SetupCheckView { case .navigateDown: navigate(.down) case .confirm: activate() case .cancel: - if isFirstRun { shake() } else { close() } + if isFirstRun { backToFound() } else { close() } default: break } } @@ -85,6 +85,12 @@ extension SetupCheckView { } } + /// B during the first launch: back to what Arcane found on the Mac. + func backToFound() { + SoundEffectService.shared.play(.back) + viewModel.returnToFound() + } + func close() { viewModel.showSetupCheck = false } diff --git a/Sources/NXLibrary/Views/Setup/SetupCheckView.swift b/Sources/NXLibrary/Views/Setup/SetupCheckView.swift index 8db09f7f..b0646604 100644 --- a/Sources/NXLibrary/Views/Setup/SetupCheckView.swift +++ b/Sources/NXLibrary/Views/Setup/SetupCheckView.swift @@ -36,7 +36,7 @@ struct SetupCheckView: View { SeleneBackdrop() VStack(spacing: 0) { SetupStepIndicator(page: .requirements).padding(.bottom, canvas.u(18)) - Text(L10n.text("Let's get NX Library ready")) + Text(L10n.text("Let's get Arcane ready")) .seleneFont(46, .semibold) .foregroundColor(SeleneTheme.ink) Text(L10n.text("Check what you need to build. Your games come next.")) @@ -51,7 +51,7 @@ struct SetupCheckView: View { .offset(y: canvas.u(-20)) VStack { Spacer(minLength: 0) - SeleneHintsBar(right: isFirstRun ? [HintItem(.a, L10n.text("Select"))] : [HintItem(.a, L10n.text("Select")), HintItem(.b, L10n.text("Back"))], + SeleneHintsBar(right: [HintItem(.a, L10n.text("Select")), HintItem(.b, L10n.text("Back"))], bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) } } @@ -206,7 +206,7 @@ struct SetupCheckView: View { } if names.isEmpty { return Story(icon: .check, tone: SeleneTheme.success, title: L10n.text("Install all"), state: "Done", - about: L10n.text("Everything NX Library can install by itself is installed."), + about: L10n.text("Everything Arcane can install by itself is installed."), detail: L10n.text("Import your keys on their card if needed."), action: nil) } return Story(icon: .sync, tone: SeleneTheme.glyph, title: L10n.text("Install all"), state: L10n.format("%@ to go", [String(describing: (names.count))]), @@ -218,7 +218,7 @@ struct SetupCheckView: View { let left = required.filter { $0.state != .ready }.map(\.title) if left.isEmpty { return Story(icon: .check, tone: SeleneTheme.success, title: L10n.text("All set"), state: L10n.text("Ready"), - about: L10n.text("Everything NX Library needs is here."), detail: "", action: "Continue") + about: L10n.text("Everything Arcane needs is here."), detail: "", action: "Continue") } return Story(icon: .checklist, tone: SeleneTheme.glyph, title: L10n.format("%@ of %@ ready", [String(describing: (ready)), String(describing: (required.count))]), state: L10n.format("%@ left", [String(describing: (left.count))]), about: L10n.format("Still to do: %@.", [String(describing: (left.joined(separator: ", ")))]), diff --git a/Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift b/Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift index f09cd98a..ece4b1d5 100644 --- a/Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift +++ b/Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift @@ -111,39 +111,15 @@ struct YourGamesSetupView: View { private func row(_ target: FirstRunSetup.Focus, title: String, detail: String, icon: MaterialIcon, trailing: String? = nil, enabled: Bool = true, action: @escaping () -> Void) -> some View { - let focused = focus == target - return Button { + SetupCardRow(title: title, detail: detail, icon: icon, + trailing: trailing.map { .text($0) } ?? .chevron, + focused: focus == target, enabled: enabled, + onHover: { move(to: target) }) { move(to: target) guard enabled else { return } SoundEffectService.shared.play(.click) action() - } label: { - HStack(spacing: canvas.u(22)) { - MaterialIconView(icon, size: 30).frame(width: canvas.u(40)) - VStack(alignment: .leading, spacing: canvas.u(5)) { - Text(title).seleneFont(22, .semibold) - Text(detail).seleneFont(15).foregroundColor(SeleneTheme.ink75) - .lineLimit(2).truncationMode(.middle) - } - Spacer(minLength: canvas.u(12)) - if let trailing { Text(trailing).seleneFont(16, .semibold) } - else { MaterialIconView(.chevron, size: 22) } - } - .foregroundColor(SeleneTheme.ink) - .padding(.horizontal, canvas.u(24)) - .frame(width: canvas.u(960), height: canvas.u(112)) - .background(RoundedRectangle(cornerRadius: canvas.u(SeleneTheme.cardRadius), style: .continuous) - .fill(SeleneTheme.glassCard)) - .overlay(RoundedRectangle(cornerRadius: canvas.u(SeleneTheme.cardRadius), style: .continuous) - .strokeBorder(focused ? SeleneTheme.focus : SeleneTheme.ink15, lineWidth: canvas.u(focused ? 2 : 1))) - .shadow(color: focused ? SeleneTheme.focusGlow : .clear, radius: canvas.u(16)) - .opacity(enabled ? 1 : 0.45) - .contentShape(Rectangle()) } - .buttonStyle(.plain) - .disabled(!enabled) - .onHover { if $0 { move(to: target) } } - .animation(reduceMotion ? nil : SeleneTheme.focusIn, value: focused) } private func move(to next: FirstRunSetup.Focus) { @@ -174,6 +150,7 @@ struct YourGamesSetupView: View { case .folder: onChooseFolder() case .back: viewModel.returnToSetupRequirements() case .finish: onFinish() + case .steamToggle, .portingCard, .openLibrary: break } } } @@ -202,3 +179,58 @@ struct SetupStepIndicator: View { } } } + +/// A first-launch card row: icon, title, detail and what sits on the right. Focus draws the outline and glow. +struct SetupCardRow: View { + enum Trailing { case chevron, text(String), toggle(Bool), none } + + @Environment(\.seleneCanvas) private var canvas + @Environment(\.seleneReduceMotion) private var reduceMotion + let title: String + let detail: String + var note: String? = nil + let icon: MaterialIcon + var trailing: Trailing = .chevron + var height: CGFloat = 112 + let focused: Bool + var enabled: Bool = true + var onHover: () -> Void = {} + let action: () -> Void + + var body: some View { + Button(action: action) { + HStack(spacing: canvas.u(22)) { + MaterialIconView(icon, size: 30).frame(width: canvas.u(40)) + VStack(alignment: .leading, spacing: canvas.u(5)) { + Text(title).seleneFont(22, .semibold) + Text(detail).seleneFont(15).foregroundColor(SeleneTheme.ink75) + .lineLimit(2).truncationMode(.middle) + if let note { + Text(note).seleneFont(13).foregroundColor(SeleneTheme.ink60).padding(.top, canvas.u(1)) + } + } + Spacer(minLength: canvas.u(12)) + switch trailing { + case .chevron: MaterialIconView(.chevron, size: 22) + case .text(let text): Text(text).seleneFont(16, .semibold) + case .toggle(let isOn): SeleneSwitch(isOn: .constant(isOn)).allowsHitTesting(false) + case .none: EmptyView() + } + } + .foregroundColor(SeleneTheme.ink) + .padding(.horizontal, canvas.u(24)) + .frame(width: canvas.u(960), height: canvas.u(height)) + .background(RoundedRectangle(cornerRadius: canvas.u(SeleneTheme.cardRadius), style: .continuous) + .fill(SeleneTheme.glassCard)) + .overlay(RoundedRectangle(cornerRadius: canvas.u(SeleneTheme.cardRadius), style: .continuous) + .strokeBorder(focused ? SeleneTheme.focus : SeleneTheme.ink15, lineWidth: canvas.u(focused ? 2 : 1))) + .shadow(color: focused ? SeleneTheme.focusGlow : .clear, radius: canvas.u(16)) + .opacity(enabled ? 1 : 0.45) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(!enabled) + .onHover { if $0 { onHover() } } + .animation(reduceMotion ? nil : SeleneTheme.focusIn, value: focused) + } +} diff --git a/Sources/NXLibrary/Views/Shell/AppShellState.swift b/Sources/NXLibrary/Views/Shell/AppShellState.swift new file mode 100644 index 00000000..eee16d07 --- /dev/null +++ b/Sources/NXLibrary/Views/Shell/AppShellState.swift @@ -0,0 +1,39 @@ +import NXLibraryCore + +/// Prepared before the shell enters SwiftUI's view graph. Model startup can +/// update AppKit and shared observable services; it must not run during a view's +/// StateObject creation while the prepared shell enters the view graph. +@MainActor +final class AppShellState { + let settings: AppSettingsStore + let viewModel: AppViewModel + let router: AppRouter + let sources: CatalogSourcesModel + /// The Mods card keeps its prepared cover across navigation; Spotlight observes it only while visible. + let modStoreHost = ModStoreHost() + /// "Welcome to Arcane" is up from the first frame, so the library never shows before it. Decided before save recovery starts; what it raises opens above. + let opensWithWelcome: Bool + + init(settings: AppSettingsStore, catalog: CatalogDocument, repository: CatalogRepository) { + self.settings = settings + AppDelegate.settingsStore = settings + AppLocalization.shared.configure(settings.settings) + ThemeStore.shared.apply(id: settings.settings.colorThemeID) + let model = AppViewModel(settingsStore: settings, catalog: catalog, repository: repository) + viewModel = model + AppDelegate.isBusy = { [weak model] in + guard let model else { return false } + return model.isBuilding || model.isUpdatingApp || model.hasActiveSaveOperations + } + sources = CatalogSourcesModel(repository: repository, initialConfiguration: catalog.source(.steam) ?? .init(integration: .steam)) { [weak model] document in + model?.applyCatalog(document) + } + let router = AppRouter() + router.setInitialRoute(AppRouter.initialRoute(for: settings.settings.startOn, last: settings.settings.lastHome)) + self.router = router + opensWithWelcome = ArcaneWelcome.shouldShow(setupCompleted: model.setupCompleted, + shown: settings.settings.welcomeArcaneShown, + hasPendingRecovery: false) + model.isWelcomeOpen = opensWithWelcome + } +} diff --git a/Sources/NXLibrary/Views/Shell/AppShellView.swift b/Sources/NXLibrary/Views/Shell/AppShellView.swift index 7cf701b8..af42b445 100644 --- a/Sources/NXLibrary/Views/Shell/AppShellView.swift +++ b/Sources/NXLibrary/Views/Shell/AppShellView.swift @@ -12,20 +12,32 @@ public struct AppShellView: View { @StateObject private var runningGames = RunningGameMonitor() @StateObject private var sessionCard = SessionCardPresenter() @StateObject private var updater = AppUpdater() + @StateObject private var sources: CatalogSourcesModel + private let modStoreHost: ModStoreHost @StateObject private var nativeMenus = NativeMenuCommands.shared @ObservedObject private var theme = ThemeStore.shared @ObservedObject private var localization = AppLocalization.shared @State private var gestureKeyMonitor: Any? + /// Rescans the Steam source when Steam rewrites a manifest (a download finishing, a game installed or removed). + @State private var steamWatcher = SteamManifestWatcher() @State private var setupSourceEntryID: UUID? + /// "Welcome to Arcane" is on screen (once, after the update from NX Library). + @State private var showsWelcome = false + /// Closed in this session: never presented again, even while its fade has not yet saved it as shown. + @State private var welcomeDismissed = false /// Dismisses the Close Game confirmation when its game quits by itself. @State private var closeGameWatch: AnyCancellable? + @State private var sharedBackdrop: SeleneBackdropRequest? @Environment(\.accessibilityReduceMotion) private var accessibilityReduceMotion - public init(settingsStore store: AppSettingsStore) { - _settings = StateObject(wrappedValue: store) - _viewModel = StateObject(wrappedValue: AppViewModel(settingsStore: store)) - _router = StateObject(wrappedValue: Self.startingRouter(saved: store.settings)) + @MainActor init(state: AppShellState) { + _sources = StateObject(wrappedValue: state.sources) + _settings = StateObject(wrappedValue: state.settings) + _viewModel = StateObject(wrappedValue: state.viewModel) + _router = StateObject(wrappedValue: state.router) + modStoreHost = state.modStoreHost + _showsWelcome = State(initialValue: state.opensWithWelcome) } private func updateLocale() { @@ -36,23 +48,24 @@ public struct AppShellView: View { } } - /// The router, already on the screen the Start on setting names. - private static func startingRouter(saved: AppSettings) -> AppRouter { - // The palette is in place before the first frame. - ThemeStore.shared.apply(id: saved.colorThemeID) - let router = AppRouter() - router.setInitialRoute(AppRouter.initialRoute(for: saved.startOn, last: saved.lastHome)) - router.isIntroShowing = saved.introAnimation - return router - } - private var backdropStyle: SeleneBackdropStyle { - SeleneBackdropStyle(wallpaperURL: theme.wallpaper(for: settings.settings.wallpaperID)?.url, + SeleneBackdropStyle(palette: theme.palette, + wallpaperURL: theme.wallpaper(for: settings.settings.wallpaperID)?.url, sizing: settings.settings.backgroundSizing, animated: settings.settings.animatedBackground, brightness: settings.settings.wallpaperBrightness) } + private func updateSharedBackdrop(_ request: SeleneBackdropRequest?) { + if let request { + sharedBackdrop = request + } else if var last = sharedBackdrop { + // No page requests a background: keep its last frame, without a live clock. + last.still = true + sharedBackdrop = last + } + } + /// Spotlight or Collection: the screens that pick a game. private var isHomeRoute: Bool { router.route == .library || router.route == .collection @@ -63,17 +76,17 @@ public struct AppShellView: View { viewModel.gameToClose != nil || viewModel.gameToRemove != nil || showsUpdateOffer || showsInstallFailure || showsSettingsNotice } private var showsInstallFailure: Bool { - viewModel.gameWithInstallFailure != nil && !router.isIntroShowing && !viewModel.showSetupCheck + viewModel.gameWithInstallFailure != nil && !viewModel.showSetupCheck && viewModel.launchOverlay == nil && viewModel.gameToClose == nil && viewModel.gameToRemove == nil } - /// The update dialog waits for the intro and the Setup check. + /// The update dialog waits for the Setup check. private var showsUpdateOffer: Bool { - (updater.offer != nil || updater.isCheckPresented) && !router.isIntroShowing && !viewModel.showSetupCheck + (updater.offer != nil || updater.isCheckPresented) && !viewModel.showSetupCheck && !showsInstallFailure && viewModel.gameToClose == nil && viewModel.gameToRemove == nil && viewModel.launchOverlay == nil && !router.isScreenshotViewerOpen } private var showsSettingsNotice: Bool { - viewModel.settingsNotice != nil && !router.isIntroShowing && !viewModel.showSetupCheck + viewModel.settingsNotice != nil && !viewModel.showSetupCheck && !router.isScreenshotViewerOpen && viewModel.launchOverlay == nil && viewModel.gameToClose == nil && viewModel.gameToRemove == nil && !showsInstallFailure && !showsUpdateOffer @@ -83,25 +96,48 @@ public struct AppShellView: View { settings.settings.reduceMotion || accessibilityReduceMotion } + /// Native alerts and file pickers own input, including while their parent has no key window. + /// Check at delivery: controller actions under a dialog are dropped, never replayed after it closes. + private var nativeDialogOwnsInput: Bool { + viewModel.alertMessage != nil || NSApp.modalWindow != nil + || NSApp.keyWindow?.isSheet == true || NSApp.keyWindow?.attachedSheet != nil + || NSApp.mainWindow?.attachedSheet != nil + } + private var nativeMenuAvailability: NativeMenuAvailability { - let general = !router.isIntroShowing && !viewModel.showSetupCheck + let general = !viewModel.showSetupCheck && !showsWelcome && !isCloseGameOpen && !router.isScreenshotViewerOpen && !router.isSearchPresented - && viewModel.gameForSettingsSheet == nil && viewModel.launchOverlay == nil && NSApp.modalWindow == nil - && NSApp.keyWindow?.attachedSheet == nil && NSApp.keyWindow?.isSheet != true + && !viewModel.isGameOptionsOpen && viewModel.launchOverlay == nil && !nativeDialogOwnsInput let game = general && !router.isMenuPresented ? viewModel.currentFocusedGame : nil - return NativeMenuAvailability(general: general, play: game?.isPlayableLocally == true, - details: isHomeRoute && game != nil, options: game != nil) + let focused = general && !router.isMenuPresented ? viewModel.currentFocusedCatalogGame : nil + let steam = focused?.integration == .steam ? focused : nil + // A Steam game's details are its Spotlight page; it has no separate Details screen. + return NativeMenuAvailability(general: general, + play: game?.isPlayableLocally == true || steam.map(SteamPlayCoordinator.shared.canPlay) == true, + details: isHomeRoute && focused != nil && (focused?.integration != .steam || router.route == .library), + options: game != nil || steam != nil, + catalogRecovery: general && !viewModel.isBuilding && !viewModel.catalogBuildRecoveries.isEmpty) } - /// The launch screen sits over everything, menu included, until the game's window shows. - @ViewBuilder private var launchLayer: some View { - if router.isIntroShowing { - IntroView(settings: settings, reduceMotion: reduceMotion) { router.isIntroShowing = false } - } else if let state = viewModel.launchOverlay { + /// A game the session card or the launch screen names: a library build, else a Steam game of the catalog. + private func playedGame(_ id: UUID) -> PlayedGame? { + if let game = viewModel.libraryGames.first(where: { $0.id == id }) { return .nxnative(game) } + return viewModel.catalogGames.first { $0.id == id && $0.integration == .steam }.map(PlayedGame.steam) + } + + /// The launch screen, in its own window over every app and Space (`LaunchCoverWindow`). Its window has its own + /// SwiftUI root: the canvas and the locale are given to it here. + private var launchCover: some View { + LaunchCoverWindow(state: viewModel.launchOverlay, onPrepared: { SteamPlayCoordinator.shared.launchCoverPrepared(for: $0) }) { state in LaunchScreenView(state: state, viewModel: viewModel, artwork: artwork, settings: settings.settings, reduceMotion: reduceMotion) .id(state.game.id) + .seleneCanvasRoot() + .environment(\.locale, localization.context.formatLocale) + .environment(\.nxAppLocale, localization.context) } + .frame(width: 0, height: 0) + .accessibilityHidden(true) } /// Game options, Add game and the console open and close alike: a fade with a slight scale. @@ -109,39 +145,69 @@ public struct AppShellView: View { reduceMotion ? .opacity : .opacity.combined(with: .scale(scale: 0.985)) } + private var contentBlur: CGFloat { + !viewModel.isGameOptionsOpen && !router.route.isOverlay ? 0 : 10 + } + + private var currentBackdropCover: ShellBackdropCover { + .resolve(setup: viewModel.showSetupCheck, welcome: showsWelcome, + themePicker: router.isMenuPresented && router.isThemePickerOpen) + } + + private var fullScreenCover: Bool { currentBackdropCover.covers(0) } + + private func opacityBelowCover(_ priority: Double) -> Double { + currentBackdropCover.covers(priority) ? 0.001 : 1 + } + /// The screen plus the overlays that sit on it; split from `body` for the type checker. private var layers: some View { ZStack { - SeleneTheme.scrim.ignoresSafeArea() + let background = sharedBackdrop ?? SeleneBackdropRequest(style: backdropStyle, still: true) + SeleneBackdrop(baseOpacity: background.baseOpacity, still: background.still, modsTint: background.modsTint) + .environment(\.seleneBackdropStyle, background.style) + .environment(\.seleneSharesBackdrop, false) + .blur(radius: contentBlur) content // Game options, Add game and the console blur the screen behind instead of darkening it. - .blur(radius: viewModel.gameForSettingsSheet == nil && !router.route.isOverlay ? 0 : 10) - .allowsHitTesting(!router.route.isOverlay && viewModel.gameForSettingsSheet == nil) + .blur(radius: contentBlur) + // Keep artwork/tiles drawn and warm, as during Spotlight's entrance, while the full page covers them. + .opacity(fullScreenCover ? 0.001 : 1) + .allowsHitTesting(!fullScreenCover && !router.route.isOverlay && !viewModel.isGameOptionsOpen) if router.route == .addGame { AddGameView(viewModel: viewModel, router: router, artwork: artwork, showsHints: settings.settings.showButtonHints, reviewSelectionID: setupSourceEntryID) - .allowsHitTesting(!viewModel.showSetupCheck) + .opacity(opacityBelowCover(0.8)) + .allowsHitTesting(!currentBackdropCover.covers(0.8)) .transition(overlayTransition) .zIndex(0.8) } if router.route == .console { ConsoleView(viewModel: viewModel, router: router, showsHints: settings.settings.showButtonHints) + .opacity(opacityBelowCover(0.8)) + .allowsHitTesting(!currentBackdropCover.covers(0.8)) .transition(overlayTransition) .zIndex(0.8) } if router.isSearchPresented && isHomeRoute { FindGameView(router: router, viewModel: viewModel, playSessions: playSessions, artwork: artwork) + .opacity(opacityBelowCover(0.5)) + .allowsHitTesting(!currentBackdropCover.covers(0.5)) .transition(.opacity) .zIndex(0.5) } if viewModel.showSetupCheck { Group { - if viewModel.firstRunSetup.page == .games { + if viewModel.firstRunSetup.page == .found { + FoundGamesSetupView(viewModel: viewModel, steamRoot: sources.discoveryRoot) { importPorted in + finishFromFound(importPorted: importPorted) + } + } else if viewModel.firstRunSetup.page == .games { YourGamesSetupView(viewModel: viewModel, onChooseFiles: { chooseFirstGame(usingFolder: false) }, onChooseFolder: { chooseFirstGame(usingFolder: true) }, @@ -154,7 +220,23 @@ public struct AppShellView: View { } } .transition(.opacity) - .zIndex(2.5) + .zIndex(ShellBackdropCover.setup.priority) + .transformPreference(SeleneBackdropRequestKey.self) { $0?.priority = ShellBackdropCover.setup.priority } + } + if showsWelcome { + ArcaneWelcomeView(steamEnabled: sources.configuration.isEnabled, + steamRoot: sources.discoveryRoot, + appsFolder: viewModel.gameAppsFolder, + onAddSteam: { + sources.configure(enabled: true, root: sources.discoveryRoot) + }, + onExit: closeWelcome) + .opacity(opacityBelowCover(ShellBackdropCover.welcome.priority)) + .allowsHitTesting(!currentBackdropCover.covers(ShellBackdropCover.welcome.priority)) + .transition(.opacity) + // Below Setup: a Setup check that opens after the welcome owns the input, so it is drawn on top. + .zIndex(ShellBackdropCover.welcome.priority) + .transformPreference(SeleneBackdropRequestKey.self) { $0?.priority = ShellBackdropCover.welcome.priority } } if let game = viewModel.gameToClose { closeGameOverlay(game) @@ -182,19 +264,23 @@ public struct AppShellView: View { .zIndex(4) } if router.isMenuPresented { - if router.isThemePickerOpen { - ThemePickerView(viewModel: viewModel, router: router, settings: settings, games: viewModel.libraryGames) + Group { + if router.isThemePickerOpen { + ThemePickerView(viewModel: viewModel, router: router, settings: settings, games: viewModel.libraryGames) + .transition(.opacity) + .transformPreference(SeleneBackdropRequestKey.self) { $0?.priority = ShellBackdropCover.themePicker.priority } + } else { + MenuOverlayView( + router: router, + onSelect: { runMenuAction($0) }, + onSelectPower: { runPower($0) } + ) .transition(.opacity) - .zIndex(1) - } else { - MenuOverlayView( - router: router, - onSelect: { runMenuAction($0) }, - onSelectPower: { runPower($0) } - ) - .transition(.opacity) - .zIndex(1) + } } + .opacity(opacityBelowCover(ShellBackdropCover.themePicker.priority)) + .allowsHitTesting(!currentBackdropCover.covers(ShellBackdropCover.themePicker.priority)) + .zIndex(ShellBackdropCover.themePicker.priority) } if let game = viewModel.gameForSettingsSheet { GameOptionsView( @@ -212,10 +298,30 @@ public struct AppShellView: View { }, opensMods: viewModel.gameOptionsOpensMods ) + .opacity(opacityBelowCover(2)) + .allowsHitTesting(!currentBackdropCover.covers(2)) + .transition(overlayTransition) + .zIndex(2) + } + if let game = viewModel.steamOptionsGame { + SteamOptionsView( + viewModel: viewModel, + game: game, + origin: viewModel.gameOptionsOrigin, + onClose: { viewModel.steamOptionsGame = nil }, + onMove: { + viewModel.steamOptionsGame = nil + router.requestSpotlightMove(SpotlightItem.game(game.id).key) + } + ) + .opacity(opacityBelowCover(2)) + .allowsHitTesting(!currentBackdropCover.covers(2)) + .id(game.id) .transition(overlayTransition) .zIndex(2) } } + .onPreferenceChange(SeleneBackdropRequestKey.self, perform: updateSharedBackdrop) } /// Layers with environment, sheets and lifecycle; split from `body` for the type checker. @@ -223,18 +329,20 @@ public struct AppShellView: View { layers .allowsHitTesting(!nativeMenus.isTracking) .background(FullscreenCursorView()) - .background(StartupWindowView(fullscreen: settings.settings.startInFullscreen)) + .background(StartupWindowView(fullscreen: settings.settings.startInFullscreen) { + viewModel.isWindowSettling = false + }) .focusedSceneValue(\.nxMenuAvailability, nativeMenuAvailability) .overlay { - SessionCardLayer(presenter: sessionCard, games: viewModel.libraryGames, + SessionCardLayer(presenter: sessionCard, game: playedGame, metadata: viewModel.storeMetadata, artwork: artwork) } - .overlay { launchLayer } + .background { launchCover } .modifier(SoundCueHooks(router: router, viewModel: viewModel)) // Inside the canvas root so the sheet inherits the window's canvas units. .seleneCanvasRoot() .animation(reduceMotion ? nil : SeleneTheme.screen, - value: viewModel.gameForSettingsSheet?.id) + value: viewModel.optionsGameID) .animation(reduceMotion ? nil : SeleneTheme.quick, value: router.isMenuPresented) .animation(reduceMotion ? nil : SeleneTheme.screen, value: router.isThemePickerOpen) @@ -253,9 +361,16 @@ public struct AppShellView: View { .animation(reduceMotion ? nil : SeleneTheme.quick, value: showsUpdateOffer) .environment(\.seleneReduceMotion, reduceMotion) .environment(\.seleneBackdropStyle, backdropStyle) + .environment(\.seleneSharesBackdrop, true) .environment(\.seleneShowButtonHints, settings.settings.showButtonHints) .environment(\.seleneButtonNames, settings.settings.buttonNames) .environmentObject(updater) + .environmentObject(sources) + .onAppear { + steamWatcher.onChange = { [weak sources] in sources?.steamFilesChanged() } + sources.startIfEnabled() + } + .onReceive(sources.$libraryRoots) { roots in steamWatcher.watch(roots, root: sources.configuration.rootURL) } .preferredColorScheme(.dark) .frame(minWidth: 1100, minHeight: 700) .onAppear(perform: startRuntime) @@ -271,21 +386,66 @@ public struct AppShellView: View { } .onDisappear { runningGames.stop() + SteamPlayCoordinator.shared.stop() + SteamPlaytimeCoordinator.shared.stop() + SteamAchievementsStore.shared.stop() + steamWatcher.stop() removeGestureKeyMonitor() } .onChange(of: viewModel.libraryGames) { games in runningGames.setGames(games) } + .onChange(of: viewModel.catalogGames) { games in + SteamPlayCoordinator.shared.setGames(games, sources: viewModel.catalogSourceConfigurations) + SteamPlaytimeCoordinator.shared.setGames(games, sources: viewModel.catalogSourceConfigurations) + } + .onChange(of: viewModel.catalogSourceConfigurations) { sources in + SteamPlayCoordinator.shared.setGames(viewModel.catalogGames, sources: sources) + SteamPlaytimeCoordinator.shared.setGames(viewModel.catalogGames, sources: sources) + SteamAchievementsStore.shared.setSources(sources) + } + .onReceive(playSessions.starts) { gameID in + // A game that starts leads the Spotlight row, as on a console's home; a move in progress is left alone. + guard viewModel.spotlight.lift == nil else { return } + let order = SpotlightRow.playing(gameID, previousOrder: settings.settings.spotlightOrder) + if order != settings.settings.spotlightOrder { settings.settings.spotlightOrder = order } + } .onReceive(runningGames.$endedSession) { summary in sessionCard.ended(summary, enabled: settings.settings.showsSessionCard) } + .onReceive(SteamPlayCoordinator.shared.$endedSession) { summary in + sessionCard.ended(summary, enabled: settings.settings.showsSessionCard) + } + .onReceive(SteamPlayCoordinator.shared.$launchScreen) { screen in + // A Steam game's launch screen is the nxnative one: shown on Play, leaving when the coordinator says. + guard let screen else { return } + if viewModel.launchOverlay?.game.id == screen.gameID { + if screen.ready { viewModel.launchOverlay?.isReady = true } + } else if !screen.ready, viewModel.launchOverlay == nil, let game = playedGame(screen.gameID) { + viewModel.launchOverlay = LaunchOverlayState(game: game) + SoundEffectService.shared.play(.launch) + } else { + // Not on screen (another launch is) or already over: there is no wait to hold the front for. + SteamPlayCoordinator.shared.launchScreenClosed(screen.gameID) + } + } + .onChange(of: viewModel.launchOverlay?.game.id) { shown in + // The screen faded, the player dismissed it or another game's took its place: NX Library stops holding + // the front for the Steam game. + if let screen = SteamPlayCoordinator.shared.launchScreen, shown != screen.gameID { + SteamPlayCoordinator.shared.launchScreenClosed(screen.gameID) + } + } .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in sessionCard.becameActive() + SteamPlaytimeCoordinator.shared.refresh() } .onChange(of: settings.settings.showsSessionCard) { on in if !on { sessionCard.clear() } } .onChange(of: showsUpdateOffer) { viewModel.isUpdateOfferOpen = $0 } + // Closing clears it once the fade has ended (`closeWelcome`), so nothing under it moves or takes input before. + .onChange(of: showsWelcome) { if $0 { viewModel.isWelcomeOpen = true } } .onChange(of: router.route) { route in recordLastHome(route) switch route { @@ -308,35 +468,38 @@ public struct AppShellView: View { styled .environment(\.locale, localization.context.formatLocale) .environment(\.nxAppLocale, localization.context) + .environment(\.catalogPersonalizations, viewModel.personalizations) .onChange(of: settings.settings.appLanguage) { _ in updateLocale() } .onChange(of: settings.settings.appRegion) { _ in updateLocale() } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryPlayFocused)) { _ in guard !router.isMenuPresented, nativeMenuAvailability.play, - viewModel.gameForSettingsSheet == nil, - !isCloseGameOpen, - let game = viewModel.currentFocusedGame else { return } - viewModel.launchGame(game) + !viewModel.isGameOptionsOpen, + !isCloseGameOpen else { return } + if let steam = viewModel.currentFocusedCatalogGame, steam.integration == .steam { + SteamPlayCoordinator.shared.press(steam) + } else if let game = viewModel.currentFocusedGame { + viewModel.launchGame(game) + } } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryOpenDetails)) { _ in guard !router.isMenuPresented, - viewModel.gameForSettingsSheet == nil, + !viewModel.isGameOptionsOpen, !isCloseGameOpen, isHomeRoute, - let game = viewModel.currentFocusedGame else { return } + let game = viewModel.currentFocusedCatalogGame else { return } if router.route == .library { viewModel.spotlight.showGameDetails() } - else { router.showDetail(game.id) } + else if game.integration != .steam { router.showDetail(game.id) } } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryOpenGameOptions)) { _ in guard nativeMenuAvailability.options else { return } switch router.route { - case .library: - if let game = viewModel.currentFocusedGame { - viewModel.openGameOptions(game, from: .spotlight) - } - case .collection: - if let game = viewModel.currentFocusedGame { - viewModel.openGameOptions(game, from: .collection) + case .library, .collection: + let origin: GameOptionsOrigin = router.route == .library ? .spotlight : .collection + if let steam = viewModel.currentFocusedCatalogGame, steam.integration == .steam { + viewModel.openSteamOptions(steam, from: origin) + } else if let game = viewModel.currentFocusedGame { + viewModel.openGameOptions(game, from: origin) } case .detail(let id): if let game = viewModel.libraryGames.first(where: { $0.id == id }) { @@ -356,21 +519,25 @@ public struct AppShellView: View { updater.checkNow() } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryOpenMenu)) { _ in - guard !isCloseGameOpen, viewModel.gameForSettingsSheet == nil, !router.isScreenshotViewerOpen else { return } + guard !isCloseGameOpen, !viewModel.isGameOptionsOpen, !router.isScreenshotViewerOpen else { return } router.isMenuPresented = true } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryOpenSettings)) { _ in - guard !isCloseGameOpen, !router.isScreenshotViewerOpen, viewModel.gameForSettingsSheet == nil else { return } + guard !isCloseGameOpen, !router.isScreenshotViewerOpen, !viewModel.isGameOptionsOpen else { return } router.closeMenu() router.openSettings(.startUp) } + .onReceive(NotificationCenter.default.publisher(for: .nxLibraryRetryCatalogSave)) { _ in + guard nativeMenuAvailability.catalogRecovery else { return } + viewModel.retrySavingBuildResults() + } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryOpenConsole)) { _ in - guard !isCloseGameOpen, !router.isScreenshotViewerOpen, viewModel.gameForSettingsSheet == nil else { return } + guard !isCloseGameOpen, !router.isScreenshotViewerOpen, !viewModel.isGameOptionsOpen else { return } router.closeMenu() router.openConsole() } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryPortingNoticeOpened)) { note in - guard !isCloseGameOpen, !router.isScreenshotViewerOpen, viewModel.gameForSettingsSheet == nil, + guard !isCloseGameOpen, !router.isScreenshotViewerOpen, !viewModel.isGameOptionsOpen, let id = (note.userInfo?["gameID"] as? String).flatMap(UUID.init(uuidString:)) else { return } router.closeMenu() if note.userInfo?["outcome"] as? String == "failed" { @@ -387,13 +554,13 @@ public struct AppShellView: View { } } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryOpenLibrary)) { _ in - guard !isCloseGameOpen, !router.isScreenshotViewerOpen, viewModel.gameForSettingsSheet == nil else { return } + guard !isCloseGameOpen, !router.isScreenshotViewerOpen, !viewModel.isGameOptionsOpen else { return } router.closeMenu() router.showLibrary() } .onReceive(NotificationCenter.default.publisher(for: .nxLibraryOpenAddGame)) { _ in guard !isCloseGameOpen, !router.isMenuPresented, !router.isScreenshotViewerOpen, - viewModel.gameForSettingsSheet == nil else { return } + !viewModel.isGameOptionsOpen else { return } router.closeMenu() openFreshAddGame() } @@ -410,7 +577,7 @@ public struct AppShellView: View { viewModel.dismissRemoveGame() } else if showsUpdateOffer { updater.later() - } else if viewModel.gameForSettingsSheet != nil { + } else if viewModel.isGameOptionsOpen { // Game options steps back (dialog, then Edit details) or closes. NotificationCenter.default.post(name: .nxGameOptionsGamepadAction, object: GamepadAction.cancel) } else if router.isMenuPresented { @@ -432,6 +599,21 @@ public struct AppShellView: View { .onChange(of: viewModel.alertMessage) { _ in presentLegacyNotice() } + .onChange(of: viewModel.setupCompleted) { done in + // The Steam switch of `found` applies however the first launch ends (Open library, Porting, Skip). + if done, let choice = viewModel.firstRunSetup.steamChoice, + choice != sources.configuration.isEnabled { + sources.configure(enabled: choice, root: sources.discoveryRoot) + } + // A first setup finished today: this player starts on Arcane and never needs the welcome. + if done, !showsWelcome, !settings.settings.welcomeArcaneShown { + settings.settings = ArcaneWelcome.markShown(settings.settings) + } + } + .task(id: welcomeTrigger) { await presentWelcomeIfDue() } + .onChange(of: viewModel.settingsNotice?.id) { id in + if id == nil { presentLegacyNotice() } + } } /// The current screen; under Add game or the console, the screen they were opened from. @@ -445,7 +627,8 @@ public struct AppShellView: View { settings: settings, playSessions: playSessions, runningGames: runningGames, - artwork: artwork + artwork: artwork, + storeHost: modStoreHost ) case .collection: CollectionView( @@ -490,11 +673,22 @@ public struct AppShellView: View { viewModel.playSessionStore = playSessions viewModel.settingsStore = settings SoundEffectService.shared.bind(to: settings) + // The opening's boot cue, with Spotlight's entrance (Settings → Start-up → Entrance animation). + if settings.settings.introAnimation { SoundEffectService.shared.play(.boot) } artwork.trimCache() viewModel.refreshBoxArtIndex() - if settings.settings.checkEngineAtLaunch { SetupCheckModel.checkAtLaunch(viewModel: viewModel) } + if settings.settings.checkEngineAtLaunch && !AppData.profile.isDevelopment { SetupCheckModel.checkAtLaunch(viewModel: viewModel) } runningGames.start(sessions: playSessions) runningGames.setGames(viewModel.libraryGames) + // Steam's playtime first: a Steam game already running starts a session at once, and trimming needs Steam's last values. + SteamPlaytimeCoordinator.shared.setGames(viewModel.catalogGames, sources: viewModel.catalogSourceConfigurations) + SteamPlaytimeCoordinator.shared.start(sessions: playSessions) + SteamAchievementsStore.shared.setSources(viewModel.catalogSourceConfigurations) + // After the nxnative reconcile, which closes a Steam session left by a restart at its last heartbeat. + SteamPlayCoordinator.shared.setGames(viewModel.catalogGames, sources: viewModel.catalogSourceConfigurations) + SteamPlayCoordinator.shared.nativeGames = runningGames + SteamPlayCoordinator.shared.isLaunchScreenShowing = { [weak viewModel] in viewModel?.launchOverlay != nil } + SteamPlayCoordinator.shared.start(sessions: playSessions, settings: settings) viewModel.installPendingBuilds() viewModel.syncPendingAppIcons() closeGameWatch = runningGames.$runningGameIDs.sink { [weak viewModel] ids in @@ -538,12 +732,7 @@ public struct AppShellView: View { installGestureKeyMonitor() GameControllerService.shared.onAction = { [weak viewModel, weak router] action in guard let viewModel, let router else { return } - guard !nativeMenus.isTracking else { return } - if router.isIntroShowing { - // Any controller input skips the intro. - NotificationCenter.default.post(name: .nxIntroSkip, object: nil) - return - } + guard !nativeMenus.isTracking, !nativeDialogOwnsInput else { return } if viewModel.showSetupCheck { // The Setup check owns the controller; Menu does nothing there (as in Selene). NotificationCenter.default.post(name: .nxSetupCheckGamepadAction, object: action) @@ -553,6 +742,11 @@ public struct AppShellView: View { settingsNoticeInput(action) return } + if showsWelcome, !showsInstallFailure, viewModel.gameToClose == nil, viewModel.gameToRemove == nil, + !showsUpdateOffer { + NotificationCenter.default.post(name: .nxArcaneWelcomeGamepadAction, object: action) + return + } if showsInstallFailure { installFailureInput(action) return @@ -573,7 +767,7 @@ public struct AppShellView: View { menuInput(action) return } - if viewModel.gameForSettingsSheet != nil { + if viewModel.isGameOptionsOpen { NotificationCenter.default.post(name: .nxGameOptionsGamepadAction, object: action) return } @@ -640,12 +834,60 @@ public struct AppShellView: View { viewModel.settingsNotice = nil notice?.onDismiss?() if choice == 1 { notice?.retry?() } + presentLegacyNotice() + } + + /// Anything that comes before the welcome: Setup, dialogs, a launch, the screenshot viewer. + private var welcomeBlocked: Bool { + viewModel.showSetupCheck || showsSettingsNotice || showsInstallFailure + || showsUpdateOffer || viewModel.gameToClose != nil || viewModel.gameToRemove != nil + || viewModel.launchOverlay != nil || router.isScreenshotViewerOpen + } + + private var welcomeTrigger: [Bool] { + [welcomeBlocked, viewModel.setupCompleted, settings.settings.welcomeArcaneShown, + viewModel.gameWithInstallFailure != nil, viewModel.hasActiveSaveOperations] + } + + private func presentWelcomeIfDue() async { + guard !showsWelcome, !welcomeDismissed, !welcomeBlocked, viewModel.setupCompleted, + !settings.settings.welcomeArcaneShown else { return } + // `hasActiveSaveOperations` is in the trigger: the welcome comes back here when the save recovery ends. + let pending = viewModel.hasActiveSaveOperations || viewModel.saveGate.hasActiveOperations + || viewModel.gameWithInstallFailure != nil + guard !Task.isCancelled, !welcomeBlocked, + ArcaneWelcome.shouldShow(setupCompleted: viewModel.setupCompleted, + shown: settings.settings.welcomeArcaneShown, + hasPendingRecovery: pending) else { return } + withAnimation(reduceMotion ? nil : SeleneTheme.screen) { showsWelcome = true } + } + + /// The welcome fades first; saving and moving to the library wait until it has gone, so no redraw of the + /// whole shell lands in the fade's first frames (Selene does its home work once the layer has really gone). + private func closeWelcome(_ exit: ArcaneWelcome.Exit) { + guard showsWelcome else { return } + welcomeDismissed = true + let finish = { + settings.settings = ArcaneWelcome.settings(after: exit, from: settings.settings) + if exit == .openLibrary { router.navigate(to: .library) } + viewModel.isWelcomeOpen = false + } + guard !reduceMotion else { + showsWelcome = false + finish() + return + } + withAnimation(SeleneTheme.screen) { showsWelcome = false } + Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(SeleneTheme.screenDuration * 1_000_000_000)) + finish() + } } private func presentLegacyNotice() { - guard let message = viewModel.alertMessage else { return } + guard viewModel.settingsNotice == nil, let message = viewModel.alertMessage else { return } viewModel.alertMessage = nil - viewModel.showSettingsNotice(title: L10n.text("NX Library"), message: message) + viewModel.showSettingsNotice(title: AppIdentity.name, message: message) } private func settingsNoticeInput(_ action: GamepadAction) { @@ -827,16 +1069,16 @@ public struct AppShellView: View { if nativeMenus.isTracking { return event } // The screenshot viewer owns the keyboard (its own monitor handles it); no navigating underneath. if router.isScreenshotViewerOpen { return event } - // The intro's own monitor takes any key as "skip". - if router.isIntroShowing { return event } // An alert or another window's sheet owns Return and Esc. - if viewModel.alertMessage != nil || NSApp.modalWindow != nil + if nativeDialogOwnsInput || event.window?.attachedSheet != nil || event.window?.isSheet == true { return event } let mods = event.modifierFlags.intersection([.command, .control, .option, .shift]) - // The Setup check takes the keyboard: arrows, Return, Space and Esc go to it. - if viewModel.showSetupCheck { + // The Setup check and the welcome take the keyboard: arrows, Return, Space and Esc go to them. + if viewModel.showSetupCheck || (showsWelcome && !showsSettingsNotice && !showsInstallFailure + && !showsUpdateOffer && viewModel.gameToClose == nil + && viewModel.gameToRemove == nil) { guard mods.isEmpty, !(event.window?.firstResponder is NSText) else { return event } let setupAction: GamepadAction? switch event.keyCode { @@ -983,6 +1225,10 @@ public struct AppShellView: View { case .refreshLibrary: router.closeMenu() viewModel.refreshLibrary() + if sources.configuration.isEnabled { sources.refresh() } + case .manageSources: + router.closeMenu() + router.openSettings(.sources) case .settings: router.closeMenu() router.openSettings(.startUp) @@ -1028,9 +1274,10 @@ public struct AppShellView: View { do { try helper.run() } catch { - viewModel.alertMessage = L10n.format("NX Library could not restart: %@", [String(describing: (error.localizedDescription))]) + viewModel.alertMessage = L10n.format("Arcane could not restart: %@", [String(describing: (error.localizedDescription))]) return } + AppDelegate.relaunchScheduled = true NSApplication.shared.terminate(nil) } @@ -1045,6 +1292,13 @@ public struct AppShellView: View { if settings.settings.lastHome != home { settings.settings.lastHome = home } } + /// Open library on the first launch's `found` page; the Steam switch applies with the finish. + private func finishFromFound(importPorted: Bool) { + guard viewModel.showSetupCheck, viewModel.firstRunSetup.page == .found else { return } + viewModel.finishFromFound(importPorted: importPorted) + router.navigate(to: .library) + } + private func chooseFirstGame(usingFolder: Bool) { guard viewModel.showSetupCheck, viewModel.firstRunSetup.page == .games else { return } @@ -1079,7 +1333,7 @@ private struct SoundCueHooks: ViewModifier { .onChange(of: router.isMenuPresented) { open in SoundEffectService.shared.play(open ? .openPanel : .back) } - .onChange(of: viewModel.gameForSettingsSheet?.id) { id in + .onChange(of: viewModel.optionsGameID) { id in SoundEffectService.shared.play(id == nil ? .back : .openPanel) } .onChange(of: viewModel.gameToClose?.id) { id in diff --git a/Sources/NXLibrary/Views/Shell/StartupWindowView.swift b/Sources/NXLibrary/Views/Shell/StartupWindowView.swift index 72c775c8..16a2e0eb 100644 --- a/Sources/NXLibrary/Views/Shell/StartupWindowView.swift +++ b/Sources/NXLibrary/Views/Shell/StartupWindowView.swift @@ -1,20 +1,32 @@ import AppKit import SwiftUI -/// Reads the launch preference once; changing Settings never changes the current window's mode. +/// Reads the launch preference once; changing Settings never changes the current window's mode. `onSettled` runs +/// once the window has its launch mode (after it has faded in and gone full screen, or at once without a transition; +/// at most 3 s after the window's own wait). struct StartupWindowView: NSViewRepresentable { let fullscreen: Bool - func makeNSView(context: Context) -> StartupWindowObserver { StartupWindowObserver(fullscreen: fullscreen) } + var onSettled: () -> Void = {} + func makeNSView(context: Context) -> StartupWindowObserver { + StartupWindowObserver(fullscreen: fullscreen, onSettled: onSettled) + } func updateNSView(_ view: StartupWindowObserver, context: Context) {} static func dismantleNSView(_ view: StartupWindowObserver, coordinator: ()) { view.stop() } } final class StartupWindowObserver: NSView { private let fullscreen: Bool + private let onSettled: () -> Void private var applied = false + private var settled = false private var observer: NSObjectProtocol? + private var transition: [NSObjectProtocol] = [] - init(fullscreen: Bool) { self.fullscreen = fullscreen; super.init(frame: .zero) } + init(fullscreen: Bool, onSettled: @escaping () -> Void) { + self.fullscreen = fullscreen + self.onSettled = onSettled + super.init(frame: .zero) + } required init?(coder: NSCoder) { nil } override func hitTest(_ point: NSPoint) -> NSView? { nil } @@ -25,17 +37,41 @@ final class StartupWindowObserver: NSView { observer = NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { [weak self] _ in self?.applyWhenReady() } applyWhenReady() + // Never held longer: a window that is not made key, or a transition that never reports its end. + DispatchQueue.main.asyncAfter(deadline: .now() + LaunchReveal.limit + 3) { [weak self] in self?.settle() } } private func applyWhenReady() { DispatchQueue.main.async { [weak self] in - guard let self, !self.applied, let window = self.window, window.isVisible, window.isKeyWindow else { return } + guard let self, !self.applied, let window = self.window else { return } + guard window.isVisible, window.isKeyWindow else { return } self.applied = true self.stop() - if window.styleMask.contains(.fullScreen) != self.fullscreen { window.toggleFullScreen(nil) } + // The fullscreen transition animates a picture of the window: it waits for the window to show the + // moonlight (`LaunchReveal`), never a black window. + LaunchReveal.whenShown { [weak self] in self?.applyMode(window) } } } + private func applyMode(_ window: NSWindow) { + guard window.styleMask.contains(.fullScreen) != fullscreen else { return settle() } + transition = [NSWindow.didEnterFullScreenNotification, NSWindow.didExitFullScreenNotification] + .map { name in + NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in + self?.settle() + } + } + window.toggleFullScreen(nil) + } + + private func settle() { + guard !settled else { return } + settled = true + transition.forEach(NotificationCenter.default.removeObserver) + transition = [] + onSettled() + } + func stop() { if let observer { NotificationCenter.default.removeObserver(observer) } observer = nil diff --git a/Sources/NXLibrary/Views/Spotlight/AchievementDetail.swift b/Sources/NXLibrary/Views/Spotlight/AchievementDetail.swift new file mode 100644 index 00000000..1fd00305 --- /dev/null +++ b/Sources/NXLibrary/Views/Spotlight/AchievementDetail.swift @@ -0,0 +1,104 @@ +import SwiftUI +import NXLibraryCore + +/// One achievement in full, over the Achievements screen (A on a row), as a medallion (maintainer's choice "A", +/// 16 Nov 2026): on one centred axis the achievement's icon large with its tier crystal as a small badge on the +/// corner, the whole name and description the list cuts, then how many players have it and when it was unlocked. +/// The arrows step it through the list, A or B (or a click outside the card) close it. Without Steam's rarity the +/// icon has no badge. +struct AchievementDetail: View { + @Environment(\.seleneCanvas) private var canvas + + let row: AchievementRow + let appID: UInt32 + let onClose: () -> Void + + static let width: CGFloat = 720 + static let icon: CGFloat = 200 + static let badge: CGFloat = 64 + + var body: some View { + let unlocked = row.unlockedAt != nil + let shape = RoundedRectangle(cornerRadius: canvas.u(SeleneTheme.modalRadius), style: .continuous) + ZStack { + Color.black.opacity(0.55) + .ignoresSafeArea() + .contentShape(Rectangle()) + .onTapGesture(perform: onClose) + VStack(spacing: 0) { + medal(unlocked: unlocked) + Text(row.name) + .seleneFont(32, .semibold) + .foregroundColor(SeleneTheme.ink) + .multilineTextAlignment(.center) + .lineLimit(3) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, canvas.u(34)) + if !row.description.isEmpty { + Text(row.description) + .seleneFont(19) + .foregroundColor(SeleneTheme.ink82) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .padding(.top, canvas.u(10)) + } + Rectangle() + .fill(SeleneTheme.ink15) + .frame(width: canvas.u(80), height: max(1, canvas.u(1))) + .padding(.top, canvas.u(26)) + VStack(spacing: canvas.u(10)) { + if let tier = row.tier, let percent = row.percent { + HStack(spacing: canvas.u(10)) { + Text(tier.displayName()) + .foregroundColor(SeleneTheme.ink) + Text("·").foregroundColor(SeleneTheme.ink60) + Text(L10n.format("%@ of players", [AchievementsScreen.percent(percent)])) + .foregroundColor(SeleneTheme.ink75) + .monospacedDigit() + } + } + if let date = row.unlockedAt { + Label { + Text(L10n.format("Unlocked on %@", [AchievementsScreen.date(date)])) + } icon: { + Image(systemName: "checkmark.circle.fill") + } + .labelStyle(.titleAndIcon) + .foregroundColor(SeleneTheme.ink82) + } else { + Text(L10n.text("Not unlocked")) + .foregroundColor(SeleneTheme.ink.opacity(0.5)) + } + } + .seleneFont(18, .semibold) + .lineLimit(1) + .padding(.top, canvas.u(22)) + } + .padding(.horizontal, canvas.u(56)) + .padding(.top, canvas.u(56)) + .padding(.bottom, canvas.u(48)) + .frame(width: canvas.u(Self.width)) + .background(shape.fill(SeleneTheme.glassCard)) + .overlay(shape.strokeBorder(SeleneTheme.ink15, lineWidth: max(1, canvas.u(1)))) + .shadow(color: .black.opacity(0.45), radius: canvas.u(30), y: canvas.u(10)) + // A click on the card stays on the card. + .contentShape(shape) + .onTapGesture {} + .accessibilityElement(children: .combine) + .accessibilityAddTraits(.isModal) + } + } + + /// The icon, the thing earned, with its grade on the corner as a trophy's: the tier crystal, a little out of + /// the icon's square, lifted off it by a soft shadow. + private func medal(unlocked: Bool) -> some View { + AchievementIcon(appID: appID, file: row.icon, size: Self.icon, dimmed: !unlocked, secret: row.isMasked) + .overlay(alignment: .bottomTrailing) { + if let tier = row.tier { + TierCrystal(tier: tier, size: Self.badge, dimmed: !unlocked) + .shadow(color: .black.opacity(0.55), radius: canvas.u(8), y: canvas.u(3)) + .offset(x: canvas.u(Self.badge * 0.35), y: canvas.u(Self.badge * 0.3)) + } + } + } +} diff --git a/Sources/NXLibrary/Views/Spotlight/AchievementsScreen.swift b/Sources/NXLibrary/Views/Spotlight/AchievementsScreen.swift new file mode 100644 index 00000000..c46f3e15 --- /dev/null +++ b/Sources/NXLibrary/Views/Spotlight/AchievementsScreen.swift @@ -0,0 +1,582 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// A Steam game's achievements, over the game's art (darker), laid out like Selene's: the logo and the recently +/// unlocked icons on the left, the progress and the tier crystals on the right, filters between LB and RB, a +/// one-column list. +/// A pure view like `ScreenshotViewer`: Spotlight owns `AchievementsScreenState` and routes input through +/// `AchievementsScreen.handle`. Present it as an overlay inside the canvas root so the canvas scaling applies. +struct AchievementsScreen: View { + @Environment(\.seleneCanvas) private var canvas + @Environment(\.seleneReduceMotion) private var reduceMotion + /// The earned Arcane comes to colour just after the screen opens (`arcaneOrb`). + @State private var arcaneLit = false + @ObservedObject private var logos = SteamLogoCache.shared + @ObservedObject private var picks = SteamPersonalizations.shared.artwork + @ObservedObject var model: AchievementsScreenModel + + let game: CatalogGame + let summary: AchievementSummary + /// The page's art, as on Spotlight behind it. + let art: NSImage? + let onFilter: (AchievementFilter) -> Void + /// LB (-1) or RB (+1), as the controller does. + let onShiftFilter: (Int) -> Void + /// Y or a click on the order: the next order. + let onCycleOrder: () -> Void + let onFocus: (Int) -> Void + /// A, the hint or a click on the focused row: the focused achievement's detail. + let onOpen: () -> Void + let onCloseDetail: () -> Void + let onClose: () -> Void + + static let side: CGFloat = 110 + /// The list's one column, as wide as the two columns and their gap it replaced. + static let listWidth: CGFloat = 1700 + static let rowHeight: CGFloat = 96 + /// The Recently unlocked strip's length. + static let recentLimit = 12 + /// The list's last row can rise this far above the bottom edge: clear of the fade and the hints bar. + static let bottomRoom: CGFloat = hintsBand + bottomFade + /// The fades at the list's edges. + static let topFade: CGFloat = 40 + static let bottomFade: CGFloat = 110 + /// The shared footer stays entirely clear of rows, below the fade. + static let hintsBand: CGFloat = SeleneBottomScrim.contentClearance + static let rowSpacing: CGFloat = 16 + /// Room for the focus ring around the rows. + static let ring: CGFloat = 6 + + private var state: AchievementsScreenState { model.state } + + var body: some View { + let rows = summary.rows(state.filter, order: state.order) + ZStack(alignment: .topLeading) { + backdrop + VStack(alignment: .leading, spacing: 0) { + // The game on the left; the progress on the right, level with the list's right edge. + // The medallion sits centred on the game's column (logo and Recently unlocked); the gauge, at its top. + HStack(alignment: summary.isComplete ? .center : .top, spacing: 0) { + header + Spacer(minLength: canvas.u(40)) + progress + } + .frame(width: canvas.u(Self.listWidth + Self.ring)) + .padding(.top, canvas.u(70)) + pills.padding(.top, canvas.u(30)) + AchievementsList(scroll: model.scroll, model: model, rows: rows, focused: state.index, + appID: game.steamGame?.appID ?? 0, onFocus: onFocus) + .padding(.top, canvas.u(28)) + } + .padding(.leading, canvas.u(Self.side)) + if state.isDetailOpen, let id = state.focusedID, let row = rows.first(where: { $0.id == id }) { + AchievementDetail(row: row, appID: game.steamGame?.appID ?? 0, onClose: onCloseDetail) + .transition(.opacity) + } + VStack(spacing: 0) { + Spacer(minLength: 0) + SeleneHintsBar(left: [HintItem(.b, L10n.text("Back")) { + if state.isDetailOpen { onCloseDetail() } else { onClose() } + }], + right: state.isDetailOpen ? [] : listHints(hasRows: !rows.isEmpty), + bottom: SeleneBottomScrim.hintsBottom, leftInset: 18) + } + } + .animation(SeleneTheme.quick, value: state.isDetailOpen) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .accessibilityElement(children: .contain) + .accessibilityLabel(L10n.text("Achievements")) + } + + // MARK: - Parts + + private var backdrop: some View { + ZStack { + Rectangle().fill(SeleneTheme.baseGradient) + if let art { + // The art fills the screen's frame and is cut to it: an `.aspectRatio(.fill)` image under a + // `.frame(maxWidth: .infinity)` made the frame as wide as the filled art, which widened the + // whole screen past the window's edges (most in full screen) and pushed it off-centre. + Color.clear + .overlay(Image(nsImage: art) + .resizable() + .interpolation(.high) + .aspectRatio(contentMode: .fill)) + .clipped() + } + LinearGradient(colors: [.black.opacity(0.8), .black.opacity(0.5)], startPoint: .leading, endPoint: .trailing) + // A little more shade at the bottom, under the hints. + VStack(spacing: 0) { + Spacer(minLength: 0) + LinearGradient(colors: [.black.opacity(0), .black.opacity(0.45)], startPoint: .top, endPoint: .bottom) + .frame(height: canvas.u(240)) + } + } + .ignoresSafeArea() + // Swallows clicks so the page underneath never takes them. + .contentShape(Rectangle()) + .onTapGesture {} + } + + /// The logo, then the newest unlocked icons (look only, no focus stop); no strip before the first unlock. + private var header: some View { + let recent = summary.recentUnlockedIcons(limit: Self.recentLimit) + return VStack(alignment: .leading, spacing: canvas.u(24)) { + Group { + if let logo = logos.logo(for: "\(game.id)|\(picks.revision)") { + Image(nsImage: logo) + .resizable() + .interpolation(.high) + .aspectRatio(contentMode: .fit) + .frame(maxWidth: canvas.u(520), maxHeight: canvas.u(130), alignment: .leading) + } else { + Text(game.name) + .seleneFont(40, .semibold) + .foregroundColor(SeleneTheme.ink) + .lineLimit(1) + } + } + .shadow(color: .black.opacity(0.4), radius: canvas.u(6)) + .accessibilityLabel(game.name) + + if !recent.isEmpty { + VStack(alignment: .leading, spacing: canvas.u(12)) { + Text(L10n.text("Recently unlocked")) + .seleneFont(19, .semibold) + .foregroundColor(SeleneTheme.ink90) + .accessibilityAddTraits(.isHeader) + HStack(spacing: canvas.u(14)) { + ForEach(Array(recent.enumerated()), id: \.offset) { _, icon in + AchievementIcon(appID: game.steamGame?.appID ?? 0, file: icon, size: 72) + } + } + } + } + } + } + + /// Arcane, Gold, Silver, Bronze with unlocked/total under each, as PS5 trophies, dimmed while not earned (only + /// Arcane until Steam's rarity arrives). Under them the gauge, as wide as the four trophies: the large + /// percentage, its bar and the count line, all starting at the first trophy's edge (layout "A, barra larga", + /// maintainer's choice, 16 Nov 2026). Arcane earned, the medallion instead. + @ViewBuilder + private var progress: some View { + if summary.isComplete { + medallion + } else { + TrophyColumn(minWidth: canvas.u(Self.fourTrophies), spacing: canvas.u(24)) { + board + gauge + } + } + } + + private var gauge: some View { + let fraction = summary.total > 0 ? Double(summary.unlocked) / Double(summary.total) : 0 + return VStack(alignment: .leading, spacing: 0) { + Text(Self.wholePercent(summary.percentComplete)) + .seleneFont(44, .semibold) + .monospacedDigit() + .foregroundColor(SeleneTheme.ink) + .lineLimit(1) + // As wide as the trophies above, the width `TrophyColumn` gives the gauge. + AchievementProgressBar(fraction: fraction, height: 4, track: SeleneTheme.ink25) + .frame(maxWidth: .infinity) + .padding(.top, canvas.u(4)) + // A long language wraps under the trophies rather than overflowing them. + countLineText(lines: 2) + .padding(.top, canvas.u(10)) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(L10n.format("Achievements: %d of %d", [summary.unlocked, summary.total])) + } + + /// The board's trophies, in canvas units. + private static let trophy: CGFloat = 64 + private static let trophySpacing: CGFloat = 26 + /// All four trophies' width: the gauge keeps it while only Arcane shows, so Arcane does not move when Steam's + /// rarity brings the other three. + private static let fourTrophies: CGFloat = 4 * trophy + 3 * trophySpacing + + private var board: some View { + let counts = summary.tierCounts + let tiers = summary.hasRarity ? AchievementTier.allCases : [.arcane] + return HStack(alignment: .top, spacing: canvas.u(Self.trophySpacing)) { + ForEach(tiers, id: \.self) { tier in + let count = counts[tier] ?? TierCount(unlocked: 0, total: 0) + VStack(spacing: canvas.u(6)) { + TierCrystal(tier: tier, size: Self.trophy, dimmed: count.unlocked == 0) + countText(count, size: 18) + } + .fixedSize() + .accessibilityElement(children: .ignore) + .accessibilityLabel(Self.tierLabel(tier, count)) + } + } + } + + /// Arcane earned (layout "B", the medallion, maintainer's choice, 16 Nov 2026): everything on one centred axis, + /// the orb on top, its name, the count line, and Gold, Silver and Bronze as small crystals with their counts. It + /// replaces the gauge and the board: "100%", a full bar and "1 / 1" would only repeat the orb. + private var medallion: some View { + VStack(spacing: 0) { + arcaneOrb + Text(AchievementTier.arcane.displayName()) + .seleneFont(40, .semibold) + .foregroundColor(SeleneTheme.ink) + .lineLimit(1) + .padding(.top, canvas.u(10)) + countLineText(lines: 1) + .padding(.top, canvas.u(4)) + if summary.hasRarity { + let counts = summary.tierCounts + HStack(spacing: canvas.u(24)) { + ForEach([AchievementTier.gold, .silver, .bronze], id: \.self) { tier in + let count = counts[tier] ?? TierCount(unlocked: 0, total: 0) + HStack(spacing: canvas.u(6)) { + TierCrystal(tier: tier, size: 28, dimmed: count.unlocked == 0) + countText(count, size: 16) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(Self.tierLabel(tier, count)) + } + } + .padding(.top, canvas.u(16)) + } + } + .fixedSize() + } + + /// The card's looping orb, large, coming to colour just after the screen opens and playing while it stays + /// open (still, in colour, with Reduce motion). The still orb without the video. + private var arcaneOrb: some View { + Group { + if let video = AchievementTier.arcane.videoURL { + ArcaneOrbVideo(url: video, active: arcaneLit, moves: !reduceMotion) + } else { + TierCrystal(tier: .arcane, size: 128) + } + } + .frame(width: canvas.u(128), height: canvas.u(128)) + .task { + // After the orb's first, grey state is drawn, so the change to colour is seen. + try? await Task.sleep(nanoseconds: 150_000_000) + arcaneLit = true + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(L10n.format("%@, every achievement unlocked", [AchievementTier.arcane.displayName()])) + } + + /// "36 / 36": the unlocked count bright, the total dimmer. + private func countText(_ count: TierCount, size: CGFloat) -> some View { + (Text("\(count.unlocked)").foregroundColor(SeleneTheme.ink) + + Text(" / \(count.total)").foregroundColor(SeleneTheme.ink75)) + .seleneFont(size, .semibold) + .monospacedDigit() + // Its own width, never a share of the crystal's: squeezed, "0 / 13" read "0…". + .fixedSize() + } + + /// The count line as the gauge and the medallion show it, in up to `lines` lines. + private func countLineText(lines: Int) -> some View { + Text(countLine) + .seleneFont(16) + .foregroundColor(SeleneTheme.ink75) + .monospacedDigit() + .lineLimit(lines) + .fixedSize(horizontal: false, vertical: true) + } + + /// "Gold, 3 of 12", for VoiceOver. + private static func tierLabel(_ tier: AchievementTier, _ count: TierCount) -> String { + L10n.format("%1$@, %2$d of %3$d", [tier.displayName(), count.unlocked, count.total]) + } + + /// "17 of 50 unlocked · last on 31 Jul 2026"; the count alone before the first unlock. + private var countLine: String { + if let last = summary.lastUnlockedAt { + return L10n.format("%1$d of %2$d unlocked · last on %3$@", + [summary.unlocked, summary.total, Self.date(last)]) + } + return L10n.format("%1$d of %2$d unlocked", [summary.unlocked, summary.total]) + } + + /// 34 → "34%" in the app's locale ("34 %" in French). + static func wholePercent(_ value: Int) -> String { + (Double(value) / 100).formatted(.percent.precision(.fractionLength(0)).locale(L10n.context.formatLocale)) + } + + /// The filters between the shoulder badges, as on Selene: LB and RB step through them (and take a click). + private var pills: some View { + HStack(spacing: canvas.u(12)) { + shoulder(.lb, L10n.text("Previous"), step: -1) + ForEach(AchievementFilter.allCases, id: \.self) { filter in + let selected = filter == state.filter + let count = summary.rows(filter).count + Button { onFilter(filter) } label: { + (Text(Self.title(filter)) + + Text(" \(count)").foregroundColor(selected ? SeleneTheme.onFocus.opacity(0.7) : SeleneTheme.ink60)) + .seleneFont(16, .semibold) + .monospacedDigit() + .foregroundColor(selected ? SeleneTheme.onFocus : SeleneTheme.ink90) + .padding(.horizontal, canvas.u(20)) + .padding(.vertical, canvas.u(8)) + .background(Capsule().fill(selected ? SeleneTheme.focus : SeleneTheme.ink15)) + } + .buttonStyle(.plain) + .accessibilityLabel("\(Self.title(filter)), \(count)") + .accessibilityAddTraits(selected ? .isSelected : []) + } + shoulder(.rb, L10n.text("Next"), step: 1) + } + .animation(SeleneTheme.quick, value: state.filter) + } + + private func shoulder(_ button: PromptButton, _ label: String, step: Int) -> some View { + Button { onShiftFilter(step) } label: { + SelenePromptBadge(button: button, height: 22) + .frame(minWidth: canvas.u(30), minHeight: canvas.u(36)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(label) + } + + static func title(_ filter: AchievementFilter) -> String { + switch filter { + case .all: return L10n.text("All") + case .unlocked: return L10n.text("Unlocked") + case .locked: return L10n.text("Locked") + } + } + + /// Order and Open share the bottom-right hints. Keep Order available even when the filter is empty. + private func listHints(hasRows: Bool) -> [HintItem] { + var hints = [HintItem(.y, Self.title(state.order)) { onCycleOrder() }] + if hasRows { hints.append(HintItem(.a, L10n.text("Open")) { onOpen() }) } + return hints + } + + static func title(_ order: AchievementOrder) -> String { + switch order { + case .default: return L10n.text("Default order") + case .rarest: return L10n.text("Rarest first") + case .commonest: return L10n.text("Most common first") + } + } + + /// "31 Jul 2026" in the app's locale. + static func date(_ date: Date) -> String { + date.formatted(.dateTime.day().month(.abbreviated).year().locale(L10n.context.formatLocale)) + } + + /// 4.5 → "4.5%" in the app's locale ("4,5 %" in French). + static func percent(_ value: Double) -> String { + (value / 100).formatted(.percent.precision(.fractionLength(1)).locale(L10n.context.formatLocale)) + } +} + +/// One achievement: icon, name and description; on the right its tier crystal with how many players have it, +/// and the unlock date (or Not unlocked). +private struct AchievementsScreenRow: View { + @Environment(\.seleneCanvas) private var canvas + @State private var hovered = false + + let row: AchievementRow + let appID: UInt32 + let focused: Bool + + var body: some View { + let radius = canvas.u(SeleneTheme.contentRadius) + let shape = RoundedRectangle(cornerRadius: radius, style: .continuous) + let unlocked = row.unlockedAt != nil + HStack(spacing: canvas.u(18)) { + AchievementIcon(appID: appID, file: row.icon, size: 64, dimmed: !unlocked, secret: row.isMasked) + VStack(alignment: .leading, spacing: canvas.u(4)) { + Text(row.name) + .seleneFont(18, .semibold) + .foregroundColor(unlocked ? SeleneTheme.ink : SeleneTheme.ink82) + .lineLimit(1) + Text(row.description) + .seleneFont(14) + .foregroundColor(SeleneTheme.ink60) + .lineLimit(2) + .truncationMode(.tail) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: canvas.u(16)) + // The tier with its crystal and how many players have it, the date under it. + VStack(alignment: .trailing, spacing: canvas.u(6)) { + if let tier = row.tier, let percent = row.percent { + HStack(spacing: canvas.u(6)) { + TierCrystal(tier: tier, size: 24, dimmed: !unlocked) + Text(tier.displayName()) + .foregroundColor(unlocked ? SeleneTheme.ink : SeleneTheme.ink75) + Text("· \(AchievementsScreen.percent(percent))") + .foregroundColor(SeleneTheme.ink60) + .monospacedDigit() + } + } + if let date = row.unlockedAt { + Label { + Text(AchievementsScreen.date(date)) + } icon: { + Image(systemName: "checkmark.circle.fill") + } + .labelStyle(.titleAndIcon) + .foregroundColor(SeleneTheme.ink82) + } else { + Text(L10n.text("Not unlocked")) + .foregroundColor(SeleneTheme.ink.opacity(0.45)) + } + } + .seleneFont(13, .semibold) + .lineLimit(1) + .fixedSize() + } + .padding(.horizontal, canvas.u(18)) + .frame(width: canvas.u(AchievementsScreen.listWidth), height: canvas.u(AchievementsScreen.rowHeight), alignment: .leading) + // The page's card surface: lightly tinted, a thin outline, a little lighter focused or under the pointer. + .background(shape.fill(SeleneTheme.ink.opacity(focused ? 0.10 : hovered ? 0.08 : 0.05))) + .overlay(shape.strokeBorder(hovered || focused ? SeleneTheme.ink25 : SeleneTheme.ink15, + lineWidth: max(1, canvas.u(1)))) + .seleneRowFocus(focused, radius: radius) + .contentShape(shape) + // Instant: the list scrolling under a still pointer flips rows in and out of hover, and an animation + // for each would pile up on the scroll. + .onHover { hovered = $0 } + .animation(SeleneTheme.quick, value: focused) + .accessibilityElement(children: .combine) + .accessibilityAddTraits(focused ? .isSelected : []) + } +} + +/// The one-column list, moved by its own offset (`ListScroll`) instead of a scroll view: the wheel and the +/// arrows glide the same offset, and only the lines in view (and a window's worth either side, for a glide) +/// are drawn. Observes the scroll alone, so a scroll frame redraws the list, not the screen. +private struct AchievementsList: View { + @Environment(\.seleneCanvas) private var canvas + @Environment(\.seleneReduceMotion) private var reduceMotion + @ObservedObject var scroll: ListScroll + /// Not observed: the list only reports its size to it. + let model: AchievementsScreenModel + let rows: [AchievementRow] + let focused: Int + let appID: UInt32 + let onFocus: (Int) -> Void + + private typealias Screen = AchievementsScreen + + private var layout: GridListLayout { + GridListLayout(columns: AchievementsScreenState.columns, rowHeight: canvas.u(Screen.rowHeight), + spacing: canvas.u(Screen.rowSpacing), topPad: canvas.u(Screen.ring), + bottomRoom: canvas.u(Screen.bottomRoom)) + } + + private var width: CGFloat { canvas.u(Screen.listWidth + Screen.ring * 2) } + + var body: some View { + GeometryReader { proxy in + let height = proxy.size.height + Group { + if rows.isEmpty { + Text(L10n.text("No achievements here yet.")) + .seleneFont(17) + .foregroundColor(SeleneTheme.ink60) + .padding(.top, canvas.u(20)) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } else { + content(height: height) + } + } + // A rapid reopen reuses the outgoing view at the same size, but the new model needs its layout. + .task(id: ObjectIdentifier(model)) { report(height) } + .onChange(of: height) { report($0) } + .onChange(of: canvas.scale) { _ in report(height) } + .onChange(of: reduceMotion) { _ in report(height) } + } + .frame(width: width) + } + + private func content(height: CGFloat) -> some View { + let layout = layout + let offset = scroll.state.offset + let lines = layout.visibleLines(count: rows.count, offset: offset, visible: height, buffer: height) + let indices = lines.map { ($0.lowerBound * layout.columns)..<min(($0.upperBound + 1) * layout.columns, rows.count) } + ?? 0..<0 + let pitch = canvas.u(Screen.listWidth) + return ZStack(alignment: .topLeading) { + ForEach(indices, id: \.self) { index in + let top = layout.top(of: index) + // Only rows inside the window take a click: one scrolled under the pills still sits there. + let inView = top + layout.rowHeight > offset && top < offset + height + AchievementsScreenRow(row: rows[index], appID: appID, focused: index == focused) + .id(rows[index].id) + .offset(x: canvas.u(Screen.ring) + CGFloat(index % layout.columns) * pitch, y: top) + .onTapGesture { onFocus(index) } + .allowsHitTesting(inView) + .transition(.identity) + } + } + .frame(width: width, height: height, alignment: .topLeading) + // Rows made, and icons arriving, during a glide ride it with the rest (`GlideGroup`). + .modifier(GlideGroup()) + .offset(y: -offset) + .frame(width: width, height: height, alignment: .topLeading) + .clipped() + // The rows fade out above the hints bar, gone before its buttons, and at the top once the list has + // scrolled: no row sits under a button. No chevrons (maintainer's choice): the fades alone say there is more. + .mask(mask(atTop: scroll.state.atTop)) + .contentShape(Path(CGRect(x: 0, y: 0, width: width, + height: max(0, height - canvas.u(Screen.hintsBand))))) + } + + /// Opaque in the middle; the top fades only once rows have scrolled past it; the bottom always fades out, + /// to nothing by the hints bar's band (at 0.15 the rows showed through the buttons). + private func mask(atTop: Bool) -> some View { + VStack(spacing: 0) { + LinearGradient(colors: [.black.opacity(atTop ? 1 : 0), .black], startPoint: .top, endPoint: .bottom) + .frame(height: canvas.u(Screen.topFade)) + .animation(.easeInOut(duration: 0.3), value: atTop) + Color.black + LinearGradient(colors: [.black, .black.opacity(0)], startPoint: .top, endPoint: .bottom) + .frame(height: canvas.u(Screen.bottomFade)) + Color.clear + .frame(height: canvas.u(Screen.hintsBand)) + } + } + + /// The focused row keeps the top fade and a little more above it, and the bottom room below. + private func report(_ height: CGFloat) { + model.setLayout(layout, visible: height, above: canvas.u(Screen.topFade + 12), + below: canvas.u(Screen.bottomRoom), animates: !reduceMotion) + } +} + +/// The trophies, then the gauge under them: the first view sets the column's width (at least `minWidth`) and every +/// view below is offered that width, left-aligned. A `VStack` would take the widest line's width instead, so a long +/// count line would push the trophies off their place. +private struct TrophyColumn: Layout { + var minWidth: CGFloat + var spacing: CGFloat + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let width = columnWidth(subviews) + let heights = subviews.map { $0.sizeThatFits(ProposedViewSize(width: width, height: nil)).height } + return CGSize(width: width, height: heights.reduce(0, +) + spacing * CGFloat(max(0, subviews.count - 1))) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let offer = ProposedViewSize(width: columnWidth(subviews), height: nil) + var y = bounds.minY + for view in subviews { + view.place(at: CGPoint(x: bounds.minX, y: y), anchor: .topLeading, proposal: offer) + y += view.sizeThatFits(offer).height + spacing + } + } + + private func columnWidth(_ subviews: Subviews) -> CGFloat { + max(minWidth, subviews.first?.sizeThatFits(.unspecified).width ?? 0) + } +} diff --git a/Sources/NXLibrary/Views/Spotlight/ArcaneOrbVideo.swift b/Sources/NXLibrary/Views/Spotlight/ArcaneOrbVideo.swift new file mode 100644 index 00000000..f24486e8 --- /dev/null +++ b/Sources/NXLibrary/Views/Spotlight/ArcaneOrbVideo.swift @@ -0,0 +1,217 @@ +import SwiftUI +import AppKit +import AVFoundation +import NXLibraryCore + +/// The Arcane orb as the maintainer's looping video (`AchievementTier.videoURL`, 16 Nov 2026), for the achievements +/// card and, always active, the earned Arcane on the Achievements screen. At rest it is the current frame in grey; +/// active (hover or focus) it comes to colour and plays; inactive again it stops on its frame and greys. The next +/// appearance, on any page, resumes from that frame. +/// +/// The video is decoded by the media engine (AVPlayerLayer); grey ↔ colour, light and scale are Core Animation +/// on the layer, run by the render server, so the change stays smooth while the app is busy. Nothing plays while +/// the card is inactive, with Reduce motion, or while the app is in the background, and the player exists only +/// while the card is on screen. +struct ArcaneOrbVideo: NSViewRepresentable { + let url: URL + /// Hovered or focused. + let active: Bool + /// Motion allowed (the card's `moves`): playback and the scale; otherwise only colour and light change. + let moves: Bool + + func makeNSView(context: Context) -> ArcaneOrbView { ArcaneOrbView(url: url) } + + func updateNSView(_ view: ArcaneOrbView, context: Context) { + view.update(active: active, moves: moves) + } + + static func dismantleNSView(_ view: ArcaneOrbView, coordinator: ()) { view.tearDown() } +} + +final class ArcaneOrbView: NSView { + /// Where the orb last stopped, shared by every card for the app's life. + private static var resume: CMTime = .zero + + /// Layers: `orb` carries the grey filter and the light, and is never transformed; the video inside it carries the + /// scale. Any scale on or above the filtered layer made the end of the shrink jump (maintainer's checks, + /// 16 Nov 2026: gone with the scale off, still there with it on a parent): macOS draws a transformed filtered + /// layer one way and an untransformed one another. Scaled inside, the video is only content changing under a + /// still filter, as when it plays and stops. + private let orb = CALayer() + /// The video's growth when the card is active; `orb` is this much larger than the video, so it never clips. + private static let grow: CGFloat = 1.06 + private let playerLayer = AVPlayerLayer() + private let player = AVQueuePlayer() + private var looper: AVPlayerLooper? + private var readyObservation: NSKeyValueObservation? + private var observers: [NSObjectProtocol] = [] + private var state: (active: Bool, moves: Bool)? + private var playing = false + private var revealing = false + + /// The card's reveal: slow and soft, never past its target; with Reduce motion, Selene's quick change. + private static let reveal = CAMediaTimingFunction(controlPoints: 0.22, 1, 0.36, 1) + private static let toneKey = "filters.tone.inputSaturation" + /// Playback speed (maintainer's choice, 16 Nov 2026): faster than recorded feels more alive and fluid; + /// 1.7× was a touch too quick, 1.5× kept. + static let speed: Float = 1.5 + + init(url: URL) { + super.init(frame: .zero) + // Layer-hosting (the layer set before `wantsLayer`): this view owns its layer tree, as AppKit requires + // for sublayers and filters it adds itself. + layer = CALayer() + wantsLayer = true + layerUsesCoreImageFilters = true + + let tone = CIFilter(name: "CIColorControls")! + tone.setDefaults() + tone.name = "tone" + tone.setValue(0, forKey: kCIInputSaturationKey) + orb.filters = [tone] + orb.opacity = 0.88 + + playerLayer.player = player + playerLayer.videoGravity = .resizeAspect + // Hidden until the first frame is decoded, then faded in: never an empty or black square. + playerLayer.opacity = 0 + orb.addSublayer(playerLayer) + layer?.addSublayer(orb) + applyBackingScale() + + player.isMuted = true + player.preventsDisplaySleepDuringVideoPlayback = false + player.defaultRate = Self.speed + player.actionAtItemEnd = .advance + let item = AVPlayerItem(asset: AVURLAsset(url: url)) + looper = AVPlayerLooper(player: player, templateItem: item) + + readyObservation = playerLayer.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weak self] layer, _ in + guard layer.isReadyForDisplay else { return } + DispatchQueue.main.async { self?.resumeThenReveal() } + } + let center = NotificationCenter.default + for name in [NSApplication.didResignActiveNotification, NSApplication.didBecomeActiveNotification] { + observers.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.syncPlayback() } + }) + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } + + /// Pointer and clicks belong to the card around the orb. + override func hitTest(_ point: NSPoint) -> NSView? { nil } + + override func layout() { + super.layout() + // A square of whole pixels in the middle: SwiftUI may give 68.5 × 68 points, and the square video was then + // fitted a quarter point off its layer. + let scale = window?.backingScaleFactor ?? NSScreen.main?.backingScaleFactor ?? 2 + let side = (min(bounds.width, bounds.height) * scale).rounded(.down) / scale + // Whole pixels of room on each side for the growth, so the video stays centred on the pixel grid. + let margin = (side * (Self.grow - 1) / 2 * scale).rounded(.up) / scale + 1 / scale + let room = side + 2 * margin + CATransaction.begin(); CATransaction.setDisableActions(true) + orb.bounds = CGRect(x: 0, y: 0, width: room, height: room) + orb.position = CGPoint(x: bounds.midX, y: bounds.midY) + playerLayer.bounds = CGRect(x: 0, y: 0, width: side, height: side) + playerLayer.position = CGPoint(x: room / 2, y: room / 2) + CATransaction.commit() + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + applyBackingScale() + needsLayout = true + } + + override func viewDidChangeBackingProperties() { + super.viewDidChangeBackingProperties() + applyBackingScale() + needsLayout = true + } + + /// AppKit leaves a layer-hosting view's layers at 1x: their pixel density follows the window's (Retina) here. + private func applyBackingScale() { + let scale = window?.backingScaleFactor ?? NSScreen.main?.backingScaleFactor ?? 2 + CATransaction.begin(); CATransaction.setDisableActions(true) + for layer in [layer, orb, playerLayer].compactMap({ $0 }) { layer.contentsScale = scale } + CATransaction.commit() + } + + func update(active: Bool, moves: Bool) { + let previous = state + guard previous?.active != active || previous?.moves != moves else { return } + state = (active, moves) + let duration: CFTimeInterval = moves ? 0.45 : 0.18 + // The first state is set as it is; later ones animate from where the layer is now, so an + // interrupted change blends towards the new end instead of jumping. + let animated = previous != nil + set(Self.toneKey, on: orb, to: active ? 1 : 0, duration: duration, animated: animated) + set("opacity", on: orb, to: active ? 1 : 0.88, duration: duration, animated: animated) + set("transform.scale", on: playerLayer, to: active && moves ? Self.grow : 1, duration: duration, animated: animated) + syncPlayback() + } + + func tearDown() { + pause() + readyObservation?.invalidate(); readyObservation = nil + observers.forEach(NotificationCenter.default.removeObserver) + observers.removeAll() + looper?.disableLooping(); looper = nil + player.removeAllItems() + } + + private func set(_ keyPath: String, on target: CALayer, to value: CGFloat, duration: CFTimeInterval, animated: Bool) { + let from = (target.presentation() ?? target).value(forKeyPath: keyPath) + CATransaction.begin(); CATransaction.setDisableActions(true) + target.setValue(value, forKeyPath: keyPath) + CATransaction.commit() + guard animated, let from else { return } + let animation = CABasicAnimation(keyPath: keyPath) + animation.fromValue = from + animation.toValue = value + animation.duration = duration + animation.timingFunction = Self.reveal + target.add(animation, forKey: keyPath) + } + + /// Once the first frame is ready, move to where the orb last stopped (exactly, a seek before then may be + /// dropped), then fade it in: the jump from the first frame is never seen. + private func resumeThenReveal() { + guard !revealing else { return } + revealing = true + let target = Self.resume + guard target > .zero else { return reveal() } + player.seek(to: target, toleranceBefore: .zero, toleranceAfter: .zero) { [weak self] _ in + DispatchQueue.main.async { self?.reveal() } + } + } + + private func reveal() { + guard playerLayer.opacity == 0 else { return } + CATransaction.begin(); CATransaction.setDisableActions(true) + playerLayer.opacity = 1 + CATransaction.commit() + let fade = CABasicAnimation(keyPath: "opacity") + fade.fromValue = 0; fade.toValue = 1; fade.duration = 0.18 + fade.timingFunction = Self.reveal + playerLayer.add(fade, forKey: "reveal") + } + + /// Plays only while active, with motion allowed, and with the app in front. + private func syncPlayback() { + let wanted = (state?.active ?? false) && (state?.moves ?? false) && NSApp.isActive + guard wanted != playing else { return } + if wanted { playing = true; player.play() } else { pause() } + } + + private func pause() { + guard playing else { return } + playing = false + player.pause() + Self.resume = player.currentTime() + } +} diff --git a/Sources/NXLibrary/Views/Spotlight/GameArtLoader+Played.swift b/Sources/NXLibrary/Views/Spotlight/GameArtLoader+Played.swift new file mode 100644 index 00000000..abcb4547 --- /dev/null +++ b/Sources/NXLibrary/Views/Spotlight/GameArtLoader+Played.swift @@ -0,0 +1,83 @@ +import AppKit +import NXLibraryCore + +/// Art for a `PlayedGame`: an nxnative game's through the loader's own lookups, a Steam game's through the same +/// picks and automatic choices its pages use, decoded at the same sizes. Steam art is cached under the player's +/// pick revision, so a new pick is read the next time. +extension GameArtLoader { + func cachedHero(for game: PlayedGame) -> NSImage? { + switch game { + case .nxnative(let game): return cachedHero(for: game) + case .steam(let game): return steamArt.object(forKey: Self.steamKey(game, .hero)) + } + } + + func cachedLogo(for game: PlayedGame) -> NSImage? { + switch game { + case .nxnative(let game): return cachedLogo(for: game) + case .steam(let game): return steamArt.object(forKey: Self.steamKey(game, .logo)) + } + } + + func hero(for game: PlayedGame, metadata: NintendoStoreMetadata?, artwork: ArtworkStore, + personalizations: CatalogPersonalizations) async -> NSImage? { + switch game { + case .nxnative(let game): + return await hero(for: game, metadata: metadata, artwork: artwork, personalizations: personalizations) + case .steam(let game): + if let cached = cachedHero(for: .steam(game)) { return cached } + let key = Self.steamKey(game, .hero) + guard let url = await Self.steamHeroURL(for: game, artwork: artwork), + let image = await Self.decodeHero(at: url) else { return nil } + steamArt.setObject(image, forKey: key) + return image + } + } + + func logo(for game: PlayedGame, metadata: NintendoStoreMetadata?, artwork: ArtworkStore, + personalizations: CatalogPersonalizations) async -> NSImage? { + switch game { + case .nxnative(let game): + return await logo(for: game, metadata: metadata, artwork: artwork, personalizations: personalizations) + case .steam(let game): + if let cached = cachedLogo(for: .steam(game)) { return cached } + let key = Self.steamKey(game, .logo) + guard let url = await Self.steamLogoURL(for: game), + let image = await Self.decodeLogo(at: url) else { return nil } + steamArt.setObject(image, forKey: key) + return image + } + } + + /// A Steam game's hero: the player's pick, else the automatic choice kept from last time, else a new one + /// (`SteamBackdropChoice`: screen-shaped store art, LaunchBox's PC fan art, then the first screenshot, the + /// library banner last). + static func steamHeroURL(for game: CatalogGame, artwork: ArtworkStore) async -> URL? { + let request = SteamArtworkRequest(game: game, role: .hero) + let titleKey = game.personalizationReference.key + if let url = request.localURL(picks: SteamPersonalizations.shared.artwork) + ?? artwork.cachedURL(titleID: titleKey, kind: .hero) { return url } + guard let id = request.appID else { return nil } + await SteamGameFacts.shared.load(game, language: L10n.context.language) + let shots = SteamGameFacts.shared.metadata(for: game)?.screenshots ?? [] + let banner = SteamStoreArt.candidates(appID: Int(id), slot: .background).first?.url + let store = await SteamBackdropChoice.storeArt(names: [game.name]) + let order = SteamBackdropChoice.ordered(storeArt: store, screenshots: shots, libraryHero: banner) + guard let chosen = await SteamBackdropChoice.choose(order, fallback: banner, + data: { await SteamBackdropChoice.download($0) }), + !Task.isCancelled else { return nil } + return await artwork.fetch(titleID: titleKey, remoteURL: chosen, kind: .hero) + } + + /// A Steam game's logo: the player's pick, else the store's, as its pages show it. + static func steamLogoURL(for game: CatalogGame) async -> URL? { + let request = SteamArtworkRequest(game: game, role: .logo) + if let local = request.localURL(picks: SteamPersonalizations.shared.artwork) { return local } + guard let id = game.steamGame?.appID else { return nil } + return await SteamMetadataService.shared.image(appID: id, slot: .logo, remote: nil) + } + + private static func steamKey(_ game: CatalogGame, _ role: LibraryArtworkRole) -> NSString { + "\(game.id.uuidString)|\(role.rawValue)|\(SteamPersonalizations.shared.artwork.revision)" as NSString + } +} diff --git a/Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift b/Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift index 95fea85a..db63baed 100644 --- a/Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift +++ b/Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift @@ -11,12 +11,15 @@ final class GameArtLoader { private let heroes = NSCache<NSUUID, NSImage>() private let logos = NSCache<NSUUID, NSImage>() + /// Steam games' launch-screen and session-card art, by game, role and pick revision (`GameArtLoader+Played`). + let steamArt = NSCache<NSString, NSImage>() /// Games already looked up online this launch, found or not. private var searchedOnline: Set<UUID> = [] private init() { heroes.countLimit = 24 logos.countLimit = 64 + steamArt.countLimit = 16 } func cachedHero(for game: PortedGame) -> NSImage? { heroes.object(forKey: game.id as NSUUID) } @@ -30,9 +33,9 @@ final class GameArtLoader { /// The player's pick, local hero files, the disk cache, then the store / /// titledb banner. - func hero(for game: PortedGame, metadata: NintendoStoreMetadata?, artwork: ArtworkStore) async -> NSImage? { + func hero(for game: PortedGame, metadata: NintendoStoreMetadata?, artwork: ArtworkStore, personalizations: CatalogPersonalizations) async -> NSImage? { if let cached = cachedHero(for: game) { return cached } - let titleKey = game.titleId ?? game.uniqueKey + let titleKey = personalizations.nxnativeKey(for: game) var image: NSImage? if let picked = ArtworkPicks.shared.url(titleID: titleKey, slot: .background) { @@ -71,9 +74,9 @@ final class GameArtLoader { /// The player's pick, the disk cache, a local logo.png, the store logo then /// the online sources' logos in their order (Steam, GOG, TheGamesDB, /// Wikidata, Commons, the fan wikis). - func logo(for game: PortedGame, metadata: NintendoStoreMetadata?, artwork: ArtworkStore) async -> NSImage? { + func logo(for game: PortedGame, metadata: NintendoStoreMetadata?, artwork: ArtworkStore, personalizations: CatalogPersonalizations) async -> NSImage? { if let cached = cachedLogo(for: game) { return cached } - let titleKey = game.titleId ?? game.uniqueKey + let titleKey = personalizations.nxnativeKey(for: game) var image: NSImage? // Every read and decode runs off the main thread (`decodeLogo`); a @@ -100,7 +103,8 @@ final class GameArtLoader { } if image == nil, !Task.isCancelled, searchedOnline.insert(game.id).inserted { let names = [game.name, metadata?.name].compactMap { $0 } - let found = await OnlineArtwork.find(names: names, slot: .logo) + let found = await OnlineArtwork.find(names: names, slot: .logo, + platform: game.isSwitch2 ? .switch2 : .switch) for remote in found.flatMap({ [$0.url, $0.fallback] }) where image == nil && !Task.isCancelled { if let url = await artwork.fetch(titleID: titleKey, remoteURL: remote, kind: .logo) { image = await Self.decodeLogo(at: url) diff --git a/Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift b/Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift index 4153d78b..8e6688cf 100644 --- a/Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift +++ b/Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift @@ -8,6 +8,8 @@ import NXLibraryCore /// crossfading on change, and the left, bottom and top shades at 0.3 scaled by /// the Background shade setting. Shared by Spotlight and Collection. struct SeleneArtBackground: View { + @Environment(\.seleneBackdropStyle) private var style + @Environment(\.seleneSharesBackdrop) private var sharesBackdrop let image: NSImage? /// Changes whenever `image` does; drives the crossfade. let imageKey: String @@ -19,15 +21,26 @@ struct SeleneArtBackground: View { var showsArt = true /// The Mods card: no art, the moonlight turns gold (`SeleneBackdrop.modsTint`). var modsTint = false + /// Spotlight's entrance (`SpotlightEntrance`): the game's art hidden until the flight, then rising over the + /// moonlight, which keeps moving until the art is in. + var reveal: ArtReveal = .shown private var art: NSImage? { showsArt ? image : nil } + /// The entrance's background rise (`SpotlightEntrance.backgroundDuration`) on the crossfade's curve + /// (`OpacityFade`), the art layer's own: soft at both ends, as when moving between games. + static let rise = Animation.timingCurve(Double(OpacityFade.controlPoints.0), Double(OpacityFade.controlPoints.1), + Double(OpacityFade.controlPoints.2), Double(OpacityFade.controlPoints.3), + duration: SpotlightEntrance.backgroundDuration) + var body: some View { ZStack { - // Under a game's art the moonlight is hidden: it holds still (Selene fades it out there). - backdrop.still(art != nil).modsTint(modsTint) + if !sharesBackdrop { Color(hex: style.palette.scrim) } + // Under a game's art the moonlight is hidden: it holds still (Selene fades it out there). While the art + // rises it keeps moving, so nothing shows through still. + backdrop.still(art != nil && reveal == .shown).modsTint(modsTint) // A crossfade is not movement: it stays under reduce motion (spec §8). - SeleneArtLayer(image: art, key: art == nil ? "none" : imageKey, crossfade: crossfade) + SeleneArtLayer(image: art, key: art == nil ? "none" : imageKey, crossfade: crossfade, reveal: reveal) SeleneShades(shade: shade) } .allowsHitTesting(false) @@ -38,8 +51,9 @@ struct SeleneArtBackground: View { /// The home's left, bottom and top shades at 0.3 scaled by the Background shade /// setting, in the palette's scrim colour. The Theme screen's preview takes the same. struct SeleneShades: View { + @Environment(\.seleneBackdropStyle) private var style var shade: BackgroundShade = .balanced - var scrim: Color = SeleneTheme.scrim + var scrim: Color? = nil var body: some View { let k = 0.3 * shade.scrimMultiplier @@ -58,10 +72,15 @@ struct SeleneShades: View { /// A scrim stop: Selene's opacity-mask alpha times the shade's opacity. private func stop(_ mask: Double, _ opacity: Double, at location: CGFloat) -> Gradient.Stop { - .init(color: scrim.opacity(min(1, mask * opacity)), location: location) + .init(color: (scrim ?? Color(hex: style.palette.scrim)).opacity(min(1, mask * opacity)), location: location) } } +/// How the art layer shows as a whole: hidden under a cover, fading up with Spotlight's entrance, or shown. +enum ArtReveal: Equatable { + case hidden, rising, shown +} + /// The art as one Core Animation layer: a change dissolves old into new in the render server, so the crossfade /// never dips through to the moonlight halfway (both images half faded) and never stutters while the main thread /// is busy (a page building, a store opening). No SwiftUI work per frame. @@ -70,10 +89,12 @@ struct SeleneArtLayer: NSViewRepresentable { /// Changes whenever `image` does; "none" without art. let key: String let crossfade: Double + var reveal: ArtReveal = .shown func makeNSView(context: Context) -> SeleneArtLayerView { SeleneArtLayerView() } func updateNSView(_ view: SeleneArtLayerView, context: Context) { + view.reveal(reveal) view.show(image, key: key, crossfade: crossfade) } } @@ -88,6 +109,9 @@ final class SeleneArtLayerView: NSView { /// Animation, which has no presentation for a layer added in the pass still open. private var fades: [ObjectIdentifier: OpacityFade] = [:] private var key: String? + private var revealed = ArtReveal.shown + /// Held for Spotlight's entrance once: the first art then fades in too, even when it arrives after the rise. + private var heldOnce = false init() { super.init(frame: .zero) @@ -109,11 +133,34 @@ final class SeleneArtLayerView: NSView { CATransaction.commit() } + /// The whole art layer, apart from each image's crossfade: the entrance's slow rise from hidden on the crossfade's + /// curve, in the render server so a busy main thread never holds it; shown (landing) ends a rise at once. + func reveal(_ reveal: ArtReveal) { + if reveal == .hidden { heldOnce = true } + guard reveal != revealed, let layer else { return } + let from = revealed + revealed = reveal + CATransaction.begin() + CATransaction.setDisableActions(true) + layer.removeAnimation(forKey: "entrance") + layer.opacity = reveal == .hidden ? 0 : 1 + if reveal == .rising, from == .hidden { + let rise = CABasicAnimation(keyPath: "opacity") + rise.fromValue = 0 + rise.toValue = 1 + rise.duration = SpotlightEntrance.backgroundDuration + let (x1, y1, x2, y2) = OpacityFade.controlPoints + rise.timingFunction = CAMediaTimingFunction(controlPoints: x1, y1, x2, y2) + layer.add(rise, forKey: "entrance") + } + CATransaction.commit() + } + func show(_ image: NSImage?, key: String, crossfade: Double) { guard key != self.key else { return } let first = self.key == nil self.key = key - let duration = first ? 0 : crossfade + let duration = first && !heldOnce ? 0 : crossfade let now = CACurrentMediaTime() let cg = image?.cgImage(forProposedRect: nil, context: nil, hints: nil) let interrupted = stack.filter { fades[ObjectIdentifier($0)].map { !$0.isDone(at: now) } ?? false }.count diff --git a/Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift b/Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift index e7db59b3..dccd699c 100644 --- a/Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift +++ b/Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift @@ -34,7 +34,7 @@ final class SeleneHeroArt: ObservableObject { /// `current` re-reads the screen's selected game after each await. /// `settle` is the pause before loading; Collection waits longer so its logo leads. func loadHero(game: PortedGame?, current: () -> UUID?, metadata: NintendoStoreMetadata?, - artwork: ArtworkStore, + artwork: ArtworkStore, personalizations: CatalogPersonalizations, settle: UInt64 = 150_000_000, keepsWithoutGame: Bool = false) async { guard let game else { // Spotlight keeps the last game's art over a card, so coming back to that game needs no reload. @@ -50,19 +50,45 @@ final class SeleneHeroArt: ObservableObject { try? await Task.sleep(nanoseconds: settle) guard !Task.isCancelled else { return } let loaded = await GameArtLoader.shared.hero( - for: game, metadata: metadata, artwork: artwork) + for: game, metadata: metadata, artwork: artwork, personalizations: personalizations) + guard !Task.isCancelled, current() == game.id else { return } + image = loaded + key = loaded.map { loadedFor + "\(ObjectIdentifier($0).hashValue)" } ?? "none" + } + + func steamHeroTaskKey(_ game: CatalogGame?) -> String { + guard let game, game.integration == .steam else { return "none" } + return "steam-hero|\(game.id)|\(SteamPersonalizations.shared.artwork.revision)" + } + + /// A Steam game's hero through the same image, key and crossfade as an nxnative one: the + /// player's pick, else the automatic choice kept from last time, else a new one (`SteamBackdropChoice`: + /// screen-shaped store art, LaunchBox's PC fan art, then the first screenshot, the library banner last). No game (or an + /// nxnative one) leaves the image to `loadHero`. + func loadSteamHero(game: CatalogGame?, current: () -> UUID?, artwork: ArtworkStore, + settle: UInt64 = 150_000_000) async { + guard let game, game.integration == .steam else { return } + let picks = SteamPersonalizations.shared.artwork + let loadedFor = "\(game.id.uuidString)|s\(picks.revision)|" + if key.hasPrefix(loadedFor) { return } + try? await Task.sleep(nanoseconds: settle) + guard !Task.isCancelled else { return } + let url = await GameArtLoader.steamHeroURL(for: game, artwork: artwork) + guard !Task.isCancelled else { return } + // Decoded off the main thread like an nxnative hero; a lazily decoded file cost its first frame 40–60 ms. + let loaded: NSImage? = if let url { await GameArtLoader.decodeHero(at: url) } else { nil } guard !Task.isCancelled, current() == game.id else { return } image = loaded key = loaded.map { loadedFor + "\(ObjectIdentifier($0).hashValue)" } ?? "none" } func loadLogo(game: PortedGame?, metadata: NintendoStoreMetadata?, - artwork: ArtworkStore) async { + artwork: ArtworkStore, personalizations: CatalogPersonalizations) async { guard let game, GameArtLoader.shared.cachedLogo(for: game) == nil else { return } try? await Task.sleep(nanoseconds: 150_000_000) guard !Task.isCancelled else { return } let loaded = await GameArtLoader.shared.logo( - for: game, metadata: metadata, artwork: artwork) + for: game, metadata: metadata, artwork: artwork, personalizations: personalizations) guard loaded != nil, !Task.isCancelled else { return } withAnimation(.easeOut(duration: 0.3)) { logoTick += 1 } } diff --git a/Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift b/Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift index f6aeef31..de0f1d7d 100644 --- a/Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift +++ b/Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift @@ -36,7 +36,7 @@ struct SpotlightGameInfoView: View { var body: some View { VStack(alignment: .leading, spacing: 0) { logoArea - .offset(x: slid ? 0 : canvas.u(-30)) + .offset(x: slid ? 0 : canvas.u(Self.logoSlideDistance)) .opacity(shown ? 1 : 0) Group { if isRunning { @@ -76,29 +76,7 @@ struct SpotlightGameInfoView: View { } private var logoArea: some View { - ZStack(alignment: .bottomLeading) { - if let logo { - Image(nsImage: logo) - .resizable() - .interpolation(.high) - .aspectRatio(contentMode: .fit) - // The logo box: 700 × 240 (195 plus a −45 top margin), bottom-left. - .frame(width: canvas.u(700), height: canvas.u(240), alignment: .bottomLeading) - .shadow(color: .black.opacity(0.35), radius: canvas.u(8)) - .transition(.opacity) - } else { - Text(game.name) - .seleneFont(56) - .foregroundColor(SeleneTheme.ink) - .lineLimit(1) - .truncationMode(.tail) - .shadow(color: .black.opacity(0.45), radius: canvas.u(6)) - } - } - .frame(width: canvas.u(900), height: canvas.u(195), alignment: .bottomLeading) - .accessibilityElement(children: .ignore) - .accessibilityLabel(game.name) - .accessibilityAddTraits(.isHeader) + GameLogoArea(title: game.name, logo: logo) } /// The time left while porting, or the last failure over a working app. @@ -155,16 +133,11 @@ struct SpotlightGameInfoView: View { } private var normalPills: some View { - HStack(spacing: canvas.u(14)) { - pill(0, SelenePillButton(title: primaryTitle, height: 52, focused: focusedPill == 0, - enabled: isRunning || pillSet.unavailableReason == nil) { onPill(0) }) - pill(1, SelenePillButton(title: isRunning ? L10n.text("Close Game") : L10n.text("Options"), height: 52, - focused: focusedPill == 1) { onPill(1) }) - pill(2, SelenePillButton(title: nil, icon: game.isFavorite ? .favorite : .favoriteBorder, - iconSize: 20, minWidth: 52, height: 52, horizontalPadding: 0, - focused: focusedPill == 2) { onPill(2) }) - .accessibilityLabel(game.isFavorite ? L10n.text("Remove from favorites") : L10n.text("Add to favorites")) - } + GamePrimaryActions(primaryTitle: primaryTitle, + secondaryTitle: isRunning ? "Close Game" : "Options", + isFavorite: game.isFavorite, focused: focusedPill, + primaryEnabled: isRunning || pillSet.unavailableReason == nil, + onAction: onPill, onHover: onHoverPill) } private var primaryTitle: String { @@ -199,6 +172,10 @@ struct SpotlightGameInfoView: View { /// The pills and stats' fade after a change (the genres below come in with them, `SpotlightInfoFollow`). static let restMotion = Animation.easeOut(duration: 0.4).delay(0.42) + /// The logo's fade and slide after a change. A Steam game's head uses the same three motions. + static let logoFade = Animation.easeOut(duration: 0.45).delay(0.3) + static let logoSlide = SeleneTheme.cubicOut(0.55).delay(0.3) + static let logoSlideDistance: CGFloat = -30 /// Reduce motion keeps the fades and drops the slide. private func reveal() { @@ -210,10 +187,10 @@ struct SpotlightGameInfoView: View { slid = reduceMotion } DispatchQueue.main.async { - withAnimation(.easeOut(duration: 0.45).delay(0.3)) { shown = true } + withAnimation(Self.logoFade) { shown = true } withAnimation(Self.restMotion) { restShown = true } if !reduceMotion { - withAnimation(SeleneTheme.cubicOut(0.55).delay(0.3)) { slid = true } + withAnimation(Self.logoSlide) { slid = true } } } } diff --git a/Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift b/Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift index cd7b2698..47dabda5 100644 --- a/Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift +++ b/Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift @@ -3,11 +3,12 @@ import AppKit import NXLibraryCore /// What Spotlight's page needs below the stats: the game's details, -/// Build & Sources' actions and More like this. +/// the Details panel's rows and links, and More like this. struct SpotlightPageModel { let presentation: GameDetailPresentation - let rows: [BuildSourcesRow] - let more: [PortedGame] + let facts: [DetailsFact] + let links: [DetailsLink] + let more: [CatalogGame] /// The Metal gate refuses new builds. let buildBlocked: Bool } @@ -28,6 +29,14 @@ struct SpotlightBlockKey: PreferenceKey { } } +/// Whether About this game shows Read more, as drawn. Input reads this rather than cutting the text again: +/// the keyboard reaches Spotlight through a copy of the view made when the monitor was installed, whose +/// canvas can be an earlier window size, so its own cut could disagree with the one on screen. +struct SpotlightReadMoreKey: PreferenceKey { + static var defaultValue = false + static func reduce(value: inout Bool, nextValue: () -> Bool) { value = value || nextValue() } +} + extension View { /// Reports this view's height (apply after its top padding) under `block`. func spotlightBlock(_ block: SpotlightPageBlock) -> some View { @@ -62,7 +71,7 @@ struct SpotlightGenreChips: View { /// The store description under the screenshots, at least as tall as the /// column beside it (`excerpt`), with Read more for the rest. Read more takes -/// controller focus left of Build & Sources. +/// controller focus left of Details. struct SpotlightDescription: View { @Environment(\.seleneCanvas) private var canvas let text: String diff --git a/Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift b/Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift index 78a1f23e..fb754dbd 100644 --- a/Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift +++ b/Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift @@ -12,6 +12,7 @@ struct SpotlightRowView: View { let items: [SpotlightItem] let gamesByID: [UUID: PortedGame] + var catalogGamesByID: [UUID: CatalogGame] = [:] let selectedKey: String? /// The tile lifted for moving: raised 12u, its ring stays. var liftedKey: String? = nil @@ -21,6 +22,10 @@ struct SpotlightRowView: View { var tileLook: (PortedGame) -> PortingTileLook = { _ in .normal } /// Mods' art for the Mods card's face (up to four); empty draws Selene's own face. var modsCover: [URL] = [] + /// Spotlight's entrance (`SpotlightView+Entrance`): the tiles fly in from the centre while it plays. + var entrance: SpotlightEntrance.Phase = .landed + /// The flight is over: everything is in. + var onEntranceEnd: () -> Void = {} let onSelect: (SpotlightItem) -> Void let onActivate: (SpotlightItem) -> Void @@ -28,6 +33,7 @@ struct SpotlightRowView: View { @State private var titleTask: Task<Void, Never>? /// The tile last lifted for moving, while it is still the selection. @State private var lastLifted: String? + @State private var entranceEnd: Task<Void, Never>? static let pitch = SpotlightRowGeometry.pitch static let host = SpotlightRowGeometry.host @@ -47,11 +53,18 @@ struct SpotlightRowView: View { // While a tile is lifted, and after it is put down until the selection moves on, only it is grown: the // tiles it passes swap places under it at their own size. let alone = liftedKey != nil || (lastLifted != nil && lastLifted == selectedKey) + let flights = entranceFlights(window: window, position: position) + let launched = entrance == .playing || entrance == .landed ZStack(alignment: .topLeading) { ForEach(window.map { (index: $0, item: items[$0]) }, id: \.item.key) { entry in let index = entry.index, item = entry.item let isSelected = index == selected tile(item, selected: isSelected) + // Inside the glide: the tile grows about its own centre; the shift is undone by its own size. + .entrance(flights.isEmpty ? nil : flights[index - window.lowerBound], launched: launched, + unit: canvas.u(1), + outerScale: alone ? (isSelected ? SpotlightRowGeometry.grow : 1) + : SpotlightRowGeometry.scale(of: CGFloat(index), at: position)) .modifier(TileGlide(position: position, index: CGFloat(index), rise: item.key == liftedKey ? 3 - 12 : 3, grown: alone ? isSelected : nil, unit: canvas.u(1))) @@ -75,6 +88,8 @@ struct SpotlightRowView: View { if let isEmptyFilter { // Beside the last card, whatever the card count and selection, never over them. emptyMessage(isEmptyFilter) + .entrance(entrance == .landed ? nil : SpotlightEntrance.message(after: flights), + launched: launched, unit: canvas.u(1)) .offset(x: canvas.u(SpotlightRowGeometry.place(of: items.count, selected: selected) + 32), y: canvas.u(3 + Self.host / 2 - 26)) .transition(.opacity) @@ -98,7 +113,43 @@ struct SpotlightRowView: View { .onChange(of: liftedKey) { key in if let key { lastLifted = key } } - .onDisappear { titleTask?.cancel() } + .onChange(of: entrance) { phase in + entranceEnd?.cancel() + guard phase == .playing else { return } + scheduleTitle(delay: SpotlightEntrance.titleDelay) + let layout = currentLayout() + let end = SpotlightEntrance.end(of: entranceFlights(window: layout.window, position: layout.position)) + entranceEnd = Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(end * 1_000_000_000)) + guard !Task.isCancelled else { return } + onEntranceEnd() + } + } + .onDisappear { + titleTask?.cancel() + entranceEnd?.cancel() + } + } + + /// The visible tiles and the selection's glide position, as `body` works them out. + private func currentLayout() -> (window: Range<Int>, position: CGFloat) { + let selected = selectedKey.flatMap { key in items.firstIndex { $0.key == key } } + let offset = selected.map(SpotlightState.scrollOffset(selectedIndex:)) ?? 0 + return (visibleRange(offset: offset), selected.map { CGFloat($0) } ?? SpotlightRowGeometry.noSelection) + } + + /// The entrance's flight for each tile in `window`, in order, from where each one sits in the window (Selene + /// measures the row, which spans the window); empty once landed. + private func entranceFlights(window: Range<Int>, position: CGFloat) -> [SpotlightEntrance.Flight?] { + guard entrance != .landed else { return [] } + let unit = max(canvas.u(1), 0.0001) + let shift = SpotlightRowGeometry.camera(at: position) + canvas.stageOrigin.x / unit + let tiles = window.map { index -> ClosedRange<CGFloat> in + let i = CGFloat(index) + let x = SpotlightRowGeometry.place(of: i, at: position) + 1 + shift + return x...(x + Self.host * SpotlightRowGeometry.scale(of: i, at: position)) + } + return SpotlightEntrance.flights(tiles: tiles, rowWidth: canvas.size.width / unit) } /// Items from a few tiles left of the screen to a few past its right edge; tiles @@ -143,6 +194,10 @@ struct SpotlightRowView: View { .portingLook(tileLook(game), cornerRadius: canvas.u(12)) .frame(width: side, height: side) .clipShape(face) + } else if let game = catalogGamesByID[id] { + CatalogNativeArtwork(game: game, role: .square, look: PortingTileLook.make(catalog: game)) + .frame(width: side, height: side) + .clipShape(face) } case .card(.mods): ModsCardCover(urls: modsCover, side: side) @@ -160,6 +215,10 @@ struct SpotlightRowView: View { // snapped to the pixel grid on their own, so they shook against their tile in a quick run of presses. // The shine is a Core Animation layer and stays outside. .drawingGroup() + // So is a download's pulsing mark. + if case .game(let id) = item, gamesByID[id] == nil, let game = catalogGamesByID[id] { + PortingDownloadMark(look: PortingTileLook.make(catalog: game), width: side, height: side) + } SeleneShine(cornerRadius: canvas.u(12), active: selected) } .frame(width: side, height: side) @@ -169,7 +228,7 @@ struct SpotlightRowView: View { private func title(of item: SpotlightItem) -> String { switch item { case .card(let card): return card.title - case .game(let id): return gamesByID[id]?.name ?? "" + case .game(let id): return gamesByID[id]?.name ?? catalogGamesByID[id]?.name ?? "" } } diff --git a/Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift b/Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift new file mode 100644 index 00000000..78b125ab --- /dev/null +++ b/Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift @@ -0,0 +1,171 @@ +import SwiftUI +import NXLibraryCore + +/// Spotlight's entrance, the app's opening: the first time the home shows after launch (`SpotlightEntrance`, +/// Selene's flight at a calmer pace). While the welcome or Setup covers the screen, the row, the bar, the pill, +/// the info and the art stay hidden over a shared moving moonlight. Once the cover has gone, the entrance waits for the +/// breath on the moving moonlight and for the visible tiles' art (at most 1 s more), then the background fades in +/// slowly, the tiles fly in from the centre while they grow and the info rises; the top bar and the button hints come in last. +/// No key, click, wheel or controller press skips it (`Phase.takesInput`). Every later visit, Reduce motion and a +/// launch on another screen land it at once. +extension SpotlightView { + /// Drawn over Spotlight: the welcome until its fade has ended, or Setup (the first launch's pages come first). + var isOverlaid: Bool { viewModel.isWelcomeOpen || viewModel.showSetupCheck } + + /// Overlaid, or the window still taking its launch mode (a fullscreen transition would cut the flight). + var isCovered: Bool { isOverlaid || viewModel.isWindowSettling } + + /// What a held or not-yet-arrived piece shows: nothing to the eye (under half a step of 8 bits), but drawn. *Why:* + /// at opacity 0 a tile was first drawn the moment it appeared, its shadow, shine and app icon in one frame + /// (measured: SwiftUI's late frames fell exactly as tiles 5, 7 and 11 began). Drawn under the cover, the flight + /// only moves what is ready, as Selene flies a cached picture of each tile. + static let unseenOpacity = 0.001 + + /// The row while held: drawn, not seen (`unseenOpacity`); 0 off the row as before. + var rowOpacity: Double { + guard rowShown else { return 0 } + return entrance.holdsHidden ? Self.unseenOpacity : 1 + } + + /// The pieces' clocks run (`View.entrance`): from the start of the flight on. + var entranceLaunched: Bool { entrance == .playing || entrance == .landed } + + /// The pill comes up with the background as the flight starts; landing is instant. + var entranceRise: Animation? { + entrance == .playing ? SeleneArtBackground.rise : nil + } + + var artReveal: ArtReveal { + switch entrance { + case .covered, .waiting: return .hidden + case .playing: return .rising + case .landed: return .shown + } + } + + func entranceAppear() { + let enabled = settings.settings.introAnimation + let due = SpotlightEntrance.plays(isFirstHome: !viewModel.homeSeen, route: router.route, + reduceMotion: reduceMotion, enabled: enabled) + viewModel.homeSeen = true + guard due else { return landEntrance() } + if !isCovered { uncoverEntrance() } + } + + func uncoverEntrance() { + guard entrance == .covered else { return } + entrance.uncover() + entranceWait?.cancel() + // A breath on the moving moonlight, then the flight once the tiles' art is in (at most 1 s more). + entranceWait = Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(SpotlightEntrance.hold * 1_000_000_000)) + guard !Task.isCancelled else { return } + entranceBreathed = true + if pendingTileArt == 0 { return startEntrance() } + try? await Task.sleep(nanoseconds: 1_000_000_000) + guard !Task.isCancelled else { return } + startEntrance() + } + } + + /// The tiles' art look-ups (`TileArtPendingKey`); the last one to end starts a waiting entrance. + func tileArtPending(_ count: Int) { + guard entrance != .landed else { return } + pendingTileArt = count + if count == 0, entranceBreathed { startEntrance() } + } + + func startEntrance() { + guard entrance == .waiting else { return } + entranceWait?.cancel() + entrance.start() + // The row ends the flight (`onEntranceEnd`). Input waits for the landing, so a flight the row never + // ends must still land: well after the longest entrance (about 2.5 s), it finishes here. + entranceWait = Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(SpotlightEntrance.longestWait * 1_000_000_000)) + guard !Task.isCancelled else { return } + finishEntrance() + } + } + + /// Everything in its place at once, top bar and hints included, without animation: leaving, a resize mid-flight, Reduce + /// motion, or an entrance that is not due. + func landEntrance() { + land() + guard !controlsShown else { return } + var still = Transaction() + still.disablesAnimations = true + withTransaction(still) { controlsShown = true } + } + + /// The flight's end: everything is in place, then the top bar and the button hints fade in last, together. + func finishEntrance() { + land() + guard !controlsShown else { return } + withAnimation(.easeOut(duration: SpotlightEntrance.controlsFade)) { controlsShown = true } + } + + private func land() { + entranceWait?.cancel() + guard entrance != .landed else { return } + var still = Transaction() + still.disablesAnimations = true + withTransaction(still) { entrance.land() } + } +} + +extension View { + /// One piece of Spotlight's entrance: from `flight`'s start to its place once `launched`. Every piece's clock + /// starts at the flight's start and runs in real time, its delay counted inside (`EntranceFlight`): one start + /// for the whole entrance, not one per tile. *Why:* with one delayed animation per tile, SwiftUI's late frames + /// fell exactly as tiles 7, 8, 10, 13 and 20 began. Without a flight it is in its + /// place. `outerScale` is the scale an outer effect gives it (a grown tile), so the shift stays in stage units. + func entrance(_ flight: SpotlightEntrance.Flight?, launched: Bool, unit: CGFloat, + outerScale: CGFloat = 1) -> some View { + let end = flight.map { $0.delay + $0.length } ?? 0 + let time = launched ? end : 0 + return modifier(EntranceFlight(time: time, flight: flight, unit: unit, outerScale: outerScale)) + .modifier(EntranceFade(time: time, flight: flight)) + .animation(flight.map { _ in .linear(duration: end) }, value: launched) + } +} + +/// A piece scaled about its centre and shifted, from its flight's start to its place (`Flight.move`). +struct EntranceFlight: GeometryEffect { + /// Seconds since the entrance began (the piece's delay included). + var time: Double + let flight: SpotlightEntrance.Flight? + let unit: CGFloat + var outerScale: CGFloat = 1 + + var animatableData: Double { + get { time } + set { time = newValue } + } + + func effectValue(size: CGSize) -> ProjectionTransform { + guard let flight, !flight.fadesOnly else { return ProjectionTransform() } + let rest = 1 - flight.move(at: time - flight.delay) + let scale = 1 - (1 - flight.fromScale) * rest + let shift = unit * rest / max(outerScale, 0.01) + let cx = size.width / 2, cy = size.height / 2 + return ProjectionTransform(CGAffineTransform(translationX: cx + flight.fromX * shift, y: cy + flight.fromY * shift) + .scaledBy(x: scale, y: scale) + .translatedBy(x: -cx, y: -cy)) + } +} + +/// A piece's opacity on its flight's clock (`Flight.opacity`). +struct EntranceFade: ViewModifier, Animatable { + var time: Double + let flight: SpotlightEntrance.Flight? + + var animatableData: Double { + get { time } + set { time = newValue } + } + + func body(content: Content) -> some View { + content.opacity(flight.map { max(SpotlightView.unseenOpacity, $0.opacity(at: time - $0.delay)) } ?? 1) + } +} diff --git a/Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift b/Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift index 57452d5b..c13c4c56 100644 --- a/Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift +++ b/Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift @@ -5,7 +5,10 @@ import NXLibraryCore /// Spotlight's controller, keyboard and pointer input. extension SpotlightView { func handle(_ action: GamepadAction) { + // The entrance plays to its end: no press skips it or acts underneath. + guard entrance.takesInput else { return } if viewer != nil { return handleViewer(action) } + if achievementsScreen != nil { return handleAchievements(action) } if viewModel.spotlight.isLifted { return handleLifted(action) } if cardMenu != nil { return handleCardMenu(action) } if modsHost.isPanelOpen { return modsHost.handlePanel(action) } @@ -15,41 +18,45 @@ extension SpotlightView { // Y (the card's menu), X and the row's jumps belong to the row, not the store. if [.contextAction, .secondaryAction, .jumpToStart, .jumpToEnd].contains(action) { return } } - let items = self.items + if handleRowGlide(action) { return } let shots = screenshotCount let tops = topGameCount let page = currentPage - let actions = page?.rows.count ?? 0 + let actions = page?.links.count ?? 0 let more = page?.more.count ?? 0 - let readMore = page.map { aboutExcerpt($0).truncated } ?? false + // As drawn: this copy's canvas may be an older window size than the page's (`SpotlightReadMoreKey`). + let readMore = page != nil && aboutReadMore + let hasAchievements = selectedAchievements != nil let mods = selectedGame.flatMap { modsHost.game?.id == $0.id ? modsHost.tiles.count : nil } ?? 0 var moved = false switch action { case .navigateLeft, .navigateRight: let delta = action == .navigateLeft ? -1 : 1 mutate { state in - moved = state.focus == .row - ? state.move(by: delta, in: items) - : state.moveSideways(by: delta, screenshotCount: shots, topGameCount: tops, - actionCount: actions, moreCount: more, readMore: readMore, modsCount: mods) + moved = state.moveSideways(by: delta, screenshotCount: shots, topGameCount: tops, + actionCount: actions, moreCount: more, readMore: readMore, modsCount: mods, + hasAchievements: hasAchievements) } case .navigateDown where selectedItem == .card(.mods) && viewModel.spotlight.focus == .row: enterStore() case .navigateDown: - let isGame = selectedGame != nil + let isGame = selectedCatalogGame != nil let isActivity = selectedItem == .card(.activity) mutate { moved = $0.moveDown(selectedIsGame: isGame, screenshotCount: shots, selectedIsActivity: isActivity, topGameCount: tops, - actionCount: actions, moreCount: more, modsCount: mods) + actionCount: actions, moreCount: more, modsCount: mods, + hasAchievements: hasAchievements) } case .navigateUp: - mutate { moved = $0.moveUp(screenshotCount: shots, actionCount: actions, modsCount: mods) } + mutate { moved = $0.moveUp(screenshotCount: shots, actionCount: actions, modsCount: mods, + hasAchievements: hasAchievements) } case .tabPrevious: setFilter(filter.shifted(by: -1)) case .tabNext: setFilter(filter.shifted(by: 1)) case .jumpToStart, .jumpToEnd: + let items = self.items mutate { moved = $0.jump(toEnd: action == .jumpToEnd, in: items) } case .confirm: confirm() @@ -58,10 +65,15 @@ extension SpotlightView { mutate { if $0.focus != .row { $0.focus = .row; moved = true } } case .secondaryAction: // X scrolls to the game's page (the pills), like Down from the row. - if selectedGame != nil { + if selectedGame != nil || selectedCatalogGame?.integration == .steam { mutate { if $0.focus == .row { moved = $0.showGameDetails() } } } case .contextAction: + if let steam = selectedCatalogGame, steam.integration == .steam { + SoundEffectService.shared.play(.click) + viewModel.openSteamOptions(steam, from: .spotlight) + return + } if let game = selectedGame { viewModel.openGameOptions(game, from: .spotlight) } else if case .card(let card) = selectedItem { @@ -82,6 +94,27 @@ extension SpotlightView { if moved { SoundEffectService.shared.play(.focus) } } + /// Horizontal browsing only needs the row. Constructing the game page here does disk and layout work before the glide. + func handleRowGlide(_ action: GamepadAction) -> Bool { + guard viewModel.spotlight.focus == .row, action == .navigateLeft || action == .navigateRight else { return false } + let items = self.items + let delta = action == .navigateLeft ? -1 : 1 + var moved = false + mutate { moved = $0.move(by: delta, in: items) } + if moved { SoundEffectService.shared.play(.focus) } + return true + } + + func pressCatalogPill(_ index: Int, game: CatalogGame) { + switch index { + // The positions of Play, Options and favorite, as for an nxnative game. + case 0: SoundEffectService.shared.play(.click); SteamPlayCoordinator.shared.press(game) + case 1: SoundEffectService.shared.play(.click); viewModel.openSteamOptions(game, from: .spotlight) + case 2: viewModel.setCatalogFavorite(game) + default: break + } + } + private func confirm() { let state = viewModel.spotlight switch state.focus { @@ -89,13 +122,14 @@ extension SpotlightView { if let item = selectedItem { activate(item) } case .pills: if let game = selectedGame { pressPill(state.pillIndex, game: game) } + else if let game = selectedCatalogGame { pressCatalogPill(state.pillIndex, game: game) } case .strip: openViewer(at: state.stripIndex) case .about: aboutExpanded.toggle() SoundEffectService.shared.play(.click) case .actions: - let rows = currentPage?.rows ?? [] + let rows = currentPage?.links ?? [] guard state.actionIndex < rows.count else { return } rows[state.actionIndex].action() case .more: @@ -110,17 +144,62 @@ extension SpotlightView { if state.topGameIndex < ids.count { selectGame(ids[state.topGameIndex]) } case .store: break // The store takes A itself (`handleStore`). + case .achievements: + openAchievements() + } + } + + // MARK: - Achievements + + /// Reads the selected Steam game's achievements (again), in the app's language. + func loadAchievements() { + guard let appID = selectedCatalogGame?.steamGame?.appID else { return } + achievementsStore.load(appID: appID, language: SteamMetadata.language(L10n.context.language)) + } + + /// Opens on All, and reads Steam's files again for unlocks made since the page opened. + func openAchievements() { + guard let summary = selectedAchievements, achievementsScreen == nil else { return } + achievementsScreen = AchievementsScreenModel(ids: summary.rows(.all).map(\.id)) + SoundEffectService.shared.play(.click) + loadAchievements() + } + + /// Closing returns Spotlight's focus to the tile. + func closeAchievements() { + guard achievementsScreen != nil else { return } + achievementsScreen = nil + if selectedAchievements != nil { mutate { $0.focus = .achievements } } + SoundEffectService.shared.play(.focus) + } + + private func handleAchievements(_ action: GamepadAction) { + guard let screen = achievementsScreen, let summary = selectedAchievements else { + achievementsScreen = nil + return + } + switch screen.handle(action, summary: summary) { + case .moved: SoundEffectService.shared.play(.focus) + case .filtered, .ordered: SoundEffectService.shared.play(.tabSwitch) + case .opened: SoundEffectService.shared.play(.click) + case .closedDetail: SoundEffectService.shared.play(.focus) + case .close: closeAchievements() + case .ignored: break } } // MARK: - Screenshot viewer func openViewer(at index: Int) { - guard let game = selectedGame else { return } - let urls = Array((viewModel.storeMetadata[game.id]?.screenshotURLs ?? []) - .prefix(SpotlightScreenshotStrip.maxCount)) + let titleID: String, all: [URL] + if let game = selectedGame { + titleID = viewModel.personalizationKey(for: game); all = viewModel.storeMetadata[game.id]?.screenshotURLs ?? [] + } else if let game = selectedCatalogGame, game.integration == .steam { + titleID = game.personalizationReference.key; all = steamFacts.metadata(for: game)?.screenshots ?? [] + } else { return } + let urls = Array(all.prefix(SpotlightScreenshotStrip.maxCount)) guard !urls.isEmpty else { return } - viewer = ViewerContext(titleID: game.titleId ?? game.uniqueKey, urls: urls, + viewer = ViewerContext(titleID: titleID, urls: urls, state: ScreenshotViewerState(count: urls.count, start: index)) SoundEffectService.shared.play(.click) } @@ -162,12 +241,9 @@ extension SpotlightView { var order: [String]? mutate { order = $0.drop() } if let order { - // Under a filter, fold the visible order into the full one. - let full = SpotlightRow.build( - games: LibraryQuery(filter: .all).apply(to: viewModel.libraryGames, history: playSessions), - enabledCards: settings.settings.visibleSpotlightCards, - order: settings.settings.spotlightOrder).map(\.key) - settings.settings.spotlightOrder = SpotlightRow.merging(visibleOrder: order, into: full) + settings.settings.spotlightOrder = SpotlightRow.saving( + visibleOrder: order, gameIDs: viewModel.catalogGames.map(\.id), + previousOrder: settings.settings.spotlightOrder) } SoundEffectService.shared.play(.click) case .cancel: @@ -223,6 +299,9 @@ extension SpotlightView { func activate(_ item: SpotlightItem) { switch item { case .game(let id): + if let steam = viewModel.visibleCatalogGames.first(where: { $0.id == id }), steam.integration == .steam { + SoundEffectService.shared.play(.click); SteamPlayCoordinator.shared.press(steam); return + } guard let game = viewModel.libraryGames.first(where: { $0.id == id }) else { return } if viewModel.portingPills(game) == .porting { SoundEffectService.shared.play(.click) @@ -287,17 +366,19 @@ extension SpotlightView { } } + /// Play, or Build for a game not built yet (as on the Details page); the page has no build button any more. private func play(_ game: PortedGame) { - guard GameResourceState.unavailableReason(for: game) == nil else { - SoundEffectService.shared.play(.error) - return - } - if game.isPlayableLocally { + let step = GamePrimaryStep.decide(unavailable: GameResourceState.unavailableReason(for: game) != nil, + playable: game.isPlayableLocally, + sourcesAvailable: GameResourceState.sourcesAvailable(for: game)) + switch step { + case .play: viewModel.launchGame(game) - } else { - // Not built yet: scroll down to Build & Sources. - let canBuild = GameResourceState.sourcesAvailable(for: game) - mutate { $0.focus = .actions; $0.actionIndex = canBuild ? 1 : 0 } + case .build: + viewModel.startBuild(for: game) + if viewModel.isBuilding { router.openAddGame() } + case .refuse: + SoundEffectService.shared.play(.error) } } @@ -343,20 +424,36 @@ extension SpotlightView { guard !router.isMenuPresented, !NativeMenuCommands.shared.isTracking, !router.isSearchPresented, - !router.isIntroShowing, router.route == .library, viewModel.alertMessage == nil, viewModel.settingsNotice == nil, - viewModel.gameForSettingsSheet == nil, + !viewModel.isGameOptionsOpen, viewModel.gameToClose == nil, viewModel.gameToRemove == nil, !viewModel.isUpdateOfferOpen, + !viewModel.isWelcomeOpen, !viewModel.showSetupCheck, let window = event.window, !window.isSheet, window.attachedSheet == nil, NSApp.modalWindow == nil, !(window.firstResponder is NSText) else { return event } + // The entrance plays to its end: keys and the wheel are taken; ⌘, ⌃ and ⌥ shortcuts still pass. + if !entrance.takesInput { + let shortcut = event.type == .keyDown + && !event.modifierFlags.intersection([.command, .control, .option]).isEmpty + return shortcut ? event : nil + } if event.type == .scrollWheel { + // The Achievements screen's list takes the wheel on its own offset, like a mod panel's + // description: a notch glides, a trackpad follows the fingers; the page beneath stays. + if let screen = achievementsScreen { + let dy = event.scrollingDeltaY + if abs(dy) >= abs(event.scrollingDeltaX) { + let precise = event.hasPreciseScrollingDeltas + screen.wheel(by: -(precise ? dy : dy * canvas.u(48)), animated: !precise && !reduceMotion) + } + return nil + } // An open mod panel takes the wheel: its description scrolls, the page beneath stays. if let panel = [modsHost, storeHost.panel].first(where: \.isPanelOpen) { let dy = event.scrollingDeltaY @@ -488,7 +585,8 @@ extension SpotlightView { // The row is reached only by the glide, never by settling. var areas: [SpotlightFocusArea] = [.pills] if screenshotCount > 0 { areas.append(.strip) } - if !page.rows.isEmpty { areas.append(.actions) } + if selectedAchievements != nil { areas.append(.achievements) } + if !page.links.isEmpty { areas.append(.actions) } if modsHost.localMods != nil { areas.append(.mods) } if !page.more.isEmpty { areas.append(.more) } let current = scroll diff --git a/Sources/NXLibrary/Views/Spotlight/SpotlightView.swift b/Sources/NXLibrary/Views/Spotlight/SpotlightView.swift index 819ae18d..6dc0e961 100644 --- a/Sources/NXLibrary/Views/Spotlight/SpotlightView.swift +++ b/Sources/NXLibrary/Views/Spotlight/SpotlightView.swift @@ -10,7 +10,7 @@ import NXLibraryCore /// reach the window edges. /// /// Below the stats the screen is one page: genres, screenshots, the -/// description with Your activity and Build & Sources beside it, More like this. Down +/// description with Details beside it, More like this. Down /// from the row shifts everything up (the row and the bar fade away, the logo /// rises to the top) and keeps going section by section; Up comes back. public struct SpotlightView: View { @@ -18,21 +18,32 @@ public struct SpotlightView: View { @ObservedObject var router: AppRouter @ObservedObject var settings: AppSettingsStore @ObservedObject var playSessions: PlaySessionStore + /// Steam Play phases drive the A hint. + @ObservedObject var steamPlayer = SteamPlayCoordinator.shared @ObservedObject var runningGames: RunningGameMonitor @ObservedObject var artwork: ArtworkStore @Environment(\.seleneCanvas) var canvas @Environment(\.seleneReduceMotion) var reduceMotion + @Environment(\.nxAppLocale) private var localization @StateObject var art = SeleneHeroArt() /// Art the player picks redraws the hero and logo (their task keys carry its revision). @ObservedObject var picks = ArtworkPicks.shared + /// Steam store facts and personal fields, shared with the Steam head. + @ObservedObject var steamFacts = SteamGameFacts.shared + @ObservedObject var achievementsStore = SteamAchievementsStore.shared + @ObservedObject var steamFields = SteamPersonalizations.shared.metadata + /// Only traits are retained for the cache pass, without artwork, screenshots or descriptions. + @State private var cachedSteamRelated: (request: SteamRelatedRequest, traits: [UInt32: MoreLikeThis.Traits])? @State var keyMonitor: Any? @State var hadGames = false /// The card Y menu: which card and the focused row. @State var cardMenu: CardMenuState? /// The open screenshot viewer (the game's titleID, its urls and the paging state). @State var viewer: ViewerContext? + /// The open Achievements screen's selection; the game is the selected Steam game. + @State var achievementsScreen: AchievementsScreenModel? /// The filter pill: shown while the filter is not All, and for 1.2 s after switching to All. @State var pillFilter: LibraryFilter = .all @State var pillVisible = false @@ -57,16 +68,28 @@ public struct SpotlightView: View { @State var wheelSettle: Task<Void, Never>? /// About this game shows its whole text (Read more); closes with the game. @State var aboutExpanded = false + /// About this game shows Read more, as last drawn (`SpotlightReadMoreKey`). + @State var aboutReadMore = false /// The selected game's Mods band (installed mods, GameBanana's, their panels); shared with Details. @StateObject var modsHost = ModsBandHost() /// The Mods card's store, below the card. - @StateObject var storeHost = ModStoreHost() + @ObservedObject var storeHost: ModStoreHost /// The backdrop's gold (`updateModsBackdrop`). @State var modsBackdrop = false /// Whether the previous game's art may stay while the next game's loads (`shownArt`). @State var artRule = BackdropArtRule() /// The wheel's travel inside the store, toward the next section. @State var storeWheel: CGFloat = 0 + /// The first home's entrance (`SpotlightView+Entrance`); landed on every later visit. + @State var entrance: SpotlightEntrance.Phase + /// Visible tiles still looking up their first art (`TileArtPendingKey`). + @State var pendingTileArt = 0 + /// The entrance's longest wait for the tiles' art. + @State var entranceWait: Task<Void, Never>? + /// The top bar and the button hints, held until the entrance has landed (`finishEntrance`). + @State var controlsShown: Bool + /// The breath on the moving moonlight is over (`SpotlightEntrance.hold`). + @State var entranceBreathed = false var isGliding: Bool { Date() < glideEnds } struct ViewerContext: Equatable { @@ -82,13 +105,17 @@ public struct SpotlightView: View { init(viewModel: AppViewModel, router: AppRouter, settings: AppSettingsStore, playSessions: PlaySessionStore, runningGames: RunningGameMonitor, - artwork: ArtworkStore) { + artwork: ArtworkStore, storeHost: ModStoreHost) { self.viewModel = viewModel self.router = router self.settings = settings self.playSessions = playSessions self.runningGames = runningGames self.artwork = artwork + self.storeHost = storeHost + // Held hidden from the first frame (the opening, or under the welcome); `entranceAppear` lands it when not due. + _entrance = State(initialValue: viewModel.homeSeen ? .landed : .covered) + _controlsShown = State(initialValue: viewModel.homeSeen) } // MARK: - Model @@ -100,11 +127,22 @@ public struct SpotlightView: View { LibraryQuery(filter: filter).apply(to: viewModel.libraryGames, history: playSessions) } - var items: [SpotlightItem] { - SpotlightRow.build(games: games, - enabledCards: settings.settings.visibleSpotlightCards, - order: viewModel.spotlight.lift?.order ?? settings.settings.spotlightOrder, - front: viewModel.frontGameID) + var rowGames: [CatalogGame] { + LibraryQuery(filter: filter).applyCatalog(to: viewModel.visibleCatalogGames, history: playSessions) + } + var selectedCatalogGame: CatalogGame? { + guard case .game(let id) = selectedItem else { return nil } + return viewModel.visibleCatalogGames.first { $0.id == id } + } + var items: [SpotlightItem] { rowItems(for: rowGames) } + + private func rowItems(for games: [CatalogGame]) -> [SpotlightItem] { + let ids = games.map(\.id) + return SpotlightRow.build(gameIDs: ids, + enabledCards: settings.settings.visibleSpotlightCards, + order: viewModel.spotlight.lift?.order ?? settings.settings.spotlightOrder, + front: SpotlightRow.leaders(porting: viewModel.frontGameID, + downloads: viewModel.sessionDownloads.ids, row: ids)) } var selectedItem: SpotlightItem? { viewModel.spotlight.selectedItem(in: items) } @@ -117,18 +155,26 @@ public struct SpotlightView: View { /// Everything one render needs, computed once per body. struct Snapshot { let items: [SpotlightItem] + let rowGameCount: Int let gamesByID: [UUID: PortedGame] let selectedItem: SpotlightItem? let selectedGame: PortedGame? + let catalogGamesByID: [UUID: CatalogGame] + let selectedCatalogGame: CatalogGame? } private func snapshot() -> Snapshot { - let items = self.items + let visible = viewModel.visibleCatalogGames + let rowGames = LibraryQuery(filter: filter).applyCatalog(to: visible, history: playSessions) + let items = rowItems(for: rowGames) let gamesByID = Dictionary(viewModel.libraryGames.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) let item = viewModel.spotlight.selectedItem(in: items) - var game: PortedGame? - if case .game(let id) = item { game = gamesByID[id] } - return Snapshot(items: items, gamesByID: gamesByID, selectedItem: item, selectedGame: game) + let catalog = Dictionary(visible.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) + let id: UUID? + if case .game(let selected) = item { id = selected } else { id = nil } + return Snapshot(items: items, rowGameCount: rowGames.count, gamesByID: gamesByID, selectedItem: item, + selectedGame: id.flatMap { gamesByID[$0] }, catalogGamesByID: catalog, + selectedCatalogGame: id.flatMap { catalog[$0] }) } /// One pill while the selected game ports, three otherwise. @@ -137,6 +183,9 @@ public struct SpotlightView: View { } var screenshotCount: Int { + if let game = selectedCatalogGame, game.integration == .steam { + return min(steamFacts.metadata(for: game)?.screenshots.count ?? 0, SpotlightScreenshotStrip.maxCount) + } guard let game = selectedGame else { return 0 } let urls = viewModel.storeMetadata[game.id]?.screenshotURLs ?? [] return min(urls.count, SpotlightScreenshotStrip.maxCount) @@ -154,14 +203,16 @@ public struct SpotlightView: View { onMenu: { router.isMenuPresented = true }), rightHints: contextHints(model, state), rightReserve: hintReserve(state), - hintsHidden: router.overlayHasHints(viewModel), + hintsHidden: router.overlayHasHints(viewModel) || achievementsScreen != nil, + hintsHeld: !controlsShown, backdrop: { // On a card no art; on the Mods card the moonlight glides to gold (and stays gold until the next // game's art has arrived, so leaving the card is one change, not gold → blue → art). let shown = shownArt(model) SeleneArtBackground(image: shown, imageKey: shown == nil ? "none" : art.key, shade: settings.settings.backgroundShade, crossfade: 0.8, - showsArt: !settings.settings.keepWallpaperOnGames, modsTint: modsBackdrop) + showsArt: !settings.settings.keepWallpaperOnGames, modsTint: modsBackdrop, + reveal: artReveal) // Deeper in the page the art dims so the text reads. Color.black.opacity(dimmed ? 0.4 : 0) .allowsHitTesting(false) @@ -169,21 +220,45 @@ public struct SpotlightView: View { stage: { stage(model, state: state) }) .overlay(viewerOverlay) .animation(.easeOut(duration: 0.2), value: viewer != nil) + .overlay(achievementsOverlay(model)) + .animation(SeleneTheme.screen, value: achievementsScreen != nil) .overlay(model.selectedGame.map { ModsBandOverlay(host: modsHost, find: modsHost.find, game: $0) }) .overlay(storeOverlay(model)) .onAppear(perform: appear) + .onAppear(perform: entranceAppear) + .onChange(of: isCovered) { covered in if !covered { uncoverEntrance() } } + .onChange(of: reduceMotion) { reduced in if reduced { landEntrance() } } + // A resize mid-flight lands it; before the flight the starts follow the window (the launch can still size it). + .onChange(of: canvas) { _ in if entrance == .playing { landEntrance() } } .onAppear { storeHost.loadCover(titleIDs: Set(storeGames.compactMap { viewModel.modStore(for: $0)?.titleID })) } .onAppear { mutate { $0.setPillLimit(selectedPillCount) } } .onChange(of: selectedPillCount) { count in mutate { $0.setPillLimit(count) } } + // A re-read can remove the tile (the files went away): the focus leaves it for the screenshots. + .onChange(of: selectedAchievements == nil) { gone in + guard gone else { return } + achievementsScreen = nil + guard viewModel.spotlight.focus == .achievements else { return } + mutate { $0.focus = screenshotCount > 0 ? .strip : .pills } + } + // A re-read while the screen is open: the selection stays inside the list. + .onChange(of: selectedAchievements) { summary in + guard let summary, let screen = achievementsScreen else { return } + screen.setIDs(summary.rows(screen.state.filter, order: screen.state.order).map(\.id)) + } + // Another game, or the row: the screen belongs to the game it opened on. + .onChange(of: viewModel.spotlight.selectedKey) { _ in achievementsScreen = nil } .onDisappear { + landEntrance() removeKeyMonitor() router.isScreenshotViewerOpen = false + achievementsScreen = nil modsHost.stop() storeHost.close() pillTask?.cancel() mutate { $0.cancelLift() } } - .onChange(of: viewModel.libraryGames) { _ in gamesChanged() } + .onChange(of: viewModel.catalogGames) { _ in gamesChanged() } + .onChange(of: viewModel.catalogSourceConfigurations) { _ in gamesChanged() } .onChange(of: filter) { newFilter in reconcile() filterChanged(to: newFilter) @@ -199,13 +274,14 @@ public struct SpotlightView: View { startModsOnline(focus) } // Game options (its Mods panel) closing, or NX Library coming back from Finder, re-reads the mods. - .onChange(of: viewModel.gameForSettingsSheet == nil) { closed in if closed { reloadMods() } } + .onChange(of: !viewModel.isGameOptionsOpen) { closed in if closed { reloadMods() } } .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in reloadMods() } .onChange(of: blocks) { _ in syncPage() } // Inside the store the page glides section to section on a shorter curve. .onChange(of: storeHost.focus) { _ in syncPage(glide: Self.storeGlide) } .onChange(of: storeHost.sections.map(\.kind)) { _ in syncPage(glide: Self.storeGlide) } - .onChange(of: viewer != nil) { router.isScreenshotViewerOpen = $0 } + // The viewer and the Achievements screen both keep the shell's own buttons away. + .onChange(of: viewer != nil || achievementsScreen != nil) { router.isScreenshotViewerOpen = $0 } .onChange(of: router.pendingSpotlightMove) { _ in consumePendingMove() } .onReceive(NotificationCenter.default.publisher(for: .nxFindGameSelect)) { note in guard let id = note.object as? UUID else { return } @@ -218,11 +294,16 @@ public struct SpotlightView: View { } } .onReceive(NotificationCenter.default.publisher(for: .nxSpotlightGamepadAction)) { note in - guard viewModel.alertMessage == nil, viewModel.settingsNotice == nil else { return } + // The welcome's fade: the controller reaches Spotlight only once it has gone. + guard viewModel.alertMessage == nil, viewModel.settingsNotice == nil, !isOverlaid else { return } if let action = note.object as? GamepadAction { handle(action) } } .onChange(of: playSessions.sessions.count) { _ in reconcile() } .task(id: art.heroTaskKey(model.selectedGame, metadata: model.selectedGame.flatMap { viewModel.storeMetadata[$0.id] })) { await loadHero(model.selectedGame) } + .task(id: art.steamHeroTaskKey(model.selectedCatalogGame)) { + await art.loadSteamHero(game: model.selectedCatalogGame, current: { selectedCatalogGame?.id }, artwork: artwork, settle: 420_000_000) + if model.selectedCatalogGame?.integration == .steam, !Task.isCancelled { modsBackdrop = false } + } .task(id: art.logoTaskKey(model.selectedGame, metadata: model.selectedGame.flatMap { viewModel.storeMetadata[$0.id] })) { await loadLogo(model.selectedGame) } } @@ -242,18 +323,56 @@ public struct SpotlightView: View { } } + @ViewBuilder + private func achievementsOverlay(_ model: Snapshot) -> some View { + if let screen = achievementsScreen, let game = model.selectedCatalogGame, let summary = selectedAchievements { + AchievementsScreen(model: screen, game: game, summary: summary, art: shownArt(model), + onFilter: { filter in + guard filter != screen.state.filter else { return } + screen.setFilter(filter, summary: summary) + SoundEffectService.shared.play(.tabSwitch) + }, + onShiftFilter: { delta in + screen.shiftFilter(by: delta, summary: summary) + SoundEffectService.shared.play(.tabSwitch) + }, + onCycleOrder: { + screen.cycleOrder(summary: summary) + SoundEffectService.shared.play(.tabSwitch) + }, + onFocus: { index in + // A click on the focused row opens it, as A does. + guard index != screen.state.index else { + if screen.openDetail() { SoundEffectService.shared.play(.click) } + return + } + screen.focus(index) + SoundEffectService.shared.play(.focus) + }, + onOpen: { if screen.openDetail() { SoundEffectService.shared.play(.click) } }, + onCloseDetail: { + screen.closeDetail() + SoundEffectService.shared.play(.focus) + }, + onClose: closeAchievements) + .transition(.opacity) + } + } + private func stage(_ model: Snapshot, state: SpotlightState) -> some View { let items = model.items return ZStack(alignment: .topLeading) { SpotlightTopBar(filter: filter, showClock: settings.settings.showClock, onSelect: { if !state.isLifted { setFilter($0) } }) - .opacity(rowShown ? 1 : 0) - .allowsHitTesting(rowShown) + // Comes in last with the hints (`finishEntrance`). + .opacity(rowShown && controlsShown ? 1 : 0) + .allowsHitTesting(rowShown && entrance.takesInput) ZStack(alignment: .topLeading) { SpotlightRowView( items: items, gamesByID: model.gamesByID, + catalogGamesByID: model.catalogGamesByID, selectedKey: state.selectedKey, liftedKey: state.lift?.key, isEmptyFilter: LibraryEmptyState.showsMessage( @@ -262,6 +381,8 @@ public struct SpotlightView: View { artwork: artwork, tileLook: viewModel.portingTileLook, modsCover: storeHost.cover, + entrance: entrance, + onEntranceEnd: { finishEntrance() }, onSelect: { item in guard !state.isLifted else { return } mutate { $0.select(item) } @@ -274,26 +395,39 @@ public struct SpotlightView: View { ) .offset(y: canvas.u(130)) // The icons give way as the page rises (and stop taking the pointer). - .opacity(rowShown ? 1 : 0) - .allowsHitTesting(rowShown) + .opacity(rowOpacity) + .allowsHitTesting(rowShown && entrance.takesInput) + .onPreferenceChange(TileArtPendingKey.self, perform: tileArtPending) - SpotlightFilterPill(filter: pillFilter, count: games.count) + SpotlightFilterPill(filter: pillFilter, count: model.rowGameCount) .offset(x: canvas.u(80), y: canvas.u(88)) // Opacity fades always run, reduce motion or not. - .opacity(pillVisible ? 1 : 0) + .opacity(pillVisible && !entrance.holdsHidden ? 1 : 0) .animation(.easeOut(duration: 0.2), value: pillVisible) + .animation(entranceRise, value: entrance.holdsHidden) info(model, state: state) .offset(x: canvas.u(80), y: canvas.u(420)) + .entrance(entrance == .landed ? nil : SpotlightEntrance.info, launched: entranceLaunched, + unit: canvas.u(1)) + .allowsHitTesting(entrance.takesInput) } .onPreferenceChange(SpotlightBlockKey.self) { heights in if !Self.sameLayout(heights, blocks) { blocks = heights } } + .onPreferenceChange(SpotlightReadMoreKey.self) { shown in + if shown != aboutReadMore { aboutReadMore = shown } + } + // Every block rides the glide as one: the fades that run beside it (`setPageFades`) re-timed leaves + // of their own and they slid at their own pace (`GlideGroup`). + .modifier(GlideGroup()) // One page: the focus scrolls it; the glide is movement, so reduce motion jumps. .offset(y: scroll) // The page fades out short of the window's edges, top and bottom. .frame(width: canvas.stageSize.width, height: canvas.size.height, alignment: .topLeading) .mask(pageMask) + .contentShape(Path(CGRect(x: 0, y: 0, width: canvas.stageSize.width, + height: max(0, canvas.size.height - canvas.u(SeleneBottomScrim.contentClearance))))) // Off the row, the page has risen: there is more above (More like this is the end). SpotlightUpHint() @@ -323,7 +457,7 @@ public struct SpotlightView: View { private func info(_ model: Snapshot, state: SpotlightState) -> some View { if let game = model.selectedGame { let metadata = viewModel.storeMetadata[game.id] - let page = page(for: game) + let genres = GameGenre.list(metadata?.genres ?? []) VStack(alignment: .leading, spacing: 0) { SpotlightGameInfoView( game: game, @@ -352,8 +486,8 @@ public struct SpotlightView: View { .id(game.id) .spotlightBlock(.head) - if !page.presentation.genres.isEmpty { - SpotlightGenreChips(genres: page.presentation.genres) + if !genres.isEmpty { + SpotlightGenreChips(genres: genres) // They leave and come back with the pills, not stay while the rest changes. .modifier(SpotlightInfoFollow()) .id(game.id) @@ -361,43 +495,54 @@ public struct SpotlightView: View { .spotlightBlock(.genres) } - SpotlightScreenshotStrip( - titleID: game.titleId ?? game.uniqueKey, - urls: metadata?.screenshotURLs ?? [], - known: screenshotsKnown(game, metadata: metadata), - focusedIndex: state.focus == .strip ? state.stripIndex : nil, - scrollIndex: state.stripIndex, - artwork: artwork, - onSelect: { index in - guard !state.isLifted else { return } - mutate { $0.focus = .strip; $0.stripIndex = index } - openViewer(at: index) - } - ) - // On the row the screenshots dissolve downwards (Selene's home): the - // hints sit on the dark below them, and the fade says there is more below. - // Gradient stops do not animate, so the fade lifts by a solid layer - // fading in over it, along with the glide. The mask reaches past the - // strip's edges so the focus ring outside a tile shows. - .mask(ZStack { - LinearGradient(stops: [ - .init(color: .black, location: 0), - .init(color: .black, location: 0.3), - .init(color: .black.opacity(0.35), location: 0.62), - .init(color: .black.opacity(0), location: 0.86) - ], startPoint: .top, endPoint: .bottom) - Color.black.opacity(stripFull ? 1 : 0) + screenshotStrip(id: game.id, titleID: viewModel.personalizationKey(for: game), + urls: metadata?.screenshotURLs ?? [], + known: screenshotsKnown(game, metadata: metadata), state: state) + + // The lower page is offscreen on the row. Build it only as the page rises. + if belowShown { pageBelow(game, page: page(for: game), state: state).transition(.opacity) } + } + } else if let game = model.selectedCatalogGame, game.integration == .steam { + let metadata = steamFacts.metadata(for: game) + let genres = GameDetailPresentation.steamGenres( + for: game, metadata: metadata, + override: steamFields.value(titleID: game.personalizationReference.key, field: .genres)) + VStack(alignment: .leading, spacing: 0) { + CatalogSteamInfo(game: game, totalPlaytime: playSessions.totalDuration(for: game.id), + lastPlayed: playSessions.lastPlayed(for: game.id), + focused: state.focus == .pills ? state.pillIndex : nil, + onAction: { index in + guard !state.isLifted else { return } + mutate { $0.focus = .pills; $0.pillIndex = index } + pressCatalogPill(index, game: game) + }, + onHover: { index in + guard !state.isLifted, state.focus == .pills, !isGliding else { return } + mutate { $0.pillIndex = index } + }) + .id(game.id) + .spotlightBlock(.head) + + if !genres.isEmpty { + SpotlightGenreChips(genres: genres) + .modifier(SpotlightInfoFollow()) + .id(game.id) + .padding(.top, canvas.u(20)) + .spotlightBlock(.genres) } - .padding(-canvas.u(16))) - // They arrive after the logo, not before it. - .seleneReveal(delay: 0.6) - .id(game.id) - .padding(.top, canvas.u(30)) - .spotlightBlock(.strip) - pageBelow(game, page: page, state: state) - // Hidden while the row has focus: it rises in with the page. - .opacity(belowShown ? 1 : 0) + screenshotStrip(id: game.id, titleID: game.personalizationReference.key, + urls: metadata?.screenshots ?? [], + known: steamFacts.isKnown(game), state: state) + + if belowShown { + let request = SteamRelatedRequest( + appIDs: Set(model.catalogGamesByID.values.compactMap { $0.isHidden ? nil : $0.steamGame?.appID }), + language: SteamMetadata.language(localization.language)) + steamPageBelow(steamPage(for: game), state: state) + .task(id: request) { await loadCachedSteamRelated(request) } + .transition(.opacity) + } } } else if model.selectedItem == .card(.mods) { VStack(alignment: .leading, spacing: 0) { @@ -415,12 +560,12 @@ public struct SpotlightView: View { } else if case .card(let card) = model.selectedItem { let summary = card == .activity ? activitySummary : ActivitySummary() let top = summary.topGames.compactMap { model.gamesByID[$0] }.filter { !$0.isHidden } - let visible = viewModel.libraryGames.filter { !$0.isHidden } + let visible = viewModel.visibleCatalogGames // Selene's card panels sit 40 under the row, 10 lower than a game's. SpotlightCardInfoView( card: card, gameCount: visible.count, - installedCount: visible.filter(\.isPlayableLocally).count, + installedCount: LibraryQuery(filter: .installed).applyCatalog(to: visible, history: playSessions).count, poolLabel: Self.poolLabel(settings.settings.surprisePool), activity: summary, topGames: top, @@ -480,7 +625,7 @@ public struct SpotlightView: View { if state.isLifted || cardMenu != nil { return [] } switch state.focus { case .row: return [[], ["Play", "Build", "Pick", "Open"]] - case .pills, .strip, .mods, .about, .actions, .more: return [[], ["Select", "View", "Show"]] + case .pills, .strip, .mods, .about, .actions, .more, .achievements: return [[], ["Select", "View", "Show", "Open"]] case .store: return [[], ["Sort", "View"]] case .topGames: return [] } @@ -502,6 +647,8 @@ public struct SpotlightView: View { return [HintItem(.b, L10n.text("Back")), HintItem(.a, L10n.text("Select"))] case .more: return [HintItem(.b, L10n.text("Back")), HintItem(.a, L10n.text("Show"))] + case .achievements: + return [HintItem(.b, L10n.text("Back")), HintItem(.a, L10n.text("Open"))] case .topGames: return [HintItem(.a, L10n.text("Show"))] case .store: @@ -515,6 +662,9 @@ public struct SpotlightView: View { let more = [HintItem(.y, L10n.text("Card options"))] return card == .activity ? more : more + [HintItem(.a, card == .surprise ? L10n.text("Pick") : card == .mods ? L10n.text("Browse") : L10n.text("Open"))] case .game: + if let steam = model.selectedCatalogGame, steam.integration == .steam { + return [HintItem(.y, L10n.text("Options"))] + SteamPlayCoordinator.shared.hint(for: steam) + } guard let game = model.selectedGame else { return [] } if viewModel.portingPills(game) == .porting { return [HintItem(.y, L10n.text("Options")), HintItem(.a, L10n.text("Porting"))] @@ -548,7 +698,7 @@ public struct SpotlightView: View { mutate { $0.startingTabApplied = true } viewModel.librarySelection.query.filter = LibraryFilter(startingTab: settings.settings.startingTab) } - hadGames = !viewModel.libraryGames.isEmpty + hadGames = !viewModel.visibleCatalogGames.isEmpty reconcile() selectionChanged() pillFilter = filter @@ -592,7 +742,7 @@ public struct SpotlightView: View { viewModel.preloadCachedStoreMetadata() // The whole library, not the filtered row: a filter change never // counts as "the library arrived". - let hasGames = !viewModel.libraryGames.isEmpty + let hasGames = !viewModel.visibleCatalogGames.isEmpty // The library loads after the first frame: a card picked while it was // empty gives way to the restored (or first) game. if !hadGames, hasGames, case .card = selectedItem { @@ -608,7 +758,7 @@ public struct SpotlightView: View { if let lifted = viewModel.spotlight.lift?.key, !items.contains(where: { $0.key == lifted }) { mutate { $0.cancelLift() } } - let preferred = settings.settings.restoreLastGame ? settings.settings.lastSelectedGameID : nil + let preferred = settings.settings.restoreLastGame ? settings.lastSelectedGameID : nil let items = self.items mutate { $0.reconcile(with: items, preferredGameID: preferred) } } @@ -624,21 +774,25 @@ public struct SpotlightView: View { private func selectionChanged() { if selectedItem == .card(.mods) { openStore() } else { storeHost.close() } updateModsBackdrop() - artRule.select(viewModel.spotlight.selectedKey, isGame: selectedGame != nil) + // A Steam game is a game too: moving to or from it keeps the art until the next arrives, never the wallpaper. + artRule.select(viewModel.spotlight.selectedKey, isGame: selectedGame != nil || selectedCatalogGame?.integration == .steam) reloadMods() startModsOnline(viewModel.spotlight.focus) - guard let game = selectedGame else { return } - if settings.settings.lastSelectedGameID != game.id { - settings.settings.lastSelectedGameID = game.id - } - viewModel.loadStoreMetadata(for: game) + let game = selectedGame + if let id = game?.id ?? selectedCatalogGame?.id { settings.rememberLastSelectedGame(id) } + loadAchievements() + if let game { viewModel.loadStoreMetadata(for: game) } } // MARK: - Mods - /// The selected game's installed mods; another game (or a card) stops the previous game's band. + /// The Mods band lives on the game page. Browsing the row releases the previous band without reading the next. func reloadMods() { - if let game = selectedGame { modsHost.reload(game, viewModel: viewModel) } else { modsHost.stop() } + guard viewModel.spotlight.focus != .row, let game = selectedGame else { + modsHost.clearGame() + return + } + modsHost.reload(game, viewModel: viewModel) } /// GameBanana is asked once the game's page is open, not while the row is browsed. @@ -682,7 +836,7 @@ public struct SpotlightView: View { let storeTop = canvas.u(420) + (blocks[.head] ?? 0) + canvas.u(Self.storeGap) let target = canvas.u(150) - storeTop - canvas.u(ModStoreLayout.top(of: at, in: kinds)) let bottom = storeTop + canvas.u(ModStoreLayout.top(of: kinds.count, in: kinds)) + canvas.u(90) - let end = canvas.size.height - canvas.u(130) - bottom + let end = canvas.size.height - canvas.u(Self.pageBottomInset) - bottom return min(first, max(target, end)) } @@ -690,7 +844,7 @@ public struct SpotlightView: View { private func loadHero(_ game: PortedGame?) async { await art.loadHero(game: game, current: { selectedGame?.id }, - metadata: game.flatMap { viewModel.storeMetadata[$0.id] }, artwork: artwork, + metadata: game.flatMap { viewModel.storeMetadata[$0.id] }, artwork: artwork, personalizations: viewModel.personalizations, // The logo leads (0.3 s); the art turns after it. settle: 420_000_000, keepsWithoutGame: true) // The game's art is in (or it has none): the gold gives way under it. @@ -701,8 +855,9 @@ public struct SpotlightView: View { /// loads when browsing from game to game (never another game's art right after a card). The rule answers for /// the selection this render sees, so the art never drops out for the render before `onChange` runs. private func shownArt(_ model: Snapshot) -> NSImage? { - guard let game = model.selectedGame, let image = art.image else { return nil } - return art.key.hasPrefix(game.id.uuidString) + let id = model.selectedGame?.id ?? model.selectedCatalogGame.flatMap { $0.integration == .steam ? $0.id : nil } + guard let id, let image = art.image else { return nil } + return art.key.hasPrefix(id.uuidString) || artRule.keepsOtherArt(selection: viewModel.spotlight.selectedKey, isGame: true) ? image : nil } @@ -724,7 +879,7 @@ public struct SpotlightView: View { /// The page's scroll for the focus, in points. The pills and the strip /// share the first shift (the strip only moves further if it would sit - /// under the hints); Build & Sources brings About this game and the column + /// under the hints); Details brings About this game and the column /// beside it up to 150 by their titles; More like this rises until the /// page's end sits above the hints, never further (`SpotlightPageScroll`). /// Positions add up the blocks' heights from the column's top at 420. @@ -750,16 +905,16 @@ public struct SpotlightView: View { return first case .strip: // Keep the strip clear of the hints on the window's bottom edge. - return min(first, canvas.size.height - canvas.u(130) - stripBottom) - case .about, .actions, .mods, .more: + return min(first, canvas.size.height - canvas.u(Self.pageBottomInset) - stripBottom) + case .about, .actions, .mods, .more, .achievements: // The bands report a height only when they are shown. let more = h(.more) > 0 let pageBottom = stripBottom + h(.description) + h(.mods) + (more ? h(.more) : 0) let rest = SpotlightPageScroll.resting( first: first, aboutTop: aboutTop, moreTop: more ? moreTop : nil, pageBottom: pageBottom, - top: canvas.u(150), viewport: canvas.size.height, bottomInset: canvas.u(130)) + top: canvas.u(150), viewport: canvas.size.height, bottomInset: canvas.u(Self.pageBottomInset)) switch area { - case .actions: return rest.actions + case .actions, .achievements: return rest.actions case .more: return rest.more case .mods: // The band's title rises to the top line, as More like this does, unless the page ends first. @@ -767,11 +922,11 @@ public struct SpotlightView: View { return SpotlightPageScroll.resting( first: first, aboutTop: aboutTop, moreTop: modsTop, pageBottom: pageBottom, top: canvas.u(150), viewport: canvas.size.height, - bottomInset: canvas.u(130)).more + bottomInset: canvas.u(Self.pageBottomInset)).more default: // Read more (or Show less, under the whole text) comes into view. return SpotlightPageScroll.revealing(rest.actions, bottom: aboutTop + h(.about), - viewport: canvas.size.height, bottomInset: canvas.u(130)) + viewport: canvas.size.height, bottomInset: canvas.u(Self.pageBottomInset)) } } } @@ -779,7 +934,10 @@ public struct SpotlightView: View { /// The page's edges, in canvas units: clear up to `clear` from the window's /// edge, solid from `solid` (the top bar's breathing room, top and bottom). static let pageEdge = (top: (clear: CGFloat(28), solid: CGFloat(84)), - bottom: (clear: CGFloat(36), solid: CGFloat(100))) + bottom: (clear: SeleneBottomScrim.contentClearance, + solid: SeleneBottomScrim.contentClearance + 64)) + /// A focused band clears both the footer and its fade, with space for its ring. + static let pageBottomInset: CGFloat = pageEdge.bottom.solid + 30 private var pageMask: some View { let height = max(canvas.size.height, 1) @@ -858,10 +1016,70 @@ public struct SpotlightView: View { /// Past the screenshots the art dims behind the text. func isDeep(_ state: SpotlightState) -> Bool { state.focus == .about || state.focus == .actions || state.focus == .mods || state.focus == .more - || state.focus == .store + || state.focus == .store || state.focus == .achievements + } + + var currentPage: SpotlightPageModel? { + if let game = selectedGame { return page(for: game) } + return selectedCatalogGame.flatMap { $0.integration == .steam ? steamPage(for: $0) : nil } + } + + private struct SteamRelatedRequest: Equatable { + let appIDs: Set<UInt32> + let language: String + } + + private func loadCachedSteamRelated(_ request: SteamRelatedRequest) async { + guard cachedSteamRelated?.request != request else { return } + let traits = await SteamMetadataService.shared.cachedRelatedTraits(appIDs: request.appIDs, language: request.language) + guard !Task.isCancelled else { return } + cachedSteamRelated = (request, traits) } - var currentPage: SpotlightPageModel? { selectedGame.map(page(for:)) } + private func relatedTraits(for game: CatalogGame, language: String) -> MoreLikeThis.Traits? { + if let native = game.nxnativeGame { + return viewModel.storeMetadata[native.id].map { + MoreLikeThis.Traits(developers: $0.developers, publishers: $0.publishers, genres: GameGenre.list($0.genres)) + } + } + guard let appID = game.steamGame?.appID else { return nil } + let key = game.personalizationReference.key + let loaded = steamFacts.metadata(for: game).flatMap { $0.language == language ? MoreLikeThis.Traits(steam: $0) : nil } + let cached = cachedSteamRelated.flatMap { $0.request.language == language ? $0.traits[appID] : nil } + let traits = loaded ?? cached + let developer = steamFields.value(titleID: key, field: .developer) + let publisher = steamFields.value(titleID: key, field: .publisher) + let genres = steamFields.value(titleID: key, field: .genres) + guard traits != nil || developer != nil || publisher != nil || genres != nil else { return nil } + return MoreLikeThis.Traits(developers: developer.map { [$0] } ?? traits?.developers ?? [], + publishers: publisher.map { [$0] } ?? traits?.publishers ?? [], + genres: GameGenre.list(genres.map { $0.split(separator: ",").map(String.init) } ?? traits?.genres ?? [])) + } + + func steamPage(for game: CatalogGame) -> SpotlightPageModel { + let visible = viewModel.visibleCatalogGames + let playtimes = Dictionary(visible.map { ($0.id, playSessions.totalDuration(for: $0.id)) }, + uniquingKeysWith: { first, _ in first }) + let key = game.personalizationReference.key + var overrides: [MetadataField: String] = [:] + for field in MetadataField.allCases { overrides[field] = steamFields.value(titleID: key, field: field) } + let presentation = GameDetailPresentation( + steamRecord: game, metadata: steamFacts.metadata(for: game), overrides: overrides, + totalPlaytime: playSessions.totalDuration(for: game.id), + lastPlayed: playSessions.lastPlayed(for: game.id), + sessions: playSessions.sessions, libraryGames: visible, playtimeByGame: playtimes) + let facts = DetailsFacts.steamGame(game, metadata: steamFacts.metadata(for: game), overrides: overrides, + volumeName: DetailsLink.volumeName(of: game)) + let app = presentation.appPath.isEmpty ? nil : URL(fileURLWithPath: presentation.appPath) + let language = SteamMetadata.language(localization.language) + let ids = belowShown ? MoreLikeThis.pick(for: game, in: visible, fallbackToOtherSources: true, + traits: { relatedTraits(for: $0, language: language) }) : [] + let byID = Dictionary(visible.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + return SpotlightPageModel(presentation: presentation, facts: facts, + links: DetailsLink.links(app: app, store: presentation.storeURL, + hltb: presentation.hltbURL, viewModel: viewModel), + more: ids.compactMap { byID[$0] }, buildBlocked: false) + } func page(for game: PortedGame) -> SpotlightPageModel { let library = viewModel.libraryGames @@ -873,59 +1091,130 @@ public struct SpotlightView: View { lastPlayed: playSessions.lastPlayed(for: game.id), sessions: playSessions.sessions, libraryGames: library, playtimeByGame: playtimes) let blocked = viewModel.compatibilityReport != nil && !viewModel.canPassToolchainGate - let rows = BuildSourcesRow.rows(for: game, presentation: presentation, buildBlocked: blocked, - viewModel: viewModel, rebuild: { rebuild(game, canRebuild: presentation.canRebuild) }) + let facts = DetailsFacts.switchGame(game, metadata: viewModel.storeMetadata[game.id], + folderName: DetailsLink.folderName(of: game.url)) + let links = DetailsLink.links(app: game.url, store: presentation.storeURL, hltb: presentation.hltbURL, + viewModel: viewModel) let ids = MoreLikeThis.pick(for: game, in: library, metadata: { viewModel.storeMetadata[$0] }, limit: 6) let byID = Dictionary(library.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) - return SpotlightPageModel(presentation: presentation, rows: rows, - more: ids.compactMap { byID[$0] }, buildBlocked: blocked) + return SpotlightPageModel(presentation: presentation, facts: facts, links: links, + more: ids.compactMap { byID[$0].map(CatalogGame.init(nxnative:)) }, buildBlocked: blocked) } - private func rebuild(_ game: PortedGame, canRebuild: Bool) { - guard canRebuild else { - SoundEffectService.shared.play(.error) - return + /// About this game with the column beside it (a Steam game's achievements, then the source's panel): + /// the same geometry, focus blocks and excerpt for every source. + private func aboutAndColumn<Panel: View>(_ page: SpotlightPageModel, state: SpotlightState, + @ViewBuilder panel: () -> Panel) -> some View { + HStack(alignment: .top, spacing: 0) { + let excerpt = aboutExcerpt(page) + SpotlightDescription(text: page.presentation.description, languageNote: page.presentation.descriptionLanguageNote, excerpt: excerpt, + expanded: aboutExpanded, focused: state.focus == .about, + onToggle: { aboutExpanded.toggle() }) + .spotlightBlock(.about) + .preference(key: SpotlightReadMoreKey.self, value: excerpt.truncated) + Spacer(minLength: 0) + VStack(alignment: .leading, spacing: canvas.u(40)) { + if let summary = selectedAchievements, let appID = selectedCatalogGame?.steamGame?.appID { + DetailsAchievementsCard(summary: summary, appID: appID, focused: state.focus == .achievements, + onOpen: { + guard !state.isLifted else { return } + mutate { $0.focus = .achievements } + openAchievements() + }) + } + panel() + } + .spotlightBlock(.column) } - SoundEffectService.shared.play(.click) - viewModel.startBuild(for: game) - if viewModel.isBuilding { router.openAddGame() } + .frame(width: canvas.u(1700), alignment: .topLeading) + .padding(.top, canvas.u(44)) + .spotlightBlock(.description) + } + + /// The selected Steam game's achievements, when it has some and Steam's files read. + var selectedAchievements: AchievementSummary? { + guard let appID = selectedCatalogGame?.steamGame?.appID, + let summary = achievementsStore.summaries[appID], summary.total > 0 else { return nil } + return summary } - /// Below the screenshots: About this game, with Your activity and Build & - /// Sources in a column on its right (beside it however long it is), then More like this. + /// The Details panel in the column beside About this game, the same for every source. + private func detailsPanel(_ page: SpotlightPageModel, state: SpotlightState) -> some View { + DetailsPanel( + facts: page.facts, links: page.links, + focusedLink: state.focus == .actions ? state.actionIndex : nil, + onHoverLink: { index in + guard state.focus == .actions, !isGliding else { return } + mutate { $0.actionIndex = index } + }, + onPressLink: { index in + mutate { $0.focus = .actions; $0.actionIndex = index } + if index < page.links.count { page.links[index].action() } + }, + ratingQuery: selectedRatingQuery) + } + + private var selectedRatingQuery: CriticRatingQuery? { + if let game = selectedGame { + return CriticRatingQuery(game: game, name: viewModel.storeMetadata[game.id]?.name) + } + guard let game = selectedCatalogGame, let steam = game.steamGame else { return nil } + return CriticRatingQuery(name: steam.name, platform: .mac, steamAppID: steam.appID) + } + + /// A Steam game's page under the head: About, its achievements, Details, then related games. + private func steamPageBelow(_ page: SpotlightPageModel, state: SpotlightState) -> some View { + VStack(alignment: .leading, spacing: 0) { + aboutAndColumn(page, state: state) { detailsPanel(page, state: state) } + relatedBand(page, state: state) + } + } + + /// The screenshot strip under the head, for any source: the same tiles, fade and arrival. + private func screenshotStrip(id: UUID, titleID: String, urls: [URL], known: Bool, state: SpotlightState) -> some View { + SpotlightScreenshotStrip( + titleID: titleID, + urls: urls, + known: known, + focusedIndex: state.focus == .strip ? state.stripIndex : nil, + scrollIndex: state.stripIndex, + artwork: artwork, + onSelect: { index in + guard !state.isLifted else { return } + mutate { $0.focus = .strip; $0.stripIndex = index } + openViewer(at: index) + } + ) + // On the row the screenshots dissolve downwards (Selene's home): the + // hints sit on the dark below them, and the fade says there is more below. + // Gradient stops do not animate, so the fade lifts by a solid layer + // fading in over it, along with the glide. The mask reaches past the + // strip's edges so the focus ring outside a tile shows. + .mask(ZStack { + LinearGradient(stops: [ + .init(color: .black, location: 0), + .init(color: .black, location: 0.3), + .init(color: .black.opacity(0.35), location: 0.62), + .init(color: .black.opacity(0), location: 0.86) + ], startPoint: .top, endPoint: .bottom) + Color.black.opacity(stripFull ? 1 : 0) + } + .padding(-canvas.u(16))) + // They arrive after the logo, not before it. + .seleneReveal(delay: 0.6) + .id(id) + .padding(.top, canvas.u(30)) + .spotlightBlock(.strip) + } + + /// Below the screenshots: About this game, with Details in a column on its right + /// (beside it however long it is), then More like this. private func pageBelow(_ game: PortedGame, page: SpotlightPageModel, state: SpotlightState) -> some View { VStack(alignment: .leading, spacing: 0) { - HStack(alignment: .top, spacing: 0) { - SpotlightDescription(text: page.presentation.description, languageNote: page.presentation.descriptionLanguageNote, excerpt: aboutExcerpt(page), - expanded: aboutExpanded, focused: state.focus == .about, - onToggle: { aboutExpanded.toggle() }) - .spotlightBlock(.about) - Spacer(minLength: 0) - VStack(alignment: .leading, spacing: canvas.u(40)) { - DetailsActivityColumn(presentation: page.presentation) - BuildSourcesPanel( - presentation: page.presentation, - appFileName: game.url.lastPathComponent, - buildBlocked: page.buildBlocked && page.presentation.canRebuild, - blockedHint: viewModel.toolchainGateSummary, - rows: page.rows, - focusedRow: state.focus == .actions ? state.actionIndex : nil, - onHoverRow: { index in - guard state.focus == .actions, !isGliding else { return } - mutate { $0.actionIndex = index } - }, - onPressRow: { index in - mutate { $0.focus = .actions; $0.actionIndex = index } - if index < page.rows.count { page.rows[index].action() } - }, - width: BuildSourcesPanel.narrowWidth) - } - .spotlightBlock(.column) + aboutAndColumn(page, state: state) { + detailsPanel(page, state: state) } - .frame(width: canvas.u(1700), alignment: .topLeading) - .padding(.top, canvas.u(44)) - .spotlightBlock(.description) if let mods = modsHost.localMods, modsHost.game?.id == game.id { DetailsModsBand( @@ -945,27 +1234,32 @@ public struct SpotlightView: View { .spotlightBlock(.mods) } - if !page.more.isEmpty { - DetailsMoreBand( - games: page.more, - focusedIndex: state.focus == .more ? state.moreIndex : nil, - artwork: artwork, - boxArt: viewModel.boxArt, - boxArtIndexVersion: viewModel.boxArtIndexVersion, - officialName: { viewModel.storeMetadata[$0.id]?.name }, - onFocus: { index in mutate { $0.focus = .more; $0.moreIndex = index } }, - onOpen: { index in - SoundEffectService.shared.play(.click) - selectGame(page.more[index].id) - }) + relatedBand(page, state: state) + } + } + + @ViewBuilder + private func relatedBand(_ page: SpotlightPageModel, state: SpotlightState) -> some View { + if !page.more.isEmpty { + DetailsMoreBand( + games: page.more, + focusedIndex: state.focus == .more ? state.moreIndex : nil, + artwork: artwork, + boxArt: viewModel.boxArt, + boxArtIndexVersion: viewModel.boxArtIndexVersion, + officialName: { viewModel.storeMetadata[$0.id]?.name }, + onFocus: { index in mutate { $0.focus = .more; $0.moreIndex = index } }, + onOpen: { index in + SoundEffectService.shared.play(.click) + selectGame(page.more[index].id) + }) .padding(.top, canvas.u(Self.moreGap)) .spotlightBlock(.more) - } } } private func loadLogo(_ game: PortedGame?) async { await art.loadLogo(game: game, metadata: game.flatMap { viewModel.storeMetadata[$0.id]}, - artwork: artwork) + artwork: artwork, personalizations: viewModel.personalizations) } } diff --git a/Sources/NXLibrary/Views/Spotlight/TierCrystal.swift b/Sources/NXLibrary/Views/Spotlight/TierCrystal.swift new file mode 100644 index 00000000..a884c411 --- /dev/null +++ b/Sources/NXLibrary/Views/Spotlight/TierCrystal.swift @@ -0,0 +1,44 @@ +import SwiftUI +import AppKit +import NXLibraryCore + +/// A tier's crystal (Arcane, Gold, Silver, Bronze), from the prerendered art in Core's resources. Dimmed: +/// a tier not earned yet, or a locked achievement's tier — gray and faint, so the lit ones read first. +/// Draws nothing if the art is missing. +struct TierCrystal: View { + @Environment(\.seleneCanvas) private var canvas + + let tier: AchievementTier + /// The square the art fills, in canvas units; the crystal is about half as wide as it is tall. + let size: CGFloat + var dimmed = false + + var body: some View { + Group { + if let image = Self.image(tier) { + Image(nsImage: image) + .resizable() + .interpolation(.high) + .aspectRatio(contentMode: .fit) + // Not earned: a trace of its colour, so gold, silver and bronze still tell apart (in black and + // white the three read alike; maintainer's choice, 16 Nov 2026). + .saturation(dimmed ? 0.35 : 1) + .opacity(dimmed ? 0.55 : 1) + } else { + Color.clear + } + } + .frame(width: canvas.u(size), height: canvas.u(size)) + .accessibilityHidden(true) + } + + /// Four small PNGs, decoded once and kept for the app's life. + @MainActor private static var cache: [AchievementTier: NSImage] = [:] + + @MainActor private static func image(_ tier: AchievementTier) -> NSImage? { + if let image = cache[tier] { return image } + guard let url = tier.imageURL, let image = NSImage(contentsOf: url) else { return nil } + cache[tier] = image + return image + } +} diff --git a/Sources/NXLibrary/Views/Store/ModStorePage.swift b/Sources/NXLibrary/Views/Store/ModStorePage.swift index 570fddb7..0db54ed6 100644 --- a/Sources/NXLibrary/Views/Store/ModStorePage.swift +++ b/Sources/NXLibrary/Views/Store/ModStorePage.swift @@ -69,7 +69,7 @@ struct ModStorePage: View { Text(line).seleneFont(18, .medium).foregroundColor(SeleneTheme.ink75) } } - Text(L10n.text("Mod data provided by GameBanana · only mods that work with NX Library are shown")) + Text(L10n.text("Mod data provided by GameBanana · only mods that work with Arcane are shown")) .seleneFont(14) .foregroundColor(SeleneTheme.ink60) } @@ -85,7 +85,7 @@ struct ModStorePage: View { case .ready: if catalog.games.isEmpty { return catalog.refreshing ? L10n.text("Looking for mods that work with your games…") - : L10n.text("No mods for your games work with NX Library yet.") + : L10n.text("No mods for your games work with Arcane yet.") } return catalog.refreshing ? L10n.text("Looking for more mods…") : nil } diff --git a/Sources/NXLibrary/Views/Theme/CatalogPersonalizationsEnvironment.swift b/Sources/NXLibrary/Views/Theme/CatalogPersonalizationsEnvironment.swift new file mode 100644 index 00000000..2fc86e61 --- /dev/null +++ b/Sources/NXLibrary/Views/Theme/CatalogPersonalizationsEnvironment.swift @@ -0,0 +1,13 @@ +import SwiftUI +import NXLibraryCore + +private struct CatalogPersonalizationsKey: EnvironmentKey { + static let defaultValue = CatalogPersonalizations.empty +} + +extension EnvironmentValues { + var catalogPersonalizations: CatalogPersonalizations { + get { self[CatalogPersonalizationsKey.self] } + set { self[CatalogPersonalizationsKey.self] = newValue } + } +} diff --git a/Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift b/Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift index 4b4bbe3a..c6adadd9 100644 --- a/Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift +++ b/Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift @@ -3,8 +3,9 @@ import Metal import QuartzCore import CoreVideo import NXLibraryCore +import os -/// The shaders' uniforms, four float4s (see `MoonlightShaders`). +/// The shaders' uniforms, seven float4s (see `MoonlightShaders`). struct MoonlightUniforms { var size: SIMD4<Float> var accent: SIMD4<Float> @@ -16,19 +17,24 @@ struct MoonlightUniforms { } /// The moonlight's colors, as the shaders take them. -struct MoonlightColors: Equatable { +struct MoonlightColors: Equatable, Hashable { var accent: SIMD3<Float> var ink: SIMD3<Float> /// How much of the Mods card's gold ground the shader draws under the light (0...1); glides with the accent. var tint: Float = 0 /// The whole layer's opacity (0...1): the Mods card's moonlight over a wallpaper glides in and out with it. var presence: Float = 1 + var arcane: Float = 0 + var flow: Float = 0 - init(accent: Color, ink: Color, tint: Float = 0, presence: Float = 1) { + init(accent: Color, ink: Color, tint: Float = 0, presence: Float = 1, + surface: MoonlightSurface = .classic) { self.accent = Self.rgb(accent) self.ink = Self.rgb(ink) self.tint = tint self.presence = presence + self.arcane = surface == .classic ? 0 : 1 + self.flow = surface == .flow ? 1 : 0 } /// The Mods card's ground (`SeleneBackdrop.modsGradient` at the base's 0.6 over the black scrim). @@ -85,7 +91,7 @@ final class MoonlightEngine: @unchecked Sendable { light = try pipeline("moon_full_vertex", "moon_light_fragment") dots = try pipeline("moon_dot_vertex", "moon_dot_fragment") } catch { - NSLog("NX Library: moonlight shaders unavailable: \(error)") + NSLog("Arcane: moonlight shaders unavailable: \(error)") return nil } guard let buffer = particles.withUnsafeBytes({ @@ -103,7 +109,7 @@ final class MoonlightEngine: @unchecked Sendable { return MoonlightUniforms(size: SIMD4(w, h, time, w / h), accent: SIMD4(colors.accent, 1), ink: SIMD4(colors.ink, 0), - look: SIMD4(breath, colors.presence, 0, 0), + look: SIMD4(breath, colors.presence, colors.flow, colors.arcane), tintTop: SIMD4(MoonlightColors.tintTop, colors.tint), tintMid: SIMD4(MoonlightColors.tintMid, 0), tintBottom: SIMD4(MoonlightColors.tintBottom, 0)) @@ -122,10 +128,9 @@ final class MoonlightEngine: @unchecked Sendable { encoder.endEncoding() } - /// Renders one frame into the layer's next drawable and presents it. Safe - /// from any thread: the render thread while moving, the main thread otherwise. - func render(into layer: CAMetalLayer, uniforms: MoonlightUniforms) { - guard let drawable = layer.nextDrawable(), let buffer = queue.makeCommandBuffer() else { return } + /// Renders one frame into a drawable the caller already has (a `CAMetalDisplayLink` update) and presents it. + func render(into drawable: CAMetalDrawable, uniforms: MoonlightUniforms) { + guard let buffer = queue.makeCommandBuffer() else { return } let pass = MTLRenderPassDescriptor() pass.colorAttachments[0].texture = drawable.texture pass.colorAttachments[0].loadAction = .clear @@ -137,7 +142,8 @@ final class MoonlightEngine: @unchecked Sendable { } /// One still frame as an image (the Theme screen's preview, clipped to its rounded card). - func snapshot(width: Int, height: Int, colors: MoonlightColors) -> CGImage? { + func snapshot(width: Int, height: Int, colors: MoonlightColors, + time: Float = stillTime, breath: Float = stillBreath) -> CGImage? { guard width > 0, height > 0 else { return nil } let d = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false) @@ -149,8 +155,8 @@ final class MoonlightEngine: @unchecked Sendable { pass.colorAttachments[0].loadAction = .clear pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0) pass.colorAttachments[0].storeAction = .store - encode(pass, buffer, Self.uniforms(width: width, height: height, time: Self.stillTime, - breath: Self.stillBreath, colors: colors)) + encode(pass, buffer, Self.uniforms(width: width, height: height, time: time, + breath: breath, colors: colors)) if texture.storageMode == .managed, let blit = buffer.makeBlitCommandEncoder() { blit.synchronize(resource: texture) blit.endEncoding() @@ -187,10 +193,26 @@ struct MoonlightMetalView: NSViewRepresentable { /// A Metal layer drawn from a display link on its own thread, so a busy main /// thread (a game's art arriving, the page laying out) never stalls the motes. +/// +/// On macOS 14 and later the link is a `CAMetalDisplayLink` asking for 60 fps: it tells the +/// system how often the motes change, so a variable-refresh display (ProMotion) keeps its +/// rate while nothing else on screen moves, and it hands over each drawable when the screen +/// can take it. A `CVDisplayLink` says neither: idle for ~10 s, the display slowed down and +/// `nextDrawable` waited up to 80 ms (measured: 60 fps fell to ~30). macOS 13 keeps it. +/// +/// On macOS 14 and later only the link draws, still frames included: while a `CAMetalDisplayLink` is attached the +/// layer's drawables are its own and `nextDrawable` raises an exception (two crashes, 14 Nov 2026). A still frame +/// (the motes stopping, a new size) runs the link for one frame, which then stops (`State.stillPending`). final class MoonlightLayerView: NSView { + private static let transitionLog = Logger(subsystem: "local.nxlibrary.development", category: "backdrop-transition") + private let traceID = String(UUID().uuidString.prefix(6)) + private let createdAt = CACurrentMediaTime() + private var tracedPresentation = false private let engine: MoonlightEngine private let metalLayer = CAMetalLayer() private var link: CVDisplayLink? + /// The `CAMetalDisplayLink` (macOS 14+), held untyped for the macOS 13 build. + private var metalLink: AnyObject? private var occlusion: NSObjectProtocol? /// Shared with the render thread, under `lock`. @@ -210,6 +232,8 @@ final class MoonlightLayerView: NSView { /// Starts part way in, so the motes are already spread along the road. var clock: Double = 40 var lastTick: CFTimeInterval? + /// A still frame waits for the link (macOS 14+): it runs for that frame, then stops. + var stillPending = false } private var state = State() private let lock = NSLock() @@ -217,6 +241,7 @@ final class MoonlightLayerView: NSView { static let blend: CFTimeInterval = 1.2 /// The frame rate's ceiling (a 120 Hz display draws every other refresh). private static let frameInterval = 1.0 / 60 - 0.002 + static let framesPerSecond: Float = 60 init(engine: MoonlightEngine) { self.engine = engine @@ -228,6 +253,9 @@ final class MoonlightLayerView: NSView { metalLayer.colorspace = CGColorSpace(name: CGColorSpace.sRGB) metalLayer.needsDisplayOnBoundsChange = false wantsLayer = true + if AppData.profile.isDevelopment { + Self.transitionLog.notice("Backdrop created \(self.traceID, privacy: .public)") + } } required init?(coder: NSCoder) { nil } @@ -251,8 +279,20 @@ final class MoonlightLayerView: NSView { state.moving = moving if !moving { state.lastTick = nil } lock.unlock() - updateLink() - if !moving { renderFrame() } + if moving { updateLink() } else { drawStill() } + } + + /// One still frame: from the link on macOS 14+ (the only one to take the layer's drawables), here before. + private func drawStill() { + if #available(macOS 14.0, *) { + lock.lock() + state.stillPending = true + lock.unlock() + updateLink() + } else { + updateLink() + renderFrame() + } } /// Gone (presence 0, no glide): the layer is hidden and draws nothing, so a moonlight kept ready over a @@ -276,6 +316,7 @@ final class MoonlightLayerView: NSView { func stop() { if let link { CVDisplayLinkStop(link) } link = nil + stopMetalLink() if let occlusion { NotificationCenter.default.removeObserver(occlusion) } occlusion = nil } @@ -319,7 +360,7 @@ final class MoonlightLayerView: NSView { metalLayer.contentsScale = scale if metalLayer.drawableSize != size { metalLayer.drawableSize = size - renderFrame() + drawStill() } } @@ -334,6 +375,8 @@ final class MoonlightLayerView: NSView { c.ink = from.ink + (c.ink - from.ink) * e c.tint = from.tint + (c.tint - from.tint) * e c.presence = from.presence + (c.presence - from.presence) * e + c.arcane = from.arcane + (c.arcane - from.arcane) * e + c.flow = from.flow + (c.flow - from.flow) * e return c } @@ -345,9 +388,14 @@ final class MoonlightLayerView: NSView { private func updateLink() { lock.lock() let now = CACurrentMediaTime() - let run = ((state.moving && !isAbsent(at: now)) || blending(at: now)) && state.visible && window != nil + let run = (((state.moving || state.stillPending) && !isAbsent(at: now)) || blending(at: now)) + && state.visible && window != nil lock.unlock() updateVisibility() + if #available(macOS 14.0, *) { + if run { startMetalLink() } else { stopMetalLink() } + return + } if run { if link == nil { var created: CVDisplayLink? @@ -366,6 +414,31 @@ final class MoonlightLayerView: NSView { } } + @available(macOS 14.0, *) + private func startMetalLink() { + guard metalLink == nil else { return } + let link = CAMetalDisplayLink(metalLayer: metalLayer) + link.preferredFrameRateRange = CAFrameRateRange(minimum: Self.framesPerSecond / 2, + maximum: Self.framesPerSecond, + preferred: Self.framesPerSecond) + let target = MoonlightLinkTarget(view: self) + link.delegate = target + metalLink = MoonlightLinkHandle(link: link, target: target) + MoonlightRenderThread.shared.perform { link.add(to: .current, forMode: .default) } + } + + /// The layer's last frame stays on screen. + private func stopMetalLink() { + guard let handle = metalLink as? MoonlightLinkHandle else { return } + metalLink = nil + if #available(macOS 14.0, *), let link = handle.link as? CAMetalDisplayLink { link.invalidate() } + } + + /// The render thread, on the `CAMetalDisplayLink` (macOS 14+): `presentation` is when the frame shows. + fileprivate func render(_ drawable: CAMetalDrawable, presentation: CFTimeInterval) { + renderFrame(at: presentation, drawable: drawable) + } + /// The display link's thread. private func tick() { let now = CACurrentMediaTime() @@ -378,7 +451,7 @@ final class MoonlightLayerView: NSView { renderFrame(at: now) } - private func renderFrame(at now: CFTimeInterval = CACurrentMediaTime()) { + private func renderFrame(at now: CFTimeInterval = CACurrentMediaTime(), drawable: CAMetalDrawable? = nil) { lock.lock() if state.moving { // A late frame (the window was hidden or the link paused) never skips ahead. @@ -390,15 +463,97 @@ final class MoonlightLayerView: NSView { let colors = Self.blended(state, at: now) let glideEnded = state.from != nil && !blending(at: now) if glideEnded { state.from = nil } + // The link's frame is the still frame it ran for. + let stillDrawn = drawable != nil && state.stillPending + if drawable != nil { state.stillPending = false } lock.unlock() - // The glide is over: a still layer's link stops on its last frame, a gone one hides. - if glideEnded { DispatchQueue.main.async { [weak self] in self?.updateLink() } } + // The glide or the still frame is over: a still layer's link stops on its last frame, a gone one hides. + if glideEnded || stillDrawn { DispatchQueue.main.async { [weak self] in self?.updateLink() } } let size = metalLayer.drawableSize guard size.width >= 1, size.height >= 1 else { return } let breath = Float(0.5 + 0.5 * sin(2 * .pi * clock / MoonlightEngine.breathPeriod)) - engine.render(into: metalLayer, uniforms: MoonlightEngine.uniforms( - width: Int(size.width), height: Int(size.height), - time: Float(clock), breath: breath, colors: colors)) + let uniforms = MoonlightEngine.uniforms(width: Int(size.width), height: Int(size.height), + time: Float(clock), breath: breath, colors: colors) + // Both display-link paths announce readiness only when an acquired drawable is presented. + guard let frame = drawable ?? metalLayer.nextDrawable() else { return } + Self.announceFirstFrame(frame) + traceFirstPresentation(frame) + engine.render(into: frame, uniforms: uniforms) + } + + /// Local Dev diagnostics for a newly mounted background; no per-frame logging. + private func traceFirstPresentation(_ drawable: CAMetalDrawable) { + guard AppData.profile.isDevelopment else { return } + lock.lock() + let alreadyTraced = tracedPresentation + tracedPresentation = true + lock.unlock() + guard !alreadyTraced else { return } + let id = traceID, start = createdAt + drawable.addPresentedHandler { _ in + let milliseconds = (CACurrentMediaTime() - start) * 1_000 + Self.transitionLog.notice("Backdrop presented \(id, privacy: .public), since creation \(milliseconds, privacy: .public) ms") + } + } + + /// The first frame any moonlight puts on screen in this launch lets the window show (`LaunchReveal`). + private static var firstFrameAnnounced = false + private static let firstFrameLock = NSLock() + + private static func announceFirstFrame(_ drawable: CAMetalDrawable) { + firstFrameLock.lock() + let first = !firstFrameAnnounced + firstFrameAnnounced = true + firstFrameLock.unlock() + guard first else { return } + // The handler must be registered before the command buffer presents the drawable. + drawable.addPresentedHandler { _ in Task { @MainActor in LaunchReveal.moonlightShown() } } + } +} + +/// The link and its delegate, kept together (the link holds its delegate weakly). +private final class MoonlightLinkHandle { + let link: AnyObject + let target: AnyObject + init(link: AnyObject, target: AnyObject) { self.link = link; self.target = target } +} + +@available(macOS 14.0, *) +private final class MoonlightLinkTarget: NSObject, CAMetalDisplayLinkDelegate { + weak var view: MoonlightLayerView? + init(view: MoonlightLayerView) { self.view = view } + func metalDisplayLink(_ link: CAMetalDisplayLink, needsUpdate update: CAMetalDisplayLink.Update) { + view?.render(update.drawable, presentation: update.targetPresentationTimestamp) + } +} + +/// One thread with its own run loop for the moonlight's display links, so the motes never wait on the main thread. +private final class MoonlightRenderThread: Thread { + static let shared: MoonlightRenderThread = { + let thread = MoonlightRenderThread() + thread.name = "Moonlight render" + thread.qualityOfService = .userInteractive + thread.start() + thread.ready.wait() + return thread + }() + + private let ready = DispatchSemaphore(value: 0) + private var loop: CFRunLoop? + + override func main() { + loop = CFRunLoopGetCurrent() + // A port keeps the run loop alive while no link is attached. + RunLoop.current.add(NSMachPort(), forMode: .default) + ready.signal() + while true { RunLoop.current.run(mode: .default, before: .distantFuture) } + } + + /// Runs `work` on this thread's run loop. + func perform(_ work: @escaping () -> Void) { + guard let loop else { return } + CFRunLoopPerformBlock(loop, CFRunLoopMode.defaultMode.rawValue, work) + CFRunLoopWakeUp(loop) } } @@ -408,6 +563,11 @@ struct MoonlightStill: View { let colors: MoonlightColors @Environment(\.displayScale) private var scale @State private var image: CGImage? + private struct Key: Hashable { + let width: Int + let height: Int + let colors: MoonlightColors + } var body: some View { GeometryReader { geometry in @@ -417,7 +577,7 @@ struct MoonlightStill: View { Image(decorative: image, scale: scale).resizable() } } - .task(id: [w, h] + [colors.accent, colors.ink].flatMap { [$0.x, $0.y, $0.z].map { Int($0 * 255) } }) { + .task(id: Key(width: w, height: h, colors: colors)) { // Keep the last frame while resizing. A cancelled request never // replaces the latest size/palette with a late result. do { try await Task.sleep(nanoseconds: 40_000_000) } catch { return } diff --git a/Sources/NXLibrary/Views/Theme/MoonlightShaders.swift b/Sources/NXLibrary/Views/Theme/MoonlightShaders.swift index 467357c6..5cbfb3c4 100644 --- a/Sources/NXLibrary/Views/Theme/MoonlightShaders.swift +++ b/Sources/NXLibrary/Views/Theme/MoonlightShaders.swift @@ -1,3 +1,5 @@ +import NXLibraryCore + /// The moonlight's Metal shaders, compiled at launch by the system's runtime /// compiler (SwiftPM builds no .metal files, and the app needs no Metal toolchain). /// @@ -7,6 +9,10 @@ /// brightest channel, so the layer composites over the theme's gradient like a /// screen blend. enum MoonlightShaders { + private static let spectrum = MoonlightChromatics.colors.map { + "float3(\($0.x), \($0.y), \($0.z))" + }.joined(separator: ", ") + static let source = #""" #include <metal_stdlib> using namespace metal; @@ -15,7 +21,7 @@ struct Uniforms { float4 size; // width px, height px, time s, aspect float4 accent; // rgb, overall strength float4 ink; // rgb, unused - float4 look; // breath 0...1, presence 0...1 (the whole layer's opacity), unused... + float4 look; // breath, presence, Flow blend, Arcane surface blend float4 tintTop; // the Mods card's ground: top rgb, amount 0...1 float4 tintMid; // rgb at 0.45 of the height float4 tintBottom; // rgb at the bottom @@ -23,6 +29,95 @@ struct Uniforms { struct Particle { float start, lane, depth, speed, size, phase, kind, tint; }; +constant float3 arcaneColors[3] = { \#(spectrum) }; +constant float arcanePeriod = \#(MoonlightChromatics.period); +constant float arcaneIntensity = \#(MoonlightChromatics.intensity); + +float3 arcaneSpectrum(float2 uv, float time, float offset) { + float phase = time / arcanePeriod * 6.2831853; + float2 p = (uv - float2(0.18,0.77)) / float2(0.42,0.5); + float2 c = (uv - float2(0.84,0.43)) / float2(0.42,0.5); + float pw = exp(-dot(p,p)), cw = exp(-dot(c,c)); + float3 drift = float3(2.5*sin(phase),1.8*sin(phase+1.0),2.6*sin(phase+2.0))/255.0; + return (arcaneColors[0]*pw + arcaneColors[1]*cw + arcaneColors[2]*0.25)/(pw+cw+0.25)+drift; +} + +// Analytic moving surfaces, evaluated in the existing light pass. No texture, +// geometry upload, extra timer, or sampling loop per pixel. +float arcaneGlow(float2 uv, float2 centre, float2 radius) { + float2 d=(uv-centre)/radius; + return exp(-dot(d,d)*2.5); +} + +// Travelling, overlapping wind waves bend the whole thread, not just its glow. +float filamentY(float x, float2 a, float2 b, float bend, float phase, float seed) { + float s=clamp((x-a.x)/(b.x-a.x),0.0,1.0); + float envelope=sin(s*3.1415927); + float wind=0.026*sin(s*5.2-phase*1.35+seed) + + 0.009*sin(s*11.7-phase*1.91+seed*0.63); + return mix(a.y,b.y,s) + envelope*(bend+wind); +} + +// A subpixel luminous core integrated across a pixel. Soft, dim scattering +// gives it air without widening it into a neon ribbon. +float filamentProfile(float distancePixels) { + return 0.34*exp(-0.5*distancePixels*distancePixels/0.25) + + 0.018*exp(-0.5*distancePixels*distancePixels/4.84); +} + +float3 filament(float2 uv, float2 a, float2 b, float bend, float phase, + float time, float seed, float3 color, float height) { + float s=(uv.x-a.x)/(b.x-a.x); + float gate=smoothstep(0.0,0.12,s)*(1.0-smoothstep(0.78,1.0,s)); + float y=filamentY(uv.x,a,b,bend,phase,seed); + float distance=uv.y-y; + float footprint=max(length(float2(dfdx(distance),dfdy(distance))),1.0/height); + float separation=(0.0015+0.006*sin(clamp(s,0.0,1.0)*3.1415927)) + *(0.75+0.25*sin(s*4.8-phase*0.8+seed)); + float strands=filamentProfile(distance/footprint) + + 0.32*filamentProfile((distance-separation)/footprint) + + 0.18*filamentProfile((distance+separation*1.4)/footprint); + float glint=0.78+0.22*cos(6.2831853*(s*0.65-time/(100.0+seed*3.0)-seed*0.137)); + return color*gate*strands*glint; +} + +float3 arcaneSurface(float2 uv,float time,float flow,float height) { + float phase=time/ mix(120.0,140.0,flow)*6.2831853; + float2 left=mix(float2(0.18,0.77),float2(0.12,0.79),flow) + + float2(0.006*sin(phase),0.009*cos(phase)); + float2 right=mix(float2(0.84,0.43),float2(0.93,0.56),flow) + + float2(0.007*sin(phase+2.0),0.012*cos(phase+2.0)); + float cp=time/arcanePeriod*6.2831853; + float3 drift=float3(2.5*sin(cp),1.8*sin(cp+1.0),2.6*sin(cp+2.0))/255.0; + float3 pink=arcaneColors[0]+drift, cyan=arcaneColors[1]+drift; + float3 base=mix(mix(float3(0.094,0.09,0.18),float3(0.035,0.055,0.125),uv.y), + mix(float3(0.165,0.16,0.30),float3(0.078,0.118,0.208),uv.y),flow); + float3 result=base+pink*arcaneGlow(uv,left,float2(0.40,0.48))*mix(0.016,0.022,flow) + + cyan*arcaneGlow(uv,right,float2(0.37,0.47))*mix(0.015,0.021,flow) + + arcaneColors[2]*arcaneGlow(uv,float2(0.22,0.2),float2(0.6,0.8))*mix(0.006,0.014,flow); + float3 angular = float3(0.0); + if (flow < 1.0) { + float2 junction=float2(0.56+0.007*sin(phase+1.0),0.60+0.015*sin(phase+0.3)); + float2 upper=float2(0.96+0.008*sin(phase),0.26+0.01*cos(phase+1.0)); + angular=filament(uv,left,junction,0.007,phase,time,0.0,pink,height) + + filament(uv,right,junction,0.007,phase,time,4.0,cyan,height) + + filament(uv,right,upper,0.004,phase,time,6.0,cyan,height) + + filament(uv,left,float2(0.32,0.49),0.003,phase,time,2.0,pink*0.3,height); + } + float3 flowing = float3(0.0); + if (flow > 0.0) { + float2 a=float2(-0.06,0.49+0.012*sin(phase)), b=float2(0.72,1.02+0.012*cos(phase)); + float2 c=float2(1.04,0.31+0.013*cos(phase)), d=float2(0.38,0.79+0.009*sin(phase+2.0)); + float bendA=0.045+0.022*sin(phase+0.7),bendB=0.08+0.024*sin(phase+0.5); + flowing=filament(uv,a,b,bendA,phase,time,1.0,pink,height) + + filament(uv,c,d,bendB,phase,time,4.0,cyan,height) + + filament(uv,float2(-0.02,0.87),float2(0.58,0.94),-0.07+0.016*sin(phase+1.0),phase,time,7.0,pink*0.35,height); + } + result+=mix(angular,flowing,flow); + float vignette=1.0-0.2*smoothstep(0.4,1.0,length((uv-float2(0.5,0.48))*float2(1.0,0.8))); + return result*vignette; +} + // MARK: Look (window heights and shares of the width) constant float2 beamSource = float2(0.14, -0.20); // x: share of the width @@ -106,7 +201,16 @@ vertex FullOut moon_full_vertex(uint vid [[vertex_id]]) { fragment float4 moon_light_fragment(FullOut in [[stage_in]], constant Uniforms &u [[buffer(0)]]) { float aspect = u.size.w, t = u.size.z, breath = u.look.x; float2 p = in.position.xy / u.size.y; + float2 uv = float2(p.x / aspect, p.y); + // Uniform branch: a settled Arcane surface does not evaluate the classic beam. + // Intermediate blends still draw both paths for the shared colour glide. + if (u.look.w >= 1.0 && u.tintTop.w <= 0.0) { + float3 surface=arcaneSurface(uv,t,u.look.z,u.size.y); + surface+=(hash21(in.position.xy)-0.5)/255.0; + return float4(surface,1.0)*u.look.y; + } float3 accent = u.accent.rgb; + if (u.look.w > 0.0) { accent = mix(accent, arcaneSpectrum(uv, t, 0.0), u.look.w); } // The beam: a cone from above the top left that bends right as it falls, // its edges smoking slowly. @@ -155,6 +259,11 @@ fragment float4 moon_light_fragment(FullOut in [[stage_in]], constant Uniforms & // Dither so the dark gradients never band. c += (hash21(in.position.xy + fract(t)) - 0.5) / 255.0; float4 light = premultiplied(c); + if (u.look.w > 0.0) { + float3 surface=arcaneSurface(uv,t,u.look.z,u.size.y); + surface+=(hash21(in.position.xy)-0.5)/255.0; + light=mix(light,float4(surface,1.0),u.look.w); + } // The Mods card's ground under the light, as opaque as `amount`: drawn here, on the render thread, so it // glides in step with the accent and costs a few operations per pixel of a pass that runs anyway. float amount = u.tintTop.w; @@ -257,6 +366,11 @@ vertex DotOut moon_dot_vertex(uint vid [[vertex_id]], uint iid [[instance_id]], o.alpha = place.life * spread * far * twinkle * bright * u.accent.w * u.look.y * clamp(sharp / 0.9, 0.3, 1.0); o.bokeh = smoothstep(2.5, 12.0, blur); o.color = q.tint > 0.5 ? mix(u.ink.rgb, u.accent.rgb, 0.25) : mix(u.accent.rgb, float3(1.0), 0.3); + if (u.look.w > 0.0) { + float3 spectral = arcaneSpectrum(float2(p.x / aspect, p.y), t, q.phase * 0.11); + o.color = mix(o.color, mix(spectral, float3(1.0), q.tint > 0.5 ? 0.55 : 0.18), u.look.w); + } + o.alpha *= mix(1.0, arcaneIntensity * 1.45 * mix(0.85, 0.22, o.bokeh), u.look.w); return o; } diff --git a/Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift b/Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift index 35255059..7f5cf18c 100644 --- a/Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift +++ b/Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift @@ -4,12 +4,36 @@ import NXLibraryCore /// What the backdrop draws, set once on the shell from settings. struct SeleneBackdropStyle: Equatable { + var palette: SelenePalette = .fallback var wallpaperURL: URL? var sizing: BackgroundSizing = .fill var animated = true var brightness: WallpaperBrightness = .balanced } +/// Pages describe the background; the shell keeps the drawing surface alive. +struct SeleneBackdropRequest: Equatable { + var style: SeleneBackdropStyle + var baseOpacity = 0.6 + var still = false + var modsTint = false + var priority: Double = 0 +} + +struct SeleneBackdropRequestKey: PreferenceKey { + static let defaultValue: SeleneBackdropRequest? = nil + static func reduce(value: inout SeleneBackdropRequest?, nextValue: () -> SeleneBackdropRequest?) { + if let next = nextValue() { + if let current = value, current.priority > next.priority { return } + value = next + } + } +} + +private struct SeleneSharesBackdropKey: EnvironmentKey { + static let defaultValue = false +} + extension WallpaperBrightness { /// A left-to-right mask carrying the setting's opacity, for a wallpaper or a video. var mask: LinearGradient { @@ -23,6 +47,10 @@ private struct SeleneBackdropStyleKey: EnvironmentKey { } extension EnvironmentValues { + var seleneSharesBackdrop: Bool { + get { self[SeleneSharesBackdropKey.self] } + set { self[SeleneSharesBackdropKey.self] = newValue } + } var seleneBackdropStyle: SeleneBackdropStyle { get { self[SeleneBackdropStyleKey.self] } set { self[SeleneBackdropStyleKey.self] = newValue } @@ -48,6 +76,7 @@ final class WallpaperImageCache { /// moonlight, `MoonlightBackdrop`): moving when on and motion is allowed, still otherwise. struct SeleneBackdrop: View { @Environment(\.seleneBackdropStyle) private var style + @Environment(\.seleneSharesBackdrop) private var sharesBackdrop @Environment(\.seleneReduceMotion) private var reduceMotion /// The base gradient's opacity; the wallpaper's follows Wallpaper brightness. @@ -81,11 +110,26 @@ struct SeleneBackdrop: View { } var body: some View { + Group { + if sharesBackdrop { + Color.clear.preference(key: SeleneBackdropRequestKey.self, + value: SeleneBackdropRequest(style: style, baseOpacity: baseOpacity, + still: still, modsTint: modsTint)) + } else { + drawing + } + } + .ignoresSafeArea() + .allowsHitTesting(false) + .accessibilityHidden(true) + } + + private var drawing: some View { let moving = style.animated && !reduceMotion && !still let hasWallpaper = style.wallpaperURL != nil return ZStack { - SeleneTheme.scrim - Rectangle().fill(SeleneTheme.baseGradient).opacity(baseOpacity) + Color(hex: style.palette.scrim) + Rectangle().fill(SeleneTheme.baseGradient(for: style.palette)).opacity(baseOpacity) if MoonlightEngine.shared == nil { // Without Metal the tint is a layer of its own; with it the moonlight's shader draws the ground, // in step with its light and off the main thread. @@ -99,19 +143,21 @@ struct SeleneBackdrop: View { wallpaper(image) .mask(style.brightness.mask) } else { - MoonlightBackdrop(accent: modsTint ? Self.modsAccent : SeleneTheme.glyph, ink: SeleneTheme.ink, - tint: modsTint ? 1 : 0, moving: moving) + MoonlightBackdrop(accent: modsTint ? Self.modsAccent : Color(hex: style.palette.glyph), + ink: Color(hex: style.palette.ink), + tint: modsTint ? 1 : 0, moving: moving, + surface: modsTint ? .classic : style.palette.surface) } if hasWallpaper, MoonlightEngine.shared != nil { // Over a wallpaper the Mods card brings its own moonlight. It stays mounted (hidden and idle while // gone) and glides in and out on its render thread, so a quick there-and-back carries on from // where it is, and the motes never start over. - MoonlightBackdrop(accent: Self.modsAccent, ink: SeleneTheme.ink, tint: 1, + MoonlightBackdrop(accent: Self.modsAccent, ink: Color(hex: style.palette.ink), tint: 1, presence: modsTint ? 1 : 0, moving: moving) } else if modsTint, hasWallpaper { ZStack { modsGround - MoonlightBackdrop(accent: Self.modsAccent, ink: SeleneTheme.ink, tint: 1, moving: moving) + MoonlightBackdrop(accent: Self.modsAccent, ink: Color(hex: style.palette.ink), tint: 1, moving: moving) } .transition(.opacity) } @@ -125,7 +171,7 @@ struct SeleneBackdrop: View { /// The Mods card's ground, the base it replaces (its own scrim, so no blue shows through and greys it). private var modsGround: some View { ZStack { - SeleneTheme.scrim + Color(hex: style.palette.scrim) Rectangle().fill(Self.modsGradient).opacity(baseOpacity) } } @@ -151,7 +197,7 @@ struct SeleneBackdrop: View { /// theme's accent falling from the top left onto a pool of light on the floor, /// breathing; from the pool a band of thousands of motes rises to the right, far /// ones fine and sharp, near ones blurred into bokeh. Drawn by Metal -/// (`MoonlightEngine`, `MoonlightShaders`; the field is `MoonlightField`), 30 fps +/// (`MoonlightEngine`, `MoonlightShaders`; the field is `MoonlightField`), 60 fps /// or one still frame. Without Metal, the beam and pool hold still in SwiftUI. struct MoonlightBackdrop: View { let accent: Color @@ -163,9 +209,11 @@ struct MoonlightBackdrop: View { var moving = true /// A still image instead of a live layer: for small cards that clip and round it. var asImage = false + var surface: MoonlightSurface = .classic var body: some View { - let colors = MoonlightColors(accent: accent, ink: ink, tint: tint, presence: presence) + let colors = MoonlightColors(accent: accent, ink: ink, tint: tint, presence: presence, + surface: surface) if let engine = MoonlightEngine.shared { if asImage { MoonlightStill(engine: engine, colors: colors) @@ -188,8 +236,13 @@ struct MoonlightBackdrop: View { var squeezed = context squeezed.translateBy(x: size.width * x, y: size.height * y) squeezed.scaleBy(x: size.width * rx / radius, y: 1) + let light: Color + if surface != .classic { + let rgb = MoonlightChromatics.sample(x: Float(x), y: Float(y), time: MoonlightEngine.stillTime) + light = Color(.sRGB, red: Double(rgb.x), green: Double(rgb.y), blue: Double(rgb.z), opacity: 1) + } else { light = accent } squeezed.fill(Path(ellipseIn: CGRect(x: -radius, y: -radius, width: 2 * radius, height: 2 * radius)), - with: .radialGradient(Gradient(colors: [accent.opacity(strength), accent.opacity(0)]), + with: .radialGradient(Gradient(colors: [light.opacity(strength), light.opacity(0)]), center: .zero, startRadius: 0, endRadius: radius)) } } diff --git a/Sources/NXLibrary/Views/Theme/SeleneTheme.swift b/Sources/NXLibrary/Views/Theme/SeleneTheme.swift index 705b491c..24d0f138 100644 --- a/Sources/NXLibrary/Views/Theme/SeleneTheme.swift +++ b/Sources/NXLibrary/Views/Theme/SeleneTheme.swift @@ -22,6 +22,7 @@ public enum SeleneTheme { /// Selene's confirmation card (dialogs are a touch more solid than rows). public static var glassCard: Color { Color(hex: palette.glass, opacity: 0.96) } public static var glyph: Color { Color(hex: palette.glyph) } + static var moonlightSurface: MoonlightSurface { palette.surface } /// Every list icon in one colour: on Selene a soft ink (its blue accent read poorly /// on the glass), elsewhere the palette's glyph. public static var rowIcon: Color { palette.id == SelenePaletteCatalog.defaultID ? ink82 : glyph } @@ -58,7 +59,8 @@ public enum SeleneTheme { public static let standard = Animation.timingCurve(0.32, 0.72, 0, 1, duration: 0.24) public static let focusIn = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.18) public static let focusOut = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.20) - public static let screen = Animation.timingCurve(0.32, 0.72, 0, 1, duration: 0.32) + public static let screenDuration = 0.32 + public static let screen = Animation.timingCurve(0.32, 0.72, 0, 1, duration: screenDuration) public static func cubicOut(_ duration: Double) -> Animation { .timingCurve(0.215, 0.61, 0.355, 1, duration: duration) } diff --git a/Sources/NXLibrary/Views/Theme/ThemePickerView.swift b/Sources/NXLibrary/Views/Theme/ThemePickerView.swift index af9225bb..76305fcd 100644 --- a/Sources/NXLibrary/Views/Theme/ThemePickerView.swift +++ b/Sources/NXLibrary/Views/Theme/ThemePickerView.swift @@ -52,7 +52,7 @@ struct ThemePickerView: View { var body: some View { ZStack(alignment: .top) { - SeleneBackdrop() + SeleneBackdrop().still(true) Color.black.opacity(0.3).ignoresSafeArea() Group { @@ -155,7 +155,7 @@ struct ThemePickerView: View { private var themeStep: some View { let palette = palettes[min(state.themeIndex, palettes.count - 1)] return ZStack(alignment: .top) { - header(L10n.text("Choose your theme"), L10n.text("Colors for all of NX Library. Move through them to see each one in the preview.")) + header(L10n.text("Choose your theme"), L10n.text("Colors for all of Arcane. Move through them to see each one in the preview.")) HStack(alignment: .top, spacing: canvas.u(60)) { grid(count: palettes.count, columns: ThemePickerState.themeColumns) { index in swatch(palettes[index], focused: index == state.themeIndex) @@ -163,7 +163,8 @@ struct ThemePickerView: View { } VStack(alignment: .leading, spacing: 0) { ThemePreview(palette: palette, wallpaperURL: previewWallpaper(theme: palette), - games: games, width: 780, shade: settings.settings.backgroundShade) + games: games, width: 780, shade: settings.settings.backgroundShade, + animated: settings.settings.animatedBackground) chips(palette) .padding(.top, canvas.u(18)) .padding(.leading, canvas.u(4)) @@ -302,7 +303,8 @@ struct ThemePickerView: View { } VStack(alignment: .leading, spacing: 0) { ThemePreview(palette: theme.palette, wallpaperURL: previewURL(focused), games: games, width: 820, - videoURL: previewVideo, shade: settings.settings.backgroundShade) + videoURL: previewVideo, shade: settings.settings.backgroundShade, + animated: settings.settings.animatedBackground) Text(creditLine(focused) ?? " ") .seleneFont(17) .foregroundColor(SeleneTheme.ink75) @@ -409,7 +411,8 @@ struct ThemePickerView: View { tileLabel("Theme's own") case .none: if state.tab == .live { - MoonlightBackdrop(accent: SeleneTheme.glyph, ink: SeleneTheme.ink, moving: false, asImage: true) + MoonlightBackdrop(accent: SeleneTheme.glyph, ink: SeleneTheme.ink, moving: false, asImage: true, + surface: SeleneTheme.moonlightSurface) } tileLabel(state.tab == .live ? L10n.text("Moonlight") : "None") case .add: @@ -762,8 +765,8 @@ struct ThemePickerView: View { let live = state.tab == .live let panel = NSOpenPanel() panel.message = live - ? L10n.text("Choose a video for your live background (MP4, MOV or M4V). NX Library keeps its own copy and plays it muted.") - : L10n.text("Choose a picture for your background. NX Library keeps its own copy.") + ? L10n.text("Choose a video for your live background (MP4, MOV or M4V). Arcane keeps its own copy and plays it muted.") + : L10n.text("Choose a picture for your background. Arcane keeps its own copy.") panel.allowedContentTypes = live ? WallpaperCatalog.videoExtensions.compactMap { UTType(filenameExtension: $0) } : [.image] @@ -830,7 +833,7 @@ struct ThemePickerView: View { let name = theme.credits[id]?.title ?? theme.wallpaperTitle(for: id) var message = downloaded ? L10n.format("%@ goes to the Trash, so you can bring it back from there, or download it again whenever you like.", [String(describing: (name))]) - : L10n.format("NX Library's copy of %@ goes to the Trash, so you can bring it back from there. Your original file stays where it is.", [String(describing: (name))]) + : L10n.format("Arcane's copy of %@ goes to the Trash, so you can bring it back from there. Your original file stays where it is.", [String(describing: (name))]) if settings.settings.wallpaperID == id { message += L10n.text(" Your theme’s own background takes its place.") } return ZStack { SeleneTheme.scrim45 diff --git a/Sources/NXLibrary/Views/Theme/ThemePreview.swift b/Sources/NXLibrary/Views/Theme/ThemePreview.swift index 12bce29d..1898daea 100644 --- a/Sources/NXLibrary/Views/Theme/ThemePreview.swift +++ b/Sources/NXLibrary/Views/Theme/ThemePreview.swift @@ -16,6 +16,8 @@ struct ThemePreview: View { var videoURL: URL? = nil /// The home's Background shade, so the preview is as dark as the home and no darker. var shade: BackgroundShade = .balanced + var animated = false + @Environment(\.seleneReduceMotion) private var reduceMotion @Environment(\.seleneBackdropStyle) private var style @State private var art: [NSImage] = [] @@ -47,7 +49,9 @@ struct ThemePreview: View { } } else { MoonlightBackdrop(accent: Color(hex: palette.glyph), ink: Color(hex: palette.ink), - moving: false, asImage: true) + moving: animated && !reduceMotion, + asImage: !animated || reduceMotion, + surface: palette.surface) } SeleneShades(shade: shade, scrim: Color(hex: palette.scrim)) home(w: w, h: h) diff --git a/Sources/NXLibraryCore/Models/AchievementSummary.swift b/Sources/NXLibraryCore/Models/AchievementSummary.swift new file mode 100644 index 00000000..eb8b43f3 --- /dev/null +++ b/Sources/NXLibraryCore/Models/AchievementSummary.swift @@ -0,0 +1,142 @@ +import Foundation + +/// The Achievements screen's filters (LB/RB). +public enum AchievementFilter: CaseIterable, Sendable { + case all, unlocked, locked +} + +/// The order of the screen's list (Y), inside the filter. Default: unlocked newest first, then locked most +/// common first. By rarity, the achievements whose rarity is unknown come last; ties keep the default order. +public enum AchievementOrder: CaseIterable, Sendable { + case `default`, rarest, commonest +} + +/// One achievement as the card and the screen show it. A hidden achievement still locked is masked. +public struct AchievementRow: Equatable, Identifiable, Sendable { + /// Steam's API name. + public let id: String + public let name: String + public let description: String + /// The color icon once unlocked, the gray one while locked. + public let icon: String? + public let unlockedAt: Date? + /// Share of Steam's players who have it, 0–100; nil while unknown. + public let percent: Double? + public let isMasked: Bool + + /// Its crystal from its rarity; nil while the rarity is unknown. + public var tier: AchievementTier? { AchievementTier.forPercent(percent) } +} + +/// A game's achievements for the page's card and the Achievements screen, from `SteamAchievementReader` and +/// Steam's public rarity. Pure: the views only render it. +public struct AchievementSummary: Equatable, Sendable { + public let total: Int + public let unlocked: Int + private let unlockedRows: [AchievementRow] + private let lockedRows: [AchievementRow] + + public init(achievements: [SteamAchievement], percents: [String: Double]) { + let rows = achievements.enumerated().map { index, achievement in + (index, Self.row(achievement, percent: percents[achievement.apiName])) + } + total = achievements.count + unlockedRows = rows.filter { $0.1.unlockedAt != nil } + .sorted { ($0.1.unlockedAt!, -$0.0) > ($1.1.unlockedAt!, -$1.0) }.map(\.1) + unlocked = unlockedRows.count + // Most common first; unknown rarity after, in Steam's order. + lockedRows = rows.filter { $0.1.unlockedAt == nil } + .sorted { Self.commoner($0.1.percent, $0.0, than: $1.1.percent, $1.0) }.map(\.1) + } + + /// Every achievement unlocked, which earns Arcane; never without achievements. + public var isComplete: Bool { total > 0 && unlocked == total } + + /// Rounded to a whole percent; 0 without achievements. + public var percentComplete: Int { + total > 0 ? Int((Double(unlocked) * 100 / Double(total)).rounded()) : 0 + } + + /// The last three unlocked with an icon, newest first; before any unlock, the first three locked ones in gray. + /// Rows, not file names: the card shows a secret among them locked (`AchievementRow.isMasked`). + public var recentIcons: [AchievementRow] { + Array((unlockedRows.isEmpty ? lockedRows : unlockedRows).filter { $0.icon != nil }.prefix(3)) + } + + /// Unlocked and total per tier. Arcane is one per game, lit when everything is unlocked (0/0 without + /// achievements); the others count the achievements whose rarity is known. + public var tierCounts: [AchievementTier: TierCount] { + var counts: [AchievementTier: TierCount] = [ + .arcane: TierCount(unlocked: isComplete ? 1 : 0, total: total > 0 ? 1 : 0), + ] + for tier in [AchievementTier.gold, .silver, .bronze] { + counts[tier] = TierCount(unlocked: unlockedRows.filter { $0.tier == tier }.count, + total: (unlockedRows + lockedRows).filter { $0.tier == tier }.count) + } + return counts + } + + /// The best crystal earned, for the page's card: Arcane with everything unlocked, otherwise the rarest tier + /// among the unlocked achievements; nil with nothing unlocked or while their rarity is unknown. + public var bestTier: AchievementTier? { + if isComplete { return .arcane } + let earned = Set(unlockedRows.compactMap(\.tier)) + return AchievementTier.allCases.first { earned.contains($0) } + } + + /// Whether Steam's rarity has arrived for any achievement. + public var hasRarity: Bool { (unlockedRows + lockedRows).contains { $0.percent != nil } } + + /// When the newest unlock happened. + public var lastUnlockedAt: Date? { unlockedRows.first?.unlockedAt } + + /// The Achievements screen's Recently unlocked strip: the newest unlocked icons first, at most `limit`; + /// none before the first unlock. + public func recentUnlockedIcons(limit: Int) -> [String] { + Array(unlockedRows.compactMap(\.icon).prefix(limit)) + } + + public func rows(_ filter: AchievementFilter, order: AchievementOrder = .default) -> [AchievementRow] { + let rows: [AchievementRow] + switch filter { + case .all: rows = unlockedRows + lockedRows + case .unlocked: rows = unlockedRows + case .locked: rows = lockedRows + } + guard order != .default else { return rows } + let rarestFirst = order == .rarest + // The default position breaks ties, so a re-read never shuffles them. + let known: [(position: Int, percent: Double, row: AchievementRow)] = rows.enumerated().compactMap { item in + item.element.percent.map { (item.offset, $0, item.element) } + } + let sorted = known.sorted { a, b in + if a.percent == b.percent { return a.position < b.position } + return rarestFirst ? a.percent < b.percent : a.percent > b.percent + } + return sorted.map(\.row) + rows.filter { $0.percent == nil } + } + + private static func commoner(_ a: Double?, _ ai: Int, than b: Double?, _ bi: Int) -> Bool { + switch (a, b) { + case let (a?, b?): return a != b ? a > b : ai < bi + case (.some, nil): return true + case (nil, .some): return false + case (nil, nil): return ai < bi + } + } + + private static func row(_ achievement: SteamAchievement, percent: Double?) -> AchievementRow { + let unlocked = achievement.unlockedAt != nil + let masked = !unlocked && achievement.hidden + return AchievementRow( + id: achievement.apiName, + name: masked ? L10n.text("Hidden achievement") : achievement.name, + description: masked ? L10n.text("Keep playing to reveal it.") : achievement.description, + // A masked row never falls back to the color icon: it would give the secret away. + icon: unlocked ? (achievement.icon ?? achievement.grayIcon) + : masked ? achievement.grayIcon : (achievement.grayIcon ?? achievement.icon), + unlockedAt: achievement.unlockedAt, + percent: percent, + isMasked: masked) + } +} diff --git a/Sources/NXLibraryCore/Models/AchievementTier.swift b/Sources/NXLibraryCore/Models/AchievementTier.swift new file mode 100644 index 00000000..49b87c78 --- /dev/null +++ b/Sources/NXLibraryCore/Models/AchievementTier.swift @@ -0,0 +1,56 @@ +import Foundation + +/// A tier crystal, as PS5 trophies: one Arcane per game for unlocking everything (the violet crystal, where +/// PS5 has Platinum), and Gold, Silver or Bronze for each achievement from how many Steam players have it. +/// Declared rarest first: the Achievements screen's board shows them in this order. +public enum AchievementTier: CaseIterable, Sendable { + case arcane, gold, silver, bronze + + /// Fewer than one player in ten. + public static let goldBelow = 10.0 + /// Fewer than three in ten; the rest is bronze. + public static let silverBelow = 30.0 + + /// An achievement's tier from Steam's global rarity (0–100); nil while unknown. Never arcane. + public static func forPercent(_ percent: Double?) -> AchievementTier? { + guard let raw = percent else { return nil } + // The screen shows one decimal: 9.96 reads "10.0%", so it must not be Gold. + let percent = (raw * 10).rounded() / 10 + if percent < goldBelow { return .gold } + if percent < silverBelow { return .silver } + return .bronze + } + + /// The tier's crystal: a 1024 px PNG of the maintainer's own art, large enough for the achievement detail, in + /// Core's resources; found as the translations are (the installed app's bundle first); nil only if it is missing. + public var imageURL: URL? { + L10n.resources()?.url(forResource: "crystal-\(self)", withExtension: "png") + } + + /// Arcane's looping video, the maintainer's own (chosen on 16 Nov 2026): 384 px HEVC with alpha, 180 frames at + /// 24 fps; nil for the other tiers, which stay still. + public var videoURL: URL? { + self == .arcane ? L10n.resources()?.url(forResource: "crystal-arcane", withExtension: "mov") : nil + } + + /// The tier's name in the app's language (or `context`'s): Arcane, Gold, Silver, Bronze. + public func displayName(context: AppLocale? = nil) -> String { + switch self { + case .arcane: return L10n.text("Arcane", context: context) + case .gold: return L10n.text("Gold", context: context) + case .silver: return L10n.text("Silver", context: context) + case .bronze: return L10n.text("Bronze", context: context) + } + } +} + +/// How many achievements of a tier are unlocked, out of how many. +public struct TierCount: Equatable, Sendable { + public let unlocked: Int + public let total: Int + + public init(unlocked: Int, total: Int) { + self.unlocked = unlocked + self.total = total + } +} diff --git a/Sources/NXLibraryCore/Models/AchievementsScreenState.swift b/Sources/NXLibraryCore/Models/AchievementsScreenState.swift new file mode 100644 index 00000000..557b62d3 --- /dev/null +++ b/Sources/NXLibraryCore/Models/AchievementsScreenState.swift @@ -0,0 +1,89 @@ +import Foundation + +/// Selection on the Achievements screen: a filter, an order and a row in a one-column list, clamped to its edges. +/// It keeps the rows' ids so a list that changes under it (the rarity arriving, an unlock) keeps the same +/// achievement in focus. A opens the focused achievement's detail over the list; moving while it is open steps +/// the detail through the list. +public struct AchievementsScreenState: Equatable { + public enum MoveDirection: Sendable { case up, down, left, right } + + public static let columns = 1 + + public private(set) var filter: AchievementFilter = .all + public private(set) var order: AchievementOrder = .default + public var index = 0 + /// The current filter's rows, by `AchievementRow.id`. + public private(set) var ids: [String] + /// The focused achievement's detail is over the list. + public private(set) var isDetailOpen = false + + public init(ids: [String]) { + self.ids = ids + } + + public var count: Int { ids.count } + + public var focusedID: String? { ids.indices.contains(index) ? ids[index] : nil } + + /// Moves within the list; returns whether the selection moved. + @discardableResult + public mutating func move(_ direction: MoveDirection) -> Bool { + guard count > 0 else { return false } + let column = index % Self.columns + let next: Int + switch direction { + case .left: next = column > 0 ? index - 1 : index + case .right: next = column < Self.columns - 1 && index + 1 < count ? index + 1 : index + case .up: next = index >= Self.columns ? index - Self.columns : index + case .down: next = index + Self.columns < count ? index + Self.columns : index + } + defer { index = next } + return next != index + } + + /// Opens the focused achievement's detail; returns false when the list is empty. + @discardableResult + public mutating func openDetail() -> Bool { + isDetailOpen = focusedID != nil + return isDetailOpen + } + + public mutating func closeDetail() { + isDetailOpen = false + } + + /// A new filter starts at its first tile, with the detail closed. + public mutating func setFilter(_ filter: AchievementFilter, ids: [String]) { + isDetailOpen = false + self.filter = filter + self.ids = ids + index = 0 + } + + /// Y: the next order, wrapping around, from the top of the list; `ids` gives the rows in that order. + public mutating func cycleOrder(ids: (AchievementOrder) -> [String]) { + let all = AchievementOrder.allCases + order = all[((all.firstIndex(of: order) ?? 0) + 1) % all.count] + isDetailOpen = false + self.ids = ids(order) + index = 0 + } + + /// LB/RB: the filter beside the current one, wrapping around; `ids` gives each filter's rows. + public mutating func shiftFilter(by delta: Int, ids: (AchievementFilter) -> [String]) { + let all = AchievementFilter.allCases + let current = all.firstIndex(of: filter) ?? 0 + let next = all[((current + delta) % all.count + all.count) % all.count] + setFilter(next, ids: ids(next)) + } + + /// The list changed under the same filter: the focused achievement keeps the focus where it went; + /// gone from the list, its place does, inside the list, and an open detail closes rather than show another. + public mutating func setIDs(_ ids: [String]) { + let focused = focusedID + let kept = focused.flatMap { ids.firstIndex(of: $0) } + self.ids = ids + index = kept ?? min(index, max(ids.count - 1, 0)) + if kept == nil { isDetailOpen = false } + } +} diff --git a/Sources/NXLibraryCore/Models/AppIconProgress.swift b/Sources/NXLibraryCore/Models/AppIconProgress.swift index 4c1c2c1f..d7c5b338 100644 --- a/Sources/NXLibraryCore/Models/AppIconProgress.swift +++ b/Sources/NXLibraryCore/Models/AppIconProgress.swift @@ -10,7 +10,7 @@ public enum AppIconProgress: Equatable { case .searching: return L10n.text("Looking for an icon…") case .updating: return L10n.text("Updating the app icon in Finder and the Dock… large games can take a minute") case .updated: return L10n.text("App icon updated in Finder and the Dock") - case .launcherOnly: return L10n.text("Icon used only in NX Library") + case .launcherOnly: return L10n.text("Icon used only in Arcane") case .original: return L10n.text("Using the game's original app icon") case .unavailable: return L10n.text("No icon available. You can choose one.") case .failed(let reason): return L10n.format("The app icon was not changed: %@", [String(describing: (reason))]) @@ -28,6 +28,6 @@ public enum AppIconProgress: Equatable { let handle = try FileHandle(forWritingTo: url) defer { try? handle.close() } try handle.seekToEnd() - try handle.write(contentsOf: Data("\n[NX Library · Icon] \(buildMessage)\n".utf8)) + try handle.write(contentsOf: Data("\n[Arcane · Icon] \(buildMessage)\n".utf8)) } } diff --git a/Sources/NXLibraryCore/Models/AppIdentity.swift b/Sources/NXLibraryCore/Models/AppIdentity.swift new file mode 100644 index 00000000..492472c6 --- /dev/null +++ b/Sources/NXLibraryCore/Models/AppIdentity.swift @@ -0,0 +1,21 @@ +import Foundation + +/// The app's visible name and the one User-Agent every web request sends. The public project page +/// is the contact Wikidata asks clients for; no personal data goes in it. +public enum AppIdentity { + public static let name = "Arcane" + /// The name players knew before Arcane; only the one-time welcome says it. + public static let formerName = "NX Library" + /// The module that ports games to the Mac. A name, like the app's, so it is never translated. + public static let portingName = "Porting" + public static let projectPage = "https://github.com/Bium23/NxLibrary" + + /// The running app's version, "0" when the bundle has none (tests, command-line runs). + public static var version: String { + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" + } + + public static func userAgent(version: String = AppIdentity.version) -> String { + "\(name)/\(version) (macOS; +\(projectPage))" + } +} diff --git a/Sources/NXLibraryCore/Models/AppSettings.swift b/Sources/NXLibraryCore/Models/AppSettings.swift index 448a1d19..e4960550 100644 --- a/Sources/NXLibraryCore/Models/AppSettings.swift +++ b/Sources/NXLibraryCore/Models/AppSettings.swift @@ -169,6 +169,10 @@ public struct AppSettings: Codable, Equatable { public var keepWallpaperOnGames = false /// A card with this session's and the total playtime when a game closes. public var showsSessionCard = true + /// Steam starts silently and stays out of sight while a Steam game starts; it comes back if it needs the player. + public var steamInBackground = true + /// The one-time "Welcome to Arcane" screen was shown, or a first setup finished (new installs never see it). + public var welcomeArcaneShown = false public init(backgroundShade: BackgroundShade = .balanced, readableText: Bool = true, @@ -256,6 +260,8 @@ public struct AppSettings: Codable, Equatable { case wallpaperID, backgroundSizing, animatedBackground, wallpaperBrightness, launchStyle, launchMotion, launchShade case notifyPortingEnds, checkAppUpdatesAtLaunch case settingsWallpaperID, keepWallpaperOnGames, showsSessionCard + case steamInBackground + case welcomeArcaneShown } public init(from decoder: Decoder) throws { @@ -303,5 +309,7 @@ public struct AppSettings: Codable, Equatable { self.settingsWallpaperID = try container.decodeIfPresent(String.self, forKey: .settingsWallpaperID) self.keepWallpaperOnGames = try container.decodeIfPresent(Bool.self, forKey: .keepWallpaperOnGames) ?? false self.showsSessionCard = try container.decodeIfPresent(Bool.self, forKey: .showsSessionCard) ?? true + self.steamInBackground = try container.decodeIfPresent(Bool.self, forKey: .steamInBackground) ?? true + self.welcomeArcaneShown = try container.decodeIfPresent(Bool.self, forKey: .welcomeArcaneShown) ?? false } } diff --git a/Sources/NXLibraryCore/Models/ArcaneWelcome.swift b/Sources/NXLibraryCore/Models/ArcaneWelcome.swift new file mode 100644 index 00000000..4d4d7617 --- /dev/null +++ b/Sources/NXLibraryCore/Models/ArcaneWelcome.swift @@ -0,0 +1,57 @@ +import Foundation + +/// The one-time "Welcome to Arcane" screen for players who update from NX Library: when it shows, +/// the Steam offer it may carry, its focus and how every exit marks it shown. +public enum ArcaneWelcome { + /// Once, after the update: setup already done, never shown, and no save recovery or failed + /// install waiting (those screens come first, so the welcome waits for them). + public static func shouldShow(setupCompleted: Bool, shown: Bool, hasPendingRecovery: Bool) -> Bool { + setupCompleted && !shown && !hasPendingRecovery + } + + public enum Offer: Equatable, Sendable { + case steam(gameCount: Int) + } + + /// Steam is offered only when it was found with games and its source is still off. + public static func offer(steamEnabled: Bool, steamGameCount: Int?) -> Offer? { + guard !steamEnabled, let count = steamGameCount, count > 0 else { return nil } + return .steam(gameCount: count) + } + + /// Open library, or B / Esc. + public enum Exit: CaseIterable, Sendable { case openLibrary, back } + + public static func markShown(_ settings: AppSettings) -> AppSettings { + var next = settings + next.welcomeArcaneShown = true + return next + } + + /// Every exit marks the welcome shown, so it never comes back. + public static func settings(after exit: Exit, from settings: AppSettings) -> AppSettings { + markShown(settings) + } + + public enum Focus: Equatable, Sendable { + case add, notNow, openLibrary + + public static func order(offer: Offer?) -> [Focus] { + offer == nil ? [.openLibrary] : [.add, .notNow, .openLibrary] + } + + public static func initial(offer: Offer?) -> Focus { order(offer: offer)[0] } + + /// Add and Not now sit side by side on the offer row; Open library is below it. + public func moved(_ direction: MoveDirection, offer: Offer?) -> Focus { + guard offer != nil else { return .openLibrary } + switch (self, direction) { + case (.add, .right): return .notNow + case (.notNow, .left): return .add + case (.add, .down), (.notNow, .down): return .openLibrary + case (.openLibrary, .up): return .add + default: return self + } + } + } +} diff --git a/Sources/NXLibraryCore/Models/BuildWarningCopy.swift b/Sources/NXLibraryCore/Models/BuildWarningCopy.swift index 425cd046..d2b0a3ca 100644 --- a/Sources/NXLibraryCore/Models/BuildWarningCopy.swift +++ b/Sources/NXLibraryCore/Models/BuildWarningCopy.swift @@ -4,6 +4,10 @@ import Foundation /// was built and plays, but without something that stage makes. public enum BuildWarningCopy { public static func text(stage: String, summary: String?) -> String { + if stage.localizedCaseInsensitiveContains(PortingProgress.prewarmStageName) { + return L10n.text("Some pipelines could not be prepared during porting. The game will prepare them on its first start, which can take longer. ") + + L10n.text("The log has the reason; rebuilding tries again.") + } if stage.localizedCaseInsensitiveContains("pipeline archive") { return L10n.text("The pipeline archive could not be made, so the app was packed without one. ") + L10n.text("The game prepares its shaders the first time it needs them, so its first start can take longer. ") diff --git a/Sources/NXLibraryCore/Models/CatalogBuildRecoveries.swift b/Sources/NXLibraryCore/Models/CatalogBuildRecoveries.swift new file mode 100644 index 00000000..5ebf8143 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogBuildRecoveries.swift @@ -0,0 +1,41 @@ +import Foundation + +/// Session-only outcomes whose file effects happened but whose catalog save did +/// not. Never choose an older persisted pending app over a retained generation. +public struct CatalogBuildRecoveries { + private var records: [UUID: PortedGame] = [:] + public init() {} + public subscript(id: UUID) -> PortedGame? { records[id] } + public var values: [PortedGame] { Array(records.values) } + public var isEmpty: Bool { records.isEmpty } + + public mutating func retain(_ outcome: PortedGame) { records[outcome.id] = outcome } + public mutating func acknowledge(id: UUID, matching expected: PortedGame?) { + if records[id] == expected { records[id] = nil } + } + public func pendingCandidate(persisted: PortedGame, explicitRetry: Bool) throws -> PortedGame? { + guard let retained = records[persisted.id] else { return persisted } + guard explicitRetry else { return nil } + var result = persisted + try result.applyCatalogBuildOutcome(retained) + return result + } +} + +extension PortedGame { + public mutating func applyCatalogBuildOutcome(_ outcome: PortedGame) throws { + guard id == outcome.id else { throw CatalogModelError.identityMismatch } + url = outcome.url + sizeBytes = outcome.sizeBytes + modificationDate = outcome.modificationDate + bundleId = outcome.bundleId + versionString = outcome.versionString + status = outcome.status + toolchain = outcome.toolchain + lastBuild = outcome.lastBuild + portingFailure = outcome.portingFailure + portingFailureReason = outcome.portingFailureReason + pendingInstall = outcome.pendingInstall + appIconPending = outcome.appIconPending + } +} diff --git a/Sources/NXLibraryCore/Models/CatalogDocument.swift b/Sources/NXLibraryCore/Models/CatalogDocument.swift new file mode 100644 index 00000000..b4f69eb1 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogDocument.swift @@ -0,0 +1,86 @@ +import Foundation + +public struct CatalogSourceConfiguration: Codable, Equatable, Sendable { + public let integration: CatalogIntegration + public var isEnabled: Bool + public var rootURL: URL? + public internal(set) var generation: UUID + + public init(integration: CatalogIntegration, isEnabled: Bool = false, rootURL: URL? = nil, generation: UUID = UUID()) { + self.integration = integration; self.isEnabled = isEnabled; self.rootURL = rootURL; self.generation = generation + } + private enum CodingKeys: String, CodingKey { case integration, isEnabled, rootURL, generation } + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + integration = try c.decode(CatalogIntegration.self, forKey: .integration) + isEnabled = try c.decode(Bool.self, forKey: .isEnabled) + rootURL = try c.decodeIfPresent(URL.self, forKey: .rootURL) + // Older schema-one files predate source generations. Use a stable + // sentinel until the first explicit source configuration transaction. + generation = try c.decodeIfPresent(UUID.self, forKey: .generation) + ?? UUID(uuidString: "00000000-0000-0000-0000-000000000000")! + } + +} + +/// Fingerprint of the legacy input at migration or the last explicit conflict +/// acknowledgement. Legacy files remain untouched, not another writable catalog. +public struct CatalogLegacyOrigin: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case absent, primary, backup } + public let kind: Kind + public let sha256: String? + public static let absent = Self(kind: .absent, sha256: nil) +} + +public struct CatalogDocument: Codable, Equatable { + public let schemaVersion: Int + public internal(set) var revision: UUID + public let legacyOrigin: CatalogLegacyOrigin + public var sources: [CatalogSourceConfiguration] + public var games: [CatalogGame] + + public init(schemaVersion: Int = 1, revision: UUID = UUID(), legacyOrigin: CatalogLegacyOrigin = .absent, + sources: [CatalogSourceConfiguration] = [.init(integration: .nxnative), .init(integration: .steam)], + games: [CatalogGame] = []) { + self.schemaVersion = schemaVersion; self.revision = revision; self.legacyOrigin = legacyOrigin + self.sources = sources; self.games = games + } + + public func source(_ integration: CatalogIntegration) -> CatalogSourceConfiguration? { + sources.first { $0.integration == integration } + } + + public static func converting(_ legacy: LibraryFile, origin: CatalogLegacyOrigin = .absent) throws -> Self { + guard legacy.schemaVersion == 1 else { throw CatalogModelError.unsupportedSchema(legacy.schemaVersion) } + let result = Self(legacyOrigin: origin, sources: [.init(integration: .nxnative, isEnabled: true), .init(integration: .steam)], + games: legacy.games.map { .init(nxnative: $0) }) + try result.validate() + return result + } + + public func validate() throws { + guard schemaVersion == 1 else { throw CatalogModelError.unsupportedSchema(schemaVersion) } + guard Set(sources.map(\.integration)).count == sources.count else { throw CatalogModelError.invalidRecord } + switch legacyOrigin.kind { + case .absent: guard legacyOrigin.sha256 == nil else { throw CatalogModelError.invalidRecord } + case .primary, .backup: + guard let digest = legacyOrigin.sha256, digest.utf8.count == 64, + digest.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { throw CatalogModelError.invalidRecord } + } + for source in sources { + if let root = source.rootURL, !root.isFileURL { throw CatalogModelError.invalidRecord } + if source.integration == .steam && source.isEnabled && source.rootURL == nil { throw CatalogModelError.invalidRecord } + } + var ids = Set<UUID>(), appIDs = Set<UInt32>(), installationIDs = Set<UUID>() + for game in games { + try game.validateRecord() + guard ids.insert(game.id).inserted else { throw CatalogModelError.duplicateGameID } + if let steam = game.steamGame { + guard appIDs.insert(steam.appID).inserted else { throw CatalogModelError.duplicateSteamAppID } + for installation in steam.installations { + guard installationIDs.insert(installation.id).inserted else { throw CatalogModelError.duplicateInstallationID } + } + } + } + } +} diff --git a/Sources/NXLibraryCore/Models/CatalogGame.swift b/Sources/NXLibraryCore/Models/CatalogGame.swift new file mode 100644 index 00000000..b2837945 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogGame.swift @@ -0,0 +1,224 @@ +import Foundation + +public enum CatalogIntegration: String, Codable, Hashable, Sendable { case nxnative, steam } + +/// Namespace and key travel together: a legacy free-form key cannot collide with Steam storage. +public struct CatalogPersonalizationReference: Codable, Equatable, Sendable { + public let namespace: CatalogIntegration + public let key: String +} + +public enum CatalogModelError: Error, Equatable { + case wrongIntegration, identityMismatch, invalidRecord, duplicateGameID, duplicateSteamAppID, duplicateInstallationID + case unsupportedSchema(Int) +} + +public enum CatalogInstallationAvailability: String, Codable, Sendable { + case available, unavailable, requiresReview, notDetected, sourceUnavailable +} + +public struct CatalogNativeApplication: Codable, Equatable, Sendable { + public let url: URL + public let executableURL: URL + public let bundleIdentifier: String? + public let name: String + public let architectures: [MacExecutableArchitecture] + public let isDeclaredGame: Bool + + public init(_ observed: NativeMacApplication) { + url = observed.url + executableURL = observed.executableURL + bundleIdentifier = observed.bundleIdentifier + name = observed.name + architectures = observed.architectures.sorted { $0.rawValue < $1.rawValue } + isDeclaredGame = observed.isDeclaredGame + } +} + +public struct SteamCatalogInstallation: Codable, Equatable, Identifiable, Sendable { + public let id: UUID + public var libraryURL: URL + public var contentURL: URL + public var applications: [CatalogNativeApplication] + public var availability: CatalogInstallationAvailability + public var reportedSizeBytes: Int64? + public var buildID: String? + public var lastObservedAt: Date + /// Steam has not finished installing it (no FullyInstalled flag); `availability` stays `.unavailable`. + /// A separate key, not an availability case, so a catalog written now still loads in an older NX Library. + public var isDownloading: Bool + + public init(id: UUID = UUID(), libraryURL: URL, contentURL: URL, applications: [CatalogNativeApplication] = [], + availability: CatalogInstallationAvailability = .requiresReview, reportedSizeBytes: Int64? = nil, + buildID: String? = nil, lastObservedAt: Date = Date(), isDownloading: Bool = false) { + self.isDownloading = isDownloading + self.id = id + self.libraryURL = libraryURL + self.contentURL = contentURL + self.applications = applications + self.availability = availability + self.reportedSizeBytes = reportedSizeBytes + self.buildID = buildID + self.lastObservedAt = lastObservedAt + } + + public var primaryApplication: CatalogNativeApplication? { + let games = applications.filter(\.isDeclaredGame) + return games.count == 1 ? games[0] : nil + } + + private enum CodingKeys: String, CodingKey { + case id, libraryURL, contentURL, applications, availability, reportedSizeBytes, buildID, lastObservedAt, isDownloading + } + + /// Catalogs written before downloads were tracked have no `isDownloading`: not downloading. + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(UUID.self, forKey: .id) + libraryURL = try c.decode(URL.self, forKey: .libraryURL) + contentURL = try c.decode(URL.self, forKey: .contentURL) + applications = try c.decode([CatalogNativeApplication].self, forKey: .applications) + availability = try c.decode(CatalogInstallationAvailability.self, forKey: .availability) + reportedSizeBytes = try c.decodeIfPresent(Int64.self, forKey: .reportedSizeBytes) + buildID = try c.decodeIfPresent(String.self, forKey: .buildID) + lastObservedAt = try c.decode(Date.self, forKey: .lastObservedAt) + isDownloading = try c.decodeIfPresent(Bool.self, forKey: .isDownloading) ?? false + } +} + +public struct SteamCatalogGame: Codable, Equatable, Identifiable, Sendable { + public let id: UUID + public let appID: UInt32 + public var name: String + public var isFavorite = false + public var isHidden = false + public var hasBeenRecognized = false + /// Ambiguity survives missing/partial sources; only complete evidence clears it. + public var needsInstallationReview = false + public var installations: [SteamCatalogInstallation] = [] + + public init(id: UUID = UUID(), appID: UInt32, name: String) { self.id = id; self.appID = appID; self.name = name } + + /// Descriptive lookup in catalog order, shared by artwork, facts and process observation. + /// Play separately checks source status, review and installation uniqueness in `CatalogGamePresentation`. + public var firstAvailableInstallation: SteamCatalogInstallation? { + installations.first { $0.availability == .available } + } + + /// Steam is installing it: of the installations still detected, the only one is downloading. An old folder no + /// longer detected (a game removed and installed again elsewhere) does not hide the download. + public var isDownloading: Bool { + let detected = installations.filter { $0.availability != .notDetected } + return detected.count == 1 && detected[0].isDownloading + } + + /// For Settings → Steam's "to review": never recognized or ambiguous, and not simply still downloading. + public var needsReview: Bool { !isDownloading && (!hasBeenRecognized || needsInstallationReview) } +} + +/// One catalog entry, with one owner for each field. The old record remains a +/// lossless nxnative payload; a Steam entry never needs its build/settings defaults. +public struct CatalogGame: Identifiable, Codable, Equatable { + enum Payload: Equatable { case nxnative(PortedGame), steam(SteamCatalogGame) } + private(set) var payload: Payload + public let personalizationReference: CatalogPersonalizationReference + + public init(nxnative game: PortedGame) { + payload = .nxnative(game) + personalizationReference = .init(namespace: .nxnative, key: game.titleId ?? game.uniqueKey) + } + + public init(steam game: SteamCatalogGame) { + payload = .steam(game) + personalizationReference = .init(namespace: .steam, key: "steam-\(game.appID)") + } + + public var integration: CatalogIntegration { if case .nxnative = payload { return .nxnative }; return .steam } + public var id: UUID { switch payload { case .nxnative(let g): return g.id; case .steam(let g): return g.id } } + public var name: String { switch payload { case .nxnative(let g): return g.name; case .steam(let g): return g.name } } + public var isFavorite: Bool { switch payload { case .nxnative(let g): return g.isFavorite; case .steam(let g): return g.isFavorite } } + public var isHidden: Bool { switch payload { case .nxnative(let g): return g.isHidden; case .steam(let g): return g.isHidden } } + public var personalizationKey: String { personalizationReference.key } + public var nxnativeGame: PortedGame? { if case .nxnative(let g) = payload { return g }; return nil } + public var steamGame: SteamCatalogGame? { if case .steam(let g) = payload { return g }; return nil } + + public mutating func setFavorite(_ value: Bool) { + switch payload { + case .nxnative(var game): game.isFavorite = value; payload = .nxnative(game) + case .steam(var game): game.isFavorite = value; payload = .steam(game) + } + } + + public mutating func setHidden(_ value: Bool) { + switch payload { + case .nxnative(var game): game.isHidden = value; payload = .nxnative(game) + case .steam(var game): game.isHidden = value; payload = .steam(game) + } + } + + public mutating func updateNXNative(_ game: PortedGame) throws { + guard integration == .nxnative else { throw CatalogModelError.wrongIntegration } + guard id == game.id else { throw CatalogModelError.identityMismatch } + payload = .nxnative(game) + } + + mutating func updateSteam(_ game: SteamCatalogGame) throws { + guard let old = steamGame else { throw CatalogModelError.wrongIntegration } + guard old.id == game.id, old.appID == game.appID else { throw CatalogModelError.identityMismatch } + payload = .steam(game) + } + + func validateRecord() throws { + guard personalizationReference.namespace == integration, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw CatalogModelError.invalidRecord + } + switch payload { + case .nxnative(let game): + guard game.url.isFileURL, game.sizeBytes >= 0 else { throw CatalogModelError.invalidRecord } + case .steam(let game): + guard game.appID > 0, personalizationKey == "steam-\(game.appID)" else { throw CatalogModelError.invalidRecord } + var contentsByLibrary: [URL: Set<URL>] = [:] + for installation in game.installations { + guard contentsByLibrary[installation.libraryURL.standardizedFileURL, default: []] + .insert(installation.contentURL.standardizedFileURL).inserted else { throw CatalogModelError.invalidRecord } + guard installation.libraryURL.isFileURL, installation.contentURL.isFileURL, + installation.reportedSizeBytes.map({ $0 >= 0 }) != false, + installation.applications.allSatisfy({ $0.url.isFileURL && $0.executableURL.isFileURL }) else { + throw CatalogModelError.invalidRecord + } + let common = installation.libraryURL.appendingPathComponent("steamapps/common").standardizedFileURL + guard NativeMacApplication.isWithin(installation.contentURL.standardizedFileURL, root: common), + installation.contentURL.standardizedFileURL != common, + installation.applications.allSatisfy({ + $0.url.pathExtension.lowercased() == "app" && !$0.architectures.isEmpty && + NativeMacApplication.isWithin($0.url.standardizedFileURL, root: installation.contentURL.standardizedFileURL) && + NativeMacApplication.isWithin($0.executableURL.standardizedFileURL, root: $0.url.standardizedFileURL) + }) else { throw CatalogModelError.invalidRecord } + if installation.availability == .available, installation.primaryApplication == nil { + throw CatalogModelError.invalidRecord + } + } + } + } + + private enum CodingKeys: String, CodingKey { case integration, data, personalization } + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + switch try c.decode(CatalogIntegration.self, forKey: .integration) { + case .nxnative: payload = .nxnative(try c.decode(PortedGame.self, forKey: .data)) + case .steam: payload = .steam(try c.decode(SteamCatalogGame.self, forKey: .data)) + } + personalizationReference = try c.decode(CatalogPersonalizationReference.self, forKey: .personalization) + try validateRecord() + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(integration, forKey: .integration) + try c.encode(personalizationReference, forKey: .personalization) + switch payload { + case .nxnative(let game): try c.encode(game, forKey: .data) + case .steam(let game): try c.encode(game, forKey: .data) + } + } +} diff --git a/Sources/NXLibraryCore/Models/CatalogGameOptions.swift b/Sources/NXLibraryCore/Models/CatalogGameOptions.swift new file mode 100644 index 00000000..77380b34 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogGameOptions.swift @@ -0,0 +1,65 @@ +import Foundation + +/// Shared library operations are ordered once. What a game's source can do is fixed by its record's +/// payload: `CatalogRepository` and `CatalogGame` refuse an nxnative change on a Steam game (`wrongIntegration`). +public enum CatalogGameOptions { + /// The main list's rows every source offers, in the order nxnative's Game options shows them. + /// The store page sits in Edit details for every source. + public static func commonRows(origin: GameOptionsOrigin) -> [GameOptionsRow] { + var rows: [GameOptionsRow] = [.play, .editDetails] + if origin == .spotlight { rows.append(.move) } + rows += [.favorite, .hidden, .showInFinder] + return rows + } +} + +/// A Steam game's Options: only what NX Library can do for it. The shared rows keep +/// nxnative's order and look; nothing about engines, builds, saves or sources. +public struct SteamOptionsPresentation: Equatable, Sendable { + /// One available, recognized installation in an enabled source. + public let canPlay: Bool + /// The installation's app was found, so Finder has something to reveal. + public let hasApp: Bool + + public init(canPlay: Bool, hasApp: Bool) { + self.canPlay = canPlay + self.hasApp = hasApp + } + + public func entries(level: GameOptionsLevel, origin: GameOptionsOrigin) -> [GameOptionsEntry] { + switch level { + case .main: + return CatalogGameOptions.commonRows(origin: origin).map(GameOptionsEntry.row) + case .editDetails: + return [.heading("Edit details"), .row(.changeArtwork), .row(.changeMetadata), .row(.storePage)] + } + } + + public func focusableRows(level: GameOptionsLevel, origin: GameOptionsOrigin) -> [GameOptionsRow] { + entries(level: level, origin: origin).compactMap { entry in + if case .row(let row) = entry { return row } + return nil + } + } + + /// Dim rows still take focus; their action explains itself (Play shows why in the head). + public func isDimmed(_ row: GameOptionsRow) -> Bool { + switch row { + case .play: return !canPlay + case .showInFinder: return !hasApp + default: return false + } + } + + public func about(_ row: GameOptionsRow) -> String? { + switch row { + case .play: return L10n.text("Start the game through Steam.") + case .editDetails: return L10n.text("Artwork, metadata and the store page.") + case .changeArtwork: return L10n.text("Cover, background, icon and logo, from Steam, online sources or a file.") + case .storePage: return L10n.text("Open the game’s Steam store page.") + case .move, .favorite, .hidden, .showInFinder, .changeMetadata: + return GameOptionsPresentation(supportsRenderScale: false, isPlayable: false, sourcesDetached: false).about(row) + default: return nil + } + } +} diff --git a/Sources/NXLibraryCore/Models/CatalogGamePresentation.swift b/Sources/NXLibraryCore/Models/CatalogGamePresentation.swift new file mode 100644 index 00000000..3d3d6070 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogGamePresentation.swift @@ -0,0 +1,69 @@ +import Foundation + +public enum CatalogLaunchTarget: Equatable, Sendable { case nxnative(appURL: URL), steam(appID: UInt32) } + +public enum CatalogInstallationSize: Equatable, Sendable { case cached(Int64), steamReported(Int64), unknown } + +public struct CatalogInstallationPresentation: Identifiable, Equatable, Sendable { + public let id: String + public let contentURL: URL + public let applicationURL: URL? + public let executableURL: URL? + public let bundleIdentifier: String? + public let availability: CatalogInstallationAvailability + public let size: CatalogInstallationSize +} + +/// A value projection. No engine service, filesystem probe or view initialization +/// is needed to decide which integration owns an operation. +public struct CatalogGamePresentation { + public let id: UUID + public let name: String + public let integration: CatalogIntegration + public let personalizationReference: CatalogPersonalizationReference + public let isFavorite: Bool + public let isHidden: Bool + public let isListedNormally: Bool + public let requiresReview: Bool + /// A Steam game Steam is still installing: listed, never launched, not to review. + public let isDownloading: Bool + public let installations: [CatalogInstallationPresentation] + public let launchTarget: CatalogLaunchTarget? + + public init(game: CatalogGame, sourceEnabled: Bool) { + id = game.id + name = game.name + integration = game.integration + personalizationReference = game.personalizationReference + isFavorite = game.isFavorite + isHidden = game.isHidden + switch game.payload { + case .nxnative(let legacy): + requiresReview = false + isDownloading = false + isListedNormally = sourceEnabled && !legacy.isHidden + launchTarget = sourceEnabled && legacy.isPlayableLocally ? .nxnative(appURL: legacy.url) : nil + installations = legacy.url.pathExtension.lowercased() == "app" ? [ + .init(id: "nxnative-\(legacy.id.uuidString.lowercased())", contentURL: legacy.url, applicationURL: legacy.url, + executableURL: nil, bundleIdentifier: legacy.effectiveBundleId, + availability: legacy.isPlayableLocally ? .available : (legacy.status == .appMissing ? .notDetected : .unavailable), + size: .cached(legacy.sizeBytes)) + ] : [] + case .steam(let steam): + requiresReview = !steam.isDownloading && (!steam.hasBeenRecognized || steam.needsInstallationReview + || steam.installations.contains { $0.availability == .requiresReview } + || steam.installations.filter { $0.availability == .available }.count > 1) + isDownloading = sourceEnabled && !steam.isHidden && steam.isDownloading + isListedNormally = sourceEnabled && !steam.isHidden && (steam.hasBeenRecognized || steam.isDownloading) + let available = steam.installations.filter { $0.availability == .available && $0.primaryApplication != nil } + launchTarget = sourceEnabled && steam.appID > 0 && steam.hasBeenRecognized && available.count == 1 && !requiresReview ? .steam(appID: steam.appID) : nil + installations = steam.installations.map { installation in + let app = installation.primaryApplication + return .init(id: "steam-\(installation.id.uuidString.lowercased())", contentURL: installation.contentURL, + applicationURL: app?.url, executableURL: app?.executableURL, bundleIdentifier: app?.bundleIdentifier, + availability: installation.availability, + size: installation.reportedSizeBytes.map(CatalogInstallationSize.steamReported) ?? .unknown) + } + } + } +} diff --git a/Sources/NXLibraryCore/Models/CatalogLibraryProjection.swift b/Sources/NXLibraryCore/Models/CatalogLibraryProjection.swift new file mode 100644 index 00000000..1fe4e3cd --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogLibraryProjection.swift @@ -0,0 +1,8 @@ +import Foundation + +public enum CatalogLibraryProjection { + public static func visible(games: [CatalogGame], sources: [CatalogSourceConfiguration]) -> [CatalogGame] { + let enabled = Set(sources.filter(\.isEnabled).map(\.integration)) + return games.filter { CatalogGamePresentation(game: $0, sourceEnabled: enabled.contains($0.integration)).isListedNormally } + } +} diff --git a/Sources/NXLibraryCore/Models/CatalogPersonalizations.swift b/Sources/NXLibraryCore/Models/CatalogPersonalizations.swift new file mode 100644 index 00000000..02aa4c86 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogPersonalizations.swift @@ -0,0 +1,25 @@ +import Foundation + +/// Immutable lookup map captured by the presentation. Physical nxnative paths +/// remain compatible; each other integration has its own personal-data root. +public struct CatalogPersonalizations: Equatable, Sendable { + private let references: [UUID: CatalogPersonalizationReference] + public static let empty = Self(references: [:]) + private init(references: [UUID: CatalogPersonalizationReference]) { self.references = references } + public init(document: CatalogDocument) { + references = Dictionary(document.games.map { ($0.id, $0.personalizationReference) }, uniquingKeysWith: { first, _ in first }) + } + public func nxnativeKey(for game: PortedGame) -> String { + guard let reference = references[game.id], reference.namespace == .nxnative else { return game.titleId ?? game.uniqueKey } + return reference.key + } +} + +extension CatalogPersonalizationReference { + public func supportRoot(in launcherRoot: URL) -> URL { + switch namespace { + case .nxnative: return launcherRoot + case .steam: return launcherRoot.appendingPathComponent("integrations/steam", isDirectory: true) + } + } +} diff --git a/Sources/NXLibraryCore/Models/CatalogRecovery.swift b/Sources/NXLibraryCore/Models/CatalogRecovery.swift new file mode 100644 index 00000000..294a67d8 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CatalogRecovery.swift @@ -0,0 +1,15 @@ +import Foundation + +/// An offer, not a repair. Re-check both fingerprints when the player accepts. +public struct CatalogRecoveryCandidate: Equatable, Sendable { + public let gameCount: Int + let directory: URL + let primaryDigest: String? + let backupDigest: String +} + +/// An explicit choice to keep the current catalog, never a merge with legacy data. +public struct CatalogLegacyConflictCandidate: Equatable, Sendable { + let directory: URL + let digests: [String?] +} diff --git a/Sources/NXLibraryCore/Models/CriticRating.swift b/Sources/NXLibraryCore/Models/CriticRating.swift new file mode 100644 index 00000000..50a8b204 --- /dev/null +++ b/Sources/NXLibraryCore/Models/CriticRating.swift @@ -0,0 +1,113 @@ +import Foundation + +/// Public lookup identity only. Never sends catalog paths, account IDs or play history. +public struct CriticRatingQuery: Hashable, Codable, Sendable { + public enum Platform: String, Codable, Sendable { + case mac, `switch`, switch2 + var wikidataID: String { + switch self { + case .mac: return "Q14116" + case .switch: return "Q19610114" + case .switch2: return "Q122761124" + } + } + var igdbID: Int { + switch self { + case .mac: return 14 + case .switch: return 130 + case .switch2: return 508 + } + } + } + public let name: String + public let platform: Platform + public let steamAppID: UInt32? + + public init(name: String, platform: Platform, steamAppID: UInt32? = nil) { + self.name = name.trimmingCharacters(in: .whitespacesAndNewlines) + self.platform = platform + self.steamAppID = steamAppID + } + + /// Use the same console identity as the game's Details, including Switch 2 titles. + public init(game: PortedGame, name: String? = nil) { + self.init(name: name ?? game.name, platform: game.isSwitch2 ? .switch2 : .switch) + } +} + +/// One attributed average; community scores are explicit fallbacks, never mixed with critics. +public struct CriticRating: Equatable, Codable, Sendable { + public enum Audience: String, Codable, Sendable { case critics, users } + public enum Source: String, Codable, Sendable { + case openCritic, metacritic, criticDB, igdb + public var name: String { + switch self { + case .openCritic: return "OpenCritic" + case .metacritic: return "Metacritic" + case .criticDB: return "CriticDB" + case .igdb: return "IGDB" + } + } + var priority: Int { + switch self { case .igdb: return -1; case .openCritic: return 0; case .metacritic: return 1; case .criticDB: return 2 } + } + } + public let score: Double + public let source: Source + public let entityID: String? + public let statementID: String? + public let referenceURLs: [URL] + public let referenceItems: [String] + /// Wikidata's point-in-time, not the date the app fetched this value. + public let scoreDate: String? + /// Empty means platform unspecified; never inferred from the requesting game's platform. + public let platforms: [String] + public let igdbID: Int? + public let igdbURL: URL? + public let reviewCount: Int? + /// Nil in older caches means critics; users are always explicitly identified. + public let audience: Audience? + + public init(score: Double, source: Source, entityID: String? = nil, statementID: String? = nil, + referenceURLs: [URL] = [], referenceItems: [String] = [], scoreDate: String? = nil, + platforms: [String] = [], igdbID: Int? = nil, igdbURL: URL? = nil, reviewCount: Int? = nil, + audience: Audience = .critics) { + self.score = score; self.source = source; self.entityID = entityID; self.statementID = statementID + self.referenceURLs = referenceURLs; self.referenceItems = referenceItems; self.scoreDate = scoreDate + self.platforms = platforms; self.igdbID = igdbID; self.igdbURL = igdbURL; self.reviewCount = reviewCount + self.audience = audience + } + + public var isCommunity: Bool { audience == .users } + public var labelKey: String { isCommunity ? "User score" : "Critic score" } + public func attribution(context: AppLocale? = nil) -> String { + if isCommunity { return L10n.text("Users · IGDB", context: context) } + return source == .igdb ? "IGDB" : "\(source.name) · Wikidata" + } + public var starFills: [Double] { (0..<5).map { max(0, min(1, score / 20 - Double($0))) } } + public func number(locale: Locale = L10n.context.formatLocale) -> String { + score.formatted(.number.precision(.fractionLength(0...1)).locale(locale)) + "/100" + } + public var sourceURL: URL { + if source == .igdb { return igdbURL ?? URL(string: "https://www.igdb.com")! } + var url = URLComponents(string: "https://www.wikidata.org/wiki/\(entityID ?? "")")! + url.fragment = statementID + return url.url! + } + var isValid: Bool { + guard score.isFinite, (0...100).contains(score), !isCommunity || source == .igdb else { return false } + if source == .igdb { + let minimum = isCommunity ? 1 : IGDBRatings.minimumCriticReviews + return (igdbID ?? 0) > 0 && (reviewCount ?? 0) >= minimum && igdbURL.flatMap(IGDBRatings.safeGameURL) != nil + } + guard let entityID, let statementID else { return false } + return WikidataRatings.isItemID(entityID) && statementID.hasPrefix(entityID + "$") + && (!referenceURLs.isEmpty || !referenceItems.isEmpty) + } +} + +public struct CriticRatingResult: Equatable, Sendable { + public let rating: CriticRating? + public let fetchedAt: Date? + public let isStale: Bool +} diff --git a/Sources/NXLibraryCore/Models/DetailsFacts.swift b/Sources/NXLibraryCore/Models/DetailsFacts.swift new file mode 100644 index 00000000..455c14e1 --- /dev/null +++ b/Sources/NXLibraryCore/Models/DetailsFacts.swift @@ -0,0 +1,84 @@ +import Foundation + +/// One line of a game's Details panel: a player-facing fact with its label and grey icon. +public struct DetailsFact: Equatable, Identifiable, Sendable { + public enum Kind: String, CaseIterable, Sendable { case developer, publisher, version, size, location } + + public let kind: Kind + public let value: String + public var id: String { kind.rawValue } + + public init(kind: Kind, value: String) { + self.kind = kind + self.value = value + } + + public var label: String { + switch kind { + case .developer: return L10n.text("Developer") + case .publisher: return L10n.text("Publisher") + case .version: return L10n.text("Version") + case .size: return L10n.text("Size on disk") + case .location: return L10n.text("Installed in") + } + } + + /// The SF Symbol beside the label. + public var symbol: String { + switch kind { + case .developer: return "hammer" + case .publisher: return "building.2" + case .version: return "number" + case .size: return "internaldrive" + case .location: return "folder" + } + } +} + +/// The Details panel's rows for any source, in `Kind` order. A fact with no value has no row (never "—"). +/// Nothing technical: no engine, build, sources or Steam build ID. The two display names that need the +/// file system (the app's folder, the Steam library's volume) come from the caller. +public enum DetailsFacts { + public static func switchGame(_ game: PortedGame, metadata: NintendoStoreMetadata?, + folderName: String?, locale: Locale = L10n.context.formatLocale) -> [DetailsFact] { + rows([.developer: names(metadata?.developers), + .publisher: names(metadata?.publishers), + .version: text(game.versionString), + .size: size(game.sizeBytes, locale: locale), + .location: text(folderName)]) + } + + /// A Steam game without an available installation (still downloading, not detected) shows only its credits. + public static func steamGame(_ game: CatalogGame, metadata: SteamMetadata?, + overrides: [MetadataField: String] = [:], volumeName: String?, + locale: Locale = L10n.context.formatLocale) -> [DetailsFact] { + let appID = game.steamGame?.appID + let facts = metadata.flatMap { $0.appID == appID ? $0 : nil } + let installation = game.steamGame?.firstAvailableInstallation + return rows([.developer: names(overrides[.developer].map { [$0] } ?? facts?.developers), + .publisher: names(overrides[.publisher].map { [$0] } ?? facts?.publishers), + .size: installation.flatMap { size($0.reportedSizeBytes, locale: locale) }, + .location: installation.map { _ in text(volumeName).map { "Steam · " + $0 } ?? "Steam" }]) + } + + private static func rows(_ values: [DetailsFact.Kind: String?]) -> [DetailsFact] { + DetailsFact.Kind.allCases.compactMap { kind in + (values[kind] ?? nil).map { DetailsFact(kind: kind, value: $0) } + } + } + + private static func names(_ list: [String]?) -> String? { + let names = (list ?? []).compactMap(text) + return names.isEmpty ? nil : names.joined(separator: ", ") + } + + private static func text(_ raw: String?) -> String? { + guard let trimmed = raw?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty else { return nil } + return trimmed + } + + private static func size(_ bytes: Int64?, locale: Locale) -> String? { + guard let bytes, bytes > 0 else { return nil } + return bytes.formatted(.byteCount(style: .file).locale(locale)) + } +} diff --git a/Sources/NXLibraryCore/Models/DetailsFocus.swift b/Sources/NXLibraryCore/Models/DetailsFocus.swift index 0ead696a..a11f9f2c 100644 --- a/Sources/NXLibraryCore/Models/DetailsFocus.swift +++ b/Sources/NXLibraryCore/Models/DetailsFocus.swift @@ -2,7 +2,7 @@ import Foundation /// Focus on the Details page (spec §5.4). Zone 0 is the top block (Play or /// Build, then Game options). Zones 1 to 4 are the bands: Screenshots, -/// Build & Sources (a grid of actions, the activity beside it), Mods and +/// Details (its links in a grid), Mods and /// More like this, as on Spotlight's page. A band with nothing to focus is skipped; Down goes to the /// next band, Up back to the previous one, and Up from the first returns to /// the top block. @@ -39,7 +39,7 @@ public struct DetailsFocus: Equatable { public static let moreZone = 4 /// Play or Build, then Options, then the Favorite heart. public static let pillCount = 3 - /// Build & Sources lays its actions out in rows, as on Spotlight. + /// The Details links sit in rows, as on Spotlight. public static let actionColumns = SpotlightState.actionColumns public var zone = DetailsFocus.topZone diff --git a/Sources/NXLibraryCore/Models/DisplayNameCache.swift b/Sources/NXLibraryCore/Models/DisplayNameCache.swift new file mode 100644 index 00000000..75292bbe --- /dev/null +++ b/Sources/NXLibraryCore/Models/DisplayNameCache.swift @@ -0,0 +1,20 @@ +import Foundation + +/// Display names read from the file system (a folder's Finder name, a volume's name), once per URL: +/// the page rebuilds on every render and key press, and a sleeping external disk would block each time. +@MainActor +public final class DisplayNameCache { + private var names: [URL: String?] = [:] + private let resolve: (URL) -> String? + + public init(resolve: @escaping (URL) -> String?) { + self.resolve = resolve + } + + public func name(for url: URL) -> String? { + if let known = names[url] { return known } + let name = resolve(url) + names[url] = name + return name + } +} diff --git a/Sources/NXLibraryCore/Models/FirstRunFindings.swift b/Sources/NXLibraryCore/Models/FirstRunFindings.swift new file mode 100644 index 00000000..2f6e5827 --- /dev/null +++ b/Sources/NXLibraryCore/Models/FirstRunFindings.swift @@ -0,0 +1,77 @@ +import Foundation + +/// What the first launch finds already on the Mac, read only and without the network: +/// installed native Mac games in the chosen Steam folder and ported apps in the Game apps folder. +public struct FirstRunFindings: Equatable, Sendable { + /// Ready Mac games in Steam; nil when Steam is absent, unreadable, read only in part, or the read was cancelled. + public let steamGameCount: Int? + public let portedAppCount: Int + /// An error or partial read is not evidence that Steam or its games are absent. + public let steamReadFailed: Bool + + public init(steamGameCount: Int?, portedAppCount: Int, steamReadFailed: Bool = false) { + self.steamGameCount = steamGameCount + self.portedAppCount = portedAppCount + self.steamReadFailed = steamReadFailed + } + + public var isEmpty: Bool { !steamReadFailed && steamGameCount == nil && portedAppCount == 0 } + + /// Blocking; run it on a worker. A failed/partial Steam scan can be retried without changing sources. + public static func read(steamRoot: URL, appsFolder: URL, cancelled: @escaping () -> Bool) -> FirstRunFindings { + let steam = readSteam(root: steamRoot, cancelled: cancelled) + guard !cancelled() else { return FirstRunFindings(steamGameCount: nil, portedAppCount: 0) } + let ported = ImportService().scan(directories: [appsFolder]).count + guard !cancelled() else { return FirstRunFindings(steamGameCount: nil, portedAppCount: 0) } + return FirstRunFindings(steamGameCount: steam.count, portedAppCount: ported, steamReadFailed: steam.failed) + } + + private static func readSteam(root: URL, cancelled: @escaping () -> Bool) -> (count: Int?, failed: Bool) { + do { + let metadata = try root.resolvingSymlinksInPath().resourceValues(forKeys: [.isDirectoryKey]) + guard metadata.isDirectory == true else { return (nil, true) } + } catch let error as NSError { + let missing = error.domain == NSCocoaErrorDomain + && [NSFileReadNoSuchFileError, NSFileNoSuchFileError].contains(error.code) + return (nil, !missing) + } + guard let snapshot = try? SteamLibrarySource(root: root).scan(cancelled: cancelled), + !cancelled(), snapshot.isComplete, !snapshot.libraries.isEmpty + else { return (nil, true) } + return (snapshot.games.filter { $0.state == .nativeReady }.count, false) + } +} + +/// Reads the findings once on a cancellable worker; only the latest request publishes. +@MainActor +public final class FirstRunFindingsReader: ObservableObject { + @Published public private(set) var findings: FirstRunFindings? + private var requestID = 0 + private var task: Task<Void, Never>? + + public init() {} + + public var isReading: Bool { task != nil } + + public func start(steamRoot: URL, appsFolder: URL) { + cancel() + findings = nil + let id = requestID + let worker = Task.detached(priority: .userInitiated) { + FirstRunFindings.read(steamRoot: steamRoot, appsFolder: appsFolder, cancelled: { Task.isCancelled }) + } + task = Task { [weak self] in + let result = await withTaskCancellationHandler(operation: { await worker.value }, + onCancel: { worker.cancel() }) + guard !Task.isCancelled, let self, self.requestID == id else { return } + self.findings = result + self.task = nil + } + } + + public func cancel() { + requestID += 1 + task?.cancel() + task = nil + } +} diff --git a/Sources/NXLibraryCore/Models/FirstRunSetup.swift b/Sources/NXLibraryCore/Models/FirstRunSetup.swift index 3da02308..0374ed38 100644 --- a/Sources/NXLibraryCore/Models/FirstRunSetup.swift +++ b/Sources/NXLibraryCore/Models/FirstRunSetup.swift @@ -1,19 +1,42 @@ import Foundation /// First launch stays unfinished until the player opens the library, picks sources, or explicitly skips. +/// It starts on `found` (what is already on the Mac); the Porting card leads to `requirements` and `games`. public struct FirstRunSetup: Equatable { - public enum Page: String { case requirements, games } + public enum Page: String { case found, requirements, games } public enum LibraryState: Equatable { case scanning, empty, ready } public private(set) var page: Page public private(set) var isCompleted: Bool + /// The Steam switch on `found`: nil until Steam is found, then kept on every page of the first launch + /// and applied when it finishes, through Open library or through Porting. + public private(set) var steamChoice: Bool? - public init(completed: Bool = false, savedPage: String? = nil) { + public init(completed: Bool = false, savedPage: String? = nil, savedSteamChoice: Bool? = nil) { isCompleted = completed - page = completed ? .requirements : savedPage.flatMap(Page.init(rawValue:)) ?? .requirements + steamChoice = completed ? nil : savedSteamChoice + // Settings → Open Setup starts on the requirements; an interrupted first launch resumes where it was. + page = completed ? .requirements : savedPage.flatMap(Page.init(rawValue:)) ?? .found } public var pageToRemember: String? { isCompleted ? nil : page.rawValue } + public var steamChoiceToRemember: Bool? { isCompleted ? nil : steamChoice } + + public mutating func chooseSteam(_ on: Bool) { + guard !isCompleted else { return } + steamChoice = on + } + + /// The Porting card on `found`: the requirements of today's Setup. + public mutating func openPorting() { + page = .requirements + } + + /// Back from the requirements during the first launch; a finished setup has no `found` page. + public mutating func returnToFound() { + guard !isCompleted else { return } + page = .found + } public mutating func advance() { page = .games @@ -46,6 +69,20 @@ public struct FirstRunSetup: Equatable { public enum Focus: Equatable { case apps, file, folder, back, finish + /// The `found` page: the Steam switch (only when Steam is there), the Porting card, Open library. + case steamToggle, portingCard, openLibrary + + public static let initialOnFound: Self = .openLibrary + + public func movedOnFound(_ direction: MoveDirection, hasSteam: Bool) -> Self { + switch (self, direction) { + case (.steamToggle, .down): return .portingCard + case (.portingCard, .up): return hasSteam ? .steamToggle : .portingCard + case (.portingCard, .down): return .openLibrary + case (.openLibrary, .up): return .portingCard + default: return self + } + } public func moved(_ direction: MoveDirection) -> Self { switch (self, direction) { diff --git a/Sources/NXLibraryCore/Models/GameDetailPresentation+Steam.swift b/Sources/NXLibraryCore/Models/GameDetailPresentation+Steam.swift new file mode 100644 index 00000000..6fbc0a23 --- /dev/null +++ b/Sources/NXLibraryCore/Models/GameDetailPresentation+Steam.swift @@ -0,0 +1,61 @@ +import Foundation + +extension GameDetailPresentation { + /// A Steam game's page facts, for the same About, activity and stats views as an nxnative game. + /// Facts delivered for another AppID are ignored; personal fields win. Nothing nxnative is + /// claimed: no engine, build, sources or save folder, and Play waits for the Steam launch step. + public init(steamRecord game: CatalogGame, metadata: SteamMetadata?, + overrides: [MetadataField: String] = [:], + totalPlaytime: TimeInterval, lastPlayed: Date?, now: Date = Date(), + sessions: [PlaySession] = [], libraryGames: [CatalogGame] = [], + playtimeByGame: [UUID: TimeInterval] = [:], calendar: Calendar = .current) { + let appID = game.steamGame?.appID + let facts = metadata.flatMap { $0.appID == appID ? $0 : nil } + title = game.name + console = "Steam" + eyebrow = "" + description = overrides[.description] ?? facts?.description ?? "" + descriptionIsEnglishFallback = false + descriptionLanguageNote = nil + genres = Self.steamGenres(for: game, metadata: metadata, override: overrides[.genres]) + // Steam's dates are display text in the store's language: shown as given, never re-parsed. + let release = (overrides[.releaseDate] ?? facts?.releaseDate)?.trimmingCharacters(in: .whitespaces) + released = release.flatMap { $0.isEmpty ? nil : $0 } + releaseYear = release.flatMap { text in + text.range(of: #"\b(?:19|20)\d{2}\b"#, options: .regularExpression).map { String(text[$0]) } + } + let developers = overrides[.developer].map { [$0] } ?? facts?.developers ?? [] + let publishers = overrides[.publisher].map { [$0] } ?? facts?.publishers ?? [] + developerLine = [developers, publishers] + .map { $0.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } } + .first { !$0.isEmpty }?.joined(separator: ", ") + publisher = publishers.first + let week = Activity.summary(sessions: sessions.filter { $0.gameID == game.id }, now: now, calendar: calendar) + thisWeek = LibraryPresentation.duration(week.thisWeek) + rank = Self.rank(id: game.id, name: game.name, total: totalPlaytime, + others: libraryGames.filter { !$0.isHidden }.map { ($0.id, $0.name) }, playtimes: playtimeByGame) + playtime = LibraryPresentation.duration(totalPlaytime) + self.lastPlayed = LibraryPresentation.relative(lastPlayed, now: now) + version = "—" + size = "—" + engineCommitShort = "—" + toolchainVerified = false + toolchainNote = nil + canPlay = false + canRebuild = false + sourcesDetached = false + hasBaseSource = false + storeURL = appID.flatMap { URL(string: "https://store.steampowered.com/app/\($0)/") } + hltbURL = Self.hltbURL(for: game.name) + appPath = game.steamGame?.firstAvailableInstallation?.primaryApplication?.url.path ?? "" + savePath = "" + } + + /// The genre chips can draw without building the page's rank, activity and details. + public static func steamGenres(for game: CatalogGame, metadata: SteamMetadata?, override: String?) -> [String] { + let facts = metadata.flatMap { $0.appID == game.steamGame?.appID ? $0 : nil } + let names = override.map { $0.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) } } + ?? facts?.genres ?? [] + return GameGenre.list(names) + } +} diff --git a/Sources/NXLibraryCore/Models/GameDetailPresentation.swift b/Sources/NXLibraryCore/Models/GameDetailPresentation.swift index 9afe36c3..96d8f2c2 100644 --- a/Sources/NXLibraryCore/Models/GameDetailPresentation.swift +++ b/Sources/NXLibraryCore/Models/GameDetailPresentation.swift @@ -109,11 +109,19 @@ public struct GameDetailPresentation: Equatable { private static func rank(game: PortedGame, total: TimeInterval, library: [PortedGame], playtimes: [UUID: TimeInterval]) -> String? { + rank(id: game.id, name: game.name, total: total, + others: library.filter { !$0.isHidden }.map { ($0.id, $0.name) }, playtimes: playtimes) + } + + /// "#2 of 5" among the visible games with play time, whatever their source. + static func rank(id: UUID, name: String, total: TimeInterval, others: [(id: UUID, name: String)], + playtimes: [UUID: TimeInterval]) -> String? { guard total > 0 else { return nil } - var entries: [(id: UUID, name: String, time: TimeInterval)] = [(game.id, game.name, total)] - for other in library where other.id != game.id && !other.isHidden { + var entries: [(id: UUID, name: String, time: TimeInterval)] = [(id, name, total)] + for other in others where other.id != id { if let t = playtimes[other.id], t > 0 { entries.append((other.id, other.name, t)) } } + let game = (id: id, name: name) entries.sort { a, b in if a.time != b.time { return a.time > b.time } let c = a.name.localizedCaseInsensitiveCompare(b.name) @@ -138,7 +146,7 @@ public struct GameDetailPresentation: Equatable { return "" } - private static func hltbURL(for name: String) -> URL? { + static func hltbURL(for name: String) -> URL? { var components = URLComponents(string: "https://howlongtobeat.com/") components?.queryItems = [URLQueryItem(name: "q", value: name)] return components?.url diff --git a/Sources/NXLibraryCore/Models/GameFileItem.swift b/Sources/NXLibraryCore/Models/GameFileItem.swift index f73c4bac..9ee7671e 100644 --- a/Sources/NXLibraryCore/Models/GameFileItem.swift +++ b/Sources/NXLibraryCore/Models/GameFileItem.swift @@ -40,12 +40,14 @@ public struct GameFileItem: Identifiable, Codable, Equatable { /// Absent in older libraries, whose sources are packages. public var sourceLayout: SourceLayout? public var requiresTitleSelection: Bool? + /// Absent in older records. A selected NUP program is independent of the application's DLC IDs. + public var nupProgram: NUPProgramSelection? public var layout: SourceLayout { sourceLayout ?? .package } public init(id: UUID = UUID(), url: URL, name: String, sizeBytes: Int64, type: SourceKind, titleId: String? = nil, versionString: String? = nil, isSymlink: Bool = false, sourceLayout: SourceLayout? = nil, - requiresTitleSelection: Bool? = nil) { + requiresTitleSelection: Bool? = nil, nupProgram: NUPProgramSelection? = nil) { self.id = id self.url = url self.name = name @@ -56,16 +58,17 @@ public struct GameFileItem: Identifiable, Codable, Equatable { self.isSymlink = isSymlink self.sourceLayout = sourceLayout self.requiresTitleSelection = requiresTitleSelection + self.nupProgram = nupProgram } public init(id: UUID = UUID(), url: URL, kind: SourceKind, titleId: String? = nil, versionString: String? = nil, sizeBytes: Int64, isSymlink: Bool = false, sourceLayout: SourceLayout? = nil, - requiresTitleSelection: Bool? = nil) { + requiresTitleSelection: Bool? = nil, nupProgram: NUPProgramSelection? = nil) { self.init(id: id, url: url, name: url.lastPathComponent, sizeBytes: sizeBytes, type: kind, titleId: titleId, versionString: versionString, isSymlink: isSymlink, sourceLayout: sourceLayout, - requiresTitleSelection: requiresTitleSelection) + requiresTitleSelection: requiresTitleSelection, nupProgram: nupProgram) } public var kind: SourceKind { type } diff --git a/Sources/NXLibraryCore/Models/GameFoldersCopy.swift b/Sources/NXLibraryCore/Models/GameFoldersCopy.swift index 5e32c8b8..5d81ab2e 100644 --- a/Sources/NXLibraryCore/Models/GameFoldersCopy.swift +++ b/Sources/NXLibraryCore/Models/GameFoldersCopy.swift @@ -8,7 +8,7 @@ public enum GameFoldersCopy { L10n.text("Existing games and new builds.") } public static var appsPickerMessage: String { - L10n.text("Choose where to keep your game apps. Put any existing nxnative games (.app) here. Change it later in Settings → Library.") + L10n.text("Choose where to keep your game apps. Put any existing nxnative games (.app) here. Change it later in Settings → Porting → Library.") } public static let sourcesTitle = "Game files" @@ -21,6 +21,6 @@ public enum GameFoldersCopy { } public static func sourcesPickerMessage(extractedFolders: Bool) -> String { - L10n.format("Choose a folder with your %@. Existing apps play without these files. Change it later in Settings → Library.", [String(describing: (sourceFormats(extractedFolders: extractedFolders)))]) + L10n.format("Choose a folder with your %@. Existing apps play without these files. Change it later in Settings → Porting → Library.", [String(describing: (sourceFormats(extractedFolders: extractedFolders)))]) } } diff --git a/Sources/NXLibraryCore/Models/GameOptionsPresentation.swift b/Sources/NXLibraryCore/Models/GameOptionsPresentation.swift index 8cf8ba68..7ff41ce2 100644 --- a/Sources/NXLibraryCore/Models/GameOptionsPresentation.swift +++ b/Sources/NXLibraryCore/Models/GameOptionsPresentation.swift @@ -19,7 +19,7 @@ public enum GameOptionsRow: String, CaseIterable, Sendable { case fullscreen, fps60, frameRate, metalFX, gameUpscaler, metalHUD, consoleMode, language, rumble, rumbleStrength case renderScale, moreSettings, restoreDefaults case cheats, mods, rebuild, showInFinder, openSaves, editDetails, removeGame - case changeArtwork, changeMetadata, storePage, attachSources, openLog, removeSources + case changeArtwork, changeMetadata, storePage, searchStore, attachSources, openLog, removeSources public var title: String { switch self { @@ -50,6 +50,7 @@ public enum GameOptionsRow: String, CaseIterable, Sendable { case .changeArtwork: return L10n.text("Change artwork") case .changeMetadata: return L10n.text("Change metadata") case .storePage: return L10n.text("Store page") + case .searchStore: return L10n.text("Search Nintendo Store") case .attachSources: return L10n.text("Attach sources…") case .openLog: return L10n.text("Open log") case .removeSources: return L10n.text("Remove sources & build cache") @@ -83,6 +84,7 @@ public enum GameOptionsRow: String, CaseIterable, Sendable { case .changeArtwork: return .image case .changeMetadata: return .edit case .storePage: return .store + case .searchStore: return .search case .attachSources: return .link case .openLog: return .terminal } @@ -166,6 +168,8 @@ public struct GameOptionsPresentation: Equatable { /// What the gate says about the refusal (ToolchainGateCopy.Summary.buildHint); nil keeps the generic line. public let toolchainHint: String? public let hasStorePage: Bool + /// The game has no description: Edit details offers a Nintendo store search. + public let offersStoreSearch: Bool public let gameName: String public let appPath: String public let canDeleteBundle: Bool @@ -179,6 +183,7 @@ public struct GameOptionsPresentation: Equatable { public init(supportsRenderScale: Bool, isPlayable: Bool, sourcesDetached: Bool, toolchainBlocked: Bool = false, toolchainHint: String? = nil, hasStorePage: Bool = false, + offersStoreSearch: Bool = false, gameName: String = "", appPath: String = "", canDeleteBundle: Bool = false, cheatsValue: String = "None", modsValue: String = "None", settings: GameSettingsSnapshot? = nil) { self.cheatsValue = cheatsValue @@ -190,6 +195,7 @@ public struct GameOptionsPresentation: Equatable { self.toolchainBlocked = toolchainBlocked self.toolchainHint = toolchainHint.flatMap { $0.isEmpty ? nil : $0 } self.hasStorePage = hasStorePage + self.offersStoreSearch = offersStoreSearch self.gameName = gameName self.appPath = appPath self.canDeleteBundle = canDeleteBundle @@ -205,7 +211,7 @@ public struct GameOptionsPresentation: Equatable { /// Says where to fix a dimmed Rebuild: the sources or the Metal gate. public var rebuildAbout: String { if sourcesDetached { return L10n.text("Game files are missing or not attached. Attach sources in Edit details.") } - if toolchainBlocked { return toolchainHint.map { $0 + "." } ?? L10n.text("Blocked by the Metal gate. See Settings → Engine.") } + if toolchainBlocked { return toolchainHint.map { $0 + "." } ?? L10n.text("Blocked by the Metal gate. See Settings → Setup and engine.") } return L10n.text("Build a new app; the old app stays if the build fails.") } @@ -274,6 +280,7 @@ public struct GameOptionsPresentation: Equatable { case .changeArtwork: return L10n.text("Cover, background, icon and logo, from GameTDB, Title DB or a file.") case .changeMetadata: return L10n.text("Description, genres, developer, publisher and release date.") case .storePage: return L10n.text("Open the game's Nintendo store page.") + case .searchStore: return L10n.text("Find this game on the Nintendo store.") case .attachSources: return attachAbout case .openLog: return L10n.text("Reveal the latest build log.") case .removeSources: return L10n.text("Deletes only the source files named in this game and its app-owned workspace. The app and saves stay.") @@ -334,6 +341,7 @@ public struct GameOptionsPresentation: Equatable { case .editDetails: var entries: [GameOptionsEntry] = [.heading("Edit details"), .row(.changeArtwork), .row(.changeMetadata)] if hasStorePage { entries.append(.row(.storePage)) } + if offersStoreSearch { entries.append(.row(.searchStore)) } entries += [.row(.attachSources), .row(.openLog), .gap, .row(.removeSources)] return entries } diff --git a/Sources/NXLibraryCore/Models/GameResourceState.swift b/Sources/NXLibraryCore/Models/GameResourceState.swift index 00399504..e82a4d48 100644 --- a/Sources/NXLibraryCore/Models/GameResourceState.swift +++ b/Sources/NXLibraryCore/Models/GameResourceState.swift @@ -52,3 +52,15 @@ public enum GameResourceState { return game.status } } + +/// What a Switch game's Play does on Spotlight: play it, build it when it is not built yet and its +/// sources are there, or refuse with a sound (the note above the pills says why). +public enum GamePrimaryStep: Equatable, Sendable { + case play, build, refuse + + public static func decide(unavailable: Bool, playable: Bool, sourcesAvailable: Bool) -> GamePrimaryStep { + if unavailable { return .refuse } + if playable { return .play } + return sourcesAvailable ? .build : .refuse + } +} diff --git a/Sources/NXLibraryCore/Models/GameRuntimeConfig.swift b/Sources/NXLibraryCore/Models/GameRuntimeConfig.swift index 690c27ee..6496cbdd 100644 --- a/Sources/NXLibraryCore/Models/GameRuntimeConfig.swift +++ b/Sources/NXLibraryCore/Models/GameRuntimeConfig.swift @@ -111,7 +111,7 @@ public struct GameRuntimeConfig: Codable, Equatable { } public static func load(for game: PortedGame) -> GameRuntimeConfig { - if let data = UserDefaults.standard.data(forKey: storageKey(for: game)), + if let data = AppData.preferences.data(forKey: storageKey(for: game)), let config = try? JSONDecoder().decode(GameRuntimeConfig.self, from: data) { return config } @@ -134,7 +134,7 @@ public struct GameRuntimeConfig: Codable, Equatable { public func save(for game: PortedGame, baseDirectory: URL = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/nxnative"), - preferences: UserDefaults = .standard) throws { + preferences: UserDefaults = AppData.preferences) throws { let data = try JSONEncoder().encode(self) try applyToDisk(for: game, baseDirectory: baseDirectory) preferences.set(data, forKey: Self.storageKey(for: game)) diff --git a/Sources/NXLibraryCore/Models/GridListLayout.swift b/Sources/NXLibraryCore/Models/GridListLayout.swift new file mode 100644 index 00000000..3ee8e2be --- /dev/null +++ b/Sources/NXLibraryCore/Models/GridListLayout.swift @@ -0,0 +1,68 @@ +import CoreGraphics + +/// A list of equal rows in columns, scrolled by an offset of its own (`TextScroll`) rather than a scroll view: +/// where each row sits, how tall the whole list is, which lines to draw for a window, and where the focus goes +/// when the wheel left it out of view. Points throughout; line 0 is the top one. +public struct GridListLayout: Equatable, Sendable { + public let columns: Int + public let rowHeight: CGFloat + public let spacing: CGFloat + /// Room above the first line (for its focus ring) and below the last (so it can rise clear of the hints). + public let topPad: CGFloat + public let bottomRoom: CGFloat + + public init(columns: Int, rowHeight: CGFloat, spacing: CGFloat, topPad: CGFloat, bottomRoom: CGFloat) { + self.columns = max(columns, 1) + self.rowHeight = rowHeight + self.spacing = spacing + self.topPad = topPad + self.bottomRoom = bottomRoom + } + + private var pitch: CGFloat { rowHeight + spacing } + + public func lines(count: Int) -> Int { (max(count, 0) + columns - 1) / columns } + + public func contentHeight(count: Int) -> CGFloat { + let lines = lines(count: count) + return topPad + CGFloat(lines) * rowHeight + CGFloat(max(lines - 1, 0)) * spacing + bottomRoom + } + + public func top(of index: Int) -> CGFloat { top(line: index / columns) } + + private func top(line: Int) -> CGFloat { topPad + CGFloat(line) * pitch } + + /// The row with `above` and `below` of room around it: what the window shows when the row has the focus. + public func revealSpan(of index: Int, above: CGFloat, below: CGFloat) -> ClosedRange<CGFloat> { + let top = top(of: index) + return (top - above)...(top + rowHeight + below) + } + + /// The lines that touch the window, widened by `buffer` each side so a glide has its rows drawn already. + public func visibleLines(count: Int, offset: CGFloat, visible: CGFloat, buffer: CGFloat) -> ClosedRange<Int>? { + let lines = lines(count: count) + guard lines > 0 else { return nil } + let low = offset - buffer, high = offset + visible + buffer + let first = max(0, Int(((low - topPad - rowHeight) / pitch).rounded(.up))) + let last = min(lines - 1, Int(((high - topPad) / pitch).rounded(.down))) + return first <= last ? first...last : nil + } + + /// After the wheel, the focused row may be out of view: the nearest line shown whole between the margins, + /// in the same column (the line's last row when it is short). Nil while the focused row is in view (its + /// middle inside the window, margins or not: a row at the very top stays focused) or when no line fits. + public func nearestVisible(index: Int, count: Int, offset: CGFloat, visible: CGFloat, + above: CGFloat, below: CGFloat) -> Int? { + let lines = lines(count: count) + guard count > 0, lines > 0 else { return nil } + let line = min(max(index, 0), count - 1) / columns + let middle = top(line: line) + rowHeight / 2 + if middle >= offset, middle <= offset + visible { return nil } + // A point of slack: an offset left by a reveal against a margin is not exact. + let bandTop = offset + above - 1, bandBottom = offset + visible - below + 1 + func whole(_ line: Int) -> Bool { top(line: line) >= bandTop && top(line: line) + rowHeight <= bandBottom } + let shown = (0..<lines).filter(whole) + guard let nearest = shown.min(by: { abs($0 - line) < abs($1 - line) }) else { return nil } + return min(nearest * columns + index % columns, count - 1) + } +} diff --git a/Sources/NXLibraryCore/Models/LibraryArtworkRole.swift b/Sources/NXLibraryCore/Models/LibraryArtworkRole.swift new file mode 100644 index 00000000..3d1eb130 --- /dev/null +++ b/Sources/NXLibraryCore/Models/LibraryArtworkRole.swift @@ -0,0 +1,15 @@ +import Foundation + +/// Layout roles stay separate from the provider. A square never requests/crops +/// the portrait cover; the renderer can keep the original Finder app artwork. +public enum LibraryArtworkRole: String, CaseIterable, Sendable { + case square, cover, hero, logo + public var slot: ArtworkSlot { + switch self { + case .square: return .icon + case .cover: return .cover + case .hero: return .background + case .logo: return .logo + } + } +} diff --git a/Sources/NXLibraryCore/Models/LibraryFilter.swift b/Sources/NXLibraryCore/Models/LibraryFilter.swift index 51b89d13..7a93c79c 100644 --- a/Sources/NXLibraryCore/Models/LibraryFilter.swift +++ b/Sources/NXLibraryCore/Models/LibraryFilter.swift @@ -28,15 +28,18 @@ public struct LibraryQuery: Equatable { self.searchText = searchText } - public func apply(to games: [PortedGame], history: PlayHistory) -> [PortedGame] { + public func apply(to games: [PortedGame], history: PlayHistory) -> [PortedGame] { applyRecords(games, history: history) } + public func applyCatalog(to games: [CatalogGame], history: PlayHistory) -> [CatalogGame] { applyRecords(games, history: history) } + + private func applyRecords<Game: LibraryQueryRecord>(_ games: [Game], history: PlayHistory) -> [Game] { let visible = games.filter { !$0.isHidden } let dates = Dictionary(uniqueKeysWithValues: visible.map { ($0.id, history.lastPlayed(for: $0.id)) }) - func played(_ game: PortedGame) -> Date? { dates[game.id] ?? nil } + func played(_ game: Game) -> Date? { dates[game.id] ?? nil } - let filtered: [PortedGame] + let filtered: [Game] switch filter { case .all: filtered = visible - case .installed: filtered = visible.filter(\.isPlayableLocally) + case .installed: filtered = visible.filter(\.isInstalledForLibrary) case .recentlyPlayed: filtered = visible.filter { played($0) != nil } case .favorites: filtered = visible.filter(\.isFavorite) case .notPlayed: filtered = visible.filter { played($0) == nil } @@ -45,8 +48,7 @@ public struct LibraryQuery: Equatable { let query = normalized(searchText) let searched = query.isEmpty ? filtered : filtered.filter { game in normalized(game.name).contains(query) - || normalized(game.titleId ?? "").contains(query) - || normalized(game.bundleId ?? "").contains(query) + || game.librarySearchTerms.contains { normalized($0).contains(query) } } return searched.sorted { lhs, rhs in @@ -66,3 +68,30 @@ public struct LibraryQuery: Equatable { .trimmingCharacters(in: .whitespacesAndNewlines) } } + + +private protocol LibraryQueryRecord { + var id: UUID { get } + var name: String { get } + var isFavorite: Bool { get } + var isHidden: Bool { get } + var isInstalledForLibrary: Bool { get } + var librarySearchTerms: [String] { get } +} +extension PortedGame: LibraryQueryRecord { + fileprivate var isInstalledForLibrary: Bool { isPlayableLocally } + fileprivate var librarySearchTerms: [String] { [titleId, bundleId].compactMap { $0 } } +} +extension CatalogGame: LibraryQueryRecord { + fileprivate var isInstalledForLibrary: Bool { + if let game = nxnativeGame { return game.isPlayableLocally } + guard let game = steamGame, game.hasBeenRecognized else { return false } + return game.installations.contains { $0.availability == .available || ($0.availability == .requiresReview && $0.primaryApplication != nil) } + } + fileprivate var librarySearchTerms: [String] { + switch payload { + case .nxnative(let game): return game.librarySearchTerms + case .steam(let game): return ["Steam", String(game.appID)] + game.installations.flatMap { $0.applications.compactMap(\.bundleIdentifier) } + } + } +} diff --git a/Sources/NXLibraryCore/Models/LibraryPresentation.swift b/Sources/NXLibraryCore/Models/LibraryPresentation.swift index 02fd5236..39f49f76 100644 --- a/Sources/NXLibraryCore/Models/LibraryPresentation.swift +++ b/Sources/NXLibraryCore/Models/LibraryPresentation.swift @@ -31,6 +31,40 @@ public struct LibraryPresentation: Equatable { .trimmingCharacters(in: .whitespacesAndNewlines) } + /// Common display boundary; provider facts never become a fabricated NX game. + public init(game: CatalogGame, steamMetadata: SteamMetadata?, + nxnativeMetadata: NintendoStoreMetadata? = nil, + overrides: [MetadataField: String] = [:], totalPlaytime: TimeInterval, + lastPlayed: Date?, now: Date = Date()) { + if let native = game.nxnativeGame { + self = Self(game: native, metadata: nxnativeMetadata, totalPlaytime: totalPlaytime, lastPlayed: lastPlayed, now: now) + return + } + self = Self(steamRecord: game, metadata: steamMetadata, overrides: overrides, + totalPlaytime: totalPlaytime, lastPlayed: lastPlayed, now: now) + } + + private init(steamRecord game: CatalogGame, metadata steamMetadata: SteamMetadata?, + overrides: [MetadataField: String], totalPlaytime: TimeInterval, lastPlayed: Date?, now: Date) { + // Reject facts accidentally delivered for another external identity. + let facts = steamMetadata.flatMap { $0.appID == game.steamGame?.appID ? $0 : nil } + title = game.name + eyebrow = Self.eyebrow(from: game.name) + let selectedGenres = overrides[.genres].map { $0.split(separator: ",").map(String.init) } ?? facts?.genres ?? [] + genres = Array(GameGenre.list(selectedGenres).prefix(3)) + publisher = overrides[.publisher] ?? facts?.publishers.first + let release = overrides[.releaseDate] ?? facts?.releaseDate ?? "" + if let range = release.range(of: #"\b(?:19|20)\d{2}\b"#, options: .regularExpression) { + releaseYear = String(release[range]) + } else { releaseYear = nil } + playtime = Self.duration(totalPlaytime) + self.lastPlayed = Self.relative(lastPlayed, now: now) + platform = "Steam" + console = "Steam" + sourcesDetached = false + summary = overrides[.description] ?? facts?.description ?? "" + } + private static func eyebrow(from name: String) -> String { let separators = [":", " – "] for separator in separators { diff --git a/Sources/NXLibraryCore/Models/LibrarySelectionState.swift b/Sources/NXLibraryCore/Models/LibrarySelectionState.swift index 1b94ecac..ca2fafea 100644 --- a/Sources/NXLibraryCore/Models/LibrarySelectionState.swift +++ b/Sources/NXLibraryCore/Models/LibrarySelectionState.swift @@ -1,51 +1,52 @@ import Foundation -/// The library filter and the game selected on the Collection screen. The -/// filter is shared with Spotlight (both read `query.filter`). +/// The shared home filter and stable UUID selection, independent of integration. public struct LibrarySelectionState: Equatable { public var query: LibraryQuery public var selectedGameID: UUID? - - public init(query: LibraryQuery = LibraryQuery(), - selectedGameID: UUID? = nil) { - self.query = query - self.selectedGameID = selectedGameID + public init(query: LibraryQuery = LibraryQuery(), selectedGameID: UUID? = nil) { + self.query = query; self.selectedGameID = selectedGameID } - @discardableResult - public mutating func reconcile(with games: [PortedGame], history: PlayHistory, - preferredGameID: UUID? = nil) -> [PortedGame] { + public mutating func reconcile(with games: [PortedGame], history: PlayHistory, preferredGameID: UUID? = nil) -> [PortedGame] { let filtered = query.apply(to: games, history: history) - if let selectedGameID, - filtered.contains(where: { $0.id == selectedGameID }) { - return filtered - } - if let preferredGameID, filtered.contains(where: { $0.id == preferredGameID }) { - selectedGameID = preferredGameID - } else { - selectedGameID = filtered.first?.id - } + reconcileIDs(filtered.map(\.id), preferred: preferredGameID) + return filtered + } + @discardableResult + public mutating func reconcileCatalog(with games: [CatalogGame], history: PlayHistory, preferredGameID: UUID? = nil) -> [CatalogGame] { + let filtered = query.applyCatalog(to: games, history: history) + reconcileIDs(filtered.map(\.id), preferred: preferredGameID) return filtered } - @discardableResult public mutating func move(by delta: Int, in games: [PortedGame], history: PlayHistory) -> UUID? { - let filtered = query.apply(to: games, history: history) - guard !filtered.isEmpty else { - selectedGameID = nil - return nil - } - let current = filtered.firstIndex { $0.id == selectedGameID } ?? 0 - let next = min(max(current + delta, 0), filtered.count - 1) - selectedGameID = filtered[next].id - return selectedGameID + moveIDs(query.apply(to: games, history: history).map(\.id), by: delta) + } + @discardableResult + public mutating func moveCatalog(by delta: Int, in games: [CatalogGame], history: PlayHistory) -> UUID? { + moveIDs(query.applyCatalog(to: games, history: history).map(\.id), by: delta) } - - /// Selects the first or last game of the filtered list (LT / RT). @discardableResult public mutating func jump(toEnd: Bool, in games: [PortedGame], history: PlayHistory) -> UUID? { - let filtered = query.apply(to: games, history: history) - selectedGameID = (toEnd ? filtered.last : filtered.first)?.id + jumpIDs(query.apply(to: games, history: history).map(\.id), toEnd: toEnd) + } + @discardableResult + public mutating func jumpCatalog(toEnd: Bool, in games: [CatalogGame], history: PlayHistory) -> UUID? { + jumpIDs(query.applyCatalog(to: games, history: history).map(\.id), toEnd: toEnd) + } + private mutating func reconcileIDs(_ ids: [UUID], preferred: UUID?) { + if let selectedGameID, ids.contains(selectedGameID) { return } + selectedGameID = preferred.flatMap { ids.contains($0) ? $0 : nil } ?? ids.first + } + private mutating func moveIDs(_ ids: [UUID], by delta: Int) -> UUID? { + guard !ids.isEmpty else { selectedGameID = nil; return nil } + let current = ids.firstIndex { $0 == selectedGameID } ?? 0 + selectedGameID = ids[min(max(current + delta, 0), ids.count - 1)] + return selectedGameID + } + private mutating func jumpIDs(_ ids: [UUID], toEnd: Bool) -> UUID? { + selectedGameID = toEnd ? ids.last : ids.first return selectedGameID } } diff --git a/Sources/NXLibraryCore/Models/MenuSelectionModel.swift b/Sources/NXLibraryCore/Models/MenuSelectionModel.swift index c4503df9..315ee19d 100644 --- a/Sources/NXLibraryCore/Models/MenuSelectionModel.swift +++ b/Sources/NXLibraryCore/Models/MenuSelectionModel.swift @@ -2,7 +2,7 @@ import Foundation /// The control-center row, left to right (Selene's menu.png). public enum MenuAction: String, CaseIterable, Identifiable, Equatable { - case addGame, refreshLibrary, settings, theme, console, setupCheck, power + case addGame, refreshLibrary, settings, theme, console, setupCheck, manageSources, power public var id: String { rawValue } public var title: String { @@ -10,6 +10,7 @@ public enum MenuAction: String, CaseIterable, Identifiable, Equatable { case .addGame: return L10n.text("Add Game") case .refreshLibrary: return L10n.text("Library refresh") case .settings: return L10n.text("Settings") + case .manageSources: return L10n.text("Manage sources") case .theme: return "Theme" case .console: return "Console" case .setupCheck: return L10n.text("Setup check") @@ -22,6 +23,7 @@ public enum MenuAction: String, CaseIterable, Identifiable, Equatable { case .addGame: return .add case .refreshLibrary: return .sync case .settings: return .tune + case .manageSources: return .collections case .theme: return .palette case .console: return .terminal case .setupCheck: return .checklist diff --git a/Sources/NXLibraryCore/Models/ModsBandLayout.swift b/Sources/NXLibraryCore/Models/ModsBandLayout.swift index 23a3bb03..4934db56 100644 --- a/Sources/NXLibraryCore/Models/ModsBandLayout.swift +++ b/Sources/NXLibraryCore/Models/ModsBandLayout.swift @@ -36,7 +36,7 @@ public enum ModsBandLayout { } /// The band is a grid that never slides sideways: six tiles to a row, as many rows as it needs, and Down walks - /// the rows as in Build & Sources. + /// the rows as in Details. public static let columns = 6 public static func rows(count: Int) -> Int { diff --git a/Sources/NXLibraryCore/Models/MoonlightAppearance.swift b/Sources/NXLibraryCore/Models/MoonlightAppearance.swift new file mode 100644 index 00000000..3b3866e4 --- /dev/null +++ b/Sources/NXLibraryCore/Models/MoonlightAppearance.swift @@ -0,0 +1,20 @@ +import Foundation + +public enum MoonlightSurface: String, Sendable { + case classic, arcane, flow +} + +/// Fixed local hues, with only a small drift over three minutes. +public enum MoonlightChromatics { + public static let period: Float = 180 + public static let intensity: Float = 0.5 + public static let colors: [SIMD3<Float>] = [SIMD3(187,91,179), SIMD3(92,181,228), SIMD3(103,92,165)].map { $0 / 255 } + + public static func sample(x: Float, y: Float, time: Float, offset: Float = 0) -> SIMD3<Float> { + let phase = time / period * 2 * Float.pi + let pinkWeight = exp(-pow((x - 0.18) / 0.42, 2) - pow((y - 0.77) / 0.5, 2)) + let cyanWeight = exp(-pow((x - 0.84) / 0.42, 2) - pow((y - 0.43) / 0.5, 2)) + let drift = SIMD3<Float>(2.5 * sin(phase), 1.8 * sin(phase + 1), 2.6 * sin(phase + 2)) / 255 + return (colors[0] * pinkWeight + colors[1] * cyanWeight + colors[2] * 0.25) / (pinkWeight + cyanWeight + 0.25) + drift + } +} diff --git a/Sources/NXLibraryCore/Models/MoreLikeThis.swift b/Sources/NXLibraryCore/Models/MoreLikeThis.swift index 69d6cf20..dc339e6d 100644 --- a/Sources/NXLibraryCore/Models/MoreLikeThis.swift +++ b/Sources/NXLibraryCore/Models/MoreLikeThis.swift @@ -3,14 +3,48 @@ import Foundation /// "More like this" for the Details page: other games ranked by shared /// developer/publisher (+2) and shared genres (+1 each). public enum MoreLikeThis { + public struct Traits: Sendable { + public let developers: [String] + public let publishers: [String] + public let genres: [String] + + public init(developers: [String] = [], publishers: [String] = [], genres: [String] = []) { + self.developers = developers + self.publishers = publishers + self.genres = genres + } + + public init(steam metadata: SteamMetadata) { + self.init(developers: metadata.developers, publishers: metadata.publishers, genres: metadata.genres) + } + } + public static func pick(for game: PortedGame, in games: [PortedGame], metadata: (UUID) -> NintendoStoreMetadata?, limit: Int = 6) -> [UUID] { - guard limit > 0, let mine = metadata(game.id) else { return [] } + rank(for: game, in: games, name: \.name, hidden: \.isHidden, limit: limit) { record in + metadata(record.id).map { Traits(developers: $0.developers, publishers: $0.publishers, genres: $0.genres) } + } + } + + /// Prefer the current source. A caller can opt into matching across the library when that source has no match. + public static func pick(for game: CatalogGame, in games: [CatalogGame], + fallbackToOtherSources: Bool = false, traits: (CatalogGame) -> Traits?, limit: Int = 6) -> [UUID] { + let sameSource = rank(for: game, in: games, name: \.name, + hidden: { $0.isHidden || $0.integration != game.integration }, limit: limit, traits: traits) + guard sameSource.isEmpty, fallbackToOtherSources else { return sameSource } + return rank(for: game, in: games, name: \.name, + hidden: { $0.isHidden || $0.integration == game.integration }, limit: limit, traits: traits) + } + + private static func rank<Game: Identifiable>(for game: Game, in games: [Game], + name: (Game) -> String, hidden: (Game) -> Bool, + limit: Int, traits: (Game) -> Traits?) -> [UUID] where Game.ID == UUID { + guard limit > 0, let mine = traits(game) else { return [] } let makers = Set((mine.developers + mine.publishers).map(normalized).filter { !$0.isEmpty }) let genres = Set(mine.genres.map(normalized).filter { !$0.isEmpty && $0 != "other" }) - var scored: [(game: PortedGame, score: Int)] = [] - for other in games where other.id != game.id && !other.isHidden { - guard let theirs = metadata(other.id) else { continue } + var scored: [(game: Game, score: Int)] = [] + for other in games where other.id != game.id && !hidden(other) { + guard let theirs = traits(other) else { continue } var score = 0 let theirMakers = Set((theirs.developers + theirs.publishers).map(normalized)) if !makers.isDisjoint(with: theirMakers) { score += 2 } @@ -19,7 +53,7 @@ public enum MoreLikeThis { } scored.sort { a, b in a.score != b.score ? a.score > b.score - : a.game.name.localizedCaseInsensitiveCompare(b.game.name) == .orderedAscending + : name(a.game).localizedCaseInsensitiveCompare(name(b.game)) == .orderedAscending } return scored.prefix(limit).map { $0.game.id } } diff --git a/Sources/NXLibraryCore/Models/NUPProgramSelection.swift b/Sources/NXLibraryCore/Models/NUPProgramSelection.swift new file mode 100644 index 00000000..018b14da --- /dev/null +++ b/Sources/NXLibraryCore/Models/NUPProgramSelection.swift @@ -0,0 +1,18 @@ +import Foundation + +/// The program packed from a NUP, its owning application and its independent DLC numbering base. +/// Persist it with the sources so a rebuild cannot silently follow a different default program. +public struct NUPProgramSelection: Codable, Equatable, Hashable { + public let programID: UInt64 + public let applicationID: UInt64 + public let addOnContentBaseID: UInt64 + + public init(programID: UInt64, applicationID: UInt64, addOnContentBaseID: UInt64) { + self.programID = programID + self.applicationID = applicationID + self.addOnContentBaseID = addOnContentBaseID + } + + public var index: Int { Int(programID & 0xFFF) } + public var isValid: Bool { programID != 0 && applicationID != 0 && addOnContentBaseID != 0 } +} diff --git a/Sources/NXLibraryCore/Models/PortingFailureReason.swift b/Sources/NXLibraryCore/Models/PortingFailureReason.swift index a537f973..837e45ae 100644 --- a/Sources/NXLibraryCore/Models/PortingFailureReason.swift +++ b/Sources/NXLibraryCore/Models/PortingFailureReason.swift @@ -97,17 +97,17 @@ public struct PortingFailureReason: Codable, Equatable, Sendable { return L10n.format("%@ has no verified nxnative game profile%@; the pinned engine does not support it yet.", [String(describing: (game)), String(describing: (at))]) case .unknown: if let language = missingLanguage { return L10n.format("%@ has no %@, the language set in its Game options.", [String(describing: (game)), String(describing: (language))]) } - return L10n.text("The engine stopped without a message NX Library recognises.") + return L10n.text("The engine stopped without a message Arcane recognises.") } } public var next: String { switch kind { - case .rosetta: return L10n.text("Reinstall NX Library so the porting uses its own arm64 Python.") + case .rosetta: return L10n.text("Reinstall Arcane so the porting uses its own arm64 Python.") case .translator: return L10n.text("Open Setup and check the nxnative engine card.") - case .zbic: return L10n.text("Update NX Library: its built-in Python includes zbic from 0.1.3.2. Installing zbic with pip does not reach it.") + case .zbic: return L10n.text("Update Arcane: its built-in Python includes zbic from 0.1.3.2. Installing zbic with pip does not reach it.") case .cltSelected: return L10n.text("Open Setup and select Xcode.") - case .otherMetal: return L10n.text("Install the certified compiler from Setup, or allow untested toolchains in Settings → Engine.") + case .otherMetal: return L10n.text("Install the certified compiler from Setup, or allow untested toolchains in Settings → Setup and engine.") case .shaderRegression: return L10n.text("Port anyway to keep the broken shaders out, or wait for an engine update.") case .damagedNSP: return isUnreadableDamage ? L10n.text("Dump or download the game again.") diff --git a/Sources/NXLibraryCore/Models/PortingPresentation.swift b/Sources/NXLibraryCore/Models/PortingPresentation.swift index bc57d25d..17c25d43 100644 --- a/Sources/NXLibraryCore/Models/PortingPresentation.swift +++ b/Sources/NXLibraryCore/Models/PortingPresentation.swift @@ -20,6 +20,11 @@ public enum PortingETA { if let last = lastFinishingSeconds { return "About \(duration(eta + last)) left" } return "Shaders: about \(duration(eta))" case .finishing: + // Prewarm has no reliable counter and can dwarf an older build's + // finishing time. Keep the activity visible without reusing that ETA. + if progress.stageName == PortingProgress.prewarmStageName { + return L10n.text("Preparing the first launch") + } if let eta = progress.finishingETA { return "Pipelines: about \(duration(eta))" } guard let last = lastFinishingSeconds else { return "Finishing up" } return "About \(duration(max(0, last - progress.finishingElapsed))) left" @@ -64,6 +69,13 @@ public enum PortingTileLook: Equatable { case filling(Double) /// No app can be played: black and white with a lock. case locked + /// A Steam game Steam is still installing: black and white, the download glyph and "Downloading". + case downloading + + /// A catalog game's tile outside porting: downloading while Steam installs it. + public static func make(catalog game: CatalogGame) -> PortingTileLook { + game.steamGame?.isDownloading == true ? .downloading : .normal + } public static func make(game: PortedGame, portingGameID: UUID?, progress: PortingProgress?) -> PortingTileLook { if game.id == portingGameID, let progress { diff --git a/Sources/NXLibraryCore/Models/PortingProgress.swift b/Sources/NXLibraryCore/Models/PortingProgress.swift index 61666dd5..6cbe1d6f 100644 --- a/Sources/NXLibraryCore/Models/PortingProgress.swift +++ b/Sources/NXLibraryCore/Models/PortingProgress.swift @@ -16,6 +16,7 @@ public struct PortingProgress: Equatable { public static let shaderStageName = "Mac shaders" public static let pipelineArchiveStageName = "Pipeline archive" + public static let prewarmStageName = "Prewarm pipelines" public static let shaderShare = 0.9 /// The stages after the shaders when the engine has not counted them yet. public static let expectedFinishingStages = 3 diff --git a/Sources/NXLibraryCore/Models/SaveLocation.swift b/Sources/NXLibraryCore/Models/SaveLocation.swift index 346c0083..b36c64e5 100644 --- a/Sources/NXLibraryCore/Models/SaveLocation.swift +++ b/Sources/NXLibraryCore/Models/SaveLocation.swift @@ -24,7 +24,21 @@ public enum SaveFailure: LocalizedError, Equatable { } } -public enum SaveSlot: String, Codable, CaseIterable, Hashable { case account, device } +public enum SaveSlot: String, Codable, CaseIterable, Hashable { + case account, device, user2, user3, user4, user5, user6, user7, user8, users + + public static let legacyCases: [SaveSlot] = [.account, .device] + public var isLegacy: Bool { Self.legacyCases.contains(self) } + public var isDirectory: Bool { self != .users } + public var fileName: String { + switch self { + case .account: return "save" + case .device: return "save_device" + case .users: return "save.users" + default: return "save_" + rawValue + } + } +} public struct SaveContext { public let location: SaveLocation public let cloudReason: String? @@ -35,7 +49,8 @@ public struct SaveContext { public struct SaveLocation: Equatable { public let titleID: String public let root: URL - public func directory(_ slot: SaveSlot) -> URL { root.appendingPathComponent(slot == .account ? "save" : "save_device") } + /// Historical name: the users component is a regular registry file; the other components are directories. + public func directory(_ slot: SaveSlot) -> URL { root.appendingPathComponent(slot.fileName) } /// nxnative's journal of a cloud-save pull (dm/host/save_sync.c, `<DM_SAVE>.pull`, nxnative e6048dea): while it is /// there, the game's next start puts this device's save back, so nothing may replace the save folders first. public var cloudPullJournal: URL { root.appendingPathComponent("save.pull") } @@ -71,7 +86,7 @@ public struct SaveLocation: Equatable { if let sync = env["DM_SAVE_SYNC"] { if !sync.isEmpty && sync != "0" { reason = origins["DM_SAVE_SYNC"] } } else if let libraryCloudFolder, !libraryCloudFolder.isEmpty { - reason = "NX Library → Settings → Games" + reason = "Arcane → Settings → Cloud saves" } else if let gameCloudFolder, !gameCloudFolder.isEmpty { reason = "the game's Cloud saves settings" } diff --git a/Sources/NXLibraryCore/Models/SavePresentation.swift b/Sources/NXLibraryCore/Models/SavePresentation.swift index 597ad3e6..13a3943c 100644 --- a/Sources/NXLibraryCore/Models/SavePresentation.swift +++ b/Sources/NXLibraryCore/Models/SavePresentation.swift @@ -8,9 +8,19 @@ public enum SavePresentation { return cloud ? .cloudSettings : .chooseFolder } public static var closedNotice: String { L10n.text("Keep the game closed, including launches from Finder, until the operation finishes.") } - public static var cloudNotice: String { L10n.text("Backups capture the local committed save, which may differ from a save not yet received from the cloud.") } + public static var cloudScope: String { L10n.text("Cloud sync covers only the primary user and device save.") } + public static var cloudNotice: String { + L10n.text("Backups capture the local committed save, which may differ from a save not yet received from the cloud.") + "\n" + cloudScope + } public static var importWarning: String { L10n.text("A save from a newer game version may not load. Cloud saves may replace this local save if you turn sync on later.") } - public static func slotName(_ slot: SaveSlot) -> String { slot == .account ? L10n.text("User save") : L10n.text("Device save") } + public static func slotName(_ slot: SaveSlot) -> String { + switch slot { + case .account: return L10n.text("User save") + case .device: return L10n.text("Device save") + case .users: return L10n.text("Local users") + default: return L10n.format("User %@", [String(slot.rawValue.dropFirst(4))]) + } + } public static func size(_ bytes: Int64) -> String { bytes.formatted(.byteCount(style: .file).locale(L10n.context.formatLocale)) } public static func date(_ date: Date) -> String { let formatter = DateFormatter() @@ -21,7 +31,10 @@ public enum SavePresentation { public static func restoreMessage(_ snapshot: SaveSnapshot, installedVersion: String?) -> String { let saved = snapshot.identity.version ?? L10n.text("Unknown") let current = installedVersion ?? L10n.text("Unknown") - return L10n.format("Restore the backup from %@? The current save will be backed up first.\n\nBackup game version: %@ · Installed: %@. Different versions may be incompatible.\n\nCloud saves may replace the restored local save if sync is enabled later.", [date(snapshot.created), saved, current]) + let scope = snapshot.schemaVersion == 1 + ? L10n.text("This older backup restores only the primary user and device save. Other local users will be kept.") + : L10n.text("This backup restores all local users and their registry.") + return L10n.format("Restore the backup from %@? The current save will be backed up first.\n\nBackup game version: %@ · Installed: %@. Different versions may be incompatible.\n\nCloud saves may replace the restored local save if sync is enabled later.", [date(snapshot.created), saved, current]) + "\n\n" + scope + "\n" + cloudScope } public static func importSummary(_ preview: SaveImportPreview, version: String?) -> String { let files = L10n.count("%lld files", preview.fileCount) diff --git a/Sources/NXLibraryCore/Models/SaveSnapshot.swift b/Sources/NXLibraryCore/Models/SaveSnapshot.swift index 7faa8336..292859f8 100644 --- a/Sources/NXLibraryCore/Models/SaveSnapshot.swift +++ b/Sources/NXLibraryCore/Models/SaveSnapshot.swift @@ -27,6 +27,10 @@ public struct SaveSnapshot: Codable, Equatable, Identifiable { public var presentSlots: Set<SaveSlot> public var entries: [SaveInventoryEntry] public var byteCount: Int64 { entries.reduce(0) { $0 + $1.byteCount } } + internal var hasSupportedSchema: Bool { + schemaVersion == 2 || (schemaVersion == 1 && presentSlots.allSatisfy(\.isLegacy) + && entries.allSatisfy { $0.slot.isLegacy }) + } } public struct SaveImportPreview: Equatable { public let id: UUID diff --git a/Sources/NXLibraryCore/Models/SelenePalette.swift b/Sources/NXLibraryCore/Models/SelenePalette.swift index 6d3dbfac..b5ac8032 100644 --- a/Sources/NXLibraryCore/Models/SelenePalette.swift +++ b/Sources/NXLibraryCore/Models/SelenePalette.swift @@ -32,11 +32,13 @@ public struct SelenePalette: Codable, Equatable, Identifiable { public var glass: UInt32 public var glyph: UInt32 public var success: UInt32 + public var moonlight: String? = nil + public var surface: MoonlightSurface { MoonlightSurface(rawValue: moonlight ?? "") ?? .classic } public var base: BaseGradient /// Built-in Selene palette, used when palettes.json is unavailable. public static let fallback = SelenePalette( - id: "selene", name: "Default", mode: .dark, + id: "selene", name: AppIdentity.name, mode: .dark, focus: 0xFFFFFF, onFocus: 0x111111, ink: 0xFFFFFF, scrim: 0x000000, glass: 0x14181F, glyph: 0x9CCBFF, success: 0x3DDC84, base: .init(kind: .linear, stops: [ diff --git a/Sources/NXLibraryCore/Models/SessionSummary.swift b/Sources/NXLibraryCore/Models/SessionSummary.swift index bbc55549..778895b7 100644 --- a/Sources/NXLibraryCore/Models/SessionSummary.swift +++ b/Sources/NXLibraryCore/Models/SessionSummary.swift @@ -13,11 +13,20 @@ public struct SessionSummary: Equatable, Identifiable { public let total: String public init?(session: PlaySession, game: PortedGame, total: TimeInterval) { - guard session.gameID == game.id, let length = session.duration, + self.init(session: session, gameID: game.id, gameName: game.name, total: total) + } + + /// A catalog game's session: a Steam game's card reads like an nxnative one's. + public init?(session: PlaySession, game: CatalogGame, total: TimeInterval) { + self.init(session: session, gameID: game.id, gameName: game.name, total: total) + } + + private init?(session: PlaySession, gameID: UUID, gameName: String, total: TimeInterval) { + guard session.gameID == gameID, let length = session.duration, length >= Self.minimumDuration else { return nil } id = session.id - gameID = game.id - gameName = game.name + self.gameID = gameID + self.gameName = gameName thisSession = Self.duration(length) self.total = Self.duration(max(total, length)) } diff --git a/Sources/NXLibraryCore/Models/SettingsCatalog.swift b/Sources/NXLibraryCore/Models/SettingsCatalog.swift index e9fa9dab..a8959ca7 100644 --- a/Sources/NXLibraryCore/Models/SettingsCatalog.swift +++ b/Sources/NXLibraryCore/Models/SettingsCatalog.swift @@ -34,24 +34,33 @@ public enum SettingsCatalog { SettingDescriptor(id: id, group: group, title: title, about: about) } - public static let all: [SettingDescriptor] = [ + /// In sidebar order (`SettingsSidebarGroup`), each section's rows as listed. + public static let all: [SettingDescriptor] = { + let order = SettingsSidebarGroup.all.flatMap(\.sections) + return listed.enumerated().sorted { + (order.firstIndex(of: $0.element.group) ?? order.count, $0.offset) + < (order.firstIndex(of: $1.element.group) ?? order.count, $1.offset) + }.map(\.element) + }() + + private static let listed: [SettingDescriptor] = [ // Start-up row("appLanguage", .startUp, "App language", "Menus, genres and available game descriptions. The games’ own language stays separate.") { $0.appLanguage }, row("appRegion", .startUp, "Regional formats", "Dates, numbers and sizes only. Game descriptions follow the app language.") { $0.appRegion }, row("startOn", .startUp, "Start on", - "The screen NX Library opens on: Spotlight, Collection, or where you left it.") { $0.startOn }, + "The screen Arcane opens on: Spotlight, Collection, or where you left it.") { $0.startOn }, row("restoreLastGame", .startUp, "Restore last game", "Opens with the game you had selected last time.") { $0.restoreLastGame }, row("startInFullscreen", .startUp, "Start in fullscreen", - "Open NX Library in fullscreen. Applies at the next launch.") { $0.startInFullscreen }, - row("checkEngineAtLaunch", .startUp, "Check engine at launch", - "Checks the engine and toolchain each time NX Library starts.") { $0.checkEngineAtLaunch }, - row("refreshLibraryAtLaunch", .startUp, "Refresh library at launch", + "Open Arcane in fullscreen. Applies at the next launch.") { $0.startInFullscreen }, + row("checkEngineAtLaunch", .engine, "Check engine at launch", + "Checks the engine and toolchain each time Arcane starts.") { $0.checkEngineAtLaunch }, + row("refreshLibraryAtLaunch", .library, "Refresh library at launch", "Scans your library folders for new or removed games at start.") { $0.refreshLibraryAtLaunch }, row("checkAppUpdatesAtLaunch", .startUp, "Check for app updates", - "Looks for a newer NX Library release at launch, at most once a day.") { $0.checkAppUpdatesAtLaunch }, - row("introAnimation", .startUp, "Intro animation", - "Plays a short opening with the boot sound when the app opens.") { $0.introAnimation }, + "Looks for a newer Arcane release at launch, at most once a day.") { $0.checkAppUpdatesAtLaunch }, + row("introAnimation", .startUp, "Entrance animation", + "The library's tiles fly in with the boot sound when the app opens.") { $0.introAnimation }, // Navigation row("showButtonHints", .navigation, "Button hints", @@ -103,25 +112,27 @@ public enum SettingsCatalog { row("reduceMotion", .look, "Reduce motion", "Replaces slides and zooms with fades.") { $0.reduceMotion }, action("iconAppearance", .look, "App icon", "The icon appearance in the Dock."), - action("boxCovers", .look, "Box covers", "Open GameTDB for box covers."), - action("steamGridDB", .look, "SteamGridDB", "Add your API key to find covers, backgrounds, logos and icons in Change artwork."), + action("boxCovers", .library, "Box covers", "Open GameTDB for box covers."), + // Optional connections shared by all library platforms. + action("igdb", .apiServices, "IGDB", "Personal IGDB credentials for critic scores. Wikidata remains available without a key."), + action("steamGridDB", .apiServices, "SteamGridDB", "Add your API key to find covers, backgrounds, logos and icons in Change artwork."), - // Games - row("launchStyle", .games, "Launch screen style", + // Games (Library) and New games (Porting) + row("launchStyle", .libraryGames, "Launch screen style", "What shows while a game starts: art and logo, art only, logo on black, or minimal.") { $0.launchStyle }, - row("launchMotion", .games, "Launch screen motion", + row("launchMotion", .libraryGames, "Launch screen motion", "A slow drift of the art while the game starts.") { $0.launchMotion }, - row("launchShade", .games, "Launch screen shade", + row("launchShade", .libraryGames, "Launch screen shade", "How much the launch art is darkened.") { $0.launchShade }, - row("surprisePool", .games, "Surprise me pool", + row("surprisePool", .libraryGames, "Surprise me pool", "Which games Surprise me picks from.") { $0.surprisePool }, - row("cloudSaves", .games, "Cloud saves", - "One sync choice for all games, applied at next launch: Off, iCloud Drive or a folder you choose.") { $0.cloudSaves }, - row("cloudSavesPickedFolder", .games, "Cloud saves folder", + row("cloudSaves", .cloudSaves, "Cloud saves", + "One sync choice for all games, applied at next launch: Off, iCloud Drive or a folder you choose. Only the primary user and device save sync.") { $0.cloudSaves }, + row("cloudSavesPickedFolder", .cloudSaves, "Cloud saves folder", "The chosen folder for save sync; choosing a folder enables it.") { $0.cloudSavesPickedFolder }, - row("showsSessionCard", .games, "Session card", + row("showsSessionCard", .libraryGames, "Session card", "When you close a game, a card shows how long you played this time and in total.") { $0.showsSessionCard }, - action("hiddenGames", .games, "Hidden games", + action("hiddenGames", .libraryGames, "Hidden games", "Games you hid from Game options; Show puts one back in your lists."), row("gameDefaults.fullscreen", .games, "Fullscreen", "New games: start in fullscreen or a window.") { $0.gameDefaults.fullscreen }, @@ -144,37 +155,42 @@ public enum SettingsCatalog { action("buttonLayout", .controllers, "Button layout", "View the library controls."), action("controllerDeadzone", .controllers, "Stick navigation deadzone", "Thumbstick threshold for library navigation; does not alter game input."), - row("gameDefaults.rumble", .controllers, "Rumble", - "Default controller vibration for new games.") { $0.gameDefaults.rumble }, - row("gameDefaults.rumbleGain", .controllers, "Rumble strength", - "Default vibration strength for new games.") { $0.gameDefaults.rumbleGain }, + row("gameDefaults.rumble", .games, "Rumble", + "New games: default controller vibration for new ported games.") { $0.gameDefaults.rumble }, + row("gameDefaults.rumbleGain", .games, "Rumble strength", + "New games: default vibration strength for new ported games.") { $0.gameDefaults.rumbleGain }, // Library action("gameFolder", .library, GameFoldersCopy.sourcesTitle, "Game sources: NSP, XCI, NSZ and XCZ files, or Switch 2 NUP files and extracted folders, for builds. Optional for existing apps."), action("libraryFolder", .library, GameFoldersCopy.appsTitle, "Choose where to find existing nxnative game apps and install new builds."), action("libraryRefresh", .library, "Scan game apps", "Find existing nxnative builds and refresh the library."), row("notifyPortingEnds", .library, "Notify when a porting ends", - "A notification when a porting finishes while NX Library is in the background.") { $0.notifyPortingEnds }, + "A notification when a porting finishes while Arcane is in the background.") { $0.notifyPortingEnds }, + // Steam + action("steamSource", .sources, "Steam", "Find installed native Mac games in your Steam libraries."), + action("steamRefresh", .sources, "Refresh Steam", "Check enabled Steam libraries without changing your game files."), + action("steamFolder", .sources, "Steam folder", "Choose the Steam folder containing steamapps."), + row("steamInBackground", .sources, "Keep Steam in the background", + "Steam starts quietly when possible and comes forward if it needs you.") { $0.steamInBackground }, // Storage action("storageUsage", .storage, "Storage usage", "See per-game app, cache and log sizes and free disk space."), - action("buildCaches", .storage, "Build caches", "Delete a game's build cache or clear all caches after confirmation; rebuilds may take longer."), + action("buildCaches", .portingStorage, "Build caches", "Delete a game's build cache or clear all caches after confirmation; rebuilds may take longer."), action("logs", .storage, "Logs", "Delete build and launch logs after confirmation."), action("metadataCache", .storage, "Metadata cache", "Clear cached store descriptions and links."), action("artworkCache", .storage, "Artwork cache", "Clear downloaded images; manual picks are kept."), action("saveBackups", .storage, "Save backups", "Open the folder of verified per-game backups."), - action("console", .storage, "Console", "View, search and copy logs."), + action("console", .console, "Console", "View, search and copy logs."), // Engine action("engineFolder", .engine, "Engine repository", "The upstream checkout used for porting; updates stay manual."), - action("engineStatus", .engine, "Compatibility", "Engine commit, Metal compiler, toolchain gate and required flags."), + action("engineStatus", .engine, "Compatibility", "Engine commit, Metal compiler, build environment, toolchain gate and required flags."), action("toolchainOverride", .engine, "Untested toolchain override", "Explicitly allow unverified new portings."), action("upstream", .engine, "Upstream", "Check newer engine commits without installing them."), - action("newestEngine", .engine, "Newest engine", "Build with nxnative main before NX Library has tested it, or go back to the tested engine."), + action("newestEngine", .engine, "Newest engine", "Build with nxnative main before Arcane has tested it, or go back to the tested engine."), action("compare", .engine, "Compare", "Open the commit comparison on GitHub."), - action("keys", .engine, "prod.keys", "Import, replace or detect private keys."), - action("setup", .startUp, "Setup", "Open the setup checklist."), - action("environment", .startUp, "Environment", "Re-check the environment and build requirements."), + action("keys", .keys, "prod.keys", "Import, replace or detect private keys."), + action("setup", .engine, "Setup", "Open the setup checklist."), action("diagnostics", .about, "Copy diagnostics", "Copy a scrubbed support report."), action("appUpdates", .about, "App updates", "Check now, update or read release notes."), action("projectDocs", .about, "Open project docs", "Open the project documentation."), diff --git a/Sources/NXLibraryCore/Models/SettingsReset.swift b/Sources/NXLibraryCore/Models/SettingsReset.swift new file mode 100644 index 00000000..d52bae55 --- /dev/null +++ b/Sources/NXLibraryCore/Models/SettingsReset.swift @@ -0,0 +1,71 @@ +import Foundation + +/// What Reset group puts back in `AppSettings`, one section at a time. Preferences outside +/// `AppSettings` (theme applied, app icon, stick deadzone, game apps folder) are reset by the +/// Settings screen beside this; cloud saves and credentials are never reset. +public enum SettingsReset { + public static func canReset(_ section: SettingsSection) -> Bool { + switch section { + case .startUp, .navigation, .spotlight, .soundMusic, .look, .controllers, .libraryGames, .library, .games: + return true + case .search, .changed, .apiServices, .sources, .storage, .engine, .keys, .cloudSaves, .portingStorage, + .about, .console: + return false + } + } + + /// `settings` with the section's values back at their defaults; everything else unchanged. + public static func reset(_ section: SettingsSection, in settings: AppSettings) -> AppSettings { + let defaults = AppSettings() + var next = settings + switch section { + case .startUp: + next.appLanguage = defaults.appLanguage + next.appRegion = defaults.appRegion + next.startOn = defaults.startOn + next.restoreLastGame = defaults.restoreLastGame + next.startInFullscreen = defaults.startInFullscreen + next.checkAppUpdatesAtLaunch = defaults.checkAppUpdatesAtLaunch + next.introAnimation = defaults.introAnimation + case .navigation: + next.showButtonHints = defaults.showButtonHints + next.buttonNames = defaults.buttonNames + next.viewButtonSwitches = defaults.viewButtonSwitches + case .spotlight: + next.visibleSpotlightCards = defaults.visibleSpotlightCards + next.startingTab = defaults.startingTab + next.spotlightOrder = defaults.spotlightOrder + case .soundMusic: + next.interfaceSounds = defaults.interfaceSounds + next.soundVolume = defaults.soundVolume + next.quietLaunch = defaults.quietLaunch + case .look: + next.colorThemeID = defaults.colorThemeID + next.wallpaperID = defaults.wallpaperID + next.settingsWallpaperID = defaults.settingsWallpaperID + next.keepWallpaperOnGames = defaults.keepWallpaperOnGames + next.backgroundSizing = defaults.backgroundSizing + next.wallpaperBrightness = defaults.wallpaperBrightness + next.backgroundShade = defaults.backgroundShade + next.readableText = defaults.readableText + next.animatedBackground = defaults.animatedBackground + next.showClock = defaults.showClock + next.reduceMotion = defaults.reduceMotion + case .libraryGames: + next.launchStyle = defaults.launchStyle + next.launchMotion = defaults.launchMotion + next.launchShade = defaults.launchShade + next.showsSessionCard = defaults.showsSessionCard + next.surprisePool = defaults.surprisePool + case .games: + next.gameDefaults = defaults.gameDefaults + case .library: + next.refreshLibraryAtLaunch = defaults.refreshLibraryAtLaunch + next.notifyPortingEnds = defaults.notifyPortingEnds + case .controllers, .search, .changed, .apiServices, .sources, .storage, .engine, .keys, .cloudSaves, + .portingStorage, .about, .console: + break + } + return next + } +} diff --git a/Sources/NXLibraryCore/Models/SettingsSection.swift b/Sources/NXLibraryCore/Models/SettingsSection.swift index 097c3c4a..ea6fb355 100644 --- a/Sources/NXLibraryCore/Models/SettingsSection.swift +++ b/Sources/NXLibraryCore/Models/SettingsSection.swift @@ -1,10 +1,15 @@ import Foundation -/// The groups on the Settings screen (spec §5.7). `search` and `changed` are -/// computed lists; `about` is informational and has no catalog rows. +/// The sections on the Settings screen. `search` and `changed` are computed lists. public enum SettingsSection: String, CaseIterable, Identifiable, Equatable { - case search, changed, startUp, navigation, spotlight, soundMusic - case look, games, controllers, library, storage, engine, about + // Declared in sidebar order (`SettingsSidebarGroup`), so `allCases` steps through it as drawn. + // Raw values are identities and never change: `sources` is the Sources page, `library` and + // `games` are Porting's Library and New games. + case search, changed + case startUp, navigation, spotlight, soundMusic, look, controllers, apiServices + case sources, libraryGames, storage + case engine, keys, library, games, cloudSaves, portingStorage + case about, console public var id: String { rawValue } @@ -23,12 +28,19 @@ public enum SettingsSection: String, CaseIterable, Identifiable, Equatable { case .spotlight: return "Spotlight" case .soundMusic: return "Sound & music" case .look: return "Look" - case .games: return "Games" + case .apiServices: return "Online services" case .controllers: return "Controllers" - case .library: return "Library" + case .sources: return "Settings section: Sources" + case .libraryGames: return "Games" case .storage: return "Storage" - case .engine: return "Engine" + case .engine: return "Setup and engine" + case .keys: return "Keys" + case .library: return "Library" + case .games: return "New games" + case .cloudSaves: return "Cloud saves" + case .portingStorage: return "Storage" case .about: return "About" + case .console: return "Console" } } @@ -36,17 +48,24 @@ public enum SettingsSection: String, CaseIterable, Identifiable, Equatable { switch self { case .search: return L10n.text("Find any setting by name or description.") case .changed: return L10n.text("Settings that differ from the defaults.") - case .startUp: return L10n.text("Startup, setup and readiness.") + case .startUp: return L10n.text("Language, the first screen and what runs at launch.") case .navigation: return L10n.text("Button hints, button names and the View button.") case .spotlight: return L10n.text("Which cards show on Spotlight and where it opens.") case .soundMusic: return L10n.text("Interface sounds, volume and the launch screen.") - case .look: return L10n.text("How NX Library looks and moves.") - case .games: return L10n.text("Launch screen, hidden games and defaults for new games.") - case .controllers: return L10n.text("Library controls and new-game rumble.") - case .library: return L10n.text("Folders, imports and artwork caches.") - case .storage: return L10n.text("Caches, logs, saves and the console.") - case .engine: return L10n.text("Engine pin, toolchain gate and keys.") + case .look: return L10n.text("How Arcane looks and moves.") + case .apiServices: return L10n.text("Optional connections for ratings and game artwork.") + case .controllers: return L10n.text("Gamepad, button layout and stick deadzone for the library.") + case .sources: return L10n.text("Steam libraries, refresh and how Play opens Steam.") + case .libraryGames: return L10n.text("Launch screen, Surprise me, session card and hidden games.") + case .storage: return L10n.text("Storage usage, logs, metadata and artwork caches, save backups.") + case .engine: return L10n.text("Engine pin, toolchain gate and setup.") + case .keys: return L10n.text("Import, replace or detect prod.keys.") + case .library: return L10n.text("Folders, scans and box covers.") + case .games: return L10n.text("Defaults copied into each new ported game.") + case .cloudSaves: return L10n.text("Save sync for ported games: Off, iCloud Drive or a folder.") + case .portingStorage: return L10n.text("Build caches for each game and for all games.") case .about: return L10n.text("Version, credits and licenses.") + case .console: return L10n.text("Filter, search and copy build and launch logs.") } } @@ -60,12 +79,58 @@ public enum SettingsSection: String, CaseIterable, Identifiable, Equatable { case .spotlight: return .spotlight case .soundMusic: return .volume case .look: return .palette - case .games: return .play + case .apiServices: return .link case .controllers: return .gamepad - case .library: return .collections + case .sources: return .collections + case .libraryGames: return .play case .storage: return .storage case .engine: return .build + case .keys: return .key + case .library: return .collections + case .games: return .tune + case .cloudSaves: return .sync + case .portingStorage: return .folder case .about: return .info + case .console: return .terminal } } + + public var group: SettingsSidebarGroup { + SettingsSidebarGroup.all.first { $0.sections.contains(self) } ?? SettingsSidebarGroup.all[0] + } + + /// The name Search and Changed show: a platform's section carries its group ("Porting · New games"). + public var place: String { place(in: L10n.context) } + + public func place(in context: AppLocale) -> String { + guard group.isPlatform, let heading = group.title(in: context) else { return title(in: context) } + return "\(heading) · \(title(in: context))" + } +} + +/// The sidebar's groups, in order: app-wide settings, the library of every source, the Porting +/// platform, then System. A heading is a label, never a stop. +public struct SettingsSidebarGroup: Identifiable, Equatable { + /// Localization key ("Settings group: Porting"); the first group has none. + public let heading: String? + public let sections: [SettingsSection] + /// A platform's group: its settings act only on that platform's games. + public let isPlatform: Bool + + public var id: String { heading ?? "top" } + + /// The heading as drawn, from its own key so a bare word is never translated as a verb. + public var title: String? { title(in: L10n.context) } + + public func title(in context: AppLocale) -> String? { + heading.map { L10n.text($0, context: context) } + } + + public static let all: [SettingsSidebarGroup] = [ + .init(heading: nil, sections: [.search, .changed], isPlatform: false), + .init(heading: "Settings group: General", sections: [.startUp, .navigation, .spotlight, .soundMusic, .look, .controllers, .apiServices], isPlatform: false), + .init(heading: "Settings group: Library", sections: [.sources, .libraryGames, .storage], isPlatform: false), + .init(heading: "Settings group: Porting", sections: [.engine, .keys, .library, .games, .cloudSaves, .portingStorage], isPlatform: true), + .init(heading: "Settings group: System", sections: [.about, .console], isPlatform: false), + ] } diff --git a/Sources/NXLibraryCore/Models/SetupCheck.swift b/Sources/NXLibraryCore/Models/SetupCheck.swift index 5a91bf6f..e7e40414 100644 --- a/Sources/NXLibraryCore/Models/SetupCheck.swift +++ b/Sources/NXLibraryCore/Models/SetupCheck.swift @@ -65,7 +65,7 @@ public struct SetupFacts: Equatable { /// The checkout's HEAD is an ancestor of the pin (an NX Library update brought a newer engine); false when it /// is ahead or elsewhere; nil when git cannot tell (the pin is not fetched yet, so it is newer). public var engineBehind: Bool? - /// The newest nxnative the player chose in Settings → Engine; nil while the tested engine is in use. + /// The newest nxnative the player chose in Settings → Setup and engine; nil while the tested engine is in use. public var newestEngine: NewestEngineChoice? = nil public init(xcodeStatus: Int32?, metalVersion: String?, certifiedMetal: String, allowUntested: Bool, @@ -97,7 +97,7 @@ public enum SetupOverride: Equatable { } public enum SetupCheck { - /// The technical screen has no folder choices; those belong to Your games and Settings → Library. + /// The technical screen has no folder choices; those belong to Your games and Settings → Porting → Library. public static func requirements(_ items: [SetupItem]) -> [SetupItem] { items.filter { $0.id != .library && $0.id != .sources } } @@ -182,7 +182,7 @@ public enum SetupCheck { let about = L10n.text("Compiles each game's shaders for this Mac's GPU.") guard let version = f.metalVersion else { return SetupItem(id: id, title: L10n.text("Metal compiler"), state: .missing, chip: "NOT INSTALLED", - about: about, detail: L10n.text("NX Library downloads it through Xcode."), actionTitle: L10n.text("Install")) + about: about, detail: L10n.text("Arcane downloads it through Xcode."), actionTitle: L10n.text("Install")) } if version == f.certifiedMetal { return ready(id, "Metal compiler", about, L10n.format("Version %@, the one this engine is tested with.", [String(describing: (version))])) @@ -193,26 +193,26 @@ public enum SetupCheck { } if f.requirements.metalDownload(for: f.certifiedMetal) != nil { return SetupItem(id: id, title: L10n.text("Metal compiler"), state: .warning, chip: "NOT CERTIFIED", about: about, - detail: L10n.format("Version %@; the engine is tested with %@. NX Library installs %@ through Xcode.", [String(describing: (version)), String(describing: (f.certifiedMetal)), String(describing: (f.certifiedMetal))]), + detail: L10n.format("Version %@; the engine is tested with %@. Arcane installs %@ through Xcode.", [String(describing: (version)), String(describing: (f.certifiedMetal)), String(describing: (f.certifiedMetal))]), actionTitle: L10n.format("Install %@", [String(describing: (f.certifiedMetal))])) } return SetupItem(id: id, title: L10n.text("Metal compiler"), state: .warning, chip: "WAITING FOR ENGINE", about: about, - detail: L10n.format("Version %@ came with this Xcode; the engine is tested with %@. New builds wait for an NX Library update tested with it. Games you built still play.", [String(describing: (version)), String(describing: (f.certifiedMetal))]), + detail: L10n.format("Version %@ came with this Xcode; the engine is tested with %@. New builds wait for an Arcane update tested with it. Games you built still play.", [String(describing: (version)), String(describing: (f.certifiedMetal))]), actionTitle: nil) case .engine: - let about = L10n.text("nxnative, used as it is upstream, at the commit this NX Library is tested with.") + let about = L10n.text("nxnative, used as it is upstream, at the commit this version of Arcane is tested with.") let short = String(f.pinnedCommit.prefix(7)) switch f.engine { case .missing: return SetupItem(id: id, title: L10n.text("nxnative engine"), state: .missing, chip: "NOT INSTALLED", about: about, - detail: L10n.format("NX Library clones it into %@ at %@.", [String(describing: (f.engineFolder.path)), String(describing: (short))]), actionTitle: L10n.text("Clone")) + detail: L10n.format("Arcane clones it into %@ at %@.", [String(describing: (f.engineFolder.path)), String(describing: (short))]), actionTitle: L10n.text("Clone")) case .notACheckout: return SetupItem(id: id, title: L10n.text("nxnative engine"), state: .warning, chip: "NOT A CHECKOUT", about: about, detail: L10n.format("%@ is not a git checkout of nxnative. Move it away, then check again.", [String(describing: (f.engineFolder.path))]), actionTitle: nil) case .checkout(_, true): return SetupItem(id: id, title: L10n.text("nxnative engine"), state: .warning, chip: "LOCAL CHANGES", about: about, - detail: L10n.format("%@ has changed files. NX Library never touches them: put them aside, then check again.", [String(describing: (f.engineFolder.path))]), + detail: L10n.format("%@ has changed files. Arcane never touches them: put them aside, then check again.", [String(describing: (f.engineFolder.path))]), actionTitle: nil) case .checkout(let head, false) where head == f.newestEngine?.commit && head != f.pinnedCommit: // The player's own choice: ready, never "other version", and A goes back to the tested engine. @@ -226,20 +226,20 @@ public enum SetupCheck { // Warning either way: Setup reopens for it and Install all runs it. if f.engineBehind == false { return SetupItem(id: id, title: L10n.text("nxnative engine"), state: .warning, chip: "OTHER VERSION", about: about, - detail: L10n.format("The engine here is at %@, not the %@ this NX Library is tested with. Switch moves it to %@. Games you built keep playing.", [String(describing: (head.prefix(7))), String(describing: (short)), String(describing: (short))]), + detail: L10n.format("The engine here is at %@, not the %@ this version of Arcane is tested with. Switch moves it to %@. Games you built keep playing.", [String(describing: (head.prefix(7))), String(describing: (short)), String(describing: (short))]), actionTitle: L10n.text("Switch")) } return SetupItem(id: id, title: L10n.text("nxnative engine"), state: .warning, chip: "UPDATE READY", about: about, - detail: L10n.format("This NX Library uses nxnative %@; the engine here is at %@. Update downloads it and switches to it. Games you built keep playing.", [String(describing: (short)), String(describing: (head.prefix(7)))]), + detail: L10n.format("This version of Arcane uses nxnative %@; the engine here is at %@. Update downloads it and switches to it. Games you built keep playing.", [String(describing: (short)), String(describing: (head.prefix(7)))]), actionTitle: L10n.text("Update")) case .checkout: return ready(id, L10n.text("nxnative engine"), about, "At \(short) in \(f.engineFolder.path).") } case .runtime: - let about = L10n.text("Python 3.14 with its modules, zstd and glslang, inside NX Library.") + let about = L10n.text("Python 3.14 with its modules, zstd and glslang, inside Arcane.") if let problem = f.runtimeProblem { return SetupItem(id: id, title: L10n.text("Python and tools"), state: .failed, chip: "REINSTALL APP", about: about, - detail: L10n.format("%@. Reinstall NX Library from its DMG.", [String(describing: (problem))]), actionTitle: nil) + detail: L10n.format("%@. Reinstall Arcane from its DMG.", [String(describing: (problem))]), actionTitle: nil) } return SetupItem(id: id, title: L10n.text("Python and tools"), state: .ready, chip: "✓ INCLUDED", about: about, detail: L10n.text("Nothing to install."), actionTitle: nil) @@ -271,7 +271,7 @@ public enum SetupCheck { case false?: return SetupItem(id: id, title: GameFoldersCopy.appsTitle, state: .warning, chip: "NOT READABLE", about: about, detail: f.libraryFolder.map { L10n.format("Cannot read %@. Reconnect it or choose another.", [String(describing: ($0.path))]) } - ?? L10n.text("NX Library cannot read this folder. Reconnect it or choose another."), actionTitle: L10n.text("Choose folder")) + ?? L10n.text("Arcane cannot read this folder. Reconnect it or choose another."), actionTitle: L10n.text("Choose folder")) case true?: if f.libraryWritable == false { return SetupItem(id: id, title: GameFoldersCopy.appsTitle, state: .warning, chip: "READ ONLY", about: about, @@ -287,7 +287,7 @@ public enum SetupCheck { switch f.sourcesReadable { case nil: return SetupItem(id: id, title: GameFoldersCopy.sourcesTitle, state: .ready, chip: "OPTIONAL", about: about, - detail: L10n.text("Existing game apps play without sources. Choose later in Settings → Library."), + detail: L10n.text("Existing game apps play without sources. Choose later in Settings → Porting → Library."), actionTitle: L10n.text("Choose folder"), isRequired: false) case false?: return SetupItem(id: id, title: GameFoldersCopy.sourcesTitle, state: .warning, chip: "FOLDER UNAVAILABLE", about: about, diff --git a/Sources/NXLibraryCore/Models/SourceSelection.swift b/Sources/NXLibraryCore/Models/SourceSelection.swift index 0fe16ef0..ac4ef753 100644 --- a/Sources/NXLibraryCore/Models/SourceSelection.swift +++ b/Sources/NXLibraryCore/Models/SourceSelection.swift @@ -51,11 +51,33 @@ public enum SourceSelection { } public static func supported(_ files: [GameFileItem], titleSelection: Bool, extractedFolders: Bool, - nupContainers: Bool = false) -> Bool { - files.allSatisfy { ($0.layout != .extracted || extractedFolders) + nupContainers: Bool = false, nupPrograms: Bool = false) -> Bool { + if files.contains(where: { $0.layout == .container }) { + guard files.allSatisfy({ $0.layout == .container }), Set(files.map(path)).count == 1 else { return false } + } + if let program = files.compactMap(\.nupProgram).first { + guard nupPrograms, program.isValid, + files.allSatisfy({ $0.layout == .container && $0.nupProgram == program }), + Set(files.map(path)).count == 1 else { return false } + } + return files.allSatisfy { ($0.layout != .extracted || extractedFolders) && ($0.layout != .container || nupContainers) && ($0.requiresTitleSelection != true || titleSelection) } } + + public static func matchesNUPProgram(_ files: [GameFileItem], titleID: String) -> Bool { + guard let title = UInt64(titleID, radix: 16) else { return false } + return files.compactMap(\.nupProgram).allSatisfy { $0.isValid && $0.programID == title } + } + + /// Old NUP records describe program zero. Pin that program explicitly when a newer engine's + /// default could otherwise select the highest program of the same application. + public static func programIndex(for files: [GameFileItem], titleID: String, nupPrograms: Bool) -> Int? { + guard nupPrograms, !files.isEmpty, files.allSatisfy({ $0.layout == .container }), + Set(files.map(path)).count == 1, + let title = UInt64(titleID, radix: 16), matchesNUPProgram(files, titleID: titleID) else { return nil } + return Int(title & 0xFFF) + } private static func path(_ file: GameFileItem) -> String { file.url.resolvingSymlinksInPath().standardizedFileURL.path } diff --git a/Sources/NXLibraryCore/Models/SpotlightEntrance.swift b/Sources/NXLibraryCore/Models/SpotlightEntrance.swift new file mode 100644 index 00000000..5c7de7cb --- /dev/null +++ b/Sources/NXLibraryCore/Models/SpotlightEntrance.swift @@ -0,0 +1,131 @@ +import CoreGraphics + +/// Spotlight's entrance, the app's opening: a breath on the moving moonlight, then the game's background +/// fades in as when moving between games, only slower, while the tiles fly in from the row's centre and +/// grow, then the info rises; the top bar and the button hints come last. Nothing skips it. The shape is Selene's (`HomeNav.PlayIntro`) at a calmer pace. +/// Lengths in stage units, times in seconds. +public enum SpotlightEntrance { + /// How one tile comes in. A tile that only fades keeps its place and size. + public struct Flight: Equatable, Sendable { + public let delay: Double + public let fromX: CGFloat + public let fromY: CGFloat + public let fromScale: CGFloat + public let duration: Double + public let fadeDuration: Double + public let fadesOnly: Bool + + /// How long this piece runs from its delay: its move or its fade, whichever is longer. + public var length: Double { max(duration, fadeDuration) } + + /// How far it has moved (0 at the start, 1 in place) `time` seconds after its delay, on a cubic out. + public func move(at time: Double) -> CGFloat { + guard duration > 0 else { return 1 } + let rest = 1 - min(1, max(0, time / duration)) + return CGFloat(1 - rest * rest * rest) + } + + /// Its opacity `time` seconds after its delay, linear. + public func opacity(at time: Double) -> Double { + guard fadeDuration > 0 else { return 1 } + return min(1, max(0, time / fadeDuration)) + } + } + + /// The moving moonlight alone before anything else comes in. + public static let hold = 0.5 + /// The game's art fading in over the moonlight, on the crossfade's own curve (`OpacityFade`). + public static let backgroundDuration = 1.4 + public static let infoDelay = 1.3 + public static let infoFade = 0.7 + public static let infoLift: CGFloat = 40 + public static let infoLiftDuration = 0.8 + /// The title under the selected tile comes once the tiles are in. + public static let titleDelay = 2.0 + /// The top bar and the button hints come in last, together, once everything else has landed. + public static let controlsFade = 0.4 + /// A started flight lands by then whatever happens, so input is never held for long. + public static let longestWait = 5.0 + + /// The game's title and info: they fade in and rise 40 units once the background is up. + public static let info = Flight(delay: infoDelay, fromX: 0, fromY: infoLift, fromScale: 1, + duration: infoLiftDuration, fadeDuration: infoFade, fadesOnly: false) + + static let firstDelay = 0.6 + static let step = 0.06 + static let flightDuration = 0.9 + static let flightFade = 0.5 + static let lateFade = 0.4 + static let maxLate = 12 + + /// One entry per tile, from each tile's horizontal extent on the stage. Tiles left of the + /// stage stay as they are (`nil`); tiles past its right edge only fade, on the schedule of the + /// tiles that fly, and at most twelve of them. + public static func flights(tiles: [ClosedRange<CGFloat>], rowWidth: CGFloat) -> [Flight?] { + let center = rowWidth / 2 + var flown = 0 + var late = 0 + return tiles.map { tile in + guard tile.upperBound >= 0 else { return nil } + let delay = firstDelay + Double(flown) * step + if tile.lowerBound > rowWidth { + guard late < maxLate else { return nil } + late += 1 + return Flight(delay: delay, fromX: 0, fromY: 0, fromScale: 1, + duration: 0, fadeDuration: lateFade, fadesOnly: true) + } + flown += 1 + let tileCenter = (tile.lowerBound + tile.upperBound) / 2 + return Flight(delay: delay, fromX: (center - tileCenter) * 0.75, fromY: -18, fromScale: 0.35, + duration: flightDuration, fadeDuration: flightFade, fadesOnly: false) + } + } + + /// An empty tab's message comes in just after the last tile that flies (Selene's `RowEmptyIn`). + public static func message(after flights: [Flight?]) -> Flight { + let flown = flights.filter { $0.map { !$0.fadesOnly } ?? false }.count + return Flight(delay: firstDelay + Double(flown) * step + 0.25, fromX: 0, fromY: 0, fromScale: 1, + duration: 0, fadeDuration: lateFade, fadesOnly: true) + } + + /// When everything is in: the tiles, the info and an empty tab's message. + public static func end(of flights: [Flight?]) -> Double { + [duration(of: flights), info.delay + info.length, message(after: flights).delay + lateFade].max() ?? 0 + } + + /// When the last tile has landed (or finished fading). + public static func duration(of flights: [Flight?]) -> Double { + flights.compactMap { $0.map { $0.delay + max($0.duration, $0.fadeDuration) } }.max() ?? 0 + } + + /// Once per launch, only when the home opens on Spotlight, with Settings → Start-up → Entrance animation on + /// (`AppSettings.introAnimation`), never with Reduce motion. + public static func plays(isFirstHome: Bool, route: AppRoute, reduceMotion: Bool, enabled: Bool) -> Bool { + enabled && isFirstHome && route == .library && !reduceMotion + } + + /// Covered by the welcome or Setup, waiting for the visible covers, flying, or done. + public enum Phase: Equatable, Sendable { + case covered, waiting, playing, landed + + public mutating func uncover() { + if self == .covered { self = .waiting } + } + + public mutating func start() { + if self == .waiting { self = .playing } + } + + /// The end of the flight, Reduce motion, a resize or leaving: everything is in its place at once. + public mutating func land() { + self = .landed + } + + /// Row, info and background are held hidden until the flight starts. + public var holdsHidden: Bool { self == .covered || self == .waiting } + + /// Keys, clicks, the wheel and the controller reach Spotlight only once it has landed: the entrance + /// always plays to its end. + public var takesInput: Bool { self == .landed } + } +} diff --git a/Sources/NXLibraryCore/Models/SpotlightPage.swift b/Sources/NXLibraryCore/Models/SpotlightPage.swift index 5ead81d9..7418d8e6 100644 --- a/Sources/NXLibraryCore/Models/SpotlightPage.swift +++ b/Sources/NXLibraryCore/Models/SpotlightPage.swift @@ -42,8 +42,8 @@ public struct DescriptionExcerpt: Equatable, Sendable { } } -/// Where Spotlight's page rests for Build & Sources and More like this. Build & -/// Sources brings About this game up to `top`, More like this comes up to `top`, +/// Where Spotlight's page rests for Details and More like this. Details +/// brings About this game up to `top`, More like this comes up to `top`, /// but neither scrolls past the page's end resting `bottomInset` above the /// window's bottom; neither rises above the pills' shift (`first`). Positions /// are from the page's top, in points. diff --git a/Sources/NXLibraryCore/Models/SpotlightRow.swift b/Sources/NXLibraryCore/Models/SpotlightRow.swift index dd595a2a..fac05505 100644 --- a/Sources/NXLibraryCore/Models/SpotlightRow.swift +++ b/Sources/NXLibraryCore/Models/SpotlightRow.swift @@ -47,16 +47,14 @@ public enum SpotlightRow { /// ordered item that preceded it in the default sequence, or at the start /// when no ordered item preceded it. /// - /// `front` (the game being ported) becomes the first game: right after the Add - /// game card wherever it is, or in the first game's place without it. - public static func build(games: [PortedGame], - enabledCards: [SpotlightCard], - order: [String], - front: UUID? = nil) -> [SpotlightItem] { + /// `front` (the game being ported, then the games Steam downloads: `leaders`) become + /// the first games, in that order: right after the Add game card wherever it is, or + /// in the first game's place without it. + public static func build(gameIDs: [UUID], enabledCards: [SpotlightCard], order: [String], front: [UUID] = []) -> [SpotlightItem] { let enabled = Set(enabledCards) let defaults: [SpotlightItem] = SpotlightCard.allCases.filter(enabled.contains).map { .card($0) } - + games.map { .game($0.id) } + + gameIDs.map { .game($0) } var rank: [String: Int] = [:] for (i, key) in order.enumerated() where rank[key] == nil { rank[key] = i } @@ -82,16 +80,25 @@ public enum SpotlightRow { result.append(item) result.append(contentsOf: trailing[item.key] ?? []) } - if let front, let index = result.firstIndex(of: .game(front)) { - let item = result.remove(at: index) - let slot = result.firstIndex(of: .card(.addGame)).map { $0 + 1 } - ?? result.firstIndex { if case .game = $0 { return true } else { return false } } - ?? result.endIndex - result.insert(item, at: slot) - } + let leaders = front.map { SpotlightItem.game($0) }.filter(result.contains) + guard !leaders.isEmpty else { return result } + result.removeAll(where: leaders.contains) + let slot = result.firstIndex(of: .card(.addGame)).map { $0 + 1 } + ?? result.firstIndex { if case .game = $0 { return true } else { return false } } + ?? result.endIndex + result.insert(contentsOf: leaders, at: slot) return result } + /// The games that lead the row, as Nintendo's home leads with a game it is preparing: the + /// one being ported, then those Steam downloads (or has finished downloading) this session, + /// in the row's order. Only games in `row` lead. + public static func leaders(porting: UUID?, downloads: Set<UUID>, row: [UUID]) -> [UUID] { + let shown = Set(row) + let first = porting.flatMap { shown.contains($0) ? [$0] : nil } ?? [] + return first + row.filter { downloads.contains($0) && $0 != porting } + } + /// Folds a reordered *visible* subsequence (a filtered row) back into the /// full saved order. `fullOrder` is the unfiltered row's keys; the slots the /// visible keys occupy are refilled, in sequence, with `visibleOrder`, so @@ -108,6 +115,25 @@ public enum SpotlightRow { } } + /// Save a visible move without losing hidden/disabled games or cards. + /// `gameIDs` must include the whole catalog, not only its visible projection. + public static func saving(visibleOrder: [String], gameIDs: [UUID], previousOrder: [String]) -> [String] { + let full = build(gameIDs: gameIDs, enabledCards: SpotlightCard.allCases, order: previousOrder).map(\.key) + return merging(visibleOrder: visibleOrder, into: full) + } + + /// A game started: it becomes the first game of a saved order, which otherwise stays as it was + /// (cards keep their places). Without a saved order nothing is saved: the row already leads with + /// the most recently played game. + public static func playing(_ gameID: UUID, previousOrder: [String]) -> [String] { + guard !previousOrder.isEmpty else { return [] } + let key = SpotlightItem.game(gameID).key + var order = previousOrder.filter { $0 != key } + let firstGame = order.firstIndex { $0.hasPrefix("game:") } ?? order.endIndex + order.insert(key, at: firstGame) + return order + } + /// Moves `item` by `delta` positions, clamped to the row's ends. /// Returns `items` unchanged if the item is absent. public static func moving(_ item: SpotlightItem, by delta: Int, @@ -145,3 +171,21 @@ public enum Surprise { return candidates.randomElement(using: &random)?.id } } + +/// The Steam games seen downloading since NX Library started. They lead Spotlight's row +/// (`SpotlightRow.leaders`) until quit, also once Steam has finished them, as a ported +/// game does: the player finds the new game first, ready to play. +public struct SessionDownloads: Equatable { + public private(set) var ids: Set<UUID> = [] + + public init() {} + + /// Remembers the games downloading now. True when one is new. + @discardableResult + public mutating func note(_ games: [CatalogGame]) -> Bool { + let downloading = games.filter { $0.steamGame?.isDownloading == true }.map(\.id) + let before = ids.count + ids.formUnion(downloading) + return ids.count != before + } +} diff --git a/Sources/NXLibraryCore/Models/SpotlightState.swift b/Sources/NXLibraryCore/Models/SpotlightState.swift index 74b8d057..0d7717ec 100644 --- a/Sources/NXLibraryCore/Models/SpotlightState.swift +++ b/Sources/NXLibraryCore/Models/SpotlightState.swift @@ -1,12 +1,12 @@ import Foundation /// Where controller focus sits on Spotlight. Below the pills the screen is one -/// page that scrolls up: screenshots, About this game beside Build & Sources, More like this. +/// page that scrolls up: screenshots, About this game beside Details, More like this. public enum SpotlightFocusArea: Hashable { case row, pills, strip - /// About this game's Read more, left of Build & Sources. + /// About this game's Read more, left of Details. case about - /// Build & Sources' actions, `SpotlightState.actionColumns` to a row. + /// The Details links, `SpotlightState.actionColumns` to a row. case actions /// More like this. case more @@ -16,6 +16,9 @@ public enum SpotlightFocusArea: Hashable { case topGames /// The Mods card's store, below the card; `ModStoreFocus` moves inside it. case store + /// A Steam game's achievements card, at the top of the column right of About this game, above the + /// source's panel. + case achievements } /// A tile lifted off the row to be moved. `order` is the working order (item @@ -33,7 +36,7 @@ public struct SpotlightState: Equatable { public static let anchorSlot = 2 /// Play, Options, Favorite. public static let pillCount = 3 - /// Build & Sources lays its actions out as small buttons, three to a row. + /// The Details links are small buttons, three to a row. public static let actionColumns = 3 public var selectedKey: String? @@ -151,12 +154,13 @@ public struct SpotlightState: Equatable { modsIndex = 0 } - /// Down: row → pills (games only) → strip → Build & Sources (row by row) → Mods (row by row) → - /// More like this, skipping whatever is empty. + /// Down: row → pills (games only) → strip → Achievements (when shown) → Details (row by row) → + /// Mods (row by row) → More like this, skipping whatever is empty. @discardableResult public mutating func moveDown(selectedIsGame: Bool, screenshotCount: Int, selectedIsActivity: Bool = false, topGameCount: Int = 0, - actionCount: Int = 0, moreCount: Int = 0, modsCount: Int = 0) -> Bool { + actionCount: Int = 0, moreCount: Int = 0, modsCount: Int = 0, + hasAchievements: Bool = false) -> Bool { switch focus { case .row: if selectedIsActivity { @@ -176,8 +180,12 @@ public struct SpotlightState: Equatable { stripIndex = min(stripIndex, screenshotCount - 1) return true } + if hasAchievements { focus = .achievements; return true } return enterActions(actionCount: actionCount, moreCount: moreCount, modsCount: modsCount) case .strip: + if hasAchievements { focus = .achievements; return true } + return enterActions(actionCount: actionCount, moreCount: moreCount, modsCount: modsCount) + case .achievements: return enterActions(actionCount: actionCount, moreCount: moreCount, modsCount: modsCount) case .actions: if let below = Self.actionBelow(actionIndex, count: actionCount) { @@ -227,16 +235,21 @@ public struct SpotlightState: Equatable { return true } - /// Up: More like this → Mods (row by row) → Build & Sources (row by row) → strip → pills → row. + /// Up: More like this → Mods (row by row) → Details (row by row) → Achievements (when shown) → + /// strip → pills → row. @discardableResult - public mutating func moveUp(screenshotCount: Int = 1, actionCount: Int = 0, modsCount: Int = 0) -> Bool { - let aboveActions: SpotlightFocusArea = screenshotCount > 0 ? .strip : .pills + public mutating func moveUp(screenshotCount: Int = 1, actionCount: Int = 0, modsCount: Int = 0, + hasAchievements: Bool = false) -> Bool { + let aboveTiles: SpotlightFocusArea = screenshotCount > 0 ? .strip : .pills + let aboveActions: SpotlightFocusArea = hasAchievements ? .achievements : aboveTiles switch focus { case .row: return false case .pills, .topGames, .store: focus = .row case .strip: focus = .pills + case .achievements: focus = aboveTiles case .about: - focus = aboveActions + // The card sits beside About, not above it. + focus = aboveTiles case .actions: if actionIndex >= Self.actionColumns { actionIndex -= Self.actionColumns @@ -261,7 +274,7 @@ public struct SpotlightState: Equatable { return true } - /// Up into Build & Sources lands on its last row's first action. + /// Up into the Details links lands on its last row's first link. private mutating func enterLastActionRow(actionCount: Int, otherwise: SpotlightFocusArea) { guard actionCount > 0 else { focus = otherwise @@ -271,19 +284,28 @@ public struct SpotlightState: Equatable { actionIndex = ((actionCount - 1) / Self.actionColumns) * Self.actionColumns } - /// Left/Right inside the pills, the strip, Build & Sources or More like this. - /// Left of Build & Sources' first column is Read more, when `readMore`. + /// Left/Right inside the pills, the strip, Details or More like this. + /// Left of the Details links' first column, and of the achievements card, is Read more, when `readMore`. @discardableResult public mutating func moveSideways(by delta: Int, screenshotCount: Int, topGameCount: Int = 0, actionCount: Int = 0, moreCount: Int = 0, readMore: Bool = false, - modsCount: Int = 0) -> Bool { + modsCount: Int = 0, hasAchievements: Bool = false) -> Bool { switch focus { + case .achievements: + guard delta < 0, readMore else { return false } + focus = .about + return true case .mods: guard let next = ModsBandLayout.beside(modsIndex, by: delta, count: modsCount) else { return false } modsIndex = next return true case .about: - guard delta > 0, actionCount > 0 else { return false } + guard delta > 0 else { return false } + if hasAchievements { + focus = .achievements + return true + } + guard actionCount > 0 else { return false } focus = .actions actionIndex -= actionIndex % Self.actionColumns return true diff --git a/Sources/NXLibraryCore/Models/SteamReturnFocus.swift b/Sources/NXLibraryCore/Models/SteamReturnFocus.swift new file mode 100644 index 00000000..00400ba7 --- /dev/null +++ b/Sources/NXLibraryCore/Models/SteamReturnFocus.swift @@ -0,0 +1,39 @@ +import Foundation + +/// Whether NX Library comes back to the front when a Steam game quits: the rule of `GameFocus` (the game was the +/// app in front and no other library game is open), and only for a Play pressed in NX Library. A game started +/// from Steam leaves the player in Steam. Each Play counts for one session. +public struct SteamReturnFocus: Equatable, Sendable { + private var playedHere: Set<UUID> = [] + private var inFront: UUID? + + public init() {} + + public mutating func playPressed(_ gameID: UUID) { playedHere.insert(gameID) } + + /// Play was cancelled or failed before the game ran. + public mutating func playAbandoned(_ gameID: UUID) { playedHere.remove(gameID) } + + public mutating func gameCameForward(_ gameID: UUID) { inFront = gameID } + + /// Another app stayed in front while this game kept running: the player left the game. + public mutating func otherAppStayedForward(whileRunning gameID: UUID) { + if inFront == gameID { inFront = nil } + } + + public var gameInFront: UUID? { inFront } + + /// The game quit. True when NX Library should come forward. + /// What a game's quit means: whether NX Library comes back, and whether the player was still in the game. + public struct Ending: Equatable, Sendable { + public let returnsToLibrary: Bool + public let wasInFront: Bool + } + + public mutating func gameEnded(_ gameID: UUID, othersRunning: Bool) -> Ending { + let wasInFront = inFront == gameID + if wasInFront { inFront = nil } + let playedHere = playedHere.remove(gameID) != nil + return Ending(returnsToLibrary: playedHere && wasInFront && !othersRunning, wasInFront: wasInFront) + } +} diff --git a/Sources/NXLibraryCore/Models/ThemePicker.swift b/Sources/NXLibraryCore/Models/ThemePicker.swift index 2109f9a7..b81d2367 100644 --- a/Sources/NXLibraryCore/Models/ThemePicker.swift +++ b/Sources/NXLibraryCore/Models/ThemePicker.swift @@ -61,7 +61,8 @@ public struct ThemePickerState: Equatable { public mutating func move(_ direction: GridDirection, count: Int) -> Bool { switch step { case .theme: - guard let next = GridNavigation.move(themeIndex, direction, count: count, columns: Self.themeColumns) else { return false } + guard let next = GridNavigation.move(themeIndex, direction, count: count, + columns: Self.themeColumns) else { return false } themeIndex = next case .background: guard let next = GridNavigation.move(backgroundIndex, direction, count: count, diff --git a/Sources/NXLibraryCore/Models/TileMotion.swift b/Sources/NXLibraryCore/Models/TileMotion.swift index 9cf1e767..6c85546f 100644 --- a/Sources/NXLibraryCore/Models/TileMotion.swift +++ b/Sources/NXLibraryCore/Models/TileMotion.swift @@ -5,6 +5,16 @@ import Foundation /// Played by Core Animation, the loops cost the app nothing between frames; redrawn by SwiftUI at the screen's /// rate, they kept a quarter of a core busy on a still screen. public enum TileMotion { + /// A downloading game's mark pulses once in this time (1.4 s each way): slow, like the ring's glow. + public static let downloadPeriod: Double = 2.8 + + /// The download mark's own brightness: dim, then full, sine in-out. Its colour never changes, only how much shows. + public static func downloadMarkOpacity(at t: Double) -> Double { + let p = t.truncatingRemainder(dividingBy: downloadPeriod) / (downloadPeriod / 2) + let tri = p <= 1 ? p : 2 - p + return 0.4 + 0.6 * (0.5 - 0.5 * cos(.pi * tri)) + } + /// The ring's gradient turns once in this time. public static let ringPeriod: Double = 5 /// The glow rises and falls once in this time (1.8 s each way). diff --git a/Sources/NXLibraryCore/Models/ToolchainGateCopy.swift b/Sources/NXLibraryCore/Models/ToolchainGateCopy.swift index c0ffde10..cb1cb6f8 100644 --- a/Sources/NXLibraryCore/Models/ToolchainGateCopy.swift +++ b/Sources/NXLibraryCore/Models/ToolchainGateCopy.swift @@ -1,6 +1,6 @@ import Foundation -/// What the compatibility gate says (Settings → Engine, the Rebuild hints). A Metal compiler newer than the certified +/// What the compatibility gate says (Settings → Setup and engine, the Rebuild hints). A Metal compiler newer than the certified /// one is information, an older one a warning; both still need the untested-toolchain override to build (AGENTS.md). /// Any other failed check stays "Blocked". public enum ToolchainGateCopy { @@ -46,20 +46,20 @@ public enum ToolchainGateCopy { return Summary(label: overrideOn ? L10n.text("Newer Metal · override on") : L10n.text("Newer Metal"), tone: .info, message: head + (overrideOn ? L10n.text(" There should be no problems; builds are recorded as untested.") : L10n.text(" There should be no problems: turn on Untested toolchain override to build.")), - buildHint: L10n.text("Newer Metal: turn on the override in Settings → Engine")) + buildHint: L10n.text("Newer Metal: turn on the override in Settings → Setup and engine")) case .older(let installed, let required): let head = L10n.format("Your Metal compiler (%@) is older than the one nxnative needs (%@). ", [String(describing: (installed)), String(describing: (required))]) + L10n.format("Updating to Metal %@ is strongly recommended.", [String(describing: (required))]) return Summary(label: overrideOn ? L10n.text("Older Metal · override on") : L10n.text("Update recommended"), tone: .warning, message: head + (overrideOn ? L10n.text(" Builds are recorded as untested.") : L10n.text(" Untested toolchain override builds anyway, at your own risk.")), - buildHint: L10n.text("Older Metal: update it, or use the override in Settings → Engine")) + buildHint: L10n.text("Older Metal: update it, or use the override in Settings → Setup and engine")) case .same, .unknown: break } } return overrideOn ? Summary(label: L10n.text("Override enabled"), tone: .override, message: nil, buildHint: "") - : Summary(label: L10n.text("Blocked"), tone: .blocked, message: nil, buildHint: L10n.text("Build blocked — Settings → Engine")) + : Summary(label: L10n.text("Blocked"), tone: .blocked, message: nil, buildHint: L10n.text("Build blocked — Settings → Setup and engine")) } } diff --git a/Sources/NXLibraryCore/Models/UpstreamCopy.swift b/Sources/NXLibraryCore/Models/UpstreamCopy.swift index b7f58722..d8db8e47 100644 --- a/Sources/NXLibraryCore/Models/UpstreamCopy.swift +++ b/Sources/NXLibraryCore/Models/UpstreamCopy.swift @@ -1,10 +1,10 @@ import Foundation -/// Settings → Engine's Upstream row. Newer upstream commits are information: they reach players with NX Library +/// Settings → Setup and engine's Upstream row. Newer upstream commits are information: they reach players with NX Library /// updates, once tested. The Newest engine row is the only way to use them earlier, by the player's own choice. public enum UpstreamCopy { public static func subtitle(upToDate: Bool, newCommits: Int) -> String { - if upToDate { return L10n.text("This NX Library uses the newest nxnative.") } - return L10n.count("nxnative has %lld newer commits. Engine updates reach you with NX Library updates, once tested.", newCommits, arguments: []) + if upToDate { return L10n.text("This version of Arcane uses the newest nxnative.") } + return L10n.count("nxnative has %lld newer commits. Engine updates reach you with Arcane updates, once tested.", newCommits, arguments: []) } } diff --git a/Sources/NXLibraryCore/Navigation/AppRouter.swift b/Sources/NXLibraryCore/Navigation/AppRouter.swift index d1fcdfe4..8b862f41 100644 --- a/Sources/NXLibraryCore/Navigation/AppRouter.swift +++ b/Sources/NXLibraryCore/Navigation/AppRouter.swift @@ -15,13 +15,33 @@ public enum AppRoute: Equatable { public var isOverlay: Bool { self == .addGame || self == .console } } +/// A full-screen page covers lower UI layers while their shared background stays mounted. +public enum ShellBackdropCover: Equatable { + case none, themePicker, welcome, setup + + public var priority: Double { + switch self { + case .none: return 0 + case .themePicker: return 1 + case .welcome: return 2.4 + case .setup: return 2.5 + } + } + + public func covers(_ layer: Double) -> Bool { priority > layer } + + public static func resolve(setup: Bool, welcome: Bool, themePicker: Bool) -> Self { + if setup { return .setup } + if welcome { return .welcome } + return themePicker ? .themePicker : .none + } +} + public final class AppRouter: ObservableObject { @Published public private(set) var route: AppRoute = .library @Published public private(set) var isReturningFromBack = false @Published public var isMenuPresented = false @Published public var isSearchPresented = false - /// The cold-launch intro is on screen; screens ignore input until it ends. - @Published public var isIntroShowing = false /// True while the full-screen screenshot viewer is open; the shell ignores its global shortcuts. @Published public var isScreenshotViewerOpen = false @Published public var menuSelection = MenuSelectionModel() diff --git a/Sources/NXLibraryCore/Resources/Localizable.xcstrings b/Sources/NXLibraryCore/Resources/Localizable.xcstrings index de61c48d..8f1a10ce 100644 --- a/Sources/NXLibraryCore/Resources/Localizable.xcstrings +++ b/Sources/NXLibraryCore/Resources/Localizable.xcstrings @@ -1,6 +1,211 @@ { "sourceLanguage": "en", "strings": { + "A free, open-source game library and launcher for Mac. Play installed games and port compatible Switch titles with nxnative.": { + "comment": "SettingsAboutSection.swift", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Eine kostenlose Open-Source-Spielebibliothek mit Launcher für den Mac. Starte installierte Spiele und portiere kompatible Switch-Titel mit nxnative." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "A free, open-source game library and launcher for Mac. Play installed games and port compatible Switch titles with nxnative." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Una biblioteca y un lanzador de juegos gratuitos y de código abierto para Mac. Juega a tus juegos instalados y adapta títulos compatibles de Switch con nxnative." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Une bibliothèque et un lanceur de jeux gratuits et open source pour Mac. Lancez vos jeux installés et portez les titres Switch compatibles avec nxnative." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Una libreria e un launcher di giochi per Mac, gratuiti e open source. Avvia i giochi installati e converti i titoli Switch compatibili con nxnative." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Uma biblioteca e um inicializador de jogos gratuitos e de código aberto para Mac. Abra os jogos instalados e porte títulos compatíveis de Switch com nxnative." + } + } + } + }, + "All achievements": { + "comment": "Achievements card on a game's page, under the tier's name when every achievement is unlocked.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "All achievements" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Tutti gli obiettivi" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Tous les succès" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Alle Erfolge" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Todos los logros" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Todas as conquistas" + } + } + } + }, + "%@, every achievement unlocked": { + "comment": "VoiceOver label of the earned Arcane on the Achievements screen; %@ is the tier's name (Arcane).", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@, every achievement unlocked" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%@, tutti gli obiettivi sbloccati" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@, tous les succès débloqués" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@, alle Erfolge freigeschaltet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%@, todos los logros desbloqueados" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%@, todas as conquistas desbloqueadas" + } + } + } + }, + "Applied before each game starts, including Off. Custom save-sync overrides are reported in Saves. Cloud sync covers only the primary user and device save.": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Applied before each game starts, including Off. Custom save-sync overrides are reported in Saves. Cloud sync covers only the primary user and device save." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Applicato prima di ogni avvio, anche se disattivato. Le impostazioni personalizzate che prevalgono sulla sincronizzazione dei salvataggi sono indicate in Salvataggi. Il cloud sincronizza solo i salvataggi dell’utente principale e del dispositivo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Appliqué avant chaque démarrage de jeu, y compris Désactivé. Les réglages personnalisés de synchronisation des sauvegardes sont signalés dans Sauvegardes. Le cloud ne synchronise que les sauvegardes de l’utilisateur principal et de l’appareil." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Wird vor jedem Spielstart angewendet, auch „Aus“. Eigene Überschreibungen der Spielstandsynchronisierung werden unter „Spielstände“ angezeigt. Die Cloud synchronisiert nur den Spielstand des Hauptbenutzers und den Gerätespielstand." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Se aplica antes de iniciar cada juego, también al desactivarlo. Las personalizaciones de sincronización de partidas se indican en Partidas guardadas. La nube solo sincroniza las partidas del usuario principal y del dispositivo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Aplicado antes de cada jogo iniciar, inclusive Desativado. Substituições personalizadas da sincronização são informadas em Dados salvos. A nuvem sincroniza apenas os salvamentos do usuário principal e do dispositivo." + } + } + } + }, + "Arcane": { + "comment": "Achievement tier (a violet crystal) for unlocking every achievement of a game, where PlayStation has Platinum.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Arcane" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Arcano" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Arcane" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Arkan" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Arcano" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Arcano" + } + } + } + }, "\n\n--- Build log: %@ ---\n": { "comment": "ConsoleView.swift:481", "localizations": { @@ -739,6 +944,129 @@ } } }, + "%1$@, %2$d of %3$d": { + "comment": "VoiceOver: a tier crystal's count, e.g. \"Radiant, 4 of 6\".", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%1$@, %2$d of %3$d" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%1$@, %2$d su %3$d" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%1$@, %2$d sur %3$d" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%1$@, %2$d von %3$d" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%1$@, %2$d de %3$d" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%1$@, %2$d de %3$d" + } + } + } + }, + "%1$d of %2$d unlocked": { + "comment": "Achievements screen, under the tier crystals, before any unlock: e.g. \"0 of 50 unlocked\".", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%1$d of %2$d unlocked" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%1$d su %2$d sbloccati" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%1$d sur %2$d débloqués" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%1$d von %2$d freigeschaltet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%1$d de %2$d desbloqueados" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%1$d de %2$d desbloqueadas" + } + } + } + }, + "%1$d of %2$d unlocked · last on %3$@": { + "comment": "Achievements screen, under the tier crystals: count and date of the newest unlock, e.g. \"17 of 50 unlocked · last on 31 Jul 2026\".", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%1$d of %2$d unlocked · last on %3$@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%1$d su %2$d sbloccati · l’ultimo il %3$@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%1$d sur %2$d débloqués · le dernier le %3$@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%1$d von %2$d freigeschaltet · zuletzt am %3$@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%1$d de %2$d desbloqueados · el último el %3$@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%1$d de %2$d desbloqueadas · a última em %3$@" + } + } + } + }, "%@ (recommended)": { "comment": "ModDetailPanel.swift:297", "localizations": { @@ -1313,43 +1641,43 @@ } } }, - "%@ has changed files. NX Library never touches them: put them aside, then check again.": { + "%@ has changed files. Arcane never touches them: put them aside, then check again.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "%@ has changed files. NX Library never touches them: put them aside, then check again." + "value": "%@ has changed files. Arcane never touches them: put them aside, then check again." } }, "it": { "stringUnit": { "state": "translated", - "value": "%@ contiene file modificati. NX Library non li tocca mai: mettili da parte, poi ricontrolla." + "value": "%@ contiene file modificati. Arcane non li tocca mai: mettili da parte, poi ricontrolla." } }, "fr": { "stringUnit": { "state": "translated", - "value": "%@ contient des fichiers modifiés. NX Library n’y touche jamais : mettez-les de côté, puis vérifiez à nouveau." + "value": "%@ contient des fichiers modifiés. Arcane n’y touche jamais : mettez-les de côté, puis vérifiez à nouveau." } }, "de": { "stringUnit": { "state": "translated", - "value": "%@ enthält geänderte Dateien. NX Library verändert sie niemals: Lege sie beiseite und prüfe erneut." + "value": "%@ enthält geänderte Dateien. Arcane verändert sie niemals: Lege sie beiseite und prüfe erneut." } }, "es": { "stringUnit": { "state": "translated", - "value": "%@ contiene archivos modificados. NX Library nunca los modifica: apártalos y vuelve a comprobar." + "value": "%@ contiene archivos modificados. Arcane nunca los modifica: apártalos y vuelve a comprobar." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "%@ tem arquivos alterados. O NX Library nunca os modifica: guarde-os em outro local e verifique novamente." + "value": "%@ tem arquivos alterados. O Arcane nunca os modifica: guarde-os em outro local e verifique novamente." } } } @@ -2461,6 +2789,47 @@ } } }, + "%@ of players": { + "comment": "Achievement detail: how many Steam players have it, e.g. \"4.5% of players\".", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ of players" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%@ dei giocatori" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ des joueurs" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ der Spieler" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%@ de los jugadores" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%@ dos jogadores" + } + } + } + }, "%@ of the tested %@.": { "comment": "SettingsEngineSection.swift:320", "localizations": { @@ -2953,43 +3322,43 @@ } } }, - "%@. Reinstall NX Library from its DMG.": { + "%@. Reinstall Arcane from its DMG.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "%@. Reinstall NX Library from its DMG." + "value": "%@. Reinstall Arcane from its DMG." } }, "it": { "stringUnit": { "state": "translated", - "value": "%@. Reinstalla NX Library dal suo DMG." + "value": "%@. Reinstalla Arcane dal suo DMG." } }, "fr": { "stringUnit": { "state": "translated", - "value": "%@. Réinstallez NX Library depuis son DMG." + "value": "%@. Réinstallez Arcane depuis son DMG." } }, "de": { "stringUnit": { "state": "translated", - "value": "%@. Installiere NX Library erneut aus der DMG-Datei." + "value": "%@. Installiere Arcane erneut aus der DMG-Datei." } }, "es": { "stringUnit": { "state": "translated", - "value": "%@. Reinstala NX Library desde su DMG." + "value": "%@. Reinstala Arcane desde su DMG." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "%@. Reinstale o NX Library a partir do DMG." + "value": "%@. Reinstale o Arcane a partir do DMG." } } } @@ -3240,6 +3609,273 @@ } } }, + "%d%% complete": { + "comment": "Share of a game's achievements unlocked.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%d%% complete" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Completato al %d%%" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Terminé à %d %%" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%d %% abgeschlossen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%d %% completado" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%d%% concluído" + } + } + } + }, + "%lld Steam games need review": { + "comment": "Steam source discovery count.", + "localizations": { + "en": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam game needs review" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam games need review" + } + } + } + } + }, + "it": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld gioco Steam da controllare" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld giochi Steam da controllare" + } + } + } + } + }, + "fr": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld jeu Steam à vérifier" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld jeux Steam à vérifier" + } + } + } + } + }, + "de": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam-Spiel muss geprüft werden" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam-Spiele müssen geprüft werden" + } + } + } + } + }, + "es": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld juego de Steam requiere revisión" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld juegos de Steam requieren revisión" + } + } + } + } + }, + "pt-BR": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld jogo Steam requer revisão" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld jogos Steam requerem revisão" + } + } + } + } + } + } + }, + "%lld Steam installations found": { + "comment": "Steam source discovery count.", + "localizations": { + "en": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam installation found" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam installations found" + } + } + } + } + }, + "it": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld installazione Steam trovata" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld installazioni Steam trovate" + } + } + } + } + }, + "fr": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld installation Steam trouvée" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld installations Steam trouvées" + } + } + } + } + }, + "de": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam-Installation gefunden" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam-Installationen gefunden" + } + } + } + } + }, + "es": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld instalación de Steam encontrada" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld instalaciones de Steam encontradas" + } + } + } + } + }, + "pt-BR": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld instalação Steam encontrada" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld instalações Steam encontradas" + } + } + } + } + } + } + }, "%lld commits ahead": { "comment": "Quantity-sensitive UI message; preserve %lld count and other placeholders.", "localizations": { @@ -4849,84 +5485,43 @@ } } }, - "A notification when a porting finishes while NX Library is in the background.": { + "A notification when a porting finishes while Arcane is in the background.": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "A notification when a porting finishes while NX Library is in the background." + "value": "A notification when a porting finishes while Arcane is in the background." } }, "it": { "stringUnit": { "state": "translated", - "value": "Una notifica quando la creazione dell’app per Mac termina mentre NX Library è in background." + "value": "Una notifica quando la creazione dell’app per Mac termina mentre Arcane è in background." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Une notification quand la création d’une app Mac se termine alors que NX Library est en arrière-plan." + "value": "Une notification quand la création d’une app Mac se termine alors qu’Arcane est en arrière-plan." } }, "de": { "stringUnit": { "state": "translated", - "value": "Eine Mitteilung, wenn die App-Erstellung endet, während NX Library im Hintergrund ist." + "value": "Eine Mitteilung, wenn die App-Erstellung endet, während Arcane im Hintergrund ist." } }, "es": { "stringUnit": { "state": "translated", - "value": "Envía una notificación cuando termina una compilación mientras NX Library está en segundo plano." + "value": "Envía una notificación cuando termina una compilación mientras Arcane está en segundo plano." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Uma notificação quando uma compilação terminar enquanto o NX Library estiver em segundo plano." - } - } - } - }, - "A personal macOS front-end for building and launching your own Switch games with nxnative.": { - "comment": "SettingsAboutSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "A personal macOS front-end for building and launching your own Switch games with nxnative." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Un’interfaccia personale per macOS per creare e avviare i tuoi giochi Switch con nxnative." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Une interface macOS personnelle pour compiler et lancer vos propres jeux Switch avec nxnative." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Eine persönliche macOS-Oberfläche zum Erstellen und Starten deiner eigenen Switch-Spiele als Apps mit nxnative." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Una interfaz personal para macOS que permite compilar y ejecutar tus propios juegos de Switch con nxnative." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Uma interface pessoal para macOS que compila e executa seus próprios jogos de Switch com o nxnative." + "value": "Uma notificação quando uma compilação terminar enquanto o Arcane estiver em segundo plano." } } } @@ -5341,6 +5936,88 @@ } } }, + "Achievements": { + "comment": "Title of a Steam game's Achievements screen.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Achievements" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Obiettivi" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Succès" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erfolge" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Logros" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Conquistas" + } + } + } + }, + "Achievements: %d of %d": { + "comment": "Accessibility label of the achievements tile: unlocked of total.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Achievements: %d of %d" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Obiettivi: %d su %d" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Succès : %d sur %d" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erfolge: %d von %d" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Logros: %d de %d" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Conquistas: %d de %d" + } + } + } + }, "Activity": { "comment": "SpotlightCardInfoView.swift:50", "localizations": { @@ -7022,6 +7699,47 @@ } } }, + "Another version changed your previous library. Both versions have been kept. Close the other copy and review the library folder.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Another version changed your previous library. Both versions have been kept. Close the other copy and review the library folder." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Un’altra versione ha modificato la libreria precedente. Entrambe le versioni sono state conservate. Chiudi l’altra copia e controlla la cartella della libreria." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Une autre version a modifié votre ancienne bibliothèque. Les deux versions ont été conservées. Fermez l’autre copie et examinez le dossier de la bibliothèque." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Eine andere Version hat deine bisherige Bibliothek geändert. Beide Versionen wurden aufbewahrt. Schließe die andere Kopie und prüfe den Bibliotheksordner." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Otra versión ha modificado tu biblioteca anterior. Se han conservado ambas versiones. Cierra la otra copia y revisa la carpeta de la biblioteca." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Outra versão alterou sua biblioteca anterior. Ambas as versões foram preservadas. Feche a outra cópia e verifique a pasta da biblioteca." + } + } + } + }, "App": { "comment": "AddGameView+Rows.swift", "localizations": { @@ -7514,125 +8232,124 @@ } } }, - "Applied before each game starts, including Off. Reset group keeps cloud sync and its folder. Custom save-sync overrides are reported in Saves.": { - "comment": "SettingsGamesSection.swift", + "Applies at the next launch.": { + "comment": "SettingsStartUpSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Applied before each game starts, including Off. Reset group keeps cloud sync and its folder. Custom save-sync overrides are reported in Saves." + "value": "Applies at the next launch." } }, "it": { "stringUnit": { "state": "translated", - "value": "Applicato prima di ogni avvio, anche se disattivato. Reimposta gruppo conserva la sincronizzazione cloud e la relativa cartella. Le impostazioni personalizzate che prevalgono sulla sincronizzazione dei salvataggi sono indicate in Salvataggi." + "value": "Si applica al prossimo avvio." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Appliqué avant chaque démarrage de jeu, y compris Désactivé. Réinitialiser le groupe conserve la synchronisation cloud et son dossier. Les réglages personnalisés de synchronisation des sauvegardes sont signalés dans Sauvegardes." + "value": "S’applique au prochain lancement." } }, "de": { "stringUnit": { "state": "translated", - "value": "Wird vor jedem Spielstart angewendet, auch „Aus“. „Gruppe zurücksetzen“ behält die Cloud-Synchronisierung und ihren Ordner bei. Eigene Überschreibungen der Spielstandsynchronisierung werden unter „Spielstände“ angezeigt." + "value": "Gilt beim nächsten Start." } }, "es": { "stringUnit": { "state": "translated", - "value": "Se aplica antes de iniciar cada juego, también al desactivarlo. Restablecer el grupo conserva la sincronización en la nube y su carpeta. Las personalizaciones de sincronización de partidas se indican en Partidas guardadas." + "value": "Se aplica en el próximo inicio." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Aplicado antes de cada jogo iniciar, inclusive Desativado. Redefinir o grupo mantém a sincronização na nuvem e sua pasta. Substituições personalizadas da sincronização são informadas em Dados salvos." + "value": "Aplicado na próxima abertura." } } } }, - "Applies at the next launch.": { - "comment": "SettingsStartUpSection.swift", + "Apps, build caches and logs for each game, including hidden games.": { + "comment": "SettingsStorageSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Applies at the next launch." + "value": "Apps, build caches and logs for each game, including hidden games." } }, "it": { "stringUnit": { "state": "translated", - "value": "Si applica al prossimo avvio." + "value": "App, cache di compilazione e log di ogni gioco, inclusi quelli nascosti." } }, "fr": { "stringUnit": { "state": "translated", - "value": "S’applique au prochain lancement." + "value": "Apps, caches de compilation et journaux de chaque jeu, y compris les jeux masqués." } }, "de": { "stringUnit": { "state": "translated", - "value": "Gilt beim nächsten Start." + "value": "Apps, Build-Caches und Protokolle pro Spiel, einschließlich ausgeblendeter Spiele." } }, "es": { "stringUnit": { "state": "translated", - "value": "Se aplica en el próximo inicio." + "value": "Apps, cachés de compilación y registros de cada juego, incluidos los ocultos." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Aplicado na próxima abertura." + "value": "Apps, caches de compilação e logs de cada jogo, incluindo jogos ocultos." } } } }, - "Apps, build caches and logs for each game, including hidden games.": { - "comment": "SettingsStorageSection.swift", + "Arcane reads Steam and your Game apps folder without changing anything. You can open the library now and add sources later in Settings.": { "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Apps, build caches and logs for each game, including hidden games." + "value": "Arcane reads Steam and your Game apps folder without changing anything. You can open the library now and add sources later in Settings." } }, "it": { "stringUnit": { "state": "translated", - "value": "App, cache di compilazione e log di ogni gioco, inclusi quelli nascosti." + "value": "Arcane legge Steam e la cartella delle app dei giochi senza cambiare nulla. Puoi aprire subito la libreria e aggiungere le fonti dopo, dalle Impostazioni." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Apps, caches de compilation et journaux de chaque jeu, y compris les jeux masqués." + "value": "Arcane lit Steam et le dossier des apps de jeux sans rien modifier. Vous pouvez ouvrir la bibliothèque maintenant et ajouter les sources plus tard dans les réglages." } }, "de": { "stringUnit": { "state": "translated", - "value": "Apps, Build-Caches und Protokolle pro Spiel, einschließlich ausgeblendeter Spiele." + "value": "Arcane liest Steam und den Spiele-App-Ordner, ohne etwas zu ändern. Du kannst die Mediathek jetzt öffnen und Quellen später in den Einstellungen hinzufügen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Apps, cachés de compilación y registros de cada juego, incluidos los ocultos." + "value": "Arcane lee Steam y la carpeta de apps de juegos sin cambiar nada. Puedes abrir la biblioteca ahora y añadir las fuentes más tarde en Ajustes." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Apps, caches de compilação e logs de cada jogo, incluindo jogos ocultos." + "value": "O Arcane lê o Steam e a pasta de apps de jogos sem alterar nada. Você pode abrir a biblioteca agora e adicionar as fontes depois, nos Ajustes." } } } @@ -7965,6 +8682,47 @@ } } }, + "Artwork, metadata and the store page.": { + "comment": "CatalogGameOptions.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Artwork, metadata and the store page." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Immagini, metadati e pagina dello store." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Illustrations, métadonnées et page du magasin." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bilder, Metadaten und Store-Seite." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Imágenes, metadatos y página de la tienda." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Imagens, metadados e página da loja." + } + } + } + }, "Artwork, metadata, store page, sources and the build log.": { "comment": "GameOptionsPresentation.swift", "localizations": { @@ -8170,47 +8928,6 @@ } } }, - "At %@, %@ of the tested %@, chosen in Settings → Engine.": { - "comment": "NewestEngine.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "At %@, %@ of the tested %@, chosen in Settings → Engine." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Al commit %@, %@ rispetto al commit testato %@, scelto in Impostazioni → Motore." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Au commit %@, %@ par rapport au commit testé %@, choisi dans Réglages → Moteur." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Stand %@, %@ (getestet: %@), gewählt unter Einstellungen → Engine." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "En %@, %@ de la versión probada %@, elegido en Ajustes → Motor." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Em %@, %@ em relação à versão testada %@, escolhido em Ajustes → Engine." - } - } - } - }, "Attach sources…": { "comment": "GameOptionsPresentation.swift", "localizations": { @@ -8744,6 +9461,47 @@ } } }, + "Back up all local users and the device save.": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Back up all local users and the device save." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Salva una copia di tutti gli utenti locali e del salvataggio del dispositivo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Sauvegardez tous les utilisateurs locaux et la sauvegarde de l’appareil." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Sichere alle lokalen Benutzer und den Gerätespielstand." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Crea una copia de todos los usuarios locales y de la partida del dispositivo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Faça backup de todos os usuários locais e do salvamento do dispositivo." + } + } + } + }, "Back up now": { "comment": "SavesPanel.swift", "localizations": { @@ -9318,47 +10076,6 @@ } } }, - "Blocked by the Metal gate. See Settings → Engine.": { - "comment": "GameOptionsPresentation.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Blocked by the Metal gate. See Settings → Engine." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Bloccato dal controllo Metal. Vedi Impostazioni → Motore." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Bloqué par le contrôle Metal. Consultez Réglages → Moteur." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Durch die Metal-Prüfung gesperrt. Siehe Einstellungen → Engine." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Bloqueado por el control de Metal. Consulta Ajustes → Motor." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Bloqueado pela verificação do Metal. Veja Ajustes → Engine." - } - } - } - }, "Box covers": { "comment": "SettingsCatalog.swift", "localizations": { @@ -9564,6 +10281,47 @@ } } }, + "Bronze": { + "comment": "Achievement tier (a crystal), as PlayStation trophy tiers.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Bronze" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Bronzo" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Bronze" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bronze" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Bronce" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Bronze" + } + } + } + }, "Browse": { "comment": "SpotlightView.swift", "localizations": { @@ -9810,47 +10568,6 @@ } } }, - "Build & Sources": { - "comment": "BuildSourcesPanel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Build & Sources" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Compilazione e sorgenti" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Compilation et sources" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Build & Quellen" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Compilación y archivos de origen" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Compilação e arquivos de origem" - } - } - } - }, "Build a game and it shows up here.": { "comment": "SpotlightRowView.swift:192", "localizations": { @@ -10138,47 +10855,6 @@ } } }, - "Build blocked — Settings → Engine": { - "comment": "ToolchainGateCopy.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Build blocked — Settings → Engine" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Compilazione bloccata — Impostazioni → Motore" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Compilation bloquée — Réglages → Moteur" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Build gesperrt — Einstellungen → Engine" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Compilación bloqueada — Ajustes → Motor" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Compilação bloqueada — Ajustes → Engine" - } - } - } - }, "Build cache (%@)": { "comment": "Source removal safety copy. User paths/names remain verbatim.", "localizations": { @@ -10589,84 +11265,84 @@ } } }, - "Build with nxnative main (%@, %@) before NX Library has tested it.": { + "Build with nxnative main (%@, %@) before Arcane has tested it.": { "comment": "NewestEngine.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Build with nxnative main (%@, %@) before NX Library has tested it." + "value": "Build with nxnative main (%@, %@) before Arcane has tested it." } }, "it": { "stringUnit": { "state": "translated", - "value": "Compila con nxnative main (%@, %@) prima che NX Library l’abbia testato." + "value": "Compila con nxnative main (%@, %@) prima che Arcane l’abbia testato." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Compiler avec nxnative main (%@, %@) avant qu’il soit testé par NX Library." + "value": "Compiler avec nxnative main (%@, %@) avant qu’il soit testé par Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Mit nxnative main (%@, %@) erstellen, bevor NX Library es getestet hat." + "value": "Mit nxnative main (%@, %@) erstellen, bevor Arcane es getestet hat." } }, "es": { "stringUnit": { "state": "translated", - "value": "Compila con main de nxnative (%@, %@) antes de que NX Library lo haya probado." + "value": "Compila con main de nxnative (%@, %@) antes de que Arcane lo haya probado." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Compile com o main do nxnative (%@, %@) antes de o NX Library testá-lo." + "value": "Compile com o main do nxnative (%@, %@) antes de o Arcane testá-lo." } } } }, - "Build with nxnative main before NX Library has tested it, or go back to the tested engine.": { + "Build with nxnative main before Arcane has tested it, or go back to the tested engine.": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Build with nxnative main before NX Library has tested it, or go back to the tested engine." + "value": "Build with nxnative main before Arcane has tested it, or go back to the tested engine." } }, "it": { "stringUnit": { "state": "translated", - "value": "Compila con nxnative main prima che NX Library l’abbia testato oppure torna al motore testato." + "value": "Compila con nxnative main prima che Arcane l’abbia testato oppure torna al motore testato." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Compiler avec nxnative main avant qu’il soit testé par NX Library, ou revenir au moteur testé." + "value": "Compiler avec nxnative main avant qu’il soit testé par Arcane, ou revenir au moteur testé." } }, "de": { "stringUnit": { "state": "translated", - "value": "Mit nxnative main erstellen, bevor NX Library es getestet hat, oder zur getesteten Engine zurückkehren." + "value": "Mit nxnative main erstellen, bevor Arcane es getestet hat, oder zur getesteten Engine zurückkehren." } }, "es": { "stringUnit": { "state": "translated", - "value": "Compila con main de nxnative antes de que NX Library lo haya probado o vuelve al motor probado." + "value": "Compila con main de nxnative antes de que Arcane lo haya probado o vuelve al motor probado." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Compile com o main do nxnative antes de o NX Library testá-lo ou volte à engine testada." + "value": "Compile com o main do nxnative antes de o Arcane testá-lo ou volte à engine testada." } } } @@ -10712,43 +11388,43 @@ } } }, - "Builds games with nxnative main instead of the engine this NX Library is tested with. ": { + "Builds games with nxnative main instead of the engine this version of Arcane is tested with. ": { "comment": "NewestEngine.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Builds games with nxnative main instead of the engine this NX Library is tested with. " + "value": "Builds games with nxnative main instead of the engine this version of Arcane is tested with. " } }, "it": { "stringUnit": { "state": "translated", - "value": "Compila i giochi con nxnative main anziché con il motore con cui è testata questa NX Library. " + "value": "Compila i giochi con nxnative main anziché con il motore con cui è testata questa versione di Arcane. " } }, "fr": { "stringUnit": { "state": "translated", - "value": "Compile les jeux avec nxnative main au lieu du moteur avec lequel cette version de NX Library a été testée. " + "value": "Compile les jeux avec nxnative main au lieu du moteur avec lequel cette version d’Arcane a été testée. " } }, "de": { "stringUnit": { "state": "translated", - "value": "Erstellt Spiele-Apps mit nxnative main statt mit der Engine, mit der diese NX Library-Version getestet wurde. " + "value": "Erstellt Spiele-Apps mit nxnative main statt mit der Engine, mit der diese Arcane-Version getestet wurde. " } }, "es": { "stringUnit": { "state": "translated", - "value": "Compila juegos con main de nxnative en lugar del motor con el que se ha probado este NX Library. " + "value": "Compila juegos con main de nxnative en lugar del motor con el que se ha probado este Arcane. " } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Compila jogos com o main do nxnative em vez da engine com a qual este NX Library foi testado. " + "value": "Compila jogos com o main do nxnative em vez da engine com a qual este Arcane foi testado. " } } } @@ -11204,125 +11880,125 @@ } } }, - "CONSOLE": { - "comment": "ConsoleView.swift", + "Cloud sync covers only the primary user and device save.": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "CONSOLE" + "value": "Cloud sync covers only the primary user and device save." } }, "it": { "stringUnit": { "state": "translated", - "value": "CONSOLE" + "value": "Il cloud sincronizza solo i salvataggi dell’utente principale e del dispositivo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "CONSOLE" + "value": "Le cloud ne synchronise que les sauvegardes de l’utilisateur principal et de l’appareil." } }, "de": { "stringUnit": { "state": "translated", - "value": "KONSOLE" + "value": "Die Cloud synchronisiert nur den Spielstand des Hauptbenutzers und den Gerätespielstand." } }, "es": { "stringUnit": { "state": "translated", - "value": "CONSOLA" + "value": "La nube solo sincroniza las partidas del usuario principal y del dispositivo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "CONSOLE" + "value": "A nuvem sincroniza apenas os salvamentos do usuário principal e do dispositivo." } } } }, - "Cache changed": { - "comment": "AppViewModel.swift", + "CONSOLE": { + "comment": "ConsoleView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Cache changed" + "value": "CONSOLE" } }, "it": { "stringUnit": { "state": "translated", - "value": "Cache modificata" + "value": "CONSOLE" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Cache modifié" + "value": "CONSOLE" } }, "de": { "stringUnit": { "state": "translated", - "value": "Cache geändert" + "value": "KONSOLE" } }, "es": { "stringUnit": { "state": "translated", - "value": "La caché ha cambiado" + "value": "CONSOLA" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Cache alterado" + "value": "CONSOLE" } } } }, - "Caches, logs, saves and the console.": { - "comment": "SettingsSection.swift", + "Cache changed": { + "comment": "AppViewModel.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Caches, logs, saves and the console." + "value": "Cache changed" } }, "it": { "stringUnit": { "state": "translated", - "value": "Cache, log, salvataggi e console." + "value": "Cache modificata" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Caches, journaux, sauvegardes et console." + "value": "Cache modifié" } }, "de": { "stringUnit": { "state": "translated", - "value": "Caches, Protokolle, Spielstände und Konsole." + "value": "Cache geändert" } }, "es": { "stringUnit": { "state": "translated", - "value": "Cachés, registros, partidas guardadas y consola." + "value": "La caché ha cambiado" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Caches, logs, dados salvos e console." + "value": "Cache alterado" } } } @@ -12475,6 +13151,47 @@ } } }, + "Check enabled Steam libraries without changing your game files.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check enabled Steam libraries without changing your game files." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Controlla le librerie Steam attive senza modificare i file dei giochi." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Vérifiez les bibliothèques Steam activées sans modifier les fichiers des jeux." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Prüfe aktive Steam-Bibliotheken, ohne Spieldateien zu ändern." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Revisa las bibliotecas de Steam activas sin cambiar los archivos de tus juegos." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Verifique as bibliotecas Steam ativas sem alterar os arquivos dos jogos." + } + } + } + }, "Check engine at launch": { "comment": "SettingsCatalog.swift", "localizations": { @@ -12803,6 +13520,47 @@ } } }, + "Check these installations in Steam, then refresh this source. Only recognized native Mac games appear in the library.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check these installations in Steam, then refresh this source. Only recognized native Mac games appear in the library." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Controlla queste installazioni in Steam, poi aggiorna la fonte. Nella libreria compaiono solo i giochi Mac nativi riconosciuti." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Vérifiez ces installations dans Steam, puis actualisez cette source. Seuls les jeux Mac natifs reconnus apparaissent dans la bibliothèque." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Prüfe diese Installationen in Steam und aktualisiere dann diese Quelle. Nur erkannte native Mac-Spiele erscheinen in der Bibliothek." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Revisa estas instalaciones en Steam y después actualiza esta fuente. Solo aparecen en la biblioteca los juegos nativos de Mac reconocidos." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Verifique estas instalações no Steam e atualize esta fonte. Apenas jogos nativos para Mac reconhecidos aparecem na biblioteca." + } + } + } + }, "Check what you need to build. Your games come next.": { "comment": "SetupCheckView.swift", "localizations": { @@ -12926,6 +13684,47 @@ } } }, + "Checking Steam libraries…": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Checking Steam libraries…" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Controllo delle librerie Steam…" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Vérification des bibliothèques Steam…" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam-Bibliotheken werden geprüft…" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Revisando bibliotecas de Steam…" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Verificando bibliotecas Steam…" + } + } + } + }, "Checking download…": { "comment": "SettingsAboutSection.swift:229", "localizations": { @@ -13254,43 +14053,43 @@ } } }, - "Checks the engine and toolchain each time NX Library starts.": { + "Checks the engine and toolchain each time Arcane starts.": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Checks the engine and toolchain each time NX Library starts." + "value": "Checks the engine and toolchain each time Arcane starts." } }, "it": { "stringUnit": { "state": "translated", - "value": "Controlla il motore e la toolchain a ogni avvio di NX Library." + "value": "Controlla il motore e la toolchain a ogni avvio di Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Vérifie le moteur et la chaîne d’outils à chaque démarrage de NX Library." + "value": "Vérifie le moteur et la chaîne d’outils à chaque démarrage d’Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Prüft Engine und Toolchain bei jedem Start von NX Library." + "value": "Prüft Engine und Toolchain bei jedem Start von Arcane." } }, "es": { "stringUnit": { "state": "translated", - "value": "Comprueba el motor y la cadena de herramientas cada vez que se inicia NX Library." + "value": "Comprueba el motor y la cadena de herramientas cada vez que se inicia Arcane." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Verifica a engine e o conjunto de ferramentas sempre que o NX Library inicia." + "value": "Verifica a engine e o conjunto de ferramentas sempre que o Arcane inicia." } } } @@ -13541,47 +14340,6 @@ } } }, - "Choose a folder with your %@. Existing apps play without these files. Change it later in Settings → Library.": { - "comment": "GameFoldersCopy.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Choose a folder with your %@. Existing apps play without these files. Change it later in Settings → Library." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Scegli una cartella con i tuoi %@. Le app esistenti funzionano senza questi file. Puoi cambiarla in seguito in Impostazioni → Libreria." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Choisissez un dossier contenant vos %@. Les apps existantes fonctionnent sans ces fichiers. Vous pourrez modifier ce choix dans Réglages → Bibliothèque." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Wähle einen Ordner mit deinen %@. Vorhandene Apps lassen sich ohne diese Dateien spielen. Du kannst den Ordner später unter Einstellungen → Bibliothek ändern." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Elige una carpeta con tus %@. Las apps existentes se pueden ejecutar sin estos archivos. Puedes cambiarlo más tarde en Ajustes → Biblioteca." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Escolha uma pasta com seus %@. Apps existentes funcionam sem esses arquivos. Altere depois em Ajustes → Biblioteca." - } - } - } - }, "Choose a game": { "comment": "AddGameView+Rows.swift", "localizations": { @@ -13705,43 +14463,43 @@ } } }, - "Choose a picture for your background. NX Library keeps its own copy.": { + "Choose a picture for your background. Arcane keeps its own copy.": { "comment": "ThemePickerView.swift:766", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Choose a picture for your background. NX Library keeps its own copy." + "value": "Choose a picture for your background. Arcane keeps its own copy." } }, "it": { "stringUnit": { "state": "translated", - "value": "Scegli un’immagine per lo sfondo. NX Library ne conserva una copia." + "value": "Scegli un’immagine per lo sfondo. Arcane ne conserva una copia." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Choisissez une image pour votre arrière-plan. NX Library en conserve une copie." + "value": "Choisissez une image pour votre arrière-plan. Arcane en conserve une copie." } }, "de": { "stringUnit": { "state": "translated", - "value": "Wähle ein Bild für deinen Hintergrund. NX Library behält eine eigene Kopie." + "value": "Wähle ein Bild für deinen Hintergrund. Arcane behält eine eigene Kopie." } }, "es": { "stringUnit": { "state": "translated", - "value": "Elige una imagen para tu fondo. NX Library conserva su propia copia." + "value": "Elige una imagen para tu fondo. Arcane conserva su propia copia." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Escolha uma imagem para seu fundo. O NX Library mantém uma cópia própria." + "value": "Escolha uma imagem para seu fundo. O Arcane mantém uma cópia própria." } } } @@ -13787,43 +14545,43 @@ } } }, - "Choose a video for your live background (MP4, MOV or M4V). NX Library keeps its own copy and plays it muted.": { + "Choose a video for your live background (MP4, MOV or M4V). Arcane keeps its own copy and plays it muted.": { "comment": "ThemePickerView.swift:765", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Choose a video for your live background (MP4, MOV or M4V). NX Library keeps its own copy and plays it muted." + "value": "Choose a video for your live background (MP4, MOV or M4V). Arcane keeps its own copy and plays it muted." } }, "it": { "stringUnit": { "state": "translated", - "value": "Scegli un video per lo sfondo animato (MP4, MOV o M4V). NX Library ne conserva una copia e lo riproduce senza audio." + "value": "Scegli un video per lo sfondo animato (MP4, MOV o M4V). Arcane ne conserva una copia e lo riproduce senza audio." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Choisissez une vidéo pour votre arrière-plan animé (MP4, MOV ou M4V). NX Library en conserve une copie et la lit sans le son." + "value": "Choisissez une vidéo pour votre arrière-plan animé (MP4, MOV ou M4V). Arcane en conserve une copie et la lit sans le son." } }, "de": { "stringUnit": { "state": "translated", - "value": "Wähle ein Video für deinen Live-Hintergrund (MP4, MOV oder M4V). NX Library behält eine eigene Kopie und spielt es ohne Ton ab." + "value": "Wähle ein Video für deinen Live-Hintergrund (MP4, MOV oder M4V). Arcane behält eine eigene Kopie und spielt es ohne Ton ab." } }, "es": { "stringUnit": { "state": "translated", - "value": "Elige un vídeo para tu fondo animado (MP4, MOV o M4V). NX Library conserva su propia copia y lo reproduce sin sonido." + "value": "Elige un vídeo para tu fondo animado (MP4, MOV o M4V). Arcane conserva su propia copia y lo reproduce sin sonido." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Escolha um vídeo para seu fundo animado (MP4, MOV ou M4V). O NX Library mantém uma cópia própria e o reproduz sem som." + "value": "Escolha um vídeo para seu fundo animado (MP4, MOV ou M4V). O Arcane mantém uma cópia própria e o reproduz sem som." } } } @@ -14238,6 +14996,47 @@ } } }, + "Choose the Steam folder containing steamapps.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose the Steam folder containing steamapps." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Scegli la cartella Steam che contiene steamapps." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Choisissez le dossier Steam contenant steamapps." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Wähle den Steam-Ordner, der steamapps enthält." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Elige la carpeta de Steam que contiene steamapps." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Escolha a pasta do Steam que contém steamapps." + } + } + } + }, "Choose the folder containing your game apps.": { "comment": "SetupCheck.swift", "localizations": { @@ -14484,47 +15283,6 @@ } } }, - "Choose where to keep your game apps. Put any existing nxnative games (.app) here. Change it later in Settings → Library.": { - "comment": "GameFoldersCopy.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Choose where to keep your game apps. Put any existing nxnative games (.app) here. Change it later in Settings → Library." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Scegli dove conservare le app dei giochi. Inserisci qui eventuali giochi nxnative (.app) esistenti. Puoi cambiarla in seguito in Impostazioni → Libreria." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Choisissez où conserver vos apps de jeux. Placez-y vos jeux nxnative existants (.app). Vous pourrez modifier ce choix dans Réglages → Bibliothèque." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Wähle, wo deine Spiele-Apps gespeichert werden. Lege hier auch vorhandene nxnative-Spiele (.app) ab. Du kannst den Ordner später unter Einstellungen → Bibliothek ändern." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Elige dónde guardar tus apps de juegos. Coloca aquí tus juegos existentes de nxnative (.app). Puedes cambiarlo más tarde en Ajustes → Biblioteca." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Escolha onde manter os apps dos seus jogos. Coloque aqui os jogos existentes do nxnative (.app). Altere depois em Ajustes → Biblioteca." - } - } - } - }, "Choose where to keep your game apps. Put any existing nxnative games (.app) here. Changing folders does not move apps; rebuilds update them where they are.": { "comment": "SettingsLibrarySection.swift", "localizations": { @@ -15345,6 +16103,47 @@ } } }, + "Close the other Arcane copy, then try again. Your original library has not been changed.": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Close the other Arcane copy, then try again. Your original library has not been changed." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Chiudi l’altra copia di Arcane e riprova. La libreria originale non è stata modificata." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fermez l’autre copie d’Arcane, puis réessayez. Votre bibliothèque d’origine n’a pas été modifiée." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Schließe die andere Kopie von Arcane und versuche es erneut. Deine Originalbibliothek wurde nicht verändert." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Cierra la otra copia de Arcane e inténtalo de nuevo. Tu biblioteca original no se ha modificado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Feche a outra cópia do Arcane e tente novamente. Sua biblioteca original não foi alterada." + } + } + } + }, "Cloud on": { "comment": "SavesPanel.swift:136", "localizations": { @@ -15632,47 +16431,6 @@ } } }, - "Cloud sync kept": { - "comment": "SettingsView.swift:265", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Cloud sync kept" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Sincronizzazione cloud conservata" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Synchronisation cloud conservée" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Cloud-Synchronisierung beibehalten" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Sincronización en la nube conservada" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Sincronização na nuvem mantida" - } - } - } - }, "Cloud unavailable": { "comment": "AppViewModel.swift", "localizations": { @@ -15878,43 +16636,43 @@ } } }, - "Colors for all of NX Library. Move through them to see each one in the preview.": { + "Colors for all of Arcane. Move through them to see each one in the preview.": { "comment": "ThemePickerView.swift:158", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Colors for all of NX Library. Move through them to see each one in the preview." + "value": "Colors for all of Arcane. Move through them to see each one in the preview." } }, "it": { "stringUnit": { "state": "translated", - "value": "Colori per tutta NX Library. Scorri le opzioni per vederle in anteprima." + "value": "Colori per tutto Arcane. Scorri le opzioni per vederle in anteprima." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Des couleurs pour toute l’interface de NX Library. Parcourez-les pour voir chaque thème dans l’aperçu." + "value": "Des couleurs pour toute l’interface d’Arcane. Parcourez-les pour voir chaque thème dans l’aperçu." } }, "de": { "stringUnit": { "state": "translated", - "value": "Farben für ganz NX Library. Wechsle zwischen ihnen, um jedes Design in der Vorschau zu sehen." + "value": "Farben für ganz Arcane. Wechsle zwischen ihnen, um jedes Design in der Vorschau zu sehen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Colores para todo NX Library. Recorre los temas para ver cada uno en la vista previa." + "value": "Colores para todo Arcane. Recorre los temas para ver cada uno en la vista previa." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Cores para todo o NX Library. Navegue entre elas para ver cada uma na prévia." + "value": "Cores para todo o Arcane. Navegue entre elas para ver cada uma na prévia." } } } @@ -17846,6 +18604,47 @@ } } }, + "Cover, background, icon and logo, from Steam, online sources or a file.": { + "comment": "CatalogGameOptions.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Cover, background, icon and logo, from Steam, online sources or a file." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Copertina, sfondo, icona e logo, da Steam, fonti online o un file." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Jaquette, fond, icône et logo, depuis Steam, des sources en ligne ou un fichier." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Cover, Hintergrund, Symbol und Logo, von Steam, Online-Quellen oder aus einer Datei." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Portada, fondo, icono y logotipo, de Steam, fuentes en línea o un archivo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Capa, fundo, ícone e logotipo, do Steam, de fontes online ou de um arquivo." + } + } + } + }, "Credits": { "comment": "SettingsAboutSection.swift", "localizations": { @@ -18092,47 +18891,6 @@ } } }, - "Default controller vibration for new games.": { - "comment": "SettingsCatalog.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Default controller vibration for new games." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Vibrazione predefinita del controller per i nuovi giochi." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Vibrations de la manette par défaut pour les nouveaux jeux." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Standard-Controller-Vibration für neue Spiele." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Vibración predeterminada del mando para juegos nuevos." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Vibração padrão do controle para novos jogos." - } - } - } - }, "Default game inputs. Older builds may differ.": { "comment": "ControlsView.swift", "localizations": { @@ -18215,43 +18973,43 @@ } } }, - "Default vibration strength for new games.": { - "comment": "SettingsCatalog.swift", + "Default order": { + "comment": "Achievements screen: the list order (Y), as the game lists them.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Default vibration strength for new games." + "value": "Default order" } }, "it": { "stringUnit": { "state": "translated", - "value": "Intensità predefinita della vibrazione per i nuovi giochi." + "value": "Ordine predefinito" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Intensité des vibrations par défaut pour les nouveaux jeux." + "value": "Ordre par défaut" } }, "de": { "stringUnit": { "state": "translated", - "value": "Standard-Vibrationsstärke für neue Spiele." + "value": "Standardreihenfolge" } }, "es": { "stringUnit": { "state": "translated", - "value": "Intensidad de vibración predeterminada para juegos nuevos." + "value": "Orden predeterminado" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Intensidade padrão da vibração para novos jogos." + "value": "Ordem padrão" } } } @@ -19742,6 +20500,47 @@ } } }, + "Development library unavailable": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Development library unavailable" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Libreria di sviluppo non disponibile" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Bibliothèque de développement indisponible" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Entwicklungsbibliothek nicht verfügbar" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Biblioteca de desarrollo no disponible" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Biblioteca de desenvolvimento indisponível" + } + } + } + }, "Device save": { "comment": "Save safety and presentation; user content stays unchanged.", "localizations": { @@ -20439,6 +21238,47 @@ } } }, + "Downloading": { + "comment": "Steam tile: Steam is still installing the game.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Downloading" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "In download" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Téléchargement" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Download läuft" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Descargando" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Baixando" + } + } + } + }, "Downloading %@%%": { "comment": "SettingsAboutSection.swift:228", "localizations": { @@ -21218,166 +22058,166 @@ } } }, - "Enable untested toolchain?": { - "comment": "SettingsEngineSection.swift", + "Enable Steam to find its installed Mac games.": { + "comment": "Steam source management and native Mac library presentation.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Enable untested toolchain?" + "value": "Enable Steam to find its installed Mac games." } }, "it": { "stringUnit": { "state": "translated", - "value": "Abilitare la toolchain non testata?" + "value": "Attiva Steam per trovare i suoi giochi Mac installati." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Activer la chaîne d’outils non testée ?" + "value": "Activez Steam pour trouver ses jeux Mac installés." } }, "de": { "stringUnit": { "state": "translated", - "value": "Ungetestete Toolchain aktivieren?" + "value": "Aktiviere Steam, um seine installierten Mac-Spiele zu finden." } }, "es": { "stringUnit": { "state": "translated", - "value": "¿Activar la cadena de herramientas no probada?" + "value": "Activa Steam para encontrar sus juegos de Mac instalados." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Permitir conjunto de ferramentas não testado?" + "value": "Ative o Steam para encontrar seus jogos de Mac instalados." } } } }, - "Encode thread": { - "comment": "Engine game setting presentation; never translate env keys or values.", + "Enable untested toolchain?": { + "comment": "SettingsEngineSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Encode thread" + "value": "Enable untested toolchain?" } }, "it": { "stringUnit": { "state": "translated", - "value": "Thread di codifica" + "value": "Abilitare la toolchain non testata?" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Thread d’encodage" + "value": "Activer la chaîne d’outils non testée ?" } }, "de": { "stringUnit": { "state": "translated", - "value": "Kodierungs-Thread" + "value": "Ungetestete Toolchain aktivieren?" } }, "es": { "stringUnit": { "state": "translated", - "value": "Hilo de codificación" + "value": "¿Activar la cadena de herramientas no probada?" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Thread de codificação" + "value": "Permitir conjunto de ferramentas não testado?" } } } }, - "Engine": { - "comment": "SettingsSection.swift", + "Encode thread": { + "comment": "Engine game setting presentation; never translate env keys or values.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Engine" + "value": "Encode thread" } }, "it": { "stringUnit": { "state": "translated", - "value": "Motore" + "value": "Thread di codifica" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Moteur" + "value": "Thread d’encodage" } }, "de": { "stringUnit": { "state": "translated", - "value": "Engine" + "value": "Kodierungs-Thread" } }, "es": { "stringUnit": { "state": "translated", - "value": "Motor" + "value": "Hilo de codificación" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Engine" + "value": "Thread de codificação" } } } }, - "Engine %@": { - "comment": "BuildSourcesPanel.swift", + "Engine": { + "comment": "SettingsSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Engine %@" + "value": "Engine" } }, "it": { "stringUnit": { "state": "translated", - "value": "Motore %@" + "value": "Motore" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Moteur %@" + "value": "Moteur" } }, "de": { "stringUnit": { "state": "translated", - "value": "Engine %@" + "value": "Engine" } }, "es": { "stringUnit": { "state": "translated", - "value": "Motor %@" + "value": "Motor" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Engine %@" + "value": "Engine" } } } @@ -21423,47 +22263,6 @@ } } }, - "Engine %@ · %@ · %@ · %@": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Engine %@ · %@ · %@ · %@" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Motore %@ · %@ · %@ · %@" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Moteur %@ · %@ · %@ · %@" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Engine %@ · %@ · %@ · %@" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Motor %@ · %@ · %@ · %@" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Engine %@ · %@ · %@ · %@" - } - } - } - }, "Engine back to the tested %@.": { "comment": "AppViewModel+NewestEngine.swift", "localizations": { @@ -21546,84 +22345,43 @@ } } }, - "Engine commit, Metal compiler, toolchain gate and required flags.": { + "Engine commit, Metal compiler, build environment, toolchain gate and required flags.": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Engine commit, Metal compiler, toolchain gate and required flags." + "value": "Engine commit, Metal compiler, build environment, toolchain gate and required flags." } }, "it": { "stringUnit": { "state": "translated", - "value": "Commit del motore, compilatore Metal, controllo della toolchain e flag richiesti." + "value": "Commit del motore, compilatore Metal, ambiente di build, controllo della toolchain e flag richiesti." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Commit du moteur, compilateur Metal, contrôle de la chaîne d’outils et options requises." + "value": "Commit du moteur, compilateur Metal, environnement de compilation, contrôle de la chaîne d’outils et options requises." } }, "de": { "stringUnit": { "state": "translated", - "value": "Engine-Commit, Metal-Compiler, Toolchain-Prüfung und erforderliche Optionen." + "value": "Engine-Commit, Metal-Compiler, Build-Umgebung, Toolchain-Prüfung und erforderliche Optionen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Commit del motor, compilador Metal, control de la cadena de herramientas y opciones necesarias." + "value": "Commit del motor, compilador Metal, entorno de compilación, control de la cadena de herramientas y opciones necesarias." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Commit da engine, compilador Metal, verificação do conjunto de ferramentas e opções obrigatórias." - } - } - } - }, - "Engine pin, toolchain gate and keys.": { - "comment": "SettingsSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Engine pin, toolchain gate and keys." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Versione fissata del motore, controllo della toolchain e chiavi." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Version épinglée du moteur, contrôle de la chaîne d’outils et clés." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Festgelegte Engine-Version, Toolchain-Prüfung und Schlüssel." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Versión fijada del motor, control de la cadena de herramientas y claves." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Versão fixada da engine, verificação do conjunto de ferramentas e chaves." + "value": "Commit da engine, compilador Metal, ambiente de build, verificação do conjunto de ferramentas e opções obrigatórias." } } } @@ -21874,43 +22632,43 @@ } } }, - "Environment": { + "Entrance animation": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Environment" + "value": "Entrance animation" } }, "it": { "stringUnit": { "state": "translated", - "value": "Ambiente" + "value": "Animazione d’entrata" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Environnement" + "value": "Animation d’entrée" } }, "de": { "stringUnit": { "state": "translated", - "value": "Umgebung" + "value": "Eingangsanimation" } }, "es": { "stringUnit": { "state": "translated", - "value": "Entorno" + "value": "Animación de entrada" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Ambiente" + "value": "Animação de entrada" } } } @@ -22202,84 +22960,84 @@ } } }, - "Everything NX Library can install by itself is installed.": { + "Everything Arcane can install by itself is installed.": { "comment": "SetupCheckView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Everything NX Library can install by itself is installed." + "value": "Everything Arcane can install by itself is installed." } }, "it": { "stringUnit": { "state": "translated", - "value": "Tutto ciò che NX Library può installare da sola è installato." + "value": "Tutto ciò che Arcane può installare da sola è installato." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Tout ce que NX Library peut installer seul est installé." + "value": "Tout ce qu’Arcane peut installer seul est installé." } }, "de": { "stringUnit": { "state": "translated", - "value": "Alles, was NX Library selbst installieren kann, ist installiert." + "value": "Alles, was Arcane selbst installieren kann, ist installiert." } }, "es": { "stringUnit": { "state": "translated", - "value": "Ya está instalado todo lo que NX Library puede instalar por sí mismo." + "value": "Ya está instalado todo lo que Arcane puede instalar por sí mismo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Tudo o que o NX Library pode instalar por conta própria está instalado." + "value": "Tudo o que o Arcane pode instalar por conta própria está instalado." } } } }, - "Everything NX Library needs is here.": { + "Everything Arcane needs is here.": { "comment": "SetupCheckView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Everything NX Library needs is here." + "value": "Everything Arcane needs is here." } }, "it": { "stringUnit": { "state": "translated", - "value": "È presente tutto ciò che serve a NX Library." + "value": "È presente tutto ciò che serve a Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Tout ce dont NX Library a besoin est présent." + "value": "Tout ce dont Arcane a besoin est présent." } }, "de": { "stringUnit": { "state": "translated", - "value": "Alles, was NX Library benötigt, ist vorhanden." + "value": "Alles, was Arcane benötigt, ist vorhanden." } }, "es": { "stringUnit": { "state": "translated", - "value": "Ya está todo lo que necesita NX Library." + "value": "Ya está todo lo que necesita Arcane." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Tudo o que o NX Library precisa está aqui." + "value": "Tudo o que o Arcane precisa está aqui." } } } @@ -22324,47 +23082,6 @@ } } }, - "Existing game apps play without sources. Choose later in Settings → Library.": { - "comment": "SetupCheck.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Existing game apps play without sources. Choose later in Settings → Library." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Le app dei giochi esistenti funzionano senza sorgenti. Puoi scegliere più tardi in Impostazioni → Libreria." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Les apps de jeux existantes fonctionnent sans sources. Vous pourrez choisir plus tard dans Réglages → Bibliothèque." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Vorhandene Spiele-Apps lassen sich ohne Quellen spielen. Wähle sie später unter Einstellungen → Bibliothek aus." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Las apps de juegos existentes se pueden ejecutar sin sus archivos de origen. Puedes elegirlos más tarde en Ajustes → Biblioteca." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Apps de jogos existentes funcionam sem os arquivos de origem. Escolha depois em Ajustes → Biblioteca." - } - } - } - }, "Existing game apps play without their sources. Reset group keeps this folder. Clear removes the selection, keeping your files.": { "comment": "SettingsLibrarySection.swift", "localizations": { @@ -23472,6 +24189,47 @@ } } }, + "Find installed native Mac games in your Steam libraries.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Find installed native Mac games in your Steam libraries." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Trova i giochi Mac nativi installati nelle tue librerie Steam." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Recherchez les jeux Mac natifs installés dans vos bibliothèques Steam." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Finde installierte native Mac-Spiele in deinen Steam-Bibliotheken." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Encuentra los juegos nativos de Mac instalados en tus bibliotecas de Steam." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Encontre jogos nativos para Mac instalados nas suas bibliotecas Steam." + } + } + } + }, "Find the game": { "comment": "DetailsBands.swift", "localizations": { @@ -23513,6 +24271,47 @@ } } }, + "Find this game on the Nintendo store.": { + "comment": "GameOptionsPresentation.swift: Search Nintendo Store row", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Find this game on the Nintendo store." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Cerca questo gioco nel Nintendo Store." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Rechercher ce jeu sur le Nintendo Store." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieses Spiel im Nintendo Store suchen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Busca este juego en la tienda de Nintendo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Procure este jogo na loja da Nintendo." + } + } + } + }, "Finishing…": { "comment": "SetupCheckView.swift", "localizations": { @@ -23677,43 +24476,43 @@ } } }, - "Folders, imports and artwork caches.": { + "Folders, scans and box covers.": { "comment": "SettingsSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Folders, imports and artwork caches." + "value": "Folders, scans and box covers." } }, "it": { "stringUnit": { "state": "translated", - "value": "Cartelle, importazioni e cache delle immagini." + "value": "Cartelle, scansioni e copertine." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Dossiers, importations et caches d’illustrations." + "value": "Dossiers, analyses et jaquettes." } }, "de": { "stringUnit": { "state": "translated", - "value": "Ordner, Importe und Artwork-Caches." + "value": "Ordner, Scans und Cover." } }, "es": { "stringUnit": { "state": "translated", - "value": "Carpetas, importaciones y cachés de imágenes." + "value": "Carpetas, búsquedas y carátulas." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Pastas, importações e caches de artes." + "value": "Pastas, buscas e capas." } } } @@ -25071,47 +25870,6 @@ } } }, - "Game files are missing or not attached. Attach them to build.": { - "comment": "BuildSourcesPanel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Game files are missing or not attached. Attach them to build." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "I file del gioco non sono disponibili o non sono collegati. Collegali per compilare." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Les fichiers du jeu sont introuvables ou non associés. Associez-les pour compiler." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Spieldateien fehlen oder sind nicht zugeordnet. Ordne sie zu, um die App zu erstellen." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Los archivos del juego faltan o no están vinculados. Vincúlalos para compilar." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Os arquivos do jogo não foram encontrados ou não estão vinculados. Vincule-os para compilar." - } - } - } - }, "Game files are missing or not attached. Attach them to rebuild.": { "comment": "GameOptionsPresentation.swift", "localizations": { @@ -25153,47 +25911,6 @@ } } }, - "Game files are missing or not attached. Play is available; attach them to rebuild.": { - "comment": "BuildSourcesPanel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Game files are missing or not attached. Play is available; attach them to rebuild." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "I file del gioco non sono disponibili o non sono collegati. Puoi giocare; collegali per ricompilare." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Les fichiers du jeu sont introuvables ou non associés. Vous pouvez jouer ; associez-les pour recompiler." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Spieldateien fehlen oder sind nicht zugeordnet. Spielen ist möglich; ordne die Dateien zu, um die App erneut zu erstellen." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Los archivos del juego faltan o no están vinculados. Puedes jugar; vincúlalos para recompilar." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Os arquivos do jogo não foram encontrados ou não estão vinculados. Você pode jogar; vincule-os para recompilar." - } - } - } - }, "Game files not found": { "comment": "GameResourceState.swift", "localizations": { @@ -26506,6 +27223,47 @@ } } }, + "Game sources": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Game sources" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Fonti" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Sources de jeux" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Spielequellen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Fuentes de juegos" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Fontes de jogos" + } + } + } + }, "Game sources: NSP, XCI, NSZ and XCZ files, or Switch 2 NUP files and extracted folders, for builds. Optional for existing apps.": { "comment": "SettingsCatalog.swift", "localizations": { @@ -27695,6 +28453,47 @@ } } }, + "Gold": { + "comment": "Achievement tier (a crystal), as PlayStation trophy tiers.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Gold" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Oro" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Or" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Gold" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Oro" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Ouro" + } + } + } + }, "Graphics & effects": { "comment": "ModCatalog.swift", "localizations": { @@ -27941,6 +28740,129 @@ } } }, + "Hidden Steam games": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hidden Steam games" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Giochi Steam nascosti" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Jeux Steam masqués" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Ausgeblendete Steam-Spiele" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Juegos de Steam ocultos" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Jogos Steam ocultos" + } + } + } + }, + "Hidden achievement": { + "comment": "AchievementSummary.swift: a hidden achievement still locked", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hidden achievement" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Obiettivo nascosto" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Succès caché" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Verborgener Erfolg" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Logro oculto" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Conquista oculta" + } + } + } + }, + "Hidden from the library": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hidden from the library" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nascosto nella libreria" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Masqué dans la bibliothèque" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "In der Bibliothek ausgeblendet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Oculto en la biblioteca" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Oculto na biblioteca" + } + } + } + }, "Hidden games": { "comment": "SettingsCatalog.swift", "localizations": { @@ -28433,43 +29355,43 @@ } } }, - "How NX Library looks and moves.": { + "How Arcane looks and moves.": { "comment": "SettingsSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "How NX Library looks and moves." + "value": "How Arcane looks and moves." } }, "it": { "stringUnit": { "state": "translated", - "value": "L’aspetto e le animazioni di NX Library." + "value": "L’aspetto e le animazioni di Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "L’apparence et les animations de NX Library." + "value": "L’apparence et les animations d’Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Wie NX Library aussieht und sich bewegt." + "value": "Wie Arcane aussieht und sich bewegt." } }, "es": { "stringUnit": { "state": "translated", - "value": "El aspecto y el movimiento de NX Library." + "value": "El aspecto y el movimiento de Arcane." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A aparência e os movimentos do NX Library." + "value": "A aparência e os movimentos do Arcane." } } } @@ -28598,7 +29520,7 @@ } }, "HowLongToBeat": { - "comment": "BuildSourcesPanel.swift", + "comment": "Details panel and Options", "localizations": { "en": { "stringUnit": { @@ -28761,43 +29683,43 @@ } } }, - "Icon used only in NX Library": { + "Icon used only in Arcane": { "comment": "AppIconProgress.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Icon used only in NX Library" + "value": "Icon used only in Arcane" } }, "it": { "stringUnit": { "state": "translated", - "value": "Icona usata solo in NX Library" + "value": "Icona usata solo in Arcane" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Icône utilisée uniquement dans NX Library" + "value": "Icône utilisée uniquement dans Arcane" } }, "de": { "stringUnit": { "state": "translated", - "value": "Symbol wird nur in NX Library verwendet" + "value": "Symbol wird nur in Arcane verwendet" } }, "es": { "stringUnit": { "state": "translated", - "value": "Icono usado solo en NX Library" + "value": "Icono usado solo en Arcane" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Ícone usado apenas no NX Library" + "value": "Ícone usado apenas no Arcane" } } } @@ -29622,43 +30544,43 @@ } } }, - "Included in NX Library": { + "Included in Arcane": { "comment": "SettingsEngineSection.swift:497", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Included in NX Library" + "value": "Included in Arcane" } }, "it": { "stringUnit": { "state": "translated", - "value": "Incluso in NX Library" + "value": "Incluso in Arcane" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Intégré à NX Library" + "value": "Intégré à Arcane" } }, "de": { "stringUnit": { "state": "translated", - "value": "In NX Library enthalten" + "value": "In Arcane enthalten" } }, "es": { "stringUnit": { "state": "translated", - "value": "Incluido en NX Library" + "value": "Incluido en Arcane" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Incluído no NX Library" + "value": "Incluído no Arcane" } } } @@ -30073,47 +30995,6 @@ } } }, - "Install the certified compiler from Setup, or allow untested toolchains in Settings → Engine.": { - "comment": "PortingFailureReason.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Install the certified compiler from Setup, or allow untested toolchains in Settings → Engine." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Installa il compilatore certificato da Configurazione oppure consenti le toolchain non testate in Impostazioni → Motore." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Installez le compilateur certifié depuis Configuration, ou autorisez les chaînes d’outils non testées dans Réglages → Moteur." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Installiere den zertifizierten Compiler über die Einrichtung oder erlaube ungetestete Toolchains unter Einstellungen → Engine." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Instala el compilador certificado desde Configuración inicial o permite cadenas de herramientas no probadas en Ajustes → Motor." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Instale o compilador certificado em Configuração ou permita conjuntos de ferramentas não testados em Ajustes → Engine." - } - } - } - }, "Install these cheats?": { "comment": "CheatCopy.swift", "localizations": { @@ -30319,6 +31200,47 @@ } } }, + "Installed in": { + "comment": "DetailsFacts.swift: the folder or Steam library", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Installed in" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Installato in" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Installé dans" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Installiert in" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Instalado en" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Instalado em" + } + } + } + }, "Installed the new build of %@.": { "comment": "AppViewModel+PendingInstall.swift", "localizations": { @@ -30770,47 +31692,6 @@ } } }, - "Intro animation": { - "comment": "SettingsCatalog.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Intro animation" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Animazione introduttiva" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Animation d’introduction" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Intro-Animation" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Animación de entrada" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Animação de abertura" - } - } - } - }, "Invalid key line number %@.": { "comment": "KeyStore.swift", "localizations": { @@ -30975,43 +31856,43 @@ } } }, - "Its new features reach NX Library in a future version.": { + "Its new features reach Arcane in a future version.": { "comment": "NewestEngine.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Its new features reach NX Library in a future version." + "value": "Its new features reach Arcane in a future version." } }, "it": { "stringUnit": { "state": "translated", - "value": "Le sue nuove funzionalità arriveranno in una futura versione di NX Library." + "value": "Le sue nuove funzionalità arriveranno in una futura versione di Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Ses nouvelles fonctionnalités seront intégrées à une future version de NX Library." + "value": "Ses nouvelles fonctionnalités seront intégrées à une future version d’Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Seine neuen Funktionen kommen in einer künftigen Version in NX Library an." + "value": "Seine neuen Funktionen kommen in einer künftigen Version in Arcane an." } }, "es": { "stringUnit": { "state": "translated", - "value": "Sus nuevas funciones llegarán a NX Library en una versión futura." + "value": "Sus nuevas funciones llegarán a Arcane en una versión futura." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Seus novos recursos chegarão ao NX Library em uma versão futura." + "value": "Seus novos recursos chegarão ao Arcane em uma versão futura." } } } @@ -31098,6 +31979,87 @@ } } }, + "Keep Arcane's library": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Keep Arcane's library" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Mantieni la libreria di Arcane" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Conserver la bibliothèque d’Arcane" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Arcane-Mediathek behalten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Conservar la biblioteca de Arcane" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Manter a biblioteca do Arcane" + } + } + } + }, + "Keep Steam in the background": { + "comment": "SettingsSourcesSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Keep Steam in the background" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Tieni Steam in secondo piano" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Garder Steam en arrière-plan" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam im Hintergrund halten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Mantener Steam en segundo plano" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Manter o Steam em segundo plano" + } + } + } + }, "Keep a copy of your current progress.": { "comment": "SavesPanel.swift", "localizations": { @@ -31221,6 +32183,47 @@ } } }, + "Keep playing to reveal it.": { + "comment": "AchievementSummary.swift: a hidden achievement's description", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Keep playing to reveal it." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Continua a giocare per scoprirlo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Continuez à jouer pour le découvrir." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Spiel weiter, um ihn freizulegen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Sigue jugando para descubrirlo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Continue jogando para revelá-la." + } + } + } + }, "Keep the game closed, including launches from Finder, until the operation finishes.": { "comment": "Save safety and presentation; user content stays unchanged.", "localizations": { @@ -31262,6 +32265,46 @@ } } }, + "Keep the games and sources in Arcane. The older app's changes will be archived separately, without merging the libraries.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Keep the games and sources in Arcane. The older app's changes will be archived separately, without merging the libraries." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Mantieni i giochi e le fonti di Arcane. Le modifiche della vecchia app saranno archiviate separatamente, senza unire le librerie." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Conservez les jeux et les sources d’Arcane. Les modifications de l’ancienne app seront archivées séparément, sans fusionner les bibliothèques." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Spiele und Quellen in Arcane bleiben erhalten. Änderungen aus der älteren App werden separat archiviert, ohne die Mediatheken zusammenzuführen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Conserva los juegos y las fuentes de Arcane. Los cambios de la app anterior se archivarán por separado, sin combinar las bibliotecas." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Mantenha os jogos e as fontes do Arcane. As alterações do app antigo serão arquivadas separadamente, sem mesclar as bibliotecas." + } + } + } + }, "Keeps a pipeline archive; uses more memory.": { "comment": "Engine game setting presentation; never translate env keys or values.", "localizations": { @@ -31590,6 +32633,47 @@ } } }, + "Local users": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Local users" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Utenti locali" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Utilisateurs locaux" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Lokale Benutzer" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Usuarios locales" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Usuários locais" + } + } + } + }, "LOOKING ON %@…": { "comment": "OnlineBrowsePanel.swift:146", "localizations": { @@ -31754,6 +32838,47 @@ } } }, + "Language, the first screen and what runs at launch.": { + "comment": "SettingsSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Language, the first screen and what runs at launch." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Lingua, schermata iniziale e cosa avviene all’apertura." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Langue, premier écran et ce qui se lance au démarrage." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Sprache, erster Bildschirm und was beim Start passiert." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Idioma, primera pantalla y lo que se ejecuta al abrir." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Idioma, primeira tela e o que acontece ao abrir." + } + } + } + }, "Largest build caches first. Sizes describe file contents; the space recovered can differ. Shared folders count once in totals.": { "comment": "SettingsStorageSection.swift", "localizations": { @@ -32164,47 +33289,6 @@ } } }, - "Launch screen, hidden games and defaults for new games.": { - "comment": "SettingsSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Launch screen, hidden games and defaults for new games." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Schermata di avvio, giochi nascosti e valori predefiniti per i nuovi giochi." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Écran de lancement, jeux masqués et réglages par défaut des nouveaux jeux." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Startbildschirm, ausgeblendete Spiele und Standards für neue Spiele." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Pantalla de inicio, juegos ocultos y valores predeterminados para juegos nuevos." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Tela de abertura, jogos ocultos e padrões para novos jogos." - } - } - } - }, "Launch the installed Mac app.": { "comment": "GameOptionsPresentation.swift", "localizations": { @@ -32328,43 +33412,43 @@ } } }, - "Let's get NX Library ready": { + "Let's get Arcane ready": { "comment": "SetupCheckView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Let's get NX Library ready" + "value": "Let's get Arcane ready" } }, "it": { "stringUnit": { "state": "translated", - "value": "Prepariamo NX Library" + "value": "Prepariamo Arcane" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Préparons NX Library" + "value": "Préparons Arcane" } }, "de": { "stringUnit": { "state": "translated", - "value": "Machen wir NX Library startklar" + "value": "Machen wir Arcane startklar" } }, "es": { "stringUnit": { "state": "translated", - "value": "Vamos a preparar NX Library" + "value": "Vamos a preparar Arcane" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Vamos preparar o NX Library" + "value": "Vamos preparar o Arcane" } } } @@ -32574,84 +33658,84 @@ } } }, - "Library controls and new-game rumble.": { - "comment": "SettingsSection.swift", + "Library navigation": { + "comment": "SettingsControllersSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Library controls and new-game rumble." + "value": "Library navigation" } }, "it": { "stringUnit": { "state": "translated", - "value": "Comandi della libreria e vibrazione dei nuovi giochi." + "value": "Navigazione nella libreria" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Commandes de la bibliothèque et vibrations des nouveaux jeux." + "value": "Navigation dans la bibliothèque" } }, "de": { "stringUnit": { "state": "translated", - "value": "Bibliothekssteuerung und Vibration für neue Spiele." + "value": "Bibliotheksnavigation" } }, "es": { "stringUnit": { "state": "translated", - "value": "Controles de la biblioteca y vibración de juegos nuevos." + "value": "Navegación de la biblioteca" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Controles da biblioteca e vibração para novos jogos." + "value": "Navegação na biblioteca" } } } }, - "Library navigation": { - "comment": "SettingsControllersSection.swift", + "Library not saved": { + "comment": "Catalog activation and recovery", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Library navigation" + "value": "Library not saved" } }, "it": { "stringUnit": { "state": "translated", - "value": "Navigazione nella libreria" + "value": "Libreria non salvata" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Navigation dans la bibliothèque" + "value": "Bibliothèque non enregistrée" } }, "de": { "stringUnit": { "state": "translated", - "value": "Bibliotheksnavigation" + "value": "Bibliothek nicht gespeichert" } }, "es": { "stringUnit": { "state": "translated", - "value": "Navegación de la biblioteca" + "value": "Biblioteca sin guardar" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Navegação na biblioteca" + "value": "Biblioteca não salva" } } } @@ -32779,6 +33863,47 @@ } } }, + "Library unavailable": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Library unavailable" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Libreria non disponibile" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Bibliothèque indisponible" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bibliothek nicht verfügbar" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Biblioteca no disponible" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Biblioteca indisponível" + } + } + } + }, "Library · Launch": { "comment": "ChangeArtworkView.swift:310", "localizations": { @@ -33025,43 +34150,43 @@ } } }, - "Locally cached game metadata such as title IDs, publisher names, release dates, and category tags fetched during library scans.": { - "comment": "SettingsLibrarySection.swift", + "Locked": { + "comment": "Achievements filter: locked ones.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Locally cached game metadata such as title IDs, publisher names, release dates, and category tags fetched during library scans." + "value": "Locked" } }, "it": { "stringUnit": { "state": "translated", - "value": "Metadati dei giochi conservati nella cache locale, come title ID, nomi degli editori, date di uscita e tag delle categorie, recuperati durante le scansioni della libreria." + "value": "Bloccati" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Métadonnées de jeu mises en cache localement, telles que les title ID, les noms d’éditeur, les dates de sortie et les catégories, récupérées lors des analyses de la bibliothèque." + "value": "Verrouillés" } }, "de": { "stringUnit": { "state": "translated", - "value": "Lokal zwischengespeicherte Spielmetadaten wie title IDs, Publisher-Namen, Veröffentlichungsdaten und Kategorien, die beim Durchsuchen der Bibliothek abgerufen werden." + "value": "Gesperrt" } }, "es": { "stringUnit": { "state": "translated", - "value": "Metadatos de juegos guardados en la caché local, como title IDs, nombres de editoras, fechas de lanzamiento y etiquetas de categorías, obtenidos al analizar la biblioteca." + "value": "Bloqueados" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Metadados de jogos em cache local, como title IDs, nomes de publicadoras, datas de lançamento e categorias, obtidos durante as buscas na biblioteca." + "value": "Bloqueadas" } } } @@ -33271,43 +34396,43 @@ } } }, - "Look for a newer NX Library release at launch, at most once a day.": { + "Look for a newer Arcane release at launch, at most once a day.": { "comment": "SettingsStartUpSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Look for a newer NX Library release at launch, at most once a day." + "value": "Look for a newer Arcane release at launch, at most once a day." } }, "it": { "stringUnit": { "state": "translated", - "value": "Cerca una nuova versione di NX Library all’avvio, al massimo una volta al giorno." + "value": "Cerca una nuova versione di Arcane all’avvio, al massimo una volta al giorno." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Rechercher une nouvelle version de NX Library au lancement, au maximum une fois par jour." + "value": "Rechercher une nouvelle version d’Arcane au lancement, au maximum une fois par jour." } }, "de": { "stringUnit": { "state": "translated", - "value": "Beim Start nach einer neueren NX Library-Veröffentlichung suchen, höchstens einmal täglich." + "value": "Beim Start nach einer neueren Arcane-Veröffentlichung suchen, höchstens einmal täglich." } }, "es": { "stringUnit": { "state": "translated", - "value": "Busca una versión más reciente de NX Library al abrir, como máximo una vez al día." + "value": "Busca una versión más reciente de Arcane al abrir, como máximo una vez al día." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Busca uma versão mais recente do NX Library ao iniciar, no máximo uma vez por dia." + "value": "Busca uma versão mais recente do Arcane ao iniciar, no máximo uma vez por dia." } } } @@ -33640,43 +34765,43 @@ } } }, - "Looks for a newer NX Library release at launch, at most once a day.": { + "Looks for a newer Arcane release at launch, at most once a day.": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Looks for a newer NX Library release at launch, at most once a day." + "value": "Looks for a newer Arcane release at launch, at most once a day." } }, "it": { "stringUnit": { "state": "translated", - "value": "Cerca una nuova versione di NX Library all’avvio, al massimo una volta al giorno." + "value": "Cerca una nuova versione di Arcane all’avvio, al massimo una volta al giorno." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Recherche une nouvelle version de NX Library au lancement, au maximum une fois par jour." + "value": "Recherche une nouvelle version d’Arcane au lancement, au maximum une fois par jour." } }, "de": { "stringUnit": { "state": "translated", - "value": "Sucht beim Start nach einer neueren NX Library-Veröffentlichung, höchstens einmal täglich." + "value": "Sucht beim Start nach einer neueren Arcane-Veröffentlichung, höchstens einmal täglich." } }, "es": { "stringUnit": { "state": "translated", - "value": "Busca una versión más reciente de NX Library al abrir, como máximo una vez al día." + "value": "Busca una versión más reciente de Arcane al abrir, como máximo una vez al día." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Busca uma versão mais recente do NX Library ao iniciar, no máximo uma vez por dia." + "value": "Busca uma versão mais recente do Arcane ao iniciar, no máximo uma vez por dia." } } } @@ -33927,6 +35052,47 @@ } } }, + "Manage sources": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manage sources" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Gestisci fonti" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Gérer les sources" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Quellen verwalten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Gestionar fuentes" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Gerenciar fontes" + } + } + } + }, "Manual backup": { "comment": "Save safety and presentation; user content stays unchanged.", "localizations": { @@ -34337,47 +35503,6 @@ } } }, - "Metal unknown": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Metal unknown" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Metal sconosciuto" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Metal inconnu" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Metal unbekannt" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Metal desconocido" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Metal desconhecido" - } - } - } - }, "MetalFX": { "comment": "Engine setting option display label.", "localizations": { @@ -34624,43 +35749,43 @@ } } }, - "Mod data provided by GameBanana · only mods that work with NX Library are shown": { + "Mod data provided by GameBanana · only mods that work with Arcane are shown": { "comment": "ModStorePage.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Mod data provided by GameBanana · only mods that work with NX Library are shown" + "value": "Mod data provided by GameBanana · only mods that work with Arcane are shown" } }, "it": { "stringUnit": { "state": "translated", - "value": "Dati delle mod forniti da GameBanana · vengono mostrate solo le mod compatibili con NX Library" + "value": "Dati delle mod forniti da GameBanana · vengono mostrate solo le mod compatibili con Arcane" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Données des mods fournies par GameBanana · seuls les mods compatibles avec NX Library sont affichés" + "value": "Données des mods fournies par GameBanana · seuls les mods compatibles avec Arcane sont affichés" } }, "de": { "stringUnit": { "state": "translated", - "value": "Mod-Daten von GameBanana · Es werden nur Mods angezeigt, die mit NX Library funktionieren" + "value": "Mod-Daten von GameBanana · Es werden nur Mods angezeigt, die mit Arcane funktionieren" } }, "es": { "stringUnit": { "state": "translated", - "value": "Datos de mods proporcionados por GameBanana · solo se muestran mods compatibles con NX Library" + "value": "Datos de mods proporcionados por GameBanana · solo se muestran mods compatibles con Arcane" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Dados de mods fornecidos pelo GameBanana · apenas mods compatíveis com o NX Library são exibidos" + "value": "Dados de mods fornecidos pelo GameBanana · apenas mods compatíveis com o Arcane são exibidos" } } } @@ -35034,6 +36159,47 @@ } } }, + "Most common first": { + "comment": "Achievements screen: the list order (Y), most players first.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Most common first" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Prima i più comuni" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les plus courants d’abord" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Häufigste zuerst" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Más comunes primero" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Mais comuns primeiro" + } + } + } + }, "Most liked": { "comment": "ModCatalog.swift", "localizations": { @@ -35157,84 +36323,84 @@ } } }, - "Move NX Library to Applications before updating.": { + "Move Arcane to Applications before updating.": { "comment": "AppUpdateDialog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Move NX Library to Applications before updating." + "value": "Move Arcane to Applications before updating." } }, "it": { "stringUnit": { "state": "translated", - "value": "Sposta NX Library in Applicazioni prima di aggiornarla." + "value": "Sposta Arcane in Applicazioni prima di aggiornarla." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Déplacez NX Library dans Applications avant de la mettre à jour." + "value": "Déplacez Arcane dans Applications avant de la mettre à jour." } }, "de": { "stringUnit": { "state": "translated", - "value": "Verschiebe NX Library vor dem Aktualisieren in den Programme-Ordner." + "value": "Verschiebe Arcane vor dem Aktualisieren in den Programme-Ordner." } }, "es": { "stringUnit": { "state": "translated", - "value": "Mueve NX Library a Aplicaciones antes de actualizar." + "value": "Mueve Arcane a Aplicaciones antes de actualizar." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Mova o NX Library para Applications antes de atualizar." + "value": "Mova o Arcane para Applications antes de atualizar." } } } }, - "Move NX Library to Applications to update": { + "Move Arcane to Applications to update": { "comment": "SettingsAboutSection.swift:220", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Move NX Library to Applications to update" + "value": "Move Arcane to Applications to update" } }, "it": { "stringUnit": { "state": "translated", - "value": "Sposta NX Library in Applicazioni per aggiornarla" + "value": "Sposta Arcane in Applicazioni per aggiornarla" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Déplacez NX Library dans Applications pour la mettre à jour" + "value": "Déplacez Arcane dans Applications pour la mettre à jour" } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library zum Aktualisieren in den Programme-Ordner verschieben" + "value": "Arcane zum Aktualisieren in den Programme-Ordner verschieben" } }, "es": { "stringUnit": { "state": "translated", - "value": "Mueve NX Library a Aplicaciones para actualizar" + "value": "Mueve Arcane a Aplicaciones para actualizar" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Mova o NX Library para Applications para atualizar" + "value": "Mova o Arcane para Applications para atualizar" } } } @@ -35772,822 +36938,781 @@ } } }, - "NX Library": { - "comment": "AppShellView.swift", + "Arcane %@": { + "comment": "AppUpdateDialog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library" + "value": "Arcane %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library" + "value": "Arcane %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library" + "value": "Arcane %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library" + "value": "Arcane %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library" + "value": "Arcane %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "NX Library" + "value": "Arcane %@" } } } }, - "NX Library %@": { - "comment": "AppUpdateDialog.swift", + "Arcane %@ needs macOS %@ or later; nothing was changed.": { + "comment": "AppUpdater.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library %@" + "value": "Arcane %@ needs macOS %@ or later; nothing was changed." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library %@" + "value": "Arcane %@ richiede macOS %@ o successivo; non è stato modificato nulla." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library %@" + "value": "Arcane %@ nécessite macOS %@ ou ultérieur ; aucune modification n’a été effectuée." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library %@" + "value": "Arcane %@ benötigt macOS %@ oder neuer; es wurde nichts geändert." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library %@" + "value": "Arcane %@ requiere macOS %@ o posterior; no se ha cambiado nada." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "NX Library %@" + "value": "O Arcane %@ requer macOS %@ ou posterior; nada foi alterado." } } } }, - "NX Library %@ needs macOS %@ or later; nothing was changed.": { - "comment": "AppUpdater.swift", + "Arcane cannot read this folder. Reconnect it or choose another.": { + "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library %@ needs macOS %@ or later; nothing was changed." + "value": "Arcane cannot read this folder. Reconnect it or choose another." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library %@ richiede macOS %@ o successivo; non è stato modificato nulla." + "value": "Arcane non può leggere questa cartella. Ricollegala o scegline un’altra." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library %@ nécessite macOS %@ ou ultérieur ; aucune modification n’a été effectuée." + "value": "Arcane ne peut pas lire ce dossier. Reconnectez-le ou choisissez-en un autre." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library %@ benötigt macOS %@ oder neuer; es wurde nichts geändert." + "value": "Arcane kann diesen Ordner nicht lesen. Verbinde ihn erneut oder wähle einen anderen." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library %@ requiere macOS %@ o posterior; no se ha cambiado nada." + "value": "Arcane no puede leer esta carpeta. Vuelve a conectarla o elige otra." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library %@ requer macOS %@ ou posterior; nada foi alterado." + "value": "O Arcane não consegue ler esta pasta. Reconecte ou escolha outra." } } } }, - "NX Library cannot read this folder. Reconnect it or choose another.": { + "Arcane clones it into %@ at %@.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library cannot read this folder. Reconnect it or choose another." + "value": "Arcane clones it into %@ at %@." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Arcane lo clona in %@ al commit %@." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Arcane le clone dans %@ au commit %@." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Arcane klont es nach %@ mit Stand %@." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Arcane lo clona en %@ en el commit %@." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O Arcane clona o repositório em %@ no commit %@." + } + } + } + }, + "Arcane could not read the file.": { + "comment": "CheatsPanel.swift:455", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Arcane could not read the file." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Arcane non ha potuto leggere il file." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Arcane n’a pas pu lire le fichier." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Arcane konnte die Datei nicht lesen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Arcane no ha podido leer el archivo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O Arcane não conseguiu ler o arquivo." + } + } + } + }, + "Arcane could not restart: %@": { + "comment": "AppShellView.swift:1029", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Arcane could not restart: %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Arcane non ha potuto riavviarsi: %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Arcane n’a pas pu redémarrer : %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Arcane konnte nicht neu gestartet werden: %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Arcane no ha podido reiniciarse: %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível reiniciar o Arcane: %@" + } + } + } + }, + "Arcane could not save your library, so recent changes may be lost when it quits: ": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Arcane could not save your library, so recent changes may be lost when it quits: " } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library non può leggere questa cartella. Ricollegala o scegline un’altra." + "value": "Arcane non ha potuto salvare la libreria; le modifiche recenti potrebbero andare perse alla chiusura: " } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library ne peut pas lire ce dossier. Reconnectez-le ou choisissez-en un autre." + "value": "Arcane n’a pas pu enregistrer votre bibliothèque. Les modifications récentes risquent donc d’être perdues à sa fermeture : " } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library kann diesen Ordner nicht lesen. Verbinde ihn erneut oder wähle einen anderen." + "value": "Arcane konnte deine Bibliothek nicht speichern. Daher können beim Beenden die letzten Änderungen verloren gehen: " } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library no puede leer esta carpeta. Vuelve a conectarla o elige otra." + "value": "Arcane no ha podido guardar la biblioteca, por lo que los cambios recientes podrían perderse al salir: " } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library não consegue ler esta pasta. Reconecte ou escolha outra." + "value": "O Arcane não conseguiu salvar sua biblioteca. Por isso, as alterações recentes podem ser perdidas quando o app for encerrado: " } } } }, - "NX Library clones it into %@ at %@.": { + "Arcane downloads Microsoft's installer; macOS asks for your password.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library clones it into %@ at %@." + "value": "Arcane downloads Microsoft's installer; macOS asks for your password." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library lo clona in %@ al commit %@." + "value": "Arcane scarica il programma di installazione di Microsoft; macOS chiede la tua password." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library le clone dans %@ au commit %@." + "value": "Arcane télécharge le programme d’installation de Microsoft ; macOS vous demande votre mot de passe." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library klont es nach %@ mit Stand %@." + "value": "Arcane lädt das Installationsprogramm von Microsoft; macOS fragt nach deinem Passwort." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library lo clona en %@ en el commit %@." + "value": "Arcane descarga el instalador de Microsoft; macOS pide tu contraseña." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library clona o repositório em %@ no commit %@." + "value": "O Arcane baixa o instalador da Microsoft; o macOS pede sua senha." } } } }, - "NX Library could not read the file.": { - "comment": "CheatsPanel.swift:455", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "NX Library could not read the file." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "NX Library non ha potuto leggere il file." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "NX Library n’a pas pu lire le fichier." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "NX Library konnte die Datei nicht lesen." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "NX Library no ha podido leer el archivo." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "O NX Library não conseguiu ler o arquivo." - } - } - } - }, - "NX Library could not restart: %@": { - "comment": "AppShellView.swift:1029", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "NX Library could not restart: %@" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "NX Library non ha potuto riavviarsi: %@" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "NX Library n’a pas pu redémarrer : %@" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "NX Library konnte nicht neu gestartet werden: %@" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "NX Library no ha podido reiniciarse: %@" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Não foi possível reiniciar o NX Library: %@" - } - } - } - }, - "NX Library could not save your library, so recent changes may be lost when it quits: ": { - "comment": "AppViewModel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "NX Library could not save your library, so recent changes may be lost when it quits: " - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "NX Library non ha potuto salvare la libreria; le modifiche recenti potrebbero andare perse alla chiusura: " - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "NX Library n’a pas pu enregistrer votre bibliothèque. Les modifications récentes risquent donc d’être perdues à sa fermeture : " - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "NX Library konnte deine Bibliothek nicht speichern. Daher können beim Beenden die letzten Änderungen verloren gehen: " - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "NX Library no ha podido guardar la biblioteca, por lo que los cambios recientes podrían perderse al salir: " - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "O NX Library não conseguiu salvar sua biblioteca. Por isso, as alterações recentes podem ser perdidas quando o app for encerrado: " - } - } - } - }, - "NX Library downloads Microsoft's installer; macOS asks for your password.": { - "comment": "SetupCheck.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "NX Library downloads Microsoft's installer; macOS asks for your password." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "NX Library scarica il programma di installazione di Microsoft; macOS chiede la tua password." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "NX Library télécharge le programme d’installation de Microsoft ; macOS vous demande votre mot de passe." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "NX Library lädt das Installationsprogramm von Microsoft; macOS fragt nach deinem Passwort." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "NX Library descarga el instalador de Microsoft; macOS pide tu contraseña." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "O NX Library baixa o instalador da Microsoft; o macOS pede sua senha." - } - } - } - }, - "NX Library downloads it through Xcode.": { + "Arcane downloads it through Xcode.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library downloads it through Xcode." + "value": "Arcane downloads it through Xcode." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library lo scarica tramite Xcode." + "value": "Arcane lo scarica tramite Xcode." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library le télécharge via Xcode." + "value": "Arcane le télécharge via Xcode." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library lädt ihn über Xcode herunter." + "value": "Arcane lädt ihn über Xcode herunter." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library lo descarga a través de Xcode." + "value": "Arcane lo descarga a través de Xcode." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library faz o download pelo Xcode." + "value": "O Arcane faz o download pelo Xcode." } } } }, - "NX Library is personal software released under the MIT license. nxnative, Ryujinx, SPIR-V Cross, LibHac and the other dependencies retain their own licenses through the engine.": { + "Arcane is personal software released under the MIT license. nxnative, Ryujinx, SPIR-V Cross, LibHac and the other dependencies retain their own licenses through the engine.": { "comment": "SettingsAboutSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library is personal software released under the MIT license. nxnative, Ryujinx, SPIR-V Cross, LibHac and the other dependencies retain their own licenses through the engine." + "value": "Arcane is personal software released under the MIT license. nxnative, Ryujinx, SPIR-V Cross, LibHac and the other dependencies retain their own licenses through the engine." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library è un software personale distribuito con licenza MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac e le altre dipendenze mantengono le proprie licenze tramite il motore." + "value": "Arcane è un software personale distribuito con licenza MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac e le altre dipendenze mantengono le proprie licenze tramite il motore." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library est un logiciel personnel publié sous licence MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac et les autres dépendances conservent leurs propres licences via le moteur." + "value": "Arcane est un logiciel personnel publié sous licence MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac et les autres dépendances conservent leurs propres licences via le moteur." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library ist persönliche Software unter der MIT-Lizenz. nxnative, Ryujinx, SPIR-V Cross, LibHac und die übrigen Abhängigkeiten behalten über die Engine ihre eigenen Lizenzen." + "value": "Arcane ist persönliche Software unter der MIT-Lizenz. nxnative, Ryujinx, SPIR-V Cross, LibHac und die übrigen Abhängigkeiten behalten über die Engine ihre eigenen Lizenzen." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library es software personal distribuido bajo la licencia MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac y las demás dependencias conservan sus propias licencias a través del motor." + "value": "Arcane es software personal distribuido bajo la licencia MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac y las demás dependencias conservan sus propias licencias a través del motor." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library é um software pessoal disponibilizado sob a licença MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac e as demais dependências mantêm suas próprias licenças por meio da engine." + "value": "O Arcane é um software pessoal disponibilizado sob a licença MIT. nxnative, Ryujinx, SPIR-V Cross, LibHac e as demais dependências mantêm suas próprias licenças por meio da engine." } } } }, - "NX Library is up to date": { + "Arcane is up to date": { "comment": "SettingsAboutSection.swift:223", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library is up to date" + "value": "Arcane is up to date" } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library è aggiornata" + "value": "Arcane è aggiornata" } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library est à jour" + "value": "Arcane est à jour" } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library ist auf dem neuesten Stand" + "value": "Arcane ist auf dem neuesten Stand" } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library está al día" + "value": "Arcane está al día" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library está atualizado" + "value": "O Arcane está atualizado" } } } }, - "NX Library restarts to finish.": { + "Arcane restarts to finish.": { "comment": "AppUpdateDialog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library restarts to finish." + "value": "Arcane restarts to finish." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library si riavvia per completare l’operazione." + "value": "Arcane si riavvia per completare l’operazione." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library redémarre pour terminer." + "value": "Arcane redémarre pour terminer." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library wird zum Abschließen neu gestartet." + "value": "Arcane wird zum Abschließen neu gestartet." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library se reinicia para finalizar." + "value": "Arcane se reinicia para finalizar." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library será reiniciado para concluir." + "value": "O Arcane será reiniciado para concluir." } } } }, - "NX Library uses symlinks to your game ROM files to build the macOS native binary. Rebuilding uses your current engine pin and settings, and preserves your game saves. ": { - "comment": "BuildSourcesPanel.swift", + "Arcane will reopen automatically.": { + "comment": "AppUpdateDialog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library uses symlinks to your game ROM files to build the macOS native binary. Rebuilding uses your current engine pin and settings, and preserves your game saves. " + "value": "Arcane will reopen automatically." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library usa collegamenti simbolici ai file ROM dei tuoi giochi per compilare il binario nativo per macOS. La ricompilazione usa la versione del motore attualmente fissata e le impostazioni correnti, e conserva i salvataggi. " + "value": "Arcane si riaprirà automaticamente." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library utilise des liens symboliques vers vos fichiers ROM de jeu pour compiler le binaire natif macOS. La recompilation utilise votre version de moteur épinglée et vos réglages actuels, et préserve vos sauvegardes de jeu. " + "value": "Arcane se rouvrira automatiquement." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library verwendet symbolische Links zu deinen Spiel-ROM-Dateien, um die native macOS-App zu erstellen. Beim erneuten Erstellen werden die aktuell festgelegte Engine-Version und deine Einstellungen verwendet. Deine Spielstände bleiben erhalten. " + "value": "Arcane wird automatisch wieder geöffnet." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library usa enlaces simbólicos a los archivos ROM de tus juegos para compilar el binario nativo de macOS. Al recompilar, se usan la versión fijada del motor y los ajustes actuales, y se conservan las partidas guardadas. " + "value": "Arcane se volverá a abrir automáticamente." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library usa links simbólicos para os arquivos ROM dos seus jogos para compilar o binário nativo para macOS. A recompilação usa a versão fixada atual da engine e seus ajustes, preservando os dados salvos do jogo. " + "value": "O Arcane será reaberto automaticamente." } } } }, - "NX Library will reopen automatically.": { - "comment": "AppUpdateDialog.swift", + "Arcane's copy of %@ goes to the Trash, so you can bring it back from there. Your original file stays where it is.": { + "comment": "ThemePickerView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library will reopen automatically." + "value": "Arcane's copy of %@ goes to the Trash, so you can bring it back from there. Your original file stays where it is." } }, "it": { "stringUnit": { "state": "translated", - "value": "NX Library si riaprirà automaticamente." + "value": "La copia di %@ di Arcane viene spostata nel Cestino: puoi ripristinarla da lì. Il file originale resta dov’è." } }, "fr": { "stringUnit": { "state": "translated", - "value": "NX Library se rouvrira automatiquement." + "value": "La copie de %@ utilisée par Arcane est placée dans la corbeille ; vous pourrez l’y récupérer. Votre fichier d’origine reste à son emplacement." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library wird automatisch wieder geöffnet." + "value": "Die Arcane-Kopie von %@ wird in den Papierkorb gelegt. Du kannst sie von dort zurückholen. Deine Originaldatei bleibt an ihrem Platz." } }, "es": { "stringUnit": { "state": "translated", - "value": "NX Library se volverá a abrir automáticamente." + "value": "La copia de %@ de Arcane se mueve a la Papelera para que puedas recuperarla. Tu archivo original permanece en su ubicación." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O NX Library será reaberto automaticamente." + "value": "A cópia de %@ do Arcane vai para o Lixo, de onde você poderá restaurá-la. Seu arquivo original permanece onde está." } } } }, - "NX Library's copy of %@ goes to the Trash, so you can bring it back from there. Your original file stays where it is.": { - "comment": "ThemePickerView.swift", + "Name": { + "comment": "AddGameView+Rows.swift:156", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "NX Library's copy of %@ goes to the Trash, so you can bring it back from there. Your original file stays where it is." + "value": "Name" } }, "it": { "stringUnit": { "state": "translated", - "value": "La copia di %@ di NX Library viene spostata nel Cestino: puoi ripristinarla da lì. Il file originale resta dov’è." + "value": "Nome" } }, "fr": { "stringUnit": { "state": "translated", - "value": "La copie de %@ utilisée par NX Library est placée dans la corbeille ; vous pourrez l’y récupérer. Votre fichier d’origine reste à son emplacement." + "value": "Nom" } }, "de": { "stringUnit": { "state": "translated", - "value": "Die NX Library-Kopie von %@ wird in den Papierkorb gelegt. Du kannst sie von dort zurückholen. Deine Originaldatei bleibt an ihrem Platz." + "value": "Name" } }, "es": { "stringUnit": { "state": "translated", - "value": "La copia de %@ de NX Library se mueve a la Papelera para que puedas recuperarla. Tu archivo original permanece en su ubicación." + "value": "Nombre" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A cópia de %@ do NX Library vai para o Lixo, de onde você poderá restaurá-la. Seu arquivo original permanece onde está." + "value": "Nome" } } } }, - "Name": { - "comment": "AddGameView+Rows.swift:156", + "Navigate Arcane.": { + "comment": "ControlsView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Name" + "value": "Navigate Arcane." } }, "it": { "stringUnit": { "state": "translated", - "value": "Nome" + "value": "Naviga in Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Nom" + "value": "Naviguer dans Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Name" + "value": "In Arcane navigieren." } }, "es": { "stringUnit": { "state": "translated", - "value": "Nombre" + "value": "Navega por Arcane." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Nome" + "value": "Navegue pelo Arcane." } } } }, - "Navigate NX Library.": { - "comment": "ControlsView.swift", + "Navigation": { + "comment": "SettingsSection.swift:16", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Navigate NX Library." + "value": "Navigation" } }, "it": { "stringUnit": { "state": "translated", - "value": "Naviga in NX Library." + "value": "Navigazione" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Naviguer dans NX Library." + "value": "Navigation" } }, "de": { "stringUnit": { "state": "translated", - "value": "In NX Library navigieren." + "value": "Navigation" } }, "es": { "stringUnit": { "state": "translated", - "value": "Navega por NX Library." + "value": "Navegación" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Navegue pelo NX Library." + "value": "Navegação" } } } }, - "Navigation": { - "comment": "SettingsSection.swift:16", + "Needed for NSP/XCI packages. Extracted folders do not use keys.": { + "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Navigation" + "value": "Needed for NSP/XCI packages. Extracted folders do not use keys." } }, "it": { "stringUnit": { "state": "translated", - "value": "Navigazione" + "value": "Necessario per i pacchetti NSP/XCI. Le cartelle estratte non usano chiavi." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Navigation" + "value": "Nécessaire pour les paquets NSP/XCI. Les dossiers extraits n’utilisent pas de clés." } }, "de": { "stringUnit": { "state": "translated", - "value": "Navigation" + "value": "Für NSP/XCI-Pakete erforderlich. Entpackte Ordner benötigen keine Schlüssel." } }, "es": { "stringUnit": { "state": "translated", - "value": "Navegación" + "value": "Necesario para paquetes NSP/XCI. Las carpetas extraídas no usan claves." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Navegação" + "value": "Necessário para pacotes NSP/XCI. Pastas extraídas não usam chaves." } } } }, - "Needed for NSP/XCI packages. Extracted folders do not use keys.": { - "comment": "SetupCheck.swift", + "Needs review": { + "comment": "Steam source management and native Mac library presentation.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Needed for NSP/XCI packages. Extracted folders do not use keys." + "value": "Needs review" } }, "it": { "stringUnit": { "state": "translated", - "value": "Necessario per i pacchetti NSP/XCI. Le cartelle estratte non usano chiavi." + "value": "Da controllare" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Nécessaire pour les paquets NSP/XCI. Les dossiers extraits n’utilisent pas de clés." + "value": "À vérifier" } }, "de": { "stringUnit": { "state": "translated", - "value": "Für NSP/XCI-Pakete erforderlich. Entpackte Ordner benötigen keine Schlüssel." + "value": "Prüfung erforderlich" } }, "es": { "stringUnit": { "state": "translated", - "value": "Necesario para paquetes NSP/XCI. Las carpetas extraídas no usan claves." + "value": "Requiere revisión" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Necessário para pacotes NSP/XCI. Pastas extraídas não usam chaves." + "value": "Requer revisão" } } } @@ -37084,47 +38209,6 @@ } } }, - "Newer Metal: turn on the override in Settings → Engine": { - "comment": "ToolchainGateCopy.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Newer Metal: turn on the override in Settings → Engine" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Metal più recente: ignora il controllo in Impostazioni → Motore" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Metal plus récent : activez la dérogation dans Réglages → Moteur" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Neueres Metal: Ausnahme unter Einstellungen → Engine aktivieren" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Metal más reciente: activa la excepción en Ajustes → Motor" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Metal mais recente: ative a exceção em Ajustes → Engine" - } - } - } - }, "Newest": { "comment": "ModCatalog.swift:62", "localizations": { @@ -37248,43 +38332,43 @@ } } }, - "Newest nxnative, not yet tested by NX Library. It usually works, but something may not. ": { + "Newest nxnative, not yet tested by Arcane. It usually works, but something may not. ": { "comment": "NewestEngine.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Newest nxnative, not yet tested by NX Library. It usually works, but something may not. " + "value": "Newest nxnative, not yet tested by Arcane. It usually works, but something may not. " } }, "it": { "stringUnit": { "state": "translated", - "value": "La versione più recente di nxnative, non ancora testata da NX Library. Di solito funziona, ma qualcosa potrebbe non funzionare. " + "value": "La versione più recente di nxnative, non ancora testata da Arcane. Di solito funziona, ma qualcosa potrebbe non funzionare. " } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le dernier nxnative, pas encore testé par NX Library. Il fonctionne généralement, mais des problèmes restent possibles. " + "value": "Le dernier nxnative, pas encore testé par Arcane. Il fonctionne généralement, mais des problèmes restent possibles. " } }, "de": { "stringUnit": { "state": "translated", - "value": "Neuestes nxnative, noch nicht von NX Library getestet. Es funktioniert in der Regel, aber manches möglicherweise nicht. " + "value": "Neuestes nxnative, noch nicht von Arcane getestet. Es funktioniert in der Regel, aber manches möglicherweise nicht. " } }, "es": { "stringUnit": { "state": "translated", - "value": "El nxnative más reciente, aún no probado por NX Library. Suele funcionar, pero algo podría fallar. " + "value": "El nxnative más reciente, aún no probado por Arcane. Suele funcionar, pero algo podría fallar. " } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "nxnative mais recente, ainda não testado pelo NX Library. Geralmente funciona, mas algo pode falhar. " + "value": "nxnative mais recente, ainda não testado pelo Arcane. Geralmente funciona, mas algo pode falhar. " } } } @@ -37535,47 +38619,6 @@ } } }, - "Nintendo Store descriptions, genres and links.": { - "comment": "SettingsLibrarySection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Nintendo Store descriptions, genres and links." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Descrizioni, generi e link del Nintendo Store." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Descriptions, genres et liens du Nintendo Store." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Beschreibungen, Genres und Links aus dem Nintendo Store." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Descripciones, géneros y enlaces de Nintendo Store." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Descrições, gêneros e links da Nintendo Store." - } - } - } - }, "Nintendo Store returned a response this app could not read.": { "comment": "NintendoStoreMetadata.swift", "localizations": { @@ -37658,43 +38701,43 @@ } } }, - "Nintendo Switch cryptographic keys required to decrypt game packages (NSP/XCI). NX Library stores a private copy with mode 0600 permissions; key values are never displayed or logged.": { + "Nintendo Switch cryptographic keys required to decrypt game packages (NSP/XCI). Arcane stores a private copy with mode 0600 permissions; key values are never displayed or logged.": { "comment": "SettingsEngineSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Nintendo Switch cryptographic keys required to decrypt game packages (NSP/XCI). NX Library stores a private copy with mode 0600 permissions; key values are never displayed or logged." + "value": "Nintendo Switch cryptographic keys required to decrypt game packages (NSP/XCI). Arcane stores a private copy with mode 0600 permissions; key values are never displayed or logged." } }, "it": { "stringUnit": { "state": "translated", - "value": "Chiavi crittografiche Nintendo Switch necessarie per decrittare i pacchetti di gioco (NSP/XCI). NX Library ne conserva una copia privata con permessi 0600; i valori delle chiavi non vengono mai mostrati né registrati nei log." + "value": "Chiavi crittografiche Nintendo Switch necessarie per decrittare i pacchetti di gioco (NSP/XCI). Arcane ne conserva una copia privata con permessi 0600; i valori delle chiavi non vengono mai mostrati né registrati nei log." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Clés cryptographiques Nintendo Switch nécessaires au déchiffrement des paquets de jeu (NSP/XCI). NX Library en conserve une copie privée avec des permissions 0600 ; les valeurs des clés ne sont jamais affichées ni inscrites dans les journaux." + "value": "Clés cryptographiques Nintendo Switch nécessaires au déchiffrement des paquets de jeu (NSP/XCI). Arcane en conserve une copie privée avec des permissions 0600 ; les valeurs des clés ne sont jamais affichées ni inscrites dans les journaux." } }, "de": { "stringUnit": { "state": "translated", - "value": "Kryptografische Nintendo Switch-Schlüssel zum Entschlüsseln von Spielpaketen (NSP/XCI). NX Library speichert eine private Kopie mit Zugriffsrechten 0600; Schlüsselwerte werden nie angezeigt oder protokolliert." + "value": "Kryptografische Nintendo Switch-Schlüssel zum Entschlüsseln von Spielpaketen (NSP/XCI). Arcane speichert eine private Kopie mit Zugriffsrechten 0600; Schlüsselwerte werden nie angezeigt oder protokolliert." } }, "es": { "stringUnit": { "state": "translated", - "value": "Claves criptográficas de Nintendo Switch necesarias para descifrar paquetes de juegos (NSP/XCI). NX Library guarda una copia privada con permisos 0600; los valores de las claves nunca se muestran ni se escriben en los registros." + "value": "Claves criptográficas de Nintendo Switch necesarias para descifrar paquetes de juegos (NSP/XCI). Arcane guarda una copia privada con permisos 0600; los valores de las claves nunca se muestran ni se escriben en los registros." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Chaves criptográficas do Nintendo Switch necessárias para descriptografar pacotes de jogos (NSP/XCI). O NX Library armazena uma cópia privada com permissões 0600; os valores das chaves nunca são exibidos nem registrados em logs." + "value": "Chaves criptográficas do Nintendo Switch necessárias para descriptografar pacotes de jogos (NSP/XCI). O Arcane armazena uma cópia privada com permissões 0600; os valores das chaves nunca são exibidos nem registrados em logs." } } } @@ -37863,6 +38906,47 @@ } } }, + "No achievements here yet.": { + "comment": "An Achievements filter with nothing in it.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No achievements here yet." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Ancora nessun obiettivo qui." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucun succès ici pour l'instant." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Hier noch keine Erfolge." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Aún no hay logros aquí." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhuma conquista aqui ainda." + } + } + } + }, "No backups": { "comment": "SavesPanel.swift", "localizations": { @@ -38765,84 +39849,84 @@ } } }, - "No mods for this game work with NX Library yet": { + "No mods for this game work with Arcane yet": { "comment": "GameBananaBandModel.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "No mods for this game work with NX Library yet" + "value": "No mods for this game work with Arcane yet" } }, "it": { "stringUnit": { "state": "translated", - "value": "Per questo gioco non ci sono ancora mod compatibili con NX Library" + "value": "Per questo gioco non ci sono ancora mod compatibili con Arcane" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Aucun mod de ce jeu n’est encore compatible avec NX Library" + "value": "Aucun mod de ce jeu n’est encore compatible avec Arcane" } }, "de": { "stringUnit": { "state": "translated", - "value": "Für dieses Spiel gibt es noch keine Mods, die mit NX Library funktionieren" + "value": "Für dieses Spiel gibt es noch keine Mods, die mit Arcane funktionieren" } }, "es": { "stringUnit": { "state": "translated", - "value": "Aún no hay mods de este juego compatibles con NX Library" + "value": "Aún no hay mods de este juego compatibles con Arcane" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Ainda não há mods deste jogo compatíveis com o NX Library" + "value": "Ainda não há mods deste jogo compatíveis com o Arcane" } } } }, - "No mods for your games work with NX Library yet.": { + "No mods for your games work with Arcane yet.": { "comment": "ModStorePage.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "No mods for your games work with NX Library yet." + "value": "No mods for your games work with Arcane yet." } }, "it": { "stringUnit": { "state": "translated", - "value": "Per i tuoi giochi non ci sono ancora mod compatibili con NX Library." + "value": "Per i tuoi giochi non ci sono ancora mod compatibili con Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Aucun mod pour vos jeux n’est encore compatible avec NX Library." + "value": "Aucun mod pour vos jeux n’est encore compatible avec Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Für deine Spiele gibt es noch keine Mods, die mit NX Library funktionieren." + "value": "Für deine Spiele gibt es noch keine Mods, die mit Arcane funktionieren." } }, "es": { "stringUnit": { "state": "translated", - "value": "Aún no hay mods para tus juegos compatibles con NX Library." + "value": "Aún no hay mods para tus juegos compatibles con Arcane." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Ainda não há mods para seus jogos compatíveis com o NX Library." + "value": "Ainda não há mods para seus jogos compatíveis com o Arcane." } } } @@ -39544,47 +40628,6 @@ } } }, - "Not checked": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Not checked" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Non verificato" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Non vérifié" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Nicht geprüft" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Sin comprobar" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Não verificado" - } - } - } - }, "Not connected": { "comment": "SettingsControllersSection.swift", "localizations": { @@ -40036,6 +41079,47 @@ } } }, + "Not unlocked": { + "comment": "An achievement's status before it is unlocked.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not unlocked" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non sbloccato" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Non débloqué" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nicht freigeschaltet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No desbloqueado" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não desbloqueada" + } + } + } + }, "Nothing changed yet.": { "comment": "SettingsSearchSection.swift", "localizations": { @@ -40405,207 +41489,207 @@ } } }, - "ONLINE · %@ · %@": { - "comment": "OnlineBrowsePanel.swift:147", + "One sync choice for all games, applied at next launch: Off, iCloud Drive or a folder you choose. Only the primary user and device save sync.": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "ONLINE · %@ · %@" + "value": "One sync choice for all games, applied at next launch: Off, iCloud Drive or a folder you choose. Only the primary user and device save sync." } }, "it": { "stringUnit": { "state": "translated", - "value": "ONLINE · %@ · %@" + "value": "Un’unica scelta di sincronizzazione per tutti i giochi, applicata al prossimo avvio: Disattivo, iCloud Drive o una cartella a tua scelta. Il cloud sincronizza solo i salvataggi dell’utente principale e del dispositivo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "EN LIGNE · %@ · %@" + "value": "Un choix de synchronisation pour tous les jeux, appliqué au prochain lancement : Désactivé, iCloud Drive ou un dossier de votre choix. Le cloud ne synchronise que les sauvegardes de l’utilisateur principal et de l’appareil." } }, "de": { "stringUnit": { "state": "translated", - "value": "ONLINE · %@ · %@" + "value": "Eine Synchronisierungswahl für alle Spiele, angewendet beim nächsten Spielstart: Aus, iCloud Drive oder ein selbst gewählter Ordner. Die Cloud synchronisiert nur den Spielstand des Hauptbenutzers und den Gerätespielstand." } }, "es": { "stringUnit": { "state": "translated", - "value": "EN LÍNEA · %@ · %@" + "value": "Una opción de sincronización para todos los juegos, aplicada en el próximo inicio: Desactivado, iCloud Drive o una carpeta que elijas. La nube solo sincroniza las partidas del usuario principal y del dispositivo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "ON-LINE · %@ · %@" + "value": "Uma opção de sincronização para todos os jogos, aplicada na próxima abertura: Desativado, iCloud Drive ou uma pasta à sua escolha. A nuvem sincroniza apenas os salvamentos do usuário principal e do dispositivo." } } } }, - "Off": { - "comment": "GameOptionsPresentation.swift", + "ONLINE · %@ · %@": { + "comment": "OnlineBrowsePanel.swift:147", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Off" + "value": "ONLINE · %@ · %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "Disattivo" + "value": "ONLINE · %@ · %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Désactivé" + "value": "EN LIGNE · %@ · %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "Aus" + "value": "ONLINE · %@ · %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "Desactivado" + "value": "EN LÍNEA · %@ · %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Desativado" + "value": "ON-LINE · %@ · %@" } } } }, - "Off keeps every cheat from running, whatever is switched on.": { - "comment": "CheatsPanel.swift:284", + "Off": { + "comment": "GameOptionsPresentation.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Off keeps every cheat from running, whatever is switched on." + "value": "Off" } }, "it": { "stringUnit": { "state": "translated", - "value": "Se disattivato, impedisce l’esecuzione di tutti i trucchi, anche di quelli attivi." + "value": "Disattivo" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Désactivé empêche l’exécution de tous les codes de triche, quels que soient ceux activés individuellement." + "value": "Désactivé" } }, "de": { "stringUnit": { "state": "translated", - "value": "„Aus“ verhindert die Ausführung aller Cheats, unabhängig davon, welche einzeln aktiviert sind." + "value": "Aus" } }, "es": { "stringUnit": { "state": "translated", - "value": "Desactivado impide ejecutar cualquier truco, aunque esté activado individualmente." + "value": "Desactivado" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Desativado impede a execução de todas as trapaças, independentemente das que estiverem ativadas." + "value": "Desativado" } } } }, - "Older Metal · override on": { - "comment": "ToolchainGateCopy.swift", + "Off keeps every cheat from running, whatever is switched on.": { + "comment": "CheatsPanel.swift:284", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Older Metal · override on" + "value": "Off keeps every cheat from running, whatever is switched on." } }, "it": { "stringUnit": { "state": "translated", - "value": "Metal precedente · controllo ignorato" + "value": "Se disattivato, impedisce l’esecuzione di tutti i trucchi, anche di quelli attivi." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Metal plus ancien · dérogation activée" + "value": "Désactivé empêche l’exécution de tous les codes de triche, quels que soient ceux activés individuellement." } }, "de": { "stringUnit": { "state": "translated", - "value": "Älteres Metal · Ausnahme aktiv" + "value": "„Aus“ verhindert die Ausführung aller Cheats, unabhängig davon, welche einzeln aktiviert sind." } }, "es": { "stringUnit": { "state": "translated", - "value": "Metal anterior · excepción activada" + "value": "Desactivado impide ejecutar cualquier truco, aunque esté activado individualmente." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Metal mais antigo · exceção ativada" + "value": "Desativado impede a execução de todas as trapaças, independentemente das que estiverem ativadas." } } } }, - "Older Metal: update it, or use the override in Settings → Engine": { + "Older Metal · override on": { "comment": "ToolchainGateCopy.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Older Metal: update it, or use the override in Settings → Engine" + "value": "Older Metal · override on" } }, "it": { "stringUnit": { "state": "translated", - "value": "Metal precedente: aggiornalo oppure ignora il controllo in Impostazioni → Motore" + "value": "Metal precedente · controllo ignorato" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Metal plus ancien : mettez-le à jour ou utilisez la dérogation dans Réglages → Moteur" + "value": "Metal plus ancien · dérogation activée" } }, "de": { "stringUnit": { "state": "translated", - "value": "Älteres Metal: aktualisieren oder Ausnahme unter Einstellungen → Engine verwenden" + "value": "Älteres Metal · Ausnahme aktiv" } }, "es": { "stringUnit": { "state": "translated", - "value": "Metal anterior: actualízalo o usa la excepción en Ajustes → Motor" + "value": "Metal anterior · excepción activada" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Metal mais antigo: atualize ou use a exceção em Ajustes → Engine" + "value": "Metal mais antigo · exceção ativada" } } } @@ -40979,43 +42063,43 @@ } } }, - "Only here changes the image inside NX Library. Use on the Mac also shows it in Finder and the Dock. Automatic uses the game's own icon, then an online image if available. Changing the image keeps this location choice.": { + "Only here changes the image inside Arcane. Use on the Mac also shows it in Finder and the Dock. Automatic uses the game's own icon, then an online image if available. Changing the image keeps this location choice.": { "comment": "ChangeArtworkView.swift:192", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Only here changes the image inside NX Library. Use on the Mac also shows it in Finder and the Dock. Automatic uses the game's own icon, then an online image if available. Changing the image keeps this location choice." + "value": "Only here changes the image inside Arcane. Use on the Mac also shows it in Finder and the Dock. Automatic uses the game's own icon, then an online image if available. Changing the image keeps this location choice." } }, "it": { "stringUnit": { "state": "translated", - "value": "Solo qui cambia l’immagine all’interno di NX Library. Usa sul Mac la mostra anche nel Finder e nel Dock. Automatico usa l’icona del gioco, poi un’immagine online se disponibile. Cambiare immagine mantiene questa scelta di posizione." + "value": "Solo qui cambia l’immagine all’interno di Arcane. Usa sul Mac la mostra anche nel Finder e nel Dock. Automatico usa l’icona del gioco, poi un’immagine online se disponibile. Cambiare immagine mantiene questa scelta di posizione." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Uniquement ici modifie l’image dans NX Library. Utiliser sur le Mac l’affiche aussi dans le Finder et le Dock. Automatique utilise l’icône du jeu, puis une image en ligne si disponible. Changer l’image conserve ce choix d’emplacement." + "value": "Uniquement ici modifie l’image dans Arcane. Utiliser sur le Mac l’affiche aussi dans le Finder et le Dock. Automatique utilise l’icône du jeu, puis une image en ligne si disponible. Changer l’image conserve ce choix d’emplacement." } }, "de": { "stringUnit": { "state": "translated", - "value": "„Nur hier“ ändert das Bild innerhalb von NX Library. „Auf dem Mac verwenden“ zeigt es auch im Finder und im Dock. „Automatisch“ verwendet das spieleigene Symbol und danach ein Online-Bild, falls verfügbar. Ein Bildwechsel behält diese Ortsauswahl bei." + "value": "„Nur hier“ ändert das Bild innerhalb von Arcane. „Auf dem Mac verwenden“ zeigt es auch im Finder und im Dock. „Automatisch“ verwendet das spieleigene Symbol und danach ein Online-Bild, falls verfügbar. Ein Bildwechsel behält diese Ortsauswahl bei." } }, "es": { "stringUnit": { "state": "translated", - "value": "Solo aquí cambia la imagen dentro de NX Library. Usar en el Mac también la muestra en el Finder y el Dock. Automático usa el icono propio del juego y, si no está disponible, una imagen en línea. Cambiar la imagen conserva esta elección de ubicación." + "value": "Solo aquí cambia la imagen dentro de Arcane. Usar en el Mac también la muestra en el Finder y el Dock. Automático usa el icono propio del juego y, si no está disponible, una imagen en línea. Cambiar la imagen conserva esta elección de ubicación." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Só aqui altera a imagem dentro do NX Library. Usar no Mac também a exibe no Finder e no Dock. Automático usa o ícone do próprio jogo e, se não houver, uma imagem on-line disponível. Alterar a imagem mantém esta escolha de local." + "value": "Só aqui altera a imagem dentro do Arcane. Usar no Mac também a exibe no Finder e no Dock. Automático usa o ícone do próprio jogo e, se não houver, uma imagem on-line disponível. Alterar a imagem mantém esta escolha de local." } } } @@ -41266,43 +42350,43 @@ } } }, - "Open NX Library in fullscreen. Applies at the next launch.": { + "Open Arcane in fullscreen. Applies at the next launch.": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Open NX Library in fullscreen. Applies at the next launch." + "value": "Open Arcane in fullscreen. Applies at the next launch." } }, "it": { "stringUnit": { "state": "translated", - "value": "Apri NX Library a schermo intero. Si applica al prossimo avvio." + "value": "Apri Arcane a schermo intero. Si applica al prossimo avvio." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Ouvrir NX Library en plein écran. S’applique au prochain lancement." + "value": "Ouvrir Arcane en plein écran. S’applique au prochain lancement." } }, "de": { "stringUnit": { "state": "translated", - "value": "NX Library im Vollbild öffnen. Gilt beim nächsten Start." + "value": "Arcane im Vollbild öffnen. Gilt beim nächsten Start." } }, "es": { "stringUnit": { "state": "translated", - "value": "Abre NX Library en pantalla completa. Se aplica en el próximo inicio." + "value": "Abre Arcane en pantalla completa. Se aplica en el próximo inicio." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Abra o NX Library em tela cheia. Aplicado na próxima abertura." + "value": "Abra o Arcane em tela cheia. Aplicado na próxima abertura." } } } @@ -41717,6 +42801,47 @@ } } }, + "Open library folder": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open library folder" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Apri cartella della libreria" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ouvrir le dossier de la bibliothèque" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bibliotheksordner öffnen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Abrir carpeta de la biblioteca" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Abrir pasta da biblioteca" + } + } + } + }, "Open log": { "comment": "GameOptionsPresentation.swift", "localizations": { @@ -41922,84 +43047,43 @@ } } }, - "Open save folder": { - "comment": "BuildSourcesPanel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Open save folder" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Apri cartella dei salvataggi" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Ouvrir le dossier des sauvegardes" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Spielstandordner öffnen" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Abrir carpeta de partidas" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Abrir pasta de dados salvos" - } - } - } - }, - "Open the Setup check: what NX Library needs and what is ready.": { + "Open the Setup check: what Arcane needs and what is ready.": { "comment": "SettingsStartUpSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Open the Setup check: what NX Library needs and what is ready." + "value": "Open the Setup check: what Arcane needs and what is ready." } }, "it": { "stringUnit": { "state": "translated", - "value": "Apri il controllo di configurazione: cosa serve a NX Library e cosa è pronto." + "value": "Apri il controllo di configurazione: cosa serve a Arcane e cosa è pronto." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Ouvrir la vérification de configuration : ce dont NX Library a besoin et ce qui est prêt." + "value": "Ouvrir la vérification de configuration : ce dont Arcane a besoin et ce qui est prêt." } }, "de": { "stringUnit": { "state": "translated", - "value": "Einrichtungsprüfung öffnen: Was NX Library benötigt und was bereit ist." + "value": "Einrichtungsprüfung öffnen: Was Arcane benötigt und was bereit ist." } }, "es": { "stringUnit": { "state": "translated", - "value": "Abre la comprobación inicial: qué necesita NX Library y qué está listo." + "value": "Abre la comprobación inicial: qué necesita Arcane y qué está listo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Abra a verificação de configuração: o que o NX Library precisa e o que já está pronto." + "value": "Abra a verificação de configuração: o que o Arcane precisa e o que já está pronto." } } } @@ -42168,6 +43252,47 @@ } } }, + "Open the game’s Steam store page.": { + "comment": "CatalogGameOptions.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open the game’s Steam store page." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Apri la pagina del gioco nello store di Steam." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ouvrir la page du jeu sur le magasin Steam." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Öffne die Seite des Spiels im Steam-Shop." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Abre la página del juego en la tienda de Steam." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Abra a página do jogo na loja Steam." + } + } + } + }, "Open the log, or copy diagnostics for a bug report.": { "comment": "PortingFailureReason.swift", "localizations": { @@ -42414,6 +43539,47 @@ } } }, + "Optional contributions support development and maintenance.": { + "comment": "SettingsAboutSection.swift", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Freiwillige Beiträge unterstützen die Entwicklung und Pflege der App." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Optional contributions support development and maintenance." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Las aportaciones voluntarias apoyan el desarrollo y el mantenimiento de la app." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les contributions volontaires soutiennent le développement et la maintenance de l’app." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Un contributo facoltativo per lo sviluppo e la manutenzione dell’app." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Contribuições voluntárias ajudam no desenvolvimento e na manutenção do app." + } + } + } + }, "Optional: %@ for building.": { "comment": "GameFoldersCopy.swift", "localizations": { @@ -42578,6 +43744,47 @@ } } }, + "Order: %@": { + "comment": "Achievements screen, VoiceOver: the current list order, e.g. \"Order: Rarest first\".", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Order: %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Ordine: %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ordre : %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Reihenfolge: %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Orden: %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Ordem: %@" + } + } + } + }, "Other settings this build offers.": { "comment": "GameOptionsPresentation.swift", "localizations": { @@ -42865,13 +44072,13 @@ } } }, - "PLAY TIME": { - "comment": "DetailsBands.swift:66", + "PLAYTIME": { + "comment": "DetailsTopBlock.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "PLAY TIME" + "value": "PLAYTIME" } }, "it": { @@ -42906,84 +44113,83 @@ } } }, - "PLAYTIME": { - "comment": "DetailsTopBlock.swift", + "PNG or JPEG": { + "comment": "ChangeArtworkView.swift:450", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "PLAYTIME" + "value": "PNG or JPEG" } }, "it": { "stringUnit": { "state": "translated", - "value": "TEMPO DI GIOCO" + "value": "PNG o JPEG" } }, "fr": { "stringUnit": { "state": "translated", - "value": "TEMPS DE JEU" + "value": "PNG ou JPEG" } }, "de": { "stringUnit": { "state": "translated", - "value": "SPIELZEIT" + "value": "PNG oder JPEG" } }, "es": { "stringUnit": { "state": "translated", - "value": "TIEMPO DE JUEGO" + "value": "PNG o JPEG" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "TEMPO DE JOGO" + "value": "PNG ou JPEG" } } } }, - "PNG or JPEG": { - "comment": "ChangeArtworkView.swift:450", + "Preparing the first launch": { "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "PNG or JPEG" + "value": "Preparing the first launch" } }, "it": { "stringUnit": { "state": "translated", - "value": "PNG o JPEG" + "value": "Preparazione del primo avvio" } }, "fr": { "stringUnit": { "state": "translated", - "value": "PNG ou JPEG" + "value": "Préparation du premier lancement" } }, "de": { "stringUnit": { "state": "translated", - "value": "PNG oder JPEG" + "value": "Erster Start wird vorbereitet" } }, "es": { "stringUnit": { "state": "translated", - "value": "PNG o JPEG" + "value": "Preparando el primer inicio" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "PNG ou JPEG" + "value": "Preparando a primeira inicialização" } } } @@ -43643,43 +44849,43 @@ } } }, - "Play time is tracked only for launches from NX Library. Not affiliated with Nintendo.": { + "Play time is tracked only for launches from Arcane. Not affiliated with Nintendo.": { "comment": "SettingsAboutSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Play time is tracked only for launches from NX Library. Not affiliated with Nintendo." + "value": "Play time is tracked only for launches from Arcane. Not affiliated with Nintendo." } }, "it": { "stringUnit": { "state": "translated", - "value": "Il tempo di gioco viene registrato solo per gli avvii da NX Library. Non affiliata a Nintendo." + "value": "Il tempo di gioco viene registrato solo per gli avvii da Arcane. Non affiliata a Nintendo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le temps de jeu est comptabilisé uniquement pour les lancements depuis NX Library. Sans affiliation avec Nintendo." + "value": "Le temps de jeu est comptabilisé uniquement pour les lancements depuis Arcane. Sans affiliation avec Nintendo." } }, "de": { "stringUnit": { "state": "translated", - "value": "Spielzeit wird nur bei Starts über NX Library erfasst. Keine Verbindung zu Nintendo." + "value": "Spielzeit wird nur bei Starts über Arcane erfasst. Keine Verbindung zu Nintendo." } }, "es": { "stringUnit": { "state": "translated", - "value": "El tiempo de juego solo se registra al iniciar desde NX Library. Sin afiliación con Nintendo." + "value": "El tiempo de juego solo se registra al iniciar desde Arcane. Sin afiliación con Nintendo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O tempo de jogo é registrado apenas quando o jogo é aberto pelo NX Library. Sem afiliação com a Nintendo." + "value": "O tempo de jogo é registrado apenas quando o jogo é aberto pelo Arcane. Sem afiliação com a Nintendo." } } } @@ -43725,47 +44931,6 @@ } } }, - "Plays a short opening with the boot sound when the app opens.": { - "comment": "SettingsCatalog.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Plays a short opening with the boot sound when the app opens." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Riproduce una breve introduzione con il suono di avvio all’apertura dell’app." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Affiche une courte introduction accompagnée du son de démarrage à l’ouverture de l’app." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Spielt beim Öffnen der App ein kurzes Intro mit Startklang ab." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Reproduce una breve animación con el sonido de arranque al abrir la app." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Reproduz uma breve abertura com o som de inicialização ao abrir o app." - } - } - } - }, "Plays a short sound when you move, select, go back or launch a game.": { "comment": "SettingsCatalog.swift", "localizations": { @@ -44463,6 +45628,47 @@ } } }, + "Preparing your development library": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Preparing your development library" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Preparazione della libreria di sviluppo" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Préparation de votre bibliothèque de développement" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Entwicklungsbibliothek wird vorbereitet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Preparando tu biblioteca de desarrollo" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Preparando sua biblioteca de desenvolvimento" + } + } + } + }, "Press a button to join": { "comment": "Engine game setting presentation; never translate env keys or values.", "localizations": { @@ -44791,43 +45997,43 @@ } } }, - "Python 3.14 with its modules, zstd and glslang, inside NX Library.": { + "Python 3.14 with its modules, zstd and glslang, inside Arcane.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Python 3.14 with its modules, zstd and glslang, inside NX Library." + "value": "Python 3.14 with its modules, zstd and glslang, inside Arcane." } }, "it": { "stringUnit": { "state": "translated", - "value": "Python 3.14 con i suoi moduli, zstd e glslang, all’interno di NX Library." + "value": "Python 3.14 con i suoi moduli, zstd e glslang, all’interno di Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Python 3.14 avec ses modules, zstd et glslang, intégrés à NX Library." + "value": "Python 3.14 avec ses modules, zstd et glslang, intégrés à Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Python 3.14 mit seinen Modulen, zstd und glslang, in NX Library enthalten." + "value": "Python 3.14 mit seinen Modulen, zstd und glslang, in Arcane enthalten." } }, "es": { "stringUnit": { "state": "translated", - "value": "Python 3.14 con sus módulos, zstd y glslang, dentro de NX Library." + "value": "Python 3.14 con sus módulos, zstd y glslang, dentro de Arcane." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Python 3.14 com seus módulos, zstd e glslang, dentro do NX Library." + "value": "Python 3.14 com seus módulos, zstd e glslang, dentro do Arcane." } } } @@ -44914,88 +46120,6 @@ } } }, - "Python included": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Python included" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Python incluso" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Python intégré" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Python enthalten" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Python incluido" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Python incluído" - } - } - } - }, - "Python missing": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Python missing" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Python non disponibile" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Python manquant" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Python fehlt" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Falta Python" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Python ausente" - } - } - } - }, "Python venv": { "comment": "CompatibilityChecker.swift", "localizations": { @@ -45037,47 +46161,6 @@ } } }, - "Python venv ready": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Python venv ready" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Venv Python pronto" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Environnement venv Python prêt" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Python-venv bereit" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Entorno virtual de Python listo" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "venv do Python pronto" - } - } - } - }, "Q": { "comment": "ButtonPrompts.swift:39", "localizations": { @@ -45283,47 +46366,6 @@ } } }, - "RANK": { - "comment": "DetailsBands.swift:72", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "RANK" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "POSIZIONE" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "RANG" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "RANG" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "POSICIÓN" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "POSIÇÃO" - } - } - } - }, "RELEASED": { "comment": "DetailsTopBlock.swift", "localizations": { @@ -45365,125 +46407,84 @@ } } }, - "Re-check": { - "comment": "SettingsStartUpSection.swift", + "Rarest first": { + "comment": "Achievements screen: the list order (Y), fewest players first.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Re-check" + "value": "Rarest first" } }, "it": { "stringUnit": { "state": "translated", - "value": "Ricontrolla" + "value": "Prima i più rari" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Revérifier" + "value": "Les plus rares d’abord" } }, "de": { "stringUnit": { "state": "translated", - "value": "Erneut prüfen" + "value": "Seltenste zuerst" } }, "es": { "stringUnit": { "state": "translated", - "value": "Volver a comprobar" + "value": "Más raros primero" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Verificar novamente" + "value": "Mais raras primeiro" } } } }, - "Re-check the environment and build requirements.": { - "comment": "SettingsCatalog.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Re-check the environment and build requirements." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Ricontrolla l’ambiente e i requisiti di compilazione." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Revérifier l’environnement et les prérequis de compilation." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Umgebung und Build-Voraussetzungen erneut prüfen." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Vuelve a comprobar el entorno y los requisitos de compilación." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Verifique novamente o ambiente e os requisitos de compilação." - } - } - } - }, - "Re-run the environment and compatibility checks.": { + "Re-check": { "comment": "SettingsStartUpSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Re-run the environment and compatibility checks." + "value": "Re-check" } }, "it": { "stringUnit": { "state": "translated", - "value": "Ripeti i controlli dell’ambiente e della compatibilità." + "value": "Ricontrolla" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Relancer les vérifications de l’environnement et de la compatibilité." + "value": "Revérifier" } }, "de": { "stringUnit": { "state": "translated", - "value": "Umgebungs- und Kompatibilitätsprüfung erneut ausführen." + "value": "Erneut prüfen" } }, "es": { "stringUnit": { "state": "translated", - "value": "Vuelve a ejecutar las comprobaciones del entorno y de compatibilidad." + "value": "Volver a comprobar" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Execute novamente as verificações de ambiente e compatibilidade." + "value": "Verificar novamente" } } } @@ -45529,47 +46530,6 @@ } } }, - "Readiness": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Readiness" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Stato di preparazione" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "État de préparation" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Bereitschaft" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Estado de preparación" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Prontidão" - } - } - } - }, "Reading the folder…": { "comment": "AddGameView+Rows.swift", "localizations": { @@ -45652,43 +46612,43 @@ } } }, - "Ready to build and play": { - "comment": "SettingsStartUpSection.swift", + "Ready to check Steam.": { + "comment": "Steam source management and native Mac library presentation.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Ready to build and play" + "value": "Ready to check Steam." } }, "it": { "stringUnit": { "state": "translated", - "value": "Pronto per compilare e giocare" + "value": "Pronto per controllare Steam." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Prêt à compiler et à jouer" + "value": "Prêt à vérifier Steam." } }, "de": { "stringUnit": { "state": "translated", - "value": "Bereit zum Erstellen und Spielen" + "value": "Bereit, Steam zu prüfen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Listo para compilar y jugar" + "value": "Listo para revisar Steam." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Pronto para compilar e jogar" + "value": "Pronto para verificar o Steam." } } } @@ -45817,7 +46777,7 @@ } }, "Rebuild": { - "comment": "BuildSourcesPanel.swift", + "comment": "Details panel and Options", "localizations": { "en": { "stringUnit": { @@ -45980,6 +46940,47 @@ } } }, + "Recently unlocked": { + "comment": "Achievements screen: title of the strip of the newest unlocked achievement icons.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Recently unlocked" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Sbloccati di recente" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Débloqués récemment" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Kürzlich freigeschaltet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Desbloqueados recientemente" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Desbloqueadas recentemente" + } + } + } + }, "Recently updated": { "comment": "ModCatalog.swift", "localizations": { @@ -46267,6 +47268,47 @@ } } }, + "Refresh Steam": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Refresh Steam" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Aggiorna Steam" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Actualiser Steam" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam aktualisieren" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Actualizar Steam" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Atualizar Steam" + } + } + } + }, "Refresh library at launch": { "comment": "SettingsCatalog.swift", "localizations": { @@ -46308,6 +47350,47 @@ } } }, + "Refresh the Steam source or check the installation in Steam.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Refresh the Steam source or check the installation in Steam." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Aggiorna la fonte Steam o controlla l’installazione in Steam." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Actualisez la source Steam ou vérifiez l’installation dans Steam." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Aktualisiere die Steam-Quelle oder prüfe die Installation in Steam." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Actualiza la fuente de Steam o revisa la instalación en Steam." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Atualize a fonte Steam ou verifique a instalação no Steam." + } + } + } + }, "Region": { "comment": "Language/region preferences and existing library filters.", "localizations": { @@ -46390,43 +47473,43 @@ } } }, - "Reinstall NX Library so the porting uses its own arm64 Python.": { + "Reinstall Arcane so the porting uses its own arm64 Python.": { "comment": "PortingFailureReason.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Reinstall NX Library so the porting uses its own arm64 Python." + "value": "Reinstall Arcane so the porting uses its own arm64 Python." } }, "it": { "stringUnit": { "state": "translated", - "value": "Reinstalla NX Library affinché la creazione dell’app per Mac usi il Python arm64 incluso." + "value": "Reinstalla Arcane affinché la creazione dell’app per Mac usi il Python arm64 incluso." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Réinstallez NX Library pour que la création de l’app Mac utilise son propre Python arm64." + "value": "Réinstallez Arcane pour que la création de l’app Mac utilise son propre Python arm64." } }, "de": { "stringUnit": { "state": "translated", - "value": "Installiere NX Library erneut, damit zur App-Erstellung das eigene arm64-Python verwendet wird." + "value": "Installiere Arcane erneut, damit zur App-Erstellung das eigene arm64-Python verwendet wird." } }, "es": { "stringUnit": { "state": "translated", - "value": "Reinstala NX Library para que la compilación use su propio Python arm64." + "value": "Reinstala Arcane para que la compilación use su propio Python arm64." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Reinstale o NX Library para que a compilação use o Python arm64 incluído no app." + "value": "Reinstale o Arcane para que a compilação use o Python arm64 incluído no app." } } } @@ -47773,6 +48856,119 @@ } } }, + "Restore backup (%lld games)": { + "comment": "Explicit restore of the offered catalog backup; original damaged file is retained.", + "localizations": { + "en": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Restore backup (%lld game)" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Restore backup (%lld games)" + } + } + } + } + }, + "it": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Ripristina backup (%lld gioco)" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Ripristina backup (%lld giochi)" + } + } + } + } + }, + "fr": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Restaurer la sauvegarde (%lld jeu)" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Restaurer la sauvegarde (%lld jeux)" + } + } + } + } + }, + "de": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Sicherung wiederherstellen (%lld Spiel)" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Sicherung wiederherstellen (%lld Spiele)" + } + } + } + } + }, + "es": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Restaurar copia (%lld juego)" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Restaurar copia (%lld juegos)" + } + } + } + } + }, + "pt-BR": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Restaurar backup (%lld jogo)" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Restaurar backup (%lld jogos)" + } + } + } + } + } + } + }, "Restore last game": { "comment": "SettingsCatalog.swift", "localizations": { @@ -48101,207 +49297,207 @@ } } }, - "Return / Space · ": { - "comment": "ControlsView.swift:47", + "Retry saving library": { + "comment": "Available while a finished build outcome is waiting for its catalog save.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Return / Space · " + "value": "Retry saving library" } }, "it": { "stringUnit": { "state": "translated", - "value": "Invio / Spazio · " + "value": "Riprova a salvare la libreria" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Retour / Espace · " + "value": "Réessayer d’enregistrer la bibliothèque" } }, "de": { "stringUnit": { "state": "translated", - "value": "Return / Leertaste · " + "value": "Bibliothek erneut speichern" } }, "es": { "stringUnit": { "state": "translated", - "value": "Retorno / Espacio · " + "value": "Reintentar guardar la biblioteca" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Return / Espaço · " + "value": "Tentar salvar a biblioteca novamente" } } } }, - "Return · Tab": { - "comment": "ControlsView.swift:35", + "Return / Space · ": { + "comment": "ControlsView.swift:47", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Return · Tab" + "value": "Return / Space · " } }, "it": { "stringUnit": { "state": "translated", - "value": "Invio · Tab" + "value": "Invio / Spazio · " } }, "fr": { "stringUnit": { "state": "translated", - "value": "Retour · Tab" + "value": "Retour / Espace · " } }, "de": { "stringUnit": { "state": "translated", - "value": "Return · Tab" + "value": "Return / Leertaste · " } }, "es": { "stringUnit": { "state": "translated", - "value": "Retorno · Tabulador" + "value": "Retorno / Espacio · " } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Return · Tab" + "value": "Return / Espaço · " } } } }, - "Returning to the tested engine…": { - "comment": "SetupCheckModel.swift", + "Return · Tab": { + "comment": "ControlsView.swift:35", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Returning to the tested engine…" + "value": "Return · Tab" } }, "it": { "stringUnit": { "state": "translated", - "value": "Ritorno al motore testato…" + "value": "Invio · Tab" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Retour au moteur testé…" + "value": "Retour · Tab" } }, "de": { "stringUnit": { "state": "translated", - "value": "Zur getesteten Engine wird zurückgekehrt …" + "value": "Return · Tab" } }, "es": { "stringUnit": { "state": "translated", - "value": "Volviendo al motor probado…" + "value": "Retorno · Tabulador" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Voltando à engine testada…" + "value": "Return · Tab" } } } }, - "Reveal": { - "comment": "SettingsEngineSection.swift", + "Returning to the tested engine…": { + "comment": "SetupCheckModel.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Reveal" + "value": "Returning to the tested engine…" } }, "it": { "stringUnit": { "state": "translated", - "value": "Mostra nel Finder" + "value": "Ritorno al motore testato…" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Afficher" + "value": "Retour au moteur testé…" } }, "de": { "stringUnit": { "state": "translated", - "value": "Im Finder zeigen" + "value": "Zur getesteten Engine wird zurückgekehrt …" } }, "es": { "stringUnit": { "state": "translated", - "value": "Mostrar" + "value": "Volviendo al motor probado…" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Mostrar" + "value": "Voltando à engine testada…" } } } }, - "Reveal app in Finder": { - "comment": "BuildSourcesPanel.swift", + "Reveal": { + "comment": "SettingsEngineSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Reveal app in Finder" + "value": "Reveal" } }, "it": { "stringUnit": { "state": "translated", - "value": "Mostra app nel Finder" + "value": "Mostra nel Finder" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Afficher l’app dans le Finder" + "value": "Afficher" } }, "de": { "stringUnit": { "state": "translated", - "value": "App im Finder zeigen" + "value": "Im Finder zeigen" } }, "es": { "stringUnit": { "state": "translated", - "value": "Mostrar app en el Finder" + "value": "Mostrar" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Mostrar app no Finder" + "value": "Mostrar" } } } @@ -48511,6 +49707,47 @@ } } }, + "Review installations": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Review installations" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Controlla le installazioni" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Vérifier les installations" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Installationen prüfen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Revisar instalaciones" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Revisar instalações" + } + } + } + }, "Right stick": { "comment": "ControlsView.swift:37", "localizations": { @@ -48839,6 +50076,46 @@ } } }, + "Some pipelines could not be prepared during porting. The game will prepare them on its first start, which can take longer. ": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Some pipelines could not be prepared during porting. The game will prepare them on its first start, which can take longer. " + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile preparare alcune pipeline durante il porting. Il gioco le preparerà al primo avvio, che potrà richiedere più tempo. " + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Certains pipelines n’ont pas pu être préparés pendant le portage. Le jeu les préparera au premier lancement, qui pourra prendre plus de temps. " + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Einige Pipelines konnten beim Portieren nicht vorbereitet werden. Das Spiel bereitet sie beim ersten Start vor, der dadurch länger dauern kann. " + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron preparar algunas canalizaciones durante la conversión. El juego las preparará en su primer inicio, que puede tardar más. " + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível preparar alguns pipelines durante a conversão. O jogo os preparará na primeira inicialização, que poderá demorar mais. " + } + } + } + }, "SPIRV-Cross Metal Shading Language compiler": { "comment": "SettingsAboutSection.swift:19", "localizations": { @@ -49536,6 +50813,47 @@ } } }, + "Scan stopped. Refresh when you are ready.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Scan stopped. Refresh when you are ready." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Scansione interrotta. Aggiorna quando vuoi." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Analyse arrêtée. Actualisez quand vous le souhaitez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Suche angehalten. Aktualisiere, wenn du bereit bist." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Exploración detenida. Actualiza cuando quieras." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Busca interrompida. Atualize quando quiser." + } + } + } + }, "Scanning game apps…": { "comment": "SettingsLibrarySection.swift", "localizations": { @@ -49659,6 +50977,47 @@ } } }, + "Screen-shaped art, then Steam": { + "comment": "ChangeArtworkView.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Screen-shaped art, then Steam" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Immagini in formato schermo, poi Steam" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Images au format écran, puis Steam" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bilder im Bildschirmformat, dann Steam" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Imágenes con forma de pantalla, luego Steam" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Imagens no formato da tela, depois o Steam" + } + } + } + }, "Screenshot %@": { "comment": "SpotlightScreenshotStrip.swift", "localizations": { @@ -49906,7 +51265,7 @@ } }, "Search Nintendo Store": { - "comment": "BuildSourcesPanel.swift", + "comment": "GameOptionsPresentation.swift", "localizations": { "en": { "stringUnit": { @@ -50151,43 +51510,43 @@ } } }, - "See how this NX Library's engine compares with seedds/nxnative main.": { + "See how this version's engine compares with seedds/nxnative main.": { "comment": "SettingsEngineSection.swift:256", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "See how this NX Library's engine compares with seedds/nxnative main." + "value": "See how this version's engine compares with seedds/nxnative main." } }, "it": { "stringUnit": { "state": "translated", - "value": "Confronta il motore di questa NX Library con seedds/nxnative main." + "value": "Confronta il motore di questa versione di Arcane con seedds/nxnative main." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Comparer le moteur de cette version de NX Library avec main de seedds/nxnative." + "value": "Comparer le moteur de cette version d’Arcane avec main de seedds/nxnative." } }, "de": { "stringUnit": { "state": "translated", - "value": "Vergleiche die Engine dieser NX Library-Version mit seedds/nxnative main." + "value": "Vergleiche die Engine dieser Arcane-Version mit seedds/nxnative main." } }, "es": { "stringUnit": { "state": "translated", - "value": "Compara el motor de este NX Library con main de seedds/nxnative." + "value": "Compara el motor de este Arcane con main de seedds/nxnative." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Veja como a engine deste NX Library se compara ao main de seedds/nxnative." + "value": "Veja como a engine deste Arcane se compara ao main de seedds/nxnative." } } } @@ -50397,43 +51756,43 @@ } } }, - "Selene is a Playnite theme for Windows. No Selene name, logo, wallpaper, avatar or sound is used as NX Library branding; this is a visual adaptation in SwiftUI.": { + "Selene is a Playnite theme for Windows. No Selene name, logo, wallpaper, avatar or sound is used as Arcane branding; this is a visual adaptation in SwiftUI.": { "comment": "SettingsAboutSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Selene is a Playnite theme for Windows. No Selene name, logo, wallpaper, avatar or sound is used as NX Library branding; this is a visual adaptation in SwiftUI." + "value": "Selene is a Playnite theme for Windows. No Selene name, logo, wallpaper, avatar or sound is used as Arcane branding; this is a visual adaptation in SwiftUI." } }, "it": { "stringUnit": { "state": "translated", - "value": "Selene è un tema di Playnite per Windows. Il nome, il logo, gli sfondi, gli avatar e i suoni di Selene non sono usati come identità di NX Library; si tratta di un adattamento visivo in SwiftUI." + "value": "Selene è un tema di Playnite per Windows. Il nome, il logo, gli sfondi, gli avatar e i suoni di Selene non sono usati come identità di Arcane; si tratta di un adattamento visivo in SwiftUI." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Selene est un thème Playnite pour Windows. NX Library n’utilise ni le nom, ni le logo, ni les fonds d’écran, avatars ou sons de Selene comme identité de marque ; il s’agit d’une adaptation visuelle en SwiftUI." + "value": "Selene est un thème Playnite pour Windows. Arcane n’utilise ni le nom, ni le logo, ni les fonds d’écran, avatars ou sons de Selene comme identité de marque ; il s’agit d’une adaptation visuelle en SwiftUI." } }, "de": { "stringUnit": { "state": "translated", - "value": "Selene ist ein Playnite-Theme für Windows. Name, Logo, Hintergrundbilder, Avatare und Sounds von Selene werden nicht als Markenauftritt von NX Library verwendet; dies ist eine visuelle Adaption in SwiftUI." + "value": "Selene ist ein Playnite-Theme für Windows. Name, Logo, Hintergrundbilder, Avatare und Sounds von Selene werden nicht als Markenauftritt von Arcane verwendet; dies ist eine visuelle Adaption in SwiftUI." } }, "es": { "stringUnit": { "state": "translated", - "value": "Selene es un tema de Playnite para Windows. NX Library no usa el nombre, el logotipo, los fondos, los avatares ni los sonidos de Selene como identidad de marca; es una adaptación visual en SwiftUI." + "value": "Selene es un tema de Playnite para Windows. Arcane no usa el nombre, el logotipo, los fondos, los avatares ni los sonidos de Selene como identidad de marca; es una adaptación visual en SwiftUI." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Selene é um tema do Playnite para Windows. Nenhum nome, logotipo, papel de parede, avatar ou som do Selene é usado como identidade do NX Library; esta é uma adaptação visual em SwiftUI." + "value": "Selene é um tema do Playnite para Windows. Nenhum nome, logotipo, papel de parede, avatar ou som do Selene é usado como identidade do Arcane; esta é uma adaptação visual em SwiftUI." } } } @@ -50725,6 +52084,88 @@ } } }, + "Settings group: General": { + "comment": "SettingsSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "General" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Generali" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Général" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Allgemein" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "General" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Geral" + } + } + } + }, + "Settings group: System": { + "comment": "SettingsSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "System" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Sistema" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Système" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "System" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Sistema" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Sistema" + } + } + } + }, "Settings not saved": { "comment": "AppShellView.swift", "localizations": { @@ -51094,47 +52535,6 @@ } } }, - "Setup needed or builds blocked": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Setup needed or builds blocked" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Configurazione necessaria o compilazioni bloccate" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Configuration requise ou compilations bloquées" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Einrichtung erforderlich oder Builds gesperrt" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Falta configurar o la compilación está bloqueada" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Configuração necessária ou compilações bloqueadas" - } - } - } - }, "Several files could be these cheats: add the one you want.": { "comment": "CheatCopy.swift", "localizations": { @@ -51709,6 +53109,47 @@ } } }, + "Silver": { + "comment": "Achievement tier (a crystal), as PlayStation trophy tiers.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Silver" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Argento" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Argent" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Silber" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Plata" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Prata" + } + } + } + }, "Simulates the Nintendo Switch docked TV profile (1080p target, higher clocks and memory limits). Disabling uses handheld profile (720p target, lower GPU load).": { "comment": "SettingsGamesSection.swift", "localizations": { @@ -51750,6 +53191,47 @@ } } }, + "Size on disk": { + "comment": "DetailsFacts.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Size on disk" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Spazio su disco" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Taille sur le disque" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Größe auf dem Volume" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Tamaño en disco" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Tamanho no disco" + } + } + } + }, "Skip for now": { "comment": "YourGamesSetupView.swift", "localizations": { @@ -52160,6 +53642,88 @@ } } }, + "Some installations could not be checked. Your library has been kept.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Some installations could not be checked. Your library has been kept." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile controllare alcune installazioni. La tua libreria è stata conservata." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Certaines installations n’ont pas pu être vérifiées. Votre bibliothèque a été conservée." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Einige Installationen konnten nicht geprüft werden. Deine Bibliothek bleibt erhalten." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron revisar algunas instalaciones. Tu biblioteca se ha conservado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Algumas instalações não puderam ser verificadas. Sua biblioteca foi mantida." + } + } + } + }, + "Some launcher data could not be read. The original data has not been changed.": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Some launcher data could not be read. The original data has not been changed." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Impossibile leggere alcuni dati del launcher. I dati originali non sono stati modificati." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Certaines données du lanceur n’ont pas pu être lues. Les données d’origine n’ont pas été modifiées." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Einige Launcher-Daten konnten nicht gelesen werden. Die Originaldaten wurden nicht verändert." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron leer algunos datos del launcher. Los datos originales no se han modificado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível ler alguns dados do launcher. Os dados originais não foram alterados." + } + } + } + }, "Some shaders broke in this engine": { "comment": "PortingFailureReason.swift", "localizations": { @@ -52447,47 +54011,6 @@ } } }, - "Sources attached": { - "comment": "BuildSourcesPanel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Sources attached" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Sorgenti collegate" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Sources associées" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Quellen zugeordnet" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Archivos de origen vinculados" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Arquivos de origem vinculados" - } - } - } - }, "Sources attached to %@; rebuild is now available if the toolchain gate allows it.": { "comment": "AppViewModel.swift", "localizations": { @@ -52570,47 +54093,6 @@ } } }, - "Sources detached": { - "comment": "BuildSourcesPanel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Sources detached" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Sorgenti scollegate" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Sources dissociées" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Quellen getrennt" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Archivos de origen desvinculados" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Arquivos de origem desvinculados" - } - } - } - }, "Sources folder kept": { "comment": "SettingsView.swift:282", "localizations": { @@ -52980,6 +54462,47 @@ } } }, + "Start the game through Steam.": { + "comment": "CatalogGameOptions.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Start the game through Steam." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Avvia il gioco tramite Steam." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Lancer le jeu via Steam." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Starte das Spiel über Steam." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Inicia el juego a través de Steam." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Inicie o jogo pelo Steam." + } + } + } + }, "Start-up": { "comment": "SettingsSection.swift", "localizations": { @@ -53185,43 +54708,494 @@ } } }, - "Startup, setup and readiness.": { + "Steam": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Steam" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Steam" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Steam" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Steam" + } + } + } + }, + "Steam could not be refreshed. Your library has been kept.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam could not be refreshed. Your library has been kept." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile aggiornare Steam. La tua libreria è stata conservata." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Steam n’a pas pu être actualisé. Votre bibliothèque a été conservée." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam konnte nicht aktualisiert werden. Deine Bibliothek bleibt erhalten." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo actualizar Steam. Tu biblioteca se ha conservado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível atualizar o Steam. Sua biblioteca foi mantida." + } + } + } + }, + "Steam couldn't be read completely. Try again or continue and check Settings → Sources later.": { + "comment": "First launch Steam scan failed or was partial; Retry is the action on the row. Continuing does not imply that Steam is empty.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam couldn't be read completely. Try again or continue and check Settings → Sources later." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile leggere tutti i dati di Steam. Riprova o continua e controlla Impostazioni → Fonti più tardi." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible de lire toutes les données Steam. Réessayez ou continuez et vérifiez Réglages → Sources plus tard." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam konnte nicht vollständig gelesen werden. Erneut versuchen oder fortfahren und später unter Einstellungen → Quellen prüfen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron leer todos los datos de Steam. Reintenta o continúa y revisa Ajustes → Fuentes más tarde." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível ler todos os dados do Steam. Tente novamente ou continue e confira Ajustes → Fontes depois." + } + } + } + }, + "Steam did not receive the request. Try again.": { + "comment": "CatalogSteamInfo.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam did not receive the request. Try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Steam non ha ricevuto la richiesta. Riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Steam n’a pas reçu la demande. Réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam hat die Anfrage nicht erhalten. Versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Steam no recibió la solicitud. Inténtalo de nuevo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O Steam não recebeu a solicitação. Tente novamente." + } + } + } + }, + "Steam downloads": { + "comment": "First pill and A hint of a Steam game Steam is still installing: opens Steam on its Downloads page.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam downloads" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Download di Steam" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Téléchargements Steam" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam-Downloads" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Descargas de Steam" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Downloads da Steam" + } + } + } + }, + "Steam folder": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam folder" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Cartella Steam" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Dossier Steam" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam-Ordner" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Carpeta de Steam" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Pasta do Steam" + } + } + } + }, + "Steam installation data could not be verified. Your library has been kept.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam installation data could not be verified. Your library has been kept." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile verificare i dati delle installazioni Steam. La tua libreria è stata conservata." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les données des installations Steam n’ont pas pu être vérifiées. Votre bibliothèque a été conservée." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Steam-Installationsdaten konnten nicht geprüft werden. Deine Bibliothek bleibt erhalten." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron verificar los datos de las instalaciones de Steam. Tu biblioteca se ha conservado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível verificar os dados das instalações Steam. Sua biblioteca foi mantida." + } + } + } + }, + "Steam is not installed on this Mac.": { + "comment": "CatalogSteamInfo.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam is not installed on this Mac." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Steam non è installato su questo Mac." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Steam n’est pas installé sur ce Mac." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam ist auf diesem Mac nicht installiert." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Steam no está instalado en este Mac." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O Steam não está instalado neste Mac." + } + } + } + }, + "Steam libraries, refresh and how Play opens Steam.": { "comment": "SettingsSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Startup, setup and readiness." + "value": "Steam libraries, refresh and how Play opens Steam." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Librerie Steam, aggiornamento e come Gioca apre Steam." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Bibliothèques Steam, actualisation et ouverture de Steam par Jouer." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam-Bibliotheken, Aktualisieren und wie „Spielen“ Steam öffnet." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Bibliotecas de Steam, actualización y cómo Jugar abre Steam." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Bibliotecas do Steam, atualização e como Jogar abre o Steam." + } + } + } + }, + "Steam may need you. Check Steam, the game starts after.": { + "comment": "CatalogSteamInfo.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam may need you. Check Steam, the game starts after." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Steam potrebbe aver bisogno di te. Controlla Steam, poi il gioco si avvia." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Steam a peut-être besoin de vous. Vérifiez Steam, le jeu démarrera ensuite." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam braucht dich vielleicht. Sieh in Steam nach, danach startet das Spiel." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Puede que Steam te necesite. Revisa Steam y luego se iniciará el juego." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O Steam pode precisar de você. Confira o Steam; depois o jogo inicia." + } + } + } + }, + "Steam starts quietly when possible and comes forward if it needs you.": { + "comment": "SettingsSourcesSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam starts quietly when possible and comes forward if it needs you." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Steam si avvia in background quando possibile e viene in primo piano se serve il tuo intervento." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Steam démarre en arrière-plan si possible et passe au premier plan si votre intervention est nécessaire." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Steam startet wenn möglich im Hintergrund und kommt nach vorne, wenn deine Eingabe nötig ist." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Steam se inicia en segundo plano cuando es posible y pasa al primer plano si necesita tu intervención." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O Steam inicia em segundo plano quando possível e vem para a frente se precisar da sua atenção." + } + } + } + }, + "Steam: %@": { + "comment": "ChangeMetadataView.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam: %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "Avvio, configurazione e stato di preparazione." + "value": "Steam: %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Démarrage, configuration et état de préparation." + "value": "Steam : %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "Start, Einrichtung und Bereitschaft." + "value": "Steam: %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "Inicio, configuración y estado de preparación." + "value": "Steam: %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Inicialização, configuração e prontidão." + "value": "Steam: %@" } } } @@ -53431,6 +55405,88 @@ } } }, + "Steam’s library cover": { + "comment": "ChangeArtworkView.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam’s library cover" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La copertina della libreria di Steam" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La jaquette de la bibliothèque Steam" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Das Bibliothekscover von Steam" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La portada de la biblioteca de Steam" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A capa da biblioteca do Steam" + } + } + } + }, + "Steam’s logo": { + "comment": "ChangeArtworkView.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Steam’s logo" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Il logo di Steam" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le logo de Steam" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Das Logo von Steam" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "El logotipo de Steam" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O logotipo do Steam" + } + } + } + }, "Step %@ of 3": { "comment": "AddGameView.swift", "localizations": { @@ -53923,43 +55979,43 @@ } } }, - "Summarizes the 4 essential gates: valid prod.keys, cloned nxnative repository, Python build environment, and certified Metal compiler version.": { - "comment": "SettingsStartUpSection.swift", + "Support Arcane": { + "comment": "SettingsAboutSection.swift", "localizations": { - "en": { + "de": { "stringUnit": { "state": "translated", - "value": "Summarizes the 4 essential gates: valid prod.keys, cloned nxnative repository, Python build environment, and certified Metal compiler version." + "value": "Arcane unterstützen" } }, - "it": { + "en": { "stringUnit": { "state": "translated", - "value": "Riepiloga i 4 requisiti essenziali: prod.keys valido, repository nxnative clonato, ambiente di compilazione Python e versione certificata del compilatore Metal." + "value": "Support Arcane" } }, - "fr": { + "es": { "stringUnit": { "state": "translated", - "value": "Résume les 4 contrôles essentiels : prod.keys valide, dépôt nxnative cloné, environnement de compilation Python et version du compilateur Metal certifiée." + "value": "Apoyar a Arcane" } }, - "de": { + "fr": { "stringUnit": { "state": "translated", - "value": "Fasst die 4 grundlegenden Voraussetzungen zusammen: gültige prod.keys, geklontes nxnative-Repository, Python-Build-Umgebung und zertifizierte Metal-Compiler-Version." + "value": "Soutenir Arcane" } }, - "es": { + "it": { "stringUnit": { "state": "translated", - "value": "Resume los 4 requisitos esenciales: prod.keys válido, repositorio de nxnative clonado, entorno de compilación Python y versión del compilador Metal certificada." + "value": "Sostieni Arcane" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Resume as 4 verificações essenciais: prod.keys válido, repositório nxnative clonado, ambiente Python de compilação e versão certificada do compilador Metal." + "value": "Apoiar o Arcane" } } } @@ -54333,6 +56389,170 @@ } } }, + "The library's tiles fly in with the boot sound when the app opens.": { + "comment": "SettingsCatalog.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The library's tiles fly in with the boot sound when the app opens." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "All’apertura dell’app le tessere della libreria entrano in volo, con il suono di avvio." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "À l’ouverture de l’app, les tuiles de la bibliothèque arrivent en vol, avec le son de démarrage." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Beim Öffnen der App fliegen die Kacheln der Bibliothek mit dem Startklang herein." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Al abrir la app, los mosaicos de la biblioteca entran volando con el sonido de arranque." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Ao abrir o app, os blocos da biblioteca entram voando com o som de inicialização." + } + } + } + }, + "The selected NUP program no longer matches this game. Choose the source again.": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The selected NUP program no longer matches this game. Choose the source again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Il programma selezionato nel NUP non corrisponde più a questo gioco. Scegli di nuovo la sorgente." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le programme sélectionné dans le NUP ne correspond plus à ce jeu. Sélectionnez à nouveau la source." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Das gewählte NUP-Programm entspricht nicht mehr diesem Spiel. Wähle die Quelle erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "El programa seleccionado del NUP ya no corresponde a este juego. Vuelve a elegir la fuente." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O programa selecionado no NUP não corresponde mais a este jogo. Escolha a fonte novamente." + } + } + } + }, + "This backup restores all local users and their registry.": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This backup restores all local users and their registry." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Questo backup ripristina tutti gli utenti locali e il loro registro." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cette sauvegarde restaure tous les utilisateurs locaux et leur registre." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieses Backup stellt alle lokalen Benutzer und ihre Registrierung wieder her." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Esta copia restaura todos los usuarios locales y su registro." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Este backup restaura todos os usuários locais e seu registro." + } + } + } + }, + "This older backup restores only the primary user and device save. Other local users will be kept.": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This older backup restores only the primary user and device save. Other local users will be kept." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Questo vecchio backup ripristina solo i salvataggi dell’utente principale e del dispositivo. Gli altri utenti locali verranno conservati." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cette ancienne sauvegarde ne restaure que l’utilisateur principal et la sauvegarde de l’appareil. Les autres utilisateurs locaux seront conservés." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieses ältere Backup stellt nur den Hauptbenutzer- und den Gerätespielstand wieder her. Andere lokale Benutzer bleiben erhalten." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Esta copia antigua solo restaura las partidas del usuario principal y del dispositivo. Los demás usuarios locales se conservarán." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Este backup antigo restaura apenas os salvamentos do usuário principal e do dispositivo. Os outros usuários locais serão mantidos." + } + } + } + }, "THIS WEEK": { "comment": "DetailsBands.swift:70", "localizations": { @@ -54538,43 +56758,43 @@ } } }, - "That file is not an image NX Library can read.": { + "That file is not an image Arcane can read.": { "comment": "ArtworkPicker.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "That file is not an image NX Library can read." + "value": "That file is not an image Arcane can read." } }, "it": { "stringUnit": { "state": "translated", - "value": "Il file non è un’immagine leggibile da NX Library." + "value": "Il file non è un’immagine leggibile da Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Ce fichier n’est pas une image lisible par NX Library." + "value": "Ce fichier n’est pas une image lisible par Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Diese Datei ist kein für NX Library lesbares Bild." + "value": "Diese Datei ist kein für Arcane lesbares Bild." } }, "es": { "stringUnit": { "state": "translated", - "value": "Ese archivo no es una imagen que NX Library pueda leer." + "value": "Ese archivo no es una imagen que Arcane pueda leer." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Esse arquivo não é uma imagem que o NX Library consiga ler." + "value": "Esse arquivo não é uma imagem que o Arcane consiga ler." } } } @@ -54620,6 +56840,47 @@ } } }, + "That game is no longer in the library. Refresh it and try again.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "That game is no longer in the library. Refresh it and try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Il gioco non è più nella libreria. Aggiornala e riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ce jeu n’est plus dans la bibliothèque. Actualisez-la et réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieses Spiel ist nicht mehr in der Bibliothek. Aktualisiere sie und versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Ese juego ya no está en la biblioteca. Actualízala y vuelve a intentarlo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Esse jogo não está mais na biblioteca. Atualize-a e tente novamente." + } + } + } + }, "That is not a SteamGridDB API key. Copy it from Preferences → API in your SteamGridDB profile.": { "comment": "SteamGridDBArt.swift", "localizations": { @@ -54661,43 +56922,43 @@ } } }, - "The Game apps folder is unavailable. Reconnect it or choose another in Settings → Library.": { - "comment": "GameAppDestination.swift", + "The Mac app’s own icon": { + "comment": "ChangeArtworkView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The Game apps folder is unavailable. Reconnect it or choose another in Settings → Library." + "value": "The Mac app’s own icon" } }, "it": { "stringUnit": { "state": "translated", - "value": "La cartella App dei giochi non è disponibile. Ricollegala o scegline un’altra in Impostazioni → Libreria." + "value": "L’icona dell’app Mac" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le dossier Apps de jeux est indisponible. Reconnectez-le ou choisissez-en un autre dans Réglages → Bibliothèque." + "value": "L’icône de l’app Mac" } }, "de": { "stringUnit": { "state": "translated", - "value": "Der Spiele-App-Ordner ist nicht verfügbar. Verbinde ihn erneut oder wähle unter Einstellungen → Bibliothek einen anderen." + "value": "Das eigene Symbol der Mac-App" } }, "es": { "stringUnit": { "state": "translated", - "value": "La carpeta Apps de juegos no está disponible. Vuelve a conectarla o elige otra en Ajustes → Biblioteca." + "value": "El icono propio de la app de Mac" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A pasta de Apps de jogos está indisponível. Reconecte ou escolha outra em Ajustes → Biblioteca." + "value": "O ícone do próprio app para Mac" } } } @@ -54743,6 +57004,47 @@ } } }, + "The Steam library changed while it was being checked. Refresh it again.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The Steam library changed while it was being checked. Refresh it again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La libreria Steam è cambiata durante il controllo. Aggiornala di nuovo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La bibliothèque Steam a changé pendant la vérification. Actualisez-la à nouveau." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Steam-Bibliothek hat sich während der Prüfung geändert. Aktualisiere sie erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La biblioteca de Steam cambió durante la revisión. Actualízala de nuevo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A biblioteca Steam mudou durante a verificação. Atualize-a novamente." + } + } + } + }, "The app bundle is missing: %@": { "comment": "NXLibraryError.swift", "localizations": { @@ -55317,6 +57619,47 @@ } } }, + "The build result is kept for this session. Free space if needed, then retry saving before closing Arcane.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The build result is kept for this session. Free space if needed, then retry saving before closing Arcane." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Il risultato della build viene conservato per questa sessione. Libera spazio se necessario, poi ritenta il salvataggio prima di chiudere Arcane." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le résultat de la compilation est conservé pour cette session. Libérez de l’espace si nécessaire, puis réessayez d’enregistrer avant de fermer Arcane." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Das Build-Ergebnis bleibt für diese Sitzung erhalten. Gib bei Bedarf Speicherplatz frei und versuche das Speichern erneut, bevor du Arcane schließt." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "El resultado de la compilación se conserva durante esta sesión. Libera espacio si es necesario y vuelve a guardarlo antes de cerrar Arcane." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O resultado da compilação será mantido nesta sessão. Libere espaço se necessário e tente salvar novamente antes de fechar o Arcane." + } + } + } + }, "The built app is invalid: %@": { "comment": "BuildOutputInstaller.swift", "localizations": { @@ -55563,6 +57906,129 @@ } } }, + "The development data folder already exists without a completed import. It has been preserved.": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The development data folder already exists without a completed import. It has been preserved." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La cartella dei dati di sviluppo esiste già, ma l’importazione non è completa. È stata conservata." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le dossier des données de développement existe déjà, mais l’importation est incomplète. Il a été conservé." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Der Entwicklungsdatenordner ist bereits vorhanden, aber der Import ist nicht abgeschlossen. Er wurde beibehalten." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La carpeta de datos de desarrollo ya existe, pero la importación no está completa. Se ha conservado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A pasta de dados de desenvolvimento já existe, mas a importação não foi concluída. Ela foi mantida." + } + } + } + }, + "The development preferences could not be saved. Try again.": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The development preferences could not be saved. Try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Impossibile salvare le preferenze di sviluppo. Riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les préférences de développement n’ont pas pu être enregistrées. Réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Entwicklungseinstellungen konnten nicht gespeichert werden. Versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron guardar las preferencias de desarrollo. Inténtalo de nuevo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível salvar as preferências de desenvolvimento. Tente novamente." + } + } + } + }, + "The development profile configuration is invalid.": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The development profile configuration is invalid." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La configurazione del profilo di sviluppo non è valida." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La configuration du profil de développement est invalide." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Konfiguration des Entwicklungsprofils ist ungültig." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La configuración del perfil de desarrollo no es válida." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A configuração do perfil de desenvolvimento é inválida." + } + } + } + }, "The disk filled up during the porting.": { "comment": "PortingFailureReason.swift", "localizations": { @@ -55686,43 +58152,43 @@ } } }, - "The download is not a valid NX Library %@; nothing was changed.": { + "The download is not a valid Arcane %@; nothing was changed.": { "comment": "AppUpdater.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The download is not a valid NX Library %@; nothing was changed." + "value": "The download is not a valid Arcane %@; nothing was changed." } }, "it": { "stringUnit": { "state": "translated", - "value": "Il file scaricato non è una copia valida di NX Library %@; non è stato modificato nulla." + "value": "Il file scaricato non è una copia valida di Arcane %@; non è stato modificato nulla." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le téléchargement n’est pas une copie valide de NX Library %@ ; aucune modification n’a été effectuée." + "value": "Le téléchargement n’est pas une copie valide d’Arcane %@ ; aucune modification n’a été effectuée." } }, "de": { "stringUnit": { "state": "translated", - "value": "Der Download ist keine gültige Version von NX Library %@; es wurde nichts geändert." + "value": "Der Download ist keine gültige Version von Arcane %@; es wurde nichts geändert." } }, "es": { "stringUnit": { "state": "translated", - "value": "La descarga no es una copia válida de NX Library %@; no se ha cambiado nada." + "value": "La descarga no es una copia válida de Arcane %@; no se ha cambiado nada." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O download não é uma cópia válida do NX Library %@; nada foi alterado." + "value": "O download não é uma cópia válida do Arcane %@; nada foi alterado." } } } @@ -55891,43 +58357,43 @@ } } }, - "The engine folder has changed files. NX Library never touches them: put them aside, then try again.": { + "The engine folder has changed files. Arcane never touches them: put them aside, then try again.": { "comment": "NewestEngine.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The engine folder has changed files. NX Library never touches them: put them aside, then try again." + "value": "The engine folder has changed files. Arcane never touches them: put them aside, then try again." } }, "it": { "stringUnit": { "state": "translated", - "value": "La cartella del motore contiene file modificati. NX Library non li tocca mai: mettili da parte, poi riprova." + "value": "La cartella del motore contiene file modificati. Arcane non li tocca mai: mettili da parte, poi riprova." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le dossier du moteur contient des fichiers modifiés. NX Library n’y touche jamais : mettez-les de côté, puis réessayez." + "value": "Le dossier du moteur contient des fichiers modifiés. Arcane n’y touche jamais : mettez-les de côté, puis réessayez." } }, "de": { "stringUnit": { "state": "translated", - "value": "Der Engine-Ordner enthält geänderte Dateien. NX Library verändert sie niemals: Lege sie beiseite und versuche es erneut." + "value": "Der Engine-Ordner enthält geänderte Dateien. Arcane verändert sie niemals: Lege sie beiseite und versuche es erneut." } }, "es": { "stringUnit": { "state": "translated", - "value": "La carpeta del motor contiene archivos modificados. NX Library nunca los modifica: apártalos e inténtalo de nuevo." + "value": "La carpeta del motor contiene archivos modificados. Arcane nunca los modifica: apártalos e inténtalo de nuevo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A pasta da engine tem arquivos alterados. O NX Library nunca os modifica: guarde-os em outro local e tente novamente." + "value": "A pasta da engine tem arquivos alterados. O Arcane nunca os modifica: guarde-os em outro local e tente novamente." } } } @@ -55973,43 +58439,43 @@ } } }, - "The engine here is at %@, not the %@ this NX Library is tested with. Switch moves it to %@. Games you built keep playing.": { + "The engine here is at %@, not the %@ this version of Arcane is tested with. Switch moves it to %@. Games you built keep playing.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The engine here is at %@, not the %@ this NX Library is tested with. Switch moves it to %@. Games you built keep playing." + "value": "The engine here is at %@, not the %@ this version of Arcane is tested with. Switch moves it to %@. Games you built keep playing." } }, "it": { "stringUnit": { "state": "translated", - "value": "Il motore qui è al commit %@, diverso da %@ con cui è testata questa NX Library. Con Cambia lo porti a %@. I giochi già compilati continuano a funzionare." + "value": "Il motore qui è al commit %@, diverso da %@ con cui è testata questa versione di Arcane. Con Cambia lo porti a %@. I giochi già compilati continuano a funzionare." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le moteur présent est au commit %@, et non au commit %@ avec lequel cette version de NX Library a été testée. Changer le fait passer au commit %@. Les jeux déjà compilés restent jouables." + "value": "Le moteur présent est au commit %@, et non au commit %@ avec lequel cette version d’Arcane a été testée. Changer le fait passer au commit %@. Les jeux déjà compilés restent jouables." } }, "de": { "stringUnit": { "state": "translated", - "value": "Die Engine hier steht auf %@ statt auf %@, womit diese NX Library-Version getestet wurde. „Wechseln“ setzt sie auf %@. Bereits erstellte Spiele bleiben spielbar." + "value": "Die Engine hier steht auf %@ statt auf %@, womit diese Arcane-Version getestet wurde. „Wechseln“ setzt sie auf %@. Bereits erstellte Spiele bleiben spielbar." } }, "es": { "stringUnit": { "state": "translated", - "value": "El motor local está en %@, en lugar de %@, con el que se ha probado este NX Library. Cambiar lo mueve a %@. Los juegos ya compilados siguen funcionando." + "value": "El motor local está en %@, en lugar de %@, con el que se ha probado este Arcane. Cambiar lo mueve a %@. Los juegos ya compilados siguen funcionando." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A engine aqui está em %@, e não em %@, com o qual este NX Library foi testado. Trocar a move para %@. Seus jogos compilados continuam funcionando." + "value": "A engine aqui está em %@, e não em %@, com o qual este Arcane foi testado. Trocar a move para %@. Seus jogos compilados continuam funcionando." } } } @@ -56055,43 +58521,43 @@ } } }, - "The engine stopped without a message NX Library recognises.": { + "The engine stopped without a message Arcane recognises.": { "comment": "PortingFailureReason.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The engine stopped without a message NX Library recognises." + "value": "The engine stopped without a message Arcane recognises." } }, "it": { "stringUnit": { "state": "translated", - "value": "Il motore si è interrotto senza un messaggio riconosciuto da NX Library." + "value": "Il motore si è interrotto senza un messaggio riconosciuto da Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le moteur s’est arrêté sans message reconnu par NX Library." + "value": "Le moteur s’est arrêté sans message reconnu par Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Die Engine wurde ohne eine für NX Library erkennbare Meldung gestoppt." + "value": "Die Engine wurde ohne eine für Arcane erkennbare Meldung gestoppt." } }, "es": { "stringUnit": { "state": "translated", - "value": "El motor se ha detenido sin un mensaje que NX Library reconozca." + "value": "El motor se ha detenido sin un mensaje que Arcane reconozca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A engine parou sem uma mensagem que o NX Library reconheça." + "value": "A engine parou sem uma mensagem que o Arcane reconheça." } } } @@ -56465,6 +58931,47 @@ } } }, + "The game did not start. Check Steam, then try again.": { + "comment": "CatalogSteamInfo.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The game did not start. Check Steam, then try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Il gioco non si è avviato. Controlla Steam, poi riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le jeu n’a pas démarré. Vérifiez Steam, puis réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Das Spiel wurde nicht gestartet. Prüfe Steam und versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "El juego no se inició. Revisa Steam y vuelve a intentarlo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O jogo não iniciou. Verifique o Steam e tente novamente." + } + } + } + }, "The game does not have this language": { "comment": "PortingFailureReason.swift", "localizations": { @@ -56916,43 +59423,43 @@ } } }, - "The icon is not an image NX Library can read.": { + "The icon is not an image Arcane can read.": { "comment": "AppIconWriter.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The icon is not an image NX Library can read." + "value": "The icon is not an image Arcane can read." } }, "it": { "stringUnit": { "state": "translated", - "value": "L’icona non è un’immagine leggibile da NX Library." + "value": "L’icona non è un’immagine leggibile da Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "L’icône n’est pas une image lisible par NX Library." + "value": "L’icône n’est pas une image lisible par Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Das Symbol ist kein für NX Library lesbares Bild." + "value": "Das Symbol ist kein für Arcane lesbares Bild." } }, "es": { "stringUnit": { "state": "translated", - "value": "El icono no es una imagen que NX Library pueda leer." + "value": "El icono no es una imagen que Arcane pueda leer." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O ícone não é uma imagem que o NX Library consiga ler." + "value": "O ícone não é uma imagem que o Arcane consiga ler." } } } @@ -57244,6 +59751,293 @@ } } }, + "The latest save could not be confirmed. Reload the library before trying again.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The latest save could not be confirmed. Reload the library before trying again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile confermare l’ultimo salvataggio. Ricarica la libreria prima di riprovare." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le dernier enregistrement n’a pas pu être confirmé. Rechargez la bibliothèque avant de réessayer." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Das letzte Speichern konnte nicht bestätigt werden. Lade die Bibliothek neu, bevor du es erneut versuchst." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo confirmar el último guardado. Vuelve a cargar la biblioteca antes de intentarlo de nuevo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível confirmar o último salvamento. Recarregue a biblioteca antes de tentar novamente." + } + } + } + }, + "The launcher file %@ could not be read. The original data has not been changed.": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The launcher file %@ could not be read. The original data has not been changed." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Impossibile leggere il file del launcher %@. I dati originali non sono stati modificati." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le fichier du lanceur %@ n’a pas pu être lu. Les données d’origine n’ont pas été modifiées." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Launcher-Datei %@ konnte nicht gelesen werden. Die Originaldaten wurden nicht verändert." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo leer el archivo del launcher %@. Los datos originales no se han modificado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível ler o arquivo do launcher %@. Os dados originais não foram alterados." + } + } + } + }, + "The library changed. Reload it and try again.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The library changed. Reload it and try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La libreria è cambiata. Ricaricala e riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La bibliothèque a changé. Rechargez-la et réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Bibliothek hat sich geändert. Lade sie neu und versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La biblioteca ha cambiado. Vuelve a cargarla e inténtalo de nuevo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A biblioteca mudou. Recarregue-a e tente novamente." + } + } + } + }, + "The library contains conflicting or unsupported records. Its files have been kept.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The library contains conflicting or unsupported records. Its files have been kept." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La libreria contiene dati in conflitto o non supportati. I file sono stati conservati." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La bibliothèque contient des données en conflit ou non prises en charge. Ses fichiers ont été conservés." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Bibliothek enthält widersprüchliche oder nicht unterstützte Einträge. Die Dateien wurden aufbewahrt." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La biblioteca contiene datos en conflicto o no compatibles. Sus archivos se han conservado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A biblioteca contém dados conflitantes ou não compatíveis. Os arquivos foram preservados." + } + } + } + }, + "The library copy contains a symbolic link or an unsupported file. The original data has not been changed.": { + "comment": "Development profile bootstrap; do not expose credential values.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The library copy contains a symbolic link or an unsupported file. The original data has not been changed." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La copia della libreria contiene un collegamento simbolico o un file non supportato. I dati originali non sono stati modificati." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La copie de la bibliothèque contient un lien symbolique ou un fichier non pris en charge. Les données d’origine n’ont pas été modifiées." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Bibliothekskopie enthält einen symbolischen Link oder eine nicht unterstützte Datei. Die Originaldaten wurden nicht verändert." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La copia de la biblioteca contiene un enlace simbólico o un archivo no compatible. Los datos originales no se han modificado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A cópia da biblioteca contém um link simbólico ou um arquivo não compatível. Os dados originais não foram alterados." + } + } + } + }, + "The library folder could not be used safely. Its files have been kept.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The library folder could not be used safely. Its files have been kept." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile usare la cartella della libreria in modo sicuro. I file sono stati conservati." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible d’utiliser le dossier de la bibliothèque en toute sécurité. Ses fichiers ont été conservés." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Der Bibliotheksordner konnte nicht sicher verwendet werden. Die Dateien wurden aufbewahrt." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo usar la carpeta de la biblioteca de forma segura. Sus archivos se han conservado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível usar a pasta da biblioteca com segurança. Os arquivos foram preservados." + } + } + } + }, + "The library is busy. Try again shortly.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The library is busy. Try again shortly." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "La libreria è occupata. Riprova tra poco." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La bibliothèque est occupée. Réessayez dans un instant." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Bibliothek ist beschäftigt. Versuche es gleich erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La biblioteca está ocupada. Vuelve a intentarlo en un momento." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A biblioteca está ocupada. Tente novamente em instantes." + } + } + } + }, "The library is in a cloud folder": { "comment": "PortingFailureReason.swift", "localizations": { @@ -57572,43 +60366,43 @@ } } }, - "The newest nxnative needs Metal %@, so it needs a newer NX Library.": { + "The newest nxnative needs Metal %@, so it needs a newer Arcane.": { "comment": "NewestEngine.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The newest nxnative needs Metal %@, so it needs a newer NX Library." + "value": "The newest nxnative needs Metal %@, so it needs a newer Arcane." } }, "it": { "stringUnit": { "state": "translated", - "value": "La versione più recente di nxnative richiede Metal %@, quindi serve una NX Library più recente." + "value": "La versione più recente di nxnative richiede Metal %@, quindi serve una versione più recente di Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Le dernier nxnative nécessite Metal %@ et requiert donc une version plus récente de NX Library." + "value": "Le dernier nxnative nécessite Metal %@ et requiert donc une version plus récente d’Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Das neueste nxnative benötigt Metal %@ und daher eine neuere NX Library-Version." + "value": "Das neueste nxnative benötigt Metal %@ und daher eine neuere Arcane-Version." } }, "es": { "stringUnit": { "state": "translated", - "value": "El nxnative más reciente necesita Metal %@, por lo que requiere una versión más reciente de NX Library." + "value": "El nxnative más reciente necesita Metal %@, por lo que requiere una versión más reciente de Arcane." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O nxnative mais recente precisa do Metal %@, por isso requer um NX Library mais recente." + "value": "O nxnative mais recente precisa do Metal %@, por isso requer um Arcane mais recente." } } } @@ -57654,47 +60448,6 @@ } } }, - "The nxnative checkout was not found. Choose it in Settings → Engine.": { - "comment": "NXLibraryError.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "The nxnative checkout was not found. Choose it in Settings → Engine." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Il checkout di nxnative non è stato trovato. Selezionalo in Impostazioni → Motore." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "La copie de travail de nxnative est introuvable. Choisissez-la dans Réglages → Moteur." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Der nxnative-Checkout wurde nicht gefunden. Wähle ihn unter Einstellungen → Engine aus." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "No se ha encontrado la copia local de nxnative. Selecciónala en Ajustes → Motor." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "O checkout do nxnative não foi encontrado. Selecione-o em Ajustes → Engine." - } - } - } - }, "The original file is untouched. The stored copy is mode 0600 and key values are never shown or logged.": { "comment": "SettingsEngineSection.swift", "localizations": { @@ -57736,43 +60489,43 @@ } } }, - "The original sources are attached. Rebuild writes a new app and keeps the previous one if it fails.": { - "comment": "BuildSourcesPanel.swift", + "The original library changed during the copy. Close the other launcher copy and try again.": { + "comment": "Development profile bootstrap; do not expose credential values.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The original sources are attached. Rebuild writes a new app and keeps the previous one if it fails." + "value": "The original library changed during the copy. Close the other launcher copy and try again." } }, "it": { "stringUnit": { "state": "translated", - "value": "Le sorgenti originali sono collegate. La ricompilazione crea una nuova app e conserva quella precedente in caso di errore." + "value": "La libreria originale è cambiata durante la copia. Chiudi l’altra copia del launcher e riprova." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Les sources d’origine sont associées. La recompilation crée une nouvelle app et conserve la précédente en cas d’échec." + "value": "La bibliothèque d’origine a changé pendant la copie. Fermez l’autre copie du lanceur et réessayez." } }, "de": { "stringUnit": { "state": "translated", - "value": "Die ursprünglichen Quellen sind zugeordnet. Beim erneuten Erstellen wird eine neue App geschrieben; schlägt dies fehl, bleibt die bisherige erhalten." + "value": "Die Originalbibliothek wurde während des Kopierens geändert. Schließe die andere Launcher-Kopie und versuche es erneut." } }, "es": { "stringUnit": { "state": "translated", - "value": "Los archivos de origen originales están vinculados. Al recompilar, se crea una nueva app y se conserva la anterior si hay un fallo." + "value": "La biblioteca original cambió durante la copia. Cierra la otra copia del launcher e inténtalo de nuevo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Os arquivos de origem originais estão vinculados. A recompilação cria um novo app e mantém o anterior em caso de falha." + "value": "A biblioteca original mudou durante a cópia. Feche a outra cópia do launcher e tente novamente." } } } @@ -58310,84 +61063,84 @@ } } }, - "The screen NX Library opens on.": { + "The screen Arcane opens on.": { "comment": "SettingsStartUpSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The screen NX Library opens on." + "value": "The screen Arcane opens on." } }, "it": { "stringUnit": { "state": "translated", - "value": "La schermata iniziale di NX Library." + "value": "La schermata iniziale di Arcane." } }, "fr": { "stringUnit": { "state": "translated", - "value": "L’écran affiché à l’ouverture de NX Library." + "value": "L’écran affiché à l’ouverture d’Arcane." } }, "de": { "stringUnit": { "state": "translated", - "value": "Die Ansicht, mit der NX Library geöffnet wird." + "value": "Die Ansicht, mit der Arcane geöffnet wird." } }, "es": { "stringUnit": { "state": "translated", - "value": "La pantalla que muestra NX Library al abrirse." + "value": "La pantalla que muestra Arcane al abrirse." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A tela inicial do NX Library." + "value": "A tela inicial do Arcane." } } } }, - "The screen NX Library opens on: Spotlight, Collection, or where you left it.": { + "The screen Arcane opens on: Spotlight, Collection, or where you left it.": { "comment": "SettingsCatalog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The screen NX Library opens on: Spotlight, Collection, or where you left it." + "value": "The screen Arcane opens on: Spotlight, Collection, or where you left it." } }, "it": { "stringUnit": { "state": "translated", - "value": "La schermata iniziale di NX Library: Spotlight, Raccolta o l’ultima aperta." + "value": "La schermata iniziale di Arcane: Spotlight, Raccolta o l’ultima aperta." } }, "fr": { "stringUnit": { "state": "translated", - "value": "L’écran affiché à l’ouverture de NX Library : À la une, Collection ou le dernier écran utilisé." + "value": "L’écran affiché à l’ouverture d’Arcane : À la une, Collection ou le dernier écran utilisé." } }, "de": { "stringUnit": { "state": "translated", - "value": "Die Ansicht, mit der NX Library geöffnet wird: Spotlight, Sammlung oder die zuletzt verwendete." + "value": "Die Ansicht, mit der Arcane geöffnet wird: Spotlight, Sammlung oder die zuletzt verwendete." } }, "es": { "stringUnit": { "state": "translated", - "value": "La pantalla que muestra NX Library al abrirse: Destacados, Colección o donde lo dejaste." + "value": "La pantalla que muestra Arcane al abrirse: Destacados, Colección o donde lo dejaste." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A tela inicial do NX Library: Destaques, Coleção ou onde você parou." + "value": "A tela inicial do Arcane: Destaques, Coleção ou onde você parou." } } } @@ -58679,84 +61432,84 @@ } } }, - "The source files are missing. Attach or locate the original base, update and DLC files first.": { - "comment": "NXLibraryError.swift", + "The source changed during the scan. Refresh it again.": { + "comment": "Steam source management and native Mac library presentation.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The source files are missing. Attach or locate the original base, update and DLC files first." + "value": "The source changed during the scan. Refresh it again." } }, "it": { "stringUnit": { "state": "translated", - "value": "I file sorgente non sono disponibili. Prima collega o individua i file originali del gioco base, degli aggiornamenti e dei DLC." + "value": "La fonte è cambiata durante la scansione. Aggiornala di nuovo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Les fichiers sources sont introuvables. Associez ou localisez d’abord les fichiers d’origine du jeu de base, des mises à jour et des DLC." + "value": "La source a changé pendant l’analyse. Actualisez-la à nouveau." } }, "de": { "stringUnit": { "state": "translated", - "value": "Die Quelldateien fehlen. Ordne zuerst die ursprünglichen Dateien für Basisspiel, Update und DLC zu oder suche sie." + "value": "Die Quelle hat sich während der Suche geändert. Aktualisiere sie erneut." } }, "es": { "stringUnit": { "state": "translated", - "value": "Faltan los archivos de origen. Primero vincula o localiza los archivos originales del juego base, las actualizaciones y los DLC." + "value": "La fuente cambió durante la exploración. Actualízala de nuevo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Os arquivos de origem não foram encontrados. Primeiro, vincule ou localize os arquivos originais do jogo base, das atualizações e dos DLCs." + "value": "A fonte mudou durante a busca. Atualize-a novamente." } } } }, - "The sources are detached: attach them again to rebuild.": { - "comment": "BuildSourcesPanel.swift", + "The source files are missing. Attach or locate the original base, update and DLC files first.": { + "comment": "NXLibraryError.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The sources are detached: attach them again to rebuild." + "value": "The source files are missing. Attach or locate the original base, update and DLC files first." } }, "it": { "stringUnit": { "state": "translated", - "value": "Le sorgenti sono scollegate: collegale di nuovo per ricompilare." + "value": "I file sorgente non sono disponibili. Prima collega o individua i file originali del gioco base, degli aggiornamenti e dei DLC." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Les sources sont dissociées : associez-les à nouveau pour recompiler." + "value": "Les fichiers sources sont introuvables. Associez ou localisez d’abord les fichiers d’origine du jeu de base, des mises à jour et des DLC." } }, "de": { "stringUnit": { "state": "translated", - "value": "Die Quellen sind getrennt: Ordne sie erneut zu, um die App erneut zu erstellen." + "value": "Die Quelldateien fehlen. Ordne zuerst die ursprünglichen Dateien für Basisspiel, Update und DLC zu oder suche sie." } }, "es": { "stringUnit": { "state": "translated", - "value": "Los archivos de origen están desvinculados: vuelve a vincularlos para recompilar." + "value": "Faltan los archivos de origen. Primero vincula o localiza los archivos originales del juego base, las actualizaciones y los DLC." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Os arquivos de origem estão desvinculados: vincule-os novamente para recompilar." + "value": "Os arquivos de origem não foram encontrados. Primeiro, vincule ou localize os arquivos originais do jogo base, das atualizações e dos DLCs." } } } @@ -59663,84 +62416,125 @@ } } }, - "This NX Library uses nxnative %@; the engine here is at %@. Update downloads it and switches to it. Games you built keep playing.": { + "This version of Arcane uses nxnative %@; the engine here is at %@. Update downloads it and switches to it. Games you built keep playing.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "This NX Library uses nxnative %@; the engine here is at %@. Update downloads it and switches to it. Games you built keep playing." + "value": "This version of Arcane uses nxnative %@; the engine here is at %@. Update downloads it and switches to it. Games you built keep playing." } }, "it": { "stringUnit": { "state": "translated", - "value": "Questa NX Library usa nxnative %@; il motore qui è al commit %@. Con Aggiorna lo scarichi e passi a quella versione. I giochi già compilati continuano a funzionare." + "value": "Questa Arcane usa nxnative %@; il motore qui è al commit %@. Con Aggiorna lo scarichi e passi a quella versione. I giochi già compilati continuano a funzionare." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Cette version de NX Library utilise nxnative %@ ; le moteur présent est au commit %@. Mettre à jour le télécharge et bascule dessus. Les jeux déjà compilés restent jouables." + "value": "Cette version d’Arcane utilise nxnative %@ ; le moteur présent est au commit %@. Mettre à jour le télécharge et bascule dessus. Les jeux déjà compilés restent jouables." } }, "de": { "stringUnit": { "state": "translated", - "value": "Diese NX Library-Version verwendet nxnative %@; die Engine hier steht auf %@. „Aktualisieren“ lädt die Version und wechselt zu ihr. Bereits erstellte Spiele bleiben spielbar." + "value": "Diese Arcane-Version verwendet nxnative %@; die Engine hier steht auf %@. „Aktualisieren“ lädt die Version und wechselt zu ihr. Bereits erstellte Spiele bleiben spielbar." } }, "es": { "stringUnit": { "state": "translated", - "value": "Este NX Library usa nxnative %@; el motor local está en %@. Actualizar lo descarga y cambia a esa versión. Los juegos ya compilados siguen funcionando." + "value": "Este Arcane usa nxnative %@; el motor local está en %@. Actualizar lo descarga y cambia a esa versión. Los juegos ya compilados siguen funcionando." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Este NX Library usa o nxnative %@; a engine aqui está em %@. Atualizar baixa a versão e muda para ela. Seus jogos compilados continuam funcionando." + "value": "Este Arcane usa o nxnative %@; a engine aqui está em %@. Atualizar baixa a versão e muda para ela. Seus jogos compilados continuam funcionando." } } } }, - "This NX Library uses the newest nxnative.": { + "This version of Arcane uses the newest nxnative.": { "comment": "UpstreamCopy.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "This NX Library uses the newest nxnative." + "value": "This version of Arcane uses the newest nxnative." } }, "it": { "stringUnit": { "state": "translated", - "value": "Questa NX Library usa la versione più recente di nxnative." + "value": "Questa Arcane usa la versione più recente di nxnative." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Cette version de NX Library utilise le dernier nxnative." + "value": "Cette version d’Arcane utilise le dernier nxnative." } }, "de": { "stringUnit": { "state": "translated", - "value": "Diese NX Library-Version verwendet das neueste nxnative." + "value": "Diese Arcane-Version verwendet das neueste nxnative." } }, "es": { "stringUnit": { "state": "translated", - "value": "Este NX Library usa el nxnative más reciente." + "value": "Este Arcane usa el nxnative más reciente." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Este NX Library usa o nxnative mais recente." + "value": "Este Arcane usa o nxnative mais recente." + } + } + } + }, + "This action is not available for this game.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This action is not available for this game." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Questa azione non è disponibile per il gioco." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cette action n’est pas disponible pour ce jeu." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Diese Aktion ist für dieses Spiel nicht verfügbar." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Esta acción no está disponible para este juego." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Esta ação não está disponível para este jogo." } } } @@ -59786,6 +62580,47 @@ } } }, + "This app is not affiliated with Valve.": { + "comment": "SettingsAboutSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This app is not affiliated with Valve." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Questa app non è affiliata a Valve." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cette app n’est pas affiliée à Valve." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Diese App steht in keiner Verbindung zu Valve." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Esta app no está afiliada a Valve." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Este app não tem afiliação com a Valve." + } + } + } + }, "This archive can't be opened.": { "comment": "ModInstaller.swift", "localizations": { @@ -59991,43 +62826,43 @@ } } }, - "This changes NX Library, not the language inside your games.": { + "This changes Arcane, not the language inside your games.": { "comment": "Language/region preferences and existing library filters.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "This changes NX Library, not the language inside your games." + "value": "This changes Arcane, not the language inside your games." } }, "it": { "stringUnit": { "state": "translated", - "value": "Modifica NX Library, non la lingua all’interno dei giochi." + "value": "Modifica Arcane, non la lingua all’interno dei giochi." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Ce réglage modifie NX Library, pas la langue dans vos jeux." + "value": "Ce réglage modifie Arcane, pas la langue dans vos jeux." } }, "de": { "stringUnit": { "state": "translated", - "value": "Dies ändert NX Library, nicht die Sprache in deinen Spielen." + "value": "Dies ändert Arcane, nicht die Sprache in deinen Spielen." } }, "es": { "stringUnit": { "state": "translated", - "value": "Esto cambia NX Library, no el idioma de tus juegos." + "value": "Esto cambia Arcane, no el idioma de tus juegos." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Isso altera o NX Library, não o idioma dentro dos seus jogos." + "value": "Isso altera o Arcane, não o idioma dentro dos seus jogos." } } } @@ -60688,6 +63523,47 @@ } } }, + "This source is disabled. Enable it in Game sources.": { + "comment": "Steam source management and native Mac library presentation.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This source is disabled. Enable it in Game sources." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Questa fonte è disattivata. Attivala in Fonti." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cette source est désactivée. Activez-la dans Sources de jeux." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Diese Quelle ist deaktiviert. Aktiviere sie unter Spielequellen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Esta fuente está desactivada. Actívala en Fuentes de juegos." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Esta fonte está desativada. Ative-a em Fontes de jogos." + } + } + } + }, "This version's cheat files go to the Trash.": { "comment": "CheatsPanel.swift:298", "localizations": { @@ -61221,47 +64097,6 @@ } } }, - "Turn off Cloud saves in Settings → Games to import or restore.": { - "comment": "SavesPanel.swift:204", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Turn off Cloud saves in Settings → Games to import or restore." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Disattiva Salvataggi cloud in Impostazioni → Giochi per importare o ripristinare." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Désactivez Sauvegardes dans le cloud dans Réglages → Jeux pour importer ou restaurer." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Deaktiviere Cloud-Spielstände unter Einstellungen → Spiele, um Spielstände zu importieren oder wiederherzustellen." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Desactiva Partidas en la nube en Ajustes → Juegos para importar o restaurar." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Desative Dados salvos na nuvem em Ajustes → Jogos para importar ou restaurar." - } - } - } - }, "Turn off Cloud saves in the game's own settings first.": { "comment": "SavesPanel.swift:206", "localizations": { @@ -61713,84 +64548,125 @@ } } }, - "Unsaved progress in the game will be lost.": { - "comment": "AppShellView.swift", + "Unlocked": { + "comment": "Achievements filter: unlocked ones.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Unsaved progress in the game will be lost." + "value": "Unlocked" } }, "it": { "stringUnit": { "state": "translated", - "value": "I progressi non salvati nel gioco andranno persi." + "value": "Sbloccati" } }, "fr": { "stringUnit": { "state": "translated", - "value": "La progression non sauvegardée dans le jeu sera perdue." + "value": "Débloqués" } }, "de": { "stringUnit": { "state": "translated", - "value": "Nicht gespeicherter Spielfortschritt geht verloren." + "value": "Freigeschaltet" } }, "es": { "stringUnit": { "state": "translated", - "value": "Se perderá el progreso del juego que no hayas guardado." + "value": "Desbloqueados" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O progresso não salvo no jogo será perdido." + "value": "Desbloqueadas" } } } }, - "Untested toolchain": { - "comment": "BuildSourcesPanel.swift", + "Unlocked on %@": { + "comment": "Achievement detail: the unlock date, e.g. \"Unlocked on 31 Jul 2026\".", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Untested toolchain" + "value": "Unlocked on %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "Toolchain non testata" + "value": "Sbloccato il %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Chaîne d’outils non testée" + "value": "Débloqué le %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "Ungetestete Toolchain" + "value": "Freigeschaltet am %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "Cadena de herramientas no probada" + "value": "Desbloqueado el %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Conjunto de ferramentas não testado" + "value": "Desbloqueado em %@" + } + } + } + }, + "Unsaved progress in the game will be lost.": { + "comment": "AppShellView.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unsaved progress in the game will be lost." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "I progressi non salvati nel gioco andranno persi." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "La progression non sauvegardée dans le jeu sera perdue." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nicht gespeicherter Spielfortschritt geht verloren." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Se perderá el progreso del juego que no hayas guardado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O progresso não salvo no jogo será perdido." } } } @@ -61918,43 +64794,43 @@ } } }, - "Update NX Library: its built-in Python includes zbic from 0.1.3.2. Installing zbic with pip does not reach it.": { + "Update Arcane: its built-in Python includes zbic from 0.1.3.2. Installing zbic with pip does not reach it.": { "comment": "PortingFailureReason.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Update NX Library: its built-in Python includes zbic from 0.1.3.2. Installing zbic with pip does not reach it." + "value": "Update Arcane: its built-in Python includes zbic from 0.1.3.2. Installing zbic with pip does not reach it." } }, "it": { "stringUnit": { "state": "translated", - "value": "Aggiorna NX Library: dalla versione 0.1.3.2 il Python incluso contiene zbic. Installare zbic con pip non lo rende disponibile nell’ambiente incluso." + "value": "Aggiorna Arcane: dalla versione 0.1.3.2 il Python incluso contiene zbic. Installare zbic con pip non lo rende disponibile nell’ambiente incluso." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Mettez NX Library à jour : son Python intégré inclut zbic depuis la version 0.1.3.2. Installer zbic avec pip n’a aucun effet sur ce Python." + "value": "Mettez Arcane à jour : son Python intégré inclut zbic depuis la version 0.1.3.2. Installer zbic avec pip n’a aucun effet sur ce Python." } }, "de": { "stringUnit": { "state": "translated", - "value": "Aktualisiere NX Library: Das integrierte Python enthält zbic ab 0.1.3.2. Eine Installation von zbic mit pip erreicht es nicht." + "value": "Aktualisiere Arcane: Das integrierte Python enthält zbic ab 0.1.3.2. Eine Installation von zbic mit pip erreicht es nicht." } }, "es": { "stringUnit": { "state": "translated", - "value": "Actualiza NX Library: su Python integrado incluye zbic desde la versión 0.1.3.2. Instalar zbic con pip no lo añade a ese Python." + "value": "Actualiza Arcane: su Python integrado incluye zbic desde la versión 0.1.3.2. Instalar zbic con pip no lo añade a ese Python." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Atualize o NX Library: seu Python integrado inclui o zbic desde a versão 0.1.3.2. Instalar o zbic com pip não afeta esse Python." + "value": "Atualize o Arcane: seu Python integrado inclui o zbic desde a versão 0.1.3.2. Instalar o zbic com pip não afeta esse Python." } } } @@ -62574,6 +65450,47 @@ } } }, + "User %@": { + "comment": "NUP program identity or local multiuser save scope; cloud still covers the primary user and device only.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "User %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Utente %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Utilisateur %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Benutzer %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Usuario %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Usuário %@" + } + } + } + }, "User save": { "comment": "Save safety and presentation; user content stays unchanged.", "localizations": { @@ -62779,166 +65696,125 @@ } } }, - "Version %@": { - "comment": "SettingsSidebar.swift:12", + "Version": { + "comment": "DetailsFacts.swift: the game version row", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Version %@" + "value": "Version" } }, "it": { "stringUnit": { "state": "translated", - "value": "Versione %@" + "value": "Versione" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Version %@" + "value": "Version" } }, "de": { "stringUnit": { "state": "translated", - "value": "Version %@" + "value": "Version" } }, "es": { "stringUnit": { "state": "translated", - "value": "Versión %@" + "value": "Versión" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Versão %@" + "value": "Versão" } } } }, - "Version %@ · %@": { - "comment": "BuildSourcesPanel.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Version %@ · %@" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Versione %@ · %@" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Version %@ · %@" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Version %@ · %@" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Versión %@ · %@" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Versão %@ · %@" - } - } - } - }, - "Version %@ · %@ · %@": { - "comment": "BuildSourcesPanel.swift", + "Version %@": { + "comment": "SettingsSidebar.swift:12", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Version %@ · %@ · %@" + "value": "Version %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "Versione %@ · %@ · %@" + "value": "Versione %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Version %@ · %@ · %@" + "value": "Version %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "Version %@ · %@ · %@" + "value": "Version %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "Versión %@ · %@ · %@" + "value": "Versión %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Versão %@ · %@ · %@" + "value": "Versão %@" } } } }, - "Version %@ came with this Xcode; the engine is tested with %@. New builds wait for an NX Library update tested with it. Games you built still play.": { + "Version %@ came with this Xcode; the engine is tested with %@. New builds wait for an Arcane update tested with it. Games you built still play.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Version %@ came with this Xcode; the engine is tested with %@. New builds wait for an NX Library update tested with it. Games you built still play." + "value": "Version %@ came with this Xcode; the engine is tested with %@. New builds wait for an Arcane update tested with it. Games you built still play." } }, "it": { "stringUnit": { "state": "translated", - "value": "La versione %@ è inclusa in questo Xcode; il motore è testato con %@. Per nuove compilazioni occorre attendere un aggiornamento di NX Library testato con questa versione. I giochi già compilati funzionano comunque." + "value": "La versione %@ è inclusa in questo Xcode; il motore è testato con %@. Per nuove compilazioni occorre attendere un aggiornamento di Arcane testato con questa versione. I giochi già compilati funzionano comunque." } }, "fr": { "stringUnit": { "state": "translated", - "value": "La version %@ est fournie avec ce Xcode ; le moteur est testé avec %@. Les nouvelles compilations attendent une mise à jour de NX Library testée avec elle. Les jeux déjà compilés restent jouables." + "value": "La version %@ est fournie avec ce Xcode ; le moteur est testé avec %@. Les nouvelles compilations attendent une mise à jour d’Arcane testée avec elle. Les jeux déjà compilés restent jouables." } }, "de": { "stringUnit": { "state": "translated", - "value": "Version %@ wurde mit diesem Xcode geliefert; die Engine wurde mit %@ getestet. Neue Builds warten auf ein damit getestetes NX Library-Update. Bereits erstellte Spiele bleiben spielbar." + "value": "Version %@ wurde mit diesem Xcode geliefert; die Engine wurde mit %@ getestet. Neue Builds warten auf ein damit getestetes Arcane-Update. Bereits erstellte Spiele bleiben spielbar." } }, "es": { "stringUnit": { "state": "translated", - "value": "La versión %@ viene con este Xcode; el motor se ha probado con %@. Las nuevas compilaciones deben esperar a una actualización de NX Library probada con ella. Los juegos ya compilados siguen funcionando." + "value": "La versión %@ viene con este Xcode; el motor se ha probado con %@. Las nuevas compilaciones deben esperar a una actualización de Arcane probada con ella. Los juegos ya compilados siguen funcionando." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "A versão %@ veio com este Xcode; a engine foi testada com %@. Novas compilações aguardam uma atualização do NX Library testada com ela. Seus jogos compilados continuam funcionando." + "value": "A versão %@ veio com este Xcode; a engine foi testada com %@. Novas compilações aguardam uma atualização do Arcane testada com ela. Seus jogos compilados continuam funcionando." } } } @@ -63066,43 +65942,43 @@ } } }, - "Version %@; the engine is tested with %@. NX Library installs %@ through Xcode.": { + "Version %@; the engine is tested with %@. Arcane installs %@ through Xcode.": { "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Version %@; the engine is tested with %@. NX Library installs %@ through Xcode." + "value": "Version %@; the engine is tested with %@. Arcane installs %@ through Xcode." } }, "it": { "stringUnit": { "state": "translated", - "value": "Versione %@; il motore è testato con %@. NX Library installa %@ tramite Xcode." + "value": "Versione %@; il motore è testato con %@. Arcane installa %@ tramite Xcode." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Version %@ ; le moteur est testé avec %@. NX Library installe %@ via Xcode." + "value": "Version %@ ; le moteur est testé avec %@. Arcane installe %@ via Xcode." } }, "de": { "stringUnit": { "state": "translated", - "value": "Version %@; die Engine wurde mit %@ getestet. NX Library installiert %@ über Xcode." + "value": "Version %@; die Engine wurde mit %@ getestet. Arcane installiert %@ über Xcode." } }, "es": { "stringUnit": { "state": "translated", - "value": "Versión %@; el motor se ha probado con %@. NX Library instala %@ a través de Xcode." + "value": "Versión %@; el motor se ha probado con %@. Arcane instala %@ a través de Xcode." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Versão %@; a engine foi testada com %@. O NX Library instala %@ pelo Xcode." + "value": "Versão %@; a engine foi testada com %@. O Arcane instala %@ pelo Xcode." } } } @@ -63271,6 +66147,47 @@ } } }, + "View all": { + "comment": "DetailsAchievementsCard.swift: replaces the completion while the card is hovered or focused; opens the Achievements screen", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "View all" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Vedi tutti" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Tout afficher" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Alle anzeigen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Ver todos" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Ver todos" + } + } + } + }, "View all on GitHub": { "comment": "SettingsEngineSection.swift", "localizations": { @@ -63681,6 +66598,47 @@ } } }, + "Waiting for Steam to start the game…": { + "comment": "CatalogSteamInfo.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Waiting for Steam to start the game…" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "In attesa che Steam avvii il gioco…" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "En attente du lancement du jeu par Steam…" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Warte, bis Steam das Spiel startet …" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Esperando a que Steam inicie el juego…" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Aguardando o Steam iniciar o jogo…" + } + } + } + }, "Waiting for build output…": { "comment": "BuildLiveLogsDrawer.swift", "localizations": { @@ -64132,6 +67090,47 @@ } } }, + "When Play opens Steam, it starts quietly. The waiting screen stays visible while the game starts. Steam comes forward if it needs input or the game takes too long.": { + "comment": "SettingsSourcesSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "When Play opens Steam, it starts quietly. The waiting screen stays visible while the game starts. Steam comes forward if it needs input or the game takes too long." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Quando Gioca apre Steam, lo avvia in background. La schermata di attesa resta visibile mentre parte il gioco. Steam viene in primo piano se serve una risposta o se il gioco tarda ad avviarsi." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Quand Jouer ouvre Steam, il démarre en arrière-plan. L’écran d’attente reste visible pendant le lancement du jeu. Steam passe au premier plan s’il attend une réponse ou si le jeu tarde à démarrer." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Wenn „Spielen“ Steam öffnet, startet es im Hintergrund. Der Wartebildschirm bleibt beim Spielstart sichtbar. Steam kommt nach vorne, wenn eine Eingabe nötig ist oder der Start zu lange dauert." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Cuando Jugar abre Steam, lo inicia en segundo plano. La pantalla de espera sigue visible mientras se inicia el juego. Steam pasa al primer plano si necesita una respuesta o si el juego tarda demasiado." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Quando Jogar abre o Steam, ele inicia em segundo plano. A tela de espera continua visível enquanto o jogo inicia. O Steam vem para a frente se precisar de uma resposta ou se o jogo demorar para iniciar." + } + } + } + }, "When you close a game, a card shows how long you played this time and in total.": { "comment": "SettingsCatalog.swift", "localizations": { @@ -65034,47 +68033,6 @@ } } }, - "Xcode unknown": { - "comment": "SettingsStartUpSection.swift", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Xcode unknown" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Xcode sconosciuto" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Xcode inconnu" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Xcode unbekannt" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "Xcode desconocido" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Xcode desconhecido" - } - } - } - }, "Y": { "comment": "ButtonPrompts.swift:38", "localizations": { @@ -65198,43 +68156,43 @@ } } }, - "You have NX Library %@. No newer release is available.": { + "You have Arcane %@. No newer release is available.": { "comment": "AppUpdateDialog.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "You have NX Library %@. No newer release is available." + "value": "You have Arcane %@. No newer release is available." } }, "it": { "stringUnit": { "state": "translated", - "value": "Hai NX Library %@. Non sono disponibili versioni più recenti." + "value": "Hai Arcane %@. Non sono disponibili versioni più recenti." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Vous disposez de NX Library %@. Aucune version plus récente n’est disponible." + "value": "Vous disposez d’Arcane %@. Aucune version plus récente n’est disponible." } }, "de": { "stringUnit": { "state": "translated", - "value": "Du hast NX Library %@. Es ist keine neuere Veröffentlichung verfügbar." + "value": "Du hast Arcane %@. Es ist keine neuere Veröffentlichung verfügbar." } }, "es": { "stringUnit": { "state": "translated", - "value": "Tienes NX Library %@. No hay ninguna versión más reciente." + "value": "Tienes Arcane %@. No hay ninguna versión más reciente." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Você tem o NX Library %@. Não há versão mais recente disponível." + "value": "Você tem o Arcane %@. Não há versão mais recente disponível." } } } @@ -65403,43 +68361,43 @@ } } }, - "Your activity": { - "comment": "DetailsBands.swift:63", + "Your Steam files stay where they are. Disabling this source keeps its games and personal choices.": { + "comment": "Steam source management and native Mac library presentation.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Your activity" + "value": "Your Steam files stay where they are. Disabling this source keeps its games and personal choices." } }, "it": { "stringUnit": { "state": "translated", - "value": "La tua attività" + "value": "I file di Steam restano al loro posto. Disattivando questa fonte, i giochi e le tue scelte vengono conservati." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Votre activité" + "value": "Vos fichiers Steam restent à leur place. Désactiver cette source conserve ses jeux et vos choix personnels." } }, "de": { "stringUnit": { "state": "translated", - "value": "Deine Aktivität" + "value": "Deine Steam-Dateien bleiben an ihrem Platz. Beim Deaktivieren dieser Quelle bleiben ihre Spiele und deine Einstellungen erhalten." } }, "es": { "stringUnit": { "state": "translated", - "value": "Tu actividad" + "value": "Tus archivos de Steam permanecen donde están. Al desactivar esta fuente se conservan sus juegos y tus preferencias." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Sua atividade" + "value": "Seus arquivos Steam ficam onde estão. Desativar esta fonte mantém seus jogos e suas preferências." } } } @@ -65813,6 +68771,88 @@ } } }, + "Your library could not be read. Its files have been kept. Open the library folder, then try again.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your library could not be read. Its files have been kept. Open the library folder, then try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile leggere la libreria. I file sono stati conservati. Apri la cartella della libreria, poi riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible de lire votre bibliothèque. Ses fichiers ont été conservés. Ouvrez le dossier de la bibliothèque, puis réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Deine Bibliothek konnte nicht gelesen werden. Die Dateien wurden aufbewahrt. Öffne den Bibliotheksordner und versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo leer tu biblioteca. Sus archivos se han conservado. Abre la carpeta de la biblioteca y vuelve a intentarlo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível ler sua biblioteca. Os arquivos foram preservados. Abra a pasta da biblioteca e tente novamente." + } + } + } + }, + "Your library could not be read. Restore its backup or open the library folder to review the files.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your library could not be read. Restore its backup or open the library folder to review the files." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile leggere la libreria. Ripristina il backup oppure apri la cartella della libreria per controllare i file." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible de lire votre bibliothèque. Restaurez sa sauvegarde ou ouvrez son dossier pour examiner les fichiers." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Deine Bibliothek konnte nicht gelesen werden. Stelle die Sicherung wieder her oder öffne den Bibliotheksordner, um die Dateien zu prüfen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo leer tu biblioteca. Restaura su copia de seguridad o abre la carpeta de la biblioteca para revisar los archivos." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível ler sua biblioteca. Restaure o backup ou abra a pasta da biblioteca para verificar os arquivos." + } + } + } + }, "Your own": { "comment": "WallpaperCatalog.swift", "localizations": { @@ -66018,6 +69058,47 @@ } } }, + "Your previous library could not be read. The original files have been kept.": { + "comment": "Catalog activation and recovery", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your previous library could not be read. The original files have been kept." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile leggere la libreria precedente. I file originali sono stati conservati." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible de lire votre ancienne bibliothèque. Les fichiers originaux ont été conservés." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Deine bisherige Bibliothek konnte nicht gelesen werden. Die Originaldateien wurden aufbewahrt." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudo leer tu biblioteca anterior. Se han conservado los archivos originales." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível ler sua biblioteca anterior. Os arquivos originais foram preservados." + } + } + } + }, "You’re up to date": { "comment": "AppUpdateDialog.swift", "localizations": { @@ -66223,2698 +69304,7204 @@ } } }, - "checked by the build command": { + "current %@, expected %@": { + "comment": "CompatibilityChecker.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "current %@, expected %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "attuale %@, previsto %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "actuel %@, attendu %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "aktuell %@, erwartet %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "actual %@, esperado %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "atual %@, esperado %@" + } + } + } + }, + "done": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "done" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "completato" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "terminé" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "fertig" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "hecho" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "concluído" + } + } + } + }, + "end": { + "comment": "ButtonPrompts.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "end" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "end" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "fin" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Ende" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "fin" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "end" + } + } + } + }, + "esc": { + "comment": "ButtonPrompts.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "esc" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "esc" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "esc" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "esc" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "esc" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "esc" + } + } + } + }, + "fullGameImageFileName": { + "comment": "LaunchBoxArt.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "fullGameImageFileName" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "fullGameImageFileName" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "fullGameImageFileName" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "fullGameImageFileName" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "fullGameImageFileName" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "fullGameImageFileName" + } + } + } + }, + "git could not run": { + "comment": "NewestEngine.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "git could not run" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "impossibile eseguire git" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "git n’a pas pu s’exécuter" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "git konnte nicht ausgeführt werden" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "no se ha podido ejecutar git" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "não foi possível executar git" + } + } + } + }, + "header_key does not open %@.": { + "comment": "PortingFailureReason.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "header_key does not open %@." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "header_key non apre %@." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "header_key ne permet pas de déchiffrer %@." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "header_key kann %@ nicht öffnen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "header_key no abre %@." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "header_key não abre %@." + } + } + } + }, + "header_key present · %@ application key generations": { "comment": "SettingsEngineSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "checked by the build command" + "value": "header_key present · %@ application key generations" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "header_key presente · %@ generazioni di chiavi applicazione" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "header_key présente · %@ générations de clés d’application" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "header_key vorhanden · %@ Anwendungsschlüsselgenerationen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "header_key presente · %@ generaciones de claves de aplicación" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "header_key presente · %@ gerações de chaves de aplicativo" + } + } + } + }, + "home": { + "comment": "ButtonPrompts.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "home" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "home" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "début" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Pos1" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "inicio" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "home" + } + } + } + }, + "iCloud Drive": { + "comment": "CloudSaves.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive" + } + } + } + }, + "iCloud Drive is not on for this Mac. Turn it on in System Settings › Apple Account › iCloud, or choose a folder.": { + "comment": "CloudSavesPreferences.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive is not on for this Mac. Turn it on in System Settings › Apple Account › iCloud, or choose a folder." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive non è attivo su questo Mac. Attivalo in Impostazioni di Sistema › Apple Account › iCloud oppure scegli una cartella." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive n’est pas activé sur ce Mac. Activez-le dans Réglages Système › Compte Apple › iCloud, ou choisissez un dossier." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive ist auf diesem Mac nicht aktiviert. Aktiviere es unter Systemeinstellungen › Apple Account › iCloud oder wähle einen Ordner." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "iCloud Drive no está activado en este Mac. Actívalo en Ajustes del Sistema › Cuenta de Apple › iCloud o elige una carpeta." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O iCloud Drive não está ativado neste Mac. Ative-o em Ajustes do Sistema › Conta Apple › iCloud ou escolha uma pasta." + } + } + } + }, + "iPhone Duo screen (1.43:1)": { + "comment": "Engine setting option display label.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "iPhone Duo screen (1.43:1)" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Schermo iPhone Duo (1.43:1)" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Écran iPhone Duo (1.43:1)" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "iPhone Duo-Bildschirm (1.43:1)" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Pantalla de iPhone Duo (1.43:1)" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Tela do iPhone Duo (1.43:1)" + } + } + } + }, + "imageFileName": { + "comment": "LaunchBoxArt.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "imageFileName" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "imageFileName" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "imageFileName" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "imageFileName" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "imageFileName" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "imageFileName" + } + } + } + }, + "imageTypeName": { + "comment": "LaunchBoxArt.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "imageTypeName" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "imageTypeName" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "imageTypeName" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "imageTypeName" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "imageTypeName" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "imageTypeName" + } + } + } + }, + "in": { + "comment": "SeleneArtBackground.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "in" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "presente" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "chargée" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "eingeblendet" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "en" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "carregada" + } + } + } + }, + "installed %@ · required %@": { + "comment": "SettingsEngineSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "installed %@ · required %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "installato %@ · richiesto %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "installé %@ · requis %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "installiert %@ · erforderlich %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "instalado %@ · necesario %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "instalado %@ · necessário %@" + } + } + } + }, + "installed %@, tested %@": { + "comment": "CompatibilityChecker.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "installed %@, tested %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "installato %@, testato %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "installé %@, testé %@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "installiert %@, getestet %@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "instalado %@, probado %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "instalado %@, testado %@" + } + } + } + }, + "local.nxlibrary.build.io": { + "comment": "BuildService.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.build.io" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.build.io" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.build.io" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.build.io" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.build.io" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.build.io" + } + } + } + }, + "local.nxlibrary.saves": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.saves" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.saves" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.saves" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.saves" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.saves" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.saves" + } + } + } + }, + "local.nxlibrary.sounds": { + "comment": "SoundEffectService.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.sounds" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.sounds" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.sounds" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.sounds" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.sounds" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "local.nxlibrary.sounds" + } + } + } + }, + "macOS could not launch %@.": { + "comment": "NXLibraryError.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "macOS could not launch %@." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "macOS non ha potuto avviare %@." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "macOS n’a pas pu lancer %@." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "macOS konnte %@ nicht starten." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "macOS no ha podido abrir %@." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O macOS não conseguiu abrir %@." + } + } + } + }, + "main has moved on: %@%@.": { + "comment": "NewestEngine.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "main has moved on: %@%@." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "main è avanzato: %@%@." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "main a progressé : %@%@." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "main hat sich weiterentwickelt: %@%@." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "main ha avanzado: %@%@." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "main avançou: %@%@." + } + } + } + }, + "missing": { + "comment": "NXNativeEnvironment.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "missing" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "non disponibile" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "manquant" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "fehlt" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "falta" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "ausente" + } + } + } + }, + "missing %@": { + "comment": "CompatibilityChecker.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "missing %@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "manca %@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ manquant" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ fehlt" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "falta %@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "falta %@" + } + } + } + }, + "none": { + "comment": "SeleneArtBackground.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "none" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "nessuna" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "aucune" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "keine" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "ninguno" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "ausente" + } + } + } + }, + "not found": { + "comment": "SettingsEngineSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "not found" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "non trovato" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "introuvable" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "nicht gefunden" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "no encontrado" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "não encontrado" + } + } + } + }, + "nxlibrary.setup-check": { + "comment": "SetupCheckModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "nxlibrary.setup-check" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "nxlibrary.setup-check" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "nxlibrary.setup-check" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "nxlibrary.setup-check" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "nxlibrary.setup-check" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "nxlibrary.setup-check" + } + } + } + }, + "nxnative CLI": { + "comment": "CompatibilityChecker.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "nxnative CLI" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "CLI di nxnative" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "CLI nxnative" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "nxnative-CLI" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "CLI de nxnative" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "CLI do nxnative" + } + } + } + }, + "nxnative engine": { + "comment": "SetupCheck.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "nxnative engine" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Motore nxnative" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Moteur nxnative" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "nxnative-Engine" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Motor nxnative" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Engine nxnative" + } + } + } + }, + "nxnative has %lld newer commits. Engine updates reach you with Arcane updates, once tested.": { + "comment": "Quantity-sensitive UI message; preserve %lld count and other placeholders.", + "localizations": { + "en": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "nxnative has %lld newer commit. Engine updates reach you with Arcane updates, once tested." + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "nxnative has %lld newer commits. Engine updates reach you with Arcane updates, once tested." + } + } + } + } + }, + "it": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "nxnative ha %lld commit più recente. Gli aggiornamenti del motore arrivano con gli aggiornamenti di Arcane, dopo essere stati testati." + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "nxnative ha %lld commit più recenti. Gli aggiornamenti del motore arrivano con gli aggiornamenti di Arcane, dopo essere stati testati." + } + } + } + } + }, + "fr": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "nxnative compte %lld commit plus récent. Les mises à jour du moteur vous parviennent avec celles de Arcane, une fois testées." + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "nxnative compte %lld commits plus récents. Les mises à jour du moteur vous parviennent avec celles de Arcane, une fois testées." + } + } + } + } + }, + "de": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "nxnative hat %lld neueren Commit. Engine-Updates erhältst du mit Arcane-Updates, sobald sie getestet wurden." + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "nxnative hat %lld neuere Commits. Engine-Updates erhältst du mit Arcane-Updates, sobald sie getestet wurden." + } + } + } + } + }, + "es": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "nxnative tiene %lld commit más reciente. Las actualizaciones del motor te llegan con las de Arcane, una vez probadas." + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "nxnative tiene %lld commits más recientes. Las actualizaciones del motor te llegan con las de Arcane, una vez probadas." + } + } + } + } + }, + "pt-BR": { + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "O nxnative tem %lld commit mais recente. As atualizações da engine chegam com as atualizações do Arcane, após serem testadas." + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "O nxnative tem %lld commits mais recentes. As atualizações da engine chegam com as atualizações do Arcane, após serem testadas." + } + } + } + } + } + } + }, + "nxnative, used as it is upstream, at the commit this version of Arcane is tested with.": { + "comment": "SetupCheck.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "nxnative, used as it is upstream, at the commit this version of Arcane is tested with." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "nxnative, usato senza modifiche rispetto a upstream, al commit con cui è testata questa versione di Arcane." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "nxnative, utilisé tel quel depuis le dépôt amont, au commit avec lequel cette version d’Arcane a été testée." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "nxnative, unverändert aus dem Upstream, mit dem Commit, mit dem diese Arcane-Version getestet wurde." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "nxnative, sin modificar respecto al proyecto original, en el commit con el que se ha probado este Arcane." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "nxnative, usado sem alterações do repositório original, no commit com o qual este Arcane foi testado." + } + } + } + }, + "picture": { + "comment": "Display copy only; internal values and paths remain unchanged.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "picture" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "immagine" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "image" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bild" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "imagen" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "imagem" + } + } + } + }, + "prod.keys": { + "comment": "SettingsEngineSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "prod.keys" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "prod.keys" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "prod.keys" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "prod.keys" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "prod.keys" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "prod.keys" + } + } + } + }, + "prod.keys imported: header key present, %@ application key generations.": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "prod.keys imported: header key present, %@ application key generations." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "prod.keys importato: chiave header presente, %@ generazioni di chiavi applicazione." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "prod.keys importé : clé d’en-tête présente, %@ générations de clés d’application." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "prod.keys importiert: Header-Schlüssel vorhanden, %@ Anwendungsschlüsselgenerationen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "prod.keys importado: clave de cabecera presente, %@ generaciones de claves de aplicación." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "prod.keys importado: chave de cabeçalho presente, %@ gerações de chaves de aplicativo." + } + } + } + }, + "prod.keys is missing, unreadable or has no header_key.": { + "comment": "PortingFailureReason.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "prod.keys is missing, unreadable or has no header_key." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "prod.keys non è disponibile, non è leggibile o non contiene header_key." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "prod.keys est absent, illisible ou ne contient pas de header_key." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "prod.keys fehlt, ist nicht lesbar oder enthält keinen header_key." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "prod.keys falta, no se puede leer o no contiene header_key." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "prod.keys está ausente, ilegível ou sem header_key." + } + } + } + }, + "prod.keys is missing. Import it in Settings.": { + "comment": "NXLibraryError.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "prod.keys is missing. Import it in Settings." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "prod.keys non è disponibile. Importalo in Impostazioni." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "prod.keys est introuvable. Importez-le dans les Réglages." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "prod.keys fehlt. Importiere die Datei in den Einstellungen." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Falta prod.keys. Impórtalo en Ajustes." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O arquivo prod.keys não foi encontrado. Importe-o nos Ajustes." + } + } + } + }, + "regionName": { + "comment": "LaunchBoxArt.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "regionName" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "regionName" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "regionName" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "regionName" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "regionName" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "regionName" + } + } + } + }, + "required options present": { + "comment": "CompatibilityChecker.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "required options present" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "opzioni richieste presenti" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "options requises présentes" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "erforderliche Optionen vorhanden" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "opciones necesarias presentes" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "opções obrigatórias presentes" + } + } + } + }, + "switched to": { + "comment": "AppViewModel+NewestEngine.swift:69", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "switched to" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "passato a" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "basculé vers" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "gewechselt zu" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "cambiado a" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "trocada para" + } + } + } + }, + "tab": { + "comment": "ButtonPrompts.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "tab" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "tab" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "tab" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Tab" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "tab" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "tab" + } + } + } + }, + "terminal": { + "comment": "BuildLiveLogsDrawer.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "terminal" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "terminale" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "terminal" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Terminal" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "terminal" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "terminal" + } + } + } + }, + "the bundled Python is missing; reinstall Arcane": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "the bundled Python is missing; reinstall Arcane" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "il Python incluso non è disponibile; reinstalla Arcane" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "le Python intégré est introuvable ; réinstallez Arcane" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "das mitgelieferte Python fehlt; installiere Arcane erneut" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "falta el Python incluido; reinstala Arcane" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "o Python incluído não foi encontrado; reinstale o Arcane" + } + } + } + }, + "the drive": { + "comment": "Display copy only; internal values and paths remain unchanged.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "the drive" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "il disco" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "le disque" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "das Laufwerk" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "la unidad" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "a unidade" + } + } + } + }, + "the environment check is still running": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "the environment check is still running" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "il controllo dell’ambiente è ancora in corso" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "la vérification de l’environnement est toujours en cours" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "die Umgebungsprüfung läuft noch" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "la comprobación del entorno sigue en curso" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "a verificação do ambiente ainda está em andamento" + } + } + } + }, + "the game": { + "comment": "Fallback display name when no game name is available.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "the game" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "il gioco" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "le jeu" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "das Spiel" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "el juego" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "o jogo" + } + } + } + }, + "the game’s files": { + "comment": "Display copy only; internal values and paths remain unchanged.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "the game’s files" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "i file del gioco" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "les fichiers du jeu" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "die Dateien des Spiels" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "los archivos del juego" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "os arquivos do jogo" + } + } + } + }, + "the nxnative venv Python is missing": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "the nxnative venv Python is missing" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "il Python del venv di nxnative non è disponibile" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "le Python de l’environnement venv de nxnative est introuvable" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "das Python der nxnative-venv fehlt" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "falta el Python del entorno virtual de nxnative" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "o Python do venv do nxnative não foi encontrado" + } + } + } + }, + "this session": { + "comment": "SessionCard.swift:91", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "this session" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "questa sessione" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "cette session" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "diese Sitzung" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "esta sesión" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "nesta sessão" + } + } + } + }, + "total": { + "comment": "SessionCard.swift:95", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "total" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "totale" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "au total" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "insgesamt" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "total" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "total" + } + } + } + }, + "truncated": { + "comment": "CheatFile.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "truncated" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "troncato" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "tronqué" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "abgeschnitten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "truncado" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "truncado" + } + } + } + }, + "turn them back on here or in the game's Cheats panel (⌘⇧C).": { + "comment": "CheatCopy.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "turn them back on here or in the game's Cheats panel (⌘⇧C)." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "riattivali qui o nel pannello Trucchi del gioco (⌘⇧C)." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "réactivez-les ici ou dans le panneau Codes de triche du jeu (⌘⇧C)." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "aktiviere sie hier oder im Cheats-Bereich des Spiels (⌘⇧C) erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "vuelve a activarlos aquí o en el panel de trucos del juego (⌘⇧C)." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "ative-as novamente aqui ou no painel Trapaças do jogo (⌘⇧C)." + } + } + } + }, + "under a minute": { + "comment": "Compact playtime units, metadata heading or accessible duration.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "under a minute" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "meno di un minuto" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "moins d’une minute" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "unter einer Minute" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "menos de un minuto" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "menos de um minuto" + } + } + } + }, + "unknown error": { + "comment": "NewestEngine.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "unknown error" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "errore sconosciuto" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "erreur inconnue" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "unbekannter Fehler" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "error desconocido" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "erro desconhecido" + } + } + } + }, + "updated from %@ to": { + "comment": "AppViewModel+NewestEngine.swift:69", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "updated from %@ to" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "aggiornato da %@ a" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "mis à jour de %@ vers" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "von %@ aktualisiert auf" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "actualizado de %@ a" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "atualizada de %@ para" + } + } + } + }, + "version %@ (build %@)": { + "comment": "CheatCopy.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "version %@ (build %@)" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "versione %@ (build %@)" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "version %@ (build %@)" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Version %@ (Build %@)" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "versión %@ (compilación %@)" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "versão %@ (build %@)" + } + } + } + }, + "version unavailable (requires 3.12+)": { + "comment": "CompatibilityChecker.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "version unavailable (requires 3.12+)" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "versione non disponibile (richiede 3.12+)" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "version indisponible (nécessite 3.12+)" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Version nicht verfügbar (3.12+ erforderlich)" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "versión no disponible (requiere 3.12+)" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "versão indisponível (requer 3.12+)" + } + } + } + }, + "video": { + "comment": "Display copy only; internal values and paths remain unchanged.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "video" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "video" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "vidéo" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Video" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "vídeo" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "vídeo" + } + } + } + }, + "wait for storage cleanup to finish": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "wait for storage cleanup to finish" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "attendi il termine della pulizia dello spazio di archiviazione" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "attendez la fin du nettoyage du stockage" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "warte, bis die Speicherbereinigung abgeschlossen ist" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "espera a que termine la limpieza del almacenamiento" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "aguarde o término da limpeza do armazenamento" + } + } + } + }, + "wait for the app icon update to finish": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "wait for the app icon update to finish" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "attendi il termine dell’aggiornamento dell’icona dell’app" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "attendez la fin de la mise à jour de l’icône de l’app" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "warte, bis das App-Symbol aktualisiert wurde" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "espera a que termine la actualización del icono de la app" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "aguarde o término da atualização do ícone do app" + } + } + } + }, + "wait for the app update to finish": { + "comment": "AppViewModel.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "wait for the app update to finish" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "attendi il termine dell’aggiornamento dell’app" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "attendez la fin de la mise à jour de l’app" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "warte, bis das App-Update abgeschlossen ist" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "espera a que termine la actualización de la app" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "aguarde o término da atualização do app" + } + } + } + }, + "©2026 Valve Corporation. Steam and the Steam logo are trademarks and/or registered trademarks of Valve Corporation in the U.S. and/or other countries.": { + "comment": "SettingsAboutSection.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "©2026 Valve Corporation. Steam and the Steam logo are trademarks and/or registered trademarks of Valve Corporation in the U.S. and/or other countries." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "©2026 Valve Corporation. Steam e il logo Steam sono marchi e/o marchi registrati appartenenti a Valve Corporation negli Stati Uniti e/o in altri Paesi." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "©2026 Valve Corporation. Steam et le logo Steam sont des marques déposées et/ou des marques enregistrées par Valve Corporation aux É.U. et/ou dans d'autres pays." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "©2026 Valve Corporation. Steam und das Steam Logo sind Marken und/oder eingetragene Warenzeichen von Valve Corporation in den USA und/oder anderen Ländern." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "©2026 Valve Corporation. Steam y el logotipo de Steam son marcas comerciales o marcas registradas de Valve Corporation en EE. UU. y otros países." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "©2026 Valve Corporation. Steam e o logotipo Steam são marcas e/ou marcas registradas da Valve Corporation nos EUA e/ou em outros países." + } + } + } + }, + "⌘K": { + "comment": "ButtonPrompts.swift:44", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "⌘K" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "⌘K" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "⌘K" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "⌘K" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "⌘K" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "⌘K" + } + } + } + }, + "⌘Return to save · Empty for Automatic": { + "comment": "ChangeMetadataView.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "⌘Return to save · Empty for Automatic" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "⌘Invio per salvare · Lascia vuoto per Automatico" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "⌘Retour pour enregistrer · Laisser vide pour Automatique" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "⌘Return zum Speichern · Leer lassen für „Automatisch“" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "⌘Retorno para guardar · Vacío para Automático" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "⌘Return para salvar · Deixe em branco para Automático" + } + } + } + }, + "◂ ▸ Move": { + "comment": "SpotlightView.swift", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "◂ ▸ Move" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "◂ ▸ Sposta" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "◂ ▸ Déplacer" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "◂ ▸ Verschieben" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "◂ ▸ Mover" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "◂ ▸ Mover" + } + } + } + }, + "%@ via Wikidata": { + "comment": "Critic score in Details: referenced aggregate via Wikidata; not a personal rating.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ via Wikidata" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%@ tramite Wikidata" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ via Wikidata" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ über Wikidata" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%@ a través de Wikidata" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%@ via Wikidata" + } + } + } + }, + "Critic score": { + "comment": "Critic score in Details: referenced aggregate via Wikidata; not a personal rating.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Critic score" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Voto della critica" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Note de la critique" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Kritikerwertung" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Puntuación de la crítica" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nota da crítica" + } + } + } + }, + "Platform not specified": { + "comment": "Critic score in Details: referenced aggregate via Wikidata; not a personal rating.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Platform not specified" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Piattaforma non specificata" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plateforme non précisée" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Plattform nicht angegeben" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Plataforma no especificada" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Plataforma não especificada" + } + } + } + }, + "Rating unavailable": { + "comment": "Critic score in Details: referenced aggregate via Wikidata; not a personal rating.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rating unavailable" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Voto non disponibile" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Note indisponible" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Wertung nicht verfügbar" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Puntuación no disponible" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nota indisponível" + } + } + } + }, + "Saved rating · refresh unavailable": { + "comment": "Critic score in Details: referenced aggregate via Wikidata; not a personal rating.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Saved rating · refresh unavailable" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Voto salvato · aggiornamento non disponibile" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Note enregistrée · actualisation indisponible" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Gespeicherte Wertung · Aktualisierung nicht verfügbar" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Puntuación guardada · actualización no disponible" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nota salva · atualização indisponível" + } + } + } + }, + "IGDB": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IGDB" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IGDB" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "IGDB" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "IGDB" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "IGDB" + } + } + } + }, + "Ratings": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Ratings" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Valutazioni" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Évaluations" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Bewertungen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Valoraciones" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Avaliações" + } + } + } + }, + "Connect": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Connect" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Collega" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Connecter" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Verbinden" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Conectar" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Conectar" + } + } + } + }, + "Edit credentials": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit credentials" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Modifica credenziali" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Modifier les identifiants" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Zugangsdaten bearbeiten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Editar credenciales" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Editar credenciais" + } + } + } + }, + "Client ID": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Client ID" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Client ID" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Client ID" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Client ID" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Client ID" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Client ID" + } + } + } + }, + "Client Secret": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Client Secret" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Client Secret" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Client Secret" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Client Secret" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Client Secret" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Client Secret" + } + } + } + }, + "Check and save": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check and save" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Verifica e salva" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Vérifier et enregistrer" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Prüfen und speichern" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Verificar y guardar" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Verificar e salvar" + } + } + } + }, + "Developer portal": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Developer portal" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Portale sviluppatori" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Portail développeurs" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Entwicklerportal" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Portal de desarrolladores" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Portal de desenvolvedores" + } + } + } + }, + "Setup guide": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Setup guide" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Guida alla configurazione" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Guide de configuration" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Einrichtungsanleitung" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Guía de configuración" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Guia de configuração" + } + } + } + }, + "Personal IGDB credentials for critic scores. Wikidata remains available without a key.": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Personal IGDB credentials for critic scores. Wikidata remains available without a key." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Credenziali IGDB personali per i voti della critica. Wikidata resta disponibile senza chiave." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Identifiants IGDB personnels pour les notes de la critique. Wikidata reste disponible sans clé." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Eigene IGDB-Zugangsdaten für Kritikerwertungen. Wikidata bleibt ohne Schlüssel verfügbar." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Credenciales personales de IGDB para las puntuaciones de la crítica. Wikidata sigue disponible sin clave." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Credenciais pessoais do IGDB para notas da crítica. O Wikidata continua disponível sem chave." + } + } + } + }, + "Critic scores with your own credentials": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Critic scores with your own credentials" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Voti della critica con le tue credenziali" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Notes de la critique avec vos identifiants" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Kritikerwertungen mit eigenen Zugangsdaten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Puntuaciones de la crítica con tus credenciales" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Notas da crítica com suas credenciais" + } + } + } + }, + "IGDB connected · Wikidata is the fallback": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB connected · Wikidata is the fallback" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IGDB collegato · Wikidata come alternativa" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IGDB connecté · Wikidata en secours" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "IGDB verbunden · Wikidata als Rückfallquelle" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "IGDB conectado · Wikidata como alternativa" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "IGDB conectado · Wikidata como alternativa" + } + } + } + }, + "Optional critic scores with your own credentials": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Optional critic scores with your own credentials" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Voti della critica facoltativi con le tue credenziali" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Notes de la critique facultatives avec vos identifiants" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Optionale Kritikerwertungen mit eigenen Zugangsdaten" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Puntuaciones de la crítica opcionales con tus credenciales" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Notas da crítica opcionais com suas credenciais" + } + } + } + }, + "Use your Twitch application credentials for critic scores. They stay on this Mac and are sent only to Twitch and IGDB.": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Use your Twitch application credentials for critic scores. They stay on this Mac and are sent only to Twitch and IGDB." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Usa le credenziali della tua applicazione Twitch per i voti della critica. Restano su questo Mac e vengono inviate solo a Twitch e IGDB." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Utilisez les identifiants de votre application Twitch pour les notes de la critique. Ils restent sur ce Mac et sont envoyés uniquement à Twitch et IGDB." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nutze die Zugangsdaten deiner Twitch-Anwendung für Kritikerwertungen. Sie bleiben auf diesem Mac und werden nur an Twitch und IGDB gesendet." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Usa las credenciales de tu aplicación Twitch para las puntuaciones de la crítica. Se guardan en este Mac y solo se envían a Twitch e IGDB." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Use as credenciais do seu aplicativo Twitch para notas da crítica. Elas ficam neste Mac e são enviadas apenas à Twitch e ao IGDB." + } + } + } + }, + "Enter the Client ID and Client Secret from your Twitch developer application.": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Enter the Client ID and Client Secret from your Twitch developer application." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Inserisci Client ID e Client Secret della tua applicazione nel portale sviluppatori Twitch." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Saisissez le Client ID et le Client Secret de votre application du portail développeurs Twitch." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Gib Client ID und Client Secret deiner Anwendung aus dem Twitch-Entwicklerportal ein." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Introduce el Client ID y el Client Secret de tu aplicación del portal de desarrolladores de Twitch." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Insira o Client ID e o Client Secret do seu aplicativo no portal de desenvolvedores da Twitch." + } + } + } + }, + "IGDB did not accept these credentials. Check the Client ID and Client Secret.": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB did not accept these credentials. Check the Client ID and Client Secret." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IGDB non ha accettato queste credenziali. Controlla Client ID e Client Secret." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IGDB a refusé ces identifiants. Vérifiez le Client ID et le Client Secret." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "IGDB hat diese Zugangsdaten abgelehnt. Prüfe Client ID und Client Secret." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "IGDB no ha aceptado estas credenciales. Comprueba el Client ID y el Client Secret." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O IGDB não aceitou essas credenciais. Confira o Client ID e o Client Secret." + } + } + } + }, + "IGDB could not be reached. Check the connection and try again.": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB could not be reached. Check the connection and try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IGDB non è raggiungibile. Controlla la connessione e riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IGDB est inaccessible. Vérifiez la connexion et réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "IGDB ist nicht erreichbar. Prüfe die Verbindung und versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se puede conectar con IGDB. Comprueba la conexión e inténtalo de nuevo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível acessar o IGDB. Verifique a conexão e tente novamente." + } + } + } + }, + "IGDB is busy. Wait a moment and try again.": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB is busy. Wait a moment and try again." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IGDB è occupato. Attendi un momento e riprova." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IGDB est occupé. Patientez un instant et réessayez." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "IGDB ist ausgelastet. Warte kurz und versuche es erneut." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "IGDB está ocupado. Espera un momento e inténtalo de nuevo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O IGDB está ocupado. Aguarde um momento e tente novamente." + } + } + } + }, + "IGDB credentials could not be saved on this Mac.": { + "comment": "Optional personal IGDB integration: settings, connection check and safe error copy.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB credentials could not be saved on this Mac." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Non è stato possibile salvare le credenziali IGDB su questo Mac." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible d’enregistrer les identifiants IGDB sur ce Mac." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die IGDB-Zugangsdaten konnten auf diesem Mac nicht gespeichert werden." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se han podido guardar las credenciales de IGDB en este Mac." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível salvar as credenciais do IGDB neste Mac." + } + } + } + }, + "Optional connections for ratings and game artwork.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Optional connections for ratings and game artwork." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Collegamenti facoltativi per valutazioni e immagini dei giochi." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Connexions facultatives pour les évaluations et les images des jeux." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Optionale Verbindungen für Bewertungen und Spielbilder." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Conexiones opcionales para valoraciones e imágenes de juegos." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Conexões opcionais para avaliações e imagens dos jogos." + } + } + } + }, + "Connect optional services to enrich your library with ratings and artwork. Public sources remain available without API keys.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Connect optional services to enrich your library with ratings and artwork. Public sources remain available without API keys." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Collega servizi facoltativi per arricchire la libreria con valutazioni e immagini. Le fonti pubbliche restano disponibili anche senza chiavi API." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Connectez des services facultatifs pour enrichir votre bibliothèque avec des évaluations et des images. Les sources publiques restent disponibles sans clé API." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Verbinde optionale Dienste, um deine Bibliothek mit Bewertungen und Bildern zu ergänzen. Öffentliche Quellen bleiben auch ohne API-Schlüssel verfügbar." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Conecta servicios opcionales para enriquecer tu biblioteca con valoraciones e imágenes. Las fuentes públicas siguen disponibles sin claves API." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Conecte serviços opcionais para enriquecer sua biblioteca com avaliações e imagens. As fontes públicas continuam disponíveis sem chaves de API." + } + } + } + }, + "Open the developer portal: Applications → Register Your Application.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open the developer portal: Applications → Register Your Application." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Apri il portale: Applications → Register Your Application." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ouvrez le portail : Applications → Register Your Application." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Öffne das Portal: Applications → Register Your Application." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Abre el portal: Applications → Register Your Application." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Abra o portal: Applications → Register Your Application." + } + } + } + }, + "Choose a unique name. OAuth Redirect URLs: http://localhost → Add.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose a unique name. OAuth Redirect URLs: http://localhost → Add." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Scegli un nome univoco. OAuth Redirect URLs: http://localhost → Add." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Choisissez un nom unique. OAuth Redirect URLs : http://localhost → Add." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Wähle einen eindeutigen Namen. OAuth Redirect URLs: http://localhost → Add." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Elige un nombre único. OAuth Redirect URLs: http://localhost → Add." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Escolha um nome único. OAuth Redirect URLs: http://localhost → Add." + } + } + } + }, + "Category: Application Integration. Client Type: Confidential.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Category: Application Integration. Client Type: Confidential." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Category: Application Integration. Client Type: Confidential." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Category: Application Integration. Client Type: Confidential." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Category: Application Integration. Client Type: Confidential." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Category: Application Integration. Client Type: Confidential." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Category: Application Integration. Client Type: Confidential." + } + } + } + }, + "Create → Manage → New Secret.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Create → Manage → New Secret." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Create → Manage → New Secret." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Create → Manage → New Secret." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Create → Manage → New Secret." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Create → Manage → New Secret." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Create → Manage → New Secret." + } + } + } + }, + "Paste Client ID and Client Secret below, then Check and save.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Paste Client ID and Client Secret below, then Check and save." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Incolla Client ID e Client Secret qui sotto, poi Verifica e salva." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Collez le Client ID et le Client Secret ci-dessous, puis Vérifier et enregistrer." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Füge Client ID und Client Secret unten ein, dann Prüfen und speichern." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Pega el Client ID y el Client Secret abajo y pulsa Verificar y guardar." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Cole o Client ID e o Client Secret abaixo e selecione Verificar e salvar." + } + } + } + }, + "Twitch requires a verified email and two-factor authentication.": { + "comment": "General API services page and concise Twitch/IGDB setup instructions. Keep official portal control names in English.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Twitch requires a verified email and two-factor authentication." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Twitch richiede email verificata e autenticazione a due fattori." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Twitch exige une adresse e-mail vérifiée et l’authentification à deux facteurs." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Twitch benötigt eine bestätigte E-Mail-Adresse und Zwei-Faktor-Authentifizierung." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Twitch requiere un correo verificado y autenticación de dos factores." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A Twitch exige e-mail verificado e autenticação de dois fatores." + } + } + } + }, + "User score": { + "comment": "Details rating: distinguish IGDB community scores from critic averages.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "User score" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Voto utenti" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Note des joueurs" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nutzerwertung" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Nota de usuarios" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nota dos usuários" + } + } + } + }, + "Users · IGDB": { + "comment": "Details rating: distinguish IGDB community scores from critic averages.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Users · IGDB" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Utenti · IGDB" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Joueurs · IGDB" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nutzer · IGDB" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Usuarios · IGDB" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Usuários · IGDB" + } + } + } + }, + "User ratings: %d": { + "comment": "Details rating: distinguish IGDB community scores from critic averages.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "User ratings: %d" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Voti utenti: %d" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Votes des joueurs : %d" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Nutzerbewertungen: %d" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Votos de usuarios: %d" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Votos dos usuários: %d" + } + } + } + }, + "Critic reviews: %d": { + "comment": "Details rating: distinguish IGDB community scores from critic averages.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Critic reviews: %d" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Recensioni della critica: %d" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Critiques de la presse : %d" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Kritikerrezensionen: %d" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Reseñas de la crítica: %d" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Resenhas da crítica: %d" + } + } + } + }, + "Looking for metadata…": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Looking for metadata…" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Ricerca metadati…" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Recherche de métadonnées…" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Metadaten werden gesucht…" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Buscando metadatos…" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Buscando metadados…" + } + } + } + }, + "Saved IGDB information · refresh unavailable": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Saved IGDB information · refresh unavailable" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Dati IGDB salvati · aggiornamento non disponibile" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Données IGDB enregistrées · actualisation indisponible" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Gespeicherte IGDB-Daten · Aktualisierung nicht verfügbar" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Datos IGDB guardados · actualización no disponible" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Dados IGDB salvos · atualização indisponível" + } + } + } + }, + "No matching IGDB game for this platform.": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No matching IGDB game for this platform." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessun gioco IGDB corrispondente per questa piattaforma." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucun jeu IGDB correspondant pour cette plateforme." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Kein passendes IGDB-Spiel für diese Plattform." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No hay un juego IGDB coincidente para esta plataforma." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhum jogo IGDB correspondente para esta plataforma." + } + } + } + }, + "Multiple IGDB matches · no game chosen automatically.": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Multiple IGDB matches · no game chosen automatically." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Più risultati IGDB · nessun gioco scelto automaticamente." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Plusieurs résultats IGDB · aucun jeu choisi automatiquement." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Mehrere IGDB-Treffer · kein Spiel automatisch ausgewählt." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Varios resultados IGDB · no se eligió ningún juego automáticamente." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Vários resultados IGDB · nenhum jogo escolhido automaticamente." + } + } + } + }, + "IGDB unavailable · other sources remain available.": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB unavailable · other sources remain available." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IGDB non disponibile · le altre fonti restano accessibili." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IGDB indisponible · les autres sources restent accessibles." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "IGDB nicht verfügbar · andere Quellen bleiben verfügbar." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "IGDB no disponible · las demás fuentes siguen disponibles." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "IGDB indisponível · as outras fontes continuam disponíveis." + } + } + } + }, + "IGDB has no value for this field.": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB has no value for this field." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IGDB non ha dati per questo campo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IGDB ne propose aucune valeur pour ce champ." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "IGDB hat keinen Wert für dieses Feld." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "IGDB no tiene datos para este campo." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O IGDB não tem dados para este campo." + } + } + } + }, + "IGDB descriptions are shown in their original language.": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "IGDB descriptions are shown in their original language." } }, "it": { "stringUnit": { "state": "translated", - "value": "verificato dal comando di compilazione" + "value": "Le descrizioni IGDB sono mostrate nella lingua originale." } }, "fr": { "stringUnit": { "state": "translated", - "value": "vérifié par la commande de compilation" + "value": "Les descriptions IGDB sont affichées dans leur langue d’origine." } }, "de": { "stringUnit": { "state": "translated", - "value": "wird vom Build-Befehl geprüft" + "value": "IGDB-Beschreibungen werden in der Originalsprache angezeigt." } }, "es": { "stringUnit": { "state": "translated", - "value": "se comprueba en el comando de compilación" + "value": "Las descripciones de IGDB se muestran en su idioma original." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "verificado pelo comando de compilação" + "value": "As descrições do IGDB são exibidas no idioma original." } } } }, - "current %@, expected %@": { - "comment": "CompatibilityChecker.swift", + "IGDB: %@": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "current %@, expected %@" + "value": "IGDB: %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "attuale %@, previsto %@" + "value": "IGDB: %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "actuel %@, attendu %@" + "value": "IGDB: %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "aktuell %@, erwartet %@" + "value": "IGDB: %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "actual %@, esperado %@" + "value": "IGDB: %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "atual %@, esperado %@" + "value": "IGDB: %@" } } } }, - "done": { - "comment": "AppViewModel.swift", + "Retry IGDB": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "done" + "value": "Retry IGDB" } }, "it": { "stringUnit": { "state": "translated", - "value": "completato" + "value": "Riprova IGDB" } }, "fr": { "stringUnit": { "state": "translated", - "value": "terminé" + "value": "Réessayer IGDB" } }, "de": { "stringUnit": { "state": "translated", - "value": "fertig" + "value": "IGDB erneut versuchen" } }, "es": { "stringUnit": { "state": "translated", - "value": "hecho" + "value": "Reintentar IGDB" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "concluído" + "value": "Tentar IGDB novamente" } } } }, - "end": { - "comment": "ButtonPrompts.swift", + "Other sources and your saved choices remain available.": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "end" + "value": "Other sources and your saved choices remain available." } }, "it": { "stringUnit": { "state": "translated", - "value": "end" + "value": "Le altre fonti e le tue scelte salvate restano disponibili." } }, "fr": { "stringUnit": { "state": "translated", - "value": "fin" + "value": "Les autres sources et vos choix enregistrés restent disponibles." } }, "de": { "stringUnit": { "state": "translated", - "value": "Ende" + "value": "Andere Quellen und gespeicherte Auswahlen bleiben verfügbar." } }, "es": { "stringUnit": { "state": "translated", - "value": "fin" + "value": "Las demás fuentes y tus elecciones guardadas siguen disponibles." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "end" + "value": "As outras fontes e suas escolhas salvas continuam disponíveis." } } } }, - "esc": { - "comment": "ButtonPrompts.swift", + "Same as Automatic": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "esc" + "value": "Same as Automatic" } }, "it": { "stringUnit": { "state": "translated", - "value": "esc" + "value": "Uguale ad Automatico" } }, "fr": { "stringUnit": { "state": "translated", - "value": "esc" + "value": "Identique à Automatique" } }, "de": { "stringUnit": { "state": "translated", - "value": "esc" + "value": "Wie Automatisch" } }, "es": { "stringUnit": { "state": "translated", - "value": "esc" + "value": "Igual que Automático" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "esc" + "value": "Igual a Automático" } } } }, - "fullGameImageFileName": { - "comment": "LaunchBoxArt.swift", + "Saved copy": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "fullGameImageFileName" + "value": "Saved copy" } }, "it": { "stringUnit": { "state": "translated", - "value": "fullGameImageFileName" + "value": "Copia salvata" } }, "fr": { "stringUnit": { "state": "translated", - "value": "fullGameImageFileName" + "value": "Copie enregistrée" } }, "de": { "stringUnit": { "state": "translated", - "value": "fullGameImageFileName" + "value": "Gespeicherte Kopie" } }, "es": { "stringUnit": { "state": "translated", - "value": "fullGameImageFileName" + "value": "Copia guardada" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "fullGameImageFileName" + "value": "Cópia salva" } } } }, - "git could not run": { - "comment": "NewestEngine.swift", + "Retry %@": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "git could not run" + "value": "Retry %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "impossibile eseguire git" + "value": "Riprova %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "git n’a pas pu s’exécuter" + "value": "Réessayer %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "git konnte nicht ausgeführt werden" + "value": "%@ erneut versuchen" } }, "es": { "stringUnit": { "state": "translated", - "value": "no se ha podido ejecutar git" + "value": "Reintentar %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "não foi possível executar git" + "value": "Tentar %@ novamente" } } } }, - "header_key does not open %@.": { - "comment": "PortingFailureReason.swift", + "Descriptions are shown in the source’s original language.": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "header_key does not open %@." + "value": "Descriptions are shown in the source’s original language." } }, "it": { "stringUnit": { "state": "translated", - "value": "header_key non apre %@." + "value": "Le descrizioni sono mostrate nella lingua originale della fonte." } }, "fr": { "stringUnit": { "state": "translated", - "value": "header_key ne permet pas de déchiffrer %@." + "value": "Les descriptions sont affichées dans la langue d’origine de la source." } }, "de": { "stringUnit": { "state": "translated", - "value": "header_key kann %@ nicht öffnen." + "value": "Beschreibungen werden in der Originalsprache der Quelle angezeigt." } }, "es": { "stringUnit": { "state": "translated", - "value": "header_key no abre %@." + "value": "Las descripciones se muestran en el idioma original de la fuente." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "header_key não abre %@." + "value": "As descrições são exibidas no idioma original da fonte." } } } }, - "header_key present · %@ application key generations": { - "comment": "SettingsEngineSection.swift", + "Choose a source for each field.": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "header_key present · %@ application key generations" + "value": "Choose a source for each field." } }, "it": { "stringUnit": { "state": "translated", - "value": "header_key presente · %@ generazioni di chiavi applicazione" + "value": "Scegli una fonte per ogni campo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "header_key présente · %@ générations de clés d’application" + "value": "Choisissez une source pour chaque champ." } }, "de": { "stringUnit": { "state": "translated", - "value": "header_key vorhanden · %@ Anwendungsschlüsselgenerationen" + "value": "Wähle für jedes Feld eine Quelle." } }, "es": { "stringUnit": { "state": "translated", - "value": "header_key presente · %@ generaciones de claves de aplicación" + "value": "Elige una fuente para cada campo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "header_key presente · %@ gerações de chaves de aplicativo" + "value": "Escolha uma fonte para cada campo." } } } }, - "home": { - "comment": "ButtonPrompts.swift", + "Unavailable · choose this row to retry.": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "home" + "value": "Unavailable · choose this row to retry." } }, "it": { "stringUnit": { "state": "translated", - "value": "home" + "value": "Non disponibile · seleziona questa riga per riprovare." } }, "fr": { "stringUnit": { "state": "translated", - "value": "début" + "value": "Indisponible · sélectionnez cette ligne pour réessayer." } }, "de": { "stringUnit": { "state": "translated", - "value": "Pos1" + "value": "Nicht verfügbar · diese Zeile zum Wiederholen auswählen." } }, "es": { "stringUnit": { "state": "translated", - "value": "inicio" + "value": "No disponible · selecciona esta fila para reintentar." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "home" + "value": "Indisponível · selecione esta linha para tentar novamente." } } } }, - "iCloud Drive": { - "comment": "CloudSaves.swift", + "No unique match for this edition.": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "iCloud Drive" + "value": "No unique match for this edition." } }, "it": { "stringUnit": { "state": "translated", - "value": "iCloud Drive" + "value": "Nessuna corrispondenza univoca per questa edizione." } }, "fr": { "stringUnit": { "state": "translated", - "value": "iCloud Drive" + "value": "Aucune correspondance unique pour cette édition." } }, "de": { "stringUnit": { "state": "translated", - "value": "iCloud Drive" + "value": "Kein eindeutiger Treffer für diese Edition." } }, "es": { "stringUnit": { "state": "translated", - "value": "iCloud Drive" + "value": "No hay una coincidencia única para esta edición." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "iCloud Drive" + "value": "Nenhuma correspondência única para esta edição." } } } }, - "iCloud Drive is not on for this Mac. Turn it on in System Settings › Apple Account › iCloud, or choose a folder.": { - "comment": "CloudSavesPreferences.swift", + "No matching game for this platform.": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "iCloud Drive is not on for this Mac. Turn it on in System Settings › Apple Account › iCloud, or choose a folder." + "value": "No matching game for this platform." } }, "it": { "stringUnit": { "state": "translated", - "value": "iCloud Drive non è attivo su questo Mac. Attivalo in Impostazioni di Sistema › Apple Account › iCloud oppure scegli una cartella." + "value": "Nessun gioco corrispondente per questa piattaforma." } }, "fr": { "stringUnit": { "state": "translated", - "value": "iCloud Drive n’est pas activé sur ce Mac. Activez-le dans Réglages Système › Compte Apple › iCloud, ou choisissez un dossier." + "value": "Aucun jeu correspondant pour cette plateforme." } }, "de": { "stringUnit": { "state": "translated", - "value": "iCloud Drive ist auf diesem Mac nicht aktiviert. Aktiviere es unter Systemeinstellungen › Apple Account › iCloud oder wähle einen Ordner." + "value": "Kein passendes Spiel für diese Plattform." } }, "es": { "stringUnit": { "state": "translated", - "value": "iCloud Drive no está activado en este Mac. Actívalo en Ajustes del Sistema › Cuenta de Apple › iCloud o elige una carpeta." + "value": "No hay un juego coincidente para esta plataforma." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O iCloud Drive não está ativado neste Mac. Ative-o em Ajustes do Sistema › Conta Apple › iCloud ou escolha uma pasta." + "value": "Nenhum jogo correspondente para esta plataforma." } } } }, - "iPhone Duo screen (1.43:1)": { - "comment": "Engine setting option display label.", + "No data for this field.": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "iPhone Duo screen (1.43:1)" + "value": "No data for this field." } }, "it": { "stringUnit": { "state": "translated", - "value": "Schermo iPhone Duo (1.43:1)" + "value": "Nessun dato per questo campo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "Écran iPhone Duo (1.43:1)" + "value": "Aucune donnée pour ce champ." } }, "de": { "stringUnit": { "state": "translated", - "value": "iPhone Duo-Bildschirm (1.43:1)" + "value": "Keine Daten für dieses Feld." } }, "es": { "stringUnit": { "state": "translated", - "value": "Pantalla de iPhone Duo (1.43:1)" + "value": "No hay datos para este campo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Tela do iPhone Duo (1.43:1)" + "value": "Nenhum dado para este campo." } } } }, - "imageFileName": { - "comment": "LaunchBoxArt.swift", + "Community metadata and game artwork": { + "comment": "Metadata source picker: availability, source attribution or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "imageFileName" + "value": "Community metadata and game artwork" } }, "it": { "stringUnit": { "state": "translated", - "value": "imageFileName" + "value": "Metadati della community e immagini dei giochi" } }, "fr": { "stringUnit": { "state": "translated", - "value": "imageFileName" + "value": "Métadonnées communautaires et visuels des jeux" } }, "de": { "stringUnit": { "state": "translated", - "value": "imageFileName" + "value": "Community-Metadaten und Spielbilder" } }, "es": { "stringUnit": { "state": "translated", - "value": "imageFileName" + "value": "Metadatos de la comunidad e imágenes de juegos" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "imageFileName" + "value": "Metadados da comunidade e imagens de jogos" } } } }, - "imageTypeName": { - "comment": "LaunchBoxArt.swift", + "Your choice": { + "comment": "The saved metadata value, separate from live source proposals.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "imageTypeName" + "value": "Your choice" } }, "it": { "stringUnit": { "state": "translated", - "value": "imageTypeName" + "value": "La tua scelta" } }, "fr": { "stringUnit": { "state": "translated", - "value": "imageTypeName" + "value": "Votre choix" } }, "de": { "stringUnit": { "state": "translated", - "value": "imageTypeName" + "value": "Deine Auswahl" } }, "es": { "stringUnit": { "state": "translated", - "value": "imageTypeName" + "value": "Tu elección" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "imageTypeName" + "value": "Sua escolha" } } } }, - "in": { - "comment": "SeleneArtBackground.swift", + "At %@, %@ of the tested %@, chosen in Settings → Setup and engine.": { + "comment": "NewestEngine.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "in" + "value": "At %@, %@ of the tested %@, chosen in Settings → Setup and engine." } }, "it": { "stringUnit": { "state": "translated", - "value": "presente" + "value": "Al commit %@, %@ rispetto al commit testato %@, scelto in Impostazioni → Configurazione e motore." } }, "fr": { "stringUnit": { "state": "translated", - "value": "chargée" + "value": "Au commit %@, %@ par rapport au commit testé %@, choisi dans Réglages → Configuration et moteur." } }, "de": { "stringUnit": { "state": "translated", - "value": "eingeblendet" + "value": "Stand %@, %@ (getestet: %@), gewählt unter Einstellungen → Einrichtung und Engine." } }, "es": { "stringUnit": { "state": "translated", - "value": "en" + "value": "En %@, %@ de la versión probada %@, elegido en Ajustes → Configuración y motor." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "carregada" + "value": "Em %@, %@ em relação à versão testada %@, escolhido em Ajustes → Configuração e engine." } } } }, - "installed %@ · required %@": { - "comment": "SettingsEngineSection.swift", + "Blocked by the Metal gate. See Settings → Setup and engine.": { + "comment": "GameOptionsPresentation.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "installed %@ · required %@" + "value": "Blocked by the Metal gate. See Settings → Setup and engine." } }, "it": { "stringUnit": { "state": "translated", - "value": "installato %@ · richiesto %@" + "value": "Bloccato dal controllo Metal. Vedi Impostazioni → Configurazione e motore." } }, "fr": { "stringUnit": { "state": "translated", - "value": "installé %@ · requis %@" + "value": "Bloqué par le contrôle Metal. Consultez Réglages → Configuration et moteur." } }, "de": { "stringUnit": { "state": "translated", - "value": "installiert %@ · erforderlich %@" + "value": "Durch die Metal-Prüfung gesperrt. Siehe Einstellungen → Einrichtung und Engine." } }, "es": { "stringUnit": { "state": "translated", - "value": "instalado %@ · necesario %@" + "value": "Bloqueado por el control de Metal. Consulta Ajustes → Configuración y motor." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "instalado %@ · necessário %@" + "value": "Bloqueado pela verificação do Metal. Veja Ajustes → Configuração e engine." } } } }, - "installed %@, tested %@": { - "comment": "CompatibilityChecker.swift", + "Build blocked — Settings → Setup and engine": { + "comment": "ToolchainGateCopy.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "installed %@, tested %@" + "value": "Build blocked — Settings → Setup and engine" } }, "it": { "stringUnit": { "state": "translated", - "value": "installato %@, testato %@" + "value": "Compilazione bloccata — Impostazioni → Configurazione e motore" } }, "fr": { "stringUnit": { "state": "translated", - "value": "installé %@, testé %@" + "value": "Compilation bloquée — Réglages → Configuration et moteur" } }, "de": { "stringUnit": { "state": "translated", - "value": "installiert %@, getestet %@" + "value": "Build gesperrt — Einstellungen → Einrichtung und Engine" } }, "es": { "stringUnit": { "state": "translated", - "value": "instalado %@, probado %@" + "value": "Compilación bloqueada — Ajustes → Configuración y motor" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "instalado %@, testado %@" + "value": "Compilação bloqueada — Ajustes → Configuração e engine" } } } }, - "local.nxlibrary.build.io": { - "comment": "BuildService.swift", + "Install the certified compiler from Setup, or allow untested toolchains in Settings → Setup and engine.": { + "comment": "PortingFailureReason.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.build.io" + "value": "Install the certified compiler from Setup, or allow untested toolchains in Settings → Setup and engine." } }, "it": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.build.io" + "value": "Installa il compilatore certificato da Configurazione oppure consenti le toolchain non testate in Impostazioni → Configurazione e motore." } }, "fr": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.build.io" + "value": "Installez le compilateur certifié depuis Configuration, ou autorisez les chaînes d’outils non testées dans Réglages → Configuration et moteur." } }, "de": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.build.io" + "value": "Installiere den zertifizierten Compiler über die Einrichtung oder erlaube ungetestete Toolchains unter Einstellungen → Einrichtung und Engine." } }, "es": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.build.io" + "value": "Instala el compilador certificado desde Configuración inicial o permite cadenas de herramientas no probadas en Ajustes → Configuración y motor." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.build.io" + "value": "Instale o compilador certificado em Configuração ou permita conjuntos de ferramentas não testados em Ajustes → Configuração e engine." } } } }, - "local.nxlibrary.saves": { - "comment": "AppViewModel.swift", + "Newer Metal: turn on the override in Settings → Setup and engine": { + "comment": "ToolchainGateCopy.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.saves" + "value": "Newer Metal: turn on the override in Settings → Setup and engine" } }, "it": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.saves" + "value": "Metal più recente: ignora il controllo in Impostazioni → Configurazione e motore" } }, "fr": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.saves" + "value": "Metal plus récent : activez la dérogation dans Réglages → Configuration et moteur" } }, "de": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.saves" + "value": "Neueres Metal: Ausnahme unter Einstellungen → Einrichtung und Engine aktivieren" } }, "es": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.saves" + "value": "Metal más reciente: activa la excepción en Ajustes → Configuración y motor" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.saves" + "value": "Metal mais recente: ative a exceção em Ajustes → Configuração e engine" } } } }, - "local.nxlibrary.sounds": { - "comment": "SoundEffectService.swift", + "Older Metal: update it, or use the override in Settings → Setup and engine": { + "comment": "ToolchainGateCopy.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.sounds" + "value": "Older Metal: update it, or use the override in Settings → Setup and engine" } }, "it": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.sounds" + "value": "Metal precedente: aggiornalo oppure ignora il controllo in Impostazioni → Configurazione e motore" } }, "fr": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.sounds" + "value": "Metal plus ancien : mettez-le à jour ou utilisez la dérogation dans Réglages → Configuration et moteur" } }, "de": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.sounds" + "value": "Älteres Metal: aktualisieren oder Ausnahme unter Einstellungen → Einrichtung und Engine verwenden" } }, "es": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.sounds" + "value": "Metal anterior: actualízalo o usa la excepción en Ajustes → Configuración y motor" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "local.nxlibrary.sounds" + "value": "Metal mais antigo: atualize ou use a exceção em Ajustes → Configuração e engine" } } } }, - "macOS could not launch %@.": { + "The nxnative checkout was not found. Choose it in Settings → Setup and engine.": { "comment": "NXLibraryError.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "macOS could not launch %@." + "value": "The nxnative checkout was not found. Choose it in Settings → Setup and engine." } }, "it": { "stringUnit": { "state": "translated", - "value": "macOS non ha potuto avviare %@." + "value": "Il checkout di nxnative non è stato trovato. Selezionalo in Impostazioni → Configurazione e motore." } }, "fr": { "stringUnit": { "state": "translated", - "value": "macOS n’a pas pu lancer %@." + "value": "La copie de travail de nxnative est introuvable. Choisissez-la dans Réglages → Configuration et moteur." } }, "de": { "stringUnit": { "state": "translated", - "value": "macOS konnte %@ nicht starten." + "value": "Der nxnative-Checkout wurde nicht gefunden. Wähle ihn unter Einstellungen → Einrichtung und Engine aus." } }, "es": { "stringUnit": { "state": "translated", - "value": "macOS no ha podido abrir %@." + "value": "No se ha encontrado la copia local de nxnative. Selecciónala en Ajustes → Configuración y motor." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O macOS não conseguiu abrir %@." + "value": "O checkout do nxnative não foi encontrado. Selecione-o em Ajustes → Configuração e engine." } } } }, - "main has moved on: %@%@.": { - "comment": "NewestEngine.swift", + "Choose a folder with your %@. Existing apps play without these files. Change it later in Settings → Porting → Library.": { + "comment": "GameFoldersCopy.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "main has moved on: %@%@." + "value": "Choose a folder with your %@. Existing apps play without these files. Change it later in Settings → Porting → Library." } }, "it": { "stringUnit": { "state": "translated", - "value": "main è avanzato: %@%@." + "value": "Scegli una cartella con i tuoi %@. Le app esistenti funzionano senza questi file. Puoi cambiarla in seguito in Impostazioni → Porting → Libreria." } }, "fr": { "stringUnit": { "state": "translated", - "value": "main a progressé : %@%@." + "value": "Choisissez un dossier contenant vos %@. Les apps existantes fonctionnent sans ces fichiers. Vous pourrez modifier ce choix dans Réglages → Porting → Bibliothèque." } }, "de": { "stringUnit": { "state": "translated", - "value": "main hat sich weiterentwickelt: %@%@." + "value": "Wähle einen Ordner mit deinen %@. Vorhandene Apps lassen sich ohne diese Dateien spielen. Du kannst den Ordner später unter Einstellungen → Porting → Bibliothek ändern." } }, "es": { "stringUnit": { "state": "translated", - "value": "main ha avanzado: %@%@." + "value": "Elige una carpeta con tus %@. Las apps existentes se pueden ejecutar sin estos archivos. Puedes cambiarlo más tarde en Ajustes → Porting → Biblioteca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "main avançou: %@%@." + "value": "Escolha uma pasta com seus %@. Apps existentes funcionam sem esses arquivos. Altere depois em Ajustes → Porting → Biblioteca." } } } }, - "missing": { - "comment": "NXNativeEnvironment.swift", + "Choose where to keep your game apps. Put any existing nxnative games (.app) here. Change it later in Settings → Porting → Library.": { + "comment": "GameFoldersCopy.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "missing" + "value": "Choose where to keep your game apps. Put any existing nxnative games (.app) here. Change it later in Settings → Porting → Library." } }, "it": { "stringUnit": { "state": "translated", - "value": "non disponibile" + "value": "Scegli dove conservare le app dei giochi. Inserisci qui eventuali giochi nxnative (.app) esistenti. Puoi cambiarla in seguito in Impostazioni → Porting → Libreria." } }, "fr": { "stringUnit": { "state": "translated", - "value": "manquant" + "value": "Choisissez où conserver vos apps de jeux. Placez-y vos jeux nxnative existants (.app). Vous pourrez modifier ce choix dans Réglages → Porting → Bibliothèque." } }, "de": { "stringUnit": { "state": "translated", - "value": "fehlt" + "value": "Wähle, wo deine Spiele-Apps gespeichert werden. Lege hier auch vorhandene nxnative-Spiele (.app) ab. Du kannst den Ordner später unter Einstellungen → Porting → Bibliothek ändern." } }, "es": { "stringUnit": { "state": "translated", - "value": "falta" + "value": "Elige dónde guardar tus apps de juegos. Coloca aquí tus juegos existentes de nxnative (.app). Puedes cambiarlo más tarde en Ajustes → Porting → Biblioteca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "ausente" + "value": "Escolha onde manter os apps dos seus jogos. Coloque aqui os jogos existentes do nxnative (.app). Altere depois em Ajustes → Porting → Biblioteca." } } } }, - "missing %@": { - "comment": "CompatibilityChecker.swift", + "Existing game apps play without sources. Choose later in Settings → Porting → Library.": { + "comment": "SetupCheck.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "missing %@" + "value": "Existing game apps play without sources. Choose later in Settings → Porting → Library." } }, "it": { "stringUnit": { "state": "translated", - "value": "manca %@" + "value": "Le app dei giochi esistenti funzionano senza sorgenti. Puoi scegliere più tardi in Impostazioni → Porting → Libreria." } }, "fr": { "stringUnit": { "state": "translated", - "value": "%@ manquant" + "value": "Les apps de jeux existantes fonctionnent sans sources. Vous pourrez choisir plus tard dans Réglages → Porting → Bibliothèque." } }, "de": { "stringUnit": { "state": "translated", - "value": "%@ fehlt" + "value": "Vorhandene Spiele-Apps lassen sich ohne Quellen spielen. Wähle sie später unter Einstellungen → Porting → Bibliothek aus." } }, "es": { "stringUnit": { "state": "translated", - "value": "falta %@" + "value": "Las apps de juegos existentes se pueden ejecutar sin sus archivos de origen. Puedes elegirlos más tarde en Ajustes → Porting → Biblioteca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "falta %@" + "value": "Apps de jogos existentes funcionam sem os arquivos de origem. Escolha depois em Ajustes → Porting → Biblioteca." } } } }, - "none": { - "comment": "SeleneArtBackground.swift", + "The Game apps folder is unavailable. Reconnect it or choose another in Settings → Porting → Library.": { + "comment": "GameAppDestination.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "none" + "value": "The Game apps folder is unavailable. Reconnect it or choose another in Settings → Porting → Library." } }, "it": { "stringUnit": { "state": "translated", - "value": "nessuna" + "value": "La cartella App dei giochi non è disponibile. Ricollegala o scegline un’altra in Impostazioni → Porting → Libreria." } }, "fr": { "stringUnit": { "state": "translated", - "value": "aucune" + "value": "Le dossier Apps de jeux est indisponible. Reconnectez-le ou choisissez-en un autre dans Réglages → Porting → Bibliothèque." } }, "de": { "stringUnit": { "state": "translated", - "value": "keine" + "value": "Der Spiele-App-Ordner ist nicht verfügbar. Verbinde ihn erneut oder wähle unter Einstellungen → Porting → Bibliothek einen anderen." } }, "es": { "stringUnit": { "state": "translated", - "value": "ninguno" + "value": "La carpeta Apps de juegos no está disponible. Vuelve a conectarla o elige otra en Ajustes → Porting → Biblioteca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "ausente" + "value": "A pasta de Apps de jogos está indisponível. Reconecte ou escolha outra em Ajustes → Porting → Biblioteca." } } } }, - "not found": { - "comment": "SettingsEngineSection.swift", + "Turn off Cloud saves in Settings → Cloud saves to import or restore.": { + "comment": "SavesPanel.swift:204", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "not found" + "value": "Turn off Cloud saves in Settings → Cloud saves to import or restore." } }, "it": { "stringUnit": { "state": "translated", - "value": "non trovato" + "value": "Disattiva Salvataggi cloud in Impostazioni → Salvataggi cloud per importare o ripristinare." } }, "fr": { "stringUnit": { "state": "translated", - "value": "introuvable" + "value": "Désactivez Sauvegardes dans le cloud dans Réglages → Sauvegardes dans le cloud pour importer ou restaurer." } }, "de": { "stringUnit": { "state": "translated", - "value": "nicht gefunden" + "value": "Deaktiviere Cloud-Spielstände unter Einstellungen → Cloud-Spielstände, um Spielstände zu importieren oder wiederherzustellen." } }, "es": { "stringUnit": { "state": "translated", - "value": "no encontrado" + "value": "Desactiva Partidas en la nube en Ajustes → Partidas en la nube para importar o restaurar." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "não encontrado" + "value": "Desative Dados salvos na nuvem em Ajustes → Dados salvos na nuvem para importar ou restaurar." } } } }, - "nxlibrary.setup-check": { - "comment": "SetupCheckModel.swift", + "IGDB is optional · connect it in Settings → Online services.": { + "comment": "Change metadata: optional IGDB source preview, status or retry.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "nxlibrary.setup-check" + "value": "IGDB is optional · connect it in Settings → Online services." } }, "it": { "stringUnit": { "state": "translated", - "value": "nxlibrary.setup-check" + "value": "IGDB è facoltativo · collegalo in Impostazioni → Servizi online." } }, "fr": { "stringUnit": { "state": "translated", - "value": "nxlibrary.setup-check" + "value": "IGDB est facultatif · connectez-le dans Paramètres → Services en ligne." } }, "de": { "stringUnit": { "state": "translated", - "value": "nxlibrary.setup-check" + "value": "IGDB ist optional · unter Einstellungen → Online-Dienste verbinden." } }, "es": { "stringUnit": { "state": "translated", - "value": "nxlibrary.setup-check" + "value": "IGDB es opcional · conéctalo en Ajustes → Servicios en línea." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "nxlibrary.setup-check" + "value": "O IGDB é opcional · conecte em Configurações → Serviços online." } } } }, - "nxnative CLI": { - "comment": "CompatibilityChecker.swift", + "Settings group: Library": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "nxnative CLI" + "value": "Library" } }, "it": { "stringUnit": { "state": "translated", - "value": "CLI di nxnative" + "value": "Libreria" } }, "fr": { "stringUnit": { "state": "translated", - "value": "CLI nxnative" + "value": "Bibliothèque" } }, "de": { "stringUnit": { "state": "translated", - "value": "nxnative-CLI" + "value": "Bibliothek" } }, "es": { "stringUnit": { "state": "translated", - "value": "CLI de nxnative" + "value": "Biblioteca" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "CLI do nxnative" + "value": "Biblioteca" } } } }, - "nxnative engine": { - "comment": "SetupCheck.swift", + "Settings group: Porting": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "nxnative engine" + "value": "Porting" } }, "it": { "stringUnit": { "state": "translated", - "value": "Motore nxnative" + "value": "Porting" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Moteur nxnative" + "value": "Porting" } }, "de": { "stringUnit": { "state": "translated", - "value": "nxnative-Engine" + "value": "Porting" } }, "es": { "stringUnit": { "state": "translated", - "value": "Motor nxnative" + "value": "Porting" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Engine nxnative" + "value": "Porting" } } } }, - "nxnative has %lld newer commits. Engine updates reach you with NX Library updates, once tested.": { - "comment": "Quantity-sensitive UI message; preserve %lld count and other placeholders.", + "Settings section: Sources": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { - "variations": { - "plural": { - "one": { - "stringUnit": { - "state": "translated", - "value": "nxnative has %lld newer commit. Engine updates reach you with NX Library updates, once tested." - } - }, - "other": { - "stringUnit": { - "state": "translated", - "value": "nxnative has %lld newer commits. Engine updates reach you with NX Library updates, once tested." - } - } - } + "stringUnit": { + "state": "translated", + "value": "Sources" } }, "it": { - "variations": { - "plural": { - "one": { - "stringUnit": { - "state": "translated", - "value": "nxnative ha %lld commit più recente. Gli aggiornamenti del motore arrivano con gli aggiornamenti di NX Library, dopo essere stati testati." - } - }, - "other": { - "stringUnit": { - "state": "translated", - "value": "nxnative ha %lld commit più recenti. Gli aggiornamenti del motore arrivano con gli aggiornamenti di NX Library, dopo essere stati testati." - } - } - } + "stringUnit": { + "state": "translated", + "value": "Fonti" } }, "fr": { - "variations": { - "plural": { - "one": { - "stringUnit": { - "state": "translated", - "value": "nxnative compte %lld commit plus récent. Les mises à jour du moteur vous parviennent avec celles de NX Library, une fois testées." - } - }, - "other": { - "stringUnit": { - "state": "translated", - "value": "nxnative compte %lld commits plus récents. Les mises à jour du moteur vous parviennent avec celles de NX Library, une fois testées." - } - } - } + "stringUnit": { + "state": "translated", + "value": "Sources" } }, "de": { - "variations": { - "plural": { - "one": { - "stringUnit": { - "state": "translated", - "value": "nxnative hat %lld neueren Commit. Engine-Updates erhältst du mit NX Library-Updates, sobald sie getestet wurden." - } - }, - "other": { - "stringUnit": { - "state": "translated", - "value": "nxnative hat %lld neuere Commits. Engine-Updates erhältst du mit NX Library-Updates, sobald sie getestet wurden." - } - } - } + "stringUnit": { + "state": "translated", + "value": "Quellen" } }, "es": { - "variations": { - "plural": { - "one": { - "stringUnit": { - "state": "translated", - "value": "nxnative tiene %lld commit más reciente. Las actualizaciones del motor te llegan con las de NX Library, una vez probadas." - } - }, - "other": { - "stringUnit": { - "state": "translated", - "value": "nxnative tiene %lld commits más recientes. Las actualizaciones del motor te llegan con las de NX Library, una vez probadas." - } - } - } + "stringUnit": { + "state": "translated", + "value": "Fuentes" } }, "pt-BR": { - "variations": { - "plural": { - "one": { - "stringUnit": { - "state": "translated", - "value": "O nxnative tem %lld commit mais recente. As atualizações da engine chegam com as atualizações do NX Library, após serem testadas." - } - }, - "other": { - "stringUnit": { - "state": "translated", - "value": "O nxnative tem %lld commits mais recentes. As atualizações da engine chegam com as atualizações do NX Library, após serem testadas." - } - } - } + "stringUnit": { + "state": "translated", + "value": "Fontes" } } } }, - "nxnative, used as it is upstream, at the commit this NX Library is tested with.": { - "comment": "SetupCheck.swift", + "Online services": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "nxnative, used as it is upstream, at the commit this NX Library is tested with." + "value": "Online services" } }, "it": { "stringUnit": { "state": "translated", - "value": "nxnative, usato senza modifiche rispetto a upstream, al commit con cui è testata questa NX Library." + "value": "Servizi online" } }, "fr": { "stringUnit": { "state": "translated", - "value": "nxnative, utilisé tel quel depuis le dépôt amont, au commit avec lequel cette version de NX Library a été testée." + "value": "Services en ligne" } }, "de": { "stringUnit": { "state": "translated", - "value": "nxnative, unverändert aus dem Upstream, mit dem Commit, mit dem diese NX Library-Version getestet wurde." + "value": "Online-Dienste" } }, "es": { "stringUnit": { "state": "translated", - "value": "nxnative, sin modificar respecto al proyecto original, en el commit con el que se ha probado este NX Library." + "value": "Servicios en línea" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "nxnative, usado sem alterações do repositório original, no commit com o qual este NX Library foi testado." + "value": "Serviços online" } } } }, - "picture": { - "comment": "Display copy only; internal values and paths remain unchanged.", + "Setup and engine": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "picture" + "value": "Setup and engine" } }, "it": { "stringUnit": { "state": "translated", - "value": "immagine" + "value": "Configurazione e motore" } }, "fr": { "stringUnit": { "state": "translated", - "value": "image" + "value": "Configuration et moteur" } }, "de": { "stringUnit": { "state": "translated", - "value": "Bild" + "value": "Einrichtung und Engine" } }, "es": { "stringUnit": { "state": "translated", - "value": "imagen" + "value": "Configuración y motor" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "imagem" + "value": "Configuração e engine" } } } }, - "prod.keys": { - "comment": "SettingsEngineSection.swift", + "Gamepad, button layout and stick deadzone for the library.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "prod.keys" + "value": "Gamepad, button layout and stick deadzone for the library." } }, "it": { "stringUnit": { "state": "translated", - "value": "prod.keys" + "value": "Controller, schema dei tasti e zona morta della levetta per la libreria." } }, "fr": { "stringUnit": { "state": "translated", - "value": "prod.keys" + "value": "Manette, disposition des boutons et zone morte du stick pour la bibliothèque." } }, "de": { "stringUnit": { "state": "translated", - "value": "prod.keys" + "value": "Controller, Tastenbelegung und Stick-Totzone für die Bibliothek." } }, "es": { "stringUnit": { "state": "translated", - "value": "prod.keys" + "value": "Mando, distribución de botones y zona muerta del stick para la biblioteca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "prod.keys" + "value": "Controle, layout dos botões e zona morta do analógico para a biblioteca." } } } }, - "prod.keys imported: header key present, %@ application key generations.": { - "comment": "AppViewModel.swift", + "Launch screen, Surprise me, session card and hidden games.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "prod.keys imported: header key present, %@ application key generations." + "value": "Launch screen, Surprise me, session card and hidden games." } }, "it": { "stringUnit": { "state": "translated", - "value": "prod.keys importato: chiave header presente, %@ generazioni di chiavi applicazione." + "value": "Schermata di avvio, Sorprendimi, card della sessione e giochi nascosti." } }, "fr": { "stringUnit": { "state": "translated", - "value": "prod.keys importé : clé d’en-tête présente, %@ générations de clés d’application." + "value": "Écran de lancement, Surprends-moi, carte de session et jeux masqués." } }, "de": { "stringUnit": { "state": "translated", - "value": "prod.keys importiert: Header-Schlüssel vorhanden, %@ Anwendungsschlüsselgenerationen." + "value": "Startbildschirm, Überrasch mich, Sitzungskarte und ausgeblendete Spiele." } }, "es": { "stringUnit": { "state": "translated", - "value": "prod.keys importado: clave de cabecera presente, %@ generaciones de claves de aplicación." + "value": "Pantalla de inicio, Sorpréndeme, tarjeta de sesión y juegos ocultos." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "prod.keys importado: chave de cabeçalho presente, %@ gerações de chaves de aplicativo." + "value": "Tela de abertura, Surpreenda-me, cartão da sessão e jogos ocultos." } } } }, - "prod.keys is missing, unreadable or has no header_key.": { - "comment": "PortingFailureReason.swift", + "Storage usage, logs, metadata and artwork caches, save backups.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "prod.keys is missing, unreadable or has no header_key." + "value": "Storage usage, logs, metadata and artwork caches, save backups." } }, "it": { "stringUnit": { "state": "translated", - "value": "prod.keys non è disponibile, non è leggibile o non contiene header_key." + "value": "Spazio usato, log, cache di metadati e immagini, backup dei salvataggi." } }, "fr": { "stringUnit": { "state": "translated", - "value": "prod.keys est absent, illisible ou ne contient pas de header_key." + "value": "Espace utilisé, journaux, caches des métadonnées et des illustrations, sauvegardes de progression." } }, "de": { "stringUnit": { "state": "translated", - "value": "prod.keys fehlt, ist nicht lesbar oder enthält keinen header_key." + "value": "Speichernutzung, Protokolle, Metadaten- und Artwork-Cache, Spielstand-Backups." } }, "es": { "stringUnit": { "state": "translated", - "value": "prod.keys falta, no se puede leer o no contiene header_key." + "value": "Uso del almacenamiento, registros, cachés de metadatos e imágenes, copias de partidas." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "prod.keys está ausente, ilegível ou sem header_key." + "value": "Uso do armazenamento, registros, caches de metadados e imagens, backups dos dados salvos." } } } }, - "prod.keys is missing. Import it in Settings.": { - "comment": "NXLibraryError.swift", + "Engine pin, toolchain gate and setup.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "prod.keys is missing. Import it in Settings." + "value": "Engine pin, toolchain gate and setup." } }, "it": { "stringUnit": { "state": "translated", - "value": "prod.keys non è disponibile. Importalo in Impostazioni." + "value": "Versione fissata del motore, controllo degli strumenti e configurazione." } }, "fr": { "stringUnit": { "state": "translated", - "value": "prod.keys est introuvable. Importez-le dans les Réglages." + "value": "Version épinglée du moteur, contrôle des outils et configuration." } }, "de": { "stringUnit": { "state": "translated", - "value": "prod.keys fehlt. Importiere die Datei in den Einstellungen." + "value": "Fixierte Engine-Version, Toolchain-Prüfung und Einrichtung." } }, "es": { "stringUnit": { "state": "translated", - "value": "Falta prod.keys. Impórtalo en Ajustes." + "value": "Versión fijada del motor, control de herramientas y configuración." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "O arquivo prod.keys não foi encontrado. Importe-o nos Ajustes." + "value": "Versão fixada da engine, verificação das ferramentas e configuração." } } } }, - "regionName": { - "comment": "LaunchBoxArt.swift", + "Import, replace or detect prod.keys.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "regionName" + "value": "Import, replace or detect prod.keys." } }, "it": { "stringUnit": { "state": "translated", - "value": "regionName" + "value": "Importa, sostituisci o rileva prod.keys." } }, "fr": { "stringUnit": { "state": "translated", - "value": "regionName" + "value": "Importer, remplacer ou détecter prod.keys." } }, "de": { "stringUnit": { "state": "translated", - "value": "regionName" + "value": "prod.keys importieren, ersetzen oder erkennen." } }, "es": { "stringUnit": { "state": "translated", - "value": "regionName" + "value": "Importa, sustituye o detecta prod.keys." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "regionName" + "value": "Importe, substitua ou detecte prod.keys." } } } }, - "required options present": { - "comment": "CompatibilityChecker.swift", + "Defaults copied into each new ported game.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "required options present" + "value": "Defaults copied into each new ported game." } }, "it": { "stringUnit": { "state": "translated", - "value": "opzioni richieste presenti" + "value": "Valori iniziali copiati in ogni nuovo gioco convertito." } }, "fr": { "stringUnit": { "state": "translated", - "value": "options requises présentes" + "value": "Valeurs par défaut copiées dans chaque nouveau jeu porté." } }, "de": { "stringUnit": { "state": "translated", - "value": "erforderliche Optionen vorhanden" + "value": "Standardwerte, die in jedes neu portierte Spiel übernommen werden." } }, "es": { "stringUnit": { "state": "translated", - "value": "opciones necesarias presentes" + "value": "Valores predeterminados copiados en cada nuevo juego portado." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "opções obrigatórias presentes" + "value": "Padrões copiados para cada novo jogo portado." } } } }, - "switched to": { - "comment": "AppViewModel+NewestEngine.swift:69", + "Save sync for ported games: Off, iCloud Drive or a folder.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "switched to" + "value": "Save sync for ported games: Off, iCloud Drive or a folder." } }, "it": { "stringUnit": { "state": "translated", - "value": "passato a" + "value": "Sincronizzazione dei salvataggi dei giochi convertiti: No, iCloud Drive o una cartella." } }, "fr": { "stringUnit": { "state": "translated", - "value": "basculé vers" + "value": "Synchronisation des sauvegardes des jeux portés : désactivée, iCloud Drive ou un dossier." } }, "de": { "stringUnit": { "state": "translated", - "value": "gewechselt zu" + "value": "Spielstand-Synchronisierung portierter Spiele: Aus, iCloud Drive oder ein Ordner." } }, "es": { "stringUnit": { "state": "translated", - "value": "cambiado a" + "value": "Sincronización de partidas de los juegos portados: desactivada, iCloud Drive o una carpeta." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "trocada para" + "value": "Sincronização dos dados salvos de jogos portados: desativada, iCloud Drive ou uma pasta." } } } }, - "tab": { - "comment": "ButtonPrompts.swift", + "Build caches for each game and for all games.": { + "comment": "SettingsSection.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "tab" + "value": "Build caches for each game and for all games." } }, "it": { "stringUnit": { "state": "translated", - "value": "tab" + "value": "Cache di compilazione di ogni gioco e di tutti i giochi." } }, "fr": { "stringUnit": { "state": "translated", - "value": "tab" + "value": "Caches de compilation de chaque jeu et de tous les jeux." } }, "de": { "stringUnit": { "state": "translated", - "value": "Tab" + "value": "Build-Caches für jedes Spiel und für alle Spiele." } }, "es": { "stringUnit": { "state": "translated", - "value": "tab" + "value": "Cachés de compilación de cada juego y de todos los juegos." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "tab" + "value": "Caches de compilação de cada jogo e de todos os jogos." } } } }, - "terminal": { - "comment": "BuildLiveLogsDrawer.swift", + "New games: default controller vibration for new ported games.": { + "comment": "SettingsCatalog.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "terminal" + "value": "New games: default controller vibration for new ported games." } }, "it": { "stringUnit": { "state": "translated", - "value": "terminale" + "value": "Nuovi giochi: vibrazione predefinita del controller per i nuovi giochi convertiti." } }, "fr": { "stringUnit": { "state": "translated", - "value": "terminal" + "value": "Nouveaux jeux : vibration de la manette par défaut pour les nouveaux jeux portés." } }, "de": { "stringUnit": { "state": "translated", - "value": "Terminal" + "value": "Neue Spiele: Standard-Controllervibration für neu portierte Spiele." } }, "es": { "stringUnit": { "state": "translated", - "value": "terminal" + "value": "Juegos nuevos: vibración predeterminada del mando para los nuevos juegos portados." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "terminal" + "value": "Novos jogos: vibração padrão do controle para novos jogos portados." } } } }, - "the bundled Python is missing; reinstall NX Library": { - "comment": "AppViewModel.swift", + "New games: default vibration strength for new ported games.": { + "comment": "SettingsCatalog.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "the bundled Python is missing; reinstall NX Library" + "value": "New games: default vibration strength for new ported games." } }, "it": { "stringUnit": { "state": "translated", - "value": "il Python incluso non è disponibile; reinstalla NX Library" + "value": "Nuovi giochi: intensità predefinita della vibrazione per i nuovi giochi convertiti." } }, "fr": { "stringUnit": { "state": "translated", - "value": "le Python intégré est introuvable ; réinstallez NX Library" + "value": "Nouveaux jeux : intensité de vibration par défaut pour les nouveaux jeux portés." } }, "de": { "stringUnit": { "state": "translated", - "value": "das mitgelieferte Python fehlt; installiere NX Library erneut" + "value": "Neue Spiele: Standard-Vibrationsstärke für neu portierte Spiele." } }, "es": { "stringUnit": { "state": "translated", - "value": "falta el Python incluido; reinstala NX Library" + "value": "Juegos nuevos: intensidad predeterminada de la vibración para los nuevos juegos portados." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "o Python incluído não foi encontrado; reinstale o NX Library" + "value": "Novos jogos: intensidade padrão da vibração para novos jogos portados." } } } }, - "the drive": { - "comment": "Display copy only; internal values and paths remain unchanged.", + "Vibration in new ported games": { + "comment": "SettingsCatalog.swift", + "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "the drive" + "value": "Vibration in new ported games" } }, "it": { "stringUnit": { "state": "translated", - "value": "il disco" + "value": "Vibrazione nei nuovi giochi convertiti" } }, "fr": { "stringUnit": { "state": "translated", - "value": "le disque" + "value": "Vibration dans les nouveaux jeux portés" } }, "de": { "stringUnit": { "state": "translated", - "value": "das Laufwerk" + "value": "Vibration in neu portierten Spielen" } }, "es": { "stringUnit": { "state": "translated", - "value": "la unidad" + "value": "Vibración en los nuevos juegos portados" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "a unidade" + "value": "Vibração em novos jogos portados" } } } }, - "the environment check is still running": { - "comment": "AppViewModel.swift", + "Applied before each game starts, including Off. Custom save-sync overrides are reported in Saves.": { + "comment": "SettingsGamesSection.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "the environment check is still running" + "value": "Applied before each game starts, including Off. Custom save-sync overrides are reported in Saves." } }, "it": { "stringUnit": { "state": "translated", - "value": "il controllo dell’ambiente è ancora in corso" + "value": "Applicato prima di ogni avvio, anche se disattivato. Le impostazioni personalizzate che prevalgono sulla sincronizzazione dei salvataggi sono indicate in Salvataggi." } }, "fr": { "stringUnit": { "state": "translated", - "value": "la vérification de l’environnement est toujours en cours" + "value": "Appliqué avant chaque démarrage de jeu, y compris Désactivé. Les réglages personnalisés de synchronisation des sauvegardes sont signalés dans Sauvegardes." } }, "de": { "stringUnit": { "state": "translated", - "value": "die Umgebungsprüfung läuft noch" + "value": "Wird vor jedem Spielstart angewendet, auch „Aus“. Eigene Überschreibungen der Spielstandsynchronisierung werden unter „Spielstände“ angezeigt." } }, "es": { "stringUnit": { "state": "translated", - "value": "la comprobación del entorno sigue en curso" + "value": "Se aplica antes de iniciar cada juego, también al desactivarlo. Las personalizaciones de sincronización de partidas se indican en Partidas guardadas." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "a verificação do ambiente ainda está em andamento" + "value": "Aplicado antes de cada jogo iniciar, inclusive Desativado. Substituições personalizadas da sincronização são informadas em Dados salvos." } } } }, - "the game": { - "comment": "Fallback display name when no game name is available.", + "Looking at your Mac…": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "the game" + "value": "Looking at your Mac…" } }, "it": { "stringUnit": { "state": "translated", - "value": "il gioco" + "value": "Sto guardando il tuo Mac…" } }, "fr": { "stringUnit": { "state": "translated", - "value": "le jeu" + "value": "Analyse de votre Mac…" } }, "de": { "stringUnit": { "state": "translated", - "value": "das Spiel" + "value": "Dein Mac wird durchsucht…" } }, "es": { "stringUnit": { "state": "translated", - "value": "el juego" + "value": "Revisando tu Mac…" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "o jogo" + "value": "Verificando seu Mac…" } } } }, - "the game’s files": { - "comment": "Display copy only; internal values and paths remain unchanged.", + "No games found": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "the game’s files" + "value": "No games found" } }, "it": { "stringUnit": { "state": "translated", - "value": "i file del gioco" + "value": "Nessun gioco trovato" } }, "fr": { "stringUnit": { "state": "translated", - "value": "les fichiers du jeu" + "value": "Aucun jeu trouvé" } }, "de": { "stringUnit": { "state": "translated", - "value": "die Dateien des Spiels" + "value": "Keine Spiele gefunden" } }, "es": { "stringUnit": { "state": "translated", - "value": "los archivos del juego" + "value": "No se han encontrado juegos" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "os arquivos do jogo" + "value": "Nenhum jogo encontrado" } } } }, - "the nxnative venv Python is missing": { - "comment": "AppViewModel.swift", + "Here's what's on your Mac": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "the nxnative venv Python is missing" + "value": "Here's what's on your Mac" } }, "it": { "stringUnit": { "state": "translated", - "value": "il Python del venv di nxnative non è disponibile" + "value": "Ecco cosa c'è sul tuo Mac" } }, "fr": { "stringUnit": { "state": "translated", - "value": "le Python de l’environnement venv de nxnative est introuvable" + "value": "Voici ce qu'il y a sur votre Mac" } }, "de": { "stringUnit": { "state": "translated", - "value": "das Python der nxnative-venv fehlt" + "value": "Das ist auf deinem Mac" } }, "es": { "stringUnit": { "state": "translated", - "value": "falta el Python del entorno virtual de nxnative" + "value": "Esto es lo que hay en tu Mac" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "o Python do venv do nxnative não foi encontrado" + "value": "Veja o que há no seu Mac" } } } }, - "this session": { - "comment": "SessionCard.swift:91", + "Steam and ported apps aren't here yet. Add them later from Settings → Sources or with Porting.": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "this session" + "value": "Steam and ported apps aren't here yet. Add them later from Settings → Sources or with Porting." } }, "it": { "stringUnit": { "state": "translated", - "value": "questa sessione" + "value": "Steam e le app portate non ci sono ancora. Puoi aggiungerli dopo, da Impostazioni → Fonti o con Porting." } }, "fr": { "stringUnit": { "state": "translated", - "value": "cette session" + "value": "Steam et les apps portées ne sont pas encore là. Ajoutez-les plus tard depuis Réglages → Sources ou avec Porting." } }, "de": { "stringUnit": { "state": "translated", - "value": "diese Sitzung" + "value": "Steam und portierte Apps sind noch nicht da. Füge sie später unter Einstellungen → Quellen oder mit Porting hinzu." } }, "es": { "stringUnit": { "state": "translated", - "value": "esta sesión" + "value": "Steam y las apps portadas aún no están. Añádelos después desde Ajustes → Fuentes o con Porting." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "nesta sessão" + "value": "O Steam e os apps portados ainda não estão aqui. Adicione-os depois em Ajustes → Fontes ou com Porting." } } } }, - "total": { - "comment": "SessionCard.swift:95", + "Arcane looked without changing anything. Choose what goes in your library.": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "total" + "value": "Arcane looked without changing anything. Choose what goes in your library." } }, "it": { "stringUnit": { "state": "translated", - "value": "totale" + "value": "Arcane ha guardato senza cambiare nulla. Scegli cosa mettere nella libreria." } }, "fr": { "stringUnit": { "state": "translated", - "value": "au total" + "value": "Arcane a regardé sans rien modifier. Choisissez ce qui va dans votre bibliothèque." } }, "de": { "stringUnit": { "state": "translated", - "value": "insgesamt" + "value": "Arcane hat nachgesehen, ohne etwas zu ändern. Wähle, was in deine Bibliothek kommt." } }, "es": { "stringUnit": { "state": "translated", - "value": "total" + "value": "Arcane ha mirado sin cambiar nada. Elige qué va a tu biblioteca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "total" + "value": "O Arcane olhou sem alterar nada. Escolha o que vai para a sua biblioteca." } } } }, - "truncated": { - "comment": "CheatFile.swift", + "Already ported: %@": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "truncated" + "value": "Already ported: %@" } }, "it": { "stringUnit": { "state": "translated", - "value": "troncato" + "value": "Giochi già portati: %@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "tronqué" + "value": "Déjà portés : %@" } }, "de": { "stringUnit": { "state": "translated", - "value": "abgeschnitten" + "value": "Bereits portiert: %@" } }, "es": { "stringUnit": { "state": "translated", - "value": "truncado" + "value": "Ya portados: %@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "truncado" + "value": "Já portados: %@" } } } }, - "turn them back on here or in the game's Cheats panel (⌘⇧C).": { - "comment": "CheatCopy.swift", + "They're in your library.": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "turn them back on here or in the game's Cheats panel (⌘⇧C)." + "value": "They're in your library." } }, "it": { "stringUnit": { "state": "translated", - "value": "riattivali qui o nel pannello Trucchi del gioco (⌘⇧C)." + "value": "Sono già nella libreria." } }, "fr": { "stringUnit": { "state": "translated", - "value": "réactivez-les ici ou dans le panneau Codes de triche du jeu (⌘⇧C)." + "value": "Ils sont dans votre bibliothèque." } }, "de": { "stringUnit": { "state": "translated", - "value": "aktiviere sie hier oder im Cheats-Bereich des Spiels (⌘⇧C) erneut." + "value": "Sie sind in deiner Bibliothek." } }, "es": { "stringUnit": { "state": "translated", - "value": "vuelve a activarlos aquí o en el panel de trucos del juego (⌘⇧C)." + "value": "Están en tu biblioteca." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "ative-as novamente aqui ou no painel Trapaças do jogo (⌘⇧C)." + "value": "Eles estão na sua biblioteca." } } } }, - "under a minute": { - "comment": "Compact playtime units, metadata heading or accessible duration.", + "Bring the Nintendo Switch games you own to the Mac.": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "under a minute" + "value": "Bring the Nintendo Switch games you own to the Mac." } }, "it": { "stringUnit": { "state": "translated", - "value": "meno di un minuto" + "value": "Porta sul Mac i giochi Nintendo Switch che possiedi." } }, "fr": { "stringUnit": { "state": "translated", - "value": "moins d’une minute" + "value": "Amenez sur le Mac les jeux Nintendo Switch que vous possédez." } }, "de": { "stringUnit": { "state": "translated", - "value": "unter einer Minute" + "value": "Bring deine eigenen Nintendo-Switch-Spiele auf den Mac." } }, "es": { "stringUnit": { "state": "translated", - "value": "menos de un minuto" + "value": "Lleva al Mac los juegos de Nintendo Switch que tienes." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "menos de um minuto" + "value": "Leve para o Mac os jogos de Nintendo Switch que você tem." } } } }, - "unknown error": { - "comment": "NewestEngine.swift", + "Arcane is not affiliated with Nintendo.": { + "comment": "FoundGamesSetupView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "unknown error" + "value": "Arcane is not affiliated with Nintendo." } }, "it": { "stringUnit": { "state": "translated", - "value": "errore sconosciuto" + "value": "Arcane non è affiliato a Nintendo." } }, "fr": { "stringUnit": { "state": "translated", - "value": "erreur inconnue" + "value": "Arcane n'est pas affilié à Nintendo." } }, "de": { "stringUnit": { "state": "translated", - "value": "unbekannter Fehler" + "value": "Arcane ist nicht mit Nintendo verbunden." } }, "es": { "stringUnit": { "state": "translated", - "value": "error desconocido" + "value": "Arcane no está afiliado a Nintendo." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "erro desconhecido" + "value": "O Arcane não é afiliado à Nintendo." } } } }, - "updated from %@ to": { - "comment": "AppViewModel+NewestEngine.swift:69", + "%lld installed Mac games": { + "comment": "Quantity-sensitive UI message; preserve %lld count and other placeholders.", "localizations": { "en": { - "stringUnit": { - "state": "translated", - "value": "updated from %@ to" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld installed Mac game" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld installed Mac games" + } + } + } } }, "it": { - "stringUnit": { - "state": "translated", - "value": "aggiornato da %@ a" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld gioco per Mac installato" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld giochi per Mac installati" + } + } + } } }, "fr": { - "stringUnit": { - "state": "translated", - "value": "mis à jour de %@ vers" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld jeu Mac installé" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld jeux Mac installés" + } + } + } } }, "de": { - "stringUnit": { - "state": "translated", - "value": "von %@ aktualisiert auf" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld installiertes Mac-Spiel" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld installierte Mac-Spiele" + } + } + } } }, "es": { - "stringUnit": { - "state": "translated", - "value": "actualizado de %@ a" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld juego para Mac instalado" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld juegos para Mac instalados" + } + } + } } }, "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "atualizada de %@ para" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld jogo para Mac instalado" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld jogos para Mac instalados" + } + } + } } } } }, - "version %@ (build %@)": { - "comment": "CheatCopy.swift", + "Welcome to Arcane": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "version %@ (build %@)" + "value": "Welcome to Arcane" } }, "it": { "stringUnit": { "state": "translated", - "value": "versione %@ (build %@)" + "value": "Benvenuto in Arcane" } }, "fr": { "stringUnit": { "state": "translated", - "value": "version %@ (build %@)" + "value": "Bienvenue dans Arcane" } }, "de": { "stringUnit": { "state": "translated", - "value": "Version %@ (Build %@)" + "value": "Willkommen bei Arcane" } }, "es": { "stringUnit": { "state": "translated", - "value": "versión %@ (compilación %@)" + "value": "Te damos la bienvenida a Arcane" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "versão %@ (build %@)" + "value": "Boas-vindas ao Arcane" } } } }, - "version unavailable (requires 3.12+)": { - "comment": "CompatibilityChecker.swift", + "What's new": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "version unavailable (requires 3.12+)" + "value": "What's new" } }, "it": { "stringUnit": { "state": "translated", - "value": "versione non disponibile (richiede 3.12+)" + "value": "Novità" } }, "fr": { "stringUnit": { "state": "translated", - "value": "version indisponible (nécessite 3.12+)" + "value": "Nouveautés" } }, "de": { "stringUnit": { "state": "translated", - "value": "Version nicht verfügbar (3.12+ erforderlich)" + "value": "Neuigkeiten" } }, "es": { "stringUnit": { "state": "translated", - "value": "versión no disponible (requiere 3.12+)" + "value": "Novedades" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "versão indisponível (requer 3.12+)" + "value": "Novidades" } } } }, - "video": { - "comment": "Display copy only; internal values and paths remain unchanged.", + "Steam games for Mac in the same library": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "video" + "value": "Steam games for Mac in the same library" } }, "it": { "stringUnit": { "state": "translated", - "value": "video" + "value": "I giochi Steam per Mac nella stessa libreria" } }, "fr": { "stringUnit": { "state": "translated", - "value": "vidéo" + "value": "Les jeux Steam pour Mac dans la même bibliothèque" } }, "de": { "stringUnit": { "state": "translated", - "value": "Video" + "value": "Steam-Spiele für Mac in derselben Bibliothek" } }, "es": { "stringUnit": { "state": "translated", - "value": "vídeo" + "value": "Los juegos de Steam para Mac en la misma biblioteca" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "vídeo" + "value": "Jogos do Steam para Mac na mesma biblioteca" } } } }, - "wait for storage cleanup to finish": { - "comment": "AppViewModel.swift", + "Achievements, with rarity and crystal trophies": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "wait for storage cleanup to finish" + "value": "Achievements, with rarity and crystal trophies" } }, "it": { "stringUnit": { "state": "translated", - "value": "attendi il termine della pulizia dello spazio di archiviazione" + "value": "Gli achievement, con rarità e trofei a cristallo" } }, "fr": { "stringUnit": { "state": "translated", - "value": "attendez la fin du nettoyage du stockage" + "value": "Les succès, avec leur rareté et des trophées de cristal" } }, "de": { "stringUnit": { "state": "translated", - "value": "warte, bis die Speicherbereinigung abgeschlossen ist" + "value": "Errungenschaften, mit Seltenheit und Kristalltrophäen" } }, "es": { "stringUnit": { "state": "translated", - "value": "espera a que termine la limpieza del almacenamiento" + "value": "Los logros, con rareza y trofeos de cristal" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "aguarde o término da limpeza do armazenamento" + "value": "Conquistas, com raridade e troféus de cristal" } } } }, - "wait for the app icon update to finish": { - "comment": "AppViewModel.swift", + "Critic scores and metadata from more sources": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "wait for the app icon update to finish" + "value": "Critic scores and metadata from more sources" } }, "it": { "stringUnit": { "state": "translated", - "value": "attendi il termine dell’aggiornamento dell’icona dell’app" + "value": "Voti della critica e metadati da più fonti" } }, "fr": { "stringUnit": { "state": "translated", - "value": "attendez la fin de la mise à jour de l’icône de l’app" + "value": "Notes de la critique et métadonnées de plusieurs sources" } }, "de": { "stringUnit": { "state": "translated", - "value": "warte, bis das App-Symbol aktualisiert wurde" + "value": "Kritikerwertungen und Metadaten aus mehr Quellen" } }, "es": { "stringUnit": { "state": "translated", - "value": "espera a que termine la actualización del icono de la app" + "value": "Notas de la crítica y metadatos de más fuentes" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "aguarde o término da atualização do ícone do app" + "value": "Notas da crítica e metadados de mais fontes" } } } }, - "wait for the app update to finish": { - "comment": "AppViewModel.swift", + "Settings regrouped: General, Library, Porting, System": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "wait for the app update to finish" + "value": "Settings regrouped: General, Library, Porting, System" } }, "it": { "stringUnit": { "state": "translated", - "value": "attendi il termine dell’aggiornamento dell’app" + "value": "Impostazioni riordinate: Generali, Libreria, Porting, Sistema" } }, "fr": { "stringUnit": { "state": "translated", - "value": "attendez la fin de la mise à jour de l’app" + "value": "Réglages regroupés : Général, Bibliothèque, Porting, Système" } }, "de": { "stringUnit": { "state": "translated", - "value": "warte, bis das App-Update abgeschlossen ist" + "value": "Einstellungen neu geordnet: Allgemein, Bibliothek, Porting, System" } }, "es": { "stringUnit": { "state": "translated", - "value": "espera a que termine la actualización de la app" + "value": "Ajustes reorganizados: General, Biblioteca, Porting, Sistema" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "aguarde o término da atualização do app" + "value": "Ajustes reorganizados: Geral, Biblioteca, Porting, Sistema" } } } }, - "⌘K": { - "comment": "ButtonPrompts.swift:44", + "Adding them doesn't change Steam's files.": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "⌘K" + "value": "Adding them doesn't change Steam's files." } }, "it": { "stringUnit": { "state": "translated", - "value": "⌘K" + "value": "Aggiungerli alla libreria non cambia i file di Steam." } }, "fr": { "stringUnit": { "state": "translated", - "value": "⌘K" + "value": "Les ajouter ne modifie pas les fichiers de Steam." } }, "de": { "stringUnit": { "state": "translated", - "value": "⌘K" + "value": "Das Hinzufügen ändert keine Steam-Dateien." } }, "es": { "stringUnit": { "state": "translated", - "value": "⌘K" + "value": "Añadirlos no cambia los archivos de Steam." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "⌘K" + "value": "Adicioná-los não altera os arquivos do Steam." } } } }, - "⌘Return to save · Empty for Automatic": { - "comment": "ChangeMetadataView.swift", + "Found %lld Steam games": { + "comment": "Quantity-sensitive UI message; preserve %lld count and other placeholders.", "localizations": { "en": { - "stringUnit": { - "state": "translated", - "value": "⌘Return to save · Empty for Automatic" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Found %lld Steam game" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Found %lld Steam games" + } + } + } } }, "it": { - "stringUnit": { - "state": "translated", - "value": "⌘Invio per salvare · Lascia vuoto per Automatico" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Ho trovato %lld gioco Steam" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Ho trovato %lld giochi Steam" + } + } + } } }, "fr": { - "stringUnit": { - "state": "translated", - "value": "⌘Retour pour enregistrer · Laisser vide pour Automatique" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld jeu Steam trouvé" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld jeux Steam trouvés" + } + } + } } }, "de": { - "stringUnit": { - "state": "translated", - "value": "⌘Return zum Speichern · Leer lassen für „Automatisch“" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam-Spiel gefunden" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld Steam-Spiele gefunden" + } + } + } } }, "es": { - "stringUnit": { - "state": "translated", - "value": "⌘Retorno para guardar · Vacío para Automático" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "Se ha encontrado %lld juego de Steam" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "Se han encontrado %lld juegos de Steam" + } + } + } } }, "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "⌘Return para salvar · Deixe em branco para Automático" + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld jogo do Steam encontrado" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld jogos do Steam encontrados" + } + } + } } } } }, - "◂ ▸ Move": { - "comment": "SpotlightView.swift", + "%@ has a new name: your games and settings are right where you left them.": { + "comment": "ArcaneWelcomeView.swift", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "◂ ▸ Move" + "value": "%@ has a new name: your games and settings are right where you left them." } }, "it": { "stringUnit": { "state": "translated", - "value": "◂ ▸ Sposta" + "value": "%@ ha un nome nuovo: i tuoi giochi e le tue impostazioni sono dove li hai lasciati." } }, "fr": { "stringUnit": { "state": "translated", - "value": "◂ ▸ Déplacer" + "value": "%@ change de nom : vos jeux et vos réglages sont là où vous les avez laissés." } }, "de": { "stringUnit": { "state": "translated", - "value": "◂ ▸ Verschieben" + "value": "%@ hat einen neuen Namen: Deine Spiele und Einstellungen sind genau dort, wo du sie gelassen hast." } }, "es": { "stringUnit": { "state": "translated", - "value": "◂ ▸ Mover" + "value": "%@ tiene un nombre nuevo: tus juegos y ajustes siguen donde los dejaste." } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "◂ ▸ Mover" + "value": "O %@ tem um nome novo: seus jogos e ajustes estão onde você os deixou." } } } diff --git a/Sources/NXLibraryCore/Resources/crystal-arcane.mov b/Sources/NXLibraryCore/Resources/crystal-arcane.mov new file mode 100644 index 00000000..cd1be5c0 Binary files /dev/null and b/Sources/NXLibraryCore/Resources/crystal-arcane.mov differ diff --git a/Sources/NXLibraryCore/Resources/crystal-arcane.png b/Sources/NXLibraryCore/Resources/crystal-arcane.png new file mode 100644 index 00000000..92fb2ff2 Binary files /dev/null and b/Sources/NXLibraryCore/Resources/crystal-arcane.png differ diff --git a/Sources/NXLibraryCore/Resources/crystal-bronze.png b/Sources/NXLibraryCore/Resources/crystal-bronze.png new file mode 100644 index 00000000..a6d8e826 Binary files /dev/null and b/Sources/NXLibraryCore/Resources/crystal-bronze.png differ diff --git a/Sources/NXLibraryCore/Resources/crystal-gold.png b/Sources/NXLibraryCore/Resources/crystal-gold.png new file mode 100644 index 00000000..25b08fb1 Binary files /dev/null and b/Sources/NXLibraryCore/Resources/crystal-gold.png differ diff --git a/Sources/NXLibraryCore/Resources/crystal-silver.png b/Sources/NXLibraryCore/Resources/crystal-silver.png new file mode 100644 index 00000000..1a5f825c Binary files /dev/null and b/Sources/NXLibraryCore/Resources/crystal-silver.png differ diff --git a/Sources/NXLibraryCore/Services/AppBundleRename.swift b/Sources/NXLibraryCore/Services/AppBundleRename.swift new file mode 100644 index 00000000..b3be60c2 --- /dev/null +++ b/Sources/NXLibraryCore/Services/AppBundleRename.swift @@ -0,0 +1,29 @@ +import Foundation + +/// Gives a release copy still called "NX Library.app" its current name when the app quits. +/// Renaming while it runs would leave `Bundle.main` on the old path for the rest of the session, +/// so it happens only at quit, and only when nothing else is about to use that path. +public enum AppBundleRename { + public static let oldName = "NX Library.app" + public static var newName: String { "\(AppIdentity.name).app" } + + /// Where the bundle should go, or nil when it stays as it is: a development or translocated + /// copy, an app busy updating, saving or relaunching itself, any other name, a read-only + /// folder, or an "Arcane.app" already beside it. + public static func target(bundleURL: URL, isRelease: Bool, isTranslocated: Bool, isBusy: Bool, + fileManager: FileManager = .default) -> URL? { + guard isRelease, !isTranslocated, !isBusy else { return nil } + let bundle = bundleURL.standardizedFileURL + guard bundle.lastPathComponent == oldName else { return nil } + let folder = bundle.deletingLastPathComponent() + let target = folder.appendingPathComponent(newName) + guard fileManager.isWritableFile(atPath: folder.path), + !fileManager.fileExists(atPath: target.path) else { return nil } + return target + } + + /// One move within the same folder; a failure leaves the bundle where it was. + public static func perform(bundleURL: URL, to target: URL, fileManager: FileManager = .default) throws { + try fileManager.moveItem(at: bundleURL, to: target) + } +} diff --git a/Sources/NXLibraryCore/Services/AppDataProfile.swift b/Sources/NXLibraryCore/Services/AppDataProfile.swift new file mode 100644 index 00000000..79fed695 --- /dev/null +++ b/Sources/NXLibraryCore/Services/AppDataProfile.swift @@ -0,0 +1,56 @@ +import Foundation + +/// Immutable location policy. The build declares its profile; filenames and branch names do not select it. +public struct AppDataProfile: Sendable { + public let home: URL + public let isDevelopment: Bool + public init(home: URL = FileManager.default.homeDirectoryForCurrentUser, isDevelopment: Bool) { + self.home = home + self.isDevelopment = isDevelopment + } + /// Folders are built as folders (`isDirectory: true`), never by asking the disk, so a root is the same URL + /// before and after it is created: equal to `file.deletingLastPathComponent()` on a fresh Mac too. + public var stableSupportRoot: URL { home.appendingPathComponent("Library/Application Support/NXLibrary", isDirectory: true) } + public var supportRoot: URL { + isDevelopment ? home.appendingPathComponent("Library/Application Support/NXLibrary-Development", isDirectory: true) : stableSupportRoot + } + public var cacheRoot: URL { home.appendingPathComponent("Library/Caches/" + (isDevelopment ? "NXLibrary-Development" : "NXLibrary"), isDirectory: true) } + public func automaticStagingFolders(appFolders: [URL]) -> [URL] { + BuildScratch.tempFolders(core: supportRoot, appFolders: isDevelopment ? [] : appFolders) + } + public var preferencesDomain: String { isDevelopment ? "local.nxlibrary.development" : "local.nxlibrary" } +} + +/// All app-owned stores use this composition-root policy, including their default initializers. +/// Game installations, their runtime preferences and saves are separate, explicitly operated-on resources. +public enum AppData { + public static let profile = AppDataProfile(isDevelopment: Bundle.main.object(forInfoDictionaryKey: "NXLibraryDevelopmentProfile") as? Bool == true) + public static var supportRoot: URL { profile.supportRoot } + public static var cacheRoot: URL { profile.cacheRoot } + // Each packaged profile has its own bundle ID. Foundation already binds + // standard preferences to that ID and rejects reopening it as a suite. + public static var preferences: UserDefaults { .standard } + public static func validateBuildIdentity(_ info: [String: Any]) throws { + let development = info["NXLibraryDevelopmentProfile"] as? Bool == true + let release = info["NXLibraryRelease"] as? Bool == true + let identifier = info["CFBundleIdentifier"] as? String + guard (development && !release && identifier == "local.nxlibrary.development") + || (release && !development && identifier == "local.nxlibrary") else { + throw DevelopmentProfileError.invalidConfiguration + } + } + public static func prepare() throws { + // An unmarked/mispackaged executable must not silently open the live profile. + try validateBuildIdentity(Bundle.main.infoDictionary ?? [:]) + guard profile.isDevelopment else { return } + let defaults = preferences + _ = try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { + UserDefaults.standard.persistentDomain(forName: "local.nxlibrary") ?? [:] + }, savePreferences: { values in + defaults.setPersistentDomain(values, forName: profile.preferencesDomain) + guard CFPreferencesAppSynchronize(profile.preferencesDomain as CFString) else { + throw DevelopmentProfileError.preferencesUnavailable + } + }) + } +} diff --git a/Sources/NXLibraryCore/Services/AppIconWriter.swift b/Sources/NXLibraryCore/Services/AppIconWriter.swift index 4b4ec1d2..9a687575 100644 --- a/Sources/NXLibraryCore/Services/AppIconWriter.swift +++ b/Sources/NXLibraryCore/Services/AppIconWriter.swift @@ -21,7 +21,7 @@ public struct AppIconWriter { public var errorDescription: String? { switch self { case .notAnApp: return L10n.text("The game's app was not found.") - case .notAnImage: return L10n.text("The icon is not an image NX Library can read.") + case .notAnImage: return L10n.text("The icon is not an image Arcane can read.") case .iconFailed(let detail): return L10n.format("The icon could not be made: %@", [String(describing: (detail))]) case .signingFailed(let detail): return L10n.format("The app could not be signed again, so it was left as it was: %@", [String(describing: (detail))]) } @@ -40,8 +40,7 @@ public struct AppIconWriter { private let iconutil: URL private let xattr: URL - public init(backups: URL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/app-icons"), + public init(backups: URL = AppData.supportRoot.appendingPathComponent("app-icons"), runner: CommandRunning = SystemCommandRunner(), fileManager: FileManager = .default, codesign: URL = URL(fileURLWithPath: "/usr/bin/codesign"), iconutil: URL = URL(fileURLWithPath: "/usr/bin/iconutil"), diff --git a/Sources/NXLibraryCore/Services/AppSettingsStore.swift b/Sources/NXLibraryCore/Services/AppSettingsStore.swift index 28924691..a6befdab 100644 --- a/Sources/NXLibraryCore/Services/AppSettingsStore.swift +++ b/Sources/NXLibraryCore/Services/AppSettingsStore.swift @@ -3,9 +3,17 @@ import Combine public final class AppSettingsStore: ObservableObject { @Published public var settings: AppSettings { - didSet { save() } + didSet { + if settings.lastSelectedGameID != oldValue.lastSelectedGameID { + lastSelectedGameID = settings.lastSelectedGameID + } + save() + } } + /// Navigation state. Publishing it as a settings change re-enters the view graph during a row move. + public private(set) var lastSelectedGameID: UUID? + public enum ErrorKind { case reading, writing } @Published public private(set) var loadError: String? public private(set) var errorKind: ErrorKind? @@ -13,6 +21,10 @@ public final class AppSettingsStore: ObservableObject { public let fileURL: URL private let fileManager: FileManager private var isLoading = false + // The main thread owns the snapshots and their revision. The writer serializes file replacement. + private let writer = DispatchQueue(label: "local.nxlibrary.settings-write", qos: .utility) + private var writeRevision = 0 + private var pendingSelectionWrite: DispatchWorkItem? private var needsRecoveryCopy = false public init(fileURL: URL = AppSettingsStore.defaultURL(), @@ -24,19 +36,61 @@ public final class AppSettingsStore: ObservableObject { } public static func defaultURL() -> URL { - FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/settings.json") + AppData.supportRoot.appendingPathComponent("settings.json") } @discardableResult public func save() -> Bool { guard !isLoading else { return true } + let revision = nextWriteRevision() + let snapshot = snapshotForWrite() + let outcome = writer.sync { write(snapshot) } + publish(outcome, revision: revision) + return outcome.error == nil + } + + /// Update the restore choice without invalidating settings observers or writing on the animation thread. + @MainActor public func rememberLastSelectedGame(_ id: UUID) { + guard lastSelectedGameID != id else { return } + lastSelectedGameID = id + + let revision = nextWriteRevision() + let snapshot = snapshotForWrite() + let work = DispatchWorkItem { [weak self] in + guard let self else { return } + let outcome = self.write(snapshot) + DispatchQueue.main.async { [weak self] in self?.publish(outcome, revision: revision) } + } + pendingSelectionWrite = work + writer.async(execute: work) + } + + /// Quitting can overtake the queued write. Save the latest value before exiting. + @MainActor public func flushPendingSelection() { + if pendingSelectionWrite != nil { save() } + } + + private func snapshotForWrite() -> AppSettings { + var snapshot = settings + snapshot.lastSelectedGameID = lastSelectedGameID + return snapshot + } + + private func nextWriteRevision() -> Int { + pendingSelectionWrite?.cancel() + pendingSelectionWrite = nil + writeRevision += 1 + return writeRevision + } + + private func write(_ snapshot: AppSettings) -> (recovery: URL?, error: Error?) { + var recovery: URL? do { try fileManager.createDirectory( at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true ) - try preserveUnreadableFile() - let data = try JSONEncoder().encode(settings) + recovery = try preserveUnreadableFile() + let data = try JSONEncoder().encode(snapshot) let temp = fileURL.deletingLastPathComponent() .appendingPathComponent(".settings-\(UUID()).tmp") defer { try? fileManager.removeItem(at: temp) } @@ -46,13 +100,22 @@ public final class AppSettingsStore: ObservableObject { } else { try fileManager.moveItem(at: temp, to: fileURL) } - errorKind = nil - loadError = nil - return true + return (recovery, nil) } catch { + return (recovery, error) + } + } + + private func publish(_ outcome: (recovery: URL?, error: Error?), revision: Int) { + if let copied = outcome.recovery { recoveryFileURL = copied } + guard writeRevision == revision else { return } + pendingSelectionWrite = nil + if let error = outcome.error { errorKind = .writing loadError = error.localizedDescription - return false + } else { + errorKind = nil + if loadError != nil { loadError = nil } } } @@ -61,13 +124,13 @@ public final class AppSettingsStore: ObservableObject { loadError = nil } - private func preserveUnreadableFile() throws { - guard needsRecoveryCopy else { return } + private func preserveUnreadableFile() throws -> URL? { + guard needsRecoveryCopy else { return nil } let copy = fileURL.deletingLastPathComponent() .appendingPathComponent("settings.unreadable-\(UUID()).json") try fileManager.copyItem(at: fileURL, to: copy) - recoveryFileURL = copy needsRecoveryCopy = false + return copy } private func load() { @@ -81,7 +144,7 @@ public final class AppSettingsStore: ObservableObject { } catch { settings = AppSettings() needsRecoveryCopy = true - try? preserveUnreadableFile() + recoveryFileURL = try? preserveUnreadableFile() errorKind = .reading loadError = error.localizedDescription } diff --git a/Sources/NXLibraryCore/Services/AppUpdate.swift b/Sources/NXLibraryCore/Services/AppUpdate.swift index bc9e5950..4f1b0a9d 100644 --- a/Sources/NXLibraryCore/Services/AppUpdate.swift +++ b/Sources/NXLibraryCore/Services/AppUpdate.swift @@ -3,6 +3,7 @@ import Foundation import CryptoKit +import Darwin /// The rules of NX Library's self-update: which release, what may be installed, which copy may /// replace itself, and the swap. Everything works on paths it is given, so the tests run it on @@ -19,6 +20,9 @@ public enum AppUpdate { public static let defaultRepository: String? = "Bium23/NxLibrary" /// A UserDefaults override of `defaultRepository`, for testing before publishing. public static let repositoryOverrideKey = "NXLibrary_UpdateRepository" + /// A repository that may replace `defaultRepository` under another name. GitHub redirects the old + /// release API there, so its assets are accepted too; nil while the project keeps its name. + public static let successorRepository: String? = nil /// The Info.plist key that marks a release copy. public static let releaseMarker = "NXLibraryRelease" static let interval: TimeInterval = 24 * 3600 @@ -28,10 +32,12 @@ public enum AppUpdate { /// of the version in progress, so it never reads like a published release. public static func versionLabel(_ info: [String: Any]?) -> String { let short = info?["CFBundleShortVersionString"] as? String ?? "?" - return info?[releaseMarker] as? Bool == true ? short : "\(short) (development build)" + if info?[releaseMarker] as? Bool == true { return short } + if info?["NXLibraryDevelopmentProfile"] as? Bool == true { return "\(short) (Dev · Launcher)" } + return "\(short) (development build)" } - public static func repository(defaults: UserDefaults = .standard) -> String? { + public static func repository(defaults: UserDefaults = AppData.preferences) -> String? { if let value = defaults.string(forKey: repositoryOverrideKey)?.trimmingCharacters(in: .whitespaces), value.range(of: #"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"#, options: .regularExpression) != nil { return value @@ -113,8 +119,10 @@ public enum AppUpdate { return notes } - /// GitHub's `releases/latest` answer, with the asset named `NXLibrary-<version>.zip`. - public static func parseRelease(_ json: Data, repository: String = "Bium23/NxLibrary") -> Release? { + /// GitHub's `releases/latest` answer, with the asset named `NXLibrary-<version>.zip` in `repository` + /// or, when there is one, in its `successor`. + public static func parseRelease(_ json: Data, repository: String = "Bium23/NxLibrary", + successor: String? = AppUpdate.successorRepository) -> Release? { guard json.count <= 1024 * 1024, let object = try? JSONSerialization.jsonObject(with: json) as? [String: Any], let tag = object["tag_name"] as? String, let version = version(fromTag: tag), @@ -122,7 +130,9 @@ public enum AppUpdate { let asset = assets.first(where: { $0["name"] as? String == "NXLibrary-\(version).zip" }), let link = asset["browser_download_url"] as? String, let url = URL(string: link), trustedDownloadURL(url), url.host?.lowercased() == "github.com", - url.path == "/\(repository)/releases/download/\(tag)/NXLibrary-\(version).zip", + ([repository] + [successor].compactMap { $0 }).contains(where: { owner in + url.path == "/\(owner)/releases/download/\(tag)/NXLibrary-\(version).zip" + }), url.query == nil, url.fragment == nil, let bytes = asset["size"] as? Int64, bytes > 0, bytes <= maximumDownloadBytes, let digest = asset["digest"] as? String, @@ -236,7 +246,7 @@ public enum AppUpdate { FileManager.default.isExecutableFile(atPath: app.appendingPathComponent("Contents/MacOS/" + exe).path) else { return .noExecutable } guard info["CFBundleShortVersionString"] as? String == version else { return .wrongVersion } - guard info[releaseMarker] as? Bool == true else { return .notRelease } + guard info[releaseMarker] as? Bool == true, info["NXLibraryDevelopmentProfile"] as? Bool != true else { return .notRelease } if let text = info["LSMinimumSystemVersion"] as? String, let minimum = numbers(text) { let running = [runningOS.majorVersion, runningOS.minorVersion, runningOS.patchVersion] let padded = minimum + Array(repeating: 0, count: max(0, 3 - minimum.count)) @@ -256,7 +266,7 @@ public enum AppUpdate { } public static func installability(_ bundle: URL) -> Installability { - guard bundle.pathExtension == "app", info(bundle)?[releaseMarker] as? Bool == true else { return .developer } + guard bundle.pathExtension == "app", let metadata = info(bundle), metadata[releaseMarker] as? Bool == true, metadata["NXLibraryDevelopmentProfile"] as? Bool != true else { return .developer } let standardized = bundle.standardizedFileURL if standardized.path.contains("/AppTranslocation/") { return .readOnly } if !FileManager.default.isWritableFile(atPath: standardized.deletingLastPathComponent().path) { return .readOnly } @@ -267,32 +277,63 @@ public enum AppUpdate { public enum InstallError: Error, Equatable { case failed(String) } - /// Copies `staged` beside `current`, then exchanges the two in one replace, so a failure - /// anywhere leaves a working app at `current`. The old copy goes to the Trash (`trashOld`; the - /// tests remove it), and the new one loses the quarantine flag (releases are ad-hoc signed). + /// Stages on the destination volume in an exclusively owned directory, then + /// atomically exchanges the apps. A failed Trash operation retains the old app there. @discardableResult public static func install(_ staged: URL, over current: URL, trashOld: Bool = true) throws -> URL { - let fm = FileManager.default - let folder = current.deletingLastPathComponent() - let name = current.deletingPathExtension().lastPathComponent - let incoming = folder.appendingPathComponent(name + " (new).app") - let backupName = name + " (old).app" - let backup = folder.appendingPathComponent(backupName) - try? fm.removeItem(at: incoming) - try? fm.removeItem(at: backup) + try install(staged, over: current, trashOld: trashOld, fileManager: .default, io: BuildInstallIO()) + } + + static func install(_ staged: URL, over current: URL, trashOld: Bool, + fileManager fm: FileManager, io: BuildInstallIO) throws -> URL { + guard let previous = updateIdentity(current) else { throw InstallError.failed("The installed app is missing or unsafe.") } + var template = Array(current.deletingLastPathComponent().appendingPathComponent(".arcane-update.XXXXXX").path.utf8CString) + let work = try template.withUnsafeMutableBufferPointer { buffer -> URL in + guard let path = mkdtemp(buffer.baseAddress!) else { throw InstallError.failed(String(cString: strerror(errno))) } + return URL(fileURLWithPath: String(cString: path), isDirectory: true) + } + // Never recursively remove this directory: after a swap it may hold the old app. + defer { _ = rmdir(work.path) } + let incoming = work.appendingPathComponent(current.lastPathComponent) do { try fm.copyItem(at: staged, to: incoming) - let placed = try fm.replaceItemAt(current, withItemAt: incoming, backupItemName: backupName, - options: [.withoutDeletingBackupItem]) - if fm.fileExists(atPath: backup.path) { - if trashOld { try? fm.trashItem(at: backup, resultingItemURL: nil) } else { try? fm.removeItem(at: backup) } - } - clearQuarantine(placed ?? current) - return placed ?? current } catch { + // Only a partial copy inside this attempt's private directory is owned. try? fm.removeItem(at: incoming) throw InstallError.failed(error.localizedDescription) } + guard let prepared = updateIdentity(incoming), updateIdentity(current) == previous else { + try? fm.removeItem(at: incoming) + throw InstallError.failed("The installed app changed while the update was being prepared.") + } + do { + try io.publish(incoming, current, true) + try io.afterPublish() + } catch { + // If publication already happened, finish the successful installation. + // Otherwise remove only the candidate whose identity we recorded. + guard updateIdentity(current) == prepared, updateIdentity(incoming) == previous else { + if updateIdentity(incoming) == prepared { try? fm.removeItem(at: incoming) } + throw InstallError.failed(error.localizedDescription) + } + } + if updateIdentity(incoming) == previous { + if trashOld { try? fm.trashItem(at: incoming, resultingItemURL: nil) } + else { try? fm.removeItem(at: incoming) } + } + clearQuarantine(current) + return current + } + + private struct UpdateIdentity: Equatable { + let device: dev_t + let inode: ino_t + } + + private static func updateIdentity(_ url: URL) -> UpdateIdentity? { + var info = stat() + guard lstat(url.path, &info) == 0, info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) else { return nil } + return UpdateIdentity(device: info.st_dev, inode: info.st_ino) } /// Waits until `$1` (a pid) has exited, at most `$3` ticks of 0.2 s, then opens `$2` with `$4`. diff --git a/Sources/NXLibraryCore/Services/ArtworkBrowse.swift b/Sources/NXLibraryCore/Services/ArtworkBrowse.swift index 73792ba5..704633bd 100644 --- a/Sources/NXLibraryCore/Services/ArtworkBrowse.swift +++ b/Sources/NXLibraryCore/Services/ArtworkBrowse.swift @@ -45,13 +45,14 @@ public enum ArtworkBrowseSource: String, CaseIterable, Sendable { /// Searches the source. A name the player searches is taken loosely: the first Switch result (LaunchBox) or the /// first result (SteamGridDB) when no title matches it exactly. - public func search(_ query: String, gameNames: [String], switch2: Bool, key: String?, + /// `computer`: a native Mac game (Steam), looked for among LaunchBox's Mac and Windows entries. + public func search(_ query: String, gameNames: [String], switch2: Bool, computer: Bool = false, key: String?, client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> Found { let names = Self.names(for: query, gameNames: gameNames) guard !names.isEmpty else { return Found(page: nil, candidates: []) } switch self { case .launchBox: - let game = await LaunchBoxArt.game(names: names, switch2: switch2, loose: true, client: client) + let game = await LaunchBoxArt.game(names: names, switch2: switch2, computer: computer, loose: true, client: client) return Found(page: game?.page, candidates: game?.candidates ?? []) case .steamGridDB: guard let key else { return Found(page: nil, candidates: []) } diff --git a/Sources/NXLibraryCore/Services/ArtworkPicker.swift b/Sources/NXLibraryCore/Services/ArtworkPicker.swift index 89800bbe..02802b3f 100644 --- a/Sources/NXLibraryCore/Services/ArtworkPicker.swift +++ b/Sources/NXLibraryCore/Services/ArtworkPicker.swift @@ -93,7 +93,7 @@ public struct TitleDBInfo: Equatable, Sendable { let url = URL(string: "https://api.nlib.cc/nx/\(titleID)") else { return nil } var request = URLRequest(url: url) request.timeoutInterval = 15 - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") guard let (data, http) = try? await client.data(for: request), (200..<300).contains(http.statusCode) else { return nil } @@ -195,6 +195,27 @@ public enum ArtworkCandidates { return list } + /// A Steam game's images for `slot`: Steam's own art for the exact AppID first, its store + /// screenshots as backgrounds, then everything found online (`OnlineArtwork`), without repeats. + /// Steam has no icon art: the Icon tab offers only online images and files. + public static func steamList(for slot: ArtworkSlot, appID: UInt32, screenshots: [URL], + online: [ArtworkCandidate] = []) -> [ArtworkCandidate] { + // Named for where Steam shows it, so the library hero is recognizable among the backgrounds. + var list = (appID > 0 ? SteamStoreArt.candidates(appID: Int(appID), slot: slot) : []).map { + ArtworkCandidate(slot: $0.slot, source: "Steam library", url: $0.url, fallback: $0.fallback) + } + if slot == .background { + for shot in OnlineArtwork.screenshots(screenshots.map(\.absoluteString), source: "Steam screenshot", stripQuery: true) + where !list.contains(where: { $0.url == shot.url }) { + list.append(shot) + } + } + for candidate in online where candidate.slot == slot && !list.contains(where: { $0.url == candidate.url }) { + list.append(candidate) + } + return list + } + /// Downloads a candidate (or its fallback) and reads its size; nil when both are missing or not images. public static func load(_ candidate: ArtworkCandidate, client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> LoadedArtwork? { @@ -214,7 +235,7 @@ public enum ArtworkCandidates { client: ArtworkHTTPClient, timeout: TimeInterval = 20) async -> LoadedArtwork? { var request = URLRequest(url: url) request.timeoutInterval = timeout - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") guard let (data, http) = try? await client.data(for: request), (200..<300).contains(http.statusCode), let size = pixelSize(of: data) else { return nil } return LoadedArtwork(candidate: candidate, data: data, pixelWidth: size.width, pixelHeight: size.height) @@ -237,15 +258,14 @@ public final class ArtworkPicks: ObservableObject { public enum Failure: LocalizedError { case notAnImage - public var errorDescription: String? { L10n.text("That file is not an image NX Library can read.") } + public var errorDescription: String? { L10n.text("That file is not an image Arcane can read.") } } public let directory: URL /// Bumps on every change, so screens reload their art. @Published public private(set) var revision = 0 - public init(directory: URL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/artwork-picks")) { + public init(directory: URL = AppData.supportRoot.appendingPathComponent("artwork-picks")) { self.directory = directory } diff --git a/Sources/NXLibraryCore/Services/ArtworkStore.swift b/Sources/NXLibraryCore/Services/ArtworkStore.swift index a8fd5742..32d976e2 100644 --- a/Sources/NXLibraryCore/Services/ArtworkStore.swift +++ b/Sources/NXLibraryCore/Services/ArtworkStore.swift @@ -2,6 +2,7 @@ import Foundation import AppKit import ImageIO import Combine +import os public enum ArtworkKind: String, Codable { case hero, logo, square @@ -44,6 +45,8 @@ public final class ArtworkStore: ObservableObject { private let client: ArtworkHTTPClient private let automaticIcons: AutomaticIconResolver private let fileManager: FileManager + /// Steam games LaunchBox had no Square for, this session: not searched again until the next launch. + private let steamIconMisses = OSAllocatedUnfairLock(initialState: Set<String>()) public init(cacheDirectory: URL = ArtworkStore.defaultDirectory(), client: ArtworkHTTPClient = URLSessionArtworkClient(), @@ -55,8 +58,7 @@ public final class ArtworkStore: ObservableObject { } public static func defaultDirectory() -> URL { - FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/artwork") + AppData.supportRoot.appendingPathComponent("artwork") } public func cachedURL(titleID: String, kind: ArtworkKind) -> URL? { @@ -79,6 +81,22 @@ public final class ArtworkStore: ObservableObject { return await automaticIcons.resolve(titleID: titleID, name: name) } + /// The icon of a Steam game with no app of its own (Steam still installing it): LaunchBox's Square for its + /// Mac or Windows entry, matched by name as for its backgrounds, kept as the game's square. Nil when LaunchBox + /// has none: the tile stays neutral rather than show another image cropped to a square. The player's pick + /// and the app's own icon come first, in the caller. + public func automaticSteamIcon(titleID: String, names: [String]) async -> URL? { + if let cached = cachedURL(titleID: titleID, kind: .square) { return cached } + guard !steamIconMisses.withLock({ $0.contains(titleID) }) else { return nil } + let game = await LaunchBoxArt.game(names: names, switch2: false, computer: true, client: client) + guard let square = game.flatMap({ LaunchBoxArt.square(in: $0.candidates) }), + let url = await fetch(titleID: titleID, remoteURL: square, kind: .square) else { + steamIconMisses.withLock { _ = $0.insert(titleID) } + return nil + } + return url + } + public func automaticIconSource(titleID: String) -> String? { try? String(contentsOf: cacheDirectory.appendingPathComponent(Self.folderName(for: titleID.uppercased())) .appendingPathComponent("square-source.txt"), encoding: .utf8) @@ -95,7 +113,7 @@ public final class ArtworkStore: ObservableObject { var request = URLRequest(url: fetchURL) request.timeoutInterval = 15 - request.setValue("NXLibrary/0.1 (macOS; personal app)", + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") do { @@ -155,7 +173,7 @@ public final class ArtworkStore: ObservableObject { var request = URLRequest(url: remoteURL) request.timeoutInterval = 15 - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") do { let (data, http) = try await client.data(for: request) guard (200..<300).contains(http.statusCode), !data.isEmpty else { return nil } diff --git a/Sources/NXLibraryCore/Services/AutomaticIconResolver.swift b/Sources/NXLibraryCore/Services/AutomaticIconResolver.swift index 8b9dad13..18433253 100644 --- a/Sources/NXLibraryCore/Services/AutomaticIconResolver.swift +++ b/Sources/NXLibraryCore/Services/AutomaticIconResolver.swift @@ -136,7 +136,7 @@ actor AutomaticIconResolver { private static func get(_ url: URL, client: ArtworkHTTPClient, limit: Int = 8 * 1024 * 1024) async -> Data? { var request = URLRequest(url: url) request.timeoutInterval = 8 - request.setValue("NXLibrary (macOS; automatic icon lookup)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") guard let (data, response) = try? await client.data(for: request), response.statusCode == 200, !data.isEmpty, data.count <= limit, let final = response.url, final.scheme == "https", final.user == nil, final.password == nil, diff --git a/Sources/NXLibraryCore/Services/BoundedDownload.swift b/Sources/NXLibraryCore/Services/BoundedDownload.swift new file mode 100644 index 00000000..204b9626 --- /dev/null +++ b/Sources/NXLibraryCore/Services/BoundedDownload.swift @@ -0,0 +1,90 @@ +import Foundation + +/// A size-bounded HTTP read that keeps the chunks URLSession delivers. Iterating `URLSession.AsyncBytes` +/// one byte at a time cost about 6 µs per byte (a 640 KB LaunchBox page: 5.4 s instead of 2.0 s, almost all +/// of it CPU; measured 16 Nov 2026), so the public-source and Steam downloads read through this instead. +/// Redirects are never followed: the redirect response itself is returned, for the caller's URL checks. +enum BoundedDownload { + static func data(for request: URLRequest, session: URLSession, limit: Int) async throws -> (Data, URLResponse) { + try Task.checkCancellation() + let collector = Collector(limit: limit) + let task = session.dataTask(with: request) + task.delegate = collector + return try await withTaskCancellationHandler(operation: { + try await withCheckedThrowingContinuation { continuation in + collector.start(continuation) + task.resume() + } + }, onCancel: { task.cancel() }) + } + + private final class Collector: NSObject, URLSessionDataDelegate, @unchecked Sendable { + private let limit: Int + private let lock = NSLock() + private var data = Data() + private var response: URLResponse? + private var failure: Error? + private var outcome: Result<(Data, URLResponse), Error>? + private var continuation: CheckedContinuation<(Data, URLResponse), Error>? + + init(limit: Int) { self.limit = limit } + + func start(_ continuation: CheckedContinuation<(Data, URLResponse), Error>) { + lock.lock() + if let outcome { lock.unlock(); continuation.resume(with: outcome); return } + self.continuation = continuation + lock.unlock() + } + + private func finish(_ result: Result<(Data, URLResponse), Error>) { + lock.lock() + guard outcome == nil else { lock.unlock(); return } + outcome = result + let waiting = continuation; continuation = nil + lock.unlock() + waiting?.resume(with: result) + } + + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + lock.lock(); self.response = response; lock.unlock() + completionHandler(nil) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + lock.lock() + self.response = response + let tooLong = response.expectedContentLength > Int64(limit) + if tooLong { failure = URLError(.dataLengthExceedsMaximum) } + lock.unlock() + completionHandler(tooLong ? .cancel : .allow) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) { + lock.lock() + guard failure == nil else { lock.unlock(); return } + if data.count + chunk.count > limit { + failure = URLError(.dataLengthExceedsMaximum) + lock.unlock() + dataTask.cancel() + return + } + data.append(chunk) + lock.unlock() + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + lock.lock() + let failure = failure, data = data, response = response ?? task.response + lock.unlock() + if let failure { return finish(.failure(failure)) } + if let error { + let cancelled = (error as? URLError)?.code == .cancelled + return finish(.failure(cancelled ? CancellationError() : error)) + } + guard let response else { return finish(.failure(URLError(.badServerResponse))) } + finish(.success((data, response))) + } + } +} diff --git a/Sources/NXLibraryCore/Services/BoxArtService.swift b/Sources/NXLibraryCore/Services/BoxArtService.swift index 938a1f4f..a4ec81a0 100644 --- a/Sources/NXLibraryCore/Services/BoxArtService.swift +++ b/Sources/NXLibraryCore/Services/BoxArtService.swift @@ -33,15 +33,17 @@ public actor BoxArtService { public func boxArt(titleID: String, names: [String]) async -> URL? { if let cached = artwork.cachedURL(titleID: titleID, kind: .boxart) { return cached } guard let entries = loadEntries() else { return nil } - // "tgdb": misses recorded before the TheGamesDB fallback are tried again. - let missKey = (["tgdb", titleID] + names.map(GameTDB.normalize)).joined(separator: "|") + let platform: CriticRatingQuery.Platform = titleID.hasPrefix("04") ? .switch2 : .switch + // Retry Switch 2 misses recorded when this fallback searched the original Switch catalog. + let resolver = platform == .switch2 ? "tgdb-switch2" : "tgdb" + let missKey = ([resolver, titleID] + names.map(GameTDB.normalize)).joined(separator: "|") if let missed = missTable()[missKey], now().timeIntervalSince(missed) < Self.missRetry { return nil } let match = names.lazy.compactMap { GameTDB.exactMatch(for: $0, in: entries) }.first for url in match.map({ GameTDB.coverURLs(id: $0.id) }) ?? [] { if let found = await artwork.fetch(titleID: titleID, remoteURL: url, kind: .boxart) { return found } } - let covers = await TheGamesDBArt.find(names: names, client: client).filter { $0.slot == .cover } + let covers = await TheGamesDBArt.find(names: names, platform: platform, client: client).filter { $0.slot == .cover } for candidate in covers { if let found = await artwork.fetch(titleID: titleID, remoteURL: candidate.url, kind: .boxart) { return found } } @@ -69,7 +71,7 @@ public actor BoxArtService { guard index.isStale(now: now()) else { return false } var request = URLRequest(url: GameTDB.databaseURL) request.timeoutInterval = 60 - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") guard let (data, http) = try? await client.data(for: request), (200..<300).contains(http.statusCode), let xml = try? unzip(data), let parsed = try? GameTDB.parse(xml), !parsed.isEmpty else { return false } try? index.save(parsed, at: now()) diff --git a/Sources/NXLibraryCore/Services/BuildCommandBuilder.swift b/Sources/NXLibraryCore/Services/BuildCommandBuilder.swift index c2d06726..284e8502 100644 --- a/Sources/NXLibraryCore/Services/BuildCommandBuilder.swift +++ b/Sources/NXLibraryCore/Services/BuildCommandBuilder.swift @@ -16,6 +16,7 @@ public enum BuildCommandBuilder { motion: Bool? = nil, romfsMode: String? = nil, titleId: String? = nil, + programIndex: Int? = nil, packageVersion: String? = nil, allowUntestedToolchain: Bool = false, extraArguments: [String] = [] @@ -30,6 +31,7 @@ public enum BuildCommandBuilder { ] if let keys { args += ["-k", keys.path] } if let titleId { args += ["--title-id", titleId] } + if let programIndex { args += ["--program", String(programIndex)] } if let packageVersion { args += ["-p", packageVersion] } if let appName, !appName.isEmpty { args += ["--app-name", appName] } if let bundleId, !bundleId.isEmpty { args += ["--bundle-id", bundleId] } diff --git a/Sources/NXLibraryCore/Services/BuildService.swift b/Sources/NXLibraryCore/Services/BuildService.swift index 74c71c2d..69ad8c48 100644 --- a/Sources/NXLibraryCore/Services/BuildService.swift +++ b/Sources/NXLibraryCore/Services/BuildService.swift @@ -97,7 +97,7 @@ public final class BuildService { if IOPMAssertionCreateWithName( kIOPMAssertionTypeNoIdleSleep as CFString, IOPMAssertionLevel(kIOPMAssertionLevelOn), - "NX Library build" as CFString, + "Arcane build" as CFString, &assertion ) == kIOReturnSuccess { sleepAssertion = assertion @@ -147,6 +147,14 @@ public final class BuildService { do { try process.run() } catch { + // Nothing will reach EOF or the termination handler: close the log and both pipes here. + for pipe in [out, err] { + pipe.fileHandleForReading.readabilityHandler = nil + try? pipe.fileHandleForReading.close() + try? pipe.fileHandleForWriting.close() + } + logHandle?.closeFile() + logHandle = nil releaseAssertion() stateLock.lock() let done = self.completion diff --git a/Sources/NXLibraryCore/Services/Catalog/CatalogErrorCopy.swift b/Sources/NXLibraryCore/Services/Catalog/CatalogErrorCopy.swift new file mode 100644 index 00000000..46671640 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Catalog/CatalogErrorCopy.swift @@ -0,0 +1,43 @@ +import Foundation + +extension CatalogScanError: LocalizedError { + public var errorDescription: String? { + switch self { + case .sourceDisabled: return L10n.text("This source is disabled. Enable it in Game sources.") + case .staleScan: return L10n.text("The source changed during the scan. Refresh it again.") + case .wrongSourceRoot: return L10n.text("The Steam library changed while it was being checked. Refresh it again.") + case .invalidSnapshot: return L10n.text("Steam installation data could not be verified. Your library has been kept.") + } + } +} + +extension CatalogStoreError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidLegacy: return L10n.text("Your previous library could not be read. The original files have been kept.") + case .invalidCatalog(let available): + return available + ? L10n.text("Your library could not be read. Restore its backup or open the library folder to review the files.") + : L10n.text("Your library could not be read. Its files have been kept. Open the library folder, then try again.") + case .legacyChanged: return L10n.text("Another version changed your previous library. Both versions have been kept. Close the other copy and review the library folder.") + case .staleRevision: return L10n.text("The library changed. Reload it and try again.") + case .busy: return L10n.text("The library is busy. Try again shortly.") + case .unsafeDirectory: return L10n.text("The library folder could not be used safely. Its files have been kept.") + case .commitUncertain: return L10n.text("The latest save could not be confirmed. Reload the library before trying again.") + } + } +} + +extension CatalogRepositoryError: LocalizedError { + public var errorDescription: String? { L10n.text("That game is no longer in the library. Refresh it and try again.") } +} + +extension CatalogModelError: LocalizedError { + public var errorDescription: String? { + switch self { + case .wrongIntegration: return L10n.text("This action is not available for this game.") + case .identityMismatch: return L10n.text("The library changed. Reload it and try again.") + default: return L10n.text("The library contains conflicting or unsupported records. Its files have been kept.") + } + } +} diff --git a/Sources/NXLibraryCore/Services/Catalog/CatalogPublication.swift b/Sources/NXLibraryCore/Services/Catalog/CatalogPublication.swift new file mode 100644 index 00000000..55bae74b --- /dev/null +++ b/Sources/NXLibraryCore/Services/Catalog/CatalogPublication.swift @@ -0,0 +1,46 @@ +import Foundation +import Darwin + +/// Only the commit boundary is replaceable; staging, decoding, locking and +/// source/revision checks remain real in failure and concurrency tests. +struct CatalogPublication { + let publish: (_ staged: URL, _ destination: URL, _ replacing: Bool, _ validate: () throws -> Void) throws -> Void + + let syncDirectory: (URL) throws -> Void + + init(syncDirectory: @escaping (URL) throws -> Void = Self.synchronize, + publish: @escaping (URL, URL, Bool, () throws -> Void) throws -> Void) { + self.syncDirectory = syncDirectory + self.publish = publish + } + + private static func synchronize(_ directory: URL) throws { + let fd = open(directory.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + defer { close(fd) } + guard fsync(fd) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + } + + static let atomic = Self { staged, destination, replacing, validate in + try validate() + let result = replacing ? rename(staged.path, destination.path) : link(staged.path, destination.path) + guard result == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + } + + static func stage(_ data: Data, in directory: URL) throws -> URL { + let url = directory.appendingPathComponent(".catalog-stage-" + UUID().uuidString) + let fd = open(url.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + do { + try handle.write(contentsOf: data) + guard fsync(fd) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + try handle.close() + return url + } catch { + try? handle.close() + try? FileManager.default.removeItem(at: url) + throw error + } + } +} diff --git a/Sources/NXLibraryCore/Services/Catalog/CatalogRepository.swift b/Sources/NXLibraryCore/Services/Catalog/CatalogRepository.swift new file mode 100644 index 00000000..c215afd8 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Catalog/CatalogRepository.swift @@ -0,0 +1,155 @@ +import Foundation + +public enum CatalogRepositoryError: Error, Equatable { case gameNotFound } + +extension CatalogDocument { + /// A projection for the still-nxnative screens, never another writable store. + public var nxnativeGames: [PortedGame] { games.compactMap(\.nxnativeGame) } +} + +/// Typed transactions against one authoritative catalog. No cached second +/// document and no automatic replay of closures with game-file side effects. +public struct CatalogRepository { + private let store: CatalogStore + public init(store: CatalogStore) { self.store = store } + public func load() throws -> CatalogDocument { try store.loadOrMigrate() } + + @discardableResult + public func updateNXNative(id: UUID, _ change: (inout PortedGame) throws -> Void) throws -> CatalogDocument { + try transaction { document in + guard let index = document.games.firstIndex(where: { $0.id == id }) else { throw CatalogRepositoryError.gameNotFound } + guard var game = document.games[index].nxnativeGame else { throw CatalogModelError.wrongIntegration } + try change(&game) + try document.games[index].updateNXNative(game) + } + } + + @discardableResult + public func updateNXNativeGames(_ change: (inout [PortedGame]) throws -> Void) throws -> CatalogDocument { + try mutateNXNativeGames(enablingSource: false, requiringEnabledSource: false, change) + } + + private func mutateNXNativeGames(enablingSource: Bool, requiringEnabledSource: Bool, + _ change: (inout [PortedGame]) throws -> Void) throws -> CatalogDocument { + try transaction { document in + if requiringEnabledSource && !enablingSource && document.source(.nxnative)?.isEnabled != true { throw CatalogScanError.sourceDisabled } + var games = document.nxnativeGames + try change(&games) + guard Set(games.map(\.id)).count == games.count else { throw CatalogModelError.duplicateGameID } + var updates = Dictionary(uniqueKeysWithValues: games.map { ($0.id, $0) }) + document.games = try document.games.compactMap { record in + guard record.integration == .nxnative else { return record } + guard let updated = updates.removeValue(forKey: record.id) else { return nil } + var result = record + try result.updateNXNative(updated) + return result + } + for game in games where updates[game.id] != nil { document.games.append(.init(nxnative: game)) } + if enablingSource { + var config = document.source(.nxnative) ?? .init(integration: .nxnative) + if !config.isEnabled { config.generation = UUID() } + config.isEnabled = true + if let index = document.sources.firstIndex(where: { $0.integration == .nxnative }) { document.sources[index] = config } + else { document.sources.append(config) } + } + } + } + + @discardableResult + public func mergeNXNative(scanned: [PortedGame], replacingSources: Bool = false, enableSource: Bool = false, + observedFrom baseline: [PortedGame]? = nil, + reconcile: (inout [PortedGame], Set<UUID>) throws -> Void = { _, _ in }) throws -> CatalogDocument { + try mutateNXNativeGames(enablingSource: enableSource, requiringEnabledSource: true) { games in + let baselineByID = baseline.map { Dictionary($0.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) } + let protected = Set(games.filter { current in + if current.status == .building { return true } + guard let baselineByID else { return false } + guard let earlier = baselineByID[current.id] else { return true } + return !Self.sameObservationGeneration(earlier, current) + }.map(\.id)) + let accepted = scanned.filter { observation in + let current = games.first { candidate in + candidate.id == observation.id || (observation.titleId.map { + candidate.titleId?.caseInsensitiveCompare($0) == .orderedSame + } ?? false) + } + return current.map { !protected.contains($0.id) } ?? true + } + games = NXNativeLibraryMerge.merge(scanned: accepted, into: games, replacingSources: replacingSources) + try reconcile(&games, Set(games.map(\.id)).subtracting(protected)) + } + } + + private static func sameObservationGeneration(_ earlier: PortedGame, _ current: PortedGame) -> Bool { + earlier.url == current.url && earlier.status == current.status && earlier.modificationDate == current.modificationDate + && earlier.lastBuild == current.lastBuild && earlier.pendingInstall == current.pendingInstall + && earlier.toolchain == current.toolchain && earlier.sources == current.sources + && earlier.workspacePath == current.workspacePath && earlier.buildCachePath == current.buildCachePath + && earlier.appIconPending == current.appIconPending + } + + private func transaction(_ change: (inout CatalogDocument) throws -> Void) throws -> CatalogDocument { + let current = try load() + var draft = current + try change(&draft) + return try store.save(draft, expectedRevision: current.revision) + } +} + +extension CatalogRepository { + /// Apply only fields owned by the finished build. In-flight personal/runtime + /// changes must not be replaced by the build's earlier payload snapshot. + @discardableResult + public func recordNXNativeBuild(_ outcome: PortedGame) throws -> CatalogDocument { + try updateNXNative(id: outcome.id) { game in + try game.applyCatalogBuildOutcome(outcome) + } + } +} + + +extension CatalogRepository { + @discardableResult + public func configureSource(_ integration: CatalogIntegration, enabled: Bool, root: URL?) throws -> CatalogDocument { + try transaction { document in + var config = document.source(integration) ?? .init(integration: integration) + let nextRoot = root.map { $0.resolvingSymlinksInPath().standardizedFileURL } ?? config.rootURL + if config.isEnabled != enabled || config.rootURL != nextRoot { config.generation = UUID() } + config.isEnabled = enabled; config.rootURL = nextRoot + if let index = document.sources.firstIndex(where: { $0.integration == integration }) { document.sources[index] = config } + else { document.sources.append(config) } + } + } + + @discardableResult + public func toggleFavorite(for id: UUID) throws -> CatalogDocument { + try transaction { document in + guard let index = document.games.firstIndex(where: { $0.id == id }) else { throw CatalogRepositoryError.gameNotFound } + document.games[index].setFavorite(!document.games[index].isFavorite) + } + } + + @discardableResult + public func setFavorite(_ value: Bool, for id: UUID) throws -> CatalogDocument { + try transaction { document in + guard let index = document.games.firstIndex(where: { $0.id == id }) else { throw CatalogRepositoryError.gameNotFound } + document.games[index].setFavorite(value) + } + } + @discardableResult + public func setHidden(_ value: Bool, for id: UUID) throws -> CatalogDocument { + try transaction { document in + guard let index = document.games.firstIndex(where: { $0.id == id }) else { throw CatalogRepositoryError.gameNotFound } + document.games[index].setHidden(value) + } + } + + @discardableResult + public func applySteam(_ snapshot: SteamLibrarySnapshot, expectedSource: CatalogSourceConfiguration) throws -> CatalogDocument { + let current = try load() + guard expectedSource.integration == .steam, expectedSource.isEnabled, + current.source(.steam) == expectedSource else { throw CatalogScanError.staleScan } + let draft = try SteamCatalogReconciler.applying(snapshot, ticket: current.steamScanTicket(), to: current) + return try store.save(draft, expectedRevision: current.revision) + } +} diff --git a/Sources/NXLibraryCore/Services/Catalog/CatalogSourcesModel.swift b/Sources/NXLibraryCore/Services/Catalog/CatalogSourcesModel.swift new file mode 100644 index 00000000..3d15e88f --- /dev/null +++ b/Sources/NXLibraryCore/Services/Catalog/CatalogSourcesModel.swift @@ -0,0 +1,159 @@ +import Foundation +import Combine + +public enum CatalogSourceStatus: Equatable, Sendable { case disabled, idle, scanning, ready, partial, cancelled, failed } + +/// Source UI state and a cancellable reader. CatalogRepository alone owns the +/// persisted source configuration and game records; no competing catalog cache. +@MainActor +public final class CatalogSourcesModel: ObservableObject { + /// Steam's own folder, where the first launch and Settings → Sources look first. + public static var defaultSteamRoot: URL { AppData.profile.home.appendingPathComponent("Library/Application Support/Steam") } + /// Discovery and its eventual opt-in must use the same folder, including a disabled source's choice. + public var discoveryRoot: URL { configuration.rootURL ?? Self.defaultSteamRoot } + public typealias Scanner = @Sendable (URL, @escaping () -> Bool) throws -> SteamLibrarySnapshot + @Published public private(set) var configuration: CatalogSourceConfiguration + @Published public private(set) var status: CatalogSourceStatus + @Published public private(set) var observedGameCount = 0 + @Published public private(set) var reviewCount = 0 + @Published public private(set) var issues: [SteamScanIssue] = [] + @Published public private(set) var errorMessage: String? + /// The libraries the last committed scan read (the source's root first): what `SteamManifestWatcher` watches. + /// Empty while the source is disabled or before its first scan. + @Published public private(set) var libraryRoots: [URL] = [] + private let repository: CatalogRepository + private let scanner: Scanner + private let onCommit: (CatalogDocument) -> Void + private var requestID = UUID() + private var task: Task<Void, Never>? + /// Rescans asked for by Steam's files changing: after `rescanQuiet` without changes, at most once every + /// `rescanSpacing`, never over a running scan (one follows it instead). + private let rescanQuiet: TimeInterval + private let rescanSpacing: TimeInterval + private var rescanTimer: Task<Void, Never>? + private var rescanAfterScan = false + private var lastScanStart: Date? + + public init(repository: CatalogRepository, initialConfiguration: CatalogSourceConfiguration, + scanner: @escaping Scanner = { root, cancelled in try SteamLibrarySource(root: root).scan(cancelled: cancelled) }, + rescanQuiet: TimeInterval = 3, rescanSpacing: TimeInterval = 15, + onCommit: @escaping (CatalogDocument) -> Void) { + self.repository = repository; configuration = initialConfiguration + self.scanner = scanner; self.onCommit = onCommit + self.rescanQuiet = rescanQuiet; self.rescanSpacing = rescanSpacing + status = initialConfiguration.isEnabled ? .idle : .disabled + } + public func startIfEnabled() { if configuration.isEnabled && status == .idle { refresh() } } + public func configure(enabled: Bool, root: URL?) { + invalidate() + dropRescan() + libraryRoots = [] + do { + let document = try repository.configureSource(.steam, enabled: enabled, root: root) + configuration = document.source(.steam)! + errorMessage = nil; issues = []; observedGameCount = 0; reviewCount = 0 + status = enabled ? .idle : .disabled + onCommit(document) + if enabled { refresh() } + } catch { failed(error) } + } + public func cancel() { + invalidate() + dropRescan() + status = configuration.isEnabled ? .cancelled : .disabled + } + public func refresh() { + invalidate() + let expected: CatalogSourceConfiguration + do { + let current = try repository.load() + guard let source = current.source(.steam), source.isEnabled, let _ = source.rootURL else { + configuration = current.source(.steam) ?? .init(integration: .steam) + status = .disabled + onCommit(current) + return + } + expected = source; configuration = source + } catch { failed(error); return } + let id = requestID + lastScanStart = Date() + status = .scanning; errorMessage = nil + let scan = scanner, root = expected.rootURL! + let worker = Task.detached(priority: .userInitiated) { + try scan(root) { Task.isCancelled } + } + task = Task { [weak self] in + do { + let snapshot = try await withTaskCancellationHandler(operation: { try await worker.value }, onCancel: { worker.cancel() }) + try Task.checkCancellation() + guard let self, self.requestID == id else { return } + let document = try self.repository.applySteam(snapshot, expectedSource: expected) + self.configuration = document.source(.steam)! + self.observedGameCount = Set(snapshot.games.map(\.appID)).count + let seen = Set(snapshot.games.map(\.appID)) + self.reviewCount = document.games.compactMap(\.steamGame).filter { + seen.contains($0.appID) && $0.needsReview + }.count + self.issues = snapshot.issues + // The paths may be unchanged while a previously missing volume has become available. + self.libraryRoots = snapshot.libraries.map(\.root) + self.status = snapshot.isComplete ? .ready : .partial + self.task = nil + self.onCommit(document) + self.scanEnded() + } catch { + guard let self, self.requestID == id else { return } + self.task = nil + if error is CancellationError { self.status = .cancelled } + else { self.failed(error) } + self.scanEnded() + } + } + } + /// Steam rewrote a manifest or the library index: rescan once things are quiet. + public func steamFilesChanged() { + guard configuration.isEnabled else { return } + armRescan(after: rescanQuiet) + } + + private func armRescan(after delay: TimeInterval) { + rescanTimer?.cancel() + rescanTimer = Task { [weak self] in + try? await Task.sleep(nanoseconds: UInt64(max(delay, 0) * 1_000_000_000)) + guard !Task.isCancelled else { return } + self?.rescanDue() + } + } + + private func rescanDue() { + rescanTimer = nil + guard configuration.isEnabled else { return } + if status == .scanning { rescanAfterScan = true; return } + let wait = lastScanStart.map { rescanSpacing - Date().timeIntervalSince($0) } ?? 0 + if wait > 0 { armRescan(after: wait) } else { refresh() } + } + + private func scanEnded() { + guard rescanAfterScan else { return } + rescanAfterScan = false + rescanDue() + } + + private func dropRescan() { + rescanTimer?.cancel(); rescanTimer = nil + rescanAfterScan = false + } + + private func invalidate() { + requestID = UUID(); task?.cancel(); task = nil + } + private func failed(_ error: Error) { + // Publication uncertainty/stale config may have committed a newer + // source. Read it, if possible, before presenting a recoverable error. + if let actual = try? repository.load() { + configuration = actual.source(.steam) ?? .init(integration: .steam) + onCommit(actual) + } + errorMessage = error.localizedDescription; status = .failed + } +} diff --git a/Sources/NXLibraryCore/Services/Catalog/CatalogStore.swift b/Sources/NXLibraryCore/Services/Catalog/CatalogStore.swift new file mode 100644 index 00000000..7b1b1e19 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Catalog/CatalogStore.swift @@ -0,0 +1,287 @@ +import Foundation +import CryptoKit +import Darwin + +public enum CatalogStoreError: Error, Equatable { + case invalidLegacy, invalidCatalog(backupAvailable: Bool), legacyChanged, staleRevision, busy, unsafeDirectory + /// Main may already contain the new revision. Reload before deciding whether to retry. + case commitUncertain +} + +/// Versioned persistence for the generalization branch. CatalogRepository owns +/// all app game-record mutations; legacy files remain recovery inputs. +public struct CatalogStore { + public let directory: URL + private let publication: CatalogPublication + private static let maximumBytes = 16 * 1024 * 1024 + + public init(directory: URL) { self.init(directory: directory, publication: .atomic) } + init(directory: URL, publication: CatalogPublication) { + self.directory = directory.standardizedFileURL + self.publication = publication + } + private func file(_ name: String) -> URL { directory.appendingPathComponent(name) } + + static func decode(_ data: Data) throws -> CatalogDocument { + // Deferred-to-Date keeps the exact Date value; the legacy decoder below + // alone uses ISO8601. This is part of catalog schema 1. + let document = try JSONDecoder().decode(CatalogDocument.self, from: data) + try document.validate() + return document + } + private static func encode(_ document: CatalogDocument) throws -> Data { + try document.validate() + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .prettyPrinted] + let data = try encoder.encode(document) + guard data.count <= maximumBytes else { throw InstallationFileReadError.tooLarge } + guard try decode(data) == document else { throw CatalogModelError.invalidRecord } + return data + } + + public func loadOrMigrate() throws -> CatalogDocument { + try locked { + let current = try currentCatalog() + if let document = current.document { + try verifyLegacy(document.legacyOrigin) + return document + } + let (document, observations) = try convertedLegacy() + let data = try Self.encode(document) + try commit(data, previous: nil, current: current.state) { + for observation in observations { try observation.verifyUnchanged() } + try self.verifyLegacy(document.legacyOrigin) + } + return document + } + } + + public func save(_ draft: CatalogDocument, expectedRevision: UUID) throws -> CatalogDocument { + try locked { + let current = try currentCatalog() + guard let old = current.document, old.revision == expectedRevision, draft.revision == expectedRevision, + old.legacyOrigin == draft.legacyOrigin else { throw CatalogStoreError.staleRevision } + try verifyLegacy(old.legacyOrigin) + var committed = draft + committed.revision = UUID() + let data = try Self.encode(committed) + try commit(data, previous: current.state.data, current: current.state) { try self.verifyLegacy(old.legacyOrigin) } + return committed + } + } + + private struct FileState { + let data: Data? + let observation: InstallationFileObservation + func verify() throws { try observation.verifyUnchanged() } + } + private func read(_ name: String) throws -> FileState { + let target = file(name) + do { + let snapshot = try InstallationFileSnapshot.read(at: target, maximumBytes: Self.maximumBytes) + return FileState(data: snapshot.data, observation: snapshot.observation) + } catch let error as POSIXError where error.code == .ENOENT { + return FileState(data: nil, observation: try .absent(at: target)) + } + } + + private func currentCatalog() throws -> (document: CatalogDocument?, state: FileState) { + let backup = try? read("catalog.json.bak") + let backupAvailable = backup?.data.flatMap { try? Self.decode($0) } != nil + do { + let main = try read("catalog.json") + if let data = main.data { return (try Self.decode(data), main) } + // An existing backup, valid or damaged, is evidence of an older + // catalog. Never interpret a missing main as a fresh profile. + guard backup?.data == nil else { throw CatalogStoreError.invalidCatalog(backupAvailable: backupAvailable) } + // Unsafe/unreadable backups also require explicit recovery. + if backup == nil { throw CatalogStoreError.invalidCatalog(backupAvailable: false) } + return (nil, main) + } catch { throw CatalogStoreError.invalidCatalog(backupAvailable: backupAvailable) } + } + + private static func digest(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + private func convertedLegacy() throws -> (CatalogDocument, [InstallationFileObservation]) { + do { + let main = try read("library.json") + let selected: FileState, origin: CatalogLegacyOrigin + if let data = main.data { + selected = main; origin = .init(kind: .primary, sha256: Self.digest(data)) + } else { + let backup = try read("library.json.bak") + guard let bytes = backup.data else { + return (CatalogDocument(), [main.observation, backup.observation]) + } + selected = backup; origin = .init(kind: .backup, sha256: Self.digest(bytes)) + } + let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601 + let legacy = try decoder.decode(LibraryFile.self, from: selected.data!) + return (try CatalogDocument.converting(legacy, origin: origin), [main.observation, selected.observation]) + } catch { throw CatalogStoreError.invalidLegacy } + } + + private func verifyLegacy(_ origin: CatalogLegacyOrigin) throws { + do { + let main = try read("library.json") + switch origin.kind { + case .primary: + guard let data = main.data, Self.digest(data) == origin.sha256 else { throw CatalogStoreError.legacyChanged } + case .backup: + guard main.data == nil, let backup = try read("library.json.bak").data, + Self.digest(backup) == origin.sha256 else { throw CatalogStoreError.legacyChanged } + case .absent: + guard main.data == nil, try read("library.json.bak").data == nil else { throw CatalogStoreError.legacyChanged } + } + } catch { throw CatalogStoreError.legacyChanged } + } + + private func commit(_ data: Data, previous: Data?, current: FileState, + restorePoint: Data? = nil, expectedBackup: FileState? = nil, + validate: () throws -> Void) throws { + let candidate = try CatalogPublication.stage(data, in: directory) + defer { try? FileManager.default.removeItem(at: candidate) } + // Re-read the actual staged bytes, not just the in-memory draft. + _ = try Self.decode(InstallationFileSnapshot.read(at: candidate, maximumBytes: Self.maximumBytes).data) + try current.verify(); try validate() + let backup = try read("catalog.json.bak") + try expectedBackup?.verify() + let backupStage = try CatalogPublication.stage(restorePoint ?? previous ?? data, in: directory) + defer { try? FileManager.default.removeItem(at: backupStage) } + // A valid old main is the new restore point. Initial create also has a + // restore point before the main is exposed. Explicit acknowledgement uses + // the accepted baseline for both copies; its old restore point is archived. + try CatalogPublication.atomic.publish(backupStage, file("catalog.json.bak"), backup.data != nil) { + try expectedBackup?.verify() + try backup.verify(); try current.verify(); try validate() + } + try publication.publish(candidate, file("catalog.json"), previous != nil) { + try current.verify(); try validate() + } + // Persist directory entries after both renames/links. File data was + // fsynced before publication; a valid restore point precedes the main. + do { try publication.syncDirectory(directory) } + catch { throw CatalogStoreError.commitUncertain } + } + + private func locked<T>(_ operation: () throws -> T) throws -> T { + guard directory.isFileURL else { throw CatalogStoreError.unsafeDirectory } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + var status = stat() + guard lstat(directory.path, &status) == 0, status.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) else { + throw CatalogStoreError.unsafeDirectory + } + let fd = open(file(".catalog.lock").path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, 0o600) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + defer { close(fd) } + _ = try InstallationFileObservation.capture(fileDescriptor: fd, url: file(".catalog.lock")) + guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { throw CatalogStoreError.busy } + defer { _ = flock(fd, LOCK_UN) } + return try operation() + } +} + +extension CatalogStore { + private static let conflictNames = ["catalog.json", "catalog.json.bak", "library.json", "library.json.bak"] + + private func legacyBaseline(_ states: [FileState]) -> CatalogLegacyOrigin { + if let data = states[2].data { return .init(kind: .primary, sha256: Self.digest(data)) } + if let data = states[3].data { return .init(kind: .backup, sha256: Self.digest(data)) } + return .absent + } + + /// A valid catalog with a changed legacy baseline needs a different choice + /// from restoring a damaged catalog. Reading this offer does not modify inputs. + public func legacyConflictCandidate() throws -> CatalogLegacyConflictCandidate? { + try locked { + let states = try Self.conflictNames.map(read) + guard let bytes = states[0].data else { return nil } + let document = try Self.decode(bytes) + guard legacyBaseline(states) != document.legacyOrigin else { return nil } + return .init(directory: directory, digests: states.map { $0.data.map(Self.digest) }) + } + } + + /// Keeps catalog records and archives every input before acknowledging the + /// legacy bytes. A later legacy edit still blocks load/save in the usual way. + public func keepCurrentLibrary(_ candidate: CatalogLegacyConflictCandidate) throws -> CatalogDocument { + try locked { + guard candidate.directory == directory else { throw CatalogStoreError.staleRevision } + let states = try Self.conflictNames.map(read) + guard states.map({ $0.data.map(Self.digest) }) == candidate.digests, + let bytes = states[0].data else { throw CatalogStoreError.staleRevision } + let document = try Self.decode(bytes) + let origin = legacyBaseline(states) + guard origin != document.legacyOrigin else { throw CatalogStoreError.staleRevision } + let kept = CatalogDocument(schemaVersion: document.schemaVersion, legacyOrigin: origin, + sources: document.sources, games: document.games) + let data = try Self.encode(kept) + func validateAll() throws { for state in states { try state.verify() } } + try validateAll() + + var template = Array(file("catalog-conflict-XXXXXX").path.utf8CString) + let archive = try template.withUnsafeMutableBufferPointer { buffer -> URL in + guard let path = mkdtemp(buffer.baseAddress!) else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + return URL(fileURLWithPath: String(cString: path), isDirectory: true) + } + // Archives, even partial ones after an error, are deliberately kept. + for (name, state) in zip(Self.conflictNames, states) { + guard let bytes = state.data else { continue } + let staged = try CatalogPublication.stage(bytes, in: archive) + defer { try? FileManager.default.removeItem(at: staged) } + try publication.publish(staged, archive.appendingPathComponent(name), false, validateAll) + } + try publication.syncDirectory(archive) + try publication.syncDirectory(directory) + try validateAll() + try commit(data, previous: bytes, current: states[0], restorePoint: data, expectedBackup: states[1]) { + try states[2].verify(); try states[3].verify() + } + return kept + } + } + + /// Read-only validation used on an import stage, before making it visible. + func validateImportedOrigin(_ document: CatalogDocument) throws { try verifyLegacy(document.legacyOrigin) } + + public func recoveryCandidate() throws -> CatalogRecoveryCandidate? { + try locked { + let main = try read("catalog.json") + if let bytes = main.data, (try? Self.decode(bytes)) != nil { return nil } + let backup = try read("catalog.json.bak") + guard let bytes = backup.data else { return nil } + let document = try Self.decode(bytes) + try verifyLegacy(document.legacyOrigin) + return .init(gameCount: document.games.count, directory: directory, + primaryDigest: main.data.map(Self.digest), backupDigest: Self.digest(bytes)) + } + } + + public func restoreBackup(_ candidate: CatalogRecoveryCandidate) throws -> CatalogDocument { + try locked { + guard candidate.directory == directory else { throw CatalogStoreError.staleRevision } + let main = try read("catalog.json"), backup = try read("catalog.json.bak") + guard main.data.map(Self.digest) == candidate.primaryDigest, + let bytes = backup.data, Self.digest(bytes) == candidate.backupDigest else { throw CatalogStoreError.staleRevision } + var restored = try Self.decode(bytes) + try verifyLegacy(restored.legacyOrigin) + restored.revision = UUID() // A restore never revives an old writer's revision. + let staged = try CatalogPublication.stage(Self.encode(restored), in: directory) + defer { try? FileManager.default.removeItem(at: staged) } + _ = try Self.decode(InstallationFileSnapshot.read(at: staged, maximumBytes: Self.maximumBytes).data) + func validate() throws { + try main.verify(); try backup.verify(); try verifyLegacy(restored.legacyOrigin) + } + try validate() + if let damaged = main.data { + let kept = try CatalogPublication.stage(damaged, in: directory) + defer { try? FileManager.default.removeItem(at: kept) } + let archive = file("catalog.json.recovered-" + UUID().uuidString + ".json") + try CatalogPublication.atomic.publish(kept, archive, false, validate) + } + try publication.publish(staged, file("catalog.json"), main.data != nil, validate) + do { try publication.syncDirectory(directory) } + catch { throw CatalogStoreError.commitUncertain } + return restored + } + } +} diff --git a/Sources/NXLibraryCore/Services/Catalog/SteamCatalogReconciler.swift b/Sources/NXLibraryCore/Services/Catalog/SteamCatalogReconciler.swift new file mode 100644 index 00000000..91f625ae --- /dev/null +++ b/Sources/NXLibraryCore/Services/Catalog/SteamCatalogReconciler.swift @@ -0,0 +1,108 @@ +import Foundation + +public enum CatalogScanError: Error, Equatable { case sourceDisabled, staleScan, wrongSourceRoot, invalidSnapshot } + +public struct CatalogScanTicket: Equatable, Sendable { + public let revision: UUID + public let rootURL: URL + let configuredRootURL: URL +} + +extension CatalogDocument { + /// Capture this after committing source configuration, before starting I/O. + public func steamScanTicket() throws -> CatalogScanTicket { + try validate() + guard let config = source(.steam), config.isEnabled, let root = config.rootURL else { throw CatalogScanError.sourceDisabled } + return .init(revision: revision, rootURL: root.resolvingSymlinksInPath().standardizedFileURL, + configuredRootURL: root.standardizedFileURL) + } +} + +/// Pure reconciliation: no scans, game launches, settings writes or disk probes. +/// The caller commits the returned draft through CatalogStore's revision check. +public enum SteamCatalogReconciler { + private struct InstallationKey: Hashable { + let library: URL + let content: URL + init(_ library: URL, _ content: URL) { + self.library = library.standardizedFileURL; self.content = content.standardizedFileURL + } + } + + public static func applying(_ snapshot: SteamLibrarySnapshot, ticket: CatalogScanTicket, to document: CatalogDocument, + observedAt: Date = Date()) throws -> CatalogDocument { + try document.validate() + guard let source = document.source(.steam), source.isEnabled, let root = source.rootURL else { throw CatalogScanError.sourceDisabled } + guard document.revision == ticket.revision, root.standardizedFileURL == ticket.configuredRootURL else { throw CatalogScanError.staleScan } + let libraries = snapshot.libraries.map { $0.root.standardizedFileURL } + guard libraries.contains(ticket.rootURL) else { throw CatalogScanError.wrongSourceRoot } + guard Set(libraries).count == libraries.count, libraries.allSatisfy(\.isFileURL) else { throw CatalogScanError.invalidSnapshot } + let unreadable = Set(snapshot.libraries.filter { !$0.isReadable }.map { $0.root.standardizedFileURL }) + let grouped = Dictionary(grouping: snapshot.games, by: \.appID) + for observation in snapshot.games { + guard observation.appID > 0, libraries.contains(observation.libraryURL.standardizedFileURL), + !unreadable.contains(observation.libraryURL.standardizedFileURL) else { throw CatalogScanError.invalidSnapshot } + } + var result = document + var indices = Dictionary(uniqueKeysWithValues: result.games.enumerated().compactMap { index, record in + record.steamGame.map { ($0.appID, index) } + }) + let seenByAppID = grouped.mapValues { Set($0.map { InstallationKey($0.libraryURL, $0.installationURL) }) } + // Absence is meaningful only for a complete source. A source error can + // report unavailability, but can never erase an entry or its identity. + for index in result.games.indices { + guard var game = result.games[index].steamGame else { continue } + if game.installations.contains(where: { $0.availability == .requiresReview }) + || game.installations.filter({ $0.availability == .available }).count > 1 { + game.needsInstallationReview = true + } + if snapshot.isComplete && grouped[game.appID] == nil { game.needsInstallationReview = false } + for i in game.installations.indices { + let installation = game.installations[i] + let key = InstallationKey(installation.libraryURL, installation.contentURL) + if seenByAppID[game.appID]?.contains(key) != true { + if unreadable.contains(key.library) { game.installations[i].availability = .sourceUnavailable } + else if snapshot.isComplete { game.installations[i].availability = .notDetected } + } + } + try result.games[index].updateSteam(game) + } + for appID in grouped.keys.sorted() { + let observations = grouped[appID]!.sorted { + ($0.libraryURL.path, $0.installationURL.path) < ($1.libraryURL.path, $1.installationURL.path) + } + guard Set(observations.map { InstallationKey($0.libraryURL, $0.installationURL) }).count == observations.count else { + throw CatalogScanError.invalidSnapshot + } + let index = indices[appID] + var game = index.flatMap { result.games[$0].steamGame } ?? SteamCatalogGame(appID: appID, name: observations[0].name) + game.name = observations[0].name + var installs = Dictionary(uniqueKeysWithValues: game.installations.enumerated().map { + (InstallationKey($0.element.libraryURL, $0.element.contentURL), $0.offset) + }) + var observedAmbiguity = false + for observed in observations { + let key = InstallationKey(observed.libraryURL, observed.installationURL) + let apps = observed.nativeApps.map(CatalogNativeApplication.init) + let ready = observed.state == .nativeReady && apps.filter(\.isDeclaredGame).count == 1 + let availability: CatalogInstallationAvailability = observations.count > 1 ? .requiresReview + : (ready ? .available : ([.unavailable, .downloading].contains(observed.state) ? .unavailable : .requiresReview)) + if availability == .requiresReview { observedAmbiguity = true } + if ready && observations.count == 1 { game.hasBeenRecognized = true } + let installIndex = installs[key] + let installation = SteamCatalogInstallation(id: installIndex.map { game.installations[$0].id } ?? UUID(), + libraryURL: key.library, contentURL: key.content, applications: apps, availability: availability, + reportedSizeBytes: observed.reportedSizeBytes, buildID: observed.buildID, lastObservedAt: observedAt, + isDownloading: observations.count == 1 && observed.state == .downloading) + if let installIndex { game.installations[installIndex] = installation } + else { installs[key] = game.installations.count; game.installations.append(installation) } + } + if observedAmbiguity { game.needsInstallationReview = true } + else if snapshot.isComplete { game.needsInstallationReview = false } + if let index { try result.games[index].updateSteam(game) } + else { indices[appID] = result.games.count; result.games.append(.init(steam: game)) } + } + try result.validate() + return result + } +} diff --git a/Sources/NXLibraryCore/Services/CriticRatingService.swift b/Sources/NXLibraryCore/Services/CriticRatingService.swift new file mode 100644 index 00000000..de70b1b3 --- /dev/null +++ b/Sources/NXLibraryCore/Services/CriticRatingService.swift @@ -0,0 +1,159 @@ +import Foundation +import CryptoKit + +/// Keyless, on-demand enrichment for Details. Cache and failures never alter the catalog. +public actor CriticRatingService { + public typealias Transport = @Sendable (URL) async throws -> Data + public static let shared = CriticRatingService() + private let directory: URL + private let transport: Transport + private struct Cache: Codable { + let query: CriticRatingQuery + let rating: CriticRating? + let fetchedAt: Date + let resolverVersion: Int? + } + private struct Flight { + let id: UUID + let task: Task<CriticRatingResult, Never> + var waiters: Set<UUID> + } + private var pending: [CriticRatingQuery: Flight] = [:] + private var requestTail: Task<Void, Never>? + private var backoffUntil = Date.distantPast + + public init(directory: URL = AppData.supportRoot.appendingPathComponent("ratings/wikidata"), + transport: @escaping Transport = { try await CriticRatingService.download($0) }) { + self.directory = directory + self.transport = transport + } + /// IGDB critics, public critics, then explicitly identified IGDB community scores. + public func preferred(_ query: CriticRatingQuery, credentials: IGDBCredentials?, + igdb: IGDBRatingService = .shared) async -> CriticRatingResult { + var community: CriticRatingResult? + if let credentials { + let primary = await igdb.load(query, credentials: credentials) + if !Task.isCancelled, let rating = primary.rating { + if !rating.isCommunity { return primary } + community = primary + } + } + let fallback = await load(query) + guard !Task.isCancelled else { return CriticRatingResult(rating: nil, fetchedAt: nil, isStale: false) } + return fallback.rating != nil ? fallback : (community ?? fallback) + } + public func load(_ query: CriticRatingQuery, now: Date = Date()) async -> CriticRatingResult { + let empty = CriticRatingResult(rating: nil, fetchedAt: nil, isStale: false) + guard !Task.isCancelled, !query.name.isEmpty, query.name.count <= 300 else { return empty } + let waiter = UUID() + var flight: Flight + if let current = pending[query] { flight = current; flight.waiters.insert(waiter) } + else { + guard pending.count < 4 else { return empty } + flight = Flight(id: UUID(), task: Task { await self.resolve(query, now: now) }, waiters: [waiter]) + } + pending[query] = flight + let task = flight.task, id = flight.id + return await withTaskCancellationHandler(operation: { + defer { release(query, id: id, waiter: waiter) } + let result = await task.value + return Task.isCancelled ? empty : result + }, onCancel: { Task { await self.release(query, id: id, waiter: waiter) } }) + } + private func release(_ query: CriticRatingQuery, id: UUID, waiter: UUID) { + guard var flight = pending[query], flight.id == id else { return } + flight.waiters.remove(waiter) + if flight.waiters.isEmpty { flight.task.cancel(); pending[query] = nil } + else { pending[query] = flight } + } + private func resolve(_ query: CriticRatingQuery, now: Date) async -> CriticRatingResult { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let key = SHA256.hash(data: (try? encoder.encode(query)) ?? Data()) + .map { String(format: "%02x", $0) }.joined() + let file = directory.appendingPathComponent(key + ".json") + let cached = (try? InstallationFileSnapshot.read(at: file, maximumBytes: 65_536).data) + .flatMap { try? JSONDecoder().decode(Cache.self, from: $0) } + .flatMap { $0.query == query && ($0.rating?.isValid ?? true) + && ($0.rating != nil || $0.resolverVersion == 2) ? $0 : nil } + func result(_ cache: Cache?, stale: Bool) -> CriticRatingResult { + CriticRatingResult(rating: cache?.rating, fetchedAt: cache?.fetchedAt, isStale: stale && cache != nil) + } + let age = cached.map { now.timeIntervalSince($0.fetchedAt) } + let ttl: TimeInterval = cached?.rating == nil ? 86400 : 7 * 86400 + if let age, age >= 0, age < ttl { return result(cached, stale: false) } + guard Date() >= backoffUntil else { return result(cached, stale: true) } + do { + try Task.checkCancellation() + var ids: [String] = [] + if let appID = query.steamAppID, let url = WikidataRatings.steamSearchURL(appID: appID) { + ids = try WikidataRatings.steamIDs(in: await fetch(url)) + } + let bySteamID = !ids.isEmpty + if ids.isEmpty { + guard let searchURL = WikidataRatings.searchURL(name: query.name) else { return result(cached, stale: true) } + let search = try await fetch(searchURL) + ids = try WikidataRatings.ids(in: search, name: query.name) + } + var rating: CriticRating? + if let url = WikidataRatings.entitiesURL(ids: ids) { + let data = try await fetch(url) + rating = try WikidataRatings.rating(in: data, ids: ids, query: query, requireSteamID: bySteamID) + } + try Task.checkCancellation() + let value = Cache(query: query, rating: rating, fetchedAt: now, resolverVersion: 2) + // An unwritable cache does not discard a valid network answer. + if let encoded = try? JSONEncoder().encode(value), encoded.count <= 65_536 { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try encoded.write(to: file, options: .atomic) + } catch { /* Enrichment remains usable in memory for this appearance. */ } + } + return result(value, stale: false) + } catch { + if !Task.isCancelled && !(error is CancellationError) { backoffUntil = Date().addingTimeInterval(60) } + return result(cached, stale: true) + } + } + /// Requests are serial across games, as requested by MediaWiki's API etiquette. + private func fetch(_ url: URL) async throws -> Data { + try Task.checkCancellation() + let previous = requestTail, transport = transport + let request = Task { + await previous?.value + try Task.checkCancellation() + return try await transport(url) + } + requestTail = Task { _ = try? await request.value } + return try await withTaskCancellationHandler(operation: { + let data = try await request.value + try Task.checkCancellation() + return data + }, onCancel: { request.cancel() }) + } + + private final class NoRedirects: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } + } + private static let session: URLSession = { + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForResource = 20 + config.timeoutIntervalForRequest = 12 + config.httpMaximumConnectionsPerHost = 1 + config.httpShouldSetCookies = false + config.httpCookieStorage = nil + return URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil) + }() + public static func download(_ url: URL) async throws -> Data { + guard url.scheme == "https", url.host == "www.wikidata.org", url.path == "/w/api.php", + url.user == nil, url.password == nil, url.port == nil || url.port == 443 else { throw URLError(.badURL) } + var request = URLRequest(url: url) + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") + request.setValue("application/json", forHTTPHeaderField: "Accept") + let (data, response) = try await BoundedDownload.data(for: request, session: session, limit: 4_194_304) + guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), + http.url == url else { throw URLError(.badServerResponse) } + return data + } +} diff --git a/Sources/NXLibraryCore/Services/DatabaseMetadata.swift b/Sources/NXLibraryCore/Services/DatabaseMetadata.swift new file mode 100644 index 00000000..10435164 --- /dev/null +++ b/Sources/NXLibraryCore/Services/DatabaseMetadata.swift @@ -0,0 +1,156 @@ +import Foundation + +/// The two public databases offered alongside store-specific metadata. A shop ID is not required. +public enum MetadataDatabase: String, CaseIterable, Codable, Sendable { + case launchBox, theGamesDB + public var name: String { self == .launchBox ? "LaunchBox" : "TheGamesDB" } + var host: String { self == .launchBox ? "gamesdb.launchbox-app.com" : "thegamesdb.net" } + func platforms(for query: CriticRatingQuery) -> [String] { + switch query.platform { + case .mac: return self == .launchBox ? ["Apple Mac OS", "Windows"] : ["Mac OS", "PC"] + case .switch: return ["Nintendo Switch"] + case .switch2: return ["Nintendo Switch 2"] + } + } +} + +public struct DatabaseMetadataPreview: Codable, Equatable, Sendable { + public let database: MetadataDatabase + public let name: String + public let platform: String + public let page: URL + public let values: [MetadataField: String] + public func option(for field: MetadataField) -> MetadataOption? { + values[field].map { MetadataOption(field: field, source: "\(database.name) · \(platform)", value: $0) } + } + var isValid: Bool { + !name.isEmpty && name.count <= 300 && !platform.isEmpty + && DatabaseMetadataParser.safe(page, database: database) + && values.values.allSatisfy { !$0.isEmpty && $0.count <= 32_768 } + } +} + +public enum DatabaseMetadataIssue: String, Codable, Equatable, Sendable { case notFound, ambiguous, unavailable, cancelled } +public struct DatabaseMetadataResult: Equatable, Sendable { + public let preview: DatabaseMetadataPreview? + public let issue: DatabaseMetadataIssue? + public let isStale: Bool + static func missing(_ issue: DatabaseMetadataIssue) -> Self { .init(preview: nil, issue: issue, isStale: false) } +} + +public struct DatabaseMetadataCandidate: Hashable, Sendable { + public let url: URL + public let title: String + public let platform: String +} + +/// Bounded, string-only parsing of the same public pages used by the existing artwork flows. +public enum DatabaseMetadataParser { + static func safe(_ url: URL, database: MetadataDatabase) -> Bool { + guard url.scheme == "https", url.host == database.host, url.user == nil, url.password == nil, + url.port == nil || url.port == 443, url.fragment == nil else { return false } + if database == .launchBox { + return url.path.range(of: #"^/games/details/[0-9]+-[A-Za-z0-9-]*$"#, options: .regularExpression) != nil + && (Int(url.lastPathComponent.prefix { $0.isNumber }) ?? 0) > 0 && url.query == nil + } + let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + return url.path == "/game.php" && items.count == 1 && items[0].name == "id" && (Int(items[0].value ?? "") ?? 0) > 0 + } + static func capture(_ pattern: String, in html: String) -> String? { + guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .dotMatchesLineSeparators]), + let match = regex.firstMatch(in: html, range: NSRange(html.startIndex..., in: html)), + let range = Range(match.range(at: 1), in: html) else { return nil } + return String(html[range]) + } + static func text(_ html: String) -> String { GameBananaAPI.plainText(fromHTML: html) } + static func sameName(_ name: String, query: CriticRatingQuery) -> Bool { IGDBRatings.normalized(name) == IGDBRatings.normalized(query.name) } + + public static func launchBoxCandidates(in html: String, query: CriticRatingQuery) -> [DatabaseMetadataCandidate] { + let named = LaunchBoxArt.results(in: html).filter { sameName($0.title, query: query) } + for platform in MetadataDatabase.launchBox.platforms(for: query) { + let matches = named.filter { $0.platform == platform }.compactMap { result -> DatabaseMetadataCandidate? in + guard let url = URL(string: result.path, relativeTo: LaunchBoxArt.site)?.absoluteURL, safe(url, database: .launchBox) else { return nil } + return .init(url: url, title: result.title, platform: platform) + } + if !matches.isEmpty { return Array(Set(matches)).sorted { $0.url.absoluteString < $1.url.absoluteString } } + } + return [] + } + + public static func launchBox(in html: String, query: CriticRatingQuery, page: URL) throws -> DatabaseMetadataResult { + guard safe(page, database: .launchBox), html.utf8.count <= 2_097_152, + let json = capture(#"<script[^>]*id=["']__NUXT_DATA__["'][^>]*>(.*?)</script>"#, in: html), + let graph = try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [Any] else { return .missing(.unavailable) } + func value(_ object: [String: Any], _ key: String) -> Any? { + guard let index = object[key] as? Int, graph.indices.contains(index) else { return nil } + return graph[index] + } + func names(_ object: [String: Any], _ key: String) -> String { + let indices = value(object, key) as? [Int] ?? [] + return indices.compactMap { index -> String? in + guard graph.indices.contains(index), let named = graph[index] as? [String: Any] else { return nil } + return value(named, "name") as? String + }.joined(separator: ", ") + } + let id = Int(page.lastPathComponent.prefix { $0.isNumber }) + let objects = graph.compactMap { $0 as? [String: Any] }.filter { (value($0, "gameKey") as? Int) == id && $0["overview"] != nil } + guard objects.count == 1, let object = objects.first, + let name = value(object, "name") as? String, + let platformObject = value(object, "platform") as? [String: Any], + let platform = value(platformObject, "name") as? String else { return .missing(.unavailable) } + guard sameName(name, query: query), MetadataDatabase.launchBox.platforms(for: query).contains(platform) else { return .missing(.notFound) } + return preview(database: .launchBox, name: name, platform: platform, page: page, query: query, values: [ + .description: value(object, "overview") as? String ?? "", + .genres: names(object, "gameGenres"), .developer: names(object, "gameDevelopers"), + .publisher: names(object, "gamePublishers"), .releaseDate: value(object, "releaseDate") as? String ?? "" + ]) + } + + static let gamesDBPlatformIDs = ["Mac OS": "37", "PC": "1", "Nintendo Switch": "4971", "Nintendo Switch 2": "5021"] + static func gamesDBSearch(query: CriticRatingQuery, platform: String) -> URL? { + guard let id = gamesDBPlatformIDs[platform] else { return nil } + var url = URLComponents(string: "https://thegamesdb.net/search.php")! + url.queryItems = [.init(name: "name", value: IGDBRatings.clean(query.name)), .init(name: "platform_id[]", value: id)] + return url.url + } + static func gamesDBCandidates(in html: String, query: CriticRatingQuery, platform: String) -> [DatabaseMetadataCandidate] { + var found = Set<DatabaseMetadataCandidate>() + for card in html.components(separatedBy: "game.php?id=").dropFirst() { + guard let id = Int(card.prefix { $0.isNumber }), id > 0, + let footer = card.range(of: "card-footer"), + let title = capture(#"<p\b[^>]*>(.*?)</p>"#, in: String(card[footer.upperBound...])), + let from = capture(#"<p[^>]*class=["'][^"']*text-muted[^"']*["'][^>]*>(.*?)</p>"#, in: card), + text(from) == platform, sameName(text(title), query: query) else { continue } + found.insert(.init(url: TheGamesDBArt.gameURL(id: id), title: text(title), platform: platform)) + } + return found.sorted { $0.url.absoluteString < $1.url.absoluteString } + } + public static func theGamesDB(in html: String, query: CriticRatingQuery, page: URL) -> DatabaseMetadataResult { + guard safe(page, database: .theGamesDB), html.utf8.count <= 2_097_152, + let heading = capture(#"<h1\b[^>]*>(.*?)</h1>"#, in: html), + let platformHTML = capture(#"<p\b[^>]*>\s*Platform:\s*(.*?)</p>"#, in: html) else { return .missing(.unavailable) } + let name = text(heading), platform = text(platformHTML) + guard sameName(name, query: query), MetadataDatabase.theGamesDB.platforms(for: query).contains(platform) else { return .missing(.notFound) } + func field(_ label: String) -> String { + capture(#"<p\b[^>]*>\s*"# + NSRegularExpression.escapedPattern(for: label) + #"\s*(.*?)</p>"#, in: html).map(text) ?? "" + } + return preview(database: .theGamesDB, name: name, platform: platform, page: page, query: query, values: [ + .description: capture(#"<p[^>]*class=["'][^"']*game-overview[^"']*["'][^>]*>(.*?)</p>"#, in: html) ?? "", + .developer: field("Developer(s):"), .publisher: field("Publishers(s):"), + .genres: field("Genre(s):").components(separatedBy: "|").map { $0.trimmingCharacters(in: .whitespaces) }.joined(separator: ", "), + .releaseDate: field("ReleaseDate:") + ]) + } + private static func preview(database: MetadataDatabase, name: String, platform: String, page: URL, + query: CriticRatingQuery, values: [MetadataField: String]) -> DatabaseMetadataResult { + var fields = values.mapValues(text).filter { !$0.value.isEmpty && $0.value.count <= 32_768 } + if let date = fields[.releaseDate] { + let format = DateFormatter(); format.locale = Locale(identifier: "en_US_POSIX"); format.timeZone = TimeZone(secondsFromGMT: 0) + format.dateFormat = "yyyy-MM-dd"; format.isLenient = false + if date.count != 10 || format.date(from: date).map({ format.string(from: $0) == date }) != true { fields[.releaseDate] = nil } + } + if query.platform == .mac && ["PC", "Windows"].contains(platform) { fields[.releaseDate] = nil } + let result = DatabaseMetadataPreview(database: database, name: name, platform: platform, page: page, values: fields) + return result.isValid ? .init(preview: result, issue: nil, isStale: false) : .missing(.unavailable) + } +} diff --git a/Sources/NXLibraryCore/Services/DatabaseMetadataService.swift b/Sources/NXLibraryCore/Services/DatabaseMetadataService.swift new file mode 100644 index 00000000..a6baecf4 --- /dev/null +++ b/Sources/NXLibraryCore/Services/DatabaseMetadataService.swift @@ -0,0 +1,152 @@ +import Foundation + +/// Two bounded public-page lookups, isolated from artwork downloads and personal choices. +public actor DatabaseMetadataService { + public typealias Transport = @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + private static let launchBox = DatabaseMetadataService(database: .launchBox) + private static let theGamesDB = DatabaseMetadataService(database: .theGamesDB) + public static func shared(_ database: MetadataDatabase) -> DatabaseMetadataService { + database == .launchBox ? launchBox : theGamesDB + } + private let database: MetadataDatabase + private let directory: URL + private let transport: Transport + private struct Cache: Codable { + let query: CriticRatingQuery + let preview: DatabaseMetadataPreview? + let issue: DatabaseMetadataIssue? + let fetchedAt: Date + } + private struct Flight { + let id: UUID + let task: Task<DatabaseMetadataResult, Never> + var waiters: Set<UUID> + } + private var pending: [CriticRatingQuery: Flight] = [:] + + public init(database: MetadataDatabase, directory: URL = AppData.supportRoot.appendingPathComponent("metadata/databases"), + transport: Transport? = nil) { + self.database = database; self.directory = directory.appendingPathComponent(database.rawValue) + self.transport = transport ?? { try await DatabaseMetadataService.download($0) } + } + public func load(_ query: CriticRatingQuery, now: Date = Date(), forceRefresh: Bool = false) async -> DatabaseMetadataResult { + guard !Task.isCancelled else { return .missing(.cancelled) } + guard !query.name.isEmpty, query.name.count <= 300 else { return .missing(.notFound) } + let waiter = UUID() + var flight: Flight + if let saved = pending[query] { flight = saved; flight.waiters.insert(waiter) } + else { + guard pending.count < 4 else { return .missing(.unavailable) } + flight = Flight(id: UUID(), task: Task { await self.resolve(query, now: now, forceRefresh: forceRefresh) }, waiters: [waiter]) + } + pending[query] = flight + let id = flight.id, task = flight.task + return await withTaskCancellationHandler(operation: { + defer { release(query, id: id, waiter: waiter) } + let result = await task.value + return Task.isCancelled ? .missing(.cancelled) : result + }, onCancel: { Task { await self.release(query, id: id, waiter: waiter) } }) + } + private func release(_ query: CriticRatingQuery, id: UUID, waiter: UUID) { + guard var flight = pending[query], flight.id == id else { return } + flight.waiters.remove(waiter) + if flight.waiters.isEmpty { flight.task.cancel(); pending[query] = nil } + else { pending[query] = flight } + } + private func resolve(_ query: CriticRatingQuery, now: Date, forceRefresh: Bool) async -> DatabaseMetadataResult { + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + guard let data = try? encoder.encode(query) else { return .missing(.unavailable) } + let file = directory.appendingPathComponent(IGDBCredentials.digest(String(decoding: data, as: UTF8.self)) + ".json") + let bytes = try? InstallationFileSnapshot.read(at: file, maximumBytes: 262_144).data + let decoded = bytes.flatMap { try? JSONDecoder().decode(Cache.self, from: $0) } + let cached = decoded.flatMap { saved -> Cache? in + guard saved.query == query else { return nil } + if let preview = saved.preview { + return preview.database == database && preview.isValid && database.platforms(for: query).contains(preview.platform) ? saved : nil + } + return saved.issue == .notFound || saved.issue == .ambiguous ? saved : nil + } + let ttl: TimeInterval = cached?.preview == nil ? 86400 : 7 * 86400 + if !forceRefresh, let cached, (0..<ttl).contains(now.timeIntervalSince(cached.fetchedAt)) { + return .init(preview: cached.preview, issue: cached.issue, isStale: false) + } + do { + let result = try await fetch(query) + try Task.checkCancellation() + if result.issue == nil || result.issue == .notFound || result.issue == .ambiguous { + let saved = Cache(query: query, preview: result.preview, issue: result.issue, fetchedAt: now) + if let data = try? encoder.encode(saved), data.count <= 262_144 { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try data.write(to: file, options: .atomic) + } catch { /* A valid preview does not depend on writing its cache. */ } + } + return result + } + } catch { + if Task.isCancelled || error is CancellationError { return .missing(.cancelled) } + } + return .init(preview: cached?.preview, issue: .unavailable, isStale: cached?.preview != nil) + } + private func fetch(_ query: CriticRatingQuery) async throws -> DatabaseMetadataResult { + let candidates: [DatabaseMetadataCandidate] + switch database { + case .launchBox: + guard let url = LaunchBoxArt.searchURL(for: IGDBRatings.clean(query.name)) else { return .missing(.notFound) } + let html = try await get(url) + guard html.contains("__NUXT_DATA__") || html.contains("/games/details/") else { return .missing(.unavailable) } + candidates = DatabaseMetadataParser.launchBoxCandidates(in: html, query: query) + case .theGamesDB: + var found: [DatabaseMetadataCandidate] = [] + for platform in database.platforms(for: query) { + guard let url = DatabaseMetadataParser.gamesDBSearch(query: query, platform: platform) else { continue } + let html = try await get(url) + guard html.contains("game.php?id=") || html.contains("TheGamesDB") else { return .missing(.unavailable) } + found = DatabaseMetadataParser.gamesDBCandidates(in: html, query: query, platform: platform) + if !found.isEmpty { break } + } + candidates = found + } + guard candidates.count <= 1 else { return .missing(.ambiguous) } + guard let match = candidates.first else { return .missing(.notFound) } + let html = try await get(match.url) + let result = try database == .launchBox + ? DatabaseMetadataParser.launchBox(in: html, query: query, page: match.url) + : DatabaseMetadataParser.theGamesDB(in: html, query: query, page: match.url) + guard result.preview == nil || result.preview?.platform == match.platform else { return .missing(.unavailable) } + return result + } + private func get(_ url: URL) async throws -> String { + try Task.checkCancellation() + guard Self.allowed(url), url.host == database.host else { throw URLError(.badURL) } + var request = URLRequest(url: url); request.timeoutInterval = 12 + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") + let (data, response) = try await transport(request) + try Task.checkCancellation() + guard (200..<300).contains(response.statusCode), response.url == url, data.count <= 2_097_152, + let html = String(data: data, encoding: .utf8) else { throw URLError(.badServerResponse) } + return html + } + private static func allowed(_ url: URL) -> Bool { + guard url.scheme == "https", url.user == nil, url.password == nil, url.fragment == nil, + url.port == nil || url.port == 443 else { return false } + if url.host == "gamesdb.launchbox-app.com" { return url.path.hasPrefix("/games/results/") || DatabaseMetadataParser.safe(url, database: .launchBox) } + return url.host == "thegamesdb.net" && (url.path == "/search.php" || DatabaseMetadataParser.safe(url, database: .theGamesDB)) + } + private final class NoRedirects: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } + } + private static let session: URLSession = { + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForResource = 20; config.timeoutIntervalForRequest = 12 + config.httpCookieStorage = nil; config.httpShouldSetCookies = false + return URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil) + }() + private static func download(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + guard let url = request.url, allowed(url) else { throw URLError(.badURL) } + let (data, response) = try await BoundedDownload.data(for: request, session: session, limit: 2_097_152) + guard let http = response as? HTTPURLResponse, http.url == url else { throw URLError(.badServerResponse) } + return (data, http) + } +} diff --git a/Sources/NXLibraryCore/Services/DevelopmentOperationStore.swift b/Sources/NXLibraryCore/Services/DevelopmentOperationStore.swift new file mode 100644 index 00000000..2a254f00 --- /dev/null +++ b/Sources/NXLibraryCore/Services/DevelopmentOperationStore.swift @@ -0,0 +1,32 @@ +import Foundation + +/// Only explicit operations created in this Dev profile may resume automatically after a restart. +/// This file is deliberately absent from the stable-to-development import allowlist. +public final class DevelopmentOperationStore { + public enum Kind: String, Codable { case build, icon } + private let file: URL + private let isDevelopment: Bool + private var requested: [String: Set<UUID>] = [:] + public private(set) var loadError: Error? + + public init(file: URL = AppData.supportRoot.appendingPathComponent(".development-operations.json"), + isDevelopment: Bool = AppData.profile.isDevelopment) { + self.file = file + self.isDevelopment = isDevelopment + guard isDevelopment, FileManager.default.fileExists(atPath: file.path) else { return } + do { requested = try JSONDecoder().decode([String: Set<UUID>].self, from: Data(contentsOf: file)) } + catch { loadError = error } + } + public func permits(_ kind: Kind, gameID: UUID) -> Bool { + !isDevelopment || (loadError == nil && requested[kind.rawValue]?.contains(gameID) == true) + } + public func authorize(_ kind: Kind, gameID: UUID) throws { + guard isDevelopment else { return } + if let loadError { throw loadError } + var next = requested + next[kind.rawValue, default: []].insert(gameID) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONEncoder().encode(next).write(to: file, options: .atomic) + requested = next + } +} diff --git a/Sources/NXLibraryCore/Services/DevelopmentProfileImporter.swift b/Sources/NXLibraryCore/Services/DevelopmentProfileImporter.swift new file mode 100644 index 00000000..eed77925 --- /dev/null +++ b/Sources/NXLibraryCore/Services/DevelopmentProfileImporter.swift @@ -0,0 +1,170 @@ +import Foundation +import CryptoKit + +public enum DevelopmentProfileError: Error, LocalizedError { + case invalidConfiguration, destinationExists, unsafeFile, invalidData, sourceChanged, preferencesUnavailable + case unreadableFile(String) + public var errorDescription: String? { + let context = AppLocale(language: .automatic, region: nil) + switch self { + case .unreadableFile(let name): return L10n.format("The launcher file %@ could not be read. The original data has not been changed.", [name], context: context) + case .invalidConfiguration: return L10n.text("The development profile configuration is invalid.", context: context) + case .destinationExists: return L10n.text("The development data folder already exists without a completed import. It has been preserved.", context: context) + case .unsafeFile: return L10n.text("The library copy contains a symbolic link or an unsupported file. The original data has not been changed.", context: context) + case .invalidData: return L10n.text("Some launcher data could not be read. The original data has not been changed.", context: context) + case .sourceChanged: return L10n.text("The original library changed during the copy. Close the other launcher copy and try again.", context: context) + case .preferencesUnavailable: return L10n.text("The development preferences could not be saved. Try again.", context: context) + } + } +} + +/// An allowlisted, one-time snapshot. Reads source bytes directly: source-store load/recovery hooks never run. +public struct DevelopmentProfileImporter { + private let fm: FileManager + public init(fileManager: FileManager = .default) { fm = fileManager } + private static let files = ["library.json", "library.json.bak", "catalog.json", "catalog.json.bak", "settings.json", "play-sessions.json", "play-sessions-totals.json", "metadata-picks.json", "integrations/steam/metadata-picks.json", "app-sizes.json"] + private static let folders = ["artwork-picks", "integrations/steam/artwork-picks", "artwork", "metadata", "SeleneImports", "app-icons", "mods", "gamebanana"] + private static let marker = ".development-import.json" + private static let preferenceFile = ".import-preferences.plist" + private struct ImportState: Codable { + let version: Int + var ready: Bool + let hashes: [String: String] + } + public func prepare(profile: AppDataProfile, sourcePreferences: () throws -> [String: Any], + savePreferences: ([String: Any]) throws -> Void) throws -> Bool { + guard profile.isDevelopment else { return false } + let source = profile.stableSupportRoot, destination = profile.supportRoot + guard source.resolvingSymlinksInPath() != destination.resolvingSymlinksInPath() else { throw DevelopmentProfileError.invalidConfiguration } + if try exists(destination) { + try regularDirectory(destination) + let marker = destination.appendingPathComponent(Self.marker) + guard (try? fm.attributesOfItem(atPath: marker.path)[.type] as? FileAttributeType) == .typeRegular else { throw DevelopmentProfileError.destinationExists } + guard let data = try? Data(contentsOf: marker), let state = try? JSONDecoder().decode(ImportState.self, from: data), state.version == 1 else { + throw DevelopmentProfileError.destinationExists + } + if state.ready { return false } + try finish(destination, state: state, savePreferences: savePreferences) + return true + } + if try exists(source) { try regularDirectory(source) } + let before = try snapshot(source) + let preferences = try sourcePreferences().filter { Self.ownedPreference($0.key) } + let preferencesData = try PropertyListSerialization.data(fromPropertyList: preferences, format: .binary, options: 0) + let parent = destination.deletingLastPathComponent() + try fm.createDirectory(at: parent, withIntermediateDirectories: true) + let stage = parent.appendingPathComponent(".NXLibrary-Development-import-" + UUID().uuidString) + try fm.createDirectory(at: stage, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + defer { try? fm.removeItem(at: stage) } // Only the staging folder created by this invocation. + for relative in before.keys.sorted() { + let from = source.appendingPathComponent(relative), to = stage.appendingPathComponent(relative) + try fm.createDirectory(at: to.deletingLastPathComponent(), withIntermediateDirectories: true) + guard try fm.attributesOfItem(atPath: from.path)[.type] as? FileAttributeType == .typeRegular else { throw DevelopmentProfileError.sourceChanged } + try fm.copyItem(at: from, to: to) + guard try digest(to) == before[relative] else { throw DevelopmentProfileError.sourceChanged } + if relative.hasSuffix(".json") { + do { _ = try JSONSerialization.jsonObject(with: Data(contentsOf: to), options: [.fragmentsAllowed]) } + catch { throw DevelopmentProfileError.unreadableFile(relative) } + } + } + try validateRequiredData(stage) + guard try snapshot(source) == before, + NSDictionary(dictionary: try sourcePreferences().filter { Self.ownedPreference($0.key) }).isEqual(to: preferences) else { throw DevelopmentProfileError.sourceChanged } + try preferencesData.write(to: stage.appendingPathComponent(Self.preferenceFile), options: .atomic) + // End a copied unfinished session at its last recorded heartbeat, never at the current time. + let sessionFile = stage.appendingPathComponent("play-sessions.json") + if try exists(sessionFile) { + var sessions = try JSONDecoder().decode([PlaySession].self, from: Data(contentsOf: sessionFile)) + if sessions.contains(where: \.isActive) { + for i in sessions.indices where sessions[i].isActive { + sessions[i].endedAt = max(sessions[i].startedAt, sessions[i].lastHeartbeatAt) + } + try JSONEncoder().encode(sessions).write(to: sessionFile, options: .atomic) + } + } + let state = ImportState(version: 1, ready: false, hashes: try snapshot(stage)) + try JSONEncoder().encode(state).write(to: stage.appendingPathComponent(Self.marker), options: .atomic) + // Moving into place never replaces an existing destination. A racing import fails safely. + try fm.moveItem(at: stage, to: destination) + try finish(destination, state: state, savePreferences: savePreferences) + return true + } + private func finish(_ destination: URL, state: ImportState, savePreferences: ([String: Any]) throws -> Void) throws { + guard try snapshot(destination) == state.hashes else { throw DevelopmentProfileError.invalidData } + let preferenceFile = destination.appendingPathComponent(Self.preferenceFile) + guard try fm.attributesOfItem(atPath: preferenceFile.path)[.type] as? FileAttributeType == .typeRegular else { throw DevelopmentProfileError.unsafeFile } + let data = try Data(contentsOf: preferenceFile) + guard let values = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { throw DevelopmentProfileError.invalidData } + try savePreferences(values.filter { Self.ownedPreference($0.key) }) + var ready = state + ready.ready = true + try JSONEncoder().encode(ready).write(to: destination.appendingPathComponent(Self.marker), options: .atomic) + } + // Version-one legacy launcher preference schema. Do not copy future secrets just because they share a prefix. + private static let preferenceKeys: Set<String> = [ + "NXLibrary.lastPortingFinishSeconds", "NXLibrary_AllowUntestedToolchain", "NXLibrary_EngineFolder", + "NXLibrary_NewestEngineChoice", "NXLibrary_SetupCompleted", "NXLibrary_SetupLastStates", "NXLibrary_SetupPage", + "NXLibrary_SetupSteamChoice", + "NXLibrary_UpdateLastCheck", "NXLibrary_UpdateLaterAt", "NXLibrary_UpdateLaterVersion", "NXLibrary_UpdateRepository", + "NXLibrary_UpstreamStatus", "NXNative_ControllerDeadzone", "NXNative_SavedGameFolder", "NXNative_SavedIconAppearanceMode", + "NXNative_SavedLibraryFolder", "NXNative_SavedProdKeysPath" + ] + public static func ownedPreference(_ key: String) -> Bool { + preferenceKeys.contains(key) || key.hasPrefix("NXNative_GameConfig_") + } + private func validateRequiredData(_ root: URL) throws { + for name in ["library.json", "catalog.json", "catalog.json.bak", "settings.json", "play-sessions.json"] { + let file = root.appendingPathComponent(name) + guard fm.fileExists(atPath: file.path) else { continue } + let data = try Data(contentsOf: file) + do { + switch name { + case "library.json": + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + _ = try decoder.decode(LibraryFile.self, from: data) + case "catalog.json", "catalog.json.bak": + let document = try CatalogStore.decode(data) + try CatalogStore(directory: root).validateImportedOrigin(document) + case "settings.json": _ = try JSONDecoder().decode(AppSettings.self, from: data) + default: _ = try JSONDecoder().decode([PlaySession].self, from: data) + } + } catch { throw DevelopmentProfileError.unreadableFile(name) } + } + } + private func snapshot(_ root: URL) throws -> [String: String] { + var result: [String: String] = [:] + func visit(_ relative: String, depth: Int) throws { + guard depth < 32, result.count < 100_000 else { throw DevelopmentProfileError.unsafeFile } + let url = root.appendingPathComponent(relative) + let attrs = try fm.attributesOfItem(atPath: url.path) + switch attrs[.type] as? FileAttributeType { + case .typeRegular: result[relative] = try digest(url) + case .typeDirectory: + for name in try fm.contentsOfDirectory(atPath: url.path).sorted() { try visit(relative + "/" + name, depth: depth + 1) } + default: throw DevelopmentProfileError.unsafeFile + } + } + for name in Self.files + Self.folders { + let url = root.appendingPathComponent(name) + // attributes also detects broken symlinks, which fileExists would silently skip. + if try exists(url) { try visit(name, depth: 0) } + } + return result + } + private func exists(_ url: URL) throws -> Bool { + do { _ = try fm.attributesOfItem(atPath: url.path); return true } + catch let error as CocoaError where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile { return false } + } + private func regularDirectory(_ url: URL) throws { + guard try fm.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType == .typeDirectory else { throw DevelopmentProfileError.unsafeFile } + } + private func digest(_ url: URL) throws -> String { + guard try fm.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType == .typeRegular else { throw DevelopmentProfileError.unsafeFile } + let handle = try FileHandle(forReadingFrom: url) + defer { try? handle.close() } + var hash = SHA256() + while let bytes = try handle.read(upToCount: 1024 * 1024), !bytes.isEmpty { hash.update(data: bytes) } + return hash.finalize().map { String(format: "%02x", $0) }.joined() + } +} diff --git a/Sources/NXLibraryCore/Services/DiagnosticsReport.swift b/Sources/NXLibraryCore/Services/DiagnosticsReport.swift index 86aaad10..f703b788 100644 --- a/Sources/NXLibraryCore/Services/DiagnosticsReport.swift +++ b/Sources/NXLibraryCore/Services/DiagnosticsReport.swift @@ -40,7 +40,7 @@ public enum DiagnosticsReport { public static func markdown(_ i: Inputs) -> String { func value(_ s: String?) -> String { s.map { $0.isEmpty ? "—" : $0 } ?? "—" } func yes(_ b: Bool) -> String { b ? "yes" : "no" } - var lines = ["# NX Library diagnostics", ""] + var lines = ["# Arcane diagnostics", ""] lines += ["## App", "- Version: \(i.appVersion)" + (i.buildDate.map { " (built \($0))" } ?? ""), "- Bundle ID: \(i.bundleID)", diff --git a/Sources/NXLibraryCore/Services/EngineLocation.swift b/Sources/NXLibraryCore/Services/EngineLocation.swift index 419f6896..cfaf4ac8 100644 --- a/Sources/NXLibraryCore/Services/EngineLocation.swift +++ b/Sources/NXLibraryCore/Services/EngineLocation.swift @@ -1,6 +1,6 @@ import Foundation -/// Where the nxnative checkout is: `~/nxnative`, or the folder the player chose in Settings → Engine while that +/// Where the nxnative checkout is: `~/nxnative`, or the folder the player chose in Settings → Setup and engine while that /// folder exists. public enum EngineLocation { public static func defaultFolder(home: URL) -> URL { home.appendingPathComponent("nxnative") } diff --git a/Sources/NXLibraryCore/Services/EnginePackageReader.swift b/Sources/NXLibraryCore/Services/EnginePackageReader.swift index e40fe759..f6561b92 100644 --- a/Sources/NXLibraryCore/Services/EnginePackageReader.swift +++ b/Sources/NXLibraryCore/Services/EnginePackageReader.swift @@ -48,6 +48,7 @@ public struct EngineSourceCapabilities { public let extractedFolders: Bool /// Builds from a `.nup` file (scripts/pack_nup.py). public let nupContainers: Bool + public let nupPrograms: Bool /// A NUP or an extracted folder of a game with no registered profile gets a provisional one, as an NSP does /// (nxnative 056e41fe: survey_nup, survey_dump). Before it, such a game is refused. public let provisionalNUP: Bool @@ -61,6 +62,7 @@ public struct EngineSourceCapabilities { titleSelection = text.contains("'--title-id'") || text.contains("\"--title-id\"") extractedFolders = text.contains("import pack_dump") && titleSelection nupContainers = text.contains("import pack_nup") && titleSelection + nupPrograms = nupContainers && text.contains("pack_nup.scan(n, program)") provisionalNUP = nupContainers && text.contains("survey_nup") provisionalDumps = extractedFolders && text.contains("survey_dump") } diff --git a/Sources/NXLibraryCore/Services/GameAppDestination.swift b/Sources/NXLibraryCore/Services/GameAppDestination.swift index eb75c093..a72e7ee9 100644 --- a/Sources/NXLibraryCore/Services/GameAppDestination.swift +++ b/Sources/NXLibraryCore/Services/GameAppDestination.swift @@ -44,7 +44,7 @@ public enum GameAppDestination { guard folder.isFileURL, folder.standardizedFileURL.path != "/", fm.fileExists(atPath: folder.path, isDirectory: &isDirectory), isDirectory.boolValue, fm.isReadableFile(atPath: folder.path), fm.isExecutableFile(atPath: folder.path) else { - return L10n.text("The Game apps folder is unavailable. Reconnect it or choose another in Settings → Library.") + return L10n.text("The Game apps folder is unavailable. Reconnect it or choose another in Settings → Porting → Library.") } guard fm.isWritableFile(atPath: folder.path) else { return L10n.format("The app folder is read-only: %@. Allow writing here before building.", [String(describing: (folder.path))]) diff --git a/Sources/NXLibraryCore/Services/GameBanana/GameBananaBandModel.swift b/Sources/NXLibraryCore/Services/GameBanana/GameBananaBandModel.swift index 5311a7b1..e46fee4d 100644 --- a/Sources/NXLibraryCore/Services/GameBanana/GameBananaBandModel.swift +++ b/Sources/NXLibraryCore/Services/GameBanana/GameBananaBandModel.swift @@ -251,7 +251,7 @@ public final class GameBananaBandModel: ObservableObject { case .looking: return L10n.text("Looking for mods that work…") case .ask: return L10n.text("Is this the right game?") case .noPage: return L10n.text("No GameBanana page found") - case .noneWork: return L10n.text("No mods for this game work with NX Library yet") + case .noneWork: return L10n.text("No mods for this game work with Arcane yet") case .offline: return L10n.text("No connection. Mods you installed still work.") case .failed: return L10n.text("GameBanana didn't answer. Try again in a moment.") case .idle, .matching, .ready: return nil diff --git a/Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift b/Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift index f6ad6f20..95b2eb5e 100644 --- a/Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift +++ b/Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift @@ -34,7 +34,7 @@ actor GameBananaGate { /// cached on disk (game searches 1 day, mod pages 6 h, archive listings forever, since a file's contents never /// change; an empty listing is not kept, since GameBanana may still be reading a new file). When the network fails, an expired cache entry is used rather than nothing. public actor GameBananaClient { - public static func userAgent(version: String) -> String { "NXLibrary/\(version) (macOS; personal app)" } + public static func userAgent(version: String) -> String { AppIdentity.userAgent(version: version) } private let http: ArtworkHTTPClient private let cacheFolder: URL diff --git a/Sources/NXLibraryCore/Services/IGDBClient.swift b/Sources/NXLibraryCore/Services/IGDBClient.swift new file mode 100644 index 00000000..8631e406 --- /dev/null +++ b/Sources/NXLibraryCore/Services/IGDBClient.swift @@ -0,0 +1,114 @@ +import Foundation + +/// Shared IGDB authentication and bounded serial requests; provider data stays in its own services. +actor IGDBClient { + typealias Transport = @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + static let shared = IGDBClient() + private let transport: Transport + private struct Token { let owner: String; let value: String; let expires: Date } + private var token: Token? + private var lastRequest = Date.distantPast + private var tail: Task<Void, Never>? + private var jobs: [UUID: Task<Data, Error>] = [:] + + init(transport: @escaping Transport = { try await IGDBClient.download($0) }) { + self.transport = transport + } + func resetToken() { token = nil } + + func request(_ endpoint: String, body: String, credentials: IGDBCredentials, renewToken: Bool = false) async throws -> Data { + guard ["games", "external_games"].contains(endpoint), body.utf8.count <= 16_384 else { throw IGDBError.invalidResponse } + guard jobs.count < 8 else { throw IGDBError.rateLimited } + let id = UUID(), prior = tail + let task = Task { + await prior?.value + try Task.checkCancellation() + if renewToken { self.token = nil } + return try await self.api(endpoint, body: body, credentials: credentials) + } + jobs[id] = task + tail = Task { _ = try? await task.value } + defer { jobs[id] = nil } + return try await withTaskCancellationHandler(operation: { try await task.value }, onCancel: { task.cancel() }) + } + private func accessToken(_ credentials: IGDBCredentials) async throws -> String { + if let token, token.owner == credentials.fingerprint, token.expires > Date() { return token.value } + var form = URLComponents() + form.queryItems = [.init(name: "client_id", value: credentials.clientID), .init(name: "client_secret", value: credentials.clientSecret), + .init(name: "grant_type", value: "client_credentials")] + var request = URLRequest(url: URL(string: "https://id.twitch.tv/oauth2/token")!) + request.httpMethod = "POST" + request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + request.httpBody = form.percentEncodedQuery?.data(using: .utf8) + let (data, response) = try await send(request) + guard response.statusCode == 200 else { + throw [400, 401, 403].contains(response.statusCode) ? IGDBError.rejected : IGDBError.unreachable + } + struct Wire: Decodable { let access_token: String; let expires_in: Double; let token_type: String } + guard let wire = try? JSONDecoder().decode(Wire.self, from: data), wire.token_type.lowercased() == "bearer", + wire.expires_in.isFinite, wire.expires_in > 60, wire.access_token.count <= 2048, + !wire.access_token.isEmpty, wire.access_token.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_" || $0 == "-") }) + else { throw IGDBError.invalidResponse } + try Task.checkCancellation() + token = Token(owner: credentials.fingerprint, value: wire.access_token, + expires: Date().addingTimeInterval(min(wire.expires_in, 31_622_400) - 60)) + return wire.access_token + } + private func api(_ endpoint: String, body: String, credentials: IGDBCredentials) async throws -> Data { + for attempt in 0...1 { + let access = try await accessToken(credentials) + var request = URLRequest(url: URL(string: "https://api.igdb.com/v4/\(endpoint)")!) + request.httpMethod = "POST"; request.httpBody = Data(body.utf8) + request.setValue(credentials.clientID, forHTTPHeaderField: "Client-ID") + request.setValue("Bearer " + access, forHTTPHeaderField: "Authorization") + request.setValue("text/plain", forHTTPHeaderField: "Content-Type") + let (data, response) = try await send(request) + if response.statusCode == 401, attempt == 0 { token = nil; continue } + guard (200..<300).contains(response.statusCode) else { + if response.statusCode == 429 { throw IGDBError.rateLimited } + throw [401,403].contains(response.statusCode) ? IGDBError.rejected : IGDBError.unreachable + } + return data + } + throw IGDBError.rejected + } + private func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + try Task.checkCancellation() + let delay = 0.26 - Date().timeIntervalSince(lastRequest) + if delay > 0 { try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) } + try Task.checkCancellation() + lastRequest = Date() + do { + let result = try await transport(request) + try Task.checkCancellation() + guard result.0.count <= 2_097_152, result.1.url == request.url else { throw IGDBError.invalidResponse } + return result + } catch is CancellationError { throw CancellationError() } + catch let error as IGDBError { throw error } + catch { throw IGDBError.unreachable } + } + private final class NoRedirects: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } + } + private static let session: URLSession = { + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForResource = 20; config.timeoutIntervalForRequest = 12 + config.httpShouldSetCookies = false; config.httpCookieStorage = nil + return URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil) + }() + public static func download(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + guard let url = request.url, url.scheme == "https", url.user == nil, url.password == nil, + url.port == nil || url.port == 443, url.query == nil, request.httpMethod == "POST", + (url.host == "id.twitch.tv" && url.path == "/oauth2/token") || + (url.host == "api.igdb.com" && ["/v4/games", "/v4/external_games"].contains(url.path)) else { throw IGDBError.unreachable } + var request = request + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") + let data: Data, response: URLResponse + do { (data, response) = try await BoundedDownload.data(for: request, session: session, limit: 2_097_152) } + catch let error as URLError where error.code == .dataLengthExceedsMaximum { throw IGDBError.invalidResponse } + guard let http = response as? HTTPURLResponse, http.url == url else { throw IGDBError.invalidResponse } + return (data, http) + } +} diff --git a/Sources/NXLibraryCore/Services/IGDBCredentials.swift b/Sources/NXLibraryCore/Services/IGDBCredentials.swift new file mode 100644 index 00000000..329dc6b7 --- /dev/null +++ b/Sources/NXLibraryCore/Services/IGDBCredentials.swift @@ -0,0 +1,60 @@ +import Foundation +import CryptoKit + +/// The player's own Twitch application credentials; never bundled, logged or put in settings. +public struct IGDBCredentials: Equatable, Codable, Sendable { + public let clientID: String + public let clientSecret: String + public init?(clientID: String, clientSecret: String) { + func normalized(_ text: String) -> String? { + let value = text.trimmingCharacters(in: .whitespacesAndNewlines) + return (8...128).contains(value.count) && value.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber) } ? value : nil + } + guard let id = normalized(clientID), let secret = normalized(clientSecret) else { return nil } + self.clientID = id; self.clientSecret = secret + } + /// Only a digest names in-flight work. Neither credentials nor tokens appear in filenames. + var fingerprint: String { Self.digest(clientID + ":" + clientSecret) } + static func digest(_ text: String) -> String { SHA256.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined() } +} + +public struct IGDBCredentialsStore { + public let url: URL + public init(url: URL = AppData.supportRoot.appendingPathComponent("credentials/igdb.json")) { self.url = url } + public func load() -> IGDBCredentials? { + guard let data = try? InstallationFileSnapshot.read(at: url, maximumBytes: 4096).data, + let value = try? JSONDecoder().decode(IGDBCredentials.self, from: data) else { return nil } + return IGDBCredentials(clientID: value.clientID, clientSecret: value.clientSecret) + } + public func save(_ value: IGDBCredentials) throws { + let fm = FileManager.default + let temp = url.deletingLastPathComponent().appendingPathComponent(".igdb-" + UUID().uuidString) + defer { try? fm.removeItem(at: temp) } + do { + let folder = url.deletingLastPathComponent() + try fm.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + // Creation applies the mode only to a new folder; an existing one is made private too. + try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: folder.path) + let data = try JSONEncoder().encode(value) + guard fm.createFile(atPath: temp.path, contents: data, attributes: [.posixPermissions: 0o600]), + rename(temp.path, url.path) == 0 else { throw IGDBError.notSaved } + } catch { throw IGDBError.notSaved } + } + public func remove() throws { + guard FileManager.default.fileExists(atPath: url.path) else { return } + do { try FileManager.default.removeItem(at: url) } catch { throw IGDBError.notSaved } + } +} + +public enum IGDBError: Error, LocalizedError, Equatable { + case invalidCredentials, rejected, unreachable, rateLimited, invalidResponse, notSaved + public var errorDescription: String? { + switch self { + case .invalidCredentials: return L10n.text("Enter the Client ID and Client Secret from your Twitch developer application.") + case .rejected: return L10n.text("IGDB did not accept these credentials. Check the Client ID and Client Secret.") + case .unreachable, .invalidResponse: return L10n.text("IGDB could not be reached. Check the connection and try again.") + case .rateLimited: return L10n.text("IGDB is busy. Wait a moment and try again.") + case .notSaved: return L10n.text("IGDB credentials could not be saved on this Mac.") + } + } +} diff --git a/Sources/NXLibraryCore/Services/IGDBMetadata.swift b/Sources/NXLibraryCore/Services/IGDBMetadata.swift new file mode 100644 index 00000000..bdeb9830 --- /dev/null +++ b/Sources/NXLibraryCore/Services/IGDBMetadata.swift @@ -0,0 +1,116 @@ +import Foundation + +/// A source preview, never a personalization. Values are applied only through the existing picker. +public struct IGDBMetadata: Codable, Equatable, Sendable { + public let id: Int + public let name: String + public let platform: CriticRatingQuery.Platform + public let url: URL + public let values: [MetadataField: String] + + public func option(for field: MetadataField) -> MetadataOption? { + values[field].map { MetadataOption(field: field, source: "IGDB", value: $0) } + } + var isValid: Bool { + id > 0 && !name.isEmpty && name.count <= 300 && IGDBRatings.safeGameURL(url) != nil + && values.values.allSatisfy { !$0.isEmpty && $0.count <= 32_768 } + } +} + +public enum IGDBMetadataIssue: String, Codable, Equatable, Sendable { + case notFound, ambiguous, unavailable, cancelled +} + +public struct IGDBMetadataResult: Equatable, Sendable { + public let metadata: IGDBMetadata? + public let issue: IGDBMetadataIssue? + public let isStale: Bool +} + +public enum IGDBMetadataParser { + static let fields = "id,name,alternative_names.name,platforms,url,summary,genres.name,involved_companies.company.name,involved_companies.developer,involved_companies.publisher,release_dates.platform,release_dates.date,release_dates.date_format.format" + + private struct Game: Decodable { + struct Name: Decodable { let name: String } + struct Company: Decodable { let company: Name?; let developer: Bool?; let publisher: Bool? } + struct Release: Decodable { + struct Format: Decodable { let format: String } + let platform: Int? + let date: Double? + let date_format: Format? + } + let id: Int + let name: String + let alternative_names: [Name]? + let platforms: [Int]? + let url: URL? + let summary: String? + let genres: [Name]? + let involved_companies: [Company]? + let release_dates: [Release]? + + func preview(for query: CriticRatingQuery) -> IGDBMetadata? { + guard id > 0, let url, let safe = IGDBRatings.safeGameURL(url) else { return nil } + var values: [MetadataField: String] = [:] + func add(_ field: MetadataField, _ value: String?) { + guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty, value.count <= 32_768 else { return } + values[field] = value + } + func names(_ list: [String]) -> String { + var seen = Set<String>() + return list.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty && seen.insert($0.lowercased()).inserted }.joined(separator: ", ") + } + add(.description, summary) + add(.genres, names((genres ?? []).map(\.name))) + add(.developer, names((involved_companies ?? []).filter { $0.developer == true }.compactMap { $0.company?.name })) + add(.publisher, names((involved_companies ?? []).filter { $0.publisher == true }.compactMap { $0.company?.name })) + let dates = (release_dates ?? []).compactMap { release -> Double? in + guard release.platform == query.platform.igdbID, release.date_format?.format == "YYYYMMDD", + let date = release.date, date.isFinite, (-2_208_988_800...7_258_118_400).contains(date) else { return nil } + return date + } + if let date = dates.min() { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withFullDate]; formatter.timeZone = TimeZone(secondsFromGMT: 0) + add(.releaseDate, formatter.string(from: Date(timeIntervalSince1970: date))) + } + let metadata = IGDBMetadata(id: id, name: name, platform: query.platform, url: safe, values: values) + return metadata.isValid ? metadata : nil + } + } + + public static func result(in data: Data, query: CriticRatingQuery) throws -> IGDBMetadataResult { + let games: [Game] = try decode(data) + let matching = games.filter { + IGDBRatings.matches(name: $0.name, aliases: ($0.alternative_names ?? []).map(\.name), platforms: $0.platforms ?? [], query: query) + } + return result(matching, query: query) + } + + public static func steamResult(in data: Data, query: CriticRatingQuery) throws -> IGDBMetadataResult { + struct External: Decodable { + struct Source: Decodable { let name: String } + let uid: String + let external_game_source: Source + let game: Game + } + guard let appID = query.steamAppID else { return result([], query: query) } + let entries: [External] = try decode(data) + let matching = entries.filter { $0.uid == String(appID) && $0.external_game_source.name.lowercased() == "steam" } + let unique = Dictionary(grouping: matching.map(\.game), by: \.id).compactMap { $0.value.first } + return result(unique, query: query) + } + + private static func result(_ games: [Game], query: CriticRatingQuery) -> IGDBMetadataResult { + guard games.count <= 1 else { return .init(metadata: nil, issue: .ambiguous, isStale: false) } + guard let metadata = games.first?.preview(for: query) else { return .init(metadata: nil, issue: .notFound, isStale: false) } + return .init(metadata: metadata, issue: nil, isStale: false) + } + private static func decode<T: Decodable>(_ data: Data) throws -> T { + guard data.count <= 2_097_152 else { throw IGDBError.invalidResponse } + do { return try JSONDecoder().decode(T.self, from: data) } + catch { throw IGDBError.invalidResponse } + } +} diff --git a/Sources/NXLibraryCore/Services/IGDBMetadataService.swift b/Sources/NXLibraryCore/Services/IGDBMetadataService.swift new file mode 100644 index 00000000..4e56b1c2 --- /dev/null +++ b/Sources/NXLibraryCore/Services/IGDBMetadataService.swift @@ -0,0 +1,66 @@ +import Foundation + +/// On-demand source previews, separate from both the rating cache and personal metadata choices. +public actor IGDBMetadataService { + public static let shared = IGDBMetadataService() + private let directory: URL + private let client: IGDBClient + private struct Cache: Codable { + let query: CriticRatingQuery + let metadata: IGDBMetadata? + let issue: IGDBMetadataIssue? + let fetchedAt: Date + } + public init(directory: URL = AppData.supportRoot.appendingPathComponent("metadata/igdb"), + transport: IGDBRatingService.Transport? = nil) { + self.directory = directory + client = transport.map { IGDBClient(transport: $0) } ?? .shared + } + public func load(_ query: CriticRatingQuery, credentials: IGDBCredentials, now: Date = Date()) async -> IGDBMetadataResult { + guard !Task.isCancelled else { return .init(metadata: nil, issue: .cancelled, isStale: false) } + guard !query.name.isEmpty, query.name.count <= 300 else { return .init(metadata: nil, issue: .notFound, isStale: false) } + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + guard let data = try? encoder.encode(query) else { return .init(metadata: nil, issue: .unavailable, isStale: false) } + let key = IGDBCredentials.digest(credentials.clientID + String(decoding: data, as: UTF8.self)) + let file = directory.appendingPathComponent(key + ".json") + let bytes = try? InstallationFileSnapshot.read(at: file, maximumBytes: 262_144).data + let decoded = bytes.flatMap { try? JSONDecoder().decode(Cache.self, from: $0) } + let cached = decoded.flatMap { saved -> Cache? in + guard saved.query == query else { return nil } + if let metadata = saved.metadata { + return metadata.isValid && metadata.platform == query.platform ? saved : nil + } + return [.notFound, .ambiguous].contains(saved.issue) ? saved : nil + } + let ttl: TimeInterval = cached?.metadata == nil ? 86400 : 7 * 86400 + if let cached, (0..<ttl).contains(now.timeIntervalSince(cached.fetchedAt)) { + return .init(metadata: cached.metadata, issue: cached.issue, isStale: false) + } + do { + let result = try await fetch(query, credentials: credentials) + try Task.checkCancellation() + let saved = Cache(query: query, metadata: result.metadata, issue: result.issue, fetchedAt: now) + if let data = try? encoder.encode(saved), data.count <= 262_144 { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try data.write(to: file, options: .atomic) + } catch { /* An unavailable cache never discards a valid preview. */ } + } + return result + } catch { + if Task.isCancelled || error is CancellationError { return .init(metadata: nil, issue: .cancelled, isStale: false) } + return .init(metadata: cached?.metadata, issue: .unavailable, isStale: cached?.metadata != nil) + } + } + private func fetch(_ query: CriticRatingQuery, credentials: IGDBCredentials) async throws -> IGDBMetadataResult { + if let appID = query.steamAppID { + let fields = IGDBMetadataParser.fields.split(separator: ",").map { "game." + $0 }.joined(separator: ",") + let body = "fields uid,external_game_source.name,\(fields); where uid = \"\(appID)\" & external_game_source.name = \"Steam\"; limit 10;" + let data = try await client.request("external_games", body: body, credentials: credentials) + let result = try IGDBMetadataParser.steamResult(in: data, query: query) + if result.issue != .notFound { return result } + } + let body = IGDBRatings.body(for: query, fields: IGDBMetadataParser.fields) + return try IGDBMetadataParser.result(in: await client.request("games", body: body, credentials: credentials), query: query) + } +} diff --git a/Sources/NXLibraryCore/Services/IGDBRatingService.swift b/Sources/NXLibraryCore/Services/IGDBRatingService.swift new file mode 100644 index 00000000..1448e602 --- /dev/null +++ b/Sources/NXLibraryCore/Services/IGDBRatingService.swift @@ -0,0 +1,121 @@ +import Foundation + +/// User-owned IGDB credentials only. Tokens live in memory; network errors never include server bodies. +public actor IGDBRatingService { + public typealias Transport = @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + public static let shared = IGDBRatingService() + private let directory: URL + private let client: IGDBClient + private struct Cache: Codable { + let query: CriticRatingQuery + let rating: CriticRating? + let fetchedAt: Date + let resolverVersion: Int? + } + private struct Flight { let id: UUID; let task: Task<CriticRatingResult, Never>; var waiters: Set<UUID> } + private var pending: [String: Flight] = [:] + private var workTail: Task<Void, Never>? + private var backoff: [String: Date] = [:] + + public init(directory: URL = AppData.supportRoot.appendingPathComponent("ratings/igdb"), + transport: Transport? = nil) { + self.directory = directory + self.client = transport.map { IGDBClient(transport: $0) } ?? .shared + } + public func invalidate() async { + for flight in pending.values { flight.task.cancel() } + pending.removeAll(); backoff.removeAll() + await client.resetToken() + } + public func check(_ credentials: IGDBCredentials) async throws { + let prior = workTail + let task = Task { + await prior?.value + try Task.checkCancellation() + let data = try await self.api("games", body: "fields id; limit 1;", credentials: credentials, renewToken: true) + guard (try? JSONSerialization.jsonObject(with: data)) is [[String: Any]] else { throw IGDBError.invalidResponse } + self.backoff[credentials.fingerprint] = nil + } + workTail = Task { _ = try? await task.value } + try await withTaskCancellationHandler(operation: { try await task.value }, onCancel: { task.cancel() }) + } + public func load(_ query: CriticRatingQuery, credentials: IGDBCredentials, now: Date = Date()) async -> CriticRatingResult { + let empty = CriticRatingResult(rating: nil, fetchedAt: nil, isStale: false) + guard !Task.isCancelled, !query.name.isEmpty, query.name.count <= 300 else { return empty } + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + guard let encoded = try? encoder.encode(query) else { return empty } + let key = IGDBCredentials.digest(credentials.fingerprint + String(decoding: encoded, as: UTF8.self)) + let cacheKey = IGDBCredentials.digest(credentials.clientID + String(decoding: encoded, as: UTF8.self)) + let waiter = UUID() + var flight: Flight + if let existing = pending[key] { flight = existing; flight.waiters.insert(waiter) } + else { + guard pending.count < 4 else { return empty } + let prior = workTail + let task = Task { + await prior?.value + guard !Task.isCancelled else { return empty } + return await self.resolve(query, credentials: credentials, key: cacheKey, now: now) + } + workTail = Task { _ = await task.value } + flight = Flight(id: UUID(), task: task, waiters: [waiter]) + } + pending[key] = flight + let id = flight.id, task = flight.task + return await withTaskCancellationHandler(operation: { + defer { release(key, id: id, waiter: waiter) } + let result = await task.value + return Task.isCancelled ? empty : result + }, onCancel: { Task { await self.release(key, id: id, waiter: waiter) } }) + } + private func release(_ key: String, id: UUID, waiter: UUID) { + guard var flight = pending[key], flight.id == id else { return } + flight.waiters.remove(waiter) + if flight.waiters.isEmpty { flight.task.cancel(); pending[key] = nil } + else { pending[key] = flight } + } + private func resolve(_ query: CriticRatingQuery, credentials: IGDBCredentials, key: String, now: Date) async -> CriticRatingResult { + let file = directory.appendingPathComponent(key + ".json") + let bytes = try? InstallationFileSnapshot.read(at: file, maximumBytes: 65_536).data + let decoded = bytes.flatMap { try? JSONDecoder().decode(Cache.self, from: $0) } + let cached: Cache? = { + guard let saved = decoded, saved.query == query else { return nil } + if let rating = saved.rating { + return rating.source == .igdb && rating.isValid ? saved : nil + } + return saved.resolverVersion == 2 ? saved : nil + }() + func result(_ cache: Cache?, stale: Bool) -> CriticRatingResult { + CriticRatingResult(rating: cache?.rating, fetchedAt: cache?.fetchedAt, isStale: stale && cache != nil) + } + let ttl: TimeInterval = cached?.rating == nil ? 86400 : 7 * 86400 + if let cached, (0..<ttl).contains(now.timeIntervalSince(cached.fetchedAt)) { return result(cached, stale: false) } + if let pause = backoff[credentials.fingerprint], pause > Date() { return result(cached, stale: true) } + do { + var rating: CriticRating? + if let appID = query.steamAppID { + let fields = IGDBRatings.fields.split(separator: ",").map { "game." + $0 }.joined(separator: ",") + let body = "fields uid,external_game_source.name,\(fields); where uid = \"\(appID)\" & external_game_source.name = \"Steam\"; limit 10;" + let data = try await api("external_games", body: body, credentials: credentials) + rating = try IGDBRatings.steamRating(in: data, appID: appID) + } + if rating == nil { + let data = try await api("games", body: IGDBRatings.body(for: query), credentials: credentials) + rating = try IGDBRatings.rating(in: data, query: query) + } + try Task.checkCancellation() + let value = Cache(query: query, rating: rating, fetchedAt: now, resolverVersion: 2) + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try JSONEncoder().encode(value).write(to: file, options: .atomic) + } catch { /* A valid rating still works for this appearance if cache writing is unavailable. */ } + return result(value, stale: false) + } catch { + if !Task.isCancelled && !(error is CancellationError) { backoff[credentials.fingerprint] = Date().addingTimeInterval(60) } + return result(cached, stale: true) + } + } + private func api(_ endpoint: String, body: String, credentials: IGDBCredentials, renewToken: Bool = false) async throws -> Data { + try await client.request(endpoint, body: body, credentials: credentials, renewToken: renewToken) + } +} diff --git a/Sources/NXLibraryCore/Services/IGDBRatings.swift b/Sources/NXLibraryCore/Services/IGDBRatings.swift new file mode 100644 index 00000000..72a9f4eb --- /dev/null +++ b/Sources/NXLibraryCore/Services/IGDBRatings.swift @@ -0,0 +1,85 @@ +import Foundation + +/// Exact identity, preferring external critics; user scores remain an explicitly identified fallback. +public enum IGDBRatings { + /// Fewer critic reviews are not a consensus: the explicit user average (or another source) is used instead. + static let minimumCriticReviews = 3 + static let fields = "id,name,alternative_names.name,platforms,aggregated_rating,aggregated_rating_count,rating,rating_count,url" + static func clean(_ name: String) -> String { + ["™", "®", "©"].reduce(name) { $0.replacingOccurrences(of: $1, with: "") } + .split(whereSeparator: \.isWhitespace).joined(separator: " ") + } + static func normalized(_ name: String) -> String { + String(clean(name).folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "en_US_POSIX")) + .unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) }) + } + static func body(for query: CriticRatingQuery) -> String { + body(for: query, fields: fields) + } + static func body(for query: CriticRatingQuery, fields: String) -> String { + let escaped = clean(query.name).replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + return "search \"\(escaped)\"; fields \(fields); limit 20;" + } + static func matches(name: String, aliases: [String], platforms: [Int], query: CriticRatingQuery) -> Bool { + ([name] + aliases).contains { normalized($0) == normalized(query.name) } + && platforms.contains(query.platform.igdbID) + } + static func safeGameURL(_ url: URL) -> URL? { + guard url.scheme == "https", ["www.igdb.com", "igdb.com"].contains(url.host ?? ""), + url.user == nil, url.password == nil, url.port == nil || url.port == 443, + url.path.hasPrefix("/games/") else { return nil } + return url + } + public static func rating(in data: Data, query: CriticRatingQuery) throws -> CriticRating? { + let games = try decode(data) + let matching = games.filter { game in + matches(name: game.name, aliases: (game.alternative_names ?? []).map(\.name), + platforms: game.platforms ?? [], query: query) + } + guard matching.count == 1, let game = matching.first else { return nil } + return game.resolvedRating + } + struct Game: Decodable { + struct Name: Decodable { let name: String } + let id: Int + let name: String + let alternative_names: [Name]? + let platforms: [Int]? + let aggregated_rating: Double? + let aggregated_rating_count: Int? + let rating: Double? + let rating_count: Int? + let url: URL? + var resolvedRating: CriticRating? { + guard id > 0, let url, let safe = safeGameURL(url) else { return nil } + func make(_ score: Double?, _ count: Int?, audience: CriticRating.Audience) -> CriticRating? { + let minimum = audience == .critics ? IGDBRatings.minimumCriticReviews : 1 + guard let score, score.isFinite, (0...100).contains(score), let count, count >= minimum else { return nil } + return CriticRating(score: score, source: .igdb, igdbID: id, igdbURL: safe, reviewCount: count, audience: audience) + } + return make(aggregated_rating, aggregated_rating_count, audience: .critics) + ?? make(rating, rating_count, audience: .users) + } + } + static func decode(_ data: Data) throws -> [Game] { + guard data.count <= 2_097_152 else { throw IGDBError.invalidResponse } + do { return try JSONDecoder().decode([Game].self, from: data) } catch { throw IGDBError.invalidResponse } + } + static func steamRating(in data: Data, appID: UInt32) throws -> CriticRating? { + struct External: Decodable { + struct Source: Decodable { let name: String } + let uid: String + let external_game_source: Source + let game: Game + } + guard data.count <= 2_097_152 else { throw IGDBError.invalidResponse } + let entries: [External] + do { entries = try JSONDecoder().decode([External].self, from: data) } catch { throw IGDBError.invalidResponse } + let matching = entries.filter { $0.uid == String(appID) && $0.external_game_source.name.lowercased() == "steam" } + let games = Dictionary(grouping: matching, by: { $0.game.id }) + guard games.count == 1, let game = matching.first?.game else { return nil } + // The exact external ID establishes identity even when a Mac port is absent from IGDB's platform list. + // Its returned score remains explicitly an overall game aggregate, not a Mac-specific score. + return game.resolvedRating + } +} diff --git a/Sources/NXLibraryCore/Services/KeyCheck.swift b/Sources/NXLibraryCore/Services/KeyCheck.swift index cadec62a..16053308 100644 --- a/Sources/NXLibraryCore/Services/KeyCheck.swift +++ b/Sources/NXLibraryCore/Services/KeyCheck.swift @@ -49,7 +49,7 @@ public enum KeyCheck { return ("Your keys are too old for this \(what)", "It needs keys from \(firmware) or later. Dump prod.keys again from your console.", true) case .cannotCheck(let file): - return ("Keys not checked against \(file)", "NX Library reads NSP and NSZ headers only; the porting checks the rest.", false) + return ("Keys not checked against \(file)", "Arcane reads NSP and NSZ headers only; the porting checks the rest.", false) } } } diff --git a/Sources/NXLibraryCore/Services/LaunchBoxArt.swift b/Sources/NXLibraryCore/Services/LaunchBoxArt.swift index 994bc7e9..cd2b7c6c 100644 --- a/Sources/NXLibraryCore/Services/LaunchBoxArt.swift +++ b/Sources/NXLibraryCore/Services/LaunchBoxArt.swift @@ -11,6 +11,8 @@ public enum LaunchBoxArt { public static let site = URL(string: "https://gamesdb.launchbox-app.com")! static let images = URL(string: "https://images.launchbox-app.com/")! static let gameplay = "Screenshot - Gameplay" + /// How a fan art candidate's source starts ("LaunchBox · Fanart - Background (region)"). + public static let fanartSource = "LaunchBox · Fanart - Background" /// Screenshots Details shows when Title DB has none. public static let screenshotLimit = 6 @@ -28,7 +30,8 @@ public enum LaunchBoxArt { public static func searchURL(for name: String) -> URL? { var allowed = CharacterSet.urlPathAllowed allowed.remove(charactersIn: "/?#") - let term = name.trimmingCharacters(in: .whitespacesAndNewlines) + // LaunchBox redirects mixed-case searches; construct its canonical path directly. + let term = name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() guard !term.isEmpty, let path = term.addingPercentEncoding(withAllowedCharacters: allowed) else { return nil } return URL(string: "/games/results/\(path)", relativeTo: site)?.absoluteURL } @@ -55,12 +58,22 @@ public enum LaunchBoxArt { /// `loose` (a name the player typed) falls back to the first Switch result when no title matches the name. public static func pick(_ results: [Result], names: [String], switch2: Bool, loose: Bool = false) -> Result? { let own = switch2 ? "Nintendo Switch 2" : "Nintendo Switch" + return pick(results, names: names, loose: loose, preferring: [{ $0 == own }, { $0.hasPrefix("Nintendo Switch") }]) + } + + /// The result that is this game on a computer, for a native Mac game (Steam): its Mac entry first, then + /// Windows, where LaunchBox keeps most PC art. A console entry is never taken. + public static func pick(_ results: [Result], names: [String], computer: Bool, loose: Bool = false) -> Result? { + pick(results, names: names, loose: loose, preferring: [{ $0 == "Apple Mac OS" }, { $0 == "Windows" }]) + } + + private static func pick(_ results: [Result], names: [String], loose: Bool, + preferring platforms: [(String) -> Bool]) -> Result? { let named = results.filter { ArtworkNames.matches($0.title, names) } - if let found = named.first(where: { $0.platform == own }) ?? named.first(where: { $0.platform.hasPrefix("Nintendo Switch") }) { - return found - } + for wanted in platforms { if let found = named.first(where: { wanted($0.platform) }) { return found } } guard loose else { return nil } - return results.first { $0.platform == own } ?? results.first { $0.platform.hasPrefix("Nintendo Switch") } + for wanted in platforms { if let found = results.first(where: { wanted($0.platform) }) { return found } } + return nil } /// The images a game page's payload lists, each in its slot with its preview, full file and size, credited @@ -82,6 +95,12 @@ public enum LaunchBoxArt { return list } + /// The game's Square, at full size: the icon of a game that has no app of its own yet (a Steam game still + /// installing). Never another kind cropped to a square. + public static func square(in candidates: [ArtworkCandidate]) -> URL? { + candidates.first { $0.slot == .icon && $0.source.hasPrefix("LaunchBox · Square") }.map { $0.full ?? $0.url } + } + struct PayloadImage: Equatable { let kind: String let region: String? @@ -129,12 +148,14 @@ public enum LaunchBoxArt { } /// Searches each name until one finds this game on a Switch, then reads its page. - public static func game(names: [String], switch2: Bool, loose: Bool = false, + /// `computer`: the game is a native Mac game (Steam), so its Mac or Windows entry is looked for, not Switch. + public static func game(names: [String], switch2: Bool, computer: Bool = false, loose: Bool = false, client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> Game? { for name in names { guard let url = searchURL(for: name), let data = await OnlineArtworkRequest.data(url, client: client), let html = String(data: data, encoding: .utf8), - let result = pick(results(in: html), names: names, switch2: switch2, loose: loose), + let result = computer ? pick(results(in: html), names: names, computer: true, loose: loose) + : pick(results(in: html), names: names, switch2: switch2, loose: loose), let page = URL(string: result.path, relativeTo: site)?.absoluteURL else { continue } guard let body = await OnlineArtworkRequest.data(page, client: client), let text = String(data: body, encoding: .utf8) else { return nil } diff --git a/Sources/NXLibraryCore/Services/LibraryStore.swift b/Sources/NXLibraryCore/Services/LibraryStore.swift deleted file mode 100644 index 5e3b250c..00000000 --- a/Sources/NXLibraryCore/Services/LibraryStore.swift +++ /dev/null @@ -1,141 +0,0 @@ -import Foundation - -public final class LibraryStore { - public let directory: URL - public let fileURL: URL - private let backupURL: URL - private let fm: FileManager - - public init(directory: URL, fileManager: FileManager = .default) { - self.directory = directory - self.fileURL = directory.appendingPathComponent("library.json") - self.backupURL = directory.appendingPathComponent("library.json.bak") - self.fm = fileManager - } - - private static func encoder() -> JSONEncoder { - let encoder = JSONEncoder() - encoder.dateEncodingStrategy = .iso8601 - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - return encoder - } - - private static func decoder() -> JSONDecoder { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 - return decoder - } - - public func load() throws -> LibraryFile { - try fm.createDirectory(at: directory, withIntermediateDirectories: true) - if !fm.fileExists(atPath: fileURL.path) { - if fm.fileExists(atPath: backupURL.path), - let backup = try? Self.decoder().decode(LibraryFile.self, - from: Data(contentsOf: backupURL)) { - return backup - } - return LibraryFile() - } - do { - return try Self.decoder().decode(LibraryFile.self, from: Data(contentsOf: fileURL)) - } catch { - // Move the unreadable file aside so the next save cannot write over it; the backup (or an empty - // library) carries on, and the games in it can still be recovered by hand. - keepAside() - if fm.fileExists(atPath: backupURL.path), - let backup = try? Self.decoder().decode(LibraryFile.self, from: Data(contentsOf: backupURL)) { - return backup - } - return LibraryFile() - } - } - - /// `library.json.damaged-<date>-<id>`, beside the library. - private func keepAside() { - let stamp = ISO8601DateFormatter.string(from: Date(), timeZone: .current, - formatOptions: [.withYear, .withMonth, .withDay, .withTime]) - let id = UUID().uuidString.prefix(4) - try? fm.moveItem(at: fileURL, to: directory.appendingPathComponent("library.json.damaged-\(stamp)-\(id)")) - } - - public func save(_ library: LibraryFile) throws { - try fm.createDirectory(at: directory, withIntermediateDirectories: true) - // Never rotate a corrupt main file over the last known good backup. - if let existing = try? Data(contentsOf: fileURL), - (try? Self.decoder().decode(LibraryFile.self, from: existing)) != nil { - try? fm.removeItem(at: backupURL) - try? fm.copyItem(at: fileURL, to: backupURL) - } - let data = try Self.encoder().encode(library) - try data.write(to: fileURL, options: .atomic) - // Keep a restore point even on the first save; later saves keep the - // previous valid file because it was copied before the write. - if !fm.fileExists(atPath: backupURL.path) { - try? fm.copyItem(at: fileURL, to: backupURL) - } - } - - public func merge(scanned: [PortedGame], replacingSources: Bool = false) throws -> LibraryFile { - var library = try load() - for game in scanned { - if let index = library.games.firstIndex(where: { existing in - guard let target = game.titleId else { return existing.titleId == nil } - return existing.titleId?.caseInsensitiveCompare(target) == .orderedSame - }) { - let old = library.games[index] - // Scans refresh disk observations. Application-owned state survives a scan. - var merged = old - merged.name = game.name - merged.url = game.url - merged.platform = game.platform - merged.sizeBytes = game.sizeBytes - merged.modificationDate = game.modificationDate - merged.bundleId = game.bundleId - merged.titleId = game.titleId - merged.versionString = game.versionString - merged.status = game.status - merged.toolchain = game.toolchain - merged.lastBuild = game.lastBuild - let explicitSources = replacingSources && !game.sources.isEmpty - if explicitSources || old.sources.isEmpty { - merged.sources = game.sources - } else { - let oldSourcesExist = old.sources.allSatisfy { - fm.fileExists(atPath: $0.url.path) - } - merged.sources = (oldSourcesExist || game.sources.isEmpty) - ? old.sources : game.sources - } - merged.workspacePath = explicitSources ? game.workspacePath ?? old.workspacePath : old.workspacePath ?? game.workspacePath - merged.buildCachePath = explicitSources ? game.buildCachePath ?? old.buildCachePath : old.buildCachePath ?? game.buildCachePath - if (old.status == .built || old.status == .builtSourcesMissing - || old.status == .needsRebuild), - old.url.pathExtension.lowercased() == "app", - fm.fileExists(atPath: old.url.path) { - merged.url = old.url - merged.sizeBytes = old.sizeBytes - merged.bundleId = old.bundleId ?? merged.bundleId - merged.versionString = old.versionString ?? merged.versionString - } - if old.status == .built || old.status == .builtSourcesMissing - || old.status == .needsRebuild { - if merged.sources.isEmpty { - merged.status = game.status == .built ? .built : .builtSourcesMissing - } else { - let sourcesExist = merged.sources.allSatisfy { - fm.fileExists(atPath: $0.url.path) - } - merged.status = sourcesExist ? .built : .builtSourcesMissing - } - merged.toolchain = old.toolchain - merged.lastBuild = old.lastBuild - } - library.games[index] = merged - } else { - library.games.append(game) - } - } - try save(library) - return library - } -} diff --git a/Sources/NXLibraryCore/Services/MetadataPicker.swift b/Sources/NXLibraryCore/Services/MetadataPicker.swift index 0f14263c..a2c42bec 100644 --- a/Sources/NXLibraryCore/Services/MetadataPicker.swift +++ b/Sources/NXLibraryCore/Services/MetadataPicker.swift @@ -19,7 +19,7 @@ public enum MetadataField: String, CaseIterable, Codable, Sendable { /// One value a source offers for a field. Genres are one comma-separated line. public struct MetadataOption: Equatable, Hashable, Sendable { public let field: MetadataField - /// "Nintendo store", "Title DB", "GameTDB". + /// "Nintendo store", "Title DB", "GameTDB", "IGDB". public let source: String public let value: String @@ -84,8 +84,7 @@ public final class MetadataPicks: ObservableObject { private var fileURL: URL { directory.appendingPathComponent("metadata-picks.json") } - public init(directory: URL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary")) { + public init(directory: URL = AppData.supportRoot) { self.directory = directory let url = directory.appendingPathComponent("metadata-picks.json") table = (try? Data(contentsOf: url)) diff --git a/Sources/NXLibraryCore/Services/ModFolderScanner.swift b/Sources/NXLibraryCore/Services/ModFolderScanner.swift index 1606b801..2749602a 100644 --- a/Sources/NXLibraryCore/Services/ModFolderScanner.swift +++ b/Sources/NXLibraryCore/Services/ModFolderScanner.swift @@ -17,11 +17,23 @@ public enum ModFolderScanner { /// The mods folder's visible entries, sorted by name: subfolders and stray files (an archive not unzipped yet, which /// is then shown as not a mod). Hidden entries and symlinks are left out. public static func entries(in modsFolder: URL) -> [URL] { - let fm = FileManager.default - let entries = (try? fm.contentsOfDirectory(at: modsFolder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], - options: .skipsHiddenFiles)) ?? [] - return entries + ((try? listedEntries(in: modsFolder)) ?? []) .filter { (try? $0.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == false } + } + + /// A caller removing records needs a complete listing. Read failures cannot stand for missing mods. + static func checkedEntries(in modsFolder: URL) throws -> [URL] { + try listedEntries(in: modsFolder).filter { entry in + guard let isLink = try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink else { + throw CocoaError(.fileReadUnknown) + } + return !isLink + } + } + + private static func listedEntries(in modsFolder: URL) throws -> [URL] { + try FileManager.default.contentsOfDirectory(at: modsFolder, includingPropertiesForKeys: [.isSymbolicLinkKey], + options: .skipsHiddenFiles) .sorted { $0.lastPathComponent < $1.lastPathComponent } } diff --git a/Sources/NXLibraryCore/Services/ModStore.swift b/Sources/NXLibraryCore/Services/ModStore.swift index b6f70575..9d9e575b 100644 --- a/Sources/NXLibraryCore/Services/ModStore.swift +++ b/Sources/NXLibraryCore/Services/ModStore.swift @@ -59,14 +59,16 @@ public struct ModStore { public let recordsFile: URL public let titleID: String private let canWrite: () -> Bool + private let allowsAutomaticMaintenance: Bool private let trash: (URL) throws -> Void public init(supportFolder: URL, recordsFile: URL, titleID: String, - canWrite: @escaping () -> Bool, trash: @escaping (URL) throws -> Void) { + canWrite: @escaping () -> Bool, trash: @escaping (URL) throws -> Void, allowsAutomaticMaintenance: Bool = true) { self.supportFolder = supportFolder self.recordsFile = recordsFile self.titleID = titleID.uppercased() self.canWrite = canWrite + self.allowsAutomaticMaintenance = allowsAutomaticMaintenance self.trash = trash } @@ -82,12 +84,41 @@ public struct ModStore { /// Recorded mods in their order (only those whose folder exists), then folders without a record, off, by name. public func mods() -> [LocalMod] { - let names = ModFolderScanner.entries(in: modsFolder).map(\.lastPathComponent) + mods(entries: ModFolderScanner.entries(in: modsFolder), records: loadRecords()) + } + + private func mods(entries: [URL], records: [ModRecord]) -> [LocalMod] { + let names = entries.map(\.lastPathComponent) let present = Set(names) - let recorded = loadRecords().filter { present.contains($0.folderName) } + let recorded = records.filter { present.contains($0.folderName) } let known = Set(recorded.map(\.folderName)) - return recorded.map { mod($0.folderName, on: $0.isOn) } + let list = recorded.map { mod($0.folderName, on: $0.isOn) } + names.filter { !known.contains($0) }.map { mod($0, on: false) } + return allowsAutomaticMaintenance ? list : readingLiveOverlay(list) + } + + /// A copied record orders metadata; the actual game's overlay determines what is active. + /// Reading a separate profile must neither write the overlay nor display stale enabled states. + private func readingLiveOverlay(_ list: [LocalMod]) -> [LocalMod] { + guard let text = try? String(contentsOf: envFile, encoding: .utf8) else { return list } + let value = text.components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) } + .last { $0.hasPrefix(Self.overlayKey + "=") } + .map { String($0.dropFirst(Self.overlayKey.count + 1)) } ?? "" + let paths = value.split(separator: ":").map { URL(fileURLWithPath: String($0)).standardizedFileURL.resolvingSymlinksInPath().path } + var order: [String: Int] = [:] + for (index, path) in paths.enumerated() where order[path] == nil { order[path] = index } + var observed: [(rank: Int, index: Int, item: LocalMod)] = [] + for (index, original) in list.enumerated() { + var item = original + let rank: Int? = item.romfs.flatMap { order[$0.standardizedFileURL.resolvingSymlinksInPath().path] } + item.isOn = rank != nil + observed.append((rank: rank ?? Int.max, index: index, item: item)) + } + observed.sort { first, second in + if first.rank == second.rank { return first.index < second.index } + return first.rank < second.rank + } + return observed.map { $0.item } } /// The overlay value for the mods that are on, top first; nil when none is. @@ -119,7 +150,7 @@ public struct ModStore { /// staging folders and `.installing-<UUID>.download` archives. Mods and other files stay; nothing happens while /// the game runs. public func removeLeftoverInstalls() { - guard canWrite() else { return } + guard allowsAutomaticMaintenance, canWrite() else { return } let fm = FileManager.default for name in (try? fm.contentsOfDirectory(atPath: modsFolder.path)) ?? [] where name.hasPrefix(".installing-") { try? fm.removeItem(at: modsFolder.appendingPathComponent(name)) @@ -194,13 +225,14 @@ public struct ModStore { /// Drops records whose folder is gone and brings the overlay line in line with the list. Does nothing while the /// game runs, or before NX Library has managed this game's mods (no records yet: a hand-written overlay stays). A - /// list whose overlay no longer fits the launcher's line leaves `env.txt` as it is and throws `overlayTooLong`. - public func sync() throws { + /// failed read or overlong overlay leaves both the records and `env.txt` intact. + public func sync(automatic: Bool = true) throws { + guard !automatic || allowsAutomaticMaintenance else { return } guard canWrite(), FileManager.default.fileExists(atPath: recordsFile.path) else { return } - let list = mods() + let stored = try readRecords() + let list = mods(entries: try ModFolderScanner.checkedEntries(in: modsFolder), records: stored) let value = overlay(for: list) if let value, value.utf8.count > Self.overlayLimit { throw ModStoreError.overlayTooLong } - let stored = loadRecords() let recorded = Set(stored.map(\.folderName)) let kept = list.filter { recorded.contains($0.folderName) }.map(\.folderName) if kept != stored.map(\.folderName) { @@ -249,8 +281,11 @@ public struct ModStore { } private func loadRecords() -> [ModRecord] { - guard let data = try? Data(contentsOf: recordsFile) else { return [] } - return (try? JSONDecoder().decode([ModRecord].self, from: data)) ?? [] + (try? readRecords()) ?? [] + } + + private func readRecords() throws -> [ModRecord] { + try JSONDecoder().decode([ModRecord].self, from: Data(contentsOf: recordsFile)) } private func write(records: [ModRecord]) throws { diff --git a/Sources/NXLibraryCore/Services/MoreArtworkSources.swift b/Sources/NXLibraryCore/Services/MoreArtworkSources.swift index c64ddb94..1b05fdde 100644 --- a/Sources/NXLibraryCore/Services/MoreArtworkSources.swift +++ b/Sources/NXLibraryCore/Services/MoreArtworkSources.swift @@ -37,7 +37,7 @@ public enum OnlineArtwork { static let screenshotLimit = 4 /// Asks every source that has art for `slot` (all of them for nil) at once. - public static func find(names: [String], slot: ArtworkSlot? = nil, + public static func find(names: [String], slot: ArtworkSlot? = nil, platform: CriticRatingQuery.Platform = .switch, client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> [ArtworkCandidate] { func wants(_ slots: Set<ArtworkSlot>) -> Bool { slot.map(slots.contains) ?? true } async let wikidata = wants([.logo, .cover, .background]) ? WikidataArt.find(names: names, client: client) @@ -47,7 +47,7 @@ public enum OnlineArtwork { async let xbox = wants([.cover, .background, .icon]) ? XboxStoreArt.find(names: names, client: client) : [] async let gog = wants([.logo, .cover, .background]) ? GOGArt.find(names: names, client: client) : [] async let europe = wants([.background, .icon]) ? NintendoEuropeArt.find(names: names, client: client) : [] - async let gamesDB = wants([.logo, .cover, .background]) ? TheGamesDBArt.find(names: names, client: client) : [] + async let gamesDB = wants([.logo, .cover, .background]) ? TheGamesDBArt.find(names: names, platform: platform, client: client) : [] async let commons = wants([.logo]) ? MediaWikiLogos.commons.candidates(names: names, client: client) : [] async let wikis = wants([.logo]) ? fanWikiLogos(names: names, client: client) : [] async let wallhaven = wants([.background]) ? WallhavenGameArt.find(names: names, client: client) : [] @@ -331,31 +331,8 @@ public enum WikidataArt { } /// TheGamesDB, the community database: clear logos, box fronts, fan art and -/// screenshots for Switch games, read from its public pages. +/// screenshots for the requested game platform, read from its public pages. public enum TheGamesDBArt { - static let switchPlatform = "4971" - - public static func searchURL(for name: String) -> URL? { - let term = SteamStoreArt.plain(name) - guard !term.isEmpty else { return nil } - var components = URLComponents(string: "https://thegamesdb.net/search.php")! - components.queryItems = [.init(name: "name", value: term), .init(name: "platform_id[]", value: switchPlatform)] - return components.url - } - - /// The first result card whose title is the game's. - public static func gameID(in html: String, matching names: [String]) -> Int? { - for card in html.components(separatedBy: "game.php?id=").dropFirst() { - let id = Int(card.prefix { $0.isNumber }) - guard let id, let footer = card.range(of: "card-footer"), - let open = card.range(of: "<p>", range: footer.upperBound..<card.endIndex), - let close = card.range(of: "</p>", range: open.upperBound..<card.endIndex) else { continue } - let title = decodeEntities(String(card[open.upperBound..<close.lowerBound])) - if ArtworkNames.matches(title, names) { return id } - } - return nil - } - public static func gameURL(id: Int) -> URL { URL(string: "https://thegamesdb.net/game.php?id=\(id)")! } @@ -378,12 +355,26 @@ public enum TheGamesDBArt { + OnlineArtwork.screenshots(byKind["screenshot"] ?? [], source: "TheGamesDB screenshot") } - public static func find(names: [String], client: ArtworkHTTPClient) async -> [ArtworkCandidate] { - guard let name = names.first, let url = searchURL(for: name), - let data = await OnlineArtworkRequest.data(url, client: client), - let id = gameID(in: String(decoding: data, as: UTF8.self), matching: names), - let page = await OnlineArtworkRequest.data(gameURL(id: id), client: client) else { return [] } - return candidates(in: String(decoding: page, as: UTF8.self), id: id) + public static func find(names: [String], platform: CriticRatingQuery.Platform = .switch, client: ArtworkHTTPClient) async -> [ArtworkCandidate] { + guard let name = names.first else { return [] } + let query = CriticRatingQuery(name: name, platform: platform) + for platformName in MetadataDatabase.theGamesDB.platforms(for: query) { + guard !Task.isCancelled, let url = DatabaseMetadataParser.gamesDBSearch(query: query, platform: platformName), + let data = await OnlineArtworkRequest.data(url, client: client) else { continue } + let html = String(decoding: data, as: UTF8.self) + let matches = Set(names.flatMap { alias in + DatabaseMetadataParser.gamesDBCandidates(in: html, query: CriticRatingQuery(name: alias, platform: platform), platform: platformName) + }) + guard matches.count <= 1 else { return [] } + guard let match = matches.first else { continue } + guard !Task.isCancelled, let data = await OnlineArtworkRequest.data(match.url, client: client) else { return [] } + let page = String(decoding: data, as: UTF8.self) + let verified = DatabaseMetadataParser.theGamesDB(in: page, query: CriticRatingQuery(name: match.title, platform: platform), page: match.url) + guard verified.preview?.platform == platformName, + let id = URLComponents(url: match.url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "id" })?.value.flatMap(Int.init) else { return [] } + return candidates(in: page, id: id) + } + return [] } private static func decodeEntities(_ text: String) -> String { diff --git a/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift b/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift index f769cc32..6e591e7b 100644 --- a/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift +++ b/Sources/NXLibraryCore/Services/NUPSourceCatalog.swift @@ -55,6 +55,9 @@ try: name = raw.decode('utf-8', 'replace'); break if name: break print(f'title {app:016X}') + if getattr(n, 'application', None) is not None: + print(f'application {n.application:016X}') + print(f'aoc_base {n.aoc_base:016X}') print('name ' + name.encode().hex()) if base is not None: print(f'base {n.tree_bytes(base.root)}') for v, k in sorted(vers.items()): print(f'update {v} {n.tree_bytes(k.root)}') @@ -86,13 +89,37 @@ except pack_nup.Error as e: var updates: [DetectedSource] = [] var dlcs: [DetectedSource] = [] let lines = output.split(separator: "\n").map { $0.split(separator: " ").map(String.init) } + guard lines.filter({ $0.first == "title" }).count == 1 else { + throw EngineSourceError.invalidContainer("invalid program title ID") + } for fields in lines where fields.first == "title" { - guard fields.count == 2, let id = UInt64(fields[1], radix: 16), id != 0, id & 0xFFF == 0 else { + guard fields.count == 2, fields[1].count == 16, let id = UInt64(fields[1], radix: 16), id != 0 else { throw EngineSourceError.invalidContainer("invalid base title ID") } title = id } guard let title else { throw EngineSourceError.invalidContainer("no base title ID") } + let applications = lines.filter { $0.first == "application" } + let aocBases = lines.filter { $0.first == "aoc_base" } + let selection: NUPProgramSelection? + if !applications.isEmpty || !aocBases.isEmpty { + guard applications.count == 1, aocBases.count == 1, + applications[0].count == 2, aocBases[0].count == 2, + applications[0][1].count == 16, aocBases[0][1].count == 16, + let application = UInt64(applications[0][1], radix: 16), + let aocBase = UInt64(aocBases[0][1], radix: 16) else { + throw EngineSourceError.invalidContainer("invalid program metadata") + } + let program = NUPProgramSelection(programID: title, applicationID: application, addOnContentBaseID: aocBase) + guard program.isValid else { throw EngineSourceError.invalidContainer("invalid program metadata") } + selection = program + } else { + guard title & 0xFFF == 0 else { throw EngineSourceError.invalidContainer("invalid base title ID") } + selection = nil + } + let (legacyAOCBase, aocOverflow) = title.addingReportingOverflow(0x1000) + guard selection != nil || !aocOverflow else { throw EngineSourceError.invalidContainer("invalid DLC base") } + let aocBase = selection?.addOnContentBaseID ?? legacyAOCBase for fields in lines { switch fields.first { case "name": @@ -103,14 +130,16 @@ except pack_nup.Error as e: guard fields.count == 3, let version = Int(fields[1]), version > 0, let bytes = Int64(fields[2]) else { throw EngineSourceError.invalidContainer("invalid update record") } - updates.append(DetectedSource(url: nup, kind: .update, titleId: title + 0x800, version: version, - sizeBytes: bytes, layout: .container)) + let (updateID, overflow) = title.addingReportingOverflow(0x800) + guard !overflow else { throw EngineSourceError.invalidContainer("invalid update record") } + updates.append(DetectedSource(url: nup, kind: .update, titleId: updateID, version: version, + sizeBytes: bytes, layout: .container, nupProgram: selection)) case "dlc": - guard fields.count == 3, let id = UInt64(fields[1], radix: 16), id > title + 0x1000, - id - title - 0x1000 <= 2000, let bytes = Int64(fields[2]) else { + guard fields.count == 3, let id = UInt64(fields[1], radix: 16), id > aocBase, + id - aocBase <= 2000, let bytes = Int64(fields[2]) else { throw EngineSourceError.invalidContainer("invalid DLC record") } - dlcs.append(DetectedSource(url: nup, kind: .dlc, titleId: id, sizeBytes: bytes, layout: .container)) + dlcs.append(DetectedSource(url: nup, kind: .dlc, titleId: id, sizeBytes: bytes, layout: .container, nupProgram: selection)) default: break } @@ -124,7 +153,7 @@ except pack_nup.Error as e: let profileName = profile?.split(separator: "\n").first(where: { $0.hasPrefix("name\t") }).map { String($0.dropFirst(5)) } let name = profileName ?? (nacpName.isEmpty ? identity : nacpName) let base = hasBase - ? DetectedSource(url: nup, kind: .base, titleId: title, version: 0, sizeBytes: fileSize, layout: .container) + ? DetectedSource(url: nup, kind: .base, titleId: title, version: 0, sizeBytes: fileSize, layout: .container, nupProgram: selection) : nil return DetectedGame(baseTitleId: title, name: name, base: base, updates: updates.sorted { ($0.version ?? 0) < ($1.version ?? 0) }, dlcs: dlcs) diff --git a/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift b/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift index 6d57c84d..26f9eb35 100644 --- a/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift +++ b/Sources/NXLibraryCore/Services/NXNativeGameSettings.swift @@ -56,7 +56,7 @@ public struct NXNativeGameSettings { store: SavedChoicesStore = SystemSavedChoices(), supportDirectory: URL = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/nxnative"), - preferences: UserDefaults = .standard) -> NXNativeGameSettings? { + preferences: UserDefaults = AppData.preferences) -> NXNativeGameSettings? { guard let titleId = game.titleId, !titleId.isEmpty else { return nil } let plist = game.url.appendingPathComponent("Contents/Info.plist") guard let data = try? Data(contentsOf: plist), diff --git a/Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift b/Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift new file mode 100644 index 00000000..52f4ac99 --- /dev/null +++ b/Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift @@ -0,0 +1,70 @@ +import Foundation + +/// The established nxnative scan merge, shared with the legacy store. It only +/// handles nxnative payloads; other catalog integrations never enter this path. +enum NXNativeLibraryMerge { + static func merge(scanned: [PortedGame], into existing: [PortedGame], replacingSources: Bool = false, + fileManager fm: FileManager = .default) -> [PortedGame] { + var games = existing + for game in scanned { + if let index = games.firstIndex(where: { existing in + if existing.id == game.id { return true } + guard let target = game.titleId else { return false } + return existing.titleId?.caseInsensitiveCompare(target) == .orderedSame + }) { + let old = games[index] + // Scans refresh disk observations. Application-owned state survives a scan. + var merged = old + merged.name = game.name + merged.url = game.url + merged.platform = game.platform + merged.sizeBytes = game.sizeBytes + merged.modificationDate = game.modificationDate + merged.bundleId = game.bundleId + merged.titleId = game.titleId + merged.versionString = game.versionString + merged.status = game.status + merged.toolchain = game.toolchain + merged.lastBuild = game.lastBuild + let explicitSources = replacingSources && !game.sources.isEmpty + if explicitSources || old.sources.isEmpty { + merged.sources = game.sources + } else { + let oldSourcesExist = old.sources.allSatisfy { + fm.fileExists(atPath: $0.url.path) + } + merged.sources = (oldSourcesExist || game.sources.isEmpty) + ? old.sources : game.sources + } + merged.workspacePath = explicitSources ? game.workspacePath ?? old.workspacePath : old.workspacePath ?? game.workspacePath + merged.buildCachePath = explicitSources ? game.buildCachePath ?? old.buildCachePath : old.buildCachePath ?? game.buildCachePath + if (old.status == .built || old.status == .builtSourcesMissing + || old.status == .needsRebuild), + old.url.pathExtension.lowercased() == "app", + fm.fileExists(atPath: old.url.path) { + merged.url = old.url + merged.sizeBytes = old.sizeBytes + merged.bundleId = old.bundleId ?? merged.bundleId + merged.versionString = old.versionString ?? merged.versionString + } + if old.status == .built || old.status == .builtSourcesMissing + || old.status == .needsRebuild { + if merged.sources.isEmpty { + merged.status = game.status == .built ? .built : .builtSourcesMissing + } else { + let sourcesExist = merged.sources.allSatisfy { + fm.fileExists(atPath: $0.url.path) + } + merged.status = sourcesExist ? .built : .builtSourcesMissing + } + merged.toolchain = old.toolchain + merged.lastBuild = old.lastBuild + } + games[index] = merged + } else { + games.append(game) + } + } + return games + } +} diff --git a/Sources/NXLibraryCore/Services/NewestEngine.swift b/Sources/NXLibraryCore/Services/NewestEngine.swift index 3397513c..e9600f37 100644 --- a/Sources/NXLibraryCore/Services/NewestEngine.swift +++ b/Sources/NXLibraryCore/Services/NewestEngine.swift @@ -1,6 +1,6 @@ import Foundation -/// The player's choice to build with nxnative main before NX Library has tested it (Settings → Engine, +/// The player's choice to build with nxnative main before NX Library has tested it (Settings → Setup and engine, /// Newest engine). NX Library never follows main by itself: the choice is explicit, turns the untested-toolchain /// override on, and records every build it makes as untested. public struct NewestEngineChoice: Codable, Equatable, Sendable { @@ -30,7 +30,7 @@ public enum NewestEngineReadiness: Equatable, Sendable { case unknown } -/// A button on Settings → Engine's Newest engine row. +/// A button on Settings → Setup and engine's Newest engine row. public enum NewestEngineAction: Equatable, Sendable { case useNewest, update, backToTested } @@ -43,29 +43,29 @@ public enum UpstreamCommitMark: Equatable, Sendable { /// The words every screen uses for the newest engine, so Settings and Setup say the same thing. public enum NewestEngineCopy { public static var note: String { - L10n.text("Newest nxnative, not yet tested by NX Library. It usually works, but something may not. ") - + L10n.text("Its new features reach NX Library in a future version.") + L10n.text("Newest nxnative, not yet tested by Arcane. It usually works, but something may not. ") + + L10n.text("Its new features reach Arcane in a future version.") } public static func ahead(_ count: Int) -> String { L10n.count("%lld commits ahead", count, arguments: []) } - /// Settings → Engine, Newest engine row, while the tested engine is in use. + /// Settings → Setup and engine, Newest engine row, while the tested engine is in use. public static func offer(commit: String, aheadBy: Int) -> String { - L10n.format("Build with nxnative main (%@, %@) before NX Library has tested it.", [String(describing: (commit.prefix(7))), String(describing: (ahead(aheadBy)))]) + L10n.format("Build with nxnative main (%@, %@) before Arcane has tested it.", [String(describing: (commit.prefix(7))), String(describing: (ahead(aheadBy)))]) } public static func needsNewerApp(metal: String) -> String { - L10n.format("The newest nxnative needs Metal %@, so it needs a newer NX Library.", [String(describing: (metal))]) + L10n.format("The newest nxnative needs Metal %@, so it needs a newer Arcane.", [String(describing: (metal))]) } /// Setup's engine card while the newest engine is in use (the note is its description). public static func setupDetail(choice: NewestEngineChoice, tested: String) -> String { - L10n.format("At %@, %@ of the tested %@, chosen in Settings → Engine.", [String(describing: (choice.shortCommit)), String(describing: (ahead(choice.aheadBy))), String(describing: (tested.prefix(7)))]) + L10n.format("At %@, %@ of the tested %@, chosen in Settings → Setup and engine.", [String(describing: (choice.shortCommit)), String(describing: (ahead(choice.aheadBy))), String(describing: (tested.prefix(7)))]) } - /// Settings → Engine, Newest engine row, while main is past the commit in use. `aheadBy` counts from the pin, + /// Settings → Setup and engine, Newest engine row, while main is past the commit in use. `aheadBy` counts from the pin, /// like the choice's own count; a rewritten main (not further ahead) gets no count. public static func update(choice: NewestEngineChoice, main: String, aheadBy: Int) -> String { let newer = aheadBy - choice.aheadBy @@ -74,7 +74,7 @@ public enum NewestEngineCopy { } public static var info: String { - L10n.text("Builds games with nxnative main instead of the engine this NX Library is tested with. ") + L10n.text("Builds games with nxnative main instead of the engine this version of Arcane is tested with. ") + L10n.text("Builds are recorded as untested and the untested-toolchain override stays on. ") + L10n.text("Back to tested returns to the tested engine; games you built keep playing.") } @@ -89,7 +89,7 @@ public enum NewestEngineError: Error, Equatable, LocalizedError { public var errorDescription: String? { switch self { case .localChanges: - return L10n.text("The engine folder has changed files. NX Library never touches them: put them aside, then try again.") + return L10n.text("The engine folder has changed files. Arcane never touches them: put them aside, then try again.") case .downloadFailed: return L10n.text("The newest nxnative could not be downloaded. Check the connection, then try again.") case .needsNewerApp(let metal): @@ -128,7 +128,7 @@ public enum NewestEngine { guard let url = lockURL(commit: commit) else { return nil } var request = URLRequest(url: url) request.timeoutInterval = 20 - request.setValue("NXLibrary/0.1", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") guard let (data, http) = try? await client.data(for: request), (200..<300).contains(http.statusCode) else { return nil } @@ -155,7 +155,7 @@ public enum NewestEngine { return (primary, actions.dropFirst().first) } - /// Tags for Settings → Engine's upstream list (newest first): the commit the newest engine is at is In use, + /// Tags for Settings → Setup and engine's upstream list (newest first): the commit the newest engine is at is In use, /// those above it New. Nothing on the tested engine, or when the commit in use is not in the list. public static func marks(_ commits: [UpstreamCommit], inUse: String?) -> [String: UpstreamCommitMark] { guard let inUse, let index = commits.firstIndex(where: { $0.sha == inUse }) else { return [:] } diff --git a/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift b/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift index 9315284e..da0d1c89 100644 --- a/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift +++ b/Sources/NXLibraryCore/Services/NintendoStoreMetadata.swift @@ -132,8 +132,7 @@ public final class NintendoStoreMetadataService: @unchecked Sendable { public init( client: NintendoStoreHTTPClient = URLSessionNintendoStoreClient(), - cacheDirectory: URL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/metadata"), + cacheDirectory: URL = AppData.supportRoot.appendingPathComponent("metadata"), fileManager: FileManager = .default ) { self.client = client @@ -476,7 +475,7 @@ public final class NintendoStoreMetadataService: @unchecked Sendable { request.setValue(Self.appID, forHTTPHeaderField: "X-Algolia-Application-Id") request.setValue(key, forHTTPHeaderField: "X-Algolia-API-Key") request.setValue("application/json", forHTTPHeaderField: "Content-Type") - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") request.httpBody = try JSONEncoder().encode(body) let (data, http) = try await client.data(for: request) guard (200..<300).contains(http.statusCode) else { @@ -490,7 +489,7 @@ public final class NintendoStoreMetadataService: @unchecked Sendable { private func fetchProductPage(_ url: URL) async throws -> PageProduct { var request = URLRequest(url: url) request.timeoutInterval = 15 - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") let (data, http) = try await client.data(for: request) guard (200..<300).contains(http.statusCode) else { throw NintendoStoreError.http(http.statusCode) diff --git a/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift b/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift index 2685e901..da40895b 100644 --- a/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift +++ b/Sources/NXLibraryCore/Services/OnlineArtworkSources.swift @@ -180,7 +180,7 @@ enum OnlineArtworkRequest { static func data(_ url: URL, client: ArtworkHTTPClient) async -> Data? { var request = URLRequest(url: url) request.timeoutInterval = 15 - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") guard let (data, http) = try? await client.data(for: request), (200..<300).contains(http.statusCode) else { return nil } diff --git a/Sources/NXLibraryCore/Services/PlaySessionStore.swift b/Sources/NXLibraryCore/Services/PlaySessionStore.swift index d4ab5d81..4fb30886 100644 --- a/Sources/NXLibraryCore/Services/PlaySessionStore.swift +++ b/Sources/NXLibraryCore/Services/PlaySessionStore.swift @@ -7,7 +7,14 @@ public final class PlaySessionStore: ObservableObject, PlayHistory { /// Play time and last start of sessions trimmed from `sessions`, per game, /// so totals and last-played survive trimming. @Published public private(set) var carried: [UUID: CarriedPlaytime] = [:] + /// Another launcher's own total for a game (Steam's), with when it was seen. Not persisted here. + @Published public private(set) var external: [UUID: ExternalPlaytime] = [:] + /// When each game's external value was seen, kept while its total is hidden (source off, another + /// account, launch), so trimming still keeps the part after it. + public private(set) var trimReferences: [UUID: Date] = [:] public static let maxSessions = 200 + /// Each game whose session just started (not a duplicate start). + public let starts = PassthroughSubject<UUID, Never>() public private(set) var loadError: String? /// Recent sessions, a bare `[PlaySession]` array as in every earlier version, @@ -31,8 +38,7 @@ public final class PlaySessionStore: ObservableObject, PlayHistory { } public static func defaultURL() -> URL { - FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/play-sessions.json") + AppData.supportRoot.appendingPathComponent("play-sessions.json") } @discardableResult @@ -49,6 +55,23 @@ public final class PlaySessionStore: ObservableObject, PlayHistory { sessions.append(session) let folded = trim() save(totals: folded) + starts.send(game.id) + return true + } + + /// A session for a game of another integration, which observes its own process. `sourceID` is the + /// qualified identity ("steam-570"), never a made-up Nintendo title ID. The session is ended by its + /// owner, and a restart closes it at its last heartbeat. A game found already + /// running when its owner starts watching is not a new start: `announces: false` keeps it off `starts`. + @discardableResult + public func start(gameID: UUID, sourceID: String, announces: Bool = true) -> Bool { + if isRunning(gameID: gameID) { return false } + let date = now() + sessions.append(PlaySession(gameID: gameID, titleID: sourceID, bundleID: nil, + startedAt: date, lastHeartbeatAt: date)) + let folded = trim() + save(totals: folded) + if announces { starts.send(gameID) } return true } @@ -58,15 +81,18 @@ public final class PlaySessionStore: ObservableObject, PlayHistory { save() } - public func end(gameID: UUID) { + /// Ends the game's running sessions and returns them, ended. + @discardableResult + public func end(gameID: UUID) -> [PlaySession] { let date = now() - var changed = false + var ended: [PlaySession] = [] for index in sessions.indices where sessions[index].gameID == gameID && sessions[index].isActive { sessions[index].endedAt = date sessions[index].lastHeartbeatAt = date - changed = true + ended.append(sessions[index]) } - if changed { save() } + if !ended.isEmpty { save() } + return ended } /// Ends the game's running sessions and returns them, ended. @@ -101,18 +127,39 @@ public final class PlaySessionStore: ObservableObject, PlayHistory { if changed { save() } } + /// Sets the external totals; publishes only a change. + public func setExternal(_ values: [UUID: ExternalPlaytime]) { + if values != external { external = values } + } + + public func setTrimReferences(_ values: [UUID: Date]) { trimReferences = values } + + /// With an external total: that total plus the part of this store's sessions after it was seen + /// (it already counts what came before), including trimmed sessions' part after that same value. + /// Without one: carried time plus every session. public func totalDuration(for gameID: UUID) -> TimeInterval { + totalDuration(for: gameID, with: external[gameID]) + } + + /// The total under a given external value (nil: none), whatever is published. + public func totalDuration(for gameID: UUID, with external: ExternalPlaytime?) -> TimeInterval { let date = now() - return sessions - .filter { $0.gameID == gameID } - .reduce(carried[gameID]?.duration ?? 0) { total, session in + let own = sessions.filter { $0.gameID == gameID } + guard let base = external else { + return own.reduce(carried[gameID]?.duration ?? 0) { total, session in total + max(0, (session.endedAt ?? date).timeIntervalSince(session.startedAt)) } + } + let trimmed = carried[gameID].flatMap { $0.externalSince == base.since ? $0.afterExternal : nil } ?? 0 + return own.reduce(base.duration + trimmed) { total, session in + let end = min(session.endedAt ?? date, date) + return total + max(0, end.timeIntervalSince(max(session.startedAt, base.since))) + } } public func lastPlayed(for gameID: UUID) -> Date? { let recent = sessions.filter { $0.gameID == gameID }.map(\.startedAt).max() - return [recent, carried[gameID]?.lastPlayed].compactMap { $0 }.max() + return [recent, carried[gameID]?.lastPlayed, external[gameID]?.lastPlayed].compactMap { $0 }.max() } public func isRunning(gameID: UUID) -> Bool { @@ -132,6 +179,12 @@ public final class PlaySessionStore: ObservableObject, PlayHistory { var entry = carried[session.gameID] ?? CarriedPlaytime(duration: 0, lastPlayed: session.startedAt) entry.duration += session.duration ?? 0 entry.lastPlayed = max(entry.lastPlayed, session.startedAt) + // The part after an external value was seen is not in that value yet: keep it, tied to that value. + if let since = external[session.gameID]?.since ?? trimReferences[session.gameID] { + if entry.externalSince != since { entry.externalSince = since; entry.afterExternal = 0 } + let end = session.endedAt ?? session.lastHeartbeatAt + entry.afterExternal += max(0, end.timeIntervalSince(max(session.startedAt, since))) + } carried[session.gameID] = entry } let droppedIDs = Set(dropped.map(\.id)) @@ -192,14 +245,41 @@ public final class PlaySessionStore: ObservableObject, PlayHistory { } } -/// Play time folded out of the recent-session list for one game. +/// A game's total as another launcher keeps it, and when NX Library first saw that value. +public struct ExternalPlaytime: Equatable, Sendable { + public let duration: TimeInterval + public let lastPlayed: Date? + public let since: Date + + public init(duration: TimeInterval, lastPlayed: Date?, since: Date) { + self.duration = duration + self.lastPlayed = lastPlayed + self.since = since + } +} + +/// Play time folded out of the recent-session list for one game. `afterExternal` is the part of it after +/// the external value seen at `externalSince` (Steam's), which that value does not count yet. public struct CarriedPlaytime: Codable, Equatable { public var duration: TimeInterval public var lastPlayed: Date + public var externalSince: Date? + public var afterExternal: TimeInterval - public init(duration: TimeInterval, lastPlayed: Date) { + public init(duration: TimeInterval, lastPlayed: Date, externalSince: Date? = nil, afterExternal: TimeInterval = 0) { self.duration = duration self.lastPlayed = lastPlayed + self.externalSince = externalSince + self.afterExternal = afterExternal + } + + private enum CodingKeys: String, CodingKey { case duration, lastPlayed, externalSince, afterExternal } + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + duration = try c.decode(TimeInterval.self, forKey: .duration) + lastPlayed = try c.decode(Date.self, forKey: .lastPlayed) + externalSince = try c.decodeIfPresent(Date.self, forKey: .externalSince) + afterExternal = try c.decodeIfPresent(TimeInterval.self, forKey: .afterExternal) ?? 0 } } diff --git a/Sources/NXLibraryCore/Services/SaveFileIO.swift b/Sources/NXLibraryCore/Services/SaveFileIO.swift index 64c8213a..0051ac92 100644 --- a/Sources/NXLibraryCore/Services/SaveFileIO.swift +++ b/Sources/NXLibraryCore/Services/SaveFileIO.swift @@ -72,7 +72,7 @@ extension SaveFiles { } return portableAttributes(result) } - static func inventory(_ directory: URL, slot: SaveSlot) throws -> [SaveInventoryEntry] { + static func inventory(_ directory: URL, slot: SaveSlot, componentRoot: Bool = true) throws -> [SaveInventoryEntry] { try safePath(directory) guard exists(directory) else { return [] } var entries: [SaveInventoryEntry] = [] @@ -82,6 +82,10 @@ extension SaveFiles { guard lstat(url.path, &st) == 0 else { throw SaveFailure.changed } let kind = st.st_mode & S_IFMT guard kind == S_IFDIR || kind == S_IFREG else { throw SaveFailure.unsafePath } + if relative.isEmpty && componentRoot { + guard (kind == S_IFDIR) == slot.isDirectory else { throw SaveFailure.unsafePath } + if slot == .users, st.st_size > 64 * 1024 { throw SaveFailure.invalidSnapshot } + } guard relative.isEmpty || validRelative(relative) else { throw SaveFailure.unsafePath } var digest = "" if kind == S_IFREG { @@ -101,7 +105,6 @@ extension SaveFiles { } } try visit(directory, relative: "") - guard entries.first?.isDirectory == true else { throw SaveFailure.unsafePath } return entries } static func inventory(_ location: SaveLocation) throws -> [SaveInventoryEntry] { diff --git a/Sources/NXLibraryCore/Services/SaveRestorePreview.swift b/Sources/NXLibraryCore/Services/SaveRestorePreview.swift index cd751426..76d9cbd4 100644 --- a/Sources/NXLibraryCore/Services/SaveRestorePreview.swift +++ b/Sources/NXLibraryCore/Services/SaveRestorePreview.swift @@ -13,7 +13,7 @@ extension SaveSnapshotStore { do { let source = try directory(snapshotID: snapshot.id, titleID: location.titleID) for slot in SaveSlot.allCases where snapshot.presentSlots.contains(slot) { - let name = slot == .account ? "save" : "save_device" + let name = slot.fileName try io.copy(source.appendingPathComponent(name), staging.appendingPathComponent(name)) } try verifyContents(snapshot, directory: staging) diff --git a/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift b/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift index a727b959..9b36a0f6 100644 --- a/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift +++ b/Sources/NXLibraryCore/Services/SaveSnapshotStore.swift @@ -54,10 +54,12 @@ public final class SaveSnapshotStore { defer { try? SaveFiles.remove(temp) } let slots = Set(before.map(\.slot)) for slot in SaveSlot.allCases where slots.contains(slot) { - try io.copy(location.directory(slot), temp.appendingPathComponent(slot == .account ? "save" : "save_device")) + try io.copy(location.directory(slot), temp.appendingPathComponent(slot.fileName)) } guard try SaveFiles.inventory(location) == before else { throw SaveFailure.changed } - let snapshot = SaveSnapshot(id: id, identity: identity, created: created, reason: reason, presentSlots: slots, entries: before) + let version = slots.allSatisfy(\.isLegacy) ? 1 : 2 + let snapshot = SaveSnapshot(schemaVersion: version, id: id, identity: identity, created: created, + reason: reason, presentSlots: slots, entries: before) try verifyContents(snapshot, directory: temp) try SaveFiles.syncTree(temp) try SaveFiles.durableWrite(snapshot, to: temp.appendingPathComponent("manifest.json")) @@ -92,7 +94,7 @@ public final class SaveSnapshotStore { try SaveFiles.safePath(file) guard let data = try? SaveFiles.readRegular(file, limit: 32 * 1024 * 1024), let snapshot = try? JSONDecoder().decode(SaveSnapshot.self, from: data), - snapshot.schemaVersion == 1, snapshot.identity.titleID == titleID.uppercased(), + snapshot.hasSupportedSchema, snapshot.identity.titleID == titleID.uppercased(), snapshot.entries.allSatisfy({ ($0.path.isEmpty || SaveFiles.validRelative($0.path)) && $0.byteCount >= 0 && $0.byteCount < Int64.max / Int64(max(1, snapshot.entries.count)) }) else { throw SaveFailure.invalidSnapshot } // Read older schema-1 backups portably too: provenance is assigned by macOS to a copy. var portable = snapshot @@ -102,12 +104,13 @@ public final class SaveSnapshotStore { internal func verifyContents(_ snapshot: SaveSnapshot, directory: URL) throws { var actual: [SaveInventoryEntry] = [] for slot in SaveSlot.allCases { - actual += try SaveFiles.inventory(directory.appendingPathComponent(slot == .account ? "save" : "save_device"), slot: slot) + actual += try SaveFiles.inventory(directory.appendingPathComponent(slot.fileName), slot: slot) } guard actual == snapshot.entries, Set(actual.map(\.slot)) == snapshot.presentSlots else { throw SaveFailure.invalidSnapshot } } public func currentInventory(location: SaveLocation) throws -> [SaveInventoryEntry] { try SaveFiles.inventory(location) } public func stageImport(source: URL, slot: SaveSlot, location: SaveLocation) throws -> SaveImportPreview { + guard slot.isLegacy else { throw SaveFailure.unsafePath } try location.validate() try SaveFiles.safePath(source) let source = try RyujinxSaveFolder.payload(for: source, titleID: location.titleID) @@ -133,6 +136,7 @@ public final class SaveSnapshotStore { try SaveFiles.inventory(location) == preview.currentEntries else { throw SaveFailure.changed } } private func validateStaging(_ preview: SaveImportPreview, location: SaveLocation) throws { + guard preview.slot.isLegacy else { throw SaveFailure.unsafePath } guard preview.staging.path == location.root.appendingPathComponent(".nxlibrary-save-preview-\(preview.id)").path else { throw SaveFailure.unsafePath } try location.validate(); try SaveFiles.safePath(preview.staging) } diff --git a/Sources/NXLibraryCore/Services/SaveTransaction.swift b/Sources/NXLibraryCore/Services/SaveTransaction.swift index 6bf69da2..8c55789f 100644 --- a/Sources/NXLibraryCore/Services/SaveTransaction.swift +++ b/Sources/NXLibraryCore/Services/SaveTransaction.swift @@ -12,7 +12,29 @@ public final class SaveTransaction { let titleID: String let before: UUID let after: [SaveInventoryEntry] + /// Missing in historical journals, which mutate the two legacy slots. + var mutatedSlots: Set<SaveSlot>? + /// Durable deletion intent: remaining staging entries must be a subset of these verified trees. + var cleanupArtifacts: [String: [SaveInventoryEntry]]? = nil var committed: Bool + + var observedSlots: [SaveSlot] { version == 1 ? SaveSlot.legacyCases : SaveSlot.allCases } + var mutationOrder: [SaveSlot] { observedSlots.filter { mutatedSlots?.contains($0) ?? true } } + var isValid: Bool { + guard version == 1 || version == 2, version == 1 || mutatedSlots != nil, + !mutationOrder.isEmpty else { return false } + let allowed = Set(observedSlots) + guard mutatedSlots?.isSubset(of: allowed) ?? true, + after.allSatisfy({ allowed.contains($0.slot) && ($0.path.isEmpty || SaveFiles.validRelative($0.path)) + && $0.byteCount >= 0 && ($0.slot != .users || (!$0.isDirectory && $0.path.isEmpty && $0.byteCount <= 65536)) }) + else { return false } + guard Set(after.map { $0.slot.rawValue + ":" + $0.path }).count == after.count else { return false } + for (name, entries) in cleanupArtifacts ?? [:] { + guard let slot = mutationOrder.first(where: { name == $0.rawValue || name == "rollback-" + $0.rawValue }), + entries.allSatisfy({ $0.slot == slot && ($0.path.isEmpty || SaveFiles.validRelative($0.path)) }) else { return false } + } + return true + } } public init(store: SaveSnapshotStore, isRunning: @escaping () -> Bool, validateAccess: @escaping () throws -> Void = {}) { @@ -34,9 +56,8 @@ public final class SaveTransaction { public func importSave(_ preview: SaveImportPreview, location: SaveLocation, identity: SaveIdentity) throws -> SaveSnapshot { try check(location) try store.validate(preview, location: location) - return try replace(location: location, identity: identity, reason: .beforeImport, - desired: { slot in slot == preview.slot ? preview.staging : location.directory(slot) }, - revalidate: { try self.store.validate(preview, location: location) }) + return try replace(location: location, identity: identity, reason: .beforeImport, slots: [preview.slot], + desired: { _ in preview.staging }, revalidate: { try self.store.validate(preview, location: location) }) } @discardableResult public func restore(_ snapshot: SaveSnapshot, location: SaveLocation, identity: SaveIdentity) throws -> SaveSnapshot { @@ -50,22 +71,24 @@ public final class SaveTransaction { try check(location) guard identity.titleID == location.titleID else { throw SaveFailure.invalidSnapshot } try store.validateRestore(preview, location: location) - return try replace(location: location, identity: identity, reason: .beforeRestore, - desired: { preview.staging.appendingPathComponent($0 == .account ? "save" : "save_device") }, + let slots = preview.snapshot.schemaVersion == 1 ? SaveSlot.legacyCases : SaveSlot.allCases + return try replace(location: location, identity: identity, reason: .beforeRestore, slots: slots, + desired: { preview.staging.appendingPathComponent($0.fileName) }, revalidate: { try self.store.validateRestore(preview, location: location) }) } - private func replace(location: SaveLocation, identity: SaveIdentity, reason: SaveSnapshotReason, + private func replace(location: SaveLocation, identity: SaveIdentity, reason: SaveSnapshotReason, slots: [SaveSlot], desired: (SaveSlot) -> URL, revalidate: () throws -> Void) throws -> SaveSnapshot { guard !Self.needsRecovery(location: location) else { throw SaveFailure.recoveryRequired } guard !SaveFiles.exists(location.cloudPullJournal) else { throw SaveFailure.cloudPullPending } try check(location) let previous = try SaveFiles.inventory(location) - let id = UUID(); let stage = staging(id, location) + let id = UUID(), stage = staging(id, location) try SaveFiles.makeDirectory(stage) var journalWritten = false defer { if !journalWritten { try? SaveFiles.remove(stage) } } var after: [SaveInventoryEntry] = [] for slot in SaveSlot.allCases { + guard slots.contains(slot) else { after += previous.filter { $0.slot == slot }; continue } let source = desired(slot) let entries = try SaveFiles.inventory(source, slot: slot) after += entries @@ -76,32 +99,45 @@ public final class SaveTransaction { try SaveFiles.syncTree(next) } } + try SaveFiles.syncDirectory(stage) try revalidate(); try check(location) guard try SaveFiles.inventory(location) == previous else { throw SaveFailure.changed } let safety = try store.create(location: location, identity: identity, reason: reason) guard safety.entries == previous else { throw SaveFailure.changed } try revalidate(); try check(location) guard try SaveFiles.inventory(location) == previous else { throw SaveFailure.changed } - var journal = Journal(id: id, titleID: location.titleID, before: safety.id, after: after, committed: false) + let version = previous.allSatisfy({ $0.slot.isLegacy }) && after.allSatisfy({ $0.slot.isLegacy }) + && slots.allSatisfy(\.isLegacy) ? 1 : 2 + var journal = Journal(version: version, id: id, titleID: location.titleID, before: safety.id, + after: after, mutatedSlots: Set(slots), committed: false) try SaveFiles.durableWrite(journal, to: journalURL(location)) journalWritten = true do { try io.afterMutation("journal") - for slot in SaveSlot.allCases { + for slot in journal.mutationOrder { try check(location) - try swap(stage.appendingPathComponent(slot.rawValue), into: location.directory(slot)) + try io.afterMutation("before-" + slot.rawValue) + let next = stage.appendingPathComponent(slot.rawValue) + guard try SaveFiles.inventory(location.directory(slot), slot: slot) == previous.filter({ $0.slot == slot }), + try SaveFiles.inventory(next, slot: slot) == after.filter({ $0.slot == slot }) else { throw SaveFailure.changed } + try swap(next, into: location.directory(slot)) try SaveFiles.syncDirectory(location.root) + try SaveFiles.syncDirectory(stage) + // A writer holding an old inode may change it even after the path is exchanged. + guard try SaveFiles.inventory(next, slot: slot) == previous.filter({ $0.slot == slot }) else { throw SaveFailure.changed } try io.afterMutation(slot.rawValue) } + try check(location) guard try SaveFiles.inventory(location) == after else { throw SaveFailure.recoveryRequired } + try validateArtifacts(journal, location, before: previous) journal.committed = true try SaveFiles.durableWrite(journal, to: journalURL(location)) try io.afterMutation("committed") - try cleanup(journal, location) + try cleanup(journal, location, before: previous, expected: after) return safety } catch { throw SaveFailure.recoveryRequired } } - /// Moves a next tree in, retaining the old one in staging. An absent next tree means restore absence. + /// Moves a next tree/file in, retaining the old one in staging. Absence restores absence. private func swap(_ next: URL, into destination: URL) throws { try SaveFiles.safePath(next); try SaveFiles.safePath(destination) if SaveFiles.exists(next) && SaveFiles.exists(destination) { @@ -112,6 +148,26 @@ public final class SaveTransaction { try FileManager.default.moveItem(at: destination, to: next) } } + private func observedInventory(_ journal: Journal, _ location: SaveLocation) throws -> [SaveInventoryEntry] { + try location.validate() + return try journal.observedSlots.flatMap { try SaveFiles.inventory(location.directory($0), slot: $0) } + } + /// Never delete unrecognized or externally changed data from a managed transaction folder. + private func validateArtifacts(_ journal: Journal, _ location: SaveLocation, before: [SaveInventoryEntry]) throws { + let stage = staging(journal.id, location) + try SaveFiles.safePath(stage) + guard SaveFiles.exists(stage) else { return } + let portableAfter = journal.after.map(\.portable) + for child in try FileManager.default.contentsOfDirectory(at: stage, includingPropertiesForKeys: nil) { + guard let slot = journal.mutationOrder.first(where: { + child.lastPathComponent == $0.rawValue || child.lastPathComponent == "rollback-" + $0.rawValue + }) else { throw SaveFailure.recoveryRequired } + let entries = try SaveFiles.inventory(child, slot: slot) + guard entries == before.filter({ $0.slot == slot }) || entries == portableAfter.filter({ $0.slot == slot }) else { + throw SaveFailure.recoveryRequired + } + } + } public func recover(location: SaveLocation) throws { guard Self.needsRecovery(location: location) else { return } // Recovery is local rollback, not a new import: cloud settings do not prevent it. @@ -119,43 +175,118 @@ public final class SaveTransaction { try location.validate() let file = journalURL(location) try SaveFiles.safePath(file) - guard let data = try? SaveFiles.readRegular(file, limit: 32 * 1024 * 1024), - let journal = try? JSONDecoder().decode(Journal.self, from: data), journal.version == 1, - journal.titleID == location.titleID, - journal.after.allSatisfy({ $0.path.isEmpty || SaveFiles.validRelative($0.path) }) else { throw SaveFailure.recoveryRequired } + guard let data = try? SaveFiles.readRegular(file, limit: 96 * 1024 * 1024), + let journal = try? JSONDecoder().decode(Journal.self, from: data), journal.isValid, + journal.titleID == location.titleID else { throw SaveFailure.recoveryRequired } let original = try store.verify(snapshotID: journal.before, titleID: location.titleID) + guard journal.version != 1 || original.schemaVersion == 1 else { throw SaveFailure.recoveryRequired } let expectedAfter = journal.after.map(\.portable) - if journal.committed { - guard try SaveFiles.inventory(location) == expectedAfter else { throw SaveFailure.recoveryRequired } - } else { + let before = original.entries.filter { journal.observedSlots.contains($0.slot) } + if journal.cleanupArtifacts != nil || journal.committed { + try cleanup(journal, location, before: before, expected: journal.committed ? expectedAfter : before) + return + } + if try observedInventory(journal, location) == before { + try cleanup(journal, location, before: before, expected: before) + return + } + try validateArtifacts(journal, location, before: before) + do { let backup = try store.directory(snapshotID: journal.before, titleID: location.titleID) let stage = staging(journal.id, location) try SaveFiles.makeDirectory(stage) - for slot in SaveSlot.allCases { + for slot in journal.mutationOrder { guard !isRunning() else { throw SaveFailure.running } let current = try SaveFiles.inventory(location.directory(slot), slot: slot) - let before = original.entries.filter { $0.slot == slot } + let previous = before.filter { $0.slot == slot } let after = expectedAfter.filter { $0.slot == slot } - if current == before { continue } - // Never destroy a save modified outside this transaction. + if current == previous { continue } guard current == after else { throw SaveFailure.recoveryRequired } - let rollback = stage.appendingPathComponent("rollback-\(slot.rawValue)") + let rollback = stage.appendingPathComponent("rollback-" + slot.rawValue) + try validateArtifacts(journal, location, before: before) try SaveFiles.remove(rollback) if original.presentSlots.contains(slot) { - try io.copy(backup.appendingPathComponent(slot == .account ? "save" : "save_device"), rollback) - guard try SaveFiles.inventory(rollback, slot: slot) == before else { throw SaveFailure.invalidSnapshot } + try io.copy(backup.appendingPathComponent(slot.fileName), rollback) + guard try SaveFiles.inventory(rollback, slot: slot) == previous else { throw SaveFailure.invalidSnapshot } try SaveFiles.syncTree(rollback) } try location.validate() + guard try SaveFiles.inventory(location.directory(slot), slot: slot) == after else { throw SaveFailure.recoveryRequired } try swap(rollback, into: location.directory(slot)) try SaveFiles.syncDirectory(location.root) + try SaveFiles.syncDirectory(stage) + guard try SaveFiles.inventory(rollback, slot: slot) == after else { throw SaveFailure.recoveryRequired } + try io.afterMutation("recovery-" + slot.rawValue) } - guard try SaveFiles.inventory(location) == original.entries else { throw SaveFailure.recoveryRequired } + guard try observedInventory(journal, location) == before else { throw SaveFailure.recoveryRequired } + } + try cleanup(journal, location, before: before, expected: before) + } + + private func isSubset(_ actual: [SaveInventoryEntry], of expected: [SaveInventoryEntry]) -> Bool { + var byPath: [String: SaveInventoryEntry] = [:] + for entry in expected.map(\.portable) { + guard byPath.updateValue(entry, forKey: entry.path) == nil else { return false } } - try cleanup(journal, location) + return actual.allSatisfy { byPath[$0.path] == $0 } } - private func cleanup(_ journal: Journal, _ location: SaveLocation) throws { - try SaveFiles.remove(staging(journal.id, location)) + + private func cleanupRecord(_ journal: Journal, _ location: SaveLocation, before: [SaveInventoryEntry]) throws -> [String: [SaveInventoryEntry]] { + let stage = staging(journal.id, location) + try SaveFiles.safePath(stage) + guard SaveFiles.exists(stage) else { return [:] } + var records: [String: [SaveInventoryEntry]] = [:] + for child in try FileManager.default.contentsOfDirectory(at: stage, includingPropertiesForKeys: nil) { + guard let slot = journal.mutationOrder.first(where: { + child.lastPathComponent == $0.rawValue || child.lastPathComponent == "rollback-" + $0.rawValue + }) else { throw SaveFailure.recoveryRequired } + let actual = try SaveFiles.inventory(child, slot: slot) + let candidates = [before.filter { $0.slot == slot }, journal.after.filter { $0.slot == slot }.map(\.portable)] + guard let known = candidates.first(where: { isSubset(actual, of: $0) }) else { throw SaveFailure.recoveryRequired } + records[child.lastPathComponent] = known + } + return records + } + + private func removeCleanupArtifacts(_ journal: Journal, _ location: SaveLocation) throws { + let stage = staging(journal.id, location) + try SaveFiles.safePath(stage) + guard SaveFiles.exists(stage), let records = journal.cleanupArtifacts else { return } + let children = try FileManager.default.contentsOfDirectory(at: stage, includingPropertiesForKeys: nil) + guard children.allSatisfy({ records[$0.lastPathComponent] != nil }) else { throw SaveFailure.recoveryRequired } + for child in children { + let expected = records[child.lastPathComponent]! + guard let slot = journal.mutationOrder.first(where: { child.lastPathComponent == $0.rawValue || child.lastPathComponent == "rollback-" + $0.rawValue }), + isSubset(try SaveFiles.inventory(child, slot: slot), of: expected) else { throw SaveFailure.recoveryRequired } + // Reverse preorder: children before their parent. unlink/rmdir never recursively delete surprises. + for entry in expected.reversed() { + guard !isRunning() else { throw SaveFailure.running } + let url = entry.path.isEmpty ? child : child.appendingPathComponent(entry.path) + try SaveFiles.safePath(url) + guard SaveFiles.exists(url) else { continue } + var actual = try SaveFiles.inventory(url, slot: slot, componentRoot: false) + guard actual.count == 1 else { throw SaveFailure.recoveryRequired } + actual[0].path = entry.path + guard actual[0] == entry.portable else { throw SaveFailure.recoveryRequired } + let result = entry.isDirectory ? rmdir(url.path) : unlink(url.path) + guard result == 0 else { throw SaveFailure.recoveryRequired } + try io.afterMutation("cleanup-item") + } + } + guard rmdir(stage.path) == 0 else { throw SaveFailure.recoveryRequired } + try io.afterMutation("cleanup-stage") + } + + private func cleanup(_ journal: Journal, _ location: SaveLocation, before: [SaveInventoryEntry], expected: [SaveInventoryEntry]) throws { + guard !isRunning(), try observedInventory(journal, location) == expected else { throw SaveFailure.recoveryRequired } + var cleaning = journal + if cleaning.cleanupArtifacts == nil { + cleaning.cleanupArtifacts = try cleanupRecord(journal, location, before: before) + try SaveFiles.durableWrite(cleaning, to: journalURL(location)) + try io.afterMutation("cleanup") + } + try removeCleanupArtifacts(cleaning, location) + try SaveFiles.syncDirectory(location.root) try SaveFiles.remove(journalURL(location)) try SaveFiles.syncDirectory(location.root) } @@ -164,16 +295,17 @@ public final class SaveTransaction { extension SaveFiles { static func syncTree(_ directory: URL) throws { try safePath(directory) - let children = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey]) - for child in children { - if try child.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true { try syncTree(child) } - else { - let fd = open(child.path, O_RDONLY | O_NOFOLLOW) - guard fd >= 0 else { throw SaveFailure.io("Could not persist the staged save.") } - let result = fsync(fd); close(fd) - guard result == 0 else { throw SaveFailure.io("Could not persist the staged save.") } - } + var info = stat() + guard lstat(directory.path, &info) == 0 else { throw SaveFailure.changed } + if (info.st_mode & S_IFMT) == S_IFREG { + let fd = open(directory.path, O_RDONLY | O_NOFOLLOW) + guard fd >= 0 else { throw SaveFailure.io("Could not persist the staged save.") } + defer { close(fd) } + guard fsync(fd) == 0 else { throw SaveFailure.io("Could not persist the staged save.") } + } else { + guard (info.st_mode & S_IFMT) == S_IFDIR else { throw SaveFailure.unsafePath } + for child in try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) { try syncTree(child) } + try syncDirectory(directory) } - try syncDirectory(directory) } } diff --git a/Sources/NXLibraryCore/Services/ScreenshotFallback.swift b/Sources/NXLibraryCore/Services/ScreenshotFallback.swift index bb6b413d..7f76cd0f 100644 --- a/Sources/NXLibraryCore/Services/ScreenshotFallback.swift +++ b/Sources/NXLibraryCore/Services/ScreenshotFallback.swift @@ -19,8 +19,7 @@ public struct ScreenshotFallbackStore: Sendable { public let directory: URL - public init(directory: URL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/metadata/launchbox-screenshots")) { + public init(directory: URL = AppData.supportRoot.appendingPathComponent("metadata/launchbox-screenshots")) { self.directory = directory } diff --git a/Sources/NXLibraryCore/Services/SeleneImporter.swift b/Sources/NXLibraryCore/Services/SeleneImporter.swift index 496b85f9..13f7b12d 100644 --- a/Sources/NXLibraryCore/Services/SeleneImporter.swift +++ b/Sources/NXLibraryCore/Services/SeleneImporter.swift @@ -70,8 +70,7 @@ public struct SeleneImporter { "activation", "CloseAdditionalView", "Alert"] public static var defaultDestination: URL { - URL(fileURLWithPath: NSHomeDirectory()) - .appendingPathComponent("Library/Application Support/NXLibrary/SeleneImports") + AppData.supportRoot.appendingPathComponent("SeleneImports") } public let destination: URL diff --git a/Sources/NXLibraryCore/Services/SourceCatalog.swift b/Sources/NXLibraryCore/Services/SourceCatalog.swift index a962f7d3..4f6bb9ec 100644 --- a/Sources/NXLibraryCore/Services/SourceCatalog.swift +++ b/Sources/NXLibraryCore/Services/SourceCatalog.swift @@ -9,10 +9,11 @@ public struct DetectedSource: Identifiable, Equatable { public var sizeBytes: Int64 public var layout: SourceLayout public var requiresTitleSelection: Bool + public var nupProgram: NUPProgramSelection? public init(id: UUID = UUID(), url: URL, kind: SourceKind, titleId: UInt64, version: Int? = nil, sizeBytes: Int64, layout: SourceLayout = .package, - requiresTitleSelection: Bool = false) { + requiresTitleSelection: Bool = false, nupProgram: NUPProgramSelection? = nil) { self.id = id self.url = url self.kind = kind @@ -21,6 +22,7 @@ public struct DetectedSource: Identifiable, Equatable { self.sizeBytes = sizeBytes self.layout = layout self.requiresTitleSelection = requiresTitleSelection + self.nupProgram = nupProgram } } diff --git a/Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift b/Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift new file mode 100644 index 00000000..cf74591f --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift @@ -0,0 +1,50 @@ +import Foundation +import Darwin + +typealias InstallationDirectoryReader = @Sendable (URL, Int, () -> Bool) throws -> InstallationDirectorySnapshot + +/// One directory-read boundary shared by library inventory and app discovery. +struct InstallationDirectorySnapshot: Sendable { + let entries: [URL] + let isComplete: Bool + let observation: InstallationFileObservation + + static func read(at url: URL, maximumEntries: Int, cancelled: () -> Bool) throws -> Self { + if cancelled() { throw CancellationError() } + let fd = Darwin.open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK | O_DIRECTORY) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + guard let directory = fdopendir(fd) else { + let failure = errno + Darwin.close(fd) + throw POSIXError(POSIXErrorCode(rawValue: failure) ?? .EIO) + } + defer { closedir(directory) } + let observation = try InstallationFileObservation.capture(fileDescriptor: fd, url: url, expectedType: mode_t(S_IFDIR)) + let budget = min(max(0, maximumEntries), 10_000) + var entries: [URL] = [] + var examined = 0 + var complete = true + while true { + if cancelled() { throw CancellationError() } + errno = 0 + guard let entry = readdir(directory) else { + guard errno == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + break + } + let count = Int(entry.pointee.d_namlen) + let name = withUnsafePointer(to: &entry.pointee.d_name) { pointer in + pointer.withMemoryRebound(to: UInt8.self, capacity: count) { + String(bytes: UnsafeBufferPointer(start: $0, count: count), encoding: .utf8) + } + } + guard let name, !name.isEmpty else { throw InstallationFileReadError.invalidText } + if name == "." || name == ".." { continue } + guard examined < budget else { complete = false; break } + examined += 1 + if name.hasPrefix(".") { continue } + entries.append(url.appendingPathComponent(name)) + } + try observation.verifyUnchanged() + return Self(entries: entries, isComplete: complete, observation: observation) + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift b/Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift new file mode 100644 index 00000000..ae0d5de9 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift @@ -0,0 +1,101 @@ +import Foundation +import Darwin + +enum InstallationFileReadError: Error { case tooLarge, unsafeFile, sourceChanged, invalidText } + +/// Retain only this small identity after parsing, not all source-file contents. +struct InstallationFileObservation: Equatable, Sendable { + let url: URL + private let identity: Identity? + private let fileType: mode_t + + fileprivate struct Identity: Equatable, Sendable { + let device: Int32 + let inode: UInt64 + let size: Int64 + let modifiedSeconds: Int + let modifiedNanoseconds: Int + let changedSeconds: Int + let changedNanoseconds: Int + + init(_ status: stat) { + device = status.st_dev + inode = status.st_ino + size = status.st_size + modifiedSeconds = status.st_mtimespec.tv_sec + modifiedNanoseconds = status.st_mtimespec.tv_nsec + changedSeconds = status.st_ctimespec.tv_sec + changedNanoseconds = status.st_ctimespec.tv_nsec + } + } + + private init(url: URL, status: stat) { + self.url = url + identity = Identity(status) + fileType = status.st_mode & mode_t(S_IFMT) + } + private init(absentURL: URL) { url = absentURL; identity = nil; fileType = 0 } + var byteCount: Int64 { identity?.size ?? 0 } + + static func capture(fileDescriptor: Int32, url: URL, expectedType: mode_t = mode_t(S_IFREG)) throws -> Self { + var status = stat() + guard fstat(fileDescriptor, &status) == 0, status.st_mode & mode_t(S_IFMT) == expectedType else { + throw InstallationFileReadError.unsafeFile + } + return Self(url: url, status: status) + } + + static func absent(at url: URL) throws -> Self { + var status = stat() + if lstat(url.path, &status) == 0 { throw InstallationFileReadError.sourceChanged } + guard errno == ENOENT else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + return Self(absentURL: url) + } + + func verifyUnchanged() throws { + var current = stat() + let result = lstat(url.path, ¤t) + if identity == nil { + guard result == -1, errno == ENOENT else { throw InstallationFileReadError.sourceChanged } + return + } + guard result == 0, current.st_mode & mode_t(S_IFMT) == fileType, Identity(current) == identity else { + throw InstallationFileReadError.sourceChanged + } + } +} + +/// Bounded read from a regular file with no final symlink following. +/// The same identity is checked after the read and again before scan publication. +struct InstallationFileSnapshot { + let data: Data + let observation: InstallationFileObservation + + static func read(at url: URL, maximumBytes: Int) throws -> Self { + guard maximumBytes >= 0, maximumBytes < Int.max else { throw InstallationFileReadError.tooLarge } + let handle = try openReadOnly(url) + defer { try? handle.close() } + let observation = try InstallationFileObservation.capture(fileDescriptor: handle.fileDescriptor, url: url) + guard observation.byteCount >= 0, observation.byteCount <= Int64(maximumBytes) else { throw InstallationFileReadError.tooLarge } + let bytes = try handle.read(upToCount: maximumBytes + 1) ?? Data() + guard bytes.count <= maximumBytes else { throw InstallationFileReadError.tooLarge } + try observation.verifyUnchanged() + guard Int64(bytes.count) == observation.byteCount else { throw InstallationFileReadError.sourceChanged } + return Self(data: bytes, observation: observation) + } + + static func openReadOnly(_ url: URL) throws -> FileHandle { + let fd = Darwin.open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + return FileHandle(fileDescriptor: fd, closeOnDealloc: true) + } + + func verifyUnchanged() throws { try observation.verifyUnchanged() } + + var text: String { + get throws { + guard let result = String(data: data, encoding: .utf8) else { throw InstallationFileReadError.invalidText } + return result + } + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift b/Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift new file mode 100644 index 00000000..81abceff --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift @@ -0,0 +1,144 @@ +import Foundation + +public enum MacExecutableArchitecture: String, Hashable, Codable, Sendable { case arm64, x86_64 } + +public enum NativeMacApplicationError: Error, Equatable { + case invalidBundle, unsafePath, invalidExecutable, metadataTooLarge +} + +/// Evidence about an installed app, independent of Steam and of any launch operation. +public struct NativeMacApplication: Equatable, Sendable { + public let url: URL + public let executableURL: URL + public let bundleIdentifier: String? + public let name: String + public let architectures: Set<MacExecutableArchitecture> + public let isDeclaredGame: Bool + let fileObservations: [InstallationFileObservation] + + public static func inspect(at app: URL, within root: URL) throws -> Self { + let fm = FileManager.default + let root = root.resolvingSymlinksInPath().standardizedFileURL + let app = app.resolvingSymlinksInPath().standardizedFileURL + guard app.pathExtension.lowercased() == "app", isWithin(app, root: root) else { + throw NativeMacApplicationError.unsafePath + } + let plist = app.appendingPathComponent("Contents/Info.plist").resolvingSymlinksInPath().standardizedFileURL + guard isWithin(plist, root: app) else { throw NativeMacApplicationError.unsafePath } + let metadata: InstallationFileSnapshot + do { metadata = try InstallationFileSnapshot.read(at: plist, maximumBytes: 1024 * 1024) } + catch InstallationFileReadError.tooLarge { throw NativeMacApplicationError.metadataTooLarge } + let data = metadata.data + guard let info = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], + info["CFBundlePackageType"] as? String == "APPL", + info["LSRequiresIPhoneOS"] as? Bool != true, + let executable = info["CFBundleExecutable"] as? String, + !executable.isEmpty, executable != ".", executable != "..", + !executable.contains("/"), !executable.contains("\\") else { throw NativeMacApplicationError.invalidBundle } + if let platforms = info["CFBundleSupportedPlatforms"] as? [String], + !platforms.isEmpty, !platforms.contains("MacOSX") { throw NativeMacApplicationError.invalidBundle } + let executableURL = app.appendingPathComponent("Contents/MacOS").appendingPathComponent(executable) + .resolvingSymlinksInPath().standardizedFileURL + guard isWithin(executableURL, root: app) else { throw NativeMacApplicationError.unsafePath } + guard fm.isExecutableFile(atPath: executableURL.path) else { throw NativeMacApplicationError.invalidExecutable } + let executableEvidence = try MacExecutableHeader.inspect(at: executableURL) + let bundleID = (info["CFBundleIdentifier"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let name = [info["CFBundleDisplayName"] as? String, info["CFBundleName"] as? String] + .compactMap { $0 }.first { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + ?? app.deletingPathExtension().lastPathComponent + let category = info["LSApplicationCategoryType"] as? String ?? "" + try metadata.verifyUnchanged() + return Self(url: app, executableURL: executableURL, bundleIdentifier: bundleID, name: name, + architectures: executableEvidence.architectures, isDeclaredGame: gameCategories.contains(category), + fileObservations: [metadata.observation, executableEvidence.observation]) + } + + static func isWithin(_ url: URL, root: URL) -> Bool { + url.path == root.path || url.path.hasPrefix(root.path.hasSuffix("/") ? root.path : root.path + "/") + } + + private static let gameCategories: Set<String> = Set([ + "games", "action-games", "adventure-games", "arcade-games", "board-games", "card-games", + "casino-games", "dice-games", "educational-games", "family-games", "kids-games", "music-games", + "puzzle-games", "racing-games", "role-playing-games", "simulation-games", "sports-games", + "strategy-games", "trivia-games", "word-games" + ].map { "public.app-category." + $0 }) +} + +/// Reads only bounded Mach-O headers and fat architecture tables, never executable contents. +private enum MacExecutableHeader { + static func inspect(at url: URL) throws -> (architectures: Set<MacExecutableArchitecture>, observation: InstallationFileObservation) { + let file = try InstallationFileSnapshot.openReadOnly(url) + defer { try? file.close() } + let observation = try InstallationFileObservation.capture(fileDescriptor: file.fileDescriptor, url: url) + let size = try file.seekToEnd() + let result = try architectures(file: file, size: size) + try observation.verifyUnchanged() + return (result, observation) + } + + private static func architectures(file: FileHandle, size: UInt64) throws -> Set<MacExecutableArchitecture> { + func read(_ offset: UInt64, _ count: Int) throws -> Data { + guard offset <= size, UInt64(count) <= size - offset else { throw NativeMacApplicationError.invalidExecutable } + try file.seek(toOffset: offset) + guard let bytes = try file.read(upToCount: count), bytes.count == count else { + throw NativeMacApplicationError.invalidExecutable + } + return bytes + } + let first = try read(0, 8) + let magic = word(first, 0, bigEndian: true) + let isFat64 = magic == 0xcafebabf || magic == 0xbfbafeca + let isFat = isFat64 || magic == 0xcafebabe || magic == 0xbebafeca + if !isFat { return [try thin(try read(0, 32), expectedCPU: nil)] } + let bigEndian = magic == 0xcafebabe || magic == 0xcafebabf + let count = Int(word(first, 4, bigEndian: bigEndian)) + guard (1...64).contains(count) else { throw NativeMacApplicationError.invalidExecutable } + let stride = isFat64 ? 32 : 20 + let table = try read(8, count * stride) + let tableEnd = UInt64(8 + count * stride) + var result: Set<MacExecutableArchitecture> = [] + for index in 0..<count { + let start = index * stride + let cpu = word(table, start, bigEndian: bigEndian) + let offset = isFat64 ? longWord(table, start + 8, bigEndian: bigEndian) + : UInt64(word(table, start + 8, bigEndian: bigEndian)) + let length = isFat64 ? longWord(table, start + 16, bigEndian: bigEndian) + : UInt64(word(table, start + 12, bigEndian: bigEndian)) + guard offset >= tableEnd, offset <= size, length >= 32, length <= size - offset else { + throw NativeMacApplicationError.invalidExecutable + } + if cpu == 0x01000007 || cpu == 0x0100000c { + result.insert(try thin(try read(offset, 32), expectedCPU: cpu)) + } + } + guard !result.isEmpty else { throw NativeMacApplicationError.invalidExecutable } + return result + } + + private static func thin(_ data: Data, expectedCPU: UInt32?) throws -> MacExecutableArchitecture { + let magic = word(data, 0, bigEndian: true) + guard magic == 0xcffaedfe || magic == 0xfeedfacf else { throw NativeMacApplicationError.invalidExecutable } + let bigEndian = magic == 0xfeedfacf + let cpu = word(data, 4, bigEndian: bigEndian) + guard word(data, 12, bigEndian: bigEndian) == 2, expectedCPU == nil || cpu == expectedCPU else { + throw NativeMacApplicationError.invalidExecutable + } + switch cpu { + case 0x01000007: return .x86_64 + case 0x0100000c: return .arm64 + default: throw NativeMacApplicationError.invalidExecutable + } + } + + private static func word(_ data: Data, _ offset: Int, bigEndian: Bool) -> UInt32 { + let shifts = bigEndian ? [24, 16, 8, 0] : [0, 8, 16, 24] + return (0..<4).reduce(0) { $0 | UInt32(data[offset + $1]) << shifts[$1] } + } + + private static func longWord(_ data: Data, _ offset: Int, bigEndian: Bool) -> UInt64 { + let first = UInt64(word(data, offset, bigEndian: bigEndian)) + let second = UInt64(word(data, offset + 4, bigEndian: bigEndian)) + return bigEndian ? (first << 32) | second : first | (second << 32) + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift b/Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift new file mode 100644 index 00000000..dd8cbed4 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift @@ -0,0 +1,60 @@ +import Foundation + +/// Steam's public achievement data that needs no key: how many players have each achievement +/// (`GetGlobalAchievementPercentagesForApp`) and the icons on Steam's CDN. Fetched and cached by +/// `SteamMetadataService.achievementPercents` and `.achievementIcon`. +public enum SteamAchievementRarity { + static let host = "api.steampowered.com" + static let path = "/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/" + /// How long the percentages are reused before Steam is asked again. + public static let freshFor: TimeInterval = 86_400 + + public static func url(appID: UInt32) -> URL { + URL(string: "https://\(host)\(path)?gameid=\(appID)")! + } + + /// `achievementpercentages.achievements[{name, percent}]`, the percent as a number or a numeric string. + public static func decode(_ data: Data) throws -> [String: Double] { + struct Body: Decodable { + struct Inner: Decodable { let achievements: [Entry] } + struct Entry: Decodable { + let name: String + let percent: Double + enum Keys: String, CodingKey { case name, percent } + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Keys.self) + name = try container.decode(String.self, forKey: .name) + if let number = try? container.decode(Double.self, forKey: .percent) { + percent = number + } else if let number = Double(try container.decode(String.self, forKey: .percent)) { + percent = number + } else { + throw DecodingError.dataCorruptedError(forKey: .percent, in: container, debugDescription: "percent") + } + } + } + let achievementpercentages: Inner + } + let entries = try JSONDecoder().decode(Body.self, from: data).achievementpercentages.achievements + // "nan" and "inf" parse as numbers but are no rarity; clamping would keep NaN and turn infinity into 100. + return Dictionary(entries.filter { $0.percent.isFinite }.map { ($0.name, min(max($0.percent, 0), 100)) }, + uniquingKeysWith: { first, _ in first }) + } + + /// An icon's address on Steam's CDN, for a plain file name from Steam's schema (`<hash>.jpg`); anything else is refused. + /// Steam's community-assets host: the older `steamcommunity/public/images` path answers 404 for icons added + /// recently (17 of Crimson Desert's 82, 16 Nov 2026), and this one serves both those and older games' icons. + public static func iconURL(appID: UInt32, file: String) -> URL? { + let lower = file.lowercased() + guard file.count > 4, file.count <= 128, !file.contains("/"), !file.contains("\\"), !file.hasPrefix("."), + file.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "_" || $0 == "-") }), + lower.hasSuffix(".jpg") || lower.hasSuffix(".png") else { return nil } + return SteamMetadata.safeImage(URL(string: "https://shared.akamai.steamstatic.com/community_assets/images/apps/\(appID)/\(file)")) + } +} + +/// The percentages as cached on disk. +struct SteamAchievementPercentsCache: Codable { + let fetchedAt: Date + let percents: [String: Double] +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift b/Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift new file mode 100644 index 00000000..8f57a8e1 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift @@ -0,0 +1,94 @@ +import Foundation + +/// One Steam achievement as this Mac's Steam cache knows it, for the current account. +public struct SteamAchievement: Equatable, Sendable { + /// Steam's API name (`ACH_0039`), the key for its rarity. + public let apiName: String + public let name: String + public let description: String + public let hidden: Bool + /// File names on Steam's CDN (`<hash>.jpg`), color and gray. + public let icon: String? + public let grayIcon: String? + public let unlockedAt: Date? + + public init(apiName: String, name: String, description: String, hidden: Bool, icon: String?, grayIcon: String?, unlockedAt: Date?) { + self.apiName = apiName; self.name = name; self.description = description; self.hidden = hidden + self.icon = icon; self.grayIcon = grayIcon; self.unlockedAt = unlockedAt + } +} + +/// Reads a game's achievements from Steam's cache in `appcache/stats`: the schema (`UserGameStatsSchema_<AppID>.bin`: +/// names and descriptions in every language, hidden, icons) and the current account's stats +/// (`UserGameStats_<account>_<AppID>.bin`), of which only `AchievementTimes` is read. Nothing is written, logged +/// or kept beyond the returned values. The format is Valve's and undocumented: anything unexpected throws. +public enum SteamAchievementReader { + public static func schemaURL(root: URL, appID: UInt32) -> URL { + root.appendingPathComponent("appcache/stats/UserGameStatsSchema_\(appID).bin") + } + + public static func statsURL(root: URL, account: UInt32, appID: UInt32) -> URL { + root.appendingPathComponent("appcache/stats/UserGameStats_\(account)_\(appID).bin") + } + + /// The game's achievements, or nil when there is no schema, no signed-in account, or no stats file for that + /// account (it never loaded this game's stats here: the numbers would be wrong). Throws on unreadable files. + public static func read(root: URL, appID: UInt32, language: String) throws -> [SteamAchievement]? { + let schema = schemaURL(root: root, appID: appID) + guard FileManager.default.fileExists(atPath: schema.path), + let account = try SteamPlaytimeReader.accountID(root: root) else { return nil } + let stats = statsURL(root: root, account: account, appID: appID) + guard FileManager.default.fileExists(atPath: stats.path) else { return nil } + return try achievements(schema: SteamBinaryKeyValues.parse(data(at: schema)), + stats: SteamBinaryKeyValues.parse(data(at: stats)), appID: appID, language: language) + } + + static func achievements(schema: [KeyValuesEntry], stats: [KeyValuesEntry], appID: UInt32, language: String) throws -> [SteamAchievement] { + let times = unlockTimes(stats) + guard let game = schema.firstObject(for: "\(appID)"), let statList = game.firstObject(for: "stats") else { return [] } + var result: [(stat: Int, bit: Int, achievement: SteamAchievement)] = [] + for stat in statList { + guard case .object(let statFields) = stat.value, let bits = statFields.firstObject(for: "bits"), + let statNumber = Int(stat.key) else { continue } + for bit in bits { + guard case .object(let fields) = bit.value, let bitNumber = Int(bit.key), + let api = fields.firstString(for: "name") else { continue } + let display = fields.firstObject(for: "display") ?? [] + let names = display.firstObject(for: "name") ?? [] + let descs = display.firstObject(for: "desc") ?? [] + let seconds = times[stat.key]?[bit.key].flatMap { Int64($0) } ?? 0 + result.append((statNumber, bitNumber, SteamAchievement( + apiName: api, + name: localized(names, language) ?? api, + description: localized(descs, language) ?? "", + hidden: display.firstString(for: "hidden") == "1", + icon: display.firstString(for: "icon").flatMap { $0.isEmpty ? nil : $0 }, + grayIcon: display.firstString(for: "icon_gray").flatMap { $0.isEmpty ? nil : $0 }, + unlockedAt: seconds > 0 ? Date(timeIntervalSince1970: TimeInterval(seconds)) : nil))) + } + } + return result.sorted { ($0.stat, $0.bit) < ($1.stat, $1.bit) }.map(\.achievement) + } + + /// `cache › <stat> › AchievementTimes › <bit>`; nothing else of the stats file is read. + private static func unlockTimes(_ stats: [KeyValuesEntry]) -> [String: [String: String]] { + guard let cache = stats.firstObject(for: "cache") else { return [:] } + var times: [String: [String: String]] = [:] + for stat in cache { + guard case .object(let fields) = stat.value, let list = fields.firstObject(for: "AchievementTimes") else { continue } + for entry in list { if case .string(let value) = entry.value { times[stat.key, default: [:]][entry.key] = value } } + } + return times + } + + private static func localized(_ entries: [KeyValuesEntry], _ language: String) -> String? { + for key in [language, "english"] { + if let text = entries.firstString(for: key), !text.isEmpty { return text } + } + return nil + } + + private static func data(at url: URL) throws -> Data { + try InstallationFileSnapshot.read(at: url, maximumBytes: SteamBinaryKeyValues.maximumBytes).data + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift b/Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift new file mode 100644 index 00000000..39d8d3a3 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift @@ -0,0 +1,55 @@ +import Foundation + +/// What a Steam game's tile asks for in one layout role. Personal picks always come +/// first. A square then uses the installed app's own icon file, never the portrait +/// cover; other roles have no local default and go to the Steam store art. +public struct SteamArtworkRequest: Equatable { + public let game: CatalogGame + public let role: LibraryArtworkRole + + public init(game: CatalogGame, role: LibraryArtworkRole) { + self.game = game; self.role = role + } + + public var slot: ArtworkSlot { role.slot } + public var appID: UInt32? { game.steamGame?.appID } + /// The installed app this game launches, as the rest of the library reads it. + public var application: CatalogNativeApplication? { + game.steamGame?.firstAvailableInstallation?.primaryApplication + } + + /// A square with no app to take the icon from (Steam still installing the game): it asks for an automatic + /// icon (`ArtworkStore.automaticSteamIcon`, LaunchBox's Square), never another image cropped to a square. + public var wantsAutomaticIcon: Bool { role == .square && application == nil } + + /// A file on this Mac for the role: the player's pick, else (square only) the app's own icon. + public func localURL(picks: SteamPersonalizationStore) -> URL? { + if let picked = picks.url(titleID: game.personalizationReference.key, slot: slot), + FileManager.default.fileExists(atPath: picked.path) { return picked } + return automaticLocalURL + } + + /// What the role shows with no pick: the app's own icon for the square, nothing else on this Mac. + public var automaticLocalURL: URL? { + guard role == .square, let application else { return nil } + return Self.bundleIcon(of: application.url) + } + + /// `CFBundleIconFile` inside the bundle's own Resources folder. A name that points + /// elsewhere (a path, or a link that leaves the folder) is not followed. + static func bundleIcon(of app: URL) -> URL? { + let plist = app.appendingPathComponent("Contents/Info.plist") + guard let data = try? InstallationFileSnapshot.read(at: plist, maximumBytes: 1_048_576).data, + let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], + let name = (info["CFBundleIconFile"] as? String)?.trimmingCharacters(in: .whitespaces), + !name.isEmpty, !name.hasPrefix("."), name == URL(fileURLWithPath: name).lastPathComponent else { return nil } + let resources = app.appendingPathComponent("Contents/Resources") + let file = resources.appendingPathComponent(name.hasSuffix(".icns") ? name : name + ".icns") + let folder = resources.resolvingSymlinksInPath().standardizedFileURL.path + "/" + let resolved = file.resolvingSymlinksInPath().standardizedFileURL + var isDirectory: ObjCBool = false + guard resolved.path.hasPrefix(folder), + FileManager.default.fileExists(atPath: resolved.path, isDirectory: &isDirectory), !isDirectory.boolValue else { return nil } + return file + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift b/Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift new file mode 100644 index 00000000..fd5ea6c9 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift @@ -0,0 +1,74 @@ +import Foundation +import ImageIO + +/// The automatic full-screen background of a Steam game. Steam's library hero is a wide banner +/// (about 3:1) made for the top of Steam's own page: filling a 16:9 screen enlarges and crops it. +/// So clean 16:9 art comes first: the stores' hero backgrounds found by the game's name (Xbox, +/// GOG Galaxy, TheGamesDB fan art, each matched by `ArtworkNames`), then Steam's own first +/// screenshot for the exact AppID, and the library hero only when nothing else fits. +/// The player's own pick always comes before all of this, outside this type. +public enum SteamBackdropChoice { + /// Screen-shaped: between 3:2 and 2:1, and wide enough not to be blown up on a large display. + public static func suits(width: Int, height: Int) -> Bool { + guard width >= 1280, height > 0 else { return false } + let ratio = Double(width) / Double(height) + return ratio >= 1.5 && ratio <= 2.0 + } + + /// Candidates in trial order. Only each store's own clean hero is taken (not titled heroes, + /// wide covers or their screenshots); Steam's art is the exact AppID's, never a name match. + public static func ordered(storeArt: [ArtworkCandidate], screenshots: [URL], libraryHero: URL?) -> [URL] { + func first(_ source: String) -> [URL] { + storeArt.first { $0.slot == .background && $0.source == source }.map { [$0.url] } ?? [] + } + // LaunchBox's fan art for the game's computer entry, at full size: only one whose stated size suits a + // screen (a size it does not state is checked by `choose`). + let fanart = storeArt.first { candidate in + guard candidate.slot == .background, candidate.source.hasPrefix(LaunchBoxArt.fanartSource) else { return false } + guard let width = candidate.width, let height = candidate.height else { return true } + return suits(width: width, height: height) + }.map { $0.full ?? $0.url } + var urls = first("Xbox Store") + first("GOG") + first("TheGamesDB fan art") + (fanart.map { [$0] } ?? []) + urls += screenshots.prefix(1) + if let libraryHero { urls.append(libraryHero) } + var seen: Set<URL> = [] + return urls.filter { seen.insert($0).inserted } + } + + /// The first candidate whose image suits a full screen. When none does: `fallback` (Steam's library + /// banner, shown cropped), else the first candidate that loaded at all. Nothing is kept here: the caller + /// caches the choice. + public static func choose(_ urls: [URL], fallback: URL?, data: (URL) async -> Data?) async -> URL? { + var loaded: URL? + for url in urls { + guard !Task.isCancelled else { return nil } + guard let bytes = await data(url), let size = pixelSize(bytes) else { continue } + if suits(width: size.width, height: size.height) { return url } + if loaded == nil { loaded = url } + } + return fallback ?? loaded + } + + /// Store art for the name, from the sources that publish clean 16:9 heroes, and LaunchBox's fan art for + /// the game's Mac or Windows entry (never a console's). + public static func storeArt(names: [String], client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> [ArtworkCandidate] { + async let xbox = XboxStoreArt.find(names: names, client: client) + async let gog = GOGArt.find(names: names, client: client) + async let gamesDB = TheGamesDBArt.find(names: names, client: client) + async let launchBox = LaunchBoxArt.game(names: names, switch2: false, computer: true, client: client) + return await xbox + gog + gamesDB + (launchBox?.candidates ?? []) + } + + /// Fetches a candidate for `choose`. + public static func download(_ url: URL, client: ArtworkHTTPClient = URLSessionArtworkClient()) async -> Data? { + await OnlineArtworkRequest.data(url, client: client) + } + + static func pixelSize(_ data: Data) -> (width: Int, height: Int)? { + guard let source = CGImageSourceCreateWithData(data as CFData, nil), + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, + let height = properties[kCGImagePropertyPixelHeight] as? Int else { return nil } + return (width, height) + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift b/Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift new file mode 100644 index 00000000..12d7f385 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift @@ -0,0 +1,47 @@ +import Foundation + +/// The waiting screen and silent launch arguments for Steam games started from Play. +/// A closed Steam can start with `-silent` and `-nofriendsui`. Past the wait's `patience` without the +/// game, the launch screen makes way for Steam so the player can check sign-in, updates or a cloud conflict. +public enum SteamBackgroundLaunch { + /// The wait with Steam already open. + public static let attentionDelay: TimeInterval = 15 + /// The wait when Play has to start Steam, which takes a while before it even looks at the request. + public static let coldStartDelay: TimeInterval = 45 + + public static func patience(steamWasRunning: Bool) -> TimeInterval { + steamWasRunning ? attentionDelay : coldStartDelay + } + + /// Arguments for a Steam that Play itself starts; an open Steam ignores launch arguments. + public static func arguments(enabled: Bool, steamRunning: Bool) -> [String] { + enabled && !steamRunning ? ["-silent", "-nofriendsui"] : [] + } + + /// The game is late: Steam is back in view and the head says to check it. + public static func mayNeedPlayer(phase: SteamPlayState.Phase, now: Date, + patience: TimeInterval = attentionDelay) -> Bool { + guard case .starting(let since) = phase else { return false } + return now.timeIntervalSince(since) > patience + } + + /// Where the launch screen of a Steam game stands. + public enum LaunchScreen: Equatable, Sendable { + /// The game is on its way: the waiting screen stays up. + case waiting + /// The game's app is running: the screen leaves once its window is up. + case gameStarted + /// No game within the patience: the screen gives way to Steam. + case late + /// Play was cancelled or failed. + case over + } + + public static func launchScreen(phase: SteamPlayState.Phase, now: Date, patience: TimeInterval) -> LaunchScreen { + switch phase { + case .starting(let since): return now.timeIntervalSince(since) > patience ? .late : .waiting + case .running: return .gameStarted + case .idle, .failed: return .over + } + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift b/Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift new file mode 100644 index 00000000..90504c95 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift @@ -0,0 +1,63 @@ +import Foundation + +/// Steam's binary KeyValues (the `appcache/stats/*.bin` files), read into the same entries as the text format. +/// Each entry is a type byte, a NUL-terminated key and a value: 0 a subtree ending at 8, 1 a NUL-terminated string, +/// 2, 4 and 6 an int32, 3 a float32, 7 a uint64, all little-endian. Numbers become their decimal text. Every level, +/// the top one too, ends at 8 (Steam's files do). Anything else, or data that ends before that, is malformed. +public enum SteamBinaryKeyValues { + public static let maximumBytes = 8 * 1024 * 1024 + + public static func parse(_ data: Data, maximumDepth: Int = 32, maximumEntries: Int = 200_000) throws -> [KeyValuesEntry] { + guard data.count <= maximumBytes else { throw KeyValuesError.limitExceeded } + var cursor = Cursor(bytes: Array(data), maximumDepth: maximumDepth, maximumEntries: maximumEntries) + return try cursor.object(depth: 0) + } + + private struct Cursor { + let bytes: [UInt8] + let maximumDepth: Int + let maximumEntries: Int + var offset = 0 + var count = 0 + + mutating func object(depth: Int) throws -> [KeyValuesEntry] { + guard depth <= maximumDepth else { throw KeyValuesError.limitExceeded } + var entries: [KeyValuesEntry] = [] + while true { + // Every level, the top one too, ends with its terminator: data that stops before it is a file + // cut while Steam wrote it, never a shorter file (an empty stats file would read as no unlocks). + guard offset < bytes.count else { throw KeyValuesError.malformed } + let type = bytes[offset] + offset += 1 + if type == 8 { return entries } + count += 1 + guard count <= maximumEntries else { throw KeyValuesError.limitExceeded } + let key = try string() + let value: KeyValuesValue + switch type { + case 0: value = .object(try object(depth: depth + 1)) + case 1: value = .string(try string()) + case 2, 4, 6: value = .string(String(Int32(bitPattern: UInt32(try integer(4))))) + case 3: value = .string(String(Float(bitPattern: UInt32(try integer(4))))) + case 7: value = .string(String(try integer(8))) + default: throw KeyValuesError.malformed + } + entries.append(KeyValuesEntry(key: key, value: value)) + } + } + + private mutating func string() throws -> String { + guard let end = bytes[offset...].firstIndex(of: 0) else { throw KeyValuesError.malformed } + defer { offset = end + 1 } + return String(decoding: bytes[offset..<end], as: UTF8.self) + } + + private mutating func integer(_ size: Int) throws -> UInt64 { + guard offset + size <= bytes.count else { throw KeyValuesError.malformed } + var value: UInt64 = 0 + for index in 0..<size { value |= UInt64(bytes[offset + index]) << (8 * index) } + offset += size + return value + } + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamKeyValues.swift b/Sources/NXLibraryCore/Services/Steam/SteamKeyValues.swift new file mode 100644 index 00000000..3f213d93 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamKeyValues.swift @@ -0,0 +1,182 @@ +import Foundation + +public enum KeyValuesError: Error, Equatable { + case malformed, limitExceeded + case duplicateField(String), unsupportedDirective(String) +} + +public enum KeyValuesValue: Equatable, Sendable { + case string(String) + case object([KeyValuesEntry]) +} + +public struct KeyValuesEntry: Equatable, Sendable { + public let key: String + public let value: KeyValuesValue +} + +public extension Array where Element == KeyValuesEntry { + /// The first matching key, regardless of its value's type. Later copies are not consulted. + func firstValue(for key: String) -> KeyValuesValue? { + matchingEntries(for: key).first?.value + } + + /// The first matching string, skipping same-named values of another type (Steam achievement data). + func firstString(for key: String) -> String? { + for entry in matchingEntries(for: key) { + if case .string(let value) = entry.value { return value } + } + return nil + } + + /// The first matching object, skipping same-named values of another type (Steam achievement data). + func firstObject(for key: String) -> [KeyValuesEntry]? { + for entry in matchingEntries(for: key) { + if case .object(let value) = entry.value { return value } + } + return nil + } + + /// Missing is nil; duplicate keys of any type are ambiguous and fail. + func uniqueValue(for key: String) throws -> KeyValuesValue? { + var result: KeyValuesValue? + for entry in matchingEntries(for: key) { + guard result == nil else { throw KeyValuesError.duplicateField(key) } + result = entry.value + } + return result + } + + /// A single string or nil when absent; duplicates and a value of another type fail. + func uniqueString(for key: String) throws -> String? { + guard let value = try uniqueValue(for: key) else { return nil } + guard case .string(let text) = value else { throw KeyValuesError.malformed } + return text + } + + private func matchingEntries(for key: String) -> LazyFilterSequence<[KeyValuesEntry]> { + lazy.filter { $0.key.caseInsensitiveCompare(key) == .orderedSame } + } +} + +/// The bounded text subset used by Steam's local indexes and manifests. +/// Entries retain order and duplicates; unique lookups reject ambiguous fields. +/// Directives never cause filesystem access: a `#` key is refused, or with `rejectsDirectives` +/// off (for files that only hold data, such as `localconfig.vdf`) read as an ordinary key. +public struct KeyValuesDocument: Sendable { + public let entries: [KeyValuesEntry] + + public init(text: String, maximumDepth: Int = 32, maximumEntries: Int = 20_000, rejectsDirectives: Bool = true) throws { + guard text.utf8.count <= 8 * 1024 * 1024, maximumDepth >= 0, maximumEntries >= 0 else { + throw KeyValuesError.limitExceeded + } + var reader = Reader(bytes: Array(text.utf8), maximumDepth: maximumDepth, maximumEntries: maximumEntries, + rejectsDirectives: rejectsDirectives) + entries = try reader.object(depth: 0) + } + + public func uniqueValue(for key: String) throws -> KeyValuesValue? { + try entries.uniqueValue(for: key) + } +} + +private struct Reader { + let bytes: [UInt8] + let maximumDepth: Int + let maximumEntries: Int + let rejectsDirectives: Bool + private var offset = 0 + private var count = 0 + + init(bytes: [UInt8], maximumDepth: Int, maximumEntries: Int, rejectsDirectives: Bool) { + self.bytes = bytes + self.maximumDepth = maximumDepth + self.maximumEntries = maximumEntries + self.rejectsDirectives = rejectsDirectives + if bytes.starts(with: [0xef, 0xbb, 0xbf]) { offset = 3 } + } + + private enum Token { case scalar(String), open, close } + + mutating func object(depth: Int) throws -> [KeyValuesEntry] { + var entries: [KeyValuesEntry] = [] + while let token = try readToken() { + if case .close = token { + guard depth > 0 else { throw KeyValuesError.malformed } + return entries + } + guard case .scalar(let key) = token, !key.isEmpty else { throw KeyValuesError.malformed } + guard !rejectsDirectives || !key.hasPrefix("#") else { throw KeyValuesError.unsupportedDirective(key) } + guard count < maximumEntries else { throw KeyValuesError.limitExceeded } + count += 1 + let value: KeyValuesValue + switch try readToken() { + case .scalar(let text): value = .string(text) + case .open: + guard depth < maximumDepth else { throw KeyValuesError.limitExceeded } + value = .object(try object(depth: depth + 1)) + default: throw KeyValuesError.malformed + } + entries.append(KeyValuesEntry(key: key, value: value)) + } + guard depth == 0 else { throw KeyValuesError.malformed } + return entries + } + + private mutating func readToken() throws -> Token? { + skipTrivia() + guard offset < bytes.count else { return nil } + let first = bytes[offset] + offset += 1 + if first == 123 { return .open } + if first == 125 { return .close } + if first == 34 { return .scalar(try quoted()) } + guard first != 0 else { throw KeyValuesError.malformed } + let start = offset - 1 + while offset < bytes.count { + let byte = bytes[offset] + if isWhitespace(byte) || byte == 123 || byte == 125 || isComment { break } + guard byte != 0, byte != 34 else { throw KeyValuesError.malformed } + offset += 1 + } + return .scalar(String(decoding: bytes[start..<offset], as: UTF8.self)) + } + + private mutating func quoted() throws -> String { + var result: [UInt8] = [] + while offset < bytes.count { + let byte = bytes[offset] + offset += 1 + if byte == 34 { return String(decoding: result, as: UTF8.self) } + guard byte != 0 else { throw KeyValuesError.malformed } + if byte == 92 { + guard offset < bytes.count else { throw KeyValuesError.malformed } + let escaped = bytes[offset] + offset += 1 + switch escaped { + case 34, 92: result.append(escaped) + case 110: result.append(10) + case 116: result.append(9) + case 114: result.append(13) + default: throw KeyValuesError.malformed + } + } else { result.append(byte) } + } + throw KeyValuesError.malformed + } + + private var isComment: Bool { + offset + 1 < bytes.count && bytes[offset] == 47 && bytes[offset + 1] == 47 + } + + private func isWhitespace(_ byte: UInt8) -> Bool { byte == 32 || (9...13).contains(byte) } + + private mutating func skipTrivia() { + while offset < bytes.count { + if isWhitespace(bytes[offset]) { offset += 1 } + else if isComment { + while offset < bytes.count && bytes[offset] != 10 && bytes[offset] != 13 { offset += 1 } + } else { return } + } + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift b/Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift new file mode 100644 index 00000000..d93cb5c5 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift @@ -0,0 +1,117 @@ +import Foundation + +/// A launch Steam holds until the player answers it: Steam writes `GameAction [AppID <id>, …] : LaunchApp waiting +/// for user response to <question>` to its console log when a launch stops on a question (the game is playing on +/// another device, a cloud conflict, …), and a later `GameAction` line for that game once it moves on. +/// `ShowInterstitials` is a generic startup step that can use the same wording during a cold start. +/// Other questions count only after `grace`. +/// Only `GameAction` lines are read; nothing is kept but which games wait and since when. +public struct SteamLaunchQuestions: Equatable, Sendable { + public static let grace: TimeInterval = 1 + + /// Games whose launch waits on a question, with when NX Library first read it. + private var pending: [UInt32: Date] = [:] + + public init() {} + + /// Reads complete log lines, in order (`SteamConsoleLog` keeps unfinished lines). `now` is when read. + public mutating func read(_ text: String, now: Date) { + for line in text.split(separator: "\n") { take(line, now: now) } + } + + /// Steam started a new log: what the old one said no longer holds. + public mutating func reset() { + pending = [:] + } + + /// Steam has been waiting on the player for this game's launch for at least `grace`. + public func isAsking(appID: UInt32, now: Date) -> Bool { + guard let since = pending[appID] else { return false } + return now.timeIntervalSince(since) >= Self.grace + } + + private static let action = "GameAction [AppID " + private static let question = "LaunchApp waiting for user response to " + + private mutating func take(_ line: Substring, now: Date) { + guard let start = line.range(of: Self.action)?.upperBound, + let end = line[start...].firstIndex(where: { !$0.isNumber }), + let appID = UInt32(line[start..<end]) else { return } + guard let question = line[end...].range(of: Self.question), + line[question.upperBound...].prefix(while: { !$0.isWhitespace }) != "ShowInterstitials" else { + pending[appID] = nil + return + } + if pending[appID] == nil { pending[appID] = now } + } +} + +/// Steam's console log (`<Steam>/logs/console_log.txt`), read from where the last read stopped, whole lines only: a +/// line Steam is still writing is read once it ends. Steam starts a new file each time it starts; a different or +/// shorter file is read again from the top. +public struct SteamConsoleLog: Sendable { + public let fileURL: URL + private var file: (number: UInt64, offset: UInt64)? + + public init(steamRoot: URL) { + fileURL = steamRoot.appendingPathComponent("logs/console_log.txt") + } + + /// The whole lines written since the last read, or nil without a log. `isNewFile` on the first read, for a new + /// file and when more than `limit` bytes arrived at once: only the last `limit` bytes are read then, from their + /// first whole line, and what came before is lost. + public mutating func readNew(limit: Int = 1 << 20) -> (text: String, isNewFile: Bool)? { + guard let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path), + let size = (attributes[.size] as? NSNumber)?.uint64Value, + let number = (attributes[.systemFileNumber] as? NSNumber)?.uint64Value, + let handle = try? FileHandle(forReadingFrom: fileURL) else { return nil } + defer { try? handle.close() } + let limit = UInt64(max(limit, 1)) + var start: UInt64 = 0 + var isNewFile = true + if let file, file.number == number, file.offset <= size { + start = file.offset + isNewFile = false + } + var cut = false + if size - start > limit { + start = size - limit + cut = true + isNewFile = true + } + guard (try? handle.seek(toOffset: start)) != nil, + let data = try? handle.read(upToCount: Int(size - start)) ?? Data() else { return nil } + let newline = UInt8(ascii: "\n") + var lines = data[...] + // A cut first line starts after its newline. + if cut, start > 0 { + lines = lines.firstIndex(of: newline).map { lines[lines.index(after: $0)...] } ?? lines[lines.endIndex...] + } + let end = lines.lastIndex(of: newline).map { lines.index(after: $0) } ?? lines.startIndex + lines = lines[..<end] + self.file = (number, start + UInt64(end - data.startIndex)) + return (String(decoding: lines, as: UTF8.self), isNewFile) + } +} + +/// Watches one Play's launch for a question in Steam's log: reads the log (from its last megabyte the first time, +/// so a question still open from an earlier Play counts) and says when Steam waits on the player. +public struct SteamLaunchQuestionWatch: Sendable { + public let appID: UInt32 + private var log: SteamConsoleLog + private var questions = SteamLaunchQuestions() + + public init(appID: UInt32, steamRoot: URL) { + self.appID = appID + log = SteamConsoleLog(steamRoot: steamRoot) + } + + /// Reads what Steam wrote since the last look; true once Steam waits on the player for this game. + public mutating func look(now: Date) -> Bool { + if let new = log.readNew() { + if new.isNewFile { questions.reset() } + questions.read(new.text, now: now) + } + return questions.isAsking(appID: appID, now: now) + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift b/Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift new file mode 100644 index 00000000..03511d78 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift @@ -0,0 +1,312 @@ +import Foundation + +public struct SteamScanLimits: Sendable { + public var maximumTextBytes = 8 * 1024 * 1024 + public var maximumLibraries = 64 + public var maximumManifests = 10_000 + public var maximumDirectoriesPerInstall = 256 + public var maximumInstallDepth = 4 + public var maximumDirectoryEntries = 10_000 + public static let standard = Self() + public init() {} +} + +public struct SteamScanIssue: Equatable, Sendable { + public enum Reason: Equatable, Sendable { + case unavailableLibrary, invalidIndex, oversizedIndex, invalidManifest, oversizedManifest + case conflictingIdentity, unsafePath, directoryLimit, unreadableAppMetadata, libraryLimit, manifestLimit + } + public let url: URL + public let appID: UInt32? + public let reason: Reason +} + +public struct SteamLibraryObservation: Equatable, Sendable { + public let root: URL + public let isReadable: Bool + public var isComplete: Bool +} + +public struct SteamGameObservation: Equatable, Sendable { + /// `downloading`: Steam has not marked the game fully installed yet (StateFlags without bit 4); its folder is + /// not read, since Steam is still writing it. + public enum State: Equatable, Sendable { case nativeReady, requiresReview, unavailable, downloading } + public let appID: UInt32 + public let name: String + public let installationURL: URL + public let libraryURL: URL + public let reportedSizeBytes: Int64? + public let buildID: String? + public let nativeApps: [NativeMacApplication] + public var state: State +} + +public struct SteamLibrarySnapshot: Sendable { + public let libraries: [SteamLibraryObservation] + public let games: [SteamGameObservation] + public let issues: [SteamScanIssue] + /// A partial source must never authorize pruning unseen libraries or games. + public var isComplete: Bool { issues.isEmpty && libraries.allSatisfy(\.isComplete) } +} + +public enum SteamSourceError: Error, Equatable { case sourceChanged } + +/// Reads only Steam's declared libraries. No scan starts until explicitly requested; +/// this source owns no persistence, process launch, credentials or user opt-in. +public struct SteamLibrarySource: Sendable { + private let root: URL + private let limits: SteamScanLimits + private let directoryReader: InstallationDirectoryReader + public init(root: URL, limits: SteamScanLimits = .standard) { + self.init(root: root, limits: limits, directoryReader: { url, budget, cancelled in + try InstallationDirectorySnapshot.read(at: url, maximumEntries: budget, cancelled: cancelled) + }) + } + + init(root: URL, limits: SteamScanLimits = .standard, directoryReader: @escaping InstallationDirectoryReader) { + self.root = root + self.limits = limits + self.directoryReader = directoryReader + } + + public func scan(cancelled: @escaping () -> Bool = { false }) throws -> SteamLibrarySnapshot { + var scan = Scan(root: root, limits: limits, cancelled: cancelled, directoryReader: directoryReader) + do { return try scan.run() } + catch InstallationFileReadError.sourceChanged { throw SteamSourceError.sourceChanged } + } +} + +private struct Scan { + let root: URL + let limits: SteamScanLimits + let cancelled: () -> Bool + let directoryReader: InstallationDirectoryReader + private let fm = FileManager.default + private var observations: [InstallationFileObservation] = [] + private var issues: [SteamScanIssue] = [] + private var games: [SteamGameObservation] = [] + + init(root: URL, limits: SteamScanLimits, cancelled: @escaping () -> Bool, directoryReader: @escaping InstallationDirectoryReader) { + self.root = root.resolvingSymlinksInPath().standardizedFileURL + self.limits = limits + self.cancelled = cancelled + self.directoryReader = directoryReader + } + + mutating func run() throws -> SteamLibrarySnapshot { + try checkCancellation() + let paths = try libraryPaths() + var libraries: [SteamLibraryObservation] = [] + var manifestsSeen = 0 + for library in paths { + try checkCancellation() + let before = issues.count + let steamapps = library.appendingPathComponent("steamapps").resolvingSymlinksInPath().standardizedFileURL + guard NativeMacApplication.isWithin(steamapps, root: library) else { + issue(.unsafePath, at: steamapps) + libraries.append(.init(root: library, isReadable: false, isComplete: false)) + continue + } + let files: [URL] + do { files = try readDirectory(steamapps) } + catch is CancellationError { throw CancellationError() } + catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged } + catch { + issue(.unavailableLibrary, at: library) + libraries.append(.init(root: library, isReadable: false, isComplete: false)) + continue + } + let manifests = files.filter { $0.lastPathComponent.hasPrefix("appmanifest_") && $0.pathExtension == "acf" } + .sorted { $0.path < $1.path } + for file in manifests { + try checkCancellation() + guard manifestsSeen < max(0, limits.maximumManifests) else { + issue(.manifestLimit, at: library) + break + } + manifestsSeen += 1 + try readManifest(file, library: library) + } + libraries.append(.init(root: library, isReadable: true, isComplete: issues.count == before)) + } + let conflicting = Dictionary(grouping: games.indices, by: { games[$0].appID }).values.filter { $0.count > 1 } + for indices in conflicting { + for index in indices { + games[index].state = .requiresReview + issue(.conflictingIdentity, at: games[index].installationURL, appID: games[index].appID) + if let library = libraries.firstIndex(where: { $0.root.path == games[index].libraryURL.path }) { + libraries[library].isComplete = false + } + } + } + // Errors reading the index may hide entire libraries, so source-level completeness matters too. + if issues.contains(where: { [.invalidIndex, .oversizedIndex, .libraryLimit].contains($0.reason) }) { + for index in libraries.indices { libraries[index].isComplete = false } + } + for observation in observations { try checkCancellation(); try observation.verifyUnchanged() } + games.sort { $0.appID == $1.appID ? $0.libraryURL.path < $1.libraryURL.path : $0.appID < $1.appID } + return SteamLibrarySnapshot(libraries: libraries, games: games, issues: issues) + } + + private mutating func libraryPaths() throws -> [URL] { + var paths = [root] + let steamapps = root.appendingPathComponent("steamapps").resolvingSymlinksInPath().standardizedFileURL + guard NativeMacApplication.isWithin(steamapps, root: root) else { + issue(.unsafePath, at: steamapps) + return paths + } + let index = root.appendingPathComponent("steamapps/libraryfolders.vdf") + if fm.fileExists(atPath: index.path) { + do { + let document = try readDocument(index) + guard case .object(let entries)? = try document.uniqueValue(for: "libraryfolders") else { throw KeyValuesError.malformed } + for entry in entries where Self.numeric(entry.key) != nil || entry.key == "0" { + let path: String + switch entry.value { + case .string(let value): path = value + case .object(let children): + guard let value = try children.uniqueString(for: "path") else { throw KeyValuesError.malformed } + path = value + } + guard path.hasPrefix("/"), !path.contains("\0") else { issue(.unsafePath, at: index); continue } + let url = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL + if !paths.contains(where: { $0.path == url.path }) { + guard paths.count < max(1, limits.maximumLibraries) else { issue(.libraryLimit, at: index); continue } + paths.append(url) + } + } + } catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged } + catch InstallationFileReadError.tooLarge { issue(.oversizedIndex, at: index) } + catch { issue(.invalidIndex, at: index) } + } else { + do { observations.append(try InstallationFileObservation.absent(at: index)) } + catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged } + catch { issue(.invalidIndex, at: index) } + } + return paths + } + + private mutating func readManifest(_ file: URL, library: URL) throws { + let stem = file.deletingPathExtension().lastPathComponent + let filenameID = Self.numeric(String(stem.dropFirst("appmanifest_".count))) + do { + guard let filenameID else { throw KeyValuesError.malformed } + let document = try readDocument(file) + guard case .object(let fields)? = try document.uniqueValue(for: "AppState"), + let idText = try fields.uniqueString(for: "appid"), let id = Self.numeric(idText) else { throw KeyValuesError.malformed } + guard id == filenameID else { issue(.conflictingIdentity, at: file, appID: filenameID); return } + guard let name = try fields.uniqueString(for: "name"), !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + let directory = try fields.uniqueString(for: "installdir"), !directory.isEmpty else { throw KeyValuesError.malformed } + let components = directory.split(separator: "/", omittingEmptySubsequences: false) + guard !directory.hasPrefix("/"), !directory.contains("\\"), !directory.contains("\0"), + !components.contains(where: { $0 == ".." || $0 == "." || $0.isEmpty }) else { + issue(.unsafePath, at: file, appID: id); return + } + let common = library.appendingPathComponent("steamapps/common").resolvingSymlinksInPath().standardizedFileURL + let install = common.appendingPathComponent(directory).resolvingSymlinksInPath().standardizedFileURL + guard NativeMacApplication.isWithin(common, root: library), NativeMacApplication.isWithin(install, root: common), install.path != common.path else { + issue(.unsafePath, at: file, appID: id); return + } + let size = try fields.uniqueString(for: "SizeOnDisk").flatMap(Self.nonnegativeSize) + let build = try fields.uniqueString(for: "buildid") + // Bit 4 is FullyInstalled. Missing or unreadable flags keep the folder check alone, as before. + if let flags = try fields.uniqueString(for: "StateFlags").flatMap({ UInt64($0) }), flags & 4 == 0 { + games.append(.init(appID: id, name: name, installationURL: install, libraryURL: library, + reportedSizeBytes: size, buildID: build, nativeApps: [], state: .downloading)) + return + } + let before = issues.count + let apps = try nativeApps(in: install, appID: id) + let mainApps = apps.filter(\.isDeclaredGame) + let state: SteamGameObservation.State = mainApps.count == 1 && issues.count == before ? .nativeReady + : (apps.isEmpty && issues.count == before ? .unavailable : .requiresReview) + games.append(.init(appID: id, name: name, installationURL: install, libraryURL: library, + reportedSizeBytes: size, buildID: build, nativeApps: apps, state: state)) + } catch is CancellationError { throw CancellationError() } + catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged } + catch InstallationFileReadError.tooLarge { issue(.oversizedManifest, at: file, appID: filenameID) } + catch { issue(.invalidManifest, at: file, appID: filenameID) } + } + + private mutating func nativeApps(in install: URL, appID: UInt32) throws -> [NativeMacApplication] { + guard fm.fileExists(atPath: install.path) else { return [] } + var level = [install] + var depth = 0 + var visited = 0 + var apps: [NativeMacApplication] = [] + var seen: Set<String> = [] + let keys: Set<URLResourceKey> = [.isDirectoryKey, .isSymbolicLinkKey, .isPackageKey] + while !level.isEmpty { + try checkCancellation() + var nextLevel: [URL] = [] + var truncated = false + let remaining = max(0, max(1, limits.maximumDirectoriesPerInstall) - visited - level.count) + for directory in level { + let files: [URL] + do { files = try readDirectory(directory, appID: appID) } + catch is CancellationError { throw CancellationError() } + catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged } + catch { issue(.unreadableAppMetadata, at: directory, appID: appID); continue } + for file in files.sorted(by: { $0.path < $1.path }) { + try checkCancellation() + if file.pathExtension.lowercased() == "app" { + do { + let app = try NativeMacApplication.inspect(at: file, within: install) + observations.append(contentsOf: app.fileObservations) + if seen.insert(app.url.path).inserted { apps.append(app) } + } catch InstallationFileReadError.sourceChanged { throw InstallationFileReadError.sourceChanged } + catch { issue(.unreadableAppMetadata, at: file, appID: appID) } + continue // Every bundle is a boundary, including an invalid one. + } + let values: URLResourceValues + do { values = try file.resourceValues(forKeys: keys) } + catch { issue(.unreadableAppMetadata, at: file, appID: appID); continue } + guard values.isDirectory == true, values.isSymbolicLink != true, values.isPackage != true else { continue } + if nextLevel.count < remaining { nextLevel.append(file) } + else { truncated = true } + } + } + visited += level.count + // Compare all apps at this depth. Once game candidates exist, deeper + // loose-data trees do not decide which top-level application is primary. + if apps.contains(where: \.isDeclaredGame) { return apps } + if truncated || (!nextLevel.isEmpty && depth >= max(0, limits.maximumInstallDepth)) { + issue(.directoryLimit, at: level[0], appID: appID) + return apps + } + level = nextLevel + depth += 1 + } + return apps + } + + private mutating func readDocument(_ url: URL) throws -> KeyValuesDocument { + let snapshot = try InstallationFileSnapshot.read(at: url, maximumBytes: min(max(0, limits.maximumTextBytes), 8 * 1024 * 1024)) + let document = try KeyValuesDocument(text: snapshot.text) + observations.append(snapshot.observation) + return document + } + + private mutating func readDirectory(_ url: URL, appID: UInt32? = nil) throws -> [URL] { + let snapshot = try directoryReader(url, limits.maximumDirectoryEntries, cancelled) + observations.append(snapshot.observation) + if !snapshot.isComplete { issue(.directoryLimit, at: url, appID: appID) } + return snapshot.entries + } + + private mutating func issue(_ reason: SteamScanIssue.Reason, at url: URL, appID: UInt32? = nil) { + issues.append(SteamScanIssue(url: url, appID: appID, reason: reason)) + } + + private func checkCancellation() throws { if cancelled() { throw CancellationError() } } + + private static func numeric(_ text: String) -> UInt32? { + guard !text.isEmpty, text.utf8.allSatisfy({ (48...57).contains($0) }), let value = UInt32(text), value > 0 else { return nil } + return value + } + + private static func nonnegativeSize(_ text: String) -> Int64? { + guard !text.isEmpty, text.utf8.allSatisfy({ (48...57).contains($0) }), let value = Int64(text) else { return nil } + return value + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift b/Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift new file mode 100644 index 00000000..1ffb9c34 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift @@ -0,0 +1,108 @@ +import Foundation +import CoreServices + +/// Tells NX Library when Steam rewrites a manifest (a download starts, pauses or finishes, a game is installed, +/// removed or launched) or the library index, so the Steam source can rescan without a Refresh. One FSEvents +/// stream over the `steamapps` folders of the libraries the last scan read. FSEvents is recursive, so a download's +/// writes under `downloading/` reach the callback too: its 2 s latency batches them and only the paths are +/// compared, nothing is read. `CatalogSourcesModel.steamFilesChanged` paces the rescans. +@MainActor +public final class SteamManifestWatcher { + /// Called on the main thread, at most once per batch of events. + public var onChange: (@MainActor () -> Void)? + + private var stream: FSEventStreamRef? + private var watched: [String] = [] + private var libraries: [String] = [] + private var root: String? + + public init(onChange: (@MainActor () -> Void)? = nil) { self.onChange = onChange } + + /// Watches these libraries (the scan's, the source's root among them). Rechecks available folders even for + /// the same set, so a library returning on an external drive joins the stream. None stops watching. + public func watch(_ libraries: [URL], root: URL?) { + let paths = libraries.map { $0.resolvingSymlinksInPath().standardizedFileURL.path } + let rootPath = root.map { $0.resolvingSymlinksInPath().standardizedFileURL.path } + let folders = paths.map { $0 + "/steamapps" }.filter { FileManager.default.fileExists(atPath: $0) } + guard paths != self.libraries || rootPath != self.root || folders != watched else { return } + stop() + guard !folders.isEmpty else { return } + // The stream holds the watcher until it is released in `stop`, so a callback already queued on the main + // queue never reaches a freed watcher. + var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), + retain: { info in + guard let info else { return nil } + _ = Unmanaged<SteamManifestWatcher>.fromOpaque(info).retain() + return info + }, + release: { info in + guard let info else { return } + Unmanaged<SteamManifestWatcher>.fromOpaque(info).release() + }, + copyDescription: nil) + let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagUseCFTypes + | kFSEventStreamCreateFlagNoDefer) + guard let stream = FSEventStreamCreate(nil, Self.callback, &context, folders as CFArray, + FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 2, flags) else { return } + FSEventStreamSetDispatchQueue(stream, DispatchQueue.main) + guard FSEventStreamStart(stream) else { + FSEventStreamInvalidate(stream); FSEventStreamRelease(stream) + return + } + self.stream = stream + self.libraries = paths + self.root = rootPath + watched = folders + } + + public func stop() { + if let stream { + FSEventStreamStop(stream); FSEventStreamInvalidate(stream); FSEventStreamRelease(stream) + } + stream = nil; watched = []; libraries = []; root = nil + } + + /// An event that may change the library. With `dropped` (the system lost events under `path` and asks for a + /// rescan of it), only a drop at a `steamapps` folder or above counts: one inside `downloading/` or `common/` + /// says nothing about the manifests, and a long download could otherwise rescan every batch. + public nonisolated static func isRelevant(_ path: String, dropped: Bool, libraries: [String], root: String?) -> Bool { + guard dropped else { return isRelevant(path, libraries: libraries, root: root) } + let folder = path.hasSuffix("/") ? String(path.dropLast()) : path + return libraries.contains { library in + let steamapps = library + "/steamapps" + return steamapps == folder || steamapps.hasPrefix(folder + "/") + } + } + + /// `<library>/steamapps/appmanifest_<digits>.acf`, or the root's `steamapps/libraryfolders.vdf`. + public nonisolated static func isRelevant(_ path: String, libraries: [String], root: String?) -> Bool { + if let root, path == root + "/steamapps/libraryfolders.vdf" { return true } + for library in libraries { + let prefix = library + "/steamapps/" + guard path.hasPrefix(prefix) else { continue } + let name = path.dropFirst(prefix.count) + guard name.hasPrefix("appmanifest_"), name.hasSuffix(".acf") else { return false } + let digits = name.dropFirst("appmanifest_".count).dropLast(".acf".count) + return !digits.isEmpty && digits.utf8.allSatisfy { (48...57).contains($0) } + } + return false + } + + private func received(_ paths: [String], flags: [FSEventStreamEventFlags]) { + let mustScan = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs) + let changed = zip(paths, flags).contains { path, flag in + // FSEvents can spell /var and /tmp with /private; compare in the same form as `watch`. + let canonical = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path + return Self.isRelevant(canonical, dropped: flag & mustScan != 0, libraries: libraries, root: root) + } + if changed { onChange?() } + } + + private static let callback: FSEventStreamCallback = { _, info, count, eventPaths, eventFlags, _ in + guard let info else { return } + let paths = (unsafeBitCast(eventPaths, to: NSArray.self) as? [String]) ?? [] + let flags = Array(UnsafeBufferPointer(start: eventFlags, count: count)) + let watcher = Unmanaged<SteamManifestWatcher>.fromOpaque(info).takeUnretainedValue() + MainActor.assumeIsolated { watcher.received(paths, flags: flags) } + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift b/Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift new file mode 100644 index 00000000..9912b8d8 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift @@ -0,0 +1,58 @@ +import Foundation + +/// Store facts are distinct from installation observations and personal choices. +public struct SteamMetadata: Codable, Equatable, Sendable { + public let appID: UInt32 + public let language: String + public let description: String + public let genres: [String] + public let developers: [String] + public let publishers: [String] + public let releaseDate: String? + public let screenshots: [URL] + public let fetchedAt: Date + + public static func language(_ language: AppLanguage) -> String { + switch language { + case .italian: return "italian" + case .french: return "french" + case .german: return "german" + case .spanish: return "spanish" + case .portugueseBrazil: return "brazilian" + default: return "english" + } + } + public static func safeImage(_ url: URL?) -> URL? { + guard let url, url.scheme == "https", url.user == nil, url.password == nil, + url.port == nil || url.port == 443, let host = url.host?.lowercased(), + ["steamstatic.com", "steamusercontent.com"].contains(where: { host == $0 || host.hasSuffix("." + $0) }) else { return nil } + return url + } + public static func decode(_ data: Data, appID: UInt32, language: String) throws -> Self { + struct Envelope: Decodable { + struct Body: Decodable { + struct Genre: Decodable { let description: String } + struct Shot: Decodable { let path_full: URL } + struct Release: Decodable { let date: String? } + let steam_appid: UInt32 + let short_description: String? + let genres: [Genre]? + let developers: [String]? + let publishers: [String]? + let release_date: Release? + let screenshots: [Shot]? + } + let success: Bool + let data: Body? + } + guard data.count <= 2_097_152, appID > 0, + let envelope = try JSONDecoder().decode([String: Envelope].self, from: data)[String(appID)], + envelope.success, let body = envelope.data, body.steam_appid == appID else { throw URLError(.cannotParseResponse) } + return Self(appID: appID, language: language, + description: GameBananaAPI.plainText(fromHTML: body.short_description ?? ""), + genres: Array((body.genres ?? []).prefix(24)).map(\.description), + developers: Array((body.developers ?? []).prefix(12)), publishers: Array((body.publishers ?? []).prefix(12)), + releaseDate: body.release_date?.date, + screenshots: Array((body.screenshots ?? []).compactMap { safeImage($0.path_full) }.prefix(12)), fetchedAt: Date()) + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift b/Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift new file mode 100644 index 00000000..84f62462 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift @@ -0,0 +1,212 @@ +import Foundation +import CryptoKit + +/// Bounded, source-specific enrichment. Failures preserve disk cache; no catalog +/// writes, credentials, game-content reads or Nintendo lookups. +public actor SteamMetadataService { + public typealias Transport = @Sendable (URL) async throws -> Data + public static let shared = SteamMetadataService() + private let directory: URL + private let transport: Transport + private struct Flight { + let id: UUID + let task: Task<Data, Error> + var waiters: Set<UUID> + } + private var pending: [URL: Flight] = [:] + private var failedAt: [URL: Date] = [:] + /// At most this many downloads at once; later requests wait for a free one (a screen of achievement + /// icons asks for dozens together: refused, they stayed blank until their row was drawn again). + static let concurrentDownloads = 6 + private var slotWaiters: [UUID: CheckedContinuation<Void, Error>] = [:] + public static let resourceDeadline: TimeInterval = 20 + final class NoRedirects: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } + } + private static let session: URLSession = { + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForResource = resourceDeadline + config.timeoutIntervalForRequest = 10 + config.httpMaximumConnectionsPerHost = 4 + return URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil) + }() + public static func allowed(_ url: URL) -> Bool { + guard url.scheme == "https", url.user == nil, url.password == nil, url.port == nil || url.port == 443 else { return false } + // `URL.path` drops the trailing slash; the components keep it. + if url.host == SteamAchievementRarity.host { + return URLComponents(url: url, resolvingAgainstBaseURL: false)?.path == SteamAchievementRarity.path + } + return url.host == "store.steampowered.com" || SteamMetadata.safeImage(url) != nil + } + + public init(directory: URL = AppData.supportRoot.appendingPathComponent("integrations/steam/enrichment"), + transport: @escaping Transport = { try await SteamMetadataService.download($0) }) { + self.directory = directory; self.transport = transport + } + public static func download(_ url: URL) async throws -> Data { + guard allowed(url) else { throw URLError(.badURL) } + var request = URLRequest(url: url); request.timeoutInterval = 15 + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") + let limit = url.host == "store.steampowered.com" || url.host == SteamAchievementRarity.host ? 2_097_152 : 12_582_912 + let (data, response) = try await BoundedDownload.data(for: request, session: session, limit: limit) + guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), + let final = http.url, allowed(final) else { throw URLError(.badServerResponse) } + return data + } + private func release(_ url: URL, flightID: UUID, waiter: UUID) { + guard var flight = pending[url], flight.id == flightID else { return } + flight.waiters.remove(waiter) + if flight.waiters.isEmpty { flight.task.cancel(); pending[url] = nil; wakeSlotWaiters() } + else { pending[url] = flight } + } + /// Every waiter looks again: one may now share a flight that started meanwhile, or take the free slot. + private func wakeSlotWaiters() { + let waiting = slotWaiters.values + slotWaiters.removeAll() + waiting.forEach { $0.resume() } + } + private func waitForSlot() async throws { + let id = UUID() + try await withTaskCancellationHandler(operation: { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in + // Runs on the actor before `cancelWait` can: a cancellation before this point shows here. + if Task.isCancelled { continuation.resume(throwing: CancellationError()) } + else { slotWaiters[id] = continuation } + } + }, onCancel: { Task { await self.cancelWait(id) } }) + } + private func cancelWait(_ id: UUID) { + slotWaiters.removeValue(forKey: id)?.resume(throwing: CancellationError()) + } + private func refuseIfFailedRecently(_ url: URL) throws { + if let failed = failedAt[url], Date().timeIntervalSince(failed) < 60 { throw URLError(.resourceUnavailable) } + } + private func fetch(_ url: URL) async throws -> Data { + try Task.checkCancellation() + // A recent failure answers at once, before and after waiting for a slot (it may fail meanwhile). + try refuseIfFailedRecently(url) + while pending[url] == nil && pending.count >= Self.concurrentDownloads { try await waitForSlot() } + try refuseIfFailedRecently(url) + let waiter = UUID() + var flight: Flight + if let existing = pending[url] { flight = existing; flight.waiters.insert(waiter) } + else { + let transport = transport + flight = Flight(id: UUID(), task: Task { try await transport(url) }, waiters: [waiter]) + } + pending[url] = flight + let id = flight.id, task = flight.task + return try await withTaskCancellationHandler(operation: { + defer { release(url, flightID: id, waiter: waiter) } + do { let data = try await task.value; try Task.checkCancellation(); return data } + catch { + if !Task.isCancelled && !(error is CancellationError) { failedAt[url] = Date() } + throw error + } + }, onCancel: { Task { await self.release(url, flightID: id, waiter: waiter) } }) + } + private static let metadataLanguages: Set<String> = ["english", "italian", "french", "german", "spanish", "brazilian"] + + private func metadataFile(appID: UInt32, language: String) -> URL { + directory.appendingPathComponent("\(appID)/\(language).json") + } + + private func cachedMetadata(appID: UInt32, language: String) -> SteamMetadata? { + let file = metadataFile(appID: appID, language: language) + let cached = (try? InstallationFileSnapshot.read(at: file, maximumBytes: 2_097_152).data).flatMap { try? JSONDecoder().decode(SteamMetadata.self, from: $0) } + return cached.flatMap { $0.appID == appID && $0.language == language ? $0 : nil } + } + + /// The game's related row needs only scoring traits. Read existing entries and leave other games off the network. + public func cachedRelatedTraits(appIDs: Set<UInt32>, language: String) -> [UInt32: MoreLikeThis.Traits] { + guard Self.metadataLanguages.contains(language) else { return [:] } + var traits: [UInt32: MoreLikeThis.Traits] = [:] + for appID in appIDs where appID > 0 { + guard !Task.isCancelled else { return [:] } + if let cached = cachedMetadata(appID: appID, language: language) { traits[appID] = .init(steam: cached) } + } + return traits + } + + public func metadata(appID: UInt32, language: String, refresh: Bool = false) async -> SteamMetadata? { + guard appID > 0, Self.metadataLanguages.contains(language) else { return nil } + let file = metadataFile(appID: appID, language: language) + let valid = cachedMetadata(appID: appID, language: language) + if let valid, !refresh, Date().timeIntervalSince(valid.fetchedAt) < 604800 { return valid } + let url = URL(string: "https://store.steampowered.com/api/appdetails?appids=\(appID)&l=\(language)")! + do { + let bytes = try await fetch(url) + try Task.checkCancellation() + let result: SteamMetadata + do { result = try SteamMetadata.decode(bytes, appID: appID, language: language) } + catch { failedAt[url] = Date(); throw error } + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONEncoder().encode(result).write(to: file, options: .atomic) + return result + } catch { return valid } + } + /// How many of Steam's players have each achievement (`SteamAchievementRarity`), by API name, kept for a day. + /// Offline or on a bad answer, the last percentages known, or nil. + public func achievementPercents(appID: UInt32) async -> [String: Double]? { + guard appID > 0 else { return nil } + let file = directory.appendingPathComponent("\(appID)/achievement-percents.json") + let cached = (try? InstallationFileSnapshot.read(at: file, maximumBytes: 2_097_152).data) + .flatMap { try? JSONDecoder().decode(SteamAchievementPercentsCache.self, from: $0) } + if let cached, Date().timeIntervalSince(cached.fetchedAt) < SteamAchievementRarity.freshFor { return cached.percents } + let url = SteamAchievementRarity.url(appID: appID) + do { + let bytes = try await fetch(url) + try Task.checkCancellation() + let percents: [String: Double] + do { percents = try SteamAchievementRarity.decode(bytes) } + catch { failedAt[url] = Date(); throw error } + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONEncoder().encode(SteamAchievementPercentsCache(fetchedAt: Date(), percents: percents)).write(to: file, options: .atomic) + return percents + } catch { return cached?.percents } + } + + /// An achievement's icon from Steam's CDN, kept on disk as long as it reads as an image. + public func achievementIcon(appID: UInt32, file name: String) async -> URL? { + guard appID > 0, !Task.isCancelled, let url = SteamAchievementRarity.iconURL(appID: appID, file: name) else { return nil } + let file = directory.appendingPathComponent("\(appID)/achievements/\(name)") + let limit = 2_097_152 + if let data = try? InstallationFileSnapshot.read(at: file, maximumBytes: limit).data, + ArtworkStore.downsample(data, maxPixelSize: 256) != nil { return file } + guard let data = try? await fetch(url), !Task.isCancelled else { return nil } + guard data.count <= limit, ArtworkStore.downsample(data, maxPixelSize: 256) != nil else { failedAt[url] = Date(); return nil } + do { + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: file, options: .atomic) + return file + } catch { return nil } + } + + public func image(appID: UInt32, slot: ArtworkSlot, remote: URL? = nil) async -> URL? { + guard appID > 0, !Task.isCancelled else { return nil } + // Screenshots use their full URL in the cache key; no basename collisions. + let token = remote.map { SHA256.hash(data: Data($0.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined() } + let file = directory.appendingPathComponent("\(appID)/images/\(token ?? slot.rawValue).png") + let cached = try? InstallationFileSnapshot.read(at: file, maximumBytes: 12_582_912).data + let validCache = cached.flatMap { ArtworkStore.downsample($0, maxPixelSize: slot.kind.maxPixelSize, png: true) } != nil + let modified = try? file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate + if validCache, let modified, Date().timeIntervalSince(modified) < 604800 { return file } + let candidates = remote.map { [ArtworkCandidate(slot: slot, source: "Steam", url: $0)] } + ?? SteamStoreArt.candidates(appID: Int(appID), slot: slot) + for candidate in candidates { + for url in [candidate.url, candidate.fallback].compactMap({ $0 }).compactMap(SteamMetadata.safeImage) { + guard !Task.isCancelled else { return validCache ? file : nil } + guard let data = try? await fetch(url) else { continue } + guard !Task.isCancelled else { return validCache ? file : nil } + guard data.count <= 12_582_912, + let image = ArtworkStore.downsample(data, maxPixelSize: slot.kind.maxPixelSize, png: true) else { failedAt[url] = Date(); continue } + do { + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try image.write(to: file, options: .atomic); return file + } catch { return nil } + } + } + return validCache ? file : nil + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift b/Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift new file mode 100644 index 00000000..378fe4d0 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift @@ -0,0 +1,63 @@ +import Foundation +import Combine + +/// One manifest publishes a complete title draft. New image files are prepared +/// first; a failed manifest commit leaves every previous reference untouched. +public final class SteamPersonalizationStore: ObservableObject { + private struct Entry: Codable { var fields: [String: String]; var art: [String: String] } + @Published public private(set) var revision = 0 + private let directory: URL + private let publish: (Data, URL) throws -> Void + private let invalidManifest: Bool + private var entries: [String: Entry] + public init(directory: URL, publish: @escaping (Data, URL) throws -> Void = { try $0.write(to: $1, options: .atomic) }) { + self.directory = directory; self.publish = publish + let decoded = (try? InstallationFileSnapshot.read(at: directory.appendingPathComponent("personal.json"), maximumBytes: 16_777_216).data) + .flatMap { try? JSONDecoder().decode([String: Entry].self, from: $0) } + entries = decoded ?? [:] + invalidManifest = FileManager.default.fileExists(atPath: directory.appendingPathComponent("personal.json").path) && decoded == nil + } + public func value(titleID: String, field: MetadataField) -> String? { entries[titleID]?.fields[field.rawValue] } + public func url(titleID: String, slot: ArtworkSlot) -> URL? { + guard let name = entries[titleID]?.art[slot.rawValue], name == URL(fileURLWithPath: name).lastPathComponent else { return nil } + return directory.appendingPathComponent("assets").appendingPathComponent(name) + } + public func save(fields: [MetadataField: String], images: [ArtworkSlot: Data], automatic: Set<ArtworkSlot>, titleID: String) throws { + guard !invalidManifest else { throw URLError(.cannotParseResponse) } + var draft = entries + var entry = entries[titleID] ?? Entry(fields: [:], art: [:]) + var created: [URL] = [] + do { + for (field, raw) in fields { + guard raw.utf8.count <= 100_000 else { throw URLError(.dataLengthExceedsMaximum) } + let text = raw.trimmingCharacters(in: .whitespacesAndNewlines) + entry.fields[field.rawValue] = text.isEmpty ? nil : text + } + for (slot, data) in images { + guard data.count <= 12_582_912, + let normalized = ArtworkStore.downsample(data, maxPixelSize: slot.kind.maxPixelSize, png: true) else { throw URLError(.cannotDecodeContentData) } + let name = UUID().uuidString + ".png" + let file = directory.appendingPathComponent("assets").appendingPathComponent(name) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try normalized.write(to: file, options: .atomic); created.append(file); entry.art[slot.rawValue] = name + } + for slot in automatic { entry.art[slot.rawValue] = nil } + draft[titleID] = entry + let data = try JSONEncoder().encode(draft) + guard data.count <= 16_777_216 else { throw URLError(.dataLengthExceedsMaximum) } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try publish(data, directory.appendingPathComponent("personal.json")) + } catch { + for file in created { try? FileManager.default.removeItem(at: file) } + throw error + } + let retained = Set(draft.values.flatMap { $0.art.values }) + let old = Set(entries.values.flatMap { $0.art.values }).subtracting(retained) + entries = draft; revision += 1 + // Only obsolete generated copies, after successful publication. Automatic + // is removal of a manifest reference, so a file deletion cannot undo it. + for name in old where name == URL(fileURLWithPath: name).lastPathComponent { + try? FileManager.default.removeItem(at: directory.appendingPathComponent("assets").appendingPathComponent(name)) + } + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift new file mode 100644 index 00000000..764f74e4 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift @@ -0,0 +1,151 @@ +import Foundation + +/// One live process as the system reports it, reduced to what identifies an installed app. +public struct NativeProcessObservation: Equatable, Sendable { + public let pid: Int32 + public let bundleURL: URL? + public let executableURL: URL? + public init(pid: Int32, bundleURL: URL?, executableURL: URL?) { + self.pid = pid; self.bundleURL = bundleURL; self.executableURL = executableURL + } + + /// The same process with its paths resolved (symlinks, `..`), the form `SteamPlayState` compares. + /// A process's paths don't change while it lives, so callers resolve each pid once. + public func canonical() -> NativeProcessObservation { + NativeProcessObservation(pid: pid, bundleURL: bundleURL.map(SteamPlayState.canonical), + executableURL: executableURL.map(SteamPlayState.canonical)) + } +} + +public enum SteamPlayFailure: Equatable, Sendable { + /// No single available, recognized installation in an enabled source. + case unavailable + /// No Steam client registered on this Mac. + case clientMissing + /// The system did not hand the request to Steam. + case handoffRejected + /// Steam took the request but the game's own app never appeared in time. + case notStarted +} + +/// A Steam game's Play and its real session, as pure state. Handing the request to Steam +/// starts nothing: the session starts when the installation's own app is seen running and +/// ends when that process goes, whatever Steam itself does. A game started from Steam +/// directly is followed the same way. Requests carry a generation, so a late answer to an +/// older Play never changes a newer one. +public struct SteamPlayState: Equatable, Sendable { + public enum Phase: Equatable, Sendable { + case idle + /// Waiting for the game's app; a rejected hand-off changes this to `.failed`. + case starting(since: Date) + case running(pid: Int32) + case failed(SteamPlayFailure) + } + + public enum Request: Equatable, Sendable { + case handOff(URL, generation: Int) + case resume(pid: Int32) + /// Play pressed again while the first request is still on its way: nothing new is sent. + case wait + case refuse(SteamPlayFailure) + } + + public enum Change: Equatable, Sendable { + case started(pid: Int32) + case ended(pid: Int32) + } + + /// Steam may install an update or show its own window before the game starts. + public static let startDeadline: TimeInterval = 300 + + public private(set) var phase: Phase = .idle + public private(set) var generation = 0 + /// The app the running session saw start: it lasts while that process lives, whatever the catalog + /// says about the installation since (removed in a refresh, or now named at another path). + private var runningBundle: URL? + + public init() {} + + /// Steam's Downloads page, for a game Steam is still installing. With `launchURL`, the only URLs NX Library sends. + public static let downloadsURL = URL(string: "steam://open/downloads")! + + /// Built from a validated numeric AppID, nothing else. + public static func launchURL(appID: UInt32) -> URL? { + appID > 0 ? URL(string: "steam://run/\(appID)") : nil + } + + public mutating func requestPlay(target: CatalogLaunchTarget?, clientAvailable: Bool, now: Date) -> Request { + switch phase { + case .running(let pid): return .resume(pid: pid) + case .starting: return .wait + case .idle, .failed: break + } + guard case .steam(let appID)? = target, let url = Self.launchURL(appID: appID) else { + phase = .failed(.unavailable); return .refuse(.unavailable) + } + guard clientAvailable else { phase = .failed(.clientMissing); return .refuse(.clientMissing) } + generation += 1 + phase = .starting(since: now) + return .handOff(url, generation: generation) + } + + /// The system's answer to the hand-off. Only the current request's answer counts. + public mutating func handoffFinished(accepted: Bool, generation: Int) { + guard generation == self.generation, case .starting = phase else { return } + if !accepted { phase = .failed(.handoffRejected) } + } + + /// The player gave up waiting, or dismissed a failure. + public mutating func cancel() { + switch phase { + case .starting, .failed: phase = .idle; generation += 1 + case .idle, .running: break + } + } + + /// Reads the process list, given in `canonical()` form. A running session ends when its process is + /// gone; otherwise the installation's own app, once seen, starts one. Waiting too long fails without a session. + public mutating func observe(_ processes: [NativeProcessObservation], application: CatalogNativeApplication?, + now: Date) -> Change? { + if case .running(let pid) = phase { + // Same pid and still the app it started as: a pid the system reused for another program is not the game. + if processes.contains(where: { process in + process.pid == pid && (runningBundle.map { bundle in process.bundleURL.map { Self.same($0, bundle) } ?? false } ?? true) + }) { return nil } + phase = .idle + runningBundle = nil + return .ended(pid: pid) + } + // The installation's paths are resolved once here, not once per process. + if let target = application.map(Target.init), let match = processes.first(where: target.matches) { + phase = .running(pid: match.pid) + runningBundle = match.bundleURL + return .started(pid: match.pid) + } + if case .starting(let since) = phase, now.timeIntervalSince(since) > Self.startDeadline { + phase = .failed(.notStarted) + } + return nil + } + + /// An installation's app with its paths resolved, for comparing against canonical processes. + private struct Target { + let bundle: String + let executable: String + init(_ application: CatalogNativeApplication) { + bundle = SteamPlayState.canonical(application.url).path + executable = SteamPlayState.canonical(application.executableURL).path + } + func matches(_ process: NativeProcessObservation) -> Bool { + guard let url = process.bundleURL, url.standardizedFileURL.path == bundle else { return false } + guard let executableURL = process.executableURL else { return true } + return executableURL.standardizedFileURL.path == executable + } + } + + /// Symlinks and `..` resolved: two names for one app compare equal. + public static func canonical(_ url: URL) -> URL { url.resolvingSymlinksInPath().standardizedFileURL } + + /// Both URLs are canonical already: no filesystem access. + static func same(_ a: URL, _ b: URL) -> Bool { a.standardizedFileURL.path == b.standardizedFileURL.path } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift new file mode 100644 index 00000000..3082677b --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift @@ -0,0 +1,94 @@ +import Foundation + +/// Steam's total for one game and when NX Library first saw that value. `carry` is time NX Library had +/// already shown beyond Steam's new whole minutes (at most `maximumCarry`), so a rising value never +/// makes the total step back. +public struct SteamPlaytimeBaseline: Codable, Equatable, Sendable { + public static let maximumCarry: TimeInterval = 60 + public let appID: UInt32 + public let minutes: Int + public let lastPlayed: Date? + public let seenAt: Date + public let carry: TimeInterval + public init(appID: UInt32, minutes: Int, lastPlayed: Date?, seenAt: Date, carry: TimeInterval = 0) { + self.appID = appID; self.minutes = minutes; self.lastPlayed = lastPlayed; self.seenAt = seenAt; self.carry = carry + } + + private enum CodingKeys: String, CodingKey { case appID, minutes, lastPlayed, seenAt, carry } + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + appID = try c.decode(UInt32.self, forKey: .appID) + minutes = try c.decode(Int.self, forKey: .minutes) + lastPlayed = try c.decodeIfPresent(Date.self, forKey: .lastPlayed) + seenAt = try c.decode(Date.self, forKey: .seenAt) + carry = try c.decodeIfPresent(TimeInterval.self, forKey: .carry) ?? 0 + } +} + +/// The current account's Steam totals, each with when its value was first seen. NX Library adds only +/// its own play after `seenAt`: Steam's value already counts what came before. A new value (up or down) +/// or another account starts over; Steam is the source of truth. +public struct SteamPlaytimeBaselines: Equatable, Sendable { + public let fileURL: URL + public private(set) var accountID: UInt32? + public private(set) var byAppID: [UInt32: SteamPlaytimeBaseline] = [:] + + private struct File: Codable { var accountID: UInt32; var baselines: [SteamPlaytimeBaseline] } + + /// Loads the saved baselines; a missing or broken file means none. + public init(fileURL: URL) { + self.fileURL = fileURL + guard let data = try? Data(contentsOf: fileURL), + let file = try? JSONDecoder().decode(File.self, from: data) else { return } + accountID = file.accountID + byAppID = Dictionary(file.baselines.map { ($0.appID, $0) }, uniquingKeysWith: { first, _ in first }) + } + + /// Takes a new reading. `previousTotals` are the totals shown until now, by AppID: when Steam's value + /// rises, what they showed beyond it (up to a minute) is carried. Returns whether anything changed. + @discardableResult + public mutating func apply(_ snapshot: SteamPlaytimeSnapshot, now: Date, + previousTotals: [UInt32: TimeInterval] = [:]) -> Bool { + let previous = snapshot.accountID == accountID ? byAppID : [:] + var next: [UInt32: SteamPlaytimeBaseline] = [:] + for (appID, entry) in snapshot.entries { + let old = previous[appID] + var seenAt = now, carry: TimeInterval = 0 + if let old, old.minutes == entry.minutes { + seenAt = old.seenAt; carry = old.carry + } else if let old, entry.minutes > old.minutes, let shown = previousTotals[appID] { + carry = min(SteamPlaytimeBaseline.maximumCarry, max(0, shown - TimeInterval(entry.minutes) * 60)) + } + next[appID] = SteamPlaytimeBaseline(appID: appID, minutes: entry.minutes, lastPlayed: entry.lastPlayed, + seenAt: seenAt, carry: carry) + } + let changed = snapshot.accountID != accountID || next != byAppID + accountID = snapshot.accountID + byAppID = next + return changed + } + + /// Writes atomically; the directory is created when missing. + public func save() throws { + guard let accountID else { return } + let file = File(accountID: accountID, baselines: byAppID.values.sorted { $0.appID < $1.appID }) + try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONEncoder().encode(file).write(to: fileURL, options: .atomic) + } + + /// When each catalog Steam game's value was seen, for `PlaySessionStore.setTrimReferences`. + public func references(for games: [CatalogGame]) -> [UUID: Date] { + external(for: games).mapValues(\.since) + } + + /// The catalog's Steam games with a baseline, by game UUID, for `PlaySessionStore.setExternal`. + public func external(for games: [CatalogGame]) -> [UUID: ExternalPlaytime] { + var result: [UUID: ExternalPlaytime] = [:] + for game in games { + guard let appID = game.steamGame?.appID, let baseline = byAppID[appID] else { continue } + result[game.id] = ExternalPlaytime(duration: TimeInterval(baseline.minutes) * 60 + baseline.carry, + lastPlayed: baseline.lastPlayed, since: baseline.seenAt) + } + return result + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift new file mode 100644 index 00000000..f3d344d0 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift @@ -0,0 +1,84 @@ +import Foundation + +/// One game's playtime as Steam keeps it for an account: minutes on every computer, and the last start. +public struct SteamPlaytimeEntry: Codable, Equatable, Sendable { + public let minutes: Int + public let lastPlayed: Date? + public init(minutes: Int, lastPlayed: Date?) { self.minutes = minutes; self.lastPlayed = lastPlayed } +} + +/// The current account's playtime, by AppID. +public struct SteamPlaytimeSnapshot: Equatable, Sendable { + public let accountID: UInt32 + public let entries: [UInt32: SteamPlaytimeEntry] + public init(accountID: UInt32, entries: [UInt32: SteamPlaytimeEntry]) { self.accountID = accountID; self.entries = entries } +} + +/// Reads Steam's own playtime from `userdata/<account>/config/localconfig.vdf`. Only `Playtime` and +/// `LastPlayed` under `UserLocalConfigStore › Software › Valve › Steam › apps` leave this type: the file +/// also holds app tickets and other private blocks, which are parsed in passing and never kept. +/// Nothing is written to Steam. +public enum SteamPlaytimeReader { + static let maximumBytes = 8 * 1024 * 1024 + private static let steamID64Base: UInt64 = 76_561_197_960_265_728 + + /// The account signed in most recently on this Mac, or nil when none has. + /// An unreadable `loginusers.vdf` throws: Steam may be rewriting it, which is not "no account". + public static func accountID(root: URL) throws -> UInt32? { + let users = root.appendingPathComponent("config/loginusers.vdf") + guard FileManager.default.fileExists(atPath: users.path) else { return nil } + return try accountID(loginUsers: text(at: users)) + } + + public static func localConfigURL(root: URL, account: UInt32) -> URL { + root.appendingPathComponent("userdata/\(account)/config/localconfig.vdf") + } + + public static func read(config: URL, account: UInt32) throws -> SteamPlaytimeSnapshot { + SteamPlaytimeSnapshot(accountID: account, entries: try entries(localConfig: text(at: config))) + } + + /// The account marked `MostRecent`, else the latest `timestamp`. + public static func accountID(loginUsers text: String) throws -> UInt32? { + guard case .object(let users)? = try KeyValuesDocument(text: text).uniqueValue(for: "users") else { return nil } + var best: (account: UInt32, recent: Bool, timestamp: Int)? + for user in users { + guard case .object(let fields) = user.value, let id = UInt64(user.key), id >= steamID64Base, + let account = UInt32(exactly: id - steamID64Base) else { continue } + let recent = (try? fields.uniqueString(for: "MostRecent")) == "1" + let timestamp = (try? fields.uniqueString(for: "timestamp")).flatMap { Int($0) } ?? 0 + if let current = best, current.recent != recent ? current.recent : current.timestamp >= timestamp { continue } + best = (account, recent, timestamp) + } + return best?.account + } + + /// Every app with a numeric `Playtime`; a `LastPlayed` of 0 or none is no date. A file without its + /// root (empty, or mid-rewrite) throws; an account that never played anything has no entries. + /// The file only holds data, so `#` keys are ordinary keys, and a repeated block on the path is + /// read from its first copy: nothing outside the two fields can fail the read. + public static func entries(localConfig text: String) throws -> [UInt32: SteamPlaytimeEntry] { + let document = try KeyValuesDocument(text: text, maximumEntries: 500_000, rejectsDirectives: false) + guard var node = document.entries.firstValue(for: "UserLocalConfigStore") else { throw KeyValuesError.malformed } + for key in ["Software", "Valve", "Steam", "apps"] { + guard case .object(let children) = node, let child = children.firstValue(for: key) else { return [:] } + node = child + } + guard case .object(let apps) = node else { return [:] } + var result: [UInt32: SteamPlaytimeEntry] = [:] + for app in apps { + guard let appID = UInt32(app.key), appID > 0, case .object(let fields) = app.value, + let minutes = (try? fields.uniqueString(for: "Playtime")).flatMap({ Int($0) }), minutes >= 0 else { continue } + let seconds = (try? fields.uniqueString(for: "LastPlayed")).flatMap { TimeInterval($0) } ?? 0 + result[appID] = SteamPlaytimeEntry(minutes: minutes, + lastPlayed: seconds > 0 ? Date(timeIntervalSince1970: seconds) : nil) + } + return result + } + + private static func text(at url: URL) throws -> String { + let data = try InstallationFileSnapshot.read(at: url, maximumBytes: maximumBytes).data + guard let text = String(data: data, encoding: .utf8) else { throw KeyValuesError.malformed } + return text + } +} diff --git a/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift new file mode 100644 index 00000000..00c576c7 --- /dev/null +++ b/Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift @@ -0,0 +1,127 @@ +import Foundation + +/// Which `localconfig.vdf` was read, and its modification date then. +public struct SteamFileStamp: Equatable, Sendable { + public let file: URL + public let modified: Date + public init(file: URL, modified: Date) { self.file = file; self.modified = modified } +} + +/// One look at Steam's files, taken off the main thread. +public enum SteamPlaytimeReading: Equatable, Sendable { + /// No account has signed in on this Mac, or the account has no `localconfig.vdf`. + case noAccount + /// The file has not changed since `known`. + case unchanged(accountID: UInt32) + /// A file could not be read or parsed (Steam may be rewriting it); the account when known. + case failed(accountID: UInt32?) + case read(SteamPlaytimeSnapshot, SteamFileStamp) + + /// Reads only when the file's modification date moved since `known`. + public static func take(root: URL, known: SteamFileStamp?) -> Self { + let account: UInt32 + do { + guard let found = try SteamPlaytimeReader.accountID(root: root) else { return .noAccount } + account = found + } catch { return .failed(accountID: nil) } + let file = SteamPlaytimeReader.localConfigURL(root: root, account: account) + guard FileManager.default.fileExists(atPath: file.path) else { return .noAccount } + guard let modified = try? file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate + else { return .failed(accountID: account) } + let stamp = SteamFileStamp(file: file, modified: modified) + if stamp == known { return .unchanged(accountID: account) } + do { return .read(try SteamPlaytimeReader.read(config: file, account: account), stamp) } + catch { return .failed(accountID: account) } + } +} + +/// What each reading does to the saved baselines and to the totals shown. A failure keeps the last good +/// totals, unless they belong to another account; only "no account" clears them. +public struct SteamPlaytimeSync: Equatable, Sendable { + public enum Result: Equatable, Sendable { + /// Totals for `PlaySessionStore.setExternal`; `save` when the baselines changed. + case publish([UUID: ExternalPlaytime], save: Bool) + case clear + } + + public private(set) var baselines: SteamPlaytimeBaselines + /// The last file read in full; a failed reading leaves it, so the next one tries again. + public private(set) var stamp: SteamFileStamp? + /// The account the last reading named, so a reading that cannot name one does not bring back + /// totals already hidden for another account. + private var lastAccount: UInt32? + + public init(baselines: SteamPlaytimeBaselines) { self.baselines = baselines } + + /// The Steam folder changed: the next reading reads in full. + public mutating func resetStamp() { stamp = nil } + + /// `shownTotal(game, old)` is the game's total under its old baseline (`PlaySessionStore.totalDuration(for:with:)`), + /// so a rising Steam value can carry what that baseline showed (`SteamPlaytimeBaseline.carry`), whatever is + /// published at the moment. + public mutating func handle(_ reading: SteamPlaytimeReading, games: [CatalogGame], + shownTotal: (UUID, ExternalPlaytime) -> TimeInterval, now: Date) -> Result { + switch reading { + case .noAccount: + stamp = nil + lastAccount = nil + return .clear + case .unchanged(let account), .failed(let account?): + lastAccount = account + guard baselines.accountID == account else { return .clear } + return .publish(baselines.external(for: games), save: false) + case .failed(nil): + guard lastAccount == nil || lastAccount == baselines.accountID else { return .clear } + return .publish(baselines.external(for: games), save: false) + case .read(let snapshot, let newStamp): + lastAccount = snapshot.accountID + var shown: [UInt32: TimeInterval] = [:] + if snapshot.accountID == baselines.accountID { + let old = baselines.external(for: games) + for game in games { + if let appID = game.steamGame?.appID, let base = old[game.id] { shown[appID] = shownTotal(game.id, base) } + } + } + let changed = baselines.apply(snapshot, now: now, previousTotals: shown) + stamp = newStamp + return .publish(baselines.external(for: games), save: changed) + } + } +} + +/// One read of Steam's files at a time. A request during a read is served by one more read when it +/// finishes; a read whose purpose no longer holds (another Steam folder) is not applied and is read +/// again; after `stop` nothing is applied or read again. +public struct SteamPlaytimeReadQueue: Equatable, Sendable { + public private(set) var isReading = false + private var generation = 0 + private var again = false + + public init() {} + + /// The ticket to start a read, or nil while one runs. + public mutating func request() -> Int? { + if isReading { again = true; return nil } + isReading = true + return generation + } + + /// A read in progress no longer applies; one more read follows it. + public mutating func invalidate() { + generation += 1 + again = isReading + } + + /// Nothing more is wanted: the read in progress is not applied and no read follows. + public mutating func stop() { + generation += 1 + again = false + } + + /// Whether to apply the finished read's result, and whether to read again. + public mutating func finish(_ ticket: Int) -> (apply: Bool, readAgain: Bool) { + isReading = false + defer { again = false } + return (ticket == generation, again) + } +} diff --git a/Sources/NXLibraryCore/Services/SteamGridDBArt.swift b/Sources/NXLibraryCore/Services/SteamGridDBArt.swift index b3511810..2b6ebf53 100644 --- a/Sources/NXLibraryCore/Services/SteamGridDBArt.swift +++ b/Sources/NXLibraryCore/Services/SteamGridDBArt.swift @@ -9,8 +9,7 @@ public struct SteamGridDBKey { public init(url: URL = SteamGridDBKey.defaultURL()) { self.url = url } public static func defaultURL() -> URL { - FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary/steamgriddb-api-key") + AppData.supportRoot.appendingPathComponent("steamgriddb-api-key") } /// A key as SteamGridDB writes it: letters and digits only (its keys are 32 hex digits). @@ -71,7 +70,7 @@ public enum SteamGridDBArt { var request = URLRequest(url: url) request.timeoutInterval = 15 request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") - request.setValue("NXLibrary/0.1 (macOS; personal app)", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") return request } diff --git a/Sources/NXLibraryCore/Services/StorageManager.swift b/Sources/NXLibraryCore/Services/StorageManager.swift index 608f0868..670928a9 100644 --- a/Sources/NXLibraryCore/Services/StorageManager.swift +++ b/Sources/NXLibraryCore/Services/StorageManager.swift @@ -34,8 +34,7 @@ public final class StorageManager { private let fm: FileManager public init( - supportRoot: URL = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/NXLibrary"), + supportRoot: URL = AppData.supportRoot, applicationsRoot: URL = URL(fileURLWithPath: NSHomeDirectory()) .appendingPathComponent("Applications"), logsRoot: URL = FileManager.default.homeDirectoryForCurrentUser diff --git a/Sources/NXLibraryCore/Services/UpstreamChecker.swift b/Sources/NXLibraryCore/Services/UpstreamChecker.swift index f169eb23..887d69f7 100644 --- a/Sources/NXLibraryCore/Services/UpstreamChecker.swift +++ b/Sources/NXLibraryCore/Services/UpstreamChecker.swift @@ -120,7 +120,7 @@ public final class UpstreamChecker { request.timeoutInterval = 20 request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") request.setValue("2022-11-28", forHTTPHeaderField: "X-GitHub-Api-Version") - request.setValue("NXLibrary/0.1", forHTTPHeaderField: "User-Agent") + request.setValue(AppIdentity.userAgent(), forHTTPHeaderField: "User-Agent") let (data, http) = try await client.data(for: request) let message = (try? JSONDecoder().decode(APIError.self, from: data))?.message diff --git a/Sources/NXLibraryCore/Services/WikidataRatings.swift b/Sources/NXLibraryCore/Services/WikidataRatings.swift new file mode 100644 index 00000000..94f1e176 --- /dev/null +++ b/Sources/NXLibraryCore/Services/WikidataRatings.swift @@ -0,0 +1,130 @@ +import Foundation + +/// Narrow Wikidata contract: exact video-game identity and referenced /100 critic aggregates. +/// Source/metric IDs come from the inspected P444/P447/P459 statements, not label guesses. +public enum WikidataRatings { + static func isItemID(_ value: String) -> Bool { + value.first == "Q" && value.count > 1 && value.dropFirst().allSatisfy { $0.isASCII && $0.isNumber } + } + private static func normalized(_ value: String) -> String { + String(value.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "en_US_POSIX")) + .unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) }) + } + public static func searchURL(name: String) -> URL? { + guard !name.isEmpty, name.count <= 300 else { return nil } + // Store trademarks prevent wbsearchentities from finding an otherwise exact title. + // Keep edition/sequel words: those carry identity, unlike the trademark marks. + let clean = ["™", "®", "©"].reduce(name) { $0.replacingOccurrences(of: $1, with: "") } + .split(whereSeparator: \.isWhitespace).joined(separator: " ") + guard !clean.isEmpty else { return nil } + return url(["action": "wbsearchentities", "search": clean, "language": "en", "type": "item", "limit": "5"]) + } + public static func steamSearchURL(appID: UInt32) -> URL? { + guard appID > 0 else { return nil } + return url(["action": "query", "list": "search", "srsearch": "haswbstatement:P1733=\(appID)", + "srnamespace": "0", "srlimit": "5", "srprop": ""]) + } + public static func steamIDs(in data: Data) throws -> [String] { + let root = try object(data) + guard let query = root["query"] as? [String: Any], let search = query["search"] as? [[String: Any]] + else { throw URLError(.cannotParseResponse) } + return Array(Set(search.compactMap { item -> String? in + guard let id = item["title"] as? String, isItemID(id), item["ns"] as? Int == 0 else { return nil } + return id + })).sorted() + } + public static func entitiesURL(ids: [String]) -> URL? { + guard !ids.isEmpty, ids.count <= 5, ids.allSatisfy(isItemID) else { return nil } + return url(["action": "wbgetentities", "ids": ids.joined(separator: "|"), "props": "claims"]) + } + private static func url(_ values: [String: String]) -> URL? { + var components = URLComponents(string: "https://www.wikidata.org/w/api.php")! + components.queryItems = (values.merging(["format": "json", "maxlag": "5"], uniquingKeysWith: { _, b in b })) + .sorted { $0.key < $1.key }.map { .init(name: $0.key, value: $0.value) } + return components.url + } + public static func ids(in data: Data, name: String) throws -> [String] { + let root = try object(data) + guard let search = root["search"] as? [[String: Any]] else { throw URLError(.cannotParseResponse) } + let target = normalized(name) + guard !target.isEmpty else { return [] } + return Array(Set(search.compactMap { item -> String? in + guard let id = item["id"] as? String, isItemID(id) else { return nil } + var names = [item["label"] as? String].compactMap { $0 } + (item["aliases"] as? [String] ?? []) + if let match = item["match"] as? [String: String], match["type"] == "alias", let text = match["text"] { + names.append(text) + } + return names.contains { normalized($0) == target } ? id : nil + })).sorted() + } + public static func rating(in data: Data, ids: [String], query: CriticRatingQuery, + requireSteamID: Bool = false) throws -> CriticRating? { + let root = try object(data) + guard let entities = root["entities"] as? [String: [String: Any]], + ids.allSatisfy({ entities[$0] != nil }) else { throw URLError(.cannotParseResponse) } + let matched = ids.filter { id in + guard let claims = entities[id]?["claims"] as? [String: [[String: Any]]], + claimItems(claims["P31"] ?? []).contains("Q7889") else { return false } + let steam = (claims["P1733"] ?? []).filter { ($0["rank"] as? String) != "deprecated" } + .compactMap { ($0["mainsnak"] as? [String: Any]).flatMap(value) as? String } + if let expected = query.steamAppID, requireSteamID || !steam.isEmpty { return steam.contains(String(expected)) } + return true + } + guard matched.count == 1, let id = matched.first, + let claims = entities[id]?["claims"] as? [String: [[String: Any]]] else { return nil } + let ratings = (claims["P444"] ?? []).compactMap { parse($0, entityID: id, platform: query.platform.wikidataID) } + return ratings.sorted { a, b in + if a.platforms.isEmpty != b.platforms.isEmpty { return !a.platforms.isEmpty } + if a.source.priority != b.source.priority { return a.source.priority < b.source.priority } + if a.scoreDate != b.scoreDate { return (a.scoreDate ?? "") > (b.scoreDate ?? "") } + return (a.statementID ?? "") < (b.statementID ?? "") + }.first + } + private static func parse(_ claim: [String: Any], entityID: String, platform: String) -> CriticRating? { + guard claim["rank"] as? String != "deprecated", + let raw = (claim["mainsnak"] as? [String: Any]).flatMap(value) as? String, + let statement = claim["id"] as? String, statement.hasPrefix(entityID + "$"), + let quals = claim["qualifiers"] as? [String: [[String: Any]]] else { return nil } + let issuerSnaks = quals["P447"] ?? [] + let issuers = issuerSnaks.compactMap(item) + guard issuerSnaks.count == 1, issuers.count == 1 else { return nil } + let source: CriticRating.Source + let metric: String + switch issuers[0] { + case "Q21039459": source = .openCritic; metric = "Q114712322" + case "Q150248": source = .metacritic; metric = "Q106515043" + case "Q131917281": source = .criticDB; metric = "Q132178503" + default: return nil + } + let methods = (quals["P459"] ?? []).compactMap(item) + guard methods.count == (quals["P459"] ?? []).count else { return nil } + guard methods == [metric] || (methods.isEmpty && source == .metacritic) else { return nil } + let parts = raw.split(separator: "/", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) } + guard parts.count == 2, let score = Double(parts[0]), Double(parts[1]) == 100, + score.isFinite, (0...100).contains(score) else { return nil } + let platforms = (quals["P400"] ?? []).compactMap(item) + guard platforms.count == (quals["P400"] ?? []).count else { return nil } + guard platforms.isEmpty || platforms.contains(platform) else { return nil } + let refs = (claim["references"] as? [[String: Any]] ?? []).compactMap { $0["snaks"] as? [String: [[String: Any]]] } + let urls = refs.flatMap { $0["P854"] ?? [] }.compactMap { value($0) as? String }.compactMap(URL.init(string:)) + .filter { $0.scheme == "https" && $0.host != nil && $0.user == nil && $0.password == nil } + let items = refs.flatMap { $0["P248"] ?? [] }.compactMap(item) + guard !urls.isEmpty || !items.isEmpty else { return nil } + let date = (quals["P585"] ?? []).compactMap { value($0) as? [String: Any] }.compactMap { $0["time"] as? String }.sorted().last + return CriticRating(score: score, source: source, entityID: entityID, statementID: statement, + referenceURLs: urls, referenceItems: items, scoreDate: date, platforms: platforms) + } + private static func value(_ snak: [String: Any]) -> Any? { (snak["datavalue"] as? [String: Any])?["value"] } + private static func item(_ snak: [String: Any]) -> String? { + guard let id = (value(snak) as? [String: Any])?["id"] as? String, isItemID(id) else { return nil } + return id + } + private static func claimItems(_ claims: [[String: Any]]) -> [String] { + claims.filter { $0["rank"] as? String != "deprecated" }.compactMap { ($0["mainsnak"] as? [String: Any]).flatMap(item) } + } + private static func object(_ data: Data) throws -> [String: Any] { + guard data.count <= 4_194_304, let root = try JSONSerialization.jsonObject(with: data) as? [String: Any], + root["error"] == nil else { throw URLError(.cannotParseResponse) } + return root + } +} diff --git a/Tests/CatalogAppChecks/NoticeHost.swift b/Tests/CatalogAppChecks/NoticeHost.swift new file mode 100644 index 00000000..a230b4d6 --- /dev/null +++ b/Tests/CatalogAppChecks/NoticeHost.swift @@ -0,0 +1,54 @@ +import Foundation +@testable import NXLibraryCore + +struct SettingsNotice { var retry: (() -> Void)?; var onDismiss: (() -> Void)? = nil } +final class AppViewModel { + let catalogRepository: CatalogRepository + var personalizations = CatalogPersonalizations.empty + var catalogBuildRecoveries = CatalogBuildRecoveries() + var logs: [LogEntry] = [] + var alertMessage: String? + var settingsNotice: SettingsNotice? + var isBuilding = false + init(_ repository: CatalogRepository) { catalogRepository = repository } + func reportLibrarySaveFailure(_ error: Error) { alertMessage = error.localizedDescription } + func showSettingsNotice(title: String, message: String, actionTitle: String = "Retry", cancelTitle: String = "Back", retry: (() -> Void)? = nil) { + settingsNotice = SettingsNotice(retry: retry) + } + func applyCatalog(_ document: CatalogDocument) {} + func presentInstallFailure(for: PortedGame, error: String) {} +} +func require(_ ok: @autoclosure () -> Bool, _ message: String) throws { + if !ok() { throw NSError(domain: "NoticeProbe", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) } +} +func run() throws { +let root = FileManager.default.temporaryDirectory.appendingPathComponent("CatalogNotice-" + UUID().uuidString) +try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) +defer { try? FileManager.default.removeItem(at: root) } +let store = CatalogStore(directory: root) +var catalog = try store.loadOrMigrate() +let game = PortedGame(name: "Generated fixture", url: root.appendingPathComponent("Game.app"), platform: .macApp, sizeBytes: 1, modificationDate: Date()) +catalog.games = [.init(nxnative: game)] +_ = try store.save(catalog, expectedRevision: catalog.revision) +let failing = CatalogStore(directory: root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) }) +let model = AppViewModel(CatalogRepository(store: failing)) +model.reportCatalogFailure(POSIXError(.ENOSPC)) +try require(model.alertMessage == nil, "Catalog failure published legacy alert and can replace its Retry notice") +try require(model.settingsNotice?.retry != nil, "Catalog reload Retry missing") +_ = model.persistBuildOutcome(game) +try require(model.alertMessage == nil, "Build failure published legacy alert and can replace its save Retry") +try require(model.settingsNotice?.retry != nil, "Build save Retry missing") +try require(model.catalogBuildRecoveries[game.id] != nil, "Build recovery missing") +// Deliver a previously queued legacy alert after the retry notice exists. +model.alertMessage = "An earlier, unrelated alert" +let host = LegacyNoticeHost(viewModel: model) +host.deliver() +try require(model.settingsNotice?.retry != nil, "Queued legacy alert replaced the structured save Retry") +try require(model.alertMessage != nil, "Queued legacy alert was lost") +host.dismiss() +try require(model.alertMessage == nil, "Deferred legacy alert was not presented after dismissal") +try require(model.settingsNotice?.retry == nil, "Expected the deferred generic notice after dismissal") +print("Actual catalog helpers and legacy bridge preserve Retry and defer unrelated alerts.") + +} +do { try run() } catch { FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)); exit(1) } diff --git a/Tests/CatalogAppChecks/run_achievement_scroll.py b/Tests/CatalogAppChecks/run_achievement_scroll.py new file mode 100644 index 00000000..74c088c3 --- /dev/null +++ b/Tests/CatalogAppChecks/run_achievement_scroll.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Exercise actual achievement list/model lifecycle in an offscreen SwiftUI host. + +No windows, screenshots or UI automation. Graphics and external data use small +stand-ins; the list, selection model, scroll model and geometry group are real. +Run after swift test on macOS. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' +source = (ROOT / 'Sources/NXLibrary/Views/Spotlight/AchievementsScreen.swift').read_text() +start = source.index('private struct AchievementsList: View') +end = source.index('\n/// The trophies,', start) + +host = r''' +import AppKit +import SwiftUI +import NXLibraryCore + +struct ProbeCanvas { + var scale: CGFloat = 1 + func u(_ value: CGFloat) -> CGFloat { value * scale } +} +private struct CanvasKey: EnvironmentKey { static let defaultValue = ProbeCanvas() } +private struct MotionKey: EnvironmentKey { static let defaultValue = true } +extension EnvironmentValues { + var seleneCanvas: ProbeCanvas { + get { self[CanvasKey.self] } set { self[CanvasKey.self] = newValue } + } + var seleneReduceMotion: Bool { + get { self[MotionKey.self] } set { self[MotionKey.self] = newValue } + } +} +extension View { + func seleneFont(_ size: CGFloat) -> some View { font(.system(size: size)) } +} +enum SeleneTheme { static let ink60 = Color.gray } +enum DetailScroll { static let glide = Animation.spring(response: 0.3, dampingFraction: 1) } +enum AchievementsScreen { + static let rowHeight: CGFloat = 96, rowSpacing: CGFloat = 16, ring: CGFloat = 6 + static let listWidth: CGFloat = 1700, topFade: CGFloat = 40 + static let bottomFade: CGFloat = 110, hintsBand: CGFloat = 84, bottomRoom: CGFloat = 194 +} +struct AchievementsScreenRow: View { + let row: AchievementRow + let appID: UInt32 + let focused: Bool + var body: some View { Text(row.name).frame(width: 1700, height: 96) } +} +let summary = AchievementSummary(achievements: (0..<41).map { + SteamAchievement(apiName: "generated-\($0)", name: "Row \($0)", description: "Generated fixture", + hidden: false, icon: nil, grayIcon: nil, unlockedAt: nil) +}, percents: [:]) +let rows = summary.rows(.all) + +@MainActor final class Owner: ObservableObject { + @Published var model: AchievementsScreenModel? = AchievementsScreenModel(ids: rows.map(\.id)) + @Published var reducedMotion = false + @Published var height: CGFloat = 400 +} +struct ScreenHost: View { + @ObservedObject var model: AchievementsScreenModel + var body: some View { + ZStack { + AchievementsList(scroll: model.scroll, model: model, rows: rows, focused: model.state.index, + appID: 42, onFocus: { model.focus($0) }) + if model.state.isDetailOpen { Color.black.opacity(0.5).transition(.opacity) } + } + .animation(.easeOut(duration: 0.2), value: model.state.isDetailOpen) + } +} +struct Probe: View { + @ObservedObject var owner: Owner + var body: some View { + ZStack { + if let model = owner.model { ScreenHost(model: model).transition(.opacity) } + } + .frame(width: 1712, height: owner.height) + .environment(\.seleneReduceMotion, owner.reducedMotion) + .animation(.timingCurve(0.32, 0.72, 0, 1, duration: 0.32), value: owner.model != nil) + } +} + +@main struct Check { + @MainActor static func main() { + NSApplication.shared.setActivationPolicy(.prohibited) + var failures = 0 + func require(_ condition: Bool, _ message: String) { + if !condition { failures += 1; print("FAIL: " + message) } + } + for reducedMotion in [false, true] { + let owner = Owner() + owner.reducedMotion = reducedMotion + let host = NSHostingView(rootView: Probe(owner: owner)) + host.frame = CGRect(x: 0, y: 0, width: 1712, height: 400) + func settle(_ steps: Int = 10) { + for _ in 0..<steps { + _ = host.fittingSize + host.layoutSubtreeIfNeeded() + RunLoop.main.run(until: Date().addingTimeInterval(0.01)) + } + } + func walk(_ label: String) { + let model = owner.model! + for _ in 0..<12 { _ = model.handle(.navigateDown, summary: summary) } + settle() + require(model.state.index == 12, label + ": selection reaches row 12") + require(model.scroll.state.content > 4000 && model.scroll.state.visible == owner.height, + label + ": current list receives its geometry") + require(model.scroll.state.offset > 1000, label + ": viewport follows selection") + } + settle() + walk("First open") + + owner.model!.focus(0) + for _ in 0..<5 { + _ = owner.model!.handle(.confirm, summary: summary) + settle(1) + _ = owner.model!.handle(.cancel, summary: summary) + settle(1) + } + walk("Repeated first-row details") + + // The outgoing view is still in its 320 ms transition when the new model arrives. + for index in 0..<3 { + owner.model = nil + settle(1) + owner.model = AchievementsScreenModel(ids: rows.map(\.id)) + settle() + walk("Rapid reopening \(index), reduced motion \(reducedMotion)") + } + + owner.model = nil + settle(40) + owner.model = AchievementsScreenModel(ids: rows.map(\.id)) + settle() + walk("Reopening after transition") + owner.height = 320 + host.frame.size.height = 320 + settle() + require(owner.model!.scroll.state.visible == 320, "Resizing reports the new viewport") + require(host.window == nil, "Probe must never display a window") + } + if failures > 0 { exit(1) } + print("Achievement scroll checks passed: first-row details, rapid/settled reopening, resize and reduced motion. No windows displayed.") + } +} +''' + source[start:end] + +with tempfile.TemporaryDirectory(prefix='achievement-scroll-check-') as folder: + scratch = Path(folder) + swift = scratch / 'check.swift' + swift.write_text(host) + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift), + str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'), + str(ROOT / 'Sources/NXLibrary/ViewModels/AchievementsScreenModel.swift'), + str(ROOT / 'Sources/NXLibrary/ViewModels/ListScroll.swift'), + str(ROOT / 'Sources/NXLibrary/Views/Components/GlideGroup.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True) + subprocess.run([str(executable)], check=True, + env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))) diff --git a/Tests/CatalogAppChecks/run_artwork_return.py b/Tests/CatalogAppChecks/run_artwork_return.py new file mode 100644 index 00000000..d6aed328 --- /dev/null +++ b/Tests/CatalogAppChecks/run_artwork_return.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Check the artwork chosen by a recreated view before its first async task. + +Compiles the actual artwork views and task bodies. An Image value records its +input instead of rendering; no window, screenshot or UI automation. Uses real +decoding and generated files, isolated picks and no network/player data. +""" +from pathlib import Path +import os +import plistlib +import struct +import subprocess +import tempfile +import zlib +import argparse + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' +parser = argparse.ArgumentParser() +parser.add_argument('--source-root', type=Path, default=ROOT, + help='Optional source snapshot for regression checks; Core stays in the main checkout.') +SOURCE = parser.parse_args().source_root + + +def task_body(source): + start = source.index('.task(id:') + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[opening + 1:end - 1] + + +with tempfile.TemporaryDirectory(prefix='arcane-artwork-return-') as temporary: + scratch = Path(temporary) + for filename, path, old, new in ( + ('Native.swift', 'Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift', + 'ArtworkPicks.shared', 'Fixture.nativePicks'), + ('Steam.swift', 'Sources/NXLibrary/Views/Catalog/SteamArtwork.swift', + 'SteamPersonalizations.shared.artwork', 'Fixture.steamPicks'), + ): + source = (SOURCE / path).read_text().replace(old, new).replace('private ', '') + typename = 'SpotlightTileArtwork' if filename == 'Native.swift' else 'SteamArtwork' + source += '\nextension ' + typename + ' { func loadForCheck() async {\n' + task_body(source) + '\n} }\n' + (scratch / filename).write_text(source) + def chunk(kind, data): + return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)) + pixels = (b'\0' + b'\xe0\x30\x90\xff' * 16) * 16 + png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 16, 16, 8, 6, 0, 0, 0)) + png += chunk(b'IDAT', zlib.compress(pixels)) + chunk(b'IEND', b'') + (scratch / 'image.png').write_bytes(png) + pixels2 = (b'\0' + b'\x10\xe0\x10\xff' * 16) * 16 + png2 = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 16, 16, 8, 6, 0, 0, 0)) + png2 += chunk(b'IDAT', zlib.compress(pixels2)) + chunk(b'IEND', b'') + (scratch / 'image2.png').write_bytes(png2) + pixels3 = (b'\0' + b'\x20\x40\xf0\xff' * 16) * 16 + png3 = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 16, 16, 8, 6, 0, 0, 0)) + png3 += chunk(b'IDAT', zlib.compress(pixels3)) + chunk(b'IEND', b'') + (scratch / 'image3.png').write_bytes(png3) + app = scratch / 'Fixture.app' + (app / 'Contents/Resources').mkdir(parents=True) + (app / 'Contents/Resources/Icon.icns').write_bytes(png) + (app / 'Contents/Info.plist').write_bytes(plistlib.dumps({'CFBundleIconFile': 'Icon'})) + automatic = scratch / 'artwork/0100000000001000/square.png' + automatic.parent.mkdir(parents=True) + automatic.write_bytes(png) + host = scratch / 'check.swift' + host.write_text(r''' +import SwiftUI +import AppKit +@testable import NXLibraryCore + +@MainActor enum Fixture { + static let root = URL(fileURLWithPath: CommandLine.arguments[1]) + static let nativePicks = ArtworkPicks(directory: root.appendingPathComponent("native-picks")) + static let steamPicks = SteamPersonalizationStore(directory: root.appendingPathComponent("steam-picks")) + static let artwork = ArtworkStore(cacheDirectory: root.appendingPathComponent("artwork")) +} +@MainActor enum Capture { static var image: NSImage? } +struct Image: View { + init(nsImage: NSImage) { Capture.image = nsImage } + init(systemName: String) { Capture.image = nil } + func resizable() -> Self { self } + func interpolation(_ value: SwiftUI.Image.Interpolation) -> Self { self } + var body: some View { Color.clear } +} +enum SeleneTheme { static var glassSolid: Color { .gray } } +struct Canvas { func u(_ value: CGFloat) -> CGFloat { value } } +struct CanvasKey: EnvironmentKey { static let defaultValue = Canvas() } +extension EnvironmentValues { + var seleneCanvas: Canvas { get { self[CanvasKey.self] } set { self[CanvasKey.self] = newValue } } +} +@MainActor enum GameIconProvider { + static let generic = NSImage(size: NSSize(width: 32, height: 32)) + static var own: NSImage? + static func squareArt(for game: PortedGame) -> NSImage? { own } + static func icon(for game: PortedGame) -> NSImage { generic } +} +@MainActor enum AppViewModel { static var automaticIconArtwork: ArtworkStore { Fixture.artwork } } +@MainActor enum OnlineArtwork { + static func find(names: [String], slot: ArtworkSlot? = nil, + platform: CriticRatingQuery.Platform = .switch) async -> [ArtworkCandidate] { [] } +} +@main struct Check { + @MainActor static func main() async throws { + var failures = 0 + func require(_ value: Bool, _ message: String) { + if value { print("PASS: " + message) } + else { failures += 1; print("FAIL: " + message) } + } + func draw<V: View>(_ view: V) -> NSImage? { + Capture.image = nil + _ = view.body + return Capture.image + } + let root = Fixture.root + let png = try Data(contentsOf: root.appendingPathComponent("image.png")) + var native = PortedGame(name: "Fixture", url: root.appendingPathComponent("not-built"), + platform: .macApp, sizeBytes: 0, modificationDate: Date()) + native.titleId = "0100000000001000" + let automatic = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true) + await automatic.loadForCheck() + let returned = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true) + require(draw(returned).map { $0 !== GameIconProvider.generic } == true, + "nxnative automatic art is present before the recreated view's task") + + try Fixture.nativePicks.save(png, titleID: native.titleId!, slot: .icon) + let personal = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true) + await personal.loadForCheck() + let personalReturn = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true) + let personalImage = draw(personalReturn) + require(personalImage.map { $0 !== GameIconProvider.generic } == true, + "nxnative personal art is present before the recreated view's task") + Fixture.nativePicks.remove(titleID: native.titleId!, slot: .icon) + let noPick = SpotlightTileArtwork(game: native, side: 160, artwork: Fixture.artwork, ownIconFirst: true) + require(personalImage == nil || draw(noPick) !== personalImage, + "removing a pick does not reuse its decoded image") + + let app = root.appendingPathComponent("Fixture.app") + let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"), + bundleIdentifier: "fixture", name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: []) + var steam = SteamCatalogGame(appID: 10, name: "Fixture") + steam.installations = [.init(libraryURL: root, contentURL: root, + applications: [CatalogNativeApplication(observed)], availability: .available)] + let game = CatalogGame(steam: steam) + let square = SteamArtwork(game: game, slot: .icon) + await square.loadForCheck() + let squareReturn = SteamArtwork(game: game, slot: .icon) + require(draw(squareReturn) != nil, "Steam app artwork is present before the recreated view's task") + + func color(_ image: NSImage?) -> String? { + guard let data = image?.tiffRepresentation, let bitmap = NSBitmapImageRep(data: data), + let pixel = bitmap.colorAt(x: 0, y: 0)?.usingColorSpace(.deviceRGB) else { return nil } + return "\(Int((pixel.redComponent * 255).rounded())),\(Int((pixel.greenComponent * 255).rounded())),\(Int((pixel.blueComponent * 255).rounded()))" + } + let iconFile = app.appendingPathComponent("Contents/Resources/Icon.icns") + let replacement = try Data(contentsOf: root.appendingPathComponent("image2.png")) + try replacement.write(to: iconFile, options: .atomic) + var updatedSteam = steam + updatedSteam.installations[0].buildID = "updated-build" + let updatedGame = CatalogGame(steam: updatedSteam) + await SteamArtwork(game: updatedGame, slot: .icon).loadForCheck() + let freshFile = await GameArtLoader.decode(at: iconFile, maxPixelSize: 512) + require(color(draw(SteamArtwork(game: updatedGame, slot: .icon))) == color(freshFile), + "Steam update at the same app path replaces the decoded icon") + // Even a file replaced without a new build ID is revalidated behind the warm first frame. + try Data(contentsOf: root.appendingPathComponent("image3.png")).write(to: iconFile, options: .atomic) + await SteamArtwork(game: updatedGame, slot: .icon).loadForCheck() + let resetFile = await GameArtLoader.decode(at: iconFile, maxPixelSize: 512) + require(color(draw(SteamArtwork(game: updatedGame, slot: .icon))) == color(resetFile), + "an unchanged build ID cannot keep stale pixels indefinitely") + + try Fixture.steamPicks.save(fields: [:], images: [.icon: png], automatic: [], titleID: game.personalizationReference.key) + let steamPick = SteamArtwork(game: game, slot: .icon) + await steamPick.loadForCheck() + let steamPickReturn = SteamArtwork(game: game, slot: .icon) + let steamPersonal = draw(steamPickReturn) + require(steamPersonal != nil, "Steam personal artwork is present before the recreated view's task") + try Fixture.steamPicks.save(fields: [:], images: [:], automatic: [.icon], titleID: game.personalizationReference.key) + let steamReset = SteamArtwork(game: game, slot: .icon) + require(steamPersonal == nil || draw(steamReset) !== steamPersonal, + "Steam Automatic does not reuse the removed personal image") + let remoteChanged = SteamArtwork(game: game, slot: .icon, remote: URL(string: "https://fixture.invalid/other.png")) + require(steamPersonal == nil || draw(remoteChanged) !== steamPersonal, + "a different request cannot borrow the previous request's decoded image") + exit(failures == 0 ? 0 : 1) + } +} +''') + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(host), + str(scratch / 'Native.swift'), str(scratch / 'Steam.swift'), + str(ROOT / 'Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift'), + str(ROOT / 'Sources/NXLibrary/Views/Theme/CatalogPersonalizationsEnvironment.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], check=True) + view_result = subprocess.run([str(executable), str(scratch)], + env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))) + + mods = scratch / 'ModsCheck.swift' + mods.write_text(r''' +import Foundation +import AppKit +import Combine +import NXLibraryCore + +enum AppData { static let cacheRoot = URL(fileURLWithPath: CommandLine.arguments[1]) } +struct NoHTTP: ArtworkHTTPClient { + func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) { fatalError("Network forbidden") } +} +final class GameBananaServices { + static let shared = GameBananaServices() + let matches = GameBananaMatchStore(file: AppData.cacheRoot.appendingPathComponent("matches.json")) + let client = GameBananaClient(http: NoHTTP(), cacheFolder: AppData.cacheRoot.appendingPathComponent("api"), userAgent: "fixture") +} +@MainActor final class AppViewModel { + let fixtureStore: ModStore + var storeMetadata: [UUID: NintendoStoreMetadata] = [:] + init(_ store: ModStore) { fixtureStore = store } + func modStore(for game: PortedGame) -> ModStore? { fixtureStore } +} +@MainActor final class ModsBandHost: ObservableObject { + let gameBanana = GameBananaBandModel(client: GameBananaServices.shared.client, matches: GameBananaServices.shared.matches, userAgent: "fixture") + var isPanelOpen = false + func reloadRecords(viewModel: AppViewModel) {} + func stop() { gameBanana.stop(); isPanelOpen = false } + func openStoreDetail(_ mod: AvailableMod, game: PortedGame, viewModel: AppViewModel) {} +} +enum GameBananaImageView { + static func prepare(_ urls: [URL], maxPixelSize: Int) async {} + static func prewarm(_ urls: [URL], maxPixelSize: Int) {} +} +enum ModsCardCover { static let pixelSize = 700 } +enum GameBananaBlur { + static let bannerRadius = 10.0 + static func image(for url: URL, radius: Double) async {} +} +struct SoundEffectService { + enum Cue { case click, error } + static let shared = Self() + func play(_ cue: Cue) {} +} +struct CheckFailure: Error {} +enum CoverReadGate { + static let captured = DispatchSemaphore(value: 0) + static let resume = DispatchSemaphore(value: 0) + static let completed = DispatchSemaphore(value: 0) + static let lock = NSLock() + private static var armed = false + private static var held: UUID? + static func arm() { lock.lock(); armed = true; lock.unlock() } + static func didRead(_ id: UUID) { + lock.lock() + let hold = armed + if hold { armed = false; held = id } + lock.unlock() + if hold { + captured.signal() + precondition(resume.wait(timeout: .now() + 5) == .success) + } + } + static func finished(_ id: UUID) { + lock.lock(); let matches = held == id; lock.unlock() + if matches { completed.signal() } + } +} +@main struct ModsCheck { + @MainActor static func waitFor(_ message: String = "async fixture becomes ready", _ condition: () -> Bool) async throws { + let deadline = Date().addingTimeInterval(5) + while !condition() { + guard Date() < deadline else { print("FAIL: " + message); throw CheckFailure() } + try await Task.sleep(nanoseconds: 5_000_000) + } + } + static func require(_ condition: Bool, _ message: String) throws { + guard condition else { print("FAIL: " + message); throw CheckFailure() } + print("PASS: " + message) + } + @MainActor static func main() async { + do { try await check() } + catch { print("FAIL: Mods fixture: \(error)"); exit(1) } + } + @MainActor static func check() async throws { + let root = AppData.cacheRoot + let tid = "0100000000010000" + let mod = AvailableMod(id: 10, rank: 0, name: "Fixture mod", author: "Fixture", avatarURL: nil, + images: [URL(string: "https://images.gamebanana.com/img/ss/mods/fixture.png")!], thumbnailURL: nil, + version: "", updated: Date(), pageURL: URL(string: "https://gamebanana.com/mods/10")!, description: "", likes: 0, downloads: 0, + files: [GameBananaFile(id: 100, name: "fixture.zip", size: 1, downloadURL: URL(string: "https://gamebanana.com/dl/100"), md5: "fixture")]) + let matches = GameBananaServices.shared.matches + try matches.set(.game(id: 1, name: "Fixture", profileURL: URL(string: "https://gamebanana.com/games/1")!), titleID: tid) + let snapshots = ModCatalogSnapshots(folder: root.appendingPathComponent("gamebanana/store")) + try snapshots.save([mod], gameName: "Fixture", titleID: tid, gameBananaID: 1) + let store = ModStore(supportFolder: root.appendingPathComponent("support"), recordsFile: root.appendingPathComponent("records.json"), titleID: tid, + canWrite: { true }, trash: { _ in fatalError("Trash forbidden") }, allowsAutomaticMaintenance: false) + let folder = store.modsFolder.appendingPathComponent("fixture") + try FileManager.default.createDirectory(at: folder.appendingPathComponent("romfs"), withIntermediateDirectories: true) + try Data([0]).write(to: folder.appendingPathComponent("romfs/a.bin")) + try JSONEncoder().encode([ModRecord(folderName: "fixture", isOn: true, gameBananaModID: 10, gameBananaFileID: 100, md5: "fixture")]).write(to: store.recordsFile) + let model = AppViewModel(store) + var game = PortedGame(name: "Fixture", url: root.appendingPathComponent("Fixture.app"), platform: .macApp, sizeBytes: 0, modificationDate: Date()) + game.titleId = tid + let host = ModStoreHost() + host.loadCover(titleIDs: [tid]); host.open([game], viewModel: model) + try await waitFor { host.records[tid]?[10] != nil && !host.cover.isEmpty } + let prepared = host.cover + host.close() + await withCheckedContinuation { continuation in DispatchQueue.main.async { continuation.resume() } } + for _ in 0..<10 { await Task.yield() } + try require(host.cover == prepared, "closing the store keeps its prepared cover") + try FileManager.default.removeItem(at: folder) + host.open([game], viewModel: model) + try await waitFor("reopening refreshes records after external removal") { host.records[tid]?.isEmpty == true } + try require(host.chip(for: ModCatalogEntry(mod: mod, titleID: tid, gameName: "Fixture")) == nil, + "reopening refreshes badges after a mod was removed elsewhere") + host.close() + try matches.set(.noPage, titleID: tid) + host.loadCover(titleIDs: [tid]) + try await waitFor { host.cover.isEmpty } + try require(host.cover.isEmpty, "None of these removes a retained cover") + try matches.set(.game(id: 1, name: "Fixture", profileURL: URL(string: "https://gamebanana.com/games/1")!), titleID: tid) + host.loadCover(titleIDs: [tid]) + try await waitFor { !host.cover.isEmpty } + try matches.set(.game(id: 2, name: "Other", profileURL: URL(string: "https://gamebanana.com/games/2")!), titleID: tid) + host.loadCover(titleIDs: [tid]) + try await waitFor { host.cover.isEmpty } + try require(host.cover.isEmpty, "a changed match rejects a snapshot of another GameBanana page") + + try matches.set(.game(id: 1, name: "Fixture", profileURL: URL(string: "https://gamebanana.com/games/1")!), titleID: tid) + CoverReadGate.arm() + host.loadCover(titleIDs: [tid]) + try await waitFor { CoverReadGate.captured.wait(timeout: .now()) == .success } + let fresh = AvailableMod(id: 20, rank: 0, name: "Fresh", author: "Fixture", avatarURL: nil, + images: [URL(string: "https://images.gamebanana.com/img/ss/mods/fresh.png")!], thumbnailURL: nil, + version: "", updated: Date(), pageURL: URL(string: "https://gamebanana.com/mods/20")!, + description: "", likes: 0, downloads: 0, files: mod.files) + try snapshots.save([fresh], gameName: "Fixture", titleID: tid, gameBananaID: 1) + host.open([game], viewModel: model) + try await waitFor { host.cover == fresh.images } + CoverReadGate.resume.signal() + try await waitFor { CoverReadGate.completed.wait(timeout: .now()) == .success } + try require(host.cover == fresh.images && host.catalog.games.first?.mods.first?.id == 20, + "an older snapshot cannot replace a newer catalog cover") + host.close() + } +} +''') + mods_executable = scratch / 'mods-check' + model_source = (SOURCE / 'Sources/NXLibrary/ViewModels/ModStoreHost.swift').read_text() + assert model_source.count('return ModStoreLayout.coverArt(games: games)') == 1 + # Control only the filesystem-read completion, leaving the production + # publication/generation checks and all model callbacks intact. + model_source = model_source.replace('return ModStoreLayout.coverArt(games: games)', + 'CoverReadGate.didRead(requestID); return ModStoreLayout.coverArt(games: games)') + assert model_source.count(' guard let self, self.coverTitleIDs') == 1 + model_source = model_source.replace(' guard let self, self.coverTitleIDs', + ' defer { CoverReadGate.finished(requestID) }\n guard let self, self.coverTitleIDs') + assert model_source.count(' self.show(cover: urls)') == 1 + model_source = model_source.replace(' self.show(cover: urls)', + ' self.show(cover: urls)\n _ = await self.coverTask?.value') + controlled_host = scratch / 'ControlledHost.swift' + controlled_host.write_text(model_source) + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(mods), + str(controlled_host), + str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(mods_executable)], check=True) + mods_result = subprocess.run([str(mods_executable), str(scratch)], + env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))) + raise SystemExit(view_result.returncode or mods_result.returncode) diff --git a/Tests/CatalogAppChecks/run_entrance.py b/Tests/CatalogAppChecks/run_entrance.py new file mode 100644 index 00000000..8e43ba7a --- /dev/null +++ b/Tests/CatalogAppChecks/run_entrance.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Exercise entrance input and drawable readiness with no windows, GPU or player data. + +Compile the actual receiver, input prelude and render/reveal methods. Only their +surrounding view state and Metal submission/presentation boundary are substituted. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' + + +def declaration(path, signature): + source = (ROOT / path).read_text() + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +host = r''' +import Foundation +import NXLibraryCore + +typealias CFTimeInterval = Double +func CACurrentMediaTime() -> Double { 0 } +@MainActor enum LaunchReveal { + static var frames = 0 + static func moonlightShown() { frames += 1 } +} +final class CAMetalDrawable { + private var handlers: [(CAMetalDrawable) -> Void] = [] + func addPresentedHandler(_ handler: @escaping (CAMetalDrawable) -> Void) { handlers.append(handler) } + func present() { let callbacks = handlers; handlers = []; callbacks.forEach { $0(self) } } +} +final class CAMetalLayer { + var drawableSize = CGSize(width: 1920, height: 1080) + var next: CAMetalDrawable? + func nextDrawable() -> CAMetalDrawable? { next } +} +final class MoonlightEngine { + static let breathPeriod = 1.0 + static func uniforms(width: Int, height: Int, time: Float, breath: Float, colors: Int) -> Int { 0 } + var submissions = 0 + func render(into drawable: CAMetalDrawable, uniforms: Int) { submissions += 1 } + func render(into layer: CAMetalLayer, uniforms: Int) { + guard let drawable = layer.nextDrawable() else { return } + render(into: drawable, uniforms: uniforms) + } +} +final class MoonlightHost { + struct State { + var moving = false + var lastTick: Double? + var lastFrame: Double? + var clock = 0.0 + var from: Int? + var stillPending = false + } + var state = State() + let lock = NSLock() + let metalLayer = CAMetalLayer() + let engine = MoonlightEngine() + static var firstFrameAnnounced = false + static let firstFrameLock = NSLock() + static func blended(_ state: State, at now: Double) -> Int { 0 } + func blending(at now: Double) -> Bool { false } + func updateLink() {} + func traceFirstPresentation(_ drawable: CAMetalDrawable) {} + func draw(_ drawable: CAMetalDrawable? = nil) { renderFrame(at: 1, drawable: drawable) } + // ACTUAL_RENDER + // ACTUAL_READY +} +final class InputState { + var alertMessage: String? + var settingsNotice: Int? + var isWelcomeOpen = false + var showSetupCheck = false + var isWindowSettling = true +} +final class InputHost { + let viewModel = InputState() + var entrance = SpotlightEntrance.Phase.covered + var handled: [GamepadAction] = [] + // ACTUAL_OVERLAID + // ACTUAL_COVERED + func landEntrance() { entrance.land() } + func handle(_ action: GamepadAction) { + // ACTUAL_INPUT_PRELUDE + handled.append(action) + } + func receive(_ note: Notification) { + // ACTUAL_RECEIVER + } +} + +@main struct Check { + @MainActor static func main() async { + var failures = 0 + func require(_ ok: @autoclosure () -> Bool, _ message: String) { + if !ok() { failures += 1; print("FAIL: " + message) } + } + for phase: SpotlightEntrance.Phase in [.covered, .waiting, .playing] { + let input = InputHost() + input.entrance = phase + input.receive(Notification(name: .init("fixture"), object: GamepadAction.confirm)) + require(input.handled.isEmpty && input.entrance == phase, + "A press during the entrance must neither act nor skip it (phase \(phase))") + } + let landed = InputHost() + landed.entrance = .landed + landed.receive(Notification(name: .init("fixture"), object: GamepadAction.confirm)) + require(landed.handled == [.confirm], "Once landed, a press acts as usual") + for setup in [false, true] { + let input = InputHost() + input.viewModel.showSetupCheck = setup + input.viewModel.isWelcomeOpen = !setup + input.receive(Notification(name: .init("fixture"), object: GamepadAction.confirm)) + require(input.handled.isEmpty && input.entrance == .covered, + "A real welcome/Setup cover must still block Spotlight input") + } + for supplied in [false, true] { + MoonlightHost.firstFrameAnnounced = false + LaunchReveal.frames = 0 + let renderer = MoonlightHost() + renderer.draw() + for _ in 0..<20 { await Task.yield() } + require(LaunchReveal.frames == 0 && renderer.engine.submissions == 0, + "A missing drawable must not announce a ready frame") + let drawable = CAMetalDrawable() + if supplied { renderer.draw(drawable) } + else { renderer.metalLayer.next = drawable; renderer.draw() } + for _ in 0..<20 { await Task.yield() } + require(renderer.engine.submissions == 1 && LaunchReveal.frames == 0, + "Submitting a frame must not announce presentation (supplied=\(supplied))") + drawable.present() + for _ in 0..<100 where LaunchReveal.frames == 0 { await Task.yield() } + require(LaunchReveal.frames == 1, "The first presented drawable must release the reveal gate") + let another = CAMetalDrawable() + renderer.draw(another) + another.present() + for _ in 0..<20 { await Task.yield() } + require(LaunchReveal.frames == 1, "Later frames must not release the reveal gate twice") + } + if failures > 0 { exit(1) } + print("Entrance checks passed: no skip during the entrance, covers, missing drawable and presentation readiness on both render paths.") + } +} +''' +entrance = 'Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift' +renderer = 'Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift' +for marker, path, signature in ( + ('// ACTUAL_OVERLAID', entrance, ' var isOverlaid:'), + ('// ACTUAL_COVERED', entrance, ' var isCovered:'), + ('// ACTUAL_RENDER', renderer, ' private func renderFrame('), + ('// ACTUAL_READY', renderer, ' private static func announceFirstFrame('), +): + host = host.replace(marker, declaration(path, signature)) +receiver = declaration('Sources/NXLibrary/Views/Spotlight/SpotlightView.swift', + ' .onReceive(NotificationCenter.default.publisher(for: .nxSpotlightGamepadAction))') +host = host.replace('// ACTUAL_RECEIVER', receiver.split('{ note in', 1)[1].rsplit('}', 1)[0]) +handler = declaration('Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift', + ' func handle(_ action: GamepadAction)') +prelude = handler[handler.index('{') + 1:handler.index(' if viewer != nil')] +host = host.replace('// ACTUAL_INPUT_PRELUDE', prelude) +with tempfile.TemporaryDirectory(prefix='entrance-check-') as folder: + scratch = Path(folder) + swift = scratch / 'check.swift' + swift.write_text(host) + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift), + str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True) + subprocess.run([str(executable)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)), check=True) diff --git a/Tests/CatalogAppChecks/run_game_header.py b/Tests/CatalogAppChecks/run_game_header.py new file mode 100644 index 00000000..2c339e68 --- /dev/null +++ b/Tests/CatalogAppChecks/run_game_header.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Evaluate actual common header bodies without a window or app stores.""" +from pathlib import Path +import subprocess,tempfile,os +ROOT=Path(__file__).resolve().parents[2] +BIN=ROOT/'.build/debug' +files=[ROOT/'Sources/NXLibrary/Views/Components/GameLogoArea.swift', ROOT/'Sources/NXLibrary/Views/Components/GamePrimaryActions.swift'] +actual='\n'.join(p.read_text() for p in files) +host='''import SwiftUI +import NXLibraryCore +struct HeaderCanvas { func u(_ value: CGFloat) -> CGFloat { value } } +private struct CanvasKey: EnvironmentKey { static let defaultValue = HeaderCanvas() } +extension EnvironmentValues { var seleneCanvas: HeaderCanvas { get { self[CanvasKey.self] } set { self[CanvasKey.self] = newValue } } } +extension View { func seleneFont(_ size: CGFloat, _ weight: Font.Weight = .regular) -> some View { font(.system(size: size, weight: weight)) } } +enum SeleneTheme { static let ink = Color.white } +struct SelenePillButton: View { + let title: String?; var icon: MaterialIcon? = nil; var iconSize: CGFloat = 26 + var minWidth: CGFloat = 180; var height: CGFloat = 60; var horizontalPadding: CGFloat = 36 + let focused: Bool; var enabled: Bool = true; var waveDots = false; let action: () -> Void + var body: some View { Color.clear } +} +'''+actual+''' +@main struct Check { + @MainActor static func main() { + for collection in [true,false] { + withExtendedLifetime(GameLogoArea(title: "Fixture", logo: nil, collection: collection).body) {} + } + for enabled in [true,false] { + withExtendedLifetime(GamePrimaryActions(primaryTitle: "Play", secondaryTitle: "Options", isFavorite: true, focused: 0, primaryEnabled: enabled, onAction: {_ in}).body) {} + } + print("Actual shared game header bodies work without injected stores, for both layouts/action states.") + } +} +''' +with tempfile.TemporaryDirectory(prefix='game-header-check-') as folder: + folder=Path(folder);swift=folder/'check.swift';swift.write_text(host);binary=folder/'check' + subprocess.run(['xcrun','swiftc','-parse-as-library','-I',str(BIN),str(swift),str(BIN/'NXLibraryCore.o'),'-o',str(binary)],check=True) + subprocess.run([str(binary)],check=True,env=dict(os.environ,PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))) diff --git a/Tests/CatalogAppChecks/run_icon_cache.py b/Tests/CatalogAppChecks/run_icon_cache.py new file mode 100644 index 00000000..6f2ca740 --- /dev/null +++ b/Tests/CatalogAppChecks/run_icon_cache.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Check the square icon art lookup with no windows or player data. + +Compile the actual GameIconProvider: a game with no icon on disk is not read again on every +draw of its tile, and an icon that arrives later shows once the game is forgotten or built. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' + +host = r''' +import AppKit +import NXLibraryCore + +@main struct Check { + static func main() throws { + var failures = 0 + func require(_ ok: Bool, _ message: String) { + if !ok { failures += 1; print("FAIL: " + message) } + } + let root = FileManager.default.temporaryDirectory.appendingPathComponent("icon-cache-\(UUID().uuidString)") + let workspace = root.appendingPathComponent("workspace") + let titleID = "0100000000001000" + let iconFolder = workspace.appendingPathComponent("\(titleID)_build/extract/v0") + try FileManager.default.createDirectory(at: iconFolder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + var game = PortedGame(name: "Fixture", url: root.appendingPathComponent("not-built"), + platform: .macApp, sizeBytes: 0, modificationDate: Date(), titleId: titleID) + game.workspacePath = workspace.path + require(GameIconProvider.squareArt(for: game) == nil, "no icon on disk gives no square art") + + let image = NSImage(size: NSSize(width: 4, height: 4)) + image.lockFocus(); NSColor.red.setFill(); NSRect(x: 0, y: 0, width: 4, height: 4).fill(); image.unlockFocus() + let png = NSBitmapImageRep(data: image.tiffRepresentation!)!.representation(using: .png, properties: [:])! + try png.write(to: iconFolder.appendingPathComponent("icon.jpg")) + require(GameIconProvider.squareArt(for: game) == nil, + "a game with no icon is not read from disk again on the next draw") + + GameIconProvider.forget(game) + require(GameIconProvider.squareArt(for: game) != nil, "forgetting the game reads its new icon") + + var other = PortedGame(name: "Other", url: root.appendingPathComponent("other-not-built"), + platform: .macApp, sizeBytes: 0, modificationDate: Date(), titleId: "0100000000002000") + other.workspacePath = root.appendingPathComponent("other").path + require(GameIconProvider.squareArt(for: other) == nil, "a second game with no icon gives no square art") + let otherFolder = root.appendingPathComponent("other/0100000000002000_build/extract/v0") + try FileManager.default.createDirectory(at: otherFolder, withIntermediateDirectories: true) + try png.write(to: otherFolder.appendingPathComponent("icon.jpg")) + other.url = root.appendingPathComponent("Other.app") + require(GameIconProvider.squareArt(for: other) != nil, "a game that moved to its built app is looked up again") + + if failures > 0 { exit(1) } + print("Icon cache checks passed: missing icons are remembered, forgetting and building look again.") + } +} +''' +with tempfile.TemporaryDirectory(prefix='icon-cache-check-') as folder: + scratch = Path(folder) + swift = scratch / 'check.swift' + swift.write_text(host) + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift), + str(ROOT / 'Sources/NXLibrary/Views/Components/GameIconProvider.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True) + subprocess.run([str(executable)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)), check=True) diff --git a/Tests/CatalogAppChecks/run_nested_bundles.py b/Tests/CatalogAppChecks/run_nested_bundles.py new file mode 100644 index 00000000..d1d7a969 --- /dev/null +++ b/Tests/CatalogAppChecks/run_nested_bundles.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Exercise installation and icon changes on signed, synthetic nested data bundles. + +Uses the nxnative data-bundle layout and relative Resources links, real codesign +and the production Swift installer/icon writer. No UI, engine checkout, keys or +game data. The cross-volume branch is forced on the temporary fixture volume; +this does not replace a real external-volume or engine-build check. +Run after swift test. +""" +from pathlib import Path +import os +import plistlib +import struct +import subprocess +import tempfile +import zlib + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' + + +def run(*args): + result = subprocess.run([str(a) for a in args], capture_output=True, text=True) + if result.returncode: + raise SystemExit(result.stderr or result.stdout or f'Command failed: {args[0]}') + return result + + +def plist(path, values): + path.write_bytes(plistlib.dumps(values)) + + +def signed_app(path, executable, version): + contents = path / 'Contents' + resources = contents / 'Resources' + resources.mkdir(parents=True) + (contents / 'MacOS').mkdir() + for target in (contents / 'MacOS/nxnative', contents / 'MacOS/dmhost'): + target.write_bytes(executable.read_bytes()) + target.chmod(0o755) + run('/usr/bin/codesign', '--force', '--sign', '-', target) + plist(contents / 'Info.plist', { + 'CFBundleIdentifier': 'org.arcane.contractfixture', 'CFBundleName': 'Fixture', + 'CFBundleExecutable': 'nxnative', 'CFBundlePackageType': 'APPL', + 'CFBundleVersion': str(version), 'CFBundleShortVersionString': str(version), + }) + for name, top in ( + ('GameData', 'romfs.img'), ('ShaderLibraries', 'msl'), + ('PipelineArchive', 'pso'), ('AddOnContent', 'aoc'), + ('GameDataPrograms', 'romfs_programs'), ('GameData1', 'p1/romfs.img'), + ): + bundle = contents / 'PlugIns' / (name + '.bundle') + inner = bundle / 'Contents/Resources' + inner.mkdir(parents=True) + plist(bundle / 'Contents/Info.plist', { + 'CFBundleIdentifier': 'org.arcane.contractfixture.data.' + name.lower(), + 'CFBundleName': name, 'CFBundlePackageType': 'BNDL', 'CFBundleVersion': '1', + }) + payload = inner / top + if top.endswith('.img'): + payload.parent.mkdir(parents=True, exist_ok=True) + else: + payload.mkdir() + payload /= 'synthetic.bin' + payload.write_bytes(f'{name}:version:{version}'.encode()) + link = resources / top + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(os.path.relpath(inner / top, link.parent)) + run('/usr/bin/codesign', '--force', '--sign', '-', bundle) + run('/usr/bin/codesign', '--force', '--sign', '-', path) + run('/usr/bin/codesign', '--verify', '--deep', '--strict', path) + + +with tempfile.TemporaryDirectory(prefix='arcane-nested-check-') as temporary: + scratch = Path(temporary) + code = scratch / 'fixture.c' + code.write_text('int main(void) { return 0; }\n') + executable = scratch / 'fixture' + run('xcrun', 'clang', code, '-o', executable) + signed_app(scratch / 'old.app', executable, 1) + signed_app(scratch / 'rebuilt.app', executable, 2) + + def chunk(kind, data): + return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)) + + # A generated 32 x 32 solid-colour PNG; no external artwork. + pixels = (b'\0' + b'\x40\x80\xc0\xff' * 32) * 32 + (scratch / 'icon.png').write_bytes( + b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 32, 32, 8, 6, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(pixels)) + chunk(b'IEND', b'')) + main = scratch / 'main.swift' + main.write_text(r''' +import Foundation +import CryptoKit +@testable import NXLibraryCore + +struct CheckFailure: Error {} +func require(_ condition: @autoclosure () throws -> Bool) throws { + if try !condition() { throw CheckFailure() } +} +let root = URL(fileURLWithPath: CommandLine.arguments[1]) +let fm = FileManager.default +let runner = SystemCommandRunner() +let codesign = URL(fileURLWithPath: "/usr/bin/codesign") +func verify(_ app: URL) throws { + let result = try runner.run(codesign, ["--verify", "--deep", "--strict", app.path], + environment: nil, currentDirectory: nil) + try require(result.status == 0) +} +func digest(_ folder: URL) throws -> String { + let paths = try fm.subpathsOfDirectory(atPath: folder.path).sorted() + var hash = SHA256() + for path in paths { + let file = folder.appendingPathComponent(path) + let attributes = try fm.attributesOfItem(atPath: file.path) + hash.update(data: Data(path.utf8)) + if attributes[.type] as? FileAttributeType == .typeRegular { + hash.update(data: try Data(contentsOf: file)) + } + } + return hash.finalize().map { String(format: "%02x", $0) }.joined() +} +func links(_ app: URL) throws -> [String: String] { + let res = app.appendingPathComponent("Contents/Resources") + let tops = ["romfs.img", "msl", "pso", "aoc", "romfs_programs", "p1/romfs.img"] + return try Dictionary(uniqueKeysWithValues: tops.map { top in + let file = res.appendingPathComponent(top) + let link = try fm.destinationOfSymbolicLink(atPath: file.path) + try require(!link.hasPrefix("/")) + try require(fm.fileExists(atPath: file.path)) + let resolved = file.resolvingSymlinksInPath().path + try require(resolved.hasPrefix(app.appendingPathComponent("Contents/PlugIns").path + "/")) + return (top, link) + }) +} +func dataSeal(_ app: URL) throws -> String { + try digest(app.appendingPathComponent("Contents/PlugIns")) +} +func hostBytes(_ app: URL) throws -> Data { + try Data(contentsOf: app.appendingPathComponent("Contents/MacOS/dmhost")) +} +let source = root.appendingPathComponent("old.app") +let destination = root.appendingPathComponent("Installed/Game.app") +let originalSeal = try dataSeal(source) +let originalLinks = try links(source) +let originalHost = try hostBytes(source) +try BuildOutputInstaller.install(tempApp: source, finalApp: destination) +try verify(destination) +try require(try dataSeal(destination) == originalSeal) +try require(try links(destination) == originalLinks) +try require(try hostBytes(destination) == originalHost) +print("Same-volume install preserves nested signatures and relative links: PASS") + +let writer = AppIconWriter(backups: root.appendingPathComponent("backups")) +let png = try Data(contentsOf: root.appendingPathComponent("icon.png")) +try writer.apply(image: png, to: destination, key: "fixture") +try verify(destination) +try require(writer.showsWrittenIcon(destination)) +try require(try dataSeal(destination) == originalSeal) +try require(try hostBytes(destination) == originalHost) +try writer.restore(destination, key: "fixture") +try verify(destination) +try require(!writer.showsWrittenIcon(destination)) +try require(try dataSeal(destination) == originalSeal) +try require(try links(destination) == originalLinks) +try require(try hostBytes(destination) == originalHost) +print("Real icon write and restore preserve nested signatures: PASS") + +struct FailVerification: CommandRunning { + func run(_ executable: URL, _ arguments: [String], environment: [String: String]?, + currentDirectory: URL?) throws -> CommandResult { + if executable.lastPathComponent == "codesign" && arguments.contains("--verify") { + return CommandResult(status: 1, stdout: "", stderr: "synthetic verification failure") + } + return try SystemCommandRunner().run(executable, arguments, environment: environment, + currentDirectory: currentDirectory) + } +} +let beforeFailure = try digest(destination) +let failing = AppIconWriter(backups: root.appendingPathComponent("rollback-backups"), runner: FailVerification()) +do { + try failing.apply(image: png, to: destination, key: "fixture") + throw CheckFailure() +} catch AppIconWriter.Failure.signingFailed { } +try verify(destination) +try require(try digest(destination) == beforeFailure) +print("Failed verification restores the original signed app: PASS") + +let rebuilt = root.appendingPathComponent("rebuilt.app") +let rebuiltSeal = try dataSeal(rebuilt) +let rebuiltLinks = try links(rebuilt) +let rebuiltHost = try hostBytes(rebuilt) +var io = BuildInstallIO() +io.sameVolume = { _, _ in false } +io.afterPublish = { throw CocoaError(.userCancelled) } +do { + try BuildOutputInstaller.install(tempApp: rebuilt, finalApp: destination, io: io) + throw CheckFailure() +} catch let error as CocoaError where error.code == .userCancelled { } +try verify(destination) +io.afterPublish = {} +try BuildOutputInstaller.install(tempApp: rebuilt, finalApp: destination, io: io) +try verify(destination) +try require(try dataSeal(destination) == rebuiltSeal) +try require(try links(destination) == rebuiltLinks) +try require(try hostBytes(destination) == rebuiltHost) +try require(BuildOutputInstaller.version(of: destination) == "2") +print("Copied rebuild and interrupted-publication retry preserve the new app: PASS") + +let payload = destination.appendingPathComponent("Contents/Resources/romfs.img") +let original = try Data(contentsOf: payload) +try Data("tampered".utf8).write(to: payload) +let rejected = try runner.run(codesign, ["--verify", "--deep", "--strict", destination.path], + environment: nil, currentDirectory: nil) +try require(rejected.status != 0) +try original.write(to: payload) +try verify(destination) +print("Deep verification rejects changed nested payloads: PASS") +''') + host = scratch / 'check' + run('xcrun', 'swiftc', '-I', BIN, main, BIN / 'NXLibraryCore.o', '-o', host) + result = run(host, scratch) + print(result.stdout, end='') diff --git a/Tests/CatalogAppChecks/run_notices.py b/Tests/CatalogAppChecks/run_notices.py new file mode 100644 index 00000000..293d6ced --- /dev/null +++ b/Tests/CatalogAppChecks/run_notices.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Exercise actual app notice helpers/bridge without constructing SwiftUI or AppKit. + +Run after swift test on macOS. Core I/O uses generated temporary data only. +The host substitutes the surrounding view model, not the methods being checked. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' + +def method(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth = 1 + end = opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + +with tempfile.TemporaryDirectory(prefix='catalog-notice-check-') as scratch: + scratch = Path(scratch) + view = (ROOT / 'Sources/NXLibrary/Views/Shell/AppShellView.swift').read_text() + bridge = '\n'.join(method(view, signature) for signature in ( + ' private func finishSettingsNotice(choice: Int)', ' private func presentLegacyNotice()')) + host = (ROOT / 'Tests/CatalogAppChecks/NoticeHost.swift').read_text() + host += '\nstruct LegacyNoticeHost {\n let viewModel: AppViewModel\n' + host += ' func deliver() { presentLegacyNotice() }\n func dismiss() { finishSettingsNotice(choice: 0) }\n' + host += bridge + '\n}\n' + main = scratch / 'main.swift' + main.write_text(host) + executable = scratch / 'notices' + command = ['xcrun', 'swiftc', '-I', str(BIN), str(main), + str(ROOT / 'Sources/NXLibrary/Models/LogEntry.swift'), + str(ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel+Catalog.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)] + subprocess.run(command, cwd=ROOT, check=True) + env = dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN)) + subprocess.run([str(executable)], env=env, check=True) diff --git a/Tests/CatalogAppChecks/run_nup_programs.py b/Tests/CatalogAppChecks/run_nup_programs.py new file mode 100644 index 00000000..1c8c38a1 --- /dev/null +++ b/Tests/CatalogAppChecks/run_nup_programs.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Check real NUP probe/converters, persistence and rebuild arguments without app UI. + +An optional immutable engine snapshot runs its synthetic edition fixture through +Arcane's actual embedded Python probe. No checkout, game content or keys are used. +""" +from pathlib import Path +import argparse +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +parser = argparse.ArgumentParser() +parser.add_argument('--engine-snapshot', type=Path) +parser.add_argument('--python', default='python3') +args = parser.parse_args() +source = (ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel.swift').read_text() + + +def declaration(signature): + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end].replace('private static func', 'static func', 1) + + +with tempfile.TemporaryDirectory(prefix='arcane-nup-check-') as scratch: + scratch = Path(scratch) + output = 'title 0400F00000010001\napplication 0100F00000010000\naoc_base 0100F00000011000\nbase 272\ndlc 0100F00000011001 2\n' + if args.engine_snapshot: + bridge = (ROOT / 'Sources/NXLibraryCore/Services/NUPSourceCatalog.swift').read_text() + probe = bridge.split('let script = #"""', 1)[1].split('"""#', 1)[0] + generator = """ +import pathlib,sys +repo=pathlib.Path(sys.argv[1]) +sys.path.insert(0,str(repo/'dm/tools/tests')) +import test_nsp_nup as fixture +fixture.write_nup(pathlib.Path(sys.argv[2]),fixture.edition()) +""" + nup = scratch / 'synthetic.nup' + subprocess.run([args.python, '-I', '-B', '-c', generator, str(args.engine_snapshot), str(nup)], check=True) + result = subprocess.run([args.python, '-I', '-B', '-c', probe, str(args.engine_snapshot), str(nup)], + check=True, text=True, capture_output=True, timeout=20) + output = result.stdout + wire = scratch / 'probe.txt' + wire.write_text(output) + host = ''' +import Foundation +@testable import NXLibraryCore +struct Host { + // CONVERTERS +} +let scratch = URL(fileURLWithPath: CommandLine.arguments[1]) +let wire = try String(contentsOf: scratch.appendingPathComponent("probe.txt"), encoding: .utf8) +let nup = scratch.appendingPathComponent("synthetic.nup") +let game = try NUPSourceCatalog.parse(wire, nup: nup, fileSize: 400, + profiles: scratch.appendingPathComponent("profiles"), provisional: true) +precondition(game.baseTitleId == 0x0400F00000010001) +let ui = Host.selectableGame(from: game) +precondition(ui.titleId == "0400F00000010001") +let persisted = try JSONEncoder().encode(ui.files) +let restored = try JSONDecoder().decode([GameFileItem].self, from: persisted) +let detected = restored.compactMap { Host.detectedSource(from: $0) } +precondition(detected.count == game.allSources.count) +precondition(detected.allSatisfy { $0.nupProgram?.applicationID == 0x0100F00000010000 && $0.nupProgram?.index == 1 }) +precondition(detected.first(where: { $0.kind == .dlc })?.titleId == 0x0100F00000011001) +precondition(SourceSelection.supported(restored, titleSelection: true, extractedFolders: true, + nupContainers: true, nupPrograms: true)) +let command = BuildCommandBuilder.make(repo: scratch, toolchain: EngineToolchain(python: scratch.appendingPathComponent("python"), + extraPath: [], isBundled: true), workspace: scratch, keys: nil, output: scratch.appendingPathComponent("Game.app"), + developerDir: scratch, titleId: ui.titleId, + programIndex: SourceSelection.programIndex(for: restored, titleID: ui.titleId!, nupPrograms: true)) +precondition(command.arguments[command.arguments.firstIndex(of: "--program")! + 1] == "1") +print("NUP probe → real UI converters → persisted sources → rebuild program: PASS") +''' + methods = '\n'.join(declaration(signature) for signature in ( + ' private static func selectableGame(from game:', ' private static func detectedSource(from file:')) + main = scratch / 'main.swift' + main.write_text(host.replace('// CONVERTERS', methods)) + library = ROOT / '.build/debug' + executable = scratch / 'nup-check' + subprocess.run(['xcrun', 'swiftc', '-I', str(library), str(main), + str(ROOT / 'Sources/NXLibrary/Models/SelectableGame.swift'), + str(library / 'NXLibraryCore.o'), '-o', str(executable)], check=True) + subprocess.run([str(executable), str(scratch)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(library)), check=True) diff --git a/Tests/CatalogAppChecks/run_onboarding.py b/Tests/CatalogAppChecks/run_onboarding.py new file mode 100644 index 00000000..c00a7eea --- /dev/null +++ b/Tests/CatalogAppChecks/run_onboarding.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Exercise the real setup persistence and notification request sites without windows. + +Only the surrounding app and notification transport are substituted. Preferences +use a unique synthetic domain; no player profile or game data is read. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +source = (ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel.swift').read_text() + + +def declaration(signature, text=None): + text = source if text is None else text + start = text.index(signature) + opening = text.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +initial = declaration(' public init(settingsStore:') +restore = initial[initial.index(' let didCompleteSetup = '):initial.index(' // 1. Resolve safe root')] +startup_requests = '\n'.join(line for line in initial.splitlines() if 'NotificationService.shared' in line) +build = declaration(' private func beginBuild(for game:') +accepted = build[build.index(' isBuilding = true'):build.index(' buildState = .running')] +shell = (ROOT / 'Sources/NXLibrary/Views/Shell/AppShellView.swift').read_text() +start = shell.index('.onChange(of: viewModel.setupCompleted)') +opening = shell.index('{ done in', start) +depth, end = 1, opening + 1 +while depth: + depth += (shell[end] == '{') - (shell[end] == '}') + end += 1 +finish = shell[opening + len('{ done in'):end - 1] +found = (ROOT / 'Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift').read_text() +start = found.index('.onChange(of: findings)') +opening = found.index('{ found in', start) +depth, end = 1, opening + 1 +while depth: + depth += (found[end] == '{') - (found[end] == '}') + end += 1 +findings_changed = found[opening + len('{ found in'):end - 1] + +host = ''' +import Foundation +import Combine +import NXLibraryCore + +enum AppData { + static let domain = "local.nxlibrary.validation." + UUID().uuidString + static let preferences = UserDefaults(suiteName: domain)! +} +enum NotificationRegistration { static var registered = false } +final class NotificationService { + static let shared = NotificationService() + var requests = 0 + init() { NotificationRegistration.registered = true } + func requestAuthorization() { requests += 1 } +} +final class Host { + // KEYS + // SETUP + var showSetupCheck = false + var isBuilding = false + var isCancellingBuild = false + let gameAppsFolder = URL(fileURLWithPath: "/synthetic/apps") + init() { + // RESTORE + // STARTUP_REQUESTS + } + func chooseSteamOnFound(_ value: Bool) { firstRunSetup.chooseSteam(value) } + func choose(_ value: Bool) { firstRunSetup.chooseSteam(value) } + func openPorting() { firstRunSetup.openPorting() } + func openPortingFromFound() { firstRunSetup.openPorting() } + func finish() { firstRunSetup.finish() } + func acceptBuild() { + // ACCEPTED_BUILD + } +} +final class Sources { + struct Configuration { var isEnabled: Bool } + var configuration: Configuration + let discoveryRoot: URL + var applied: [(Bool, URL?)] = [] + init(enabled: Bool, root: URL) { configuration = .init(isEnabled: enabled); discoveryRoot = root } + func configure(enabled: Bool, root: URL?) { applied.append((enabled, root)); configuration.isEnabled = enabled } +} +final class Settings { var settings = AppSettings() } +final class Shell { + let viewModel: Host + let sources: Sources + let settings = Settings() + var showsWelcome = false + init(model: Host, sources: Sources) { viewModel = model; self.sources = sources } + func complete(_ done: Bool) { + // FINISH + } +} +struct NativeApp { var modalWindow: Int? } +var NSApp = NativeApp() +final class SoundEffectService { + enum Cue { case click, key, error } + static let shared = SoundEffectService() + func play(_ cue: Cue) {} +} +final class FindingsReader { + var cancellations = 0 + func cancel() { cancellations += 1 } + func start(steamRoot: URL, appsFolder: URL) {} +} +final class FoundHost { + let viewModel: Host + var findings: FirstRunFindings? + var focus = FirstRunSetup.Focus.steamToggle + let reader = FindingsReader() + let steamRoot = URL(fileURLWithPath: "/synthetic/Steam") + var opened: [(ported: Bool, cancelled: Bool)] = [] + var steamCount: Int? { findings?.steamGameCount } + var steamOn: Bool { viewModel.firstRunSetup.steamChoice ?? true } + var portedCount: Int { findings?.portedAppCount ?? 0 } + var isReading: Bool { findings == nil } + func onOpenLibrary(_ ported: Bool) { opened.append((ported, reader.cancellations > 0)) } + // ACTIVATE_FOUND + var hasSteam: Bool { findings?.steamGameCount != nil || findings?.steamReadFailed == true } + init(_ viewModel: Host) { self.viewModel = viewModel } + func move(to next: FirstRunSetup.Focus) { focus = next } + func receive(_ found: FirstRunFindings?) { + findings = found + // FINDINGS_CHANGED + } +} +var failures = 0 +func require(_ ok: @autoclosure () -> Bool, _ message: String) { + if !ok() { failures += 1; print("FAIL: " + message) } +} +defer { AppData.preferences.removePersistentDomain(forName: AppData.domain) } +let initialBoot = Host() +require(NotificationRegistration.registered, "Startup registers notification click handling without requesting authorization") +for value in [true, false] { + AppData.preferences.removePersistentDomain(forName: AppData.domain) + let before = Host() + before.choose(value) + before.openPorting() + let resumed = Host() + require(resumed.firstRunSetup.steamChoice == value, "Steam choice survives quit: \\(value)") + require(resumed.firstRunSetup.page == .requirements, "Porting page survives quit") + resumed.finish() + require(resumed.firstRunSetup.steamChoice == value, "Shell can still apply the finishing choice") + require(AppData.preferences.object(forKey: "NXLibrary_SetupSteamChoice") == nil, "Finishing removes saved choice") + require(Host().firstRunSetup.steamChoice == nil, "Completed setup does not inherit a stale choice") +} +for enabled in [true, false] { + for choice: Bool? in [true, false, nil] { + AppData.preferences.removePersistentDomain(forName: AppData.domain) + let model = Host() + if let choice { model.choose(choice) } + let custom = URL(fileURLWithPath: "/synthetic/Custom Steam") + let sources = Sources(enabled: enabled, root: custom) + let shell = Shell(model: model, sources: sources) + shell.complete(false) + require(sources.applied.isEmpty, "Incomplete setup does not apply the switch") + model.finish() + shell.complete(true) + require(sources.configuration.isEnabled == (choice ?? enabled), "Finishing applies on and off, nil preserves the source") + require(sources.applied.allSatisfy { $0.1 == custom }, "Opt-in uses the same custom root as discovery") + } +} +AppData.preferences.removePersistentDomain(forName: AppData.domain) +let retryModel = Host() +retryModel.choose(false) +let retry = FoundHost(retryModel) +retry.receive(FirstRunFindings(steamGameCount: nil, portedAppCount: 0, steamReadFailed: true)) +require(retry.focus == .steamToggle, "Retry row keeps focus while the read is incomplete") +retry.receive(nil) +retry.receive(FirstRunFindings(steamGameCount: nil, portedAppCount: 0)) +require(retry.focus == .openLibrary, "Retry that finds no Steam leaves no invisible focused row") +retry.receive(FirstRunFindings(steamGameCount: 2, portedAppCount: 0)) +require(retryModel.firstRunSetup.steamChoice == false, "Retry never resets an explicit off choice") +AppData.preferences.removePersistentDomain(forName: AppData.domain) +let waitingModel = Host() +waitingModel.showSetupCheck = true +let waiting = FoundHost(waitingModel) +waiting.activate(.openLibrary) +require(waiting.opened.count == 1 && waiting.opened.first?.ported == false, + "A pending read does not block Open library or invent ported results") +require(waiting.opened.first?.cancelled == true, "Cancel the pending request before leaving the found page") +require(waitingModel.firstRunSetup.steamChoice == nil, "No unread source is opted in") +waiting.receive(FirstRunFindings(steamGameCount: 2, portedAppCount: 3)) +waiting.activate(.openLibrary) +require(waiting.opened.last?.ported == true, "A completed read still imports found apps") +NSApp.modalWindow = 1 +waiting.activate(.openLibrary) +require(waiting.opened.count == 2, "A native modal still owns input") +NSApp.modalWindow = nil +waitingModel.showSetupCheck = false +waiting.activate(.openLibrary) +require(waiting.opened.count == 2, "A departed setup does not finish again") +NotificationService.shared.requests = 0 +let steamOnly = Host() +require(NotificationService.shared.requests == 0, "Startup and Steam-only use never request notifications") +NotificationService.shared.requests = 0 +steamOnly.acceptBuild() +require(NotificationService.shared.requests == 1, "Accepted porting requests notifications") +if failures > 0 { exit(1) } +print("Onboarding persistence and notification timing: PASS") +''' +host = host.replace('// ACTIVATE_FOUND', declaration(' func activate(', (ROOT / 'Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift').read_text())) +host = host.replace('// KEYS', declaration(' private enum StorageKeys')) +host = host.replace('// SETUP', declaration(' @Published public private(set) var firstRunSetup =')) +host = host.replace('// FINDINGS_CHANGED', findings_changed) +host = host.replace('// FINISH', finish) +host = host.replace('// RESTORE', restore).replace('// STARTUP_REQUESTS', startup_requests) +host = host.replace('// ACCEPTED_BUILD', accepted) +with tempfile.TemporaryDirectory(prefix='arcane-onboarding-check-') as scratch: + scratch = Path(scratch) + main = scratch / 'main.swift' + main.write_text(host) + binary = scratch / 'onboarding' + library = ROOT / '.build/debug' + subprocess.run(['xcrun', 'swiftc', '-I', str(library), str(main), + str(library / 'NXLibraryCore.o'), '-o', str(binary)], check=True) + subprocess.run([str(binary)], env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(library)), check=True) diff --git a/Tests/CatalogAppChecks/run_review.py b/Tests/CatalogAppChecks/run_review.py new file mode 100644 index 00000000..db7a4c7e --- /dev/null +++ b/Tests/CatalogAppChecks/run_review.py @@ -0,0 +1,438 @@ +#!/usr/bin/env python3 +"""Exercise the review regressions without opening the app or touching player data. + +Compiles the actual store/loader and focus/menu methods. Replaces only their +surrounding UI state and external services; Core readers use generated files. +Run after swift test, like run_notices.py. +""" +from pathlib import Path +import os +import struct +import subprocess +import tempfile +import re + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' + + +def declaration(path, signature): + source = (ROOT / path).read_text() + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def binary_kv(entries): + data = bytearray() + for key, value in entries: + data.append(0 if isinstance(value, list) else 2 if isinstance(value, int) else 1) + data.extend(key.encode() + b'\0') + if isinstance(value, list): + data.extend(binary_kv(value)) + elif isinstance(value, int): + data.extend(struct.pack('<i', value)) + else: + data.extend(value.encode() + b'\0') + data.append(8) + return data + + +host = r''' +import Foundation +import Combine +import NXLibraryCore + +@MainActor var failures = 0 +@MainActor func require(_ ok: @autoclosure () -> Bool, _ message: String) { + if !ok() { failures += 1; print("FAIL: " + message) } +} + +// Only external enrichment is replaced: no network or player cache writes. +actor SteamMetadataService { + static let shared = SteamMetadataService() + func achievementPercents(appID: UInt32) -> [String: Double]? { [:] } +} +@MainActor final class ArtworkStore { + enum Kind { case hero, logo } + func cachedURL(titleID: String, kind: Kind) -> URL? { nil } + func fetch(titleID: String, remoteURL: URL?, kind: Kind) async -> URL? { nil } +} +struct ArtworkPicks { + static let shared = Self() + func url(titleID: String, slot: ArtworkSlot) -> URL? { nil } +} +@MainActor enum OnlineArtwork { + static var platforms: [CriticRatingQuery.Platform] = [] + static func find(names: [String], slot: ArtworkSlot? = nil, + platform: CriticRatingQuery.Platform = .switch) async -> [ArtworkCandidate] { + platforms.append(platform) + return [] + } +} + +struct SpotlightPageModel { var links = [1]; var more: [Int] = [] } +@MainActor final class ModsHost { + var localMods: Int? + var game: PortedGame? + var reloads: [UUID] = [] + func reload(_ game: PortedGame, viewModel: ViewModel) { + self.game = game + reloads.append(game.id) + } + func stop() {} + func clearGame() { game = nil } +} +@MainActor final class ViewModel { + var spotlight = SpotlightState(focus: .actions) + var showSetupCheck = false + var isGameOptionsOpen = false + var alertMessage: String? + var gameToClose: Int? + var gameToRemove: Int? + var launchOverlay: Int? + var isBuilding = false + var catalogBuildRecoveries: [Int] = [] + var currentFocusedCatalogGame: CatalogGame? + var currentFocusedGame: PortedGame? { currentFocusedCatalogGame?.nxnativeGame } +} +@MainActor final class SoundEffectService { + enum Cue { case focus } + static let shared = SoundEffectService() + var count = 0 + func play(_ cue: Cue) { count += 1 } +} +@MainActor final class ScrollHost { + let viewModel = ViewModel() + var currentPage: SpotlightPageModel? = SpotlightPageModel() + var screenshotCount = 0 + var selectedAchievements: Int? = 1 + var selectedGame: PortedGame? + let modsHost = ModsHost() + var scroll: Double = -200 + var holdScroll = false + func offset(for area: SpotlightFocusArea) -> Double { + [.pills: 0, .strip: -100, .achievements: -200, .actions: -300, .mods: -400, .more: -500][area]! + } + func mutate(_ change: (inout SpotlightState) -> Void) { change(&viewModel.spotlight) } + func settle() { settleFocusOnScroll() } + // ACTUAL_SCROLL + // ACTUAL_MODS_RELOAD +} + +@MainActor final class RowGlideHost { + let viewModel = ViewModel() + let items: [SpotlightItem] = [.card(.collection), .card(.surprise)] + func mutate(_ change: (inout SpotlightState) -> Void) { change(&viewModel.spotlight) } + // ACTUAL_ROW_GLIDE +} + +enum LaunchCoverTrace { static func event(_ message: String) {} } +@MainActor final class CoverHandoffHost { + struct LaunchScreen { let gameID: UUID } + struct State { let generation: Int; var phase: SteamPlayState.Phase } + final class SteamClient { + var isHidden = false + var hides = 0 + func hide() { hides += 1; isHidden = true } + } + static let steamApplication: SteamClient? = SteamClient() + private static func showSteam() { steamApplication?.isHidden = false } + var states: [UUID: State] = [:] + var launchScreen: LaunchScreen? + var backgrounds: [UUID: Bool] = [:] + var late: Set<UUID> = [] + private var patience: [UUID: TimeInterval] = [:] + private var pendingHandOff: PendingHandOff? + private var handOffDeadline: Task<Void, Never>? + private static let coverWait: UInt64 = 30_000_000 + // ACTUAL_PENDING_HANDOFF + // ACTUAL_PREPARE_HANDOFF + // ACTUAL_COVER_PREPARED + // ACTUAL_SUBMIT_HANDOFF + // ACTUAL_FOLLOW_BACKGROUND + private func phase(ofID id: UUID) -> SteamPlayState.Phase { states[id]?.phase ?? .idle } + private func followLaunchScreen(now: Date) {} + func observe(at now: Date) { followBackground(now: now) } + func prepare(_ id: UUID, send: @escaping () -> Void) { + states[id] = .init(generation: 1, phase: .starting(since: Date())) + prepareHandOff(for: id, generation: 1, send: send) + } + + func waitForCoverDeadline() async { + await handOffDeadline?.value + } +} + +final class Router { + var route = AppRoute.library + var isScreenshotViewerOpen = false + var isSearchPresented = false + var isMenuPresented = false + func openSettings(_ section: SettingsSection) { route = .settings(section) } +} +final class WindowState { var attachedSheet: Int?; var isSheet = false } +final class ApplicationState { + var modalWindow: Int? + var keyWindow: WindowState? + var mainWindow: WindowState? +} +let NSApp = ApplicationState() +final class NativeMenus { var isTracking = false } +@MainActor final class GameControllerService { + static let shared = GameControllerService() + var onAction: ((GamepadAction) -> Void)? +} +@MainActor final class InputRecorder { var actions: [GamepadAction] = [] } +// ACTUAL_ACTION_NAMES +@MainActor struct SteamPlayCoordinator { + static let shared = Self() + func canPlay(_ game: CatalogGame) -> Bool { true } +} +// ACTUAL_AVAILABILITY_TYPE +@MainActor final class MenuHost { + let router = Router() + let viewModel = ViewModel() + let nativeMenus = NativeMenus() + var isCloseGameOpen = false + var showsWelcome = false + var showsSettingsNotice = false + var showsInstallFailure = false + var showsUpdateOffer = false + var dialogActions: [GamepadAction] = [] + var isHomeRoute: Bool { router.route == .library || router.route == .collection } + func availability() -> NativeMenuAvailability { nativeMenuAvailability } + func connectController() { + let viewModel = viewModel + let router = router + // ACTUAL_CONTROLLER + } + func settingsNoticeInput(_ action: GamepadAction) { dialogActions.append(action) } + func installFailureInput(_ action: GamepadAction) { dialogActions.append(action) } + func closeGameInput(_ action: GamepadAction) { dialogActions.append(action) } + func removeGameInput(_ action: GamepadAction) { dialogActions.append(action) } + func updateOfferInput(_ action: GamepadAction) { dialogActions.append(action) } + func menuInput(_ action: GamepadAction) { dialogActions.append(action) } + // ACTUAL_DIALOG + // ACTUAL_MENU +} + +@main struct Check { + @MainActor static func main() async { + let root = URL(fileURLWithPath: CommandLine.arguments[1]) + let store = SteamAchievementsStore() + store.load(appID: 42, language: "english") + store.setSources([.init(integration: .steam, isEnabled: true, rootURL: root)]) + for _ in 0..<200 where store.summaries[42] == nil { + try? await Task.sleep(nanoseconds: 5_000_000) + } + require(store.summaries[42]?.total == 1, + "Selection requested before Steam sources must load when the source arrives") + store.stop() + + for title in ["0100000000000001", "0400000000000001"] { + let game = PortedGame(name: "Generated fixture", url: root.appendingPathComponent(title + ".app"), + platform: .macApp, sizeBytes: 1, modificationDate: Date(), titleId: title) + _ = await GameArtLoader.shared.logo(for: game, metadata: nil, artwork: ArtworkStore(), personalizations: .empty) + } + require(OnlineArtwork.platforms == [.switch, .switch2], "Automatic logo search must use each game's console") + + let scroll = ScrollHost() + scroll.settle() + require(scroll.viewModel.spotlight.focus == .achievements, "Wheel settling must reach the visible achievements card") + let cues = SoundEffectService.shared.count + scroll.settle() + require(SoundEffectService.shared.count == cues, "Settling on the focused card must not play another focus cue") + scroll.selectedAchievements = nil + scroll.settle() + require(scroll.viewModel.spotlight.focus == .actions, "A missing achievements card must not take focus") + + let menu = MenuHost() + menu.viewModel.currentFocusedCatalogGame = .init(nxnative: PortedGame(name: "Fixture", url: root.appendingPathComponent("Game.app"), + platform: .macApp, sizeBytes: 1, modificationDate: Date())) + require(menu.availability().details, "Details must remain available for the selected game") + let firstModsGame = menu.viewModel.currentFocusedGame! + let nextModsGame = PortedGame(name: "Next fixture", url: root.appendingPathComponent("Next.app"), + platform: .macApp, sizeBytes: 1, modificationDate: Date()) + scroll.selectedGame = firstModsGame + scroll.reloadMods() + scroll.viewModel.spotlight.focus = .row + scroll.selectedGame = nextModsGame + scroll.reloadMods() + require(scroll.modsHost.reloads == [firstModsGame.id] && scroll.modsHost.game == nil, + "Switching games on the Spotlight row must clear the old Mods band without reading the next one") + scroll.viewModel.spotlight.focus = .pills + scroll.reloadMods() + require(scroll.modsHost.reloads == [firstModsGame.id, nextModsGame.id], + "The selected game's Mods band must load once the game page is open") + + let row = RowGlideHost() + row.viewModel.spotlight = SpotlightState(selectedKey: row.items[0].key) + require(row.handleRowGlide(.navigateRight), "The row must handle Right using only the row items") + require(row.viewModel.spotlight.selectedKey == row.items[1].key, "Right selects the next tile") + let rowCues = SoundEffectService.shared.count + require(row.handleRowGlide(.navigateRight) && SoundEffectService.shared.count == rowCues, + "Right at the row's edge is handled without playing a move cue") + row.viewModel.spotlight.focus = .pills + require(!row.handleRowGlide(.navigateLeft), "Page focus continues to use page navigation") + + let handoff = CoverHandoffHost() + let pending = UUID() + var handoffs = 0 + handoff.prepare(pending) { handoffs += 1 } + require(handoff.launchScreen?.gameID == pending && handoffs == 0, + "Steam must wait for the cover while its state is being published") + handoff.launchCoverPrepared(for: UUID()) + require(handoffs == 0, "Another cover cannot release this launch") + handoff.launchCoverPrepared(for: pending) + handoff.launchCoverPrepared(for: pending) + require(handoffs == 1, "The current cover releases Steam exactly once") + handoff.prepare(pending) { handoffs += 1 } + handoff.states[pending]?.phase = .idle + handoff.launchCoverPrepared(for: pending) + require(handoffs == 1, "Closing the launch state must prevent a stale cover from sending Play") + handoff.prepare(pending) { handoffs += 1 } + // The deadline task starts when the main actor schedules it. + await handoff.waitForCoverDeadline() + require(handoffs == 2, "Without a visible cover the deadline still lets Play proceed") + + let steam = CoverHandoffHost.steamApplication! + let start = Date(timeIntervalSince1970: 1_000) + handoff.states[pending]?.phase = .starting(since: start) + handoff.backgrounds[pending] = true + for attempt in 1...10 { + steam.isHidden = false // Steam reappears while processing Play. + handoff.observe(at: start.addingTimeInterval(Double(attempt) / 5)) + } + require(steam.hides == 0 && !steam.isHidden, + "Startup must let the cover handle Steam coming forward without hiding Steam") + steam.isHidden = true + handoff.observe(at: start.addingTimeInterval(16)) + require(handoff.late.contains(pending) && !steam.isHidden, + "A stalled launch must still show Steam after the wait") + let overlays: [(MenuHost, Bool) -> Void] = [ + { $0.router.isSearchPresented = $1 }, { $0.router.isScreenshotViewerOpen = $1 }, + { $0.viewModel.isGameOptionsOpen = $1 }, { $0.router.isMenuPresented = $1 }, + { $0.viewModel.showSetupCheck = $1 }, + { $0.isCloseGameOpen = $1 }, { $0.viewModel.launchOverlay = $1 ? 1 : nil } + ] + for (index, overlay) in overlays.enumerated() { + overlay(menu, true) + require(!menu.availability().details, "Details must be disabled under overlay \(index)") + overlay(menu, false) + } + menu.viewModel.currentFocusedCatalogGame = .init(steam: .init(appID: 42, name: "Fixture")) + require(menu.availability().details, "Steam Details must remain available in Spotlight") + menu.router.route = .collection + require(!menu.availability().details, "Steam must not acquire a separate Details screen in Collection") + + let input = MenuHost() + input.connectController() + let received = InputRecorder() + let watch = NotificationCenter.default.addObserver(forName: .nxSpotlightGamepadAction, + object: nil, queue: nil) { note in + MainActor.assumeIsolated { + if let action = note.object as? GamepadAction { received.actions.append(action) } + } + } + defer { NotificationCenter.default.removeObserver(watch); GameControllerService.shared.onAction = nil } + GameControllerService.shared.onAction?(.confirm) + require(received.actions == [.confirm], "An uncovered library must receive controller actions") + received.actions = [] + let blockers: [(String, (Bool) -> Void)] = [ + ("pending alert", { input.viewModel.alertMessage = $0 ? "Fixture alert" : nil }), + ("modal dialog", { NSApp.modalWindow = $0 ? 1 : nil }), + ("key sheet", { NSApp.keyWindow = $0 ? WindowState() : nil; NSApp.keyWindow?.isSheet = $0 }), + ("sheet on key window", { NSApp.keyWindow = $0 ? WindowState() : nil; NSApp.keyWindow?.attachedSheet = $0 ? 1 : nil }), + ("sheet on main window, no key window", { NSApp.mainWindow = $0 ? WindowState() : nil; NSApp.mainWindow?.attachedSheet = $0 ? 1 : nil }), + ("native menu", { input.nativeMenus.isTracking = $0 }) + ] + for (name, block) in blockers { + block(true) + for action: GamepadAction in [.navigateRight, .confirm, .cancel, .menu, .menuHold] { + GameControllerService.shared.onAction?(action) + } + require(received.actions.isEmpty && input.router.route == .library && !input.router.isMenuPresented, + "Controller must not navigate or launch underneath \(name)") + if name != "native menu" { + require(!input.availability().general, "Native menu commands must yield to \(name)") + } + // An internal update confirmation is also below the native window. + input.showsUpdateOffer = true + input.isCloseGameOpen = true + GameControllerService.shared.onAction?(.confirm) + require(input.dialogActions.isEmpty, "The update dialog must not receive input underneath \(name)") + input.showsUpdateOffer = false + input.isCloseGameOpen = false + block(false) + input.router.route = .library + input.router.isMenuPresented = false + received.actions = [] + GameControllerService.shared.onAction?(.navigateLeft) + require(received.actions == [.navigateLeft], "Closing \(name) must restore fresh input without replaying blocked actions") + received.actions = [] + input.dialogActions = [] + } + input.showsUpdateOffer = true + input.isCloseGameOpen = true + GameControllerService.shared.onAction?(.confirm) + require(input.dialogActions == [.confirm] && received.actions.isEmpty, + "An internal update dialog must still receive input when no native window is open") + if failures > 0 { exit(1) } + print("Actual app review checks passed: achievement startup, logo platform, wheel focus, Mods reads, Steam launch, native dialogs and input routing.") + } +} +''' + +host = host.replace('// ACTUAL_SCROLL', declaration( + 'Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift', ' private func settleFocusOnScroll()')) +host = host.replace('// ACTUAL_MODS_RELOAD', declaration( + 'Sources/NXLibrary/Views/Spotlight/SpotlightView.swift', ' func reloadMods()')) +host = host.replace('// ACTUAL_ROW_GLIDE', declaration( + 'Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift', ' func handleRowGlide(')) +coordinator = 'Sources/NXLibrary/Services/SteamPlayCoordinator.swift' +for marker, signature in ( + ('// ACTUAL_PENDING_HANDOFF', ' private struct PendingHandOff'), + ('// ACTUAL_PREPARE_HANDOFF', ' private func prepareHandOff('), + ('// ACTUAL_COVER_PREPARED', ' func launchCoverPrepared('), + ('// ACTUAL_SUBMIT_HANDOFF', ' private func submitHandOff('), + ('// ACTUAL_FOLLOW_BACKGROUND', ' private func followBackground('), +): + host = host.replace(marker, declaration(coordinator, signature)) +host = host.replace('// ACTUAL_AVAILABILITY_TYPE', declaration( + 'Sources/NXLibrary/Services/NativeMenuCommands.swift', 'struct NativeMenuAvailability')) +host = host.replace('// ACTUAL_MENU', declaration( + 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var nativeMenuAvailability:')) +host = host.replace('// ACTUAL_DIALOG', declaration( + 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var nativeDialogOwnsInput:')) +controller = declaration('Sources/NXLibrary/Views/Shell/AppShellView.swift', + ' GameControllerService.shared.onAction =') +host = host.replace('// ACTUAL_CONTROLLER', controller.replace('[weak viewModel, weak router]', '[self, weak viewModel, weak router]')) +names = sorted(set(re.findall(r'name: \.(nx\w+)', controller))) +host = host.replace('// ACTUAL_ACTION_NAMES', 'extension Notification.Name {\n' + '\n'.join( + f' static let {name} = Notification.Name("{name}")' for name in names) + '\n}') + +with tempfile.TemporaryDirectory(prefix='catalog-review-check-') as folder: + scratch = Path(folder) + (scratch / 'config').mkdir() + (scratch / 'config/loginusers.vdf').write_text('"users" { "76561197960265735" { "MostRecent" "1" } }') + stats = scratch / 'appcache/stats' + stats.mkdir(parents=True) + schema = [('42', [('stats', [('1', [('bits', [('0', [ + ('name', 'FIRST'), ('display', [('name', [('english', 'First')])])])])])])])] + (stats / 'UserGameStatsSchema_42.bin').write_bytes(binary_kv(schema)) + (stats / 'UserGameStats_7_42.bin').write_bytes(binary_kv([('cache', [('1', [('AchievementTimes', [('0', 10)])])])])) + swift = scratch / 'check.swift' + swift.write_text(host) + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift), + str(ROOT / 'Sources/NXLibrary/Services/SteamAchievementsStore.swift'), + str(ROOT / 'Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift'), + str(ROOT / 'Sources/NXLibrary/Models/GamepadType.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True) + subprocess.run([str(executable), str(scratch)], check=True, + env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))) diff --git a/Tests/CatalogAppChecks/run_save_restart.py b/Tests/CatalogAppChecks/run_save_restart.py new file mode 100644 index 00000000..8447be0e --- /dev/null +++ b/Tests/CatalogAppChecks/run_save_restart.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Crash/restart the real save transaction against generated temporary data only. + +Run after Core is ready and built with testing enabled. This script only compiles +its helper against .build/debug/NXLibraryCore.o; it never builds or opens the app. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +LIBRARY = ROOT / '.build/debug' +SLOTS = ['account', 'device', *[f'user{i}' for i in range(2, 9)], 'users'] +CRASH = 86 + +HOST = r''' +import Foundation +import Darwin +@testable import NXLibraryCore + +let fm = FileManager.default +let slots: [SaveSlot] = [.account, .device, .user2, .user3, .user4, + .user5, .user6, .user7, .user8, .users] +let names = ["save", "save_device"] + (2...8).map { "save_user\($0)" } + ["save.users"] +let identity = SaveIdentity(titleID: "0100000000000001", gameName: "Restart fixture", + version: "fixture-1", buildID: "synthetic-build") +func require(_ ok: Bool, _ message: String) throws { + if !ok { throw NSError(domain: "SaveRestartCheck", code: 1, + userInfo: [NSLocalizedDescriptionKey: message]) } +} +func write(_ data: Data, to url: URL) throws { + try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url) +} +func payload(_ prefix: String, _ slot: SaveSlot) -> Data { + Data((slot == .users ? "nxnative-users-1\n\(prefix)\n" : "\(prefix)-\(slot.rawValue)\n").utf8) +} +func content(_ root: URL, _ slot: SaveSlot, _ name: String) -> URL { + let piece = root.appendingPathComponent(name) + return slot == .users ? piece : piece.appendingPathComponent("nested/progress") +} +func seed(_ location: SaveLocation, _ prefix: String) throws { + for (slot, name) in zip(slots, names) { + try require(location.directory(slot).lastPathComponent == name, "Incorrect path: \(slot)") + try write(payload(prefix, slot), to: content(location.root, slot, name)) + } +} +func checkGroup(_ root: URL, _ prefix: String) throws { + for (slot, name) in zip(slots, names) { + let piece = root.appendingPathComponent(name) + let kind = try fm.attributesOfItem(atPath: piece.path)[.type] as? FileAttributeType + try require(kind == (slot == .users ? .typeRegular : .typeDirectory), "Incorrect type: \(name)") + try require(try Data(contentsOf: content(root, slot, name)) == payload(prefix, slot), + "Wrong \(prefix) payload: \(name)") + } +} +do { + try require(CommandLine.arguments.count == 4, "Expected mode, fixture path and checkpoint/state") + let mode = CommandLine.arguments[1], argument = CommandLine.arguments[3] + let base = URL(fileURLWithPath: CommandLine.arguments[2]).resolvingSymlinksInPath() + let location = try SaveLocation.defaultLocation(titleID: identity.titleID, + home: base.appendingPathComponent("home")) + let store = SaveSnapshotStore(root: base.appendingPathComponent("backups")) + let targetFile = base.appendingPathComponent("target-id") + try require(SaveSlot.allCases == slots, "Expected all users, with registry last") + if mode == "setup" { + try seed(location, "target") + let target = try store.create(location: location, identity: identity, reason: .manual) + try write(Data(target.id.uuidString.utf8), to: targetFile) + try seed(location, "original") + try write(Data("working".utf8), to: location.root.appendingPathComponent("save_user2.work/progress")) + try write(Data("sync".utf8), to: location.root.appendingPathComponent("save.sync")) + } else { + guard let targetID = UUID(uuidString: try String(contentsOf: targetFile, encoding: .utf8)) else { + throw SaveFailure.invalidSnapshot + } + if mode == "fail" { + let target = try store.verify(snapshotID: targetID, titleID: identity.titleID) + var io = SaveFileIO() + io.afterMutation = { if $0 == argument { _exit(86) } } + try SaveTransaction(store: store, isRunning: { false }, io: io) + .restore(target, location: location, identity: identity) + try require(false, "Forward checkpoint was not reached: \(argument)") + } else if mode == "recover" { + try require(SaveTransaction.needsRecovery(location: location), "Crash left no recovery journal") + var io = SaveFileIO() + io.afterMutation = { if $0 == argument { _exit(86) } } + let transaction = SaveTransaction(store: store, isRunning: { false }, io: io) + try transaction.recover(location: location) + try require(argument == "-", "Recovery checkpoint was not reached: \(argument)") + let once = try store.currentInventory(location: location) + try transaction.recover(location: location) + try require(try store.currentInventory(location: location) == once, "Second recovery changed saves") + try require(!SaveTransaction.needsRecovery(location: location), "Recovery left its journal") + } else if mode == "check" { + try require(argument == "target" || argument == "original", "Unknown expected state") + try require(!SaveTransaction.needsRecovery(location: location), "Recovery is still pending") + let snapshots = try store.list(titleID: identity.titleID) + try require(snapshots.count == 2 && snapshots.contains(where: { $0.id == targetID }), "Missing backup") + for snapshot in snapshots { + let verified = try store.verify(snapshotID: snapshot.id, titleID: identity.titleID) + let isTarget = snapshot.id == targetID + try require(verified == snapshot && verified.identity == identity, "Backup metadata changed") + try require(verified.schemaVersion == 2 && verified.presentSlots == Set(slots), "Incomplete backup") + try require(verified.reason == (isTarget ? .manual : .beforeRestore), "Wrong backup reason") + try checkGroup(try store.directory(snapshotID: snapshot.id, titleID: identity.titleID), + isTarget ? "target" : "original") + } + let expected = snapshots.first { ($0.id == targetID) == (argument == "target") }! + try checkGroup(location.root, argument) + try require(try store.currentInventory(location: location) == expected.entries, "Mixed save group") + try require(try String(contentsOf: location.root.appendingPathComponent("save_user2.work/progress"), encoding: .utf8) + == "working", "Working save changed") + try require(try String(contentsOf: location.root.appendingPathComponent("save.sync"), encoding: .utf8) + == "sync", "Sync sentinel changed") + } else { + try require(false, "Unknown helper mode: \(mode)") + } + } +} catch { + fputs("Save restart check failed: \(error)\n", stderr) + exit(1) +} +''' + + +def backup_bytes(fixture): + root = fixture / 'backups' + return {str(path.relative_to(root)): path.read_bytes() + for path in root.rglob('*') if path.is_file()} + + +def main(): + if not (LIBRARY / 'NXLibraryCore.o').is_file(): + raise SystemExit('Core is not ready: build it with testing enabled before running this harness.') + with tempfile.TemporaryDirectory(prefix='arcane-save-restart-') as scratch: + scratch = Path(scratch) + source, binary = scratch / 'main.swift', scratch / 'save-restart' + source.write_text(HOST) + subprocess.run(['xcrun', 'swiftc', '-I', str(LIBRARY), str(source), + str(LIBRARY / 'NXLibraryCore.o'), '-o', str(binary)], + cwd=ROOT, check=True, timeout=60) + env = dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(LIBRARY)) + + def run(mode, fixture, argument='-', expected=0): + result = subprocess.run([str(binary), mode, str(fixture), argument], + env=env, capture_output=True, text=True, timeout=30) + if result.returncode != expected: + raise RuntimeError(f'{mode} {argument}: exit {result.returncode}, expected {expected}\n' + f'{result.stdout}{result.stderr}') + + cases = [(checkpoint, None) for checkpoint in ['journal', *SLOTS, 'committed', 'cleanup', 'cleanup-item', 'cleanup-stage']] + # All pieces have been swapped at "users", but the journal is not committed. + cases += [('users', f'recovery-{slot}') for slot in SLOTS] + cases += [('users', checkpoint) for checkpoint in ['cleanup', 'cleanup-item', 'cleanup-stage']] + for checkpoint, recovery_crash in cases: + label = recovery_crash or checkpoint + with tempfile.TemporaryDirectory(prefix=f'{label}-', dir=scratch) as fixture: + fixture = Path(fixture) + run('setup', fixture) + run('fail', fixture, checkpoint, expected=CRASH) + backups = backup_bytes(fixture) + if recovery_crash: + run('recover', fixture, recovery_crash, expected=CRASH) + # A fresh process resumes, including after a crash inside rollback. + run('recover', fixture) + run('check', fixture, 'target' if checkpoint in ['committed', 'cleanup', 'cleanup-item', 'cleanup-stage'] else 'original') + if backup_bytes(fixture) != backups: + raise RuntimeError(f'{label}: recovery changed backup files') + print(f'Save restart {label}: PASS', flush=True) + print(f'Save restart checks: PASS ({len(cases)} crash/restart cases)') + + +if __name__ == '__main__': + main() diff --git a/Tests/CatalogAppChecks/run_source_access.py b/Tests/CatalogAppChecks/run_source_access.py new file mode 100644 index 00000000..23de23bf --- /dev/null +++ b/Tests/CatalogAppChecks/run_source_access.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Check source-access triggers using the real startup block, observer and pickers. + +No AppKit windows or player data: replace the picker and the scanner I/O boundary, +then count requests made by the actual AppViewModel code, as in run_review.py. +""" +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +source = (ROOT / 'Sources/NXLibrary/ViewModels/AppViewModel.swift').read_text() + + +def declaration(signature): + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +startup = source[source.index(' restoreBuildInputs(automatic: true)'): + source.index(' recoverSavesAtStartup()')] +host = r''' +import Foundation +import Combine +import UniformTypeIdentifiers + +final class Preferences { + var values: [String: String] = [:] + func string(forKey key: String) -> String? { values[key] } + func set(_ value: String, forKey key: String) { values[key] = value } + func removeObject(forKey key: String) { values[key] = nil } +} +enum AppData { + static let preferences = Preferences() + struct Profile { var isDevelopment = false } + static var profile = Profile() +} +enum StorageKeys { static let savedGameFolder = "fixture-folder" } +struct Startup { var checkEngineAtLaunch = true; var refreshLibraryAtLaunch = true } +struct GameRuntimeConfig {} +enum GameFoldersCopy { + static func sourcesPickerMessage(extractedFolders: Bool) -> String { "Fixture picker" } +} + +// Only the system picker is substituted. The production methods configure it +// and choose which scan to request; no permissions or real windows are involved. +final class NSOpenPanel { + enum Response { case OK, cancel } + static var response = Response.cancel + static var picked: [URL] = [] + static var openedAt: URL? + var canChooseFiles = false + var canChooseDirectories = false + var allowsMultipleSelection = false + var directoryURL: URL? + var prompt = "" + var message = "" + var allowedContentTypes: [UTType] = [] + var urls: [URL] { Self.picked } + var url: URL? { urls.first } + func runModal() -> Response { Self.openedAt = directoryURL; return Self.response } +} + +final class SourceHost { + private var keepsRememberedGameFolder = false + private var restoringGameFolder = false + private var selectedPackageURLs: [URL]? + var scanGeneration = UUID() + var detectedGames: [Int] = [] + var selectedGame: Int? + var selectedSourceIDs: Set<UUID> = [] + var scanError: String? + var isScanningGameFolder = false + var engineSourceCapabilities = (extractedFolders: true, unused: false) + var scans: [(folder: URL, files: [URL]?)] = [] + // ACTUAL_FOLDER + // ACTUAL_REMEMBERED_FOLDER + // ACTUAL_FOLDER_PICKER + // ACTUAL_FILE_PICKER + func restoreBuildInputs(automatic: Bool) {} + func refreshCompatibility() {} + func startNewAddGame(defaults: GameRuntimeConfig) { selectedGameFolder = nil } + func scanGameFolder(_ folder: URL) { scans.append((folder, selectedPackageURLs)) } + func boot(_ startup: Startup) { + let didCompleteSetup = true + // ACTUAL_STARTUP + } +} + +@main struct Check { + static func main() { + var failures = 0 + func require(_ ok: @autoclosure () -> Bool, _ message: String) { + if !ok() { failures += 1; print("FAIL: " + message) } + } + let folder = URL(fileURLWithPath: CommandLine.arguments[1]).appendingPathComponent("Downloads") + AppData.preferences.set(folder.path, forKey: StorageKeys.savedGameFolder) + for development in [false, true] { + AppData.profile.isDevelopment = development + for refresh in [false, true] { + let model = SourceHost() + model.boot(Startup(refreshLibraryAtLaunch: refresh)) + require(model.scans.isEmpty, "Launch must not scan remembered sources (refresh=\(refresh), dev=\(development))") + require(model.selectedGameFolder == nil, "Launch must leave the Add game draft empty") + require(model.gameFilesFolder == folder, "Launch must keep the remembered folder preference") + } + } + + let model = SourceHost() + model.boot(Startup()) + NSOpenPanel.response = .cancel + require(!model.selectGameFolder(), "Cancelling the picker must return false") + require(model.scans.isEmpty, "Cancelling the picker must not scan sources") + require(NSOpenPanel.openedAt == folder, "The folder picker must start at the remembered folder") + + NSOpenPanel.response = .OK + NSOpenPanel.picked = [folder] + require(model.selectGameFolder(), "An explicit folder choice must be accepted") + require(model.scans.count == 1 && model.scans.last?.folder == folder, + "An explicit folder choice must request one scan") + + let otherFolder = folder.deletingLastPathComponent().appendingPathComponent("Other inputs") + let files = [otherFolder.appendingPathComponent("chosen.nsp"), otherFolder.appendingPathComponent("update.nsp")] + let filesModel = SourceHost() + filesModel.boot(Startup()) + NSOpenPanel.picked = files + require(filesModel.selectGameFiles(), "Explicit file choices must be accepted") + require(filesModel.scans.count == 1 && filesModel.scans.last?.files == files, + "Explicit files must request one scan limited to those files") + require(filesModel.gameFilesFolder == folder, "File picks must preserve the remembered folder") + if failures > 0 { exit(1) } + print("Source access checks passed: no launch scan, remembered picker, cancel, explicit folder and files.") + } +} +''' +for marker, signature in ( + ('// ACTUAL_FOLDER', ' @Published public var selectedGameFolder:'), + ('// ACTUAL_REMEMBERED_FOLDER', ' public var gameFilesFolder:'), + ('// ACTUAL_FOLDER_PICKER', ' public func selectGameFolder('), + ('// ACTUAL_FILE_PICKER', ' public func selectGameFiles('), +): + host = host.replace(marker + '\n', declaration(signature) + '\n') +host = host.replace('// ACTUAL_STARTUP', startup) +with tempfile.TemporaryDirectory(prefix='source-access-check-') as folder: + scratch = Path(folder) + swift = scratch / 'check.swift' + swift.write_text(host) + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', str(swift), '-o', str(executable)], check=True) + subprocess.run([str(executable), str(scratch)], check=True) diff --git a/Tests/CatalogAppChecks/run_startup_recovery.py b/Tests/CatalogAppChecks/run_startup_recovery.py new file mode 100644 index 00000000..8ee63cf0 --- /dev/null +++ b/Tests/CatalogAppChecks/run_startup_recovery.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Exercise the actual startup recovery coordinator with isolated catalogs, no windows. + +Only profile selection/preparation and shell construction are substituted. The +catalog, conflict candidates, archives and recovery operations are real Core I/O. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' +source = (ROOT / 'Sources/NXLibrary/Views/Launch/DevelopmentStartupView.swift').read_text() +start = source.index('@MainActor\nfinal class DevelopmentStartup:') +end = source.index('\nprivate enum DevelopmentStartupFailure:', start) +coordinator = source[start:end] + +host = r''' +import Foundation +import AppKit +import Combine +import NXLibraryCore +import os + +enum AppData { + static var supportRoot = URL(fileURLWithPath: "/unused") + static var rejectPreparation = false + struct Profile { var isDevelopment = false } + static let profile = Profile() + static func prepare() throws { + if rejectPreparation { throw CocoaError(.fileReadNoPermission) } + } +} +struct AppSettingsStore {} +final class AppShellState { + let catalog: CatalogDocument + init(settings: AppSettingsStore, catalog: CatalogDocument, repository: CatalogRepository) { + self.catalog = catalog + } +} +enum DevelopmentStartupFailure: Error { case otherCopyRunning } +// ACTUAL_COORDINATOR + +@main struct Check { + @MainActor static func main() async throws { + let root = URL(fileURLWithPath: CommandLine.arguments[1]) + AppData.supportRoot = root + let store = CatalogStore(directory: root) + var mixed = try store.loadOrMigrate() + mixed.games.append(.init(steam: SteamCatalogGame(appID: 42, name: "Fixture"))) + mixed = try store.save(mixed, expectedRevision: mixed.revision) + let legacy = root.appendingPathComponent("library.json") + // Older app creates a legacy library after an initially empty migration. + try Data("older-app bytes".utf8).write(to: legacy) + + let startup = DevelopmentStartup() + await startup.prepare() + precondition(startup.shell == nil && startup.failure != nil) + precondition(startup.legacyConflict != nil && startup.recovery == nil && !startup.working) + await startup.keepCurrentLibrary() + precondition(startup.shell?.catalog.games == mixed.games) + precondition(startup.failure == nil && startup.legacyConflict == nil && !startup.working) + let unchangedLegacy = try Data(contentsOf: legacy) + precondition(unchangedLegacy == Data("older-app bytes".utf8)) + + try Data("second edit".utf8).write(to: legacy) + let stale = DevelopmentStartup() + await stale.prepare() + precondition(stale.legacyConflict != nil && stale.shell == nil) + try Data("third edit".utf8).write(to: legacy) + await stale.keepCurrentLibrary() + precondition(stale.shell == nil && stale.legacyConflict == nil && !stale.working) + precondition(stale.failure != nil) + await stale.prepare() + precondition(stale.legacyConflict != nil) + await stale.keepCurrentLibrary() + precondition(stale.shell?.catalog.games == mixed.games) + + let healthy = DevelopmentStartup() + await healthy.prepare() + precondition(healthy.shell != nil && healthy.legacyConflict == nil && healthy.recovery == nil) + + AppData.rejectPreparation = true + let blocked = DevelopmentStartup() + await blocked.prepare() + precondition(blocked.shell == nil && blocked.failure != nil && !blocked.working) + precondition(blocked.legacyConflict == nil && blocked.recovery == nil) + AppData.rejectPreparation = false + await blocked.prepare() + precondition(blocked.shell != nil && blocked.failure == nil) + print("Actual startup recovery checks passed: conflict, explicit keep, stale offer, retry, healthy startup and preparation failure.") + } +} +'''.replace('// ACTUAL_COORDINATOR', coordinator) + +with tempfile.TemporaryDirectory(prefix='catalog-startup-recovery-') as folder: + scratch = Path(folder) + swift = scratch / 'check.swift' + swift.write_text(host) + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True) + subprocess.run([str(executable), str(scratch / 'profile')], check=True, + env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))) diff --git a/Tests/CatalogAppChecks/run_theme.py b/Tests/CatalogAppChecks/run_theme.py new file mode 100644 index 00000000..5f73e9d6 --- /dev/null +++ b/Tests/CatalogAppChecks/run_theme.py @@ -0,0 +1,307 @@ +#!/usr/bin/env python3 +"""Actual theme input, soft particles and offscreen Metal contracts. + +No windows, player data, screenshots or UI automation. Metal checks are skipped +when the host has no device; Core and actual input checks still run. +""" +from pathlib import Path +import os +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / '.build/debug' + + +def declaration(path, signature): + source = (ROOT / path).read_text() + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +# Controller/keyboard order must match the actual rows, not a second manual list. +import re +look_source = (ROOT / 'Sources/NXLibrary/Views/Settings/SettingsLookSection.swift').read_text() +look_body = look_source[look_source.index(' var body:'):look_source.index(' private func publishActions')] +visible_rows = re.findall(r'Selene(?:Cycle|Toggle)Row\("([^"]+)"', look_body) +actions = declaration('Sources/NXLibrary/Views/Settings/SettingsLookSection.swift', ' private func publishActions(') +action_rows = [a or b for a, b in re.findall( + r'\.value\("[^"]+", "([^"]+)"|\.init\(id: "[^"]+", title: "([^"]+)"', actions)] +assert visible_rows == action_rows, ('Look navigation order differs from visible rows', visible_rows, action_rows) + + +host = r''' +import Foundation +import AppKit +import SwiftUI +import Metal +import NXLibraryCore + +@MainActor enum LaunchReveal { static func moonlightShown() {} } +@MainActor final class SoundEffectService { + enum Cue { case focus, key, click } + static let shared = SoundEffectService() + func play(_ cue: Cue) {} +} +final class PaletteController { + var applied: [String] = [] + func apply(id: String) { applied.append(id) } +} +struct BrowseCategory { var isSearch = false } +struct BrowseState { var focusedItem: Int?; var category = BrowseCategory() } +final class Browser { var state: BrowseState? } +@MainActor final class Host { + var state = ThemePickerState(themeIndex: 0, backgroundIndex: 0) + let palettes: [SelenePalette] + let settings: AppSettingsStore + let theme = PaletteController() + let browser = Browser() + var searchFocused = false + var placements: [String?] = [] + var backgrounds: [ThemeBackgroundChoice] { [.none] } + var focusedBackground: ThemeBackgroundChoice { .none } + init(palettes: [SelenePalette], settings: AppSettingsStore) { self.palettes = palettes; self.settings = settings } + func focusSetting(themeID: String) { state.backgroundIndex = 0 } + func choose(_ item: Int) {} + func addOwn() {} + func askPlacement(_ id: String?) { placements.append(id) } + func openSource(_ id: BackgroundSourceID) {} + // ACTUAL_METHODS + func key(_ direction: GridDirection) { move(direction) } + func next() { accept() } + func click(_ index: Int) { tap(index) } +} +// ACTUAL_STEPPING + +// ACTUAL_BACKDROP_STYLE +// ACTUAL_BACKDROP_REQUEST +// ACTUAL_BACKDROP_KEY +final class BackdropTheme { + var palette: SelenePalette + let palettes: [SelenePalette] + init(_ palettes: [SelenePalette]) { self.palettes=palettes; palette=palettes[0] } + func wallpaper(for id: String?) -> Wallpaper? { nil } + // ACTUAL_APPLY +} +final class BackdropViewModel { + var showSetupCheck = false + var isGameOptionsOpen = false +} +@MainActor final class BackdropHost { + let theme: BackdropTheme + let settings: AppSettingsStore + let viewModel = BackdropViewModel() + let router = AppRouter() + var showsWelcome = false + // ACTUAL_COVER_POLICY + // ACTUAL_COVER_PRIORITY + // ACTUAL_BLUR_POLICY + var covered: Bool { fullScreenCover } + var blur: CGFloat { contentBlur } + var sharedBackdrop: SeleneBackdropRequest? + init(theme: BackdropTheme, settings: AppSettingsStore) { self.theme=theme; self.settings=settings } + // ACTUAL_SHARED_UPDATE + func accept(_ request: SeleneBackdropRequest?) { updateSharedBackdrop(request) } + // ACTUAL_SHELL_STYLE + var snapshot: SeleneBackdropStyle { backdropStyle } +} + +@main struct Check { + @MainActor static func main() throws { + let scratch = URL(fileURLWithPath: CommandLine.arguments[1]) + let settingsURL = scratch.appendingPathComponent("settings.json") + let settings = AppSettingsStore(fileURL: settingsURL) + let palettes = SelenePaletteCatalog.pickerOrder(try SelenePaletteCatalog.load(from: + URL(fileURLWithPath: "Resources/Selene/palettes.json"))) + precondition(palettes[0].name == AppIdentity.name && palettes[0].id == "selene") + precondition(palettes[0].surface == .classic && SelenePalette.fallback.surface == .classic) + precondition(palettes.first { $0.id == "arcane-crystal" }?.surface == .arcane) + precondition(palettes.first { $0.id == "arcane-flow" }?.surface == .flow) + let backdropTheme = BackdropTheme(palettes) + let backdropHost = BackdropHost(theme: backdropTheme, settings: settings) + precondition(!backdropHost.covered && backdropHost.blur == 0) + backdropHost.showsWelcome = true; precondition(backdropHost.covered) + backdropHost.showsWelcome = false + backdropHost.viewModel.showSetupCheck = true; precondition(backdropHost.covered) + backdropHost.viewModel.showSetupCheck = false + backdropHost.router.isMenuPresented = true; precondition(!backdropHost.covered) + backdropHost.router.isThemePickerOpen = true; precondition(backdropHost.covered) + backdropHost.router.closeMenu(); precondition(!backdropHost.covered) + backdropHost.router.openAddGame(); precondition(backdropHost.blur == 10) + backdropHost.router.back(); precondition(backdropHost.blur == 0) + backdropHost.viewModel.isGameOptionsOpen = true; precondition(backdropHost.blur == 10) + backdropHost.viewModel.isGameOptionsOpen = false + let originalBackdrop = backdropHost.snapshot + let homeRequest = SeleneBackdropRequest(style: originalBackdrop) + var stacked: SeleneBackdropRequest? = homeRequest + var mods = homeRequest; mods.modsTint = true + SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { mods }) + SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { nil }) + precondition(stacked?.modsTint == true) + SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { homeRequest }) + precondition(stacked == homeRequest, "the top page replaces the underlying Mods background request") + var setupRequest = homeRequest; setupRequest.priority = 2.5 + var menuRequest = mods; menuRequest.priority = 1 + SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { setupRequest }) + SeleneBackdropRequestKey.reduce(value: &stacked, nextValue: { menuRequest }) + precondition(stacked == setupRequest, "a lower overlay visited later cannot take Setup's background") + backdropHost.accept(homeRequest) + backdropHost.accept(nil) + precondition(backdropHost.sharedBackdrop?.style == originalBackdrop && backdropHost.sharedBackdrop?.still == true, + "a temporary gap retains the background and pauses its clock") + backdropHost.accept(homeRequest) + precondition(backdropHost.sharedBackdrop == homeRequest, "same-wallpaper Settings reuses the same request") + + backdropTheme.apply(id: "arcane-crystal") + let crystalBackdrop = backdropHost.snapshot + precondition(originalBackdrop != crystalBackdrop, + "palette-only changes must update the shared backdrop even with the same wallpaper and selection") + backdropTheme.apply(id: "arcane-flow") + precondition(backdropHost.snapshot != crystalBackdrop) + backdropTheme.apply(id: "selene") + precondition(backdropHost.snapshot == originalBackdrop) + print("Shared backdrop: palette-only changes propagate without moving the selected card: PASS") + let host = Host(palettes: palettes, settings: settings) + host.state.themeIndex = palettes.count - 1 + host.key(.down) + host.key(.right) + precondition(host.state.step == .theme && host.state.themeIndex == palettes.count - 1) + host.state.themeIndex = 4 + host.key(.right) + precondition(host.state.themeIndex == 4) + host.click(0) + precondition(host.state.themeIndex == 0 && host.state.step == .theme) + host.next() + precondition(host.state.step == .background && settings.settings.colorThemeID == "selene") + precondition(host.theme.applied == ["selene"] && host.placements.isEmpty) + host.next() + precondition(host.placements == [WallpaperCatalog.none]) + print("Theme input: grid edges, mouse refocus and Next to background without a particle row: PASS") + + guard MTLCreateSystemDefaultDevice() != nil else { + print("Metal unavailable: offscreen rendering checks skipped.") + return + } + guard let engine = MoonlightEngine.shared else { fatalError("Moonlight shaders failed to initialize") } + let soft = MoonlightColors(accent: .blue, ink: .white) + let arcane = MoonlightColors(accent: .blue, ink: .white, surface: .arcane) + let flow = MoonlightColors(accent: .blue, ink: .white, surface: .flow) + let gold = MoonlightColors(accent: .yellow, ink: .white, tint: 1) + let s = MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: soft) + let a = MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: arcane) + let g = MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: gold) + precondition(s.look.z == 0 && s.look.w == 0 && a.look.z == 0 && a.look.w == 1) + precondition(g.look.w == 0 && g.tintTop.w == 1 && g.look.z == 0) + func pixels(_ colors: MoonlightColors, _ time: Float = 24) -> Data { + let frame = engine.snapshot(width: 640, height: 360, colors: colors, time: time)! + return frame.dataProvider!.data! as Data + } + let fixed = pixels(arcane) + precondition(fixed == pixels(arcane), "a still frame keeps both motion and colour fixed") + precondition(fixed != pixels(arcane, 27)) + let flowPixels = pixels(flow) + precondition(flowPixels != fixed && flowPixels != pixels(flow, 44)) + precondition(flowPixels == pixels(flow)) + var blended = flow + blended.flow = 0.5; blended.arcane = 0.5; blended.tint = 0.5 + precondition(pixels(blended) != fixed && pixels(blended) != flowPixels) + for var hidden in [arcane, flow, blended] { + hidden.presence = 0 + precondition(pixels(hidden).allSatisfy { $0 == 0 }, "covered surfaces and particles must remain transparent") + } + precondition(MoonlightEngine.uniforms(width: 640, height: 360, time: 24, breath: 0.75, colors: flow).look.z == 1) + precondition(fixed != pixels(soft), "the colour field reaches soft particles too") + precondition(pixels(gold) != fixed) + + // Exercise the very function the real fragment/vertex entry points call. + let source = MoonlightShaders.source + """ + kernel void sampleArcane(device float4 *out [[buffer(0)]], uint i [[thread_position_in_grid]]) { + out[i] = float4(arcaneSpectrum(float2(float(i) * 0.13, 0.3 + float(i) * 0.05), float(i) * 35.3, 0.0), 1.0); + } + kernel void sampleWind(device float4 *out [[buffer(0)]], uint i [[thread_position_in_grid]]) { + float phase = float(i)*0.4; + out[i] = float4(filamentY(0.5,float2(0.1,0.3),float2(0.9,0.7),0.0,phase,0.0), + filamentProfile(0.0), filamentProfile(1.0), + filamentY(0.7,float2(0.1,0.3),float2(0.9,0.7),0.0,phase,0.0)); + } + """ + let device = engine.device + let library = try device.makeLibrary(source: source, options: nil) + let pipeline = try device.makeComputePipelineState(function: library.makeFunction(name: "sampleArcane")!) + let buffer = device.makeBuffer(length: 6 * MemoryLayout<SIMD4<Float>>.stride, options: .storageModeShared)! + let command = device.makeCommandQueue()!.makeCommandBuffer()! + let encoder = command.makeComputeCommandEncoder()! + encoder.setComputePipelineState(pipeline); encoder.setBuffer(buffer, offset: 0, index: 0) + encoder.dispatchThreads(MTLSize(width: 6, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 6, height: 1, depth: 1)) + encoder.endEncoding(); command.commit(); command.waitUntilCompleted() + precondition(command.status == .completed) + let values = buffer.contents().bindMemory(to: SIMD4<Float>.self, capacity: 6) + for i in 0..<6 { + let expected = MoonlightChromatics.sample(x: Float(i) * 0.13, y: 0.3 + Float(i) * 0.05, time: Float(i) * 35.3) + for k in 0..<3 { precondition(abs(values[i][k] - expected[k]) < 0.00002) } + } + let windPipeline = try device.makeComputePipelineState(function: library.makeFunction(name: "sampleWind")!) + let windBuffer = device.makeBuffer(length: 16 * MemoryLayout<SIMD4<Float>>.stride, options: .storageModeShared)! + let windCommand = device.makeCommandQueue()!.makeCommandBuffer()! + let windEncoder = windCommand.makeComputeCommandEncoder()! + windEncoder.setComputePipelineState(windPipeline) + windEncoder.setBuffer(windBuffer, offset: 0, index: 0) + windEncoder.dispatchThreads(MTLSize(width: 16,height: 1,depth: 1), threadsPerThreadgroup: MTLSize(width: 16,height: 1,depth: 1)) + windEncoder.endEncoding(); windCommand.commit(); windCommand.waitUntilCompleted() + precondition(windCommand.status == .completed) + let wind = windBuffer.contents().bindMemory(to: SIMD4<Float>.self, capacity: 16) + let heights = (0..<16).map { wind[$0].x } + precondition(heights.max()! - heights.min()! > 0.025 && heights.max()! - heights.min()! < 0.08, + "wind must bend the curve visibly, within a small part of the height") + precondition(wind[0].z < wind[0].y * 0.2, "one pixel from the core, light must be faint") + precondition(abs((wind[3].x-wind[0].x)-(wind[3].w-wind[0].w)) > 0.001, + "wind deforms the curve instead of translating a rigid line") + for i in 1..<16 { precondition(abs(wind[i].x-wind[i-1].x) < 0.025) } + print("Actual Metal: thin core and bounded travelling wind deformation: PASS") + print("Actual Metal: local colour parity, distinct moving surfaces, soft particles, fixed frame and distinct Mods uniforms: PASS") + } +} +''' + +path = 'Sources/NXLibrary/Views/Theme/ThemePickerView.swift' +methods = '\n'.join(declaration(path, signature) for signature in ( + ' private func move(', ' private func tap(', ' private func accept(')) +host = host.replace('// ACTUAL_METHODS', methods) +host = host.replace('// ACTUAL_BACKDROP_STYLE', declaration( + 'Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift', 'struct SeleneBackdropStyle:')) +host = host.replace('// ACTUAL_BACKDROP_REQUEST', declaration( + 'Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift', 'struct SeleneBackdropRequest:')) +host = host.replace('// ACTUAL_SHARED_UPDATE', declaration( + 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private func updateSharedBackdrop(')) +host = host.replace('// ACTUAL_BACKDROP_KEY', declaration( + 'Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift', 'struct SeleneBackdropRequestKey:')) +host = host.replace('// ACTUAL_COVER_POLICY', declaration( + 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var fullScreenCover:')) +host = host.replace('// ACTUAL_COVER_PRIORITY', declaration( + 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var currentBackdropCover:')) +host = host.replace('// ACTUAL_BLUR_POLICY', declaration( + 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var contentBlur:')) +host = host.replace('// ACTUAL_APPLY', declaration( + 'Sources/NXLibrary/Views/Theme/ThemeStore.swift', ' public func apply(')) +host = host.replace('// ACTUAL_SHELL_STYLE', declaration( + 'Sources/NXLibrary/Views/Shell/AppShellView.swift', ' private var backdropStyle:')) + +host = host.replace('// ACTUAL_STEPPING', declaration( + 'Sources/NXLibrary/Views/Components/SeleneSettingsRow.swift', 'extension CaseIterable where Self: Equatable')) + +with tempfile.TemporaryDirectory(prefix='arcane-theme-check-') as folder: + scratch = Path(folder) + swift = scratch / 'check.swift' + swift.write_text(host) + executable = scratch / 'check' + subprocess.run(['xcrun', 'swiftc', '-parse-as-library', '-I', str(BIN), str(swift), + str(ROOT / 'Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift'), + str(ROOT / 'Sources/NXLibrary/Views/Theme/MoonlightShaders.swift'), + str(BIN / 'NXLibraryCore.o'), '-o', str(executable)], cwd=ROOT, check=True) + subprocess.run([str(executable), str(scratch)], cwd=ROOT, check=True, + env=dict(os.environ, PACKAGE_RESOURCE_BUNDLE_PATH=str(BIN))) diff --git a/Tests/NXLibraryCoreTests/AchievementSummaryTests.swift b/Tests/NXLibraryCoreTests/AchievementSummaryTests.swift new file mode 100644 index 00000000..2da84065 --- /dev/null +++ b/Tests/NXLibraryCoreTests/AchievementSummaryTests.swift @@ -0,0 +1,125 @@ +import XCTest +@testable import NXLibraryCore + +final class AchievementSummaryTests: XCTestCase { + private func a(_ api: String, at: TimeInterval? = nil, hidden: Bool = false) -> SteamAchievement { + SteamAchievement(apiName: api, name: "N-\(api)", description: "D-\(api)", hidden: hidden, + icon: "\(api).jpg", grayIcon: "\(api)-g.jpg", unlockedAt: at.map { Date(timeIntervalSince1970: $0) }) + } + + func testCountsAndPercentage() { + let list = (0..<50).map { a("A\($0)", at: $0 < 17 ? TimeInterval($0 + 1) : nil) } + let summary = AchievementSummary(achievements: list, percents: [:]) + XCTAssertEqual(summary.total, 50) + XCTAssertEqual(summary.unlocked, 17) + XCTAssertEqual(summary.percentComplete, 34) + } + + func testCompleteOnlyWithEveryAchievementUnlocked() { + XCTAssertTrue(AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2)], percents: [:]).isComplete) + XCTAssertFalse(AchievementSummary(achievements: [a("A", at: 1), a("B")], percents: [:]).isComplete) + XCTAssertFalse(AchievementSummary(achievements: [], percents: [:]).isComplete) + } + + func testEmptyIsZeroPercent() { + XCTAssertEqual(AchievementSummary(achievements: [], percents: [:]).percentComplete, 0) + } + + func testAllOrdersUnlockedNewestThenLockedMostCommon() { + let summary = AchievementSummary(achievements: [a("L1"), a("U1", at: 10), a("L2"), a("U2", at: 20)], + percents: ["L1": 5, "L2": 50, "U1": 1, "U2": 2]) + XCTAssertEqual(summary.rows(.all).map(\.id), ["U2", "U1", "L2", "L1"]) + } + + func testUnknownRarityGoesLast() { + let summary = AchievementSummary(achievements: [a("X"), a("Y"), a("Z")], percents: ["Z": 3]) + XCTAssertEqual(summary.rows(.locked).map(\.id), ["Z", "X", "Y"]) + XCTAssertEqual(summary.rows(.all, order: .rarest).map(\.id), ["Z", "X", "Y"]) + XCTAssertEqual(summary.rows(.all, order: .commonest).map(\.id), ["Z", "X", "Y"]) + } + + func testFiltersSplitUnlockedAndLocked() { + let summary = AchievementSummary(achievements: [a("L"), a("U", at: 1)], percents: [:]) + XCTAssertEqual(summary.rows(.unlocked).map(\.id), ["U"]) + XCTAssertEqual(summary.rows(.locked).map(\.id), ["L"]) + } + + func testRarestFirstIsAscendingRarity() { + let summary = AchievementSummary(achievements: [a("A", at: 1), a("B"), a("C")], percents: ["A": 40, "B": 2, "C": 90]) + XCTAssertEqual(summary.rows(.all, order: .rarest).map(\.id), ["B", "A", "C"]) + } + + func testMostCommonFirstIsDescendingRarity() { + let summary = AchievementSummary(achievements: [a("A", at: 1), a("B"), a("C")], percents: ["A": 40, "B": 2, "C": 90]) + XCTAssertEqual(summary.rows(.all, order: .commonest).map(\.id), ["C", "A", "B"]) + } + + /// An order sorts inside the filter: Unlocked stays the unlocked ones. + func testOrderAppliesWithinTheFilter() { + let summary = AchievementSummary(achievements: [a("U1", at: 1), a("U2", at: 2), a("L")], + percents: ["U1": 3, "U2": 60, "L": 1]) + XCTAssertEqual(summary.rows(.unlocked, order: .rarest).map(\.id), ["U1", "U2"]) + XCTAssertEqual(summary.rows(.unlocked, order: .commonest).map(\.id), ["U2", "U1"]) + XCTAssertEqual(summary.rows(.unlocked).map(\.id), ["U2", "U1"], "default: newest first") + } + + /// Equal rarity keeps the default order, so a re-read never shuffles ties. + func testTiesKeepTheDefaultOrder() { + let summary = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2), a("C")], + percents: ["A": 10, "B": 10, "C": 10]) + XCTAssertEqual(summary.rows(.all, order: .rarest).map(\.id), ["B", "A", "C"]) + XCTAssertEqual(summary.rows(.all, order: .commonest).map(\.id), ["B", "A", "C"]) + } + + func testFiltersAreAllUnlockedLocked() { + XCTAssertEqual(AchievementFilter.allCases, [.all, .unlocked, .locked]) + XCTAssertEqual(AchievementOrder.allCases, [.default, .rarest, .commonest]) + } + + func testHiddenLockedIsMaskedAndUnlockedHiddenIsNot() { + let summary = AchievementSummary(achievements: [a("H", hidden: true), a("V", at: 1, hidden: true)], percents: [:]) + let locked = summary.rows(.locked)[0] + XCTAssertTrue(locked.isMasked) + XCTAssertEqual(locked.name, L10n.text("Hidden achievement")) + XCTAssertEqual(locked.description, L10n.text("Keep playing to reveal it.")) + XCTAssertEqual(locked.icon, "H-g.jpg") + let unlocked = summary.rows(.unlocked)[0] + XCTAssertFalse(unlocked.isMasked) + XCTAssertEqual(unlocked.name, "N-V") + XCTAssertEqual(unlocked.icon, "V.jpg") + } + + func testHiddenLockedWithoutGrayIconShowsNoIcon() { + let hidden = SteamAchievement(apiName: "H", name: "N", description: "D", hidden: true, + icon: "color.jpg", grayIcon: nil, unlockedAt: nil) + let summary = AchievementSummary(achievements: [hidden], percents: [:]) + XCTAssertNil(summary.rows(.locked)[0].icon, "the color icon would give the secret away") + XCTAssertTrue(summary.recentIcons.isEmpty) + } + + /// The card locks and blurs a secret among its gray icons, as the list does. + func testRecentIconsSayWhichAreSecret() { + let summary = AchievementSummary(achievements: [a("A"), a("H", hidden: true)], percents: [:]) + XCTAssertEqual(summary.recentIcons.map(\.icon), ["A-g.jpg", "H-g.jpg"]) + XCTAssertEqual(summary.recentIcons.map(\.isMasked), [false, true]) + } + + func testRecentIconsFallBackToLockedGray() { + let none = AchievementSummary(achievements: [a("A"), a("B"), a("C"), a("D")], percents: [:]) + XCTAssertEqual(none.recentIcons.map(\.icon), ["A-g.jpg", "B-g.jpg", "C-g.jpg"]) + let some = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 3), a("C"), a("D", at: 2), a("E", at: 4)], percents: [:]) + XCTAssertEqual(some.recentIcons.map(\.icon), ["E.jpg", "B.jpg", "D.jpg"]) + } + + func testRecentUnlockedIconsNewestFirstCapped() { + let list = (0..<15).map { a("U\($0)", at: TimeInterval($0 + 1)) } + [a("L")] + let summary = AchievementSummary(achievements: list, percents: [:]) + XCTAssertEqual(summary.recentUnlockedIcons(limit: 12).count, 12) + XCTAssertEqual(summary.recentUnlockedIcons(limit: 3), ["U14.jpg", "U13.jpg", "U12.jpg"]) + } + + func testRecentUnlockedIconsEmptyBeforeAnyUnlock() { + let summary = AchievementSummary(achievements: [a("A"), a("B")], percents: [:]) + XCTAssertTrue(summary.recentUnlockedIcons(limit: 12).isEmpty, "locked gray icons are not 'recently unlocked'") + } +} diff --git a/Tests/NXLibraryCoreTests/AchievementTierTests.swift b/Tests/NXLibraryCoreTests/AchievementTierTests.swift new file mode 100644 index 00000000..0e51b6a4 --- /dev/null +++ b/Tests/NXLibraryCoreTests/AchievementTierTests.swift @@ -0,0 +1,145 @@ +import XCTest +import AVFoundation +import ImageIO +@testable import NXLibraryCore + +final class AchievementTierTests: XCTestCase { + private func a(_ api: String, at: TimeInterval? = nil) -> SteamAchievement { + SteamAchievement(apiName: api, name: "N-\(api)", description: "D-\(api)", hidden: false, + icon: nil, grayIcon: nil, unlockedAt: at.map { Date(timeIntervalSince1970: $0) }) + } + + func testThresholds() { + XCTAssertEqual(AchievementTier.forPercent(0), .gold) + XCTAssertEqual(AchievementTier.forPercent(9.94), .gold) + XCTAssertEqual(AchievementTier.forPercent(10), .silver) + XCTAssertEqual(AchievementTier.forPercent(29.94), .silver) + XCTAssertEqual(AchievementTier.forPercent(30), .bronze) + XCTAssertEqual(AchievementTier.forPercent(100), .bronze) + XCTAssertNil(AchievementTier.forPercent(nil)) + } + + /// The screen prints one decimal: the tier follows the number the player reads. + func testTierFollowsTheShownPercent() { + XCTAssertEqual(AchievementTier.forPercent(9.96), .silver, "shown as 10.0%") + XCTAssertEqual(AchievementTier.forPercent(9.94), .gold, "shown as 9.9%") + XCTAssertEqual(AchievementTier.forPercent(29.96), .bronze, "shown as 30.0%") + } + + func testBoardOrderIsRarestFirst() { + XCTAssertEqual(AchievementTier.allCases, [.arcane, .gold, .silver, .bronze]) + } + + func testRowTierFollowsPercent() { + let summary = AchievementSummary(achievements: [a("G"), a("X")], percents: ["G": 4]) + let rows = Dictionary(uniqueKeysWithValues: summary.rows(.all).map { ($0.id, $0) }) + XCTAssertEqual(rows["G"]?.tier, .gold) + XCTAssertNil(rows["X"]?.tier) + } + + func testCountsPerTier() { + let summary = AchievementSummary(achievements: [a("U1", at: 1), a("L1"), a("U2", at: 2), a("L2")], + percents: ["U1": 5, "L1": 5, "U2": 20, "L2": 50]) + XCTAssertEqual(summary.tierCounts[.gold], TierCount(unlocked: 1, total: 2)) + XCTAssertEqual(summary.tierCounts[.silver], TierCount(unlocked: 1, total: 1)) + XCTAssertEqual(summary.tierCounts[.bronze], TierCount(unlocked: 0, total: 1)) + XCTAssertEqual(summary.tierCounts[.arcane], TierCount(unlocked: 0, total: 1)) + XCTAssertTrue(summary.hasRarity) + } + + func testArcaneOnlyAtHundredPercent() { + let summary = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2)], percents: ["A": 50]) + XCTAssertEqual(summary.tierCounts[.arcane], TierCount(unlocked: 1, total: 1)) + } + + func testNoAchievementsNoArcane() { + let summary = AchievementSummary(achievements: [], percents: [:]) + for tier in AchievementTier.allCases { + XCTAssertEqual(summary.tierCounts[tier], TierCount(unlocked: 0, total: 0), "\(tier)") + } + XCTAssertNil(summary.lastUnlockedAt) + } + + // MARK: The page card's crystal: the best one earned + + /// Everything unlocked: Arcane, even before Steam's rarity arrives. + func testBestTierIsArcaneAtHundredPercent() { + let summary = AchievementSummary(achievements: [a("A", at: 1), a("B", at: 2)], percents: [:]) + XCTAssertEqual(summary.bestTier, .arcane) + } + + /// Otherwise the rarest tier among the unlocked ones; a rarer one still locked doesn't count. + func testBestTierIsTheRarestUnlocked() { + let summary = AchievementSummary(achievements: [a("B", at: 1), a("S", at: 2), a("G")], + percents: ["B": 60, "S": 20, "G": 3]) + XCTAssertEqual(summary.bestTier, .silver) + let gold = AchievementSummary(achievements: [a("B", at: 1), a("G", at: 2), a("L")], + percents: ["B": 60, "G": 3, "L": 1]) + XCTAssertEqual(gold.bestTier, .gold) + } + + func testBestTierNilWithNothingUnlocked() { + let summary = AchievementSummary(achievements: [a("G"), a("B")], percents: ["G": 3, "B": 60]) + XCTAssertNil(summary.bestTier) + XCTAssertNil(AchievementSummary(achievements: [], percents: [:]).bestTier) + } + + /// Unlocked achievements whose rarity hasn't arrived give no crystal yet: the card keeps its percent. + func testBestTierNilWhileRarityUnknown() { + let summary = AchievementSummary(achievements: [a("A", at: 1), a("B")], percents: ["B": 3]) + XCTAssertNil(summary.bestTier) + } + + func testUnknownRarityHasNoTierAndNoCounts() { + let summary = AchievementSummary(achievements: [a("A", at: 1), a("B")], percents: [:]) + XCTAssertTrue(summary.rows(.all).allSatisfy { $0.tier == nil }) + for tier in [AchievementTier.gold, .silver, .bronze] { + XCTAssertEqual(summary.tierCounts[tier], TierCount(unlocked: 0, total: 0), "\(tier)") + } + XCTAssertEqual(summary.tierCounts[.arcane], TierCount(unlocked: 0, total: 1)) + XCTAssertFalse(summary.hasRarity) + } + + func testLastUnlockedIsNewest() { + let summary = AchievementSummary(achievements: [a("A", at: 10), a("B", at: 20), a("C")], percents: [:]) + XCTAssertEqual(summary.lastUnlockedAt, Date(timeIntervalSince1970: 20)) + } + + /// The completion tier is Arcane (violet), no longer Platinum; the rarity tiers keep their classic names. + func testDisplayNames() { + let english = AppLocale(language: .english, region: "US") + XCTAssertEqual(AchievementTier.allCases.map { $0.displayName(context: english) }, + ["Arcane", "Gold", "Silver", "Bronze"]) + let italian = AppLocale(language: .italian, region: "IT") + XCTAssertEqual(AchievementTier.allCases.map { $0.displayName(context: italian) }, + ["Arcano", "Oro", "Argento", "Bronzo"]) + } + + /// 1024 px: the detail shows the crystal about 540 px tall on a Retina screen; 512 px art was upscaled there + /// and looked soft. + func testOnlyArcaneHasALoopingAlphaVideo() async throws { + for tier in [AchievementTier.gold, .silver, .bronze] { XCTAssertNil(tier.videoURL, "\(tier)") } + let url = try XCTUnwrap(AchievementTier.arcane.videoURL) + let asset = AVURLAsset(url: url) + let tracks = try await asset.loadTracks(withMediaType: .video) + let track = try XCTUnwrap(tracks.first) + let formats = try await track.load(.formatDescriptions) + let format = try XCTUnwrap(formats.first) + XCTAssertEqual(CMFormatDescriptionGetExtension(format, extensionKey: kCMFormatDescriptionExtension_ContainsAlphaChannel) as? Bool, true) + XCTAssertEqual(CMFormatDescriptionGetMediaSubType(format), kCMVideoCodecType_HEVC) // hvc1: decoded by the media engine + let size = try await track.load(.naturalSize) + XCTAssertEqual(size, CGSize(width: 384, height: 384)) + let seconds = try await asset.load(.duration).seconds + XCTAssertGreaterThanOrEqual(seconds, 7); XCTAssertLessThanOrEqual(seconds, 8) + } + + func testEveryTierHasArt() throws { + for tier in AchievementTier.allCases { + let url = try XCTUnwrap(tier.imageURL, "\(tier)") + let source = try XCTUnwrap(CGImageSourceCreateWithURL(url as CFURL, nil), "\(tier)") + let props = try XCTUnwrap(CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]) + XCTAssertGreaterThanOrEqual(props[kCGImagePropertyPixelWidth] as? Int ?? 0, 1024, "\(tier)") + XCTAssertGreaterThanOrEqual(props[kCGImagePropertyPixelHeight] as? Int ?? 0, 1024, "\(tier)") + } + } +} diff --git a/Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift b/Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift new file mode 100644 index 00000000..15493215 --- /dev/null +++ b/Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift @@ -0,0 +1,163 @@ +import XCTest +@testable import NXLibraryCore + +final class AchievementsScreenStateTests: XCTestCase { + private func ids(_ count: Int) -> [String] { (0..<count).map { "A\($0)" } } + + func testMovesInOneColumn() { + var state = AchievementsScreenState(ids: ids(3)) + XCTAssertTrue(state.move(.down)) + XCTAssertEqual(state.index, 1) + XCTAssertTrue(state.move(.down)) + XCTAssertEqual(state.index, 2) + XCTAssertFalse(state.move(.down), "no row below the last") + XCTAssertTrue(state.move(.up)) + XCTAssertEqual(state.index, 1) + state.index = 0 + XCTAssertFalse(state.move(.up)) + } + + func testLeftRightNeverMove() { + var state = AchievementsScreenState(ids: ids(4)) + state.index = 1 + XCTAssertFalse(state.move(.left)) + XCTAssertFalse(state.move(.right)) + XCTAssertEqual(state.index, 1) + } + + func testEmptyListDoesNotMove() { + var state = AchievementsScreenState(ids: ids(0)) + XCTAssertFalse(state.move(.down)) + XCTAssertFalse(state.move(.right)) + XCTAssertEqual(state.index, 0) + } + + func testFilterResetsIndex() { + var state = AchievementsScreenState(ids: ids(6)) + state.index = 5 + state.setFilter(.locked, ids: ids(2)) + XCTAssertEqual(state.filter, .locked) + XCTAssertEqual(state.index, 0) + XCTAssertEqual(state.count, 2) + } + + func testShiftFilterWraps() { + var state = AchievementsScreenState(ids: ids(3)) + state.shiftFilter(by: -1) { _ in self.ids(3) } + XCTAssertEqual(state.filter, .locked) + state.shiftFilter(by: 1) { _ in self.ids(3) } + XCTAssertEqual(state.filter, .all) + state.shiftFilter(by: 1) { self.ids($0 == .unlocked ? 1 : 3) } + XCTAssertEqual(state.filter, .unlocked) + XCTAssertEqual(state.count, 1) + } + + func testFewerRowsKeepTheIndexInside() { + var state = AchievementsScreenState(ids: ids(6)) + state.index = 5 + state.setIDs(ids(3)) + XCTAssertEqual(state.index, 2) + state.setIDs([]) + XCTAssertEqual(state.index, 0) + state.setIDs(ids(4)) + XCTAssertEqual(state.index, 0) + } + + func testAReorderedListKeepsTheFocusedAchievement() { + var state = AchievementsScreenState(ids: ["A", "B", "C", "D"]) + state.index = 2 + XCTAssertEqual(state.focusedID, "C") + // The rarity arrived (or an unlock moved a row): the same achievement keeps the focus. + state.setIDs(["C", "A", "D", "B"]) + XCTAssertEqual(state.index, 0) + XCTAssertEqual(state.focusedID, "C") + // Gone from this filter: the place it had, inside the list. + state.setIDs(["A", "D"]) + XCTAssertEqual(state.index, 0) + } + + // MARK: - Detail (A opens the focused achievement) + + func testDetailOpensOnTheFocusedRow() { + var state = AchievementsScreenState(ids: ids(3)) + state.index = 1 + XCTAssertTrue(state.openDetail()) + XCTAssertTrue(state.isDetailOpen) + XCTAssertEqual(state.focusedID, "A1") + state.closeDetail() + XCTAssertFalse(state.isDetailOpen) + XCTAssertEqual(state.index, 1, "closing keeps the row") + } + + func testDetailNeedsARow() { + var state = AchievementsScreenState(ids: []) + XCTAssertFalse(state.openDetail()) + XCTAssertFalse(state.isDetailOpen) + } + + func testMovingWhileOpenStepsTheDetail() { + var state = AchievementsScreenState(ids: ids(3)) + state.openDetail() + XCTAssertTrue(state.move(.down)) + XCTAssertTrue(state.isDetailOpen) + XCTAssertEqual(state.focusedID, "A1") + } + + func testFilterClosesTheDetail() { + var state = AchievementsScreenState(ids: ids(3)) + state.openDetail() + state.setFilter(.locked, ids: ids(2)) + XCTAssertFalse(state.isDetailOpen) + state.openDetail() + state.shiftFilter(by: 1) { _ in self.ids(2) } + XCTAssertFalse(state.isDetailOpen) + } + + /// A re-read keeps the detail on its achievement; gone from the list, the detail closes rather than show + /// another one. + func testRereadKeepsOrClosesTheDetail() { + var state = AchievementsScreenState(ids: ids(3)) + state.index = 1 + state.openDetail() + state.setIDs(["A9", "A1", "A2"]) + XCTAssertTrue(state.isDetailOpen) + XCTAssertEqual(state.focusedID, "A1") + state.setIDs(["A0", "A2"]) + XCTAssertFalse(state.isDetailOpen) + } + + // MARK: - Order (Y) + + func testOrderCyclesAndStartsAtTheTop() { + var state = AchievementsScreenState(ids: ids(4)) + XCTAssertEqual(state.order, .default) + state.index = 3 + state.cycleOrder { _ in self.ids(4) } + XCTAssertEqual(state.order, .rarest) + XCTAssertEqual(state.index, 0) + state.cycleOrder { _ in self.ids(4) } + XCTAssertEqual(state.order, .commonest) + state.cycleOrder { _ in self.ids(4) } + XCTAssertEqual(state.order, .default, "wraps") + } + + func testOrderPassesItselfForTheRows() { + var state = AchievementsScreenState(ids: ids(2)) + state.cycleOrder { $0 == .rarest ? ["R"] : [] } + XCTAssertEqual(state.ids, ["R"]) + } + + func testFilterKeepsTheOrder() { + var state = AchievementsScreenState(ids: ids(3)) + state.cycleOrder { _ in self.ids(3) } + state.setFilter(.locked, ids: ids(1)) + XCTAssertEqual(state.order, .rarest) + } + + func testOrderClosesTheDetail() { + var state = AchievementsScreenState(ids: ids(3)) + state.openDetail() + state.cycleOrder { _ in self.ids(3) } + XCTAssertFalse(state.isDetailOpen) + } +} diff --git a/Tests/NXLibraryCoreTests/AppBundleRenameTests.swift b/Tests/NXLibraryCoreTests/AppBundleRenameTests.swift new file mode 100644 index 00000000..76871425 --- /dev/null +++ b/Tests/NXLibraryCoreTests/AppBundleRenameTests.swift @@ -0,0 +1,75 @@ +import XCTest +@testable import NXLibraryCore + +final class AppBundleRenameTests: XCTestCase { + private var dir: URL! + + override func setUpWithError() throws { + dir = FileManager.default.temporaryDirectory.appendingPathComponent("AppBundleRename-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) + try? FileManager.default.removeItem(at: dir) + } + + private func makeBundle(_ name: String) throws -> URL { + let url = dir.appendingPathComponent(name) + try FileManager.default.createDirectory(at: url.appendingPathComponent("Contents"), withIntermediateDirectories: true) + return url + } + + private func target(_ bundle: URL, isRelease: Bool = true, isTranslocated: Bool = false, + isBusy: Bool = false) -> URL? { + AppBundleRename.target(bundleURL: bundle, isRelease: isRelease, isTranslocated: isTranslocated, isBusy: isBusy) + } + + func testOldNameInWritableFolderBecomesArcane() throws { + let bundle = try makeBundle("NX Library.app") + let renamed = try XCTUnwrap(target(bundle)) + XCTAssertEqual(renamed.lastPathComponent, "Arcane.app") + XCTAssertEqual(renamed.deletingLastPathComponent().standardizedFileURL, dir.standardizedFileURL) + + try AppBundleRename.perform(bundleURL: bundle, to: renamed) + XCTAssertFalse(FileManager.default.fileExists(atPath: bundle.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: renamed.appendingPathComponent("Contents").path)) + } + + func testExistingArcaneBlocksRename() throws { + let bundle = try makeBundle("NX Library.app") + try makeBundle("Arcane.app") + XCTAssertNil(target(bundle)) + } + + func testReadOnlyFolderBlocksRename() throws { + let bundle = try makeBundle("NX Library.app") + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: dir.path) + XCTAssertNil(target(bundle)) + } + + func testDevelopmentCopyNeverRenames() throws { + XCTAssertNil(target(try makeBundle("NX Library.app"), isRelease: false)) + } + + func testTranslocatedCopyNeverRenames() throws { + XCTAssertNil(target(try makeBundle("NX Library.app"), isTranslocated: true)) + } + + func testBusyAppNeverRenames() throws { + XCTAssertNil(target(try makeBundle("NX Library.app"), isBusy: true)) + } + + func testAnyOtherNameIsLeftAlone() throws { + XCTAssertNil(target(try makeBundle("My Games.app"))) + XCTAssertNil(target(try makeBundle("Arcane.app"))) + } + + func testFailedMoveLeavesTheOldBundle() throws { + let bundle = try makeBundle("NX Library.app") + let renamed = try XCTUnwrap(target(bundle)) + try makeBundle("Arcane.app") + XCTAssertThrowsError(try AppBundleRename.perform(bundleURL: bundle, to: renamed)) + XCTAssertTrue(FileManager.default.fileExists(atPath: bundle.appendingPathComponent("Contents").path)) + } +} diff --git a/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift b/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift index c6e2289e..e3bcb766 100644 --- a/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift +++ b/Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift @@ -65,11 +65,12 @@ final class AppIconPreferenceTests: XCTestCase { func testLibraryRescanPreservesOnlyHereRatherThanTakingScannedDefaults() throws { let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: dir) } - let store = LibraryStore(directory: dir) + let store = CatalogRepository(store: CatalogStore(directory: dir)) + try store.configureSource(.nxnative, enabled: true, root: nil) var saved = game() saved.appIconOnMac = false - try store.save(LibraryFile(games: [saved])) - let merged = try XCTUnwrap(try store.merge(scanned: [game()]).games.first) + try store.updateNXNativeGames { $0 = [saved] } + let merged = try XCTUnwrap(try store.mergeNXNative(scanned: [game()]).nxnativeGames.first) XCTAssertEqual(merged.appIconOnMac, false) XCTAssertFalse(merged.wantsPickedAppIcon(hasPick: true, hasOriginalIcon: false)) } diff --git a/Tests/NXLibraryCoreTests/AppLocaleTests.swift b/Tests/NXLibraryCoreTests/AppLocaleTests.swift index 44269999..16408dde 100644 --- a/Tests/NXLibraryCoreTests/AppLocaleTests.swift +++ b/Tests/NXLibraryCoreTests/AppLocaleTests.swift @@ -9,9 +9,9 @@ final class AppLocaleTests: XCTestCase { let identities = SettingsSection.allCases.map(\.id) let italian = AppLocale(language: .italian, region: "IT") let french = AppLocale(language: .french, region: "FR") - XCTAssertEqual(SettingsSection.games.title(in: italian), "Giochi") - XCTAssertEqual(SettingsSection.games.title(in: french), "Jeux") - XCTAssertEqual(SettingsSection.games.title, "Games") + XCTAssertEqual(SettingsSection.libraryGames.title(in: italian), "Giochi") + XCTAssertEqual(SettingsSection.libraryGames.title(in: french), "Jeux") + XCTAssertEqual(SettingsSection.libraryGames.title, "Games") XCTAssertEqual(SettingsSection.allCases.map(\.id), identities) XCTAssertEqual(SettingsSection.startUp.id, "startUp") } @@ -128,6 +128,9 @@ final class AppLocaleTests: XCTestCase { L10n.setContext(AppLocale(language: language, region: "CH")) let warning = BuildWarningCopy.text(stage: "Pipeline archive", summary: "RAW_INTERNAL_SENTINEL") XCTAssertFalse(warning.contains("RAW_INTERNAL_SENTINEL"), language.rawValue) + let prewarm = BuildWarningCopy.text(stage: "Prewarm pipelines", summary: "RAW_INTERNAL_SENTINEL") + XCTAssertFalse(prewarm.contains("RAW_INTERNAL_SENTINEL"), language.rawValue) + XCTAssertFalse(prewarm.contains("Some pipelines could not be prepared"), language.rawValue) let missingTicket = PortingFailureReason(kind: .keys, detail: "missing-common-ticket") XCTAssertEqual(missingTicket.action, .none) let game = PortedGame(name: "Play", url: URL(fileURLWithPath: "/tmp/Play.app"), platform: .macApp, diff --git a/Tests/NXLibraryCoreTests/AppRouterTests.swift b/Tests/NXLibraryCoreTests/AppRouterTests.swift index 9cc12948..e26a2ab6 100644 --- a/Tests/NXLibraryCoreTests/AppRouterTests.swift +++ b/Tests/NXLibraryCoreTests/AppRouterTests.swift @@ -2,6 +2,25 @@ import XCTest @testable import NXLibraryCore final class AppRouterTests: XCTestCase { + func testFullScreenBackdropCoverFollowsTheVisibleLayerPriority() { + XCTAssertEqual(ShellBackdropCover.resolve(setup: true, welcome: true, themePicker: true), .setup) + XCTAssertEqual(ShellBackdropCover.resolve(setup: false, welcome: true, themePicker: true), .welcome) + XCTAssertEqual(ShellBackdropCover.resolve(setup: false, welcome: false, themePicker: true), .themePicker) + XCTAssertEqual(ShellBackdropCover.resolve(setup: false, welcome: false, themePicker: false), .none) + for priority in [0.0, 0.5, 0.8, 1, 2, 2.4] { + XCTAssertTrue(ShellBackdropCover.setup.covers(priority)) + } + XCTAssertFalse(ShellBackdropCover.setup.covers(2.5)) + XCTAssertFalse(ShellBackdropCover.setup.covers(3)) + XCTAssertFalse(ShellBackdropCover.setup.covers(4)) + XCTAssertTrue(ShellBackdropCover.welcome.covers(2)) + XCTAssertFalse(ShellBackdropCover.welcome.covers(2.5)) + XCTAssertTrue(ShellBackdropCover.themePicker.covers(0.8)) + XCTAssertFalse(ShellBackdropCover.themePicker.covers(1)) + XCTAssertFalse(ShellBackdropCover.themePicker.covers(2)) + XCTAssertFalse(ShellBackdropCover.none.covers(0)) + } + func testInitialRoute() { let router = AppRouter() XCTAssertEqual(router.route, .library) @@ -78,7 +97,7 @@ final class AppRouterTests: XCTestCase { router.movePowerMenu(by: 1) XCTAssertEqual(router.menuSelection.power, .hide) router.moveMenu(by: -1) - XCTAssertEqual(router.menuSelection.selected, .setupCheck) + XCTAssertEqual(router.menuSelection.selected, .manageSources) } func testCloseMenuClosesPowerPills() { @@ -94,9 +113,9 @@ final class AppRouterTests: XCTestCase { final class MenuSelectionModelTests: XCTestCase { func testMenuOrder() { XCTAssertEqual(MenuAction.allCases, - [.addGame, .refreshLibrary, .settings, .theme, .console, .setupCheck, .power]) + [.addGame, .refreshLibrary, .settings, .theme, .console, .setupCheck, .manageSources, .power]) XCTAssertEqual(MenuAction.allCases.map(\.title), - ["Add Game", "Library refresh", "Settings", "Theme", "Console", "Setup check", "Power"]) + ["Add Game", "Library refresh", "Settings", "Theme", "Console", "Setup check", "Manage sources", "Power"]) XCTAssertEqual(PowerAction.allCases, [.quit, .hide, .relaunch]) XCTAssertEqual(PowerAction.allCases.map(\.title), ["Quit", "Hide", "Restart app"]) } diff --git a/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift b/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift index 166d3113..480873d4 100644 --- a/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift +++ b/Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift @@ -72,6 +72,51 @@ final class AppSettingsStoreTests: XCTestCase { XCTAssertTrue(reloaded.settings.gameDefaults.enableMetalFXUpscale) } + @MainActor + func testSelectingAGamePersistsOffTheMainThread() async throws { + let url = tempURL() + let written = expectation(description: "selection written off the main thread") + let fileManager = ObserveSettingsWrite { onMain in + XCTAssertFalse(onMain) + written.fulfill() + } + let store = AppSettingsStore(fileURL: url, fileManager: fileManager) + let id = UUID() + store.rememberLastSelectedGame(id) + XCTAssertEqual(store.lastSelectedGameID, id) + await fulfillment(of: [written], timeout: 3) + XCTAssertEqual(AppSettingsStore(fileURL: url).lastSelectedGameID, id) + } + + @MainActor + func testSelectingAGameDoesNotInvalidateSettingsObservers() { + let store = AppSettingsStore(fileURL: tempURL()) + var publications = 0 + let observation = store.objectWillChange.sink { publications += 1 } + store.rememberLastSelectedGame(UUID()) + store.flushPendingSelection() + XCTAssertEqual(publications, 0, "A row move must not invalidate views observing settings") + withExtendedLifetime(observation) {} + } + + @MainActor + func testQuittingAndExplicitSettingsWritesKeepTheLatestSelection() { + let url = tempURL() + let store = AppSettingsStore(fileURL: url) + let first = UUID(), second = UUID(), third = UUID() + store.rememberLastSelectedGame(first) + store.rememberLastSelectedGame(second) + store.flushPendingSelection() + XCTAssertEqual(AppSettingsStore(fileURL: url).settings.lastSelectedGameID, second) + + store.rememberLastSelectedGame(third) + store.settings.showClock = false + store.flushPendingSelection() + let saved = AppSettingsStore(fileURL: url).settings + XCTAssertEqual(saved.lastSelectedGameID, third) + XCTAssertFalse(saved.showClock) + } + func testCorruptFileFallsBackToDefaultsAndKeepsError() throws { let url = tempURL() try Data("{ not json".utf8).write(to: url) @@ -231,15 +276,43 @@ private final class RejectSettingsWrite: FileManager, @unchecked Sendable { } } +private final class ObserveSettingsWrite: FileManager, @unchecked Sendable { + let onWrite: (Bool) -> Void + + init(onWrite: @escaping (Bool) -> Void) { self.onWrite = onWrite } + + override func moveItem(at srcURL: URL, to dstURL: URL) throws { + try super.moveItem(at: srcURL, to: dstURL) + onWrite(Thread.isMainThread) + } +} + final class SettingsSectionTests: XCTestCase { func testAllSectionsArePresent() { XCTAssertEqual(SettingsSection.allCases.map(\.title), [ - "Search", "Changed", "Start-up", "Navigation", "Spotlight", "Sound & music", - "Look", "Games", "Controllers", "Library", "Storage", "Engine", "About" + "Search", "Changed", "Start-up", "Navigation", "Spotlight", "Sound & music", "Look", "Controllers", + "Online services", "Sources", "Games", "Storage", "Setup and engine", "Keys", "Library", "New games", + "Cloud saves", "Storage", "About", "Console" ]) XCTAssertTrue(SettingsSection.allCases.allSatisfy { !$0.icon.rawValue.isEmpty }) } + func testSidebarGroupsInScreenOrder() { + XCTAssertEqual(SettingsSidebarGroup.all.map(\.title), [nil, "General", "Library", "Porting", "System"]) + // The sidebar's Up/Down follows the groups as drawn, and every section is in exactly one group. + XCTAssertEqual(SettingsSidebarGroup.all.flatMap(\.sections), SettingsSection.allCases) + XCTAssertEqual(SettingsSection.sources.group.title, "Library") + } + + func testPortingSectionsAreNamedWithTheirGroupWhereSearchListsThem() { + XCTAssertEqual(SettingsSection.library.place, "Porting · Library") + XCTAssertEqual(SettingsSection.games.place, "Porting · New games") + XCTAssertEqual(SettingsSection.portingStorage.place, "Porting · Storage") + XCTAssertEqual(SettingsSection.sources.place, "Sources") + XCTAssertEqual(SettingsSection.look.place, "Look") + XCTAssertEqual(SettingsSection.storage.place, "Storage") + } + func testStartScreenDefaultsAndDecode() throws { let settings = AppSettings() XCTAssertEqual(settings.startOn, .spotlight) diff --git a/Tests/NXLibraryCoreTests/AppUpdateTests.swift b/Tests/NXLibraryCoreTests/AppUpdateTests.swift index c2a2fd27..f29bf0ea 100644 --- a/Tests/NXLibraryCoreTests/AppUpdateTests.swift +++ b/Tests/NXLibraryCoreTests/AppUpdateTests.swift @@ -116,6 +116,21 @@ final class AppUpdateTests: XCTestCase { } } + private let successorURL = "https://github.com/Bium23/Arcane/releases/download/v0.3.0/NXLibrary-0.3.0.zip" + + func testSuccessorRepositoryAssetIsAccepted() throws { + let json = try changingAsset { $0["browser_download_url"] = successorURL } + let release = try XCTUnwrap(AppUpdate.parseRelease(json, successor: "Bium23/Arcane")) + XCTAssertEqual(release.zipURL.absoluteString, successorURL) + XCTAssertNotNil(AppUpdate.parseRelease(Data(releaseJSON.utf8), successor: "Bium23/Arcane")) + } + + func testWithoutSuccessorOnlyTheConfiguredPathIsAccepted() throws { + let json = try changingAsset { $0["browser_download_url"] = successorURL } + XCTAssertNil(AppUpdate.parseRelease(json, successor: nil)) + XCTAssertNil(AppUpdate.successorRepository) + } + func testDownloadBudgetAndGitHubRedirectBoundary() { XCTAssertTrue(AppUpdate.downloadWithinLimit(received: 1024, expected: 1024)) XCTAssertFalse(AppUpdate.downloadWithinLimit(received: 1025, expected: 1024)) @@ -240,6 +255,16 @@ final class AppUpdateTests: XCTestCase { version: "0.2.0", runningOS: os), .noInfo) } + func testDevelopmentDataMarkerCannotShipAsAnUpdate() throws { + let app = try makeApp("Mixed.app") + let file = app.appendingPathComponent("Contents/Info.plist") + var info = try XCTUnwrap(PropertyListSerialization.propertyList(from: Data(contentsOf: file), format: nil) as? [String: Any]) + info["NXLibraryDevelopmentProfile"] = true + try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: file) + XCTAssertEqual(AppUpdate.bundleProblem(app, expectedID: "local.nxlibrary", version: "0.2.0", runningOS: os), .notRelease) + XCTAssertEqual(AppUpdate.installability(app), .developer) + } + func testBundleWithoutMarkerIsRefused() throws { let dev = try makeApp("Dev.app", release: false) XCTAssertEqual(AppUpdate.bundleProblem(dev, expectedID: "local.nxlibrary", version: "0.2.0", runningOS: os), @@ -284,6 +309,96 @@ final class AppUpdateTests: XCTestCase { XCTAssertTrue(exe.contains("old")) } + func testUpdatePreservesUserCopiesBesideTheCurrentApp() throws { + for name in ["Arcane", "NX Library"] { + let installed = dir.appendingPathComponent(UUID().uuidString) + let current = try makeApp(name + ".app", in: installed, marker: "current") + let keptNew = try makeApp(name + " (new).app", in: installed, marker: "user-new") + let keptOld = try makeApp(name + " (old).app", in: installed, marker: "user-old") + let staged = try makeApp(in: dir.appendingPathComponent(UUID().uuidString), marker: "candidate") + let placed = try AppUpdate.install(staged, over: current, trashOld: false) + XCTAssertEqual(placed, current) + XCTAssertTrue(try String(contentsOf: keptNew.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("user-new")) + XCTAssertTrue(try String(contentsOf: keptOld.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("user-old")) + XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate")) + XCTAssertTrue(FileManager.default.fileExists(atPath: staged.path), "the verified download remains available") + } + } + + func testMissingCandidatePreservesUserCopies() throws { + let current = try makeApp("Arcane.app", marker: "current") + let keptNew = try makeApp("Arcane (new).app", marker: "user-new") + let keptOld = try makeApp("Arcane (old).app", marker: "user-old") + XCTAssertThrowsError(try AppUpdate.install(dir.appendingPathComponent("missing.app"), over: current, trashOld: false)) + for kept in [keptNew, keptOld, current] { + XCTAssertTrue(FileManager.default.fileExists(atPath: kept.appendingPathComponent("Contents/Info.plist").path)) + } + } + + func testPartialCopyFailureKeepsCurrentAndCleansOwnedStage() throws { + let installed = dir.appendingPathComponent("Applications") + let current = try makeApp(in: installed, marker: "current") + let staged = try makeApp(in: dir.appendingPathComponent("download")) + XCTAssertThrowsError(try AppUpdate.install(staged, over: current, trashOld: false, + fileManager: UpdateCopyFailure(), io: BuildInstallIO())) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: installed.path), ["NXLibrary.app"]) + XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current")) + } + + func testPublicationFailureKeepsCurrentAndCandidate() throws { + let installed = dir.appendingPathComponent("Applications") + let current = try makeApp(in: installed, marker: "current") + let staged = try makeApp(in: dir.appendingPathComponent("download")) + var io = BuildInstallIO() + io.publish = { _, _, _ in throw CocoaError(.fileWriteUnknown) } + XCTAssertThrowsError(try AppUpdate.install(staged, over: current, trashOld: false, fileManager: .default, io: io)) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: installed.path), ["NXLibrary.app"]) + XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current")) + XCTAssertTrue(FileManager.default.fileExists(atPath: staged.path)) + } + + func testErrorAfterAtomicSwapFinishesTheInstalledUpdate() throws { + let current = try makeApp("Arcane.app", marker: "current") + let staged = try makeApp(in: dir.appendingPathComponent("download"), marker: "candidate") + var io = BuildInstallIO() + io.afterPublish = { throw CocoaError(.fileWriteUnknown) } + XCTAssertEqual(try AppUpdate.install(staged, over: current, trashOld: false, fileManager: .default, io: io), current) + XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate")) + } + + func testTrashFailureRetainsPreviousAppWithoutFailingSuccessfulInstall() throws { + let installed = dir.appendingPathComponent("Applications") + let current = try makeApp("Arcane.app", in: installed, marker: "current") + let staged = try makeApp(in: dir.appendingPathComponent("download"), marker: "candidate") + let fm = UpdateTrashFailure() + XCTAssertEqual(try AppUpdate.install(staged, over: current, trashOld: true, fileManager: fm, io: BuildInstallIO()), current) + let retained = try XCTUnwrap(fm.retained) + XCTAssertTrue(try String(contentsOf: retained.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current")) + XCTAssertEqual(retained.deletingLastPathComponent().deletingLastPathComponent().path, installed.path) + XCTAssertTrue(try String(contentsOf: current.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate")) + XCTAssertEqual(try fm.attributesOfItem(atPath: retained.path)[.systemNumber] as? NSNumber, + try fm.attributesOfItem(atPath: current.path)[.systemNumber] as? NSNumber) + let next = try makeApp(in: dir.appendingPathComponent("next-download"), marker: "next") + try AppUpdate.install(next, over: current, trashOld: true, fileManager: fm, io: BuildInstallIO()) + let second = try XCTUnwrap(fm.retained) + XCTAssertNotEqual(second.deletingLastPathComponent(), retained.deletingLastPathComponent()) + XCTAssertTrue(try String(contentsOf: retained.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current")) + XCTAssertTrue(try String(contentsOf: second.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("candidate")) + } + + func testAppChangedDuringCopyIsNotReplaced() throws { + let current = try makeApp("Arcane.app", marker: "current") + let staged = try makeApp(in: dir.appendingPathComponent("download"), marker: "candidate") + let moved = dir.appendingPathComponent("moved.app") + let fm = UpdateCopyHook { + try FileManager.default.moveItem(at: current, to: moved) + try FileManager.default.createDirectory(at: current, withIntermediateDirectories: false) + } + XCTAssertThrowsError(try AppUpdate.install(staged, over: current, trashOld: false, fileManager: fm, io: BuildInstallIO())) + XCTAssertTrue(try String(contentsOf: moved.appendingPathComponent("Contents/MacOS/NXLibrary")).contains("current")) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: current.path), []) + } + func testLaterIsPerVersion() { let now = Date(timeIntervalSince1970: 1_000_000) let hourAgo = now.addingTimeInterval(-3600) @@ -311,3 +426,28 @@ final class AppUpdateTests: XCTestCase { XCTAssertEqual(AppUpdate.repository(defaults: defaults), AppUpdate.defaultRepository) } } + +private final class UpdateCopyFailure: FileManager, @unchecked Sendable { + override func copyItem(at source: URL, to destination: URL) throws { + try createDirectory(at: destination, withIntermediateDirectories: false) + try Data("partial".utf8).write(to: destination.appendingPathComponent("partial")) + throw CocoaError(.fileWriteUnknown) + } +} + +private final class UpdateTrashFailure: FileManager, @unchecked Sendable { + var retained: URL? + override func trashItem(at url: URL, resultingItemURL: AutoreleasingUnsafeMutablePointer<NSURL?>?) throws { + retained = url + throw CocoaError(.fileWriteNoPermission) + } +} + +private final class UpdateCopyHook: FileManager, @unchecked Sendable { + let afterCopy: () throws -> Void + init(afterCopy: @escaping () throws -> Void) { self.afterCopy = afterCopy; super.init() } + override func copyItem(at source: URL, to destination: URL) throws { + try super.copyItem(at: source, to: destination) + try afterCopy() + } +} diff --git a/Tests/NXLibraryCoreTests/ArcaneNameTests.swift b/Tests/NXLibraryCoreTests/ArcaneNameTests.swift new file mode 100644 index 00000000..1037f12c --- /dev/null +++ b/Tests/NXLibraryCoreTests/ArcaneNameTests.swift @@ -0,0 +1,38 @@ +import XCTest +@testable import NXLibraryCore + +/// The app shows itself as Arcane everywhere a person or a web service can see a name. +final class ArcaneNameTests: XCTestCase { + private var repository: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + } + + func testCatalogShowsNoOldAppName() throws { + let url = repository.appendingPathComponent("Sources/NXLibraryCore/Resources/Localizable.xcstrings") + let catalog = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any] + let strings = try XCTUnwrap(catalog?["strings"] as? [String: Any]) + var found: [String] = [] + for (key, entry) in strings { + if key.contains("NX Library") { found.append(key) } + let localizations = (entry as? [String: Any])?["localizations"] as? [String: Any] ?? [:] + for (language, value) in localizations { + let text = ((value as? [String: Any])?["stringUnit"] as? [String: Any])?["value"] as? String ?? "" + if text.contains("NX Library") { found.append("\(language): \(key)") } + } + } + XCTAssertEqual(found.sorted(), []) + } + + func testUserAgentNamesArcane() { + XCTAssertEqual(AppIdentity.userAgent(version: "0.2"), "Arcane/0.2 (macOS; +https://github.com/Bium23/NxLibrary)") + } + + func testNoSourceSendsTheOldUserAgent() throws { + let sources = repository.appendingPathComponent("Sources") + let files = FileManager.default.enumerator(at: sources, includingPropertiesForKeys: nil)? + .compactMap { $0 as? URL }.filter { $0.pathExtension == "swift" } ?? [] + let offenders = try files.filter { try String(contentsOf: $0, encoding: .utf8).contains("\"NXLibrary/") } + .map(\.lastPathComponent) + XCTAssertEqual(offenders, []) + } +} diff --git a/Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift b/Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift new file mode 100644 index 00000000..28a2d69b --- /dev/null +++ b/Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift @@ -0,0 +1,63 @@ +import XCTest +@testable import NXLibraryCore + +final class ArcaneWelcomeTests: XCTestCase { + func testShowsOnceAfterUpdate() { + XCTAssertTrue(ArcaneWelcome.shouldShow(setupCompleted: true, shown: false, hasPendingRecovery: false)) + XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: true, shown: true, hasPendingRecovery: false)) + } + + func testUnfinishedSetupNeverShows() { + XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: false, shown: false, hasPendingRecovery: false)) + } + + func testNewInstallNeverShows() { + let finished = ArcaneWelcome.markShown(AppSettings()) + XCTAssertTrue(finished.welcomeArcaneShown) + XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: true, shown: finished.welcomeArcaneShown, + hasPendingRecovery: false)) + } + + func testWaitsForPendingRecovery() { + XCTAssertFalse(ArcaneWelcome.shouldShow(setupCompleted: true, shown: false, hasPendingRecovery: true)) + } + + func testOldSettingsFileDecodesAsNotShown() throws { + let old = Data(#"{"showClock": false}"#.utf8) + let settings = try JSONDecoder().decode(AppSettings.self, from: old) + XCTAssertFalse(settings.welcomeArcaneShown) + XCTAssertFalse(settings.showClock) + var shown = settings + shown.welcomeArcaneShown = true + let back = try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(shown)) + XCTAssertTrue(back.welcomeArcaneShown) + } + + func testOfferOnlyWhenSteamFoundAndOff() { + XCTAssertEqual(ArcaneWelcome.offer(steamEnabled: false, steamGameCount: 12), .steam(gameCount: 12)) + XCTAssertNil(ArcaneWelcome.offer(steamEnabled: true, steamGameCount: 12)) + XCTAssertNil(ArcaneWelcome.offer(steamEnabled: false, steamGameCount: 0)) + XCTAssertNil(ArcaneWelcome.offer(steamEnabled: false, steamGameCount: nil)) + } + + func testFocusOrder() { + let offer = ArcaneWelcome.Offer.steam(gameCount: 3) + XCTAssertEqual(ArcaneWelcome.Focus.order(offer: offer), [.add, .notNow, .openLibrary]) + XCTAssertEqual(ArcaneWelcome.Focus.order(offer: nil), [.openLibrary]) + XCTAssertEqual(ArcaneWelcome.Focus.initial(offer: offer), .add) + XCTAssertEqual(ArcaneWelcome.Focus.initial(offer: nil), .openLibrary) + XCTAssertEqual(ArcaneWelcome.Focus.add.moved(.right, offer: offer), .notNow) + XCTAssertEqual(ArcaneWelcome.Focus.notNow.moved(.left, offer: offer), .add) + XCTAssertEqual(ArcaneWelcome.Focus.add.moved(.down, offer: offer), .openLibrary) + XCTAssertEqual(ArcaneWelcome.Focus.notNow.moved(.down, offer: offer), .openLibrary) + XCTAssertEqual(ArcaneWelcome.Focus.openLibrary.moved(.up, offer: offer), .add) + XCTAssertEqual(ArcaneWelcome.Focus.openLibrary.moved(.up, offer: nil), .openLibrary) + XCTAssertEqual(ArcaneWelcome.Focus.add.moved(.up, offer: offer), .add) + } + + func testDismissingMarksShown() { + for exit in ArcaneWelcome.Exit.allCases { + XCTAssertTrue(ArcaneWelcome.settings(after: exit, from: AppSettings()).welcomeArcaneShown, "\(exit)") + } + } +} diff --git a/Tests/NXLibraryCoreTests/BoundedDownloadTests.swift b/Tests/NXLibraryCoreTests/BoundedDownloadTests.swift new file mode 100644 index 00000000..61075e33 --- /dev/null +++ b/Tests/NXLibraryCoreTests/BoundedDownloadTests.swift @@ -0,0 +1,82 @@ +import XCTest +@testable import NXLibraryCore + +/// Serves a fixed body in several chunks, or a redirect, without the network. +private final class ChunkedStub: URLProtocol { + nonisolated(unsafe) static var chunks: [Data] = [] + nonisolated(unsafe) static var declaredLength: Int? + nonisolated(unsafe) static var redirect: URL? + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + let url = request.url! + if let target = Self.redirect, url != target { + // A refused redirect leaves the 302 as the final response; followed, the target would load with 200. + let response = HTTPURLResponse(url: url, statusCode: 302, httpVersion: nil, headerFields: ["Location": target.absoluteString])! + client?.urlProtocol(self, wasRedirectedTo: URLRequest(url: target), redirectResponse: response) + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocolDidFinishLoading(self) + return + } + var headers: [String: String] = [:] + if let length = Self.declaredLength { headers["Content-Length"] = String(length) } + let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: headers)! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + for chunk in Self.chunks { client?.urlProtocol(self, didLoad: chunk) } + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} + +final class BoundedDownloadTests: XCTestCase { + private let url = URL(string: "https://example.invalid/page")! + private func session() -> URLSession { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [ChunkedStub.self] + return URLSession(configuration: config) + } + override func setUp() { + ChunkedStub.chunks = []; ChunkedStub.declaredLength = nil; ChunkedStub.redirect = nil + } + + func testCollectsEveryChunkUpToTheLimit() async throws { + ChunkedStub.chunks = [Data(repeating: 1, count: 4), Data(repeating: 2, count: 4), Data(repeating: 3, count: 2)] + let (data, response) = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10) + XCTAssertEqual(data, Data([1, 1, 1, 1, 2, 2, 2, 2, 3, 3])) + XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 200) + XCTAssertEqual(response.url, url) + } + + func testStopsWhenTheBodyGrowsPastTheLimit() async { + ChunkedStub.chunks = [Data(repeating: 1, count: 6), Data(repeating: 2, count: 6)] + do { + _ = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10) + XCTFail("An oversized body must not be returned") + } catch { XCTAssertEqual((error as? URLError)?.code, .dataLengthExceedsMaximum) } + } + + func testRefusesADeclaredLengthPastTheLimit() async { + ChunkedStub.chunks = [Data(repeating: 1, count: 4)] + ChunkedStub.declaredLength = 11 + do { + _ = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10) + XCTFail("A declared oversized body must not be read") + } catch { XCTAssertEqual((error as? URLError)?.code, .dataLengthExceedsMaximum) } + } + + func testNeverFollowsARedirect() async throws { + ChunkedStub.redirect = URL(string: "https://elsewhere.invalid/")! + let (_, response) = try await BoundedDownload.data(for: URLRequest(url: url), session: session(), limit: 10) + XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 302) + XCTAssertEqual(response.url, url) + } + + func testCancellationStopsTheRead() async { + ChunkedStub.chunks = [Data(repeating: 1, count: 4)] + let session = session() + let task = Task { try await BoundedDownload.data(for: URLRequest(url: self.url), session: session, limit: 10) } + task.cancel() + do { _ = try await task.value; XCTFail("A cancelled read must not return data") } + catch { XCTAssertTrue(error is CancellationError) } + } +} diff --git a/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift b/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift index 88c9273a..223cbd60 100644 --- a/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift +++ b/Tests/NXLibraryCoreTests/BoxArtServiceTests.swift @@ -82,17 +82,20 @@ final class BoxArtServiceTests: XCTestCase { func testTheGamesDBCoverWhenGameTDBHasNone() async throws { let client = RoutedClient() - let search = TheGamesDBArt.searchURL(for: "Donkey Kong Bananza")!.absoluteString + let search = "https://thegamesdb.net/search.php?name=Donkey%20Kong%20Bananza&platform_id%5B%5D=5021" client.routes[search] = Data(""" <a href="./game.php?id=132468"><div class="card"><img src="x"><div class="card-footer bg-secondary"> - <p>Donkey Kong Bananza</p><p class="text-muted">Nintendo Switch</p></div></div></a> + <p>Donkey Kong Bananza</p><p class="text-muted">Nintendo Switch 2</p></div></div></a> """.utf8) client.routes[TheGamesDBArt.gameURL(id: 132468).absoluteString] = Data(""" + <h1>Donkey Kong Bananza</h1><p>Platform: <a href="/platform.php?id=5021">Nintendo Switch 2</a></p> <a href="https://cdn.thegamesdb.net/images/original/boxart/front/132468-1.jpg"></a> """.utf8) client.routes["https://cdn.thegamesdb.net/images/original/boxart/front/132468-1.jpg"] = jpeg(width: 500, height: 500) let (boxArt, artwork, index) = try service(client) try index.save([zelda]) + let oldKey = ["tgdb", "040074A01BF12000", GameTDB.normalize("Donkey Kong Bananza")].joined(separator: "|") + try JSONEncoder().encode([oldKey: Date()]).write(to: index.directory.appendingPathComponent("boxart-misses.json")) let url = await boxArt.boxArt(titleID: "040074A01BF12000", names: ["Donkey Kong Bananza"]) XCTAssertNotNil(url) diff --git a/Tests/NXLibraryCoreTests/BuildServiceTests.swift b/Tests/NXLibraryCoreTests/BuildServiceTests.swift index ec76fb89..b0c54a4b 100644 --- a/Tests/NXLibraryCoreTests/BuildServiceTests.swift +++ b/Tests/NXLibraryCoreTests/BuildServiceTests.swift @@ -3,6 +3,31 @@ import Darwin @testable import NXLibraryCore final class BuildServiceTests: XCTestCase { + /// A build that cannot even start (here: its working folder is gone) closes its log and its output pipes. + func testBuildThatCannotStartLeavesNoFilesOpen() throws { + let fm = FileManager.default + let root = fm.temporaryDirectory.appendingPathComponent("NXNoStart-\(UUID())") + try fm.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: root) } + func openFiles() -> Int { (try? fm.contentsOfDirectory(atPath: "/dev/fd").count) ?? 0 } + let service = BuildService() + func failOnce() throws -> BuildResult? { + let done = expectation(description: "launch failure reported") + var result: BuildResult? + service.start(command: BuildCommand(executable: URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", "true"], + environment: [:], workingDirectory: root.appendingPathComponent("missing")), + logURL: root.appendingPathComponent("build.log"), tempApp: root.appendingPathComponent("t.app"), + finalApp: root.appendingPathComponent("f.app"), eventHandler: { _ in }, + completion: { result = $0; done.fulfill() }) + wait(for: [done], timeout: 10) + return result + } + XCTAssertEqual(try failOnce()?.success, false) + let before = openFiles() + for _ in 0..<20 { _ = try failOnce() } + XCTAssertLessThan(openFiles() - before, 5, "each failed start must close its log file and both pipes") + } + func testDestinationDisconnectedDuringBuildKeepsTheReadyAppWithoutRecreatingTheFolder() throws { let fm = FileManager.default let root = fm.temporaryDirectory.appendingPathComponent("NXDisconnected-\(UUID())") @@ -129,9 +154,10 @@ final class BuildServiceTests: XCTestCase { PendingInstaller.hold(pending, for: &game) XCTAssertThrowsError(try PendingInstaller.install(&game, fileManager: denied)) XCTAssertEqual(game.pendingInstall, pending) - let store = LibraryStore(directory: root.appendingPathComponent("catalog")) - try store.save(LibraryFile(games: [game])) - game = try XCTUnwrap(store.load().games.first) + let store = CatalogRepository(store: CatalogStore(directory: root.appendingPathComponent("catalog"))) + try store.configureSource(.nxnative, enabled: true, root: nil) + try store.updateNXNativeGames { $0 = [game] } + game = try XCTUnwrap(store.load().nxnativeGames.first) XCTAssertEqual(game.pendingInstall, pending) XCTAssertEqual(try PendingInstaller.install(&game), .installed) XCTAssertNil(game.pendingInstall) diff --git a/Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift b/Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift new file mode 100644 index 00000000..668786ce --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift @@ -0,0 +1,51 @@ +import XCTest +@testable import NXLibraryCore + +final class CatalogBuildRecoveryTests: XCTestCase { + private func generation(_ name: String, basedOn original: PortedGame) -> PortedGame { + var result = original + var record = original.lastBuild! + record.outputPath = "/tmp/" + name + ".app" + result.pendingInstall = PendingInstall(tempApp: URL(fileURLWithPath: "/tmp/held/" + name + ".app"), finalApp: original.url, + record: record, toolchain: original.toolchain) + result.lastBuild = record + return result + } + + func testRetainedNewerBuildSuspendsAutomaticInstallAndExplicitRetryUsesIt() throws { + let a = generation("A", basedOn: CatalogTestSupport.completeLegacyGame()) + let b = generation("B", basedOn: a) + var recoveries = CatalogBuildRecoveries() + recoveries.retain(b) + XCTAssertNil(try recoveries.pendingCandidate(persisted: a, explicitRetry: false)) + var latest = a; latest.isFavorite = false; latest.settings.language = "de" + let candidate = try XCTUnwrap(recoveries.pendingCandidate(persisted: latest, explicitRetry: true)) + XCTAssertEqual(candidate.pendingInstall?.tempApp.path, "/tmp/held/B.app") + XCTAssertEqual(candidate.lastBuild, b.lastBuild) + XCTAssertFalse(candidate.isFavorite) + XCTAssertEqual(candidate.settings.language, "de") + } + + func testCommittingOldGenerationCannotDiscardNewerRecovery() throws { + let a = generation("A", basedOn: CatalogTestSupport.completeLegacyGame()) + let b = generation("B", basedOn: a) + var recoveries = CatalogBuildRecoveries() + recoveries.retain(a); recoveries.retain(b) + recoveries.acknowledge(id: a.id, matching: a) + XCTAssertEqual(recoveries[a.id], b) + recoveries.acknowledge(id: a.id, matching: nil) + XCTAssertEqual(recoveries[a.id], b) + recoveries.acknowledge(id: a.id, matching: b) + XCTAssertNil(recoveries[a.id]) + } + + func testRetainedInstalledResultDoesNotResurrectOlderPendingInstallation() throws { + let a = generation("A", basedOn: CatalogTestSupport.completeLegacyGame()) + var b = generation("B", basedOn: a); b.pendingInstall = nil; b.status = .built + var recoveries = CatalogBuildRecoveries(); recoveries.retain(b) + let candidate = try XCTUnwrap(recoveries.pendingCandidate(persisted: a, explicitRetry: true)) + XCTAssertNil(candidate.pendingInstall) + XCTAssertEqual(candidate.lastBuild, b.lastBuild) + XCTAssertNil(try recoveries.pendingCandidate(persisted: a, explicitRetry: false)) + } +} diff --git a/Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift b/Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift new file mode 100644 index 00000000..cdabe951 --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift @@ -0,0 +1,49 @@ +import XCTest +@testable import NXLibraryCore + +final class CatalogLibraryQueryTests: XCTestCase { + private func games() -> [CatalogGame] { + var nx = CatalogTestSupport.completeLegacyGame(); nx.isHidden = false; nx.isFavorite = false + var steam = SteamCatalogGame(appID: 10, name: "Árena"); steam.hasBeenRecognized = true; steam.isFavorite = true + return [.init(nxnative: nx), .init(steam: steam)] + } + func testMixedProjectionRespectsEnabledHiddenAndRecognizedStates() throws { + var records = games() + let enabled: [CatalogSourceConfiguration] = [.init(integration: .nxnative, isEnabled: true), .init(integration: .steam, isEnabled: true, rootURL: URL(fileURLWithPath: "/tmp/Steam"))] + XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: enabled).count, 2) + XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: [.init(integration: .nxnative, isEnabled: true)]).count, 1) + records[1].setHidden(true) + XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: enabled).count, 1) + records.append(.init(steam: SteamCatalogGame(appID: 20, name: "Unclassified"))) + XCTAssertEqual(CatalogLibraryProjection.visible(games: records, sources: enabled).count, 1) + } + func testSearchAndFavoriteFilterUseSharedCatalogSemantics() { + let records = games() + XCTAssertEqual(LibraryQuery(searchText: "arena").applyCatalog(to: records, history: NoPlayHistory()).map(\.integration), [.steam]) + XCTAssertEqual(LibraryQuery(filter: .favorites).applyCatalog(to: records, history: NoPlayHistory()).map(\.integration), [.steam]) + XCTAssertEqual(LibraryQuery(searchText: "10").applyCatalog(to: records, history: NoPlayHistory()).map(\.integration), [.steam, .nxnative]) // both external IDs contain 10 + } + func testCatalogSelectionAndSpotlightOrderKeepSteamIdentity() { + let records = games() + var selection = LibrarySelectionState(selectedGameID: records[1].id) + _ = selection.reconcileCatalog(with: records, history: NoPlayHistory()) + XCTAssertEqual(selection.selectedGameID, records[1].id) + let row = SpotlightRow.build(gameIDs: records.map(\.id), enabledCards: [], order: [SpotlightItem.game(records[1].id).key]) + XCTAssertEqual(Set(row), Set(records.map { SpotlightItem.game($0.id) })) + _ = selection.reconcileCatalog(with: [records[0]], history: NoPlayHistory()) + XCTAssertEqual(selection.selectedGameID, records[0].id) + } + func testInstalledAndHistoryFiltersDoNotInferSteamPlayFromDiscovery() { + let records = games() + struct History: PlayHistory { + let played: UUID + func lastPlayed(for id: UUID) -> Date? { id == played ? Date(timeIntervalSince1970: 100) : nil } + } + let history = History(played: records[1].id) + XCTAssertEqual(LibraryQuery(filter: .installed).applyCatalog(to: records, history: history).map(\.integration), [.nxnative]) + XCTAssertEqual(LibraryQuery(filter: .recentlyPlayed).applyCatalog(to: records, history: history).map(\.integration), [.steam]) + XCTAssertEqual(LibraryQuery(filter: .notPlayed).applyCatalog(to: records, history: history).map(\.integration), [.nxnative]) + XCTAssertTrue(LibraryQuery(filter: .recentlyPlayed).applyCatalog(to: records, history: NoPlayHistory()).isEmpty) + } + +} diff --git a/Tests/NXLibraryCoreTests/CatalogModelTests.swift b/Tests/NXLibraryCoreTests/CatalogModelTests.swift new file mode 100644 index 00000000..6acec0b9 --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogModelTests.swift @@ -0,0 +1,122 @@ +import XCTest +@testable import NXLibraryCore + +final class CatalogModelTests: XCTestCase { + func testCompleteLegacyRecordRoundTripsWithoutLosingAnyField() throws { + let original = CatalogTestSupport.completeLegacyGame() + let game = CatalogGame(nxnative: original) + XCTAssertEqual(game.id, original.id) + XCTAssertEqual(game.nxnativeGame, original) + XCTAssertEqual(game.personalizationKey, "0100000000000001") + let data = try JSONEncoder().encode(game) + let loaded = try JSONDecoder().decode(CatalogGame.self, from: data) + XCTAssertEqual(loaded, game) + XCTAssertEqual(loaded.nxnativeGame, original) + XCTAssertNil(loaded.steamGame) + } + + func testLegacyKeyFallbackAndProviderNamespacesRemainDistinct() throws { + var legacy = CatalogTestSupport.completeLegacyGame() + legacy.titleId = nil + legacy.bundleId = "fixture.bundle" + let game = CatalogGame(nxnative: legacy) + XCTAssertEqual(game.personalizationKey, "fixture.bundle") + let steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Same name")) + XCTAssertNotEqual(game.personalizationReference.namespace, steam.personalizationReference.namespace) + XCTAssertNil(steam.nxnativeGame) + } + + func testCommonUserStateHasOneOwnerAndSurvivesSerialization() throws { + var game = CatalogGame(nxnative: CatalogTestSupport.completeLegacyGame()) + game.setFavorite(false) + game.setHidden(false) + XCTAssertFalse(try XCTUnwrap(game.nxnativeGame).isFavorite) + XCTAssertFalse(try XCTUnwrap(game.nxnativeGame).isHidden) + var steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "G")) + steam.setFavorite(true) + steam.setHidden(true) + let result = try JSONDecoder().decode(CatalogGame.self, from: JSONEncoder().encode(steam)) + XCTAssertTrue(result.isFavorite) + XCTAssertTrue(result.isHidden) + XCTAssertEqual(result.id, steam.id) + } + + func testUpdatesRejectIntegrationOrIdentityChangesAndKeepPersonalLookupReference() throws { + let original = CatalogTestSupport.completeLegacyGame() + var game = CatalogGame(nxnative: original) + var update = original + update.titleId = "0100000000000002" + try game.updateNXNative(update) + XCTAssertEqual(game.personalizationKey, "0100000000000001") + XCTAssertEqual(game.nxnativeGame?.titleId, "0100000000000002") + update.id = UUID() + XCTAssertThrowsError(try game.updateNXNative(update)) + var steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "G")) + XCTAssertThrowsError(try steam.updateNXNative(original)) + XCTAssertNil(steam.nxnativeGame) + } + + func testSteamDoesNotSupportEngineOrDestructiveOperations() throws { + let game = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Steam game")) + let shown = CatalogGamePresentation(game: game, sourceEnabled: true) + var record = game + XCTAssertThrowsError(try record.updateNXNative(CatalogTestSupport.completeLegacyGame())) { error in + XCTAssertEqual(error as? CatalogModelError, .wrongIntegration) + } + XCTAssertNil(shown.launchTarget) + XCTAssertFalse(shown.isListedNormally) + } + + func testLegacyPresentationPreservesPlaySemanticsWithoutConsultingTheFilesystem() throws { + var original = CatalogTestSupport.completeLegacyGame() + original.isHidden = false + let shown = CatalogGamePresentation(game: CatalogGame(nxnative: original), sourceEnabled: true) + XCTAssertEqual(shown.launchTarget, .nxnative(appURL: original.url)) + XCTAssertTrue(shown.isListedNormally) + XCTAssertEqual(shown.installations.first?.contentURL, original.url) + original.status = .appMissing + XCTAssertNil(CatalogGamePresentation(game: CatalogGame(nxnative: original), sourceEnabled: true).launchTarget) + original.status = .notBuilt + original.url = URL(fileURLWithPath: "/tmp/catalog-fixture/workspace") + XCTAssertTrue(CatalogGamePresentation(game: CatalogGame(nxnative: original), sourceEnabled: true).installations.isEmpty) + } + + func testUnknownIntegrationTagCannotBeDecodedAsAnEmptyOrLegacyGame() throws { + let game = CatalogGame(nxnative: CatalogTestSupport.completeLegacyGame()) + var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(game)) as? [String: Any]) + json["integration"] = "unknown-future-source" + let data = try JSONSerialization.data(withJSONObject: json) + XCTAssertThrowsError(try JSONDecoder().decode(CatalogGame.self, from: data)) + } + + func testDownloadingSteamGameIsListedWithoutLaunchOrReview() throws { + var steam = SteamCatalogGame(appID: 10, name: "Downloading") + steam.installations = [.init(libraryURL: URL(fileURLWithPath: "/tmp/steam"), + contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G"), + availability: .unavailable, isDownloading: true)] + let shown = CatalogGamePresentation(game: CatalogGame(steam: steam), sourceEnabled: true) + XCTAssertTrue(shown.isListedNormally) + XCTAssertTrue(shown.isDownloading) + XCTAssertFalse(shown.requiresReview) + XCTAssertNil(shown.launchTarget) + let disabled = CatalogGamePresentation(game: CatalogGame(steam: steam), sourceEnabled: false) + XCTAssertFalse(disabled.isListedNormally) + XCTAssertFalse(disabled.isDownloading) + steam.isHidden = true + let hidden = CatalogGamePresentation(game: CatalogGame(steam: steam), sourceEnabled: true) + XCTAssertFalse(hidden.isListedNormally) + XCTAssertFalse(hidden.isDownloading) + } + + func testInstallationWithoutDownloadingKeyDecodesAsNotDownloading() throws { + let installation = SteamCatalogInstallation(libraryURL: URL(fileURLWithPath: "/tmp/steam"), + contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G"), + availability: .available, isDownloading: true) + var object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(installation)) as? [String: Any]) + XCTAssertEqual(object["isDownloading"] as? Bool, true) + object["isDownloading"] = nil + let old = try JSONDecoder().decode(SteamCatalogInstallation.self, from: JSONSerialization.data(withJSONObject: object)) + XCTAssertFalse(old.isDownloading) + XCTAssertEqual(old.availability, .available) + } +} diff --git a/Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift b/Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift new file mode 100644 index 00000000..adb07e41 --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift @@ -0,0 +1,30 @@ +import XCTest +@testable import NXLibraryCore + +final class CatalogPersonalizationTests: XCTestCase { + func testPersonalKeySurvivesRenameOfATitleWithoutTitleID() throws { + var payload = CatalogTestSupport.completeLegacyGame() + payload.titleId = nil; payload.bundleId = nil; payload.name = "Old name" + var entry = CatalogGame(nxnative: payload) + payload.name = "New name" + try entry.updateNXNative(payload) + let context = CatalogPersonalizations(document: CatalogDocument(games: [entry])) + XCTAssertEqual(context.nxnativeKey(for: payload), "Old name") + XCTAssertEqual(CatalogPersonalizations.empty.nxnativeKey(for: payload), "New name", "Unpersisted previews retain their existing fallback") + } + + func testSameTextKeyInDifferentIntegrationsCannotOverwritePersonalMetadata() throws { + let root = try SteamTestFixture.temporary(in: self).root + var payload = CatalogTestSupport.completeLegacyGame() + payload.titleId = nil; payload.bundleId = "steam-10" + let nx = CatalogGame(nxnative: payload).personalizationReference + let steam = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Steam")).personalizationReference + let nxStore = MetadataPicks(directory: nx.supportRoot(in: root)) + let steamStore = MetadataPicks(directory: steam.supportRoot(in: root)) + nxStore.set("Switch text", titleID: nx.key, field: .description) + steamStore.set("Steam text", titleID: steam.key, field: .description) + XCTAssertEqual(MetadataPicks(directory: root).value(titleID: "steam-10", field: .description), "Switch text") + XCTAssertEqual(MetadataPicks(directory: steam.supportRoot(in: root)).value(titleID: "steam-10", field: .description), "Steam text") + XCTAssertNotEqual(nx.supportRoot(in: root), steam.supportRoot(in: root)) + } +} diff --git a/Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift b/Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift new file mode 100644 index 00000000..55cddadc --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift @@ -0,0 +1,233 @@ +import XCTest +@testable import NXLibraryCore + +final class CatalogRecoveryTests: XCTestCase { + private func prepared() throws -> (URL, CatalogStore, CatalogDocument, Data) { + let root = try SteamTestFixture.temporary(in: self).root + let legacy = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + let store = CatalogStore(directory: root) + return (root, store, try store.loadOrMigrate(), legacy) + } + private func file(_ root: URL, _ name: String) -> URL { root.appendingPathComponent(name) } + + func testExplicitRestorePreservesDamagedMainBackupAndOriginalLegacy() throws { + let (root, store, original, legacy) = try prepared() + let backup = try Data(contentsOf: file(root, "catalog.json.bak")) + let damaged = Data("incomplete document".utf8) + try damaged.write(to: file(root, "catalog.json")) + let candidate = try XCTUnwrap(store.recoveryCandidate()) + XCTAssertEqual(candidate.gameCount, 1) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), damaged, "Offering recovery alone must not repair anything") + let restored = try store.restoreBackup(candidate) + XCTAssertEqual(restored.games, original.games) + XCTAssertNotEqual(restored.revision, original.revision) + XCTAssertEqual(try store.loadOrMigrate(), restored) + let archives = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) + .filter { $0.lastPathComponent.hasPrefix("catalog.json.recovered-") } + XCTAssertEqual(archives.count, 1) + XCTAssertEqual(try Data(contentsOf: archives[0]), damaged) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json.bak")), backup) + XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), legacy) + } + + func testMissingMainCanBeRestoredExplicitlyAndHealthyMainHasNoOffer() throws { + let (root, store, original, _) = try prepared() + XCTAssertNil(try store.recoveryCandidate()) + try FileManager.default.removeItem(at: file(root, "catalog.json")) + let candidate = try XCTUnwrap(store.recoveryCandidate()) + XCTAssertFalse(FileManager.default.fileExists(atPath: file(root, "catalog.json").path)) + XCTAssertEqual(try store.restoreBackup(candidate).games, original.games) + XCTAssertNil(try store.recoveryCandidate()) + } + + func testStaleRecoveryOfferCannotReplaceChangedMainOrBackup() throws { + for changed in ["catalog.json", "catalog.json.bak"] { + let (root, store, _, _) = try prepared() + try Data("damaged".utf8).write(to: file(root, "catalog.json")) + let candidate = try XCTUnwrap(store.recoveryCandidate()) + let later = Data("later edit".utf8) + try later.write(to: file(root, changed)) + XCTAssertThrowsError(try store.restoreBackup(candidate)) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) } + XCTAssertEqual(try Data(contentsOf: file(root, changed)), later) + } + } + + func testChangedLegacyAndUnsafeBackupCannotBeRestored() throws { + let (root, store, _, legacy) = try prepared() + try Data("damaged".utf8).write(to: file(root, "catalog.json")) + let candidate = try XCTUnwrap(store.recoveryCandidate()) + try (legacy + Data(" ".utf8)).write(to: file(root, "library.json")) + XCTAssertThrowsError(try store.restoreBackup(candidate)) + XCTAssertThrowsError(try store.recoveryCandidate()) + try FileManager.default.removeItem(at: file(root, "catalog.json.bak")) + try FileManager.default.createSymbolicLink(at: file(root, "catalog.json.bak"), withDestinationURL: file(root, "library.json")) + XCTAssertThrowsError(try store.recoveryCandidate()) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), Data("damaged".utf8)) + } + + func testRecoveryPublicationFailureLeavesAllInputsAvailable() throws { + let (root, store, _, _) = try prepared() + let damaged = Data("damaged".utf8) + try damaged.write(to: file(root, "catalog.json")) + let backup = try Data(contentsOf: file(root, "catalog.json.bak")) + let candidate = try XCTUnwrap(store.recoveryCandidate()) + let failing = CatalogStore(directory: root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) }) + XCTAssertThrowsError(try failing.restoreBackup(candidate)) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), damaged) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json.bak")), backup) + } + + func testFreshDevCopiesTheMixedCatalogAndReadyDevIsNeverReimported() throws { + let home = try SteamTestFixture.temporary(in: self).root + let profile = AppDataProfile(home: home, isDevelopment: true) + _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: profile.stableSupportRoot) + let store = CatalogStore(directory: profile.stableSupportRoot) + var mixed = try store.loadOrMigrate() + mixed.games.append(.init(steam: SteamCatalogGame(appID: 10, name: "Steam game"))) + mixed = try store.save(mixed, expectedRevision: mixed.revision) + let importer = DevelopmentProfileImporter() + XCTAssertTrue(try importer.prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in })) + XCTAssertEqual(try CatalogStore(directory: profile.supportRoot).loadOrMigrate(), mixed) + let sourceBytes = try Data(contentsOf: profile.stableSupportRoot.appendingPathComponent("catalog.json")) + try Data("later source damage".utf8).write(to: profile.stableSupportRoot.appendingPathComponent("catalog.json")) + XCTAssertFalse(try importer.prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() })) + XCTAssertEqual(try Data(contentsOf: profile.supportRoot.appendingPathComponent("catalog.json")), sourceBytes) + } + + func testFreshDevRejectsUnsupportedOrMalformedCatalogBeforeActivation() throws { + for bytes in [Data("{\"schemaVersion\":99}".utf8), Data("{\"valid_json_wrong_document\":true}".utf8)] { + let profile = AppDataProfile(home: try SteamTestFixture.temporary(in: self).root, isDevelopment: true) + try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true) + try bytes.write(to: profile.stableSupportRoot.appendingPathComponent("catalog.json")) + XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() })) + XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path)) + } + } + + func testKeepCurrentLibraryArchivesBothVersionsWithoutMergingLegacyChanges() throws { + let (root, store, original, _) = try prepared() + var mixed = original + mixed.games.append(.init(steam: SteamCatalogGame(appID: 10, name: "Arcane addition"))) + mixed = try store.save(mixed, expectedRevision: mixed.revision) + let main = try Data(contentsOf: file(root, "catalog.json")) + let backup = try Data(contentsOf: file(root, "catalog.json.bak")) + let changed = try CatalogTestSupport.writeLegacy([], to: root) + let legacyBackup = Data("legacy backup bytes".utf8) + try legacyBackup.write(to: file(root, "library.json.bak")) + XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) } + let candidate = try XCTUnwrap(store.legacyConflictCandidate()) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), main, "The offer does not modify either library") + let kept = try store.keepCurrentLibrary(candidate) + XCTAssertEqual(kept.games, mixed.games) + XCTAssertEqual(kept.sources, mixed.sources) + XCTAssertNotEqual(kept.revision, mixed.revision) + XCTAssertEqual(try store.loadOrMigrate(), kept) + let archive = try XCTUnwrap(conflictArchives(root).first) + for (name, bytes) in [("catalog.json", main), ("catalog.json.bak", backup), ("library.json", changed), ("library.json.bak", legacyBackup)] { + XCTAssertEqual(try Data(contentsOf: archive.appendingPathComponent(name)), bytes) + } + XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), changed) + XCTAssertEqual(try Data(contentsOf: file(root, "library.json.bak")), legacyBackup) + XCTAssertNil(try store.legacyConflictCandidate()) + XCTAssertNoThrow(try store.save(kept, expectedRevision: kept.revision)) + XCTAssertThrowsError(try store.save(mixed, expectedRevision: mixed.revision)) + } + + func testStaleConflictCannotAcknowledgeLaterWritesToAnyInput() throws { + for name in ["catalog.json", "catalog.json.bak", "library.json", "library.json.bak"] { + let (root, store, _, _) = try prepared() + _ = try CatalogTestSupport.writeLegacy([], to: root) + let candidate = try XCTUnwrap(store.legacyConflictCandidate()) + let later = Data("later write".utf8) + try later.write(to: file(root, name)) + let before = try Data(contentsOf: file(root, "catalog.json")) + XCTAssertThrowsError(try store.keepCurrentLibrary(candidate)) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) } + XCTAssertEqual(try Data(contentsOf: file(root, name)), later) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), before) + XCTAssertEqual(try conflictArchives(root).count, 0) + } + } + + func testAcceptedLegacyBaselineAlsoAppliesToTheRestorePoint() throws { + let (root, store, original, _) = try prepared() + _ = try CatalogTestSupport.writeLegacy([], to: root) + let candidate = try XCTUnwrap(store.legacyConflictCandidate()) + let kept = try store.keepCurrentLibrary(candidate) + try Data("damaged main".utf8).write(to: file(root, "catalog.json")) + let recovery = try XCTUnwrap(store.recoveryCandidate()) + let restored = try store.restoreBackup(recovery) + XCTAssertEqual(restored.games, original.games) + XCTAssertEqual(restored.legacyOrigin, kept.legacyOrigin) + XCTAssertEqual(try store.loadOrMigrate(), restored) + } + + func testArchiveAndPublicationFailuresKeepCurrentAndLegacyBytes() throws { + for failure in ["archive", "catalog.json", "archive sync"] { + let (root, store, _, _) = try prepared() + let changed = try CatalogTestSupport.writeLegacy([], to: root) + let main = try Data(contentsOf: file(root, "catalog.json")) + let candidate = try XCTUnwrap(store.legacyConflictCandidate()) + let failing = CatalogStore(directory: root, publication: .init(syncDirectory: { _ in + if failure == "archive sync" { throw POSIXError(.ENOSPC) } + }) { stage, target, replace, validate in + if failure == "archive" || target == root.appendingPathComponent(failure) { throw POSIXError(.ENOSPC) } + try CatalogPublication.atomic.publish(stage, target, replace, validate) + }) + XCTAssertThrowsError(try failing.keepCurrentLibrary(candidate)) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), main) + XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), changed) + // A retry rechecks the actual backup too, rather than reusing a stale offer. + XCTAssertNoThrow(try store.keepCurrentLibrary(XCTUnwrap(store.legacyConflictCandidate()))) + } + } + + func testLegacyEditAtPublicationCannotBeAcknowledgedByAnOlderOffer() throws { + let (root, store, _, _) = try prepared() + let changed = try CatalogTestSupport.writeLegacy([], to: root) + let candidate = try XCTUnwrap(store.legacyConflictCandidate()) + let main = try Data(contentsOf: file(root, "catalog.json")) + let later = Data("an older app wrote again".utf8) + let racing = CatalogStore(directory: root, publication: .init { stage, target, replace, validate in + if target == root.appendingPathComponent("catalog.json") { + try later.write(to: root.appendingPathComponent("library.json")) + } + try CatalogPublication.atomic.publish(stage, target, replace, validate) + }) + XCTAssertThrowsError(try racing.keepCurrentLibrary(candidate)) + XCTAssertEqual(try Data(contentsOf: file(root, "catalog.json")), main) + XCTAssertEqual(try Data(contentsOf: file(root, "library.json")), later) + let archive = try XCTUnwrap(conflictArchives(root).first) + XCTAssertEqual(try Data(contentsOf: archive.appendingPathComponent("library.json")), changed) + } + + func testUnsafeLegacyInputNeverOffersAnAcknowledgement() throws { + for name in ["library.json", "library.json.bak"] { + let (root, store, _, _) = try prepared() + _ = try CatalogTestSupport.writeLegacy([], to: root) + try? FileManager.default.removeItem(at: file(root, name)) + try FileManager.default.createSymbolicLink(at: file(root, name), withDestinationURL: file(root, "catalog.json")) + XCTAssertThrowsError(try store.legacyConflictCandidate()) + } + } + + func testMissingAndBackupOnlyLegacyBaselinesCanBeAcceptedExplicitly() throws { + for backupOnly in [false, true] { + let (root, store, original, _) = try prepared() + try FileManager.default.removeItem(at: file(root, "library.json")) + if backupOnly { try Data("legacy backup".utf8).write(to: file(root, "library.json.bak")) } + let candidate = try XCTUnwrap(store.legacyConflictCandidate()) + let kept = try store.keepCurrentLibrary(candidate) + XCTAssertEqual(kept.legacyOrigin.kind, backupOnly ? .backup : .absent) + XCTAssertEqual(kept.games, original.games) + XCTAssertEqual(try store.loadOrMigrate(), kept) + _ = try CatalogTestSupport.writeLegacy([], to: root) + XCTAssertThrowsError(try store.loadOrMigrate()) + XCTAssertNotNil(try store.legacyConflictCandidate()) + } + } + + private func conflictArchives(_ root: URL) throws -> [URL] { + try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) + .filter { $0.lastPathComponent.hasPrefix("catalog-conflict-") } + } +} diff --git a/Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift b/Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift new file mode 100644 index 00000000..972bc48e --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift @@ -0,0 +1,159 @@ +import XCTest +@testable import NXLibraryCore + +final class CatalogRepositoryTests: XCTestCase { + private func mixed() throws -> (SteamTestFixture, CatalogStore, CatalogDocument) { + let f = try SteamTestFixture.temporary(in: self) + _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: f.root) + let store = CatalogStore(directory: f.root) + var document = try store.loadOrMigrate() + var steam = SteamCatalogGame(appID: 10, name: "Fixture Switch game") + steam.isFavorite = true; steam.isHidden = true + document.games.append(.init(steam: steam)) + return (f, store, try store.save(document, expectedRevision: document.revision)) + } + + func testNXNativeUpdateRetainsWholePayloadPersonalReferenceAndSteamRecord() throws { + let (_, store, original) = try mixed() + let repository = CatalogRepository(store: store) + let id = original.games[0].id + let updated = try repository.updateNXNative(id: id) { $0.titleId = "0100000000000002"; $0.isFavorite = false } + var expected = try XCTUnwrap(original.games[0].nxnativeGame) + expected.titleId = "0100000000000002"; expected.isFavorite = false + XCTAssertEqual(updated.games[0].nxnativeGame, expected) + XCTAssertEqual(updated.games[0].personalizationReference, original.games[0].personalizationReference) + XCTAssertEqual(updated.games[1], original.games[1]) + XCTAssertEqual(try repository.load(), updated) + } + + func testScanUsesLatestFlagsAndDoesNotReplaceSteamOrLegacyBytes() throws { + let (fixture, store, original) = try mixed() + let bytes = try Data(contentsOf: fixture.root.appendingPathComponent("library.json")) + let repository = CatalogRepository(store: store) + var scanned = try XCTUnwrap(original.games[0].nxnativeGame) + scanned.name = "Renamed"; scanned.isFavorite = true; scanned.isHidden = true + _ = try repository.updateNXNative(id: scanned.id) { $0.isFavorite = false; $0.isHidden = false; $0.appIconOnMac = true } + let result = try repository.mergeNXNative(scanned: [scanned], observedFrom: original.nxnativeGames) + XCTAssertEqual(result.games[0].name, "Renamed") + XCTAssertFalse(result.games[0].isFavorite); XCTAssertFalse(result.games[0].isHidden) + XCTAssertEqual(result.nxnativeGames[0].appIconOnMac, true) + XCTAssertEqual(result.games[1], original.games[1]) + XCTAssertEqual(try Data(contentsOf: fixture.root.appendingPathComponent("library.json")), bytes) + } + + func testWrongIntegrationAndMissingIDRejectBeforeOperationEffects() throws { + let (_, store, original) = try mixed() + let repository = CatalogRepository(store: store) + var calls = 0 + XCTAssertThrowsError(try repository.updateNXNative(id: original.games[1].id) { _ in calls += 1 }) + XCTAssertThrowsError(try repository.updateNXNative(id: UUID()) { _ in calls += 1 }) + XCTAssertEqual(calls, 0) + XCTAssertEqual(try repository.load(), original) + } + + func testMutationDoesNotReplayEffectsWhenPublicationFails() throws { + let (fixture, store, original) = try mixed() + let failing = CatalogStore(directory: fixture.root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) }) + let repository = CatalogRepository(store: failing) + var calls = 0 + XCTAssertThrowsError(try repository.updateNXNative(id: original.games[0].id) { game in calls += 1; game.isFavorite = false }) + XCTAssertEqual(calls, 1) + XCTAssertEqual(try store.loadOrMigrate(), original) + } + + func testConcurrentChangeIsNotOverwrittenAndOperationIsNotReplayed() throws { + let (fixture, store, original) = try mixed() + let repository = CatalogRepository(store: store) + var calls = 0 + XCTAssertThrowsError(try repository.updateNXNative(id: original.games[0].id) { game in + calls += 1 + var other = try CatalogStore(directory: fixture.root).loadOrMigrate() + other.games[1].setHidden(false) + _ = try CatalogStore(directory: fixture.root).save(other, expectedRevision: other.revision) + game.isFavorite = false + }) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) } + XCTAssertEqual(calls, 1) + let actual = try repository.load() + XCTAssertFalse(actual.games[1].isHidden) + XCTAssertTrue(actual.games[0].isFavorite) + } + + func testSourceLessRecordsUseUUIDAndCannotMergeOnMissingTitleID() throws { + let (_, store, _) = try mixed() + let repository = CatalogRepository(store: store) + var a = CatalogTestSupport.completeLegacyGame(id: UUID()), b = CatalogTestSupport.completeLegacyGame(id: UUID()) + a.titleId = nil; b.titleId = nil + a.name = "A"; b.name = "B" + let added = try repository.mergeNXNative(scanned: [a, b]) + XCTAssertEqual(added.nxnativeGames.count, 3) + a.name = "A changed" + let refreshed = try repository.mergeNXNative(scanned: [a]) + XCTAssertEqual(refreshed.nxnativeGames.count, 3) + XCTAssertEqual(refreshed.nxnativeGames.first { $0.id == a.id }?.name, "A changed") + XCTAssertEqual(refreshed.nxnativeGames.first { $0.id == b.id }?.name, "B") + } + + func testBatchPatchPreservesOtherIntegrationAndRejectsDuplicateIDs() throws { + let (_, store, original) = try mixed() + let repository = CatalogRepository(store: store) + let updated = try repository.updateNXNativeGames { $0[0].status = .needsRebuild } + XCTAssertEqual(updated.games[1], original.games[1]) + XCTAssertEqual(updated.nxnativeGames[0].status, .needsRebuild) + XCTAssertThrowsError(try repository.updateNXNativeGames { $0.append($0[0]) }) + XCTAssertEqual(try repository.load(), updated) + } + func testBuildOutcomeUpdatesBuildOwnedFieldsAndKeepsCurrentPersonalAndSourceChoices() throws { + let (_, store, original) = try mixed() + let repository = CatalogRepository(store: store) + var outcome = try XCTUnwrap(original.games[0].nxnativeGame) + outcome.url = URL(fileURLWithPath: "/tmp/Finished.app") + outcome.status = .built; outcome.sizeBytes = 9000; outcome.versionString = "3.0" + outcome.appIconPending = true; outcome.pendingInstall = nil + outcome.portingFailure = nil; outcome.portingFailureReason = nil + _ = try repository.updateNXNative(id: outcome.id) { + $0.isFavorite = false; $0.isHidden = false; $0.appIconOnMac = true + $0.settings.language = "fr"; $0.name = "User choice" + } + let updated = try repository.recordNXNativeBuild(outcome) + let game = try XCTUnwrap(updated.games[0].nxnativeGame) + XCTAssertFalse(game.isFavorite); XCTAssertFalse(game.isHidden) + XCTAssertEqual(game.settings.language, "fr"); XCTAssertEqual(game.name, "User choice") + XCTAssertEqual(game.appIconOnMac, true) + XCTAssertEqual(game.url.path, "/tmp/Finished.app"); XCTAssertEqual(game.sizeBytes, 9000) + XCTAssertEqual(game.status, .built); XCTAssertEqual(game.versionString, "3.0") + XCTAssertNil(game.pendingInstall); XCTAssertNil(game.portingFailureReason) + XCTAssertEqual(game.sources, original.nxnativeGames[0].sources) + XCTAssertEqual(updated.games[1], original.games[1]) + } + + func testOldScanCannotResetAnInProgressBuild() throws { + let (_, store, original) = try mixed() + let repository = CatalogRepository(store: store) + let id = original.games[0].id + _ = try repository.updateNXNative(id: id) { $0.status = .building } + let refreshed = try repository.mergeNXNative(scanned: original.nxnativeGames, observedFrom: original.nxnativeGames) + XCTAssertEqual(refreshed.nxnativeGames[0].status, .building) + } + + func testOldScanCannotRevertACompletedBuildOrRunItsReconcileCallbackForThatGame() throws { + let (_, store, original) = try mixed() + let repository = CatalogRepository(store: store) + var outcome = original.nxnativeGames[0] + outcome.modificationDate = Date(timeIntervalSince1970: 1000) + outcome.versionString = "3.0"; outcome.sizeBytes = 9000 + outcome.pendingInstall = nil; outcome.status = .built + outcome.lastBuild = BuildRecord(startedAt: Date(timeIntervalSince1970: 900), endedAt: Date(timeIntervalSince1970: 1000), exitCode: 0) + _ = try repository.recordNXNativeBuild(outcome) + var accepted = Set<UUID>() + let refreshed = try repository.mergeNXNative(scanned: original.nxnativeGames, observedFrom: original.nxnativeGames) { games, ids in + accepted = ids + for index in games.indices where ids.contains(games[index].id) { games[index].sizeBytes = 1234 } + } + XCTAssertFalse(accepted.contains(outcome.id)) + XCTAssertEqual(refreshed.nxnativeGames[0].versionString, "3.0") + XCTAssertEqual(refreshed.nxnativeGames[0].sizeBytes, 9000) + XCTAssertEqual(refreshed.nxnativeGames[0].modificationDate, Date(timeIntervalSince1970: 1000)) + XCTAssertEqual(refreshed.nxnativeGames[0].lastBuild, outcome.lastBuild) + } + +} diff --git a/Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift b/Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift new file mode 100644 index 00000000..39404cbc --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift @@ -0,0 +1,277 @@ +import XCTest +import Combine +@testable import NXLibraryCore + +@MainActor +final class CatalogSourcesModelTests: XCTestCase { + private static let rescanSpacing: TimeInterval = 0.2 + + func testDiscoveryUsesTheSavedSteamRootEvenWhenDisabled() throws { + let (fixture, repository, _) = try prepared() + let custom = fixture.root.appendingPathComponent("Custom Steam") + let configuration = try repository.configureSource(.steam, enabled: false, root: custom).source(.steam)! + let model = CatalogSourcesModel(repository: repository, initialConfiguration: configuration) { _ in } + XCTAssertFalse(model.configuration.isEnabled) + XCTAssertEqual(model.discoveryRoot, custom) + } + + func testDiscoveryWithoutASavedRootUsesTheDefault() throws { + let (_, repository, initial) = try prepared() + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial) { _ in } + XCTAssertEqual(model.discoveryRoot, CatalogSourcesModel.defaultSteamRoot) + } + + private func prepared() throws -> (SteamTestFixture, CatalogRepository, CatalogSourceConfiguration) { + let f = try SteamTestFixture.temporary(in: self) + _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: f.root) + let repository = CatalogRepository(store: CatalogStore(directory: f.root)) + return (f, repository, try repository.load().source(.steam)!) + } + private func snapshot(_ root: URL, id: UInt32 = 10, partial: Bool = false) -> SteamLibrarySnapshot { + let content = root.appendingPathComponent("steamapps/common/Game") + let app = content.appendingPathComponent("Game.app") + let native = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"), + bundleIdentifier: "test.steam", name: "Steam game", architectures: [.arm64], + isDeclaredGame: true, fileObservations: []) + return .init(libraries: [.init(root: root, isReadable: true, isComplete: !partial)], + games: [.init(appID: id, name: "Steam game", installationURL: content, libraryURL: root, + reportedSizeBytes: 1, buildID: nil, nativeApps: [native], state: .nativeReady)], + issues: partial ? [.init(url: root, appID: nil, reason: .invalidManifest)] : []) + } + func testDisabledInitializationDoesNotScanAndEnableCommitsDiscovery() async throws { + let (f, repository, initial) = try prepared() + let done = expectation(description: "discovered") + let calls = SourceCallCounter() + let scan = snapshot(f.root) + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in calls.increment(); return scan }) { doc in + if doc.games.contains(where: { $0.steamGame != nil }) { done.fulfill() } + } + XCTAssertEqual(calls.value, 0); XCTAssertEqual(model.status, .disabled) + model.configure(enabled: true, root: f.root) + await fulfillment(of: [done], timeout: 3) + XCTAssertEqual(calls.value, 1); XCTAssertEqual(model.status, .ready) + XCTAssertEqual(model.observedGameCount, 1) + XCTAssertEqual(try repository.load().source(.steam)?.isEnabled, true) + } + func testDisableCancelsAndIgnoredWorkerCancellationStillCannotCommit() async throws { + let (f, repository, initial) = try prepared() + let entered = expectation(description: "worker") + let gate = DispatchSemaphore(value: 0) + let scan = snapshot(f.root) + let rejected = expectation(description: "must not discover"); rejected.isInverted = true + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in + entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return scan + }) { if $0.games.contains(where: { $0.steamGame != nil }) { rejected.fulfill() } } + model.configure(enabled: true, root: f.root) + await fulfillment(of: [entered], timeout: 3) + model.configure(enabled: false, root: nil) + gate.signal() + await fulfillment(of: [rejected], timeout: 0.15) + XCTAssertEqual(model.status, .disabled) + XCTAssertEqual(try repository.load().games.count, 1) + } + func testCancelKeepsOptInAndExistingRecords() async throws { + let (f, repository, initial) = try prepared() + let entered = expectation(description: "worker") + let gate = DispatchSemaphore(value: 0) + let scan = snapshot(f.root) + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in + entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return scan + }, onCommit: { _ in }) + model.configure(enabled: true, root: f.root) + await fulfillment(of: [entered], timeout: 3) + model.cancel(); gate.signal() + XCTAssertEqual(model.status, .cancelled) + XCTAssertEqual(try repository.load().source(.steam)?.isEnabled, true) + XCTAssertEqual(try repository.load().games.count, 1) + } + func testNewRootWinsWhenOldWorkerReturnsLater() async throws { + let (f, repository, initial) = try prepared() + let entered = expectation(description: "old worker"), done = expectation(description: "new worker") + let gate = DispatchSemaphore(value: 0), other = f.root.appendingPathComponent("Other") + let oldCommitted = expectation(description: "old source must not commit"); oldCommitted.isInverted = true + let old = snapshot(f.root, id: 10), new = snapshot(other, id: 20) + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { root, _ in + if root.path == f.root.path { entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return old } + return new + }) { + if $0.games.contains(where: { $0.steamGame?.appID == 20 }) { done.fulfill() } + if $0.games.contains(where: { $0.steamGame?.appID == 10 }) { oldCommitted.fulfill() } + } + model.configure(enabled: true, root: f.root) + await fulfillment(of: [entered], timeout: 3) + model.configure(enabled: true, root: other) + await fulfillment(of: [done], timeout: 3) + gate.signal() + await fulfillment(of: [oldCommitted], timeout: 0.15) + XCTAssertEqual(try repository.load().games.compactMap { $0.steamGame?.appID }, [20]) + XCTAssertEqual(model.configuration.rootURL?.path, other.path) + XCTAssertEqual(model.status, .ready) + } + func testFavoriteChangeWhileWorkerRunsIsRetained() async throws { + let (f, repository, initial) = try prepared() + let entered = expectation(description: "worker"), done = expectation(description: "committed") + let gate = DispatchSemaphore(value: 0), scan = snapshot(f.root) + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in + entered.fulfill(); _ = gate.wait(timeout: .now() + 2); return scan + }) { if $0.games.contains(where: { $0.steamGame != nil }) { done.fulfill() } } + model.configure(enabled: true, root: f.root) + await fulfillment(of: [entered], timeout: 3) + let id = try repository.load().games[0].id + _ = try repository.setFavorite(false, for: id) + gate.signal() + await fulfillment(of: [done], timeout: 3) + XCTAssertFalse(try repository.load().games[0].isFavorite) + XCTAssertEqual(model.status, .ready) + } + func testFailedSourceCanRefreshIntoPartialSnapshotWithoutDroppingKnownData() async throws { + let (f, repository, initial) = try prepared() + let failed = expectation(description: "failure"), partial = expectation(description: "partial") + let counter = SourceCallCounter(), scan = snapshot(f.root, partial: true) + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in + if counter.increment() == 1 { throw POSIXError(.EACCES) }; return scan + }, onCommit: { _ in }) + let observation = model.$status.sink { status in + if status == .failed { failed.fulfill() }; if status == .partial { partial.fulfill() } + } + model.configure(enabled: true, root: f.root) + await fulfillment(of: [failed], timeout: 3) + XCTAssertEqual(try repository.load().games.count, 1) + model.refresh() + await fulfillment(of: [partial], timeout: 3) + XCTAssertEqual(try repository.load().games.count, 2) + XCTAssertEqual(model.issues.count, 1) + withExtendedLifetime(observation) {} + } + + func testDownloadingGameIsNotCountedForReview() async throws { + let (f, repository, initial) = try prepared() + let done = expectation(description: "committed") + let content = f.root.appendingPathComponent("steamapps/common/Game") + let scan = SteamLibrarySnapshot(libraries: [.init(root: f.root, isReadable: true, isComplete: true)], + games: [.init(appID: 10, name: "Steam game", installationURL: content, libraryURL: f.root, + reportedSizeBytes: 0, buildID: nil, nativeApps: [], state: .downloading)], + issues: []) + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, scanner: { _, _ in scan }) { doc in + if doc.games.contains(where: { $0.steamGame != nil }) { done.fulfill() } + } + model.configure(enabled: true, root: f.root) + await fulfillment(of: [done], timeout: 3) + XCTAssertEqual(model.observedGameCount, 1) + XCTAssertEqual(model.reviewCount, 0) + } + + // MARK: - Rescans when Steam rewrites a manifest + + func testEveryScanRechecksWatchedFoldersEvenWithTheSameLibraryPaths() async throws { + let (f, repository, initial) = try prepared() + let root = try f.library() + let library = f.root.appendingPathComponent("Later") + let scan = SteamLibrarySnapshot(libraries: [.init(root: root, isReadable: true, isComplete: true), + .init(root: library, isReadable: true, isComplete: true)], + games: [], issues: []) + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, + scanner: { _, _ in scan }, onCommit: { _ in }) + let watcher = SteamManifestWatcher() + defer { watcher.stop() } + let observation = model.$libraryRoots.sink { watcher.watch($0, root: root) } + defer { withExtendedLifetime(observation) {} } + model.configure(enabled: true, root: root) + await settled(model) + XCTAssertEqual(model.status, .ready) + _ = try f.library("Later") + model.refresh() + await settled(model) + XCTAssertEqual(model.status, .ready) + let changed = expectation(description: "Watcher retries an unchanged path after the scan") + watcher.onChange = { changed.fulfill() } + try f.manifest(in: library) + await fulfillment(of: [changed], timeout: 6) + } + + private func settled(_ model: CatalogSourcesModel) async { + for _ in 0..<200 where model.status == .scanning || model.status == .idle { try? await Task.sleep(nanoseconds: 10_000_000) } + } + private func watching(delay: TimeInterval = 0, extraLibraries: [URL] = []) async throws -> (CatalogSourcesModel, SourceCallCounter, URL) { + let (f, repository, initial) = try prepared() + let calls = SourceCallCounter() + let base = snapshot(f.root) + let scan: SteamLibrarySnapshot + if !extraLibraries.isEmpty { + scan = .init(libraries: ([f.root] + extraLibraries).map { .init(root: $0, isReadable: true, isComplete: true) }, + games: base.games, issues: []) + } else { scan = base } + let model = CatalogSourcesModel(repository: repository, initialConfiguration: initial, + scanner: { _, _ in calls.increment(); if delay > 0 { Thread.sleep(forTimeInterval: delay) }; return scan }, + rescanQuiet: 0.05, rescanSpacing: Self.rescanSpacing) { _ in } + model.configure(enabled: true, root: f.root) + await settled(model) + return (model, calls, f.root) + } + + func testLibraryRootsFollowTheCommittedScan() async throws { + let external = URL(fileURLWithPath: "/tmp/catalog-external-library") + let (model, _, root) = try await watching(extraLibraries: [external]) + XCTAssertEqual(model.libraryRoots, [root, external]) + } + + func testBurstOfChangesRescansOnce() async throws { + let (model, calls, _) = try await watching() + XCTAssertEqual(calls.value, 1) + for _ in 0..<5 { model.steamFilesChanged(); try await Task.sleep(nanoseconds: 10_000_000) } + try await Task.sleep(nanoseconds: 600_000_000) + await settled(model) + XCTAssertEqual(calls.value, 2) + } + + func testChangeDuringScanRescansOnceAfterIt() async throws { + let (model, calls, _) = try await watching(delay: 0.3) + XCTAssertEqual(calls.value, 1) + model.refresh() + try await Task.sleep(nanoseconds: 30_000_000) + XCTAssertEqual(model.status, .scanning) + for _ in 0..<3 { model.steamFilesChanged() } + try await Task.sleep(nanoseconds: 1_200_000_000) + await settled(model) + XCTAssertEqual(calls.value, 3) + } + + func testRescansAreSpacedApart() async throws { + let (model, calls, _) = try await watching() + let rescans = expectation(description: "both rescans start") + rescans.expectedFulfillmentCount = 2 + var starts: [Date] = [] + let observation = model.$status.sink { status in + guard status == .scanning else { return } + starts.append(Date()) + if starts.count == 1 { model.steamFilesChanged() } + rescans.fulfill() + } + defer { observation.cancel() } + model.steamFilesChanged() + await fulfillment(of: [rescans], timeout: 5) + await settled(model) + XCTAssertEqual(calls.value, 3) + guard starts.count == 2 else { return XCTFail("Expected two rescan starts") } + // Status publishes just after the model records the start time. + XCTAssertGreaterThanOrEqual(starts[1].timeIntervalSince(starts[0]), Self.rescanSpacing - 0.01) + } + + func testDisablingDropsAPendingRescanAndClearsLibraries() async throws { + let (model, calls, root) = try await watching() + XCTAssertEqual(model.libraryRoots, [root]) + model.steamFilesChanged() + model.configure(enabled: false, root: root) + XCTAssertEqual(model.libraryRoots, []) + try await Task.sleep(nanoseconds: 500_000_000) + XCTAssertEqual(calls.value, 1) + } +} + + +private final class SourceCallCounter: @unchecked Sendable { + private let lock = NSLock() + private var stored = 0 + @discardableResult func increment() -> Int { lock.lock(); defer { lock.unlock() }; stored += 1; return stored } + var value: Int { lock.lock(); defer { lock.unlock() }; return stored } +} diff --git a/Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift b/Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift new file mode 100644 index 00000000..f94244bc --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift @@ -0,0 +1,100 @@ +import XCTest +@testable import NXLibraryCore + +final class CatalogSourcesRepositoryTests: XCTestCase { + private func prepared() throws -> (SteamTestFixture, CatalogRepository) { + let fixture = try SteamTestFixture.temporary(in: self) + _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: fixture.root) + return (fixture, CatalogRepository(store: CatalogStore(directory: fixture.root))) + } + private func snapshot(_ root: URL) -> SteamLibrarySnapshot { + let content = root.appendingPathComponent("steamapps/common/Fixture") + let app = content.appendingPathComponent("Fixture.app") + let native = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"), + bundleIdentifier: "test.steam", name: "Fixture Steam", architectures: [.arm64], + isDeclaredGame: true, fileObservations: []) + return .init(libraries: [.init(root: root, isReadable: true, isComplete: true)], + games: [.init(appID: 10, name: "Fixture Steam", installationURL: content, libraryURL: root, + reportedSizeBytes: 200, buildID: "1", nativeApps: [native], state: .nativeReady)], issues: []) + } + + func testOldSchemaOneWithoutSourceGenerationDecodesDeterministically() throws { + let (_, repository) = try prepared() + let document = try repository.load() + var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(document)) as? [String: Any]) + var sources = try XCTUnwrap(json["sources"] as? [[String: Any]]) + for index in sources.indices { sources[index].removeValue(forKey: "generation") } + json["sources"] = sources + let old = try JSONSerialization.data(withJSONObject: json) + let a = try CatalogStore.decode(old), b = try CatalogStore.decode(old) + XCTAssertEqual(a, b) + XCTAssertEqual(try CatalogStore.decode(JSONEncoder().encode(a)), a) + XCTAssertEqual(a.games, document.games) + } + + func testPersonalEditsDuringAScanArePreservedWhenSnapshotCommits() throws { + let (fixture, repository) = try prepared() + let enabled = try repository.configureSource(.steam, enabled: true, root: fixture.root) + let source = try XCTUnwrap(enabled.source(.steam)) + _ = try repository.setFavorite(false, for: enabled.games[0].id) + let merged = try repository.applySteam(snapshot(fixture.root), expectedSource: source) + XCTAssertFalse(merged.games[0].isFavorite) + XCTAssertEqual(merged.games.count, 2) + XCTAssertEqual(merged.games[1].steamGame?.appID, 10) + let id = merged.games[1].id + _ = try repository.setFavorite(true, for: id) + _ = try repository.setHidden(true, for: id) + let again = try repository.applySteam(snapshot(fixture.root), expectedSource: source) + XCTAssertEqual(again.games[1].id, id) + XCTAssertTrue(again.games[1].isFavorite); XCTAssertTrue(again.games[1].isHidden) + } + + func testDisableReenableAtSameRootInvalidatesOlderSourceGeneration() throws { + let (fixture, repository) = try prepared() + let initial = try repository.configureSource(.steam, enabled: true, root: fixture.root) + let old = try XCTUnwrap(initial.source(.steam)) + _ = try repository.configureSource(.steam, enabled: false, root: fixture.root) + let enabled = try repository.configureSource(.steam, enabled: true, root: fixture.root) + XCTAssertNotEqual(enabled.source(.steam)?.generation, old.generation) + XCTAssertThrowsError(try repository.applySteam(snapshot(fixture.root), expectedSource: old)) + XCTAssertEqual(try repository.load(), enabled) + } + + func testChangingRootOrDisablingNeverAppliesOldSnapshot() throws { + let (fixture, repository) = try prepared() + let initial = try repository.configureSource(.steam, enabled: true, root: fixture.root) + let source = try XCTUnwrap(initial.source(.steam)) + _ = try repository.configureSource(.steam, enabled: true, root: fixture.root.appendingPathComponent("Other")) + XCTAssertThrowsError(try repository.applySteam(snapshot(fixture.root), expectedSource: source)) + _ = try repository.configureSource(.steam, enabled: false, root: fixture.root) + XCTAssertThrowsError(try repository.applySteam(snapshot(fixture.root), expectedSource: source)) + XCTAssertEqual(try repository.load().games.count, 1) + } + func testExplicitNXAdoptionEnablesItsExperienceWhilePassiveScanStaysDisabled() throws { + let root = try SteamTestFixture.temporary(in: self).root + let repository = CatalogRepository(store: CatalogStore(directory: root)) + let game = CatalogTestSupport.completeLegacyGame() + XCTAssertFalse(try repository.load().source(.nxnative)!.isEnabled) + XCTAssertThrowsError(try repository.mergeNXNative(scanned: [game])) + let adopted = try repository.mergeNXNative(scanned: [game], enableSource: true) + XCTAssertTrue(adopted.source(.nxnative)!.isEnabled) + XCTAssertEqual(adopted.games.first?.id, game.id) + XCTAssertFalse(adopted.source(.steam)!.isEnabled) + } + + func testRepeatedFavoriteCommandUsesLatestPersistedValue() throws { + let (fixture, repository) = try prepared() + let enabled = try repository.configureSource(.steam, enabled: true, root: fixture.root) + let scanned = try repository.applySteam(snapshot(fixture.root), expectedSource: enabled.source(.steam)!) + let captured = try XCTUnwrap(scanned.games.first { $0.integration == .steam }) + XCTAssertFalse(captured.isFavorite) + // The keyboard can retain one Details view/ID across both commands. + let favorite = try repository.toggleFavorite(for: captured.id) + XCTAssertTrue(favorite.games.first { $0.id == captured.id }!.isFavorite) + let unfavorite = try repository.toggleFavorite(for: captured.id) + XCTAssertFalse(unfavorite.games.first { $0.id == captured.id }!.isFavorite) + XCTAssertEqual(try repository.load(), unfavorite) + XCTAssertEqual(unfavorite.source(.steam), scanned.source(.steam)) + } + +} diff --git a/Tests/NXLibraryCoreTests/CatalogStoreTests.swift b/Tests/NXLibraryCoreTests/CatalogStoreTests.swift new file mode 100644 index 00000000..25b34912 --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogStoreTests.swift @@ -0,0 +1,237 @@ +import XCTest +import Darwin +@testable import NXLibraryCore + +final class CatalogStoreTests: XCTestCase { + private func fixture() throws -> SteamTestFixture { try .temporary(in: self) } + private func url(_ root: URL, _ name: String) -> URL { root.appendingPathComponent(name) } + private func assertNoCatalog(_ root: URL, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertFalse(FileManager.default.fileExists(atPath: url(root, "catalog.json").path), file: file, line: line) + } + + func testMigrationPreservesAllLegacyFieldsKeysAndBytesAndIsNotRepeated() throws { + let root = try fixture().root + let original = CatalogTestSupport.completeLegacyGame() + let bytes = try CatalogTestSupport.writeLegacy([original], to: root) + let store = CatalogStore(directory: root) + let migrated = try store.loadOrMigrate() + XCTAssertEqual(migrated.games.map(\.nxnativeGame), [original]) + XCTAssertEqual(migrated.games[0].personalizationKey, "0100000000000001") + XCTAssertEqual(migrated.source(.nxnative)?.isEnabled, true) + XCTAssertEqual(migrated.source(.steam)?.isEnabled, false) + var draft = migrated + draft.games[0].setFavorite(false) + let saved = try store.save(draft, expectedRevision: migrated.revision) + XCTAssertNotEqual(saved.revision, migrated.revision) + XCTAssertEqual(try store.loadOrMigrate(), saved) + XCTAssertFalse(saved.games[0].isFavorite) + XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), bytes) + XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), migrated) + } + + func testNewProfileDoesNotEnableAnIntegration() throws { + let root = try fixture().root + let result = try CatalogStore(directory: root).loadOrMigrate() + XCTAssertTrue(result.games.isEmpty) + XCTAssertEqual(Set(result.sources.map(\.integration)), [.steam, .nxnative]) + XCTAssertTrue(result.sources.allSatisfy { !$0.isEnabled }) + XCTAssertFalse(FileManager.default.fileExists(atPath: url(root, "library.json").path)) + XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), result) + } + + func testOnlyAbsentLegacyMainAllowsItsValidBackup() throws { + let root = try fixture().root + let original = CatalogTestSupport.completeLegacyGame() + let bytes = try CatalogTestSupport.writeLegacy([original], to: root) + try FileManager.default.moveItem(at: url(root, "library.json"), to: url(root, "library.json.bak")) + let store = CatalogStore(directory: root) + let result = try store.loadOrMigrate() + XCTAssertEqual(result.games.first?.nxnativeGame, original) + XCTAssertEqual(try Data(contentsOf: url(root, "library.json.bak")), bytes) + try bytes.write(to: url(root, "library.json")) + XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) } + } + + func testCorruptLegacyMainDoesNotSilentlyUseGoodBackup() throws { + let root = try fixture().root + let bytes = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + try bytes.write(to: url(root, "library.json.bak")) + let corrupt = Data("not-json".utf8) + try corrupt.write(to: url(root, "library.json")) + XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate()) + assertNoCatalog(root) + XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), corrupt) + XCTAssertEqual(try Data(contentsOf: url(root, "library.json.bak")), bytes) + } + + func testUnknownLegacySchemaAndDuplicateUUIDsAreRejected() throws { + for (schema, count) in [(99, 1), (1, 2)] { + let root = try fixture().root + let bytes = try CatalogTestSupport.writeLegacy(Array(repeating: CatalogTestSupport.completeLegacyGame(), count: count), to: root, schemaVersion: schema) + XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate()) + assertNoCatalog(root) + XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), bytes) + } + } + + func testLegacySymlinkAndFIFOAreRejectedWithoutFollowingOrBlocking() throws { + for special in ["symlink", "fifo"] { + let root = try fixture().root + let target = url(root, "library.json") + if special == "symlink" { + let external = url(root, "external.json") + try Data("untouched".utf8).write(to: external) + try FileManager.default.createSymbolicLink(at: target, withDestinationURL: external) + } else { XCTAssertEqual(mkfifo(target.path, 0o600), 0) } + XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate()) + assertNoCatalog(root) + } + } + + func testOversizedLegacyFileIsRejected() throws { + let root = try fixture().root + try Data(repeating: 0x20, count: 16 * 1024 * 1024 + 1).write(to: url(root, "library.json")) + XCTAssertThrowsError(try CatalogStore(directory: root).loadOrMigrate()) + assertNoCatalog(root) + } + + func testChangedLegacyMainBlocksReadsAndWritesButBackupRotationDoesNot() throws { + let root = try fixture().root + let bytes = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + let store = CatalogStore(directory: root) + let first = try store.loadOrMigrate() + try Data("an obsolete backup".utf8).write(to: url(root, "library.json.bak")) + XCTAssertEqual(try store.loadOrMigrate(), first) + try (bytes + Data(" ".utf8)).write(to: url(root, "library.json")) + XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) } + XCTAssertThrowsError(try store.save(first, expectedRevision: first.revision)) + XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json"))), first) + } + + func testNewLegacyFileAfterEmptyMigrationCannotBeIgnored() throws { + let root = try fixture().root + let store = CatalogStore(directory: root) + _ = try store.loadOrMigrate() + _ = try CatalogTestSupport.writeLegacy([], to: root) + XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .legacyChanged) } + } + + func testTwoStoresCannotSaveTheSameRevisionTwice() throws { + let root = try fixture().root + _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + let a = CatalogStore(directory: root), b = CatalogStore(directory: root) + let old = try a.loadOrMigrate() + var draft = old + draft.games[0].setHidden(false) + let committed = try a.save(draft, expectedRevision: old.revision) + XCTAssertThrowsError(try b.save(old, expectedRevision: old.revision)) { XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) } + XCTAssertEqual(try b.loadOrMigrate(), committed) + } + + func testAWriterHoldingTheLockRefusesAnotherWriterInsteadOfWaiting() throws { + let root = try fixture().root + let store = CatalogStore(directory: root) + let initial = try store.loadOrMigrate() + let competing = CatalogStore(directory: root, publication: .init { staged, target, replace, validate in + XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .busy) } + try CatalogPublication.atomic.publish(staged, target, replace, validate) + }) + _ = try competing.save(initial, expectedRevision: initial.revision) + } + + func testPublicationFailurePreservesReadableMainBackupAndLegacyBytes() throws { + let root = try fixture().root + let bytes = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + let initial = try CatalogStore(directory: root).loadOrMigrate() + let failing = CatalogStore(directory: root, publication: .init { _, _, _, _ in throw POSIXError(.ENOSPC) }) + XCTAssertThrowsError(try failing.save(initial, expectedRevision: initial.revision)) + XCTAssertEqual(try CatalogStore(directory: root).loadOrMigrate(), initial) + XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), initial) + XCTAssertEqual(try Data(contentsOf: url(root, "library.json")), bytes) + XCTAssertFalse(try FileManager.default.contentsOfDirectory(atPath: root.path).contains { $0.hasPrefix(".catalog-stage-") }) + } + + func testLegacyChangeDuringPublicationRejectsThePreparedCandidate() throws { + let root = try fixture().root + let legacy = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + let initial = try CatalogStore(directory: root).loadOrMigrate() + let changing = CatalogStore(directory: root, publication: .init { staged, target, replace, validate in + try (legacy + Data(" ".utf8)).write(to: self.url(root, "library.json")) + try CatalogPublication.atomic.publish(staged, target, replace, validate) + }) + XCTAssertThrowsError(try changing.save(initial, expectedRevision: initial.revision)) + XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json"))), initial) + } + + func testDamagedOrUnsupportedCatalogNeverActivatesEmptyOrOverwritesGoodBackup() throws { + for replacement in [Data("broken".utf8), Data("{\"schemaVersion\":99}".utf8)] { + let root = try fixture().root + let store = CatalogStore(directory: root) + let initial = try store.loadOrMigrate() + let backup = try Data(contentsOf: url(root, "catalog.json.bak")) + try replacement.write(to: url(root, "catalog.json")) + XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .invalidCatalog(backupAvailable: true)) } + XCTAssertThrowsError(try store.save(initial, expectedRevision: initial.revision)) + XCTAssertEqual(try Data(contentsOf: url(root, "catalog.json.bak")), backup) + XCTAssertEqual(try Data(contentsOf: url(root, "catalog.json")), replacement) + } + } + + func testMissingCatalogWithValidBackupRequiresRecoveryRatherThanNewMigration() throws { + let root = try fixture().root + let store = CatalogStore(directory: root) + _ = try store.loadOrMigrate() + try FileManager.default.removeItem(at: url(root, "catalog.json")) + XCTAssertThrowsError(try store.loadOrMigrate()) { XCTAssertEqual($0 as? CatalogStoreError, .invalidCatalog(backupAvailable: true)) } + assertNoCatalog(root) + } + + func testInvalidDraftCannotReplaceTheValidCatalog() throws { + let root = try fixture().root + _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + let store = CatalogStore(directory: root) + let initial = try store.loadOrMigrate() + var duplicate = initial + duplicate.games.append(initial.games[0]) + XCTAssertThrowsError(try store.save(duplicate, expectedRevision: initial.revision)) + var invalidSource = initial + invalidSource.sources = [.init(integration: .steam, isEnabled: true)] + XCTAssertThrowsError(try store.save(invalidSource, expectedRevision: initial.revision)) + XCTAssertEqual(try store.loadOrMigrate(), initial) + } + + func testFractionalDatesSurviveNewCatalogWrites() throws { + let root = try fixture().root + let store = CatalogStore(directory: root) + var draft = try store.loadOrMigrate() + var legacy = CatalogTestSupport.completeLegacyGame() + legacy.modificationDate = Date(timeIntervalSinceReferenceDate: 12345.678901) + draft.games = [.init(nxnative: legacy)] + let saved = try store.save(draft, expectedRevision: draft.revision) + XCTAssertEqual(try store.loadOrMigrate().games[0].nxnativeGame?.modificationDate, legacy.modificationDate) + XCTAssertEqual(saved.games[0].nxnativeGame, legacy) + } + func testFinalDirectorySyncFailureReportsUncertainCommitAndAllowsExplicitReload() throws { + let root = try fixture().root + _ = try CatalogTestSupport.writeLegacy([CatalogTestSupport.completeLegacyGame()], to: root) + let store = CatalogStore(directory: root) + let initial = try store.loadOrMigrate() + var draft = initial + draft.games[0].setFavorite(false) + let failing = CatalogStore(directory: root, publication: .init(syncDirectory: { _ in throw POSIXError(.EIO) }, + publish: CatalogPublication.atomic.publish)) + XCTAssertThrowsError(try failing.save(draft, expectedRevision: initial.revision)) { + XCTAssertEqual($0 as? CatalogStoreError, .commitUncertain) + } + // Publication already happened; the caller must reload, not assume + // the old revision still owns the file or retry as an empty library. + let reloaded = try store.loadOrMigrate() + XCTAssertNotEqual(reloaded.revision, initial.revision) + XCTAssertFalse(reloaded.games[0].isFavorite) + XCTAssertEqual(try CatalogStore.decode(Data(contentsOf: url(root, "catalog.json.bak"))), initial) + XCTAssertThrowsError(try store.save(draft, expectedRevision: initial.revision)) { + XCTAssertEqual($0 as? CatalogStoreError, .staleRevision) + } + } + +} diff --git a/Tests/NXLibraryCoreTests/CatalogTestSupport.swift b/Tests/NXLibraryCoreTests/CatalogTestSupport.swift new file mode 100644 index 00000000..1e462876 --- /dev/null +++ b/Tests/NXLibraryCoreTests/CatalogTestSupport.swift @@ -0,0 +1,41 @@ +import Foundation +import XCTest +@testable import NXLibraryCore + +enum CatalogTestSupport { + static func completeLegacyGame(id: UUID = UUID(uuidString: "11111111-1111-1111-1111-111111111111")!) -> PortedGame { + var game = PortedGame(id: id, name: "Fixture Switch game", url: URL(fileURLWithPath: "/tmp/catalog-fixture/Game.app"), + platform: .macApp, sizeBytes: 1234, modificationDate: Date(timeIntervalSince1970: 100), + bundleId: "org.nxnative.0100000000000001", titleId: "0100000000000001", versionString: "2.0") + game.status = .builtSourcesMissing + game.sources = [GameFileItem(url: URL(fileURLWithPath: "/tmp/catalog-fixture/base.nsp"), kind: .base, + titleId: "0100000000000001", sizeBytes: 456)] + game.workspacePath = "/tmp/catalog-fixture/workspace" + game.buildCachePath = "/tmp/catalog-fixture/workspace/cache" + game.settings.language = "it" + game.settings.metalHUD = true + game.toolchain = ToolchainInfo(engineCommit: "fixture123", metalVersion: "32023.922", xcodeVersion: "27.2", verified: true) + game.lastBuild = BuildRecord(startedAt: Date(timeIntervalSince1970: 10), endedAt: Date(timeIntervalSince1970: 20), + exitCode: 0, outputPath: game.url.path, toolchainVerified: true) + game.pendingInstall = PendingInstall(tempApp: URL(fileURLWithPath: "/tmp/catalog-fixture/held/Game.app"), finalApp: game.url, + record: game.lastBuild!, toolchain: game.toolchain) + game.portingFailure = .failed + game.portingFailureReason = PortingFailureReason(kind: .diskFull, detail: "Synthetic failure") + game.isFavorite = true + game.isHidden = true + game.usesPickedAppIcon = true + game.appIconOnMac = false + game.appIconPending = true + return game + } + + static func writeLegacy(_ games: [PortedGame], to directory: URL, schemaVersion: Int = 1) throws -> Data { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data = try encoder.encode(LibraryFile(schemaVersion: schemaVersion, games: games)) + try data.write(to: directory.appendingPathComponent("library.json")) + return data + } +} diff --git a/Tests/NXLibraryCoreTests/CriticRatingTests.swift b/Tests/NXLibraryCoreTests/CriticRatingTests.swift new file mode 100644 index 00000000..d9ee3ebc --- /dev/null +++ b/Tests/NXLibraryCoreTests/CriticRatingTests.swift @@ -0,0 +1,240 @@ +import XCTest +@testable import NXLibraryCore + +final class CriticRatingTests: XCTestCase { + private let query = CriticRatingQuery(name: "Fixture", platform: .mac, steamAppID: 42) + + private func snak(_ value: Any) -> [String: Any] { ["datavalue": ["value": value]] } + private func item(_ id: String) -> [String: Any] { snak(["id": id]) } + private func claim(_ value: Any) -> [String: Any] { ["mainsnak": snak(value)] } + private func score(_ value: String = "78/100", issuer: String = "Q21039459", + method: String = "Q114712322", platform: String? = nil, + referenced: Bool = true) -> [String: Any] { + var quals: [String: Any] = ["P447": [item(issuer)], "P459": [item(method)]] + if let platform { quals["P400"] = [item(platform)] } + var value = claim(value) + value["id"] = "Q10$statement" + value["qualifiers"] = quals + if referenced { value["references"] = [["snaks": ["P248": [item(issuer)]]]] } + return value + } + private func payload(_ scores: [[String: Any]], steam: String = "42", second: Bool = false) throws -> Data { + let entity: [String: Any] = ["claims": ["P31": [claim(["id": "Q7889"])], + "P1733": [claim(steam)], "P444": scores]] + var entities = ["Q10": entity] + if second { entities["Q11"] = entity } + return try JSONSerialization.data(withJSONObject: ["entities": entities]) + } + func testReferencedAverageAndProportionalStars() throws { + let rating = try XCTUnwrap(WikidataRatings.rating(in: payload([score()]), ids: ["Q10"], query: query)) + XCTAssertEqual(rating.score, 78) + XCTAssertEqual(rating.source, .openCritic) + XCTAssertEqual(rating.starFills.count, 5) + XCTAssertEqual(rating.starFills.reduce(0, +), 3.9, accuracy: 0.0001) + XCTAssertEqual(rating.starFills[3], 0.9, accuracy: 0.0001) + XCTAssertEqual(rating.starFills[4], 0) + XCTAssertEqual(rating.statementID, "Q10$statement") + XCTAssertEqual(rating.sourceURL.absoluteString, "https://www.wikidata.org/wiki/Q10#Q10$statement") + } + func testRecommendationIndividualReviewsAndUnreferencedValuesAreNotCriticAverages() throws { + for entry in [score("78%"), score(method: "Q119576498"), score(issuer: "Q207708"), + score(referenced: false), score("101/100"), score("-1/100"), score("4/5")] { + XCTAssertNil(try WikidataRatings.rating(in: payload([entry]), ids: ["Q10"], query: query)) + } + var multiple = score() + multiple["qualifiers"] = ["P447": [item("Q21039459"), item("Q150248")]] + XCTAssertNil(try WikidataRatings.rating(in: payload([multiple]), ids: ["Q10"], query: query)) + var unknownPlatform = score() + unknownPlatform["qualifiers"] = ["P447": [item("Q21039459")], "P459": [item("Q114712322")], + "P400": [["snaktype": "somevalue"]]] + XCTAssertNil(try WikidataRatings.rating(in: payload([unknownPlatform]), ids: ["Q10"], query: query)) + } + func testPlatformSpecificScoreWinsAndForeignPlatformsAreNeverBorrowed() throws { + let mac = score("81/100", issuer: "Q150248", method: "Q106515043", platform: "Q14116") + let windows = score("92/100", issuer: "Q150248", method: "Q106515043", platform: "Q1406") + XCTAssertEqual(try WikidataRatings.rating(in: payload([score(), mac, windows]), ids: ["Q10"], query: query)?.score, 81) + XCTAssertNil(try WikidataRatings.rating(in: payload([windows]), ids: ["Q10"], query: query)) + XCTAssertEqual(try WikidataRatings.rating(in: payload([score(), windows]), ids: ["Q10"], query: query)?.score, 78) + } + func testConflictingIdentityAmbiguityAndMalformedResponsesDoNotBecomeRatings() throws { + XCTAssertNil(try WikidataRatings.rating(in: payload([score()], steam: "99"), ids: ["Q10"], query: query)) + XCTAssertNil(try WikidataRatings.rating(in: payload([score()], second: true), ids: ["Q10", "Q11"], query: query)) + XCTAssertThrowsError(try WikidataRatings.rating(in: Data("{\"error\":{\"code\":\"maxlag\"}}".utf8), ids: ["Q10"], query: query)) + } + + func testSwitch2FallbackUsesItsOwnPlatformWithoutBorrowingSwitchScores() throws { + let switch2 = CriticRatingQuery(name: "Fixture", platform: .switch2) + let data = try payload([score("81/100", platform: "Q122761124"), + score("92/100", platform: "Q19610114")]) + XCTAssertEqual(try WikidataRatings.rating(in: data, ids: ["Q10"], query: switch2)?.score, 81) + XCTAssertNil(try WikidataRatings.rating(in: payload([score(platform: "Q19610114")]), + ids: ["Q10"], query: switch2)) + } + func testSearchRequiresExactTitleOrAliasNeverAnEditionOrSequel() throws { + let data = Data(""" + {"search":[{"id":"Q10","label":"Fixture"},{"id":"Q11","label":"Fixture II"}, + {"id":"Q12","label":"Fixture Deluxe Edition"},{"id":"Q13","label":"Other","aliases":["Fixture"]}]} + """.utf8) + XCTAssertEqual(try WikidataRatings.ids(in: data, name: "Fixture"), ["Q10", "Q13"]) + XCTAssertThrowsError(try WikidataRatings.ids(in: Data("{}".utf8), name: "Fixture")) + } + + func testSearchRemovesStoreTrademarkSymbolsWithoutRemovingEditionWords() throws { + let url = try XCTUnwrap(WikidataRatings.searchURL(name: "Fixture™: Test® Deluxe Edition")) + let params = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems + XCTAssertEqual(params?.first { $0.name == "search" }?.value, "Fixture: Test Deluxe Edition") + } + + func testSearchReadsTheRealAliasMatchField() throws { + let data = Data(""" + {"search":[{"id":"Q10","label":"Official name","match":{"type":"alias","text":"Fixture"}}, + {"id":"Q11","label":"Other","match":{"type":"description","text":"Fixture"}}]} + """.utf8) + XCTAssertEqual(try WikidataRatings.ids(in: data, name: "Fixture"), ["Q10"]) + } + + func testSteamIdentifierFindsARenamedGameWithoutGuessingItsTitle() async throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: dir) } + let body = try payload([score()]) + let service = CriticRatingService(directory: dir, transport: { url in + let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + if items.contains(where: { $0.name == "srsearch" && $0.value == "haswbstatement:P1733=42" }) { + return Data("{\"query\":{\"search\":[{\"title\":\"Q10\",\"ns\":0}]}}".utf8) + } + if url.query?.contains("wbgetentities") == true { return body } + return Data("{\"search\":[]}".utf8) + }) + let result = await service.load(CriticRatingQuery(name: "My renamed title", platform: .mac, steamAppID: 42)) + XCTAssertEqual(result.rating?.score, 78) + } + + func testOldMissingCacheIsRetriedAfterResolverFix() async throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: dir) } + let query = CriticRatingQuery(name: "Fixture™", platform: .switch) + let old = CriticRatingService(directory: dir, transport: { _ in Data("{\"search\":[]}".utf8) }) + _ = await old.load(query) + let file = try XCTUnwrap(FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil).first) + var cache = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + cache.removeValue(forKey: "resolverVersion") + try JSONSerialization.data(withJSONObject: cache).write(to: file) + let body = try payload([score()]) + let fixed = CriticRatingService(directory: dir, transport: { url in + url.query?.contains("wbgetentities") == true ? body : Data("{\"search\":[{\"id\":\"Q10\",\"label\":\"Fixture\"}]}".utf8) + }) + let result = await fixed.load(query) + XCTAssertEqual(result.rating?.score, 78) + } + + func testSteamIndexCandidatesMustStillCarryTheRequestedIdentifier() throws { + var root = try XCTUnwrap(JSONSerialization.jsonObject(with: payload([score()])) as? [String: Any]) + var entities = try XCTUnwrap(root["entities"] as? [String: [String: Any]]) + var entity = try XCTUnwrap(entities["Q10"]) + var claims = try XCTUnwrap(entity["claims"] as? [String: Any]) + claims.removeValue(forKey: "P1733") + entity["claims"] = claims; entities["Q10"] = entity; root["entities"] = entities + let body = try JSONSerialization.data(withJSONObject: root) + XCTAssertNil(try WikidataRatings.rating(in: body, ids: ["Q10"], query: query, requireSteamID: true)) + XCTAssertNotNil(try WikidataRatings.rating(in: body, ids: ["Q10"], query: query)) + let search = Data("{\"query\":{\"search\":[{\"title\":\"Q10\",\"ns\":0},{\"title\":\"Property:P1733\",\"ns\":120}]}}".utf8) + XCTAssertEqual(try WikidataRatings.steamIDs(in: search), ["Q10"]) + } + func testCacheAndOfflineFallbackKeepTheOriginalValue() async throws { + let query = CriticRatingQuery(name: "Fixture", platform: .switch) + let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: dir) } + let body = try payload([score()]) + let service = CriticRatingService(directory: dir, transport: { url in + url.query?.contains("wbsearchentities") == true ? Data("{\"search\":[{\"id\":\"Q10\",\"label\":\"Fixture\"}]}".utf8) : body + }) + let first = await service.load(query) + XCTAssertEqual(first.rating?.score, 78) + let offline = CriticRatingService(directory: dir, transport: { _ in throw URLError(.notConnectedToInternet) }) + let cached = await offline.load(query) + XCTAssertEqual(cached.rating, first.rating) + let stale = await offline.load(query, now: Date().addingTimeInterval(8 * 86400)) + XCTAssertEqual(stale.rating, first.rating) + XCTAssertTrue(stale.isStale) + let other = await offline.load(CriticRatingQuery(name: "Different", platform: .mac, steamAppID: 7)) + XCTAssertNil(other.rating) + } + func testMissingAnswersAreCachedAndConcurrentReadersShareRequests() async throws { + let query = CriticRatingQuery(name: "Fixture", platform: .switch) + actor Calls { var value = 0; func bump() { value += 1 } } + let calls = Calls(), dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: dir) } + let service = CriticRatingService(directory: dir, transport: { _ in + await calls.bump(); try await Task.sleep(nanoseconds: 20_000_000) + return Data("{\"search\":[]}".utf8) + }) + async let a = service.load(query) + async let b = service.load(query) + let results = await (a, b) + XCTAssertNil(results.0.rating); XCTAssertNil(results.1.rating) + _ = await service.load(query) + let count = await calls.value + XCTAssertEqual(count, 1) + } + + func testCancellingLookupStopsTransportWithoutCachingAbsence() async throws { + let started = expectation(description: "network request started") + let stopped = expectation(description: "network request cancelled") + let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: dir) } + let service = CriticRatingService(directory: dir, transport: { _ in + started.fulfill() + do { try await Task.sleep(nanoseconds: 10_000_000_000); return Data() } + catch { stopped.fulfill(); throw error } + }) + let task = Task { await service.load(query) } + await fulfillment(of: [started], timeout: 2) + task.cancel() + await fulfillment(of: [stopped], timeout: 2) + let answer = await task.value + XCTAssertNil(answer.rating) + XCTAssertFalse(FileManager.default.fileExists(atPath: dir.path)) + } + + func testAPIErrorBacksOffRatherThanPersistingAMissingScore() async throws { + actor Calls { var count = 0; func bump() { count += 1 } } + let calls = Calls(), dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: dir) } + let service = CriticRatingService(directory: dir, transport: { _ in + await calls.bump(); return Data("{\"error\":{\"code\":\"maxlag\"}}".utf8) + }) + _ = await service.load(query) + _ = await service.load(query) + let count = await calls.count + XCTAssertEqual(count, 1) + XCTAssertFalse(FileManager.default.fileExists(atPath: dir.path)) + } + + func testZeroIsARealScoreAndFormattingUsesTheRequestedRegion() throws { + let zero = try XCTUnwrap(WikidataRatings.rating(in: payload([score("0/100")]), ids: ["Q10"], query: query)) + XCTAssertEqual(zero.starFills, [0, 0, 0, 0, 0]) + let decimal = try XCTUnwrap(WikidataRatings.rating(in: payload([score("78.5/100")]), ids: ["Q10"], query: query)) + XCTAssertEqual(decimal.number(locale: Locale(identifier: "it_IT")), "78,5/100") + } + + func testDifferentGamesRequestThePublicAPIInSeries() async throws { + actor Activity { + var active = 0, maximum = 0 + func start() { active += 1; maximum = max(maximum, active) } + func stop() { active -= 1 } + } + let activity = Activity(), dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: dir) } + let service = CriticRatingService(directory: dir, transport: { _ in + await activity.start() + try await Task.sleep(nanoseconds: 20_000_000) + await activity.stop() + return Data("{\"search\":[]}".utf8) + }) + async let a = service.load(CriticRatingQuery(name: "Fixture", platform: .switch)) + async let b = service.load(CriticRatingQuery(name: "Other", platform: .switch)) + _ = await (a, b) + let maximum = await activity.maximum + XCTAssertEqual(maximum, 1) + } +} diff --git a/Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift b/Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift new file mode 100644 index 00000000..a5640c7b --- /dev/null +++ b/Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift @@ -0,0 +1,170 @@ +import XCTest +@testable import NXLibraryCore + +final class DatabaseMetadataTests: XCTestCase { + private let query = CriticRatingQuery(name: "Fixture™", platform: .switch2) + private let page = URL(string: "https://gamesdb.launchbox-app.com/games/details/10-fixture")! + + private func launchBoxPage(platform: String = "Nintendo Switch 2", name: String = "Fixture", id: Int = 10) throws -> String { + var graph: [Any] = [] + func add(_ value: Any) -> Int { graph.append(value); return graph.count - 1 } + let platformName = add(platform), platformObject = add(["name": platformName]) + let genre = add("Adventure"), genreObject = add(["name": genre]), genres = add([genreObject]) + let developer = add("Studio"), developerObject = add(["name": developer]), developers = add([developerObject]) + let title = add(name), key = add(id), overview = add("A <b>description</b>."), date = add("2026-11-05") + _ = add(["gameKey": key, "name": title, "platform": platformObject, "overview": overview, + "gameGenres": genres, "gameDevelopers": developers, "gamePublishers": developers, "releaseDate": date]) + let json = String(decoding: try JSONSerialization.data(withJSONObject: graph), as: UTF8.self) + return "<script id=\"__NUXT_DATA__\" type=\"application/json\">\(json)</script>" + } + private func card(_ id: Int, title: String = "Fixture", platform: String = "Nintendo Switch 2") -> String { + "<a href=\"/games/details/\(id)-fixture\"><h3>\(title)</h3><p>\(platform)</p></a>" + } + + func testLaunchBoxChecksTheFinalIdentityAndOffersFiveFields() throws { + let result = try DatabaseMetadataParser.launchBox(in: launchBoxPage(), query: query, page: page) + let preview = try XCTUnwrap(result.preview) + XCTAssertEqual(preview.option(for: .description)?.value, "A description.") + XCTAssertEqual(preview.option(for: .genres)?.value, "Adventure") + XCTAssertEqual(preview.option(for: .developer)?.value, "Studio") + XCTAssertEqual(preview.option(for: .publisher)?.value, "Studio") + XCTAssertEqual(preview.option(for: .releaseDate)?.value, "2026-11-05") + XCTAssertEqual(preview.option(for: .description)?.source, "LaunchBox · Nintendo Switch 2") + XCTAssertEqual(try DatabaseMetadataParser.launchBox(in: launchBoxPage(id: 99), query: query, page: page).issue, .unavailable) + XCTAssertEqual(try DatabaseMetadataParser.launchBox(in: launchBoxPage(name: "Fixture II"), query: query, page: page).issue, .notFound) + } + + func testMatchingKeepsEditionsAndPrefersMacButLabelsPCWithoutBorrowingItsDate() throws { + let mac = CriticRatingQuery(name: "Fixture", platform: .mac) + let html = card(1, platform: "Windows") + card(2, platform: "Apple Mac OS") + card(3, title: "Fixture Deluxe Edition", platform: "Apple Mac OS") + XCTAssertEqual(DatabaseMetadataParser.launchBoxCandidates(in: html, query: mac).map(\.url.lastPathComponent), ["2-fixture"]) + let result = try DatabaseMetadataParser.launchBox(in: launchBoxPage(platform: "Windows"), query: mac, page: page) + XCTAssertEqual(result.preview?.option(for: .description)?.source, "LaunchBox · Windows") + XCTAssertNil(result.preview?.option(for: .releaseDate)) + let foreign = try DatabaseMetadataParser.launchBox(in: launchBoxPage(platform: "Nintendo Switch"), query: query, page: page) + XCTAssertEqual(foreign.issue, .notFound) + } + + func testTheGamesDBChecksTitlePlatformAndDateInsteadOfAnyParagraph() throws { + let html = """ + <h1>Fixture</h1><p>Platform: <a href="/platform.php?id=1">PC</a></p> + <p>Developer(s): <a>Studio</a></p><p>Publishers(s): <a>Publisher</a></p> + <p>ReleaseDate: 2026-11-05</p><p>Genre(s): Adventure | Puzzle</p> + <p class="game-overview">A & B <b>description</b>.</p> + """ + let mac = CriticRatingQuery(name: "Fixture", platform: .mac) + let url = URL(string: "https://thegamesdb.net/game.php?id=10")! + let result = DatabaseMetadataParser.theGamesDB(in: html, query: mac, page: url) + XCTAssertEqual(result.preview?.option(for: .description)?.value, "A & B description.") + XCTAssertEqual(result.preview?.option(for: .developer)?.value, "Studio") + XCTAssertEqual(result.preview?.option(for: .genres)?.value, "Adventure, Puzzle") + XCTAssertNil(result.preview?.option(for: .releaseDate)) + XCTAssertEqual(DatabaseMetadataParser.theGamesDB(in: html, query: query, page: url).issue, .notFound) + } + + func testOneFetchPerPageThenNoRequestsAcrossFieldsOrFreshReopenAndStaleWorksOffline() async throws { + actor Calls { var urls: [URL] = []; func add(_ url: URL) { urls.append(url) } } + let calls = Calls(), search = card(10), detail = try launchBoxPage() + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in + await calls.add(request.url!) + let html = request.url!.path.contains("/results/") ? search : detail + return (Data(html.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let first = await service.load(query) + XCTAssertNotNil(first.preview) + for field in MetadataField.allCases { _ = first.preview?.option(for: field) } + let next = await service.load(query) + XCTAssertEqual(next.preview, first.preview) + let urls = await calls.urls + XCTAssertEqual(urls.count, 2) + let offline = DatabaseMetadataService(database: .launchBox, directory: root, transport: { _ in throw URLError(.notConnectedToInternet) }) + let stale = await offline.load(query, now: Date().addingTimeInterval(8 * 86400)) + XCTAssertEqual(stale.preview, first.preview) + XCTAssertTrue(stale.isStale) + } + + func testAmbiguousSearchNeverDownloadsAnArbitraryGamePage() async { + let search = card(10) + card(11) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in + XCTAssertTrue(request.url!.path.contains("/results/")) + return (Data(search.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let result = await service.load(query) + XCTAssertEqual(result.issue, .ambiguous) + XCTAssertNil(result.preview) + } + + func testConcurrentReadersShareTheLookup() async throws { + actor Calls { var count = 0; func add() { count += 1 } } + let calls = Calls(), search = card(10), detail = try launchBoxPage() + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in + await calls.add() + try await Task.sleep(nanoseconds: 10_000_000) + return (Data((request.url!.path.contains("/results/") ? search : detail).utf8), + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + async let first = service.load(query) + async let second = service.load(query) + let results = await (first, second) + XCTAssertEqual(results.0.preview, results.1.preview) + let count = await calls.count + XCTAssertEqual(count, 2) + } + + func testCancellationStopsTheRequestAndDoesNotCacheAnAbsence() async throws { + let started = expectation(description: "request starts"), stopped = expectation(description: "request cancels") + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { _ in + started.fulfill() + do { try await Task.sleep(nanoseconds: 10_000_000_000); throw URLError(.timedOut) } + catch { stopped.fulfill(); throw error } + }) + let query = query + let task = Task { await service.load(query) } + await fulfillment(of: [started], timeout: 2) + task.cancel() + await fulfillment(of: [stopped], timeout: 2) + let cancelled = await task.value + XCTAssertEqual(cancelled.issue, .cancelled) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.path)) + } + + func testOversizedOrRedirectedResponsesNeverBecomeMetadataOrNegativeCache() async { + for redirected in [false, true] { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in + let url = redirected ? URL(string: "https://other.example/unexpected")! : request.url! + return (redirected ? Data() : Data(repeating: 65, count: 2_097_153), + HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let result = await service.load(query) + XCTAssertEqual(result.issue, .unavailable) + XCTAssertNil(result.preview) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.path)) + } + } + + func testFailedRefreshCanRetryWithoutANegativeCacheBlockingIt() async throws { + actor Calls { var count = 0; func next() -> Int { count += 1; return count } } + let calls = Calls(), search = card(10), detail = try launchBoxPage() + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = DatabaseMetadataService(database: .launchBox, directory: root, transport: { request in + let attempt = await calls.next() + return (Data((request.url!.path.contains("/results/") ? search : detail).utf8), + HTTPURLResponse(url: request.url!, statusCode: attempt == 1 ? 503 : 200, httpVersion: nil, headerFields: nil)!) + }) + let failed = await service.load(query) + XCTAssertEqual(failed.issue, .unavailable) + let retried = await service.load(query) + XCTAssertNotNil(retried.preview) + } +} diff --git a/Tests/NXLibraryCoreTests/DetailsFactsTests.swift b/Tests/NXLibraryCoreTests/DetailsFactsTests.swift new file mode 100644 index 00000000..cfb82ecf --- /dev/null +++ b/Tests/NXLibraryCoreTests/DetailsFactsTests.swift @@ -0,0 +1,83 @@ +import XCTest +@testable import NXLibraryCore + +final class DetailsFactsTests: XCTestCase { + private let en = Locale(identifier: "en_US") + + private func switchGame(version: String? = "1.2.0", size: Int64 = 4_000_000_000) -> PortedGame { + PortedGame(name: "Zelda", url: URL(fileURLWithPath: "/tmp/Applications/Zelda.app"), platform: .macApp, + sizeBytes: size, modificationDate: Date(timeIntervalSince1970: 0), versionString: version) + } + + private func meta(developers: [String], publishers: [String]) -> NintendoStoreMetadata { + NintendoStoreMetadata(titleId: "0100", name: "X", description: "", developers: developers, + publishers: publishers, genres: [], releaseDate: nil, + storeURL: URL(string: "https://example.com")!, imageURL: nil, + headerImageURL: nil, nsuid: nil, fetchedAt: Date(timeIntervalSince1970: 0)) + } + + private func steamFacts(appID: UInt32 = 440, developers: [String] = ["Pearl Abyss"], + publishers: [String] = ["Pearl Abyss"]) -> SteamMetadata { + SteamMetadata(appID: appID, language: "english", description: "", genres: [], developers: developers, + publishers: publishers, releaseDate: nil, screenshots: [], fetchedAt: Date(timeIntervalSince1970: 0)) + } + + private func steamGame(availability: CatalogInstallationAvailability = .available, size: Int64? = 140_000_000_000, + downloading: Bool = false) -> CatalogGame { + var game = SteamCatalogGame(appID: 440, name: "Crimson Desert") + let root = URL(fileURLWithPath: "/tmp/steam") + game.installations = [SteamCatalogInstallation(libraryURL: root, contentURL: root, availability: availability, + reportedSizeBytes: size, buildID: "123", + isDownloading: downloading)] + return CatalogGame(steam: game) + } + + func testSwitchShowsEveryRowInOrder() { + let rows = DetailsFacts.switchGame(switchGame(), metadata: meta(developers: ["Nintendo EPD"], publishers: ["Nintendo"]), + folderName: "Applications", locale: en) + XCTAssertEqual(rows.map(\.kind), [.developer, .publisher, .version, .size, .location]) + XCTAssertEqual(rows.map(\.value), ["Nintendo EPD", "Nintendo", "1.2.0", "4 GB", "Applications"]) + } + + func testSwitchHidesMissingValues() { + let rows = DetailsFacts.switchGame(switchGame(version: nil, size: 0), metadata: nil, folderName: nil, locale: en) + XCTAssertEqual(rows, []) + } + + func testBlankNamesAndVersionAreHidden() { + let rows = DetailsFacts.switchGame(switchGame(version: " "), metadata: meta(developers: [" "], publishers: ["", "Sega"]), + folderName: nil, locale: en) + XCTAssertEqual(rows.map(\.kind), [.publisher, .size]) + XCTAssertEqual(rows.first?.value, "Sega") + } + + func testSteamInstalledShowsSizeAndVolumeNeverVersion() { + let rows = DetailsFacts.steamGame(steamGame(), metadata: steamFacts(), volumeName: "Macintosh HD", locale: en) + XCTAssertEqual(rows.map(\.kind), [.developer, .publisher, .size, .location]) + XCTAssertEqual(rows.first { $0.kind == .size }?.value, "140 GB") + XCTAssertEqual(rows.first { $0.kind == .location }?.value, "Steam · Macintosh HD") + } + + func testSteamWithoutVolumeNameSaysSteam() { + let rows = DetailsFacts.steamGame(steamGame(), metadata: steamFacts(), volumeName: nil, locale: en) + XCTAssertEqual(rows.first { $0.kind == .location }?.value, "Steam") + } + + func testSteamDownloadingShowsOnlyCredits() { + let rows = DetailsFacts.steamGame(steamGame(availability: .unavailable, downloading: true), metadata: steamFacts(), + volumeName: "Macintosh HD", locale: en) + XCTAssertEqual(rows.map(\.kind), [.developer, .publisher]) + } + + func testSteamOverridesWinAndForeignFactsAreIgnored() { + let rows = DetailsFacts.steamGame(steamGame(size: nil), metadata: steamFacts(appID: 999, developers: ["Other"]), + overrides: [.developer: "Mine"], volumeName: nil, locale: en) + XCTAssertEqual(rows.map(\.kind), [.developer, .location]) + XCTAssertEqual(rows.first?.value, "Mine") + } + + func testRowsCarryTheirSymbols() { + XCTAssertEqual(DetailsFact.Kind.allCases.map { DetailsFact(kind: $0, value: "x").symbol }, + ["hammer", "building.2", "number", "internaldrive", "folder"]) + } +} diff --git a/Tests/NXLibraryCoreTests/DetailsFocusTests.swift b/Tests/NXLibraryCoreTests/DetailsFocusTests.swift index b1dd483c..ef45016f 100644 --- a/Tests/NXLibraryCoreTests/DetailsFocusTests.swift +++ b/Tests/NXLibraryCoreTests/DetailsFocusTests.swift @@ -66,6 +66,22 @@ final class DetailsFocusTests: XCTestCase { XCTAssertEqual(focus.action, 0) } + /// The Details links: three at most, one row. Down and Up leave the band; Right stops at the end. + func testThreeLinksFormOneRow() { + let links = DetailsFocus.Bands(screenshots: 2, actions: 3, more: 1) + var focus = DetailsFocus() + focus.zone = DetailsFocus.actionsZone + for _ in 0..<2 { XCTAssertTrue(focus.right(in: links)) } + XCTAssertEqual(focus.action, 2) + XCTAssertFalse(focus.right(in: links)) + XCTAssertEqual(focus.action, 2) + XCTAssertTrue(focus.down(in: links)) + XCTAssertEqual(focus.zone, DetailsFocus.moreZone) + XCTAssertTrue(focus.up(in: links)) + XCTAssertEqual(focus.zone, DetailsFocus.actionsZone) + XCTAssertEqual(focus.action, 2) + } + func testActionGridLeavesBandFromLastRow() { var focus = DetailsFocus() focus.zone = DetailsFocus.actionsZone diff --git a/Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift b/Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift new file mode 100644 index 00000000..b8634e2b --- /dev/null +++ b/Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift @@ -0,0 +1,24 @@ +import XCTest +@testable import NXLibraryCore + +final class DetailsReviewFixTests: XCTestCase { + /// Play on a game not built yet builds it when its sources are there; the page has no Build button any more. + func testPrimaryStepBuildsAnUnbuiltGameWithSources() { + XCTAssertEqual(GamePrimaryStep.decide(unavailable: false, playable: true, sourcesAvailable: false), .play) + XCTAssertEqual(GamePrimaryStep.decide(unavailable: false, playable: false, sourcesAvailable: true), .build) + XCTAssertEqual(GamePrimaryStep.decide(unavailable: false, playable: false, sourcesAvailable: false), .refuse) + XCTAssertEqual(GamePrimaryStep.decide(unavailable: true, playable: true, sourcesAvailable: true), .refuse) + } + + /// A folder or volume name is read once per URL, not on every render (a sleeping disk would block each time). + @MainActor + func testDisplayNameCacheResolvesEachURLOnce() { + var calls: [String] = [] + let cache = DisplayNameCache { url in calls.append(url.path); return url.path == "/a" ? "A" : nil } + XCTAssertEqual(cache.name(for: URL(fileURLWithPath: "/a")), "A") + XCTAssertEqual(cache.name(for: URL(fileURLWithPath: "/a")), "A") + XCTAssertNil(cache.name(for: URL(fileURLWithPath: "/b"))) + XCTAssertNil(cache.name(for: URL(fileURLWithPath: "/b"))) + XCTAssertEqual(calls, ["/a", "/b"]) + } +} diff --git a/Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift b/Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift new file mode 100644 index 00000000..7b471b77 --- /dev/null +++ b/Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift @@ -0,0 +1,114 @@ +import XCTest +@testable import NXLibraryCore + +final class DevelopmentProfileEffectTests: XCTestCase { + private func root() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("NXEffects-\(UUID())") + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: url) } + return url + } + func testAutomaticModSyncCannotOverwriteRealOverlayFromCopiedRecords() throws { + let root = try root() + let game = root.appendingPathComponent("real-game") + try FileManager.default.createDirectory(at: game.appendingPathComponent("mods/Foo/romfs"), withIntermediateDirectories: true) + let env = game.appendingPathComponent("env.txt") + let original = "DM_ROMFS_OVERLAY=/current-stable-choice\n" + try Data(original.utf8).write(to: env) + let records = root.appendingPathComponent("development-records.json") + try JSONEncoder().encode([ModRecord(folderName: "Foo", isOn: true)]).write(to: records) + let store = ModStore(supportFolder: game, recordsFile: records, titleID: "0100000000000000", canWrite: { true }, trash: { _ in XCTFail() }, allowsAutomaticMaintenance: false) + try store.sync() + XCTAssertEqual(try String(contentsOf: env), original) + try store.sync(automatic: false) + XCTAssertNotEqual(try String(contentsOf: env), original, "Explicit changes must remain possible") + } + + func testModSyncPreservesRecordsAndOverlayWhenFolderCannotBeListed() throws { + let game = try root() + try Data("not a directory".utf8).write(to: game.appendingPathComponent("mods")) + let (store, records, overlay) = try modSyncFixture(game: game) + XCTAssertThrowsError(try store.sync()) + XCTAssertEqual(try Data(contentsOf: store.recordsFile), records) + XCTAssertEqual(try Data(contentsOf: store.envFile), overlay) + } + + func testModSyncPreservesAnUnreadableRecordFileAndTheOverlay() throws { + let game = try root() + try FileManager.default.createDirectory(at: game.appendingPathComponent("mods"), withIntermediateDirectories: true) + let (store, _, overlay) = try modSyncFixture(game: game) + let broken = Data("incomplete json".utf8) + try broken.write(to: store.recordsFile) + XCTAssertThrowsError(try store.sync()) + XCTAssertEqual(try Data(contentsOf: store.recordsFile), broken) + XCTAssertEqual(try Data(contentsOf: store.envFile), overlay) + } + + func testModSyncRemovesAnEntryAbsentFromAReadableFolder() throws { + let game = try root() + try FileManager.default.createDirectory(at: game.appendingPathComponent("mods"), withIntermediateDirectories: true) + let (store, _, _) = try modSyncFixture(game: game) + try store.sync() + XCTAssertEqual(try JSONDecoder().decode([ModRecord].self, from: Data(contentsOf: store.recordsFile)), []) + XCTAssertFalse(try String(contentsOf: store.envFile).contains(ModStore.overlayKey)) + } + + private func modSyncFixture(game: URL) throws -> (ModStore, Data, Data) { + let store = ModStore(supportFolder: game, recordsFile: game.appendingPathComponent("records.json"), + titleID: "0100000000000000", canWrite: { true }, trash: { _ in XCTFail() }) + let records = try JSONEncoder().encode([ModRecord(folderName: "Foo", isOn: true)]) + let overlay = Data("DM_ROMFS_OVERLAY=/current-selection\n".utf8) + try records.write(to: store.recordsFile) + try overlay.write(to: store.envFile) + return (store, records, overlay) + } + + func testBrowsingUsesActualOverlayAndKeepsOtherProfilesInstallStaging() throws { + let root = try root() + let game = root.appendingPathComponent("game") + for name in ["Foo", "Bar", ".installing-other-profile"] { + try FileManager.default.createDirectory(at: game.appendingPathComponent("mods/" + name + "/romfs"), withIntermediateDirectories: true) + } + let env = game.appendingPathComponent("env.txt") + try Data(("DM_ROMFS_OVERLAY=" + game.appendingPathComponent("mods/Bar/romfs").path + "\n").utf8).write(to: env) + let records = root.appendingPathComponent("copied-records.json") + let original = try JSONEncoder().encode([ModRecord(folderName: "Foo", isOn: true), ModRecord(folderName: "Bar", isOn: false)]) + try original.write(to: records) + let store = ModStore(supportFolder: game, recordsFile: records, titleID: "0100000000000000", canWrite: { true }, trash: { _ in XCTFail() }, allowsAutomaticMaintenance: false) + XCTAssertEqual(store.mods().filter(\.isOn).map(\.folderName), ["Bar"]) + store.removeLeftoverInstalls() + XCTAssertTrue(FileManager.default.fileExists(atPath: game.appendingPathComponent("mods/.installing-other-profile").path)) + XCTAssertEqual(try Data(contentsOf: records), original) + } + + func testDevelopmentStartupDoesNotSweepSharedStaging() throws { + let home = try root() + let folder = home.appendingPathComponent("Games") + let dev = AppDataProfile(home: home, isDevelopment: true) + XCTAssertEqual(dev.automaticStagingFolders(appFolders: [folder]), [dev.supportRoot.appendingPathComponent("Temp")]) + let stable = AppDataProfile(home: home, isDevelopment: false) + XCTAssertTrue(stable.automaticStagingFolders(appFolders: [folder]).contains(folder.appendingPathComponent(".nxlibrary-build/Temp"))) + } + func testOnlyExplicitDevelopmentOperationsSurviveRestart() throws { + let root = try root() + let file = root.appendingPathComponent("operations.json") + let imported = UUID(), requested = UUID() + let first = DevelopmentOperationStore(file: file, isDevelopment: true) + XCTAssertFalse(first.permits(.build, gameID: imported)) + try first.authorize(.build, gameID: requested) + try first.authorize(.icon, gameID: requested) + let restarted = DevelopmentOperationStore(file: file, isDevelopment: true) + XCTAssertTrue(restarted.permits(.build, gameID: requested)) + XCTAssertTrue(restarted.permits(.icon, gameID: requested)) + XCTAssertFalse(restarted.permits(.build, gameID: imported)) + XCTAssertFalse(restarted.permits(.icon, gameID: imported)) + } + func testCorruptAuthorizationFailsClosedWithoutReplacingIt() throws { + let file = try root().appendingPathComponent("operations.json") + try Data("broken".utf8).write(to: file) + let store = DevelopmentOperationStore(file: file, isDevelopment: true) + XCTAssertFalse(store.permits(.icon, gameID: UUID())) + XCTAssertThrowsError(try store.authorize(.icon, gameID: UUID())) + XCTAssertEqual(try String(contentsOf: file), "broken") + } +} diff --git a/Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift b/Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift new file mode 100644 index 00000000..d2ed1383 --- /dev/null +++ b/Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift @@ -0,0 +1,151 @@ +import XCTest +@testable import NXLibraryCore + +final class DevelopmentProfileTests: XCTestCase { + private func fixture() throws -> (URL, AppDataProfile) { + let home = FileManager.default.temporaryDirectory.appendingPathComponent("NXProfile-\(UUID())") + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: home) } + return (home, AppDataProfile(home: home, isDevelopment: true)) + } + private func put(_ data: String, _ name: String, profile: AppDataProfile) throws { + let file = profile.stableSupportRoot.appendingPathComponent(name) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(data.utf8).write(to: file) + } + func testBuildIdentityMustSelectExactlyOneMatchingProfile() throws { + XCTAssertNoThrow(try AppData.validateBuildIdentity(["CFBundleIdentifier": "local.nxlibrary", "NXLibraryRelease": true])) + XCTAssertNoThrow(try AppData.validateBuildIdentity(["CFBundleIdentifier": "local.nxlibrary.development", "NXLibraryDevelopmentProfile": true])) + for invalid: [String: Any] in [[:], ["CFBundleIdentifier": "local.nxlibrary.development"], + ["CFBundleIdentifier": "local.nxlibrary", "NXLibraryDevelopmentProfile": true], + ["CFBundleIdentifier": "local.nxlibrary.development", "NXLibraryRelease": true], + ["CFBundleIdentifier": "local.nxlibrary", "NXLibraryRelease": true, "NXLibraryDevelopmentProfile": true]] { + XCTAssertThrowsError(try AppData.validateBuildIdentity(invalid)) + } + } + func testProfileSeparatesSupportCachesAndPreferenceDomain() throws { + let (home, dev) = try fixture() + let stable = AppDataProfile(home: home, isDevelopment: false) + XCTAssertNotEqual(dev.supportRoot, stable.supportRoot) + XCTAssertNotEqual(dev.cacheRoot, stable.cacheRoot) + XCTAssertNotEqual(dev.preferencesDomain, stable.preferencesDomain) + XCTAssertEqual(stable.supportRoot, dev.stableSupportRoot) + } + func testCopiesOnlyLauncherDataAndPreservesSourceAndIdentity() throws { + let (_, profile) = try fixture() + let id = UUID() + let game = PortedGame(id: id, name: "Personal game", url: URL(fileURLWithPath: "/Applications/Game.app"), platform: .macApp, sizeBytes: 1, modificationDate: Date()) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let encoded = try encoder.encode(LibraryFile(games: [game])) + try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true) + try encoded.write(to: profile.stableSupportRoot.appendingPathComponent("library.json")) + try put("{}", "settings.json", profile: profile) + try put("personal", "artwork-picks/own.png", profile: profile) + try put("do not copy", "keys/prod.keys", profile: profile) + try put("do not copy", "workspaces/game_build/content", profile: profile) + try put("do not copy", "steamgriddb-api-key", profile: profile) + var saved: [String: Any] = [:] + let importer = DevelopmentProfileImporter() + XCTAssertTrue(try importer.prepare(profile: profile, sourcePreferences: { ["NXLibrary_SetupCompleted": true, "NXNative_GameConfig_game": Data([1]), "AppleLanguages": ["en"], "NXLibrary_AuthToken": "synthetic"] }, savePreferences: { saved = $0 })) + XCTAssertEqual(saved["NXLibrary_SetupCompleted"] as? Bool, true) + XCTAssertNil(saved["AppleLanguages"]) + XCTAssertNil(saved["NXLibrary_AuthToken"]) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + let copied = try decoder.decode(LibraryFile.self, from: Data(contentsOf: profile.supportRoot.appendingPathComponent("library.json"))) + XCTAssertEqual(copied.games.first?.id, id) + XCTAssertEqual(copied.games.first?.url, game.url) + XCTAssertEqual(try Data(contentsOf: profile.stableSupportRoot.appendingPathComponent("library.json")), encoded) + XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.appendingPathComponent("keys").path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.appendingPathComponent("workspaces").path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.appendingPathComponent("steamgriddb-api-key").path)) + } + func testSecondImportDoesNotOverwriteDevelopmentChanges() throws { + let (_, profile) = try fixture() + try put("{}", "settings.json", profile: profile) + let importer = DevelopmentProfileImporter() + _ = try importer.prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in }) + let file = profile.supportRoot.appendingPathComponent("settings.json") + try Data(#"{"showClock":false}"#.utf8).write(to: file) + XCTAssertFalse(try importer.prepare(profile: profile, sourcePreferences: { XCTFail("must not reread source preferences"); return [:] }, savePreferences: { _ in XCTFail("must not reimport preferences") })) + XCTAssertEqual(try String(contentsOf: file), #"{"showClock":false}"#) + } + func testMalformedSourceIsNotRepairedOrActivated() throws { + let (_, profile) = try fixture() + try put("broken", "library.json", profile: profile) + XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() })) + XCTAssertEqual(try String(contentsOf: profile.stableSupportRoot.appendingPathComponent("library.json")), "broken") + XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path)) + } + func testSymlinkDoesNotCopyExternalGameData() throws { + let (home, profile) = try fixture() + let external = home.appendingPathComponent("actual-game") + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: profile.stableSupportRoot.appendingPathComponent("artwork-picks"), withDestinationURL: external) + XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in })) + XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path)) + } + func testPreferenceFailureCanResumeWithoutOverwritingSource() throws { + let (_, profile) = try fixture() + try put("{}", "settings.json", profile: profile) + let importer = DevelopmentProfileImporter() + XCTAssertThrowsError(try importer.prepare(profile: profile, sourcePreferences: { ["NXLibrary_SetupCompleted": true] }, savePreferences: { _ in throw CocoaError(.fileWriteNoPermission) })) + var saved: [String: Any] = [:] + XCTAssertTrue(try importer.prepare(profile: profile, sourcePreferences: { XCTFail("resume uses captured preferences"); return [:] }, savePreferences: { saved = $0 })) + XCTAssertEqual(saved["NXLibrary_SetupCompleted"] as? Bool, true) + XCTAssertEqual(try String(contentsOf: profile.stableSupportRoot.appendingPathComponent("settings.json")), "{}") + } + func testRefusesAnExistingUnownedDestination() throws { + let (_, profile) = try fixture() + try FileManager.default.createDirectory(at: profile.supportRoot, withIntermediateDirectories: true) + XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in XCTFail() })) + } + func testChangedSourceDoesNotActivatePartialCopy() throws { + let (_, profile) = try fixture() + try put("{}", "settings.json", profile: profile) + var reads = 0 + XCTAssertThrowsError(try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { + reads += 1 + return ["NXLibrary_SetupCompleted": reads == 1] + }, savePreferences: { _ in XCTFail("must not activate") })) + XCTAssertFalse(FileManager.default.fileExists(atPath: profile.supportRoot.path)) + } + func testUnfinishedCopiedSessionEndsAtLastHeartbeatWithoutChangingTheOriginal() throws { + let (_, profile) = try fixture() + let session = PlaySession(gameID: UUID(), titleID: "fixture", bundleID: nil, + startedAt: Date(timeIntervalSince1970: 100), lastHeartbeatAt: Date(timeIntervalSince1970: 160)) + let data = try JSONEncoder().encode([session]) + try FileManager.default.createDirectory(at: profile.stableSupportRoot, withIntermediateDirectories: true) + let original = profile.stableSupportRoot.appendingPathComponent("play-sessions.json") + try data.write(to: original) + _ = try DevelopmentProfileImporter().prepare(profile: profile, sourcePreferences: { [:] }, savePreferences: { _ in }) + let copied = try JSONDecoder().decode([PlaySession].self, from: Data(contentsOf: profile.supportRoot.appendingPathComponent("play-sessions.json"))) + XCTAssertEqual(copied.first?.id, session.id) + XCTAssertEqual(copied.first?.endedAt, session.lastHeartbeatAt) + XCTAssertEqual(copied.first?.duration, 60) + XCTAssertEqual(try Data(contentsOf: original), data) + } + func testRootsAreFoldersWhetherOrNotTheyExistYet() { + let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + for development in [false, true] { + let profile = AppDataProfile(home: home, isDevelopment: development) + for root in [profile.stableSupportRoot, profile.supportRoot, profile.cacheRoot] { + XCTAssertTrue(root.hasDirectoryPath, root.path) + XCTAssertEqual(root.appendingPathComponent("settings.json").deletingLastPathComponent(), root) + } + } + } + func testSharedAndScopedDefaultPathsAreConsistent() { + XCTAssertEqual(AppSettingsStore.defaultURL().deletingLastPathComponent(), AppData.supportRoot) + XCTAssertEqual(PlaySessionStore.defaultURL().deletingLastPathComponent(), AppData.supportRoot) + XCTAssertEqual(MetadataPicks().directory, AppData.supportRoot) + XCTAssertEqual(ArtworkStore.defaultDirectory(), AppData.supportRoot.appendingPathComponent("artwork")) + XCTAssertEqual(SteamGridDBKey.defaultURL(), AppData.supportRoot.appendingPathComponent("steamgriddb-api-key")) + } + func testReleaseProfileNeverImports() throws { + let (home, _) = try fixture() + XCTAssertFalse(try DevelopmentProfileImporter().prepare(profile: AppDataProfile(home: home, isDevelopment: false), sourcePreferences: { XCTFail(); return [:] }, savePreferences: { _ in XCTFail() })) + } +} diff --git a/Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift b/Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift new file mode 100644 index 00000000..253916c6 --- /dev/null +++ b/Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift @@ -0,0 +1,113 @@ +import XCTest +@testable import NXLibraryCore + +final class FirstRunFindingsTests: XCTestCase { + private func emptyApps() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("FirstRunApps-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: url) } + return url + } + + func testMissingSteamFolderCountsNothing() throws { + let absent = FileManager.default.temporaryDirectory.appendingPathComponent("NoSteam-\(UUID().uuidString)") + let findings = FirstRunFindings.read(steamRoot: absent, appsFolder: try emptyApps(), cancelled: { false }) + XCTAssertFalse(findings.steamReadFailed) + XCTAssertNil(findings.steamGameCount) + XCTAssertEqual(findings.portedAppCount, 0) + XCTAssertTrue(findings.isEmpty) + } + + func testOnlyNativeReadyGamesCount() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + try f.manifest(in: root, id: "20", name: "Second game", directory: "Second") + try f.app(at: "Steam/steamapps/common/Second/Game.app") + try f.manifest(in: root, id: "30", name: "Downloading", directory: "Third", stateFlags: "1026") + try f.manifest(in: root, id: "40", name: "Windows only", directory: "Fourth") + try FileManager.default.createDirectory(at: root.appendingPathComponent("steamapps/common/Fourth"), + withIntermediateDirectories: true) + let snapshot = try SteamLibrarySource(root: root).scan() + XCTAssertTrue(snapshot.games.contains { $0.state == .downloading }) + XCTAssertTrue(snapshot.games.contains { $0.state != .nativeReady && $0.state != .downloading }) + XCTAssertTrue(snapshot.isComplete) + + let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false }) + XCTAssertEqual(findings.steamGameCount, 2) + XCTAssertFalse(findings.isEmpty) + } + + func testSteamWithNoMacGamesCountsZero() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false }) + XCTAssertEqual(findings.steamGameCount, 0) + } + + func testUnreadableOrPartialSteamCountsNothing() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + let broken = try f.manifest(in: root, id: "20", name: "Broken", directory: "Second") + try Data("AppState {".utf8).write(to: broken) + let partial = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false }) + XCTAssertNil(partial.steamGameCount) + XCTAssertTrue(partial.steamReadFailed) + XCTAssertFalse(partial.isEmpty, "An incomplete read cannot establish that no games exist") + + let unreadable = try f.library("Locked") + try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: unreadable.path) + addTeardownBlock { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: unreadable.path) } + let failed = FirstRunFindings.read(steamRoot: unreadable, appsFolder: try emptyApps(), cancelled: { false }) + XCTAssertNil(failed.steamGameCount) + XCTAssertTrue(failed.steamReadFailed) + XCTAssertFalse(failed.isEmpty) + } + + func testCancelledReadStops() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { true }) + XCTAssertEqual(findings, FirstRunFindings(steamGameCount: nil, portedAppCount: 0)) + } + + func testInaccessibleAncestorIsAFailedReadRatherThanAbsentSteam() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library("Hidden/Steam") + let parent = root.deletingLastPathComponent() + try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: parent.path) + addTeardownBlock { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: parent.path) } + let findings = FirstRunFindings.read(steamRoot: root, appsFolder: try emptyApps(), cancelled: { false }) + XCTAssertTrue(findings.steamReadFailed) + XCTAssertFalse(findings.isEmpty) + } + + func testSymlinkToASteamFolderIsStillReadable() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + let link = f.root.appendingPathComponent("Steam link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: root) + let findings = FirstRunFindings.read(steamRoot: link, appsFolder: try emptyApps(), cancelled: { false }) + XCTAssertEqual(findings.steamGameCount, 0) + XCTAssertFalse(findings.steamReadFailed) + } + + func testPortedAppsAreCounted() throws { + let apps = try emptyApps() + let contents = apps.appendingPathComponent("Zelda.app/Contents") + try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true) + try PropertyListSerialization.data(fromPropertyList: [ + "CFBundleName": "Ported", "CFBundleIdentifier": "org.nxnative.01007ef00011e000", + "CFBundleShortVersionString": "1.0", "DMTitleID": "01007EF00011E000", + ], format: .xml, options: 0).write(to: contents.appendingPathComponent("Info.plist")) + let absent = FileManager.default.temporaryDirectory.appendingPathComponent("NoSteam-\(UUID().uuidString)") + let findings = FirstRunFindings.read(steamRoot: absent, appsFolder: apps, cancelled: { false }) + XCTAssertEqual(findings.portedAppCount, 1) + XCTAssertFalse(findings.isEmpty) + } +} diff --git a/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift b/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift index 39ee1ba5..9570427c 100644 --- a/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift +++ b/Tests/NXLibraryCoreTests/FirstRunSetupTests.swift @@ -2,6 +2,28 @@ import XCTest @testable import NXLibraryCore final class FirstRunSetupTests: XCTestCase { + func testSteamChoiceRestoresBothOnAndOffAfterInterruptedPorting() { + for choice in [true, false] { + var first = FirstRunSetup() + first.chooseSteam(choice) + first.openPorting() + let resumed = FirstRunSetup(completed: false, savedPage: first.pageToRemember, + savedSteamChoice: first.steamChoiceToRemember) + XCTAssertEqual(resumed.page, .requirements) + XCTAssertEqual(resumed.steamChoice, choice) + XCTAssertEqual(resumed.steamChoiceToRemember, choice) + } + } + + func testCompletedSetupDropsSavedChoiceButKeepsItUntilTheShellAppliesIt() { + var flow = FirstRunSetup(savedSteamChoice: true) + flow.finish() + XCTAssertEqual(flow.steamChoice, true) + XCTAssertNil(flow.steamChoiceToRemember) + XCTAssertNil(FirstRunSetup(completed: true, savedSteamChoice: true).steamChoice) + XCTAssertNil(FirstRunSetup().steamChoiceToRemember) + } + func testSourceReviewWaitsForASingleReadyTitleAndConsumesEachArrivalOnce() { var entry = FirstRunSetup.ReviewEntry() let id = UUID() @@ -20,8 +42,53 @@ final class FirstRunSetupTests: XCTestCase { XCTAssertFalse(entry.consume(second, isReady: true, titleCount: 1)) } - func testNewUserContinuesToGamesBeforeSetupIsCompleted() { + func testNewUserStartsOnFound() { + let flow = FirstRunSetup(completed: false) + XCTAssertEqual(flow.page, .found) + XCTAssertEqual(flow.pageToRemember, "found") + } + + func testInterruptedOldSetupResumesWhereItWas() { + XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "games").page, .games) + XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "requirements").page, .requirements) + } + + func testUnknownSavedPageStartsOnFound() { + XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "unknown").page, .found) + XCTAssertEqual(FirstRunSetup(completed: false, savedPage: nil).page, .found) + } + + func testPortingCardOpensRequirements() { var flow = FirstRunSetup(completed: false) + flow.openPorting() + XCTAssertEqual(flow.page, .requirements) + XCTAssertEqual(flow.pageToRemember, "requirements") + flow.returnToFound() + XCTAssertEqual(flow.page, .found) + } + + func testCompletedSetupNeverReturnsToFound() { + var flow = FirstRunSetup(completed: true) + XCTAssertEqual(flow.page, .requirements, "Settings → Open Setup starts on the requirements") + flow.returnToFound() + XCTAssertEqual(flow.page, .requirements) + } + + func testFocusMovesThroughFoundRows() { + typealias F = FirstRunSetup.Focus + XCTAssertEqual(F.initialOnFound, .openLibrary) + XCTAssertEqual(F.openLibrary.movedOnFound(.up, hasSteam: true), .portingCard) + XCTAssertEqual(F.portingCard.movedOnFound(.up, hasSteam: true), .steamToggle) + XCTAssertEqual(F.portingCard.movedOnFound(.up, hasSteam: false), .portingCard) + XCTAssertEqual(F.steamToggle.movedOnFound(.down, hasSteam: true), .portingCard) + XCTAssertEqual(F.portingCard.movedOnFound(.down, hasSteam: true), .openLibrary) + XCTAssertEqual(F.openLibrary.movedOnFound(.down, hasSteam: true), .openLibrary) + XCTAssertEqual(F.steamToggle.movedOnFound(.up, hasSteam: true), .steamToggle) + XCTAssertEqual(F.steamToggle.movedOnFound(.left, hasSteam: true), .steamToggle) + } + + func testNewUserContinuesToGamesBeforeSetupIsCompleted() { + var flow = FirstRunSetup(completed: false, savedPage: "requirements") XCTAssertEqual(flow.page, .requirements) flow.advance() XCTAssertEqual(flow.page, .games) @@ -63,7 +130,7 @@ final class FirstRunSetupTests: XCTestCase { func testExistingUsersIgnoreStaleOrUnknownProgress() { XCTAssertTrue(FirstRunSetup(completed: true, savedPage: "games").isCompleted) - XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "unknown").page, .requirements) + XCTAssertEqual(FirstRunSetup(completed: false, savedPage: "unknown").page, .found) } func testBackReturnsToRequirementsWithoutCompletingSetup() { @@ -107,4 +174,25 @@ final class FirstRunSetupTests: XCTestCase { let folder = SetupItem(id: .library, title: "Game apps", state: .warning, chip: "", about: "", detail: "") XCTAssertFalse(SetupCheck.shouldReopen(previous: [.library: .ready], current: [folder])) } + + func testSteamChoiceSurvivesThePortingPath() { + var setup = FirstRunSetup() + XCTAssertNil(setup.steamChoice) + setup.chooseSteam(true) + setup.openPorting() + setup.advance() + setup.goBack() + setup.returnToFound() + XCTAssertEqual(setup.steamChoice, true) + setup.chooseSteam(false) + setup.openPorting() + setup.finish() + XCTAssertEqual(setup.steamChoice, false) + } + + func testFinishedSetupTakesNoSteamChoice() { + var setup = FirstRunSetup(completed: true) + setup.chooseSteam(true) + XCTAssertNil(setup.steamChoice) + } } diff --git a/Tests/NXLibraryCoreTests/GameBananaClientTests.swift b/Tests/NXLibraryCoreTests/GameBananaClientTests.swift index 95429e02..55851877 100644 --- a/Tests/NXLibraryCoreTests/GameBananaClientTests.swift +++ b/Tests/NXLibraryCoreTests/GameBananaClientTests.swift @@ -78,7 +78,7 @@ final class GameBananaClientTests: XCTestCase { http.serve("Mod/5/ProfilePage", profile) _ = try await client().profile(modID: 5) let request = try XCTUnwrap(http.requests.first) - XCTAssertEqual(request.value(forHTTPHeaderField: "User-Agent"), "NXLibrary/0.1.4 (macOS; personal app)") + XCTAssertEqual(request.value(forHTTPHeaderField: "User-Agent"), "Arcane/0.1.4 (macOS; +https://github.com/Bium23/NxLibrary)") XCTAssertEqual(request.timeoutInterval, 15) } diff --git a/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift b/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift index 29722843..a1666b04 100644 --- a/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift +++ b/Tests/NXLibraryCoreTests/GameOptionsPresentationTests.swift @@ -24,10 +24,10 @@ final class GameOptionsPresentationTests: XCTestCase { private func presentation(renderScale: Bool = true, playable: Bool = true, detached: Bool = false, blocked: Bool = false, - store: Bool = false, bundle: Bool = false) -> GameOptionsPresentation { + store: Bool = false, search: Bool = false, bundle: Bool = false) -> GameOptionsPresentation { GameOptionsPresentation(supportsRenderScale: renderScale, isPlayable: playable, sourcesDetached: detached, toolchainBlocked: blocked, - hasStorePage: store, gameName: "Game", + hasStorePage: store, offersStoreSearch: search, gameName: "Game", appPath: "/Applications/Game.app", canDeleteBundle: bundle) } @@ -131,6 +131,18 @@ final class GameOptionsPresentationTests: XCTestCase { .storePage) } + func testEditDetailsOffersStoreSearchWhenAsked() { + let rows = presentation(search: true).focusableRows(level: .editDetails, origin: .details) + XCTAssertEqual(rows, [.changeArtwork, .changeMetadata, .searchStore, .attachSources, .openLog, .removeSources]) + XCTAssertEqual(GameOptionsRow.searchStore.title, "Search Nintendo Store") + XCTAssertEqual(presentation(store: true, search: true).focusableRows(level: .editDetails, origin: .details) + .prefix(4), [.changeArtwork, .changeMetadata, .storePage, .searchStore]) + } + + func testEditDetailsHasNoStoreSearchByDefault() { + XCTAssertFalse(presentation().focusableRows(level: .editDetails, origin: .details).contains(.searchStore)) + } + func testEditDetailsEndsWithRemoveSources() { let rows = presentation().focusableRows(level: .editDetails, origin: .details) XCTAssertEqual(rows, [.changeArtwork, .changeMetadata, .attachSources, .openLog, .removeSources]) @@ -145,7 +157,7 @@ final class GameOptionsPresentationTests: XCTestCase { for origin in [GameOptionsOrigin.spotlight, .collection, .details] { for store in [false, true] { for renderScale in [false, true] { - let p = presentation(renderScale: renderScale, store: store) + let p = presentation(renderScale: renderScale, store: store, search: store) seen.formUnion(p.focusableRows(level: .main, origin: origin)) seen.formUnion(p.focusableRows(level: .editDetails, origin: origin)) seen.formUnion(savedChoices(full: true).focusableRows(level: .main, origin: origin)) @@ -187,11 +199,11 @@ final class GameOptionsPresentationTests: XCTestCase { XCTAssertEqual(presentation(detached: true).rebuildAbout, "Game files are missing or not attached. Attach sources in Edit details.") XCTAssertEqual(presentation(blocked: true).rebuildAbout, - "Blocked by the Metal gate. See Settings → Engine.") + "Blocked by the Metal gate. See Settings → Setup and engine.") let newer = GameOptionsPresentation(supportsRenderScale: true, isPlayable: true, sourcesDetached: false, toolchainBlocked: true, - toolchainHint: "Newer Metal: turn on the override in Settings → Engine") - XCTAssertEqual(newer.rebuildAbout, "Newer Metal: turn on the override in Settings → Engine.") + toolchainHint: "Newer Metal: turn on the override in Settings → Setup and engine") + XCTAssertEqual(newer.rebuildAbout, "Newer Metal: turn on the override in Settings → Setup and engine.") XCTAssertEqual(presentation(detached: true).attachAbout, "Game files are missing or not attached. Attach them to rebuild.") XCTAssertEqual(presentation().attachAbout, diff --git a/Tests/NXLibraryCoreTests/GridListLayoutTests.swift b/Tests/NXLibraryCoreTests/GridListLayoutTests.swift new file mode 100644 index 00000000..d7e27e85 --- /dev/null +++ b/Tests/NXLibraryCoreTests/GridListLayoutTests.swift @@ -0,0 +1,51 @@ +import XCTest +@testable import NXLibraryCore + +final class GridListLayoutTests: XCTestCase { + /// Two columns of 100-point rows, 20 apart, 6 above the first and 130 kept free after the last. + private let layout = GridListLayout(columns: 2, rowHeight: 100, spacing: 20, topPad: 6, bottomRoom: 130) + + func testContentHeightCountsWholeLinesAndTheRoomAfterThem() { + XCTAssertEqual(layout.lines(count: 5), 3) + XCTAssertEqual(layout.contentHeight(count: 5), 6 + 3 * 100 + 2 * 20 + 130) + XCTAssertEqual(layout.contentHeight(count: 0), 6 + 130) + } + + func testAnIndexSitsOnItsLine() { + XCTAssertEqual(layout.top(of: 0), 6) + XCTAssertEqual(layout.top(of: 1), 6) + XCTAssertEqual(layout.top(of: 4), 6 + 2 * 120) + } + + func testRevealSpanKeepsMarginsAroundTheRow() { + XCTAssertEqual(layout.revealSpan(of: 2, above: 40, below: 130), (126 - 40)...(226 + 130)) + } + + func testVisibleLinesCoverTheWindowAndABuffer() { + // Offset 300, window 400: lines touching 300...700 are 2...5; a 120 buffer adds one each side. + XCTAssertEqual(layout.visibleLines(count: 20, offset: 300, visible: 400, buffer: 120), 1...6) + XCTAssertNil(layout.visibleLines(count: 0, offset: 0, visible: 400, buffer: 120)) + XCTAssertEqual(layout.visibleLines(count: 3, offset: 0, visible: 400, buffer: 120), 0...1) + } + + func testAFocusLeftOutOfViewMovesToTheNearestVisibleLineInItsColumn() { + // Window 300...700 with margins 40 / 130: lines whole inside 340...570 are line 3 (366...466) only. + XCTAssertEqual(layout.nearestVisible(index: 1, count: 20, offset: 300, visible: 400, above: 40, below: 130), 7) + XCTAssertEqual(layout.nearestVisible(index: 18, count: 20, offset: 300, visible: 400, above: 40, below: 130), 6) + XCTAssertNil(layout.nearestVisible(index: 6, count: 20, offset: 300, visible: 400, above: 40, below: 130)) + } + + func testANarrowWindowKeepsTheFocus() { + // No line fits whole between the margins: the focus stays and the next move reveals it. + XCTAssertNil(layout.nearestVisible(index: 0, count: 20, offset: 900, visible: 150, above: 40, below: 130)) + } + + func testAFocusInViewUnderTheMarginsKeepsTheFocus() { + // The first row at the top (6...106) sits under the top margin but in view: Up must not move the focus down. + XCTAssertNil(layout.nearestVisible(index: 0, count: 20, offset: 0, visible: 400, above: 52, below: 130)) + // A row revealed against the margin, with rounding left in the offset, is in view too. + XCTAssertNil(layout.nearestVisible(index: 6, count: 20, offset: 366 - 52 + 0.0001, visible: 400, above: 52, below: 130)) + // Half under the bottom fade, still in view. + XCTAssertNil(layout.nearestVisible(index: 8, count: 20, offset: 0, visible: 600, above: 52, below: 130)) + } +} diff --git a/Tests/NXLibraryCoreTests/IGDBMetadataTests.swift b/Tests/NXLibraryCoreTests/IGDBMetadataTests.swift new file mode 100644 index 00000000..35305bda --- /dev/null +++ b/Tests/NXLibraryCoreTests/IGDBMetadataTests.swift @@ -0,0 +1,143 @@ +import XCTest +@testable import NXLibraryCore + +final class IGDBMetadataTests: XCTestCase { + private let query = CriticRatingQuery(name: "Fixture™", platform: .switch2) + private let credentials = IGDBCredentials(clientID: "fixtureClient123456", clientSecret: "fixtureSecret123456")! + private let token = Data(#"{"access_token":"fixtureToken","expires_in":3600,"token_type":"bearer"}"#.utf8) + private let game = Data(""" + [{"id":10,"name":"Fixture","platforms":[508],"url":"https://www.igdb.com/games/fixture", + "summary":" A description. ","genres":[{"name":"Adventure"},{"name":"Puzzle"}], + "involved_companies":[{"company":{"name":"Developer"},"developer":true,"publisher":false}, + {"company":{"name":"Publisher"},"developer":false,"publisher":true}, + {"company":{"name":"Support"},"developer":false,"publisher":false}], + "release_dates":[{"platform":130,"date":1704412800,"date_format":{"format":"YYYYMMDD"}}, + {"platform":508,"date":1793836800,"date_format":{"format":"YYYYMMDD"}}]}] + """.utf8) + + func testFieldsRolesAndExactPlatformDateBecomeIndividualPreviewOptions() throws { + let result = try IGDBMetadataParser.result(in: game, query: query) + let metadata = try XCTUnwrap(result.metadata) + XCTAssertEqual(metadata.id, 10) + XCTAssertEqual(metadata.option(for: .description)?.value, "A description.") + XCTAssertEqual(metadata.option(for: .description)?.source, "IGDB") + XCTAssertEqual(metadata.option(for: .genres)?.value, "Adventure, Puzzle") + XCTAssertEqual(metadata.option(for: .developer)?.value, "Developer") + XCTAssertEqual(metadata.option(for: .publisher)?.value, "Publisher") + XCTAssertEqual(metadata.option(for: .releaseDate)?.value, "2026-11-05") + XCTAssertEqual(try JSONDecoder().decode(IGDBMetadata.self, from: JSONEncoder().encode(metadata)), metadata) + } + + func testPartialDatesForeignPlatformsAndOtherEditionsAreNotInvented() throws { + let partial = Data(String(decoding: game, as: UTF8.self).replacingOccurrences(of: "YYYYMMDD", with: "YYYYMM").utf8) + XCTAssertNil(try IGDBMetadataParser.result(in: partial, query: query).metadata?.option(for: .releaseDate)) + let foreign = CriticRatingQuery(name: "Fixture", platform: .switch) + XCTAssertEqual(try IGDBMetadataParser.result(in: game, query: foreign).issue, .notFound) + XCTAssertEqual(try IGDBMetadataParser.result(in: game, query: .init(name: "Fixture II", platform: .switch2)).issue, .notFound) + let duplicate = Data(("[" + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "," + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "]").utf8) + XCTAssertEqual(try IGDBMetadataParser.result(in: duplicate, query: query).issue, .ambiguous) + let empty = Data(#"[{"id":10,"name":"Fixture","platforms":[508],"url":"https://www.igdb.com/games/fixture"}]"#.utf8) + XCTAssertNil(try IGDBMetadataParser.result(in: empty, query: query).metadata?.option(for: .description)) + XCTAssertThrowsError(try IGDBMetadataParser.result(in: Data("{}".utf8), query: query)) + } + + func testSteamIdentityUsesTheExternalIDWithoutBorrowingAPortsReleaseDate() throws { + let nested = String(decoding: game, as: UTF8.self).dropFirst().dropLast() + let external = Data(("[{\"uid\":\"42\",\"external_game_source\":{\"name\":\"Steam\"},\"game\":" + nested + "}]").utf8) + let steam = CriticRatingQuery(name: "Personal name", platform: .mac, steamAppID: 42) + let result = try IGDBMetadataParser.steamResult(in: external, query: steam) + XCTAssertEqual(result.metadata?.option(for: .description)?.value, "A description.") + XCTAssertNil(result.metadata?.option(for: .releaseDate)) + XCTAssertEqual(try IGDBMetadataParser.steamResult(in: external, query: .init(name: "Fixture", platform: .mac, steamAppID: 99)).issue, .notFound) + } + + func testCacheRemainsAvailableOfflineAndNeverChangesPersonalPicks() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let token = token, game = game + let service = IGDBMetadataService(directory: root, transport: { request in + if request.url!.host == "api.igdb.com" { + let body = String(decoding: request.httpBody ?? Data(), as: UTF8.self) + XCTAssertTrue(body.contains("involved_companies.developer")) + XCTAssertTrue(body.contains("release_dates.date_format.format")) + } + return (request.url!.host == "id.twitch.tv" ? token : game, + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let found = await service.load(query, credentials: credentials) + XCTAssertEqual(found.metadata?.id, 10) + let offline = IGDBMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) }) + let retained = await offline.load(query, credentials: credentials, now: Date().addingTimeInterval(8 * 86400)) + XCTAssertEqual(retained.metadata, found.metadata) + XCTAssertTrue(retained.isStale) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("metadata-picks.json").path)) + } + + func testCancellationDoesNotSaveAMissingMatch() async throws { + let started = expectation(description: "request starts"), stopped = expectation(description: "request stops") + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = IGDBMetadataService(directory: root, transport: { _ in + started.fulfill() + do { try await Task.sleep(nanoseconds: 10_000_000_000); throw URLError(.timedOut) } + catch { stopped.fulfill(); throw error } + }) + let query = query, credentials = credentials + let task = Task { await service.load(query, credentials: credentials) } + await fulfillment(of: [started], timeout: 2) + task.cancel() + await fulfillment(of: [stopped], timeout: 2) + let result = await task.value + XCTAssertNil(result.metadata) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.path)) + } + + func testFailureDoesNotBecomeANegativeCacheAndCanBeRetried() async throws { + actor Calls { + var games = 0 + func next() -> Int { games += 1; return games } + } + let calls = Calls(), token = token, game = game + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = IGDBMetadataService(directory: root, transport: { request in + if request.url!.host == "id.twitch.tv" { + return (token, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } + let count = await calls.next() + return (count == 1 ? Data("private server details".utf8) : game, + HTTPURLResponse(url: request.url!, statusCode: count == 1 ? 503 : 200, httpVersion: nil, headerFields: nil)!) + }) + let failed = await service.load(query, credentials: credentials) + XCTAssertEqual(failed.issue, .unavailable) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.path)) + let retried = await service.load(query, credentials: credentials) + XCTAssertEqual(retried.metadata?.id, 10) + } + + func testSharedClientSerializesDifferentLookupsAndReusesOneToken() async throws { + actor Calls { + var tokens = 0, active = 0, maximum = 0 + func begin(_ token: Bool) { + if token { tokens += 1 } + active += 1; maximum = max(maximum, active) + } + func end() { active -= 1 } + } + let calls = Calls(), token = token + let client = IGDBClient(transport: { request in + let isToken = request.url!.host == "id.twitch.tv" + await calls.begin(isToken) + try await Task.sleep(nanoseconds: 10_000_000) + await calls.end() + return (isToken ? token : Data("[]".utf8), + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + async let games = client.request("games", body: "fields id; limit 1;", credentials: credentials) + async let external = client.request("external_games", body: "fields id; limit 1;", credentials: credentials) + _ = try await (games, external) + let tokens = await calls.tokens, maximum = await calls.maximum + XCTAssertEqual(tokens, 1) + XCTAssertEqual(maximum, 1) + } +} diff --git a/Tests/NXLibraryCoreTests/IGDBRatingTests.swift b/Tests/NXLibraryCoreTests/IGDBRatingTests.swift new file mode 100644 index 00000000..7716db18 --- /dev/null +++ b/Tests/NXLibraryCoreTests/IGDBRatingTests.swift @@ -0,0 +1,343 @@ +import XCTest +@testable import NXLibraryCore + +final class IGDBRatingTests: XCTestCase { + private let credentials = IGDBCredentials(clientID: "fixtureClient123456", clientSecret: "fixtureSecret123456")! + private let query = CriticRatingQuery(name: "Fixture™", platform: .switch) + private let token = Data("{\"access_token\":\"fixtureToken\",\"expires_in\":3600,\"token_type\":\"bearer\"}".utf8) + private let game = Data(""" + [{"id":10,"name":"Fixture","aggregated_rating":83.5,"aggregated_rating_count":12, + "rating":99,"total_rating":96,"platforms":[130],"url":"https://www.igdb.com/games/fixture"}] + """.utf8) + private func response(_ request: URLRequest, _ data: Data, status: Int = 200) -> (Data, HTTPURLResponse) { + (data, HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!) + } + func testPersonalCredentialsStayPrivateAndAreNotSettings() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let store = IGDBCredentialsStore(url: root.appendingPathComponent("igdb.json")) + XCTAssertNil(store.load()) + try store.save(credentials) + XCTAssertEqual(store.load(), credentials) + let permissions = try FileManager.default.attributesOfItem(atPath: store.url.path)[.posixPermissions] as? Int + XCTAssertEqual(permissions, 0o600) + XCTAssertNil(IGDBCredentials(clientID: " bad id ", clientSecret: "secret")) + XCTAssertNil(IGDBCredentials(clientID: "valid123", clientSecret: "Bearer token")) + try store.remove() + XCTAssertNil(store.load()) + } + func testSavingTightensAnExistingCredentialsFolder() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let folder = root.appendingPathComponent("credentials") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o755]) + let store = IGDBCredentialsStore(url: folder.appendingPathComponent("igdb.json")) + try store.save(credentials) + let permissions = try FileManager.default.attributesOfItem(atPath: folder.path)[.posixPermissions] as? Int + XCTAssertEqual(permissions, 0o700) + } + + func testCriticAverageWinsWithoutMixingCommunityScores() throws { + let rating = try XCTUnwrap(IGDBRatings.rating(in: game, query: query)) + XCTAssertEqual(rating.source, .igdb) + XCTAssertEqual(rating.score, 83.5) + XCTAssertEqual(rating.reviewCount, 12) + XCTAssertEqual(rating.sourceURL.absoluteString, "https://www.igdb.com/games/fixture") + XCTAssertEqual(rating.starFills.reduce(0,+), 4.175, accuracy: 0.0001) + XCTAssertNil(rating.entityID) + XCTAssertFalse(rating.isCommunity) + let userOnly = Data("[{\"id\":10,\"name\":\"Fixture\",\"rating\":99,\"rating_count\":100,\"platforms\":[130]}]".utf8) + XCTAssertNil(try IGDBRatings.rating(in: userOnly, query: query)) + } + + func testCriticAverageNeedsThreeReviews() throws { + // Two critics are not a critic consensus: fall back to the explicit user average, or to nothing. + let few = Data(""" + [{"id":10,"name":"Fixture","aggregated_rating":95,"aggregated_rating_count":2, + "rating":71,"rating_count":40,"platforms":[130],"url":"https://www.igdb.com/games/fixture"}] + """.utf8) + let rating = try XCTUnwrap(IGDBRatings.rating(in: few, query: query)) + XCTAssertTrue(rating.isCommunity) + XCTAssertEqual(rating.score, 71) + let criticsOnly = Data(""" + [{"id":10,"name":"Fixture","aggregated_rating":95,"aggregated_rating_count":2, + "platforms":[130],"url":"https://www.igdb.com/games/fixture"}] + """.utf8) + XCTAssertNil(try IGDBRatings.rating(in: criticsOnly, query: query)) + let three = Data(String(decoding: criticsOnly, as: UTF8.self) + .replacingOccurrences(of: "\"aggregated_rating_count\":2", with: "\"aggregated_rating_count\":3").utf8) + XCTAssertEqual(try IGDBRatings.rating(in: three, query: query)?.isCommunity, false) + // A critic score saved before the minimum is no longer a valid cache entry. + let saved = CriticRating(score: 95, source: .igdb, igdbID: 10, + igdbURL: URL(string: "https://www.igdb.com/games/fixture"), reviewCount: 2) + XCTAssertFalse(saved.isValid) + let users = CriticRating(score: 71, source: .igdb, igdbID: 10, + igdbURL: URL(string: "https://www.igdb.com/games/fixture"), reviewCount: 1, audience: .users) + XCTAssertTrue(users.isValid) + } + + func testCommunityFallbackIsDistinctAndRequiresACountAndProvenance() throws { + let entry = Data(""" + [{"id":405460,"name":"The Legend of Zelda: Ocarina of Time","platforms":[508], + "rating":99.65387466304598,"rating_count":35, + "url":"https://www.igdb.com/games/the-legend-of-zelda-ocarina-of-time--1"}] + """.utf8) + let query = CriticRatingQuery(name: "The Legend of Zelda™: Ocarina of Time", platform: .switch2) + let rating = try XCTUnwrap(IGDBRatings.rating(in: entry, query: query)) + XCTAssertTrue(rating.isCommunity) + XCTAssertEqual(rating.reviewCount, 35) + XCTAssertEqual(rating.score, 99.65387466304598) + XCTAssertEqual(rating.labelKey, "User score") + XCTAssertEqual(rating.attribution(context: .init(language: .italian, region: "IT")), "Utenti · IGDB") + XCTAssertEqual(try JSONDecoder().decode(CriticRating.self, from: JSONEncoder().encode(rating)), rating) + let noVotes = Data(String(decoding: entry, as: UTF8.self).replacingOccurrences(of: "\"rating_count\":35", with: "\"rating_count\":0").utf8) + XCTAssertNil(try IGDBRatings.rating(in: noVotes, query: query)) + let invalid = Data(String(decoding: entry, as: UTF8.self).replacingOccurrences(of: "99.65387466304598", with: "101").utf8) + XCTAssertNil(try IGDBRatings.rating(in: invalid, query: query)) + } + + func testLegacyCriticCacheDecodesAndFreshLegacyMissRetriesForCommunity() async throws { + let rating = try XCTUnwrap(IGDBRatings.rating(in: game, query: query)) + var legacy = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(rating)) as? [String: Any]) + legacy.removeValue(forKey: "audience") + let decoded = try JSONDecoder().decode(CriticRating.self, from: JSONSerialization.data(withJSONObject: legacy)) + XCTAssertFalse(decoded.isCommunity) + XCTAssertTrue(decoded.isValid) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + let key = IGDBCredentials.digest(credentials.clientID + String(decoding: try encoder.encode(query), as: UTF8.self)) + let old: [String: Any] = ["query": ["name": query.name, "platform": "switch"], "fetchedAt": Date().timeIntervalSinceReferenceDate] + try JSONSerialization.data(withJSONObject: old).write(to: root.appendingPathComponent(key + ".json")) + let token = token + let community = Data(""" + [{"id":10,"name":"Fixture","platforms":[130],"rating":70,"rating_count":8,"url":"https://www.igdb.com/games/fixture"}] + """.utf8) + let service = IGDBRatingService(directory: root, transport: { request in + if request.url!.host == "api.igdb.com" { + let body = String(decoding: request.httpBody ?? Data(), as: UTF8.self) + XCTAssertTrue(body.contains(",rating,rating_count,")) + } + return (request.url!.host == "id.twitch.tv" ? token : community, + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let found = await service.load(query, credentials: credentials) + XCTAssertEqual(found.rating?.isCommunity, true) + let offline = IGDBRatingService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) }) + let saved = await offline.load(query, credentials: credentials, now: Date().addingTimeInterval(8 * 86400)) + XCTAssertEqual(saved.rating, found.rating) + XCTAssertTrue(saved.isStale) + var oldCriticCache = old + oldCriticCache["rating"] = legacy + try JSONSerialization.data(withJSONObject: oldCriticCache).write(to: root.appendingPathComponent(key + ".json")) + let retainedCritic = await offline.load(query, credentials: credentials) + XCTAssertEqual(retainedCritic.rating?.score, decoded.score) + XCTAssertEqual(retainedCritic.rating?.isCommunity, false) + XCTAssertFalse(retainedCritic.isStale) + } + func testExactTitleAliasAndPlatformWithoutSequelOrAmbiguity() throws { + let otherPlatform = Data(String(decoding: game, as: UTF8.self).replacingOccurrences(of: "[130]", with: "[6]").utf8) + XCTAssertNil(try IGDBRatings.rating(in: otherPlatform, query: query)) + XCTAssertNil(try IGDBRatings.rating(in: game, query: .init(name: "Fixture II", platform: .switch))) + let duplicate = Data(("[" + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "," + String(decoding: game, as: UTF8.self).dropFirst().dropLast() + "]").utf8) + XCTAssertNil(try IGDBRatings.rating(in: duplicate, query: query)) + } + + func testRatingQueryUsesTheGamesConsoleAndPreservesLegacySwitchIdentity() throws { + var game = PortedGame(name: "Fixture", url: URL(fileURLWithPath: "/tmp/Fixture.app"), + platform: .macApp, sizeBytes: 1, modificationDate: Date(), titleId: "0100000000000000") + XCTAssertEqual(CriticRatingQuery(game: game).platform, .switch) + game.titleId = "0400000000000000" + let query = CriticRatingQuery(game: game, name: "Official Fixture") + XCTAssertEqual(query.platform, .switch2) + XCTAssertEqual(query.name, "Official Fixture") + XCTAssertNil(query.steamAppID) + XCTAssertEqual(try JSONDecoder().decode(CriticRatingQuery.self, + from: Data(#"{"name":"Fixture","platform":"switch"}"#.utf8)).platform, .switch) + XCTAssertEqual(try JSONDecoder().decode(CriticRatingQuery.self, from: JSONEncoder().encode(query)), query) + } + + func testSameTitleOnDifferentConsolesSelectsOnlyTheRequestedEdition() throws { + // Synthetic scores: the important regression is identity, not a live game's current rating. + let games = Data(""" + [{"id":1,"name":"Fixture","platforms":[4],"aggregated_rating":99,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/original"}, + {"id":2,"name":"Fixture","platforms":[508],"aggregated_rating":85,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/remake"}, + {"id":3,"name":"Fixture","platforms":[130],"aggregated_rating":80,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/switch-edition"}] + """.utf8) + XCTAssertEqual(try IGDBRatings.rating(in: games, query: .init(name: "Fixture™", platform: .switch2))?.igdbID, 2) + XCTAssertEqual(try IGDBRatings.rating(in: games, query: query)?.igdbID, 3) + XCTAssertNil(try IGDBRatings.rating(in: games, query: .init(name: "Fixture", platform: .mac))) + let originalOnly = Data(""" + [{"id":1,"name":"Fixture","platforms":[4],"aggregated_rating":99,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/original"}] + """.utf8) + XCTAssertNil(try IGDBRatings.rating(in: originalOnly, query: .init(name: "Fixture", platform: .switch2))) + } + + func testSwitch2RetriesDespiteLegacySwitchMissAndCachesItsOwnResult() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let token = token, query = query + let old = IGDBRatingService(directory: root, transport: { request in + let data = request.url!.host == "id.twitch.tv" ? token : Data("[]".utf8) + return (data, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let missed = await old.load(query, credentials: credentials) + XCTAssertNil(missed.rating) + XCTAssertNotNil(missed.fetchedAt) + let switch2 = CriticRatingQuery(name: query.name, platform: .switch2) + let game = Data(String(decoding: game, as: UTF8.self).replacingOccurrences(of: "[130]", with: "[508]").utf8) + let fixed = IGDBRatingService(directory: root, transport: { request in + let data = request.url!.host == "id.twitch.tv" ? token : game + return (data, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let found = await fixed.load(switch2, credentials: credentials) + XCTAssertEqual(found.rating?.score, 83.5) + let cached = IGDBRatingService(directory: root, transport: { _ in + XCTFail("Fresh results for either console must remain cached separately") + throw URLError(.notConnectedToInternet) + }) + let retained = await cached.load(switch2, credentials: credentials) + XCTAssertEqual(retained.rating, found.rating) + let priorMiss = await cached.load(query, credentials: credentials) + XCTAssertNil(priorMiss.rating) + XCTAssertEqual(priorMiss.fetchedAt, missed.fetchedAt) + } + func testTokenAndAPIHostsAreIsolatedAndOfflineCacheSurvives() async throws { + actor Requests { + var items: [URLRequest] = [] + func add(_ request: URLRequest) { items.append(request) } + } + let requests = Requests(), token = token, game = game + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = IGDBRatingService(directory: root, transport: { request in + await requests.add(request) + let data = request.url!.host == "id.twitch.tv" ? token : game + return (data, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let first = await service.load(query, credentials: credentials) + XCTAssertEqual(first.rating?.score, 83.5) + let all = await requests.items + XCTAssertEqual(all.map { $0.url!.host! }, ["id.twitch.tv", "api.igdb.com"]) + XCTAssertNil(all[0].url!.query) + XCTAssertTrue(String(decoding: all[0].httpBody!, as: UTF8.self).contains("client_secret=")) + XCTAssertNil(all[0].value(forHTTPHeaderField: "Authorization")) + XCTAssertEqual(all[1].value(forHTTPHeaderField: "Authorization"), "Bearer fixtureToken") + XCTAssertFalse(String(decoding: all[1].httpBody!, as: UTF8.self).contains("fixtureSecret")) + let offline = IGDBRatingService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) }) + let retained = await offline.load(query, credentials: credentials, now: Date().addingTimeInterval(8*86400)) + XCTAssertEqual(retained.rating, first.rating) + XCTAssertTrue(retained.isStale) + } + func testRejectedCredentialsAreNotSuccessfulChecks() async throws { + let service = IGDBRatingService(transport: { request in + (Data("{\"message\":\"secret response must never be shown\"}".utf8), + HTTPURLResponse(url: request.url!, statusCode: 401, httpVersion: nil, headerFields: nil)!) + }) + do { try await service.check(credentials); XCTFail("Rejected credentials must fail") } + catch { XCTAssertEqual(error as? IGDBError, .rejected) } + } + func testSettingsSearchFindsIGDBInGeneralAPIServices() { + XCTAssertEqual(SettingsCatalog.search("IGDB").first { $0.id == "igdb" }?.group, .apiServices) + } + + func testExpiredOrRevokedTokenRenewsOnceAndConcurrentReadersShareWork() async throws { + actor Calls { + var tokens = 0, games = 0 + func next(isToken: Bool) -> Int { + if isToken { tokens += 1; return tokens } + games += 1; return games + } + } + let calls = Calls(), token = token, game = game + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = IGDBRatingService(directory: root, transport: { request in + let isToken = request.url!.host == "id.twitch.tv" + let count = await calls.next(isToken: isToken) + let status = !isToken && count == 1 ? 401 : 200 + return (isToken ? token : game, HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!) + }) + async let a = service.load(query, credentials: credentials) + async let b = service.load(query, credentials: credentials) + let values = await (a,b) + XCTAssertEqual(values.0.rating?.score, 83.5) + XCTAssertEqual(values.0.rating, values.1.rating) + let tokens = await calls.tokens, games = await calls.games + XCTAssertEqual(tokens, 2); XCTAssertEqual(games, 2) + } + + func testCancellationStopsCredentialTransmissionAndDoesNotCacheAbsence() async throws { + let started = expectation(description: "token started"), stopped = expectation(description: "token cancelled") + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = IGDBRatingService(directory: root, transport: { _ in + started.fulfill() + do { try await Task.sleep(nanoseconds: 10_000_000_000); throw IGDBError.unreachable } + catch { stopped.fulfill(); throw error } + }) + let task = Task { await service.load(query, credentials: credentials) } + await fulfillment(of: [started], timeout: 2) + task.cancel() + await fulfillment(of: [stopped], timeout: 2) + let result = await task.value + XCTAssertNil(result.rating) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.path)) + } + + func testWikidataRemainsTheFallbackWithFailedOrRemovedCredentials() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let wiki = CriticRatingService(directory: root.appendingPathComponent("wiki"), transport: { url in + if url.query?.contains("wbsearchentities") == true { + return Data("{\"search\":[{\"id\":\"Q10\",\"label\":\"Fixture\"}]}".utf8) + } + return Data(""" + {"entities":{"Q10":{"claims":{"P31":[{"mainsnak":{"datavalue":{"value":{"id":"Q7889"}}}}], + "P444":[{"id":"Q10$s","mainsnak":{"datavalue":{"value":"78/100"}}, + "qualifiers":{"P447":[{"datavalue":{"value":{"id":"Q21039459"}}}],"P459":[{"datavalue":{"value":{"id":"Q114712322"}}}]}, + "references":[{"snaks":{"P248":[{"datavalue":{"value":{"id":"Q21039459"}}}]}}]}]}}}} + """.utf8) + }) + let primary = IGDBRatingService(directory: root.appendingPathComponent("igdb"), transport: { _ in throw URLError(.notConnectedToInternet) }) + let fallback = await wiki.preferred(query, credentials: credentials, igdb: primary) + XCTAssertEqual(fallback.rating?.source, .openCritic) + let removed = await wiki.preferred(query, credentials: nil, igdb: primary) + XCTAssertEqual(removed.rating, fallback.rating) + + let token = token + let users = Data(""" + [{"id":10,"name":"Fixture","platforms":[130],"rating":99,"rating_count":35,"url":"https://www.igdb.com/games/fixture"}] + """.utf8) + let community = IGDBRatingService(directory: root.appendingPathComponent("community"), transport: { request in + (request.url!.host == "id.twitch.tv" ? token : users, + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let criticsFirst = await wiki.preferred(query, credentials: credentials, igdb: community) + XCTAssertEqual(criticsFirst.rating?.source, .openCritic) + let criticGame = game + let critic = IGDBRatingService(directory: root.appendingPathComponent("critic"), transport: { request in + (request.url!.host == "id.twitch.tv" ? token : criticGame, + HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + }) + let igdbFirst = await wiki.preferred(query, credentials: credentials, igdb: critic) + XCTAssertEqual(igdbFirst.rating?.source, .igdb) + XCTAssertEqual(igdbFirst.rating?.score, 83.5) + let missing = CriticRatingService(directory: root.appendingPathComponent("missing"), transport: { _ in Data("{\"search\":[]}".utf8) }) + let usersLast = await missing.preferred(query, credentials: credentials, igdb: community) + XCTAssertEqual(usersLast.rating?.isCommunity, true) + let removedUsers = await missing.preferred(query, credentials: nil, igdb: community) + XCTAssertNil(removedUsers.rating) + } + + func testSteamExternalMappingUsesItsSourceAndIDNotASimilarTitle() throws { + let entry = """ + [{"uid":"42","external_game_source":{"name":"Steam"},"game": + {"id":10,"name":"Official title","aggregated_rating":80,"aggregated_rating_count":3,"url":"https://www.igdb.com/games/official"}}] + """ + XCTAssertEqual(try IGDBRatings.steamRating(in: Data(entry.utf8), appID: 42)?.score, 80) + XCTAssertNil(try IGDBRatings.steamRating(in: Data(entry.utf8), appID: 99)) + XCTAssertNil(try IGDBRatings.steamRating(in: Data(entry.replacingOccurrences(of: "Steam", with: "GOG").utf8), appID: 42)) + } +} diff --git a/Tests/NXLibraryCoreTests/ImportServiceTests.swift b/Tests/NXLibraryCoreTests/ImportServiceTests.swift index 27d90ff0..5429f7f4 100644 --- a/Tests/NXLibraryCoreTests/ImportServiceTests.swift +++ b/Tests/NXLibraryCoreTests/ImportServiceTests.swift @@ -17,22 +17,23 @@ final class ImportServiceTests: XCTestCase { bundleId: "org.nxnative.new", appURL: newURL, sizeBytes: 200, modificationDate: Date(timeIntervalSince1970: 2)) let service = ImportService() - let store = LibraryStore(directory: root.appendingPathComponent("Catalog")) - _ = try store.merge(scanned: [service.makeGame(from: old)]) - let selected = service.appsForLibrary(scanned: [newer, old], existing: try store.load().games) + let store = CatalogRepository(store: CatalogStore(directory: root.appendingPathComponent("Catalog"))) + try store.configureSource(.nxnative, enabled: true, root: nil) + _ = try store.mergeNXNative(scanned: [service.makeGame(from: old)]) + let selected = service.appsForLibrary(scanned: [newer, old], existing: try store.load().nxnativeGames) XCTAssertEqual(selected.count, 1) - let library = try store.merge(scanned: selected.map { service.makeGame(from: $0) }) - let game = try XCTUnwrap(library.games.first) + let library = try store.mergeNXNative(scanned: selected.map { service.makeGame(from: $0) }) + let game = try XCTUnwrap(library.nxnativeGames.first) XCTAssertEqual(game.url, oldURL) XCTAssertEqual(game.name, "Installed") XCTAssertEqual(game.versionString, "1.0") XCTAssertEqual(game.modificationDate, Date(timeIntervalSince1970: 1)) XCTAssertEqual(selected.first?.sizeBytes, 100) // A different chosen folder does not silently switch an existing installed app. - XCTAssertTrue(service.appsForLibrary(scanned: [newer], existing: library.games).isEmpty) + XCTAssertTrue(service.appsForLibrary(scanned: [newer], existing: library.nxnativeGames).isEmpty) // If the old app is actually removed, the discovered build can replace its reference. try FileManager.default.removeItem(at: oldURL) - XCTAssertEqual(service.appsForLibrary(scanned: [newer], existing: library.games).first?.appURL, newURL) + XCTAssertEqual(service.appsForLibrary(scanned: [newer], existing: library.nxnativeGames).first?.appURL, newURL) // A new title with multiple builds starts with the newest scan result, once. XCTAssertEqual(service.appsForLibrary(scanned: [newer, old], existing: []).count, 1) } diff --git a/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift b/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift index 9f8ebd48..c15616f2 100644 --- a/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift +++ b/Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift @@ -62,13 +62,13 @@ final class LaunchBoxArtTests: XCTestCase { return page(fixed + shots + [("Fanart - Background", "World", "fanart.jpg", "fanart-full.jpg", 1920, 1080), ("Square", "World", "r2_square.jpg", "r2_square-full.jpg", 950, 950)]) } - static let search = "https://gamesdb.launchbox-app.com/games/results/Donkey%20Kong%20Bananza" + static let search = "https://gamesdb.launchbox-app.com/games/results/donkey%20kong%20bananza" static let details = "https://gamesdb.launchbox-app.com/games/details/424483-donkey-kong-bananza" func testSearchURLKeepsTheNameInThePath() { XCTAssertEqual(LaunchBoxArt.searchURL(for: "Donkey Kong Bananza")?.absoluteString, Self.search) XCTAssertEqual(LaunchBoxArt.searchURL(for: "Fate/Samurai")?.absoluteString, - "https://gamesdb.launchbox-app.com/games/results/Fate%2FSamurai") + "https://gamesdb.launchbox-app.com/games/results/fate%2Fsamurai") XCTAssertNil(LaunchBoxArt.searchURL(for: " ")) } @@ -86,6 +86,19 @@ final class LaunchBoxArtTests: XCTestCase { XCTAssertNil(LaunchBoxArt.pick(snes, names: ["Donkey Kong Bananza"], switch2: false, loose: true), "even typed") } + func testAMacGameTakesItsComputerEntryNeverAConsoleOne() { + let results = LaunchBoxArt.results(in: Self.card("3-ps", "The Witcher 3: Wild Hunt", "Sony Playstation 4") + + Self.card("2-sw", "The Witcher 3: Wild Hunt", "Nintendo Switch") + + Self.card("1-win", "The Witcher 3: Wild Hunt", "Windows")) + XCTAssertEqual(LaunchBoxArt.pick(results, names: ["The Witcher 3: Wild Hunt"], computer: true)?.path, "/games/details/1-win") + let both = LaunchBoxArt.results(in: Self.card("1-win", "Fixture", "Windows") + Self.card("4-mac", "Fixture", "Apple Mac OS")) + XCTAssertEqual(LaunchBoxArt.pick(both, names: ["Fixture"], computer: true)?.path, "/games/details/4-mac", "the Mac entry first") + let consoles = LaunchBoxArt.results(in: Self.card("2-sw", "Fixture", "Nintendo Switch")) + XCTAssertNil(LaunchBoxArt.pick(consoles, names: ["Fixture"], computer: true, loose: true)) + XCTAssertEqual(LaunchBoxArt.pick(results, names: ["The Witcher 3: Wild Hunt"], switch2: false)?.path, "/games/details/2-sw", + "a Switch game still takes the Switch entry") + } + func testATypedNameTakesTheFirstSwitchResult() { let results = LaunchBoxArt.results(in: Self.card("2-y", "Mario Kart 64", "Nintendo 64") + Self.card("1-x", "Super Mario Odyssey", "Nintendo Switch")) diff --git a/Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift b/Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift new file mode 100644 index 00000000..422e19f3 --- /dev/null +++ b/Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift @@ -0,0 +1,65 @@ +import XCTest +@testable import NXLibraryCore + +final class MoonlightAppearanceTests: XCTestCase { + func testRemovedParticlePreferenceIsIgnoredWithoutLosingOtherSettings() throws { + for value in [nil, "soft", "crystal", "future-effect"] as [String?] { + var object = try JSONSerialization.jsonObject(with: JSONEncoder().encode(AppSettings())) as! [String: Any] + object["soundVolume"] = 0.25 + object["particleStyle"] = value + let decoded = try JSONDecoder().decode(AppSettings.self, from: JSONSerialization.data(withJSONObject: object)) + XCTAssertEqual(decoded.soundVolume, 0.25) + let saved = try JSONSerialization.jsonObject(with: JSONEncoder().encode(decoded)) as! [String: Any] + XCTAssertNil(saved["particleStyle"]) + } + } + + func testLookHasNoParticleChoice() { + XCTAssertFalse(SettingsCatalog.all.contains { $0.id == "particleStyle" }) + } + + func testColorCycleIsContinuousBoundedAndSpatial() { + let period = MoonlightChromatics.period + for t: Float in [0, 1, 8, 16, 24.999] { + let color = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: t) + let looped = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: t + period) + for i in 0..<3 { + XCTAssertTrue((0...1).contains(color[i])) + XCTAssertEqual(color[i], looped[i], accuracy: 0.00001) + } + } + let near = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: period - 0.0001) + let after = MoonlightChromatics.sample(x: 0.4, y: 0.6, time: period + 0.0001) + for i in 0..<3 { XCTAssertEqual(near[i], after[i], accuracy: 0.0001) } + XCTAssertNotEqual(MoonlightChromatics.sample(x: 0, y: 0, time: 0), + MoonlightChromatics.sample(x: 1, y: 1, time: 0)) + } + + func testLocalColorsStayNearTheirOwnHueOverTheWholeCycle() { + let positions: [(Float, Float)] = [(0.18,0.77),(0.84,0.43),(0.5,0.3)] + for (x,y) in positions { + let initial = MoonlightChromatics.sample(x: x, y: y, time: 0) + for t in stride(from: Float(0), to: 180, by: 5) { + let value = MoonlightChromatics.sample(x: x, y: y, time: t) + for k in 0..<3 { XCTAssertLessThan(abs(value[k]-initial[k]), 0.025) } + } + } + let pink = MoonlightChromatics.sample(x: 0.18, y: 0.77, time: 0) + let cyan = MoonlightChromatics.sample(x: 0.84, y: 0.43, time: 0) + XCTAssertGreaterThan(pink.x, cyan.x) + XCTAssertGreaterThan(cyan.y, pink.y) + } + + func testThemeGridStopsAtItsEdgesBeforeTheBackgroundStep() { + var state = ThemePickerState(themeIndex: 11, backgroundIndex: 0) + XCTAssertFalse(state.move(.down, count: 12)) + XCTAssertEqual(state.step, .theme) + XCTAssertFalse(state.move(.right, count: 12)) + XCTAssertEqual(state.themeIndex, 11) + XCTAssertTrue(state.move(.up, count: 12)) + XCTAssertEqual(state.themeIndex, 6) + state.step = .background + XCTAssertTrue(state.move(.right, count: 4)) + XCTAssertEqual(state.backgroundIndex, 1) + } +} diff --git a/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift b/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift index 27ac5cb5..5a922677 100644 --- a/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift +++ b/Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift @@ -164,13 +164,6 @@ final class MoreArtworkSourcesTests: XCTestCase { // MARK: - TheGamesDB - private let gamesDBSearch = """ - <a href="./game.php?id=105796"><div class="card"><img src="x"><div class="card-footer bg-secondary"> - <p>Hollow Knight: Silksong</p><p class="text-muted">Nintendo Switch</p></div></div></a> - <a href="./game.php?id=56105"><div class="card"><img src="x"><div class="card-footer bg-secondary"> - <p>Hollow Knight</p><p>NTSC</p><p class="text-muted">Nintendo Switch</p></div></div></a> - """ - private let gamesDBGame = """ <a href="https://cdn.thegamesdb.net/images/original/boxart/front/56105-1.jpg"><img src="https://cdn.thegamesdb.net/images/thumb/boxart/front/56105-1.jpg"></a> <a href="https://cdn.thegamesdb.net/images/original/clearlogo/56105-1.png">logo</a> @@ -184,15 +177,6 @@ final class MoreArtworkSourcesTests: XCTestCase { <a href="https://cdn.thegamesdb.net/images/original/clearlogo/99999-1.png">another game</a> """ - func testTheGamesDBSearchesSwitchGamesAndTakesTheSameName() { - let url = TheGamesDBArt.searchURL(for: "Hollow Knight™") - XCTAssertEqual(query(url)["name"], "Hollow Knight") - XCTAssertEqual(query(url)["platform_id[]"], "4971", "Nintendo Switch") - XCTAssertEqual(TheGamesDBArt.gameID(in: gamesDBSearch, matching: ["Hollow Knight"]), 56105) - XCTAssertNil(TheGamesDBArt.gameID(in: gamesDBSearch, matching: ["Celeste"])) - XCTAssertEqual(TheGamesDBArt.gameURL(id: 56105).absoluteString, "https://thegamesdb.net/game.php?id=56105") - } - func testTheGamesDBGivesItsClearLogoCoverFanartAndScreenshots() { let list = TheGamesDBArt.candidates(in: gamesDBGame, id: 56105) let base = "https://cdn.thegamesdb.net/images/original/" @@ -204,6 +188,23 @@ final class MoreArtworkSourcesTests: XCTestCase { XCTAssertTrue(list.allSatisfy { $0.source.hasPrefix("TheGamesDB") }) } + func testTheGamesDBArtworkForMacUsesVerifiedPCFallbackInsteadOfConsole() async throws { + let client = RoutedClient(), query = CriticRatingQuery(name: "Fixture", platform: .mac) + let mac = try XCTUnwrap(DatabaseMetadataParser.gamesDBSearch(query: query, platform: "Mac OS")) + let pc = try XCTUnwrap(DatabaseMetadataParser.gamesDBSearch(query: query, platform: "PC")) + client.routes[mac.absoluteString] = Data("<p>TheGamesDB: no results</p>".utf8) + client.routes[pc.absoluteString] = Data(""" + <a href="game.php?id=10"><div class="card-footer"><p>Fixture</p><p class="text-muted">PC</p></div></a> + """.utf8) + client.routes[TheGamesDBArt.gameURL(id: 10).absoluteString] = Data(""" + <h1>Fixture</h1><p>Platform: <a href="/platform.php?id=1">PC</a></p> + <img src="https://cdn.thegamesdb.net/images/original/boxart/front/10-1.jpg"> + """.utf8) + let found = await TheGamesDBArt.find(names: ["Fixture"], platform: .mac, client: client) + XCTAssertEqual(found.map(\.slot), [.cover]) + XCTAssertEqual(found.first?.url.absoluteString, "https://cdn.thegamesdb.net/images/original/boxart/front/10-1.jpg") + } + // MARK: - Fan wikis func testFanWikisAreSearchedLikeCommons() { diff --git a/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift b/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift index b8c10d86..4122831d 100644 --- a/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift +++ b/Tests/NXLibraryCoreTests/MoreLikeThisTests.swift @@ -50,4 +50,42 @@ final class MoreLikeThisTests: XCTestCase { let data = [me.id: meta(genres: ["Other"]), other.id: meta(genres: ["other"])] XCTAssertEqual(MoreLikeThis.pick(for: me, in: [me, other], metadata: { data[$0] }), []) } + + func testSteamUsesTheSameRankingAndOnlyVisibleSteamGames() { + let current = CatalogGame(steam: .init(appID: 10, name: "Current")) + let maker = CatalogGame(steam: .init(appID: 11, name: "Bravo")) + let genres = CatalogGame(steam: .init(appID: 12, name: "Alpha")) + var hidden = CatalogGame(steam: .init(appID: 13, name: "Hidden")) + hidden.setHidden(true) + let nx = CatalogGame(nxnative: game("Native")) + let all = [current, maker, genres, hidden, nx] + let own = MoreLikeThis.Traits(developers: ["Studio"], genres: ["Action", "Puzzle"]) + let facts: [UUID: MoreLikeThis.Traits] = [ + current.id: own, maker.id: .init(publishers: [" studio "]), + genres.id: .init(genres: ["action", "puzzle"]), hidden.id: own, nx.id: own + ] + XCTAssertEqual(MoreLikeThis.pick(for: current, in: all, traits: { facts[$0.id] }), [genres.id, maker.id]) + XCTAssertEqual(MoreLikeThis.pick(for: current, in: all, traits: { facts[$0.id] }, limit: 1), [genres.id]) + XCTAssertEqual(MoreLikeThis.pick(for: current, in: all, traits: { _ in nil }), []) + } + + func testSteamFallsBackToGenuinelyRelatedGamesFromOtherSources() { + let steam = CatalogGame(steam: .init(appID: 10, name: "Current")) + let otherSteam = CatalogGame(steam: .init(appID: 11, name: "Steam candidate")) + let related = CatalogGame(nxnative: game("Related")) + let hidden = CatalogGame(nxnative: game("Hidden", hidden: true)) + let different = CatalogGame(nxnative: game("Unrelated")) + let candidates = [steam, otherSteam, related, hidden, different] + let action = MoreLikeThis.Traits(genres: ["Action"]) + let racing = MoreLikeThis.Traits(genres: ["Racing"]) + var facts = [steam.id: action, otherSteam.id: racing, related.id: action, hidden.id: action, different.id: racing] + func picks() -> [UUID] { + MoreLikeThis.pick(for: steam, in: candidates, fallbackToOtherSources: true, traits: { facts[$0.id] }) + } + XCTAssertEqual(picks(), [related.id]) + facts[otherSteam.id] = action + XCTAssertEqual(picks(), [otherSteam.id], "A matching Steam game keeps precedence") + facts[steam.id] = nil + XCTAssertTrue(picks().isEmpty) + } } diff --git a/Tests/NXLibraryCoreTests/MultiuserSaveTests.swift b/Tests/NXLibraryCoreTests/MultiuserSaveTests.swift new file mode 100644 index 00000000..c5c471a3 --- /dev/null +++ b/Tests/NXLibraryCoreTests/MultiuserSaveTests.swift @@ -0,0 +1,230 @@ +import XCTest +@testable import NXLibraryCore + +final class MultiuserSaveTests: XCTestCase { + private func seed(_ prefix: String, _ h: SaveTestHome, _ location: SaveLocation) throws { + for slot in [SaveSlot.account, .device, .user2, .user8] { + try h.write(prefix + "-" + slot.rawValue, location.directory(slot).appendingPathComponent("progress")) + } + try h.write("nxnative-users-1\n" + prefix, location.directory(.users)) + } + + func testBackupIncludesRegistryAndAllCommittedUsersAndVerifiesTampering() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("saved", h, location) + try h.write("uncommitted", location.root.appendingPathComponent("save_user3.work/progress")) + let snapshot = try store.create(location: location, identity: h.identity, reason: .manual) + XCTAssertEqual(snapshot.schemaVersion, 2) + XCTAssertEqual(snapshot.presentSlots, [.account, .device, .user2, .user8, .users]) + let registry = try XCTUnwrap(snapshot.entries.first { $0.slot == .users }) + XCTAssertEqual(registry.path, "") + XCTAssertFalse(registry.isDirectory) + XCTAssertEqual(try store.verify(snapshotID: snapshot.id, titleID: h.tid), snapshot) + let backup = try store.directory(snapshotID: snapshot.id, titleID: h.tid) + try h.write("tampered", backup.appendingPathComponent("save.users")) + XCTAssertThrowsError(try store.verify(snapshotID: snapshot.id, titleID: h.tid)) + } + + func testRestoreAllUsersAndRegistryAndRemoveUsersAbsentFromNewBackup() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("target", h, location) + let target = try store.create(location: location, identity: h.identity, reason: .manual) + try seed("current", h, location) + try h.write("new user", location.directory(.user3).appendingPathComponent("progress")) + let safety = try SaveTransaction(store: store, isRunning: { false }).restore(target, location: location, identity: h.identity) + XCTAssertEqual(safety.schemaVersion, 2) + XCTAssertTrue(safety.presentSlots.contains(.user3)) + XCTAssertFalse(SaveFiles.exists(location.directory(.user3))) + XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), "target-user2") + XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\ntarget") + } + + func testLegacyRestorePreservesAdditionalUsersAndRegistry() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try h.write("legacy", location.directory(.account).appendingPathComponent("progress")) + let legacy = try store.create(location: location, identity: h.identity, reason: .manual) + XCTAssertEqual(legacy.schemaVersion, 1) + try seed("current", h, location) + try SaveTransaction(store: store, isRunning: { false }).restore(legacy, location: location, identity: h.identity) + XCTAssertEqual(try String(contentsOf: location.directory(.account).appendingPathComponent("progress")), "legacy") + XCTAssertFalse(SaveFiles.exists(location.directory(.device))) + XCTAssertEqual(try String(contentsOf: location.directory(.user8).appendingPathComponent("progress")), "current-user8") + XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\ncurrent") + } + + func testImportPreservesOtherUsersAndRegistryAndRefusesRegistryAsAnImportTarget() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("current", h, location) + let source = h.base.appendingPathComponent("external") + try h.write("imported", source.appendingPathComponent("progress")) + XCTAssertThrowsError(try store.stageImport(source: source, slot: .users, location: location)) + let preview = try store.stageImport(source: source, slot: .account, location: location) + try SaveTransaction(store: store, isRunning: { false }).importSave(preview, location: location, identity: h.identity) + XCTAssertEqual(try String(contentsOf: location.directory(.account).appendingPathComponent("progress")), "imported") + XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), "current-user2") + XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\ncurrent") + } + + func testRegistryMutationInvalidatesRestorePreview() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("before", h, location) + let snapshot = try store.create(location: location, identity: h.identity, reason: .manual) + let preview = try store.stageRestore(snapshot, location: location) + try h.write("changed outside Arcane", location.directory(.users)) + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }).restore(preview, location: location, identity: h.identity)) + XCTAssertEqual(try String(contentsOf: location.directory(.users)), "changed outside Arcane") + try store.discardRestore(preview, location: location) + } + + func testEveryMultiuserCheckpointRecoversWithoutChangingUncommittedData() throws { + for checkpoint in ["journal"] + SaveSlot.allCases.map(\.rawValue) + ["committed"] { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("target", h, location) + let target = try store.create(location: location, identity: h.identity, reason: .manual) + try seed("current", h, location) + try h.write("working", location.root.appendingPathComponent("save_user2.work/file")) + var io = SaveFileIO() + io.afterMutation = { if $0 == checkpoint { throw SaveFailure.io("Interrupted") } } + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io) + .restore(target, location: location, identity: h.identity), checkpoint) + let restarted = SaveTransaction(store: store, isRunning: { false }) + try restarted.recover(location: location) + try restarted.recover(location: location) + let prefix = checkpoint == "committed" ? "target" : "current" + XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), prefix + "-user2", checkpoint) + XCTAssertEqual(try String(contentsOf: location.directory(.users)), "nxnative-users-1\n" + prefix, checkpoint) + XCTAssertEqual(try String(contentsOf: location.root.appendingPathComponent("save_user2.work/file")), "working") + } + } + + func testLegacyRecoveryPreservesUsersCreatedAfterInterruption() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + let account = location.directory(.account).appendingPathComponent("progress") + try h.write("target", account) + let snapshot = try store.create(location: location, identity: h.identity, reason: .manual) + try h.write("original", account) + var io = SaveFileIO() + io.afterMutation = { if $0 == "account" { throw SaveFailure.io("Interrupted") } } + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io) + .restore(snapshot, location: location, identity: h.identity)) + try h.write("external", location.directory(.user2).appendingPathComponent("progress")) + try h.write("registry", location.directory(.users)) + try SaveTransaction(store: store, isRunning: { false }).recover(location: location) + XCTAssertEqual(try String(contentsOf: account), "original") + XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), "external") + XCTAssertEqual(try String(contentsOf: location.directory(.users)), "registry") + } + + func testRegistryDirectoryAndLinkAndOversizedFileAreRefused() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + let registry = location.directory(.users) + try FileManager.default.createDirectory(at: registry, withIntermediateDirectories: true) + XCTAssertThrowsError(try store.create(location: location, identity: h.identity, reason: .manual)) + try FileManager.default.removeItem(at: registry) + try FileManager.default.createSymbolicLink(at: registry, withDestinationURL: h.home) + XCTAssertThrowsError(try store.create(location: location, identity: h.identity, reason: .manual)) + try FileManager.default.removeItem(at: registry) + try Data(repeating: 0, count: 65537).write(to: registry) + XCTAssertThrowsError(try store.create(location: location, identity: h.identity, reason: .manual)) + } + + func testSchemaOneCannotClaimOrHideNewComponents() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("original", h, location) + let snapshot = try store.create(location: location, identity: h.identity, reason: .manual) + let folder = try store.directory(snapshotID: snapshot.id, titleID: h.tid) + let manifest = folder.appendingPathComponent("manifest.json") + var json = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: manifest)) as? [String: Any]) + json["schemaVersion"] = 1 + try JSONSerialization.data(withJSONObject: json).write(to: manifest) + XCTAssertThrowsError(try store.verify(snapshotID: snapshot.id, titleID: h.tid)) + } + + func testLateRegistryEditIsNotOverwrittenAndJournalIsKept() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("target", h, location) + let target = try store.create(location: location, identity: h.identity, reason: .manual) + try seed("original", h, location) + var io = SaveFileIO() + io.afterMutation = { if $0 == "before-users" { try h.write("external", location.directory(.users)) } } + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io) + .restore(target, location: location, identity: h.identity)) + XCTAssertTrue(SaveTransaction.needsRecovery(location: location)) + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }).recover(location: location)) + XCTAssertEqual(try String(contentsOf: location.directory(.users)), "external") + } + + func testChangedDisplacedRegistryIsNeverDeletedDuringCleanupOrRecovery() throws { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("target", h, location) + let target = try store.create(location: location, identity: h.identity, reason: .manual) + try seed("original", h, location) + var displaced: URL? + var io = SaveFileIO() + io.afterMutation = { checkpoint in + guard checkpoint == "users" else { return } + let journal = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: + location.root.appendingPathComponent(".nxlibrary-save-transaction.json"))) as? [String: Any]) + let id = try XCTUnwrap(journal["id"] as? String) + let file = location.root.appendingPathComponent(".nxlibrary-save-transaction-" + id).appendingPathComponent("users") + try h.write("changed open inode", file) + displaced = file + } + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io) + .restore(target, location: location, identity: h.identity)) + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }).recover(location: location)) + XCTAssertEqual(try String(contentsOf: XCTUnwrap(displaced)), "changed open inode") + XCTAssertTrue(SaveTransaction.needsRecovery(location: location)) + } + + func testInterruptedPartialCleanupRecoversAfterCommitOrRollback() throws { + for committed in [true, false] { + let h = try SaveTestHome(); defer { h.remove() } + let location = try h.location(), store = SaveSnapshotStore(root: h.backups) + try seed("target", h, location) + let target = try store.create(location: location, identity: h.identity, reason: .manual) + try seed("original", h, location) + func partlyRemoveStaging() throws { + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: + location.root.appendingPathComponent(".nxlibrary-save-transaction.json"))) as? [String: Any]) + let id = try XCTUnwrap(json["id"] as? String) + let file = location.root.appendingPathComponent(".nxlibrary-save-transaction-" + id) + .appendingPathComponent("account/progress") + try FileManager.default.removeItem(at: file) + } + var io = SaveFileIO() + io.afterMutation = { + if $0 == (committed ? "committed" : "users") { + if committed { try partlyRemoveStaging() } + throw SaveFailure.io("Interrupted") + } + } + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: io) + .restore(target, location: location, identity: h.identity)) + if !committed { + var recoveryIO = SaveFileIO() + recoveryIO.afterMutation = { + if $0 == "recovery-users" { try partlyRemoveStaging(); throw SaveFailure.io("Interrupted rollback cleanup") } + } + XCTAssertThrowsError(try SaveTransaction(store: store, isRunning: { false }, io: recoveryIO).recover(location: location)) + } + let restarted = SaveTransaction(store: store, isRunning: { false }) + try restarted.recover(location: location) + try restarted.recover(location: location) + XCTAssertFalse(SaveTransaction.needsRecovery(location: location)) + XCTAssertEqual(try String(contentsOf: location.directory(.user2).appendingPathComponent("progress")), + (committed ? "target" : "original") + "-user2") + } + } +} diff --git a/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift b/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift index 50da7eda..9a38aaf6 100644 --- a/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift +++ b/Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift @@ -2,6 +2,88 @@ import XCTest @testable import NXLibraryCore final class NUPSourceCatalogTests: XCTestCase { + private let editionProbe = "title 0400F00000010001\napplication 0100F00000010000\naoc_base 0100F00000011000\nname 546573742047616d65\nbase 272\nupdate 5 280\ndlc 0100F00000011001 2\n" + + func testEditionKeepsSelectedProgramApplicationAndDLCIdentitySeparate() throws { + let game = try NUPSourceCatalog.parse(editionProbe, nup: dir.appendingPathComponent("Edition.nup"), + fileSize: 400, profiles: dir.appendingPathComponent("profiles"), provisional: true) + let selection = try XCTUnwrap(game.base?.nupProgram) + XCTAssertEqual(game.baseTitleId, 0x0400F00000010001) + XCTAssertEqual(selection.programID, game.baseTitleId) + XCTAssertEqual(selection.applicationID, 0x0100F00000010000) + XCTAssertEqual(selection.addOnContentBaseID, 0x0100F00000011000) + XCTAssertEqual(selection.index, 1) + XCTAssertEqual(game.dlcs.first?.titleId, 0x0100F00000011001) + XCTAssertTrue(game.allSources.allSatisfy { $0.nupProgram == selection }) + let updateOnly = try NUPSourceCatalog.parse(editionProbe.replacingOccurrences(of: "base 272\n", with: ""), + nup: dir.appendingPathComponent("Edition.nup"), fileSize: 400, + profiles: dir.appendingPathComponent("profiles"), provisional: true) + XCTAssertNil(updateOnly.base) + XCTAssertEqual(updateOnly.updates.first?.nupProgram, selection) + XCTAssertTrue(updateOnly.hasGame) + } + + func testPartialDuplicateAndMalformedProgramMetadataAreRefused() { + for output in [editionProbe.replacingOccurrences(of: "aoc_base 0100F00000011000\n", with: ""), + editionProbe + "application 0100F00000010000\n", + editionProbe.replacingOccurrences(of: "aoc_base 0100F00000011000", with: "aoc_base 0"), + editionProbe.replacingOccurrences(of: "application 0100F00000010000", with: "application not-hex"), + editionProbe.replacingOccurrences(of: "dlc 0100F00000011001", with: "dlc 0400F00000011001")] { + XCTAssertThrowsError(try NUPSourceCatalog.parse(output, nup: dir.appendingPathComponent("Edition.nup"), + fileSize: 400, profiles: dir.appendingPathComponent("profiles"), provisional: true)) + } + } + + func testProgramMetadataPersistsAndOldSourcesRemainReadable() throws { + let selection = NUPProgramSelection(programID: 0x0400F00000010001, + applicationID: 0x0100F00000010000, addOnContentBaseID: 0x0100F00000011000) + let source = GameFileItem(url: dir.appendingPathComponent("Edition.nup"), kind: .base, + titleId: "0400F00000010001", sizeBytes: 400, sourceLayout: .container, nupProgram: selection) + let saved = try JSONEncoder().encode(source) + XCTAssertEqual(try JSONDecoder().decode(GameFileItem.self, from: saved).nupProgram, selection) + var legacy = try XCTUnwrap(JSONSerialization.jsonObject(with: saved) as? [String: Any]) + legacy.removeValue(forKey: "nupProgram") + XCTAssertNil(try JSONDecoder().decode(GameFileItem.self, + from: JSONSerialization.data(withJSONObject: legacy)).nupProgram) + XCTAssertFalse(SourceSelection.supported([source], titleSelection: true, extractedFolders: true, nupContainers: true)) + XCTAssertTrue(SourceSelection.supported([source], titleSelection: true, extractedFolders: true, + nupContainers: true, nupPrograms: true)) + var conflict = source + conflict.nupProgram = NUPProgramSelection(programID: 0x0400F00000010002, + applicationID: selection.applicationID, addOnContentBaseID: selection.addOnContentBaseID) + XCTAssertFalse(SourceSelection.supported([source, conflict], titleSelection: true, extractedFolders: true, + nupContainers: true, nupPrograms: true)) + XCTAssertFalse(SourceSelection.matchesNUPProgram([source], titleID: "0100F00000010000")) + XCTAssertTrue(SourceSelection.matchesNUPProgram([source], titleID: "0400F00000010001")) + } + + func testCandidateBuildExplicitlySelectsProgramZeroForLegacyNUPRecords() throws { + let legacy = GameFileItem(url: dir.appendingPathComponent("Game.nup"), kind: .base, + titleId: "0100F00000010000", sizeBytes: 400, sourceLayout: .container) + XCTAssertEqual(SourceSelection.programIndex(for: [legacy], titleID: "0100F00000010000", nupPrograms: true), 0) + XCTAssertNil(SourceSelection.programIndex(for: [legacy], titleID: "0100F00000010000", nupPrograms: false)) + let repo = dir.appendingPathComponent("engine") + let command = BuildCommandBuilder.make(repo: repo, + toolchain: EngineToolchain(python: dir.appendingPathComponent("python"), extraPath: [], isBundled: true), + workspace: dir, keys: nil, output: dir.appendingPathComponent("Game.app"), developerDir: dir, + titleId: "0400F00000010001", programIndex: 1) + let args = command.arguments + XCTAssertEqual(args[try XCTUnwrap(args.firstIndex(of: "--program")) + 1], "1") + XCTAssertEqual(args[try XCTUnwrap(args.firstIndex(of: "--title-id")) + 1], "0400F00000010001") + XCTAssertTrue(EngineSourceCapabilities(script: "'--title-id'\nimport pack_nup\npack_nup.scan(n, program)").nupPrograms) + XCTAssertFalse(EngineSourceCapabilities(script: "'--title-id'\nimport pack_nup\npack_nup.scan(n)").nupPrograms) + } + + func testLegacyNUPSourcesMustStillBeOnePhysicalContainer() { + let first = GameFileItem(url: dir.appendingPathComponent("First.nup"), kind: .base, + titleId: "0100F00000010000", sizeBytes: 400, sourceLayout: .container) + let second = GameFileItem(url: dir.appendingPathComponent("Second.nup"), kind: .update, + titleId: "0100F00000010800", sizeBytes: 400, sourceLayout: .container) + XCTAssertFalse(SourceSelection.supported([first, second], titleSelection: true, + extractedFolders: true, nupContainers: true, nupPrograms: true)) + XCTAssertNil(SourceSelection.programIndex(for: [first, second], titleID: "0100F00000010000", nupPrograms: true)) + } + private var dir: URL! override func setUpWithError() throws { diff --git a/Tests/NXLibraryCoreTests/LibraryStoreTests.swift b/Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift similarity index 64% rename from Tests/NXLibraryCoreTests/LibraryStoreTests.swift rename to Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift index 30d64bce..5fea0f71 100644 --- a/Tests/NXLibraryCoreTests/LibraryStoreTests.swift +++ b/Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift @@ -1,7 +1,7 @@ import XCTest @testable import NXLibraryCore -final class LibraryStoreTests: XCTestCase { +final class NXNativeCatalogPersistenceTests: XCTestCase { private var dir: URL! override func setUpWithError() throws { @@ -15,7 +15,8 @@ final class LibraryStoreTests: XCTestCase { } func testExplicitSelectionReplacesExistingSourcesAndSurvivesLaterScans() throws { - let store = LibraryStore(directory: dir.appendingPathComponent("catalog")) + let store = CatalogRepository(store: CatalogStore(directory: dir.appendingPathComponent("catalog"))) + try store.configureSource(.nxnative, enabled: true, root: nil) let app = dir.appendingPathComponent("Game.app") try FileManager.default.createDirectory(at: app.appendingPathComponent("Contents"), withIntermediateDirectories: true) try Data("plist".utf8).write(to: app.appendingPathComponent("Contents/Info.plist")) @@ -30,13 +31,13 @@ final class LibraryStoreTests: XCTestCase { old.sources = [GameFileItem(url: oldSource, kind: .base, sizeBytes: 3)] old.workspacePath = dir.appendingPathComponent("old-workspace").path old.buildCachePath = dir.appendingPathComponent("old-cache").path - try store.save(LibraryFile(games: [old])) + try store.updateNXNativeGames { $0 = [old] } var selected = old selected.url = dir.appendingPathComponent("new-workspace") selected.sources = [GameFileItem(url: newSource, kind: .base, sizeBytes: 3)] selected.workspacePath = selected.url.path selected.buildCachePath = dir.appendingPathComponent("new-cache").path - let result = try XCTUnwrap(try store.merge(scanned: [selected], replacingSources: true).games.first) + let result = try XCTUnwrap(try store.mergeNXNative(scanned: [selected], replacingSources: true).nxnativeGames.first) XCTAssertEqual(result.sources, selected.sources) XCTAssertEqual(result.workspacePath, selected.workspacePath) XCTAssertEqual(result.buildCachePath, selected.buildCachePath) @@ -46,13 +47,14 @@ final class LibraryStoreTests: XCTestCase { XCTAssertTrue(result.isFavorite) var scanned = selected scanned.sources = [] - let refreshed = try XCTUnwrap(try store.merge(scanned: [scanned]).games.first) + let refreshed = try XCTUnwrap(try store.mergeNXNative(scanned: [scanned]).nxnativeGames.first) XCTAssertEqual(refreshed.sources, selected.sources) XCTAssertTrue(FileManager.default.fileExists(atPath: oldSource.path), "Replacing a selection never deletes sources") } - func testSaveLoadAndMergePreservesSettings() throws { - let store = LibraryStore(directory: dir) + func testCatalogSaveLoadAndMergePreservesSettings() throws { + let store = CatalogRepository(store: CatalogStore(directory: dir)) + try store.configureSource(.nxnative, enabled: true, root: nil) var game = PortedGame( name: "The Legend of Zelda: Breath of the Wild", url: URL(fileURLWithPath: "/tmp/game.app"), @@ -65,35 +67,36 @@ final class LibraryStoreTests: XCTestCase { ) game.status = .builtSourcesMissing game.settings.metalHUD = true - try store.save(LibraryFile(schemaVersion: 1, games: [game])) + try store.updateNXNativeGames { $0 = [game] } let loaded = try store.load() - XCTAssertEqual(loaded.games.first?.status, .builtSourcesMissing) - XCTAssertEqual(loaded.games.first?.settings.metalHUD, true) + XCTAssertEqual(loaded.nxnativeGames.first?.status, .builtSourcesMissing) + XCTAssertEqual(loaded.nxnativeGames.first?.settings.metalHUD, true) var scanned = game scanned.status = .built scanned.settings = GameRuntimeConfig() - let merged = try store.merge(scanned: [scanned]) - XCTAssertEqual(merged.games.first?.status, .built) - XCTAssertEqual(merged.games.first?.settings.metalHUD, true) - XCTAssertEqual(merged.games.count, 1) + let merged = try store.mergeNXNative(scanned: [scanned]) + XCTAssertEqual(merged.nxnativeGames.first?.status, .built) + XCTAssertEqual(merged.nxnativeGames.first?.settings.metalHUD, true) + XCTAssertEqual(merged.nxnativeGames.count, 1) } func testMergeKeepsFavoriteAndHidden() throws { - let store = LibraryStore(directory: dir) + let store = CatalogRepository(store: CatalogStore(directory: dir)) + try store.configureSource(.nxnative, enabled: true, root: nil) var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/g.app"), platform: .macApp, sizeBytes: 1, modificationDate: Date(timeIntervalSince1970: 1), titleId: "0100000000000001") game.isFavorite = true game.isHidden = true - try store.save(LibraryFile(schemaVersion: 1, games: [game])) + try store.updateNXNativeGames { $0 = [game] } var scanned = game scanned.isFavorite = false scanned.isHidden = false - let merged = try store.merge(scanned: [scanned]) - XCTAssertEqual(merged.games.first?.isFavorite, true) - XCTAssertEqual(merged.games.first?.isHidden, true) + let merged = try store.mergeNXNative(scanned: [scanned]) + XCTAssertEqual(merged.nxnativeGames.first?.isFavorite, true) + XCTAssertEqual(merged.nxnativeGames.first?.isHidden, true) } func testRepeatedScansKeepPendingInstallAndFailureDetails() throws { @@ -106,7 +109,8 @@ final class LibraryStoreTests: XCTestCase { try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) .write(to: app.appendingPathComponent("Contents/Info.plist")) let importer = ImportService() - let store = LibraryStore(directory: dir.appendingPathComponent("store")) + let store = CatalogRepository(store: CatalogStore(directory: dir.appendingPathComponent("store"))) + try store.configureSource(.nxnative, enabled: true, root: nil) var game = try XCTUnwrap(importer.scan(directories: [apps]).first.map { importer.makeGame(from: $0) }) game.isFavorite = true game.settings.metalHUD = true @@ -115,13 +119,13 @@ final class LibraryStoreTests: XCTestCase { toolchain: ToolchainInfo(engineCommit: "2716f78")) game.portingFailure = .failed game.portingFailureReason = PortingFailureReason(kind: .diskFull, detail: "Synthetic failure") - try store.save(LibraryFile(games: [game])) + try store.updateNXNativeGames { $0 = [game] } for _ in 0..<3 { let scanned = importer.scan(directories: [apps]).map { importer.makeGame(from: $0) } - let merged = try store.merge(scanned: scanned) - let saved = try XCTUnwrap(store.load().games.first) - XCTAssertEqual(merged.games.count, 1) + let merged = try store.mergeNXNative(scanned: scanned) + let saved = try XCTUnwrap(store.load().nxnativeGames.first) + XCTAssertEqual(merged.nxnativeGames.count, 1) XCTAssertEqual(saved.id, game.id) XCTAssertEqual(saved.pendingInstall, game.pendingInstall) XCTAssertEqual(saved.portingFailure, game.portingFailure) @@ -131,49 +135,9 @@ final class LibraryStoreTests: XCTestCase { } } - func testCorruptFileRestoresBackup() throws { - let store = LibraryStore(directory: dir) - var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/g.app"), - platform: .macApp, sizeBytes: 1, modificationDate: Date()) - game.titleId = "0100000000010000" - try store.save(LibraryFile(schemaVersion: 1, games: [game])) - try Data("not json".utf8).write(to: store.fileURL) - let recovered = try store.load() - XCTAssertEqual(recovered.games.count, 1) - - // Saving the recovered value must not replace the good backup with the - // corrupt main file. Corrupt the main again and recover again. - try store.save(recovered) - try Data("still not json".utf8).write(to: store.fileURL) - XCTAssertEqual(try store.load().games.count, 1) - } - - /// A library that cannot be read and has no backup is moved aside, never written over by the next save: the - /// games in it can still be recovered by hand (or by a newer NX Library that reads it). - func testUnreadableLibraryWithoutBackupIsKeptAside() throws { - let store = LibraryStore(directory: dir) - let damaged = Data(#"{"schemaVersion": 1, "games": [{"name": "#.utf8) - try damaged.write(to: store.fileURL) - XCTAssertEqual(try store.load().games.count, 0) - try store.save(LibraryFile()) - let kept = try FileManager.default.contentsOfDirectory(atPath: dir.path) - .filter { $0.hasPrefix("library.json.damaged-") } - XCTAssertEqual(kept.count, 1) - XCTAssertEqual(try Data(contentsOf: dir.appendingPathComponent(kept[0])), damaged) - } - - func testLoadUsesBackupWhenMainIsMissing() throws { - let store = LibraryStore(directory: dir) - var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/g.app"), - platform: .macApp, sizeBytes: 1, modificationDate: Date()) - game.titleId = "0100000000010000" - try store.save(LibraryFile(schemaVersion: 1, games: [game])) - try FileManager.default.removeItem(at: store.fileURL) - XCTAssertEqual(try store.load().games.count, 1) - } - func testMergePreservesBuildMetadataAndMarksMissingSources() throws { - let store = LibraryStore(directory: dir) + let store = CatalogRepository(store: CatalogStore(directory: dir)) + try store.configureSource(.nxnative, enabled: true, root: nil) let sourceFile = dir.appendingPathComponent("Game [0100000000010000].nsp") try Data("x".utf8).write(to: sourceFile) var game = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/G.app"), @@ -187,7 +151,7 @@ final class LibraryStoreTests: XCTestCase { xcodeVersion: "27.1", verified: true) game.lastBuild = BuildRecord(endedAt: Date(), exitCode: 0, outputPath: "/tmp/G.app", toolchainVerified: true) - try store.save(LibraryFile(schemaVersion: 1, games: [game])) + try store.updateNXNativeGames { $0 = [game] } var imported = game imported.status = .builtSourcesMissing @@ -195,19 +159,20 @@ final class LibraryStoreTests: XCTestCase { imported.lastBuild = nil imported.sources = [] - let merged = try store.merge(scanned: [imported]) - XCTAssertEqual(merged.games.first?.status, .built) - XCTAssertEqual(merged.games.first?.toolchain.verified, true) - XCTAssertEqual(merged.games.first?.lastBuild?.exitCode, 0) + let merged = try store.mergeNXNative(scanned: [imported]) + XCTAssertEqual(merged.nxnativeGames.first?.status, .built) + XCTAssertEqual(merged.nxnativeGames.first?.toolchain.verified, true) + XCTAssertEqual(merged.nxnativeGames.first?.lastBuild?.exitCode, 0) try FileManager.default.removeItem(at: sourceFile) - let afterDeletion = try store.merge(scanned: [imported]) - XCTAssertEqual(afterDeletion.games.first?.status, .builtSourcesMissing) - XCTAssertEqual(afterDeletion.games.first?.toolchain.verified, true) + let afterDeletion = try store.mergeNXNative(scanned: [imported]) + XCTAssertEqual(afterDeletion.nxnativeGames.first?.status, .builtSourcesMissing) + XCTAssertEqual(afterDeletion.nxnativeGames.first?.toolchain.verified, true) } func testAttachingSourcesKeepsTheImportedAppURL() throws { - let store = LibraryStore(directory: dir) + let store = CatalogRepository(store: CatalogStore(directory: dir)) + try store.configureSource(.nxnative, enabled: true, root: nil) let app = dir.appendingPathComponent("Old.app") try FileManager.default.createDirectory( at: app.appendingPathComponent("Contents"), withIntermediateDirectories: true) @@ -221,7 +186,7 @@ final class LibraryStoreTests: XCTestCase { titleId: "0100000000010000", versionString: "1.9.0") imported.status = .builtSourcesMissing - try store.save(LibraryFile(schemaVersion: 1, games: [imported])) + try store.updateNXNativeGames { $0 = [imported] } var added = PortedGame(name: "G", url: dir.appendingPathComponent("workspace"), platform: .macApp, sizeBytes: 1, modificationDate: Date(), @@ -232,15 +197,16 @@ final class LibraryStoreTests: XCTestCase { added.bundleId = "org.nxnative.0100000000010000" added.versionString = "65536" - let merged = try store.merge(scanned: [added]) - XCTAssertEqual(merged.games.first?.url, app) - XCTAssertEqual(merged.games.first?.status, .built) - XCTAssertEqual(merged.games.first?.versionString, "1.9.0") - XCTAssertEqual(merged.games.first?.bundleId, "org.nxnative.0100000000010000") + let merged = try store.mergeNXNative(scanned: [added]) + XCTAssertEqual(merged.nxnativeGames.first?.url, app) + XCTAssertEqual(merged.nxnativeGames.first?.status, .built) + XCTAssertEqual(merged.nxnativeGames.first?.versionString, "1.9.0") + XCTAssertEqual(merged.nxnativeGames.first?.bundleId, "org.nxnative.0100000000010000") } func testLocateSourcesReplacesMissingRecordedSources() throws { - let store = LibraryStore(directory: dir) + let store = CatalogRepository(store: CatalogStore(directory: dir)) + try store.configureSource(.nxnative, enabled: true, root: nil) let app = dir.appendingPathComponent("Game.app") try FileManager.default.createDirectory( at: app.appendingPathComponent("Contents"), withIntermediateDirectories: true) @@ -255,7 +221,7 @@ final class LibraryStoreTests: XCTestCase { old.status = .builtSourcesMissing old.sources = [GameFileItem(url: oldSource, kind: .base, titleId: "0100000000010000", sizeBytes: 1)] - try store.save(LibraryFile(schemaVersion: 1, games: [old])) + try store.updateNXNativeGames { $0 = [old] } var scanned = PortedGame(name: "G", url: dir.appendingPathComponent("workspace"), platform: .macApp, sizeBytes: 1, modificationDate: Date(), @@ -264,25 +230,26 @@ final class LibraryStoreTests: XCTestCase { scanned.sources = [GameFileItem(url: newSource, kind: .base, titleId: "0100000000010000", sizeBytes: 1)] - let merged = try store.merge(scanned: [scanned]) - XCTAssertEqual(merged.games.first?.sources.first?.url, newSource) - XCTAssertEqual(merged.games.first?.status, .built) - XCTAssertEqual(merged.games.first?.url, app) + let merged = try store.mergeNXNative(scanned: [scanned]) + XCTAssertEqual(merged.nxnativeGames.first?.sources.first?.url, newSource) + XCTAssertEqual(merged.nxnativeGames.first?.status, .built) + XCTAssertEqual(merged.nxnativeGames.first?.url, app) } func testMergeTitleIdsCaseInsensitively() throws { - let store = LibraryStore(directory: dir) + let store = CatalogRepository(store: CatalogStore(directory: dir)) + try store.configureSource(.nxnative, enabled: true, root: nil) var old = PortedGame(name: "G", url: URL(fileURLWithPath: "/tmp/G.app"), platform: .macApp, sizeBytes: 1, modificationDate: Date(), titleId: "01007EF00011E000") old.status = .builtSourcesMissing - try store.save(LibraryFile(schemaVersion: 1, games: [old])) + try store.updateNXNativeGames { $0 = [old] } var scanned = old scanned.titleId = "01007ef00011e000" scanned.status = .builtSourcesMissing - let merged = try store.merge(scanned: [scanned]) - XCTAssertEqual(merged.games.count, 1) - XCTAssertEqual(merged.games.first?.titleId, "01007ef00011e000") + let merged = try store.mergeNXNative(scanned: [scanned]) + XCTAssertEqual(merged.nxnativeGames.count, 1) + XCTAssertEqual(merged.nxnativeGames.first?.titleId, "01007ef00011e000") } } diff --git a/Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift b/Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift new file mode 100644 index 00000000..60e418e7 --- /dev/null +++ b/Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift @@ -0,0 +1,106 @@ +import XCTest +import Darwin +@testable import NXLibraryCore + +final class NativeMacApplicationTests: XCTestCase { + func testIdentifiesArm64GameAndPreservesItsBundleIdentity() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let app = try fixture.app() + let result = try NativeMacApplication.inspect(at: app, within: fixture.root) + XCTAssertEqual(result.url.path, app.path) + XCTAssertEqual(result.bundleIdentifier, "test.game") + XCTAssertEqual(result.name, "Fixture game") + XCTAssertEqual(result.architectures, [.arm64]) + XCTAssertTrue(result.isDeclaredGame) + } + + func testRecognizesIntelAndUniversalExecutables() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let intel = try fixture.app(at: "Intel.app", cpuTypes: [0x01000007]) + let universal = try fixture.app(at: "Universal.app", cpuTypes: [0x01000007, 0x0100000c]) + XCTAssertEqual(try NativeMacApplication.inspect(at: intel, within: fixture.root).architectures, [.x86_64]) + XCTAssertEqual(try NativeMacApplication.inspect(at: universal, within: fixture.root).architectures, [.x86_64, .arm64]) + } + + func testDoesNotClassifyToolsOrUnclassifiedAppsAsGames() throws { + let fixture = try SteamTestFixture.temporary(in: self) + for (i, category) in ["public.app-category.developer-tools", nil, "public.app-category.not-games"].enumerated() { + let app = try fixture.app(at: "Tool\(i).app", category: category) + XCTAssertFalse(try NativeMacApplication.inspect(at: app, within: fixture.root).isDeclaredGame) + } + let action = try fixture.app(at: "Action.app", category: "public.app-category.action-games") + XCTAssertTrue(try NativeMacApplication.inspect(at: action, within: fixture.root).isDeclaredGame) + } + + func testRejectsNonAppsAndIosOnlyBundles() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let invalid: [[String: Any]] = [["CFBundlePackageType": "BNDL"], ["LSRequiresIPhoneOS": true], + ["CFBundleSupportedPlatforms": ["iPhoneOS"]]] + for (i, metadata) in invalid.enumerated() { + let app = try fixture.app(at: "Invalid\(i).app", metadata: metadata) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: app, within: fixture.root)) + } + } + + func testRejectsMissingNonExecutableAndUnsupportedCpuFiles() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let missing = try fixture.app(at: "Missing.app") + try FileManager.default.removeItem(at: missing.appendingPathComponent("Contents/MacOS/fixture")) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: missing, within: fixture.root)) + let wrong = try fixture.app(at: "Wrong.app") + try Data("not Mach-O".utf8).write(to: wrong.appendingPathComponent("Contents/MacOS/fixture")) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: wrong, within: fixture.root)) + let unsupported = try fixture.app(at: "Unsupported.app", cpuTypes: [12]) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: unsupported, within: fixture.root)) + let library = try fixture.app(at: "Library.app") + try SteamTestFixture.machHeader(cpu: 0x0100000c, fileType: 6) + .write(to: library.appendingPathComponent("Contents/MacOS/fixture")) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: library, within: fixture.root)) + } + + func testRejectsExecutableTraversalAndSymlinkEscape() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let app = try fixture.app(metadata: ["CFBundleExecutable": "../fixture"]) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: app, within: fixture.root)) + let valid = try fixture.app(at: "Valid.app") + let narrowRoot = fixture.root.appendingPathComponent("narrow") + try FileManager.default.createDirectory(at: narrowRoot, withIntermediateDirectories: true) + let link = narrowRoot.appendingPathComponent("Escaping.app") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: valid) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: link, within: narrowRoot)) + } + + func testRejectsOversizedMetadataAndTruncatedFatSlices() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let app = try fixture.app() + try Data(repeating: 65, count: 1024 * 1024 + 1).write(to: app.appendingPathComponent("Contents/Info.plist")) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: app, within: fixture.root)) + let fat = try fixture.app(at: "Truncated.app", cpuTypes: [0x01000007, 0x0100000c]) + let bytes = SteamTestFixture.fatHeader(cpus: [0x01000007, 0x0100000c]).dropLast(20) + try Data(bytes).write(to: fat.appendingPathComponent("Contents/MacOS/fixture")) + XCTAssertThrowsError(try NativeMacApplication.inspect(at: fat, within: fixture.root)) + } + + func testNonRegularMetadataDoesNotBlockWaitingForAWriter() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let app = try fixture.app() + let plist = app.appendingPathComponent("Contents/Info.plist") + try FileManager.default.removeItem(at: plist) + XCTAssertEqual(mkfifo(plist.path, 0o600), 0) + let finished = expectation(description: "Inspection rejects a FIFO without blocking") + DispatchQueue.global().async { + do { + _ = try NativeMacApplication.inspect(at: app, within: fixture.root) + XCTFail("A FIFO is not app metadata") + } catch {} + finished.fulfill() + } + let result = XCTWaiter.wait(for: [finished], timeout: 1) + // Release an old blocking implementation so a failed test leaves no blocked worker behind. + if result != .completed { + let writer = Darwin.open(plist.path, O_WRONLY | O_NONBLOCK) + if writer >= 0 { Darwin.close(writer) } + } + XCTAssertEqual(result, .completed) + } +} diff --git a/Tests/NXLibraryCoreTests/NewestEngineTests.swift b/Tests/NXLibraryCoreTests/NewestEngineTests.swift index c5387c94..24bc2b1b 100644 --- a/Tests/NXLibraryCoreTests/NewestEngineTests.swift +++ b/Tests/NXLibraryCoreTests/NewestEngineTests.swift @@ -42,7 +42,7 @@ final class NewestEngineTests: XCTestCase { XCTAssertEqual(NewestEngine.readiness(newestLock: lock("32024.100"), testedMetal: "32023.922"), .needsNewerApp(metal: "32024.100")) XCTAssertEqual(NewestEngineCopy.needsNewerApp(metal: "32024.100"), - "The newest nxnative needs Metal 32024.100, so it needs a newer NX Library.") + "The newest nxnative needs Metal 32024.100, so it needs a newer Arcane.") } func testAnUnreadableLockIsUnknown() { @@ -270,7 +270,7 @@ final class NewestEngineTests: XCTestCase { XCTAssertEqual(card.chip, "NEWEST ENGINE") XCTAssertEqual(card.actionTitle, "Back to tested") XCTAssertEqual(card.about, NewestEngineCopy.note) - XCTAssertEqual(card.detail, "At 9c1d2e7, 12 commits ahead of the tested 4a0551e, chosen in Settings → Engine.") + XCTAssertEqual(card.detail, "At 9c1d2e7, 12 commits ahead of the tested 4a0551e, chosen in Settings → Setup and engine.") XCTAssertEqual(SetupActions.engineAction(for: .checkout(head: main, dirty: false), pinned: pin, newest: main), .none) } @@ -291,10 +291,10 @@ final class NewestEngineTests: XCTestCase { func testTheSentenceIsTheOneAgreed() { XCTAssertEqual(NewestEngineCopy.note, - "Newest nxnative, not yet tested by NX Library. It usually works, but something may not. " - + "Its new features reach NX Library in a future version.") + "Newest nxnative, not yet tested by Arcane. It usually works, but something may not. " + + "Its new features reach Arcane in a future version.") XCTAssertEqual(NewestEngineCopy.ahead(1), "1 commit ahead") XCTAssertEqual(NewestEngineCopy.offer(commit: main, aheadBy: 138), - "Build with nxnative main (9c1d2e7, 138 commits ahead) before NX Library has tested it.") + "Build with nxnative main (9c1d2e7, 138 commits ahead) before Arcane has tested it.") } } diff --git a/Tests/NXLibraryCoreTests/PendingInstallTests.swift b/Tests/NXLibraryCoreTests/PendingInstallTests.swift index 859ad88b..9423247d 100644 --- a/Tests/NXLibraryCoreTests/PendingInstallTests.swift +++ b/Tests/NXLibraryCoreTests/PendingInstallTests.swift @@ -132,15 +132,16 @@ final class PendingInstallTests: XCTestCase { importer.scan(directories: [root]).map { importer.makeGame(from: $0) } } let storeDirectory = root.appendingPathComponent("catalog") - let store = LibraryStore(directory: storeDirectory) + let store = CatalogRepository(store: CatalogStore(directory: storeDirectory)) + try store.configureSource(.nxnative, enabled: true, root: nil) var g = try XCTUnwrap(scanned().first) g.status = .built g.pendingInstall = p g.portingFailure = .failed g.portingFailureReason = PortingFailureReason(kind: .diskFull, detail: "Previous failure") g.settings.metalHUD = true - try store.save(LibraryFile(games: [g])) - XCTAssertEqual(try store.merge(scanned: scanned()).games.first?.pendingInstall, p) + try store.updateNXNativeGames { $0 = [g] } + XCTAssertEqual(try store.mergeNXNative(scanned: scanned()).nxnativeGames.first?.pendingInstall, p) var io = BuildInstallIO() io.afterPublish = { throw CocoaError(.userCancelled) } @@ -149,8 +150,8 @@ final class PendingInstallTests: XCTestCase { // Simulate termination after the bundle was published and staging was // cleaned, but before the new build record reached the catalog. try FileManager.default.removeItem(at: p.folder) - let reopened = LibraryStore(directory: storeDirectory) - g = try XCTUnwrap(try reopened.merge(scanned: scanned()).games.first) + let reopened = CatalogRepository(store: CatalogStore(directory: storeDirectory)) + g = try XCTUnwrap(try reopened.mergeNXNative(scanned: scanned()).nxnativeGames.first) XCTAssertEqual(g.pendingInstall, p) XCTAssertEqual(try PendingInstaller.install(&g), .installed) XCTAssertNil(g.pendingInstall) @@ -160,8 +161,8 @@ final class PendingInstallTests: XCTestCase { XCTAssertEqual(g.lastBuild, p.record) XCTAssertEqual(g.toolchain, p.toolchain) XCTAssertTrue(g.settings.metalHUD) - try reopened.save(LibraryFile(games: [g])) - g = try XCTUnwrap(try reopened.merge(scanned: scanned()).games.first) + try reopened.updateNXNativeGames { $0 = [g] } + g = try XCTUnwrap(try reopened.mergeNXNative(scanned: scanned()).nxnativeGames.first) XCTAssertNil(try PendingInstaller.install(&g)) XCTAssertEqual(g.lastBuild, p.record) XCTAssertEqual(BuildOutputInstaller.version(of: p.finalApp), "1.2.0") diff --git a/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift b/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift index e09a6f88..3b08251c 100644 --- a/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift +++ b/Tests/NXLibraryCoreTests/PlaySessionStoreTests.swift @@ -1,4 +1,5 @@ import XCTest +import Combine @testable import NXLibraryCore final class PlaySessionStoreTests: XCTestCase { @@ -49,6 +50,28 @@ final class PlaySessionStoreTests: XCTestCase { XCTAssertEqual(store.sessions.count, 1) } + func testSteamSessionIsQualifiedAndOnlyItsOwnerEndsIt() { + let store = store() + let steamID = UUID() + let nx = game() + XCTAssertTrue(store.start(gameID: steamID, sourceID: "steam-570")) + XCTAssertFalse(store.start(gameID: steamID, sourceID: "steam-570"), "one running session per game") + XCTAssertTrue(store.start(for: nx)) + now = now.addingTimeInterval(120) + // An nxnative app quitting ends its own session only. + XCTAssertEqual(store.end(bundleID: nx.bundleId).map(\.gameID), [nx.id]) + XCTAssertTrue(store.isRunning(gameID: steamID)) + store.heartbeat(for: steamID) + now = now.addingTimeInterval(60) + store.end(gameID: steamID) + XCTAssertEqual(store.totalDuration(for: steamID), 180, accuracy: 0.001) + XCTAssertEqual(store.sessions.first { $0.gameID == steamID }?.titleID, "steam-570") + XCTAssertNil(store.sessions.first { $0.gameID == steamID }?.bundleID) + // Reloaded from disk with the old decoder shape. + let reloaded = PlaySessionStore(fileURL: url, now: { [unowned self] in self.now }) + XCTAssertEqual(reloaded.totalDuration(for: steamID), 180, accuracy: 0.001) + } + func testDanglingSessionClosesAtHeartbeat() { let store = store() let game = game() @@ -113,6 +136,16 @@ final class PlaySessionStoreTests: XCTestCase { XCTAssertTrue(store.end(bundleID: "org.nxnative.0100000000010000").isEmpty) } + func testEndByGameIDReturnsTheSessionsItEnded() { + let store = store(), id = UUID() + XCTAssertTrue(store.start(gameID: id, sourceID: "steam-440")) + now = now.addingTimeInterval(120) + let ended = store.end(gameID: id) + XCTAssertEqual(ended.map(\.gameID), [id]) + XCTAssertEqual(ended.first?.duration ?? 0, 120, accuracy: 0.001) + XCTAssertTrue(store.end(gameID: id).isEmpty) + } + private func play(_ game: PortedGame, for seconds: TimeInterval, in store: PlaySessionStore) { XCTAssertTrue(store.start(for: game)) now = now.addingTimeInterval(seconds) @@ -175,4 +208,168 @@ final class PlaySessionStoreTests: XCTestCase { let decoded = try JSONDecoder().decode([PlaySession].self, from: data) XCTAssertEqual(decoded, store.sessions) } + + // MARK: - Steam's own playtime as a baseline + + private func session(_ store: PlaySessionStore, _ id: UUID, from start: TimeInterval, to end: TimeInterval?) { + now = Date(timeIntervalSince1970: start) + store.start(gameID: id, sourceID: "steam-440") + guard let end else { return } + now = Date(timeIntervalSince1970: end) + store.end(gameID: id) + } + + private func external(_ duration: TimeInterval = 3_600, lastPlayed: TimeInterval? = nil, + since: TimeInterval = 1_000) -> ExternalPlaytime { + ExternalPlaytime(duration: duration, lastPlayed: lastPlayed.map { Date(timeIntervalSince1970: $0) }, + since: Date(timeIntervalSince1970: since)) + } + + func testNoExternalKeepsTodaysTotals() { + let store = store(), id = UUID() + session(store, id, from: 1_100, to: 1_400) + store.setExternal([:]) + XCTAssertEqual(store.totalDuration(for: id), 300, accuracy: 0.001) + XCTAssertEqual(store.lastPlayed(for: id), Date(timeIntervalSince1970: 1_100)) + } + + func testExternalAloneIsItsTotal() { + let store = store(), id = UUID() + store.setExternal([id: external()]) + XCTAssertEqual(store.totalDuration(for: id), 3_600, accuracy: 0.001) + XCTAssertNil(store.lastPlayed(for: id)) + } + + func testSessionsAfterSinceAreAdded() { + let store = store(), id = UUID() + session(store, id, from: 1_100, to: 1_400) + store.setExternal([id: external()]) + XCTAssertEqual(store.totalDuration(for: id), 3_900, accuracy: 0.001) + } + + func testSessionsBeforeSinceAreNotAdded() { + let store = store(), id = UUID() + session(store, id, from: 500, to: 900) + store.setExternal([id: external()]) + XCTAssertEqual(store.totalDuration(for: id), 3_600, accuracy: 0.001) + } + + func testStraddlingSessionCountsOnlyAfterSince() { + let store = store(), id = UUID() + session(store, id, from: 800, to: 1_300) + store.setExternal([id: external()]) + XCTAssertEqual(store.totalDuration(for: id), 3_900, accuracy: 0.001) + + let running = UUID() + session(store, running, from: 800, to: nil) + now = Date(timeIntervalSince1970: 1_300) + store.setExternal([running: external()]) + XCTAssertEqual(store.totalDuration(for: running), 3_900, accuracy: 0.001) + } + + func testCarriedTimeIsIgnoredWithExternal() { + let store = store(), id = UUID() + for index in 0...PlaySessionStore.maxSessions { + let start = TimeInterval(index * 10) + session(store, id, from: start, to: start + 5) + } + XCTAssertFalse(store.carried.isEmpty) + now = Date(timeIntervalSince1970: 3_000) + store.setExternal([id: external(since: 2_002)]) + XCTAssertEqual(store.totalDuration(for: id), 3_603, accuracy: 0.001) + } + + func testLastPlayedIsTheLaterOfBoth() { + let store = store(), id = UUID() + session(store, id, from: 1_100, to: 1_400) + store.setExternal([id: external(lastPlayed: 2_000)]) + XCTAssertEqual(store.lastPlayed(for: id), Date(timeIntervalSince1970: 2_000)) + store.setExternal([id: external(lastPlayed: 900)]) + XCTAssertEqual(store.lastPlayed(for: id), Date(timeIntervalSince1970: 1_100)) + } + + // Sessions trimmed out of the recent list after Steam's value was seen still count until Steam moves on. + func testTrimmedSessionsAfterSinceStillCount() { + let store = store(), id = UUID() + store.setExternal([id: external(since: 0)]) + for index in 0...PlaySessionStore.maxSessions { + let start = TimeInterval(10 + index * 10) + session(store, id, from: start, to: start + 5) + } + XCTAssertFalse(store.carried.isEmpty) + let sessionsTotal = TimeInterval(PlaySessionStore.maxSessions + 1) * 5 + XCTAssertEqual(store.totalDuration(for: id), 3_600 + sessionsTotal, accuracy: 0.001) + + let reloaded = PlaySessionStore(fileURL: url, now: { [unowned self] in self.now }) + reloaded.setExternal([id: external(since: 0)]) + XCTAssertEqual(reloaded.totalDuration(for: id), 3_600 + sessionsTotal, accuracy: 0.001) + + store.setExternal([id: external(7_200, since: 5_000)]) + XCTAssertEqual(store.totalDuration(for: id), 7_200, accuracy: 0.001, "Steam's new value covers them") + } + + func testTrimmedStraddlingSessionCarriesOnlyItsPartAfterSince() { + let store = store(), id = UUID() + store.setExternal([id: external(since: 3)]) + session(store, id, from: 0, to: 10) + for index in 0..<PlaySessionStore.maxSessions { + let start = TimeInterval(100 + index * 10) + session(store, id, from: start, to: start + 5) + } + XCTAssertEqual(store.carried[id]?.duration, 10) + XCTAssertEqual(store.totalDuration(for: id), 3_600 + 7 + TimeInterval(PlaySessionStore.maxSessions) * 5, accuracy: 0.001) + } + + func testTotalWithAGivenExternalIgnoresThePublishedOne() { + let store = store(), id = UUID() + session(store, id, from: 1_100, to: 1_400) + store.setExternal([id: external(10)]) + XCTAssertEqual(store.totalDuration(for: id, with: external()), 3_900, accuracy: 0.001) + XCTAssertEqual(store.totalDuration(for: id, with: nil), 300, accuracy: 0.001) + } + + // While Steam's totals are hidden (source off, other account, launch), trimming still keeps its part. + func testTrimWhileTotalsAreHiddenKeepsThePartAfterTheKnownValue() { + let store = store(), id = UUID() + store.setTrimReferences([id: Date(timeIntervalSince1970: 0)]) + store.setExternal([:]) + for index in 0...PlaySessionStore.maxSessions { + let start = TimeInterval(10 + index * 10) + session(store, id, from: start, to: start + 5) + } + store.setExternal([id: external(since: 0)]) + XCTAssertEqual(store.totalDuration(for: id), 3_600 + TimeInterval(PlaySessionStore.maxSessions + 1) * 5, accuracy: 0.001) + } + + func testOlderTotalsFileWithoutExternalFieldsStillLoads() throws { + let id = UUID() + let json = #"[{"gameID":"\#(id.uuidString)","playtime":{"duration":120,"lastPlayed":0}}]"# + let probe = PlaySessionStore(fileURL: url, now: { [unowned self] in self.now }) + try Data(json.utf8).write(to: probe.totalsURL) + let loaded = PlaySessionStore(fileURL: url, now: { [unowned self] in self.now }) + XCTAssertNil(loaded.loadError) + XCTAssertEqual(loaded.carried[id], CarriedPlaytime(duration: 120, lastPlayed: Date(timeIntervalSinceReferenceDate: 0))) + } + + func testAGameFoundAlreadyRunningIsNotAnnounced() { + let store = store(), id = UUID() + var started: [UUID] = [] + let token = store.starts.sink { started.append($0) } + XCTAssertTrue(store.start(gameID: id, sourceID: "steam-440", announces: false)) + XCTAssertTrue(store.isRunning(gameID: id)) + XCTAssertEqual(started, []) + token.cancel() + } + + func testStartsAreAnnouncedOnce() { + let store = store(), id = UUID() + var started: [UUID] = [] + let token = store.starts.sink { started.append($0) } + store.start(gameID: id, sourceID: "steam-440") + store.start(gameID: id, sourceID: "steam-440") + let nx = game() + store.start(for: nx) + XCTAssertEqual(started, [id, nx.id]) + token.cancel() + } } diff --git a/Tests/NXLibraryCoreTests/PortingPresentationTests.swift b/Tests/NXLibraryCoreTests/PortingPresentationTests.swift index 27ef0b9f..35806253 100644 --- a/Tests/NXLibraryCoreTests/PortingPresentationTests.swift +++ b/Tests/NXLibraryCoreTests/PortingPresentationTests.swift @@ -70,6 +70,32 @@ final class PortingPresentationTests: XCTestCase { XCTAssertEqual(PortingETA.text(p, lastFinishingSeconds: nil), "Pipelines: about 1 hr") } + func testPrewarmReportsActivityInsteadOfAnOlderFinishingEstimate() throws { + var p = finishing + p.apply(.stageEnd(name: "Pipeline archive", ok: true, elapsed: 60, summary: nil)) + p.apply(.stage(k: 8, n: 9, name: "Prewarm pipelines", step: "local GPU")) + let before = p.overall + let heartbeat = try XCTUnwrap(BuildEventParser.parse( + #"{"ev":"progress","done":null,"total":null,"frac":null,"eta":null,"elapsed":3600}"#)) + p.apply(heartbeat) + XCTAssertEqual(p.overall, before, "elapsed time is not a completed-work counter") + XCTAssertNil(p.finishingETA) + for previousTime: Double? in [nil, 60, 7200] { + XCTAssertEqual(PortingETA.text(p, lastFinishingSeconds: previousTime), "Preparing the first launch") + } + p.apply(.stageEnd(name: "Prewarm pipelines", ok: true, elapsed: 3600, summary: nil)) + p.apply(.stage(k: 9, n: 9, name: "Mac app", step: nil)) + XCTAssertEqual(PortingETA.text(p, lastFinishingSeconds: nil), "Finishing up") + } + + func testStoppingPrewarmClearsTheActivityCaption() { + var p = finishing + p.apply(.stage(k: 8, n: 9, name: "Prewarm pipelines", step: nil)) + XCTAssertEqual(PortingETA.text(p, lastFinishingSeconds: 60), "Preparing the first launch") + p.finish(success: false) + XCTAssertNil(PortingETA.text(p, lastFinishingSeconds: 60)) + } + func testETAFormatsHoursAndMinutesWhenOverAnHour() { let oneHour = progress([.stage(k: 5, n: 7, name: "Mac shaders", step: nil), .step("compiling"), .progress(fraction: 0.1, done: nil, total: nil, unit: nil, eta: 3600)]) @@ -177,23 +203,51 @@ final class PortingPresentationTests: XCTestCase { /// The porting game is the first game: right after the Add game card, never before the cards. func testThePortingGameSitsRightAfterAddGame() { let a = UUID(), b = UUID() - let games = [game(app: true), game(app: false)].enumerated().map { index, game -> PortedGame in - var game = game - game.id = index == 0 ? a : b - return game - } - let row = SpotlightRow.build(games: games, enabledCards: [.collection, .addGame], order: [], front: b) + let row = SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection, .addGame], order: [], front: [b]) XCTAssertEqual(row, [.card(.collection), .card(.addGame), .game(b), .game(a)]) // The player moved Add game to the end: the porting game still follows it. - let moved = SpotlightRow.build(games: games, enabledCards: [.collection, .addGame], + let moved = SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection, .addGame], order: ["card:collection", "game:\(a.uuidString)", "game:\(b.uuidString)", "card:addGame"], - front: b) + front: [b]) XCTAssertEqual(moved, [.card(.collection), .game(a), .card(.addGame), .game(b)]) // Without the card: first among the games. - let noCard = SpotlightRow.build(games: games, enabledCards: [.collection], order: [], front: b) + let noCard = SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection], order: [], front: [b]) XCTAssertEqual(noCard, [.card(.collection), .game(b), .game(a)]) - XCTAssertEqual(SpotlightRow.build(games: games, enabledCards: [.collection], order: [], front: UUID()), - SpotlightRow.build(games: games, enabledCards: [.collection], order: [])) + XCTAssertEqual(SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection], order: [], front: [UUID()]), + SpotlightRow.build(gameIDs: [a, b], enabledCards: [.collection], order: [])) + } + + /// The porting game leads, then the games Steam downloads this session, in the row's order. + func testPortingThenDownloadsLeadTheRow() { + let a = UUID(), b = UUID(), c = UUID(), d = UUID() + let row = SpotlightRow.build(gameIDs: [a, b, c, d], enabledCards: [.collection, .addGame], order: [], + front: [d, b]) + XCTAssertEqual(row, [.card(.collection), .card(.addGame), .game(d), .game(b), .game(a), .game(c)]) + XCTAssertEqual(SpotlightRow.leaders(porting: d, downloads: [c, a, d], row: [a, b, c, d]), [d, a, c]) + XCTAssertEqual(SpotlightRow.leaders(porting: nil, downloads: [c], row: [a, b, c, d]), [c]) + XCTAssertEqual(SpotlightRow.leaders(porting: nil, downloads: [], row: [a, b]), []) + // A game no longer in the row (filtered out, or the download removed) leads nothing. + XCTAssertEqual(SpotlightRow.leaders(porting: UUID(), downloads: [UUID()], row: [a, b]), []) + } + + /// A game seen downloading stays remembered for the session, also once Steam has finished it. + func testSessionDownloadsRememberEveryGameSeenDownloading() { + func steam(_ appID: UInt32, downloading: Bool, id: UUID = UUID()) -> CatalogGame { + var game = SteamCatalogGame(id: id, appID: appID, name: "G\(appID)") + game.installations = [.init(libraryURL: URL(fileURLWithPath: "/tmp/steam"), + contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G\(appID)"), + availability: downloading ? .unavailable : .available, + isDownloading: downloading)] + return CatalogGame(steam: game) + } + let downloading = steam(1, downloading: true), installed = steam(2, downloading: false) + var session = SessionDownloads() + XCTAssertTrue(session.note([downloading, installed])) + XCTAssertEqual(session.ids, [downloading.id]) + XCTAssertFalse(session.note([downloading, installed])) + let finished = steam(1, downloading: false, id: downloading.id) + XCTAssertFalse(session.note([finished, installed])) + XCTAssertEqual(session.ids, [downloading.id]) } func testPillMovesStopAtTheLimit() { @@ -211,4 +265,14 @@ final class PortingPresentationTests: XCTestCase { func testLockIcon() { XCTAssertEqual(MaterialIcon.lock.rawValue, "\u{E897}") } + + func testCatalogTileLookIsDownloadingOnlyWhileSteamDownloads() { + let library = URL(fileURLWithPath: "/tmp/steam"), content = URL(fileURLWithPath: "/tmp/steam/steamapps/common/G") + var steam = SteamCatalogGame(appID: 10, name: "Steam game") + steam.installations = [.init(libraryURL: library, contentURL: content, availability: .unavailable, isDownloading: true)] + XCTAssertEqual(PortingTileLook.make(catalog: CatalogGame(steam: steam)), .downloading) + steam.installations = [.init(libraryURL: library, contentURL: content, availability: .available)] + XCTAssertEqual(PortingTileLook.make(catalog: CatalogGame(steam: steam)), .normal) + XCTAssertEqual(PortingTileLook.make(catalog: CatalogGame(nxnative: CatalogTestSupport.completeLegacyGame())), .normal) + } } diff --git a/Tests/NXLibraryCoreTests/PortingProgressTests.swift b/Tests/NXLibraryCoreTests/PortingProgressTests.swift index f5c12074..f0833267 100644 --- a/Tests/NXLibraryCoreTests/PortingProgressTests.swift +++ b/Tests/NXLibraryCoreTests/PortingProgressTests.swift @@ -211,6 +211,17 @@ final class BuildWarningTests: XCTestCase { XCTAssertEqual(BuildWarningCopy.text(stage: "pack", summary: nil), "Pack finished with a warning. The log has the details.") } + func testPrewarmWarningExplainsTheFirstLaunchWithoutRawToolOutput() { + let text = BuildWarningCopy.text(stage: "Prewarm pipelines", summary: "RAW_TOOL_FAILURE") + XCTAssertTrue(text.contains("The game will prepare them on its first start")) + XCTAssertTrue(text.contains("rebuilding tries again")) + XCTAssertFalse(text.contains("RAW_TOOL_FAILURE")) + let event = BuildEventParser.parse( + #"{"ev":"stage_end","name":"Prewarm pipelines","ok":true,"warn":true,"summary":"failed, the app is packed without them"}"#) + XCTAssertEqual(event, .stageEnd(name: "Prewarm pipelines", ok: true, elapsed: nil, + summary: "failed, the app is packed without them", warn: true)) + } + func testAWarnedStageStillCountsAsFinished() { var progress = PortingProgress() progress.apply(.stage(k: 1, n: 2, name: "Mac shaders", step: nil)) diff --git a/Tests/NXLibraryCoreTests/SavePresentationTests.swift b/Tests/NXLibraryCoreTests/SavePresentationTests.swift index 233264db..0e89859f 100644 --- a/Tests/NXLibraryCoreTests/SavePresentationTests.swift +++ b/Tests/NXLibraryCoreTests/SavePresentationTests.swift @@ -32,4 +32,15 @@ final class SavePresentationTests: XCTestCase { XCTAssertTrue(SavePresentation.closedNotice.contains("Finder")) XCTAssertTrue(SavePresentation.importWarning.contains("newer")) } + + func testLegacyAndMultiuserRestoreExplainTheirScope() { + let identity = SaveIdentity(titleID: "0100000000000001", gameName: "Game", version: nil, buildID: nil) + var snapshot = SaveSnapshot(id: UUID(), identity: identity, created: Date(), reason: .manual, presentSlots: [], entries: []) + XCTAssertTrue(SavePresentation.restoreMessage(snapshot, installedVersion: nil).contains("kept")) + snapshot.schemaVersion = 2 + XCTAssertTrue(SavePresentation.restoreMessage(snapshot, installedVersion: nil).contains("all local users")) + XCTAssertTrue(SavePresentation.cloudNotice.contains("primary")) + XCTAssertEqual(SavePresentation.slotName(.user2), "User 2") + XCTAssertEqual(SavePresentation.slotName(.users), "Local users") + } } diff --git a/Tests/NXLibraryCoreTests/SelenePaletteTests.swift b/Tests/NXLibraryCoreTests/SelenePaletteTests.swift index eb40f70b..3a0ec747 100644 --- a/Tests/NXLibraryCoreTests/SelenePaletteTests.swift +++ b/Tests/NXLibraryCoreTests/SelenePaletteTests.swift @@ -8,9 +8,9 @@ final class SelenePaletteTests: XCTestCase { .appendingPathComponent("Resources/Selene/palettes.json") } - func testLoadsAll23Palettes() throws { + func testLoadsAll25Palettes() throws { let all = try SelenePaletteCatalog.load(from: paletteURL) - XCTAssertEqual(all.count, 23) + XCTAssertEqual(all.count, 25) let ids = Set(all.map(\.id)) XCTAssertTrue(ids.isSuperset(of: ["selene", "white", "catppuccin-latte"])) } @@ -22,13 +22,14 @@ final class SelenePaletteTests: XCTestCase { XCTAssertEqual(SelenePaletteCatalog.defaultID, "selene") let rest = ordered.dropFirst().map(\.name) XCTAssertEqual(rest, rest.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }) - XCTAssertEqual(Array(rest.prefix(3)), ["Catppuccin", "Catppuccin Latte", "Ethereal"]) - XCTAssertEqual(ordered.count, 23) + XCTAssertEqual(Array(rest.prefix(3)), ["Arcane Crystal", "Arcane Flow", "Catppuccin"]) + XCTAssertEqual(ordered.count, 25) } func testSelenePaletteValues() throws { let all = try SelenePaletteCatalog.load(from: paletteURL) let p = SelenePaletteCatalog.resolve("selene", in: all) + XCTAssertEqual(p.name, AppIdentity.name) XCTAssertEqual(p.focus, 0xFFFFFF) XCTAssertEqual(p.onFocus, 0x111111) XCTAssertEqual(p.glass, 0x14181F) @@ -38,6 +39,17 @@ final class SelenePaletteTests: XCTestCase { XCTAssertEqual(p.base.stops, [.init(color: 0x102A5C, location: 0), .init(color: 0x03081A, location: 1)]) } + func testBothArcaneSurfacesAreSelectableAndOldPalettesStayClassic() throws { + let all = try SelenePaletteCatalog.load(from: paletteURL) + XCTAssertEqual(SelenePaletteCatalog.resolve("selene", in: all).surface, .classic) + XCTAssertEqual(SelenePaletteCatalog.resolve("arcane-crystal", in: all).surface, .arcane) + XCTAssertEqual(SelenePaletteCatalog.resolve("arcane-flow", in: all).surface, .flow) + XCTAssertEqual(SelenePaletteCatalog.resolve("white", in: all).surface, .classic) + var settings = AppSettings() + settings.colorThemeID = "arcane-flow" + XCTAssertEqual(try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(settings)).colorThemeID, "arcane-flow") + } + func testUnknownIdFallsBackToSelene() throws { let all = try SelenePaletteCatalog.load(from: paletteURL) XCTAssertEqual(SelenePaletteCatalog.resolve("nope", in: all).id, "selene") @@ -46,10 +58,17 @@ final class SelenePaletteTests: XCTestCase { func testMissingFileUsesFallback() { XCTAssertThrowsError(try SelenePaletteCatalog.load(from: URL(fileURLWithPath: "/nonexistent/palettes.json"))) XCTAssertEqual(SelenePaletteCatalog.resolve("selene", in: []), .fallback) + XCTAssertEqual(SelenePalette.fallback.surface, .classic) + XCTAssertEqual(SelenePalette.fallback.base.kind, .linear) + XCTAssertEqual(SelenePalette.fallback.base.stops, [ + .init(color: 0x17244A, location: 0), .init(color: 0x0C142C, location: 0.45), + .init(color: 0x05080F, location: 1) + ]) } func testSettingsDecodeWithoutColorTheme() throws { let settings = try JSONDecoder().decode(AppSettings.self, from: Data("{}".utf8)) XCTAssertEqual(settings.colorThemeID, "selene") + XCTAssertEqual(SelenePaletteCatalog.resolve(settings.colorThemeID, in: []).surface, .classic) } } diff --git a/Tests/NXLibraryCoreTests/SessionSummaryTests.swift b/Tests/NXLibraryCoreTests/SessionSummaryTests.swift index dc9a164d..85577386 100644 --- a/Tests/NXLibraryCoreTests/SessionSummaryTests.swift +++ b/Tests/NXLibraryCoreTests/SessionSummaryTests.swift @@ -54,4 +54,18 @@ final class SessionSummaryTests: XCTestCase { lastHeartbeatAt: Date(timeIntervalSince1970: 0)) XCTAssertNil(SessionSummary(session: other, game: game, total: 600)) } + + func testASteamGameSummarisesLikeAnyOther() throws { + let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game")) + let start = Date(timeIntervalSince1970: 1_000) + let played = PlaySession(gameID: steam.id, titleID: "steam-440", bundleID: nil, startedAt: start, + endedAt: start.addingTimeInterval(1_500), lastHeartbeatAt: start) + let summary = try XCTUnwrap(SessionSummary(session: played, game: steam, total: 36_000)) + XCTAssertEqual(summary.gameID, steam.id) + XCTAssertEqual(summary.gameName, "Steam game") + XCTAssertEqual(summary.thisSession, "25m") + XCTAssertEqual(summary.total, "10h 0m") + XCTAssertNil(SessionSummary(session: played, game: CatalogGame(steam: SteamCatalogGame(appID: 1, name: "Other")), + total: 0), "another game's session") + } } diff --git a/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift b/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift index ee212c1a..472f9984 100644 --- a/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift +++ b/Tests/NXLibraryCoreTests/SettingsCatalogTests.swift @@ -2,6 +2,8 @@ import XCTest @testable import NXLibraryCore final class SettingsCatalogTests: XCTestCase { + private static let english = AppLocale(language: .english, region: nil, preferredLanguages: ["en"]) + func testDefaultSettingsHaveNoChanges() { XCTAssertEqual(SettingsCatalog.changed(in: AppSettings()).map(\.id), []) } @@ -12,15 +14,128 @@ final class SettingsCatalogTests: XCTestCase { XCTAssertTrue(SettingsCatalog.changed(in: settings).map(\.id).contains("interfaceSounds")) } - func testRumbleChangesBelongToControllersRatherThanGameDefaults() { + func testRumbleChangesBelongToNewGameDefaults() { var settings = AppSettings() settings.gameDefaults.rumble.toggle() settings.gameDefaults.rumbleGain += 1 let changed = SettingsCatalog.changed(in: settings) XCTAssertEqual(Set(changed.map(\.id)), ["gameDefaults.rumble", "gameDefaults.rumbleGain"]) - XCTAssertTrue(changed.allSatisfy { $0.group == .controllers }) + XCTAssertTrue(changed.allSatisfy { $0.group == .games }) + XCTAssertTrue(changed.allSatisfy { $0.about.contains("new ported games") }) + } + + /// Every row identity as it was before the regrouping: moving rows never renames them. + private static let rowIDs: Set<String> = [ + "appLanguage", "appRegion", "startOn", "restoreLastGame", "startInFullscreen", "checkEngineAtLaunch", + "refreshLibraryAtLaunch", "checkAppUpdatesAtLaunch", "introAnimation", "showButtonHints", "buttonNames", + "viewButtonSwitches", "spotlightCards", "startingTab", "spotlightOrder", "interfaceSounds", "soundVolume", + "quietLaunch", "importSeleneSounds", "colorThemeID", "wallpaperID", "settingsWallpaperID", "backgroundSizing", + "wallpaperBrightness", "animatedBackground", "keepWallpaperOnGames", "backgroundShade", "readableText", + "showClock", "reduceMotion", "iconAppearance", "boxCovers", "igdb", "steamGridDB", "launchStyle", + "launchMotion", "launchShade", "surprisePool", "cloudSaves", "cloudSavesPickedFolder", "showsSessionCard", + "hiddenGames", "gameDefaults.fullscreen", "gameDefaults.enable60FPS", "gameDefaults.isDockedMode", + "gameDefaults.enableMetalFXUpscale", "gameDefaults.enableMetalHUD", "gameDefaults.language", + "gameDefaults.renderScale", "controllerStatus", "buttonLayout", "controllerDeadzone", "gameDefaults.rumble", + "gameDefaults.rumbleGain", "gameFolder", "libraryFolder", "libraryRefresh", "notifyPortingEnds", + "steamSource", "steamRefresh", "steamFolder", "steamInBackground", "storageUsage", "buildCaches", "logs", + "metadataCache", "artworkCache", "saveBackups", "console", "engineFolder", "engineStatus", + "toolchainOverride", "upstream", "newestEngine", "compare", "keys", "setup", "diagnostics", "appUpdates", + "projectDocs" + ] + + func testRowIDsAreUnchanged() { + XCTAssertEqual(SettingsCatalog.all.count, Self.rowIDs.count) + XCTAssertEqual(Set(SettingsCatalog.all.map(\.id)), Self.rowIDs) + } + + func testEveryRowSitsInItsNewSection() { + let groups = Dictionary(uniqueKeysWithValues: SettingsCatalog.all.map { ($0.id, $0.group) }) + for id in ["launchStyle", "launchMotion", "launchShade", "surprisePool", "showsSessionCard", "hiddenGames"] { + XCTAssertEqual(groups[id], .libraryGames, id) + } + XCTAssertEqual(groups["cloudSaves"], .cloudSaves) + XCTAssertEqual(groups["cloudSavesPickedFolder"], .cloudSaves) + XCTAssertEqual(groups["gameDefaults.rumble"], .games) + XCTAssertEqual(groups["gameDefaults.rumbleGain"], .games) + XCTAssertEqual(groups["keys"], .keys) + XCTAssertEqual(groups["buildCaches"], .portingStorage) + XCTAssertEqual(groups["console"], .console) + XCTAssertEqual(groups["logs"], .storage) + XCTAssertEqual(groups["controllerDeadzone"], .controllers) + } + + func testSidebarGroupsInOrder() { + let groups = SettingsSidebarGroup.all + XCTAssertEqual(groups.map(\.heading), [nil, "Settings group: General", "Settings group: Library", + "Settings group: Porting", "Settings group: System"]) + XCTAssertEqual(groups.map(\.sections), [ + [.search, .changed], + [.startUp, .navigation, .spotlight, .soundMusic, .look, .controllers, .apiServices], + [.sources, .libraryGames, .storage], + [.engine, .keys, .library, .games, .cloudSaves, .portingStorage], + [.about, .console], + ]) + XCTAssertEqual(groups.map(\.isPlatform), [false, false, false, true, false]) + XCTAssertEqual(SettingsSection.allCases, groups.flatMap(\.sections), "allCases follows the sidebar") + } + + func testPortingIsThePlatformGroup() { + XCTAssertEqual(SettingsSection.games.place(in: Self.english), "Porting · New games") + XCTAssertEqual(SettingsSection.engine.place(in: Self.english), "Porting · Setup and engine") + XCTAssertEqual(SettingsSection.sources.place(in: Self.english), "Sources") + XCTAssertEqual(SettingsSection.apiServices.title(in: Self.english), "Online services") + } + + func testGroupResetCoversMovedRows() { + var settings = AppSettings() + settings.launchMotion.toggle() + settings.showsSessionCard.toggle() + settings.gameDefaults.rumble.toggle() + settings.gameDefaults.fullscreen.toggle() + settings.cloudSavesPickedFolder = "/Volumes/Saves" + + let library = SettingsReset.reset(.libraryGames, in: settings) + XCTAssertEqual(library.launchMotion, AppSettings().launchMotion) + XCTAssertEqual(library.showsSessionCard, AppSettings().showsSessionCard) + XCTAssertEqual(library.gameDefaults.rumble, settings.gameDefaults.rumble, "Rumble is a new-game default") + XCTAssertEqual(library.cloudSavesPickedFolder, "/Volumes/Saves") + + let games = SettingsReset.reset(.games, in: settings) + XCTAssertEqual(games.gameDefaults, AppSettings().gameDefaults) + XCTAssertEqual(games.launchMotion, settings.launchMotion) + + XCTAssertFalse(SettingsReset.canReset(.cloudSaves)) + XCTAssertEqual(SettingsReset.reset(.cloudSaves, in: settings).cloudSavesPickedFolder, "/Volumes/Saves") + } + + func testOldSectionRawValuesStillDecode() { + for raw in ["search", "changed", "startUp", "navigation", "spotlight", "soundMusic", "look", "apiServices", + "controllers", "library", "games", "engine", "sources", "storage", "about"] { + XCTAssertNotNil(SettingsSection(rawValue: raw), raw) + } } + func testSwitchOnlyRowsLiveInTheSwitchSections() { + let groups = Dictionary(uniqueKeysWithValues: SettingsCatalog.all.map { ($0.id, $0.group) }) + XCTAssertEqual(groups["checkEngineAtLaunch"], .engine) + XCTAssertTrue(SettingsCatalog.all.filter { [.engine, .keys, .library, .games, .cloudSaves, .portingStorage].contains($0.group) } + .allSatisfy { $0.group.group.isPlatform }) + XCTAssertEqual(groups["setup"], .engine) + XCTAssertEqual(groups["refreshLibraryAtLaunch"], .library) + XCTAssertEqual(groups["boxCovers"], .library) + XCTAssertNil(groups["environment"], "Compatibility in Engine re-checks the environment") + XCTAssertFalse(SettingsCatalog.all.contains { $0.group == .startUp && !Self.generalStartUp.contains($0.id) }) + } + + func testEnvironmentIsFoundOnTheEnginePage() { + XCTAssertEqual(SettingsCatalog.search("environment").first { $0.id == "engineStatus" }?.group, .engine) + } + + private static let generalStartUp: Set<String> = [ + "appLanguage", "appRegion", "startOn", "restoreLastGame", "startInFullscreen", + "checkAppUpdatesAtLaunch", "introAnimation" + ] + func testSearchMatchesAboutText() { let titles = SettingsCatalog.search("crops").map(\.title) XCTAssertTrue(titles.contains("Wallpaper sizing")) @@ -34,7 +149,7 @@ final class SettingsCatalogTests: XCTestCase { } func testSessionCardIsAGamesRowThatCountsAsChanged() { - XCTAssertEqual(SettingsCatalog.search("Session card").first { $0.id == "showsSessionCard" }?.group, .games) + XCTAssertEqual(SettingsCatalog.search("Session card").first { $0.id == "showsSessionCard" }?.group, .libraryGames) var settings = AppSettings() settings.showsSessionCard = false XCTAssertEqual(SettingsCatalog.changed(in: settings).map(\.id), ["showsSessionCard"]) @@ -42,7 +157,16 @@ final class SettingsCatalogTests: XCTestCase { func testSearchFindsHiddenGames() { let hits = SettingsCatalog.search("hidden") - XCTAssertEqual(hits.first { $0.id == "hiddenGames" }?.group, .games) + XCTAssertEqual(hits.first { $0.id == "hiddenGames" }?.group, .libraryGames) + } + + func testPersonalAPIConnectionsShareAGeneralSectionWithoutChangingSourceIdentity() { + let connections = SettingsCatalog.all.filter { ["igdb", "steamGridDB"].contains($0.id) } + XCTAssertEqual(connections.map(\.group), [.apiServices, .apiServices]) + XCTAssertEqual(connections.map(\.id), ["igdb", "steamGridDB"]) + XCTAssertFalse(SettingsSection.apiServices.group.isPlatform) + XCTAssertEqual(SettingsSection.sources.place(in: Self.english), "Sources") + XCTAssertTrue(SettingsCatalog.search("API").contains { $0.group == .apiServices }) } func testEmptySearchReturnsNothing() { @@ -54,7 +178,7 @@ final class SettingsCatalogTests: XCTestCase { let controls: [(String, SettingsSection)] = [ ("60 FPS", .games), ("Fullscreen", .games), ("Metal HUD", .games), ("Render scale", .games), ("App icon", .look), - ("Stick navigation deadzone", .controllers), ("Cloud saves folder", .games), + ("Stick navigation deadzone", .controllers), ("Cloud saves folder", .cloudSaves), ("Engine repository", .engine), ("Game apps", .library), ("Game files", .library) ] for (name, group) in controls { diff --git a/Tests/NXLibraryCoreTests/SetupCheckTests.swift b/Tests/NXLibraryCoreTests/SetupCheckTests.swift index ba123b4d..c74b63c1 100644 --- a/Tests/NXLibraryCoreTests/SetupCheckTests.swift +++ b/Tests/NXLibraryCoreTests/SetupCheckTests.swift @@ -89,20 +89,20 @@ final class SetupCheckTests: XCTestCase { XCTAssertEqual(item(.engine).state, .ready) - // After an NX Library update the engine here is older than the pin: an update, not an error. + // After an Arcane update the engine here is older than the pin: an update, not an error. for behind in [true, nil] as [Bool?] { let update = item(.engine) { $0.engine = .checkout(head: "ee369f0", dirty: false); $0.engineBehind = behind } XCTAssertEqual(update.state, .warning, "still reopens Setup and runs with Install all") XCTAssertEqual(update.chip, "UPDATE READY") XCTAssertEqual(update.actionTitle, "Update") - XCTAssertEqual(update.detail, "This NX Library uses nxnative af616f5; the engine here is at ee369f0. Update downloads it and switches to it. Games you built keep playing.") + XCTAssertEqual(update.detail, "This version of Arcane uses nxnative af616f5; the engine here is at ee369f0. Update downloads it and switches to it. Games you built keep playing.") } // A checkout ahead of the pin (or on another branch) is moved back, said as such. let ahead = item(.engine) { $0.engine = .checkout(head: "ee369f0", dirty: false); $0.engineBehind = false } XCTAssertEqual(ahead.state, .warning) XCTAssertEqual(ahead.chip, "OTHER VERSION") XCTAssertEqual(ahead.actionTitle, "Switch") - XCTAssertEqual(ahead.detail, "The engine here is at ee369f0, not the af616f5 this NX Library is tested with. Switch moves it to af616f5. Games you built keep playing.") + XCTAssertEqual(ahead.detail, "The engine here is at ee369f0, not the af616f5 this version of Arcane is tested with. Switch moves it to af616f5. Games you built keep playing.") let dirty = item(.engine) { $0.engine = .checkout(head: "ee369f0", dirty: true) } XCTAssertEqual(dirty.state, .warning) diff --git a/Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift b/Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift new file mode 100644 index 00000000..367db6b2 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift @@ -0,0 +1,131 @@ +import XCTest +@testable import NXLibraryCore + +final class SharedGamePresentationTests: XCTestCase { + private func installation(_ name: String, availability: CatalogInstallationAvailability, + size: Int64) -> SteamCatalogInstallation { + let root = URL(fileURLWithPath: "/Volumes/\(name)/Steam") + let content = root.appendingPathComponent("steamapps/common/Fixture") + let app = content.appendingPathComponent("Game.app") + let native = CatalogNativeApplication(NativeMacApplication( + url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"), + bundleIdentifier: "test.\(name)", name: "Fixture", architectures: [.arm64], + isDeclaredGame: true, fileObservations: [])) + return SteamCatalogInstallation(libraryURL: root, contentURL: content, applications: [native], + availability: availability, reportedSizeBytes: size, + lastObservedAt: Date(timeIntervalSince1970: 0)) + } + + func testSteamArtworkAndDetailsKeepFirstAvailableInCatalogOrderWhileAmbiguousPlayIsBlocked() { + var steam = SteamCatalogGame(appID: 42, name: "Fixture") + steam.hasBeenRecognized = true + steam.installations = [installation("Old", availability: .notDetected, size: 1_000_000_000), + installation("First", availability: .available, size: 140_000_000_000), + installation("Second", availability: .available, size: 2_000_000_000)] + let game = CatalogGame(steam: steam) + let expected = "/Volumes/First/Steam/steamapps/common/Fixture/Game.app" + XCTAssertEqual(SteamArtworkRequest(game: game, role: .square).application?.url.path, expected) + let page = GameDetailPresentation(steamRecord: game, metadata: nil, totalPlaytime: 0, lastPlayed: nil) + XCTAssertEqual(page.appPath, expected) + let facts = DetailsFacts.steamGame(game, metadata: nil, volumeName: "First", locale: Locale(identifier: "en_US")) + XCTAssertEqual(facts.first { $0.kind == .size }?.value, "140 GB") + let launch = CatalogGamePresentation(game: game, sourceEnabled: true) + XCTAssertTrue(launch.requiresReview) + XCTAssertNil(launch.launchTarget) + } + + func testSteamArtworkAndDetailsIgnoreHistoricalAndUnavailableInstallations() { + for availability in [CatalogInstallationAvailability.unavailable, .notDetected, .sourceUnavailable, .requiresReview] { + var steam = SteamCatalogGame(appID: 42, name: "Fixture") + steam.hasBeenRecognized = true + steam.installations = [installation("Old", availability: availability, size: 140_000_000_000)] + let game = CatalogGame(steam: steam) + XCTAssertNil(SteamArtworkRequest(game: game, role: .square).application) + let page = GameDetailPresentation(steamRecord: game, metadata: nil, totalPlaytime: 0, lastPlayed: nil) + XCTAssertEqual(page.appPath, "") + XCTAssertEqual(DetailsFacts.steamGame(game, metadata: nil, volumeName: "Old"), []) + XCTAssertNil(CatalogGamePresentation(game: game, sourceEnabled: true).launchTarget) + } + } + + func testSteamPresentationKeepsIdentityPersonalOverridesAndHistory() throws { + let body = Data(""" + {"10":{"success":true,"data":{"steam_appid":10,"short_description":"Store text","genres":[{"description":"Strategy"}],"publishers":["Studio"],"release_date":{"date":"23 mag 2023"}}}} + """.utf8) + let facts = try SteamMetadata.decode(body, appID: 10, language: "italian") + let record = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Fixture")) + let result = LibraryPresentation(game: record, steamMetadata: facts, + overrides: [.description: "Personal", .genres: "Puzzle, Adventure"], + totalPlaytime: 7200, lastPlayed: nil) + XCTAssertEqual(result.title, "Fixture") + XCTAssertEqual(result.platform, "Steam") + XCTAssertEqual(result.console, "Steam") + XCTAssertEqual(result.summary, "Personal") + XCTAssertEqual(result.publisher, "Studio") + XCTAssertEqual(result.releaseYear, "2023") + XCTAssertEqual(result.genres.count, 2) + XCTAssertEqual(result.playtime, "2h 0m") + XCTAssertFalse(result.sourcesDetached) + } + func testNXDisplayRemainsEqualThroughCommonBoundary() { + let game = CatalogTestSupport.completeLegacyGame() + let direct = LibraryPresentation(game: game, metadata: nil, totalPlaytime: 100, lastPlayed: nil) + let common = LibraryPresentation(game: CatalogGame(nxnative: game), steamMetadata: nil, + totalPlaytime: 100, lastPlayed: nil) + XCTAssertEqual(common, direct) + } + func testPersonalFieldsRemainVisibleWithoutRemoteMetadata() { + let game = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Local title")) + let result = LibraryPresentation(game: game, steamMetadata: nil, overrides: [.description: "Offline choice", .publisher: "Mine"], + totalPlaytime: 0, lastPlayed: nil) + XCTAssertEqual(result.summary, "Offline choice") + XCTAssertEqual(result.publisher, "Mine") + XCTAssertEqual(result.title, "Local title") + } + func testSquareRoleDoesNotUsePortraitArtwork() { + XCTAssertEqual(LibraryArtworkRole.square.slot, .icon) + XCTAssertEqual(LibraryArtworkRole.cover.slot, .cover) + XCTAssertEqual(LibraryArtworkRole.hero.slot, .background) + XCTAssertEqual(LibraryArtworkRole.logo.slot, .logo) + } + func testCommonOptionsHaveSameOrderAndSourceActionsStaySeparate() { + XCTAssertEqual(CatalogGameOptions.commonRows(origin: .spotlight), + [.play, .editDetails, .move, .favorite, .hidden, .showInFinder]) + XCTAssertEqual(CatalogGameOptions.commonRows(origin: .collection), + [.play, .editDetails, .favorite, .hidden, .showInFinder]) + let options = SteamOptionsPresentation(canPlay: true, hasApp: true) + let steam = Set([GameOptionsLevel.main, .editDetails].flatMap { level in + options.entries(level: level, origin: .spotlight).compactMap { entry -> GameOptionsRow? in + if case .row(let row) = entry { return row } else { return nil } + } + }) + XCTAssertTrue(steam.isDisjoint(with: [.fullscreen, .frameRate, .consoleMode, .rebuild, .openSaves, .removeSources, + .cheats, .mods, .attachSources, .openLog])) + } + + func testSteamPagePresentationClaimsNothingFromNxnative() throws { + let body = Data(""" + {"10":{"success":true,"data":{"steam_appid":10,"short_description":"Store text","genres":[{"description":"Strategy"}],"developers":["Dev Studio"],"publishers":["Studio"],"release_date":{"date":"23 mag 2023"}}}} + """.utf8) + let facts = try SteamMetadata.decode(body, appID: 10, language: "italian") + let record = CatalogGame(steam: SteamCatalogGame(appID: 10, name: "Fixture")) + let other = CatalogGame(steam: SteamCatalogGame(appID: 20, name: "Other")) + let page = GameDetailPresentation(steamRecord: record, metadata: facts, overrides: [.publisher: "Mine"], + totalPlaytime: 60, lastPlayed: nil, + libraryGames: [record, other], playtimeByGame: [other.id: 120]) + XCTAssertEqual(page.console, "Steam") + XCTAssertEqual(page.description, "Store text") + XCTAssertEqual(page.released, "23 mag 2023") + XCTAssertEqual(page.releaseYear, "2023") + XCTAssertEqual(page.developerLine, "Dev Studio") + XCTAssertEqual(page.publisher, "Mine") + XCTAssertEqual(page.rank, "#2 of 2") + XCTAssertEqual(page.storeURL?.absoluteString, "https://store.steampowered.com/app/10/") + XCTAssertFalse(page.canPlay); XCTAssertFalse(page.canRebuild); XCTAssertFalse(page.sourcesDetached) + XCTAssertEqual(page.savePath, ""); XCTAssertEqual(page.engineCommitShort, "—") + // Facts delivered for another game never reach this page. + let stray = GameDetailPresentation(steamRecord: other, metadata: facts, totalPlaytime: 0, lastPlayed: nil) + XCTAssertEqual(stray.description, "") + XCTAssertNil(stray.rank) + } +} diff --git a/Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift b/Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift new file mode 100644 index 00000000..f13036d0 --- /dev/null +++ b/Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift @@ -0,0 +1,25 @@ +import XCTest + +/// Screens read the keyboard through their own `NSEvent` monitors. A shell overlay drawn on top of them +/// (the update offer, the welcome) must make every such monitor let the key go, or Return reaches the screen +/// underneath: a game starts instead of the overlay's button. +final class ShellOverlayInputTests: XCTestCase { + private var views: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("Sources/NXLibrary/Views") + } + + func testEveryMonitorThatYieldsToTheUpdateOfferYieldsToTheWelcome() throws { + let files = FileManager.default.enumerator(at: views, includingPropertiesForKeys: nil)? + .compactMap { $0 as? URL }.filter { $0.pathExtension == "swift" } ?? [] + var missing: [String] = [] + for file in files { + let text = try String(contentsOf: file, encoding: .utf8) + let offer = text.components(separatedBy: "!viewModel.isUpdateOfferOpen").count - 1 + let welcome = text.components(separatedBy: "!viewModel.isWelcomeOpen").count - 1 + if offer != welcome { missing.append("\(file.lastPathComponent): \(offer) vs \(welcome)") } + } + XCTAssertFalse(files.isEmpty) + XCTAssertEqual(missing.sorted(), []) + } +} diff --git a/Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift b/Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift new file mode 100644 index 00000000..3f0365cc --- /dev/null +++ b/Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift @@ -0,0 +1,167 @@ +import CoreGraphics +import XCTest +@testable import NXLibraryCore + +final class SpotlightEntranceTests: XCTestCase { + private let row: CGFloat = 1760 + + /// Tiles of side 174 with a gap of 26, the first one starting at `start`. + private func tiles(_ count: Int, from start: CGFloat = 80) -> [ClosedRange<CGFloat>] { + (0..<count).map { index in + let lower = start + CGFloat(index) * 200 + return lower...(lower + 174) + } + } + + func testFirstTileFliesInFromTheCentreWhileItGrows() throws { + let flight = try XCTUnwrap(SpotlightEntrance.flights(tiles: [80...254], rowWidth: row).first ?? nil) + XCTAssertEqual(flight.delay, 0.6, accuracy: 0.0001) + XCTAssertEqual(flight.fromScale, 0.35, accuracy: 0.0001) + XCTAssertEqual(flight.fromY, -18, accuracy: 0.0001) + XCTAssertEqual(flight.duration, 0.9, accuracy: 0.0001) + XCTAssertEqual(flight.fadeDuration, 0.5, accuracy: 0.0001) + XCTAssertEqual(flight.fromX, (880 - 167) * 0.75, accuracy: 0.0001) + XCTAssertFalse(flight.fadesOnly) + } + + func testDelayGrowsBySixtyMillisecondsPerFlownTile() throws { + let flights = SpotlightEntrance.flights(tiles: tiles(3), rowWidth: row) + let third = try XCTUnwrap(flights[2]) + XCTAssertEqual(third.delay, 0.72, accuracy: 0.0001) + } + + func testTilesLeftOfTheStageDoNotFly() throws { + let flights = SpotlightEntrance.flights(tiles: [(-300)...(-126), 80...254], rowWidth: row) + XCTAssertNil(flights[0]) + let first = try XCTUnwrap(flights[1]) + XCTAssertEqual(first.delay, 0.6, accuracy: 0.0001, "a tile off the left edge does not count") + } + + func testTilesPastTheRightEdgeOnlyFade() throws { + // Two on the stage, then fourteen past its right edge. + let flights = SpotlightEntrance.flights(tiles: tiles(2, from: 1400) + tiles(14, from: 1800), rowWidth: row) + let firstLate = try XCTUnwrap(flights[2]) + XCTAssertTrue(firstLate.fadesOnly) + XCTAssertEqual(firstLate.delay, 0.6 + 2 * 0.06, accuracy: 0.0001) + XCTAssertEqual(firstLate.fromScale, 1) + XCTAssertEqual(firstLate.fromX, 0) + XCTAssertEqual(firstLate.fromY, 0) + let secondLate = try XCTUnwrap(flights[3]) + XCTAssertEqual(secondLate.delay, firstLate.delay, accuracy: 0.0001, "fading tiles do not move the schedule") + XCTAssertNotNil(flights[13], "the twelfth tile past the edge still fades") + XCTAssertNil(flights[14], "the thirteenth and later stay as they are") + XCTAssertNil(flights[15]) + } + + func testDurationEndsWithTheLastLanding() { + let flights = SpotlightEntrance.flights(tiles: tiles(10, from: 0), rowWidth: 2000) + XCTAssertEqual(SpotlightEntrance.duration(of: flights), 0.6 + 9 * 0.06 + 0.9, accuracy: 0.0001) + XCTAssertEqual(SpotlightEntrance.duration(of: []), 0) + } + + func testPlaysOnlyOnFirstSpotlightWithTheSwitchOnAndWithoutReduceMotion() { + XCTAssertTrue(SpotlightEntrance.plays(isFirstHome: true, route: .library, reduceMotion: false, enabled: true)) + XCTAssertFalse(SpotlightEntrance.plays(isFirstHome: true, route: .collection, reduceMotion: false, enabled: true)) + XCTAssertFalse(SpotlightEntrance.plays(isFirstHome: true, route: .library, reduceMotion: true, enabled: true)) + XCTAssertFalse(SpotlightEntrance.plays(isFirstHome: false, route: .library, reduceMotion: false, enabled: true)) + XCTAssertFalse(SpotlightEntrance.plays(isFirstHome: true, route: .library, reduceMotion: false, enabled: false), + "Settings → Start-up → Entrance off: the library shows at once") + } + + func testNoInputUntilTheEntranceHasLanded() { + for phase: SpotlightEntrance.Phase in [.covered, .waiting, .playing] { + XCTAssertFalse(phase.takesInput, "no key, click, wheel or press skips the entrance (\(phase))") + } + XCTAssertTrue(SpotlightEntrance.Phase.landed.takesInput) + } + + func testTopBarAndHintsComeInLast() { + XCTAssertEqual(SpotlightEntrance.controlsFade, 0.4, "top bar and button hints fade in together once everything has landed") + } + + func testAStartedFlightAlwaysLandsWellAfterTheLongest() { + let flights = SpotlightEntrance.flights(tiles: (0..<30).map { CGFloat($0 * 190)...CGFloat($0 * 190 + 174) }, + rowWidth: 1920) + XCTAssertGreaterThan(SpotlightEntrance.longestWait, SpotlightEntrance.end(of: flights) + 1) + XCTAssertLessThanOrEqual(SpotlightEntrance.longestWait, 5) + } + + func testLandingPutsAWaitingOrPlayingEntranceInPlace() { + var waiting = SpotlightEntrance.Phase.waiting + waiting.land() + XCTAssertEqual(waiting, .landed) + + var playing = SpotlightEntrance.Phase.playing + playing.land() + XCTAssertEqual(playing, .landed) + + var landed = SpotlightEntrance.Phase.landed + landed.uncover() + landed.start() + XCTAssertEqual(landed, .landed, "a landed entrance never plays again") + } + + func testCoveredWaitsUntilUncovered() { + var phase = SpotlightEntrance.Phase.covered + phase.start() + XCTAssertEqual(phase, .covered, "nothing flies under the intro or the welcome") + phase.uncover() + XCTAssertEqual(phase, .waiting) + phase.start() + XCTAssertEqual(phase, .playing) + } + + func testABreathOnTheMoonlightThenASlowBackground() { + XCTAssertEqual(SpotlightEntrance.hold, 0.5) + XCTAssertEqual(SpotlightEntrance.backgroundDuration, 1.4) + XCTAssertEqual(SpotlightEntrance.infoDelay, 1.3) + XCTAssertEqual(SpotlightEntrance.infoFade, 0.7) + XCTAssertEqual(SpotlightEntrance.infoLift, 40) + XCTAssertEqual(SpotlightEntrance.infoLiftDuration, 0.8) + XCTAssertEqual(SpotlightEntrance.titleDelay, 2.0) + } + func testFlightEasesOutAndFadesOnItsOwnClock() throws { + let flight = try XCTUnwrap(SpotlightEntrance.flights(tiles: [80...254], rowWidth: row)[0]) + XCTAssertEqual(flight.move(at: 0), 0) + XCTAssertEqual(flight.move(at: 0.45), 1 - 0.125, accuracy: 0.0001, "cubic out at half time") + XCTAssertEqual(flight.move(at: 0.9), 1) + XCTAssertEqual(flight.move(at: 2), 1) + XCTAssertEqual(flight.opacity(at: 0.25), 0.5, accuracy: 0.0001, "linear fade") + XCTAssertEqual(flight.opacity(at: 0.5), 1) + XCTAssertEqual(flight.length, 0.9) + } + + func testFadeOnlyFlightNeverMoves() throws { + let flights = SpotlightEntrance.flights(tiles: [1800...1974], rowWidth: row) + let late = try XCTUnwrap(flights[0]) + XCTAssertEqual(late.move(at: 0), 1) + XCTAssertEqual(late.length, 0.4) + } + + func testInfoRisesFortyUnitsAfterTheBackground() { + let info = SpotlightEntrance.info + XCTAssertEqual(info.delay, 1.3) + XCTAssertEqual(info.fromY, 40) + XCTAssertEqual(info.fromX, 0) + XCTAssertEqual(info.fromScale, 1) + XCTAssertEqual(info.duration, 0.8) + XCTAssertEqual(info.fadeDuration, 0.7) + } + + func testEmptyMessageComesJustAfterTheLastTile() { + let flights = SpotlightEntrance.flights(tiles: tiles(2), rowWidth: row) + let message = SpotlightEntrance.message(after: flights) + XCTAssertEqual(message.delay, 0.6 + 2 * 0.06 + 0.25, accuracy: 0.0001) + XCTAssertTrue(message.fadesOnly) + XCTAssertEqual(SpotlightEntrance.message(after: []).delay, 0.85, accuracy: 0.0001) + } + + func testEntranceEndsWhenEverythingIsIn() { + // Ten tiles land at 2.04 s; the info is in at 2.1 s. + let flights = SpotlightEntrance.flights(tiles: tiles(10, from: 0), rowWidth: 2000) + XCTAssertEqual(SpotlightEntrance.end(of: flights), 2.1, accuracy: 0.0001) + // Twenty tiles land at 0.6 + 19 × 0.06 + 0.9 = 2.64 s. + let many = SpotlightEntrance.flights(tiles: tiles(20, from: 0), rowWidth: 4000) + XCTAssertEqual(SpotlightEntrance.end(of: many), 2.64, accuracy: 0.0001) + } +} diff --git a/Tests/NXLibraryCoreTests/SpotlightPageTests.swift b/Tests/NXLibraryCoreTests/SpotlightPageTests.swift index d42c58a3..9b794680 100644 --- a/Tests/NXLibraryCoreTests/SpotlightPageTests.swift +++ b/Tests/NXLibraryCoreTests/SpotlightPageTests.swift @@ -57,7 +57,7 @@ final class SpotlightPageTests: XCTestCase { func testShortPageNeverScrollsPastItsEnd() { let rest = SpotlightPageScroll.resting(first: -324, aboutTop: 700, moreTop: 1000, pageBottom: 1300, top: 150, viewport: 1000, bottomInset: 130) - XCTAssertEqual(rest.actions, -430, "the page's end limits Build & Sources too") + XCTAssertEqual(rest.actions, -430, "the page's end limits Details too") XCTAssertEqual(rest.more, -430) } diff --git a/Tests/NXLibraryCoreTests/SpotlightRowTests.swift b/Tests/NXLibraryCoreTests/SpotlightRowTests.swift index 1c8e607f..429a2261 100644 --- a/Tests/NXLibraryCoreTests/SpotlightRowTests.swift +++ b/Tests/NXLibraryCoreTests/SpotlightRowTests.swift @@ -31,7 +31,7 @@ final class SpotlightRowTests: XCTestCase { func testCardsThenGames() { let a = game("a"), b = game("b") - let row = SpotlightRow.build(games: [a, b], + let row = SpotlightRow.build(gameIDs: [a, b].map(\.id), enabledCards: [.surprise, .activity, .addGame], order: []) XCTAssertEqual(row, [.card(.surprise), .card(.activity), .card(.addGame), .game(a.id), .game(b.id)]) @@ -39,7 +39,7 @@ final class SpotlightRowTests: XCTestCase { func testDisabledCardsDropped() { let a = game("a") - let row = SpotlightRow.build(games: [a], enabledCards: [.addGame, .collection], order: []) + let row = SpotlightRow.build(gameIDs: [a].map(\.id), enabledCards: [.addGame, .collection], order: []) XCTAssertEqual(row, [.card(.collection), .card(.addGame), .game(a.id)]) } @@ -48,21 +48,21 @@ final class SpotlightRowTests: XCTestCase { let order = [SpotlightItem.game(b.id).key, SpotlightItem.card(.activity).key, SpotlightItem.game(a.id).key, SpotlightItem.card(.surprise).key, "game:\(UUID().uuidString)"] - let row = SpotlightRow.build(games: [a, b], enabledCards: [.surprise, .activity], order: order) + let row = SpotlightRow.build(gameIDs: [a, b].map(\.id), enabledCards: [.surprise, .activity], order: order) XCTAssertEqual(row, [.game(b.id), .card(.activity), .game(a.id), .card(.surprise)]) } func testNewGameNotInOrderAppendsAfterOrdered() { let a = game("a"), b = game("b"), c = game("c") let order = [SpotlightItem.game(a.id).key, SpotlightItem.game(b.id).key] - let row = SpotlightRow.build(games: [a, b, c], enabledCards: [.surprise], order: order) + let row = SpotlightRow.build(gameIDs: [a, b, c].map(\.id), enabledCards: [.surprise], order: order) XCTAssertEqual(row, [.card(.surprise), .game(a.id), .game(b.id), .game(c.id)]) } func testNewGameFollowsItsDefaultPredecessor() { let a = game("a"), b = game("b"), c = game("c") let order = [SpotlightItem.game(b.id).key, SpotlightItem.game(a.id).key] - let row = SpotlightRow.build(games: [a, b, c], enabledCards: [], order: order) + let row = SpotlightRow.build(gameIDs: [a, b, c].map(\.id), enabledCards: [], order: order) // c followed b in the default sequence, so it stays right after b. XCTAssertEqual(row, [.game(b.id), .game(c.id), .game(a.id)]) } @@ -79,7 +79,7 @@ final class SpotlightRowTests: XCTestCase { } func testEmptyGamesStillReturnsCards() { - let row = SpotlightRow.build(games: [], enabledCards: [.surprise, .addGame], order: []) + let row = SpotlightRow.build(gameIDs: [], enabledCards: [.surprise, .addGame], order: []) XCTAssertEqual(row, [.card(.surprise), .card(.addGame)]) } @@ -120,6 +120,21 @@ final class SpotlightRowTests: XCTestCase { } final class SpotlightRowMergeTests: XCTestCase { + func testSavingVisibleMoveRetainsDisabledHiddenAndCardPositions() { + let a = UUID(), steam = UUID(), hidden = UUID(), b = UUID() + let key: (UUID) -> String = { SpotlightItem.game($0).key } + let saved = [key(a), key(steam), key(hidden), key(b), SpotlightItem.card(.mods).key] + // Only A and B are visible; Steam is disabled, another game hidden, + // and Mods disabled. All still belong to the saved layout. + let changed = SpotlightRow.saving(visibleOrder: [key(b), key(a)], + gameIDs: [a, steam, hidden, b], previousOrder: saved) + let restored = SpotlightRow.build(gameIDs: [a, steam, hidden, b], enabledCards: [], order: changed) + XCTAssertEqual(restored, [.game(b), .game(steam), .game(hidden), .game(a)]) + XCTAssertTrue(changed.contains(SpotlightItem.card(.mods).key)) + let back = SpotlightRow.saving(visibleOrder: [key(a), key(b)], gameIDs: [a, steam, hidden, b], previousOrder: changed) + XCTAssertEqual(SpotlightRow.build(gameIDs: [a, steam, hidden, b], enabledCards: [], order: back), + [.game(a), .game(steam), .game(hidden), .game(b)]) + } func testFilteredMoveKeepsHiddenSlots() { // Saved A…E as D,A,B,C,E; Installed shows A,C,E; C moved first. let merged = SpotlightRow.merging(visibleOrder: ["C", "A", "E"], @@ -139,3 +154,34 @@ final class SpotlightRowMergeTests: XCTestCase { } } + +/// A game that starts becomes the first game of the row, the rest of a saved order staying as it was. +final class SpotlightRowPlayedTests: XCTestCase { + private let a = UUID(), b = UUID(), c = UUID(), d = UUID() + private func key(_ id: UUID) -> String { SpotlightItem.game(id).key } + private var cards: [String] { SpotlightCard.allCases.map { SpotlightItem.card($0).key } } + + func testPlayedGameBecomesTheFirstGame() { + let order = SpotlightRow.playing(c, previousOrder: cards + [key(a), key(b), key(c)]) + XCTAssertEqual(SpotlightRow.build(gameIDs: [a, b, c], enabledCards: [], order: order), [.game(c), .game(a), .game(b)]) + XCTAssertEqual(order, cards + [key(c), key(a), key(b)]) + } + + func testCardsPlacedAmongGamesStayWhereTheyAre() { + let mods = SpotlightItem.card(.mods).key + XCTAssertEqual(SpotlightRow.playing(b, previousOrder: [key(a), mods, key(b)]), [key(b), key(a), mods]) + } + + func testAGameNotInTheSavedOrderIsPlacedFirst() { + XCTAssertEqual(SpotlightRow.playing(d, previousOrder: cards + [key(a), key(b)]), cards + [key(d), key(a), key(b)]) + } + + func testNoSavedOrderStaysEmptyBecauseRecencyAlreadyLeads() { + XCTAssertEqual(SpotlightRow.playing(a, previousOrder: []), []) + } + + func testTheFirstGameStaysPut() { + let order = cards + [key(a), key(b)] + XCTAssertEqual(SpotlightRow.playing(a, previousOrder: order), order) + } +} diff --git a/Tests/NXLibraryCoreTests/SpotlightStateTests.swift b/Tests/NXLibraryCoreTests/SpotlightStateTests.swift index 4e867982..4761ebf6 100644 --- a/Tests/NXLibraryCoreTests/SpotlightStateTests.swift +++ b/Tests/NXLibraryCoreTests/SpotlightStateTests.swift @@ -152,6 +152,74 @@ final class SpotlightStateTests: XCTestCase { XCTAssertNil(SpotlightState(selectedKey: SpotlightItem.card(.collection).key).selectedGameID) XCTAssertNil(SpotlightState().selectedGameID) } + // MARK: - Achievements card + + private func gameState(_ focus: SpotlightFocusArea) -> SpotlightState { + var state = SpotlightState(selectedKey: SpotlightItem.game(UUID()).key) + state.focus = focus + return state + } + + func testDownFromStripEntersAchievements() { + var state = gameState(.strip) + XCTAssertTrue(state.moveDown(selectedIsGame: true, screenshotCount: 3, actionCount: 4, hasAchievements: true)) + XCTAssertEqual(state.focus, .achievements) + } + + func testDownFromAchievementsEntersActions() { + var state = gameState(.achievements) + XCTAssertTrue(state.moveDown(selectedIsGame: true, screenshotCount: 3, actionCount: 4, hasAchievements: true)) + XCTAssertEqual(state.focus, .actions) + XCTAssertEqual(state.actionIndex, 0) + } + + func testUpFromActionsFirstRowReturnsToAchievements() { + var state = gameState(.actions) + state.actionIndex = 1 + XCTAssertTrue(state.moveUp(screenshotCount: 3, actionCount: 4, hasAchievements: true)) + XCTAssertEqual(state.focus, .achievements) + } + + func testUpFromAboutSkipsTheCardBesideIt() { + var about = gameState(.about) + XCTAssertTrue(about.moveUp(screenshotCount: 3, actionCount: 4, hasAchievements: true)) + XCTAssertEqual(about.focus, .strip) + } + + func testReadMoreAndTheCardSitSideBySide() { + var state = gameState(.about) + XCTAssertTrue(state.moveSideways(by: 1, screenshotCount: 3, actionCount: 4, readMore: true, hasAchievements: true)) + XCTAssertEqual(state.focus, .achievements) + XCTAssertTrue(state.moveSideways(by: -1, screenshotCount: 3, actionCount: 4, readMore: true, hasAchievements: true)) + XCTAssertEqual(state.focus, .about) + // Without the card Right goes to the actions, as before. + XCTAssertTrue(state.moveSideways(by: 1, screenshotCount: 3, actionCount: 4, readMore: true)) + XCTAssertEqual(state.focus, .actions) + } + + func testWithoutAchievementsThePathIsUnchanged() { + var state = gameState(.strip) + state.moveDown(selectedIsGame: true, screenshotCount: 3, actionCount: 4) + XCTAssertEqual(state.focus, .actions) + state.moveUp(screenshotCount: 3, actionCount: 4) + XCTAssertEqual(state.focus, .strip) + } + + func testUpFromAchievementsWithoutScreenshotsGoesToPills() { + var state = gameState(.achievements) + XCTAssertTrue(state.moveUp(screenshotCount: 0, actionCount: 4, hasAchievements: true)) + XCTAssertEqual(state.focus, .pills) + var pills = gameState(.pills) + pills.moveDown(selectedIsGame: true, screenshotCount: 0, actionCount: 4, hasAchievements: true) + XCTAssertEqual(pills.focus, .achievements) + } + + func testSidewaysOnAchievementsWithoutReadMoreDoesNothing() { + var state = gameState(.achievements) + XCTAssertFalse(state.moveSideways(by: 1, screenshotCount: 3, actionCount: 4, hasAchievements: true)) + XCTAssertFalse(state.moveSideways(by: -1, screenshotCount: 3, actionCount: 4, hasAchievements: true)) + XCTAssertEqual(state.focus, .achievements) + } } final class SpotlightLiftTests: XCTestCase { @@ -388,4 +456,5 @@ final class SpotlightLiftTests: XCTestCase { XCTAssertEqual(s.focus, .strip) XCTAssertEqual(s.stripIndex, 4) } + } diff --git a/Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift b/Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift new file mode 100644 index 00000000..20dc76a4 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift @@ -0,0 +1,171 @@ +import XCTest +import ImageIO +import UniformTypeIdentifiers +@testable import NXLibraryCore + +final class SteamAchievementRarityTests: XCTestCase { + private var root: URL! + private actor Calls { var count = 0; func bump() { count += 1 } } + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("SteamRarity-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: root) + super.tearDown() + } + + private let body = Data(#"{"achievementpercentages":{"achievements":[{"name":"A","percent":"80.0"},{"name":"B","percent":4.5}]}}"#.utf8) + + func testDecodesNumbersAndStrings() throws { + XCTAssertEqual(try SteamAchievementRarity.decode(body), ["A": 80.0, "B": 4.5]) + } + + /// A percent that is not a number (`"nan"`, `"inf"`) is no rarity: clamping left NaN as it was. + func testANonFinitePercentIsLeftOut() throws { + let body = Data(#"{"achievementpercentages":{"achievements":[{"name":"A","percent":"nan"},{"name":"B","percent":"inf"},{"name":"C","percent":"12.5"}]}}"#.utf8) + XCTAssertEqual(try SteamAchievementRarity.decode(body), ["C": 12.5]) + } + + /// A file that failed a moment ago fails at once, without waiting for a free download behind six others. + func testARecentFailureDoesNotWaitForASlot() async throws { + let png = try Self.png() + let failing = Calls() + let service = SteamMetadataService(directory: root, transport: { url in + if url.lastPathComponent == "bad.jpg" { await failing.bump(); throw URLError(.badServerResponse) } + try await Task.sleep(nanoseconds: 400_000_000) + return png + }) + let first = await service.achievementIcon(appID: 7, file: "bad.jpg") + XCTAssertNil(first) + let busy = (0..<6).map { index in Task { await service.achievementIcon(appID: 7, file: "busy\(index).jpg") } } + try await Task.sleep(nanoseconds: 50_000_000) + let started = Date() + let again = await service.achievementIcon(appID: 7, file: "bad.jpg") + XCTAssertNil(again) + XCTAssertLessThan(Date().timeIntervalSince(started), 0.2) + let count = await failing.count + XCTAssertEqual(count, 1) + for task in busy { _ = await task.value } + } + + func testMalformedThrows() { + XCTAssertThrowsError(try SteamAchievementRarity.decode(Data("{}".utf8))) + XCTAssertThrowsError(try SteamAchievementRarity.decode(Data("<html>".utf8))) + } + + func testIconURLRefusesPaths() { + XCTAssertEqual(SteamAchievementRarity.iconURL(appID: 7, file: "ab12.jpg")?.absoluteString, + "https://shared.akamai.steamstatic.com/community_assets/images/apps/7/ab12.jpg") + XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: "../x.jpg")) + XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: "a/b.jpg")) + XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: "x.exe")) + XCTAssertNil(SteamAchievementRarity.iconURL(appID: 7, file: ".jpg")) + } + + func testOnlyThePercentagesPathIsAllowed() { + XCTAssertTrue(SteamMetadataService.allowed(SteamAchievementRarity.url(appID: 7))) + XCTAssertFalse(SteamMetadataService.allowed(URL(string: "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/")!)) + XCTAssertFalse(SteamMetadataService.allowed(URL(string: "http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=7")!)) + } + + func testPercentsAreCachedForADay() async { + let calls = Calls(), body = body + let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return body }) + let first = await service.achievementPercents(appID: 7) + let second = await service.achievementPercents(appID: 7) + XCTAssertEqual(first, ["A": 80, "B": 4.5]) + XCTAssertEqual(second, first) + let count = await calls.count + XCTAssertEqual(count, 1) + } + + func testOfflineKeepsTheStaleCache() async throws { + let file = root.appendingPathComponent("7/achievement-percents.json") + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(#"{"fetchedAt":0,"percents":{"A":12}}"#.utf8).write(to: file) + let service = SteamMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) }) + let percents = await service.achievementPercents(appID: 7) + XCTAssertEqual(percents, ["A": 12]) + } + + func testNothingCachedAndOfflineIsNil() async { + let service = SteamMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) }) + let percents = await service.achievementPercents(appID: 7) + XCTAssertNil(percents) + } + + func testIconIsCachedAndReused() async throws { + let calls = Calls(), png = try Self.png() + let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return png }) + let first = await service.achievementIcon(appID: 7, file: "ab.jpg") + let second = await service.achievementIcon(appID: 7, file: "ab.jpg") + XCTAssertEqual(first?.lastPathComponent, "ab.jpg") + XCTAssertEqual(second, first) + let count = await calls.count + XCTAssertEqual(count, 1) + } + + /// A screen of icons asks for more than the six downloads at once: the rest wait their turn instead of + /// failing, and no more than six run together. + func testIconsBeyondTheConcurrencyLimitWaitTheirTurn() async throws { + let gauge = Gauge(), png = try Self.png() + let service = SteamMetadataService(directory: root, transport: { _ in + await gauge.enter() + try await Task.sleep(nanoseconds: 30_000_000) + await gauge.leave() + return png + }) + let icons = await withTaskGroup(of: URL?.self) { group in + for index in 0..<15 { group.addTask { await service.achievementIcon(appID: 7, file: "icon\(index).jpg") } } + return await group.reduce(into: [URL?]()) { $0.append($1) } + } + XCTAssertEqual(icons.compactMap { $0 }.count, 15) + let peak = await gauge.peak + XCTAssertLessThanOrEqual(peak, 6) + } + + /// A request still waiting for its turn ends when its row goes away. + func testAWaitingIconRequestCanBeCancelled() async throws { + let png = try Self.png() + let service = SteamMetadataService(directory: root, transport: { _ in + try await Task.sleep(nanoseconds: 300_000_000) + return png + }) + let busy = (0..<6).map { index in Task { await service.achievementIcon(appID: 7, file: "busy\(index).jpg") } } + try await Task.sleep(nanoseconds: 50_000_000) + let waiting = Task { await service.achievementIcon(appID: 7, file: "late.jpg") } + try await Task.sleep(nanoseconds: 50_000_000) + let started = Date() + waiting.cancel() + let late = await waiting.value + XCTAssertNil(late) + XCTAssertLessThan(Date().timeIntervalSince(started), 0.2) + for task in busy { _ = await task.value } + } + + private actor Gauge { + var current = 0, peak = 0 + func enter() { current += 1; peak = max(peak, current) } + func leave() { current -= 1 } + } + + func testAnIconThatIsNotAnImageIsNotKept() async { + let service = SteamMetadataService(directory: root, transport: { _ in Data("nope".utf8) }) + let icon = await service.achievementIcon(appID: 7, file: "ab.jpg") + XCTAssertNil(icon) + } + + private static func png() throws -> Data { + let context = CGContext(data: nil, width: 4, height: 4, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(CGColor(red: 1, green: 0, blue: 0, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 4, height: 4)) + let data = NSMutableData() + let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)! + CGImageDestinationAddImage(destination, context.makeImage()!, nil) + CGImageDestinationFinalize(destination) + return data as Data + } +} diff --git a/Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift b/Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift new file mode 100644 index 00000000..0acd62e6 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift @@ -0,0 +1,197 @@ +import XCTest +@testable import NXLibraryCore + +/// Made-up schemas and stats in Steam's layout; no Valve content. +final class SteamAchievementReaderTests: XCTestCase { + private typealias E = [(String, Any)] + private let app: UInt32 = 4242 + private let account: UInt32 = 1234 + + private func bit(_ api: String, names: [String: String], descs: [String: String] = [:], hidden: Bool = false, + icon: String? = "c.jpg", gray: String? = "g.jpg") -> E { + var display: E = [("name", names.map { ($0.key, $0.value as Any) }), + ("desc", descs.map { ($0.key, $0.value as Any) }), + ("hidden", hidden ? "1" : "0")] + if let icon { display.append(("icon", icon)) } + if let gray { display.append(("icon_gray", gray)) } + return [("name", api), ("display", display)] + } + + private func schema(_ stats: [(String, E)]) -> [KeyValuesEntry] { + let tree: E = [("\(app)", [("stats", stats.map { ($0.0, $0.1 as Any) } as E), ("gamename", "Game"), ("version", Int32(3))] as E)] + return try! SteamBinaryKeyValues.parse(BinaryKV.data(tree)) + } + + private func stats(_ times: [(stat: String, bit: String, time: Int32)], extra: Bool = false) -> [KeyValuesEntry] { + var byStat: [String: E] = [:] + for t in times { byStat[t.stat, default: []].append((t.bit, t.time)) } + var cache: E = [("crc", Int32(99))] + if extra { cache.append(("PendingChanges", Int32(0))) } + for (stat, list) in byStat.sorted(by: { $0.key < $1.key }) { + cache.append((stat, [("data", Int32(7)), ("AchievementTimes", list)] as E)) + } + return try! SteamBinaryKeyValues.parse(BinaryKV.data([("cache", cache)])) + } + + private func read(_ schema: [KeyValuesEntry], _ stats: [KeyValuesEntry], language: String = "italian") throws -> [SteamAchievement] { + try SteamAchievementReader.achievements(schema: schema, stats: stats, appID: app, language: language) + } + + func testReadsNamesInTheLanguageWithEnglishFallback() throws { + let rows = try read(schema([("1", [("type", "4"), ("bits", [ + ("0", bit("A", names: ["english": "First", "italian": "Primo"], descs: ["english": "Do it", "italian": "Fallo"])), + ("1", bit("B", names: ["english": "Second"], descs: ["english": "Again"])), + ("2", bit("C", names: [:])), + ] as E)])]), stats([])) + XCTAssertEqual(rows.map(\.name), ["Primo", "Second", "C"]) + XCTAssertEqual(rows.map(\.description), ["Fallo", "Again", ""]) + } + + func testUnlockTimesComeFromTheStatsFile() throws { + let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:])), ("1", bit("B", names: [:]))] as E)])]), + stats([("1", "0", 1_700_000_000)])) + XCTAssertEqual(rows[0].unlockedAt, Date(timeIntervalSince1970: 1_700_000_000)) + XCTAssertNil(rows[1].unlockedAt) + } + + func testStatsWithoutBitsAreSkipped() throws { + let rows = try read(schema([("1", [("type", "1"), ("name", "kills")]), ("2", [("bits", [("0", bit("A", names: [:]))] as E)])]), + stats([])) + XCTAssertEqual(rows.map(\.apiName), ["A"]) + } + + func testHiddenAndIcons() throws { + let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:], hidden: true, icon: "x.jpg", gray: "y.jpg")), + ("1", bit("B", names: [:], icon: nil, gray: nil))] as E)])]), stats([])) + XCTAssertEqual(rows[0].hidden, true) + XCTAssertEqual(rows[0].icon, "x.jpg") + XCTAssertEqual(rows[0].grayIcon, "y.jpg") + XCTAssertEqual(rows[1].hidden, false) + XCTAssertNil(rows[1].icon) + } + + func testOrderIsStatThenBitNumerically() throws { + let rows = try read(schema([ + ("10", [("bits", [("0", bit("S10B0", names: [:]))] as E)]), + ("2", [("bits", [("10", bit("S2B10", names: [:])), ("9", bit("S2B9", names: [:]))] as E)]), + ]), stats([])) + XCTAssertEqual(rows.map(\.apiName), ["S2B9", "S2B10", "S10B0"]) + } + + func testOtherStatsKeysAreIgnored() throws { + let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:]))] as E)])]), stats([("1", "0", 5)], extra: true)) + XCTAssertEqual(rows.count, 1) + XCTAssertNotNil(rows[0].unlockedAt) + } + + func testAZeroTimeIsLocked() throws { + let rows = try read(schema([("1", [("bits", [("0", bit("A", names: [:]))] as E)])]), stats([("1", "0", 0)])) + XCTAssertNil(rows[0].unlockedAt) + } + + func testLookupSkipsWrongTypesAndKeepsTheFirstMatchingTypedValue() throws { + let fields: E = [("name", [] as E), ("NAME", "FIRST"), ("name", "SECOND"), + ("display", "wrong type"), ("DISPLAY", [ + ("name", [("italian", [] as E), ("ITALIAN", "Primo"), ("italian", "Secondo")] as E) + ] as E)] + let game: E = [("stats", "wrong type"), ("STATS", [("1", [ + ("bits", "wrong type"), ("BITS", [("0", fields)] as E) + ] as E)] as E)] + let schema = try SteamBinaryKeyValues.parse(BinaryKV.data([("\(app)", "wrong type"), ("\(app)", game)])) + let rows = try read(schema, stats([("1", "0", 5)])) + XCTAssertEqual(rows.map(\.apiName), ["FIRST"]) + XCTAssertEqual(rows.map(\.name), ["Primo"]) + XCTAssertEqual(rows.first?.unlockedAt, Date(timeIntervalSince1970: 5)) + } + + func testEmptyFirstLocalizedStringFallsBackToEnglishRatherThanADuplicate() throws { + let fields: E = [("name", "A"), ("display", [("name", [ + ("italian", ""), ("ITALIAN", "Ignored duplicate"), ("english", "English fallback") + ] as E)] as E)] + let rows = try read(schema([("1", [("bits", [("0", fields)] as E)])]), stats([])) + XCTAssertEqual(rows.map(\.name), ["English fallback"]) + } + + // MARK: - Files + + private var root: URL! + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("SteamAchievements-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root.appendingPathComponent("appcache/stats"), withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: root.appendingPathComponent("config"), withIntermediateDirectories: true) + let id = 76_561_197_960_265_728 + UInt64(account) + try "\"users\" { \"\(id)\" { \"AccountName\" \"someone\" \"MostRecent\" \"1\" \"timestamp\" \"1\" } }" + .write(to: root.appendingPathComponent("config/loginusers.vdf"), atomically: true, encoding: .utf8) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: root) + super.tearDown() + } + + private func writeSchema(_ data: Data) throws { + try data.write(to: SteamAchievementReader.schemaURL(root: root, appID: app)) + } + + private func writeStats(_ data: Data) throws { + try data.write(to: SteamAchievementReader.statsURL(root: root, account: account, appID: app)) + } + + private var schemaData: Data { + BinaryKV.data([("\(app)", [("stats", [("1", [("bits", [("0", bit("A", names: ["english": "First"]))] as E)] as E)] as E)] as E)]) + } + + func testFileNamesFollowSteam() { + XCTAssertEqual(SteamAchievementReader.schemaURL(root: root, appID: app).lastPathComponent, "UserGameStatsSchema_4242.bin") + XCTAssertEqual(SteamAchievementReader.statsURL(root: root, account: account, appID: app).lastPathComponent, "UserGameStats_1234_4242.bin") + } + + func testNoStatsFileForTheAccountIsNil() throws { + try writeSchema(schemaData) + XCTAssertNil(try SteamAchievementReader.read(root: root, appID: app, language: "english")) + } + + func testNoUnlockIsZeroNotNil() throws { + try writeSchema(schemaData) + try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)])) + let rows = try XCTUnwrap(SteamAchievementReader.read(root: root, appID: app, language: "english")) + XCTAssertEqual(rows.count, 1) + XCTAssertNil(rows[0].unlockedAt) + } + + func testNoSchemaIsNil() throws { + try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)])) + XCTAssertNil(try SteamAchievementReader.read(root: root, appID: app, language: "english")) + } + + func testCorruptSchemaThrows() throws { + try writeSchema(schemaData.dropLast(4)) + try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)])) + XCTAssertThrowsError(try SteamAchievementReader.read(root: root, appID: app, language: "english")) + } + + func testSchemaSymlinkIsRejected() throws { + let target = root.appendingPathComponent("schema.bin") + try schemaData.write(to: target) + try FileManager.default.createSymbolicLink(at: SteamAchievementReader.schemaURL(root: root, appID: app), + withDestinationURL: target) + try writeStats(BinaryKV.data([("cache", [] as E)])) + XCTAssertThrowsError(try SteamAchievementReader.read(root: root, appID: app, language: "english")) + } + + func testStatsSymlinkIsRejected() throws { + try writeSchema(schemaData) + let target = root.appendingPathComponent("stats.bin") + try BinaryKV.data([("cache", [] as E)]).write(to: target) + try FileManager.default.createSymbolicLink(at: SteamAchievementReader.statsURL(root: root, account: account, appID: app), + withDestinationURL: target) + XCTAssertThrowsError(try SteamAchievementReader.read(root: root, appID: app, language: "english")) + } + + func testASchemaForAnotherGameReadsNothing() throws { + try writeSchema(BinaryKV.data([("999", [("stats", [] as E)] as E)])) + try writeStats(BinaryKV.data([("cache", [("crc", Int32(1))] as E)])) + XCTAssertEqual(try SteamAchievementReader.read(root: root, appID: app, language: "english"), []) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift b/Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift new file mode 100644 index 00000000..21b32036 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift @@ -0,0 +1,86 @@ +import XCTest +import AppKit +@testable import NXLibraryCore + +final class SteamArtworkRequestTests: XCTestCase { + func testSquareUsesOriginalBundleAssetButPortraitNeverUsesIt() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let app = root.appendingPathComponent("Fixture.app") + let resources = app.appendingPathComponent("Contents/Resources") + try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true) + try PropertyListSerialization.data(fromPropertyList: ["CFBundleIconFile":"Original"], format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist")) + let icon = resources.appendingPathComponent("Original.icns") + try Data("fixture".utf8).write(to: icon) + let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"), bundleIdentifier: "fixture", name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: []) + let native = CatalogNativeApplication(observed) + let install = SteamCatalogInstallation(libraryURL: root, contentURL: root, applications: [native], availability: .available) + var steam = SteamCatalogGame(appID: 10, name: "Fixture"); steam.installations = [install]; steam.hasBeenRecognized = true + let game = CatalogGame(steam: steam), picks = SteamPersonalizationStore(directory: root.appendingPathComponent("picks")) + XCTAssertEqual(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks), icon) + XCTAssertNil(SteamArtworkRequest(game: game, role: .cover).localURL(picks: picks)) + // A malicious icon path is not a request to read outside the bundle. + try PropertyListSerialization.data(fromPropertyList: ["CFBundleIconFile":"../../outside"], format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist")) + XCTAssertNil(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks)) + } + + func testPersonalPickComesBeforeTheAppIcon() throws { + let (root, game, icon) = try fixture(iconName: "Original") + defer { try? FileManager.default.removeItem(at: root) } + let picks = SteamPersonalizationStore(directory: root.appendingPathComponent("picks")) + XCTAssertEqual(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks), icon) + let png = try XCTUnwrap(Self.png()) + try picks.save(fields: [:], images: [.icon: png, .cover: png], automatic: [], titleID: game.personalizationReference.key) + let square = try XCTUnwrap(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks)) + XCTAssertNotEqual(square, icon) + XCTAssertTrue(square.path.hasPrefix(root.appendingPathComponent("picks").path)) + XCTAssertNotNil(SteamArtworkRequest(game: game, role: .cover).localURL(picks: picks)) + XCTAssertNil(SteamArtworkRequest(game: game, role: .hero).localURL(picks: picks)) + } + + func testIconLinkLeavingTheBundleIsNotFollowed() throws { + let (root, game, icon) = try fixture(iconName: "Original.icns") + defer { try? FileManager.default.removeItem(at: root) } + let outside = root.appendingPathComponent("outside.icns") + try Data("outside".utf8).write(to: outside) + try FileManager.default.removeItem(at: icon) + try FileManager.default.createSymbolicLink(at: icon, withDestinationURL: outside) + let picks = SteamPersonalizationStore(directory: root.appendingPathComponent("picks")) + XCTAssertNil(SteamArtworkRequest(game: game, role: .square).localURL(picks: picks)) + } + + private func fixture(iconName: String) throws -> (URL, CatalogGame, URL) { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let app = root.appendingPathComponent("Fixture.app") + let resources = app.appendingPathComponent("Contents/Resources") + try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true) + try PropertyListSerialization.data(fromPropertyList: ["CFBundleIconFile": iconName], format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist")) + let icon = resources.appendingPathComponent("Original.icns") + try Data("fixture".utf8).write(to: icon) + let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"), bundleIdentifier: "fixture", name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: []) + let install = SteamCatalogInstallation(libraryURL: root, contentURL: root, applications: [CatalogNativeApplication(observed)], availability: .available) + var steam = SteamCatalogGame(appID: 10, name: "Fixture"); steam.installations = [install]; steam.hasBeenRecognized = true + return (root, CatalogGame(steam: steam), icon) + } + + private static func png() -> Data? { + let image = NSImage(size: NSSize(width: 8, height: 8)) + image.lockFocus(); NSColor.red.setFill(); NSRect(x: 0, y: 0, width: 8, height: 8).fill(); image.unlockFocus() + return image.tiffRepresentation.flatMap { NSBitmapImageRep(data: $0)?.representation(using: .png, properties: [:]) } + } + + func testOnlyASquareWithoutAnAppWantsAnAutomaticIcon() { + var steam = SteamCatalogGame(appID: 3321460, name: "Downloading") + steam.installations = [.init(libraryURL: URL(fileURLWithPath: "/tmp/steam"), + contentURL: URL(fileURLWithPath: "/tmp/steam/steamapps/common/G"), + availability: .unavailable, isDownloading: true)] + let downloading = CatalogGame(steam: steam) + XCTAssertTrue(SteamArtworkRequest(game: downloading, role: .square).wantsAutomaticIcon) + XCTAssertFalse(SteamArtworkRequest(game: downloading, role: .cover).wantsAutomaticIcon) + let root = URL(fileURLWithPath: "/tmp/steam-fixture"), app = root.appendingPathComponent("Fixture.app") + let observed = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/main"), bundleIdentifier: "fixture", + name: "Fixture", architectures: [.arm64], isDeclaredGame: true, fileObservations: []) + steam.installations = [.init(libraryURL: root, contentURL: root, applications: [CatalogNativeApplication(observed)], availability: .available)] + XCTAssertFalse(SteamArtworkRequest(game: CatalogGame(steam: steam), role: .square).wantsAutomaticIcon) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift b/Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift new file mode 100644 index 00000000..d33491e9 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift @@ -0,0 +1,76 @@ +import XCTest +import AppKit +@testable import NXLibraryCore + +/// A Steam game with no app has no icon of its own: LaunchBox's Square for its PC entry, else nothing. +final class SteamAutomaticIconTests: XCTestCase { + private final class Client: ArtworkHTTPClient, @unchecked Sendable { + var routes: [String: Data] = [:] + var asked: [String] = [] + private let lock = NSLock() + func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = request.url!.absoluteString + let body: Data? = lock.withLock { asked.append(url); return routes[url] } + return (body ?? Data(), HTTPURLResponse(url: request.url!, statusCode: body == nil ? 404 : 200, httpVersion: nil, headerFields: nil)!) + } + } + + private static let search = "https://gamesdb.launchbox-app.com/games/results/crimson%20desert%20enhanced" + private static let details = "https://gamesdb.launchbox-app.com/games/details/436343-crimson-desert-enhanced" + private static let square = "https://images.launchbox-app.com/square-full.png" + + private static var png: Data { + let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 8, pixelsHigh: 8, bitsPerSample: 8, samplesPerPixel: 4, + hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! + return rep.representation(using: .png, properties: [:])! + } + + private func store(_ client: Client) -> ArtworkStore { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("SteamIcon-" + UUID().uuidString) + addTeardownBlock { try? FileManager.default.removeItem(at: directory) } + return ArtworkStore(cacheDirectory: directory, client: client) + } + + private func client(square: Bool) -> Client { + let client = Client() + // A console entry first, as LaunchBox lists it: never taken for a Steam game. + client.routes[Self.search] = Data((LaunchBoxArtTests.card("438331-crimson-desert", "Crimson Desert Enhanced", "Sony Playstation 5") + + LaunchBoxArtTests.card("436343-crimson-desert-enhanced", "Crimson Desert Enhanced", "Windows")).utf8) + var images: [LaunchBoxArtTests.Image] = [("Box - Front", "World", "front.jpg", "front-full.jpg", 600, 900), + ("Fanart - Background", "World", "fan.jpg", "fan-full.jpg", 1920, 1080)] + if square { images.append(("Square", "World", "square.png", "square-full.png", 512, 512)) } + client.routes[Self.details] = Data(LaunchBoxArtTests.page(images).utf8) + client.routes[Self.square] = Self.png + return client + } + + func testTheSquareIsTheFullSquareImageOnly() { + let candidates = LaunchBoxArt.candidates(in: LaunchBoxArtTests.gamePage) + XCTAssertEqual(LaunchBoxArt.square(in: candidates)?.lastPathComponent, "r2_square-full.jpg") + XCTAssertNil(LaunchBoxArt.square(in: candidates.filter { $0.slot != .icon })) + } + + func testTheComputerEntrySquareIsFetchedOnceAndKept() async throws { + let client = client(square: true) + let artwork = store(client) + let first = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"]) + XCTAssertEqual(first, artwork.cachedURL(titleID: "steam-3321460", kind: .square)) + XCTAssertTrue(client.asked.contains(Self.square)) + let asked = client.asked.count + let again = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"]) + XCTAssertEqual(again, first) + XCTAssertEqual(client.asked.count, asked, "kept on disk: no new lookup") + } + + func testNoSquareGivesNothingAndIsNotAskedAgainThisSession() async { + let client = client(square: false) + let artwork = store(client) + let none = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"]) + XCTAssertNil(none) + XCTAssertFalse(client.asked.contains(Self.square)) + let asked = client.asked.count + let again = await artwork.automaticSteamIcon(titleID: "steam-3321460", names: ["Crimson Desert Enhanced"]) + XCTAssertNil(again) + XCTAssertEqual(client.asked.count, asked) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift b/Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift new file mode 100644 index 00000000..9ad5d133 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift @@ -0,0 +1,80 @@ +import XCTest +import AppKit +@testable import NXLibraryCore + +final class SteamBackdropChoiceTests: XCTestCase { + private let shot = URL(string: "https://shared.akamai.steamstatic.com/shot.jpg")! + private let hero = URL(string: "https://shared.akamai.steamstatic.com/library_hero.jpg")! + + func testScreenShapedArtOnly() { + XCTAssertTrue(SteamBackdropChoice.suits(width: 1920, height: 1080)) + XCTAssertTrue(SteamBackdropChoice.suits(width: 1920, height: 1200)) + XCTAssertFalse(SteamBackdropChoice.suits(width: 3840, height: 1240), "Steam's library hero is a banner") + XCTAssertFalse(SteamBackdropChoice.suits(width: 1024, height: 576), "too small for a full screen") + XCTAssertFalse(SteamBackdropChoice.suits(width: 600, height: 900)) + } + + func testCleanStoreHeroesComeFirstThenTheExactScreenshotThenTheBanner() { + let art = [ + ArtworkCandidate(slot: .background, source: "Xbox Store · titled", url: URL(string: "https://x/titled")!), + ArtworkCandidate(slot: .background, source: "TheGamesDB fan art", url: URL(string: "https://t/fan")!), + ArtworkCandidate(slot: .cover, source: "GOG", url: URL(string: "https://g/cover")!), + ArtworkCandidate(slot: .background, source: "GOG", url: URL(string: "https://g/galaxy")!), + ArtworkCandidate(slot: .background, source: "GOG", url: URL(string: "https://g/wide-cover")!), + ArtworkCandidate(slot: .background, source: "Xbox Store", url: URL(string: "https://x/hero")!) + ] + let order = SteamBackdropChoice.ordered(storeArt: art, screenshots: [shot, URL(string: "https://s/2")!], libraryHero: hero) + XCTAssertEqual(order.map(\.absoluteString), ["https://x/hero", "https://g/galaxy", "https://t/fan", shot.absoluteString, hero.absoluteString]) + XCTAssertEqual(SteamBackdropChoice.ordered(storeArt: [], screenshots: [], libraryHero: hero), [hero]) + } + + func testLaunchBoxComputerFanartComesAfterTheStoresAndBeforeScreenshots() { + let fanart = { (name: String, w: Int?, h: Int?) in + ArtworkCandidate(slot: .background, source: "LaunchBox · Fanart - Background", url: URL(string: "https://l/\(name)-preview")!, + full: URL(string: "https://l/\(name)"), width: w, height: h) + } + let art = [ + ArtworkCandidate(slot: .background, source: "LaunchBox · Screenshot - Gameplay", url: URL(string: "https://l/play")!, + full: URL(string: "https://l/play-full"), width: 1920, height: 1080), + fanart("banner", 3840, 1240), + fanart("small", 1024, 576), + fanart("wide", 2560, 1440), + ArtworkCandidate(slot: .background, source: "GOG", url: URL(string: "https://g/galaxy")!) + ] + let order = SteamBackdropChoice.ordered(storeArt: art, screenshots: [shot], libraryHero: hero) + // The full file, not its preview; only a screen-shaped one; gameplay shots are not fan art. + XCTAssertEqual(order.map(\.absoluteString), ["https://g/galaxy", "https://l/wide", shot.absoluteString, hero.absoluteString]) + let unsized = SteamBackdropChoice.ordered(storeArt: [fanart("unknown", nil, nil)], screenshots: [], libraryHero: nil) + XCTAssertEqual(unsized.map(\.absoluteString), ["https://l/unknown"], "a size the page does not state is checked when chosen") + } + + func testChoosesTheFirstScreenShapedImageAndFallsBackToTheBanner() async throws { + let banner = try XCTUnwrap(Self.png(width: 1500, height: 484)) + let wide = try XCTUnwrap(Self.png(width: 1600, height: 900)) + var asked: [URL] = [] + let chosen = await SteamBackdropChoice.choose([URL(string: "https://x/missing")!, hero, shot], fallback: hero) { url in + asked.append(url) + return url == hero ? banner : url == self.shot ? wide : nil + } + XCTAssertEqual(chosen, shot) + XCTAssertEqual(asked.count, 3) + let fallback = await SteamBackdropChoice.choose([shot, hero], fallback: hero) { _ in banner } + XCTAssertEqual(fallback, hero) + } + + func testWithoutAScreenShapedImageOrBannerTheFirstImageThatLoadsIsShown() async throws { + let small = try XCTUnwrap(Self.png(width: 1024, height: 576)) + let missing = URL(string: "https://x/missing")! + let chosen = await SteamBackdropChoice.choose([missing, shot], fallback: nil) { $0 == self.shot ? small : nil } + XCTAssertEqual(chosen, shot, "never the last URL just for being last: one that loads") + let none = await SteamBackdropChoice.choose([missing], fallback: nil) { _ in nil } + XCTAssertNil(none) + } + + private static func png(width: Int, height: Int) -> Data? { + guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, + samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, + bytesPerRow: 0, bitsPerPixel: 0) else { return nil } + return rep.representation(using: .png, properties: [:]) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift b/Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift new file mode 100644 index 00000000..c9e23c24 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift @@ -0,0 +1,94 @@ +import XCTest +@testable import NXLibraryCore + +/// Writes Steam's binary KeyValues for tests: a `[(key, value)]` array is a subtree, a String is type 1, an Int32 +/// type 2, a Float type 3, a UInt64 type 7. +enum BinaryKV { + static func data(_ entries: [(String, Any)], end: Bool = true) -> Data { + var out = Data() + write(entries, into: &out) + if end { out.append(8) } + return out + } + + private static func write(_ entries: [(String, Any)], into out: inout Data) { + for (key, value) in entries { + switch value { + case let sub as [(String, Any)]: + out.append(0); cString(key, &out); write(sub, into: &out); out.append(8) + case let text as String: + out.append(1); cString(key, &out); cString(text, &out) + case let number as Int32: + out.append(2); cString(key, &out); withUnsafeBytes(of: number.littleEndian) { out.append(contentsOf: $0) } + case let number as Float: + out.append(3); cString(key, &out); withUnsafeBytes(of: number.bitPattern.littleEndian) { out.append(contentsOf: $0) } + case let number as UInt64: + out.append(7); cString(key, &out); withUnsafeBytes(of: number.littleEndian) { out.append(contentsOf: $0) } + default: + preconditionFailure("unsupported test value \(value)") + } + } + } + + private static func cString(_ text: String, _ out: inout Data) { + out.append(contentsOf: Array(text.utf8)); out.append(0) + } +} + +final class SteamBinaryKeyValuesTests: XCTestCase { + func testReadsEveryType() throws { + let data = BinaryKV.data([("root", [ + ("text", "a"), ("int", Int32(-7)), ("float", Float(1.5)), ("big", UInt64(1) << 40), + ] as [(String, Any)])]) + let entries = try SteamBinaryKeyValues.parse(data) + XCTAssertEqual(entries, [KeyValuesEntry(key: "root", value: .object([ + KeyValuesEntry(key: "text", value: .string("a")), + KeyValuesEntry(key: "int", value: .string("-7")), + KeyValuesEntry(key: "float", value: .string("1.5")), + KeyValuesEntry(key: "big", value: .string("1099511627776")), + ]))]) + } + + func testKeepsOrderAndDuplicates() throws { + let entries = try SteamBinaryKeyValues.parse(BinaryKV.data([("b", "1"), ("a", "2"), ("b", "3")])) + XCTAssertEqual(entries.map(\.key), ["b", "a", "b"]) + } + + func testTruncatedThrowsMalformed() { + let data = BinaryKV.data([("root", [("int", Int32(5))] as [(String, Any)])], end: false) + XCTAssertThrowsError(try SteamBinaryKeyValues.parse(data.dropLast(2))) { + XCTAssertEqual($0 as? KeyValuesError, .malformed) + } + } + + func testUnknownTypeThrowsMalformed() { + var data = Data([5]); data.append(contentsOf: Array("x".utf8)); data.append(0) + XCTAssertThrowsError(try SteamBinaryKeyValues.parse(data)) { XCTAssertEqual($0 as? KeyValuesError, .malformed) } + } + + func testDepthLimit() { + var nested: [(String, Any)] = [("leaf", "x")] + for _ in 0..<33 { nested = [("n", nested)] } + XCTAssertThrowsError(try SteamBinaryKeyValues.parse(BinaryKV.data(nested), maximumDepth: 32)) { + XCTAssertEqual($0 as? KeyValuesError, .limitExceeded) + } + } + + func testTopLevelNeedsItsTerminator() throws { + XCTAssertEqual(try SteamBinaryKeyValues.parse(BinaryKV.data([("a", "1")], end: true)).count, 1) + // Cut just before the last byte (Steam writing the file): not a shorter file, a broken one. + XCTAssertThrowsError(try SteamBinaryKeyValues.parse(BinaryKV.data([("a", "1")], end: false))) { + XCTAssertEqual($0 as? KeyValuesError, .malformed) + } + } + + func testEmptyDataThrows() { + XCTAssertThrowsError(try SteamBinaryKeyValues.parse(Data())) { XCTAssertEqual($0 as? KeyValuesError, .malformed) } + } + + func testAnUnclosedSubtreeThrows() { + var data = Data([0]); data.append(contentsOf: Array("s".utf8)); data.append(0) + data.append(1); data.append(contentsOf: Array("k".utf8)); data.append(0); data.append(contentsOf: Array("v".utf8)); data.append(0) + XCTAssertThrowsError(try SteamBinaryKeyValues.parse(data)) { XCTAssertEqual($0 as? KeyValuesError, .malformed) } + } +} diff --git a/Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift b/Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift new file mode 100644 index 00000000..bb41a75b --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift @@ -0,0 +1,240 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamCatalogReconcilerTests: XCTestCase { + private let root = URL(fileURLWithPath: "/tmp/catalog-steam") + private let external = URL(fileURLWithPath: "/tmp/catalog-external") + private let observedAt = Date(timeIntervalSince1970: 1000.125) + + private func catalog() -> CatalogDocument { + CatalogDocument(sources: [.init(integration: .nxnative, isEnabled: true), + .init(integration: .steam, isEnabled: true, rootURL: root)], + games: [.init(nxnative: CatalogTestSupport.completeLegacyGame())]) + } + private func observation(_ id: UInt32 = 10, name: String = "Same name", library: URL? = nil, + directory: String = "Game", state: SteamGameObservation.State = .nativeReady, + size: Int64? = 100) throws -> SteamGameObservation { + let library = library ?? root + let content = library.appendingPathComponent("steamapps/common/" + directory) + let app = content.appendingPathComponent("Game.app") + let native = NativeMacApplication(url: app, executableURL: app.appendingPathComponent("Contents/MacOS/game"), + bundleIdentifier: "test.game", name: name, architectures: [.arm64], + isDeclaredGame: true, fileObservations: []) + return .init(appID: id, name: name, installationURL: content, + libraryURL: library, reportedSizeBytes: size, buildID: "42", nativeApps: [native], state: state) + } + private func snapshot(_ games: [SteamGameObservation], complete: Bool = true, + libraries: [SteamLibraryObservation]? = nil) -> SteamLibrarySnapshot { + .init(libraries: libraries ?? [.init(root: root, isReadable: true, isComplete: complete)], games: games, + issues: complete ? [] : [.init(url: root, appID: nil, reason: .invalidManifest)]) + } + private func apply(_ scan: SteamLibrarySnapshot, to document: CatalogDocument) throws -> CatalogDocument { + try SteamCatalogReconciler.applying(scan, ticket: document.steamScanTicket(), to: document, observedAt: observedAt) + } + + func testScansRequireEnabledSourceAndMatchingRevisionAndRoot() throws { + var document = catalog() + let ticket = try document.steamScanTicket() + document.sources[1].isEnabled = false + XCTAssertThrowsError(try document.steamScanTicket()) + XCTAssertThrowsError(try SteamCatalogReconciler.applying(snapshot([]), ticket: ticket, to: document)) + document = catalog(); document.revision = UUID() + XCTAssertThrowsError(try SteamCatalogReconciler.applying(snapshot([]), ticket: ticket, to: document)) + document = catalog(); document.sources[1].rootURL = external + XCTAssertThrowsError(try SteamCatalogReconciler.applying(snapshot([]), ticket: ticket, to: document)) + document = catalog() + XCTAssertThrowsError(try apply(snapshot([], libraries: [.init(root: external, isReadable: true, isComplete: true)]), to: document)) + } + + func testIdenticalNamesAcrossSourcesAndAppIDsStaySeparate() throws { + var first = try observation() + first = .init(appID: first.appID, name: "Fixture Switch game", installationURL: first.installationURL, + libraryURL: first.libraryURL, reportedSizeBytes: 100, buildID: "42", nativeApps: first.nativeApps, state: .nativeReady) + let original = catalog() + let result = try apply(snapshot([first, observation(20, name: "Fixture Switch game")]), to: original) + XCTAssertEqual(result.games.count, 3) + XCTAssertEqual(Set(result.games.map(\.id)).count, 3) + XCTAssertEqual(Set(result.games.compactMap { $0.steamGame?.appID }), [10, 20]) + XCTAssertEqual(result.games.filter { $0.integration == .steam }.map(\.personalizationKey), ["steam-10", "steam-20"]) + XCTAssertEqual(result.games[0].nxnativeGame, original.games[0].nxnativeGame) + } + + func testRefreshKeepsUUIDInstallationIDAndPersonalChoicesWhileUpdatingObservations() throws { + let game = try observation() + var document = try apply(snapshot([game]), to: catalog()) + document.games[1].setFavorite(true); document.games[1].setHidden(true) + let before = document.games[1] + let renamed = SteamGameObservation(appID: 10, name: "New name", installationURL: game.installationURL, + libraryURL: game.libraryURL, reportedSizeBytes: 200, buildID: "43", nativeApps: game.nativeApps, state: .nativeReady) + let result = try apply(snapshot([renamed]), to: document) + let after = result.games[1] + XCTAssertEqual(after.id, before.id) + XCTAssertEqual(after.steamGame?.installations.first?.id, before.steamGame?.installations.first?.id) + XCTAssertEqual(after.personalizationReference, before.personalizationReference) + XCTAssertTrue(after.isFavorite); XCTAssertTrue(after.isHidden) + XCTAssertEqual(after.name, "New name") + XCTAssertEqual(after.steamGame?.installations.first?.reportedSizeBytes, 200) + XCTAssertEqual(after.steamGame?.installations.first?.buildID, "43") + XCTAssertEqual(after.steamGame?.installations.first?.lastObservedAt, observedAt) + XCTAssertEqual(result.games[0], document.games[0]) + XCTAssertEqual(result.revision, document.revision, "Store alone assigns the committed revision") + } + + func testDuplicateAppIDRetainsBothInstallationsAndRequiresReview() throws { + let a = try observation(), b = try observation(library: external) + let scan = snapshot([a, b], libraries: [.init(root: root, isReadable: true, isComplete: true), .init(root: external, isReadable: true, isComplete: true)]) + let result = try apply(scan, to: catalog()) + XCTAssertEqual(result.games.count, 2) + XCTAssertEqual(result.games[1].steamGame?.installations.count, 2) + XCTAssertNil(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget) + XCTAssertTrue(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).requiresReview) + let repeated = try apply(scan, to: result) + XCTAssertEqual(repeated.games[1].steamGame?.installations.map(\.id), result.games[1].steamGame?.installations.map(\.id)) + } + + func testCompleteAbsenceMarksNotDetectedWithoutDeletingGameOrHistoryIdentity() throws { + let document = try apply(snapshot([observation()]), to: catalog()) + let result = try apply(snapshot([]), to: document) + XCTAssertEqual(result.games.count, 2) + XCTAssertEqual(result.games[1].id, document.games[1].id) + XCTAssertEqual(result.games[1].steamGame?.installations.first?.availability, .notDetected) + XCTAssertTrue(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).isListedNormally) + XCTAssertNil(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget) + } + + func testPartialScanPreservesUnseenStateAndUnreadableLibraryIsExplicit() throws { + let document = try apply(snapshot([observation()]), to: catalog()) + let partial = try apply(snapshot([], complete: false), to: document) + XCTAssertEqual(partial.games, document.games) + let unavailable = snapshot([], complete: false, libraries: [.init(root: root, isReadable: false, isComplete: false)]) + let missing = try apply(unavailable, to: document) + XCTAssertEqual(missing.games[1].steamGame?.installations.first?.availability, .sourceUnavailable) + XCTAssertEqual(missing.games[1].id, document.games[1].id) + XCTAssertNil(CatalogGamePresentation(game: missing.games[1], sourceEnabled: true).launchTarget) + } + + func testMovedInstallationKeepsGameIdentityAndOldObservation() throws { + let document = try apply(snapshot([observation()]), to: catalog()) + let result = try apply(snapshot([observation(directory: "Moved")]), to: document) + XCTAssertEqual(result.games[1].id, document.games[1].id) + let installs = try XCTUnwrap(result.games[1].steamGame?.installations) + XCTAssertEqual(installs.count, 2) + XCTAssertEqual(installs[0].availability, .notDetected) + XCTAssertEqual(installs[1].availability, .available) + XCTAssertEqual(installs[0].id, document.games[1].steamGame?.installations[0].id) + XCTAssertEqual(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget, .steam(appID: 10)) + } + + func testUnrecognizedCandidatesDoNotBecomeNormalGamesOrLaunchTargets() throws { + for state: SteamGameObservation.State in [.unavailable, .requiresReview] { + let result = try apply(snapshot([observation(state: state)]), to: catalog()) + let presentation = CatalogGamePresentation(game: result.games[1], sourceEnabled: true) + XCTAssertFalse(presentation.isListedNormally) + XCTAssertTrue(presentation.requiresReview) + XCTAssertNil(presentation.launchTarget) + } + } + + func testSourceDisableHidesAndBlocksLaunchWithoutLosingRecords() throws { + let document = try apply(snapshot([observation()]), to: catalog()) + let steam = CatalogGamePresentation(game: document.games[1], sourceEnabled: false) + XCTAssertFalse(steam.isListedNormally) + XCTAssertNil(steam.launchTarget) + } + + func testInvalidAppIDAndUnlistedLibraryCannotBeAccepted() throws { + XCTAssertThrowsError(try apply(snapshot([observation(0)]), to: catalog())) + XCTAssertThrowsError(try apply(snapshot([observation(library: external)]), to: catalog())) + } + func testNativeApplicationOutsideObservedInstallationIsRejected() throws { + let original = try observation() + let unsafe = SteamGameObservation(appID: 10, name: original.name, + installationURL: external.appendingPathComponent("Outside"), libraryURL: root, + reportedSizeBytes: nil, buildID: nil, nativeApps: original.nativeApps, state: .nativeReady) + XCTAssertThrowsError(try apply(snapshot([unsafe]), to: catalog())) + } + + func testDifferentAppIDReusingAPathDoesNotKeepMissingOldGameAvailable() throws { + let document = try apply(snapshot([observation(10)]), to: catalog()) + let result = try apply(snapshot([observation(20)]), to: document) + XCTAssertEqual(result.games[1].steamGame?.appID, 10) + XCTAssertEqual(result.games[1].steamGame?.installations.first?.availability, .notDetected) + XCTAssertNil(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget) + } + + func testDuplicateInstallationPathsAreRejectedBeforeReconciliation() throws { + var document = try apply(snapshot([observation()]), to: catalog()) + var game = try XCTUnwrap(document.games[1].steamGame) + let original = game.installations[0] + game.installations.append(.init(libraryURL: original.libraryURL, contentURL: original.contentURL, + applications: original.applications, availability: .available)) + try document.games[1].updateSteam(game) + XCTAssertThrowsError(try document.validate()) + } + + func testMissingDiskCannotResolveDuplicateAmbiguityAndReconnectRemainsBlocked() throws { + let a = try observation(), b = try observation(library: external) + let both = snapshot([a, b], libraries: [.init(root: root, isReadable: true, isComplete: true), + .init(root: external, isReadable: true, isComplete: true)]) + let duplicate = try apply(both, to: catalog()) + let absentDisk = snapshot([a], complete: false, libraries: [.init(root: root, isReadable: true, isComplete: true), + .init(root: external, isReadable: false, isComplete: false)]) + let partial = try apply(absentDisk, to: duplicate) + let shown = CatalogGamePresentation(game: partial.games[1], sourceEnabled: true) + XCTAssertTrue(shown.requiresReview) + XCTAssertNil(shown.launchTarget) + XCTAssertEqual(partial.games[1].steamGame?.installations.first { $0.libraryURL == external }?.availability, .sourceUnavailable) + let reloaded = try JSONDecoder().decode(CatalogDocument.self, from: JSONEncoder().encode(partial)) + XCTAssertTrue(CatalogGamePresentation(game: reloaded.games[1], sourceEnabled: true).requiresReview) + let reconnected = try apply(both, to: reloaded) + XCTAssertTrue(CatalogGamePresentation(game: reconnected.games[1], sourceEnabled: true).requiresReview) + XCTAssertNil(CatalogGamePresentation(game: reconnected.games[1], sourceEnabled: true).launchTarget) + // Only complete evidence of one remaining installation resolves it. + let resolved = try apply(snapshot([a], libraries: [.init(root: root, isReadable: true, isComplete: true), + .init(root: external, isReadable: true, isComplete: true)]), to: reconnected) + XCTAssertFalse(CatalogGamePresentation(game: resolved.games[1], sourceEnabled: true).requiresReview) + XCTAssertEqual(CatalogGamePresentation(game: resolved.games[1], sourceEnabled: true).launchTarget, .steam(appID: 10)) + XCTAssertEqual(resolved.games[1].id, duplicate.games[1].id) + } + + private func downloading(directory: String = "Game") -> SteamGameObservation { + .init(appID: 10, name: "Same name", installationURL: root.appendingPathComponent("steamapps/common/" + directory), + libraryURL: root, reportedSizeBytes: 0, buildID: "42", nativeApps: [], state: .downloading) + } + + func testDownloadingObservationIsListedButNeitherRecognizedNorReviewed() throws { + let result = try apply(snapshot([downloading()]), to: catalog()) + let steam = try XCTUnwrap(result.games[1].steamGame) + XCTAssertEqual(steam.installations.first?.availability, .unavailable) + XCTAssertEqual(steam.installations.first?.isDownloading, true) + XCTAssertTrue(steam.isDownloading) + XCTAssertFalse(steam.hasBeenRecognized) + XCTAssertFalse(steam.needsInstallationReview) + XCTAssertFalse(steam.needsReview) + } + + func testFinishedDownloadBecomesRecognizedAndClearsFlag() throws { + let first = try apply(snapshot([downloading()]), to: catalog()) + let result = try apply(snapshot([observation(directory: "Game")]), to: first) + let steam = try XCTUnwrap(result.games[1].steamGame) + XCTAssertEqual(steam.installations.count, 1) + XCTAssertEqual(steam.installations[0].id, first.games[1].steamGame?.installations[0].id) + XCTAssertFalse(steam.installations[0].isDownloading) + XCTAssertFalse(steam.isDownloading) + XCTAssertTrue(steam.hasBeenRecognized) + XCTAssertEqual(CatalogGamePresentation(game: result.games[1], sourceEnabled: true).launchTarget, .steam(appID: 10)) + } + + func testRecognizedGameReinstalledShowsDownloading() throws { + let installed = try apply(snapshot([observation(directory: "Game")]), to: catalog()) + let result = try apply(snapshot([downloading(directory: "Again")]), to: installed) + let steam = try XCTUnwrap(result.games[1].steamGame) + XCTAssertEqual(steam.installations.map(\.availability), [.notDetected, .unavailable]) + XCTAssertTrue(steam.isDownloading) + let shown = CatalogGamePresentation(game: result.games[1], sourceEnabled: true) + XCTAssertTrue(shown.isDownloading) + XCTAssertTrue(shown.isListedNormally) + XCTAssertFalse(shown.requiresReview) + XCTAssertNil(shown.launchTarget) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift b/Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift new file mode 100644 index 00000000..2fb07582 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift @@ -0,0 +1,111 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamDiscoveryConsistencyTests: XCTestCase { + func testManifestAddedAfterInventoryInvalidatesTheSource() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + let source = SteamLibrarySource(root: root, directoryReader: { url, limit, cancelled in + let read = try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: cancelled) + if url.path == root.appendingPathComponent("steamapps").path { + try f.manifest(in: root, id: "20", directory: "Second") + try f.app(at: "Steam/steamapps/common/Second/Game.app") + } + return read + }) + XCTAssertThrowsError(try source.scan()) { XCTAssertEqual($0 as? SteamSourceError, .sourceChanged) } + } + + func testPreviouslyAbsentIndexAppearingBeforeInventoryIsDetected() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library(), external = try f.library("External") + let source = SteamLibrarySource(root: root, directoryReader: { url, limit, cancelled in + if url.path == root.appendingPathComponent("steamapps").path { + try Data("libraryfolders { 1 \(SteamTestFixture.quote(external.path)) }".utf8) + .write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf")) + } + return try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: cancelled) + }) + XCTAssertThrowsError(try source.scan()) { XCTAssertEqual($0 as? SteamSourceError, .sourceChanged) } + } + + func testNativeMetadataAndExecutableAreRecheckedAfterOtherGamesAreRead() throws { + for removeExecutable in [false, true] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.manifest(in: root, id: "20", directory: "Second") + let first = try f.app(at: "Steam/steamapps/common/First/Game.app") + try f.app(at: "Steam/steamapps/common/Second/Game.app") + let second = root.appendingPathComponent("steamapps/common/Second") + let source = SteamLibrarySource(root: root, directoryReader: { url, limit, cancelled in + let read = try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: cancelled) + if url.path == second.path { + if removeExecutable { + try FileManager.default.removeItem(at: first.appendingPathComponent("Contents/MacOS/fixture")) + } else { + let file = first.appendingPathComponent("Contents/Info.plist") + var info = try XCTUnwrap(PropertyListSerialization.propertyList(from: Data(contentsOf: file), format: nil) as? [String: Any]) + info["LSApplicationCategoryType"] = "public.app-category.developer-tools" + try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: file) + } + } + return read + }) + XCTAssertThrowsError(try source.scan()) { XCTAssertEqual($0 as? SteamSourceError, .sourceChanged) } + } + } + + func testDirectoryReadEnforcesTheEntryBudget() throws { + let f = try SteamTestFixture.temporary(in: self) + for i in 0..<12 { try Data().write(to: f.root.appendingPathComponent("item\(i)")) } + let result = try InstallationDirectorySnapshot.read(at: f.root, maximumEntries: 3, cancelled: { false }) + XCTAssertEqual(result.entries.count, 3) + XCTAssertFalse(result.isComplete) + } + + func testDirectoryReadHonorsCancellationWhileCollectingEntries() throws { + let f = try SteamTestFixture.temporary(in: self) + for i in 0..<12 { try Data().write(to: f.root.appendingPathComponent("item\(i)")) } + var checkpoints = 0 + XCTAssertThrowsError(try InstallationDirectorySnapshot.read(at: f.root, maximumEntries: 100, cancelled: { + checkpoints += 1 + return checkpoints >= 2 + })) { XCTAssertTrue($0 is CancellationError) } + } + + func testHiddenEntriesAlsoConsumeTheDirectoryReadBudget() throws { + let f = try SteamTestFixture.temporary(in: self) + for i in 0..<12 { try Data().write(to: f.root.appendingPathComponent(".hidden\(i)")) } + let result = try InstallationDirectorySnapshot.read(at: f.root, maximumEntries: 3, cancelled: { false }) + XCTAssertTrue(result.entries.isEmpty) + XCTAssertFalse(result.isComplete) + } + + func testWideInstallationRemainsPartialWhenItsEntryBudgetIsReached() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + for i in 0..<12 { + try Data().write(to: root.appendingPathComponent("steamapps/common/First/item\(i)")) + } + var limits = SteamScanLimits.standard + limits.maximumDirectoryEntries = 4 + let result = try SteamLibrarySource(root: root, limits: limits).scan() + XCTAssertFalse(result.isComplete) + XCTAssertEqual(result.games.first?.state, .requiresReview) + XCTAssertTrue(result.issues.contains { $0.reason == .directoryLimit }) + } + + func testCancellationFromInventoryReaderIsNotSwallowedAsUnavailable() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + let source = SteamLibrarySource(root: root, directoryReader: { url, limit, _ in + try InstallationDirectorySnapshot.read(at: url, maximumEntries: limit, cancelled: { true }) + }) + XCTAssertThrowsError(try source.scan()) { XCTAssertTrue($0 is CancellationError) } + } +} diff --git a/Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift b/Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift new file mode 100644 index 00000000..2671fa26 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift @@ -0,0 +1,65 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamKeyValuesTests: XCTestCase { + func testReadsNestedLibraryWithSpacesAndUnicode() throws { + let document = try KeyValuesDocument(text: "\"libraryfolders\" { \"0\" { \"path\" \"/Volumes/Giochi è/SteamLibrary\" } }") + guard case .object(let libraries)? = try document.uniqueValue(for: "libraryfolders"), + case .object(let first)? = try libraries.uniqueValue(for: "0") else { + return XCTFail("Missing library") + } + XCTAssertEqual(try first.uniqueValue(for: "PATH"), .string("/Volumes/Giochi è/SteamLibrary")) + } + + func testCommentsDoNotConsumeSlashesInsideStrings() throws { + let document = try KeyValuesDocument(text: "// heading\nname \"https://example.invalid/game\" // comment\nempty {}") + XCTAssertEqual(try document.uniqueValue(for: "name"), .string("https://example.invalid/game")) + XCTAssertEqual(try document.uniqueValue(for: "empty"), .object([])) + } + + func testQuotedEscapeSequencesAndUnquotedScalars() throws { + let document = try KeyValuesDocument(text: #"name "A \"quote\" \\ slash\nline\ttab\rend" appid 10"#) + XCTAssertEqual(try document.uniqueValue(for: "name"), .string("A \"quote\" \\ slash\nline\ttab\rend")) + XCTAssertEqual(try document.uniqueValue(for: "appid"), .string("10")) + } + + func testConflictingCaseVariantsAreNotSilentlyOverwritten() throws { + let document = try KeyValuesDocument(text: "appid 10 APPID 20") + XCTAssertEqual(document.entries.count, 2) + XCTAssertThrowsError(try document.uniqueValue(for: "appid")) + } + + func testUnknownDuplicateFieldsRemainInTheDocument() throws { + let document = try KeyValuesDocument(text: "unknown first unknown second appid 10") + XCTAssertEqual(document.entries.map(\.key), ["unknown", "unknown", "appid"]) + XCTAssertEqual(try document.uniqueValue(for: "appid"), .string("10")) + XCTAssertNil(try document.uniqueValue(for: "absent")) + } + + func testRejectsMalformedAndTruncatedDocuments() { + for text in ["key", "{", "key {", "key }", "key { child value", "key value }", "key \"unterminated", #"key "bad\q""#] { + XCTAssertThrowsError(try KeyValuesDocument(text: text), text) + } + } + + func testDoesNotExecuteIncludeOrBaseDirectives() { + for directive in ["#include", "#base", "#INCLUDE"] { + XCTAssertThrowsError(try KeyValuesDocument(text: "\(directive) \"/private/should-not-be-read\"")) + } + } + + func testDepthLimitAllowsBoundaryAndRejectsOneMoreObject() throws { + XCTAssertNoThrow(try KeyValuesDocument(text: "a { b c }", maximumDepth: 1)) + XCTAssertThrowsError(try KeyValuesDocument(text: "a { b { c d } }", maximumDepth: 1)) + } + + func testEntryLimitCountsNestedEntries() throws { + XCTAssertNoThrow(try KeyValuesDocument(text: "a { b c }", maximumEntries: 2)) + XCTAssertThrowsError(try KeyValuesDocument(text: "a { b c d e }", maximumEntries: 2)) + } + + func testEmptyDocumentAndUtf8Bom() throws { + XCTAssertEqual(try KeyValuesDocument(text: " \n// empty").entries, []) + XCTAssertEqual(try KeyValuesDocument(text: "\u{FEFF}appid 10").uniqueValue(for: "appid"), .string("10")) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift b/Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift new file mode 100644 index 00000000..174ec373 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift @@ -0,0 +1,229 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamLaunchQuestionsTests: XCTestCase { + private func date(_ seconds: TimeInterval) -> Date { Date(timeIntervalSince1970: seconds) } + private func line(_ app: UInt32 = 2141910, _ text: String) -> String { + "[2026-11-14 18:03:08] GameAction [AppID \(app), ActionID 1] : LaunchApp \(text)\n" + } + private func waiting(_ app: UInt32 = 2141910, _ task: String = "KickingOtherSession") -> String { + line(app, "waiting for user response to \(task) \"Game\"") + } + + func testAQuestionAnsweredAtOnceIsNotAsking() { + var questions = SteamLaunchQuestions() + questions.read(waiting(2141910, "ShowInterstitials") + line(2141910, "continues with user response \"ShowInterstitials\""), + now: date(0)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5))) + } + + func testColdStartInterstitialDoesNotDismissTheCoverBeforeARealQuestion() { + var questions = SteamLaunchQuestions() + questions.read(line(2141910, "changed task to ShowInterstitials with \"\"") + + line(2141910, "waiting for user response to ShowInterstitials \"\""), now: date(7)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(9))) + + questions.read(waiting(), now: date(10)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(10.5))) + XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(11))) + } + + func testAnOpenQuestionAsksOnceItOutlastsTheGrace() { + var questions = SteamLaunchQuestions() + questions.read(waiting(), now: date(10)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(10.5))) + XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(10 + SteamLaunchQuestions.grace))) + } + + func testAnotherGamesQuestionIsNotOurs() { + var questions = SteamLaunchQuestions() + questions.read(waiting(440), now: date(0)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5))) + XCTAssertTrue(questions.isAsking(appID: 440, now: date(5))) + } + + func testTheLaunchMovingOnClearsTheQuestion() { + var questions = SteamLaunchQuestions() + questions.read(waiting(), now: date(0)) + questions.read(line(2141910, "changed task to SynchronizingCloud with \"\""), now: date(3)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5))) + } + + func testAQuestionRepeatedKeepsWhenItWasFirstSeen() { + var questions = SteamLaunchQuestions() + questions.read(waiting(), now: date(0)) + questions.read(waiting(), now: date(0.9)) + XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(1))) + } + + func testOtherLinesAreIgnored() { + var questions = SteamLaunchQuestions() + questions.read("[2026-11-14 18:13:38] ExecuteSteamURL: \"steam://run/2141910\"\n" + + "waiting for user response to KickingOtherSession\n", now: date(0)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5))) + } + + func testResetForgetsEverything() { + var questions = SteamLaunchQuestions() + questions.read(waiting(), now: date(0)) + questions.read("[2026-11-14 18:03:09] GameAction [AppID 2141910, Act", now: date(0)) + questions.reset() + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(5))) + questions.read("ionID 1] : LaunchApp waiting for user response to X \"\"\n", now: date(5)) + XCTAssertFalse(questions.isAsking(appID: 2141910, now: date(9)), "the half line before the reset is gone") + } + + /// Steam's own sequence for a game already playing elsewhere (console_log.txt, 14 Nov 2026). + func testSteamsSequenceForASessionElsewhereAsks() { + let log = """ + [2026-11-14 18:03:07] ExecuteSteamURL: "steam://run/2141910" + [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to RunningInstallScript with "" + [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to SynchronizingStats with "" + [2026-11-14 18:03:07] CAPIJobRequestUserStats - Server response failed 2 + [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to ShowInterstitials with "" + [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp waiting for user response to ShowInterstitials "" + [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp continues with user response "ShowInterstitials" + [2026-11-14 18:03:07] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to SynchronizingControllerConfig with "" + [2026-11-14 18:03:08] GameAction [AppID 2141910, ActionID 1] : LaunchApp changed task to KickingOtherSession with "" + [2026-11-14 18:03:08] GameAction [AppID 2141910, ActionID 1] : LaunchApp waiting for user response to KickingOtherSession "DRAGON BALL: Sparking! ZERO" + + """ + var questions = SteamLaunchQuestions() + questions.read(log, now: date(0)) + XCTAssertTrue(questions.isAsking(appID: 2141910, now: date(1))) + } +} + +final class SteamConsoleLogTests: XCTestCase { + private var folder: URL! + private var file: URL { folder.appendingPathComponent("logs/console_log.txt") } + + override func setUpWithError() throws { + folder = FileManager.default.temporaryDirectory.appendingPathComponent("SteamConsoleLog-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder.appendingPathComponent("logs"), withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: folder) + super.tearDown() + } + + private func append(_ text: String) throws { + if !FileManager.default.fileExists(atPath: file.path) { FileManager.default.createFile(atPath: file.path, contents: nil) } + let handle = try FileHandle(forWritingTo: file) + defer { try? handle.close() } + try handle.seekToEnd() + try handle.write(contentsOf: Data(text.utf8)) + } + + func testTheLogLivesInSteamsLogsFolder() { + XCTAssertEqual(SteamConsoleLog(steamRoot: folder).fileURL, file) + } + + func testAMissingLogReadsNothing() { + var log = SteamConsoleLog(steamRoot: folder) + XCTAssertNil(log.readNew()) + } + + func testTheFirstReadTakesTheFileThenOnlyWhatWasAdded() throws { + try append("one\n") + var log = SteamConsoleLog(steamRoot: folder) + XCTAssertEqual(log.readNew()?.text, "one\n") + XCTAssertEqual(log.readNew()?.isNewFile, false) + XCTAssertEqual(log.readNew()?.text, "") + try append("two\n") + let next = log.readNew() + XCTAssertEqual(next?.text, "two\n") + XCTAssertEqual(next?.isNewFile, false) + } + + func testTheFirstReadIsANewFile() throws { + try append("one\n") + var log = SteamConsoleLog(steamRoot: folder) + XCTAssertEqual(log.readNew()?.isNewFile, true) + } + + func testANewFileFromAStartingSteamIsReadFromTheTop() throws { + try append("an old session that ran long\n") + var log = SteamConsoleLog(steamRoot: folder) + _ = log.readNew() + try FileManager.default.removeItem(at: file) + try append("new\n") + let next = log.readNew() + XCTAssertEqual(next?.text, "new\n") + XCTAssertEqual(next?.isNewFile, true) + } + + func testAShorterFileIsANewFile() throws { + try append("an old session that ran long\n") + var log = SteamConsoleLog(steamRoot: folder) + _ = log.readNew() + try Data("new\n".utf8).write(to: file) + XCTAssertEqual(log.readNew()?.isNewFile, true) + } + + /// A line Steam is still writing is read once it ends, so a character cut between two reads stays whole. + func testACharacterCutBetweenReadsStaysWhole() throws { + let line = Data("GameAction \"Pokémon\"\n".utf8) + let cut = line.firstIndex(of: 0xC3)! + 1 + try line[..<cut].write(to: file) + var log = SteamConsoleLog(steamRoot: folder) + XCTAssertEqual(log.readNew()?.text, "") + let handle = try FileHandle(forWritingTo: file) + try handle.seekToEnd(); try handle.write(contentsOf: line[cut...]); try handle.close() + XCTAssertEqual(log.readNew()?.text, "GameAction \"Pokémon\"\n") + } + + func testAnUnfinishedLineWaitsForItsEnd() throws { + try append("one\ntw") + var log = SteamConsoleLog(steamRoot: folder) + XCTAssertEqual(log.readNew()?.text, "one\n") + try append("o\n") + XCTAssertEqual(log.readNew()?.text, "two\n") + } + + func testOnlyTheEndOfALongFileIsReadFromItsFirstWholeLine() throws { + try append("aaaaaaaaaa\nbbbbbbbbbb\ncccc\n") + var log = SteamConsoleLog(steamRoot: folder) + XCTAssertEqual(log.readNew(limit: 10)?.text, "cccc\n") + } +} + +final class SteamLaunchQuestionWatchTests: XCTestCase { + private var folder: URL! + private var file: URL { folder.appendingPathComponent("logs/console_log.txt") } + private func date(_ seconds: TimeInterval) -> Date { Date(timeIntervalSince1970: seconds) } + private let question = "[2026-11-14 18:03:08] GameAction [AppID 2141910, ActionID 1] : LaunchApp waiting for user response to KickingOtherSession \"Game\"\n" + + override func setUpWithError() throws { + folder = FileManager.default.temporaryDirectory.appendingPathComponent("SteamQuestionWatch-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder.appendingPathComponent("logs"), withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: folder) + super.tearDown() + } + + /// Steam asked before this Play and still waits: a new steam://run adds no GameAction line. + func testAQuestionStillOpenFromAnEarlierPlayAsks() throws { + try Data((question + "[2026-11-14 18:13:38] ExecuteSteamURL: \"steam://run/2141910\"\n").utf8).write(to: file) + var watch = SteamLaunchQuestionWatch(appID: 2141910, steamRoot: folder) + XCTAssertFalse(watch.look(now: date(0))) + XCTAssertTrue(watch.look(now: date(1))) + } + + func testAStartingSteamsNewLogForgetsTheOldQuestion() throws { + try Data(question.utf8).write(to: file) + var watch = SteamLaunchQuestionWatch(appID: 2141910, steamRoot: folder) + _ = watch.look(now: date(0)) + try FileManager.default.removeItem(at: file) + try Data("[2026-11-14 18:20:00] Console Log Start\n".utf8).write(to: file) + XCTAssertFalse(watch.look(now: date(5))) + } + + func testWithoutALogNothingAsks() { + var watch = SteamLaunchQuestionWatch(appID: 2141910, steamRoot: folder) + XCTAssertFalse(watch.look(now: date(5))) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift b/Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift new file mode 100644 index 00000000..64b6caa0 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift @@ -0,0 +1,314 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamLibrarySourceTests: XCTestCase { + func testFindsTwoDistinctGamesAndDoesNotWriteSourceFiles() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.manifest(in: root, id: "20", name: "Second game", directory: "Second") + try f.app(at: "Steam/steamapps/common/First/Game.app") + try f.app(at: "Steam/steamapps/common/Second/Game.app") + let before = try f.inventory() + let result = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(result.games.map(\.appID), [10, 20]) + XCTAssertEqual(result.games.map(\.name), ["First game", "Second game"]) + XCTAssertEqual(result.games.map(\.state), [.nativeReady, .nativeReady]) + XCTAssertEqual(result.games.first?.reportedSizeBytes, 100) + XCTAssertEqual(result.games.first?.buildID, "42") + XCTAssertTrue(result.libraries.first?.isComplete == true) + XCTAssertEqual(try f.inventory(), before) + } + + func testModernAndLegacyIndexesIncludeExternalLibrariesAndDeduplicatePaths() throws { + for modern in [false, true] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library(), external = try f.library("External library") + try f.manifest(in: external) + try f.app(at: "External library/steamapps/common/First/Game.app") + let value = modern ? "{ path \(SteamTestFixture.quote(external.path)) label \"\" }" : SteamTestFixture.quote(external.path) + let index = "libraryfolders { 0 { path \(SteamTestFixture.quote(root.path)) } 1 \(value) 2 \(value) }" + try Data(index.utf8).write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf")) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(result.libraries.count, 2) + XCTAssertEqual(result.games.map(\.appID), [10]) + } + } + + func testMissingOrMalformedIndexDoesNotHideDefaultLibraryOrItsError() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.count, 1) + try Data("libraryfolders {".utf8).write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf")) + let partial = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(partial.games.count, 1) + XCTAssertTrue(partial.issues.contains { $0.reason == .invalidIndex }) + XCTAssertFalse(partial.libraries[0].isComplete) + } + + func testUnavailableExternalLibraryIsNotASuccessfulEmptyScan() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library(), absent = f.root.appendingPathComponent("disconnected") + let index = "libraryfolders { 1 { path \(SteamTestFixture.quote(absent.path)) } }" + try Data(index.utf8).write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf")) + let result = try SteamLibrarySource(root: root).scan() + let observation = try XCTUnwrap(result.libraries.first { $0.root.path == absent.path }) + XCTAssertFalse(observation.isReadable) + XCTAssertFalse(observation.isComplete) + XCTAssertTrue(result.issues.contains { $0.reason == .unavailableLibrary }) + } + + func testInvalidManifestRetainsFilenameIdentityInIssueContext() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + let manifest = try f.manifest(in: root) + try Data("AppState {".utf8).write(to: manifest) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertTrue(result.games.isEmpty) + XCTAssertTrue(result.issues.contains { $0.reason == .invalidManifest && $0.appID == 10 }) + XCTAssertFalse(result.libraries[0].isComplete) + } + + func testDuplicateOrWrongTypedKnownScalarsRejectTheManifest() throws { + for field in ["APPID 10", "NAME Other", "INSTALLDIR First", "SizeOnDisk {}", "buildid {}", "StateFlags {}"] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + let manifest = root.appendingPathComponent("steamapps/appmanifest_10.acf") + try Data("AppState { appid 10 name Fixture installdir First \(field) }".utf8).write(to: manifest) + try f.app(at: "Steam/steamapps/common/First/Game.app") + let result = try SteamLibrarySource(root: root).scan() + XCTAssertTrue(result.games.isEmpty, field) + XCTAssertTrue(result.issues.contains { $0.reason == .invalidManifest && $0.appID == 10 }, field) + XCTAssertFalse(result.libraries[0].isComplete, field) + } + } + + func testDuplicateOrWrongTypedLibraryPathPreservesDefaultLibraryAndReportsInvalidIndex() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + for path in ["path {}", "path \"/Volumes/First\" PATH \"/Volumes/Second\""] { + let index = root.appendingPathComponent("steamapps/libraryfolders.vdf") + try Data("libraryfolders { 1 { \(path) } }".utf8).write(to: index) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(result.games.map(\.appID), [10]) + XCTAssertTrue(result.issues.contains { $0.reason == .invalidIndex }) + XCTAssertFalse(result.libraries[0].isComplete) + } + } + + func testRejectsMismatchedOrInvalidAppIdentifiers() throws { + for id in ["20", "+10", "0", "4294967296", "a10"] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root, id: id, filenameID: "10") + let result = try SteamLibrarySource(root: root).scan() + XCTAssertTrue(result.games.isEmpty, id) + XCTAssertFalse(result.issues.isEmpty, id) + } + } + + func testEscapedUnicodeNamesAndInvalidOptionalSizes() throws { + for size in ["-1", "9223372036854775808"] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root, name: "L'avventura \"è\" bella", directory: "Gioco è", size: size) + try f.app(at: "Steam/steamapps/common/Gioco è/Game.app") + let result = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(result.games.first?.name, "L'avventura \"è\" bella") + XCTAssertNil(result.games.first?.reportedSizeBytes) + XCTAssertEqual(result.games.first?.state, .nativeReady) + } + } + + func testUnsafeInstallDirectoryDoesNotEscapeTheLibrary() throws { + for directory in ["../escape", "/tmp/escape", "First/../../escape"] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root, directory: directory) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertTrue(result.games.isEmpty) + XCTAssertTrue(result.issues.contains { $0.reason == .unsafePath }) + } + } + + func testSymlinkInstallEscapeIsRejected() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + let externalApp = try f.app(at: "Elsewhere/Game.app") + try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("steamapps/common/First"), + withDestinationURL: externalApp.deletingLastPathComponent()) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertTrue(result.games.isEmpty) + XCTAssertTrue(result.issues.contains { $0.reason == .unsafePath }) + } + + func testSymlinkedSteamappsCannotSupplyAnIndexOutsideTheChosenRoot() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library(), foreign = try f.library("Foreign"), third = try f.library("Third") + try f.manifest(in: third) + try f.app(at: "Third/steamapps/common/First/Game.app") + try Data("libraryfolders { 1 \(SteamTestFixture.quote(third.path)) }".utf8) + .write(to: foreign.appendingPathComponent("steamapps/libraryfolders.vdf")) + try FileManager.default.removeItem(at: root.appendingPathComponent("steamapps")) + try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("steamapps"), + withDestinationURL: foreign.appendingPathComponent("steamapps")) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertTrue(result.games.isEmpty) + XCTAssertEqual(result.libraries.count, 1) + XCTAssertTrue(result.issues.contains { $0.reason == .unsafePath }) + } + + func testLibraryAndManifestLimitsAreReported() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library(), external = try f.library("External") + try f.manifest(in: root) + try f.manifest(in: root, id: "20", directory: "Second") + try Data("libraryfolders { 1 \(SteamTestFixture.quote(external.path)) }".utf8) + .write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf")) + var limits = SteamScanLimits.standard + limits.maximumLibraries = 1 + limits.maximumManifests = 1 + let result = try SteamLibrarySource(root: root, limits: limits).scan() + XCTAssertEqual(result.libraries.count, 1) + XCTAssertEqual(result.games.count, 1) + XCTAssertFalse(result.isComplete) + XCTAssertTrue(result.issues.contains { $0.reason == .libraryLimit }) + XCTAssertTrue(result.issues.contains { $0.reason == .manifestLimit }) + } + + func testDuplicateAppIdsAcrossLibrariesRemainAmbiguousObservations() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library(), second = try f.library("Other") + for library in [root, second] { try f.manifest(in: library) } + try f.app(at: "Steam/steamapps/common/First/Game.app") + try f.app(at: "Other/steamapps/common/First/Game.app") + try Data("libraryfolders { 1 \(SteamTestFixture.quote(second.path)) }".utf8) + .write(to: root.appendingPathComponent("steamapps/libraryfolders.vdf")) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(result.games.count, 2) + XCTAssertTrue(result.games.allSatisfy { $0.state == .requiresReview }) + XCTAssertTrue(result.issues.contains { $0.reason == .conflictingIdentity }) + } + + func testMainGameAndHelperAreNotTwoGames() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + try f.app(at: "Steam/steamapps/common/First/Helper.app", category: nil) + let result = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(result.games.first?.state, .nativeReady) + XCTAssertEqual(result.games.first?.nativeApps.filter(\.isDeclaredGame).count, 1) + } + + func testRecognizedTopLevelGameDoesNotRequireWalkingItsLooseDataTree() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/Game.app") + try FileManager.default.createDirectory(at: root.appendingPathComponent("steamapps/common/First/LooseData/deep/assets"), + withIntermediateDirectories: true) + var limits = SteamScanLimits.standard + limits.maximumDirectoriesPerInstall = 1 + let result = try SteamLibrarySource(root: root, limits: limits).scan() + XCTAssertEqual(result.games.first?.state, .nativeReady) + XCTAssertTrue(result.isComplete) + } + + func testToolsUnclassifiedAndMultipleMainAppsAreNotConfirmedGames() throws { + for categories: [String?] in [["public.app-category.developer-tools"], [nil], + ["public.app-category.games", "public.app-category.games"]] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + for (i, category) in categories.enumerated() { + try f.app(at: "Steam/steamapps/common/First/App\(i).app", category: category) + } + XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.first?.state, .requiresReview) + } + } + + func testMissingContentAndWindowsOnlyDirectoryAreNotNativeReady() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.first?.state, .unavailable) + let install = root.appendingPathComponent("steamapps/common/First") + try FileManager.default.createDirectory(at: install, withIntermediateDirectories: true) + try Data("synthetic".utf8).write(to: install.appendingPathComponent("game.exe")) + XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.first?.state, .unavailable) + } + + func testLimitsDoNotReturnADeceptivelyCompleteLibrary() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root) + try f.app(at: "Steam/steamapps/common/First/deep/Game.app") + var limits = SteamScanLimits.standard + limits.maximumDirectoriesPerInstall = 1 + let limited = try SteamLibrarySource(root: root, limits: limits).scan() + XCTAssertFalse(limited.libraries[0].isComplete) + XCTAssertTrue(limited.issues.contains { $0.reason == .directoryLimit }) + limits = .standard + limits.maximumTextBytes = 10 + let oversized = try SteamLibrarySource(root: root, limits: limits).scan() + XCTAssertTrue(oversized.games.isEmpty) + XCTAssertTrue(oversized.issues.contains { $0.reason == .oversizedManifest }) + } + + func testCancellationThrowsRatherThanPublishingPartialResults() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + XCTAssertThrowsError(try SteamLibrarySource(root: root).scan(cancelled: { true })) { + XCTAssertTrue($0 is CancellationError) + } + } + + func testSourceSnapshotDetectsAFileChangingBeforePublication() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + let file = try f.manifest(in: root) + let snapshot = try InstallationFileSnapshot.read(at: file, maximumBytes: 1024) + try Data("changed".utf8).write(to: file, options: .atomic) + XCTAssertThrowsError(try snapshot.verifyUnchanged()) + XCTAssertEqual(try String(contentsOf: file), "changed") + } + + func testManifestWithoutFullyInstalledIsDownloadingAndNotWalked() throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root, stateFlags: "1026") + // A partial bundle Steam is still writing: it must not be read or raise an issue. + try f.app(at: "Steam/steamapps/common/First/Game.app") + let result = try SteamLibrarySource(root: root).scan() + XCTAssertEqual(result.games.map(\.state), [.downloading]) + XCTAssertEqual(result.games.first?.nativeApps, []) + XCTAssertTrue(result.issues.isEmpty) + } + + func testFullyInstalledBitWinsOverUpdateBits() throws { + for flags in ["6", "1030"] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root, stateFlags: flags) + try f.app(at: "Steam/steamapps/common/First/Game.app") + XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.map(\.state), [.nativeReady], flags) + } + } + + func testMissingOrGarbageStateFlagsKeepTodayBehaviour() throws { + for flags in [nil, "abc"] as [String?] { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + try f.manifest(in: root, stateFlags: flags) + try f.manifest(in: root, id: "20", name: "Empty", directory: "Empty", stateFlags: flags) + try f.app(at: "Steam/steamapps/common/First/Game.app") + XCTAssertEqual(try SteamLibrarySource(root: root).scan().games.map(\.state), [.nativeReady, .unavailable]) + } + } +} diff --git a/Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift b/Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift new file mode 100644 index 00000000..e476f5ca --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift @@ -0,0 +1,81 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamManifestWatcherTests: XCTestCase { + func testOnlyManifestsAndTheLibraryIndexAreRelevant() { + let root = "/Users/p/Library/Application Support/Steam", second = "/Volumes/Games/SteamLibrary" + let libraries = [root, second] // as `watch` keeps them: resolved paths + func relevant(_ path: String) -> Bool { SteamManifestWatcher.isRelevant(path, libraries: libraries, root: root) } + XCTAssertTrue(relevant(root + "/steamapps/appmanifest_3321460.acf")) + XCTAssertTrue(relevant(second + "/steamapps/appmanifest_10.acf")) + XCTAssertTrue(relevant(root + "/steamapps/libraryfolders.vdf")) + XCTAssertFalse(relevant(second + "/steamapps/libraryfolders.vdf")) + XCTAssertFalse(relevant(root + "/steamapps/downloading/3321460/data.bin")) + XCTAssertFalse(relevant(root + "/steamapps/common/Game/appmanifest_1.acf")) + XCTAssertFalse(relevant(root + "/steamapps/appmanifest_1.acf.tmp")) + XCTAssertFalse(relevant(root + "/steamapps/appmanifest_x.acf")) + XCTAssertFalse(relevant(root + "/steamapps/appmanifest_.acf")) + XCTAssertFalse(relevant("/Volumes/Other/steamapps/appmanifest_1.acf")) + XCTAssertFalse(relevant(root + "/steamapps")) + } + + func testDroppedEventsCountOnlyForASteamappsFolderOrAbove() { + let root = "/Users/p/Library/Application Support/Steam" + func dropped(_ path: String) -> Bool { SteamManifestWatcher.isRelevant(path, dropped: true, libraries: [root], root: root) } + // A drop inside a download's folder says nothing about the manifests: no rescan every batch. + XCTAssertFalse(dropped(root + "/steamapps/downloading/3321460")) + XCTAssertFalse(dropped(root + "/steamapps/common/Game")) + XCTAssertTrue(dropped(root + "/steamapps")) + XCTAssertTrue(dropped(root + "/steamapps/")) + XCTAssertTrue(dropped("/Users/p/Library")) + XCTAssertFalse(dropped("/Volumes/Other")) + XCTAssertTrue(SteamManifestWatcher.isRelevant(root + "/steamapps/appmanifest_1.acf", dropped: false, libraries: [root], root: root)) + } + + @MainActor + func testRetriesTheSameLibraryWhenItsFolderBecomesAvailable() async throws { + let f = try SteamTestFixture.temporary(in: self) + let library = f.root.appendingPathComponent("Later") + let changed = expectation(description: "Newly available library is watched") + let watcher = SteamManifestWatcher { changed.fulfill() } + defer { watcher.stop() } + watcher.watch([library], root: library) + _ = try f.library("Later") + watcher.watch([library], root: library) + try f.manifest(in: library) + await fulfillment(of: [changed], timeout: 6) + } + + @MainActor + func testAddsANewlyAvailableLibraryAlongsideAnExistingStream() async throws { + let f = try SteamTestFixture.temporary(in: self) + let root = try f.library() + let library = f.root.appendingPathComponent("Later") + let changed = expectation(description: "Additional library is watched") + let watcher = SteamManifestWatcher { changed.fulfill() } + defer { watcher.stop() } + watcher.watch([root, library], root: root) + _ = try f.library("Later") + watcher.watch([root, library], root: root) + try f.manifest(in: library) + await fulfillment(of: [changed], timeout: 6) + } + + @MainActor + func testTheStreamKeepsItsWatcherAliveUntilStopped() throws { + let f = try SteamTestFixture.temporary(in: self) + let library = try f.library() + weak var weakWatcher: SteamManifestWatcher? + do { + let watcher = SteamManifestWatcher() + watcher.watch([library], root: library) + weakWatcher = watcher + } + // A callback already queued must still find its watcher. + XCTAssertNotNil(weakWatcher) + weakWatcher?.stop() + // The stream lets go of its context on its queue (the main one). + RunLoop.main.run(until: Date().addingTimeInterval(0.2)) + XCTAssertNil(weakWatcher) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamMetadataTests.swift b/Tests/NXLibraryCoreTests/SteamMetadataTests.swift new file mode 100644 index 00000000..ac503373 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamMetadataTests.swift @@ -0,0 +1,209 @@ +import XCTest +import AppKit +@testable import NXLibraryCore + +final class SteamMetadataTests: XCTestCase { + private func payload(id: Int = 10) -> Data { + Data(""" + {"10":{"success":true,"data":{"steam_appid":\(id),"name":"Fixture","short_description":"A & B","genres":[{"id":"2","description":"Strategia"}],"developers":["Studio"],"publishers":["Publisher"],"release_date":{"date":"23 mag 2023"},"screenshots":[{"path_full":"https://shared.akamai.steamstatic.com/test.jpg"},{"path_full":"http://localhost/private"}]}}} + """.utf8) + } + func testIdentityLocalizedFieldsAndSafeScreenshots() throws { + let value = try SteamMetadata.decode(payload(), appID: 10, language: "italian") + XCTAssertEqual(value.description, "A & B") + XCTAssertEqual(value.genres, ["Strategia"]) + XCTAssertEqual(value.screenshots.count, 1) + XCTAssertEqual(value.releaseDate, "23 mag 2023") + XCTAssertThrowsError(try SteamMetadata.decode(payload(id: 20), appID: 10, language: "italian")) + XCTAssertThrowsError(try SteamMetadata.decode(Data("{}".utf8), appID: 10, language: "italian")) + XCTAssertNil(SteamMetadata.safeImage(URL(string: "https://steamstatic.com.attacker.test/x"))) + } + func testLanguageMappingIsIndependentOfRegionalFormats() { + XCTAssertEqual(SteamMetadata.language(.portugueseBrazil), "brazilian") + XCTAssertEqual(SteamMetadata.language(.italian), "italian") + } + func testRelatedTraitsReadTheRequestedLanguageFromCacheWithoutNetwork() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let body = payload() + let online = SteamMetadataService(directory: root, transport: { _ in body }) + _ = await online.metadata(appID: 10, language: "italian") + let cached = SteamMetadataService(directory: root, transport: { _ in + XCTFail("Recommendations must read the cache without fetching other games") + throw URLError(.notConnectedToInternet) + }) + let italian = await cached.cachedRelatedTraits(appIDs: [10, 20], language: "italian") + let english = await cached.cachedRelatedTraits(appIDs: [10], language: "english") + XCTAssertEqual(italian[10]?.genres, ["Strategia"]) + XCTAssertEqual(italian[10]?.developers, ["Studio"]) + XCTAssertNil(italian[20]) + XCTAssertTrue(english.isEmpty) + } + func testOfflineCacheAndPersonalDataAreIndependentOfRefresh() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let body = payload() + let online = SteamMetadataService(directory: root, transport: { _ in body }) + let first = await online.metadata(appID: 10, language: "italian") + XCTAssertEqual(first?.genres, ["Strategia"]) + let offline = SteamMetadataService(directory: root, transport: { _ in throw URLError(.notConnectedToInternet) }) + let retained = await offline.metadata(appID: 10, language: "italian", refresh: true) + XCTAssertEqual(retained, first) + let other = await offline.metadata(appID: 10, language: "english") + XCTAssertNil(other) + let picks = MetadataPicks(directory: root.appendingPathComponent("personal")) + picks.set("My description", titleID: "10", field: .description) + _ = await online.metadata(appID: 10, language: "italian", refresh: true) + XCTAssertEqual(picks.value(titleID: "10", field: .description), "My description") + } + func testConcurrentMetadataRequestsShareOneTransport() async throws { + actor Counter { + var count = 0 + func bump() { count += 1 } + } + let counter = Counter(), body = payload() + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = SteamMetadataService(directory: root, transport: { _ in + await counter.bump(); try await Task.sleep(nanoseconds: 30_000_000); return body + }) + async let a = service.metadata(appID: 10, language: "english") + async let b = service.metadata(appID: 10, language: "english") + let values = await (a, b) + XCTAssertNotNil(values.0); XCTAssertEqual(values.0?.description, values.1?.description) + let count = await counter.count + XCTAssertEqual(count, 1) + } + func testFailedPersonalSaveDoesNotPublishUnsavedValues() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + try Data("not a folder".utf8).write(to: root) + let picks = SteamPersonalizationStore(directory: root) + XCTAssertThrowsError(try picks.save(fields: [.description: "Lost"], images: [:], automatic: [], titleID: "10")) + XCTAssertNil(picks.value(titleID: "10", field: .description)) + XCTAssertEqual(picks.revision, 0) + } + func testStoreFailuresAndNonHTTPSImagesAreRejected() throws { + XCTAssertThrowsError(try SteamMetadata.decode(Data("{\"10\":{\"success\":false}}".utf8), appID: 10, language: "english")) + for text in ["http://cdn.steamstatic.com/a", "https://user@cdn.steamstatic.com/a", "https://cdn.steamstatic.com:444/a", "file:///tmp/a"] { + XCTAssertNil(SteamMetadata.safeImage(URL(string: text))) + } + } + + func testSemanticFailuresBackOffWithoutLosingTheLibrary() async { + actor Calls { var count = 0; func bump() { count += 1 } } + let calls = Calls() + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return Data("{}".utf8) }) + let first = await service.metadata(appID: 10, language: "english") + let second = await service.metadata(appID: 10, language: "english") + XCTAssertNil(first); XCTAssertNil(second) + let count = await calls.count; XCTAssertEqual(count, 1) + } + func testCancellingSoleImageWaiterStopsTransportAndFallbacks() async { + actor Calls { var count = 0; func bump() { count += 1 } } + let calls = Calls(), started = expectation(description: "started"), stopped = expectation(description: "cancelled") + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = SteamMetadataService(directory: root, transport: { _ in + await calls.bump(); started.fulfill() + do { try await Task.sleep(nanoseconds: 10_000_000_000); return Data() } + catch { stopped.fulfill(); throw error } + }) + let request = Task { await service.image(appID: 10, slot: .cover) } + await fulfillment(of: [started], timeout: 1) + request.cancel() + await fulfillment(of: [stopped], timeout: 1) + let image = await request.value; XCTAssertNil(image) + let count = await calls.count; XCTAssertEqual(count, 1) + } + func testCancelledSharedWaiterPreservesInterestedReader() async { + let started = expectation(description: "started"), body = payload() + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = SteamMetadataService(directory: root, transport: { _ in + started.fulfill(); try await Task.sleep(nanoseconds: 150_000_000); return body + }) + let a = Task { await service.metadata(appID: 10, language: "english") } + await fulfillment(of: [started], timeout: 1) + let b = Task { await service.metadata(appID: 10, language: "english") } + try? await Task.sleep(nanoseconds: 30_000_000) + a.cancel() + let result = await b.value; XCTAssertNotNil(result) + let cancelled = await a.value; XCTAssertNil(cancelled) + } + func testFailedCombinedDraftKeepsAllPreviousPicksAndAutomaticReferences() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let image = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 2, pixelsHigh: 2, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! + let png = image.representation(using: .png, properties: [:])! + let initial = SteamPersonalizationStore(directory: root) + try initial.save(fields: [.description: "Previous"], images: [.cover: png], automatic: [], titleID: "10") + let original = initial.url(titleID: "10", slot: .cover)! + let before = try Data(contentsOf: original) + let failing = SteamPersonalizationStore(directory: root, publish: { _,_ in throw CocoaError(.fileWriteOutOfSpace) }) + XCTAssertThrowsError(try failing.save(fields: [.description: "New"], images: [.logo: png], automatic: [.cover], titleID: "10")) + let restored = SteamPersonalizationStore(directory: root) + XCTAssertEqual(restored.value(titleID: "10", field: .description), "Previous") + XCTAssertEqual(restored.url(titleID: "10", slot: .cover), original) + XCTAssertEqual(try Data(contentsOf: original), before) + XCTAssertNil(restored.url(titleID: "10", slot: .logo)) + XCTAssertEqual(failing.revision, 0) + try initial.save(fields: [:], images: [:], automatic: [.cover], titleID: "10") + XCTAssertNil(SteamPersonalizationStore(directory: root).url(titleID: "10", slot: .cover)) + } + + func testRedirectIsRefusedBeforeSendingAnotherRequest() { + let session = URLSession(configuration: .ephemeral) + defer { session.invalidateAndCancel() } + let initial = URL(string: "https://store.steampowered.com/api/appdetails")! + let task = session.dataTask(with: initial) + let response = HTTPURLResponse(url: initial, statusCode: 302, httpVersion: nil, headerFields: nil)! + let delegate = SteamMetadataService.NoRedirects() + var invoked = false + delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, + newRequest: URLRequest(url: URL(string: "https://example.invalid/private")!)) { request in + invoked = true; XCTAssertNil(request) + } + XCTAssertTrue(invoked) + XCTAssertEqual(task.state, .suspended) + XCTAssertFalse(SteamMetadataService.allowed(URL(string: "http://store.steampowered.com/a")!)) + } + func testInvalidImageBytesAreBackedOffForBothCandidateURLs() async { + actor Calls { var count = 0; func bump() { count += 1 } } + let calls = Calls(), root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = SteamMetadataService(directory: root, transport: { _ in await calls.bump(); return Data("invalid image".utf8) }) + _ = await service.image(appID: 10, slot: .cover) + _ = await service.image(appID: 10, slot: .cover) + let count = await calls.count; XCTAssertEqual(count, 2) + } + func testSelectionBurstBoundsOutstandingTransfers() async { + actor Calls { + var active = 0, peak = 0 + func enter() { active += 1; peak = max(peak, active) } + func leave() { active -= 1 } + } + let calls = Calls(), root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let service = SteamMetadataService(directory: root, transport: { _ in + await calls.enter(); try await Task.sleep(nanoseconds: 100_000_000); await calls.leave(); return Data("{}".utf8) + }) + await withTaskGroup(of: Void.self) { group in + for id in 1...20 { group.addTask { _ = await service.metadata(appID: UInt32(id), language: "english") } } + } + let peak = await calls.peak; XCTAssertGreaterThan(peak, 0); XCTAssertLessThanOrEqual(peak, 6) + } + func testUnreadablePersonalManifestIsPreserved() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let file = root.appendingPathComponent("personal.json"), original = Data("damaged".utf8) + try original.write(to: file) + let store = SteamPersonalizationStore(directory: root) + XCTAssertThrowsError(try store.save(fields: [.description: "New"], images: [:], automatic: [], titleID: "10")) + XCTAssertEqual(try Data(contentsOf: file), original) + } + +} diff --git a/Tests/NXLibraryCoreTests/SteamOptionsTests.swift b/Tests/NXLibraryCoreTests/SteamOptionsTests.swift new file mode 100644 index 00000000..3c74e331 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamOptionsTests.swift @@ -0,0 +1,64 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamOptionsTests: XCTestCase { + func testSteamMainRowsAreNxnativeCommonRowsInTheSameOrder() { + let nx = GameOptionsPresentation(supportsRenderScale: false, isPlayable: true, sourcesDetached: false) + for origin in [GameOptionsOrigin.spotlight, .collection] { + let steam = SteamOptionsPresentation(canPlay: true, hasApp: true).focusableRows(level: .main, origin: origin) + let shared = nx.focusableRows(level: .main, origin: origin).filter(steam.contains) + XCTAssertEqual(steam, shared) + } + XCTAssertTrue(SteamOptionsPresentation(canPlay: true, hasApp: true).focusableRows(level: .main, origin: .spotlight).contains(.move)) + XCTAssertFalse(SteamOptionsPresentation(canPlay: true, hasApp: true).focusableRows(level: .main, origin: .collection).contains(.move)) + } + + func testSteamOptionsOfferNothingFromNxnative() { + let p = SteamOptionsPresentation(canPlay: true, hasApp: true) + let all = Set(p.focusableRows(level: .main, origin: .spotlight) + p.focusableRows(level: .editDetails, origin: .spotlight)) + XCTAssertTrue(all.isDisjoint(with: [.fullscreen, .frameRate, .consoleMode, .cheats, .mods, .openSaves, .rebuild, + .attachSources, .openLog, .removeSources, .removeGame, .restoreDefaults])) + XCTAssertEqual(p.focusableRows(level: .editDetails, origin: .collection), [.changeArtwork, .changeMetadata, .storePage]) + XCTAssertTrue(all.allSatisfy { p.about($0) != nil }) + } + + func testPlayAndFinderDimWithoutAnInstallation() { + let missing = SteamOptionsPresentation(canPlay: false, hasApp: false) + XCTAssertTrue(missing.isDimmed(.play)) + XCTAssertTrue(missing.isDimmed(.showInFinder)) + XCTAssertFalse(missing.isDimmed(.favorite)) + XCTAssertFalse(SteamOptionsPresentation(canPlay: true, hasApp: true).isDimmed(.play)) + } + + func testSteamArtworkPutsTheExactAppFirstWithoutRepeats() throws { + let shot = try XCTUnwrap(URL(string: "https://shared.akamai.steamstatic.com/shot1.jpg")) + let steamCover = SteamStoreArt.candidates(appID: 10, slot: .cover) + let other = ArtworkCandidate(slot: .cover, source: "SteamGridDB", url: try XCTUnwrap(URL(string: "https://example.com/c.png"))) + let covers = ArtworkCandidates.steamList(for: .cover, appID: 10, screenshots: [shot], + online: [steamCover[0], other, ArtworkCandidate(slot: .logo, source: "x", url: shot)]) + XCTAssertEqual(covers.map(\.url), [steamCover[0].url, other.url]) + let backgrounds = ArtworkCandidates.steamList(for: .background, appID: 10, screenshots: [shot]) + XCTAssertEqual(backgrounds.map(\.source), ["Steam library", "Steam screenshot 1"]) + XCTAssertTrue(ArtworkCandidates.steamList(for: .icon, appID: 10, screenshots: [shot]).isEmpty) + XCTAssertTrue(ArtworkCandidates.steamList(for: .cover, appID: 0, screenshots: []).isEmpty) + } +} + +final class SteamLaunchSettingTests: XCTestCase { + func testSteamStaysInTheBackgroundByDefaultAndOldFilesKeepIt() throws { + XCTAssertTrue(AppSettings().steamInBackground) + let old = try JSONDecoder().decode(AppSettings.self, from: Data("{}".utf8)) + XCTAssertTrue(old.steamInBackground) + var off = AppSettings(); off.steamInBackground = false + let back = try JSONDecoder().decode(AppSettings.self, from: JSONEncoder().encode(off)) + XCTAssertFalse(back.steamInBackground) + } + + func testTheSettingIsListedWithSteamAndMarkedChangedWhenOff() throws { + let row = try XCTUnwrap(SettingsCatalog.all.first { $0.id == "steamInBackground" }) + XCTAssertEqual(row.group, .sources) + var off = AppSettings(); off.steamInBackground = false + XCTAssertTrue(row.isChanged(off)) + XCTAssertFalse(row.isChanged(AppSettings())) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamPlayStateTests.swift b/Tests/NXLibraryCoreTests/SteamPlayStateTests.swift new file mode 100644 index 00000000..16289825 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamPlayStateTests.swift @@ -0,0 +1,157 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamPlayStateTests: XCTestCase { + private let app = CatalogNativeApplication(NativeMacApplication( + url: URL(fileURLWithPath: "/Steam/steamapps/common/Game/Game.app"), + executableURL: URL(fileURLWithPath: "/Steam/steamapps/common/Game/Game.app/Contents/MacOS/Game"), + bundleIdentifier: "com.example.game", name: "Game", architectures: [.arm64], isDeclaredGame: true, fileObservations: [])) + private let t0 = Date(timeIntervalSince1970: 1_000_000) + private var game: NativeProcessObservation { + .init(pid: 42, bundleURL: app.url, executableURL: app.executableURL) + } + private let steamClient = NativeProcessObservation(pid: 7, bundleURL: URL(fileURLWithPath: "/Applications/Steam.app"), + executableURL: URL(fileURLWithPath: "/Applications/Steam.app/Contents/MacOS/steam_osx")) + + func testAnInstallationReachedThroughASymlinkMatchesTheRunningApp() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let real = root.appendingPathComponent("Drive/common/Game") + try FileManager.default.createDirectory(at: real.appendingPathComponent("Game.app/Contents/MacOS"), withIntermediateDirectories: true) + try Data().write(to: real.appendingPathComponent("Game.app/Contents/MacOS/Game")) + try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("steamapps"), withDestinationURL: root.appendingPathComponent("Drive")) + let linked = root.appendingPathComponent("steamapps/common/Game/Game.app") + let installed = CatalogNativeApplication(NativeMacApplication( + url: linked, executableURL: linked.appendingPathComponent("Contents/MacOS/Game"), + bundleIdentifier: "com.example.game", name: "Game", architectures: [.arm64], isDeclaredGame: true, fileObservations: [])) + // The system names the real path; the caller hands it over in canonical form. + let running = NativeProcessObservation(pid: 42, bundleURL: real.appendingPathComponent("Game.app"), + executableURL: real.appendingPathComponent("Game.app/Contents/MacOS/Game")).canonical() + var state = SteamPlayState() + XCTAssertEqual(state.observe([running], application: installed, now: t0), .started(pid: 42)) + XCTAssertNil(state.observe([running], application: installed, now: t0.addingTimeInterval(30)), "still the same game") + } + + func testHandOffStartsNoSessionUntilTheGameItselfRuns() { + var state = SteamPlayState() + XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0), + .handOff(URL(string: "steam://run/570")!, generation: 1)) + state.handoffFinished(accepted: true, generation: 1) + XCTAssertNil(state.observe([steamClient], application: app, now: t0.addingTimeInterval(5)), "Steam alone is not the game") + XCTAssertEqual(state.phase, .starting(since: t0)) + XCTAssertEqual(state.observe([steamClient, game], application: app, now: t0.addingTimeInterval(20)), .started(pid: 42)) + XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0), .resume(pid: 42)) + // The game quits while Steam stays open: the session ends. + XCTAssertEqual(state.observe([steamClient], application: app, now: t0.addingTimeInterval(600)), .ended(pid: 42)) + XCTAssertEqual(state.phase, .idle) + } + + func testDuplicatePlayAndLateAnswersChangeNothing() { + var state = SteamPlayState() + _ = state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0) + XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0), .wait) + state.cancel() + _ = state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0) + state.handoffFinished(accepted: false, generation: 1) // the cancelled request's answer + XCTAssertEqual(state.phase, .starting(since: t0)) + state.handoffFinished(accepted: false, generation: state.generation) + XCTAssertEqual(state.phase, .failed(.handoffRejected)) + } + + func testRefusalsAndTimeoutNeverStartASession() { + var state = SteamPlayState() + XCTAssertEqual(state.requestPlay(target: nil, clientAvailable: true, now: t0), .refuse(.unavailable)) + XCTAssertEqual(state.requestPlay(target: .nxnative(appURL: app.url), clientAvailable: true, now: t0), .refuse(.unavailable)) + XCTAssertEqual(state.requestPlay(target: .steam(appID: 0), clientAvailable: true, now: t0), .refuse(.unavailable)) + XCTAssertEqual(state.requestPlay(target: .steam(appID: 570), clientAvailable: false, now: t0), .refuse(.clientMissing)) + _ = state.requestPlay(target: .steam(appID: 570), clientAvailable: true, now: t0) + XCTAssertNil(state.observe([], application: app, now: t0.addingTimeInterval(SteamPlayState.startDeadline + 1))) + XCTAssertEqual(state.phase, .failed(.notStarted)) + // A game that appears later (an update finished) is still followed. + XCTAssertEqual(state.observe([game], application: app, now: t0.addingTimeInterval(900)), .started(pid: 42)) + } + + func testOnlyThisInstallationsAppMatches() { + let otherCopy = NativeProcessObservation(pid: 3, bundleURL: URL(fileURLWithPath: "/Volumes/Ext/Game.app"), + executableURL: URL(fileURLWithPath: "/Volumes/Ext/Game.app/Contents/MacOS/Game")) + let helper = NativeProcessObservation(pid: 4, bundleURL: app.url, + executableURL: app.url.appendingPathComponent("Contents/MacOS/CrashReporter")) + let withoutExecutable = NativeProcessObservation(pid: 1, bundleURL: app.url, executableURL: nil) + for (process, expected) in [(game, SteamPlayState.Change.started(pid: 42)), + (withoutExecutable, .started(pid: 1)), (steamClient, nil), + (otherCopy, nil), (helper, nil)] { + var state = SteamPlayState() + XCTAssertEqual(state.observe([process], application: app, now: t0), expected) + } + XCTAssertNil(SteamPlayState.launchURL(appID: 0)) + } + + func testAGameAlreadyRunningIsFollowedWithoutAPlay() { + var state = SteamPlayState() + XCTAssertEqual(state.observe([game], application: app, now: t0), .started(pid: 42)) + // The same pid reused by another program is not mistaken for the game. + XCTAssertEqual(state.observe([.init(pid: 42, bundleURL: steamClient.bundleURL, executableURL: steamClient.executableURL)], + application: app, now: t0), .ended(pid: 42)) + XCTAssertNil(state.observe([.init(pid: 42, bundleURL: steamClient.bundleURL, executableURL: steamClient.executableURL)], + application: app, now: t0)) + } + + func testARunningSessionFollowsTheProcessItSawStartNotTheInstallationNow() { + var state = SteamPlayState() + XCTAssertEqual(state.observe([game], application: app, now: t0), .started(pid: 42)) + // The installation disappears from the catalog (a refresh): the game keeps playing. + XCTAssertNil(state.observe([game], application: nil, now: t0.addingTimeInterval(60))) + // The catalog now names the app at a new path: one session, not ended and started again. + let moved = CatalogNativeApplication(NativeMacApplication( + url: URL(fileURLWithPath: "/Volumes/Games/Game.app"), + executableURL: URL(fileURLWithPath: "/Volumes/Games/Game.app/Contents/MacOS/Game"), + bundleIdentifier: "com.example.game", name: "Game", architectures: [.arm64], isDeclaredGame: true, fileObservations: [])) + XCTAssertNil(state.observe([game], application: moved, now: t0.addingTimeInterval(120))) + XCTAssertEqual(state.phase, .running(pid: 42)) + // With no installation to compare, the pid reused by another program still ends it. + XCTAssertEqual(state.observe([steamClient, .init(pid: 42, bundleURL: steamClient.bundleURL, executableURL: nil)], + application: nil, now: t0.addingTimeInterval(180)), .ended(pid: 42)) + } +} + +final class SteamBackgroundLaunchTests: XCTestCase { + func testSilentArgumentsOnlyWhenPlayStartsSteamAndTheSettingIsOn() { + XCTAssertEqual(SteamBackgroundLaunch.arguments(enabled: true, steamRunning: false), ["-silent", "-nofriendsui"]) + XCTAssertEqual(SteamBackgroundLaunch.arguments(enabled: true, steamRunning: true), []) + XCTAssertEqual(SteamBackgroundLaunch.arguments(enabled: false, steamRunning: false), []) + } + + func testSteamMayNeedThePlayerOnlyAfterAStartingGameIsLate() { + let start = Date(timeIntervalSince1970: 1_000) + let waiting = SteamPlayState.Phase.starting(since: start) + let late = start.addingTimeInterval(SteamBackgroundLaunch.attentionDelay + 1) + XCTAssertTrue(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: late)) + XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: start.addingTimeInterval(5))) + XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: .running(pid: 7), now: late)) + XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: .idle, now: late)) + } + + func testAColdSteamGetsMorePatience() { + XCTAssertEqual(SteamBackgroundLaunch.patience(steamWasRunning: true), 15) + XCTAssertEqual(SteamBackgroundLaunch.patience(steamWasRunning: false), 45) + let start = Date(timeIntervalSince1970: 1_000) + let waiting = SteamPlayState.Phase.starting(since: start) + let thirty = start.addingTimeInterval(30) + XCTAssertFalse(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: thirty, patience: 45)) + XCTAssertTrue(SteamBackgroundLaunch.mayNeedPlayer(phase: waiting, now: thirty, patience: 15)) + } + + func testTheLaunchScreenWaitsOnlyForAGameOnItsWay() { + let start = Date(timeIntervalSince1970: 1_000) + let waiting = SteamPlayState.Phase.starting(since: start) + XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: waiting, now: start.addingTimeInterval(10), patience: 15), .waiting) + XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: waiting, now: start.addingTimeInterval(16), patience: 15), .late) + XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: .running(pid: 7), now: start, patience: 15), .gameStarted) + XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: .idle, now: start, patience: 15), .over) + XCTAssertEqual(SteamBackgroundLaunch.launchScreen(phase: .failed(.notStarted), now: start, patience: 15), .over) + } + + func testDownloadsURLOpensSteamDownloads() { + XCTAssertEqual(SteamPlayState.downloadsURL.absoluteString, "steam://open/downloads") + } +} diff --git a/Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift b/Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift new file mode 100644 index 00000000..b18d183c --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift @@ -0,0 +1,126 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamPlaytimeBaselinesTests: XCTestCase { + private var url: URL! + + override func setUp() { + super.setUp() + url = FileManager.default.temporaryDirectory.appendingPathComponent("SteamPlaytime-\(UUID().uuidString).json") + } + + override func tearDown() { + try? FileManager.default.removeItem(at: url) + super.tearDown() + } + + private func date(_ seconds: TimeInterval) -> Date { Date(timeIntervalSince1970: seconds) } + + private func snapshot(account: UInt32 = 1, _ entries: [UInt32: (Int, TimeInterval?)]) -> SteamPlaytimeSnapshot { + SteamPlaytimeSnapshot(accountID: account, entries: entries.mapValues { + SteamPlaytimeEntry(minutes: $0.0, lastPlayed: $0.1.map(date)) + }) + } + + func testFirstSnapshotSetsSeenAtNow() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + XCTAssertTrue(baselines.apply(snapshot([440: (75, 500)]), now: date(1_000))) + XCTAssertEqual(baselines.accountID, 1) + XCTAssertEqual(baselines.byAppID[440], SteamPlaytimeBaseline(appID: 440, minutes: 75, lastPlayed: date(500), seenAt: date(1_000))) + } + + func testSameMinutesKeepsSeenAt() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot([440: (75, 500)]), now: date(1_000)) + XCTAssertFalse(baselines.apply(snapshot([440: (75, 500)]), now: date(2_000))) + XCTAssertTrue(baselines.apply(snapshot([440: (75, 1_500)]), now: date(3_000))) + XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(1_000)) + XCTAssertEqual(baselines.byAppID[440]?.lastPlayed, date(1_500)) + } + + func testNewMinutesResetSeenAt() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot([440: (75, 500)]), now: date(1_000)) + XCTAssertTrue(baselines.apply(snapshot([440: (80, 500)]), now: date(2_000))) + XCTAssertEqual(baselines.byAppID[440]?.minutes, 80) + XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(2_000)) + XCTAssertTrue(baselines.apply(snapshot([440: (10, 500)]), now: date(3_000)), "Steam is the source of truth, even going down") + XCTAssertEqual(baselines.byAppID[440]?.minutes, 10) + XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(3_000)) + } + + func testAnotherAccountStartsOver() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot(account: 1, [440: (75, nil), 10: (5, nil)]), now: date(1_000)) + XCTAssertTrue(baselines.apply(snapshot(account: 2, [440: (75, nil)]), now: date(2_000))) + XCTAssertEqual(baselines.accountID, 2) + XCTAssertEqual(Set(baselines.byAppID.keys), [440]) + XCTAssertEqual(baselines.byAppID[440]?.seenAt, date(2_000)) + } + + func testAppsMissingFromSnapshotAreDropped() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot([440: (75, nil), 10: (5, nil)]), now: date(1_000)) + XCTAssertTrue(baselines.apply(snapshot([440: (75, nil)]), now: date(2_000))) + XCTAssertNil(baselines.byAppID[10]) + } + + func testSaveAndReloadRoundTrip() throws { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot([440: (75, 500)]), now: date(1_000)) + try baselines.save() + XCTAssertEqual(SteamPlaytimeBaselines(fileURL: url), baselines) + } + + func testBrokenFileLoadsEmpty() throws { + try Data("not json".utf8).write(to: url) + let baselines = SteamPlaytimeBaselines(fileURL: url) + XCTAssertNil(baselines.accountID) + XCTAssertTrue(baselines.byAppID.isEmpty) + } + + func testExternalMapsOnlyCatalogSteamGames() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot([440: (75, 500), 10: (5, nil)]), now: date(1_000)) + let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game")) + let switchGame = CatalogGame(nxnative: PortedGame(name: "Switch", url: URL(fileURLWithPath: "/tmp/Switch.app"), + platform: .macApp, sizeBytes: 1, + modificationDate: date(0), bundleId: "org.nxnative.x", titleId: "0100000000010000")) + XCTAssertEqual(baselines.external(for: [steam, switchGame]), + [steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: date(500), since: date(1_000))]) + } + + // Steam keeps whole minutes: when its value rises, up to a minute NX Library already showed is kept. + func testRisingMinutesKeepUpToAMinuteAlreadyShown() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot([440: (75, nil)]), now: date(1_000)) + baselines.apply(snapshot([440: (76, nil)]), now: date(2_000), previousTotals: [440: 75 * 60 + 90]) + XCTAssertEqual(baselines.byAppID[440]?.carry, 30) + let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game")) + XCTAssertEqual(baselines.external(for: [steam])[steam.id]?.duration, 76 * 60 + 30) + + baselines.apply(snapshot([440: (77, nil)]), now: date(3_000), previousTotals: [440: 76 * 60 + 500]) + XCTAssertEqual(baselines.byAppID[440]?.carry, 60, "a bigger gap is Steam's call") + } + + func testCarryStaysWithTheSameMinutesAndResetsOtherwise() { + var baselines = SteamPlaytimeBaselines(fileURL: url) + baselines.apply(snapshot([440: (75, nil)]), now: date(1_000)) + baselines.apply(snapshot([440: (76, nil)]), now: date(2_000), previousTotals: [440: 75 * 60 + 90]) + baselines.apply(snapshot([440: (76, 1_500)]), now: date(2_500), previousTotals: [440: 99_999]) + XCTAssertEqual(baselines.byAppID[440]?.carry, 30) + baselines.apply(snapshot([440: (10, nil)]), now: date(3_000), previousTotals: [440: 76 * 60 + 30]) + XCTAssertEqual(baselines.byAppID[440]?.carry, 0, "a lower value is Steam's reset") + baselines.apply(snapshot([440: (11, nil)]), now: date(4_000), previousTotals: [440: 11 * 60 + 30]) + baselines.apply(snapshot(account: 2, [440: (12, nil)]), now: date(5_000), previousTotals: [440: 12 * 60 + 30]) + XCTAssertEqual(baselines.byAppID[440]?.carry, 0, "another account starts over") + } + + func testFilesWithoutCarryStillLoad() throws { + let json = #"{"accountID":1,"baselines":[{"appID":440,"minutes":75,"seenAt":1000}]}"# + try Data(json.utf8).write(to: url) + let baselines = SteamPlaytimeBaselines(fileURL: url) + XCTAssertEqual(baselines.byAppID[440]?.carry, 0) + XCTAssertEqual(baselines.byAppID[440]?.minutes, 75) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift b/Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift new file mode 100644 index 00000000..82b5b971 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift @@ -0,0 +1,201 @@ +import XCTest +import Darwin +@testable import NXLibraryCore + +final class SteamPlaytimeReaderTests: XCTestCase { + private static let base: UInt64 = 76_561_197_960_265_728 + + private static func localConfig(apps: String, before: String = "") -> String { + """ + "UserLocalConfigStore" + { + \(before) + "apptickets" { "440" "c2VjcmV0" } + "Software" { "Valve" { "Steam" { "apps" { + \(apps) + } } } } + } + """ + } + + private static func loginUsers(_ users: [(id: UInt64, mostRecent: Bool?, timestamp: Int)]) -> String { + let body = users.map { user in + let recent = user.mostRecent.map { "\"MostRecent\" \"\($0 ? 1 : 0)\"" } ?? "" + return "\"\(user.id)\" { \"AccountName\" \"someone\" \(recent) \"timestamp\" \"\(user.timestamp)\" }" + }.joined(separator: "\n") + return "\"users\" {\n\(body)\n}" + } + + func testEntriesReadOnlyPlaytimeAndLastPlayed() throws { + let text = Self.localConfig(apps: """ + "7" { "cloud" { "last_sync_state" "synchronized" } } + "440" { "LastPlayed" "1729257000" "Playtime" "75" "Playtime2wks" "3" } + """) + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text), + [440: SteamPlaytimeEntry(minutes: 75, lastPlayed: Date(timeIntervalSince1970: 1_729_257_000))]) + } + + func testZeroOrMissingLastPlayedIsNone() throws { + let text = Self.localConfig(apps: """ + "10" { "LastPlayed" "0" "Playtime" "5" } + "20" { "Playtime" "6" } + "30" { "LastPlayed" "1729257000" } + """) + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text), + [10: SteamPlaytimeEntry(minutes: 5, lastPlayed: nil), + 20: SteamPlaytimeEntry(minutes: 6, lastPlayed: nil)]) + } + + func testMostRecentUserWins() throws { + let text = Self.loginUsers([(Self.base + 100, false, 900), (Self.base + 200, true, 100)]) + XCTAssertEqual(try SteamPlaytimeReader.accountID(loginUsers: text), 200) + } + + func testLatestTimestampWinsWithoutMostRecent() throws { + let text = Self.loginUsers([(Self.base + 100, nil, 900), (Self.base + 200, nil, 100)]) + XCTAssertEqual(try SteamPlaytimeReader.accountID(loginUsers: text), 100) + } + + func testReadFindsTheAccountsLocalConfig() throws { + let fixture = try SteamTestFixture.temporary(in: self) + try write(Self.loginUsers([(Self.base + 42, true, 1)]), to: "config/loginusers.vdf", in: fixture.root) + try write(Self.localConfig(apps: "\"440\" { \"Playtime\" \"9\" }"), to: "userdata/42/config/localconfig.vdf", in: fixture.root) + XCTAssertEqual(try SteamPlaytimeReader.accountID(root: fixture.root), 42) + let config = SteamPlaytimeReader.localConfigURL(root: fixture.root, account: 42) + XCTAssertEqual(config.path, fixture.root.appendingPathComponent("userdata/42/config/localconfig.vdf").path) + XCTAssertEqual(try SteamPlaytimeReader.read(config: config, account: 42), + SteamPlaytimeSnapshot(accountID: 42, entries: [440: SteamPlaytimeEntry(minutes: 9, lastPlayed: nil)])) + } + + func testNoLoginUsersMeansNoAccount() throws { + let fixture = try SteamTestFixture.temporary(in: self) + XCTAssertNil(try SteamPlaytimeReader.accountID(root: fixture.root)) + } + + func testLargeConfigWithManyEntriesIsRead() throws { + let filler = "\"WebStorage\" {\n" + (0..<30_000).map { "\"k\($0)\" \"v\"" }.joined(separator: "\n") + "\n}" + let text = Self.localConfig(apps: "\"440\" { \"Playtime\" \"1\" }", before: filler) + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text)[440]?.minutes, 1) + } + + func testMalformedConfigThrows() { + XCTAssertThrowsError(try SteamPlaytimeReader.entries(localConfig: "\"UserLocalConfigStore\" { \"Software\" {")) + } + + // A file Steam is rewriting must fail the read, never look like an account with no playtime. + func testEmptyOrRootlessConfigThrows() { + for text in ["", " \n", "\"Other\" { }"] { + XCTAssertThrowsError(try SteamPlaytimeReader.entries(localConfig: text), text) + } + } + + func testAnAccountWithNoAppsHasNoEntries() throws { + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: "\"UserLocalConfigStore\" { }"), [:]) + } + + func testUnreadableLoginUsersFailsInsteadOfMeaningNoAccount() throws { + let fixture = try SteamTestFixture.temporary(in: self) + try write("\"users\" {", to: "config/loginusers.vdf", in: fixture.root) + XCTAssertThrowsError(try SteamPlaytimeReader.accountID(root: fixture.root)) + try write("\"users\" { }", to: "config/loginusers.vdf", in: fixture.root) + XCTAssertNil(try SteamPlaytimeReader.accountID(root: fixture.root)) + } + + func testDuplicatePathKeysUseTheFirst() throws { + let text = """ + "UserLocalConfigStore" { + "Software" { "Valve" { "Steam" { "apps" { "440" { "Playtime" "3" } } } } } + "software" { "Other" "x" } + } + """ + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text)[440]?.minutes, 3) + } + + func testWrongTypedFirstPathDoesNotFallThroughToALaterObject() throws { + let apps = "\"440\" { \"Playtime\" \"9\" }" + let duplicateRoot = "\"UserLocalConfigStore\" \"wrong type\" " + Self.localConfig(apps: apps) + let duplicateSoftware = Self.localConfig(apps: apps, before: "\"software\" \"wrong type\"") + for text in [duplicateRoot, duplicateSoftware] { + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text), [:]) + } + } + + func testDuplicateOrWrongTypedScalarsDoNotReplacePlaytimeOrInventDates() throws { + let text = Self.localConfig(apps: """ + "440" { "Playtime" "3" "PLAYTIME" "9" } + "441" { "Playtime" "7" "LastPlayed" "10" "LASTPLAYED" "20" } + "442" { "Playtime" {} "PLAYTIME" "9" } + "443" { "Playtime" "4" "LastPlayed" {} } + "444" { "Playtime" {} } + """) + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text), + [441: SteamPlaytimeEntry(minutes: 7, lastPlayed: nil), + 443: SteamPlaytimeEntry(minutes: 4, lastPlayed: nil)]) + } + + func testDuplicateMostRecentMarkerDoesNotTakeAnotherAccountsPriority() throws { + let text = """ + "users" { + "\(Self.base + 42)" { "MostRecent" "1" "MOSTRECENT" "1" "timestamp" "900" } + "\(Self.base + 43)" { "MostRecent" "1" "timestamp" "100" } + } + """ + XCTAssertEqual(try SteamPlaytimeReader.accountID(loginUsers: text), 43) + } + + func testHashKeysElsewhereDoNotFailTheRead() throws { + let text = Self.localConfig(apps: "\"440\" { \"Playtime\" \"2\" }", before: "\"WebStorage\" { \"#tag\" \"x\" }") + XCTAssertEqual(try SteamPlaytimeReader.entries(localConfig: text)[440]?.minutes, 2) + } + + func testOversizedConfigThrows() throws { + let fixture = try SteamTestFixture.temporary(in: self) + try write(Self.loginUsers([(Self.base + 42, true, 1)]), to: "config/loginusers.vdf", in: fixture.root) + let filler = String(repeating: " ", count: SteamPlaytimeReader.maximumBytes + 1) + try write(Self.localConfig(apps: "") + filler, to: "userdata/42/config/localconfig.vdf", in: fixture.root) + XCTAssertThrowsError(try SteamPlaytimeReader.read(config: SteamPlaytimeReader.localConfigURL(root: fixture.root, account: 42), account: 42)) + } + + func testConfigSymlinkIsRejected() throws { + let fixture = try SteamTestFixture.temporary(in: self) + try write(Self.localConfig(apps: "\"440\" { \"Playtime\" \"9\" }"), to: "target.vdf", in: fixture.root) + let link = fixture.root.appendingPathComponent("config.vdf") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: fixture.root.appendingPathComponent("target.vdf")) + XCTAssertThrowsError(try SteamPlaytimeReader.read(config: link, account: 42)) + } + + func testLoginUsersSymlinkIsRejected() throws { + let fixture = try SteamTestFixture.temporary(in: self) + try write(Self.loginUsers([(Self.base + 42, true, 1)]), to: "target.vdf", in: fixture.root) + try FileManager.default.createDirectory(at: fixture.root.appendingPathComponent("config"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: fixture.root.appendingPathComponent("config/loginusers.vdf"), + withDestinationURL: fixture.root.appendingPathComponent("target.vdf")) + XCTAssertThrowsError(try SteamPlaytimeReader.accountID(root: fixture.root)) + } + + func testConfigFIFOIsRejectedWithoutWaitingForAWriter() throws { + let fixture = try SteamTestFixture.temporary(in: self) + let fifo = fixture.root.appendingPathComponent("config.vdf") + XCTAssertEqual(mkfifo(fifo.path, 0o600), 0) + let finished = expectation(description: "Playtime rejects a FIFO without blocking") + DispatchQueue.global().async { + do { + _ = try SteamPlaytimeReader.read(config: fifo, account: 42) + XCTFail("A FIFO is not playtime data") + } catch {} + finished.fulfill() + } + let result = XCTWaiter.wait(for: [finished], timeout: 1) + if result != .completed { + let writer = Darwin.open(fifo.path, O_WRONLY | O_NONBLOCK) + if writer >= 0 { Darwin.close(writer) } + } + XCTAssertEqual(result, .completed) + } + + private func write(_ text: String, to relative: String, in root: URL) throws { + let url = root.appendingPathComponent(relative) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: url) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift b/Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift new file mode 100644 index 00000000..e639131e --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift @@ -0,0 +1,192 @@ +import XCTest +@testable import NXLibraryCore + +final class SteamPlaytimeSyncTests: XCTestCase { + private static let base: UInt64 = 76_561_197_960_265_728 + private var url: URL! + private let steam = CatalogGame(steam: SteamCatalogGame(appID: 440, name: "Steam game")) + + override func setUp() { + super.setUp() + url = FileManager.default.temporaryDirectory.appendingPathComponent("SteamPlaytimeSync-\(UUID().uuidString).json") + } + + override func tearDown() { + try? FileManager.default.removeItem(at: url) + super.tearDown() + } + + private func date(_ seconds: TimeInterval) -> Date { Date(timeIntervalSince1970: seconds) } + private func stamp(_ seconds: TimeInterval = 1) -> SteamFileStamp { + SteamFileStamp(file: URL(fileURLWithPath: "/tmp/localconfig.vdf"), modified: date(seconds)) + } + private func snapshot(account: UInt32 = 1, minutes: Int = 75) -> SteamPlaytimeSnapshot { + SteamPlaytimeSnapshot(accountID: account, entries: [440: SteamPlaytimeEntry(minutes: minutes, lastPlayed: nil)]) + } + private func handle(_ sync: inout SteamPlaytimeSync, _ reading: SteamPlaytimeReading, games: [CatalogGame]? = nil, + shown: TimeInterval = 0, now: TimeInterval = 1_000) -> SteamPlaytimeSync.Result { + sync.handle(reading, games: games ?? [steam], shownTotal: { _, _ in shown }, now: date(now)) + } + + // MARK: - Reading Steam's files + + private func write(_ text: String, to relative: String, in root: URL) throws { + let file = root.appendingPathComponent(relative) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + + private func account(_ root: URL, id: UInt64 = 42) throws { + try write("\"users\" { \"\(Self.base + id)\" { \"MostRecent\" \"1\" } }", to: "config/loginusers.vdf", in: root) + } + + func testTakeWithoutAccountOrFileIsNoAccount() throws { + let root = try SteamTestFixture.temporary(in: self).root + XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .noAccount) + try account(root) + XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .noAccount) + } + + func testTakeUnreadableLoginUsersFailsWithoutAnAccount() throws { + let root = try SteamTestFixture.temporary(in: self).root + try write("\"users\" {", to: "config/loginusers.vdf", in: root) + XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .failed(accountID: nil)) + } + + func testTakeMalformedConfigFailsWithItsAccount() throws { + let root = try SteamTestFixture.temporary(in: self).root + try account(root) + try write("", to: "userdata/42/config/localconfig.vdf", in: root) + XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: nil), .failed(accountID: 42)) + } + + func testTakeReadsOnceAndThenIsUnchanged() throws { + let root = try SteamTestFixture.temporary(in: self).root + try account(root) + try write("\"UserLocalConfigStore\" { \"Software\" { \"Valve\" { \"Steam\" { \"apps\" { \"440\" { \"Playtime\" \"9\" } } } } } }", + to: "userdata/42/config/localconfig.vdf", in: root) + guard case .read(let snapshot, let stamp) = SteamPlaytimeReading.take(root: root, known: nil) else { + return XCTFail("expected a reading") + } + XCTAssertEqual(snapshot, SteamPlaytimeSnapshot(accountID: 42, entries: [440: SteamPlaytimeEntry(minutes: 9, lastPlayed: nil)])) + XCTAssertEqual(stamp.file.lastPathComponent, "localconfig.vdf") + XCTAssertEqual(SteamPlaytimeReading.take(root: root, known: stamp), .unchanged(accountID: 42)) + } + + // MARK: - What a reading does + + func testReadPublishesAndSaves() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + XCTAssertEqual(handle(&sync, .read(snapshot(), stamp())), + .publish([steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000))], save: true)) + XCTAssertEqual(sync.stamp, stamp()) + XCTAssertEqual(handle(&sync, .read(snapshot(), stamp(2)), now: 2_000), + .publish([steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000))], save: false)) + } + + func testReadCarriesWhatWasShown() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(minutes: 75), stamp())) + XCTAssertEqual(handle(&sync, .read(snapshot(minutes: 76), stamp(2)), shown: 75 * 60 + 90, now: 2_000), + .publish([steam.id: ExternalPlaytime(duration: 76 * 60 + 30, lastPlayed: nil, since: date(2_000))], save: true)) + } + + func testUnchangedRepublishesForTheCurrentGames() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(), stamp())) + XCTAssertEqual(handle(&sync, .unchanged(accountID: 1), games: []), .publish([:], save: false)) + } + + func testFailedKeepsTheLastGoodTotals() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(), stamp())) + let kept = SteamPlaytimeSync.Result.publish([steam.id: ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000))], save: false) + XCTAssertEqual(handle(&sync, .failed(accountID: 1)), kept) + XCTAssertEqual(handle(&sync, .failed(accountID: nil)), kept) + XCTAssertEqual(sync.stamp, stamp(), "a failure does not move the stamp") + } + + func testFailedForAnotherAccountShowsNothing() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(account: 1), stamp())) + XCTAssertEqual(handle(&sync, .failed(accountID: 2)), .clear) + } + + func testNoAccountClearsAndForgetsTheStamp() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(), stamp())) + XCTAssertEqual(handle(&sync, .noAccount), .clear) + XCTAssertNil(sync.stamp) + } + + func testResetStampMakesTheNextReadingFull() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(), stamp())) + sync.resetStamp() + XCTAssertNil(sync.stamp) + } + + func testFailedWithoutAnAccountStaysClearedAfterAnotherAccountWasSeen() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(account: 1), stamp())) + XCTAssertEqual(handle(&sync, .failed(accountID: 2)), .clear) + XCTAssertEqual(handle(&sync, .failed(accountID: nil)), .clear) + } + + func testCarryIsMeasuredFromTheOldBaseline() { + var sync = SteamPlaytimeSync(baselines: SteamPlaytimeBaselines(fileURL: url)) + _ = handle(&sync, .read(snapshot(minutes: 75), stamp())) + var asked: ExternalPlaytime? + let result = sync.handle(.read(snapshot(minutes: 76), stamp(2)), games: [steam], + shownTotal: { _, old in asked = old; return old.duration + 90 }, now: date(2_000)) + XCTAssertEqual(asked, ExternalPlaytime(duration: 75 * 60, lastPlayed: nil, since: date(1_000))) + XCTAssertEqual(result, .publish([steam.id: ExternalPlaytime(duration: 76 * 60 + 30, lastPlayed: nil, since: date(2_000))], save: true)) + } +} + +final class SteamPlaytimeReadQueueTests: XCTestCase { + func testOneReadAtATime() { + var queue = SteamPlaytimeReadQueue() + let ticket = queue.request() + XCTAssertNotNil(ticket) + XCTAssertNil(queue.request()) + XCTAssertNil(queue.request()) + XCTAssertTrue(queue.isReading) + } + + func testRequestsDuringAReadReadOnceMore() throws { + var queue = SteamPlaytimeReadQueue() + let ticket = try XCTUnwrap(queue.request()) + _ = queue.request(); _ = queue.request() + XCTAssertEqual(queue.finish(ticket).apply, true) + let again = try XCTUnwrap(queue.request(), "the read after finishing starts") + XCTAssertEqual(queue.finish(again).readAgain, false, "one more read served every request") + } + + func testFinishWithoutRequestsStops() throws { + var queue = SteamPlaytimeReadQueue() + let ticket = try XCTUnwrap(queue.request()) + let result = queue.finish(ticket) + XCTAssertTrue(result.apply) + XCTAssertFalse(result.readAgain) + XCTAssertFalse(queue.isReading) + } + + func testAnInvalidatedReadIsNotAppliedAndReadsAgain() throws { + var queue = SteamPlaytimeReadQueue() + let ticket = try XCTUnwrap(queue.request()) + queue.invalidate() + let result = queue.finish(ticket) + XCTAssertFalse(result.apply) + XCTAssertTrue(result.readAgain) + } + + func testStoppingDropsPendingRequests() throws { + var queue = SteamPlaytimeReadQueue() + let ticket = try XCTUnwrap(queue.request()) + _ = queue.request() + queue.stop() + XCTAssertEqual(queue.finish(ticket).apply, false) + XCTAssertFalse(queue.isReading) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift b/Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift new file mode 100644 index 00000000..fa049052 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift @@ -0,0 +1,70 @@ +import XCTest +@testable import NXLibraryCore + +/// Arcane comes back after a Steam game only when Play came from Arcane, the game was the app in front +/// and no other library game is still open. +final class SteamReturnFocusTests: XCTestCase { + private let id = UUID() + + func testPlayedHereInFrontAndAloneComesBack() { + var focus = SteamReturnFocus() + focus.playPressed(id) + focus.gameCameForward(id) + XCTAssertTrue(focus.gameEnded(id, othersRunning: false).returnsToLibrary) + } + + func testStartedFromSteamDoesNotComeBack() { + var focus = SteamReturnFocus() + focus.gameCameForward(id) + XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary) + } + + func testLeavingTheGameForAnotherAppDoesNotComeBack() { + var focus = SteamReturnFocus() + focus.playPressed(id) + focus.gameCameForward(id) + focus.otherAppStayedForward(whileRunning: id) + XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary) + } + + func testAnotherOpenGameKeepsNXLibraryBack() { + var focus = SteamReturnFocus() + focus.playPressed(id) + focus.gameCameForward(id) + XCTAssertFalse(focus.gameEnded(id, othersRunning: true).returnsToLibrary) + } + + func testAnAbandonedPlayDoesNotCountLater() { + var focus = SteamReturnFocus() + focus.playPressed(id) + focus.playAbandoned(id) + focus.gameCameForward(id) + XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary) + } + + func testEachPlayCountsOnce() { + var focus = SteamReturnFocus() + focus.playPressed(id) + focus.gameCameForward(id) + XCTAssertTrue(focus.gameEnded(id, othersRunning: false).returnsToLibrary) + focus.gameCameForward(id) + XCTAssertFalse(focus.gameEnded(id, othersRunning: false).returnsToLibrary, "a later start from Steam is not Arcane's") + } + + // MARK: - Whether the player was still in the game + + func testAGameInFrontAtQuitWasBeingPlayed() { + var focus = SteamReturnFocus() + focus.playPressed(id) + focus.gameCameForward(id) + XCTAssertTrue(focus.gameEnded(id, othersRunning: true).wasInFront, "true even when Arcane stays back") + } + + func testAGameLeftForAnotherAppWasNotInFront() { + var focus = SteamReturnFocus() + focus.playPressed(id) + focus.gameCameForward(id) + focus.otherAppStayedForward(whileRunning: id) + XCTAssertFalse(focus.gameEnded(id, othersRunning: false).wasInFront) + } +} diff --git a/Tests/NXLibraryCoreTests/SteamTestSupport.swift b/Tests/NXLibraryCoreTests/SteamTestSupport.swift new file mode 100644 index 00000000..af7cc1f4 --- /dev/null +++ b/Tests/NXLibraryCoreTests/SteamTestSupport.swift @@ -0,0 +1,84 @@ +import Foundation +import XCTest + +/// Generated metadata/header bytes only; these fixtures are not game executables. +struct SteamTestFixture: Sendable { + let root: URL + + static func temporary(in test: XCTestCase) throws -> Self { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("SteamSourceTests-" + UUID().uuidString) + .resolvingSymlinksInPath().standardizedFileURL + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + test.addTeardownBlock { try FileManager.default.removeItem(at: root) } + return Self(root: root) + } + + @discardableResult + func app(at relative: String = "Game.app", category: String? = "public.app-category.games", + cpuTypes: [UInt32] = [0x0100000c], metadata: [String: Any] = [:]) throws -> URL { + let app = root.appendingPathComponent(relative) + try FileManager.default.createDirectory(at: app.appendingPathComponent("Contents/MacOS"), withIntermediateDirectories: true) + var info: [String: Any] = ["CFBundlePackageType": "APPL", "CFBundleIdentifier": "test.game", + "CFBundleDisplayName": "Fixture game", "CFBundleExecutable": "fixture"] + info["LSApplicationCategoryType"] = category + info.merge(metadata) { _, new in new } + try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) + .write(to: app.appendingPathComponent("Contents/Info.plist")) + let executable = app.appendingPathComponent("Contents/MacOS/fixture") + let data = cpuTypes.count == 1 ? Self.machHeader(cpu: cpuTypes[0]) : Self.fatHeader(cpus: cpuTypes) + try data.write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + return app + } + + static func words(_ values: [UInt32], bigEndian: Bool = false) -> Data { + Data(values.flatMap { word in + let shifts = bigEndian ? [24, 16, 8, 0] : [0, 8, 16, 24] + return shifts.map { UInt8(truncatingIfNeeded: word >> $0) } + }) + } + + static func machHeader(cpu: UInt32, fileType: UInt32 = 2) -> Data { + words([0xfeedfacf, cpu, 0, fileType, 0, 0, 0, 0]) + } + + func library(_ relative: String = "Steam") throws -> URL { + let library = root.appendingPathComponent(relative) + try FileManager.default.createDirectory(at: library.appendingPathComponent("steamapps/common"), withIntermediateDirectories: true) + return library + } + + @discardableResult + func manifest(in library: URL, id: String = "10", name: String = "First game", directory: String = "First", + filenameID: String? = nil, size: String = "100", stateFlags: String? = "4", extra: String = "") throws -> URL { + let file = library.appendingPathComponent("steamapps/appmanifest_\(filenameID ?? id).acf") + let flags = stateFlags.map { "\"StateFlags\" \(Self.quote($0))" } ?? "" + let text = "\"AppState\" { \"appid\" \(Self.quote(id)) \"name\" \(Self.quote(name)) \"installdir\" \(Self.quote(directory)) \"SizeOnDisk\" \(Self.quote(size)) \"buildid\" \"42\" \(flags) \(extra) }" + try Data(text.utf8).write(to: file) + return file + } + + static func quote(_ text: String) -> String { + "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" + } + + func inventory() throws -> [String: Data] { + let files = try XCTUnwrap(FileManager.default.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey])) + var result: [String: Data] = [:] + for case let file as URL in files { + if (try file.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true { + result[String(file.path.dropFirst(root.path.count))] = try Data(contentsOf: file) + } + } + return result + } + + static func fatHeader(cpus: [UInt32]) -> Data { + var data = words([0xcafebabe, UInt32(cpus.count)], bigEndian: true) + for (i, cpu) in cpus.enumerated() { + data.append(words([cpu, 0, UInt32(8 + cpus.count * 20 + i * 32), 32, 0], bigEndian: true)) + } + for cpu in cpus { data.append(machHeader(cpu: cpu)) } + return data + } +} diff --git a/Tests/NXLibraryCoreTests/TileMotionTests.swift b/Tests/NXLibraryCoreTests/TileMotionTests.swift index 14edff72..f7b7affa 100644 --- a/Tests/NXLibraryCoreTests/TileMotionTests.swift +++ b/Tests/NXLibraryCoreTests/TileMotionTests.swift @@ -74,4 +74,16 @@ final class TileMotionTests: XCTestCase { XCTAssertEqual(TileMotion.phase(period: 5, at: 812.5), 2.5, accuracy: 1e-9) XCTAssertEqual(TileMotion.phase(period: 3.6, at: 7.2), 0, accuracy: 1e-9) } + + func testDownloadMarkPulsesSlowlyBetweenDimAndFull() { + XCTAssertEqual(TileMotion.downloadPeriod, 2.8) + XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 0), 0.4, accuracy: 1e-9) + XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 1.4), 1, accuracy: 1e-9) + XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 2.8), 0.4, accuracy: 1e-9) + XCTAssertEqual(TileMotion.downloadMarkOpacity(at: 0.7), 0.7, accuracy: 1e-9) + let loop = TileMotion.loop(period: TileMotion.downloadPeriod, steps: 84) { TileMotion.downloadMarkOpacity(at: $0) } + let largest = zip(loop.values, loop.values.dropFirst()).map { abs($1 - $0) }.max()! + XCTAssertLessThan(largest, 0.05) + XCTAssertEqual(loop.values.first!, loop.values.last!, accuracy: 1e-3) + } } diff --git a/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift b/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift index c1038d88..4afca443 100644 --- a/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift +++ b/Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift @@ -30,7 +30,7 @@ final class ToolchainGateCopyTests: XCTestCase { XCTAssertEqual(off.label, "Newer Metal") XCTAssertEqual(off.tone, .info) XCTAssertEqual(off.message, "Your Metal compiler (32023.922) is newer than the one nxnative is tested with (32023.921). There should be no problems: turn on Untested toolchain override to build.") - XCTAssertEqual(off.buildHint, "Newer Metal: turn on the override in Settings → Engine") + XCTAssertEqual(off.buildHint, "Newer Metal: turn on the override in Settings → Setup and engine") let on = ToolchainGateCopy.summary(report: report(metal: newer), overrideOn: true) XCTAssertEqual(on.label, "Newer Metal · override on") XCTAssertEqual(on.tone, .info) @@ -42,7 +42,7 @@ final class ToolchainGateCopyTests: XCTestCase { XCTAssertEqual(off.label, "Update recommended") XCTAssertEqual(off.tone, .warning) XCTAssertEqual(off.message, "Your Metal compiler (32023.917) is older than the one nxnative needs (32023.921). Updating to Metal 32023.921 is strongly recommended. Untested toolchain override builds anyway, at your own risk.") - XCTAssertEqual(off.buildHint, "Older Metal: update it, or use the override in Settings → Engine") + XCTAssertEqual(off.buildHint, "Older Metal: update it, or use the override in Settings → Setup and engine") let on = ToolchainGateCopy.summary(report: report(metal: older), overrideOn: true) XCTAssertEqual(on.label, "Older Metal · override on") XCTAssertEqual(on.tone, .warning) @@ -52,7 +52,7 @@ final class ToolchainGateCopyTests: XCTestCase { let s = ToolchainGateCopy.summary(report: report(metal: newer, otherBlock: true), overrideOn: false) XCTAssertEqual(s.label, "Blocked") XCTAssertEqual(s.tone, .blocked) - XCTAssertEqual(s.buildHint, "Build blocked — Settings → Engine") + XCTAssertEqual(s.buildHint, "Build blocked — Settings → Setup and engine") let on = ToolchainGateCopy.summary(report: report(metal: .same, otherBlock: true), overrideOn: true) XCTAssertEqual(on.label, "Override enabled") XCTAssertEqual(on.tone, .override) diff --git a/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift b/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift index ee7c3cf3..cefadedc 100644 --- a/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift +++ b/Tests/NXLibraryCoreTests/UpstreamCopyTests.swift @@ -3,10 +3,10 @@ import XCTest final class UpstreamCopyTests: XCTestCase { func testNewCommitsArriveWithUpdates() { - XCTAssertEqual(UpstreamCopy.subtitle(upToDate: true, newCommits: 0), "This NX Library uses the newest nxnative.") + XCTAssertEqual(UpstreamCopy.subtitle(upToDate: true, newCommits: 0), "This version of Arcane uses the newest nxnative.") XCTAssertEqual(UpstreamCopy.subtitle(upToDate: false, newCommits: 1), - "nxnative has 1 newer commit. Engine updates reach you with NX Library updates, once tested.") + "nxnative has 1 newer commit. Engine updates reach you with Arcane updates, once tested.") XCTAssertEqual(UpstreamCopy.subtitle(upToDate: false, newCommits: 12), - "nxnative has 12 newer commits. Engine updates reach you with NX Library updates, once tested.") + "nxnative has 12 newer commits. Engine updates reach you with Arcane updates, once tested.") } } diff --git a/Tests/PublicationChecks/test_profile_boundaries.py b/Tests/PublicationChecks/test_profile_boundaries.py new file mode 100644 index 00000000..4cb6c1d6 --- /dev/null +++ b/Tests/PublicationChecks/test_profile_boundaries.py @@ -0,0 +1,19 @@ +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class ProfileBoundaries(unittest.TestCase): + def test_launcher_storage_and_default_preferences_are_centralized(self): + unexpected = [] + for file in (ROOT / 'Sources').rglob('*.swift'): + if file.name == 'AppDataProfile.swift': + continue + source = file.read_text() + if 'UserDefaults.standard' in source or re.search(r'UserDefaults\s*=\s*\.standard', source): + unexpected.append(str(file.relative_to(ROOT)) + ': unscoped preferences') + if re.search(r'\.appendingPathComponent\("Library/Application Support/NXLibrary(?:/|"|\-)', source): + unexpected.append(str(file.relative_to(ROOT)) + ': unscoped launcher directory') + self.assertEqual(unexpected, [], '\n'.join(unexpected)) diff --git a/VERSION b/VERSION index b6586755..0ea3a944 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.1.4.3 +0.2.0 diff --git a/docs/architecture.md b/docs/architecture.md index 3b873fce..8c828f3d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,26 +1,41 @@ -# NX Library — guida tecnica +# Arcane — guida tecnica -Aggiornamento 12 novembre 2026 per NX Library 0.1.4.3. Il pin è `8a5c5e7e`, con Metal 32023.922 / Xcode 27.2: adozione esplicitamente richiesta dal maintainer dopo la revisione di 152 commit. I tool dell'engine sono nativi (niente .NET); NX Library ferma i build dando all'engine il tempo di chiudere i tool nelle loro sessioni e rifiuta import/ripristino dei salvataggi mentre un download cloud dell'engine è incompleto. Build e avvio reali sull'esatto hash restano da confermare dal maintainer. Vedi la [revisione engine](upstream-upgrades/2026-11-12-79741184-8a5c5e7e-review.md). +Questa guida descrive **come funziona l'app oggi**, area per area. Non contiene storia né stati di validazione: lo storico è nel [CHANGELOG](../CHANGELOG.md) e nelle note datate, cosa ha provato il maintainer è in [validation.md](validation.md). -Questa guida descrive il funzionamento attuale. Il [catalogo dei file](file-map.md) assegna una responsabilità a ogni file versionato, suddiviso per area. +Ordine di lettura per chi lavora sul codice: +1. [AGENTS.md](../AGENTS.md): le regole. +2. Questa guida: la mappa. +3. [conventions.md](conventions.md): come si costruisce una cosa nuova. +4. [flows.md](flows.md): i percorsi completi. +5. Il documento dell'area, se c'è (per esempio [steam.md](steam.md)). +6. [file-map.md](file-map.md): un file per riga. -Il [README](../README.md) è la guida d'uso; la [guida di sviluppo](development.md) raccoglie build, runtime, CI e release. Il [changelog](../CHANGELOG.md) distingue il lavoro non pubblicato dalle versioni distribuite. Il runtime e i contenuti versionati vengono verificati da `scripts/check_publication.py`; `build_app.sh` installa il bundle completo attraverso `BuildOutputInstaller`, dopo firma e verifica. +Il [README](../README.md) è la guida d'uso; la [guida di sviluppo](development.md) raccoglie build, runtime, CI e release. + +**Engine attuale:** pin `461a5f9f95fc9fc40a690bb2a82eb23f1f03bdca`, definito in `AppViewModel.pinnedEngineCommit`. Il suo lock certifica Metal `32023.922`, asset Apple `27B47`, con Xcode minimo `27.2`. Le revisioni di ogni pin sono in [upstream-upgrades](upstream-upgrades/README.md). ## Indice - [Struttura e dipendenze](#struttura-e-dipendenze) -- [Avvio e stato dell’app](#avvio-e-stato-dellapp) -- [Libreria e navigazione](#libreria-e-navigazione) -- [Setup e compatibilità](#setup-e-compatibilità) +- [Avvio e stato dell'app](#avvio-e-stato-dellapp) +- [Catalogo, fonti e libreria](#catalogo-fonti-e-libreria) +- [Navigazione e focus](#navigazione-e-focus) +- [Impostazioni](#impostazioni) +- [Lingua e regione](#lingua-e-regione) +- [Setup, engine e compatibilità](#setup-engine-e-compatibilità) - [Sorgenti e porting](#sorgenti-e-porting) - [Avvio dei giochi e sessioni](#avvio-dei-giochi-e-sessioni) -- [Cheats](#cheats) +- [Pagina del gioco](#pagina-del-gioco) +- [Cheat](#cheat) +- [Mod](#mod) - [Salvataggi, backup e recupero](#salvataggi-backup-e-recupero) -- [Artwork, metadati e sfondi](#artwork-metadati-e-sfondi) +- [Spazio su disco](#spazio-su-disco) +- [Artwork, metadati e voti](#artwork-metadati-e-voti) - [Interfaccia Selene e input](#interfaccia-selene-e-input) - [Dati su disco](#dati-su-disco) - [Aggiornamenti e distribuzione](#aggiornamenti-e-distribuzione) - [Verifica e manutenzione](#verifica-e-manutenzione) +- [Steam](steam.md): documento a parte ## Struttura e dipendenze @@ -32,7 +47,7 @@ Il [README](../README.md) è la guida d'uso; la [guida di sviluppo](development. | `NXLibraryCore` | Modelli, persistenza, parsing, gestione file, contratti del motore, processi e logica delle funzionalità. | | `NXLibraryCoreTests` | Test XCTest del Core, con dati sintetici e dipendenze sostituibili. | -`NXLibrary` dipende da `NXLibraryCore`. Il Core usa anche framework macOS, fra cui Combine, AppKit, ImageIO, CommonCrypto e IOKit. Il package attuale usa i framework del sistema e non dichiara dipendenze SwiftPM esterne. +`NXLibrary` dipende da `NXLibraryCore`. Il Core usa anche framework macOS, fra cui Combine, AppKit, ImageIO, CommonCrypto e IOKit. Il package non dichiara dipendenze SwiftPM esterne. ```mermaid flowchart TD @@ -47,274 +62,707 @@ flowchart TD Core --> Network["Cataloghi artwork, metadati e release"] ``` -Il checkout nxnative fornisce estrattore, rewriter, shader, profili dei giochi e runtime dei giochi compilati. NX Library prepara gli argomenti, controlla i requisiti e presenta lo stato delle operazioni. Il pin attuale è `4a0551e4b9abc75ea736006e4dbd30fcac0d03a4`, definito in `AppViewModel.pinnedEngineCommit`. La cache dello stato upstream viene riutilizzata soltanto quando il suo commit di base coincide con il pin. - -## Avvio e stato dell’app - -`NXLibraryApp.swift` registra una sola `Window` e i comandi della barra menu. File → Add Game sostituisce New Window: controller, updater e catalogo condiviso non offrono un flusso multi-finestra. `AppDelegate.swift` registra il font Material Icons e gestisce chiusura e riapertura della finestra. `MainView.swift` presenta `AppShellView`. - -`AppShellView.swift` possiede gli oggetti condivisi tramite `@StateObject`. Comprendono `AppViewModel`, router, impostazioni, sessioni di gioco, artwork, monitor dei giochi e updater. Imposta palette, canvas Selene, preferenze di accessibilità e livelli sovrapposti. Intro, Setup, menu, ricerca, opzioni di un gioco e conferme ricevono una priorità esplicita nell’input. - -`NativeMenuCommands` osserva il tracking dei menu AppKit e rinvia le azioni al turno successivo della coda principale, conservando la sospensione dell’input durante il passaggio. La shell pubblica le disponibilità nella scena attiva tramite `FocusedValues`: intro, Setup, pannelli e assenza di selezione disabilitano i comandi non applicabili. Mouse, monitor tastiera e dispatch controller non cambiano selezione sotto un menu nativo. In Spotlight, Game Details usa `SpotlightState.showGameDetails` come il comando interno e conserva il titolo selezionato; in Collection apre la pagina Details. Game Options blocca l’hit testing del contenuto sottostante. - -`startInFullscreen` viene salvato in AppSettings, ha default false per i vecchi file, compare in Search/Changed e viene ripristinato dal reset Start-up. `StartupWindowView` legge il valore alla creazione e applica una sola volta la modalità alla finestra visibile e attiva. Cambiare la preferenza non altera la finestra corrente. - - -`AppViewModel.swift` coordina libreria, rilevamento dell’ambiente, selezione delle sorgenti, porting e lancio. Le estensioni `AppViewModel+…` contengono le integrazioni di cheats, salvataggi, diagnostica, controlli delle chiavi, toolchain e installazioni in attesa. Sono parti dello stesso oggetto osservabile. - -La shell condivide un solo `AppSettingsStore` con router e coordinatore. L’avvio rispetta i flag di verifica del motore e scansione della libreria; senza scansione carica il catalogo salvato. Il primo Setup accompagna l'utente in Get ready e Your games, dove Skip for now completa l'introduzione anche con libreria vuota. La verifica prima di ogni porting resta obbligatoria. I pannelli di build possono avviarla su richiesta. I risultati asincroni relativi a un checkout precedente vengono scartati e il porting registra la propria fotografia della toolchain. - -`FirstRunSetup` tiene insieme pagina corrente e completamento: `NXLibrary_SetupPage` permette di riprendere una prima configurazione interrotta, mentre `NXLibrary_SetupCompleted` mantiene compatibili gli utenti già configurati e impedisce ripetizioni automatiche dopo Skip. Open Setup riapre manualmente entrambi i passaggi senza rendere incompleta una configurazione precedente. `YourGamesSetupView` aspetta la scansione prima di distinguere libreria vuota o pronta; Open library e Skip tornano alla libreria. I due passaggi condividono backdrop, indicatore, transizioni e canale di input; Add Game sospende il proprio input quando Setup è davanti. - -`SetupCheckModel` e `SavePanelModel` possiedono lo stato dei rispettivi pannelli. `SavePanelModel`, per esempio, mantiene anteprima, operazione in corso, errore, ultimo backup ed evento di importazione riuscita. Gli aggiornamenti destinati alla UI vengono pubblicati sulla coda principale. - -## Libreria e navigazione - -`PortedGame` rappresenta un titolo della libreria. Include identità, app installata, sorgenti, impostazioni runtime, ultimo porting, toolchain e installazione eventualmente differita. `LibraryFile` è il contenitore persistito in `library.json`. - -`GameResourceState` riconcilia app, sorgenti e stato: conserva build in corso e workspace non ancora compilati, distingue app mancante e file di origine mancanti e mantiene Play per una build esistente. Le viste usano `PortingPills.unavailable` per il motivo breve e l'azione primaria disabilitata; `PortingTileLook.locked` riusa sfocatura e lucchetto. La voce rimane in libreria. Non viene aggiunta alcuna ricerca dell'app spostata; Refresh controlla le cartelle già configurate. Un cambio cartella durante la scansione scarta il contesto precedente e avvia quella nuova. - -`ImportService` scansiona i bundle `.app`, legge `Info.plist`, riconosce gli identificativi nxnative e produce le voci importabili. La candidata UX aggiunge una visita breadth-first nelle sole cartelle scelte, fino a sei livelli e 4000 directory, con deduplicazione dei percorsi canonici. Non entra in bundle/package e non segue i symlink delle sottocartelle. Limiti e letture fallite producono avvisi con motivo e azione utile: sono visibili accanto a Scan game apps nelle impostazioni e, nel primo Setup, sotto Game apps. Non aprono dialoghi automatici né un ciclo Retry all’avvio e non cancellano il catalogo. Una scansione successiva aggiorna o rimuove gli avvisi. `appsForLibrary` seleziona una sola osservazione per titolo: il percorso già registrato se esiste, altrimenti la prima osservazione del risultato ordinato dalla più recente. Se un'app esiste fuori dall'area scandita, la sua voce resta invariata. Merge e metadati usano la stessa selezione. - -`AppSizeCache` ricorda le dimensioni in funzione di percorso e data di modifica. `LibraryStore` carica e salva il catalogo, conserva `library.json.bak` e offre il merge delle voci. Il coordinamento applicativo riconcilia app trovate, dati già salvati e sorgenti disponibili. - -La candidata UX integra `FullscreenCursorView` nella shell. Un NSView osserva la propria finestra, il mouse e le transizioni native; `CursorIdleState` decide la visibilità usando il tempo monotono. In fullscreen attivo, con mouse nel contenuto, il puntatore si nasconde dopo tre secondi senza movimento. Cambi di schermata, menu interni, ricerca, opzioni, tastiera/controller, click e scroll non lo rendono visibile. La posizione reale viene campionata anche dal timer: i loop nativi di menu e controlli possono consumare gli eventi prima del monitor locale. Durante un menu nativo si sospende il nuovo nascondimento, senza svelare un puntatore già nascosto; alla chiusura viene riallineato lo stato AppKit. Un movimento riavvia il ritardo. Pannelli di sistema, perdita di focus e uscita fullscreen ripristinano la visibilità. Il distacco rimuove monitor, timer e osservatori e ripristina il precedente `acceptsMouseMovedEvents`. **Il maintainer ha confermato la revisione 2 di scansione e cursore e, nella candidata finale 0.1.2, menu nativi, dialogo aggiornamenti, avvio fullscreen, riga di scansione e gate certificato.** - -Il merge parte dalla voce persistita e aggiorna esplicitamente i dati osservati dalla scansione. Conserva impostazioni, identità, preferiti, installazione in attesa ed errore dell’ultimo porting. Restano le regole precedenti per associare le sorgenti e conservare la provenienza di una build installata. - -Settings → Library usa un'unica riga **Scan game apps**, con la stessa azione per scoperta e refresh. La riga e l'azione controller sono disabilitate durante la scansione. Il catalogo Search usa lo stesso nome; Collection conserva il proprio ingresso per importare build esistenti. - -L’aggiunta o il collegamento esplicito delle sorgenti usa `merge(replacingSources: true)`: la selezione confermata sostituisce sorgenti, workspace e percorso della cache, anche se i file precedenti esistono ancora. I file originali restano sul disco. Le scansioni automatiche continuano a conservare la selezione già registrata e il bundle installato. - -### Ambito delle impostazioni - -| Punto dell’interfaccia | Autorità | +Il checkout nxnative fornisce estrattore, rewriter, shader, profili dei giochi e runtime dei giochi compilati. Arcane prepara gli argomenti, controlla i requisiti e presenta lo stato delle operazioni. La cache dello stato upstream si riusa soltanto quando il suo commit di base coincide con il pin. + +## Avvio e stato dell'app + +**Finestra e menu.** +- `NXLibraryApp.swift` registra una sola `Window` e i comandi della barra menu. File → Add Game sostituisce New Window: controller, updater e catalogo condiviso non offrono un flusso a più finestre. +- `AppDelegate.swift` registra il font Material Icons e gestisce chiusura e riapertura della finestra. `MainView.swift` presenta `AppShellView`. +- `NativeMenuCommands` osserva il tracking dei menu AppKit e rinvia le azioni al turno successivo della coda principale, mantenendo l'input sospeso durante il passaggio. +- La shell pubblica le disponibilità nella scena attiva tramite `FocusedValues`: benvenuto, Setup, pannelli e assenza di selezione disabilitano i comandi che non si applicano. Mouse, tastiera e controller non cambiano selezione sotto un menu nativo. +- In Spotlight, Game Details usa `SpotlightState.showGameDetails` come il comando interno e conserva il titolo selezionato; in Collection apre la pagina Details. Game Options blocca l'hit testing del contenuto sottostante. + +**Profilo dei dati.** +- `AppDataProfile` e `AppData` centralizzano percorsi e preferenze. Il marker di build `NXLibraryDevelopmentProfile` e il bundle ID `local.nxlibrary.development` distinguono la Dev dalla release; la release usa i percorsi di sempre. +- `DevelopmentStartupView` prepara il profilo in background prima di costruire gli store e la shell, senza schermata di preparazione. `LaunchReveal` tiene trasparente la finestra fino al primo frame del moonlight (il drawable presentato, su entrambi i percorsi di rendering), con ripiego dopo 1 s, poi la mostra con una dissolvenza di 0,25 s. Un errore mostra il recupero senza aspettare il moonlight. *Perché:* la transizione fullscreen parte da una finestra già disegnata. `DevelopmentProfileImporter` legge la sorgente senza attivare gli store che la potrebbero riparare, copia in staging una lista dichiarata di dati, verifica gli hash e attiva la destinazione separata. +- Le preferenze storiche appartengono a una lista esplicita; file di credenziali e nuovi token non si copiano per semplice prefisso. Le sessioni rimaste aperte nella copia terminano all'ultimo heartbeat registrato. Ripetere l'avvio non reimporta e non sovrascrive la Dev. La copia fallisce con Retry/Close, senza ripiegare sul profilo stabile. +- Nella Dev il recupero dei salvataggi e la riconciliazione automatica delle icone non partono all'avvio. `DevelopmentOperationStore`, escluso dall'import, registra le richieste esplicite di build e icone e ne permette la ripresa dopo un riavvio. La pulizia automatica visita solo la Temp del profilo Dev, non lo staging sui volumi condivisi. Il factory dei `ModStore` disabilita la manutenzione automatica: consultare e aggiornare le schede non scrive l'overlay né elimina installazioni residue, e la lettura usa lo stato reale dell'overlay. Le azioni manuali agiscono sui giochi reali. +- `release.sh` rifiuta un marker Dev nel pacchetto, e `AppUpdate` rifiuta un pacchetto del genere come aggiornamento. + +**Shell.** +- `AppShellState` prepara coordinatore, router, lingua e tema sul main actor prima di pubblicare la shell pronta. L'inserimento nella finestra già visibile conserva gli oggetti preparati. Il bootstrap prepara catalogo e profilo prima della shell, quindi il modello usa quel documento senza una seconda lettura fallibile durante l'inizializzazione. +- `AppShellView.swift` possiede gli oggetti condivisi tramite `@StateObject`: `AppViewModel`, router, impostazioni, sessioni, artwork, monitor dei giochi e updater. Imposta palette, canvas Selene, preferenze di accessibilità e livelli sovrapposti. Benvenuto, Setup, menu, ricerca, opzioni di un gioco e conferme ricevono una priorità esplicita nell’input. +- La shell condivide un solo `AppSettingsStore` con router e coordinatore. L'avvio rispetta i flag di verifica del motore e di scansione della libreria; senza scansione carica il catalogo salvato. +- `startInFullscreen` sta in `AppSettings` (default false), compare in Search e Changed e torna al default con il reset di Start-up. `StartupWindowView` lo legge alla creazione e lo applica una sola volta alla finestra visibile e attiva, dopo `LaunchReveal.whenShown`. `isWindowSettling` tiene ferma l’entrata fino alla notifica di fine transizione, con ripiego a 4 s dall’aggancio alla finestra. Cambiare la preferenza non altera la finestra corrente. + +**Coordinatore.** +- `AppViewModel.swift` coordina libreria, rilevamento dell'ambiente, selezione delle sorgenti, porting e lancio. Le estensioni `AppViewModel+…` collegano cheat, salvataggi, diagnostica, chiavi, toolchain, installazioni in attesa e fonti; sono parti dello stesso oggetto osservabile. +- Gli stati di un solo pannello hanno il loro modello: `SetupCheckModel`, `SavePanelModel` (anteprima, operazione in corso, errore, ultimo backup, importazione riuscita) e gli altri elencati in [conventions.md](conventions.md#1-dove-va-il-codice). Gli aggiornamenti destinati alla UI si pubblicano sulla coda principale. + +**Primo avvio.** +- Il primo avvio apre su `found`: cosa c'è già sul Mac, letto senza cambiare nulla. + `FirstRunFindings` conta i giochi Steam per Mac installati (`.nativeReady`) e le app portate nella + cartella Game apps; `FirstRunFindingsReader` legge in un worker annullabile. Open library è utilizzabile anche durante la lettura: annulla la richiesta prima di completare il Setup, senza inventare risultati o attivare fonti non scelte. Le fonti restano aggiungibili dalle Impostazioni; un risultato tardivo è scartato dal requestID. +- La scoperta usa `CatalogSourcesModel.discoveryRoot`: cartella scelta nella fonte, anche spenta, + altrimenti quella standard. Una lettura incompleta o fallita mostra Retry senza interruttore; + non equivale a nessun gioco trovato. Retry ripete la lettura senza attivare la fonte. +- La riga Steam pronta ha un interruttore acceso; le app portate sono una riga informativa; + Porting apre i requisiti. `FirstRunSetup.steamChoice` si salva in `NXLibrary_SetupSteamChoice` + finché il Setup è incompleto, così resta anche dopo una chiusura durante Porting. + Quando il primo avvio finisce da Open library, Your games o Skip, la shell applica la scelta + con `CatalogSourcesModel.configure`. Open library completa il Setup; la fonte Switch si + accende solo se c'erano app portate, che entrano subito nella libreria. +- Dalla card Porting il Setup prosegue in Get ready e Your games; B su Get ready torna a `found` durante il primo avvio. Skip for now completa l'introduzione anche con libreria vuota. La verifica prima di ogni porting resta obbligatoria, e i pannelli di build possono avviarla su richiesta. I risultati asincroni di un checkout precedente si scartano, e il porting registra la propria fotografia della toolchain. +- `FirstRunSetup` tiene insieme pagina corrente e completamento. `NXLibrary_SetupPage` permette di riprendere una configurazione interrotta; `NXLibrary_SetupSteamChoice` conserva la scelta facoltativa (acceso, spento o mai scelta) e si elimina al completamento, dopo averla mantenuta nel modello per la shell; `NXLibrary_SetupCompleted` mantiene compatibili gli utenti già configurati e impedisce ripetizioni automatiche dopo Skip. Una configurazione completata non torna mai a `found`; Open Setup riapre manualmente Get ready e Your games senza rendere incompleta una configurazione precedente. +- `YourGamesSetupView` aspetta la scansione prima di distinguere libreria vuota o pronta; Open library e Skip tornano alla libreria. `FoundGamesSetupView` e Your games disegnano le righe con `SetupCardRow`. Le pagine condividono backdrop, indicatore, transizioni e canale di input; Add Game sospende il proprio input quando Setup è davanti. +- **Benvenuto in Arcane.** Chi aggiorna da NX Library vede una volta `ArcaneWelcomeView`: il nome nuovo, quattro novità, l'offerta di Steam se è trovato con giochi e la sua fonte è spenta (la ricerca e l’attivazione usano la stessa `discoveryRoot`; Add accende la fonte con `CatalogSourcesModel.configure`, Not now non accende nulla) e Open library. `ArcaneWelcome` decide: Setup completato, `AppSettings.welcomeArcaneShown` falso e nessun recupero in corso. +- `AppShellState` decide il benvenuto prima di pubblicare la shell, così la libreria non compare in mezzo. Benvenuto e pagine Setup chiedono lo sfondo alla shell come ogni pagina (`SeleneBackdropRequest`): il moonlight è uno solo, quindi chiuderli lascia lo stesso sfondo in movimento. I recuperi si aprono sopra; se il benvenuto non era dovuto all’avvio, la shell lo presenta più tardi solo quando Setup, dialoghi, lancio e visore sono chiusi e nessuna operazione sui salvataggi è in corso (`hasActiveSaveOperations`). Il Setup ha precedenza nel disegno e nell’input. +- Fino alla fine della dissolvenza del benvenuto, `AppViewModel.isWelcomeOpen` fa cedere la tastiera ai monitor delle schermate sotto e trattiene l’entrata di Spotlight, come `isUpdateOfferOpen` per l’offerta di aggiornamento; `ShellOverlayInputTests` controlla che ogni monitor ceda a entrambi. Ogni uscita (Open library, B, Esc) prima sfuma, poi salva e passa alla libreria (`SeleneTheme.screenDuration` dopo). Le uscite e la fine di un primo Setup impostano `welcomeArcaneShown`, così un’installazione nuova non lo vede mai. Non tocca `RunningGameMonitor` né `SteamPlayCoordinator`: un gioco aperto resta giocabile. + +## Catalogo, fonti e libreria + +**Il catalogo comune.** +- `CatalogGame` conserva un payload tipizzato: il `PortedGame` completo per nxnative oppure `SteamCatalogGame`. Nome, UUID e scelte personali hanno un solo proprietario; il riferimento alle personalizzazioni conserva chiave e namespace dell'integrazione. Non si costruisce mai un falso gioco nxnative per Steam. +- `CatalogGamePresentation` espone installazioni, operazioni supportate e un target di avvio tipizzato, senza avviare servizi o consultare il disco. La disponibilità dell'avvio resta distinta dal supporto dell'operazione, e una fonte disattivata non produce un target utilizzabile. +- `CatalogDocument` (versione 1) contiene revisioni, fonti abilitate e fingerprint della base legacy riconosciuta alla conversione o dopo una scelta esplicita di conservare il catalogo. +- `CatalogStore` legge input regolari fino a 16 MiB. Converte direttamente i byte di `library.json` (formato precedente, descritto da `LibraryFile`), mantiene UUID, payload e chiavi e lascia `library.json` intatto. + - Le scritture concorrenti usano un lock non bloccante e la revisione attesa. Il candidato si serializza, si rilegge e si valida prima della pubblicazione atomica; una copia valida precede la sostituzione del principale. + - Archivio danneggiato, versione sconosciuta, input legacy cambiato e principale assente con backup richiedono un recupero esplicito, mai una libreria vuota automatica. L'offerta di ripristino conserva gli hash di principale e backup: se i file cambiano, l'offerta non vale più; il principale danneggiato si conserva e il backup resta intatto. + - Se il catalogo è valido ma la vecchia app modifica gli input legacy, `DevelopmentStartupView` offre **Keep Arcane's library**. `CatalogLegacyConflictCandidate` cattura le impronte di catalogo, backup e input; `keepCurrentLibrary` le rivalida sotto lock e archivia i byte presenti in una cartella esclusiva `catalog-conflict-*` prima di riconoscere la nuova base legacy. Mantiene giochi e fonti Arcane, senza fusione e senza scrivere sui file legacy. Il catalogo e il suo restore point usano la stessa base riconosciuta; una successiva modifica legacy torna a bloccare letture e scritture. *Perché:* una vecchia copia riaperta dopo un aggiornamento manuale non deve imporre di scartare il catalogo nuovo. + - `commitUncertain` segnala un errore della sincronizzazione finale dopo una possibile pubblicazione: il chiamante rilegge la revisione prima di ritentare. + - Il formato usa i valori Date Codable per conservare le frazioni; solo l'ingresso legacy usa ISO8601. +- `CatalogRepository` è l'unico writer del catalogo. Carica la versione corrente e applica ogni modifica tipizzata una volta; non ritenta da solo operazioni con effetti sui file. Le scansioni confrontano la generazione osservata con build, installazione e sorgenti correnti prima di aggiornare i campi; una richiesta di refresh durante una scansione resta in coda. +- `AppViewModel` pubblica il catalogo e una proiezione nxnative di sola lettura. Scansioni, icone, sorgenti e risultati delle build passano dallo stesso repository; le righe mostrate non si salvano mai come libreria di ripiego. +- Il risultato di una build aggiorna soltanto i campi di sua competenza. Un risultato non salvato resta in `CatalogBuildRecoveries` per il retry della generazione giusta; le installazioni automatiche aspettano che sia risolto. Il risultato e il menu File tengono disponibile l'azione di salvataggio anche dopo la chiusura dell'avviso. +- `CatalogPersonalizations` porta i riferimenti alle viste e ai loader; i percorsi nxnative restano quelli di sempre, i dati personali Steam hanno una radice separata. L'importatore Dev comprende i file del catalogo. + +**I giochi Switch (nxnative).** +- `PortedGame` rappresenta un titolo nxnative: identità, app installata, sorgenti, impostazioni runtime, ultimo porting, toolchain e installazione eventualmente differita. +- `ImportService` scansiona i bundle `.app` nelle sole cartelle scelte e riconosce un gioco da `DMTitleID` o dal bundle ID `org.nxnative.<title ID>`. La visita è in ampiezza, fino a sei livelli e 4000 cartelle, con deduplicazione dei percorsi canonici. Non entra in bundle e package e non segue i link delle sottocartelle. +- Limiti e letture fallite producono avvisi con motivo e azione utile, visibili accanto a Scan game apps e, nel primo Setup, sotto Game apps. Non aprono dialoghi automatici né cicli di Retry all'avvio e non cancellano il catalogo; una scansione successiva li aggiorna o li toglie. +- `appsForLibrary` sceglie una sola osservazione per titolo: il percorso già registrato se esiste, altrimenti la più recente. Un'app fuori dall'area scandita lascia invariata la sua voce. Merge e metadati usano la stessa scelta. +- `NXNativeLibraryMerge` parte dalla voce salvata e aggiorna esplicitamente i dati osservati. Conserva impostazioni, identità, preferiti, installazione in attesa ed errore dell'ultimo porting, e la provenienza di una build installata. +- L'aggiunta o il collegamento esplicito delle sorgenti usa `merge(replacingSources: true)`: la selezione confermata sostituisce sorgenti, workspace e percorso della cache, anche se i file precedenti esistono ancora. I file originali restano sul disco. Le scansioni automatiche conservano la selezione registrata e il bundle installato. +- `GameResourceState` riconcilia app, sorgenti e stato. Conserva build in corso e workspace non ancora compilati, distingue app mancante da file d'origine mancanti e mantiene Play per una build esistente. Le viste usano `PortingPills.unavailable` per il motivo breve e l'azione primaria disabilitata; `PortingTileLook.locked` riusa sfocatura e lucchetto. La voce resta in libreria: non si cerca l'app spostata, e Refresh controlla le cartelle già configurate. Un cambio di cartella durante la scansione scarta il contesto precedente e avvia quella nuova. +- `AppSizeCache` ricorda le dimensioni per percorso e data di modifica. +- Settings → Library usa un'unica riga **Scan game apps** per scoperta e refresh, disabilitata durante la scansione (anche come azione del controller). Collection conserva il proprio ingresso per importare build esistenti. + +**Le fonti.** +- `CatalogSourcesModel` tiene configurazione e stato della fonte Steam e la richiesta di scansione corrente. La lettura avviene su un worker annullabile. Disattivazione, cambio di cartella o nuova richiesta invalidano il risultato precedente. La generazione salvata distingue anche disattivazione e riattivazione sulla stessa radice; nei cataloghi schema 1 più vecchi il valore mancante si legge come una sentinella fissa. Un risultato valido si applica all'ultima revisione conservando le modifiche indipendenti ai preferiti. +- `SteamCatalogReconciler` applica snapshot già letti, con un ticket legato alla revisione e alla radice. La fusione mantiene UUID, preferiti, nascosti e installazioni storiche. Un titolo ambiguo resta da verificare, una scansione parziale conserva le osservazioni non viste, una fonte assente segnala indisponibilità; l'assenza diventa "non rilevato" solo con uno snapshot completo. `needsInstallationReview` tiene l'ambiguità separata dalla disponibilità del disco. Nessun record o file di gioco viene eliminato. +- Menu → Manage sources e Settings → Sources attivano Steam, aggiornano o annullano la ricerca, scelgono la sua cartella e recuperano titoli nascosti o installazioni da controllare. L'avvio scansiona solo Steam già abilitato. Adottare esplicitamente sorgenti o build Switch abilita nxnative nello stesso catalogo; una scansione passiva non attiva un'esperienza non scelta. +- Tutto il resto di Steam è in [steam.md](steam.md). + +**La libreria mostrata.** +- `CatalogLibraryProjection` seleziona le voci delle fonti attive. Spotlight, Collection e ricerca usano gli stessi record, UUID, filtri e ordine salvato; le viste specifiche ricevono il payload reale. +- I giochi Steam mostrano l'icona della propria app Mac e la fonte, senza interrogare servizi Nintendo né riscrivere bundle. Hanno la stessa testata, pagina e Opzioni dei giochi nxnative. I titoli nascosti restano recuperabili dalle fonti. +- Menu e comandi specifici nxnative ricevono soltanto `PortedGame`: selezionare un gioco Steam non può avviare una build né aprire salvataggi o mod Switch. + +## Navigazione e focus + +- `AppRouter` gestisce schermata corrente, cronologia di ritorno e richieste di selezione. `SpotlightState`, `LibrarySelectionState`, `DetailsFocus`, `MenuSelectionModel` e `FocusIndex` descrivono il focus indipendentemente dal disegno SwiftUI. `LibraryQuery` applica ricerca, filtri e ordinamento. +- Le viste principali sono Spotlight, Collection e Details. Ricerca, Add Game, Console, Game Options e Settings si raggiungono dalla shell e dalle azioni del router. Le estensioni `…+Input.swift` traducono tastiera, mouse e controller in modifiche ai modelli di focus. +- **Righe di tessere.** + - `SpotlightTileArtwork` e `SteamArtwork` leggono l'immagine già decodificata dalla cache anche nel primo body, prima della `.task`. `TileArtMemo` distingue fonte, richiesta e revisione della scelta personale, con limiti di 200 immagini e 160 MB. `GameIconProvider` ricorda anche i giochi senza icona quadrata, per percorso dell'app e del workspace: la build sposta il gioco sulla sua app, e `forget` legge di nuovo dopo un cambio d'icona. Steam include il build ID dell'installazione e rivalida i file nel task senza svuotare l'immagine durante la lettura. *Perché:* tornando da Settings le viste sono nuove, ma l'arte già caricata non deve passare dal ripiego mentre il task riparte. + - Le righe di Spotlight e Collection mettono ogni tessera al suo posto e scorrono con un'unica camera (`SpotlightRowGeometry`): la riga si muove come un pezzo solo, e una tessera creata al bordo mentre la riga scorre non arriva prima delle vicine. + - Lo scorrimento è una molla smorzata: a pressioni rapide riprende la velocità che ha invece di ripartire ogni volta. Le tessere si creano quattro oltre ogni bordo dello schermo. + - In Spotlight posto e dimensione di ogni tessera e la camera si ricavano da un solo valore animato, la posizione della selezione (un indice, con frazioni a metà strada). *Perché:* animati separatamente, la crescita di una tessera partiva un paio di fotogrammi dopo il suo spostamento e la tessera si staccava dalla vicina. + - Una selezione che salta più tessere scorre attraverso quelle in mezzo; mentre una tessera è sollevata per spostarla cresce solo lei. + - In Spotlight sinistra e destra sulla riga lavorano sulla lista filtrata. La parte sotto gli screenshot si monta quando la pagina sale, così navigare tra tessere evita il calcolo di descrizioni, classifica e link fuori schermo. +- **Entrata di Spotlight** (`SpotlightView+Entrance`, tempi e fasi in `SpotlightEntrance`). + - C’è solo la prima volta che una home si vede dopo l’avvio, se è Spotlight (`AppViewModel.homeSeen`, che segna anche Collection), con **Entrance animation** accesa e mai con Riduci movimento. La chiave `introAnimation` resta compatibile; la shell usa lo stesso interruttore per il suono di avvio. + - Benvenuto e Setup, fino alla fine della chiusura, e la finestra che prende il fullscreen tengono l’entrata coperta. L’arte è nascosta (`ArtReveal.hidden`); riga e informazioni si preparano a opacità 0,001, mentre barra e pillola sono nascoste e non ricevono input. *Perché:* il primo disegno delle tessere avviene prima del volo. Benvenuto e Setup chiedono alla shell lo stesso sfondo condiviso, così chiuderli lascia lo stesso moonlight in movimento. + - Scoperta la home, il moonlight ha 0,5 s da solo. Poi l’entrata aspetta, per al massimo un altro secondo, che finisca la prima ricerca dell’arte (`TileArtPendingKey`, da `SpotlightTileArtwork` e `SteamArtwork`). + - L’arte entra in 1,4 s con la curva di `OpacityFade`, come lo scorrimento fra giochi. Il moonlight continua a muoversi finché l’arte è entrata; anche la prima immagine arrivata tardi sfuma (`SeleneArtLayerView.heldOnce`). + - Ogni tessera visibile parte più vicina al centro della riga (75% della distanza), con scala 0,35 e spostamento verticale −18 unità; vola in 0,9 s, con dissolvenza di 0,5 s, da 0,6 s più 0,06 s per tessera. Le tessere oltre il bordo destro fanno solo una dissolvenza, al massimo dodici. `EntranceFlight` e `EntranceFade` calcolano movimento e opacità su orologi lineari avviati insieme, con il ritardo dentro ogni effetto. + - Le informazioni salgono di 40 unità da 1,3 s, in 0,8 s, con dissolvenza di 0,7 s; il titolo sotto la selezione arriva da 2 s. `SpotlightEntrance.end(of:)` determina l’atterraggio finale. Le [misure dell’entrata](reviews/2026-11-17-entrance-frames.md) descrivono metodo, campioni e limiti della sonda temporanea. + - Barra in alto (tab e orologio) e hint dei pulsanti (`SeleneHomeChrome.hintsHeld`) arrivano per ultimi, insieme: a volo finito sfumano in 0,4 s (`SpotlightEntrance.controlsFade`). La pillola del filtro sale con lo sfondo. + - Nessun input salta l’entrata. Fino all’atterraggio (`Phase.takesInput`) Spotlight ignora controller, tasti e rotella e non riceve clic; passano solo le scorciatoie con ⌘, ⌃ o ⌥. *Perché:* l’entrata è l’apertura dell’app e va vista intera. Un volo iniziato atterra comunque entro 5 s (`SpotlightEntrance.longestWait`), così l’input non resta mai bloccato. + - Uscendo da Spotlight, ridimensionando durante il volo o accendendo Riduci movimento, tutto atterra subito, barra e hint compresi. +- **Cursore a schermo intero.** `FullscreenCursorView` (un NSView nella shell) osserva finestra, mouse e transizioni native; `CursorIdleState` decide la visibilità con il tempo monotono. + - In fullscreen, con il mouse nel contenuto, il puntatore si nasconde dopo tre secondi senza movimento. Cambi di schermata, menu interni, ricerca, opzioni, tastiera, controller, clic e scroll non lo rendono visibile; un movimento riavvia il ritardo. + - La posizione reale si campiona anche dal timer, perché i loop nativi di menu e controlli possono consumare gli eventi prima del monitor locale. Durante un menu nativo non parte un nuovo nascondimento, ma un puntatore già nascosto resta nascosto; alla chiusura si riallinea lo stato AppKit. + - Pannelli di sistema, perdita di focus e uscita dal fullscreen ripristinano la visibilità. Il distacco rimuove monitor, timer e osservatori e ripristina il precedente `acceptsMouseMovedEvents`. + +## Impostazioni + +**La barra laterale.** `SettingsSidebarGroup` raggruppa le sezioni: Search e Changed, poi quattro gruppi. +- **General:** Start-up, Navigation, Spotlight, Sound & music, Look, Controllers, Online services. +- **Library:** Sources, Games, Storage. Valgono per i giochi di ogni fonte. +- **Porting:** Setup and engine, Keys, Library, New games, Cloud saves, Storage. Valgono solo per i giochi convertiti. +- **System:** About, Console. In `SettingsAboutSection`, il pulsante di sostegno volontario a tutta larghezza, prima dei crediti, mostra l’icona di Buy Me a Coffee e apre la pagina nel browser predefinito. Clic, tastiera e controller usano la stessa azione. + +Regole della barra: +- Porting è l'unico gruppo di piattaforma (`isPlatform`): Search, Changed e il titolo di pagina chiamano le sue sezioni col nome del gruppo ("Porting · New games"). +- `SettingsSection` dichiara i casi nell'ordine della barra, quindi `allCases` la percorre come è disegnata. I `rawValue` sono identità e non cambiano: `sources` è la pagina Sources, `library` e `games` sono Library e New games di Porting; i casi nuovi (`libraryGames`, `keys`, `cloudSaves`, `portingStorage`, `console`) hanno identità proprie. +- Ogni riga di `SettingsCatalog` tiene il suo `rowID` quando cambia sezione. +- Dove stanno le righe che si potrebbero cercare altrove: + - schermata di lancio, Surprise me, card della sessione e giochi nascosti in Library → Games, perché valgono per ogni fonte; + - Rumble e Rumble strength in Porting → New games, perché sono default copiati nei nuovi giochi convertiti; + - prod.keys in Porting → Keys; Check engine at launch e Setup in Setup and engine, dove Compatibility ripete già il controllo dell'ambiente; + - Refresh library at launch e Box covers in Porting → Library; + - le cache di compilazione, per gioco e per tutti, in Porting → Storage; spazio usato, log, cache di metadati e artwork e backup in Library → Storage; + - App icon in Look: è l'icona del Dock. +- Online services (`apiServices`) raccoglie IGDB (voti) e SteamGridDB (artwork). La nota iniziale dice che le connessioni sono facoltative e che le fonti pubbliche funzionano senza chiavi. Non esiste un reset di gruppo che elimini le credenziali. + +**Chi decide cosa.** + +| Punto dell'interfaccia | Autorità | |---|---| -| Settings → Games → New games | Valori iniziali copiati nei nuovi titoli. | +| Settings → Porting → New games | Valori iniziali copiati nei nuovi titoli, vibrazione compresa. | | Game Options → Next launch | Configurazione di quel titolo, applicata al prossimo avvio. | | Use new game defaults | Copia una volta i default correnti nel gioco selezionato. | | Add Game → Review | Nuovo titolo: parte dai default. Titolo esistente: `GameRuntimeConfig.forReview` legge le sue opzioni effettive. La conferma salva i valori mostrati. | | Cloud saves | Preferenza riapplicata prima di ogni avvio, compreso Off. | -| Controllers | Navigazione della libreria; il sottogruppo New games contiene i default della vibrazione. | - -Options e Play leggono `GameRuntimeConfig.load`: preferenze per titolo in UserDefaults, poi `env.txt` del titolo, quello nel bundle e infine i valori del modello. Il rebuild ricava `languageForBuild` dalla configurazione del titolo e non conserva una lingua separata dal wizard. Le modifiche dei default globali non aggiornano automaticamente i giochi già aggiunti. Search e Changed attribuiscono la vibrazione a Controllers. - -Il catalogo Settings descrive i singoli controlli; Changed riceve anche le differenze delle preferenze esterne ad AppSettings. Le azioni da controller si aggiornano con lo stato dei pannelli e mantengono il focus per identità. About pubblica azioni selezionabili. Il reset aggiorna AppSettings con una sola assegnazione e segnala le scelte cloud/percorso preservate. - -`AppSettingsStore` pubblica gli errori e conserva una copia dei file illeggibili prima di consentirne la sostituzione. La UI usa un dialogo Selene, con Retry per una scrittura fallita. `GameRuntimeConfig.save` propaga gli errori di env.txt e persiste le preferenze per titolo dopo la scrittura riuscita. Un env.txt illeggibile viene conservato e segnalato. - -`AppRouter` gestisce schermata corrente, cronologia di ritorno e richieste di selezione. I modelli `SpotlightState`, `LibrarySelectionState`, `DetailsFocus`, `MenuSelectionModel` e `FocusIndex` descrivono il focus indipendentemente dal disegno SwiftUI. `LibraryQuery` applica ricerca, filtri e ordinamento. - -Le viste principali sono Spotlight, Collection e Details. Ricerca, Add Game, Console, Game Options e Settings sono raggiunti dalla shell e dalle azioni del router. Le estensioni `…+Input.swift` traducono tastiera, mouse e controller in modifiche ai modelli di focus. Le righe di Spotlight e Collection mettono ogni tessera al suo posto nella riga e scorrono con un'unica camera (`SpotlightRowGeometry`): la riga si muove come un pezzo solo, e una tessera creata al bordo mentre la riga ancora scorre non arriva prima delle vicine. Lo scorrimento è una molla smorzata, che a pressioni rapide riprende la velocità che ha invece di ripartire a ogni pressione; le tessere si creano quattro oltre ogni bordo dello schermo. In Spotlight posto e dimensione di ogni tessera e la camera si ricavano da un solo valore animato, la posizione della selezione (un indice, con frazioni a metà strada): animati separatamente (offset, scala, camera), la crescita di una tessera iniziata mentre la riga ancora scorreva partiva un paio di fotogrammi dopo il suo spostamento, e la tessera si staccava da quella alla sua destra. Una selezione che salta più tessere scorre attraverso quelle in mezzo; mentre una tessera è sollevata per spostarla cresce solo lei. - -### Lingua e regione (non pubblicato, validato dal maintainer) - -`AppLanguage` definisce auto/en/it/fr/de/es/pt-BR; `AppLocale` risolve le preferenze ordinate del Mac e una regione indipendente, valida i codici e mappa pt-BR a pt soltanto per Nlib. `AppSettings` conserva i due override in modo additivo: vecchi file e scelte non riconosciute tornano ad Automatic. `NXLibraryApp.init` carica un solo `AppSettingsStore` e configura il locale prima della creazione delle scene; lo stesso store passa a `MainView` e `AppShellView`. Gli initializer delle viste non pubblicano cambi di locale: il controllo sincrono della toolchain può far rientrare il run loop mentre SwiftUI costruisce i propri StateObject. `AppLocalization` pubblica il contesto; la shell lo propaga alle viste tramite `nxAppLocale`, una dipendenza SwiftUI esplicita che non ricrea identità o stato. Settings passa questo valore alla sidebar e `SettingsSection.title(in:)` risolve le categorie nel contesto ricevuto, anche con focus sulle righe. Righe, informazioni, pannelli e suggerimenti condivisi consumano lo stesso valore. `L10n` mantiene al massimo un bundle per ciascuna delle sei lingue; le risorse iniettate restano isolate, senza memorizzare testi interpolati o dati personali. Cattura il contesto per il lavoro asincrono e legge esplicitamente il catalogo compilato, cercando prima nel bundle installato. Nessun servizio di posizione o traduzione esterno viene usato. - -I testi controllati dall'app sono nel catalogo condiviso `NXLibraryCore/Resources/Localizable.xcstrings`, con interpolazioni e plurali. Dati personali, rawValue persistiti, regex, eventi dell'engine, variabili DM_* e identità dei controlli restano indipendenti dalla lingua. I componenti Settings risolvono le etichette alla presentazione e mantengono i rowID originali; le righe coi nomi dei giochi usano titoli verbatim. Search confronta anche i testi tradotti. I testi upstream noti di launcher.json si localizzano solo nella presentazione; valori e note sconosciute conservano il fallback upstream. - -Start-up ospita lingua e regione. `LocalePicker` offre una scelta diretta delle lingue e ricerca i nomi localizzati delle regioni per codice stabile, con input tastiera/controller distinto da Settings. Le righe distinguono la lingua di menu, generi e descrizioni dai soli formati regionali. Il cambio non ricrea il router o le sessioni e non cambia la lingua di alcun gioco. Date e dimensioni rispettano il locale scelto; nomi dei giorni e durate hanno una presentazione localizzata. - -`GameGenre` traduce alla presentazione i generi noti senza modificare i metadati e le scelte salvate; generi sconosciuti restano verbatim. `NintendoStoreMetadataService` conserva le vecchie cache come inglesi e i percorsi per lingua/regione, riusando i dati tra regioni della stessa lingua. Un cambio di sola regione non aggiorna i metadati; un cambio lingua conserva la scheda visibile, legge la cache fuori dal thread principale e, con dati freschi già presenti, richiede soltanto la descrizione tradotta. Gli ID 0400 dei giochi Switch 2 sono ammessi al lookup Nlib come gli 0100. `descriptionCheckedAt` distingue un ripiego già controllato da una vecchia cache mai cercata nella lingua richiesta: una traduzione vuota viene ricontrollata dopo 24 ore, un errore temporaneo consente un nuovo tentativo dopo un minuto. Richiede una descrizione Nlib localizzata anche quando il catalogo US ne ha già una inglese; non invia parametri regione non documentati. Fallimenti parziali conservano prima una descrizione tradotta già presente in cache, senza rinnovarne artificialmente la freschezza; in sua assenza, fallimenti o descrizioni vuote conservano il ripiego inglese; il modello conserva la lingua della descrizione e Details e Spotlight indicano la lingua effettiva quando differisce dalla lingua dell’app. Scelte personali restano prioritarie. `metadataLocaleGeneration` impedisce a una risposta precedente di ripopolare la UI dopo un cambio lingua; screenshot e artwork rimangono condivisi. - -SwiftPM compila le risorse; build_app.sh le include prima della firma, mentre `check_localizations.py` verifica copertura delle sei lingue, placeholder, plurali e risorse compilate. release.sh ripete il controllo sullo ZIP estratto. Le traduzioni iniziali sono bozze dell'agente, non revisioni madrelingua certificate. Il maintainer ha confermato nella Dev i flussi e il cambio immediato di lingua, inclusa la sidebar senza spostare il focus; nessun servizio Crowdin/Transifex è stato aperto e la issue #10 non viene chiusa automaticamente. - -## Setup e compatibilità - -`SystemDetector` e `EngineLocation` individuano checkout e cartelle dell’utente. `NXNativeEnvironment` raccoglie lo stato di Python, strumenti, Xcode e Metal; da nxnative 641636e2 i tool dell'engine sono eseguibili nativi e .NET non serve più. `EngineToolchain` risolve Python e `PATH`, preferendo il runtime incluso nel bundle quando disponibile. - -`SetupProbe` costruisce i dati del Setup. `SetupCheck` li traduce in schede, stati e azioni. `SetupCheckModel` esegue i controlli in background e coordina installazioni e avanzamento. `SetupActions` prepara gli argomenti Git per portare un checkout gestibile al pin. - -Get ready mostra soltanto i cinque requisiti tecnici, in una griglia 3 + 2; i problemi alle cartelle non riaprono questa schermata. Your games presenta Game apps, la cartella unica in cui cercare giochi nxnative esistenti e installare le prime build. Il default `~/Applications` può essere preparato al primo uso solo se non è già stato scelto o ricordato un percorso. Le destinazioni personalizzate o confermate rimangono ricordate anche quando non disponibili. La lettura basta per scoperta e Play; le nuove installazioni richiedono scrittura. Game files rimane una preferenza facoltativa in Settings → Library, separata dalla selezione temporanea del wizard. Cambiare Game apps non sposta app già registrate; cambiare Game files non sostituisce i sorgenti di un titolo senza conferma esplicita. `GameFoldersCopy` mantiene i nomi coerenti. - -`CompatibilityChecker` verifica commit, modifiche del checkout, contratto CLI e compilatore Metal richiesto dal lock del motore. `ToolchainRequirements.current` contiene Xcode minimo e asset Metal. `ToolchainGateCopy` produce la spiegazione del risultato per la UI. - -Il lock del pin attuale certifica Metal `32023.922`, asset Apple `27B47`, con Xcode minimo `27.2`. La [revisione 79741184 → 8a5c5e7e](upstream-upgrades/2026-11-12-79741184-8a5c5e7e-review.md) registra il pin della 0.1.4.3, adottato su richiesta esplicita del maintainer; la [nota dell’upgrade del 6 novembre](upstream-upgrades/2026-11-06-4a0551e4-04df08d4-review.md) registra 04df08d4, confermato dal maintainer con un build di Ocarina of Time; quella [bd979ced → 79741184](upstream-upgrades/2026-11-09-bd979ced-79741184-review.md) registra il pin della 0.1.4.2, adottato su richiesta esplicita del maintainer con gate e test automatici superati ma build/avvio sull'esatto hash ancora non confermati; quella [e5f03403 → bd979ced](upstream-upgrades/2026-11-08-e5f03403-bd979ced-review.md) registra il pin della 0.1.4.1; quella [7fe9fc4d → e5f03403](upstream-upgrades/2026-11-07-7fe9fc4d-e5f03403-review.md) registra il pin precedente, confermato dal maintainer con un rebuild di Ocarina of Time; quella [b2d46b86 → 7fe9fc4d](upstream-upgrades/2026-11-07-b2d46b86-7fe9fc4d-review.md) registra il pin precedente, confermato dal maintainer con un rebuild di Ocarina of Time; quella [04df08d4 → b2d46b86](upstream-upgrades/2026-11-06-04df08d4-b2d46b86-review.md) registra b2d46b86, che aggiunge il controllo dei file `.zs` danneggiati in NUP e cartelle (riga `files.format` del classificatore); quella [del 5 novembre](upstream-upgrades/2026-11-05-b64a5ff0-4a0551e4-review.md) registra gate certificato senza override, build reale di Wonder con archivio pipeline e avvio confermato dall’utente per 4a0551e4. Un build con override riceve `toolchainVerified=false` e `--allow-other-metal`. Play valuta la disponibilità dell’app già installata separatamente dal gate per un nuovo porting. - -L'engine più nuovo è una scelta esplicita del giocatore (Settings → Engine → **Newest engine**). Dopo il controllo Upstream, che misura sempre i commit rispetto al pin, `NewestEngine.fetchLock` legge il lock di main da GitHub: se certifica un Metal diverso da quello del lock del pin, la riga dice che serve un NX Library più nuovo e non offre il cambio. `NewestEngineSwitcher` rifiuta un checkout con file modificati, scarica, rilegge il lock con git e solo allora fa `checkout --detach`. La scelta (`NewestEngineChoice`) è salvata, diventa il commit atteso dal gate e quello registrato nelle build, accende l'override (che resta bloccato finché la scelta è attiva) e marca le build come non testate; il gate mostra **Newest engine** in arancione, mai Certified. Il Setup continua a installare il pin, ma per il commit scelto mostra la scheda pronta in arancione con **Back to tested** e non la riporta indietro da solo. La scelta decade quando il checkout non è più su quel commit o quando un aggiornamento di NX Library porta un pin che lo contiene; se l'override l'aveva acceso la scelta, torna spento. Settings e Setup usano la stessa frase (`NewestEngineCopy.note`). - -Il pin `04df08d4` (poi superato da `b2d46b86`) non cambia CLI, eventi di progresso, compilatore Metal né lettori NUP e cartelle (`pack_nup`, `pack_dump`). Cache di compilazione e librerie shader diventano un file ciascuna (`shader/cache/cas.db`, `msl/b-<chain>.img`): NX Library non legge dentro nessuno dei due. Il primo build di un gioco dopo l'aggiornamento sposta prima la vecchia cache nel nuovo file e lo annuncia con `moving the compile cache …`; `PortingProgress.isUpdatingShaderCache` lo mostra come **Updating shader cache**. Il nuovo `.github/requirements/tools.txt` dell'engine elenca numpy, pillow e texture2ddecoder, usati solo da strumenti di sviluppo: `EngineRuntimeRequirementsTests.notBundled` ne registra il motivo. - -Il pin `4a0551e4` aggiorna shader, runtime e profili (compresi nuovi giochi Switch 2) e porta le righe `Front-ends:` nei commit dell'engine, lette a ogni re-pin. Tre capacità hanno un riflesso nell'interfaccia: `stage_end` con `warn: true` (archivio pipeline mancante) mostra ⚠ sulla fase e una spiegazione in **Ready to play** (`BuildWarningCopy`); quando lo script espone `survey_nup` / `survey_dump`, `EngineSourceCapabilities` accetta NUP e cartelle estratte senza profilo, che l'engine porta con un profilo provvisorio, e Review mostra **Not tested with this engine yet** per qualunque sorgente senza profilo; la guida dei controlli elenca l'uscita con Home (2 s, poi A). Dopo 0.1.3 anche un NUP senza base (777a5f6c) è accettato: Review offre solo le versioni di update (la più recente selezionata, una sempre scelta) e la build passa quella versione con `--package`, mai `v0`. Le nuove righe di `settings.tsv` (120 fps, upscaler del gioco, forma dell'immagine) arrivano da sole tramite Game options. `--seen-shaders`, `--program` e le opzioni per i profili provvisori non vengono adottate. Un salvataggio con nomi creati prima di 7c23cc0 viene rinominato al primo mount: una build più vecchia dello stesso gioco potrebbe non leggerlo più. - -Il pin precedente `b64a5ff0` aggiorna audio, allineamento memoria, rendering, shader e profili; aggiunge il controllo chiavi anticipato e la pulizia cache. NUP resta un formato sorgente non esposto dal frontend, i diagnostici non diventano nuovi toggle e i controlli FPS rimangono quelli già supportati. Le precedenti correzioni AV1 restano incluse. Il motore compila dav1d dalle proprie sorgenti incluse; il runtime del frontend non cambia. Gli hook per incorporare la vista del gioco in un frontend non vengono adottati: NX Library avvia app di gioco separate. +| Controllers | Navigazione della libreria. | + +- Options e Play leggono `GameRuntimeConfig.load`: prima le preferenze per titolo in UserDefaults, poi `env.txt` del titolo, poi quello nel bundle, infine i valori del modello. +- Il rebuild ricava `languageForBuild` dalla configurazione del titolo e non tiene una lingua separata dal wizard. I default globali cambiati non aggiornano da soli i giochi già aggiunti. Search e Changed attribuiscono la vibrazione a Porting · New games. + +**Catalogo e salvataggio.** +- `SettingsCatalog` descrive i singoli controlli. Changed riceve anche le differenze delle preferenze esterne ad `AppSettings`. Le azioni del controller si aggiornano con lo stato dei pannelli e mantengono il focus per identità. About pubblica azioni selezionabili. +- Reset group è possibile dove `SettingsReset.canReset` lo dice. `SettingsReset.reset` rimette ai default i valori `AppSettings` della sezione in una sola assegnazione; la schermata azzera accanto le preferenze esterne (tema applicato, icona dell'app, zona morta della levetta, cartella Game apps) e segnala la cartella delle sorgenti conservata. Cloud saves e le credenziali non hanno reset. +- `AppSettingsStore` salva `settings.json` tramite un file temporaneo, pubblica gli errori e conserva una copia di un file illeggibile prima di permetterne la sostituzione. La UI usa un dialogo Selene con Retry per una scrittura fallita. + In Spotlight e Collection l'ultimo gioco selezionato è stato di navigazione nello stesso store, senza notificare gli osservatori delle impostazioni a ogni movimento. Lo store include lo stesso campo nel JSON, accoda la scrittura in background e sostituisce le scritture ancora in attesa con la selezione più recente. Un salvataggio esplicito e la chiusura conservano la selezione corrente. +- `GameRuntimeConfig.save` propaga gli errori di `env.txt` e salva le preferenze per titolo solo dopo una scrittura riuscita. Un `env.txt` illeggibile si conserva e si segnala. + +## Lingua e regione + +**Scelta della lingua.** +- `AppLanguage` definisce auto/en/it/fr/de/es/pt-BR. `AppLocale` risolve le preferenze ordinate del Mac e una regione indipendente, valida i codici e mappa pt-BR a pt soltanto per Nlib. +- `AppSettings` conserva i due override in modo additivo: vecchi file e scelte non riconosciute tornano ad Automatic. +- `DevelopmentStartupView` carica un solo `AppSettingsStore`, configura il locale e passa lo store a `MainView` e `AppShellView`. Gli initializer delle viste non pubblicano cambi di locale, perché il controllo sincrono della toolchain può far rientrare il run loop mentre SwiftUI costruisce i propri StateObject. + +**Propagazione alle viste.** +- `AppLocalization` pubblica il contesto. La shell lo propaga alle viste tramite `nxAppLocale`, una dipendenza SwiftUI esplicita che non ricrea identità o stato. +- Settings passa questo valore alla barra laterale, e `SettingsSection.title(in:)` risolve le categorie nel contesto ricevuto, anche con il focus sulle righe. Righe, informazioni, pannelli e suggerimenti condivisi usano lo stesso valore. +- `L10n` tiene al massimo un bundle per ciascuna delle sei lingue. Le risorse iniettate restano isolate, senza memorizzare testi interpolati o dati personali. Cattura il contesto per il lavoro asincrono e legge il catalogo compilato, cercando prima nel bundle installato. Non si usa nessun servizio esterno di posizione o traduzione. + +**Testi.** +- I testi controllati dall'app sono nel catalogo condiviso `NXLibraryCore/Resources/Localizable.xcstrings`, con interpolazioni e plurali. +- Restano indipendenti dalla lingua: dati personali, rawValue salvati, regex, eventi dell'engine, variabili `DM_*` e identità dei controlli. +- I componenti Settings risolvono le etichette alla presentazione e mantengono i rowID originali; le righe con i nomi dei giochi usano i titoli così come sono. Search confronta anche i testi tradotti. +- I testi upstream noti di `launcher.json` si localizzano solo nella presentazione; valori e note sconosciute tengono il testo upstream. +- Il nome dell'app, "Arcane", sta in `AppIdentity.name` e non si traduce: le viste che mostrano solo il nome lo leggono da lì, e il catalogo non contiene più il vecchio nome. Bundle ID, cartelle dei dati, chiavi delle preferenze e segni `.nxlibrary-*` tengono il nome storico, perché cambiarli separerebbe i dati di chi aggiorna. +- Ogni richiesta di rete si presenta con `AppIdentity.userAgent()`, cioè `Arcane/<versione> (macOS; +https://github.com/Bium23/NxLibrary)`. + +**Start-up.** +- Start-up ospita lingua e regione. `LocalePicker` offre la scelta diretta delle lingue e cerca i nomi localizzati delle regioni per codice stabile, con input da tastiera e controller distinto da Settings. +- Le righe distinguono la lingua di menu, generi e descrizioni dai soli formati regionali. Il cambio non ricrea router o sessioni e non cambia la lingua di nessun gioco. Date e dimensioni seguono il locale scelto; nomi dei giorni e durate sono localizzati. + +**Generi e descrizioni.** +- `GameGenre` traduce alla presentazione i generi noti senza modificare metadati e scelte salvate; i generi sconosciuti restano come sono. +- `NintendoStoreMetadataService` legge le vecchie cache come inglesi e salva i percorsi per lingua e regione, riusando i dati tra regioni della stessa lingua. + - Un cambio di sola regione non aggiorna i metadati. Un cambio di lingua conserva la scheda visibile, legge la cache fuori dal thread principale e, con dati freschi già presenti, chiede solo la descrizione tradotta. + - Gli ID 0400 dei giochi Switch 2 sono ammessi al lookup Nlib come gli 0100. + - `descriptionCheckedAt` distingue un ripiego già controllato da una vecchia cache mai cercata nella lingua richiesta. Una traduzione vuota si ricontrolla dopo 24 ore; dopo un errore temporaneo si riprova dopo un minuto. + - Chiede una descrizione Nlib localizzata anche quando il catalogo US ne ha già una inglese, e non invia parametri di regione non documentati. + - Se qualcosa fallisce, si tiene prima una descrizione tradotta già in cache, senza rinnovarne la freschezza; altrimenti si tiene il ripiego inglese. + - Il modello conserva la lingua della descrizione, e Details e Spotlight la indicano quando è diversa da quella dell'app. Le scelte personali hanno la precedenza. + - `metadataLocaleGeneration` impedisce a una risposta vecchia di ripopolare la UI dopo un cambio di lingua. Screenshot e artwork restano condivisi. + +**Controlli.** SwiftPM compila le risorse e `build_app.sh` le include prima della firma. `check_localizations.py` verifica copertura delle sei lingue, segnaposto, plurali e risorse compilate; `release.sh` ripete il controllo sullo ZIP estratto. Le traduzioni sono bozze dell'agente, non revisioni di madrelingua. + +## Setup, engine e compatibilità + +**Ambiente.** +- `SystemDetector` e `EngineLocation` trovano checkout e cartelle dell'utente. +- `NXNativeEnvironment` raccoglie lo stato di Python, strumenti, Xcode e Metal. I tool dell'engine sono eseguibili nativi: .NET non serve. +- `EngineToolchain` risolve Python e `PATH`, preferendo il runtime incluso nel bundle quando c'è. + +**Setup.** +- `SetupProbe` raccoglie i dati del Setup. `SetupCheck` li traduce in schede, stati e azioni. `SetupCheckModel` esegue i controlli in background, compresa la lettura di `xcode-select` a ogni ricontrollo (4 s), e coordina installazioni e avanzamento. `SetupActions` prepara gli argomenti Git per portare un checkout gestibile al pin. +- Get ready mostra soltanto i cinque requisiti tecnici, in una griglia 3 + 2. I problemi alle cartelle non riaprono questa schermata. +- Your games presenta Game apps, la cartella unica in cui cercare giochi nxnative esistenti e installare le prime build. + - Il default `~/Applications` si prepara al primo uso solo se non è già stato scelto o ricordato un percorso. Le destinazioni personalizzate o confermate restano ricordate anche quando non sono disponibili. + - La lettura basta per scoperta e Play; le nuove installazioni richiedono la scrittura. + - Game files è una preferenza facoltativa in Settings → Library, separata dalla selezione temporanea del wizard. + - Cambiare Game apps non sposta le app registrate; cambiare Game files non sostituisce i sorgenti di un titolo senza conferma esplicita. `GameFoldersCopy` mantiene coerenti i nomi. +- Con un engine che riconosce le cartelle estratte, Setup permette di proseguire senza chiavi. Le sorgenti cifrate continuano a richiederle e a passare dal controllo preliminare. + +**Gate di compatibilità.** +- `CompatibilityChecker` verifica commit, modifiche del checkout, contratto CLI e compilatore Metal richiesto dal lock del motore. `ToolchainRequirements.current` contiene Xcode minimo e asset Metal. `ToolchainGateCopy` spiega il risultato nella UI. +- Una build con l'override del gate riceve `toolchainVerified=false` e `--allow-other-metal`. +- Play valuta la disponibilità dell'app già installata separatamente dal gate per un nuovo porting. + +**Newest engine.** L'engine più nuovo è una scelta esplicita del giocatore (Settings → Setup and engine → **Newest engine**). +- Dopo il controllo Upstream, che misura sempre i commit rispetto al pin, `NewestEngine.fetchLock` legge il lock di main da GitHub. Se certifica un Metal diverso da quello del lock del pin, la riga dice che serve una versione più nuova di Arcane e non offre il cambio. +- `NewestEngineSwitcher` rifiuta un checkout con file modificati, scarica, rilegge il lock con git e solo allora fa `checkout --detach`. +- La scelta (`NewestEngineChoice`) è salvata e diventa il commit atteso dal gate e quello registrato nelle build. Accende l'override, che resta bloccato finché la scelta è attiva, e marca le build come non testate. Il gate mostra **Newest engine** in arancione, mai Certified. +- Il Setup continua a installare il pin, ma per il commit scelto mostra la scheda pronta in arancione con **Back to tested** e non la riporta indietro da solo. +- La scelta decade quando il checkout non è più su quel commit, o quando un aggiornamento di Arcane porta un pin che lo contiene. Se l'override l'aveva acceso la scelta, torna spento. Settings e Setup usano la stessa frase (`NewestEngineCopy.note`). + +**Capacità dell'engine adottate** (la decisione per ogni pin è nella sua nota in `upstream-upgrades/`): +- **Cartelle estratte e pacchetti con più contenuti:** `EnginePackageReader` riusa il lettore content-meta upstream; `ExtractedSourceCatalog` legge NPDM e profili registrati senza chiavi. +- **NUP e cartelle senza profilo:** quando lo script espone `survey_nup` / `survey_dump`, `EngineSourceCapabilities` li accetta e l'engine li porta con un profilo provvisorio. Review mostra **Not tested with this engine yet** per qualunque sorgente senza profilo. +- **File `.zs` danneggiati:** il classificatore dell'engine controlla i file `.zs` danneggiati in NUP e cartelle (riga `files.format`). +- **Programmi NUP:** `NUPSourceCatalog` conserva programma, applicazione e base DLC distinti in + `NUPProgramSelection`, facoltativo sui record storici. Le conversioni UI e i sorgenti salvati mantengono + la selezione. Un engine con il contratto multiprogramma riceve `--program` esplicito, anche zero per + i vecchi record, così un rebuild non segue un nuovo default. Metadati discordanti o un checkout + incapace di selezionare il programma fermano il build; non viene mascherato l'ID. +- **NUP senza base:** Review offre solo le versioni di update (la più recente selezionata, una sempre scelta), e la build passa quella versione con `--package`, mai `v0`. +- **Archivio pipeline mancante:** `stage_end` con `warn: true` mostra ⚠ sulla fase e una spiegazione in **Ready to play** (`BuildWarningCopy`). +- **Preparazione del primo avvio:** quando l'engine riporta `Prewarm pipelines`, `PortingETA` mostra un'attività localizzata invece di riusare la durata finale di un vecchio build. Il tempo trascorso resta nella lista delle fasi; senza un conteggio non si inventa una percentuale. Un warning di questa fase spiega che il gioco prepara le pipeline mancanti al primo avvio. +- **Cache shader in un file:** cache di compilazione e librerie shader sono un file ciascuna (`shader/cache/cas.db`, `msl/b-<chain>.img`); Arcane non legge dentro nessuno dei due. Quando l'engine sposta una vecchia cache, con l'evento `say` `moving the compile cache …` (`PortingProgress.shaderCacheWorkMessage`), `PortingProgress.isUpdatingShaderCache` si accende e `PortingETA` mostra **Updating shader cache** senza avanzare la percentuale né stimare una durata. Lo stato si azzera alla fase o al passo successivo e a fine build; `PortingFailureEngineTests` verifica che l'engine del pin stampi ancora quel testo. +- **Errori delle chiavi:** si riconoscono le chiavi troppo vecchie (con la versione firmware quando è nota) e il ticket comune mancante nel pacchetto. Quest'ultimo usa il kind salvato `keys` con un dettaglio identificativo, così anche un launcher precedente legge la voce durante un rollback. La UI spiega il ticket senza proporre di sostituire le chiavi o forzare il porting. +- **Interfaccia dei giochi:** la guida dei controlli elenca l'uscita con Home (2 s, poi A) e Shift + frecce per la levetta destra. Le righe nuove di `settings.tsv` (120 fps, upscaler del gioco, forma dell'immagine) arrivano da sole tramite Game options. +- **Salvataggi:** un salvataggio con nomi creati prima di 7c23cc0 si rinomina al primo mount, quindi una build più vecchia dello stesso gioco potrebbe non leggerlo più. +- **Strumenti di sviluppo:** `.github/requirements/tools.txt` dell'engine elenca numpy, pillow e texture2ddecoder, usati solo da strumenti di sviluppo; `EngineRuntimeRequirementsTests.notBundled` ne registra il motivo. dav1d si compila dalle sorgenti incluse dell'engine, e il runtime del frontend non cambia. +- **Non adottati:** `--seen-shaders`, un selettore manuale dei programmi, le opzioni per i profili provvisori, i diagnostici come nuovi interruttori e gli hook per incorporare la vista del gioco in un frontend (Arcane avvia app di gioco separate). ## Sorgenti e porting -L'integrazione di [nxnative 163a9905](upstream-upgrades/2026-11-02-2716f78-163a9905-review.md) aggiunge un ingresso per cartelle estratte e metadati per pacchetti con più contenuti. `EnginePackageReader` riusa il lettore content-meta upstream; `ExtractedSourceCatalog` legge NPDM e profili registrati senza chiavi. `SourceSelection` tiene separati contenuti selezionati e file fisici: un pacchetto si conta e si collega una sola volta, il DLC incorporato rimane incluso e la versione scelta viene passata con `-p`. - -`GameFileItem` conserva facoltativamente layout e requisito di selezione del titolo; i vecchi JSON continuano a indicare pacchetti. Questi requisiti sono verificati prima del build anche cambiando checkout. Le cartelle estratte sono collegate nel layout `base/`, `updates/<version>/`, `dlc/<title>/0/romfs/`; il restaging rimuove link esclusi e contenitori vuoti, preservando cache e originali. Un pacchetto illeggibile non nasconde gli altri giochi validi: la scansione mantiene i risultati e segnala i file saltati. - -Con un engine che riconosce cartelle estratte, Setup permette di proseguire senza chiavi. La selezione di pacchetti cifrati continua a richiederle e a eseguire il preflight. La guida In game include Shift + frecce per la levetta destra delle nuove build. L'integrazione è inclusa nella versione principale al pin riportato sopra. - -1. `AddGameView` raccoglie cartelle o file. `SourceCatalog` riconosce NSP, XCI, NSZ e XCZ e raggruppa base, aggiornamenti e DLC. Le selezioni di file vengono scandite e collegate singolarmente, senza includere altri pacchetti della cartella né modificare la preferenza globale Game files. Il reset della bozza avviene solo dopo la conferma del selettore. Più titoli richiedono una scelta esplicita; le riletture dello stesso titolo mantengono nome, impostazioni e selezioni logiche di update/DLC anche se cambiano gli UUID delle righe. -2. `AppViewModel+KeyCheck` invoca `KeyCheck` sulle sorgenti selezionate. Il risultato dipende dalla selezione corrente, così un controllo precedente non abilita un porting diverso. -3. `WorkspaceManager` usa la cartella sorgente in loco oppure prepara un workspace di collegamenti simbolici. Gestisce anche il riuso di una cache esistente. `BuildScratch` sceglie dove: workspace e app temporanea stanno sul volume dell'app. Se la cartella delle app è su un altro volume locale APFS o Mac OS esteso vanno in `.nxlibrary-build/` accanto alle app (exFAT e FAT accettano i link ma tengono gli attributi in file `._` che rompono la firma dell'app; `statfs` dà il tipo), così il disco del Mac non serve e l'installazione è una rinomina; altrimenti (stesso volume, exFAT, rete) restano in Application Support. Una cartella `workspaces` che il giocatore ha spostato su quel volume resta dov'è, e un workspace gestito già su quel volume conserva la sua cache. Un workspace gestito rimasto su un altro volume viene cancellato quando ne nasce uno nuovo, tranne se il gioco non è ancora costruito e punta ancora lì. Il controllo dello spazio misura ogni volume usato una volta sola; la pulizia all'avvio guarda anche le `.nxlibrary-build/Temp`, e cancellare un gioco o le sue sorgenti tocca solo workspace riconosciuti da `BuildScratch.isManaged`. -4. Il coordinatore ricontrolla requisiti, spazio, chiavi e destinazione. `BuildCommandBuilder` produce eseguibile, argomenti, directory di lavoro e ambiente. -5. `BuildService` avvia il processo del motore, gestisce il gruppo di processi, raccoglie stdout e stderr, scrive il log e mantiene l’asserzione contro lo stop per inattività. -6. `BuildEventParser` decodifica il progresso JSON. `PortingProgress` lo aggrega per la UI, con gli shader fino al 90% e le fasi finali nel restante 10%. Il modello alimenta wizard, tile, percentuale e stima del tempo. -7. `BuildOutputInstaller` valida il bundle temporaneo e pubblica il gioco con `renamex_np`: `RENAME_SWAP` scambia atomicamente due app esistenti; `RENAME_EXCL` installa la prima copia senza sovrascrivere una destinazione comparsa nel frattempo. Sullo stesso volume usa direttamente il bundle pronto. Fra volumi diversi prepara prima una copia nascosta accanto alla destinazione, lasciando disponibile l’app corrente fino allo scambio. -8. Se il gioco è aperto o l’installazione è trattenuta da un’operazione sui salvataggi, `PendingInstall` conserva il risultato temporaneo. `AppViewModel+PendingInstall` lo riprende quando può acquisire l’accesso necessario. - -`GameAppDestination` centralizza il percorso mostrato nella review, il volume controllato per lo spazio e la destinazione effettiva. Le prime build usano Game apps; un rebuild conserva l'app esistente quando il suo percorso è sicuro, anche dopo un cambio di cartella. I conflitti di nome con app di altri titoli ricevono un percorso distinto. La destinazione viene fissata prima del porting e rimane tale anche nelle installazioni differite. Le installazioni dei giochi richiedono che la cartella esista ancora: se si disconnette o diventa non scrivibile, il risultato pronto viene conservato per Retry. Il packaging del frontend continua a poter creare la propria cartella di installazione. - -Se il motore termina correttamente con un bundle valido e fallisce solo l’installazione, `BuildResult.heldApp` conserva la build pronta e `installationFailed` distingue questo caso dal porting fallito. Il coordinatore registra la stessa `PendingInstall` già usata per i giochi aperti. Un dialogo Selene offre Retry e Close: Retry installa quel bundle senza riavviare il motore; Close conserva la build. Gli errori delle installazioni differite passano dallo stesso dialogo. La schermata del porting offre anche Retry installation finché la build resta in attesa. Un errore di scrittura del catalogo conserva lo stato in memoria e impedisce che una scansione immediata lo sostituisca con quello precedente. - -Prima della pubblicazione, l’installer registra una piccola ricevuta accanto all’app con percorso di staging e identità filesystem dei bundle. Una ricevuta per destinazione resta dopo il successo e viene aggiornata al prossimo porting: se il processo termina prima del salvataggio del catalogo, il tentativo successivo riconosce l’app già pubblicata e completa il record, anche dopo la pulizia dello staging. Evita così un secondo scambio che rimetterebbe la vecchia app al suo posto. Una destinazione modificata esternamente durante lo stesso tentativo causa un errore conservativo. La vecchia app e l’eventuale sorgente copiata vengono eliminate solo dopo la pubblicazione. - -La 0.1.4.2 (in attesa di validazione manuale) mostra il tempo trascorso della fase attiva e formatta durate ed ETA in ore oltre i 60 minuti. Un timer a 1 Hz sul main run loop aggiorna la fase; il controllo di `logs/pso_offline_mac.log` gira fuori dal main thread. `PipelineArchiveProgress` legge soltanto log modificati dopo l'inizio della fase e conta i gruppi dichiarati `ready`, distinguendo `compiled` e `reused`: i file temporanei del compilatore e le chiavi delle vecchie cache non sono una prova di lavoro completato. Le dimensioni dei gruppi vengono dal log, senza assumere quelle predefinite. La stima riguarda le pipeline, non il confezionamento successivo dell'app. Formati ignoti non inventano un avanzamento; cambi di fase, annullamento e fine build invalidano i controlli ancora in corso. `PortingFailureClassifier` riconosce anche lo spazio richiesto da `pack_app.py`; il fallback sulle chiavi si applica solo alle sorgenti che le richiedono. - -`BuildRecord` conserva l’esito e la provenienza del build. `PortingFailureClassifier` riconosce i messaggi del motore e propone un’azione, presentata da `AppViewModel+Porting`. `PortingNotice` decide se notificare l’esito mentre l’app è in background. `NotificationService` gestisce la notifica di sistema e la destinazione del clic. - -Gli adattamenti di b64a5ff0 riconoscono i nuovi errori di chiavi troppo vecchie, conservando la versione firmware quando conosciuta, e il ticket comune mancante nel pacchetto. Quest'ultimo usa il kind persistito `keys` con un dettaglio identificativo: anche un launcher precedente riesce a leggere la voce durante un rollback. La UI corrente offre la spiegazione sul ticket senza proporre di sostituire le chiavi o forzare il porting. L'evento `say` con cui l'engine sposta una vecchia cache shader nel nuovo file (`PortingProgress.shaderCacheWorkMessage`) accende `PortingProgress.isUpdatingShaderCache`; `PortingETA` mostra **Updating shader cache** senza avanzare la percentuale né stimare una durata. Lo stato si azzera a stage o step successivo e al termine del build. `PortingFailureEngineTests` verifica che l'engine del pin stampi ancora quel testo. +Il percorso completo è in [flows.md](flows.md#5-costruire-un-gioco-switch-add-game). + +**Le sorgenti.** +- La preferenza **Game files** conserva solo il percorso iniziale del selettore. `AppViewModel` non la assegna a `selectedGameFolder` all'avvio: quell'assegnazione avvia una scansione. Il refresh della libreria riguarda le app installate; scegliere cartella o file in Add game avvia la lettura dei sorgenti. *Perché:* aprire la libreria non richiede di enumerare una cartella protetta come Download. I rebuild usano le sorgenti registrate sul gioco. +- `SourceSelection` tiene separati contenuti selezionati e file fisici: un pacchetto si conta e si collega una sola volta, il DLC incorporato resta incluso e la versione scelta passa con `-p`. +- `GameFileItem` conserva, se serve, layout e requisito di selezione del titolo; i vecchi JSON continuano a indicare pacchetti. Questi requisiti e la selezione NUP si verificano prima del build, anche dopo un cambio di checkout. Il programma salvato deve corrispondere al title ID del gioco; il DLC usa la base add-on dichiarata dall’applicazione. +- Le cartelle estratte si collegano nel layout `base/`, `updates/<version>/`, `dlc/<title>/0/romfs/`. Il restaging rimuove i link esclusi e i contenitori vuoti, preservando cache e originali. +- Un pacchetto illeggibile non nasconde gli altri giochi validi: la scansione tiene i risultati e segnala i file saltati. + +**Il percorso, passo per passo.** +1. **Scelta dei file.** `AddGameView` raccoglie cartelle o file. `SourceCatalog` riconosce NSP, XCI, NSZ e XCZ e raggruppa base, aggiornamenti e DLC. + - I file scelti si scandiscono e collegano uno per uno, senza includere altri pacchetti della cartella né cambiare la preferenza globale Game files. + - La bozza si azzera solo dopo la conferma del selettore. Più titoli richiedono una scelta esplicita. + - Le riletture dello stesso titolo mantengono nome, impostazioni e selezioni di update/DLC anche se cambiano gli UUID delle righe. +2. **Chiavi.** `AppViewModel+KeyCheck` chiama `KeyCheck` sulle sorgenti selezionate. Il risultato vale per la selezione corrente, quindi un controllo precedente non abilita un porting diverso. +3. **Workspace.** `WorkspaceManager` usa la cartella sorgente così com'è oppure prepara un workspace di collegamenti simbolici, riusando una cache esistente. `BuildScratch` sceglie dove mettere workspace e app temporanea: sul volume dell'app. + - Se la cartella delle app è su un altro volume locale APFS o Mac OS esteso, vanno in `.nxlibrary-build/` accanto alle app, così il disco del Mac non serve e l'installazione è una rinomina. exFAT e FAT accettano i link ma tengono gli attributi in file `._` che rompono la firma; il tipo lo dà `statfs`. + - Negli altri casi (stesso volume, exFAT, rete) restano in Application Support. + - Una cartella `workspaces` spostata dal giocatore su quel volume resta dov'è, e un workspace gestito già su quel volume conserva la sua cache. + - Un workspace gestito rimasto su un altro volume si cancella quando ne nasce uno nuovo, tranne se il gioco non è ancora costruito e punta ancora lì. + - Il controllo dello spazio misura ogni volume usato una sola volta. La pulizia all'avvio guarda anche le `.nxlibrary-build/Temp`, e cancellare un gioco o le sue sorgenti tocca solo i workspace riconosciuti da `BuildScratch.isManaged`. +4. **Ultimo controllo.** Il coordinatore ricontrolla requisiti, spazio, chiavi e destinazione. `BuildCommandBuilder` produce eseguibile, argomenti, cartella di lavoro e ambiente. +5. **Processo.** `BuildService` avvia il processo del motore e gestisce il suo gruppo di processi. Raccoglie stdout e stderr, scrive il log e tiene attiva l'asserzione contro lo stop per inattività. Se il processo non parte, chiude subito log e pipe. +6. **Avanzamento.** `BuildEventParser` decodifica il progresso JSON e `PortingProgress` lo aggrega per la UI: gli shader arrivano fino al 90%, le fasi finali occupano il restante 10%. Il modello alimenta wizard, tile, percentuale e stima del tempo. +7. **Installazione.** `BuildOutputInstaller` valida il bundle temporaneo e pubblica il gioco con `renamex_np`: `RENAME_SWAP` scambia atomicamente due app esistenti, `RENAME_EXCL` installa la prima copia senza sovrascrivere una destinazione comparsa nel frattempo. Sullo stesso volume usa direttamente il bundle pronto; fra volumi diversi prepara prima una copia nascosta accanto alla destinazione, e l'app corrente resta disponibile fino allo scambio. +8. **Installazione in attesa.** Se il gioco è aperto, o un'operazione sui salvataggi trattiene l'installazione, `PendingInstall` conserva il risultato temporaneo. `AppViewModel+PendingInstall` lo riprende quando può ottenere l'accesso. + +**Destinazione.** +- `GameAppDestination` centralizza il percorso mostrato nella review, il volume controllato per lo spazio e la destinazione effettiva. +- Le prime build usano Game apps; un rebuild conserva l'app esistente se il suo percorso è sicuro, anche dopo un cambio di cartella. Un nome già usato da un altro titolo riceve un percorso distinto. +- La destinazione si fissa prima del porting e resta tale anche nelle installazioni differite. Le installazioni richiedono che la cartella esista ancora: se si scollega o non è più scrivibile, il risultato pronto si conserva per Retry. Il packaging del frontend può creare la propria cartella di installazione. + +**Installazione fallita.** +- Se il motore termina bene con un bundle valido e fallisce solo l'installazione, `BuildResult.heldApp` conserva la build pronta, e `installationFailed` distingue questo caso dal porting fallito. Il coordinatore registra la stessa `PendingInstall` usata per i giochi aperti. +- Un dialogo Selene offre Retry e Close: Retry installa quel bundle senza riavviare il motore, Close conserva la build. Anche gli errori delle installazioni differite passano da questo dialogo, e la schermata del porting offre Retry installation finché la build resta in attesa. +- Un errore di scrittura del catalogo conserva lo stato in memoria e impedisce che una scansione immediata lo sostituisca con quello precedente. + +**Ricevuta di installazione.** +- Prima della pubblicazione l'installer scrive accanto all'app una piccola ricevuta, con il percorso di staging e l'identità filesystem dei bundle. Ne resta una per destinazione, aggiornata al porting successivo. +- Se il processo termina prima del salvataggio del catalogo, il tentativo successivo riconosce l'app già pubblicata e completa il record, anche dopo la pulizia dello staging. *Perché:* evita un secondo scambio che rimetterebbe la vecchia app al suo posto. +- Una destinazione modificata da fuori durante lo stesso tentativo causa un errore prudente. La vecchia app e l'eventuale sorgente copiata si eliminano solo dopo la pubblicazione. + +**Tempo e stime.** +- La fase attiva mostra il tempo trascorso; durate ed ETA passano alle ore oltre i 60 minuti. Un timer a 1 Hz sul main run loop aggiorna la fase, mentre il controllo di `logs/pso_offline_mac.log` gira fuori dal main thread. +- `PipelineArchiveProgress` legge soltanto log modificati dopo l'inizio della fase e conta i gruppi dichiarati `ready`, distinguendo `compiled` e `reused`. I file temporanei del compilatore e le chiavi delle vecchie cache non contano come lavoro finito. Le dimensioni dei gruppi vengono dal log, senza assumere quelle predefinite. +- La stima riguarda le pipeline, non il confezionamento dell'app che segue. Un formato sconosciuto non inventa un avanzamento. Cambi di fase, annullamento e fine build invalidano i controlli ancora in corso. +- Durante `Prewarm pipelines` la riga mostra **Preparing the first launch**: la durata precedente può non includere questo lavoro, quindi non viene usata come ETA. Fine build e annullamento rimuovono l'attività insieme allo stato di porting. + +**Esito.** +- `BuildRecord` conserva esito e provenienza del build. +- `PortingFailureClassifier` riconosce i messaggi del motore, compreso lo spazio richiesto da `pack_app.py`, e propone un'azione, presentata da `AppViewModel+Porting`. Il ripiego sulle chiavi vale solo per le sorgenti che le richiedono. +- `PortingNotice` decide se notificare l'esito mentre l'app è in background. `NotificationService` gestisce la notifica di sistema e la destinazione del clic. Il permesso si richiede quando un porting supera i controlli preliminari e parte, mai durante l’avvio o per la sola libreria Steam. Il delegate resta registrato all’avvio per aprire il gioco o l’errore da una notifica precedente. ## Avvio dei giochi e sessioni -Il flusso Play controlla operazioni di salvataggio, recuperi e installazioni in attesa. `GameRuntimeConfig` traduce le impostazioni in variabili `DM_*`. `LauncherSettingsReader` legge il contratto `launcher.json` del gioco e determina i controlli supportati, con fallback per le app più vecchie. - -`LaunchService` scrive `env.txt`, conserva le variabili non gestite tramite il merge del modello runtime e avvia il bundle con `NSWorkspace.OpenConfiguration`. Passa anche `DM_LAUNCHER=0`. `CloudSavesPreferences` applica la preferenza cloud al dominio del gioco prima del lancio. - -Off rimuove la preferenza cloud salvata dal launcher del gioco anche all’avvio. Gli override avanzati `DM_SAVE_SYNC` nei file o nell’ambiente mantengono la precedenza del motore: `SaveLocation.inspect` ne segnala l’origine e mantiene il blocco delle operazioni incompatibili con la sincronizzazione attiva. - -Nella 0.1.4.2 (in attesa di validazione manuale), Play durante la firma dell'icona apre il dialogo Selene **Preparing** con **Cancel**. `IconLaunchWait` lega la richiesta all'identità del gioco e del dialogo; la chiusura o sostituzione del dialogo revoca la richiesta. Solo l'ultimo aggiornamento icona riuscito può riprendere Play, che rilegge il gioco corrente e ripete tutti i controlli dei salvataggi e dell'app. Un errore non avvia il gioco. Cancel lascia terminare la firma, necessaria a mantenere il bundle valido. L'attesa usa `launchingGameId` e blocca anche l'aggiornamento del frontend. - -`RunningGameMonitor` confronta i bundle ID della libreria con le applicazioni in esecuzione e offre Resume e Close Game. `LaunchReadinessProbe` attende una finestra visibile del processo per chiudere la schermata di lancio. `PlaySessionStore` registra avvio, heartbeat, fine e riconciliazione delle sessioni. `ActivitySummary` aggrega la settimana, mentre `LibraryPresentation` e `GameDetailPresentation` preparano i valori delle schermate. - -## Cheats - -`CheatLocator` legge title ID, build ID e percorso secondo il contratto del launcher. `EngineAncestry` e `CheatStatus` determinano se l’app del gioco contiene il supporto ai cheats, dal commit del registro di build o, per un'app importata, da `DMCommit` nel suo `Info.plist`. `CheatFile` riproduce il parsing dei codici e dei metadati del motore. `CheatInstall` decide se un file appartiene alla build, richiede conferma o va rifiutato. - -`CheatStore` legge e modifica file, metadati, master switch e selezione `.enabled`. `AppViewModel+Cheats` espone contesto, stato della riga e informazioni per la diagnostica. `CheatsPanel` presenta lista, importazione, conferme e switch. Il gioco chiuso è una condizione delle modifiche. I file installati vengono poi letti dal motore al lancio. - -Le mod di file (RomFS) di un gioco stanno in `~/Library/Application Support/nxnative/<title ID>/mods/<cartella>/romfs`. `ModFolderScanner` trova le cartelle e il loro `romfs` (anche nel formato Atmosphère); un file lasciato lì (un archivio non estratto) compare come "non è una mod", e i file nascosti come `.DS_Store` non contano per i conflitti. `ModStore` tiene ordine e stato acceso/spento in `~/Library/Application Support/NXLibrary/mods/<TID>.json` e scrive nell'`env.txt` del gioco solo la riga `DM_ROMFS_OVERLAY` (con `EnvFileEditor`), che il motore legge al lancio: le mod accese, la prima vince, senza rebuild. Il valore non supera 4077 byte (il buffer di riga del launcher). Remove sposta la cartella nel Cestino; nessuna modifica mentre il gioco è aperto. All'apertura della pagina del gioco e del pannello, `sync()` toglie dalla riga le mod sparite; finché NX Library non ha mai gestito le mod di quel gioco non tocca una riga `DM_ROMFS_OVERLAY` scritta a mano. `AppViewModel+Mods` crea lo store e traduce gli errori; `ModsPanel` (Game options → Mods) e la fascia Mods della pagina del gioco (`DetailsModsBand`) presentano lo stato. Le mod che modificano il codice (exefs) non funzionano con il motore. - -Le mod di GameBanana compaiono nella stessa fascia (`Services/GameBanana/`). `GameBananaClient` parla con l'API pubblica (apiv11 e, per il contenuto degli archivi, la vecchia Core API), con un solo User-Agent, al massimo 4 richieste insieme e una cache su disco in `~/Library/Caches/NXLibrary/gamebanana` (ricerche 1 giorno, pagine delle mod 6 ore, contenuto degli archivi per sempre, tranne un elenco vuoto, perché GameBanana può ancora leggere un file nuovo; senza rete usa anche le voci scadute). `GameBananaMatch` abbina il gioco per nome (preferisce la voce "(Switch)", chiede quando non è sicuro) e `GameBananaMatchStore` ricorda la scelta per title ID in `Application Support/NXLibrary/gamebanana/matches.json`. `AvailableModsFinder` scorre le mod più scaricate e tiene solo quelle che `ModSupport` riconosce: un'unica cartella `romfs` per questo title ID, niente exefs, IPS o pchtxt, niente mod obsolete, private o con content rating. `ModInstaller` scarica (`ModDownload`, solo host `*.gamebanana.com`), controlla dimensione e MD5, legge e controlla l'archivio con `/usr/bin/bsdtar`, lo estrae in una cartella nascosta dentro `mods`, rifiuta percorsi `..`, symlink e hard link prima di estrarre, e passa l'albero a `ModStore.adopt`; un aggiornamento manda la versione vecchia nel Cestino e tiene posto e stato. La fascia Mods compare sia nella pagina del gioco della Spotlight sia in Details, tra Build & Sources e More like this (focus `.mods` in `SpotlightState`, `DetailsFocus.modsZone`); è una griglia di sei tessere per riga che non scorre di lato (`ModsBandLayout`: Sinistra/Destra restano nella riga, Giù scende di riga e dall'ultima passa a More like this): `ModsBandHost` tiene per entrambe mod installate, GameBanana e pannelli, e chiede a GameBanana solo quando la pagina è aperta, non mentre si scorre la riga. `GameBananaBandModel` coordina abbinamento, ricerca e installazioni per la pagina del gioco: cambiando gioco dimentica le mod del precedente, e alla prima apertura di un gioco in ogni avvio toglie gli avanzi di un'installazione interrotta (`ModStore.removeLeftoverInstalls`); `GameBananaFindModel` tiene lo stato della ricerca per nome. Le mod trovate entrano nella fascia in due gruppi al massimo: le prime cinque, accanto ad Add mods, appena ci sono, poi tutte le altre a ricerca finita; ogni gruppo aspetta (al massimo 1,2 s, `imageWait`) che la sua arte sia decodificata (`prepareImages`, cioè `GameBananaImageView.prepare`, in parallelo) ed entra con un'unica dissolvenza, e una tessera di stato spinta più in là sfuma nel nuovo posto invece di attraversare la griglia. I link presi dall'API valgono solo se sono `https` su un host GameBanana; `ModDetailPanel` e `GameBananaFindPanel` sono i pannelli sopra la pagina. Nel pannello della mod la descrizione mostra otto righe con Read more subito sotto; Read more la apre tutta (`TextScroll.windowHeight`) e i file, sotto il titolo Files, scendono. La colonna (intestazione, descrizione, file) scorre dentro il pannello quando è più alta (al massimo 980u): con rotella o trackpad, e con Su/Giù, che prima leggono a passi quello che c'è prima della riga seguente e poi spostano il fuoco e mostrano la riga intera (`TextScroll.step`); i bordi sfumano dove c'è altro e una barra sottile dice dove si è. Lo scorrimento sta in `ModsBandHost.detailScroll`, un oggetto a parte, così muoverlo ridisegna solo il pannello e non la pagina sotto. Un'installazione è per un file (`GameBananaBandModel.installFiles`): solo la sua riga ne mostra avanzamento ed esito, le altre aspettano che finisca. Ogni mod mostra autore e link alla sua pagina, e la fascia dice "Mod data provided by GameBanana". - -Lo store è la card **Mods** della Spotlight (`SpotlightCard.mods`; la sua visibilità sta in `showsModsCard`, mai in `spotlightCards`, così la versione rilasciata legge ancora le impostazioni). Giù dalla card porta il focus a `.store` e `ModStoreHost` muove `ModStoreFocus` dentro la pagina (`ModStorePage`): barra di ordinamento, Featured (dissolvenza tra le prime cinque), mod popolari dei tuoi giochi, una riga per categoria (`ModCategory`, raggruppate dai nomi delle categorie GameBanana) e una per gioco, dal più giocato di recente. `ModStoreLayout` costruisce le sezioni e dà a ognuna un'altezza fissa, così lo scorrimento non misura nulla e si disegnano solo le sezioni vicine al focus. `ModStoreModel` apre dalle copie su disco (`ModCatalogSnapshots`, `~/Library/Caches/NXLibrary/gamebanana/store`) e aggiorna in background quelle più vecchie di 6 ore, due giochi alla volta, pubblicando un gioco intero per volta; un gioco senza abbinamento si abbina solo se il nome è certo. L'ordinamento è locale sulle mod già trovate. Le immagini decodificate restano in memoria (`GameBananaImageView`, che le prepara in anticipo con `prewarm` per le prime tessere di ogni riga). La copertina della card Mods (`ModStoreLayout.coverArt`) sono le prime quattro mod del Featured per popolarità, qualunque sia l'ordinamento, coi giochi in ordine di title ID: all'avvio la si legge dalle copie su disco dei tuoi giochi ed è la stessa che trova lo store aperto. Cambia solo se lo store trova mod nuove, e solo dopo che tutte e quattro le immagini sono decodificate (`GameBananaImageView.prepare`), in un'unica dissolvenza. Lo sfondo del Featured è sfocato una volta sola, fuori dal main thread, su una copia di 240 px (`GameBananaBlur`): nessuna sfocatura gira a ogni frame. Mentre la pagina scorre, `ModStoreHost.hold(until:)` trattiene le mod trovate in background e ricostruisce le sezioni solo a pagina ferma (il log `store rebuild … ms` misura ogni ricostruzione). Sulla riga, la faccia della card è un mosaico sfocato dell'arte delle mod migliori col puzzle al centro (`ModsCardCover`, dalle copie su disco prima che lo store abbia cercato; senza arte, il gradiente Selene). Con la card selezionata lo sfondo non mostra arte: il moonlight sfuma in 1,2 s verso l'oro (`SeleneBackdrop.modsTint`), anche sopra una wallpaper, che resta ferma sotto. Colore e fondo oro sono uniform dello shader (il fondo lo disegna il passaggio di luce che gira comunque), che `MoonlightLayerView` interpola sul suo thread: la sfumatura non dipende dal main thread e il frame costa uguale; da fermo il display link gira solo per la durata della sfumatura. Lasciando la card verso un gioco, l'oro resta finché l'arte del gioco non è arrivata (`SpotlightView.modsBackdrop`), così il passaggio è uno solo. L'arte dei giochi (`SeleneArtLayer`) è una pila di `CALayer` animati nel render server: ogni nuova immagine entra sopra ciò che si vede, che resta fermo sotto finché non è entrata, così una dissolvenza interrotta riparte da ciò che è a schermo (niente salti, niente moonlight che traspare) e non scatta se il main thread è occupato. Ciò che un layer mostra durante una dissolvenza si calcola sull’orologio (`OpacityFade`, la stessa curva dell’animazione), non dal presentation layer, che per un layer aggiunto nello stesso passaggio non esiste ancora: due immagini in fila non fanno saltare la prima a piena opacità. Scorrendo veloce, i livelli che lasciano passare meno di mezzo gradino a 8 bit (`ArtStack`) escono subito, così la pila resta di pochi livelli invece di un’immagine a tutto schermo per ogni gioco passato. Se tenere l’arte del gioco precedente lo decide `BackdropArtRule` sulla selezione che il body vede, così il primo render di una nuova selezione, prima di `onChange`, non toglie l’arte per poi rimetterla. Sopra una wallpaper il moonlight oro resta montato, nascosto e fermo finché non serve, ed entra ed esce con l'uniform `presence` sul suo thread. Su una card Spotlight tiene l'arte dell'ultimo gioco (`loadHero(keepsWithoutGame:)`) senza mostrarla, così tornare allo stesso gioco non ricarica nulla. Il pannello della mod è lo stesso della fascia; `GameBananaBandModel.attach(store:)` installa nella cartella del gioco della mod. +I percorsi completi sono in [flows.md](flows.md#3-play-di-un-gioco-switch-nxnative) (Switch) e in [steam.md](steam.md) (Steam). + +**Preparazione.** +- Il flusso Play controlla operazioni sui salvataggi, recuperi e installazioni in attesa. +- `GameRuntimeConfig` traduce le impostazioni in variabili `DM_*`. `LauncherSettingsReader` legge il contratto `launcher.json` del gioco e decide i controlli supportati, con un ripiego per le app più vecchie. +- `LaunchService` scrive `env.txt`, conserva le variabili non gestite tramite il merge del modello runtime e avvia il bundle con `NSWorkspace.OpenConfiguration`, passando anche `DM_LAUNCHER=0`. +- `CloudSavesPreferences` applica la preferenza cloud al dominio del gioco prima del lancio. Off rimuove anche all'avvio la preferenza cloud salvata dal launcher del gioco. Gli override avanzati `DM_SAVE_SYNC`, nei file o nell'ambiente, mantengono la precedenza del motore: `SaveLocation.inspect` ne segnala l'origine e blocca le operazioni incompatibili con la sincronizzazione attiva. + +**Firma dell'icona in corso.** +- Play durante la firma dell'icona apre il dialogo Selene **Preparing** con **Cancel**. `IconLaunchWait` lega la richiesta all'identità del gioco e del dialogo; chiudere o sostituire il dialogo revoca la richiesta. +- Solo l'ultimo aggiornamento dell'icona riuscito può riprendere Play, che rilegge il gioco corrente e ripete tutti i controlli su salvataggi e app. Un errore non avvia il gioco. +- Cancel lascia finire la firma, che serve a mantenere valido il bundle. L'attesa usa `launchingGameId` e blocca anche l'aggiornamento del frontend. + +**Schermata di lancio.** +- `RunningGameMonitor` confronta i bundle ID della libreria con le applicazioni in esecuzione e offre Resume e Close Game. `LaunchReadinessProbe` aspetta una finestra visibile del processo per chiudere la schermata di lancio. +- La schermata ha una finestra propria, come la "launch cover" di Selene (`LaunchCoverWindow`). È senza bordi e trasparente (appare sfumando sopra la libreria), sta sopra ogni app, il Dock e la barra dei menu, su ogni Space compresi quelli a schermo intero, e non viene mai attivata. +- Quando un gioco si apre a schermo intero, la schermata scorre via con la libreria e rientra con lo Space del gioco, coprendolo finché il gioco non disegna. *Perché:* tenuta nel solo Space di Arcane, lì si vedeva lo sfondo della scrivania; il maintainer preferisce la schermata (prova con MTGA, 15 nov 2026). +- Il gioco parte dietro di lei; Steam che prende il primo piano o macOS che cambia Space restano dietro, quindi Arcane non deve mai riprendersi il primo piano. +- Play Steam accoda la richiesta fino a quando AppKit ordina e invia il pannello al server delle finestre. Arcane lascia al pannello il passaggio SwiftUI di preparazione prima che Steam possa cambiare Space. Se il pannello manca, Play procede comunque entro un secondo. Solo la richiesta ancora corrente può partire. +- La schermata d'attesa mostra artwork, logo o titolo del gioco secondo lo stile scelto, con l'angolo inferiore destro libero. +- Il movimento è quello di Selene (`LaunchMotion`), in Core Animation così resta fluido mentre il gioco o Steam si avviano: + - l'arte si avvicina piano (scala da 1,04 a 1,12 in 20 s); + - il logo entra una sola volta, poco dopo la dissolvenza della schermata (0,36 s): appare in 0,75 s mentre sale di 30 unità in 1 s, poi resta fermo. Al massimo metà larghezza e 38% dell'altezza, come Selene; + - con Riduci movimento l'arte resta ferma e il logo appare soltanto. + +**Sessioni.** `PlaySessionStore` registra avvio, heartbeat, fine e riconciliazione delle sessioni. `ActivitySummary` aggrega la settimana; `LibraryPresentation` e `GameDetailPresentation` preparano i valori delle schermate. + +## Pagina del gioco + +**Pannello Details.** +- La colonna destra della pagina del gioco, nella Spotlight e in Details, si chiude con lo stesso pannello per ogni fonte (`DetailsPanel`). Sono righe etichetta → valore con una piccola icona grigia (Developer, Publisher, Version, Size on disk, Installed in), direttamente sulla pagina, con separatori sottili e senza riquadro. +- La card Achievements, che si preme, ha un fondo trasparente al 5% (10% su hover e focus) e il bordo, senza materiale sfocato aggiuntivo. +- Sotto ci sono i link Reveal in Finder, Store page e HowLongToBeat (`DetailsLink`, `SeleneActionGrid`, focus `DetailsFocus.actionsZone` / `.actions`). +- `DetailsFacts` nel Core sceglie le righe: una riga senza valore non compare. Steam non mostra mai la versione (il build ID è tecnico) e, senza un'installazione disponibile (download in corso), mostra solo Developer e Publisher. Cartella e volume arrivano per nome visualizzato, mai come percorso. +- Lo stato tecnico (sorgenti, engine, toolchain, build bloccata) non sta sulla pagina. Rebuild, Attach sources, Open log, Saves e, senza descrizione, Search Nintendo Store stanno in Options; un problema che ferma il giocatore resta nella nota di Play. Nella pagina Details le righe vanno su due colonne. + +**Voto della critica.** +- L'ultima riga del pannello, dopo Installed in, mostra cinque stelle proporzionali, il voto originale /100 e la fonte. È una riga informativa, senza card o finestre aggiuntive, e non aggiunge azioni al focus. +- Caricamento e voto assente hanno un testo esplicito, senza fingere un voto zero. Provenienza, data del voto, ambito ed eventuale ripiego sulla copia salvata stanno nel testo accessibile e nell'aiuto. +- La media utenti IGDB usa "Voto utenti" e "Utenti · IGDB", conservando stelle, numero e posizione della riga. Le fonti sono descritte in [Artwork, metadati e voti](#artwork-metadati-e-voti). + +**Fascia Mods.** Sta tra Details e More like this: vedi [Mod](#mod). + +**More like this.** La fascia condivisa `DetailsMoreBand` mostra fino a sei giochi, dopo Mods per Switch e sotto About e Details per Steam. `MoreLikeThis` ordina per generi, sviluppatore ed editore in comune. Esclude il gioco corrente e quelli nascosti. Steam dà precedenza ai titoli Steam e cerca titoli Switch correlati quando non trova corrispondenze Steam. Usa scelte personali e metadati già disponibili, con i generi nella lingua dell'interfaccia. La cache Steam si legge all'apertura della pagina e la fascia compare solo con corrispondenze effettive. + +## Cheat + +- `CheatLocator` legge title ID, build ID e percorso secondo il contratto del launcher. +- `EngineAncestry` e `CheatStatus` decidono se l'app del gioco contiene il supporto ai cheat, dal commit del registro di build o, per un'app importata, da `DMCommit` nel suo `Info.plist`. +- `CheatFile` riproduce il parsing di codici e metadati del motore. `CheatInstall` decide se un file appartiene alla build, richiede conferma o va rifiutato. +- `CheatStore` legge e modifica file, metadati, master switch e selezione `.enabled`. `AppViewModel+Cheats` espone contesto, stato della riga e informazioni per la diagnostica. `CheatsPanel` presenta lista, importazione, conferme e switch. La pagina del gioco legge "Cheats on" all'apertura, al cambio del gioco, alla chiusura di Game options e al ritorno da Finder (`reloadCheats`), non a ogni ridisegno. +- Le modifiche richiedono il gioco chiuso. Il motore legge i file installati al lancio. + +## Mod + +**Mod locali.** +- Le mod di file (RomFS) di un gioco stanno in `~/Library/Application Support/nxnative/<title ID>/mods/<cartella>/romfs`. +- `ModFolderScanner` trova le cartelle e il loro `romfs`, anche nel formato Atmosphère. Un file lasciato lì (per esempio un archivio non estratto) compare come "non è una mod"; i file nascosti come `.DS_Store` non contano per i conflitti. +- `ModStore` tiene ordine e stato acceso/spento in `~/Library/Application Support/NXLibrary/mods/<TID>.json`. Nell'`env.txt` del gioco scrive solo la riga `DM_ROMFS_OVERLAY` (con `EnvFileEditor`), che il motore legge al lancio: le mod accese, la prima vince, senza rebuild. Il valore non supera 4077 byte, il buffer di riga del launcher. +- Remove sposta la cartella nel Cestino. Niente modifiche mentre il gioco è aperto. +- All'apertura della pagina e del pannello, `sync()` toglie dalla riga le mod sparite. Finché Arcane non ha mai gestito le mod di un gioco, non tocca una riga `DM_ROMFS_OVERLAY` scritta a mano. +- `AppViewModel+Mods` crea lo store e traduce gli errori; `ModsPanel` (Game options → Mods; `GameOptionsFiles` legge configurazione, impostazioni, cheat e mod una volta per apertura) e la fascia Mods della pagina (`DetailsModsBand`) presentano lo stato. Le mod che modificano il codice (exefs) non funzionano con il motore. + +**GameBanana** (`Services/GameBanana/`). +- `GameBananaClient` parla con l'API pubblica (apiv11 e, per il contenuto degli archivi, la vecchia Core API). Usa un solo User-Agent, al massimo 4 richieste insieme, e una cache su disco in `~/Library/Caches/NXLibrary/gamebanana`: + - ricerche 1 giorno, pagine delle mod 6 ore; + - contenuto degli archivi per sempre, tranne un elenco vuoto, perché GameBanana può ancora leggere un file nuovo; + - senza rete usa anche le voci scadute. +- `GameBananaMatch` abbina il gioco per nome (preferisce la voce "(Switch)" e chiede quando non è sicuro); `GameBananaMatchStore` ricorda la scelta per title ID in `Application Support/NXLibrary/gamebanana/matches.json`. +- `AvailableModsFinder` scorre le mod più scaricate e tiene solo quelle che `ModSupport` riconosce: un'unica cartella `romfs` per questo title ID, niente exefs, IPS o pchtxt, niente mod obsolete, private o con content rating. +- `ModInstaller` scarica con `ModDownload` (solo host `*.gamebanana.com`) e controlla dimensione e MD5. Legge e controlla l'archivio con `/usr/bin/bsdtar`, rifiuta percorsi `..`, symlink e hard link prima di estrarre, lo estrae in una cartella nascosta dentro `mods` e passa l'albero a `ModStore.adopt`. Un aggiornamento manda la versione vecchia nel Cestino e tiene posto e stato. +- I link presi dall'API valgono solo se sono `https` su un host GameBanana. Ogni mod mostra autore e link alla sua pagina, e la fascia dice "Mod data provided by GameBanana". + +**Fascia Mods della pagina.** +- Compare sia nella pagina del gioco della Spotlight sia in Details, tra Details e More like this (focus `.mods` in `SpotlightState`, `DetailsFocus.modsZone`). +- È una griglia di sei tessere per riga che non scorre di lato (`ModsBandLayout`): Sinistra e Destra restano nella riga, Giù scende di riga e dall'ultima passa a More like this. +- `ModsBandHost` tiene per entrambe le pagine mod installate, GameBanana e pannelli. In Spotlight legge le mod all'apertura della pagina del gioco. Cambiare selezione sulla riga svuota la fascia precedente senza leggere quella successiva, così la lettura delle mod resta fuori dallo scorrimento. + Le [misure dei primi cambi gioco](reviews/2026-11-18-spotlight-glide.md) mostrano il costo della lettura prima e dopo. +- Play riconcilia le cartelle delle mod prima di avviare il gioco, anche dalla riga. Se la cartella o i record non si leggono, `ModStore.sync` conserva entrambi i file di stato. La Dev mantiene il divieto di manutenzione automatica dell'overlay. +- `GameBananaBandModel` coordina abbinamento, ricerca e installazioni. Cambiando gioco dimentica le mod del precedente; alla prima apertura di un gioco in ogni avvio toglie gli avanzi di un'installazione interrotta (`ModStore.removeLeftoverInstalls`). `GameBananaFindModel` tiene lo stato della ricerca per nome. +- Le mod trovate entrano al massimo in due gruppi: le prime cinque, accanto ad Add mods, appena ci sono, poi tutte le altre a ricerca finita. Ogni gruppo aspetta (al massimo 1,2 s, `imageWait`) che la sua arte sia decodificata (`prepareImages`, cioè `GameBananaImageView.prepare`, in parallelo) ed entra con un'unica dissolvenza. Una tessera di stato spinta più in là sfuma nel nuovo posto invece di attraversare la griglia. +- Un'installazione è per un file (`GameBananaBandModel.installFiles`): solo la sua riga mostra avanzamento ed esito, le altre aspettano che finisca. + +**Pannello della mod.** +- `ModDetailPanel` e `GameBananaFindPanel` sono i pannelli sopra la pagina. +- La descrizione mostra otto righe con Read more subito sotto; Read more la apre tutta (`TextScroll.windowHeight`) e i file, sotto il titolo Files, scendono. +- La colonna (intestazione, descrizione, file) scorre dentro il pannello quando è più alta, al massimo 980 unità. Si scorre con rotella o trackpad, e con Su/Giù, che prima leggono a passi quello che c'è prima della riga seguente e poi spostano il fuoco e mostrano la riga intera (`TextScroll.step`). I bordi sfumano dove c'è altro, e una barra sottile dice dove si è. +- Lo scorrimento sta in `ModsBandHost.detailScroll`, un oggetto a parte, così muoverlo ridisegna solo il pannello e non la pagina sotto. + +**Store delle mod.** +- Lo store è la card **Mods** della Spotlight (`SpotlightCard.mods`). La sua visibilità sta in `showsModsCard`, mai in `spotlightCards`, così la versione rilasciata legge ancora le impostazioni. +- Giù dalla card porta il focus a `.store`, e `ModStoreHost` muove `ModStoreFocus` dentro la pagina (`ModStorePage`). La pagina contiene: + - una barra di ordinamento; + - Featured, con dissolvenza tra le prime cinque; + - le mod popolari dei tuoi giochi; + - una riga per categoria (`ModCategory`, raggruppate dai nomi delle categorie GameBanana); + - una riga per gioco, dal più giocato di recente. +- `ModStoreLayout` costruisce le sezioni e dà a ognuna un'altezza fissa, così lo scorrimento non misura nulla e si disegnano solo le sezioni vicine al focus. +- `ModStoreModel` apre dalle copie su disco (`ModCatalogSnapshots`, `~/Library/Caches/NXLibrary/gamebanana/store`) e aggiorna in background quelle più vecchie di 6 ore, due giochi alla volta, pubblicando un gioco intero per volta. Un gioco senza abbinamento si abbina solo se il nome è certo. L'ordinamento è locale sulle mod già trovate. +- Le immagini decodificate restano in memoria (`GameBananaImageView`, che le prepara in anticipo con `prewarm` per le prime tessere di ogni riga). +- La copertina della card (`ModStoreLayout.coverArt`) sono le prime quattro mod del Featured per popolarità, qualunque sia l'ordinamento, con i giochi in ordine di title ID. All'avvio si legge dalle copie su disco dei tuoi giochi ed è la stessa che trova lo store aperto. Cambia solo se lo store trova mod nuove, e solo dopo che tutte e quattro le immagini sono decodificate, in un'unica dissolvenza. +- Sulla riga, la faccia della card è un mosaico sfocato dell'arte delle mod migliori con il puzzle al centro (`ModsCardCover`, dalle copie su disco prima che lo store abbia cercato; senza arte, il gradiente Selene). + `AppShellState` possiede `ModStoreHost`, che Spotlight osserva: il mosaico pronto sopravvive alla navigazione. Uscire dalla home continua a chiudere il pannello e fermare lo store. + + A ogni ritorno gli snapshot vengono rivalidati rispetto agli abbinamenti GameBanana, mantenendo la cover finché la lettura finisce; un risultato vuoto la rimuove. Cambiare i title ID la invalida subito e le identità delle richieste scartano letture precedenti; una cover pubblicata dal catalogo invalida lo snapshot ancora in lettura. Gli stati transitori idle/loading del catalogo non svuotano il mosaico. + + I record Installed/Update vengono riletti a ogni apertura, con generazione separata per scartare letture precedenti a una chiusura o installazione. +- Lo sfondo del Featured si sfoca una volta sola, fuori dal main thread, su una copia di 240 px (`GameBananaBlur`): nessuna sfocatura gira a ogni frame. +- Mentre la pagina scorre, `ModStoreHost.hold(until:)` trattiene le mod trovate in background e ricostruisce le sezioni solo a pagina ferma (il log `store rebuild … ms` misura ogni ricostruzione). +- Con la card selezionata lo sfondo diventa oro: vedi [Interfaccia Selene e input](#interfaccia-selene-e-input). Il pannello della mod è lo stesso della fascia; `GameBananaBandModel.attach(store:)` installa nella cartella del gioco della mod. ## Salvataggi, backup e recupero -### Riconoscimento e anteprima - -Il flusso usa il title ID e conserva i percorsi interni del salvataggio per ogni gioco. `SaveLocation` ammette l’ID esadecimale di 16 caratteri, risolve il percorso predefinito e legge la configurazione cloud effettiva. `AppViewModel+Saves` verifica anche l’identità nel bundle installato e le preferenze del gioco. - -`RyujinxSaveFolder` riconosce `bis/user/save/<indice>`, risale dalle sottocartelle, confronta il title ID in `ExtraData0` e seleziona l’intero albero committed `0`. Le cartelle di esportazione ordinarie mantengono la propria struttura. Il tipo User/Device è una scelta separata dal nome della cartella sorgente. - -`SaveSnapshotStore.stageImport` prepara una copia temporanea vicino alla destinazione. L’anteprima contiene inventario, hash SHA-256, attributi estesi e impronta del salvataggio attuale. `SaveRestorePreview.swift` prepara allo stesso modo un ripristino da backup. Alla conferma vengono ricontrollati sorgente, staging e salvataggio attuale. - -### Copia protettiva e sostituzione - -`SaveTransaction` crea prima un backup verificato dei due slot committed, inclusa l’eventuale assenza di uno slot. Persiste poi il journal `.nxlibrary-save-transaction.json` e sostituisce ciascuna directory con staging sullo stesso volume. Usa `renamex_np(RENAME_SWAP)` per scambiare due directory esistenti e spostamenti per i casi di presenza o assenza. - -L’importazione sostituisce lo slot scelto. Il ripristino applica l’intero snapshot, compresa la presenza o assenza dei due slot. `SaveOperationGate` assegna lease per title ID, coordinando salvataggi, Play e installazioni anche quando più voci della libreria condividono lo stesso gioco. - -### Integrità e recupero - -`SaveFileIO` centralizza copie, hash, metadati, controlli dei percorsi, scritture durevoli e punti di errore sostituibili nei test. La verifica normalizza provenienza e label di accesso gestite da macOS, più il campo agente della quarantena. Confronta i metadati guest e il contenuto dei file. I manifest e i journal precedenti passano dalla stessa normalizzazione. - -All’avvio o al refresh, un journal incompleto porta al rollback del salvataggio precedente verificato. Un journal committed richiede la verifica del risultato prima della pulizia. Dati modificati esternamente o copie non verificabili mantengono il recupero bloccato e conservano gli artefatti per l’intervento. Play attende la risoluzione. - -`SavesPanel` espone apertura cartella, backup manuale, destinazione, importazione, refresh e cartella backup con data dell’ultima copia. L’anteprima From → To è in `SaveImportDetails`. Dopo ogni importazione riuscita, `SavePanelModel` pubblica un nuovo evento e la vista mostra `SeleneSuccessNotice`, che si chiude dopo tre secondi. Il timer della vista si annulla quando il pannello scompare. - -Storage → Save backups apre la cartella comune degli snapshot. Il vecchio export ZIP di Storage è stato rimosso; la creazione delle copie passa dal pannello Saves. - -### Spazio per gioco (non pubblicato, validato dal maintainer) - -Settings → Storage riusa `StorageManager.snapshot`: `GameStorageUsage` distingue app, cache e log per voce, compresi i giochi nascosti, ordinando le cache dalla più grande. `StorageSize` distingue file assenti da percorsi non leggibili o volumi scollegati. Le misure sono dimensioni logiche dei file, inclusi quelli nascosti; la visita fisica fts non segue i collegamenti interni e scarta misure incomplete in caso di errore. I percorsi canonici condivisi vengono misurati e contati una sola volta nei totali. Lo spazio libero è quello della cartella Game apps corrente e non ripiega sul disco interno se questa manca. - -La conferma per gioco conserva identità e percorso selezionati. Prima della cancellazione, il coordinatore ricontrolla la voce corrente; `StorageManager` richiede la cartella `<title ID>_build` immediatamente sotto il workspace registrato, rifiuta file ordinari e cache che siano symlink e protegge app, sorgenti e installazioni differite di tutte le voci. Un collegamento dentro la cache viene rimosso senza visitarne la destinazione. Le cache condivise sono indicate sia nella riga sia nella conferma. Non viene rimossa l'intera cartella workspace né modificato il catalogo: una ricompilazione ricrea la cache. - -Misura e pulizia girano sulla coda utility. `isCleaningStorage` blocca nuove pulizie, build e installazioni dell'updater; i giochi già installati restano avviabili. Una misura superata da cambi di libreria o destinazione viene ripetuta. Il termine della pulizia pubblica l'esito, espone eventuali errori e ricalcola le dimensioni. Le righe dei giochi hanno identità UUID stabili per mouse, tastiera e controller. Il maintainer ha confermato il funzionamento nella Dev il 9 novembre 2026; test automatici e build sostengono la verifica. - -I backup sono copie locali conservate fino alla gestione dell’utente. Sono automatici prima di importazione e ripristino, oppure manuali con Back up now. Importazione e ripristino richiedono sincronizzazione cloud effettivamente disattivata. I casi rifiutati e le verifiche eseguite sono descritti nelle sezioni Saves del README e dei test. - -## Artwork, metadati e sfondi - -Look distingue Wallpaper e Library screens. Game backgrounds è un controllo positivo: On mostra l’artwork del titolo in Spotlight e Collection, Off mantiene il wallpaper. Riusa la preferenza `keepWallpaperOnGames` invertendo soltanto il binding, senza migrazione dei dati. Details continua a usare l’artwork del gioco; il layout di avvio segue le proprie impostazioni globali. Wallpaper sizing riguarda il wallpaper e Library shade le maschere delle schermate della libreria. - -Change artwork conserva la precedenza delle scelte manuali per titolo. La riga di stato ha altezza stabile, testo breve per la ricerca e indicazione della destinazione dell’immagine; segnala Home: wallpaper quando lo sfondo della home è governato dal wallpaper globale. - -LaunchBox e SteamGridDB non entrano nella griglia automatica: ciascuno ha un riquadro **Browse online** che apre una griglia propria (`ArtworkBrowseSource`), con ricerca precompilata e modificabile, risultati per lo slot aperto, credito per immagine e X per la pagina del gioco sulla sorgente. La griglia carica solo le anteprime; il file pieno (`ArtworkCandidate.full`) si scarica alla scelta e viene ridimensionato come ogni scelta manuale. LaunchBox non ha API: ricerca e pagina gioco si leggono come TheGamesDB, e immagini e dimensioni vengono dal payload `__NUXT_DATA__`. SteamGridDB usa l’API v2 con la chiave personale dell’utente (file `0600`, mai registrata nei log). Per i giochi senza screenshot Title DB, il caricamento dei metadati (selezione o apertura del gioco) chiede una volta a LaunchBox gli screenshot Gameplay e li conserva 30 giorni (`ScreenshotFallbackStore`); le scansioni della libreria non avviano richieste. - -`NintendoStoreMetadataService`, `GameTDBStore`, Title DB e le sorgenti di artwork raccolgono descrizioni, date, generi, copertine, loghi, sfondi e screenshot. `ArtworkNames` confronta i nomi per limitare i candidati al gioco o alle sue edizioni. `ArtworkPicker` e `MetadataOptions` aggregano i risultati per i selettori. `ArtworkPicks` e `MetadataPicks` conservano le scelte manuali. - -La 0.1.4.2 prepara inoltre un resolver delle icone automatiche (`AutomaticIconResolver`, in attesa di validazione manuale e di chiarimento dell'accesso al provider secondario). Il gioco e le scelte manuali mantengono precedenza; `ArtworkStore.automaticIcon` prova Title DB e poi una corrispondenza esatta normalizzata in Switch Icon Showdown, senza confondere sequel, omonimi o edizioni. Un title ID Switch 2 da solo non identifica una Switch 2 Edition. La cache PNG resta separata da `ArtworkPicks`, con attribuzione e una sola piccola voce negativa per gioco (15 minuti). Il resolver condivide le richieste concorrenti della stessa istanza, limita dimensioni e tempi delle risposte, verifica host e immagini quadrate e consulta `robots.txt` prima del download secondario. **Al 9 novembre 2026, il sito esclude `/images/` dai crawler: il resolver non scarica le immagini di Switch Icon Showdown. Non considerare la issue #12 risolta o questa fonte operativa finché non viene chiarito un accesso consentito.** Le immagini automatiche disponibili possono riempire l'icona di un'app che non ne ha una, solo senza pick manuale e senza un esplicito Only here. Le app con icona propria rimangono intatte. Fallimenti di rete o ricerche ambigue non fanno fallire il porting. Nessun file del motore viene modificato. - -L'icona scelta in Change artwork (slot Icon, conservata a 1024 px) diventa anche l'icona dell'app del gioco in Finder e nel Dock (`AppIconWriter`, `AppViewModel+AppIcon`). Nella 0.1.4.2 (in attesa di validazione manuale) il pop-up offre **Only here** / **Use on the Mac** per ogni gioco, anche senza icona propria o non ancora costruito. `PortedGame.appIconOnMac` memorizza la scelta esplicita: false vieta la scrittura anche per NUP e dump; true la richiede quando esiste un'Icon pick; nil conserva la regola precedente (`usesPickedAppIcon` oppure assenza di icona originale) per le vecchie librerie fino alla prossima scelta. Riconciliazione e scrittura condividono `wantsPickedAppIcon`. Only here ripristina l'icona originale o la sua assenza se una personalizzata era già applicata. Automatic rimuove solo la scelta dell'immagine, conserva la destinazione esplicita (e l'opt-in legacy) e usa prima l'originale, anche dal backup durante una personalizzazione, poi l'icona estratta o quella online disponibile. La tile Icon location permette di modificare la destinazione anche senza pick. Se la ricerca non trova un sostituto, il writer ripristina l'originale o la sua assenza, senza lasciare la vecchia immagine personalizzata. La tile Automatic mostra l'anteprima risolta; lo stato distingue ricerca, firma e icona non disponibile. AppIconProgress conserva i testi condivisi fra UI e log. Dopo una build installata, inclusa un'installazione differita, l'esito della preparazione viene aggiunto al relativo log già chiuso dall'engine e al log della UI; assenza di artwork non cambia il successo della build. La riga informativa viene scritta solo dopo l'ultimo aggiornamento in coda, non per le successive modifiche manuali. Scansioni e rebuild conservano la preferenza. La scrittura crea `Resources/AppIcon.icns`, marca `Info.plist` con `NXLibraryAppIcon`, rifirma il bundle ad hoc come l'engine e verifica con `codesign --verify --deep --strict`; l'icona originale resta in `Application Support/NXLibrary/app-icons/<TitleID>/`, e ogni errore rimette i file toccati. Avviene dopo ogni build installata (la rebuild sostituisce l'app, e l'engine ricrea il pacchetto se trova file cambiati), all'avvio e quando un gioco si chiude, mai mentre il gioco gira o si costruisce; durante la firma (circa 50 secondi per un gioco di 9–12 GB) avvio e build del gioco attendono, e la riga di stato di Change artwork mostra l'avanzamento. Una scelta fatta mentre la stessa app si firma viene rieseguita alla fine, così vale l'ultima. Dopo ogni scansione della libreria `reconcileAppIcons` confronta lo stato voluto con l'app (marca `NXLibraryAppIcon`) e rimette in coda le differenze, per esempio una scelta fatta mentre l'app era stata spostata. - -`ArtworkStore` mantiene la cache immagini. `BoxArtService` risolve le copertine Switch di GameTDB. `GameArtLoader` e `SeleneHeroArt` alimentano sfondo e logo delle schermate con caricamento e cache dedicati. - -Per gli sfondi online, i parser dei provider sono in `OnlineBackgrounds.swift`. `OnlineBackgroundService` gestisce rete, progressi, miniature e crediti. `OnlineBrowser` e `OnlineTransfer`, definiti in `OnlineBrowsePanel.swift`, alimentano la griglia e l’importazione nel selettore temi. `ThemeStore` unisce palette, wallpaper inclusi e file importati. +Il percorso completo è in [flows.md](flows.md#6-importare-o-ripristinare-un-salvataggio). + +**Riconoscimento e anteprima.** +- Il flusso usa il title ID e conserva i percorsi interni del salvataggio per ogni gioco. `SaveLocation` ammette l'ID esadecimale di 16 caratteri, risolve il percorso predefinito e legge la configurazione cloud effettiva. `AppViewModel+Saves` verifica anche l'identità nel bundle installato e le preferenze del gioco. +- `RyujinxSaveFolder` riconosce `bis/user/save/<indice>`, risale dalle sottocartelle, confronta il title ID in `ExtraData0` e seleziona l'intero albero committed `0`. Le cartelle di esportazione ordinarie mantengono la propria struttura. Il tipo User/Device è una scelta separata dal nome della cartella sorgente. +- `SaveSnapshotStore.stageImport` prepara una copia temporanea vicino alla destinazione. L'anteprima contiene inventario, hash SHA-256, attributi estesi e impronta del salvataggio attuale. `SaveRestorePreview.swift` prepara allo stesso modo un ripristino da backup. Alla conferma si ricontrollano sorgente, staging e salvataggio attuale. + +**Copia protettiva e sostituzione.** +- `SaveSlot` descrive account e device, `user2`…`user8` e il file registro `users` (`save.users`). + Gli altri pezzi sono directory. Le cartelle transazionali dell’engine (`.work` / `.new`) non entrano + nell’inventario; il registro si copia come file regolare, con limite 64 KiB e senza seguirne link. +- `SaveSnapshotStore` crea un backup verificato di tutti i pezzi locali committed presenti, compresa + la loro assenza. Il manifest resta schema 1 per soli account/device e usa schema 2 per gli utenti + aggiuntivi o il registro. I vecchi backup non si riscrivono; versioni o dichiarazioni incoerenti si rifiutano. +- `SaveTransaction` prepara lo staging, salva il journal `.nxlibrary-save-transaction.json` e cambia + soltanto i pezzi dichiarati in `mutatedSlots`. Usa `renamex_np(RENAME_SWAP)` per scambiare file o + directory e spostamenti per presenza/assenza. Il registro si scambia per ultimo. +- L’importazione da cartella modifica solo User oppure Device; registro e utenti aggiuntivi restano + intatti, senza ricopiarli o scambiarli. Il restore schema 1 modifica solo i due slot storici e conserva + gli altri utenti correnti. Il restore schema 2 applica tutto il gruppo, comprese le assenze, sempre + dopo un backup di sicurezza. La conferma spiega l’ambito prima di agire. +- Il cloud dell’engine copre soltanto utente principale e device. Il pannello e le impostazioni lo + dichiarano; un backup locale completo non equivale alla sincronizzazione di tutti gli utenti. +- `SaveOperationGate` assegna lease per title ID, coordinando salvataggi, Play e installazioni anche quando più voci della libreria condividono lo stesso gioco. + +**Integrità e recupero.** +- `SaveFileIO` centralizza copie, hash, metadati, controlli dei percorsi, scritture durevoli e punti di errore sostituibili nei test. +- La verifica normalizza provenienza e label di accesso gestite da macOS, più il campo agente della quarantena. Confronta i metadati guest e il contenuto dei file. Manifest e journal precedenti passano dalla stessa normalizzazione. +- Prima e dopo ogni scambio si verificano contenuto live e originale spostato in staging; una modifica + inattesa conserva journal e artefatti. La pulizia registra l’intenzione e l’inventario verificato nel journal prima di eliminare i residui, un elemento alla volta; si riprende anche dopo una cancellazione parziale e rifiuta dati nuovi o cambiati. +- All’avvio o al refresh, un journal incompleto porta al rollback al salvataggio precedente verificato. + Il journal 1 osserva solo account/device, conservando eventuali utenti comparsi dopo l’interruzione; + il journal 2 osserva il gruppo completo. `mutatedSlots` manca nei journal storici, che conservano + l’ambito dei due slot originali. Un journal committed verifica il risultato prima della pulizia. + La recovery può a sua volta interrompersi e riprendere. Il gioco deve restare chiuso anche per lanci esterni. +- Dati modificati da fuori o copie non verificabili tengono il recupero bloccato e conservano gli artefatti per l'intervento. Play aspetta la risoluzione. + +**Pannello e backup.** +- `SavesPanel` offre: apertura della cartella, backup manuale, destinazione, importazione, refresh e cartella dei backup con la data dell'ultima copia. L'anteprima From → To è in `SaveImportDetails`. +- Dopo ogni importazione riuscita, `SavePanelModel` pubblica un evento e la vista mostra `SeleneSuccessNotice`, che si chiude dopo tre secondi; il timer si annulla quando il pannello scompare. +- I backup sono copie locali conservate finché l'utente non li gestisce. Sono automatici prima di importazione e ripristino, oppure manuali con Back up now. +- Importazione e ripristino richiedono la sincronizzazione cloud davvero disattivata. I casi rifiutati e le verifiche sono descritti nelle sezioni Saves del README e dei test. +- Storage → Save backups apre la cartella comune degli snapshot; le copie si creano dal pannello Saves. + +## Spazio su disco + +**Misura.** +- Settings → Storage e Porting → Storage usano `StorageManager.snapshot`. `GameStorageUsage` distingue app, cache e log per voce, compresi i giochi nascosti, e ordina le cache dalla più grande. +- `StorageSize` distingue file assenti da percorsi non leggibili o volumi scollegati. +- Le misure sono dimensioni logiche dei file, compresi quelli nascosti. La visita fisica fts non segue i collegamenti interni e scarta le misure incomplete in caso di errore. I percorsi canonici condivisi si misurano e si contano una sola volta nei totali. +- Lo spazio libero è quello della cartella Game apps corrente, senza ripiegare sul disco interno se questa manca. + +**Pulizia.** +- La conferma per gioco conserva identità e percorso scelti. Prima di cancellare, il coordinatore ricontrolla la voce corrente. +- `StorageManager` richiede la cartella `<title ID>_build` immediatamente sotto il workspace registrato. Rifiuta file ordinari e cache che siano symlink, e protegge app, sorgenti e installazioni differite di tutte le voci. +- Un collegamento dentro la cache si rimuove senza visitarne la destinazione. Le cache condivise sono indicate sia nella riga sia nella conferma. +- Non si rimuove l'intera cartella workspace né si modifica il catalogo: una ricompilazione ricrea la cache. + +**Esecuzione.** +- Misura e pulizia girano sulla coda utility. `isCleaningStorage` blocca nuove pulizie, build e installazioni dell'updater; i giochi già installati restano avviabili. +- Una misura superata da cambi di libreria o destinazione si ripete. A fine pulizia si pubblica l'esito, si mostrano gli eventuali errori e si ricalcolano le dimensioni. +- Le righe dei giochi hanno identità UUID stabili per mouse, tastiera e controller. + +## Artwork, metadati e voti + +**Sfondi delle schermate.** +- Look distingue Wallpaper e Library screens. Game backgrounds è un controllo positivo: On mostra l'artwork del titolo in Spotlight e Collection, Off tiene il wallpaper. Riusa la preferenza `keepWallpaperOnGames` invertendo solo il binding. +- Details usa sempre l'artwork del gioco, e la schermata di avvio segue le proprie impostazioni globali. Wallpaper sizing riguarda il wallpaper, Library shade le maschere delle schermate della libreria. + +**Fonti dell'artwork.** +- `NintendoStoreMetadataService`, `GameTDBStore`, Title DB e le sorgenti di artwork raccolgono descrizioni, date, generi, copertine, loghi, sfondi e screenshot. +- `ArtworkNames` confronta i nomi per limitare i candidati al gioco o alle sue edizioni. `ArtworkPicker` e `MetadataOptions` aggregano i risultati per i selettori; `ArtworkPicks` e `MetadataPicks` conservano le scelte manuali. +- `ArtworkStore` tiene la cache delle immagini. `BoxArtService` risolve le copertine Switch di GameTDB. `GameArtLoader` e `SeleneHeroArt` alimentano sfondo e logo delle schermate. + +**Change artwork.** +- Le scelte manuali per titolo hanno la precedenza. La riga di stato ha altezza stabile, testo breve per la ricerca e l'indicazione di dove va l'immagine; segnala Home: wallpaper quando lo sfondo della home dipende dal wallpaper globale. +- LaunchBox e SteamGridDB non entrano nella griglia automatica: ciascuno ha un riquadro **Browse online** con una griglia propria (`ArtworkBrowseSource`). La ricerca è precompilata e modificabile, i risultati sono per lo slot aperto, ogni immagine ha il suo credito e X apre la pagina del gioco sulla sorgente. +- La griglia carica solo le anteprime. Il file pieno (`ArtworkCandidate.full`) si scarica alla scelta e si ridimensiona come ogni scelta manuale. +- LaunchBox non ha API: ricerca e pagina del gioco si leggono come TheGamesDB, e immagini e dimensioni vengono dal payload `__NUXT_DATA__`. SteamGridDB usa l'API v2 con la chiave personale dell'utente (file `0600`, mai nei log). +- Per i giochi senza screenshot Title DB, caricare i metadati (selezione o apertura del gioco) chiede una volta a LaunchBox gli screenshot Gameplay e li conserva 30 giorni (`ScreenshotFallbackStore`). Le scansioni della libreria non avviano richieste. + +**Icone automatiche.** +- `AutomaticIconResolver` riempie l'icona di un'app che non ne ha una, solo senza scelta manuale e senza un esplicito Only here. Le app con un'icona propria restano intatte. +- `ArtworkStore.automaticIcon` prova Title DB e poi una corrispondenza esatta normalizzata in Switch Icon Showdown, senza confondere sequel, omonimi o edizioni. Un title ID Switch 2 da solo non identifica una Switch 2 Edition. +- La cache PNG è separata da `ArtworkPicks`, con attribuzione e una sola piccola voce negativa per gioco (15 minuti). Il resolver condivide le richieste concorrenti, limita dimensioni e tempi delle risposte, verifica host e immagini quadrate e consulta `robots.txt` prima del download secondario. +- Switch Icon Showdown esclude `/images/` dai crawler, quindi il resolver non scarica le sue immagini (stato in [validation.md](validation.md)). +- Fallimenti di rete o ricerche ambigue non fanno fallire il porting. Nessun file del motore viene modificato. + +**Icona dell'app del gioco.** L'icona scelta in Change artwork (slot Icon, conservata a 1024 px) diventa anche l'icona dell'app del gioco in Finder e nel Dock (`AppIconWriter`, `AppViewModel+AppIcon`). +- **La scelta.** + - Il pop-up offre **Only here** / **Use on the Mac** per ogni gioco, anche senza icona propria o non ancora costruito. + - `PortedGame.appIconOnMac` memorizza la scelta esplicita: false vieta la scrittura (anche per NUP e dump), true la richiede quando c'è una scelta Icon, nil applica la regola delle vecchie librerie (`usesPickedAppIcon` oppure assenza dell'icona originale) fino alla prossima scelta. Riconciliazione e scrittura condividono `wantsPickedAppIcon`. + - Only here ripristina l'icona originale, o la sua assenza, se era già applicata una personalizzata. + - Automatic rimuove solo la scelta dell'immagine e conserva la destinazione. Usa prima l'originale (anche dal backup durante una personalizzazione), poi l'icona estratta o quella online. Se non trova un sostituto, il writer ripristina l'originale o la sua assenza, senza lasciare la vecchia immagine personalizzata. + - La tile Icon location cambia la destinazione anche senza una scelta. La tile Automatic mostra l'anteprima risolta; lo stato distingue ricerca, firma e icona non disponibile. +- **La scrittura.** + - Crea `Resources/AppIcon.icns`, marca `Info.plist` con `NXLibraryAppIcon`, rifirma il bundle ad hoc come l'engine e verifica con `codesign --verify --deep --strict`. + - L'icona originale resta in `Application Support/NXLibrary/app-icons/<TitleID>/`; ogni errore rimette a posto i file toccati. + - Avviene dopo ogni build installata (la rebuild sostituisce l'app), all'avvio e quando un gioco si chiude, mai mentre il gioco gira o si costruisce. + - Durante la firma (circa 50 secondi per un gioco di 9–12 GB) avvio e build del gioco aspettano, e la riga di stato di Change artwork mostra l'avanzamento. Una scelta fatta mentre la stessa app si firma si riesegue alla fine, così vale l'ultima. +- **Log e riconciliazione.** + - `AppIconProgress` tiene i testi condivisi fra UI e log. Dopo una build installata, anche differita, l'esito si aggiunge al log della build già chiuso dall'engine e al log della UI; l'assenza di artwork non cambia il successo della build. La riga si scrive solo dopo l'ultimo aggiornamento in coda. + - Scansioni e rebuild conservano la preferenza. Dopo ogni scansione `reconcileAppIcons` confronta lo stato voluto con l'app (marca `NXLibraryAppIcon`) e rimette in coda le differenze. + +**Change metadata** (`ChangeMetadataView`). Il selettore propone, per descrizione, generi, sviluppatore, editore e data, i valori delle fonti disponibili per nxnative e Steam. +- **Comportamento del selettore.** + - Caricare le proposte non modifica `MetadataPicks`, `SteamPersonalizations` o i dati dello store. A decide solo il campo in anteprima, Automatic rimuove l'override, Write your own resta disponibile. + - Le descrizioni mantengono la lingua originale e lo dicono nel sottotitolo. Non si aggiungono artwork né sostituzioni automatiche. + - Il valore adottato è una copia personale, non un abbonamento alla fonte: compare una sola volta in "La tua scelta", con la spunta. Le righe delle fonti restano alternative, senza spunte multiple quando condividono lo stesso testo. Salvataggio e rimozione conservano il focus per identità della riga. + - Le righe hanno identità per fonte e alternativa, non per testo scaricato, quindi caricamento, disponibilità e cambio di campo non ricreano la lista. Sono dichiarati campo assente, risultato ambiguo, valore uguale ad Automatic, copia salvata e fonte non disponibile. + - Le righe senza azione non mostrano A Choose. Un errore permette Retry anche dal controller, senza doppie richieste. Ogni fonte aggiorna solo le sue righe, e una risposta si ignora se la query è cambiata. Il focus resta sulla scelta corrente quando arrivano nuove righe e torna ad Automatic se la scelta sparisce, senza aprire il campo di testo. + - `SeleneExpandableText` conserva estratto (240 caratteri) e testo completo alla stessa larghezza: `Layout` risolve subito la geometria finale e SwiftUI anima frame e dissolvenza. *Perché:* interpolare le misure dentro `Layout` sposterebbe il bersaglio di `scrollTo` mentre si chiude la riga precedente. Espansione e scroll usano la stessa curva, con allineamento iniziale per leggere il titolo delle descrizioni lunghe; Riduci movimento li disattiva. Vale solo per i metadati: gli altri `SeleneOptionRow` non cambiano. `scripts/check_metadata_text_layout.swift` verifica fuori schermo altezze, cambio di contenuto e destinazioni dello scroll. +- **LaunchBox e TheGamesDB** sono alternative nello stesso selettore per i giochi già gestiti. + - La ricerca usa titolo, edizione e piattaforma, non il negozio; lo Steam ID aiuta dove è supportato ma non è necessario. GameTDB e Title DB restano fonti Nintendo. + - Si leggono su richiesta una ricerca e una scheda pubblica per database, con parser separati e cache di sole proposte, senza scaricare l'intero Metadata.zip né duplicare un catalogo di immagini. I parser verificano anche la scheda finale, rifiutano le ambiguità e non eliminano parole di edizione. + - Mac ha la precedenza su PC/Windows: una proposta PC è dichiarata come tale e non fornisce una falsa data Mac. + - `DatabaseMetadataService` ha due istanze esplicite, ognuna con cache separata per la query pubblica e al massimo quattro ricerche attive. Lettori della stessa query condividono il lavoro; uscire dall'ultimo lettore annulla la richiesta senza salvare un'assenza. + - Pagine fino a 2 MiB, cache fino a 256 KiB per proposta. Host e percorsi sono vincolati, cookie e redirect disabilitati; errori HTTP e corpi inattesi non diventano metadati. + - Dati validi durano sette giorni, assenze e ambiguità un giorno. Un errore conserva la proposta precedente come copia salvata e non crea una cache negativa; Retry forza un nuovo tentativo senza cambiare i valori personali. La cache sta dentro `metadata` ed è compresa nei conteggi e nella pulizia delle informazioni del negozio. + - `LaunchBoxArt.searchURL` genera direttamente la forma canonica in minuscolo, così si evita il redirect 301. + - Se IGDB è configurato, un suo nome canonico verificato può affinare la ricerca pubblica, senza inviare account, percorsi o attività. +- `OnlineArtwork.find` riceve la piattaforma della richiesta. TheGamesDB cerca Mac OS (37), poi PC (1), oppure Switch (4971) / Switch 2 (5021). La scheda finale deve confermare titolo e piattaforma prima di proporre immagini, senza prendere il primo omonimo. LaunchBox e TheGamesDB sono attribuiti in About. +- Le vecchie assenze di copertina Switch 2 si riprovano con un'identità del resolver distinta, conservando le immagini salvate e le assenze Switch valide. + +**Voti della critica.** `CriticRatingService.preferred` ordina i risultati: prima la critica IGDB (con credenziali), poi la critica Wikidata, infine la media utenti IGDB. Un voto pubblico della critica prevale quindi su una media utenti, anche se arriva per prima. +- **Wikidata.** + - `WikidataRatings` verifica nome o alias esatti (anche il campo `match` degli alias), il tipo videogioco e l'eventuale ID Steam. Per Steam prova prima P1733, l'ID pubblico esatto, verificato di nuovo nelle dichiarazioni dell'entità. Le query tolgono soltanto i simboli ™/®/©, conservando sequel ed edizioni. + - Abbinamenti ambigui o ID contrastanti non pubblicano un voto. + - Seleziona solo medie /100 documentate di OpenCritic, Metacritic o CriticDB. Preferisce la piattaforma corrispondente, altrimenti un voto senza piattaforma dichiarata. Non prende il voto Windows per macOS, non converte percentuali di raccomandazione e non fa medie fra fonti. +- **Servizio Wikidata.** `CriticRatingService` interroga solo l'API pubblica Wikidata, senza chiavi, cookie o scraping. + - Serializza e unisce le richieste, limita dimensione e durata e sospende le richieste dopo un errore. + - La cache `ratings/wikidata` del profilo corrente dura sette giorni per un voto e un giorno per un'assenza verificata; offline conserva il dato con la sua data. La data di scaricamento resta distinta da quella del voto. + - Cambiare gioco annulla il lettore e impedisce di pubblicare un risultato precedente. Niente viene scritto nel catalogo, nei dati Steam o nei giochi. +- **IGDB (facoltativo)**, in Settings → Online services. + - **Credenziali.** + - Il dialogo chiede Client ID e Client Secret dell'applicazione Twitch personale, in cinque passi brevi con i campi del portale, il requisito email/2FA e un link diretto alla registrazione. Controlla la connessione prima di salvare e si può annullare anche durante la verifica. Tastiera e controller della pagina sotto sono sospesi. + - Search trova IGDB, About contiene l'attribuzione, e nel bundle non c'è nessuna credenziale condivisa. + - `IGDBCredentialsStore` conserva le credenziali solo nel profilo corrente, in `credentials/igdb.json` con modo 0600, dentro una cartella `credentials` riportata a 0700, esclusa dall'importazione Dev. Non passano da `AppSettings`, UserDefaults, log o URL. + - Il Client Secret va nel corpo del POST a Twitch; solo il token derivato e il Client ID raggiungono IGDB. I token stanno in memoria, si rinnovano a scadenza o una sola volta dopo 401 e non si scrivono su disco. + - **Client.** `IGDBClient` è l'unico accesso Twitch/IGDB per voti e metadati: host e endpoint vincolati, redirect e cookie rifiutati, una coda seriale fino a otto lavori con distanza fra le richieste, limiti di dimensione e durata, annullamento e messaggi senza il corpo del server. *Perché:* separare autenticazione e rete dai servizi evita di duplicare token e limiti. + - **Voti.** + - `IGDBRatingService` preferisce `aggregated_rating` e `aggregated_rating_count`, valida solo con almeno 3 recensioni (`IGDBRatings.minimumCriticReviews`). Altrimenti usa `rating` e `rating_count` come media utenti esplicita, mai `total_rating`, che è un dato misto. + - Nome o alias e piattaforma devono corrispondere, oppure l'ID Steam deve essere verificato su `external_games` con `external_game_source.name`. La console deriva da `PortedGame.isSwitch2`, come Details, e distingue `switch` (IGDB 130) da `switch2` (IGDB 508; Wikidata Q122761124), senza mai allargare il filtro alle due console insieme. La console fa parte della chiave di entrambe le cache. + - La media IGDB è del gioco, non di un port specifico, e conserva questo ambito. + - `CriticRating` distingue provenienza IGDB e Wikidata, e con `audience` critica da utenti (nil nelle vecchie cache vuol dire critica). `CriticRating.isValid` applica lo stesso minimo di 3 recensioni, quindi le cache con 1–2 recensioni si richiedono di nuovo. Le vecchie assenze IGDB senza versione si riprovano una volta. Togliere IGDB esclude anche i suoi voti utenti. + - La cache IGDB è per client pubblico e identità del gioco, senza segreti o token, e conserva offline il voto datato. Configurare o rimuovere il provider invalida richieste e token e ridisegna la riga tramite una revisione posseduta da `IGDBSettings`. + - **Metadati.** + - `IGDBMetadataParser` usa le stesse regole di nome, alias e piattaforma dei voti. Per Steam verifica `external_games.uid` e la fonte Steam; zero risultati permettono il ripiego per nome, un'identità ambigua non si indovina. + - Le aziende sono qualificate dai flag developer/publisher, non dalla semplice presenza nell'elenco. Una data richiede la piattaforma corrispondente e il formato `YYYYMMDD`: una data Windows non diventa Mac, e un anno o un mese non diventano un giorno inventato. + - `IGDBMetadataService` conserva solo la proposta e l'identità verificate, per client pubblico e query, in `metadata/igdb`: sette giorni per i dati, uno per assenze o ambiguità. Gli errori non diventano assenze in cache, e i dati salvati restano disponibili offline con un avviso. Risposte tardive o di credenziali rimosse non si pubblicano. +- **Download a blocchi.** I download di Wikidata, IGDB, LaunchBox/TheGamesDB e Steam passano da `BoundedDownload`, che conserva i blocchi ricevuti da URLSession invece di leggere un byte alla volta. Limiti di dimensione, rifiuto dei redirect e annullamento restano gli stessi. + +Prove e misure di queste scelte: [docs/reviews/2026-11-16-ratings-metadata-evidence.md](reviews/2026-11-16-ratings-metadata-evidence.md). + +**Sfondi online.** +- I parser dei provider sono in `OnlineBackgrounds.swift`. `OnlineBackgroundService` gestisce rete, progressi, miniature e crediti. +- `OnlineBrowser` e `OnlineTransfer`, in `OnlineBrowsePanel.swift`, alimentano la griglia e l'importazione nel selettore dei temi. `ThemeStore` unisce palette, wallpaper inclusi e file importati. +- Impostazioni rapide → Theme mantiene due passaggi: colori con anteprima viva, poi sfondo. Il focus si muove nella griglia delle palette e si ferma ai suoi bordi; A applica la palette e continua allo sfondo. L’anteprima usa il renderer animato quando il movimento è consentito. ## Interfaccia Selene e input -`SeleneCanvas` scala il canvas 1920×1080 nello spazio disponibile. `SeleneCanvasEnvironment` espone unità e font alle viste. `SeleneTheme` ricava colori e curve di animazione dalla palette. `MaterialIcon` elenca i glifi, mentre `SeleneFonts` registra il font e li rende in SwiftUI. - -I componenti condivisi in `Views/Components` disegnano righe, switch, pill, focus, suggerimenti dei tasti, dialoghi e conferme. L'anello e il riflesso della tile selezionata (`SeleneTileRing`, `SeleneShine`) girano in Core Animation (`TileMotionLayers`): curve e campioni stanno in `TileMotion`, il bagliore è disegnato una volta da SwiftUI (`ImageRenderer`) e poi solo dissolto, così a schermo fermo l'app non ridisegna nulla tra un frame e l'altro. Con Reduce motion l'anello resta il disegno SwiftUI fermo. `SeleneBackdrop` combina gradiente, wallpaper e sfondo animato. `MoonlightRenderer` e `MoonlightShaders` rendono la componente Metal dell’interfaccia. `LiveBackdrop` usa AVFoundation per i video in loop. - -`GameControllerService` produce `GamepadAction` e riconosce i simboli dei tasti. La shell assegna l’input al livello attivo. `ButtonPrompts` esclude i segnaposto costituiti soltanto da forme, comprese varianti come `capsule.portrait.fill`, e usa in quel caso i simboli della marca riconosciuta; conserva glifi significativi come `circle.circle` e `square.circle`. `HoldDetector` e i modelli di focus rendono verificabili mapping e navigazione. `SoundEffectService` risolve i cue tramite `SeleneImporter` e applica le impostazioni di volume e attivazione. - -La preferenza Riduci movimento unisce l’impostazione dell’app a quella di sistema. Le viste consumano `seleneReduceMotion`, insieme agli altri valori dell’ambiente Selene. +**Canvas, temi e componenti.** +- `SeleneCanvas` scala il canvas 1920×1080 nello spazio disponibile, e `SeleneCanvasEnvironment` espone unità e font alle viste. `SeleneTheme` ricava colori e curve di animazione dalla palette. `MaterialIcon` elenca i glifi; `SeleneFonts` registra il font e li rende in SwiftUI. +- I componenti condivisi in `Views/Components` disegnano righe, switch, pill, focus, suggerimenti dei tasti, dialoghi e conferme. Quando usarli è in [conventions.md](conventions.md#3-una-schermata-o-un-pannello-selene). + +**Suggerimenti dei tasti.** +- Le barre `SeleneHintsBar` stanno a 32 unità Selene dal fondo (`SeleneBottomScrim.hintsBottom`). I simboli sono da 30 unità; solo Q/E e i corrispondenti LB/RB accanto ai filtri Achievements sono da 22, con area cliccabile di 30×36. Il margine sinistro aggiuntivo è 18. +- Le schermate con la barra in un VStack riservano lo spazio nel layout. Spotlight e Achievements riservano invece una fascia trasparente di 84 unità e tengono il focus sopra la sfumatura inferiore. +- In Details la barra è ancorata alla finestra: il contenuto sparisce prima dei comandi, e le fasce in focus salgono insieme alla barra. La stessa posizione vale per le opzioni, il visualizzatore di screenshot e le schermate Home. + +**Movimento.** +- L'anello e il riflesso della tessera selezionata (`SeleneTileRing`, `SeleneShine`) girano in Core Animation (`TileMotionLayers`). Curve e campioni stanno in `TileMotion`; il bagliore si disegna una volta con SwiftUI (`ImageRenderer`) e poi si dissolve soltanto, così a schermo fermo l'app non ridisegna nulla tra un frame e l'altro. Con Riduci movimento l'anello resta il disegno SwiftUI fermo. +- Un blocco che scorre per un offset animato passa da `GlideGroup` (`geometryGroup`, macOS 14): pagina Spotlight, pagina del gioco, lista Achievements, pannello Mod, riga Collection. *Perché:* SwiftUI trasmette l'offset a ogni elemento, e un'altra animazione nello stesso momento (una dissolvenza, un ventaglio, un'immagine che arriva) ne cambiava i tempi, così testi, icone e stelle scivolavano a velocità diverse. Il gruppo risolve lo scorrimento una volta per tutto il blocco, e un nuovo blocco che scorre deve usarlo. Su macOS 13 il blocco scorre senza gruppo. +- La preferenza Riduci movimento unisce l'impostazione dell'app a quella di sistema. Le viste la leggono da `seleneReduceMotion`, insieme agli altri valori dell'ambiente Selene. + +**Sfondo.** +- `SeleneBackdrop` combina gradiente, wallpaper e sfondo animato. Dentro la shell dichiara una `SeleneBackdropRequest` (stile, pausa, Mods e opacità); una sola istanza nella shell conserva il renderer attraverso i cambi di pagina. Le pagine continuano a possedere artwork e maschere. `ShellBackdropCover` assegna la precedenza a Setup, benvenuto e scelta tema: gli strati inferiori restano montati e caldi con opacità minima ma senza input, quelli superiori rimangono visibili. Il blur di opzioni/Add game/Console si applica anche al backdrop condiviso. Senza richiesta si conserva il frame e si ferma il movimento; fuori dalla shell il componente disegna autonomamente. La shell pubblica anche la palette completa in `SeleneBackdropStyle`: un cambio di soli colori invalida il valore condiviso anche con lo stesso wallpaper e la stessa card. Sfondo, superficie Metal e maschere leggono questo snapshot, evitando di aspettare un altro evento della pagina. `MoonlightRenderer` e `MoonlightShaders` rendono la parte Metal; `LiveBackdrop` usa AVFoundation per i video in loop. + - **Arcane** (ID storico `selene`) mantiene il blu classico come predefinito, con il gradiente radiale originale `0x102A5C` → `0x03081A`. Il fallback mantiene il gradiente lineare storico `0x17244A` → `0x0C142C` → `0x05080F`. **Arcane Crystal** (`arcane-crystal`) dispone fili diagonali; **Arcane Flow** (`arcane-flow`) usa curve più ampie. Entrambi mantengono soltanto filamenti e una luce diffusa tenue, senza piani o fasci luminosi. Il metadato opzionale `moonlight` della palette seleziona `MoonlightSurface`; palette senza metadato o con valore sconosciuto restano classiche. Nessuna nuova preferenza: il selettore e Look salvano lo stesso `colorThemeID`. + - I filamenti sono funzioni analitiche nello stesso passaggio Metal della luce: nucleo luminoso antialias di circa un pixel fisico, fili secondari più deboli ed estremi sfumati. Due onde viaggianti piegano le curve lungo la loro lunghezza, invece di spostare un bordo rigido; la forma di base varia su120/140s e i bagliori intorno a100–120s. Nei soli temi alternativi i dischi sfocati grandi sono attenuati per lasciare leggibili i fili. Rosa a sinistra e ciano a destra cambiano di pochi livelli RGB su180s (`MoonlightChromatics` condiviso col fallback), senza attraversare lo spettro. Nessuna immagine o video: il movimento appartiene alle superfici. + - Le particelle sono sempre morbide, senza un selettore: due stili quasi indistinguibili non giustificano una scelta in più. Il decoder ignora l’eventuale campo storico `particleStyle`, senza modificare le altre preferenze, e non lo riscrive. + - Colore e particelle avanzano con l’orologio del display link esistente, senza timer SwiftUI. Background motion spento e Riduci movimento tengono fermo l’orologio; il fallback senza Metal resta statico. Gli altri temi mantengono la loro palette. Le uniform interpolano superficie, variante Flow, tint e presenza; la cache dei campioni fermi comprende gli stessi valori. Le regole di pausa, Riduci movimento e passaggio all’artwork restano condivise nel percorso esistente. Senza Metal il ripiego mantiene soltanto bagliori statici nei colori locali. + - Nella Dev, la categoria locale `backdrop-transition` registra creazione e prima presentazione di ogni renderer, oltre all’apertura di Settings e allo stato del fullscreen iniziale. Non registra input o dati del giocatore. + - Le misure GPU fuori schermo e i loro limiti sono nella [nota del 17 novembre](reviews/2026-11-17-arcane-moonlight.md). +- **Arte dei giochi.** `SeleneArtLayer` è una pila di `CALayer` animati nel render server. + - Ogni nuova immagine entra sopra ciò che si vede, che resta fermo sotto finché la nuova non è entrata. Così una dissolvenza interrotta riparte da ciò che è a schermo (niente salti, niente moonlight che traspare) e non scatta se il main thread è occupato. + - Ciò che un layer mostra durante una dissolvenza si calcola sull'orologio (`OpacityFade`, la stessa curva dell'animazione), non dal presentation layer, che per un layer aggiunto nello stesso passaggio non esiste ancora. *Perché:* altrimenti due immagini in fila fanno saltare la prima a piena opacità. + - Scorrendo veloce, i livelli che lasciano passare meno di mezzo gradino a 8 bit (`ArtStack`) escono subito, così la pila resta di pochi livelli. + - Se tenere l'arte del gioco precedente lo decide `BackdropArtRule` sulla selezione che il body vede, così il primo render di una nuova selezione, prima di `onChange`, non toglie l'arte per poi rimetterla. + - Su una card Spotlight tiene l'arte dell'ultimo gioco senza mostrarla (`loadHero(keepsWithoutGame:)`), così tornare allo stesso gioco non ricarica nulla. +- **Card Mods.** + - Con la card selezionata lo sfondo non mostra arte: il moonlight sfuma in 1,2 s verso l'oro (`SeleneBackdrop.modsTint`), anche sopra una wallpaper, che resta ferma sotto. + - Colore e fondo oro sono uniform dello shader, che `MoonlightLayerView` interpola sul suo thread: la sfumatura non dipende dal main thread e il frame costa uguale. Da fermo il display link gira solo per la durata della sfumatura. + - Lasciando la card verso un gioco, l'oro resta finché l'arte del gioco non è arrivata (`SpotlightView.modsBackdrop`), così il passaggio è uno solo. + - Sopra una wallpaper il moonlight oro resta montato, nascosto e fermo finché non serve, ed entra ed esce con l'uniform `presence` sul suo thread. + +**Input e suoni.** +- `GameControllerService` produce `GamepadAction` e riconosce i simboli dei tasti. La shell dà l'input al livello attivo. +- `AppShellView.nativeDialogOwnsInput` dà precedenza a un alert in attesa (`alertMessage`), a `NSApp.modalWindow`, alla sheet nella finestra key o allegata alla finestra key/main. Controller, tastiera e disponibilità dei menu condividono questo controllo; la tastiera controlla anche la finestra dell'evento. Il controller scarta l'azione prima di inoltrarla a qualunque schermata o dialogo interno. *Perché:* il controller non attraversa i monitor `NSEvent` che già cedono la tastiera ai dialoghi nativi. `run_review.py` esegue il routing reale con stati sintetici, compreso il ritorno ai comandi dopo la chiusura. +- `ButtonPrompts` esclude i segnaposto fatti solo di forme, comprese varianti come `capsule.portrait.fill`, e usa in quel caso i simboli della marca riconosciuta; conserva i glifi significativi come `circle.circle` e `square.circle`. +- `HoldDetector` e i modelli di focus rendono verificabili mapping e navigazione. +- `SoundEffectService` risolve i cue tramite `SeleneImporter` e applica volume e attivazione. ## Dati su disco -I percorsi sono relativi alla home dell’utente. `Application Support/NXLibrary` corrisponde a `~/Library/Application Support/NXLibrary`. +I percorsi sono relativi alla home. `Application Support/NXLibrary` è `~/Library/Application Support/NXLibrary`; la Dev usa la radice del suo profilo (`AppData`). | Percorso | Contenuto e proprietario | |---|---| -| `Application Support/NXLibrary/library.json` e `.bak` | Catalogo e ultima copia valida, gestiti da `LibraryStore`. | +| `Application Support/NXLibrary/library.json` e `.bak` | Input del formato precedente, conservati intatti dopo la conversione da `CatalogStore`. | +| `Application Support/NXLibrary/catalog.json` e `.bak` | Catalogo comune e copia valida, gestiti da `CatalogStore` attraverso `CatalogRepository`. | | `Application Support/NXLibrary/settings.json` | Impostazioni globali, gestite da `AppSettingsStore`. | | `Application Support/NXLibrary/play-sessions.json` | Sessioni e tempi di gioco, gestiti da `PlaySessionStore`. Array semplice delle ultime 200 sessioni, leggibile anche dalle versioni precedenti. | | `Application Support/NXLibrary/play-sessions-totals.json` | Tempo e ultima partita delle sessioni oltre le 200, per gioco: `totalDuration(for:)` e `lastPlayed(for:)` li sommano alle sessioni recenti. | | `Application Support/NXLibrary/keys/prod.keys` | Chiavi importate da `KeyStore`, con permessi `0600`. | -| `Application Support/NXLibrary/app-sizes.json` | Cache dimensioni dei bundle. | +| `Application Support/NXLibrary/credentials/igdb.json` | Credenziali IGDB personali (`0600`, cartella `0700`), escluse dall'importazione Dev. | +| `Application Support/NXLibrary/app-sizes.json` | Cache delle dimensioni dei bundle. | | `Application Support/NXLibrary/workspaces/` e `Temp/` | Collegamenti alle sorgenti, workspace e app temporanee dei porting, quando l'app va sul volume del Mac (o su un volume che non accetta link simbolici). | -| `Application Support/NXLibrary/artwork/` | Cache immagini, copertine, screenshot e miniature online. | -| `Application Support/NXLibrary/metadata/` | Cache dei metadati dello store. | +| `Application Support/NXLibrary/artwork/` | Cache di immagini, copertine, screenshot e miniature online. | +| `Application Support/NXLibrary/metadata/` | Cache dei metadati dello store e delle proposte di IGDB, LaunchBox e TheGamesDB. | +| `Application Support/NXLibrary/ratings/` | Cache dei voti (Wikidata, IGDB). | | `Application Support/NXLibrary/artwork-picks/` e `metadata-picks.json` | Scelte manuali di immagini e campi. | +| `Application Support/NXLibrary/app-icons/<TitleID>/` | Icona originale dell'app del gioco, conservata da `AppIconWriter`. | | `Application Support/NXLibrary/SeleneImports/` | Suoni, wallpaper, video e relativi crediti importati. | | `Application Support/NXLibrary/SaveBackups/<TID>/` | Snapshot datati, manifest e copie protettive. | -| `Application Support/NXLibrary/Logs/<TID>.log` | Log di porting costruito dall’app. | -| `~/Library/Application Support/nxnative/<TID>/` | `env.txt`, `save`, eventuale `save_device`, cheats e dati runtime del motore. | +| `Application Support/NXLibrary/Logs/<TID>.log` | Log del porting costruito dall'app. | | `Application Support/NXLibrary/mods/<TID>.json` | Ordine, stato e origine GameBanana delle mod di un gioco, gestiti da `ModStore`. | | `Application Support/NXLibrary/gamebanana/matches.json` | Pagina GameBanana scelta per ogni gioco, gestita da `GameBananaMatchStore`. | -| `~/Library/Caches/NXLibrary/gamebanana/` | Cache delle risposte e delle immagini di GameBanana. | +| `~/Library/Caches/NXLibrary/gamebanana/` | Cache delle risposte e delle immagini di GameBanana, comprese le copie dello store. | +| `~/Library/Application Support/nxnative/<TID>/` | `env.txt`, `save`, eventuale `save_device`, `save_user2`…`save_user8`, registro `save.users`, cheat, mod e dati runtime del motore. | | `~/Library/Logs/nxnative/<TID>.log` | Log del gioco avviato. | -| `<Game apps>/<nome>.app` | Prima installazione del gioco; default `~/Applications`. I rebuild aggiornano l'app nella sua posizione esistente. | +| `<Game apps>/<nome>.app` | Prima installazione del gioco; default `~/Applications`. I rebuild aggiornano l'app nella sua posizione. | | Accanto al gioco: `.nxlibrary-install-<hash>.json` | Ultima ricevuta di installazione per quel percorso, gestita da `BuildOutputInstaller`. | | Accanto al gioco: `.nxlibrary-incoming-<hash>.app` | Preparazione temporanea quando il bundle pronto si trova su un altro volume. | | `<Game apps>/.nxlibrary-build/workspaces/<TID>/` e `Temp/` | Workspace e app temporanee dei porting quando la cartella delle app è su un altro volume (`BuildScratch`). | -| `UserDefaults` del bundle NX Library | Percorsi ricordati, stato Setup, override toolchain e cache di alcuni controlli. | - -Nel repository, `.build/` contiene gli output SwiftPM. `work/Runtime` è il runtime preparato per il packaging, `work/release` contiene i prodotti di release e `dist/` il DMG di sviluppo. Queste cartelle sono escluse da Git. Il catalogo descrive i file versionati separatamente dai dati personali creati durante l’uso. - -## Aggiornamenti e distribuzione - -Il controllo manuale da menu macOS e About presenta `AppUpdateDialog` sia durante la richiesta sia al suo esito: versione corrente, nuova release con note scorrevoli, errore con Retry o progresso. Il dialogo ha priorità sull’input sottostante; frecce/controller scorrono le note e selezionano le azioni, Escape chiude. La chiusura durante il download lascia il trasferimento in corso. Una richiesta manuale durante un controllo automatico impedisce una successiva seconda offerta automatica per la stessa risposta. Le note mostrano la propria versione anche quando la candidata è più recente dell’ultima release pubblica. - -`AppUpdateState` descrive gli stati nel Core. `AppUpdate.mayInstall` impone versione più recente e copia installabile: i controlli manuali di copie di sviluppo o in sola lettura leggono le release, senza autorizzarne la sostituzione. Il gate viene verificato prima del download e prima dell’installazione, insieme ai controlli e ai lease già esistenti. Il motivo di attesa viene passato al dialogo come valore, così la chiusura di un gioco aggiorna il pulsante Update. +| `UserDefaults` del bundle Arcane | Percorsi ricordati, stato del Setup, override della toolchain e cache di alcuni controlli. | +I dati Steam di Arcane sono descritti in [steam.md](steam.md#dati-su-disco-di-arcane). -`UpstreamChecker` consulta il changelog del motore e `UpstreamCopy` lo presenta. L’adozione di un nuovo commit passa dalla procedura manuale in [AGENTS.md](../AGENTS.md) e dalle [note di upgrade](upstream-upgrades/README.md). +Nel repository, `.build/` contiene gli output SwiftPM, `work/Runtime` il runtime preparato per il packaging, `work/release` i prodotti di release e `dist/` il DMG di sviluppo. Queste cartelle sono escluse da Git. -`AppUpdater` coordina gli aggiornamenti di NX Library da `Bium23/NxLibrary`, senza autenticazione. Le regole di versione, requisiti, digest, identità del bundle e installazione sono in `AppUpdate`. Le copie di sviluppo non si sostituiscono. `AppUpdateDownload` limita il trasferimento alla dimensione dichiarata e agli host HTTPS di GitHub. `validate_update.py` verifica struttura e percorsi, poi estrae contando i dati effettivamente decompressi tramite il Python incluso; prima della sostituzione vengono controllati versione, marker, identificativo e firma del bundle. La firma ad hoc protegge il contenuto sigillato ma non identifica autonomamente il manutentore. La prova interattiva A → B resta necessaria. - -Prima dell’installazione, l’updater acquisisce un’esclusione globale dal `SaveOperationGate`: aspetta operazioni save/Play/installazioni attive e impedisce nuovi ingressi durante sostituzione e riavvio. Un recupero bloccato senza I/O attivo non impedisce l’aggiornamento. Il coordinatore esclude nuovi porting mentre l’app viene aggiornata. - -`bundle_runtime.sh` prepara Python e strumenti da `runtime.lock`, controlla gli hash e sistema i riferimenti Mach-O con `relink_macho.py`. `build_app.sh` compila e confeziona il bundle, risorse, plist e firma ad hoc. Il suo parametro di destinazione permette di preparare una copia temporanea prima della sostituzione della copia installata. +## Aggiornamenti e distribuzione -`release.sh` richiede albero pulito e runtime pronto, imposta versione e marker di release e crea ZIP e DMG. `--publish` abilita tag e pubblicazione GitHub con autorizzazione esplicita dell’utente. Il repository contiene anche `build_dmg.sh` per confezionare un bundle già costruito. +**Dialogo degli aggiornamenti.** +- Il controllo manuale (menu macOS e About) presenta `AppUpdateDialog` durante la richiesta e al suo esito: versione corrente, nuova release con note scorrevoli, errore con Retry, oppure avanzamento. +- Il dialogo ha priorità sull'input sottostante: frecce e controller scorrono le note e scelgono le azioni, Escape chiude. Chiuderlo durante il download lascia il trasferimento in corso. +- Una richiesta manuale durante un controllo automatico impedisce una seconda offerta automatica per la stessa risposta. Le note mostrano la propria versione anche quando la candidata è più recente dell'ultima release pubblica. + +**Regole di installazione.** +- `AppUpdateState` descrive gli stati nel Core. `AppUpdate.mayInstall` richiede una versione più recente e una copia installabile: i controlli manuali di copie di sviluppo o in sola lettura leggono le release senza autorizzarne la sostituzione. +- Il gate si verifica prima del download e prima dell'installazione, insieme ai controlli e ai lease esistenti. Il motivo dell'attesa arriva al dialogo come valore, così la chiusura di un gioco aggiorna il pulsante Update. + +**Download e verifica.** +- `AppUpdater` coordina gli aggiornamenti da `Bium23/NxLibrary`, senza autenticazione. Le regole di versione, requisiti, digest, identità del bundle e installazione sono in `AppUpdate`. +- La release si accetta solo se lo zip `NXLibrary-<versione>.zip` sta nel percorso di download di quel repository. `AppUpdate.successorRepository` (oggi `nil`) nomina un repository che può sostituirlo con un altro nome: GitHub reindirizza lì la vecchia API delle release, quindi anche i suoi asset sono accettati. +- `AppUpdateDownload` limita il trasferimento alla dimensione dichiarata e agli host HTTPS di GitHub. +- `validate_update.py` verifica struttura e percorsi, poi estrae contando i dati davvero decompressi tramite il Python incluso. Prima della sostituzione si controllano versione, marker, identificativo e firma del bundle. +- La firma ad hoc protegge il contenuto sigillato ma non identifica da sola il maintainer. +- `AppUpdate.install` copia il candidato in una cartella esclusiva `.arcane-update.*` sul volume di destinazione e scambia i bundle con `RENAME_SWAP`, mantenendo il nome corrente. Le copie già presenti accanto all’app non vengono usate né rimosse. L’app precedente va nel Cestino; se il Cestino fallisce, resta nella cartella esclusiva. Un errore prima dello scambio pulisce soltanto il candidato posseduto; la cartella finale si rimuove solo se vuota. *Perché:* nomi prevedibili come `(new)` e `(old)` possono appartenere al giocatore. +- Prima dell'installazione l'updater ottiene un'esclusione globale dal `SaveOperationGate`: aspetta che finiscano le operazioni in corso su salvataggi, Play e installazioni e impedisce nuovi ingressi durante sostituzione e riavvio. Un recupero bloccato senza I/O attivo non impedisce l'aggiornamento. Il coordinatore esclude nuovi porting mentre l'app si aggiorna. + +**Nome del file alla chiusura.** +- Lo zip dell'aggiornamento contiene sempre `NXLibrary.app`, perché le copie precedenti leggono quel nome, e l'installazione tiene il nome del file corrente. Il nome Arcane arriva al file alla chiusura. +- `AppDelegate.applicationWillTerminate` chiede ad `AppBundleRename.target` se rinominare. Lo fa solo una copia release, non traslocata, che si chiama `NX Library.app`, in una cartella scrivibile senza un `Arcane.app` accanto. +- Non rinomina mentre una build, un aggiornamento o un'operazione sui salvataggi usa ancora il bundle (`AppDelegate.isBusy`, impostato da `AppShellState`), né quando un riavvio è in programma (`AppDelegate.relaunchScheduled`, da Restart app e dall'updater): l'aiuto che riapre l'app usa il percorso attuale. +- *Perché alla chiusura:* rinominare un bundle in esecuzione lascia `Bundle.main` sul percorso vecchio fino al riavvio. Il Dock segue la rinomina nella stessa cartella ([sonda](reviews/2026-11-17-dock-rename-probe.md)). +- Un errore va nel log e non ferma la chiusura. La copia Dev non si rinomina mai: la ricostruisce `build_app.sh`. + +**Changelog dell'engine.** `UpstreamChecker` consulta il changelog del motore e `UpstreamCopy` lo presenta. L'adozione di un nuovo commit segue la procedura manuale di [AGENTS.md](../AGENTS.md) e delle [note di upgrade](upstream-upgrades/README.md). + +**Script di build e release.** +- `bundle_runtime.sh` prepara Python e strumenti da `runtime.lock`, controlla gli hash e sistema i riferimenti Mach-O con `relink_macho.py`. +- `build_app.sh` compila e confeziona bundle, risorse, plist e firma ad hoc, poi installa il bundle completo attraverso `BuildOutputInstaller` dopo firma e verifica. Il suo parametro di destinazione permette di preparare una copia temporanea prima di sostituire quella installata. +- `release.sh` richiede un albero pulito e il runtime pronto, esegue suite Swift e tutti i controlli `Tests/CatalogAppChecks/run_*.py` senza UI, imposta versione e marker di release e crea ZIP e DMG. `--publish` abilita tag e pubblicazione su GitHub, solo con autorizzazione esplicita dell'utente. `build_dmg.sh` confeziona un bundle già costruito. +- Il runtime e i contenuti versionati si verificano con `scripts/check_publication.py`. ## Verifica e manutenzione -`NX_TEST_ENGINE_REPO` permette al controllo dei messaggi del motore di usare un checkout separato; il valore esplicito non valido produce un errore. Durante una revisione, `NX_TEST_ENGINE_COMMIT` seleziona l'hash completo del candidato prima di cambiare il pin dell'app; senza override il test controlla sempre il pin. La suite Core usa fixture sintetiche, directory temporanee, runner e confini I/O sostituibili. Copre modelli, persistenza, sorgenti, chiavi, contratti CLI, processi, installazione, lancio, UI state, artwork, cheats e transazioni dei salvataggi. Il [catalogo dei test](file-map.md#test-e-fixture) indica la responsabilità di ogni file. +**Test.** +- La suite Core usa fixture sintetiche, cartelle temporanee, runner e confini I/O sostituibili. Copre modelli, persistenza, sorgenti, chiavi, contratti CLI, processi, installazione, lancio, stato della UI, artwork, cheat e transazioni dei salvataggi. Il [catalogo dei test](file-map.md#test-e-fixture) indica la responsabilità di ogni file. +- `run_nup_programs.py` verifica i convertitori reali UI/persistenza e gli argomenti NUP; con uno snapshot + immutabile dell’engine verifica anche il probe Python su un contenitore sintetico. `run_save_restart.py` + arresta e riavvia processi distinti nei checkpoint di sostituzione e recovery, conservando backup e + dati non committed; non apre finestre né accede ai salvataggi del giocatore. +- `NX_TEST_ENGINE_REPO` permette al controllo dei messaggi del motore di usare un checkout separato; un valore esplicito non valido è un errore. Durante una revisione, `NX_TEST_ENGINE_COMMIT` seleziona l'hash completo del candidato prima di cambiare il pin; senza override il test controlla sempre il pin. ```bash DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test bash scripts/build_app.sh -codesign --verify --deep --strict "$HOME/Applications/NXLibrary.app" +codesign --verify --deep --strict "$HOME/Applications/Arcane Dev.app" ``` -Le prove interattive dell’app e dei giochi sono eseguite dall’utente. Gli agenti svolgono controlli sul codice, test automatici e build/installazione, secondo `AGENTS.md`. +**Prove interattive.** Le esegue l'utente; gli agenti svolgono controlli sul codice, test automatici e build/installazione, secondo `AGENTS.md`. -Per una modifica, partire dall’area nel catalogo, seguire il collegamento al file e leggere i chiamanti reali. Aggiornare la descrizione quando cambia la responsabilità di un file. I piani datati registrano il lavoro svolto, mentre questa guida e il catalogo descrivono l’organizzazione corrente. +**Per una modifica.** Parti dall'area in questa guida e nel catalogo dei file, segui il collegamento al file e leggi i chiamanti reali. Segui la ricetta di [conventions.md](conventions.md) e aggiorna i documenti come dice la sua sezione 10. diff --git a/docs/conventions.md b/docs/conventions.md new file mode 100644 index 00000000..b8fee229 --- /dev/null +++ b/docs/conventions.md @@ -0,0 +1,127 @@ +# Arcane — come si costruisce + +Questa guida dice **dove va una cosa nuova e come si scrive**, partendo da quello che il codice fa già. Prima di scrivere codice nuovo, trova qui la ricetta che corrisponde e segui il file d'esempio indicato. Se nessuna ricetta va bene, non inventarne una in silenzio: proponila al maintainer e, una volta approvata, aggiungila qui. + +Gli altri documenti: +- [architecture.md](architecture.md): come funziona ogni area; +- [flows.md](flows.md): i percorsi completi, dall'input all'effetto; +- [file-map.md](file-map.md): un file per riga; +- [validation.md](validation.md): cosa ha validato il maintainer. + +## 1. Dove va il codice + +| Cosa | Dove | Perché | +|---|---|---| +| Modelli, regole, parsing, persistenza, rete, processi, decisioni di focus e di layout calcolabili | `Sources/NXLibraryCore` | Si prova con XCTest senza finestre. | +| Viste SwiftUI, integrazione AppKit, controller, coordinamento degli store | `Sources/NXLibrary` | Dipende dal Core, mai il contrario. | +| Testi mostrati all'utente | `NXLibraryCore/Resources/Localizable.xcstrings` | Un solo catalogo per le sei lingue. | +| Test | `Tests/NXLibraryCoreTests`; prove senza finestre dei corpi reali delle viste in `Tests/CatalogAppChecks`; controlli del pacchetto in `Tests/PublicationChecks` | — | + +Regole: +- **Una decisione sta nel Core se si può scrivere senza SwiftUI.** Esempi: + - quali righe mostra il pannello Details: `DetailsFacts`; + - dove si sposta il focus: `SpotlightState`, `DetailsFocus`, `ModStoreFocus`; + - la geometria di una riga: `SpotlightRowGeometry`, `GridListLayout`. + + La vista disegna e traduce l'input. +- **Non far crescere `AppViewModel`.** Uno stato che appartiene a una sola schermata o a un solo pannello ha il suo modello. Esempi: `SavePanelModel`, `SetupCheckModel`, `ModStoreHost`, `AchievementsScreenModel`, `CatalogSourcesModel`. Le estensioni `AppViewModel+…` servono solo a collegare il coordinatore a un servizio del Core. +- **Un solo writer per ogni file su disco.** Il catalogo lo scrive solo `CatalogRepository`, le impostazioni solo `AppSettingsStore`, le sessioni solo `PlaySessionStore`, le mod di un gioco solo `ModStore`. + +## 2. Una fonte di giochi (Steam oggi, CrossOver e altre domani) + +Esempio completo: Steam, documentato in [steam.md](steam.md). + +- Il gioco entra nel catalogo comune come `CatalogGame` con il **suo payload reale** (`SteamCatalogGame`, `PortedGame`). Non si costruisce mai un gioco di un'altra fonte finto. +- Cosa offre la pagina lo dice `CatalogGamePresentation`: installazioni, operazioni supportate, `CatalogLaunchTarget`. L'ordine delle Opzioni comuni sta in `CatalogGameOptions`. Una fonte dichiara cosa sa fare; non aggiunge schermate parallele. +- I comandi di una fonte ricevono solo il suo payload: i comandi Switch prendono `PortedGame`, quindi non possono partire da un gioco Steam. +- La lettura avviene su un worker annullabile, con limiti di dimensione e di cartelle. Il risultato porta una generazione o un ticket, e un risultato superato non si pubblica (`SteamCatalogReconciler`, `CatalogSourcesModel`). +- Un'assenza non è una cancellazione. Un disco scollegato, una scansione parziale o un titolo ambiguo conservano la voce, gli UUID e le scelte personali. +- I file di altre applicazioni si leggono e non si scrivono mai. Le letture protette passano da `InstallationFileSnapshot` e `InstallationDirectorySnapshot`. +- La fonte è facoltativa: se è spenta non si legge nulla e il resto si comporta come prima. +- **La funzione sta nell'app, il formato sta nella fonte.** Salvataggi, mod e cheat sono una sola schermata ciascuno; la fonte dice dove sono i file e come si leggono. + +## 3. Una schermata o un pannello Selene + +Esempi: `AchievementsScreen` con `AchievementsScreenModel` (schermata intera), `SavesPanel` con `SavePanelModel` (pannello), `ModStorePage` con `ModStoreHost` (pagina che scorre). + +- **Misure in unità del canvas** 1920×1080: `canvas.u(…)` da `SeleneCanvasEnvironment`, mai punti fissi. Colori, curve e font vengono da `SeleneTheme` e `SeleneFonts`, le icone da `MaterialIcon`. +- **Componenti condivisi prima di tutto** (`Views/Components`): + - `SeleneOptionRow`, `SeleneSettingsRow`; + - `SelenePillButton`, `SeleneSwitch`, `SeleneValueChip`; + - `SeleneConfirmDialog`, `SeleneSuccessNotice`; + - `SeleneHintsBar`, `GamePrimaryActions`, `DetailsPanel`. + + Un componente nuovo nasce solo se nessuno di questi va bene. +- **Focus nel Core, input in un file `+Input`.** Lo stato del focus è un tipo del Core con i suoi test. La vista ha un'estensione `…+Input.swift` che traduce tastiera, mouse e controller in azioni sul modello. +- **Priorità dell'input:** menu e dialoghi nativi vengono prima delle schermate dell'app. La shell (`AppShellView`, `nativeDialogOwnsInput`) sospende il controller prima del routing e condivide il controllo con tastiera e menu. Nell'app dà l'input al livello più alto: un pannello sopra la pagina sospende l'input della pagina sotto. +- **Suggerimenti dei tasti:** `SeleneHintsBar` alla posizione condivisa `SeleneBottomScrim.hintsBottom` (32 unità dal fondo). I simboli vengono da `ButtonPrompts`. +- **Movimento:** + - un blocco che scorre di un offset animato passa per `GlideGroup`; + - i loop continui (anelli, bagliori, sfondi) girano in Core Animation o Metal, mai con timer SwiftUI a 30 fps; + - Riduci movimento si legge da `seleneReduceMotion` e ferma tutto ciò che si muove da solo. +- **Suoni:** `SoundEffectService` con i cue Selene esistenti. +- **Testi:** frasi brevi e semplici, nelle sei lingue (sezione 7). + +## 4. Un'impostazione + +Esempio: qualunque riga di `SettingsCatalog`. + +1. Il valore sta in `AppSettings`, con un default. La decodifica è **compatibile**: un file vecchio senza il campo prende il default, e un valore sconosciuto torna ad Automatic. +2. La riga si dichiara in `SettingsCatalog` (`row`/`action`) con identità stabile, sezione, titolo e descrizione. Così compare in **Search** e in **Changed** e torna al valore iniziale con il reset del gruppo. +3. Va nella sezione giusta di `SettingsSection` / `SettingsSidebarGroup`. Una sezione di piattaforma contiene solo impostazioni che agiscono sui giochi di quella piattaforma. Ogni impostazione sta in un solo posto. +4. Le preferenze fuori da `AppSettings`, come cloud o percorsi, compaiono in Changed attraverso il catalogo. Le credenziali non passano mai da `AppSettings` (sezione 6). + +## 5. Un file su disco + +Esempi: `AppSettingsStore`, `CatalogStore`, `PlaySessionStore`, `ModStore`. + +- **Percorsi solo da `AppData`** (`AppData.supportRoot`, `AppData.cacheRoot`, `AppData.preferences`), così la copia Dev resta separata dalla release. Un file nuovo che la Dev deve ricevere va aggiunto alla lista dichiarata di `DevelopmentProfileImporter`; credenziali e token non si copiano. +- **Formato con versione** e lettura compatibile con i file vecchi; un campo nuovo è sempre facoltativo. +- **Scrittura sicura:** si scrive su un file temporaneo nella stessa cartella e lo si sostituisce in un passo solo. Per un file importante si tiene una copia valida (`.bak`) e si rilegge il candidato prima di pubblicarlo (`CatalogStore`). + + Oggi ogni store scrive per conto suo: non esiste un aiuto condiviso. Un nuovo store segue `CatalogStore` per i dati importanti e `AppSettingsStore` per le preferenze. +- **Un file illeggibile non si sovrascrive in silenzio:** si conserva e si segnala con un dialogo e Retry. Mai una libreria vuota automatica. +- **Eliminare:** si sposta nel Cestino, salvo nei casi documentati. Esempi: la cache di build di un gioco, le cartelle temporanee riconosciute da `BuildScratch.isManaged`. + +## 6. Rete, chiavi e dati privati + +Esempi: `BoundedDownload`, `GameBananaClient`, `IGDBClient`, `SteamMetadataService`. + +- Ogni download passa da `BoundedDownload`, con limite di dimensione, redirect rifiutati e annullamento. Gli host sono fissati in un elenco. +- Richieste coalescenti, un numero massimo in contemporanea, cache su disco con una durata, e uso della copia salvata senza rete. Un errore non diventa un "non trovato" salvato in cache. +- Un risultato che arriva tardi (dopo un cambio di gioco o di lingua, o dopo la rimozione delle credenziali) non si pubblica. +- **Chiavi e credenziali** in un file con modo `0600`, dentro una cartella `0700`. Non vanno mai in log, URL, `AppSettings` o `UserDefaults`. `DiagnosticsReport` toglie la home e i valori che sembrano chiavi. +- Nessun dato personale o privato va in rete, e nessun dato dei giochi altrui viene scritto. + +## 7. Testi e lingue + +- Ogni testo dell'interfaccia passa da `L10n.text` / `L10n.format` e sta in `Localizable.xcstrings` con en, it, fr, de, es e pt-BR. +- Le identità restano in inglese e non si traducono: rawValue salvati, rowID, variabili `DM_*`, eventi dell'engine. +- Le viste leggono la lingua da `nxAppLocale`, così un cambio di lingua non ricrea stato o focus. +- Controllo: `scripts/check_localizations.py`, che verifica copertura, segnaposto e plurali. + +## 8. Lavoro in background e stato + +- Il lavoro su file e rete gira fuori dal thread principale; ciò che cambia l'interfaccia si pubblica sul main actor. +- Un `body` e l'initializer di una vista non leggono file: si ridisegnano a ogni cambio della shell. Ciò che viene dal disco si legge quando la pagina si apre o quando può cambiare (`GameOptionsFiles`, `GameDetailView.reloadCheats`), e un'assenza si ricorda (`GameIconProvider`). +- Ogni lavoro annullabile porta un'identità (generazione, ticket, UUID del gioco). Il risultato si applica solo se l'identità è ancora quella attuale. +- Le operazioni su un gioco che si escludono a vicenda (salvataggi, Play, installazioni, aggiornamento dell'app) passano da `SaveOperationGate`. +- Niente ritardi a tempo, ridisegni forzati o errori nascosti per far "sembrare" che funzioni (AGENTS.md). + +## 9. Test + +- Prima il test che fallisce, poi il codice (TDD). Per un bug: prima la causa, poi un test che la riproduce. +- I dati sono sintetici, in cartelle temporanee, con dipendenze sostituibili: `CommandRunner`, trasporti di rete iniettati, `SaveTestHome`, `SteamTestSupport`, `CatalogTestSupport`. Niente file reali dell'utente, niente chiavi o ROM. +- Si prova il comportamento, non il mock. +- Comandi in [development.md](development.md#verification). I test non sostituiscono la validazione del maintainer. + +## 10. Documentazione + +Ogni modifica aggiorna, nello stesso commit: +- la riga del file in [file-map.md](file-map.md) e il totale; +- la sezione della sua area in [architecture.md](architecture.md), o il documento dell'area (come [steam.md](steam.md)); +- il percorso in [flows.md](flows.md), se cambia un flusso; +- [validation.md](validation.md), se il maintainer ha validato qualcosa o se c'è una cosa nuova da validare; +- questa guida, se nasce una ricetta nuova approvata. + +I documenti descrivono il **presente**. Lo storico ("prima faceva…") va nel [CHANGELOG](../CHANGELOG.md), nelle note datate (`docs/upstream-upgrades/`, `docs/reviews/`) o nella cronologia git. Il **perché** di una scelta resta invece accanto alla scelta, in una frase. diff --git a/docs/development.md b/docs/development.md index d911e2f9..c27af3be 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # Development and releases -This guide covers building NX Library itself. For app setup, game preparation and daily use, start with the [user guide](../README.md). Read [AGENTS.md](../AGENTS.md) before changing engine integration or installation behaviour. +This guide covers building Arcane itself. For app setup, game preparation and daily use, start with the [user guide](../README.md). Read [AGENTS.md](../AGENTS.md) before changing engine integration or installation behaviour. ## Development prerequisites @@ -19,12 +19,12 @@ From the repository root: ~~~sh bash scripts/bundle_runtime.sh bash scripts/build_app.sh -codesign --verify --deep --strict "$HOME/Applications/NXLibrary Dev.app" +codesign --verify --deep --strict "$HOME/Applications/Arcane Dev.app" ~~~ -The default destination is `~/Applications/NXLibrary Dev.app`, named **NX Library Dev**: the copy every change is tested in, kept apart from the released **NX Library** (`~/Applications/NX Library.app`, installed from GitHub and updated by itself), which a development build never replaces. Both use the bundle ID `local.nxlibrary`, so they share the library, keys and settings, and macOS runs only one at a time: quit one before opening the other. `build_app.sh` compiles the Release configuration, creates the bundle in staging, includes resources and notices, ad-hoc signs and verifies it, then installs it through the same atomic installer used by the application. It does not launch the app. +The default destination is `~/Applications/Arcane Dev.app`, named **Arcane Dev**: the copy every change is tested in, kept apart from the released copy (`~/Applications/NX Library.app`, installed from GitHub and updated by itself), which a development build never replaces. On the launcher-development branch, Dev uses bundle ID `local.nxlibrary.development`, app data under `~/Library/Application Support/NXLibrary-Development`, a separate cache root and preference domain. At its first launch it prepares an independent, one-time copy of selected launcher data; games and build caches are not copied, and credential files are excluded. Close the previous launcher copy before that initial import. The held 0.1.4.3 branch retains its previously validated behavior. `build_app.sh` compiles the Release configuration, creates the bundle in staging, includes resources and notices, ad-hoc signs and verifies it, then installs it through the same atomic installer used by the application. It does not launch the app. -A development copy carries the version in progress from the `VERSION` file at the repository root and shows it as "(development build)" in Settings; it has no release marker, so it never offers or installs app updates. `scripts/release.sh <version>` sets the released version itself and refuses to run unless `VERSION` already says that version. After a release, raise `VERSION` to the next version being worked on. +A development copy carries the version in progress from the `VERSION` file at the repository root and shows it as "(Dev · Launcher)" on this development line in Settings; it has no release marker, so it never offers or installs app updates. `scripts/release.sh <version>` sets the released version itself and refuses to run unless `VERSION` already says that version. After a release, raise `VERSION` to the next version being worked on. An alternate destination can be supplied without replacing the installed development copy: @@ -32,7 +32,7 @@ An alternate destination can be supplied without replacing the installed develop bash scripts/build_app.sh /tmp/NXLibrary-Review.app ~~~ -A plain development app uses bundle ID `local.nxlibrary`, defaults to version `0.1.0` and has no release marker. It never installs its own updates. +A plain development app uses bundle ID `local.nxlibrary.development`, takes its version from `VERSION` and has no release marker. It never installs its own updates. ### Bundled runtime @@ -59,8 +59,17 @@ python3 scripts/check_publication.py python3 scripts/check_localizations.py python3 -m unittest discover -s Tests/PublicationChecks DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_notices.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_review.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_startup_recovery.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_theme.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_nested_bundles.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_artwork_return.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_source_access.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_entrance.py +DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer python3 Tests/CatalogAppChecks/run_achievement_scroll.py bash scripts/build_app.sh -codesign --verify --deep --strict "$HOME/Applications/NXLibrary Dev.app" +codesign --verify --deep --strict "$HOME/Applications/Arcane Dev.app" ~~~ When reviewing an engine upgrade in a separate checkout, set `NX_TEST_ENGINE_REPO` to that checkout's absolute path for `swift test`. The engine-fragment regression reads the application's pin and checks it in that repository; an invalid explicit path fails. Without the variable it uses `~/nxnative`, skipping only when that default checkout is absent. This allows verification without fetching into or changing the engine used by the installed app. @@ -73,13 +82,19 @@ python3 scripts/check_publication.py --runtime work/Runtime The Swift suite covers persistence, sources, keys and permissions, CLI contracts, process output and cancellation, compatibility gates, installation and retries, launch configuration, presentation state, artwork, cheats and save recovery. Publication regressions use temporary repositories and synthetic content. Tests must never require copyrighted game content or real keys. +The nested-bundle check creates tiny Mach-O fixtures with signed data bundles and relative Resources links. It exercises the real installer, icon writer and codesign, including signature rollback, interrupted publication and rejection of modified nested data. Its forced copy branch does not establish compatibility with a real external filesystem or game build. + +The artwork-return check compiles the real tile views, loading tasks and retained Mods host with generated images and isolated preferences. It records which image the first body selects after view recreation, without rendering or opening a window, and checks pick removal, Steam app updates, Mods badges after external removal and changed GameBanana matches. Network is forbidden in the Mods fixture. + The latest complete Swift verification on 2 November 2026 passed **774 tests**, including first-run skip/resume, setup navigation, explicit title choice, source-selection restoration, chosen-folder installation/discovery and preserving ready builds after destination disconnection. The earlier publication verification passed **15 Python checks**; the development-app bundle passed signature verification, and a headless check exercised a real public GitHub download, its redirect and rejection of a mismatched size. These checks do not establish that the interactive update or a game worked. This is dated evidence, not a promise about future changes. See the [test catalog](file-map.md#test-e-fixture). For manual setup checks on an existing account, use **Settings → Start-up → Open Setup**: Continue opens Your games without resetting the library. Check file-picker cancellation, Back, Open library and source review. A fresh account additionally verifies Skip persistence and resuming an interrupted first setup. Interactive checks remain the user's responsibility; agents do not launch the UI. +`release.sh` runs the same `CatalogAppChecks/run_*.py` set after the Swift suite and stops if any check fails. These checks use synthetic inputs without opening windows; the NUP engine-snapshot probe remains optional. + ### Continuous integration -The [Checks workflow](../.github/workflows/ci.yml) runs publication checks and their regressions, Swift tests, Release compilation, development-app packaging and signature verification on the `xcode-27` runner. Pull requests from forks stay off that runner and receive the hosted publication checks instead. The checkout action is pinned, repository permissions are read-only and credentials are not retained by checkout. It does not publish releases or run the UI, games or engine builds. +The [Checks workflow](../.github/workflows/ci.yml) runs publication checks and their regressions, Swift tests, all `Tests/CatalogAppChecks/run_*.py` headless regressions, Release compilation, development-app packaging and signature verification on the `xcode-27` runner. Pull requests from forks stay off that runner and receive the hosted publication checks instead. The checkout action is pinned, repository permissions are read-only and credentials are not retained by checkout. It does not publish releases or run the UI, games or engine builds. The engine-log-fragment test skips when `~/nxnative` is absent. A private CI run completed with **703 Swift tests reported: 702 passed and one skipped**, plus five Python checks. It verifies frontend packaging without the bundled game runtime; it does not replace the runtime check or the engine compatibility gate. @@ -87,7 +102,7 @@ The engine-log-fragment test skips when `~/nxnative` is absent. A private CI run Interactive app and game checks are performed by the user. Agents must not use computer-use or other UI automation. Compilation, unit tests and signature verification cannot establish that the interface or a game works. -Before a game/toolchain combination is described as working, the user checks **Settings → Engine**, builds a real game and launches it to a visible screen. Record the engine and Metal versions and whether the untested override was used. +Before a game/toolchain combination is described as working, the user checks **Settings → Setup and engine**, builds a real game and launches it to a visible screen. Record the engine and Metal versions and whether the untested override was used. ## Engine upgrades @@ -107,6 +122,8 @@ bash scripts/release.sh 0.1.2 The script builds a release-marked app, verifies its version and signature, and produces a ZIP and DMG in `work/release/`. Without `--publish`, it does not push a tag or create a GitHub release. Version `0.1.0` is the first public alpha; use an unused version for later releases. +Valve's attribution for the Steam logo carries the year Valve's page gives ("©2026 Valve Corporation…", https://partner.steamgames.com/doc/marketing/branding/attribution). In a new year, copy Valve's current wording for each language into `NOTICE` and the `Localizable.xcstrings` entry used by Settings › About before releasing. + Publishing requires an explicit maintainer decision and the script's `--publish --notes <file>` options. Prepare reviewed notes from [CHANGELOG.md](../CHANGELOG.md), then date the version when it is actually published. The script adds engine/Xcode requirement metadata to release notes for the updater. Never publish automatically as part of an agent's verification. ### Distribution work still open @@ -141,8 +158,22 @@ These are distribution decisions. Do not bypass the dirty-tree check, change the | `scripts/` | Runtime preparation, app packaging, installation helpers, release packaging and publication checks. | | `docs/` | Current guides, audits, dated designs and engine-adoption evidence. | -For component interactions, read the [architecture guide](architecture.md). For the role of every individual file, use the [file catalog](file-map.md). Screenshots and demo placement are described in the [media guide](media/README.md). +For component interactions, read the [architecture guide](architecture.md); for where new code goes, the [conventions](conventions.md); for end-to-end paths, the [flows](flows.md). For the role of every individual file, use the [file catalog](file-map.md). Screenshots and demo placement are described in the [media guide](media/README.md). ### Localization resources SwiftPM processes the shared string catalog into `NXLibrary_NXLibraryCore.bundle`. `build_app.sh` requires and copies that bundle into `Contents/Resources`, declares the six supported app languages and validates the compiled strings/plurals before signing. `scripts/check_localizations.py --app <path.app>` verifies the same resources independently. Missing resources or placeholder mismatches fail packaging. Locale selection is independent from each game's DM_LANG setting. + +### Isolated launcher-development data + +`AppDataProfile` selects immutable roots from the explicit build marker, and `AppData` routes app-owned stores/default preferences through that policy. `DevelopmentStartupView` completes the background import before constructing app stores or the shell. A failure shows Retry/Close; it never opens a writable fallback on the release profile. A changed legacy library with a valid catalog also offers **Keep Arcane’s library**: it archives the catalog, backup and legacy inputs before acknowledging the changed fingerprint, keeping the catalog’s games and sources without merging older changes. `run_startup_recovery.py` exercises this coordinator using a synthetic profile without windows. The source is read directly, not through store load/recovery methods. A staged, hashed allowlist copy and preference import can resume after failure; a completed profile is never automatically reimported. Copied unfinished sessions end at their last recorded heartbeat. + +After the import, `AppShellState` creates the view model and initial router and applies the initial locale/theme on the main actor before publishing the ready shell. Views retain these prepared objects; they do not run model startup or mutate shared theme state as SwiftUI inserts the shell into an already-visible window. Startup logs record only phase boundaries, without library contents or preference values. + +The separate bundle IDs select separate standard preference domains. Do not open the app's own bundle ID with `UserDefaults(suiteName:)`: Foundation rejects that suite. Packaging runs `scripts/check_app_profile.swift` in a temporary headless app with the built Info.plist, exercising the real preferences accessor and profile roots without starting UI, running the importer or writing data. Ordinary unit-test hosts do not reproduce the packaged app's identity. + +The Dev does not automatically import credentials or restore saves, reconcile app icons, install copied pending builds, sync real mod overlays, or sweep shared external staging. Explicit Dev icon/build requests are recorded in `DevelopmentOperationStore` and can resume on restart. When automatic mod maintenance is disabled, browsing reads the actual overlay without rewriting it or cleaning another profile's staging. + +The isolation covers launcher data, not the physical game installations and their saves. Explicit Play, game settings, builds, save/mod actions and cleanup still refer to real resources. Do not describe this as a sandbox of all game effects. Release packaging excludes the development marker, and the updater rejects a release that also selects the development profile. Initial Dev import and native interaction remain awaiting maintainer validation. + +Launch the packaged Dev for app checks: an unmarked executable cannot silently choose the stable data profile. Build markers and bundle identity must agree before the startup transaction opens any app store. diff --git a/docs/file-map.md b/docs/file-map.md index 05088619..112a59db 100644 --- a/docs/file-map.md +++ b/docs/file-map.md @@ -1,10 +1,10 @@ -# NX Library — catalogo dei file +# Arcane — catalogo dei file -Aggiornato il 3 novembre 2026. Copertura di **398 file** del progetto, compresi i controlli di pubblicazione, la CI, il master dell’icona, le guide per sviluppo e media, gli screenshot del README, l'integrazione di nxnative, il canale di aggiornamento e il setup in due passaggi con cartella unica per scoperta e installazione dei giochi. Le cartelle personali, gli output generati e gli appunti non versionati sono esclusi. +Aggiornato il 18 novembre 2026. Copertura di **714 file** del progetto, compresi i controlli di pubblicazione, la CI con regressioni app senza UI, il master dell’icona, le guide per sviluppo e media, gli screenshot del README, l'integrazione di nxnative, il canale di aggiornamento e il primo avvio che parte da ciò che è già sul Mac, il setup del porting con cartella unica per scoperta e installazione dei giochi. Le cartelle personali, gli output generati e gli appunti non versionati sono esclusi. La [guida tecnica](architecture.md) spiega come collaborano i componenti. Qui ogni riga identifica un file e la sua responsabilità. Le sezioni Core seguono le funzionalità, quelle UI seguono schermate e componenti. Le viste usano i modelli e i servizi del Core attraverso il coordinamento applicativo. -Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Application Support sono descritti nella guida. Per i piani datati, leggere anche le note finali di esecuzione e la specifica della funzionalità interessata. +Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Application Support sono descritti nella guida. ## Indice @@ -16,10 +16,15 @@ Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Applicat - [Core · libreria, stato e sessioni](#core--libreria-stato-e-sessioni) - [Core · Setup, motore e chiavi](#core--setup-motore-e-chiavi) - [Core · sorgenti, porting, installazione e lancio](#core--sorgenti-porting-installazione-e-lancio) -- [Core · cheats](#core--cheats) +- [Core · cheat e mod](#core--cheat-e-mod) - [Core · salvataggi e cloud](#core--salvataggi-e-cloud) - [Core · artwork, metadati e sfondi online](#core--artwork-metadati-e-sfondi-online) - [Core · presentazione Selene, focus e impostazioni](#core--presentazione-selene-focus-e-impostazioni) +- [Core · catalogo comune e fonti](#core--catalogo-comune-e-fonti) +- [Core · Steam](#core--steam) +- [Core · achievement](#core--achievement) +- [Core · lingua e testi](#core--lingua-e-testi) +- [Core · profilo dei dati](#core--profilo-dei-dati) - [UI · Add Game e porting](#ui--add-game-e-porting) - [UI · Spotlight](#ui--spotlight) - [UI · Collection e Details](#ui--collection-e-details) @@ -28,6 +33,8 @@ Le cartelle generate `.build/`, `work/` e `dist/` e i dati personali in Applicat - [UI · Setup, avvio, ricerca e console](#ui--setup-avvio-ricerca-e-console) - [UI · componenti condivisi](#ui--componenti-condivisi) - [UI · temi, rendering e sfondi](#ui--temi-rendering-e-sfondi) +- [UI · fonti, Steam e libreria mista](#ui--fonti-steam-e-libreria-mista) +- [UI · achievement](#ui--achievement) - [Test e fixture](#test-e-fixture) - [Script di sviluppo e packaging](#script-di-sviluppo-e-packaging) - [Risorse incluse](#risorse-incluse) @@ -40,33 +47,38 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| +| [.github/FUNDING.yml](../.github/FUNDING.yml) | Collega il pulsante Sponsor del repository alla pagina Buy Me a Coffee di Arcane. | | [.gitignore](../.gitignore) | Esclude output di build, bundle, cache, work e file personali dell’IDE dal versionamento. | | [AGENTS.md](../AGENTS.md) | Definisce vincoli per gli agenti, procedura di upgrade del motore e verifiche assegnate all’utente. | -| [CHANGELOG.md](../CHANGELOG.md) | Registra le modifiche visibili all'utente per release; Unreleased raccoglie il lavoro non ancora pubblicato. | -| [LICENSE](../LICENSE) | Contiene la licenza MIT di NX Library. | -| [NOTICE](../NOTICE) | Conserva attribuzioni e provenienza dei componenti e dei riferimenti riutilizzati. | +| [CHANGELOG.md](../CHANGELOG.md) | Registra le modifiche visibili all'utente per versione. | +| [LICENSE](../LICENSE) | Contiene la licenza MIT di Arcane. | +| [NOTICE](../NOTICE) | Conserva attribuzioni del motore al pin corrente, dei componenti, dei loghi e delle altre risorse riutilizzate. | | [Package.swift](../Package.swift) | Dichiara i target SwiftPM, le loro dipendenze e il deployment macOS minimo. | -| [README.md](../README.md) | Presenta l'app con logo e badge, guida d'uso, requisiti, risoluzione dei problemi, crediti e note legali. | +| [README.md](../README.md) | Presenta Arcane come libreria e launcher Mac, con guide, requisiti, sostegno volontario, crediti e note legali. | | [runtime.lock](../runtime.lock) | Fissa versioni, download e hash del runtime Python e degli strumenti inclusi nel bundle. | +| [VERSION](../VERSION) | Versione in sviluppo usata dal packaging e verificata dalla procedura di release. | ## Ingresso e shell dell’app | File | Responsabilità | |---|---| | [Sources/NXLibrary/NXLibraryApp.swift](../Sources/NXLibrary/NXLibraryApp.swift) | Punto @main, finestra SwiftUI, notifiche interne e comandi della barra menu. | -| [Sources/NXLibrary/AppDelegate.swift](../Sources/NXLibrary/AppDelegate.swift) | Registra Material Icons e gestisce il ciclo di chiusura e riapertura della finestra. | +| [Sources/NXLibrary/AppDelegate.swift](../Sources/NXLibrary/AppDelegate.swift) | Registra Material Icons, gestisce il ciclo della finestra, completa la scrittura della selezione alla chiusura e dà a una copia release il nome `Arcane.app`. | | [Sources/NXLibrary/Views/MainView.swift](../Sources/NXLibrary/Views/MainView.swift) | Presenta AppShellView come contenuto della finestra principale. | -| [Sources/NXLibrary/Views/Shell/AppShellView.swift](../Sources/NXLibrary/Views/Shell/AppShellView.swift) | Possiede lo stato condiviso, compone schermate e overlay e assegna priorità all’input. | +| [Sources/NXLibrary/Views/Shell/AppShellView.swift](../Sources/NXLibrary/Views/Shell/AppShellView.swift) | Possiede il backdrop persistente e aggiorna le richieste delle pagine e la palette nello snapshot reattivo, possiede lo stato condiviso, passa a Spotlight il modello Mods della shell, compone schermate e overlay (compreso il benvenuto in Arcane) e assegna priorità all’input; `nativeDialogOwnsInput` sospende controller, tastiera e comandi dei menu sotto alert e selettori nativi. | | [Sources/NXLibrary/Views/Shell/FullscreenCursorView.swift](../Sources/NXLibrary/Views/Shell/FullscreenCursorView.swift) | Gestisce il cursore inattivo nella sola finestra fullscreen del launcher, sospendendolo per pannelli e menu e ripristinando gli eventi al distacco. | -| [Sources/NXLibrary/Views/Shell/StartupWindowView.swift](../Sources/NXLibrary/Views/Shell/StartupWindowView.swift) | Applica una sola volta alla finestra pronta la preferenza fullscreen letta al lancio. | +| [Sources/NXLibrary/Views/Shell/StartupWindowView.swift](../Sources/NXLibrary/Views/Shell/StartupWindowView.swift) | Applica il fullscreen dopo la comparsa della finestra e segnala fine transizione o scadenza alla fase dell’entrata. | | [Sources/NXLibrary/Views/Shell/MenuOverlayView.swift](../Sources/NXLibrary/Views/Shell/MenuOverlayView.swift) | Disegna il control center con azioni, focus e sottomenu Power. | | [Sources/NXLibraryCore/NXLibraryCore.swift](../Sources/NXLibraryCore/NXLibraryCore.swift) | Espone la versione nominale del modulo Core. | +| [LaunchReveal.swift](../Sources/NXLibrary/Views/Launch/LaunchReveal.swift) | Rende visibile la finestra al primo frame del moonlight, con dissolvenza e scadenza, poi consente il fullscreen; integra il bootstrap con un NSView non interattivo. | +| [DevelopmentStartupView.swift](../Sources/NXLibrary/Views/Launch/DevelopmentStartupView.swift) | Avvio asincrono senza schermata di preparazione, recupero degli errori e scelta esplicita sul conflitto legacy prima di costruire la shell. | +| [AppShellState.swift](../Sources/NXLibrary/Views/Shell/AppShellState.swift) | Prepara coordinatore, router, fonti, lingua e tema. Condivide lo store con il delegato alla chiusura e conserva la cover Mods durante la navigazione. | ## Coordinamento applicativo | File | Responsabilità | |---|---| -| [Sources/NXLibrary/ViewModels/AppViewModel.swift](../Sources/NXLibrary/ViewModels/AppViewModel.swift) | Coordina libreria, sorgenti, ambiente, porting, log, impostazioni dei giochi e lancio. | +| [Sources/NXLibrary/ViewModels/AppViewModel.swift](../Sources/NXLibrary/ViewModels/AppViewModel.swift) | Coordina libreria, sorgenti, ambiente, porting e lancio, inclusa la sincronizzazione delle mod prima di Play. Conserva scelta Steam del Setup e programma NUP, chiede notifiche al porting e non scansiona Game files all’avvio. | | [Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Cheats.swift) | Adatta Core e bundle installato al pannello Cheats, alla riga di stato e alla diagnostica. | | [Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Mods.swift) | Crea lo `ModStore` di un gioco, il valore della riga Mods e le frasi per ogni errore. | | [Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Controller.swift) | Conserva il contesto di gioco per i comandi e offre il collegamento alla cartella dei save. | @@ -92,6 +104,7 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibrary/Models/GameDetailsInfo.swift](../Sources/NXLibrary/Models/GameDetailsInfo.swift) | Ispeziona DLC e salvataggi del bundle e prepara dimensioni e dettagli del gioco. | | [Sources/NXLibrary/Models/GamepadType.swift](../Sources/NXLibrary/Models/GamepadType.swift) | Definisce brand dei controller e azioni astratte GamepadAction. | | [Sources/NXLibrary/Models/LogEntry.swift](../Sources/NXLibrary/Models/LogEntry.swift) | Rappresenta messaggi, livelli e identità delle righe di log mostrate dall’app. | +| [Sources/NXLibrary/Models/PlayedGame.swift](../Sources/NXLibrary/Models/PlayedGame.swift) | Gioco nxnative o Steam per schermata di lancio e card di fine sessione. | | [Sources/NXLibrary/Models/NXLibraryError.swift](../Sources/NXLibrary/Models/NXLibraryError.swift) | Raggruppa errori applicativi e relative spiegazioni, compresi i rifiuti prima del porting. | | [Sources/NXLibrary/Models/SelectableGame.swift](../Sources/NXLibrary/Models/SelectableGame.swift) | Rappresenta le sorgenti selezionabili e l’ordinamento delle versioni nel wizard. | | [Sources/NXLibrary/Models/UpstreamCheckState.swift](../Sources/NXLibrary/Models/UpstreamCheckState.swift) | Rappresenta gli stati del controllo del changelog upstream. | @@ -100,13 +113,14 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| -| [Sources/NXLibrary/Services/AppUpdater.swift](../Sources/NXLibrary/Services/AppUpdater.swift) | Coordina controllo release, download, verifica, installazione e riavvio di NX Library. | +| [Sources/NXLibrary/Services/AppUpdater.swift](../Sources/NXLibrary/Services/AppUpdater.swift) | Coordina controllo release, download, verifica, installazione e riavvio di Arcane. | | [Sources/NXLibrary/Services/NativeMenuCommands.swift](../Sources/NXLibrary/Services/NativeMenuCommands.swift) | Coordina tracking, disponibilità nella scena e passaggio differito dai menu macOS alle azioni del launcher. | | [Sources/NXLibrary/Services/GameControllerService.swift](../Sources/NXLibrary/Services/GameControllerService.swift) | Rileva controller e rimappature, gestisce tap e hold e produce azioni e simboli dei pulsanti. | -| [Sources/NXLibrary/Services/LaunchReadinessProbe.swift](../Sources/NXLibrary/Services/LaunchReadinessProbe.swift) | Attende una finestra visibile del gioco per terminare la schermata di lancio. | +| [Sources/NXLibrary/Services/LaunchReadinessProbe.swift](../Sources/NXLibrary/Services/LaunchReadinessProbe.swift) | Attende una finestra visibile del gioco (per bundle o, per Steam, per pid) per terminare la schermata di lancio. | | [Sources/NXLibrary/Services/NotificationService.swift](../Sources/NXLibrary/Services/NotificationService.swift) | Invia notifiche dei porting e instrada i clic verso il titolo o l’errore interessato. | | [Sources/NXLibrary/Services/OnlineBackgroundService.swift](../Sources/NXLibrary/Services/OnlineBackgroundService.swift) | Carica pagine e miniature e scarica wallpaper o video conservando progressi e crediti. | | [Sources/NXLibrary/Services/RunningGameMonitor.swift](../Sources/NXLibrary/Services/RunningGameMonitor.swift) | Riconcilia applicazioni in esecuzione e libreria e offre Resume e chiusura del gioco. | +| [Sources/NXLibrary/Services/LibraryWindow.swift](../Sources/NXLibrary/Services/LibraryWindow.swift) | Riporta davanti la finestra di Arcane dopo un gioco nxnative o Steam, mai sopra un gioco della libreria. | | [Sources/NXLibrary/Services/SoundEffectService.swift](../Sources/NXLibrary/Services/SoundEffectService.swift) | Riproduce i cue Selene e applica attivazione, volume e file importati. | | [Sources/NXLibrary/Services/SystemDetector.swift](../Sources/NXLibrary/Services/SystemDetector.swift) | Individua checkout nxnative, root personale e possibili percorsi delle chiavi. | @@ -122,21 +136,22 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibraryCore/Models/BackdropArt.swift](../Sources/NXLibraryCore/Models/BackdropArt.swift) | Regola che tiene l’arte del gioco precedente sullo sfondo Spotlight (`BackdropArtRule`) dissolvenza di un layer calcolata sull’orologio (`OpacityFade`) e livelli ormai coperti da togliere (`ArtStack`). | | [Sources/NXLibraryCore/Models/TileMotion.swift](../Sources/NXLibraryCore/Models/TileMotion.swift) | Curve e campioni dei loop di ring, bagliore e riflesso della tile selezionata, sull'orologio condiviso. | | [Sources/NXLibraryCore/Models/TextScroll.swift](../Sources/NXLibraryCore/Models/TextScroll.swift) | Scorrimento della colonna del pannello della mod: altezza della descrizione dopo Read more, limiti, riga a fuoco mostrata intera e passo Su/Giù che legge prima della riga seguente. | -| [Sources/NXLibraryCore/Models/AppSettings.swift](../Sources/NXLibraryCore/Models/AppSettings.swift) | Definisce impostazioni globali, default e decodifica compatibile dei campi aggiunti nel tempo. | -| [Sources/NXLibraryCore/Models/LibraryFilter.swift](../Sources/NXLibraryCore/Models/LibraryFilter.swift) | Definisce filtri, PlayHistory e LibraryQuery per ricerca e ordinamento dei giochi. | +| [Sources/NXLibraryCore/Models/AppSettings.swift](../Sources/NXLibraryCore/Models/AppSettings.swift) | Definisce impostazioni globali, default e decodifica compatibile; ignora la scelta storica delle particelle. | +| [Sources/NXLibraryCore/Models/LibraryFilter.swift](../Sources/NXLibraryCore/Models/LibraryFilter.swift) | Definisce filtri, PlayHistory e query condivisa per ricerca/ordine del catalogo misto, conservando l’API nxnative. | | [Sources/NXLibraryCore/Models/LibrarySelectionState.swift](../Sources/NXLibraryCore/Models/LibrarySelectionState.swift) | Mantiene selezione e spostamento nel risultato filtrato della Collection. | | [Sources/NXLibraryCore/Models/LibraryPresentation.swift](../Sources/NXLibraryCore/Models/LibraryPresentation.swift) | Formatta metadati e statistiche temporali per le schermate della libreria. | | [Sources/NXLibraryCore/Models/GameDetailPresentation.swift](../Sources/NXLibraryCore/Models/GameDetailPresentation.swift) | Prepara badge, disponibilità delle azioni, date e dati della pagina Details. | | [Sources/NXLibraryCore/Models/PlaySession.swift](../Sources/NXLibraryCore/Models/PlaySession.swift) | Descrive una sessione persistibile con gioco e riferimenti temporali. | | [Sources/NXLibraryCore/Models/ActivitySummary.swift](../Sources/NXLibraryCore/Models/ActivitySummary.swift) | Aggrega sessioni, giorni e tempi della settimana per la scheda Activity. | -| [Sources/NXLibraryCore/Models/MoreLikeThis.swift](../Sources/NXLibraryCore/Models/MoreLikeThis.swift) | Ordina i giochi correlati usando generi, sviluppatore e publisher. | -| [Sources/NXLibraryCore/Services/LibraryStore.swift](../Sources/NXLibraryCore/Services/LibraryStore.swift) | Salva il catalogo con recupero; conserva lo stato nelle scansioni e sostituisce le sorgenti solo per una selezione esplicita. | +| [Sources/NXLibraryCore/Models/MoreLikeThis.swift](../Sources/NXLibraryCore/Models/MoreLikeThis.swift) | Ordina i giochi correlati per generi, sviluppatore ed editore, con precedenza alla stessa fonte e ripiego facoltativo. | | [Sources/NXLibraryCore/Services/ImportService.swift](../Sources/NXLibraryCore/Services/ImportService.swift) | Scansiona bundle nxnative e ne ricava identità, versione, percorso e dimensioni. | | [Sources/NXLibraryCore/Models/CursorIdleState.swift](../Sources/NXLibraryCore/Models/CursorIdleState.swift) | Politica del ritardo di visibilità del puntatore e reset su mouse o perdita di eleggibilità. | | [Sources/NXLibraryCore/Services/AppSizeCache.swift](../Sources/NXLibraryCore/Services/AppSizeCache.swift) | Conserva dimensioni per percorso e data del bundle e decide lo stato vuoto della libreria. | -| [Sources/NXLibraryCore/Services/AppSettingsStore.swift](../Sources/NXLibraryCore/Services/AppSettingsStore.swift) | Pubblica impostazioni ed errori, preserva i file illeggibili e salva settings.json tramite file temporaneo. | -| [Sources/NXLibraryCore/Services/PlaySessionStore.swift](../Sources/NXLibraryCore/Services/PlaySessionStore.swift) | Registra avvio, heartbeat, fine e riconciliazione delle sessioni di gioco. | -| [Sources/NXLibraryCore/Navigation/AppRouter.swift](../Sources/NXLibraryCore/Navigation/AppRouter.swift) | Gestisce route, ritorno, menu, ricerca e richieste di selezione o spostamento su Spotlight. | +| [Sources/NXLibraryCore/Services/AppSettingsStore.swift](../Sources/NXLibraryCore/Services/AppSettingsStore.swift) | Pubblica impostazioni ed errori, preserva i file illeggibili e salva settings.json in modo atomico. Tiene l'ultima selezione fuori dalle notifiche e la scrive in background. | +| [Sources/NXLibraryCore/Services/PlaySessionStore.swift](../Sources/NXLibraryCore/Services/PlaySessionStore.swift) | Registra avvio, heartbeat, fine e riconciliazione delle sessioni di gioco; unisce i totali esterni (Steam) con le sessioni successive. | +| [Sources/NXLibraryCore/Navigation/AppRouter.swift](../Sources/NXLibraryCore/Navigation/AppRouter.swift) | Gestisce route, ritorno, menu, ricerca e richieste Spotlight; ShellBackdropCover definisce quali strati sono coperti da Setup, benvenuto e scelta tema. | +| [Sources/NXLibraryCore/Models/GameFocus.swift](../Sources/NXLibraryCore/Models/GameFocus.swift) | Quando un gioco che esce riporta Arcane davanti: solo se era l’app in primo piano e nessun altro gioco della libreria è aperto. | +| [Sources/NXLibraryCore/Models/SessionSummary.swift](../Sources/NXLibraryCore/Models/SessionSummary.swift) | Cosa dice la card di fine sessione: gioco, durata di questa sessione e totale scritto come nelle info del gioco; niente card sotto i dieci secondi. | ## Core · Setup, motore e chiavi @@ -146,18 +161,20 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibraryCore/Models/ToolchainInfo.swift](../Sources/NXLibraryCore/Models/ToolchainInfo.swift) | Registra provenienza e verifica della toolchain associata a un build. | | [Sources/NXLibraryCore/Models/ToolchainGateCopy.swift](../Sources/NXLibraryCore/Models/ToolchainGateCopy.swift) | Traduce il gate in testi distinguendo Metal certificato, precedente e successivo. | | [Sources/NXLibraryCore/Models/SetupCheck.swift](../Sources/NXLibraryCore/Models/SetupCheck.swift) | Converte fatti e override del Setup in schede, stati, azioni e condizioni di riapertura. | -| [Sources/NXLibraryCore/Models/FirstRunSetup.swift](../Sources/NXLibraryCore/Models/FirstRunSetup.swift) | Coordina pagine, completamento, ripresa del primo avvio, stato della scansione, focus e consumo unico delle selezioni avviate da Your games. | +| [Sources/NXLibraryCore/Models/FirstRunSetup.swift](../Sources/NXLibraryCore/Models/FirstRunSetup.swift) | Coordina pagina e completamento del Setup, scelta Steam persistente fino alla fine, ripresa, focus e consumo unico delle selezioni da Your games. | +| [Sources/NXLibraryCore/Models/FirstRunFindings.swift](../Sources/NXLibraryCore/Models/FirstRunFindings.swift) | Conta giochi Steam e app portate senza modifiche; distingue lettura incompleta da assenza e permette nuove letture annullabili. | +| [Sources/NXLibraryCore/Models/ArcaneWelcome.swift](../Sources/NXLibraryCore/Models/ArcaneWelcome.swift) | Decide quando compare il benvenuto in Arcane, l'offerta di Steam, il focus e come ogni uscita lo segna visto. | | [Sources/NXLibraryCore/Models/GameFoldersCopy.swift](../Sources/NXLibraryCore/Models/GameFoldersCopy.swift) | Condivide nomi delle cartelle, formati e descrizioni tra Setup, Settings e selettori dei percorsi. | | [Sources/NXLibraryCore/Models/SetupGrid.swift](../Sources/NXLibraryCore/Models/SetupGrid.swift) | Calcola disposizione, centratura e navigazione del focus nella griglia del Setup. | -| [Sources/NXLibraryCore/Models/UpstreamCopy.swift](../Sources/NXLibraryCore/Models/UpstreamCopy.swift) | Prepara i testi del changelog upstream e dell’adozione degli aggiornamenti tramite NX Library. | +| [Sources/NXLibraryCore/Models/UpstreamCopy.swift](../Sources/NXLibraryCore/Models/UpstreamCopy.swift) | Prepara i testi del changelog upstream e dell’adozione degli aggiornamenti tramite Arcane. | | [Sources/NXLibraryCore/Services/NXNativeEnvironment.swift](../Sources/NXLibraryCore/Services/NXNativeEnvironment.swift) | Ispeziona strumenti, Python, Xcode e Metal e restituisce uno stato dell’ambiente. | | [Sources/NXLibraryCore/Services/EngineLocation.swift](../Sources/NXLibraryCore/Services/EngineLocation.swift) | Risolve checkout predefinito o scelto e produce i candidati per prod.keys. | | [Sources/NXLibraryCore/Services/EngineToolchain.swift](../Sources/NXLibraryCore/Services/EngineToolchain.swift) | Individua runtime incluso o venv del checkout e prepara ambiente e PATH dei processi. | -| [Sources/NXLibraryCore/Services/EnginePackageReader.swift](../Sources/NXLibraryCore/Services/EnginePackageReader.swift) | Legge capacità delle sorgenti e content meta di tutti i pacchetti in un solo passaggio del lettore upstream (`package_reader`, o `package_title_reader` sugli engine precedenti a 5c4dc18f), validando identità e tipi senza esporre chiavi. | -| [Sources/NXLibraryCore/Models/BuildWarningCopy.swift](../Sources/NXLibraryCore/Models/BuildWarningCopy.swift) | Testo mostrato a fine build per una fase terminata con `warn` dell’engine (archivio delle pipeline mancante). | +| [Sources/NXLibraryCore/Services/EnginePackageReader.swift](../Sources/NXLibraryCore/Services/EnginePackageReader.swift) | Legge content meta e capacità del checkout, compresa selezione NUP multiprogramma, senza esporre chiavi. | +| [Sources/NXLibraryCore/Models/BuildWarningCopy.swift](../Sources/NXLibraryCore/Models/BuildWarningCopy.swift) | Testo mostrato a fine build per `warn` dell’engine: archivio mancante o pipeline da preparare al primo avvio. | | [Sources/NXLibraryCore/Models/ReleaseNotesLayout.swift](../Sources/NXLibraryCore/Models/ReleaseNotesLayout.swift) | Divide le note di release in titoli, voci e testo, una riga per volta, per il dialogo degli aggiornamenti. | | [Sources/NXLibraryCore/Services/NewestEngine.swift](../Sources/NXLibraryCore/Services/NewestEngine.swift) | Scelta dell’engine più nuovo: testi condivisi, lettura del Metal dal lock di main, cambio di commit con git senza toccare file modificati. | -| [Sources/NXLibraryCore/Services/NUPSourceCatalog.swift](../Sources/NXLibraryCore/Services/NUPSourceCatalog.swift) | Riconosce i file NUP Switch 2 e ne elenca base, update e DLC tramite il lettore pack_nup dell’engine; accetta anche un NUP senza base (solo update). | +| [Sources/NXLibraryCore/Services/NUPSourceCatalog.swift](../Sources/NXLibraryCore/Services/NUPSourceCatalog.swift) | Legge NUP con base o soli update; tiene distinti programma, applicazione e base DLC tramite il lettore upstream e conserva il default selezionato. | | [Sources/NXLibraryCore/Services/DirectorySize.swift](../Sources/NXLibraryCore/Services/DirectorySize.swift) | Misura le cartelle con fts come du, così il refresh non resta bloccato su app grandi in dischi esterni (issue #2). | | [Sources/NXLibraryCore/Services/NXNativeGameSettings.swift](../Sources/NXLibraryCore/Services/NXNativeGameSettings.swift) | Legge l’elenco impostazioni del build, i valori attuali e le chiavi fissate da env.txt. | | [Sources/NXLibraryCore/Services/SavedChoicesStore.swift](../Sources/NXLibraryCore/Services/SavedChoicesStore.swift) | Legge e scrive le scelte salvate launcher.<env> nel dominio preferenze dell’app gioco. | @@ -174,8 +191,9 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| -| [Sources/NXLibraryCore/Models/GameFileItem.swift](../Sources/NXLibraryCore/Models/GameFileItem.swift) | Descrive sorgenti, tipo base/update/DLC, percorso, dimensione e metadati rilevati. | -| [Sources/NXLibraryCore/Models/SourceSelection.swift](../Sources/NXLibraryCore/Models/SourceSelection.swift) | Gestisce scelta esplicita dei titoli, selezione e ripristino logico dei contenuti, DLC incorporati, dimensioni uniche, versione di build e requisiti del motore. | +| [Sources/NXLibraryCore/Models/GameFileItem.swift](../Sources/NXLibraryCore/Models/GameFileItem.swift) | Sorgenti salvate con layout, requisiti e selezione NUP facoltativa, compatibile con i vecchi record. | +| [NUPProgramSelection.swift](../Sources/NXLibraryCore/Models/NUPProgramSelection.swift) | Identità tipizzata del programma NUP, applicazione e base add-on; indice ricavato dal programma, persistito con i sorgenti. | +| [Sources/NXLibraryCore/Models/SourceSelection.swift](../Sources/NXLibraryCore/Models/SourceSelection.swift) | Scelte dei contenuti, dimensioni e versione di build; verifica coerenza e supporto del programma NUP e ne vincola l’indice nel rebuild. | | [Sources/NXLibraryCore/Models/BuildRecord.swift](../Sources/NXLibraryCore/Models/BuildRecord.swift) | Conserva esito, tempi, log e provenienza di un porting. | | [Sources/NXLibraryCore/Models/TargetPlatform.swift](../Sources/NXLibraryCore/Models/TargetPlatform.swift) | Definisce il target mac-app e le sue etichette per l’interfaccia. | | [Sources/NXLibraryCore/Models/GameRuntimeConfig.swift](../Sources/NXLibraryCore/Models/GameRuntimeConfig.swift) | Persiste opzioni per titolo, prepara Review e lingua del rebuild, mappa DM_* e unisce env.txt. | @@ -183,18 +201,18 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibraryCore/Models/AppIconProgress.swift](../Sources/NXLibraryCore/Models/AppIconProgress.swift) | Stati e testi della preparazione icona, con esito informativo aggiunto al log della build conclusa. | | [Sources/NXLibraryCore/Models/IconLaunchWait.swift](../Sources/NXLibraryCore/Models/IconLaunchWait.swift) | Conserva una richiesta Play durante la firma dell'icona e la revoca su annullamento, errore o chiusura del dialogo. | | [Sources/NXLibraryCore/Services/PipelineArchiveProgress.swift](../Sources/NXLibraryCore/Services/PipelineArchiveProgress.swift) | Legge il log pipeline della build corrente e conta solo i gruppi confermati pronti dal motore. | -| [Sources/NXLibraryCore/Models/PortingProgress.swift](../Sources/NXLibraryCore/Models/PortingProgress.swift) | Aggrega eventi del motore in fasi e percentuale complessiva per la UI. | -| [Sources/NXLibraryCore/Models/PortingPresentation.swift](../Sources/NXLibraryCore/Models/PortingPresentation.swift) | Definisce fallimento persistito, ETA, aspetto della tile e pill del porting. | +| [Sources/NXLibraryCore/Models/PortingProgress.swift](../Sources/NXLibraryCore/Models/PortingProgress.swift) | Aggrega eventi del motore in fasi e percentuale complessiva; identifica archivio e prewarm senza dedurre conteggi dal tempo trascorso. | +| [Sources/NXLibraryCore/Models/PortingPresentation.swift](../Sources/NXLibraryCore/Models/PortingPresentation.swift) | Definisce fallimento persistito, ETA, attività senza stima del prewarm, aspetto della tile e pill del porting. | | [Sources/NXLibraryCore/Models/PortingFailureReason.swift](../Sources/NXLibraryCore/Models/PortingFailureReason.swift) | Classifica messaggi del motore e rifiuti preliminari in motivazioni e azioni spiegabili. | | [Sources/NXLibraryCore/Models/PortingNotice.swift](../Sources/NXLibraryCore/Models/PortingNotice.swift) | Decide quando notificare l’esito di un porting e prepara il relativo messaggio. | | [Sources/NXLibraryCore/Models/PendingInstall.swift](../Sources/NXLibraryCore/Models/PendingInstall.swift) | Conserva un bundle pronto in attesa e ne gestisce installazione, scarto e aggiornamento del record, anche dopo una pubblicazione interrotta. | | [Sources/NXLibraryCore/Models/RunningGames.swift](../Sources/NXLibraryCore/Models/RunningGames.swift) | Confronta bundle ID e mantiene uno snapshot delle applicazioni in esecuzione. | -| [Sources/NXLibraryCore/Services/SourceCatalog.swift](../Sources/NXLibraryCore/Services/SourceCatalog.swift) | Riconosce sorgenti NSP/XCI/NSZ/XCZ e raggruppa titoli, aggiornamenti e DLC. | +| [Sources/NXLibraryCore/Services/SourceCatalog.swift](../Sources/NXLibraryCore/Services/SourceCatalog.swift) | Riconosce sorgenti NSP/XCI/NSZ/XCZ e raggruppa titoli, update e DLC; DetectedSource conserva la selezione NUP tipizzata. | | [Sources/NXLibraryCore/Services/ExtractedSourceCatalog.swift](../Sources/NXLibraryCore/Services/ExtractedSourceCatalog.swift) | Verifica il layout di un gioco estratto, legge NPDM e profilo registrato e rileva update e DLC. | | [Sources/NXLibraryCore/Services/WorkspaceManager.swift](../Sources/NXLibraryCore/Services/WorkspaceManager.swift) | Prepara collegamenti simbolici, verifica link interrotti e adotta workspace e cache esistenti. | | [Sources/NXLibraryCore/Services/BuildScratch.swift](../Sources/NXLibraryCore/Services/BuildScratch.swift) | Sceglie dove stanno workspace e app temporanea (sul volume dell'app quando può ospitarli), riconosce i workspace gestiti e le cartelle temporanee da pulire. | | [Sources/NXLibraryCore/Services/BuildCommand.swift](../Sources/NXLibraryCore/Services/BuildCommand.swift) | Valore con eseguibile, argomenti, ambiente e directory di lavoro del processo di porting. | -| [Sources/NXLibraryCore/Services/BuildCommandBuilder.swift](../Sources/NXLibraryCore/Services/BuildCommandBuilder.swift) | Costruisce il contratto CLI nxnative, comprese destinazione Mac, JSON e override toolchain. | +| [Sources/NXLibraryCore/Services/BuildCommandBuilder.swift](../Sources/NXLibraryCore/Services/BuildCommandBuilder.swift) | Contratto CLI nxnative: Mac, JSON, versione pacchetto, selezione --program esplicita e override toolchain. | | [Sources/NXLibraryCore/Services/BuildEvent.swift](../Sources/NXLibraryCore/Services/BuildEvent.swift) | Definisce gli eventi di fase, step, avanzamento e log ricevuti dal motore. | | [Sources/NXLibraryCore/Services/BuildEventParser.swift](../Sources/NXLibraryCore/Services/BuildEventParser.swift) | Decodifica eventi JSON e tratta le altre righe come log. | | [Sources/NXLibraryCore/Services/BuildService.swift](../Sources/NXLibraryCore/Services/BuildService.swift) | Avvia il porting, gestisce processi, cancellazione, log ed eventi; conserva il bundle valido quando fallisce solo l’installazione. | @@ -203,11 +221,12 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibraryCore/Services/LaunchService.swift](../Sources/NXLibraryCore/Services/LaunchService.swift) | Scrive l’ambiente runtime e avvia il bundle del gioco tramite NSWorkspace. | | [Sources/NXLibraryCore/Services/StorageManager.swift](../Sources/NXLibraryCore/Services/StorageManager.swift) | Misura app, cache e log per gioco e totali senza duplicare percorsi condivisi; verifica cartelle e sorgenti prima della pulizia selettiva. I backup appartengono al flusso Saves. | | [Sources/NXLibraryCore/Services/DiagnosticsReport.swift](../Sources/NXLibraryCore/Services/DiagnosticsReport.swift) | Genera il rapporto diagnostico e rimuove percorso home e valori riconosciuti come chiavi. | -| [Sources/NXLibraryCore/Services/AppUpdate.swift](../Sources/NXLibraryCore/Services/AppUpdate.swift) | Definisce repository, versioni, requisiti, limiti di download, digest, firma e regole di verifica e sostituzione dell’app NX Library. | +| [Sources/NXLibraryCore/Services/AppUpdate.swift](../Sources/NXLibraryCore/Services/AppUpdate.swift) | Definisce repository, versioni, verifica del download e sostituzione atomica dell’app in staging esclusivo, con conservazione della vecchia copia se il Cestino fallisce. | +| [Sources/NXLibraryCore/Services/AppBundleRename.swift](../Sources/NXLibraryCore/Services/AppBundleRename.swift) | Decide se una copia release che si chiama ancora `NX Library.app` diventa `Arcane.app` alla chiusura, e fa lo spostamento nella stessa cartella. | | [Sources/NXLibraryCore/Models/AppUpdatePresentation.swift](../Sources/NXLibraryCore/Models/AppUpdatePresentation.swift) | Definisce gli stati dell’updater e il gate di installazione per versione e tipo di copia. | | [Sources/NXLibraryCore/Services/AppUpdateDownload.swift](../Sources/NXLibraryCore/Services/AppUpdateDownload.swift) | Scarica gli aggiornamenti con limiti di dimensione, redirect HTTPS vincolati a GitHub e gestione del file temporaneo. | -## Core · cheats +## Core · cheat e mod | File | Responsabilità | |---|---| @@ -217,8 +236,8 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibraryCore/Models/CheatStatus.swift](../Sources/NXLibraryCore/Models/CheatStatus.swift) | Valuta il supporto del motore tramite ancestry e prepara stato della riga e indicatore attivo. | | [Sources/NXLibraryCore/Models/CheatCopy.swift](../Sources/NXLibraryCore/Models/CheatCopy.swift) | Centralizza testi di stato, rifiuto, importazione, sostituzione e rimozione dei cheats. | | [Sources/NXLibraryCore/Services/CheatStore.swift](../Sources/NXLibraryCore/Services/CheatStore.swift) | Legge e modifica cheats, file enabled, master switch e metadati della build corrente. | -| [Sources/NXLibraryCore/Services/ModStore.swift](../Sources/NXLibraryCore/Services/ModStore.swift) | Ordine, stato acceso/spento, conflitti, Cestino e riga `DM_ROMFS_OVERLAY` delle mod RomFS di un gioco. | -| [Sources/NXLibraryCore/Services/ModFolderScanner.swift](../Sources/NXLibraryCore/Services/ModFolderScanner.swift) | Trova le voci della cartella mods (cartelle e file sparsi), il loro `romfs` e i file che contengono (senza quelli nascosti). | +| [Sources/NXLibraryCore/Services/ModStore.swift](../Sources/NXLibraryCore/Services/ModStore.swift) | Ordine, interruttori, conflitti, Cestino e overlay delle mod RomFS. Ferma la riconciliazione se cartella o record non si leggono. | +| [Sources/NXLibraryCore/Services/ModFolderScanner.swift](../Sources/NXLibraryCore/Services/ModFolderScanner.swift) | Elenca cartelle, archivi e file RomFS. La lettura stretta distingue una cartella vuota da una scansione fallita durante la riconciliazione. | | [Sources/NXLibraryCore/Services/GameBanana/GameBananaAPI.swift](../Sources/NXLibraryCore/Services/GameBanana/GameBananaAPI.swift) | URL, host fidati, modelli delle risposte di GameBanana e testo semplice dalle descrizioni HTML. | | [Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift](../Sources/NXLibraryCore/Services/GameBanana/GameBananaClient.swift) | Richieste a GameBanana con User-Agent, limite di 4 alla volta e cache su disco. | | [Sources/NXLibraryCore/Services/GameBanana/GameBananaImageCache.swift](../Sources/NXLibraryCore/Services/GameBanana/GameBananaImageCache.swift) | Cache su disco delle immagini delle mod dal CDN di GameBanana. | @@ -241,16 +260,16 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| -| [Sources/NXLibraryCore/Models/SaveLocation.swift](../Sources/NXLibraryCore/Models/SaveLocation.swift) | Valida percorsi e identità, risolve cloud effettivo e definisce slot ed errori dei salvataggi. | -| [Sources/NXLibraryCore/Models/SaveSnapshot.swift](../Sources/NXLibraryCore/Models/SaveSnapshot.swift) | Definisce identità, inventario, manifest e anteprime di importazione o ripristino. | -| [Sources/NXLibraryCore/Models/SavePresentation.swift](../Sources/NXLibraryCore/Models/SavePresentation.swift) | Prepara riepiloghi, date, dimensioni, nomi degli slot e disponibilità dell’importazione. | +| [Sources/NXLibraryCore/Models/SaveLocation.swift](../Sources/NXLibraryCore/Models/SaveLocation.swift) | Percorsi e identità dei salvataggi; account/device, utenti locali aggiuntivi e file registro; cloud effettivo e percorsi sicuri. | +| [Sources/NXLibraryCore/Models/SaveSnapshot.swift](../Sources/NXLibraryCore/Models/SaveSnapshot.swift) | Identità, inventario, manifest schema 1/2 e anteprime; rifiuta dichiarazioni storiche con componenti nuovi. | +| [Sources/NXLibraryCore/Models/SavePresentation.swift](../Sources/NXLibraryCore/Models/SavePresentation.swift) | Riepiloghi e ambito dei restore storici/multiutente, nomi dei componenti e limite cloud a primario/device. | | [Sources/NXLibraryCore/Models/CloudSaves.swift](../Sources/NXLibraryCore/Models/CloudSaves.swift) | Descrive scelta cloud, cartelle iCloud o personalizzate e passaggi fra le opzioni. | | [Sources/NXLibraryCore/Services/CloudSavesPreferences.swift](../Sources/NXLibraryCore/Services/CloudSavesPreferences.swift) | Prepara la cartella e riapplica la scelta cloud ai domini dei giochi prima di ogni avvio, anche Off. | | [Sources/NXLibraryCore/Services/RyujinxSaveFolder.swift](../Sources/NXLibraryCore/Services/RyujinxSaveFolder.swift) | Riconosce contenitori Ryujinx, controlla il title ID e seleziona l’intero albero committed 0. | -| [Sources/NXLibraryCore/Services/SaveFileIO.swift](../Sources/NXLibraryCore/Services/SaveFileIO.swift) | Centralizza copie, hash, xattr portabili, controlli dei percorsi, spazio e scritture durevoli. | -| [Sources/NXLibraryCore/Services/SaveSnapshotStore.swift](../Sources/NXLibraryCore/Services/SaveSnapshotStore.swift) | Crea e verifica backup e prepara importazioni da esportazioni o backup datati. | -| [Sources/NXLibraryCore/Services/SaveRestorePreview.swift](../Sources/NXLibraryCore/Services/SaveRestorePreview.swift) | Estende lo store con staging, validazione e rilascio delle anteprime di ripristino. | -| [Sources/NXLibraryCore/Services/SaveTransaction.swift](../Sources/NXLibraryCore/Services/SaveTransaction.swift) | Esegue sostituzioni con copia protettiva e journal e recupera o ripulisce transazioni interrotte. | +| [Sources/NXLibraryCore/Services/SaveFileIO.swift](../Sources/NXLibraryCore/Services/SaveFileIO.swift) | Copie, hash e xattr portabili; inventario di directory e registro regolare limitato, controlli dei percorsi e scritture durevoli. | +| [Sources/NXLibraryCore/Services/SaveSnapshotStore.swift](../Sources/NXLibraryCore/Services/SaveSnapshotStore.swift) | Backup completi degli utenti locali e registro, formati storici compatibili, staging e import User/Device. | +| [Sources/NXLibraryCore/Services/SaveRestorePreview.swift](../Sources/NXLibraryCore/Services/SaveRestorePreview.swift) | Staging e validazione dei pezzi registrati nel backup, compreso il file utenti, con rilevamento dei cambiamenti concorrenti. | +| [Sources/NXLibraryCore/Services/SaveTransaction.swift](../Sources/NXLibraryCore/Services/SaveTransaction.swift) | Sostituzioni con ambito esplicito, backup completo e journal 1/2; verifica originali, recovery e pulizia parziale riprendibili con intento durevole. | | [Sources/NXLibraryCore/Services/SaveOperationGate.swift](../Sources/NXLibraryCore/Services/SaveOperationGate.swift) | Assegna lease per titolo e un’esclusione globale per l’updater; coordina salvataggi, Play, installazioni e recuperi. | ## Core · artwork, metadati e sfondi online @@ -273,6 +292,7 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibraryCore/Services/LaunchBoxArt.swift](../Sources/NXLibraryCore/Services/LaunchBoxArt.swift) | Legge ricerca e pagina gioco di LaunchBox; dal payload Nuxt ricava anteprime, file pieni, tipo, regione e dimensioni; screenshot Gameplay. | | [Sources/NXLibraryCore/Services/SteamGridDBArt.swift](../Sources/NXLibraryCore/Services/SteamGridDBArt.swift) | Conserva la chiave SteamGridDB in un file 0600 e interroga l’API v2 per griglie, hero, loghi e icone statiche accreditate. | | [Sources/NXLibraryCore/Services/ScreenshotFallback.swift](../Sources/NXLibraryCore/Services/ScreenshotFallback.swift) | Conserva per 30 giorni gli screenshot LaunchBox dei giochi senza screenshot Title DB e li sovrappone ai metadati. | +| [Sources/NXLibraryCore/Models/LibraryArtworkRole.swift](../Sources/NXLibraryCore/Models/LibraryArtworkRole.swift) | Ruoli di layout delle immagini (copertina, quadrato, sfondo…) separati dal fornitore: un quadrato non chiede né ritaglia mai la copertina verticale. | ## Core · presentazione Selene, focus e impostazioni @@ -280,7 +300,20 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT |---|---| | [Sources/NXLibraryCore/Models/ButtonPrompts.swift](../Sources/NXLibraryCore/Models/ButtonPrompts.swift) | Traduce azioni in simboli o etichette per tastiera e controller Switch, Xbox e PlayStation. | | [Sources/NXLibraryCore/Models/CollectionRow.swift](../Sources/NXLibraryCore/Models/CollectionRow.swift) | Definisce proporzioni delle copertine e geometria della riga Collection. | -| [Sources/NXLibraryCore/Models/DetailsFocus.swift](../Sources/NXLibraryCore/Models/DetailsFocus.swift) | Gestisce zone e spostamenti del focus nelle azioni e nelle bande di Details. | +| [Sources/NXLibraryCore/Models/DetailsFacts.swift](../Sources/NXLibraryCore/Models/DetailsFacts.swift) | Sceglie le righe del pannello Details per Switch e Steam: solo i valori presenti, niente di tecnico. | +| [Sources/NXLibraryCore/Models/CriticRating.swift](../Sources/NXLibraryCore/Models/CriticRating.swift) | Identità pubblica del gioco e console (Mac, Switch, Switch 2), voto originale /100, provenienza e riempimento proporzionale delle cinque stelle. | +| [Sources/NXLibraryCore/Services/WikidataRatings.swift](../Sources/NXLibraryCore/Services/WikidataRatings.swift) | Abbina titoli esatti e ID Steam; seleziona medie della critica documentate, senza confondere piattaforme o raccomandazioni. | +| [Sources/NXLibraryCore/Services/BoundedDownload.swift](../Sources/NXLibraryCore/Services/BoundedDownload.swift) | Lettura HTTP limitata a blocchi, senza redirect né byte per byte: usata da Wikidata, IGDB, LaunchBox/TheGamesDB e Steam. | +| [Sources/NXLibraryCore/Services/CriticRatingService.swift](../Sources/NXLibraryCore/Services/CriticRatingService.swift) | Preferenza IGDB personale → Wikidata pubblico, cache Wikidata, ripiego offline e pausa dopo errori. | +| [Sources/NXLibraryCore/Services/IGDBCredentials.swift](../Sources/NXLibraryCore/Services/IGDBCredentials.swift) | Credenziali Twitch personali in file 0600, validazione e messaggi sicuri senza segreti nei log. | +| [Sources/NXLibraryCore/Services/IGDBRatings.swift](../Sources/NXLibraryCore/Services/IGDBRatings.swift) | Abbinamento IGDB esatto o tramite ID Steam, critica preferita e ripiego utenti esplicito, con provenienza distinta da Wikidata. | +| [Sources/NXLibraryCore/Services/IGDBRatingService.swift](../Sources/NXLibraryCore/Services/IGDBRatingService.swift) | Cache dei voti, richieste coalescenti e verifica credenziali tramite il client IGDB condiviso. | +| [Sources/NXLibraryCore/Services/IGDBClient.swift](../Sources/NXLibraryCore/Services/IGDBClient.swift) | Unico accesso Twitch/IGDB per voti e metadati: token in memoria, coda limitata seriale, host vincolati, rinnovo 401 e annullamento. | +| [Sources/NXLibraryCore/Services/IGDBMetadata.swift](../Sources/NXLibraryCore/Services/IGDBMetadata.swift) | Proposte IGDB per campo: identità esatta, ruoli delle aziende e date complete della piattaforma corretta. | +| [Sources/NXLibraryCore/Services/IGDBMetadataService.swift](../Sources/NXLibraryCore/Services/IGDBMetadataService.swift) | Ricerca metadati su richiesta, ID Steam verificato, cache separata e ripiego offline; nessuna scrittura delle scelte personali. | +| [Sources/NXLibraryCore/Services/DatabaseMetadata.swift](../Sources/NXLibraryCore/Services/DatabaseMetadata.swift) | Proposte LaunchBox/TheGamesDB: identità e piattaforma verificate, campi separati, fonte esplicita e date della versione corretta. | +| [Sources/NXLibraryCore/Services/DatabaseMetadataService.swift](../Sources/NXLibraryCore/Services/DatabaseMetadataService.swift) | Letture pubbliche limitate e annullabili, richieste condivise, cache testuale per gioco/piattaforma e recupero offline. | +| [Sources/NXLibraryCore/Models/DetailsFocus.swift](../Sources/NXLibraryCore/Models/DetailsFocus.swift) | Gestisce zone e spostamenti del focus nei link e nelle bande di Details. | | [Sources/NXLibraryCore/Models/FocusIndex.swift](../Sources/NXLibraryCore/Models/FocusIndex.swift) | Mantiene un indice di focus entro i limiti di una lista. | | [Sources/NXLibraryCore/Models/SettingsRowAction.swift](../Sources/NXLibraryCore/Models/SettingsRowAction.swift) | Identifica azioni e righe Settings, mantenendo una sola azione primaria per riga senza accorpare giochi omonimi. | | [Sources/NXLibraryCore/Models/GameOptionsPresentation.swift](../Sources/NXLibraryCore/Models/GameOptionsPresentation.swift) | Definisce righe, livelli, etichette, scelte runtime e focus di Game Options. | @@ -288,18 +321,98 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibraryCore/Models/MaterialIcon.swift](../Sources/NXLibraryCore/Models/MaterialIcon.swift) | Elenca i glifi del font Material Icons incluso nel bundle. | | [Sources/NXLibraryCore/Models/MenuSelectionModel.swift](../Sources/NXLibraryCore/Models/MenuSelectionModel.swift) | Gestisce azioni selezionate nel control center e nelle scelte Power. | | [Sources/NXLibraryCore/Models/MoonlightField.swift](../Sources/NXLibraryCore/Models/MoonlightField.swift) | Genera in modo deterministico i dati delle particelle per lo sfondo Metal. | +| [MoonlightAppearance.swift](../Sources/NXLibraryCore/Models/MoonlightAppearance.swift) | Identità delle superfici classica/Arcane/Flow e campionamento dei colori locali condiviso fra shader e fallback. | | [Sources/NXLibraryCore/Models/ScreenshotViewerState.swift](../Sources/NXLibraryCore/Models/ScreenshotViewerState.swift) | Mantiene indice e limiti della navigazione nel visualizzatore screenshot. | | [Sources/NXLibraryCore/Models/SeleneCanvas.swift](../Sources/NXLibraryCore/Models/SeleneCanvas.swift) | Calcola scala uniforme, stage centrato e conversione delle unità del canvas 1920×1080. | -| [Sources/NXLibraryCore/Models/SelenePalette.swift](../Sources/NXLibraryCore/Models/SelenePalette.swift) | Decodifica palette, ordine del selettore e fallback della palette predefinita. | -| [Sources/NXLibraryCore/Models/SettingsCatalog.swift](../Sources/NXLibraryCore/Models/SettingsCatalog.swift) | Descrive righe, ricerca e valori modificati, distinguendo i default dei nuovi giochi dalla vibrazione in Controllers. | -| [Sources/NXLibraryCore/Models/SettingsSection.swift](../Sources/NXLibraryCore/Models/SettingsSection.swift) | Enumera gruppi, titoli e icone della schermata Settings. | +| [Sources/NXLibraryCore/Models/SelenePalette.swift](../Sources/NXLibraryCore/Models/SelenePalette.swift) | Decodifica palette e metadato opzionale moonlight, ordine del selettore e fallback Arcane con ID selene. | +| [Sources/NXLibraryCore/Models/SettingsCatalog.swift](../Sources/NXLibraryCore/Models/SettingsCatalog.swift) | Descrive righe, ricerca e valori modificati; ogni riga tiene il suo `rowID` e sta in una sola sezione, vibrazione compresa tra i default dei nuovi giochi. | +| [Sources/NXLibraryCore/Models/SettingsSection.swift](../Sources/NXLibraryCore/Models/SettingsSection.swift) | Sezioni di Settings con titoli e icone, dichiarate in ordine di sidebar, e `SettingsSidebarGroup`: General, Library, Porting (il gruppo di piattaforma) e System. | +| [Sources/NXLibraryCore/Models/SettingsReset.swift](../Sources/NXLibraryCore/Models/SettingsReset.swift) | Reset group per sezione: quali sezioni si azzerano e quali valori di `AppSettings` tornano ai default. | | [Sources/NXLibraryCore/Models/SpotlightPage.swift](../Sources/NXLibraryCore/Models/SpotlightPage.swift) | Calcola estratti delle descrizioni e stati dello scorrimento della pagina Spotlight. | -| [Sources/NXLibraryCore/Models/SpotlightRow.swift](../Sources/NXLibraryCore/Models/SpotlightRow.swift) | Costruisce la sequenza di card e giochi, riordino e selezione Surprise. | +| [Sources/NXLibraryCore/Models/SpotlightRow.swift](../Sources/NXLibraryCore/Models/SpotlightRow.swift) | Costruisce la sequenza per UUID e salva riordini conservando giochi/fonti/card temporaneamente nascosti; Surprise mantiene il proprio contratto nxnative. | | [Sources/NXLibraryCore/Models/SpotlightRowGeometry.swift](../Sources/NXLibraryCore/Models/SpotlightRowGeometry.swift) | Posti delle tessere nella riga, camera unica che la fa scorrere e finestra delle tessere create; posto, scala e camera lungo lo scorrimento dalla posizione continua della selezione. | -| [Sources/NXLibraryCore/Models/SpotlightState.swift](../Sources/NXLibraryCore/Models/SpotlightState.swift) | Gestisce selezione, focus, azioni e spostamento delle tile su Spotlight. | -| [Sources/NXLibraryCore/Models/ThemePicker.swift](../Sources/NXLibraryCore/Models/ThemePicker.swift) | Gestisce griglia, tab Wallpapers/Live e scelte di sfondo nel selettore temi. | +| [Sources/NXLibraryCore/Models/SpotlightState.swift](../Sources/NXLibraryCore/Models/SpotlightState.swift) | Gestisce selezione, focus (anche la card Achievements), azioni e spostamento delle tile su Spotlight. | +| [Sources/NXLibraryCore/Models/SpotlightEntrance.swift](../Sources/NXLibraryCore/Models/SpotlightEntrance.swift) | Tempi e partenze del volo delle tessere, dissolvenza oltre il bordo, sfondo, informazioni, hint e fasi della prima entrata di Spotlight, compreso quando accetta input. | +| [Sources/NXLibraryCore/Models/ThemePicker.swift](../Sources/NXLibraryCore/Models/ThemePicker.swift) | Gestisce il focus nella griglia colori, tab Wallpapers/Live e scelta dello sfondo successivo. | | [Sources/NXLibraryCore/Models/WallpaperCatalog.swift](../Sources/NXLibraryCore/Models/WallpaperCatalog.swift) | Elenca wallpaper e video, gruppi, nomi e file delle risorse incluse o importate. | | [Sources/NXLibraryCore/Models/WallpaperPlacement.swift](../Sources/NXLibraryCore/Models/WallpaperPlacement.swift) | Decide dove applicare uno sfondo scelto fra schermi principali e Settings. | +| [Sources/NXLibraryCore/Models/DisplayNameCache.swift](../Sources/NXLibraryCore/Models/DisplayNameCache.swift) | Nomi visualizzati di cartelle e volumi letti una volta per URL: la pagina si ricostruisce a ogni disegno e un disco esterno in stop bloccherebbe ogni volta. | + +## Core · catalogo comune e fonti + +| File | Responsabilità | +|---|---| +| [CatalogGame.swift](../Sources/NXLibraryCore/Models/CatalogGame.swift) | Record tipizzato nxnative/Steam, identità e personalizzazioni con namespace, osservazioni delle installazioni; lookup condiviso della prima installazione disponibile, separato dal gate di Play. | +| [CatalogDocument.swift](../Sources/NXLibraryCore/Models/CatalogDocument.swift) | Schema, revisione, base legacy riconosciuta, configurazione delle fonti e validazione delle identità. | +| [CatalogGamePresentation.swift](../Sources/NXLibraryCore/Models/CatalogGamePresentation.swift) | Contratto comune per presentazione, operazioni supportate e target di avvio; nessuna operazione I/O. | +| [CatalogStore.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogStore.swift) | Conversione conservativa, letture limitate, revisioni attese, lock e archiviazione esplicita del conflitto legacy senza fusione. | +| [CatalogPublication.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogPublication.swift) | Staging verificato, creazione esclusiva e sostituzione atomica, con confine di errore controllabile. | +| [CatalogRepository.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogRepository.swift) | Modifiche tipizzate sull'ultimo catalogo, senza replay di effetti esterni; risultati build limitati ai propri campi. | +| [NXNativeLibraryMerge.swift](../Sources/NXLibraryCore/Services/NXNativeLibraryMerge.swift) | Algoritmo di merge nxnative usato dal repository del catalogo comune. | +| [CatalogRecovery.swift](../Sources/NXLibraryCore/Models/CatalogRecovery.swift) | Offerte di recupero e conflitto legacy con impronte degli input, rivalidate all’accettazione. | +| [CatalogPersonalizations.swift](../Sources/NXLibraryCore/Models/CatalogPersonalizations.swift) | Lookup personali immutabili per identità e radici distinte per integrazione. | +| [CatalogErrorCopy.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogErrorCopy.swift) | Errori recuperabili del catalogo nelle sei lingue. | +| [CatalogBuildRecoveries.swift](../Sources/NXLibraryCore/Models/CatalogBuildRecoveries.swift) | Generazioni di build non ancora salvate, selezione del retry e conferma della sola generazione persistita. | +| [CatalogGameOptions.swift](../Sources/NXLibraryCore/Models/CatalogGameOptions.swift) | Ordine unico delle operazioni comuni della libreria; ciò che una fonte può fare dipende dal suo record (nessuna modifica nxnative su un gioco Steam). | +| [CatalogSourcesModel.swift](../Sources/NXLibraryCore/Services/Catalog/CatalogSourcesModel.swift) | Opt-in, worker annullabile e stato Steam; discoveryRoot conserva la cartella scelta anche con fonte spenta; pubblica solo documenti salvati dal repository. | +| [CatalogLibraryProjection.swift](../Sources/NXLibraryCore/Models/CatalogLibraryProjection.swift) | Visibilità comune per fonti attive e giochi riconosciuti; nessuna scansione. | + +## Core · Steam + +| File | Responsabilità | +|---|---| +| [SteamBackgroundLaunch.swift](../Sources/NXLibraryCore/Services/Steam/SteamBackgroundLaunch.swift) | Attesa di un gioco Steam avviato da Play: pazienza (15 s, 45 s se Play avvia Steam), stato della schermata di lancio, regole di «Keep Steam in the background». | +| [SteamKeyValues.swift](../Sources/NXLibraryCore/Services/Steam/SteamKeyValues.swift) | Parser testuale limitato e lookup condivisi dei lettori: prima chiave, primo valore tipizzato o campo unico, con regole esplicite sui duplicati; nessuna direttiva eseguita. | +| [SteamPlaytimeReader.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlaytimeReader.swift) | Ore e ultima partita dell’account Steam più recente da `localconfig.vdf`; nient’altro del file esce dal tipo. | +| [SteamPlaytimeBaselines.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlaytimeBaselines.swift) | Totali Steam con il momento in cui sono stati visti; nuovo valore o account ripartono; mappa ai giochi del catalogo. | +| [SteamReturnFocus.swift](../Sources/NXLibraryCore/Models/SteamReturnFocus.swift) | Quando un gioco Steam che esce riporta Arcane davanti: Play premuto qui, gioco in primo piano, nessun altro gioco aperto. | +| [SteamLaunchQuestions.swift](../Sources/NXLibraryCore/Services/Steam/SteamLaunchQuestions.swift) | Domande con cui Steam ferma un avvio, dalle righe `GameAction` di `logs/console_log.txt`. `ShowInterstitials` è avanzamento; le domande contano dopo 1 s. | +| [SteamPlaytimeSync.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlaytimeSync.swift) | Una lettura dei file Steam e cosa fa (pubblica, conserva gli ultimi totali buoni dello stesso account o azzera); coda di una lettura alla volta. | +| [InstallationFileSnapshot.swift](../Sources/NXLibraryCore/Services/Steam/InstallationFileSnapshot.swift) | Letture limitate e non bloccanti di file regolari; verifica dell'identità prima della pubblicazione. | +| [InstallationDirectorySnapshot.swift](../Sources/NXLibraryCore/Services/Steam/InstallationDirectorySnapshot.swift) | Lettura incrementale delle cartelle, budget anche sulle voci nascoste e annullamento durante l'enumerazione. | +| [NativeMacApplication.swift](../Sources/NXLibraryCore/Services/Steam/NativeMacApplication.swift) | Evidenze del bundle Mac e degli header eseguibili, architetture e categoria dichiarata, senza avvio. | +| [SteamLibrarySource.swift](../Sources/NXLibraryCore/Services/Steam/SteamLibrarySource.swift) | Snapshot delle librerie/manifest dichiarati, disponibilità, ambiguità, limiti e annullamento; non modifica il catalogo. | +| [SteamPlayState.swift](../Sources/NXLibraryCore/Services/Steam/SteamPlayState.swift) | Stato di Play per un gioco Steam: processi osservati con i percorsi risolti, passaggio a Steam, sessione solo quando gira l’app di questa installazione, attese e rifiuti. | +| [SteamBinaryKeyValues.swift](../Sources/NXLibraryCore/Services/Steam/SteamBinaryKeyValues.swift) | Lettura limitata del formato KeyValues binario di Steam (`appcache/stats`): tipi noti, profondità, voci e dimensione; qualunque altro byte è un errore. | +| [SteamAchievementReader.swift](../Sources/NXLibraryCore/Services/Steam/SteamAchievementReader.swift) | Achievement di un gioco per l’account corrente: schema (nomi nella lingua dell’app, poi inglese; nascosti; icone) e soli `AchievementTimes` del file delle statistiche; nessun file, account o statistiche: nessun dato. | +| [SteamAchievementRarity.swift](../Sources/NXLibraryCore/Services/Steam/SteamAchievementRarity.swift) | Rarità pubblica (`GetGlobalAchievementPercentagesForApp`, senza chiave) (una percentuale non numerica, «nan» o «inf», si scarta) e indirizzi delle icone sull’host community-assets del CDN di Steam, solo per nomi di file semplici. | +| [SteamManifestWatcher.swift](../Sources/NXLibraryCore/Services/Steam/SteamManifestWatcher.swift) | Uno stream FSEvents sulle cartelle `steamapps` delle librerie dell’ultima scansione; segnala solo i manifest `appmanifest_<AppID>.acf` e l’indice `libraryfolders.vdf` della radice, una volta per gruppo di eventi. | +| [SteamCatalogReconciler.swift](../Sources/NXLibraryCore/Services/Catalog/SteamCatalogReconciler.swift) | Ticket e fusione pura degli snapshot Steam, identità conservate e assenza trattata secondo completezza. | +| [SteamMetadata.swift](../Sources/NXLibraryCore/Services/Steam/SteamMetadata.swift) | Dati store Steam tipizzati, lingua e URL immagini verificati. | +| [SteamMetadataService.swift](../Sources/NXLibraryCore/Services/Steam/SteamMetadataService.swift) | Fino a sei download coalescenti, cache per lingua, ripiego offline e immagini ridimensionate. Legge i tratti dei giochi correlati solo da cache. | +| [SteamPersonalizationStore.swift](../Sources/NXLibraryCore/Services/Steam/SteamPersonalizationStore.swift) | Pubblicazione unica di metadati e riferimenti artwork; fallimenti e Automatic conservano le scelte coerenti. | +| [GameDetailPresentation+Steam.swift](../Sources/NXLibraryCore/Models/GameDetailPresentation+Steam.swift) | Dati della pagina Steam e generi della testata Spotlight; ignora i dati di altri AppID e dà precedenza ai campi personali. | +| [SteamArtworkRequest.swift](../Sources/NXLibraryCore/Services/Steam/SteamArtworkRequest.swift) | Cosa chiede la tile di un gioco Steam per ogni ruolo: prima la scelta personale, poi per il quadrato l’icona dell’app installata, mai la copertina; gli altri ruoli vanno all’arte dello store. | +| [SteamBackdropChoice.swift](../Sources/NXLibraryCore/Services/Steam/SteamBackdropChoice.swift) | Sfondo automatico di un gioco Steam: arte 16:9 pulita (Xbox, GOG, TheGamesDB, fan art LaunchBox), poi il primo screenshot, per ultimo il banner della libreria ritagliato. | + +Giochi in download: `SteamLibrarySource` (StateFlags senza il bit 4 → `.downloading`, cartella non letta), `SteamCatalogInstallation.isDownloading` e `SteamCatalogGame.isDownloading`/`needsReview`, `CatalogGamePresentation.isDownloading`, `PortingTileLook.downloading` con `PortingArtLook` (la scritta) e `PortingDownloadMark` → `DownloadMarkLayers` in `TileMotionLayers.swift` (il simbolo che pulsa, fuori dal `drawingGroup`), `SteamPlayCoordinator.openDownloads`, `CatalogSteamInfo` e `GamePrimaryActions.primaryWaveDots` (pulsante «Downloading» con i puntini, come «Porting»), il ritmo delle riscansioni in `CatalogSourcesModel.steamFilesChanged`.. + +## Core · achievement + +| File | Responsabilità | +|---|---| +| [AchievementSummary.swift](../Sources/NXLibraryCore/Models/AchievementSummary.swift) | Riepilogo puro per la tile e la schermata: conteggi, percentuale, gioco completato (`isComplete`), righe recenti con icona, conteggi per tier, sbloccati di recente, ultimo sblocco, filtri e ordini; maschera i nascosti ancora bloccati. | +| [AchievementTier.swift](../Sources/NXLibraryCore/Models/AchievementTier.swift) | Tier a cristallo come i trofei PS5: Arcano (viola, al posto del Platino) per il gioco completato, Oro / Argento / Bronzo per rarità Steam (<10%, <30%, il resto); nomi tradotti e PNG nelle risorse del Core; `videoURL` dà il video in loop dell'Arcane (`crystal-arcane.mov`, HEVC con alpha a 384 px). | +| [AchievementsScreenState.swift](../Sources/NXLibraryCore/Models/AchievementsScreenState.swift) | Filtro e selezione della schermata Achievements: due colonne, bordi fermi, LB/RB che girano i filtri. | +| [GridListLayout.swift](../Sources/NXLibraryCore/Models/GridListLayout.swift) | Geometria di una lista a colonne di righe uguali: altezza, posizione di ogni riga, linee da disegnare, riga da mostrare e riga in vista più vicina. | + +## Core · lingua e testi + +| File | Responsabilità | +|---|---| +| [Sources/NXLibraryCore/Models/AppIdentity.swift](../Sources/NXLibraryCore/Models/AppIdentity.swift) | Nome visibile dell'app ("Arcane", non tradotto), il vecchio nome detto solo dal benvenuto, il nome del modulo Porting, pagina del progetto e User-Agent unico delle richieste di rete. | +| [Sources/NXLibraryCore/Models/AppLocale.swift](../Sources/NXLibraryCore/Models/AppLocale.swift) | Sei lingue, risoluzione delle preferenze e regione indipendente; nomi e ricerca delle regioni. | +| [Sources/NXLibraryCore/Models/GameGenre.swift](../Sources/NXLibraryCore/Models/GameGenre.swift) | Generi noti tradotti alla presentazione; dati originali e generi personali conservati. | +| [Sources/NXLibraryCore/Services/AppLocalization.swift](../Sources/NXLibraryCore/Services/AppLocalization.swift) | Contesto osservabile, lookup portabile delle risorse e interpolazioni/plurali. | +| [Sources/NXLibraryCore/Resources/Localizable.xcstrings](../Sources/NXLibraryCore/Resources/Localizable.xcstrings) | Testi condivisi e traduzioni en/it/fr/de/es/pt-BR. | + +## Core · profilo dei dati + +| File | Responsabilità | +|---|---| +| [AppDataProfile.swift](../Sources/NXLibraryCore/Services/AppDataProfile.swift) | Policy di percorsi, cache, preferenze e staging del profilo. | +| [DevelopmentProfileImporter.swift](../Sources/NXLibraryCore/Services/DevelopmentProfileImporter.swift) | Copia iniziale selettiva (compresa la scelta Steam del Setup), hash, validazione e ripresa senza modificare la sorgente. | +| [DevelopmentOperationStore.swift](../Sources/NXLibraryCore/Services/DevelopmentOperationStore.swift) | Autorizzazioni persistenti per le operazioni richieste nella Dev, distinte da quelle importate. | ## UI · Add Game e porting @@ -315,47 +428,53 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| -| [Sources/NXLibrary/Views/Spotlight/SpotlightView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView.swift) | Compone home, selezione, filtri, pagina del gioco e stato delle tile. | -| [Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift) | Traduce input, card, azioni, screenshot e riordino nel modello Spotlight. | +| [Sources/NXLibrary/Views/Spotlight/SpotlightView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView.swift) | Compone home e tessere da una lista filtrata per render. Monta Dettagli, Mods e correlati quando sale la pagina. | +| [Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView+Input.swift) | Traduce input, card, azioni, screenshot e riordino. Le frecce sulla riga usano solo le tessere, prima di costruire i dati della pagina. | +| [Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightView+Entrance.swift) | Coordina l’entrata su moonlight condiviso: coperture e fullscreen, pausa, attesa dell’arte, effetti di volo e dissolvenza, barra in alto e hint per ultimi, atterraggio di sicurezza; nessun input salta l’entrata. | | [Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightRowView.swift) | Disegna la riga di tile con finestra visibile, focus e titoli; la faccia della card Mods (`ModsCardCover`). | | [Sources/NXLibrary/Views/Spotlight/SpotlightTopBar.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightTopBar.swift) | Disegna filtri, prompt dei dorsali e orologio condivisi con Collection. | | [Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightInfoView.swift) | Mostra logo, Play/Options/Favorite, statistiche e stato di porting del gioco selezionato. | | [Sources/NXLibrary/Views/Spotlight/SpotlightCardInfoView.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightCardInfoView.swift) | Mostra informazioni e azioni delle card Collection, Surprise, Activity e Add Game. | -| [Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift) | Prepara generi, descrizione, Build & Sources e giochi correlati della pagina inferiore. | +| [Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightPageSections.swift) | Modello della pagina inferiore con dettagli, link e giochi correlati del catalogo; generi e descrizione. | | [Sources/NXLibrary/Views/Spotlight/SpotlightScreenshotStrip.swift](../Sources/NXLibrary/Views/Spotlight/SpotlightScreenshotStrip.swift) | Disegna la striscia di screenshot con focus e stile adattabile alle schermate. | -| [Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift](../Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift) | Compone wallpaper, sfondo del gioco, transizioni e maschere Selene; l'arte è un `CALayer` che dissolve nel render server (`SeleneArtLayer`). | +| [Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift](../Sources/NXLibrary/Views/Spotlight/SeleneArtBackground.swift) | Compone wallpaper, sfondo del gioco, transizioni e maschere leggendo la palette dallo snapshot condiviso; l'arte è un `CALayer` che dissolve nel render server (`SeleneArtLayer`) e che l'entrata di Spotlight tiene nascosto (`ArtReveal`). | | [Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift](../Sources/NXLibrary/Views/Spotlight/SeleneHeroArt.swift) | Coordina il caricamento differito di hero e logo del gioco selezionato. | | [Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift](../Sources/NXLibrary/Views/Spotlight/GameArtLoader.swift) | Carica e memorizza hero e loghi attraverso ArtworkStore e decoder immagini dedicati. | +| [Sources/NXLibrary/Views/Spotlight/GameArtLoader+Played.swift](../Sources/NXLibrary/Views/Spotlight/GameArtLoader+Played.swift) | Hero e logo di un `PlayedGame` per schermata di lancio e card di fine sessione; per Steam le stesse scelte delle sue pagine. | ## UI · Collection e Details | File | Responsabilità | |---|---| -| [Sources/NXLibrary/Views/Collection/CollectionView.swift](../Sources/NXLibrary/Views/Collection/CollectionView.swift) | Compone la libreria a copertine, filtri e informazioni del gioco selezionato. | +| [Sources/NXLibrary/Views/Collection/CollectionView.swift](../Sources/NXLibrary/Views/Collection/CollectionView.swift) | Compone libreria a copertine, filtri, informazioni e ripristino dell'ultima selezione tramite lo store. | | [Sources/NXLibrary/Views/Collection/CollectionView+Input.swift](../Sources/NXLibrary/Views/Collection/CollectionView+Input.swift) | Gestisce navigazione, azioni e selezione nella Collection. | | [Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift](../Sources/NXLibrary/Views/Collection/CollectionCoverRow.swift) | Disegna copertine e scorrimento della riga Collection. | | [Sources/NXLibrary/Views/Detail/GameDetailView.swift](../Sources/NXLibrary/Views/Detail/GameDetailView.swift) | Compone la pagina Details e coordina bande, modello corrente e focus. | | [Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift](../Sources/NXLibrary/Views/Detail/GameDetailView+Input.swift) | Gestisce azioni, screenshot, navigazione e passaggio ai giochi correlati da Details. | | [Sources/NXLibrary/Views/Detail/DetailsBackground.swift](../Sources/NXLibrary/Views/Detail/DetailsBackground.swift) | Compone hero e maschere dello sfondo dedicato alla pagina Details. | | [Sources/NXLibrary/Views/Detail/DetailsTopBlock.swift](../Sources/NXLibrary/Views/Detail/DetailsTopBlock.swift) | Mostra logo, crediti, azioni, statistiche, generi e descrizione del gioco. | -| [Sources/NXLibrary/Views/Detail/DetailsBands.swift](../Sources/NXLibrary/Views/Detail/DetailsBands.swift) | Disegna bande screenshot, mod, attività e giochi correlati con i relativi titoli. | -| [Sources/NXLibrary/Views/Detail/BuildSourcesPanel.swift](../Sources/NXLibrary/Views/Detail/BuildSourcesPanel.swift) | Prepara e disegna le azioni di app, sorgenti, rebuild, log e cartelle. | +| [Sources/NXLibrary/Views/Detail/DetailsBands.swift](../Sources/NXLibrary/Views/Detail/DetailsBands.swift) | Disegna screenshot, mod e fascia correlati condivisa, con copertine Switch o Steam secondo la fonte. | +| [Sources/NXLibrary/Views/Detail/DetailsPanel.swift](../Sources/NXLibrary/Views/Detail/DetailsPanel.swift) | Pannello Details uguale per ogni fonte: righe con icona, voto della critica in ultima riga e link in `SeleneActionGrid`; carica solo il voto del gioco mostrato. | +| [Sources/NXLibrary/Views/Detail/CriticRatingValue.swift](../Sources/NXLibrary/Views/Detail/CriticRatingValue.swift) | Valore della riga Critic score: cinque stelle, numero /100 e fonte, senza finestre aggiuntive; caricamento e assenza espliciti. | +| [Sources/NXLibrary/ViewModels/IGDBSettings.swift](../Sources/NXLibrary/ViewModels/IGDBSettings.swift) | Configurazione IGDB facoltativa: verifica prima del salvataggio, rimozione e invalidazione delle richieste/voti precedenti. | +| [Sources/NXLibrary/Views/Components/IGDBCredentialsDialog.swift](../Sources/NXLibrary/Views/Components/IGDBCredentialsDialog.swift) | Guida sintetica in cinque passi, Client ID, Client Secret nascosto, verifica/salvataggio e annullamento; input Settings sospeso. | +| [Sources/NXLibrary/Views/Settings/SettingsAPISection.swift](../Sources/NXLibrary/Views/Settings/SettingsAPISection.swift) | Pagina generale Servizi API: nota sulle fonti facoltative, IGDB e SteamGridDB con azioni e focus condivisi. | ## UI · Game Options, cheats e salvataggi | File | Responsabilità | |---|---| -| [Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift](../Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift) | Presenta opzioni del gioco, Edit details, impostazioni runtime e conferme delle azioni. | +| [Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift](../Sources/NXLibrary/Views/GameOptions/GameOptionsView.swift) | Presenta opzioni del gioco, Edit details, impostazioni runtime e conferme delle azioni; `GameOptionsFiles` legge i file una volta per apertura. | | [Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift](../Sources/NXLibrary/Views/GameOptions/ChangeArtworkView.swift) | Seleziona artwork per titolo da rete o file e indica dove viene usato, con stato ad altezza stabile. | -| [Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift](../Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift) | Offre alternative o testo personalizzato per descrizione, generi, crediti e data. | +| [Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift](../Sources/NXLibrary/Views/GameOptions/ChangeMetadataView.swift) | Offre alternative per campo da store, Title DB, GameTDB e IGDB, oppure testo personale; anteprima, scelta, annullamento e retry con lo stesso input. | | [Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift](../Sources/NXLibrary/Views/GameOptions/CheatsPanel.swift) | Presenta file, master switch, codici, importazione, rimozione e stato di scrittura dei cheats. | | [Sources/NXLibrary/Views/GameOptions/ModsPanel.swift](../Sources/NXLibrary/Views/GameOptions/ModsPanel.swift) | Game options → Mods: accende, ordina e sposta nel Cestino le mod RomFS, apre la cartella mods. | | [Sources/NXLibrary/Views/Detail/ModDetailPanel.swift](../Sources/NXLibrary/Views/Detail/ModDetailPanel.swift) | Dettaglio di una mod GameBanana: immagini, autore, versione, descrizione, Install/Update e link. | | [Sources/NXLibrary/Views/Detail/GameBananaFindPanel.swift](../Sources/NXLibrary/Views/Detail/GameBananaFindPanel.swift) | Cerca su GameBanana la pagina del gioco quando l'abbinamento automatico non basta. | -| [Sources/NXLibrary/ViewModels/ModStoreHost.swift](../Sources/NXLibrary/ViewModels/ModStoreHost.swift) | Store della card Mods: catalogo, ordinamento, focus, chip Installed/Update e pannello della mod. | +| [Sources/NXLibrary/ViewModels/ModStoreHost.swift](../Sources/NXLibrary/ViewModels/ModStoreHost.swift) | Store della card Mods: mantiene la cover fra schermate, rivalida abbinamenti e snapshot; rilegge i badge a ogni apertura e scarta i risultati di generazioni precedenti. | | [Sources/NXLibrary/Views/Store/ModStorePage.swift](../Sources/NXLibrary/Views/Store/ModStorePage.swift) | Pagina dello store: barra di ordinamento, banner Featured, righe di tessere; disegna solo le sezioni vicine al focus. | | [Sources/NXLibrary/Views/Store/GameBananaBlur.swift](../Sources/NXLibrary/Views/Store/GameBananaBlur.swift) | Arte di una mod rimpicciolita e sfocata una volta, fuori dal main thread, e tenuta in memoria: sfondo del Featured. | -| [Sources/NXLibrary/ViewModels/ModsBandHost.swift](../Sources/NXLibrary/ViewModels/ModsBandHost.swift) | Fascia Mods condivisa da Spotlight e Details: mod installate, GameBanana, pannelli di dettaglio e ricerca. | +| [Sources/NXLibrary/ViewModels/ModsBandHost.swift](../Sources/NXLibrary/ViewModels/ModsBandHost.swift) | Fascia Mods condivisa da Spotlight e Details. Legge mod installate, coordina GameBanana e pannelli, svuota i dati del gioco precedente sulla riga Spotlight. | | [Sources/NXLibrary/ViewModels/GameBananaServices.swift](../Sources/NXLibrary/ViewModels/GameBananaServices.swift) | Client, cache delle immagini e abbinamenti GameBanana condivisi da tutta l'app. | | [Sources/NXLibrary/Views/GameOptions/SavesPanel.swift](../Sources/NXLibrary/Views/GameOptions/SavesPanel.swift) | Presenta azioni sui save, anteprime, errori e popup di successo a scomparsa automatica. | | [Sources/NXLibrary/Views/GameOptions/MoreSettingsPanel.swift](../Sources/NXLibrary/Views/GameOptions/MoreSettingsPanel.swift) | Mostra le impostazioni del launcher.json senza riga dedicata: interruttori, scelte e intervalli; le righe fissate da env.txt restano attenuate. | @@ -365,31 +484,42 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| -| [Sources/NXLibrary/Views/Settings/SettingsView.swift](../Sources/NXLibrary/Views/Settings/SettingsView.swift) | Compone sidebar e gruppo attivo e coordina focus, input e reset delle impostazioni. | -| [Sources/NXLibrary/Views/Settings/SettingsSidebar.swift](../Sources/NXLibrary/Views/Settings/SettingsSidebar.swift) | Disegna intestazione e lista dei gruppi della schermata Settings. | +| [Sources/NXLibrary/Views/Settings/SettingsView.swift](../Sources/NXLibrary/Views/Settings/SettingsView.swift) | Compone sidebar e gruppo attivo e coordina focus, input e reset; nella Dev registra apertura e stato del fullscreen per la diagnosi della transizione. | +| [Sources/NXLibrary/Views/Settings/SettingsSidebar.swift](../Sources/NXLibrary/Views/Settings/SettingsSidebar.swift) | Disegna intestazione e sezioni sotto le intestazioni di gruppo (General, Switch, Steam, System). | | [Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift](../Sources/NXLibrary/Views/Settings/SettingsSectionContent.swift) | Instrada il gruppo selezionato e fornisce sottotitoli e formattazioni condivise. | | [Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSearchSection.swift) | Presenta ricerca e Changed, con apertura del gruppo della riga selezionata. | -| [Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift) | Espone schermata iniziale, intro, Setup e controlli degli aggiornamenti all’avvio. | +| [Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStartUpSection.swift) | Espone schermata iniziale, animazione d’entrata, Setup e controlli degli aggiornamenti all’avvio. | | [Sources/NXLibrary/Views/Settings/SettingsNavigationSection.swift](../Sources/NXLibrary/Views/Settings/SettingsNavigationSection.swift) | Espone le preferenze di navigazione e dei suggerimenti dei tasti. | | [Sources/NXLibrary/Views/Settings/SettingsSpotlightSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSpotlightSection.swift) | Espone card, ordine e preferenze della home Spotlight. | | [Sources/NXLibrary/Views/Settings/SettingsSoundSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSoundSection.swift) | Espone volume e suoni e importa risorse da una cartella Selene. | | [Sources/NXLibrary/Views/Settings/SettingsLookSection.swift](../Sources/NXLibrary/Views/Settings/SettingsLookSection.swift) | Espone palette, wallpaper, luminosità, adattamento, animazione e aspetto dell’icona. | -| [Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift) | Espone default runtime, cloud saves e gestione dei giochi nascosti. | -| [Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift](../Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift) | Espone preferenze dei controller e relative azioni di gruppo. | +| [Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsGamesSection.swift) | Porting → New games: default copiati nei nuovi giochi convertiti, vibrazione compresa. | +| [Sources/NXLibrary/Views/Settings/SettingsLibraryGamesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsLibraryGamesSection.swift) | Library → Games: schermata di lancio, Surprise me, card della sessione e giochi nascosti. | +| [Sources/NXLibrary/Views/Settings/SettingsCloudSavesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsCloudSavesSection.swift) | Porting → Cloud saves: scelta e cartella; chiarisce che sincronizzano solo primario e device. | +| [Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift](../Sources/NXLibrary/Views/Settings/SettingsControllersSection.swift) | Espone controller, schema dei tasti e zona morta per la libreria. | | [Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift](../Sources/NXLibrary/Views/Settings/SettingsLibrarySection.swift) | Espone cartella della libreria, scansione e notifiche dei porting. | -| [Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift) | Mostra spazio occupato, azioni su cache/log e accesso alla cartella comune dei backup verificati. | -| [Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift](../Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift) | Mostra checkout, pin, gate, toolchain, runtime, chiavi e changelog upstream. | -| [Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift](../Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift) | Mostra versione, attribuzioni, diagnostica, documentazione e aggiornamenti dell’app. | +| [Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift](../Sources/NXLibrary/Views/Settings/SettingsStorageSection.swift) | Library → Storage: spazio occupato, log, cache di metadati e artwork, cartella comune dei backup verificati. | +| [Sources/NXLibrary/Views/Settings/SettingsPortingStorageSection.swift](../Sources/NXLibrary/Views/Settings/SettingsPortingStorageSection.swift) | Porting → Storage: cache di compilazione per gioco, dalla più grande, e per tutti i giochi, con conferma. | +| [Sources/NXLibrary/Views/Settings/SettingsConsoleSection.swift](../Sources/NXLibrary/Views/Settings/SettingsConsoleSection.swift) | System → Console: apre la console dei log di build e avvio. | +| [Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift](../Sources/NXLibrary/Views/Settings/SettingsEngineSection.swift) | Porting → Setup and engine: checkout, pin, gate, toolchain, runtime, changelog upstream e Setup. | +| [Sources/NXLibrary/Views/Settings/SettingsKeysSection.swift](../Sources/NXLibrary/Views/Settings/SettingsKeysSection.swift) | Porting → Keys: stato, importazione, sostituzione e rilevamento di prod.keys. | +| [Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift](../Sources/NXLibrary/Views/Settings/SettingsAboutSection.swift) | Mostra versione, diagnostica, aggiornamenti, pulsante di sostegno volontario, crediti e documentazione. | +| [Sources/NXLibrary/Views/Settings/LocalePicker.swift](../Sources/NXLibrary/Views/Settings/LocalePicker.swift) | Scelta diretta della lingua e ricerca dei formati regionali, con focus tastiera/controller e codici stabili. | ## UI · Setup, avvio, ricerca e console | File | Responsabilità | |---|---| | [Sources/NXLibrary/Views/Setup/SetupCheckView.swift](../Sources/NXLibrary/Views/Setup/SetupCheckView.swift) | Disegna schede dei requisiti, dettagli, progressi e pulsanti Install all/Continue. | -| [Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift](../Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift) | Gestisce focus iniziale, navigazione della griglia e attivazione delle schede Setup. | -| [Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift](../Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift) | Disegna scelta cartella, primo gioco, apertura libreria e Skip; condivide l'indicatore dei due passaggi e gestisce mouse, tastiera e controller. | -| [Sources/NXLibrary/Views/Launch/IntroView.swift](../Sources/NXLibrary/Views/Launch/IntroView.swift) | Mostra l’intro a freddo (solo lo sfondo animato, senza icona né scritta) e gestisce il salto tramite input. | -| [Sources/NXLibrary/Views/Launch/LaunchScreenView.swift](../Sources/NXLibrary/Views/Launch/LaunchScreenView.swift) | Mostra artwork e logo durante l’avvio del gioco e chiude l’overlay a finestra visibile. | +| [Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift](../Sources/NXLibrary/Views/Setup/SetupCheckView+Input.swift) | Gestisce focus iniziale, navigazione della griglia, attivazione delle schede Setup e B verso `found` durante il primo avvio. | +| [Sources/NXLibrary/Views/Setup/ArcaneWelcomeView.swift](../Sources/NXLibrary/Views/Setup/ArcaneWelcomeView.swift) | Disegna il benvenuto in Arcane: nome nuovo, novità, offerta Steam dalla cartella scelta, Add / Not now e Open library. | +| [Sources/NXLibrary/Views/Setup/ArcaneWelcomeView+Input.swift](../Sources/NXLibrary/Views/Setup/ArcaneWelcomeView+Input.swift) | Gestisce focus, mouse, tastiera e controller del benvenuto. | +| [Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift](../Sources/NXLibrary/Views/Setup/FoundGamesSetupView.swift) | Prima pagina del Setup: Steam con interruttore o Retry, app portate e card Porting; Open library resta disponibile durante la lettura. | +| [Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift](../Sources/NXLibrary/Views/Setup/FoundGamesSetupView+Input.swift) | Focus, mouse, tastiera e controller di found; Retry della lettura Steam e uscita che annulla la richiesta prima di aprire la libreria. | +| [Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift](../Sources/NXLibrary/Views/Setup/YourGamesSetupView.swift) | Disegna scelta cartella, primo gioco, apertura libreria e Skip; gestisce mouse, tastiera e controller; contiene `SetupCardRow`, la riga condivisa con `found`. | +| [Sources/NXLibrary/Views/Launch/LaunchScreenView.swift](../Sources/NXLibrary/Views/Launch/LaunchScreenView.swift) | Mostra artwork e logo per nxnative e Steam. Sfuma anche quando la finestra del gioco è già pronta alla comparsa. | +| [Sources/NXLibrary/Views/Launch/LaunchMotion.swift](../Sources/NXLibrary/Views/Launch/LaunchMotion.swift) | Movimento della schermata di lancio in Core Animation: artwork che si avvicina e logo del gioco che sale una volta. Con Riduci movimento resta la dissolvenza del logo. | +| [Sources/NXLibrary/Views/Launch/LaunchCoverWindow.swift](../Sources/NXLibrary/Views/Launch/LaunchCoverWindow.swift) | Ordina la finestra d’attesa sopra ogni app e Space e avvisa il coordinatore dopo aver inviato il pannello al server delle finestre. | | [Sources/NXLibrary/Views/Search/FindGameView.swift](../Sources/NXLibrary/Views/Search/FindGameView.swift) | Presenta ricerca nella libreria e risultati navigabili e inoltra il gioco scelto alla home. | | [Sources/NXLibrary/Views/Console/ConsoleView.swift](../Sources/NXLibrary/Views/Console/ConsoleView.swift) | Mostra log e stato corrente e offre copia di log e diagnostica. | | [Sources/NXLibrary/Views/ControlsView.swift](../Sources/NXLibrary/Views/ControlsView.swift) | Guida Selene separata fra Library e In game; stato controller, rilevamento e scorrimento delle righe con tastiera/controller. | @@ -401,17 +531,19 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibrary/Views/Components/BuildLiveLogsDrawer.swift](../Sources/NXLibrary/Views/Components/BuildLiveLogsDrawer.swift) | Mostra il log del porting con livelli, scroll sul nuovo contenuto e apertura o chiusura. | | [Sources/NXLibrary/Views/Components/BuildStageStepperView.swift](../Sources/NXLibrary/Views/Components/BuildStageStepperView.swift) | Disegna elenco delle fasi e relativo stato di completamento. | | [Sources/NXLibrary/Views/Components/DropZoneView.swift](../Sources/NXLibrary/Views/Components/DropZoneView.swift) | Presenta la zona di trascinamento per scegliere le sorgenti del gioco. | -| [Sources/NXLibrary/Views/Components/GameIconProvider.swift](../Sources/NXLibrary/Views/Components/GameIconProvider.swift) | Fornisce e conserva l’icona estratta dai bundle dei giochi. | +| [Sources/NXLibrary/Views/Components/GameIconProvider.swift](../Sources/NXLibrary/Views/Components/GameIconProvider.swift) | Fornisce e conserva l’icona estratta dai bundle dei giochi; ricorda anche quando manca. | | [Sources/NXLibrary/Views/Components/PortingArtLook.swift](../Sources/NXLibrary/Views/Components/PortingArtLook.swift) | Applica alla tile desaturazione, riempimento e barra di avanzamento del porting. | | [Sources/NXLibrary/Views/Components/ScreenshotViewer.swift](../Sources/NXLibrary/Views/Components/ScreenshotViewer.swift) | Mostra screenshot a schermo pieno e navigazione fra le immagini. | -| [Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift](../Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift) | Definisce maschera inferiore e spazi riservati ai suggerimenti dei tasti. | +| [Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift](../Sources/NXLibrary/Views/Components/SeleneBottomScrim.swift) | Definisce sfumatura inferiore, posizione condivisa dei comandi (32 unità dal fondo) e fascia libera dai contenuti. | | [Sources/NXLibrary/Views/Components/SeleneConfirmDialog.swift](../Sources/NXLibrary/Views/Components/SeleneConfirmDialog.swift) | Definisce card e pulsanti delle conferme, scelte multiple e SeleneSuccessNotice. | | [Sources/NXLibrary/Views/Components/AppUpdateDialog.swift](../Sources/NXLibrary/Views/Components/AppUpdateDialog.swift) | Presenta controllo aggiornamenti, note di release, errori e progresso nel dialogo dell’app. | -| [Sources/NXLibrary/Views/Components/SeleneHintsBar.swift](../Sources/NXLibrary/Views/Components/SeleneHintsBar.swift) | Disegna i suggerimenti contestuali allineati ai bordi inferiori della schermata. | -| [Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift](../Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift) | Rende elementi condivisi della cornice e dei controlli della home Selene. | +| [Sources/NXLibrary/Views/Components/SeleneHintsBar.swift](../Sources/NXLibrary/Views/Components/SeleneHintsBar.swift) | Disegna i suggerimenti contestuali alla posizione condivisa, con grandezza dei simboli invariata. | +| [Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift](../Sources/NXLibrary/Views/Components/SeleneHomeChrome.swift) | Rende elementi condivisi della cornice e dei controlli della home Selene; trattiene gli hint durante l’entrata. | | [Sources/NXLibrary/Views/Components/SeleneOptionRow.swift](../Sources/NXLibrary/Views/Components/SeleneOptionRow.swift) | Disegna righe di opzioni con icona, titolo, descrizione, focus e contenuto laterale. | +| [Sources/NXLibrary/Views/Components/SeleneExpandableText.swift](../Sources/NXLibrary/Views/Components/SeleneExpandableText.swift) | Rivela la descrizione completa animando l'altezza fra due layout di testo stabili; usato solo dalle righe dei metadati. | | [Sources/NXLibrary/Views/Components/SelenePillButton.swift](../Sources/NXLibrary/Views/Components/SelenePillButton.swift) | Disegna il pulsante pill condiviso da azioni e dialoghi. | | [Sources/NXLibrary/Views/Components/SelenePromptBadge.swift](../Sources/NXLibrary/Views/Components/SelenePromptBadge.swift) | Rende simbolo o etichetta del pulsante del controller o della tastiera. | +| [Sources/NXLibrary/Views/Components/GlideGroup.swift](../Sources/NXLibrary/Views/Components/GlideGroup.swift) | Fa muovere un blocco come un pezzo unico durante una scivolata (pagina Spotlight, lista Achievements, pannello Mod, pagina gioco, riga Collection): una dissolvenza, un'immagine che arriva o un'altra animazione non fanno più correre i singoli elementi a velocità diversa. Usa `geometryGroup`, quindi richiede macOS 14. | | [Sources/NXLibrary/Views/Components/SeleneReveal.swift](../Sources/NXLibrary/Views/Components/SeleneReveal.swift) | Applica l’animazione di comparsa Selene rispettando la preferenza Riduci movimento. | | [Sources/NXLibrary/Views/Components/SeleneSettingsRow.swift](../Sources/NXLibrary/Views/Components/SeleneSettingsRow.swift) | Disegna righe delle impostazioni con valore, focus e azione. | | [Sources/NXLibrary/Views/Components/SeleneStatsRow.swift](../Sources/NXLibrary/Views/Components/SeleneStatsRow.swift) | Disegna le statistiche compatte del gioco nella libreria. | @@ -419,10 +551,14 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibrary/Views/Components/SeleneTileRing.swift](../Sources/NXLibrary/Views/Components/SeleneTileRing.swift) | Ring e riflesso della tile selezionata; con Reduce motion il ring fermo disegnato da SwiftUI. | | [Sources/NXLibrary/Views/Components/TileMotionLayers.swift](../Sources/NXLibrary/Views/Components/TileMotionLayers.swift) | Ring e riflesso come layer Core Animation in loop: nessun ridisegno dell'app tra un frame e l'altro. | | [Sources/NXLibrary/Views/Components/SeleneValueChip.swift](../Sources/NXLibrary/Views/Components/SeleneValueChip.swift) | Rende valori e badge compatti nel linguaggio visivo Selene. | -| [Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift](../Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift) | Carica e disegna l’artwork quadrato usato dalle tile Spotlight. | +| [Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift](../Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift) | Disegna subito l’icona nxnative già decodificata; cache condivisa `TileArtMemo` con fonte e revisione delle scelte, caricamento annullabile e segnale `TileArtPendingKey`. | | [Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift](../Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift) | Carica e disegna la copertina Switch mantenendone le proporzioni. | | [Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift](../Sources/NXLibrary/Views/Components/SteamGridDBKeyDialog.swift) | Popup per incollare e verificare la chiave SteamGridDB da Settings → Look e da Change artwork. | | [Sources/NXLibrary/Views/Components/SwitchPlatformIcon.swift](../Sources/NXLibrary/Views/Components/SwitchPlatformIcon.swift) | Icona vettoriale della console Switch per la riga della piattaforma. | +| [Sources/NXLibrary/Views/Components/SteamPlatformLogo.swift](../Sources/NXLibrary/Views/Components/SteamPlatformLogo.swift) | Logo ufficiale Steam per la piattaforma dei giochi Steam: da solo, almeno 50 pixel, spazio libero della manovella. | +| [Sources/NXLibrary/Views/Components/GameLogoArea.swift](../Sources/NXLibrary/Views/Components/GameLogoArea.swift) | Area del logo del gioco con la geometria condivisa da Spotlight e Collection; caricamento e impostazioni restano fuori. | +| [Sources/NXLibrary/Views/Components/GamePrimaryActions.swift](../Sources/NXLibrary/Views/Components/GamePrimaryActions.swift) | Play, Options e preferito con lo stesso aspetto e gli stessi bersagli di input per ogni fonte; i puntini di «Porting» e «Downloading». | +| [Sources/NXLibrary/Views/Components/SessionCard.swift](../Sources/NXLibrary/Views/Components/SessionCard.swift) | Card di fine sessione: aspetta che Arcane sia davanti, compare 1,8 s dopo per 8 s; una sessione più recente sostituisce quella in attesa. | ## UI · temi, rendering e sfondi @@ -432,13 +568,46 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Sources/NXLibrary/Views/Theme/SeleneTheme.swift](../Sources/NXLibrary/Views/Theme/SeleneTheme.swift) | Espone colori, stili, curve di animazione, focus e chiavi dell’ambiente Selene. | | [Sources/NXLibrary/Views/Theme/SeleneFonts.swift](../Sources/NXLibrary/Views/Theme/SeleneFonts.swift) | Registra il font incluso e definisce MaterialIconView. | | [Sources/NXLibrary/Views/Theme/SeleneCanvasEnvironment.swift](../Sources/NXLibrary/Views/Theme/SeleneCanvasEnvironment.swift) | Pubblica il canvas della finestra e applica unità e font scalati. | -| [Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift](../Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift) | Compone gradiente, wallpaper e Moonlight e conserva le immagini già decodificate. | -| [Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift](../Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift) | Gestisce device Metal, pipeline, display link, particelle e rendering live o statico del backdrop. | -| [Sources/NXLibrary/Views/Theme/MoonlightShaders.swift](../Sources/NXLibrary/Views/Theme/MoonlightShaders.swift) | Contiene le sorgenti shader Metal dello sfondo compilate a runtime. | +| [Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift](../Sources/NXLibrary/Views/Theme/SeleneBackdrop.swift) | Nella shell dichiara la richiesta di sfondo condiviso, fuori dalla shell disegna; consuma lo snapshot completo della palette e compone gradiente, wallpaper e Moonlight a particelle morbide; conserva le immagini decodificate e il fallback statico. | +| [Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift](../Sources/NXLibrary/Views/Theme/MoonlightRenderer.swift) | Gestisce Metal, display link e rendering live/statico; su entrambi i percorsi il primo drawable presentato sblocca `LaunchReveal`. Da macOS 14 disegna solo il `CAMetalDisplayLink`, anche il frame fermo; nella Dev registra creazione e prima presentazione. | +| [Sources/NXLibrary/Views/Theme/MoonlightShaders.swift](../Sources/NXLibrary/Views/Theme/MoonlightShaders.swift) | Contiene gli shader Metal del Moonlight, superfici analitiche Arcane/Flow, filamenti sottili antialias piegati da onde viaggianti e particelle morbide, compilati a runtime. | | [Sources/NXLibrary/Views/Theme/LiveBackdrop.swift](../Sources/NXLibrary/Views/Theme/LiveBackdrop.swift) | Integra video AVFoundation in loop e adatta riproduzione e frame alla visibilità della finestra. | | [Sources/NXLibrary/Views/Theme/OnlineBrowsePanel.swift](../Sources/NXLibrary/Views/Theme/OnlineBrowsePanel.swift) | Mantiene stato di ricerca e download e presenta griglia e miniature degli sfondi online. | -| [Sources/NXLibrary/Views/Theme/ThemePickerView.swift](../Sources/NXLibrary/Views/Theme/ThemePickerView.swift) | Presenta palette, tab Wallpapers/Live, provider e scelta della destinazione dello sfondo. | -| [Sources/NXLibrary/Views/Theme/ThemePreview.swift](../Sources/NXLibrary/Views/Theme/ThemePreview.swift) | Disegna un’anteprima della home con palette e sfondo in valutazione. | +| [Sources/NXLibrary/Views/Theme/ThemePickerView.swift](../Sources/NXLibrary/Views/Theme/ThemePickerView.swift) | Presenta i colori con anteprima viva nel primo passo; sfondi, provider e destinazione nel passo successivo. | +| [Sources/NXLibrary/Views/Theme/ThemePreview.swift](../Sources/NXLibrary/Views/Theme/ThemePreview.swift) | Disegna un’anteprima della home con palette, sfondo e particelle morbide; il movimento segue le preferenze. | +| [Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift](../Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift) | Contesto della lingua reattivo per le viste; conserva identità, selezione e focus. | + +## UI · fonti, Steam e libreria mista + +| File | Responsabilità | +|---|---| +| [AppViewModel+Catalog.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Catalog.swift) | Rilettura, errori e retry del risultato di build senza libreria di ripiego. | +| [CatalogPersonalizationsEnvironment.swift](../Sources/NXLibrary/Views/Theme/CatalogPersonalizationsEnvironment.swift) | Dipendenza SwiftUI esplicita per le chiavi personali stabili. | +| [AppViewModel+Sources.swift](../Sources/NXLibrary/ViewModels/AppViewModel+Sources.swift) | Proiezione visibile, selezione comune e modifiche personali tipizzate. | +| [SettingsSourcesSection.swift](../Sources/NXLibrary/Views/Settings/SettingsSourcesSection.swift) | Attivazione, refresh/cancel, cartella Steam, avvio in background, revisione e recupero dei nascosti. | +| [CatalogNativeArtwork.swift](../Sources/NXLibrary/Views/Catalog/CatalogNativeArtwork.swift) | Icona nativa in sola lettura e indicatore Steam; nessun artwork Nintendo. | +| [CatalogSteamInfo.swift](../Sources/NXLibrary/Views/Catalog/CatalogSteamInfo.swift) | Intestazione condivisa nelle due librerie: Play/Riprendi/Annulla/Riprova, Opzioni e preferito, con la nota di stato. | +| [SteamPlayCoordinator.swift](../Sources/NXLibrary/Services/SteamPlayCoordinator.swift) | Play tramite il client verificato dopo la preparazione della schermata. La schermata copre Steam durante l'attesa. Sessioni dal processo dell’app installata. | +| [SteamPlaytimeCoordinator.swift](../Sources/NXLibrary/Services/SteamPlaytimeCoordinator.swift) | Una lettura alla volta delle ore di Steam fuori dal thread principale; applica `SteamPlaytimeSync` e passa i totali a `PlaySessionStore`. | +| [SteamOptionsView.swift](../Sources/NXLibrary/Views/GameOptions/SteamOptionsView.swift) | Opzioni di un gioco Steam con l’aspetto e l’input di Game options: Play, Edit details, Move, preferito, nascosto, Finder. | +| [PersonalizationSubject.swift](../Sources/NXLibrary/Views/GameOptions/PersonalizationSubject.swift) | Il gioco che Change artwork e Change metadata personalizzano: scelte nxnative o archivio personale Steam, senza icona Mac per Steam. | +| [SteamGamePage.swift](../Sources/NXLibrary/Views/Catalog/SteamGamePage.swift) | Dati store Steam dei giochi a schermo, una copia condivisa da Spotlight e Collection, per AppID e lingua; una risposta per un gioco o una lingua non più chiesti si scarta. | +| [SteamArtwork.swift](../Sources/NXLibrary/Views/Catalog/SteamArtwork.swift) | Immagini Steam con cache disponibile prima del task, identità di richiesta/build e ripiego già letto; rivalidazione dei file, scelte personali, annullamento e `TileArtPendingKey`. | +| [SteamPersonalizations.swift](../Sources/NXLibrary/Views/Catalog/SteamPersonalizations.swift) | Archivio delle scelte personali Steam (metadati e artwork), modificate da Change artwork e Change metadata. | + +## UI · achievement + +| File | Responsabilità | +|---|---| +| [SteamAchievementsStore.swift](../Sources/NXLibrary/Services/SteamAchievementsStore.swift) | Legge gli achievement fuori dal thread principale (selezione, apertura della schermata e, per il gioco selezionato, fine di una sessione Steam: subito e dopo un minuto), uno per AppID alla volta; tiene gli ultimi 16 giochi e aggiunge la rarità quando arriva. | +| [ArcaneOrbVideo.swift](../Sources/NXLibrary/Views/Spotlight/ArcaneOrbVideo.swift) | L'Arcane della card come video: grigio e fermo a riposo, a colori e in movimento con hover o focus, si ferma sul suo fotogramma e riparte da lì; colore, luce e scala animati da Core Animation. Usato anche, grande e sempre attivo, in testa alla schermata Achievements quando l'Arcane è conquistato. | +| [DetailsAchievementsCard.swift](../Sources/NXLibrary/Views/Detail/DetailsAchievementsCard.swift) | Card Achievements in cima alla colonna destra della pagina, sopra il pannello Details; prende il focus e apre la schermata. | +| [AchievementIcon.swift](../Sources/NXLibrary/Views/Detail/AchievementIcon.swift) | Icona di un achievement dalla cache di `SteamMetadataService`, decodificata fuori dal thread principale e tenuta in memoria (niente lampo quando una riga torna in vista), con un riquadro neutro finché manca; un segreto non sbloccato è sfocato sotto un lucchetto. | +| [AchievementsScreen.swift](../Sources/NXLibrary/Views/Spotlight/AchievementsScreen.swift) | Schermata Achievements sopra l’arte del gioco, impaginata come Selene: logo e sbloccati di recente a sinistra; a destra i cristalli per tier con sotto percentuale, barra larga quanto i quattro cristalli e conteggio (`TrophyColumn`), oppure, a gioco completato, il medaglione dell’Arcane (video, nome, conteggio e piccoli cristalli Oro/Argento/Bronzo); filtri tra LB e RB (Q/E su tastiera), ordine (Y) in basso a destra accanto a Open, con Q/E e LB/RB compatti ai lati delle categorie e barra alla posizione condivisa; lista e sfumatura lasciano libera la fascia dei comandi e lista in una colonna mossa da un offset proprio (niente ScrollView), disegnando solo le righe in vista. | +| [AchievementDetail.swift](../Sources/NXLibrary/Views/Spotlight/AchievementDetail.swift) | Dettaglio di un obiettivo come medaglione (A sulla riga o clic sulla riga in focus): icona grande con il cristallo della tier come piccolo distintivo sull’angolo, nome e descrizione interi centrati, percentuale dei giocatori, data di sblocco; le frecce scorrono la lista, A/B o un clic fuori chiudono. | +| [TierCrystal.swift](../Sources/NXLibrary/Views/Spotlight/TierCrystal.swift) | Il cristallo di una tier dalle risorse del Core, decodificato una volta; non ancora ottenuto, tenue con una traccia del suo colore, così oro, argento e bronzo restano distinguibili. | +| [AchievementsScreenModel.swift](../Sources/NXLibrary/ViewModels/AchievementsScreenModel.swift) | Schermata Achievements aperta: selezione, filtro, input e scorrimento della lista; un riferimento, così un passo non ridisegna la Spotlight sotto. Dopo la rotella la prima freccia porta il fuoco alla riga in vista più vicina. | +| [ListScroll.swift](../Sources/NXLibrary/ViewModels/ListScroll.swift) | Offset di una lista (`TextScroll`) con la planata del pannello delle mod: rotella, trackpad e frecce muovono lo stesso valore. | ## Test e fixture @@ -453,11 +622,15 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| | [Tests/NXLibraryCoreTests/ActivitySummaryTests.swift](../Tests/NXLibraryCoreTests/ActivitySummaryTests.swift) | Totali settimanali, distribuzione giornaliera, sessioni aperte e passaggi di mezzanotte. | -| [Tests/NXLibraryCoreTests/AppRouterTests.swift](../Tests/NXLibraryCoreTests/AppRouterTests.swift) | Route iniziale, ritorno, overlay e richieste di selezione o spostamento. | -| [Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift](../Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift) | Default, persistenza, errori osservabili, conservazione dei file illeggibili e compatibilità dei campi mancanti. | +| [Tests/NXLibraryCoreTests/AppBundleRenameTests.swift](../Tests/NXLibraryCoreTests/AppBundleRenameTests.swift) | Rinomina alla chiusura: nome vecchio, `Arcane.app` già presente, cartella in sola lettura, copia Dev, traslocata o occupata, altri nomi, spostamento fallito. | +| [Tests/NXLibraryCoreTests/AppRouterTests.swift](../Tests/NXLibraryCoreTests/AppRouterTests.swift) | Route iniziale, ritorno, overlay, richieste Spotlight e precedenza/occlusione delle coperture fullscreen. | +| [Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift](../Tests/NXLibraryCoreTests/AppSettingsStoreTests.swift) | Default, errori, recupero, compatibilità e ultima selezione persistita in background e alla chiusura, senza invalidare gli osservatori. | | [Tests/NXLibraryCoreTests/AppSizeCacheTests.swift](../Tests/NXLibraryCoreTests/AppSizeCacheTests.swift) | Riuso delle dimensioni, invalidazione sui bundle modificati e scansione senza falso stato vuoto. | -| [Tests/NXLibraryCoreTests/AppUpdateTests.swift](../Tests/NXLibraryCoreTests/AppUpdateTests.swift) | Versioni, asset release, requisiti, digest, identità del bundle e sostituzione dell’app. | +| [Tests/NXLibraryCoreTests/AppUpdateTests.swift](../Tests/NXLibraryCoreTests/AppUpdateTests.swift) | Versioni, asset release, requisiti, digest, identità del bundle, collisioni con copie esistenti e guasti di copia, scambio e Cestino. | | [Tests/NXLibraryCoreTests/AppUpdatePresentationTests.swift](../Tests/NXLibraryCoreTests/AppUpdatePresentationTests.swift) | Verifica che i controlli manuali non permettano sostituzioni di copie di sviluppo, in sola lettura o con una versione uguale/più recente. | +| [Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift](../Tests/NXLibraryCoreTests/ArcaneWelcomeTests.swift) | Una volta dopo l'aggiornamento, mai dopo un primo Setup né con un recupero in corso, decodifica di un file vecchio, offerta di Steam, focus e uscite. | +| [Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift](../Tests/NXLibraryCoreTests/ShellOverlayInputTests.swift) | Ogni monitor della tastiera che cede all'offerta di aggiornamento cede anche al benvenuto, così Invio non arriva alla schermata sotto. | +| [Tests/NXLibraryCoreTests/ArcaneNameTests.swift](../Tests/NXLibraryCoreTests/ArcaneNameTests.swift) | Nessun testo del catalogo, in nessuna lingua, mostra il vecchio nome; User-Agent con il nome Arcane e nessuna sorgente con il vecchio. | | [Tests/NXLibraryCoreTests/ArtworkPickerFocusTests.swift](../Tests/NXLibraryCoreTests/ArtworkPickerFocusTests.swift) | Spostamenti nella griglia dei candidati e passaggi fra slot di artwork. | | [Tests/NXLibraryCoreTests/ArtworkPickerTests.swift](../Tests/NXLibraryCoreTests/ArtworkPickerTests.swift) | Decodifica Title DB, candidati per slot e scelte manuali. | | [Tests/NXLibraryCoreTests/AutomaticIconTests.swift](../Tests/NXLibraryCoreTests/AutomaticIconTests.swift) | Priorità delle fonti, ambiguità, edizioni, cache offline, immagini invalide e opt-out del sito. | @@ -467,7 +640,7 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Tests/NXLibraryCoreTests/BuildEventParserTests.swift](../Tests/NXLibraryCoreTests/BuildEventParserTests.swift) | Eventi JSON, fasi, percentuali e righe ordinarie di log. | | [Tests/NXLibraryCoreTests/BuildOutputInstallerTests.swift](../Tests/NXLibraryCoreTests/BuildOutputInstallerTests.swift) | Pubblicazione atomica, interruzioni, tentativi ripetuti, copie fra volumi e conservazione dei bundle in caso di errore. | | [Tests/NXLibraryCoreTests/BuildScratchTests.swift](../Tests/NXLibraryCoreTests/BuildScratchTests.swift) | Posto dei file di build per Mac, disco esterno, exFAT e workspaces spostati; workspace gestiti e cartelle temporanee. | -| [Tests/NXLibraryCoreTests/BuildServiceTests.swift](../Tests/NXLibraryCoreTests/BuildServiceTests.swift) | Processi, eventi, cancellazione, lease e conservazione della build dopo un errore d’installazione, con retry senza nuova esecuzione del motore. | +| [Tests/NXLibraryCoreTests/BuildServiceTests.swift](../Tests/NXLibraryCoreTests/BuildServiceTests.swift) | Processi, eventi, cancellazione, lease e conservazione della build dopo un errore d’installazione, con retry senza nuova esecuzione del motore; un avvio fallito non lascia file aperti. | | [Tests/NXLibraryCoreTests/GameAppDestinationTests.swift](../Tests/NXLibraryCoreTests/GameAppDestinationTests.swift) | Installazione e scoperta nella cartella scelta, rebuild dopo il cambio cartella, conflitti di nome, sorgenti protette e cartelle non disponibili o di sola lettura. | | [Tests/NXLibraryCoreTests/ButtonPromptsTests.swift](../Tests/NXLibraryCoreTests/ButtonPromptsTests.swift) | Etichette e simboli per tastiera, controller e scelte esplicite dell’utente. | | [Tests/NXLibraryCoreTests/CheatCopyTests.swift](../Tests/NXLibraryCoreTests/CheatCopyTests.swift) | Testi di intestazione, rifiuto, conferma e rimozione dei cheats. | @@ -512,16 +685,17 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift](../Tests/NXLibraryCoreTests/LaunchBoxArtTests.swift) | Risultati di ricerca, scelta della voce Switch/Switch 2, payload Nuxt con file pieni e screenshot. | | [Tests/NXLibraryCoreTests/LibraryPresentationTests.swift](../Tests/NXLibraryCoreTests/LibraryPresentationTests.swift) | Formattazione dei metadati e delle statistiche della libreria. | | [Tests/NXLibraryCoreTests/LibraryQueryTests.swift](../Tests/NXLibraryCoreTests/LibraryQueryTests.swift) | Filtri, ricerca, ordinamento e rapporto con la cronologia di gioco. | -| [Tests/NXLibraryCoreTests/LibraryStoreTests.swift](../Tests/NXLibraryCoreTests/LibraryStoreTests.swift) | Persistenza, merge, recupero e conservazione di installazioni in attesa ed errori dopo scansioni ripetute. | +| [Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift](../Tests/NXLibraryCoreTests/NXNativeCatalogPersistenceTests.swift) | Persistenza e merge nxnative attraverso il repository attuale: sorgenti, impostazioni, preferiti, installazioni in attesa e dettagli degli errori. Recupero e conversione legacy sono verificati da CatalogStoreTests. | | [Tests/NXLibraryCoreTests/MaterialIconTests.swift](../Tests/NXLibraryCoreTests/MaterialIconTests.swift) | Integrità dei glifi e del font delle icone. | | [Tests/NXLibraryCoreTests/MetadataPickerTests.swift](../Tests/NXLibraryCoreTests/MetadataPickerTests.swift) | Alternative per campo, override persistiti e applicazione ai metadati del gioco. | | [Tests/NXLibraryCoreTests/MoonlightFieldTests.swift](../Tests/NXLibraryCoreTests/MoonlightFieldTests.swift) | Generazione deterministica e limiti dei dati delle particelle. | +| [MoonlightAppearanceTests.swift](../Tests/NXLibraryCoreTests/MoonlightAppearanceTests.swift) | Ignora la preferenza storica delle particelle senza perdere altri valori; continuità del ciclo e bordi della griglia colori. | | [Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift](../Tests/NXLibraryCoreTests/MoreArtworkSourcesTests.swift) | Matching dei titoli e risposte delle sorgenti artwork aggiuntive. | -| [Tests/NXLibraryCoreTests/MoreLikeThisTests.swift](../Tests/NXLibraryCoreTests/MoreLikeThisTests.swift) | Ranking dei giochi correlati e gestione di metadati incompleti. | +| [Tests/NXLibraryCoreTests/MoreLikeThisTests.swift](../Tests/NXLibraryCoreTests/MoreLikeThisTests.swift) | Ranking condiviso, precedenza Steam e ripiego Switch, giochi nascosti e metadati incompleti. | | [Tests/NXLibraryCoreTests/NintendoStoreMetadataTests.swift](../Tests/NXLibraryCoreTests/NintendoStoreMetadataTests.swift) | Decodifica store e Title DB, cache, screenshot e risposte incomplete. | | [Tests/NXLibraryCoreTests/ReleaseNotesLayoutTests.swift](../Tests/NXLibraryCoreTests/ReleaseNotesLayoutTests.swift) | Titoli, voci e righe vuote delle note di release, una voce per riga. | | [Tests/NXLibraryCoreTests/NewestEngineTests.swift](../Tests/NXLibraryCoreTests/NewestEngineTests.swift) | Lock e Metal di main, validità della scelta, comandi git del cambio, gate Newest engine, scheda Setup e frase. | -| [Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift](../Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift) | Magic NUP, cartelle, lettura tramite engine, nomi NACP, profili mancanti, selezione e NUP senza base. | +| [Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift](../Tests/NXLibraryCoreTests/NUPSourceCatalogTests.swift) | NUP storici, multiprogramma e soli update; identità DLC, JSON, capacità checkout, programma zero nei vecchi record e argv coerenti. | | [Tests/NXLibraryCoreTests/NXNativeGameSettingsTests.swift](../Tests/NXLibraryCoreTests/NXNativeGameSettingsTests.swift) | Build senza adattatore, migrazione da env.txt, scrittura dei soli valori diversi dal default e chiavi fissate. | | [Tests/NXLibraryCoreTests/OnlineArtworkSourcesTests.swift](../Tests/NXLibraryCoreTests/OnlineArtworkSourcesTests.swift) | Ricerca Steam e loghi MediaWiki/Commons con risposte sintetiche. | | [Tests/NXLibraryCoreTests/OnlineBackgroundsTests.swift](../Tests/NXLibraryCoreTests/OnlineBackgroundsTests.swift) | Parser degli sfondi fissi, risoluzioni, crediti e nomi dei download. | @@ -531,36 +705,43 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Tests/NXLibraryCoreTests/PortedGameTests.swift](../Tests/NXLibraryCoreTests/PortedGameTests.swift) | Modello del gioco, compatibilità dei record e condizioni di disponibilità dell’app. | | [Tests/NXLibraryCoreTests/PortingFailureReasonTests.swift](../Tests/NXLibraryCoreTests/PortingFailureReasonTests.swift) | Classificazione dei fallimenti e corrispondenza con i messaggi del pin, anche da un checkout separato scelto con NX_TEST_ENGINE_REPO. | | [Tests/NXLibraryCoreTests/PortingNoticeTests.swift](../Tests/NXLibraryCoreTests/PortingNoticeTests.swift) | Condizioni e testi delle notifiche di esito del porting. | -| [Tests/NXLibraryCoreTests/PortingPresentationTests.swift](../Tests/NXLibraryCoreTests/PortingPresentationTests.swift) | ETA, tile, pill e rappresentazione dei fallimenti del porting. | +| [Tests/NXLibraryCoreTests/PortingPresentationTests.swift](../Tests/NXLibraryCoreTests/PortingPresentationTests.swift) | ETA, attività del prewarm senza stime storiche, tile, pill e rappresentazione dei fallimenti del porting. | | [Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift](../Tests/NXLibraryCoreTests/AppIconPreferenceTests.swift) | Ambito dell’icona: scelta esplicita, vecchie librerie, scansioni, persistenza e rebuild. | | [Tests/NXLibraryCoreTests/AppIconProgressTests.swift](../Tests/NXLibraryCoreTests/AppIconProgressTests.swift) | Verifica che l'esito di un'icona mancante non sovrascriva il log o segnali una build fallita. | | [Tests/NXLibraryCoreTests/IconLaunchWaitTests.swift](../Tests/NXLibraryCoreTests/IconLaunchWaitTests.swift) | Attesa Play: successo, errore, annullamento, gioco diverso e nuova firma in coda. | | [Tests/NXLibraryCoreTests/PipelineArchiveProgressTests.swift](../Tests/NXLibraryCoreTests/PipelineArchiveProgressTests.swift) | Log obsoleti, righe incomplete, cache riusata, gruppi paralleli e GPU diverse. | -| [Tests/NXLibraryCoreTests/PortingProgressTests.swift](../Tests/NXLibraryCoreTests/PortingProgressTests.swift) | Aggregazione delle fasi, avanzamento monotono e peso degli shader. | +| [Tests/NXLibraryCoreTests/PortingProgressTests.swift](../Tests/NXLibraryCoreTests/PortingProgressTests.swift) | Aggregazione delle fasi, avanzamento monotono, peso degli shader e avvisi di archivio/prewarm. | | [Tests/NXLibraryCoreTests/ProdKeysLocationsTests.swift](../Tests/NXLibraryCoreTests/ProdKeysLocationsTests.swift) | Selezione e validazione dei possibili percorsi delle chiavi. | | [Tests/NXLibraryCoreTests/RunningGamesTests.swift](../Tests/NXLibraryCoreTests/RunningGamesTests.swift) | Associazione bundle ID, applicazioni aperte e voci della libreria. | | [Tests/NXLibraryCoreTests/RyujinxSaveImportTests.swift](../Tests/NXLibraryCoreTests/RyujinxSaveImportTests.swift) | Contenitori e slot Ryujinx, identità del titolo e importazioni con strutture e destinazioni differenti. | | [Tests/NXLibraryCoreTests/SaveLocationTests.swift](../Tests/NXLibraryCoreTests/SaveLocationTests.swift) | Identificativi, percorsi sicuri, precedenze dell’ambiente e cloud effettivo. | | [Tests/NXLibraryCoreTests/SaveOperationGateTests.swift](../Tests/NXLibraryCoreTests/SaveOperationGateTests.swift) | Lease per titolo, esclusione globale dell’updater, operazioni concorrenti e recupero bloccato senza I/O attivo. | -| [Tests/NXLibraryCoreTests/SavePresentationTests.swift](../Tests/NXLibraryCoreTests/SavePresentationTests.swift) | Riepiloghi, date, nomi degli slot e accessibilità dell’azione di importazione. | +| [Tests/NXLibraryCoreTests/SavePresentationTests.swift](../Tests/NXLibraryCoreTests/SavePresentationTests.swift) | Azioni e messaggi del pannello; distingue backup storico/completo e limite cloud. | | [Tests/NXLibraryCoreTests/SaveSnapshotStoreTests.swift](../Tests/NXLibraryCoreTests/SaveSnapshotStoreTests.swift) | Inventari, xattr, integrità dei backup, staging e selezione dei backup datati. | +| [MultiuserSaveTests.swift](../Tests/NXLibraryCoreTests/MultiuserSaveTests.swift) | Backup e restore utenti/registro, compatibilità storica, import circoscritti, fault injection e conservazione di dati cambiati da fuori. | | [Tests/NXLibraryCoreTests/SaveTestHome.swift](../Tests/NXLibraryCoreTests/SaveTestHome.swift) | Fixture condivisa che crea una home e un bundle sintetici in una directory temporanea dedicata. | | [Tests/NXLibraryCoreTests/SaveTransactionTests.swift](../Tests/NXLibraryCoreTests/SaveTransactionTests.swift) | Sostituzioni, interruzioni, rollback, modifiche esterne e compatibilità dei journal precedenti. | | [Tests/NXLibraryCoreTests/ScreenshotViewerStateTests.swift](../Tests/NXLibraryCoreTests/ScreenshotViewerStateTests.swift) | Indice, avanzamento e limiti del visualizzatore screenshot. | | [Tests/NXLibraryCoreTests/SeleneCanvasTests.swift](../Tests/NXLibraryCoreTests/SeleneCanvasTests.swift) | Scala, centratura e conversione delle unità del canvas. | | [Tests/NXLibraryCoreTests/SeleneImporterTests.swift](../Tests/NXLibraryCoreTests/SeleneImporterTests.swift) | Copia delle risorse Selene e risoluzione dei cue sonori. | -| [Tests/NXLibraryCoreTests/SelenePaletteTests.swift](../Tests/NXLibraryCoreTests/SelenePaletteTests.swift) | Lettura delle palette, ordine e fallback. | -| [Tests/NXLibraryCoreTests/SettingsCatalogTests.swift](../Tests/NXLibraryCoreTests/SettingsCatalogTests.swift) | Catalogo delle righe, ricerca e identificazione dei valori modificati. | +| [Tests/NXLibraryCoreTests/SelenePaletteTests.swift](../Tests/NXLibraryCoreTests/SelenePaletteTests.swift) | Lettura delle 25 palette, valori RGB e fallback storici del blu, alternative Crystal/Flow, persistenza ID, ordine e fallback. | +| [Tests/NXLibraryCoreTests/SettingsCatalogTests.swift](../Tests/NXLibraryCoreTests/SettingsCatalogTests.swift) | Catalogo delle righe, ricerca, valori modificati, identità invariate, sezioni e gruppi in ordine, reset delle righe spostate. | | [Tests/NXLibraryCoreTests/SetupActionsTests.swift](../Tests/NXLibraryCoreTests/SetupActionsTests.swift) | Comandi Git del Setup e rispetto delle modifiche locali nel checkout. | | [Tests/NXLibraryCoreTests/SetupCheckTests.swift](../Tests/NXLibraryCoreTests/SetupCheckTests.swift) | Stati delle schede, requisiti, override e condizioni di riapertura del Setup. | | [Tests/NXLibraryCoreTests/SetupGridTests.swift](../Tests/NXLibraryCoreTests/SetupGridTests.swift) | Bilanciamento delle righe e spostamento del focus fra le schede. | -| [Tests/NXLibraryCoreTests/FirstRunSetupTests.swift](../Tests/NXLibraryCoreTests/FirstRunSetupTests.swift) | Skip persistente, ripresa, riapertura manuale senza reset, attesa della scansione, separazione dei requisiti e navigazione del primo gioco. | +| [Tests/NXLibraryCoreTests/FirstRunSetupTests.swift](../Tests/NXLibraryCoreTests/FirstRunSetupTests.swift) | Pagina iniziale, Porting, scelta Steam acceso/spento dopo interruzione, completamento e pulizia della scelta salvata, focus, scansione e ripresa. | +| [Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift](../Tests/NXLibraryCoreTests/FirstRunFindingsTests.swift) | Steam assente, solo giochi Mac pronti, zero giochi, errore/parziale distinto da assenza, annullamento e app portate contate. | | [Tests/NXLibraryCoreTests/SmokeTests.swift](../Tests/NXLibraryCoreTests/SmokeTests.swift) | Importabilità e versione nominale del modulo Core. | +| [Tests/NXLibraryCoreTests/CriticRatingTests.swift](../Tests/NXLibraryCoreTests/CriticRatingTests.swift) | Abbinamenti esatti, metriche e piattaforme, stelle proporzionali, cache offline, richieste seriali/condivise, errori e annullamento delle valutazioni. | +| [Tests/NXLibraryCoreTests/IGDBRatingTests.swift](../Tests/NXLibraryCoreTests/IGDBRatingTests.swift) | Credenziali 0600 sintetiche, isolamento degli host, voti critica/utenti, rinnovo accesso, annullamento, cache offline e ripiego Wikidata. | +| [Tests/NXLibraryCoreTests/IGDBMetadataTests.swift](../Tests/NXLibraryCoreTests/IGDBMetadataTests.swift) | Identità, ruoli, date precise per piattaforma, Steam, cache offline, retry, annullamento e token/coda condivisi. | +| [Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift](../Tests/NXLibraryCoreTests/DatabaseMetadataTests.swift) | Parser pubblici, identità/ambiguità, date, conteggio richieste, letture concorrenti, cache, annullamento, risposte errate e retry. | | [Tests/NXLibraryCoreTests/SourceCatalogTests.swift](../Tests/NXLibraryCoreTests/SourceCatalogTests.swift) | Fixture PFS0/CNMT e riconoscimento di base, aggiornamenti e DLC. | | [Tests/NXLibraryCoreTests/EngineUpgradeSourcesTests.swift](../Tests/NXLibraryCoreTests/EngineUpgradeSourcesTests.swift) | Copre cartelle estratte, pacchetti multipli, selezione, persistenza, bridge Python, file illeggibili e restaging senza perdita di cache o originali. | | [Tests/NXLibraryCoreTests/SpotlightPageTests.swift](../Tests/NXLibraryCoreTests/SpotlightPageTests.swift) | Estratti del testo e stati dello scorrimento della pagina del gioco. | -| [Tests/NXLibraryCoreTests/SpotlightRowTests.swift](../Tests/NXLibraryCoreTests/SpotlightRowTests.swift) | Ordine, card, riordino delle tile e selezione Surprise. | +| [Tests/NXLibraryCoreTests/SpotlightRowTests.swift](../Tests/NXLibraryCoreTests/SpotlightRowTests.swift) | Ordine, card, riordino delle tile, gioco avviato primo nell’ordine salvato e selezione Surprise. | | [Tests/NXLibraryCoreTests/SpotlightStateTests.swift](../Tests/NXLibraryCoreTests/SpotlightStateTests.swift) | Focus, selezione, filtri, azioni e spostamento delle tile Spotlight. | +| [Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift](../Tests/NXLibraryCoreTests/SpotlightEntranceTests.swift) | Partenze, tempi di volo e dissolvenza, bordi, durata, messaggio vuoto, avanzamento degli effetti e fasi dell’entrata; interruttore e Riduci movimento. | | [Tests/NXLibraryCoreTests/StorageManagerTests.swift](../Tests/NXLibraryCoreTests/StorageManagerTests.swift) | Misure per gioco, cache condivise e nascoste, pulizia selettiva, protezione di app/sorgenti/symlink, file incoerenti e volumi/cartelle non disponibili. | | [Tests/NXLibraryCoreTests/ThemePickerTests.swift](../Tests/NXLibraryCoreTests/ThemePickerTests.swift) | Navigazione della griglia, tab e selezione degli sfondi. | | [Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift](../Tests/NXLibraryCoreTests/ToolchainGateCopyTests.swift) | Testi del gate per Metal certificato, precedente, successivo e altre cause di blocco. | @@ -571,39 +752,118 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | [Tests/NXLibraryCoreTests/WallpaperCatalogTests.swift](../Tests/NXLibraryCoreTests/WallpaperCatalogTests.swift) | Catalogo dei file inclusi/importati, gruppi e tipi immagine/video. | | [Tests/NXLibraryCoreTests/WallpaperPlacementTests.swift](../Tests/NXLibraryCoreTests/WallpaperPlacementTests.swift) | Destinazione dello sfondo fra home e impostazioni. | | [Tests/NXLibraryCoreTests/WorkspaceManagerTests.swift](../Tests/NXLibraryCoreTests/WorkspaceManagerTests.swift) | Collegamenti simbolici, cache adottate e rilevamento dei link interrotti. | +| [Tests/NXLibraryCoreTests/AppIconWriterTests.swift](../Tests/NXLibraryCoreTests/AppIconWriterTests.swift) | Icona scelta scritta e ripristinata, originale ricordato anche se assente, ricostruzione dell’app, firma fallita senza modifiche, icona rifilata e opaca. | +| [Tests/NXLibraryCoreTests/BackdropArtTests.swift](../Tests/NXLibraryCoreTests/BackdropArtTests.swift) | Arte tenuta fra un gioco e l’altro e mai fra card e gioco, dissolvenze sull’orologio come Core Animation, livelli coperti tolti e scorrimento rapido. | +| [Tests/NXLibraryCoreTests/BoundedDownloadTests.swift](../Tests/NXLibraryCoreTests/BoundedDownloadTests.swift) | Blocchi raccolti fino al limite, corpo o lunghezza dichiarata oltre il limite rifiutati, nessun redirect, annullamento della lettura. | +| [Tests/NXLibraryCoreTests/DetailsFactsTests.swift](../Tests/NXLibraryCoreTests/DetailsFactsTests.swift) | Righe Details per Switch e Steam: ordine, valori mancanti o vuoti nascosti, mai la versione Steam, solo crediti durante il download, simboli. | +| [Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift](../Tests/NXLibraryCoreTests/DetailsReviewFixTests.swift) | Play costruisce un gioco non ancora costruito con le sorgenti; nome di cartella o volume letto una volta per URL. | +| [Tests/NXLibraryCoreTests/EngineRuntimeRequirementsTests.swift](../Tests/NXLibraryCoreTests/EngineRuntimeRequirementsTests.swift) | Il runtime incluso porta ogni pacchetto Python che il motore fissato chiede (riga `pip install` del README e `tools.txt`). | +| [Tests/NXLibraryCoreTests/GameFocusTests.swift](../Tests/NXLibraryCoreTests/GameFocusTests.swift) | Ritorno della libreria davanti solo per il gioco in primo piano, mai con un altro gioco aperto, uscita contata una volta. | +| [Tests/NXLibraryCoreTests/ModStoreModelTests.swift](../Tests/NXLibraryCoreTests/ModStoreModelTests.swift) | Store delle mod da copia fresca o vecchia, abbinamenti incerti o sicuri, ordine della libreria, copie di un altro gioco, chiusura senza perdite. | +| [Tests/NXLibraryCoreTests/SessionSummaryTests.swift](../Tests/NXLibraryCoreTests/SessionSummaryTests.swift) | Card di fine sessione: gioco, sessione e totale, meno di un minuto, sessioni troppo brevi o in corso, altri giochi, giochi Steam. | +| [Tests/NXLibraryCoreTests/SettingsRowButtonsTests.swift](../Tests/NXLibraryCoreTests/SettingsRowButtonsTests.swift) | Riga con due pulsanti: Sinistra/Destra fra i pulsanti, uscita dalla riga, riga con un solo pulsante, A preme quello in focus. | +| [Tests/NXLibraryCoreTests/SpotlightRowGeometryTests.swift](../Tests/NXLibraryCoreTests/SpotlightRowGeometryTests.swift) | Posto a schermo = camera più posto nella riga, tessere che restano ferme durante lo scorrimento, distanze costanti e quattro tessere di riserva ai bordi. | +| [Tests/NXLibraryCoreTests/TileMotionTests.swift](../Tests/NXLibraryCoreTests/TileMotionTests.swift) | Periodi e curve di bagliore, ring e riflesso, campioni che chiudono il loop senza salti, fase nel periodo e simbolo del download. | +| [Tests/NXLibraryCoreTests/AppLocaleTests.swift](../Tests/NXLibraryCoreTests/AppLocaleTests.swift) | Preferenze, migrazione, formati, ricerca, identità e traduzioni native; avvisi pipeline localizzati senza output tecnico grezzo. | +| [Tests/PublicationChecks/test_localizations.py](../Tests/PublicationChecks/test_localizations.py) | Rifiuto di cataloghi incompleti e bundle senza risorse. | +| [DevelopmentProfileTests.swift](../Tests/NXLibraryCoreTests/DevelopmentProfileTests.swift) | Copia, conservazione della sorgente, errori, sessioni, symlink e ripetizione. | +| [DevelopmentProfileEffectTests.swift](../Tests/NXLibraryCoreTests/DevelopmentProfileEffectTests.swift) | Isolamento Dev, staging e richieste esplicite. Verifica anche che la riconciliazione delle mod conservi record e overlay dopo un errore di lettura. | +| [test_profile_boundaries.py](../Tests/PublicationChecks/test_profile_boundaries.py) | Guardia contro percorsi/defaults del launcher non centralizzati. | +| [SteamKeyValuesTests.swift](../Tests/NXLibraryCoreTests/SteamKeyValuesTests.swift) | Formato, escape, Unicode, duplicati, input troncati e limiti del parser. | +| [SteamPlaytimeReaderTests.swift](../Tests/NXLibraryCoreTests/SteamPlaytimeReaderTests.swift) | Campi letti, ultima partita, scelta dell’account, duplicati e tipi errati di blocchi/scalari, file grandi, malformati o non sicuri. | +| [SteamPlaytimeBaselinesTests.swift](../Tests/NXLibraryCoreTests/SteamPlaytimeBaselinesTests.swift) | Base mantenuta o ripartita, minuto conservato, cambio account, salvataggio e mappatura sul catalogo. | +| [SteamReturnFocusTests.swift](../Tests/NXLibraryCoreTests/SteamReturnFocusTests.swift) | Ritorno ad Arcane solo per Play premuto qui, gioco davanti e nessun altro gioco aperto. | +| [SteamLaunchQuestionsTests.swift](../Tests/NXLibraryCoreTests/SteamLaunchQuestionsTests.swift) | Fase `ShowInterstitials` a freddo, domande aperte o risposte subito, log per righe intere e sostituzione del file. | +| [SteamPlaytimeSyncTests.swift](../Tests/NXLibraryCoreTests/SteamPlaytimeSyncTests.swift) | Letture con o senza account, file illeggibili, file invariato, regole di pubblicazione e coda delle letture. | +| [NativeMacApplicationTests.swift](../Tests/NXLibraryCoreTests/NativeMacApplicationTests.swift) | Fixture native, classificazione, traversal/link, metadata non regolari e header invalidi. | +| [SteamLibrarySourceTests.swift](../Tests/NXLibraryCoreTests/SteamLibrarySourceTests.swift) | Più fonti, dischi assenti, identità, manifest/path con campi duplicati o di tipo errato, file cambiati, limiti e assenza di scritture. | +| [SteamDiscoveryConsistencyTests.swift](../Tests/NXLibraryCoreTests/SteamDiscoveryConsistencyTests.swift) | Mutazioni reali di inventario e app durante scan, indice inizialmente assente, budget e propagazione dell'annullamento. | +| [SteamTestSupport.swift](../Tests/NXLibraryCoreTests/SteamTestSupport.swift) | Genera solo metadati e header sintetici nelle directory temporanee dei test. | +| [SteamPlayStateTests.swift](../Tests/NXLibraryCoreTests/SteamPlayStateTests.swift) | Symlink, passaggio senza sessione, Play doppi e risposte tardive, rifiuti e timeout, giochi già aperti, argomenti silenziosi, pazienza di Steam a freddo e schermata di lancio. | +| [SteamBinaryKeyValuesTests.swift](../Tests/NXLibraryCoreTests/SteamBinaryKeyValuesTests.swift) | Tipi, annidamento, fine dei dati, input troncati, tipi ignoti e limiti del parser binario. | +| [SteamAchievementReaderTests.swift](../Tests/NXLibraryCoreTests/SteamAchievementReaderTests.swift) | Percorsi, account e file mancanti/non sicuri, lingue con ripiego anche su stringhe vuote duplicate, primo valore tipizzato, nascosti, icone, ordine numerico e file corrotti. | +| [SteamAchievementRarityTests.swift](../Tests/NXLibraryCoreTests/SteamAchievementRarityTests.swift) | Percentuali numeriche o testuali (non numeriche scartate), host e percorso ammessi, cache di un giorno, cache vecchia offline, icone in cache, coda oltre sei download con annullamento, errore recente senza attesa e file che non sono immagini. | +| [AchievementSummaryTests.swift](../Tests/NXLibraryCoreTests/AchievementSummaryTests.swift) | Conteggi, gioco completato, ordini dei filtri, rarità sconosciute in fondo, soglia del raro, maschera dei nascosti e icone recenti (segreti compresi). | +| [AchievementsScreenStateTests.swift](../Tests/NXLibraryCoreTests/AchievementsScreenStateTests.swift) | Movimento in due colonne, bordi, liste vuote, cambio filtro e liste che si accorciano. | +| [GridListLayoutTests.swift](../Tests/NXLibraryCoreTests/GridListLayoutTests.swift) | Linee, altezza, posizione delle righe, spazio da mostrare, linee visibili e riga in vista più vicina dopo la rotella. | +| [AchievementTierTests.swift](../Tests/NXLibraryCoreTests/AchievementTierTests.swift) | Soglie, tier dalla percentuale mostrata, ordine dal più raro, conteggi per tier, Arcane solo al 100% e mai senza achievement, miglior tier ottenuto, rarità sconosciuta. | +| [SteamManifestWatcherTests.swift](../Tests/NXLibraryCoreTests/SteamManifestWatcherTests.swift) | Filtri e durata dello stream; eventi reali da librerie tornate disponibili, da sole o accanto a una già osservata, inclusa la normalizzazione `/private`. | +| [CatalogModelTests.swift](../Tests/NXLibraryCoreTests/CatalogModelTests.swift) | Conservazione del record precedente, proprietà comuni e separazione delle azioni per integrazione. | +| [CatalogStoreTests.swift](../Tests/NXLibraryCoreTests/CatalogStoreTests.swift) | Conversione, backup, corruzione, versioni, input cambiati, scrittori concorrenti e guasti di pubblicazione. | +| [SteamCatalogReconcilerTests.swift](../Tests/NXLibraryCoreTests/SteamCatalogReconcilerTests.swift) | Identità, aggiornamenti, installazioni ambigue, fonti assenti e scansioni obsolete/parziali. | +| [CatalogTestSupport.swift](../Tests/NXLibraryCoreTests/CatalogTestSupport.swift) | Record legacy sintetico completo e scrittura di fixture; nessun contenuto di gioco. | +| [CatalogRepositoryTests.swift](../Tests/NXLibraryCoreTests/CatalogRepositoryTests.swift) | Modifiche concorrenti, confini per integrazione, campi build e conservazione di Steam/legacy. | +| [CatalogRecoveryTests.swift](../Tests/NXLibraryCoreTests/CatalogRecoveryTests.swift) | Recupero esplicito, conflitto legacy senza fusione, archivi, offerte obsolete, guasti di pubblicazione, restore point e importazione Dev. | +| [CatalogPersonalizationTests.swift](../Tests/NXLibraryCoreTests/CatalogPersonalizationTests.swift) | Rinomina senza perdita del lookup e isolamento di chiavi uguali tra fonti. | +| [CatalogBuildRecoveryTests.swift](../Tests/NXLibraryCoreTests/CatalogBuildRecoveryTests.swift) | Vecchia build persistita e nuova conservata, sospensione automatica e conferme obsolete. | +| [run_notices.py](../Tests/CatalogAppChecks/run_notices.py) | Esegue i metodi reali degli avvisi e del ponte legacy senza finestre, dopo swift test. | +| [run_review.py](../Tests/CatalogAppChecks/run_review.py) | Verifica achievement, loghi, focus, navigazione, lettura Mods e priorità dei dialoghi. Prova Steam che riappare durante Play e aspetta il completamento del task che gestisce il ripiego del pannello. Dati sintetici, senza finestre. | +| [run_startup_recovery.py](../Tests/CatalogAppChecks/run_startup_recovery.py) | Coordinatore di avvio reale su profili sintetici: conflitto, scelta esplicita, offerta obsoleta, Retry e fallimento della preparazione; nessuna finestra. | +| [run_source_access.py](../Tests/CatalogAppChecks/run_source_access.py) | Esegue il ripristino di avvio, l'observer e i selettori reali: nessuna scansione automatica dei sorgenti, cartella ricordata, annullamento e lettura dei soli file scelti; nessuna finestra o dato personale. | +| [run_onboarding.py](../Tests/CatalogAppChecks/run_onboarding.py) | Esegue observer e ripristino del Setup, uscita durante lettura pendente con annullamento, input sotto modali, scelte acceso/spento/nil, radice della fonte, focus dopo Retry e richiesta notifiche su dati sintetici; nessuna finestra. | +| [run_artwork_return.py](../Tests/CatalogAppChecks/run_artwork_return.py) | Viste, task e host Mods reali su fixture: primo body con arte warm, scelte personali, aggiornamenti Steam nello stesso percorso, badge dopo rimozione, cambi abbinamento e snapshot completato fuori ordine; nessuna finestra o rendering. | +| [run_nested_bundles.py](../Tests/CatalogAppChecks/run_nested_bundles.py) | App sintetiche con bundle dati annidati e firme reali: installazione, icona, rollback, copia forzata, ripresa e rifiuto di dati alterati; nessuna UI. | +| [run_nup_programs.py](../Tests/CatalogAppChecks/run_nup_programs.py) | Esegue il probe NUP opzionale su snapshot sintetico, convertitori UI reali, persistenza e argv del rebuild. | +| [run_save_restart.py](../Tests/CatalogAppChecks/run_save_restart.py) | Arresti reali e nuovi processi nei checkpoint di transazione, recovery e pulizia; verifica tutti gli utenti, registro e integrità dei backup su fixture temporanee. | +| [run_entrance.py](../Tests/CatalogAppChecks/run_entrance.py) | Esegue i metodi reali di input e readiness: nessun comando agisce o salta l’entrata prima dell’atterraggio, precedenza delle coperture, drawable mancante e presentazione su entrambi i percorsi. Nessuna finestra o GPU reale. | +| [run_icon_cache.py](../Tests/CatalogAppChecks/run_icon_cache.py) | Esegue il vero `GameIconProvider`: un gioco senza icona non si rilegge dal disco a ogni disegno; dopo `forget` o la build si legge di nuovo. | +| [run_theme.py](../Tests/CatalogAppChecks/run_theme.py) | Regressioni delle richieste condivise (precedenza, frame mantenuto e pausa) e del cambio palette a wallpaper/card invariati con snapshot e apply reali, ordine Look e input del selettore; shader Metal fuori schermo, colori locali GPU/Core, profilo sottile, deformazione delle onde, superfici distinte, frame fermo e uniform Mods. | +| [run_achievement_scroll.py](../Tests/CatalogAppChecks/run_achievement_scroll.py) | Verifica fuori schermo la vera lista e i modelli durante riaperture rapide, dettagli della prima riga, ridimensionamento e Riduci movimento; nessuna finestra o automazione UI. | +| [run_game_header.py](../Tests/CatalogAppChecks/run_game_header.py) | Esegue i corpi reali di logo e azioni condivisi senza finestra né store applicativi, per entrambi i layout. | +| [NoticeHost.swift](../Tests/CatalogAppChecks/NoticeHost.swift) | Host minimo per i controlli applicativi, con storage reale e dati sintetici temporanei. | +| [SharedGamePresentationTests.swift](../Tests/NXLibraryCoreTests/SharedGamePresentationTests.swift) | Presentazione Steam con identità, personalizzazioni e cronologia; prima installazione disponibile coerente per artwork e dettagli, con Play bloccato se ambiguo; confine nxnative e opzioni comuni. | +| [CatalogSourcesRepositoryTests.swift](../Tests/NXLibraryCoreTests/CatalogSourcesRepositoryTests.swift) | Compatibilità generazioni, cambi fonte, preferenze concorrenti e adozione NX esplicita. | +| [CatalogSourcesModelTests.swift](../Tests/NXLibraryCoreTests/CatalogSourcesModelTests.swift) | Opt-in, annullamento, cambio radice, recupero errori e intervallo tra riscansioni, misurato dagli avvii pubblicati dal modello. | +| [CatalogLibraryQueryTests.swift](../Tests/NXLibraryCoreTests/CatalogLibraryQueryTests.swift) | Visibilità, ricerca/filtri misti e selezione per UUID senza sessioni simulate. | +| [SteamOptionsTests.swift](../Tests/NXLibraryCoreTests/SteamOptionsTests.swift) | Righe delle opzioni Steam come quelle comuni nxnative, niente di nxnative, Play e Finder spenti senza installazione, artwork e impostazione «Keep Steam in the background». | +| [SteamMetadataTests.swift](../Tests/NXLibraryCoreTests/SteamMetadataTests.swift) | Identità, lingue, offline, URL, concorrenza, tratti correlati in cache ed esito del salvataggio. | +| [SteamArtworkRequestTests.swift](../Tests/NXLibraryCoreTests/SteamArtworkRequestTests.swift) | Quadrato dall’icona originale e mai dalla copertina, scelta personale prima, link che escono dal bundle ignorati, icona automatica solo senza app. | +| [SteamAutomaticIconTests.swift](../Tests/NXLibraryCoreTests/SteamAutomaticIconTests.swift) | Quadrato LaunchBox della voce PC preso intero, scaricato una volta e conservato; nessun quadrato non si richiede di nuovo nella sessione. | +| [SteamBackdropChoiceTests.swift](../Tests/NXLibraryCoreTests/SteamBackdropChoiceTests.swift) | Solo arte in formato schermo, ordine store → screenshot → banner, fan art LaunchBox fra store e screenshot, ripiego sulla prima immagine che si carica. | +| [test_app_bundle.py](../Tests/PublicationChecks/test_app_bundle.py) | Verifica che il bundle del launcher rinunci a Game Mode. | ## Script di sviluppo e packaging | File | Responsabilità | |---|---| | [scripts/build_app.sh](../scripts/build_app.sh) | Compila in staging, prepara plist, runtime e risorse, verifica la firma e pubblica il bundle con sostituzione atomica. | -| [scripts/install_built_app.swift](../scripts/install_built_app.swift) | Piccolo ingresso CLI che riusa BuildOutputInstaller per installare NX Library dopo il packaging. | +| [scripts/install_built_app.swift](../scripts/install_built_app.swift) | Piccolo ingresso CLI che riusa BuildOutputInstaller per installare Arcane dopo il packaging. | | [scripts/check_publication.py](../scripts/check_publication.py) | Rifiuta contenuti personali o di gioco versionati e formati di segreto riconoscibili; verifica il runtime rispetto al lock prima del packaging. | | [scripts/build_dmg.sh](../scripts/build_dmg.sh) | Confeziona un bundle già costruito in un’immagine DMG di sviluppo. | | [scripts/bundle_runtime.sh](../scripts/bundle_runtime.sh) | Prepara Python e strumenti dalle versioni bloccate, verifica gli hash e firma il runtime incluso. | -| [scripts/release.sh](../scripts/release.sh) | Controlla i prerequisiti e produce ZIP e DMG di release, con pubblicazione esplicita opzionale. | +| [scripts/release.sh](../scripts/release.sh) | Controlla prerequisiti, suite Swift e tutti gli script headless delle regressioni app; produce ZIP e DMG di release, con pubblicazione esplicita opzionale. | | [scripts/validate_update.py](../scripts/validate_update.py) | Verifica struttura, percorsi e limiti degli archivi prima dell'estrazione, sia nel bundle sia durante il packaging delle release. | | [scripts/relink_macho.py](../scripts/relink_macho.py) | Riscrive riferimenti Mach-O dei binari e delle librerie affinché il runtime incluso sia rilocabile. | | [scripts/make_icons.swift](../scripts/make_icons.swift) | Genera le risorse dell’icona dell’app nelle varianti usate dal bundle. | | [scripts/import_selene_palettes.py](../scripts/import_selene_palettes.py) | Converte le palette Selene nel catalogo JSON usato dall’app. | +| [scripts/check_localizations.py](../scripts/check_localizations.py) | Verifica copertura, placeholder, plurali e risorse nel bundle installato. | +| [scripts/check_metadata_text_layout.swift](../scripts/check_metadata_text_layout.swift) | Verifica fuori schermo il layout delle descrizioni e la destinazione dello scroll dopo cambi di focus, anche rapidi e con Riduci movimento. | +| [check_app_profile.swift](../scripts/check_app_profile.swift) | Prova senza UI di identità, accesso reale alle preferenze e percorsi nel pacchetto prodotto dalla build; non importa né scrive dati. | ## Risorse incluse | File | Responsabilità aggiuntiva | |---|---| -| [Resources/IconArtwork.png](../Resources/IconArtwork.png) | Master quadrato originale dell’icona, fornito dall’utente e creato con AI. | +| [Resources/IconArtwork.png](../Resources/IconArtwork.png) | Master quadrato originale dell’icona (cristallo nella sfera di vetro), fornito dall’utente e creato con AI. | | [Resources/IconArtwork.md](../Resources/IconArtwork.md) | Provenienza dichiarata, brief e riproduzione delle varianti tramite il generatore. | +| [crystal-arcane.png](../Sources/NXLibraryCore/Resources/crystal-arcane.png) | Immagine ferma del trofeo Arcane, anche come ripiego del video. | +| [crystal-arcane.mov](../Sources/NXLibraryCore/Resources/crystal-arcane.mov) | Animazione con alpha del trofeo Arcane. | +| [crystal-gold.png](../Sources/NXLibraryCore/Resources/crystal-gold.png) | Immagine del trofeo Oro. | +| [crystal-silver.png](../Sources/NXLibraryCore/Resources/crystal-silver.png) | Immagine del trofeo Argento. | +| [crystal-bronze.png](../Sources/NXLibraryCore/Resources/crystal-bronze.png) | Immagine del trofeo Bronzo. | | File | Responsabilità | |---|---| -| [Resources/AppIcon.icns](../Resources/AppIcon.icns) | Icona macOS del bundle NX Library. | +| [Resources/AppIcon.icns](../Resources/AppIcon.icns) | Icona macOS del bundle Arcane. | | [Resources/AppIcon-Dark.png](../Resources/AppIcon-Dark.png) | Variante scura dell’icona dell’app. | | [Resources/AppIcon-Light.png](../Resources/AppIcon-Light.png) | Variante chiara dell’icona dell’app. | | [Resources/AppIcon-Mono.png](../Resources/AppIcon-Mono.png) | Variante monocromatica dell’icona dell’app. | -| [Resources/Selene/palettes.json](../Resources/Selene/palettes.json) | Catalogo serializzato delle palette disponibili. | +| [Resources/Selene/palettes.json](../Resources/Selene/palettes.json) | Catalogo delle 25 palette: blu classico predefinito, Arcane Crystal e Arcane Flow come superfici opzionali. | | [Resources/Selene/Fonts/MaterialIcons-Regular.ttf](../Resources/Selene/Fonts/MaterialIcons-Regular.ttf) | Font dei glifi Material Icons disegnati dalla UI. | | [Resources/Selene/Fonts/MaterialIcons-LICENSE.txt](../Resources/Selene/Fonts/MaterialIcons-LICENSE.txt) | Licenza del font Material Icons incluso. | | [Resources/Selene/NOTICE.txt](../Resources/Selene/NOTICE.txt) | Attribuzioni delle risorse Selene incluse. | +| [Resources/Brands/SteamLogo.png](../Resources/Brands/SteamLogo.png) | Logo Steam inverso dalle linee guida Valve, inalterato; attribuzione in `NOTICE`. | +| [Resources/Brands/BuyMeACoffee.png](../Resources/Brands/BuyMeACoffee.png) | Icona gialla dal kit ufficiale Buy Me a Coffee per il pulsante di sostegno; attribuzione in `NOTICE`. | | [Resources/Selene/NOTICE-palettes.txt](../Resources/Selene/NOTICE-palettes.txt) | Attribuzioni delle palette incluse con esse. | | [Resources/Selene/Sounds/Boot.wav](../Resources/Selene/Sounds/Boot.wav) | Cue sonoro incluso per l’avvio. | | [Resources/Selene/Sounds/Key.wav](../Resources/Selene/Sounds/Key.wav) | Cue sonoro incluso per la pressione dei tasti. | @@ -614,12 +874,13 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| -| [docs/media/README.md](../docs/media/README.md) | Registra provenienza e posizione degli screenshot, ottimizzazione delle copie e inserimento del video futuro. | +| [docs/media/README.md](../docs/media/README.md) | Registra i media del README e la loro posizione. | | [docs/media/spotlight.webp](../docs/media/spotlight.webp) | Presenta Spotlight e la libreria nell'apertura del README. | | [docs/media/game-details.webp](../docs/media/game-details.webp) | Mostra dettagli, attività e informazioni di build di un gioco. | +| [docs/media/mod-store.webp](../docs/media/mod-store.webp) | Presenta lo store delle mod nel README. | | [docs/media/quick-menu.webp](../docs/media/quick-menu.webp) | Illustra il menu rapido sopra la libreria. | | [docs/media/porting-progress.webp](../docs/media/porting-progress.webp) | Mostra l'avanzamento di un porting dalla schermata Spotlight. | -| [docs/media/settings.webp](../docs/media/settings.webp) | Illustra le categorie di Settings e il pannello Start-up. | +| [docs/media/settings.webp](../docs/media/settings.webp) | Cattura storica di Settings in NX Library. | | [docs/media/color-themes.webp](../docs/media/color-themes.webp) | Mostra la scelta delle palette con anteprima della libreria. | | [docs/media/static-wallpapers.webp](../docs/media/static-wallpapers.webp) | Illustra il browser degli sfondi statici e la relativa anteprima. | | [docs/media/live-wallpapers.webp](../docs/media/live-wallpapers.webp) | Mostra il selettore degli sfondi animati e l'importazione di video personali. | @@ -628,7 +889,25 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT | File | Responsabilità | |---|---| -| [docs/architecture.md](../docs/architecture.md) | Spiega architettura corrente, confini dei componenti, flussi, dati su disco e verifiche. | +| [docs/architecture.md](../docs/architecture.md) | Come funziona oggi ogni area: confini dei componenti, regole, dati su disco e verifiche; niente storia né stati di validazione. | +| [docs/conventions.md](../docs/conventions.md) | Come si costruisce una cosa nuova: dove va il codice, ricette per fonte, schermata Selene, impostazione, file su disco, rete, testi, lavoro in background, test e documentazione. | +| [docs/flows.md](../docs/flows.md) | Schemi dei flussi completi: avvio, libreria, Play Switch e Steam, Add Game, salvataggi, mod, impostazioni, aggiornamento dell’app. | +| [docs/validation.md](../docs/validation.md) | Elenco unico di ciò che il maintainer ha validato o deve ancora provare, compresi i pin dell’engine. | +| [docs/steam.md](../docs/steam.md) | Riferimento unico dell’integrazione Steam: file letti, stati, osservazione, libreria, Play, ore, achievement, scelte e limiti. | +| [2026-11-18-spotlight-glide.md](../docs/reviews/2026-11-18-spotlight-glide.md) | Campioni dei primi cambi gioco e costo di mod e salvataggio selezione. | +| [2026-11-18-steam-launch-spaces.md](../docs/reviews/2026-11-18-steam-launch-spaces.md) | Riscontro video e log dei cambi rapidi di Space durante Play Steam, causa e regressione. | +| [2026-11-17-entrance-frames.md](../docs/reviews/2026-11-17-entrance-frames.md) | Metodo, campioni e limiti delle misure temporanee dell’entrata e del passaggio al fullscreen. | +| [2026-11-17-dock-rename-probe.md](../docs/reviews/2026-11-17-dock-rename-probe.md) | Sonda: il Dock apre ancora un'app rinominata nella stessa cartella. | +| [docs/reviews/2026-11-17-arcane-moonlight.md](../docs/reviews/2026-11-17-arcane-moonlight.md) | Contratti provati fuori schermo e tempi GPU del Moonlight prima/dopo, con limiti delle misure. | +| [2026-11-16-ratings-metadata-evidence.md](../docs/reviews/2026-11-16-ratings-metadata-evidence.md) | Prove e misure dietro le scelte di voti e metadati: abbinamenti Wikidata, console Switch 2 in IGDB, download a blocchi, movimento del selettore, sonde LaunchBox/TheGamesDB. | +| [2026-11-09-hotfix-0.1.4.2.md](../docs/reviews/2026-11-09-hotfix-0.1.4.2.md) | Ambito della release 0.1.4.2, autorizzazione del maintainer e verifiche ancora non confermate. | +| [04df08d4 → b2d46b86](../docs/upstream-upgrades/2026-11-06-04df08d4-b2d46b86-review.md) | Revisione del delta engine del 6 novembre e compatibilità della toolchain. | +| [b2d46b86 → 7fe9fc4d](../docs/upstream-upgrades/2026-11-07-b2d46b86-7fe9fc4d-review.md) | Revisione engine del 7 novembre, shader e requisiti. | +| [7fe9fc4d → e5f03403](../docs/upstream-upgrades/2026-11-07-7fe9fc4d-e5f03403-review.md) | Revisione engine del 7 novembre, eventi di progresso e prompt dei controller. | +| [e5f03403 → bd979ced](../docs/upstream-upgrades/2026-11-08-e5f03403-bd979ced-review.md) | Revisione engine dell’8 novembre e nuova catena di traduzione shader. | +| [bd979ced → 79741184](../docs/upstream-upgrades/2026-11-09-bd979ced-79741184-review.md) | Adozione engine per 0.1.4.2 e limiti della validazione registrata. | +| [79741184 → 8a5c5e7e](../docs/upstream-upgrades/2026-11-12-79741184-8a5c5e7e-review.md) | Adozione engine per 0.1.4.3 e limiti della validazione registrata. | +| [8a5c5e7e → 461a5f9f](../docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md) | Revisione engine per 0.2.0, confronto con il commit già provato, scelte d'integrazione e prove del gate. | | [docs/development.md](../docs/development.md) | Documenta prerequisiti, runtime, build, debug, verifiche, CI e preparazione delle release. | | [docs/file-map.md](../docs/file-map.md) | Catalogo corrente delle responsabilità di tutti i file versionati, suddiviso per area. | | [docs/upstream-upgrades/2026-10-27-06b7b3e-4f24ce6.md](../docs/upstream-upgrades/2026-10-27-06b7b3e-4f24ce6.md) | Registro della revisione del delta, scelte di adozione e verifiche per questo upgrade del motore. | @@ -644,18 +923,4 @@ La pubblicazione comprende anche [CONTRIBUTING.md](../CONTRIBUTING.md), [SECURIT ## Aggiornare questo catalogo -Quando si aggiunge, rinomina o rimuove un file versionato, aggiornare la sua riga e il totale iniziale. Quando cambia un flusso o una responsabilità, aggiornare anche la sezione corrispondente della guida tecnica. Le descrizioni dei test indicano l’ambito dei controlli, mentre l’esito di esecuzione appartiene ai rapporti di verifica. - -## Localizzazione (hotfix non pubblicato) - -| File | Responsabilità | -|---|---| -| [Sources/NXLibraryCore/Models/AppLocale.swift](../Sources/NXLibraryCore/Models/AppLocale.swift) | Sei lingue, risoluzione delle preferenze e regione indipendente; nomi e ricerca delle regioni. | -| [Sources/NXLibraryCore/Models/GameGenre.swift](../Sources/NXLibraryCore/Models/GameGenre.swift) | Generi noti tradotti alla presentazione; dati originali e generi personali conservati. | -| [Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift](../Sources/NXLibrary/Views/Theme/AppLocaleEnvironment.swift) | Contesto della lingua reattivo per le viste; conserva identità, selezione e focus. | -| [Sources/NXLibraryCore/Services/AppLocalization.swift](../Sources/NXLibraryCore/Services/AppLocalization.swift) | Contesto osservabile, lookup portabile delle risorse e interpolazioni/plurali. | -| [Sources/NXLibraryCore/Resources/Localizable.xcstrings](../Sources/NXLibraryCore/Resources/Localizable.xcstrings) | Testi condivisi e traduzioni en/it/fr/de/es/pt-BR. | -| [Sources/NXLibrary/Views/Settings/LocalePicker.swift](../Sources/NXLibrary/Views/Settings/LocalePicker.swift) | Scelta diretta della lingua e ricerca dei formati regionali, con focus tastiera/controller e codici stabili. | -| [Tests/NXLibraryCoreTests/AppLocaleTests.swift](../Tests/NXLibraryCoreTests/AppLocaleTests.swift) | Preferenze, migrazione, formati, ricerca, identità e traduzioni native. | -| [scripts/check_localizations.py](../scripts/check_localizations.py) | Verifica copertura, placeholder, plurali e risorse nel bundle installato. | -| [Tests/PublicationChecks/test_localizations.py](../Tests/PublicationChecks/test_localizations.py) | Rifiuto di cataloghi incompleti e bundle senza risorse. | +Quando si aggiunge, rinomina o rimuove un file versionato, aggiornare la sua riga nella sezione della sua area e il totale iniziale; una funzione nuova non apre una sezione in fondo al catalogo. Le regole complete sono in [conventions.md](conventions.md#10-documentazione). Quando cambia un flusso o una responsabilità, aggiornare anche la sezione corrispondente della guida tecnica. Le descrizioni dei test indicano l’ambito dei controlli, mentre l’esito di esecuzione appartiene ai rapporti di verifica. diff --git a/docs/flows.md b/docs/flows.md new file mode 100644 index 00000000..5a696be1 --- /dev/null +++ b/docs/flows.md @@ -0,0 +1,191 @@ +# Arcane — i flussi principali + +Ogni flusso segue un'azione dall'input all'effetto, nominando i tipi che se ne occupano. I dettagli e le regole di ogni passo sono nella sezione dell'area in [architecture.md](architecture.md); come costruire un pezzo nuovo è in [conventions.md](conventions.md). Se un flusso cambia, il suo schema si aggiorna nello stesso commit. + +- [1. Avvio dell'app](#1-avvio-dellapp) +- [2. Dal disco alla libreria](#2-dal-disco-alla-libreria) +- [3. Play di un gioco Switch (nxnative)](#3-play-di-un-gioco-switch-nxnative) +- [4. Play di un gioco Steam](#4-play-di-un-gioco-steam) +- [5. Costruire un gioco Switch (Add Game)](#5-costruire-un-gioco-switch-add-game) +- [6. Importare o ripristinare un salvataggio](#6-importare-o-ripristinare-un-salvataggio) +- [7. Installare una mod](#7-installare-una-mod) +- [8. Cambiare un'impostazione](#8-cambiare-unimpostazione) +- [9. Aggiornare l'app](#9-aggiornare-lapp) + +## 1. Avvio dell'app + +```mermaid +flowchart TD + A["NXLibraryApp (@main)"] --> B["DevelopmentStartupView<br/>AppData.prepare: profilo release o Dev"] + B --> C["AppSettingsStore · lingua (AppLocalization)<br/>LaunchReveal: finestra pronta, poi fullscreen"] + C --> D["CatalogStore legge catalog.json<br/>(conversione da library.json se serve)"] + D -->|"archivio danneggiato"| R["Recupero esplicito: Retry / ripristino backup"] + D -->|"catalogo valido, legacy modificato"| L["Scelta Keep Arcane’s library"] + L --> LA["Rivalida impronte → archivia catalogo, backup e legacy<br/>Mantieni i giochi Arcane e riconosci la base legacy"] + LA --> D + D --> E["AppShellState prepara coordinatore, router, tema"] + E --> F["AppShellView: AppViewModel, store, monitor, updater"] + F --> G{"Primo avvio completato?<br/>(FirstRunSetup)"} + G -->|"no"| H["Setup: found (Steam, app portate) → Open library<br/>oppure Porting → Get ready → Your games"] + G -->|"sì"| I["Benvenuto in Arcane una volta, per chi aggiorna<br/>altrimenti home scelta"] + H --> K["Prima home Spotlight: moonlight condiviso → entrata<br/>Entrance animation; niente volo con Riduci movimento"] + I --> K + F --> J["In background: recuperi dei salvataggi, installazioni in attesa,<br/>scansione Steam se attivo, controllo engine se attivo, aggiornamenti"] +``` + +Punti fissi: +- Gli store si costruiscono una volta sola, prima della shell. +- Un archivio illeggibile non diventa mai una libreria vuota. +- La Dev legge e scrive solo nel suo profilo. +- La scelta Steam del primo Setup resta salvata anche alla chiusura; lettura e attivazione usano la cartella scelta nella fonte. Una lettura incompleta offre Retry, senza dichiarare la libreria vuota. +- La cartella Game files ricordata resta una preferenza del selettore: l'avvio non ne enumera i sorgenti. +- Menu e dialoghi nativi hanno precedenza sul routing della shell: `nativeDialogOwnsInput` ferma i comandi del controller anche se un benvenuto, Setup o dialogo dell'app è già aperto sotto. + +## 2. Dal disco alla libreria + +```mermaid +flowchart TD + subgraph NX["Switch (nxnative)"] + N1["Cartella Game apps"] --> N2["ImportService<br/>DMTitleID o org.nxnative.*"] + N2 --> N3["NXNativeLibraryMerge<br/>conserva impostazioni, preferiti, build"] + end + subgraph ST["Steam"] + S1["libraryfolders.vdf + manifest"] --> S2["SteamLibrarySource<br/>(worker annullabile, limiti)"] + S2 --> S3["SteamCatalogReconciler<br/>ticket di revisione e radice"] + S4["SteamManifestWatcher (FSEvents)"] --> S2 + end + N3 --> W["CatalogRepository<br/>unico writer di catalog.json"] + S3 --> W + W --> P["CatalogLibraryProjection<br/>solo fonti attive"] + P --> V["Spotlight · Collection · Ricerca<br/>(stessi UUID, filtri, ordine)"] +``` + +Punti fissi: +- Una scansione aggiorna solo ciò che ha osservato; un'assenza non cancella nulla. +- Un risultato superato da un cambio di cartella o di fonte non si applica. + +## 3. Play di un gioco Switch (nxnative) + +```mermaid +flowchart TD + A["Play (GamePrimaryActions)"] --> B["AppViewModel.launchGame"] + B --> C{"Possibile ora?"} + C -->|"operazione sui salvataggi o recupero"| X["Attesa / spiegazione"] + C -->|"icona in firma"| Y["Dialogo Preparing (IconLaunchWait)"] + C -->|"sì"| D["SaveOperationGate: lease del titolo"] + D --> E["LauncherSettings migra launcher.json<br/>oppure LaunchService aggiorna env.txt"] + E --> F["CloudSavesPreferences applica la scelta cloud"] + F --> M["ModStore riconcilia le cartelle prima di Play"] + M --> G["LaunchService apre l'app (NSWorkspace)"] + G --> H["LaunchCoverWindow + LaunchMotion<br/>finché LaunchReadinessProbe vede una finestra"] + H --> I["RunningGameMonitor · PlaySessionStore (heartbeat)"] + I --> J["Fine: sessione salvata → SessionCard<br/>GameFocus/LibraryWindow riportano la libreria davanti"] + J --> K["Dopo la chiusura: icone, installazioni in attesa"] +``` + +## 4. Play di un gioco Steam + +```mermaid +flowchart TD + A["Play (GamePrimaryActions)"] --> B["SteamPlayCoordinator"] + B --> K["LaunchCoverWindow<br/>ripiego entro 1 s se il pannello manca"] + K --> C["steam://run/AppID al client di Valve"] + C --> D["SteamPlayState / SteamBackgroundLaunch<br/>attesa del processo del gioco"] + D -->|"Domanda effettiva o scadenza"| Q["La schermata lascia spazio a Steam"] + D --> E["LaunchCoverWindow finché il gioco disegna"] + E --> F["PlaySessionStore registra la sessione reale"] + F --> G["Fine: SessionCard · SteamReturnFocus"] + G --> H["SteamPlaytimeSync rilegge le ore da localconfig.vdf"] +``` + +Arcane legge le domande dal log di Steam. Durante `ShowInterstitials` l'attesa prosegue e il client può aprire le sue finestre dietro la schermata. Arcane non scrive mai i file di Steam e non apre l'app del gioco direttamente. Dettagli in [steam.md](steam.md). + +Nella pagina Spotlight di un titolo Steam, Giù porta anche a **More like this** quando la fascia è presente. Invio, A o doppio clic selezionano la copertina sulla riga della libreria. Se il filtro la esclude, la libreria passa a **All games** come per Switch. + +## 5. Costruire un gioco Switch (Add Game) + +```mermaid +flowchart TD + A["AddGameView: scelta esplicita di file o cartelle<br/>il selettore ricorda Game files"] --> B["SourceCatalog · ExtractedSourceCatalog · NUPSourceCatalog<br/>base, update, DLC"] + B --> C["SourceSelection: titolo e versioni scelte"] + C --> D["KeyCheck (se le sorgenti sono cifrate)<br/>NUP: identità programma e capacità del checkout"] + D --> E["Review: GameAppDestination, GameRuntimeConfig.forReview"] + E --> F{"Gate: CompatibilityChecker<br/>Metal certificato o override"} + F -->|"bloccato"| Z["Spiegazione (ToolchainGateCopy)<br/>Play delle app esistenti resta attivo"] + F -->|"ok"| G["WorkspaceManager + BuildScratch"] + G --> N["Porting accettato: richiesta permesso notifiche"] + N --> H["BuildCommandBuilder → BuildService<br/>processo dell'engine nxnative"] + H --> I["BuildEventParser → PortingProgress<br/>tile, percentuale, ETA<br/>prewarm senza conteggio: attività e tempo trascorso"] + I --> J["BuildOutputInstaller: scambio atomico"] + J -->|"gioco aperto o installazione fallita"| K["PendingInstall: Retry più tardi"] + J --> L["CatalogRepository: BuildRecord, toolchain"] + L --> M["AppIconWriter (se c'è un'icona scelta) · notifica"] +``` + +## 6. Importare o ripristinare un salvataggio + +```mermaid +flowchart TD + A["SavesPanel"] --> B["SavePanelModel"] + B --> C["AppViewModel+Saves: SaveLocation, identità, cloud"] + C -->|"cloud attivo o gioco aperto"| X["Rifiuto con motivo (SaveFailure)"] + C --> D["SaveOperationGate: lease"] + D --> E["SaveSnapshotStore.stageImport / SaveRestorePreview<br/>copia accanto, hash, anteprima From → To"] + E --> F["Conferma: sorgente, staging e salvataggio attuale<br/>schema 1: due slot · schema 2: tutti gli utenti + registro"] + F --> G["SaveTransaction: backup completo → journal → soli pezzi da modificare<br/>verifica originali; registro per ultimo"] + G --> H["SeleneSuccessNotice"] + G -.->|"interruzione"| I["Al prossimo avvio: rollback o verifica dal journal<br/>Play attende"] +``` + +## 7. Installare una mod + +```mermaid +flowchart TD + A["Fascia Mods o card Mods (store)"] --> B["GameBananaMatch: pagina del gioco"] + B --> C["AvailableModsFinder + ModSupport<br/>solo mod RomFS che funzionano"] + C --> D["ModDetailPanel: Install"] + D --> E["ModDownload (host GameBanana) · dimensione e MD5"] + E --> F["ModInstaller: bsdtar, niente .. / link"] + F --> G["ModStore.adopt: ordine e stato in mods/TID.json"] + G --> H["EnvFileEditor scrive DM_ROMFS_OVERLAY in env.txt"] + H --> I["L'engine legge le mod al prossimo avvio del gioco"] +``` + +## 8. Cambiare un'impostazione + +```mermaid +flowchart TD + A["Riga in Settings (SettingsCatalog)"] --> B["AppSettings modificato"] + B --> C["AppSettingsStore.save: file temporaneo e sostituzione"] + C -->|"errore"| X["Dialogo Selene con Retry"] + C --> D["Pubblicazione: le viste si aggiornano"] + A --> E["Search e Changed leggono lo stesso catalogo"] + F["Reset group (X)"] --> G["SettingsReset.reset: i valori della sezione tornano ai default"] + G --> B +``` + +Nel menu rapido, Theme apre prima i colori con anteprima viva; A applica la palette e passa alla selezione dello sfondo. Il tema Arcane conserva il blu classico e l’identità predefinita `selene`; le alternative Arcane Crystal e Arcane Flow salvano `arcane-crystal` e `arcane-flow` nello stesso `colorThemeID`. La shell conserva un backdrop persistente; le pagine ne dichiarano stile, pausa e Mods con `SeleneBackdropRequest`, mantenendo artwork e maschere locali. La shell passa la palette completa in `SeleneBackdropStyle`: cambia il valore dell’ambiente e aggiorna sfondo e maschere anche senza spostare la selezione. La superficie usa lo stesso renderer, con orologio e regole di pausa condivisi. Le particelle sono sempre morbide, senza una scelta aggiuntiva. La scelta dello sfondo mantiene il dialogo di destinazione esistente. + +La barra laterale segue `SettingsSidebarGroup`: General, Library, Porting e System. Ogni sezione mostra solo le righe di `SettingsCatalog` che le appartengono. + +In System → About, il pulsante Support Arcane compare tra il riepilogo dell’app e i crediti. `SettingsAboutSection` apre la pagina Buy Me a Coffee nel browser predefinito tramite clic, Invio o conferma del controller. + +Tornando alla home, le viste delle tessere ricreate leggono subito le immagini decodificate in `TileArtMemo`; i task caricano quelle mancanti e rivalidano i file Steam. La cover della card Mods resta nel `ModStoreHost` posseduto dalla shell ed è rivalidata in background rispetto agli abbinamenti correnti. + +## 9. Aggiornare l'app + +```mermaid +flowchart TD + A["AppUpdater: release su GitHub"] --> B{"AppUpdate.mayInstall<br/>versione più nuova e copia installabile"} + B -->|"no (copia Dev o sola lettura)"| X["Solo note di rilascio"] + B --> C["AppUpdateDownload: dimensione dichiarata, host GitHub"] + C --> D["validate_update.py: struttura e percorsi"] + D --> E["SaveOperationGate: esclusione globale"] + E --> F["Controllo di versione, identità e firma"] + F --> G["Copia in cartella esclusiva sul volume corrente"] + G --> H["Scambio atomico"] + H --> I["Vecchia app nel Cestino; se fallisce, conservarla nella cartella esclusiva"] + I --> J["Riavvio allo stesso percorso"] +``` + +Alla chiusura successiva, una copia release che si chiama ancora `NX Library.app` diventa `Arcane.app` (`AppBundleRename`, chiamato da `AppDelegate.applicationWillTerminate`). Non succede se un riavvio è in programma, perché l'aiuto che riapre l'app usa il percorso attuale. diff --git a/docs/media/README.md b/docs/media/README.md index 382d4a52..a9b347f4 100644 --- a/docs/media/README.md +++ b/docs/media/README.md @@ -1,41 +1,30 @@ # Immagini e video del README -Il README apre con logo, nome, descrizione e pochi badge. Spotlight introduce l'app; gli altri screenshot accompagnano la funzione descritta nella guida. Il video avrà posto subito sotto la presentazione, prima di Spotlight. Il blocco legale rimane in fondo. +Il README apre con l'icona di Arcane, il nome e la descrizione. Spotlight introduce la libreria. Le altre immagini accompagnano le funzioni della guida. ## Screenshot inclusi -Le otto catture fornite dall'utente il 2 novembre 2026 sono state rinominate nelle copie del repository. Gli originali sul Desktop restano invariati. Gli agenti non hanno aperto né automatizzato l'app. +| File nel repository | Posizione nel README | +|---|---| +| [spotlight.webp](spotlight.webp) | Apertura, prima di Overview. | +| [game-details.webp](game-details.webp) | Your library, dettagli e attività del gioco. | +| [quick-menu.webp](quick-menu.webp) | Your library, accesso al menu rapido. | +| [porting-progress.webp](porting-progress.webp) | Add or rebuild a game, avanzamento in Spotlight. | +| [color-themes.webp](color-themes.webp) | Artwork, themes and sound, scelta della palette. | +| [static-wallpapers.webp](static-wallpapers.webp) | Artwork, themes and sound, sfondi statici. | +| [live-wallpapers.webp](live-wallpapers.webp) | Artwork, themes and sound, sfondi animati. | +| [mod-store.webp](mod-store.webp) | Mods, store con banner e righe. | -| Nome originale | File nel repository | Posizione nel README | -|---|---|---| -| `Spotlight View.png` | [spotlight.webp](spotlight.webp) | Apertura, prima di Overview. | -| `Details Games.png` | [game-details.webp](game-details.webp) | Your library: dettagli e attività del gioco. | -| `Rapid Menu.png` | [quick-menu.webp](quick-menu.webp) | Your library: accesso al menu rapido. | -| `Porting State home .png` | [porting-progress.webp](porting-progress.webp) | Add or rebuild a game: avanzamento in Spotlight. | -| `Setting View.png` | [settings.webp](settings.webp) | Know which settings apply: categorie e Start-up. | -| `Color theme.png` | [color-themes.webp](color-themes.webp) | Artwork, themes and sound: scelta della palette. | -| `Background Static Wallpaper.png` | [static-wallpapers.webp](static-wallpapers.webp) | Artwork, themes and sound: sfondi statici. | -| `Background Wallpaper Live .png` | [live-wallpapers.webp](live-wallpapers.webp) | Artwork, themes and sound: sfondi animati. | -| `Mods.png` (7 novembre 2026) | [mod-store.webp](mod-store.webp) | Mods: lo store con il banner Featured e le righe. | +Le copie WebP sono larghe 1920 pixel, mantengono le proporzioni delle catture e usano il profilo colore sRGB. Le didascalie e i testi alternativi sono in inglese. [settings.webp](settings.webp) documenta l'interfaccia di NX Library precedente alla riorganizzazione di Settings. -Le copie WebP sono larghe 1920 pixel, mantengono proporzioni e contenuto delle catture e usano il profilo colore sRGB. Occupano complessivamente circa 2,3 MB, rispetto ai circa 73 MB degli originali. I metadati personali non vengono trasferiti. Le didascalie e i testi alternativi sono in inglese; ciascuna immagine ha una propria riga per preservare la leggibilità. - -La cattura di Settings mostra ancora il precedente pin `2716f78`; il pin corrente e i requisiti sono quelli del README. Aggiornare questa foto alla prossima sessione di cattura. Anche lo stato delle sorgenti e della toolchain nei dettagli di un gioco descrive soltanto il gioco fotografato. - -Le immagini illustrano la libreria dell'utente. Copertine, loghi e wallpaper visibili restano soggetti ai diritti e ai termini dei rispettivi proprietari; la licenza MIT del codice non ne modifica i termini. +Le copertine, i loghi e i wallpaper visibili nelle catture restano soggetti ai diritti e ai termini dei rispettivi proprietari. ## Aggiornare le immagini -Conservare le catture complete, senza modificare lo stato mostrato o ricreare l'interfaccia. Preparare copie ottimizzate in questa cartella e collegarle alla sezione pertinente del README con testo alternativo e una didascalia breve. Controllare che non siano visibili chiavi, percorsi privati o notifiche personali. Non aggiungere file di gioco o asset separati. - -Gli screenshot del setup in due passaggi e dell'anteprima dei salvataggi potranno essere aggiunti quando disponibili; non ci sono segnaposto visibili. Il commento `NX-SCREENSHOTS` delimita l'immagine d'apertura e `NX-DEMO` riserva il posto al video. Aggiornare anche il [catalogo dei file](../file-map.md) quando si aggiungono o rinominano immagini. +Conservare le catture complete con lo stato originale dell'interfaccia. Aggiungere una copia WebP con didascalia e testo alternativo. Controllare che percorsi privati, chiavi e notifiche personali restino fuori dalle catture. Il commento `NX-SCREENSHOTS` delimita l'immagine d'apertura. Aggiornare il [catalogo dei file](../file-map.md) se cambia l'inventario. ## Video subito dopo la presentazione -Una registrazione breve, circa 45–90 secondi, può mostrare Spotlight, Collection, le opzioni di un gioco, un'anteprima dei salvataggi e Settings. I tempi di una build vanno abbreviati dichiarandolo; non presentare una sequenza tagliata come una compilazione istantanea. - -Preferire un MP4 con H.264 per un'ampia compatibilità. Quando l'utente fornirà il video, caricarlo come allegato GitHub e mettere il suo URL su una riga autonoma al posto del commento `NX-DEMO`, subito dopo la presentazione. Non aggiungere un file video pesante alla cronologia Git. Verificare la riproduzione e l'accessibilità dell'allegato anche nel contesto di pubblicazione previsto. - -La resa degli allegati dipende dal contesto e dal browser. Se il lettore non viene mostrato nel README, usare un fermo immagine cliccabile che apra il video, conservandolo nella stessa posizione. Non inserire pulsanti Play che portano a un video ancora inesistente. Riferimenti: [allegati GitHub](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/attaching-files) e [allegati tramite GitHub CLI](https://docs.github.com/en/github-cli/github-cli/attaching-files-with-github-cli). +Il blocco `NX-DEMO` accoglie un allegato GitHub subito dopo la presentazione. Preferire un MP4 con H.264 e verificare la riproduzione nel README pubblico. Segnalare nel video eventuali tempi di compilazione abbreviati. -Quando uscirà una release, aggiornare immagini o filmato se l'interfaccia è cambiata. Il video e gli screenshot illustrano la versione mostrata e non certificano il supporto di ogni gioco. +Se il lettore non appare nel README, usare un fermo immagine che apre il video. [Allegati GitHub](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/attaching-files) diff --git a/docs/reviews/2026-11-16-ratings-metadata-evidence.md b/docs/reviews/2026-11-16-ratings-metadata-evidence.md new file mode 100644 index 00000000..6fd0f4ec --- /dev/null +++ b/docs/reviews/2026-11-16-ratings-metadata-evidence.md @@ -0,0 +1,104 @@ +# Voti e metadati: prove e verifiche (16 nov 2026) + +Nota datata. Raccoglie le verifiche reali e le misure che hanno motivato scelte descritte in [architecture.md](../architecture.md#artwork-metadati-e-voti). Il testo è quello che stava nella guida tecnica prima del riordino del 17 novembre 2026; qui resta come prova, la guida descrive solo il comportamento attuale. + +## Wikidata: difetti trovati nella libreria reale + +La verifica nella libreria reale ha individuato due difetti di ricerca: i simboli ™/®/© +nei nomi dello store davano risultati vuoti, e un nome Steam personalizzato non identificava +il titolo. Le query ora tolgono soltanto quei simboli, conservando sequel/edizioni; Steam +prova prima P1733 (ID pubblico esatto), verificato di nuovo nelle dichiarazioni dell'entità. +Il ripiego per nome usa anche il campo `match` degli alias. Le assenze salvate dal vecchio +resolver vengono ricontrollate, senza eliminare voti validi o modificare la libreria. + +## IGDB: console Switch 2 (Ocarina of Time) + +La verifica di Ocarina of Time (2026-11-16) ha individuato un filtro errato: entrambe +le pagine passavano sempre Switch (IGDB 130), scartando la scheda Switch 2. La query ora +deriva la console da `PortedGame.isSwitch2`, come Details, e distingue `switch` da +`switch2` (IGDB 508; Wikidata Q122761124). Nome/alias esatti e unicità rimangono obbligatori: +non si allarga il filtro alle due console insieme, evitando di mescolare edizioni omonime. +La console fa parte della chiave di entrambe le cache: Switch 2 riprova subito senza +riutilizzare l'assenza salvata come Switch, mentre voti validi e cache esistenti restano +intatti. Nessuna cancellazione di dati o modifica alle credenziali. Test con dati sintetici +coprono edizioni omonime, query dai giochi, compatibilità della vecchia identità Switch, +ripiego Wikidata e un'assenza preesistente. Restano da validare in Dev Ocarina/Switch 2, +un titolo Switch e uno Steam; la disponibilità effettiva del dato è stata poi verificata +con la richiesta autorizzata descritta sotto. La nuova presentazione del ripiego utenti +rimane in attesa di validazione umana. + +## IGDB: verifica diretta autorizzata + +Verifica diretta autorizzata dal maintainer il 16 novembre 2026: la stessa ricerca +dell'app restituisce la scheda Ocarina Switch 2 (405460, piattaforma 508), confermata +anche per ID. La risposta non contiene `aggregated_rating` né `aggregated_rating_count`: +ha solo `rating` (circa 99,7) e `rating_count` (35), cioè voti utenti al momento della +verifica. L'assenza nella riga della critica è quindi attesa anche dopo la correzione +della console. Non sostituire silenziosamente il voto utenti o quello di un'altra +edizione. Il maintainer ha poi approvato il ripiego utenti esplicitamente distinto. +Nessuna credenziale o token è stata registrata. + +## Download a blocchi: misura + +Correzioni del 16 novembre 2026 (in attesa di validazione umana). Una media della critica IGDB +vale solo con almeno 3 recensioni (`IGDBRatings.minimumCriticReviews`): con meno, la riga usa +Wikidata o, in sua assenza, la media utenti IGDB esplicita. `CriticRating.isValid` applica lo +stesso minimo, così le vecchie cache con 1–2 recensioni vengono richieste di nuovo. Salvare le +credenziali riporta anche una cartella `credentials` già esistente al modo 0700. I download di +Wikidata, IGDB, LaunchBox/TheGamesDB e Steam passano per `BoundedDownload`, che conserva i +blocchi ricevuti da URLSession: leggere `AsyncBytes` un byte alla volta costava circa 6 µs per +byte (pagina LaunchBox da 640 KB: 5,4 s e 3,9 s di CPU, ora 2,0 s e circa 10–30 ms di CPU). +Limiti di dimensione, rifiuto dei redirect e annullamento restano invariati. + +## Selettore dei metadati: correzione del movimento + +Correzione del movimento nel selettore: il cambio di focus sostituiva istantaneamente +l'estratto (240 caratteri) con il testo completo e avviava separatamente uno scroll +centrato, anche per righe più alte della finestra. `SeleneExpandableText` conserva i +due layout alla stessa larghezza: `Layout` risolve subito la geometria finale, +mentre SwiftUI anima i frame e la dissolvenza tra estratto e testo completo +([contratto SwiftUI](https://developer.apple.com/documentation/swiftui/layout)). +Interpolare le misure dentro `Layout` sposterebbe il bersaglio di `scrollTo` +durante la chiusura della riga precedente; la sonda fuori schermo ha riprodotto +questo errore e verificato l'allineamento con misure finali stabili. +Il selettore usa la stessa curva per espansione e scroll, con allineamento iniziale +per leggere il titolo delle descrizioni lunghe. Riduci movimento disattiva entrambi. +L'opzione è locale ai metadati: gli altri `SeleneOptionRow` restano invariati. Nessuna +modifica a richieste, cache, testi salvati o selezione delle fonti. + +`scripts/check_metadata_text_layout.swift` verifica fuori schermo le altezze a tre +larghezze, il cambio di contenuto e le destinazioni dello scroll durante cambi +di focus ripetuti, anche con Riduci movimento; non misura frame rate o fluidità reale. +Da verificare nella Dev: su/giù ripetuti fra descrizioni corte e molto lunghe, scroll +manuale fino alla fine, Q/E, scelta/salvataggio e Riduci movimento. Correzione del +movimento **in attesa di validazione umana**. + +## LaunchBox e TheGamesDB: sonde reali + +Scelta: leggere su richiesta una ricerca e una scheda pubblica per database, con +parser separati e cache di sole proposte; non scaricare l'intero Metadata.zip né +duplicare un catalogo immagini. Le sonde delle pagine pubbliche hanno misurato circa +74 KB per una scheda LaunchBox e 15 KB per una TheGamesDB, senza scaricare immagini. +Il formato corrente LaunchBox espone gameKey/name/platform e campi indicizzati nel +payload Nuxt; TheGamesDB espone titolo, piattaforma e campi etichettati. I parser +devono verificare anche la scheda finale, rifiutare ambiguità e non eliminare parole +di edizione. Mac è preferito a PC/Windows; una proposta alternativa PC è dichiarata +e non fornisce una falsa data Mac. Le righe delle fonti restano visibili e stabili, +con stati assente/uguale ad Automatico/errore e retry accessibile, senza scrivere +scelte personali durante il caricamento. Cache, dimensioni, durata, annullamento e +numero di richieste sono verificati con test e sonde: nessuna promessa di massima +prestazione deriva dalla sola compilazione. Implementato; controlli automatici e confezionamento Dev descritti sotto. +Validazione umana ancora necessaria. + +La sonda reale ha individuato un redirect LaunchBox da ricerca con maiuscole al +percorso minuscolo: `LaunchBoxArt.searchURL` ora genera direttamente la forma canonica, +evita il 301 e permette il client vincolato anche per i metadati. La prova, con cache +isolata e titoli pubblici di fixture, ha restituito cinque campi per Donkey Kong +Bananza (Switch 2) e quattro per Hollow Knight (PC come alternativa Mac, senza data +PC). In quella singola esecuzione la prima lettura ha impiegato circa 1,595 s e +0,510 s; le riletture locali circa 0,420 ms e 0,275 ms. Non sono misure di frame rate +né garanzie sulla latenza dei servizi. Il probe temporaneo non è incluso nei test +normali; i test riproducibili verificano invece due richieste per una ricerca +LaunchBox, zero richieste cambiando campo/rileggendo una cache fresca, coalescenza, +annullamento, retry e risposte sovradimensionate o di destinazione inattesa. + diff --git a/docs/reviews/2026-11-17-arcane-moonlight.md b/docs/reviews/2026-11-17-arcane-moonlight.md new file mode 100644 index 00000000..2c3f802f --- /dev/null +++ b/docs/reviews/2026-11-17-arcane-moonlight.md @@ -0,0 +1,173 @@ +# Moonlight Arcane — prove e misure del 17 novembre 2026 + +Il tema Arcane mantiene l’identità `selene` e usa un campo cromatico continuo +nei passaggi Metal già esistenti. Le misure sotto documentano anche la prima +prova di Crystal dust, successivamente rimossa; immagini e video mantengono +il proprio aspetto. + +## Contratti verificati + +`MoonlightAppearanceTests` prova compatibilità dei file vecchi e dei valori +sconosciuti, salvataggio, Changed/Reset, continuità e periodicità dei colori, +e accesso alla riga delle particelle prima della scelta dello sfondo. + +`run_theme.py` esegue i veri metodi di input con `AppSettingsStore` su una +cartella sintetica: movimento dal bordo della griglia alla riga, scelta +sinistra/destra, ritorno alle palette, mouse e A verso il passo sfondo. +Confronta anche l’ordine delle righe visibili di Look con quello delle azioni +di tastiera e controller. Questa regressione falliva prima della correzione +dell’ordine fra Background motion e Particles. + +Con Metal disponibile, lo stesso script compila gli shader reali e confronta +il campionamento GPU dello spettro con quello del Core. Verifica le uniform +dei due effetti e di Mods, la differenza dei frame delle particelle e +l’identità di due immagini renderizzate allo stesso istante. Non apre +finestre, non cattura lo schermo e non legge profili del giocatore. Senza +device Metal salta soltanto la parte GPU; con un device e shader non +compilabili fallisce. + +## Semplificazione delle particelle, 17 novembre + +Il maintainer chiede di mantenere soltanto le particelle morbide: le faccette +sono poco distinguibili e non giustificano un’opzione. Il selettore esce da +Theme e Look, dal catalogo Search/Changed/Reset e dal renderer. Il campo +storico `particleStyle` è ignorato alla lettura e non viene più salvato. + +I test di compatibilità e focus falliscono prima della rimozione e passano +dopo; la suite Swift esegue 1790 test senza errori. `run_theme.py` verifica +i metodi reali della griglia, il passaggio allo sfondo, l’ordine delle righe +Look e gli shader Metal reali: particelle morbide, campionamento GPU/Core, +frame fermo e uniform distinti per Mods. Questi controlli non sostituiscono +la prova visiva del maintainer. La tabella seguente resta la misura storica +della prima versione e non misura la rimozione delle faccette. + +## Tempo dei passaggi GPU, fuori schermo + +Misura locale con il renderer precedente e quello nuovo, stesso campo +deterministico e texture BGRA8 privata. Ogni riga ha 32 campioni dopo +10 frame di riscaldamento. Il tempo viene da `MTLCommandBuffer.gpuStartTime` +e `gpuEndTime`; include luce e particelle, non composizione della finestra, +SwiftUI, acquisizione del drawable o presentazione sul display. + +| Profilo | Dimensione | Mediana GPU | P95 GPU | +|---|---|---|---| +| Precedente | 1920 × 1080 | 0,373 ms | 1,406 ms | +| Classico nel renderer nuovo | 1920 × 1080 | 0,395 ms | 2,280 ms | +| Arcane + Crystal dust | 1920 × 1080 | 0,238 ms | 1,541 ms | +| Precedente | 3840 × 2160 | 0,751 ms | 2,414 ms | +| Classico nel renderer nuovo | 3840 × 2160 | 0,711 ms | 2,298 ms | +| Arcane + Crystal dust | 3840 × 2160 | 0,894 ms | 2,554 ms | + +L’ordine delle misure, il carico del desktop e la frequenza dinamica della GPU +non sono controllati. Le differenze non dimostrano un miglioramento di +prestazioni né garantiscono un frame rate nell’app. Servono a rilevare costi +evidenti nei soli passaggi aggiunti; fluidità, contrasto e integrazione si +verificano nella Dev. Lo stato delle prove umane è in +[validation.md](../validation.md). + +## Superfici Arcane e Arcane Flow + +Le due superfici usano filamenti analitici e piani generati nello shader. +Il colore resta locale (rosa a sinistra, ciano a destra), con variazioni +minime su180s. Nessun asset grafico esterno alimenta il movimento. +La variante è un metadato facoltativo della palette; la preferenza resta +`colorThemeID`. Le regole di pausa, Riduci movimento, copertura da artwork +ed entrata restano quelle del renderer e delle viste condivise. + +La suite esegue1792test senza errori. Il controllo Metal confronta colori +GPU/Core, superfici distinte, fotogrammi identici a tempo fermo, movimento +a tempi diversi, uniform della variante Flow e oro Mods indipendente. +I fotogrammi sintetici delle due superfici sono stati ispezionati fuori +schermo; non sono screenshot dell’app e non provano la fluidità interattiva. + +Una sonda a1920×1080 registra il tempo completo di `snapshot`, inclusi +allocazione, rendering, attesa e lettura CPU:12campioni dopo3di riscaldamento. +Mediane classico10,68ms, Arcane12,55ms, Flow12,41ms; massimi rispettivamente +11,86/13,08/13,08ms. Questi valori non sono tempi GPU né frame rate della +finestra e non sono confrontabili con la tabella GPU precedente. La prova +umana nella Dev resta necessaria per fluidità, leggibilità e ritmo. + +La revisione individua valutazioni inutili: variante nascosta e fascio classico +anche con superficie Arcane pienamente visibile. I rami uniformi ora evitano +quei percorsi a regime; durante le dissolvenze restano entrambi. Le misure +sopra precedono questa correzione e non ne quantificano il beneficio. Il +controllo finale include anche blend intermedi e trasparenza a presenza zero. + +Il blu classico resta il default `selene` e il fallback. Le superfici nuove +sono alternative esplicite: `arcane-crystal` (Arcane Crystal) e `arcane-flow` +(Arcane Flow). I controlli verificano anche questa separazione, l’ordine +predefinito e la persistenza degli ID; nessuna preferenza è riscritta. +Il ripristino del blu confronta esattamente i valori della palette storica; +il metadato delle nuove superfici è assente sia dal default sia dal fallback. +La suite completa passa ancora1792test, con una regressione inizialmente +rossa per default, fallback, ordine e numero delle alternative. + +## Ripristino effettivo della luminosità originale + +Il primo ripristino usava ancora i colori scuriti nell’esperimento5eb9862. +Il riferimento corretto è f427937: default radiale0x102A5C/0x03081A e fallback +lineare0x17244A/0x0C142C/0x05080F. Test inizialmente rossi ora proteggono +questi valori. Gli shader classici attuali sono confrontati fuori schermo con +quelli di f427937, stesso campo e uniform: differenza massima per canale +0/255 a320px,1/255 a640px,0/255 a960px. Il controllo del pacchetto Dev +conferma l’esatta palette storica, escluso il nome visibile. Non è una prova +della finestra o della composizione dello schermo. + +## Fili sottili e onde viaggianti + +La correzione mantiene intatto il percorso classico. Nei due temi opzionali +il profilo usa un nucleo gaussiano da0,5pixel sigma e dispersione molto +debole; il footprint è calcolato dalle derivate spaziali per mantenere il +tratto sottile anche sulle diagonali. Due onde sovrapposte deformano le curve +lungo la loro lunghezza, con fili secondari più deboli ed estremi sfumati. +I bokeh grandi sono attenuati soltanto nelle alternative. + +La regressione GPU inizialmente rossa prova le funzioni Metal effettive: +luce a un pixel dal nucleo inferiore al20% del picco, escursione limitata, +spostamenti continui e deformazioni diverse in due punti del filo. Restano +le prove di colori locali, trasparenza a presenza zero, blend e Mods. +Fotogrammi sintetici e una sequenza reale di18secondi a30fps sono generati +fuori schermo, senza finestre o catture; questi dati non verificano la +fluidità dell’app e la qualità visiva resta da confermare dal maintainer. + +## Cambio palette con selezione invariata + +La prova dei metodi reali della shell e di ThemeStore riproduce la regressione: +il valore di SeleneBackdropStyle restava identico quando cambiava soltanto la +palette. SwiftUI non riceveva un cambiamento dell’ambiente; il successivo +spostamento della card ridisegnava il contenuto e rileggeva i colori globali. +Ora lo snapshot comprende la palette e i consumer di sfondo/maschere usano +quel valore. La prova inizialmente rossa passa per blu → Crystal → Flow → blu +senza cambiare il wallpaper né la card. Non si ricrea la pagina con un ID. + +Su richiesta del maintainer, le alternative conservano solo filamenti e +luce ambientale molto tenue: rimossi i piani e ridotti i campi diffusi. +Il percorso classico del default resta invariato. Lo scatto/intervallo nero +nell’apertura immediata delle impostazioni resta distinto: log locali nella +sola Dev misurano renderer creato/presentato e apertura pagina, senza dati +del giocatore. I test d’ingresso verificano i contratti di readiness, non +la fluidità della finestra. + +## Continuità home → Settings + +La prova umana conferma lo scatto/nero. I log mostrano windowSettling=false +e un renderer nuovo ad ogni ingresso/ritorno, con21–57ms al primo drawable +presentato; la discontinuità non dipende soltanto dal fullscreen iniziale. +La shell conserva ora la superficie persistente. Le pagine dichiarano i +parametri tramite SeleneBackdropRequest e mantengono artwork/maschere, +senza creare un secondo sfondo. Il frame e il clock restano nella stessa +istanza; una richiesta assente conserva i parametri e mette in pausa. + +I controlli headless coprono ordine delle richieste sovrapposte, mantenimento +del frame, pausa, ritorno agli stessi parametri, cambio palette e Mods. +Passano anche ingresso, onboarding e routing reali senza finestre. La prova +finale nella Dev deve confermare continuità visiva e stesso ID del renderer +attraverso home/Settings; i test di codice non sostituiscono questa verifica. + +La revisione rileva che condividere la superficie richiede anche di coprire +i contenuti dei livelli inferiori. ShellBackdropCover definisce nel Core +la precedenza Setup2,5 → benvenuto2,4 → scelta tema1: ogni strato inferiore +resta montato/caldo ma quasi trasparente e senza input; dialoghi superiori +restano visibili. Controls applica la stessa separazione al contenuto locale +di Settings. Il blur esistente copre anche lo sfondo persistente. I test +verificano la precedenza dei tre schermi e i livelli0/0,5/0,8/1/2/2,4/2,5/3/4. diff --git a/docs/reviews/2026-11-17-dock-rename-probe.md b/docs/reviews/2026-11-17-dock-rename-probe.md new file mode 100644 index 00000000..54fa671e --- /dev/null +++ b/docs/reviews/2026-11-17-dock-rename-probe.md @@ -0,0 +1,11 @@ +# Dock e app rinominata — sonda del 17 novembre 2026 + +**Domanda:** se un'app nel Dock viene rinominata mentre è chiusa, il Dock la apre ancora? + +**Sonda** (macOS 27.2, Mac del maintainer): +1. Un'app minima `NX Probe.app` in `~/Applications`, firmata ad-hoc, bundle ID `local.nxlibrary.dockprobe`, tenuta nel Dock dal maintainer e chiusa. +2. Rinominata in `Arcane Probe.app` con `mv`, nella stessa cartella. +3. Dopo la rinomina, `defaults read com.apple.dock persistent-apps` mostra ancora `_CFURLString` = `file:///Users/<utente>/Applications/NX%20Probe.app/` e `file-label` = "NX Probe". +4. Il maintainer ha cliccato l'icona nel Dock: l'app si è aperta e la sua finestra mostrava il percorso nuovo. + +**Esito:** il Dock segue una rinomina nella stessa cartella. Il percorso salvato non serve a ritrovare l'app: per inferenza, il Dock la risolve dal segnalibro o dal bundle ID. L'app di prova è stata messa nel Cestino. diff --git a/docs/reviews/2026-11-17-entrance-frames.md b/docs/reviews/2026-11-17-entrance-frames.md new file mode 100644 index 00000000..af75dac6 --- /dev/null +++ b/docs/reviews/2026-11-17-entrance-frames.md @@ -0,0 +1,50 @@ +# Entrata della libreria — misure del 17 novembre 2026 + +## Metodo + +Una sonda temporanea nella Dev registrava `CACurrentMediaTime()` durante le +valutazioni di `EntranceFlight.effectValue`, unendo campioni distanti meno di +2 ms. Il log `entrance` riportava attesa dopo la copertura, durata, intervallo +massimo e numero di intervalli oltre 1,5 volte il periodo ricavato da +`NSScreen.maximumFramesPerSecond`. Il conteggio escludeva i primi 100 ms. + +Le aperture erano eseguite dal maintainer, con e senza benvenuto e con avvio +fullscreen. Non sono state usate automazione UI o catture dello schermo. + +## Campioni + +I campioni seguenti provengono dal log della Dev durante le iterazioni della +stessa giornata. Le versioni avevano tempi diversi: la durata non è un confronto +diretto di velocità fra prima e dopo. + +| Campione | Frequenza dichiarata | Attesa | Durata campionata | Intervallo massimo | Intervalli oltre soglia | +|---|---:|---:|---:|---:|---:| +| 10:16:33, benvenuto, prima del disegno anticipato delle tessere | 120 Hz | 0 ms | 1.471 ms | 28 ms | 3 / 160 | +| 11:08:57, benvenuto, disegno anticipato e pausa di 0,5 s | 120 Hz | 512 ms | 2.124 ms | 9 ms | 0 / 243 | +| 11:39:06, fullscreen, arte ancora in lettura alla scadenza | 120 Hz | 1.562 ms | 2.184 ms | 10 ms | 0 / 251 | +| 11:57:18, fullscreen, senza benvenuto | 120 Hz | 523 ms | 2.188 ms | 9 ms | 0 / 251 | + +Nel primo campione i tre intervalli lunghi cadevano a 523, 610 e 798 ms, +vicino alle prime apparizioni di tessere. Il disegno anticipato usa opacità +0,001 per la riga e il contenuto dell'effetto prima della comparsa: negli +ultimi campioni non si osservano intervalli oltre soglia dopo i primi 100 ms. +Resta la riga reale animata in SwiftUI; il livello dell'arte sfuma in Core Animation. + +Per l'avvio fullscreen delle 11:57, il log registra il primo frame del moonlight +a 388 ms, l'inizio della transizione a 702 ms e la fine a 1.547 ms dalla prima +apparizione della finestra. `LaunchReveal` attende il primo frame con un limite +di 1 s prima di mostrare la finestra e consentire il fullscreen. + +## Limiti e conservazione + +- I campioni misurano valutazioni dell'animazione SwiftUI sul thread principale, + non i frame presentati dalla GPU o dal compositor. +- La frequenza usata è il massimo dichiarato dallo schermo, non una misura del + refresh effettivo. La soglia è quindi un indicatore diagnostico. +- I primi 100 ms non partecipano al conteggio degli intervalli lunghi. +- Hardware, cache, libreria e tempi sono quelli delle singole aperture; questi + numeri non garantiscono lo stesso risultato su altri Mac o dati. + +La sonda e le sue chiamate sono rimosse dal codice applicativo; questa nota +conserva metodo e risultati. Lo stato delle prove manuali resta soltanto in +[validation.md](../validation.md). diff --git a/docs/reviews/2026-11-18-spotlight-glide.md b/docs/reviews/2026-11-18-spotlight-glide.md new file mode 100644 index 00000000..0f473aa6 --- /dev/null +++ b/docs/reviews/2026-11-18-spotlight-glide.md @@ -0,0 +1,77 @@ +# Primi cambi gioco in Spotlight — misure del 18 novembre 2026 + +Lo scatto compariva con destra e sinistra nei primi movimenti dopo l'entrata. +La prova manuale confronta più avvii della Dev. Una sonda temporanea campiona il +valore animato della camera della riga sul thread principale, unisce le letture +a meno di 2 ms e riporta l'intervallo più lungo e il lavoro sincrono misurato. + +| Campione | Primo aggiornamento | Intervallo massimo | Mod sul thread principale | Salvataggio selezione | +|---|---:|---:|---:|---:| +| Prima, primo cambio | 24 ms | 35 ms | 9 ms | 2 ms | +| Prima, secondo cambio | 9 ms | 15 ms | 5 ms | 1 ms | +| Dopo, primo cambio | 19 ms | 28 ms | < 0,5 ms | 9 ms | +| Dopo, secondo cambio | 15 ms | 16 ms | < 0,5 ms | 7 ms | +| Scrittura in background, primo cambio (avvio 1) | 28 ms | 52 ms | — | in background | +| Scrittura in background, secondo cambio (avvio 1) | 17 ms | 18 ms | — | in background | +| Scrittura in background, primo cambio (avvio 2) | 29 ms | 53 ms | — | in background | +| Scrittura in background, secondo cambio (avvio 2) | 14 ms | 15 ms | — | in background | + +Spotlight legge le mod all'apertura della pagina e Play riconcilia le cartelle +prima dell'avvio del gioco. Il controllo senza finestre usa la funzione di +Spotlight con un sostituto di `ModsBandHost` e verifica che la riga non legga +la fascia del gioco successivo, mentre la pagina la carica. + +Il salvataggio sincrono della selezione arriva a 7–9 ms dopo il primo intervento. +`AppSettingsStore` passa quella scrittura alla coda seriale in background e +completa la scelta alla chiusura. I test esercitano la scrittura fuori dal +thread principale e la precedenza del valore più recente al salvataggio. + +Entrambi i primi cambi nel passaggio con scrittura in background hanno 27 +aggiornamenti in circa mezzo secondo. I secondi ne hanno 58 e 59. Nei due +campioni freddi l'artwork successivo entra 45 ms dopo la fine del +campionamento della riga. La differenza di cadenza richiede una misura +dedicata e non stabilisce da sola la causa. + +Un campionamento CPU di 12 s rallenta anche i movimenti successivi, con +intervalli di 112–172 ms. Questi tempi sono esclusi dal confronto. Nelle pile +del thread principale si osserva `rememberLastSelectedGame` → setter +`@Published` → invalidazione e aggiornamento sincrono della pagina Spotlight. +La scelta diventa stato di navigazione osservato solo dalla logica di +ripristino. Lo stesso store conserva il campo nel JSON. Un test conta le +notifiche dello store e richiede zero per un cambio di selezione riuscito. + +Senza la notifica delle impostazioni, i primi cambi dei tre avvii danno +55, 51 e 27 aggiornamenti, con intervalli massimi di 25, 33 e 51 ms. +Il secondo cambio singolo dell'ultimo avvio dà 59 aggiornamenti e 22 ms. +In quest'ultimo avvio la nuova immagine sfuma dopo il campionamento. +Una prova con `CADisplayLink` chiede 120 Hz durante lo scorrimento. Core +Animation indica un obiettivo di circa 8 ms, ma la riga registra 26 +aggiornamenti e un intervallo massimo di 53 ms. La prova non risolve lo +scatto e la richiesta viene rimossa. + +Il percorso delle frecce costruiva il modello Dettagli prima di spostare +la riga, anche se non lo usava. SwiftUI impaginava la parte inferiore della +pagina anche durante la navigazione tra tessere. La riga usa ora solo la +lista filtrata. Dettagli, descrizione e giochi correlati si costruiscono +quando la pagina sale. Il controllo senza finestre verifica il cambio di +tessera, il bordo della riga e la precedenza della navigazione nella pagina. + +### Esito della riga separata + +| Avvio | Primo aggiornamento | Intervallo massimo | Aggiornamenti nel primo cambio | +|---|---:|---:|---:| +| 1 | 19 ms | 11 ms | 59 | +| 2 | 9 ms | 14 ms | 60 | +| 3 | 12 ms | 15 ms | 59 | + +Il primo cambio nella prova precedente registrava 26 aggiornamenti e un +intervallo massimo di 53 ms. La curva, la geometria della riga e l'entrata +rimangono identiche nel codice. La parte inferiore della pagina si monta +alla sua apertura, quindi i suoi caricamenti possono iniziare più tardi. +Il controllo dei file prima di Play conserva record e overlay se la lettura +fallisce. Le fixture coprono cartella illeggibile, JSON corrotto e singola +mod assente in una cartella leggibile. + +I valori provengono da singoli avvii. Indicano i tempi degli aggiornamenti di +SwiftUI, non i frame presentati dal compositor. La sonda è rimossa dalla Dev. +Lo stato delle prove manuali è in [validation.md](../validation.md). diff --git a/docs/reviews/2026-11-18-steam-launch-spaces.md b/docs/reviews/2026-11-18-steam-launch-spaces.md new file mode 100644 index 00000000..09f2ee45 --- /dev/null +++ b/docs/reviews/2026-11-18-steam-launch-spaces.md @@ -0,0 +1,7 @@ +# 2026-11-18 — Cambi ripetuti di Space durante Play Steam + +Il video mostra la schermata di attesa e la pagina di Arcane che scorrono lateralmente, alternate a Steam, scrivania e fotogrammi neri. Arcane segnala il pannello consegnato al server delle finestre e invia Play alle 09:36:06.407. Steam è già in esecuzione e si ferma a `ShowInterstitials`. Il log di sistema conta 55 eventi `DoHide(self)` di Steam fra 09:36:07.454 e 09:36:12.035, durante le oscillazioni. Alle 09:36:21.910 la schermata lascia spazio a Steam per scadenza dell'attesa. Gli eventi relativi al controller si sovrappongono al problema, con il primo evento osservato dopo l'inizio dei nascondimenti. Non stabiliscono cosa abbia fatto riapparire Steam. + +Con **Keep Steam in the background** attivo, ogni notifica di attivazione o riapertura richiamava il controllo che nascondeva il client mentre il gioco era in avvio. Il rilancio della finestra di Steam riattivava quel controllo. Limitarsi a ritardare i nascondimenti conserva la causa. Per l'attesa è già disponibile il pannello che attraversa gli Space, quindi il client può finire di aprire le finestre senza essere nascosto durante Play. + +La regressione headless esegue il metodo reale su dieci riaperture simulate. Prima della correzione rileva chiamate a `hide()`. Con la correzione il contatore resta a zero e, alla scadenza, Steam viene comunque mostrato. [Prove interattive](../validation.md) diff --git a/docs/steam.md b/docs/steam.md new file mode 100644 index 00000000..17249f14 --- /dev/null +++ b/docs/steam.md @@ -0,0 +1,343 @@ +# Steam in Arcane + +Riferimento unico dell’integrazione Steam: cosa legge, come decide, cosa mostra, e cosa resta da validare. È il +documento da leggere prima di toccare qualunque parte Steam. `architecture.md` ne tiene solo un riassunto; +`file-map.md` elenca i file uno per uno. + +Ramo: `bium/library-manager` (rilascio grande, non pubblicato). Aggiornato al 17 novembre 2026. + +## Indice + +- [Principi](#principi) +- [Stato di validazione](#stato-di-validazione) +- [File di Steam letti](#file-di-steam-letti) +- [Rilevamento e catalogo](#rilevamento-e-catalogo) +- [Stati di un gioco Steam](#stati-di-un-gioco-steam) +- [Osservazione dei file di Steam](#osservazione-dei-file-di-steam) +- [Libreria: tile, ordine, pagina](#libreria-tile-ordine-pagina) +- [Play, sessioni e primo piano](#play-sessioni-e-primo-piano) +- [Ore di gioco](#ore-di-gioco) +- [Achievement](#achievement) +- [Metadati, arte e personalizzazioni](#metadati-arte-e-personalizzazioni) +- [Dati su disco di Arcane](#dati-su-disco-di-arcane) +- [Scelte del maintainer](#scelte-del-maintainer) +- [Limiti noti e punti rimandati](#limiti-noti-e-punti-rimandati) +- [Cambiare l’integrazione](#cambiare-lintegrazione) + +## Principi + +- **Steam non viene mai scritto.** Arcane legge file di Steam e invia solo URL `steam://` al client di Valve + (bundle `com.valvesoftware.steam`); non apre mai l’app di un gioco direttamente. +- **Dati privati fuori dal tipo.** `localconfig.vdf`, `loginusers.vdf` e i file delle statistiche contengono ticket, + amici e altro: ogni lettore estrae solo i campi che servono, non li registra nei log e non li conserva oltre il + necessario. Nessun dato privato va in rete. +- **Meglio niente che un numero sbagliato.** Un file illeggibile, un formato cambiato o un account diverso nascondono + il dato (ore, achievement) invece di indovinarlo. +- **Formati di Valve non documentati.** Manifest, VDF, KeyValues binario e `console_log.txt` non hanno contratto. Ogni + lettore ha limiti di dimensione, rifiuta l’input malformato e degrada a un comportamento sicuro. +- **Solo giochi Mac nativi.** Un gioco conta se nella sua cartella c’è esattamente un’app Mac che si dichiara gioco. + Niente Windows, CrossOver o Proton. +- **Nessun gioco nxnative finto.** `CatalogGame` porta il payload reale (`SteamCatalogGame`); i comandi Switch + (build, salvataggi, mod) ricevono solo `PortedGame` e non possono partire da un gioco Steam. +- **Fonte opzionale.** Con la fonte Steam spenta non partono scansioni o watcher del catalogo. La scoperta del primo avvio e l’offerta del benvenuto leggono soltanto per proporre la scelta, senza attivare la fonte; usano la cartella Steam salvata oppure quella standard. Una lettura incompleta nel primo avvio offre Retry, senza indicare che i giochi sono assenti. + +## Stato di validazione + +Lo stato di ogni parte Steam sta nell'elenco unico [validation.md](validation.md). Una parte conta come validata solo dopo la prova del maintainer in Arcane Dev. + +## File di Steam letti + +`<Steam>` è la cartella scelta in Settings → Sources (di solito `~/Library/Application Support/Steam`). +`<lib>` è ogni libreria: `<Steam>` e quelle elencate in `libraryfolders.vdf`. + +| File | Lettore | Cosa ne esce | +|---|---|---| +| `<Steam>/steamapps/libraryfolders.vdf` | `SteamLibrarySource` | percorsi delle librerie | +| `<lib>/steamapps/appmanifest_<AppID>.acf` | `SteamLibrarySource` | AppID, nome, `installdir`, `SizeOnDisk`, `buildid`, `StateFlags` | +| `<lib>/steamapps/common/<installdir>/…` | `NativeMacApplication` | bundle Mac, header Mach-O (architetture), categoria dichiarata; mai eseguito | +| `<Steam>/config/loginusers.vdf` | `SteamPlaytimeReader` | l’account `MostRecent` | +| `<Steam>/userdata/<account>/config/localconfig.vdf` | `SteamPlaytimeReader` | per gioco solo `Playtime` (minuti) e `LastPlayed` | +| `<Steam>/appcache/stats/UserGameStatsSchema_<AppID>.bin` | `SteamAchievementReader` | nomi, descrizioni, nascosti, icone degli achievement | +| `<Steam>/appcache/stats/UserGameStats_<account>_<AppID>.bin` | `SteamAchievementReader` | solo `AchievementTimes` | +| `<Steam>/logs/console_log.txt` | `SteamLaunchQuestionWatch` | solo righe `GameAction [AppID …]`, durante un Play | + +Formati: `SteamKeyValues` (testo, campi duplicati conservati, nessuna direttiva eseguita), `SteamBinaryKeyValues` +(binario). Le letture di file e cartelle hanno limiti di dimensione e di voci (`InstallationFileSnapshot`, +`InstallationDirectorySnapshot`) e si possono annullare. + +I lookup senza distinzione maiuscole/minuscole sono condivisi nell’estensione di `[KeyValuesEntry]` in +`SteamKeyValues.swift`. Le regole restano esplicite e distinte: + +| Lookup | Regola | Uso | +|---|---|---| +| `firstValue` | prima chiave, anche se il suo valore ha un tipo inatteso | blocchi del percorso in `localconfig.vdf` | +| `firstString` / `firstObject` | primo valore del tipo richiesto; copie di altro tipo vengono saltate | schema e statistiche achievement | +| `uniqueValue` / `uniqueString` | duplicati di qualsiasi tipo rifiutati; `uniqueString` rifiuta anche un valore non stringa | manifest, indice librerie e campi delle ore/account | + +I lettori decidono l’esito al proprio confine: i campi scalari non utilizzabili delle ore mantengono i ripieghi +esistenti, mentre manifest e indici non validi producono una scansione parziale con un problema segnalato. +Una prima stringa localizzata vuota negli achievement mantiene il ripiego inglese, senza scegliere un duplicato +successivo. La pulizia del 16 novembre conserva questi risultati: sette prove aggiunte sui lettori reali passano +prima e dopo l’estrazione. La verifica nella Dev resta da confermare; non è stata cambiata la semantica dei file. + +## Rilevamento e catalogo + +1. `CatalogSourcesModel` avvia una scansione: all’avvio se Steam è abilitato, su Refresh, quando si attiva la fonte o + si cambia cartella, e quando cambiano i file di Steam (vedi sotto). Una scansione alla volta, su un worker + annullabile; disattivare, cambiare cartella o chiederne un’altra invalida il risultato precedente. +2. `SteamLibrarySource` produce uno `SteamLibrarySnapshot`: librerie lette, un’osservazione per manifest, problemi + trovati. Lo snapshot è completo solo senza problemi; uno parziale non autorizza mai a dimenticare giochi o librerie + non visti. +3. `SteamCatalogReconciler` fonde lo snapshot nel catalogo: conserva UUID, preferiti, nascosti, scelte personali e le + installazioni già note. Un gioco non visto diventa «non rilevato» solo con uno snapshot completo. +4. `CatalogRepository` è l’unico che scrive il catalogo (`CatalogDocument`, revisioni, lock); `CatalogLibraryProjection` + sceglie cosa mostrare in Spotlight, Collection e ricerca, con gli stessi UUID, filtri e ordine salvato dei giochi + Switch. + +## Stati di un gioco Steam + +Lo stato nasce dall’osservazione (`SteamGameObservation.State`) e arriva alla vista come `CatalogGamePresentation`. + +| Osservazione | Quando | Nel catalogo | Nella libreria | +|---|---|---|---| +| `nativeReady` | un’unica app Mac che si dichiara gioco, nessun problema | `.available`, riconosciuto | tile a colori, Play | +| `downloading` | `StateFlags` senza il bit 4 (FullyInstalled); la cartella non viene letta | `.unavailable` + `isDownloading` | tile in download, pulsante «Downloading» | +| `unavailable` | nessuna app nella cartella (es. disco scollegato) | `.unavailable` | resta nella riga senza Play se era già stato riconosciuto, altrimenti non entra | +| `requiresReview` | più app, problemi di lettura, stesso AppID in due librerie | da controllare | Settings → Sources, «to review» | + +- Un gioco mai riconosciuto non entra nella riga, salvo mentre scarica. Play esiste solo con un’unica installazione + disponibile e niente da controllare. +- `needsReview` è falso per un gioco in download: non compare fra quelli da controllare. +- Un aggiornamento in coda su un gioco installato (`StateFlags` 6 o 1030: bit 4 presente) resta giocabile; Steam + aggiorna al lancio. +- `StateFlags` mancante o illeggibile: si guarda solo la cartella, come prima del supporto ai download. +- Il catalogo resta leggibile da una versione più vecchia di Arcane: `isDownloading` si decodifica con `decodeIfPresent` e la + disponibilità usa casi già esistenti. + +## Osservazione dei file di Steam + +`SteamManifestWatcher` apre un solo `FSEventStream` (eventi per file, latenza 2 s) sulle cartelle `steamapps` di +tutte le librerie disponibili dell’ultima scansione. Ogni scansione ricontrolla anche i percorsi invariati: una +cartella tornata disponibile entra nello stream, anche se le altre erano già osservate. Un avvio dello stream +fallito si può ritentare. I percorsi degli eventi e delle cartelle usano la stessa normalizzazione (anche sotto +`/var` e `/tmp`). Contano solo +`appmanifest_<cifre>.acf` e il `libraryfolders.vdf` della radice; un evento «rileggi le sottocartelle» del sistema +conta solo se riguarda `steamapps` o una cartella sopra. Tutto il resto (`downloading/`, `common/`) viene scartato nel +callback. + +`CatalogSourcesModel.steamFilesChanged` decide quando riscansionare: 3 s dopo l’ultimo evento utile, al massimo ogni +15 s, mai sopra una scansione in corso (quella successiva la segue). Il watcher parte con la fonte e si ferma quando la +fonte si spegne o l’app esce. Nessun polling. + +Il test dell’intervallo minimo confronta gli avvii delle scansioni pubblicati dal modello. + +Effetto: a fine download la tile passa da sola a colori con Play; un gioco installato o rimosso in Steam appare o +sparisce senza Refresh. + +## Libreria: tile, ordine, pagina + +**Tile.** Il riquadro quadrato mostra sempre un’icona vera, mai una copertina ritagliata. Ordine: scelta del +giocatore → icona dell’app installata → «Square» di LaunchBox della voce Mac o Windows, cercata per nome +(`ArtworkStore.automaticSteamIcon`; un’assenza non si ricerca fino al prossimo avvio) → riquadro neutro. Nessuna +etichetta «Steam» sulla tile: la piattaforma è nella pagina. + +**Tile in download** (`PortingTileLook.downloading`). Bianco e nero, la stessa leggera sfocatura del lucchetto Switch, +«Downloading» sotto una freccia sottile in un cerchio (SF Symbol `arrow.down.circle`, peso light). Il simbolo pulsa +piano in luminosità (`TileMotion.downloadMarkOpacity`, 0,4 ↔ 1 in 2,8 s; fermo con Riduci movimento). È un livello +Core Animation (`DownloadMarkLayers`) posato fuori dal `drawingGroup` della tile: dentro, SwiftUI mostrerebbe un +segnaposto giallo. Niente percentuale: Steam scrive il manifest troppo di rado (misurato: fermo 8 minuti durante un +download). + +**Ordine della riga.** Ogni gioco che parte, anche da Steam, diventa il primo gioco della riga. Un gioco visto +scaricare in questa sessione la guida come un gioco in porting: subito dopo la scheda Aggiungi gioco, dopo il porting, +sopra l’ordine salvato con Move, e ci resta fino all’uscita anche a download finito (`SessionDownloads`, +`SpotlightRow.leaders`). Al riavvio torna all’ordine normale. + +**Pagina.** Gli stessi pezzi Selene dei giochi nxnative (`GameLogoArea`, `GamePrimaryActions`, `SeleneStatsRow`, +`SeleneHeroArt`), poi screenshot, About, la card Achievements e il pannello Details condiviso (`DetailsPanel`: Developer, Publisher, +Size on disk, Installed in «Steam · <volume>»; in download solo Developer e Publisher; mai il build ID). La piattaforma è il logo +ufficiale Valve (`SteamPlatformLogo`), con l’attribuzione in Settings › About e in `NOTICE`. + +**More like this** sta sotto About e Details. Usa la fascia e il focus condivisi con Switch, con fino a sei titoli correlati della libreria. I titoli Steam hanno precedenza; quando nessuno corrisponde, la fascia usa le corrispondenze Switch. Lo store legge i tratti per il punteggio dalla cache Steam all'apertura, e le scelte personali prevalgono. Doppio clic, Invio o A selezionano il gioco sulla riga di Spotlight. + +| Situazione | Primo pulsante | Nota sopra i pulsanti | +|---|---|---| +| installato | Play | — | +| in download | «Downloading» con i puntini, come «Porting»; apre `steam://open/downloads` | — | +| in download, senza client Steam | «Downloading», spento | «Steam is not installed on this Mac.» | +| in avvio, in gioco, errore | Cancel, Resume, Try again | il motivo | + +Opzioni (`SteamOptionsView`): Play, Edit details (Change artwork, Change metadata, Store page), Move (solo Spotlight), +Favorite, Hidden, Show in Finder. + +## Play, sessioni e primo piano + +- Play invia `steam://run/<AppID>` (`SteamPlayCoordinator`) solo al client di Valve registrato. La richiesta aspetta che Arcane ordini e invii la finestra d'attesa al server delle finestre, così la copertura precede il passaggio di Space. Se il pannello non si prepara, la richiesta parte entro un secondo. + Il controllo senza finestre attende il completamento del task di ripiego, così il carico del runner non anticipa l'asserzione rispetto all'invio. +- La sessione inizia quando compare il processo dell’app installata (stesso bundle ed eseguibile) e finisce quando + esce. Steam aperto non conta; un gioco avviato da Steam viene seguito allo stesso modo. Attesa massima 300 s; un pid + riusato non è il gioco. Una sessione in corso segue il processo che ha visto partire (pid e bundle) anche se il + catalogo nel frattempo cambia; le risposte tardive si scartano per generazione. Il coordinatore non osserva nulla + prima di Play: `RunningGameMonitor` chiude le sessioni rimaste aperte all’ultimo heartbeat e un gioco ancora in + esecuzione ne apre una nuova. I percorsi di ogni pid si risolvono una volta finché vive. +- La schermata di lancio dei giochi Switch copre l’attesa in una finestra propria. Se ne va quando la finestra del + gioco è visibile, quando Play finisce o fallisce, quando il log dice che Steam aspetta una risposta del giocatore + (`SteamLaunchQuestions`: una riga `LaunchApp waiting for user response…` non seguita entro 1 s), o passata la + pazienza (15 s con Steam aperto, 45 s se Play deve avviarlo). Negli ultimi due casi Steam viene mostrato e la + testata invita a controllarlo. Perché una finestra propria: riprendersi il primo piano mentre Steam si portava davanti + faceva alternare a macOS schermo intero e scrivania per tutta l’attesa. Mentre la schermata è aperta Play non fa + nulla, per nessun gioco. Un clic la chiude (Arcane torna davanti se il gioco non è arrivato, salvo un gioco in + primo piano); se ne va comunque dopo 120 s. Un gioco avviato da Steam non la mostra. +- `ShowInterstitials` è un passaggio di avvio che può restare in attesa oltre un secondo. + La schermata rimane visibile durante quel passaggio, con il normale limite di 15 s o 45 s. +- Il log si legge fuori dal thread principale ogni 0,5 s durante l’attesa, per righe intere; la prima lettura prende + l’ultimo megabyte (conta anche una domanda rimasta aperta da un Play precedente), un file nuovo (Steam riavviato) + azzera tutto. Esempio di domanda: `KickingOtherSession`, il gioco è aperto su un altro dispositivo. Se Valve cambia + il formato, resta l’attesa a tempo. +- **Keep Steam in the background** (`SteamBackgroundLaunch`): Steam avviato da Play parte con `-silent -nofriendsui`. + Durante l'attesa la schermata copre il client, che può finire di aprire le sue finestre. Nasconderlo in risposta + a ogni riapertura fa oscillare macOS fra lo Space fullscreen e la scrivania. + All'uscita di un gioco rimasto in primo piano, Steam torna fuori vista se lo era prima del Play. + [Analisi dello sfarfallio](reviews/2026-11-18-steam-launch-spaces.md) +- All’uscita del gioco Arcane torna davanti se Play era partito da qui, il gioco era in primo piano e nessun + altro gioco della libreria è aperto (`SteamReturnFocus`). Una sessione finita mostra la card di fine sessione dei + giochi Switch, con il totale che include le ore di Steam. + +## Ore di gioco + +Le ore sono quelle di Steam (`Playtime`, tutti i computer) più le sessioni di Arcane successive all’ultimo valore +visto, così nulla si conta due volte anche se Steam aggiorna il file in ritardo (`SteamPlaytimeBaselines`, +`PlaySessionStore`). Un valore più basso o un altro account ripartono da capo; il totale non torna mai indietro per +un minuto. Le letture (`SteamPlaytimeCoordinator`, una alla volta, fuori dal thread principale) avvengono quando +cambiano catalogo o fonti, quando Arcane torna attiva e a fine sessione Steam (subito e dopo un minuto), solo se +la data del file è cambiata; la regola di ogni lettura è il tipo puro `SteamPlaytimeSync`. Un file illeggibile +conserva gli ultimi totali buoni dello stesso account; solo l’assenza di un account li azzera. Le sessioni uscite +dall’elenco recente restano contate (`CarriedPlaytime.afterExternal`) finché Steam non aggiorna il valore; mentre i +totali Steam sono nascosti, `PlaySessionStore.trimReferences` conserva il momento dell’ultimo valore di ogni gioco. + +## Achievement + +Dai file locali di `appcache/stats`, per l’account delle ore. Senza schema, account o file delle statistiche non c’è +la card; un file malformato la nasconde (un file vuoto o troncato non è «nessuno sbloccato»). In rete vanno solo la +rarità pubblica (`GetGlobalAchievementPercentagesForApp`, senza chiave, in cache un giorno, usata anche scaduta +offline; una percentuale non numerica si scarta) e le icone dall’host community-assets del CDN di Steam (il vecchio +percorso `steamcommunity/public/images` risponde 404 per le icone recenti). `SteamAchievementsStore` legge alla +selezione del gioco, all’apertura della schermata e a fine sessione; tiene in memoria gli ultimi 16 giochi. + +Tier come i trofei PS5 (`AchievementTier`): Oro, Argento e Bronzo per rarità (sotto il 10%, sotto il 30%, il resto); +Arcane, al posto del Platino, quando tutto è sbloccato. I cristalli sono arte del maintainer; l’Arcane è un video in +loop (`ArcaneOrbVideo`, 1,5×) che a riposo resta fermo e grigio. Una tier non ottenuta tiene una traccia del suo +colore. Un achievement segreto non ancora sbloccato mostra il nome mascherato e l’icona sfocata sotto un lucchetto. + +In cima alla colonna a destra di About, in un pannello chiaro quasi trasparente (sfocatura leggera dell’immagine) +con il contorno sottile dei pulsanti +(`DetailsAchievementsCard`: il miglior cristallo ottenuto a sinistra, «17/50» o, a gioco completato, il nome +dell’Arcane, le ultime tre icone a ventaglio con hover o focus; selezionato, l’anello Selene sta sul bordo del +pannello); A apre `AchievementsScreen` (filtri con LB/RB, ordine con Y, raro sotto il 10%: regole in +`AchievementSummary`), B torna alla card. In testa alla schermata, a destra, i quattro cristalli con sotto la +percentuale, la barra e il conteggio; a gioco completato il medaglione dell’Arcane. A su una riga apre il dettaglio +come medaglione (`AchievementDetail`): icona grande con il cristallo sull’angolo, nome, descrizione, rarità e data. La card prende il focus fra gli screenshot e il pannello della fonte, accanto a Read more +(Sinistra/Destra). «Your activity» non c’è: ore e ultima partita sono già nella testata. Schema: nomi e descrizioni +nella lingua dell’app, poi inglese. Nessuna chiave Web API di Steam: non serve per questi dati. + +Correzione del 16 novembre, **validata dal maintainer nella Dev**: riaprire rapidamente la schermata durante la sua +transizione poteva riusare la vista della lista con un nuovo `AchievementsScreenModel`, senza richiamare +`onAppear` né cambiare altezza. La selezione avanzava, ma il nuovo modello non aveva geometria e lo scroll +restava a zero. La lista riporta ora le misure con un `task(id:)` legato all’istanza corrente del modello +([contratto SwiftUI](https://developer.apple.com/documentation/swiftui/view/task%28id%3Aname%3Apriority%3Afile%3Aline%3A_%3A%29)), +conservando i controlli per altezza, scala e Riduci movimento. Nessun reset dell’identità della vista o dello stato. +La sonda fuori schermo `run_achievement_scroll.py` riproduce il difetto con 41 righe sintetiche e verifica +riaperture rapide e dopo la transizione, dettagli della prima riga, ridimensionamento e Riduci movimento. + +Armonizzazione successiva del 16 novembre: `SteamCatalogGame.firstAvailableInstallation` è il lookup condiviso +per artwork, pagina, Opzioni, volume e osservazione dei processi. Restituisce la prima installazione con stato +`available` nell’ordine del catalogo; non effettua I/O, non modifica i record e non decide se Play sia consentito. +`CatalogGamePresentation` conserva i controlli di fonte, riconoscimento, review e unicità prima del lancio. +I test di caratterizzazione di artwork e dettagli passano prima e dopo l’estrazione, compreso Play bloccato con +più installazioni e assenza di app/dati installazione negli stati non disponibili. Questa pulizia non aggiunge +funzionalità; la verifica nell’app dopo il refactor resta da confermare. + +## Metadati, arte e personalizzazioni + +- `SteamMetadataService`: dati pubblici dello store per AppID e lingua, separati da installazioni e scelte personali. + Solo HTTPS, niente redirect, al massimo sei trasferimenti insieme (gli altri aspettano in coda e si annullano se + la loro vista sparisce), 20 s per richiesta, ripiego sui dati validi già in cache. +- Sfondo automatico (`SteamBackdropChoice`): immagini in formato schermo (Xbox, GOG, TheGamesDB, poi la fan art + LaunchBox), poi il primo screenshot, per ultimo il banner della libreria Steam ritagliato. La scelta del giocatore + vince sempre; svuotare la cache artwork ricalcola la scelta automatica. +- Le immagini si decodificano fuori dal thread principale (`GameArtLoader.decode`) alle misure dei giochi Switch + (sfondo 2560 px, logo 1600, copertina 900, icona 512): un `NSImage(contentsOf:)` si decodificava al primo disegno e + costava a quel frame 40–60 ms. +- `SteamGameFacts` condivide i dati store per AppID e lingua fra testata, pagina e input; un’assenza si richiede di + nuovo dopo un minuto. +- `SteamPersonalizationStore`: testo e immagini scelte in un solo manifest atomico; un errore conserva le scelte + precedenti. SteamGridDB usa la chiave del giocatore, in `steamgriddb-api-key` con permessi `0600`, mai nei log. + +## Dati su disco di Arcane + +Sotto `Application Support/NXLibrary` (Dev: `NXLibrary-Development`): + +| Percorso | Contenuto | +|---|---| +| catalogo (`CatalogDocument`) | giochi Steam con installazioni, preferiti, nascosti, `isDownloading` | +| `integrations/steam/enrichment/<AppID>/` | metadati store, icone degli achievement, rarità | +| `integrations/steam/artwork-picks/` | immagini scelte dal giocatore | +| `integrations/steam/metadata-picks.json` | testi scelti dal giocatore | +| `integrations/steam/playtime-baselines.json` | ultimo totale di Steam visto per gioco, con l’ora | + +## Scelte del maintainer + +- Lucchetto solo per i fallimenti Switch; un download ha il suo aspetto (15 nov 2026). +- Riquadri: solo icone vere, mai arte ritagliata; ordine scelta → icona dell’app → Square LaunchBox → neutro. +- Download: bianco e nero pieno (non colori sbiaditi), simbolo che pulsa senza alone, cerchio sottile, pulsante + «Downloading» come «Porting», nessuna nota sopra i pulsanti, gioco in testa alla riga fino all’uscita. +- Nessuna etichetta «Steam» sulle tile. +- Pagina: «Your activity» tolta, Achievements in cima alla colonna destra, in un pannello chiaro quasi trasparente + con contorno sottile (dopo aver provato senza riquadro e con un’ombra, 15 nov 2026). +- Logo Steam inalterato al posto del valore sotto PLATFORM, con lo spazio libero ridotto sopra. +- Ore: base di Steam più le sessioni successive. +- Achievement (16 nov 2026): Arcane al posto del Platino, cristalli e video dell’Arcane fatti dal maintainer, video a + 1,5×, medaglione al 100% e nel dettaglio, percentuale e barra larga sotto i cristalli, lucchetto sfocato sui segreti. + +## Limiti noti e punti rimandati + +Decisi consapevolmente: +- Un download in pausa, in coda o abbandonato ha lo stesso aspetto di uno attivo (i flag non li distinguono); i + puntini si muovono comunque. Steam → Download dice quale. +- `StateFlags` senza il bit 4 per altri motivi (file mancanti, disinstallato a metà) mostra «Downloading»: anche lì + Steam deve scaricare. +- Un manifest rimasto a 1026 dopo un download annullato continua a mostrare «Downloading». +- Un’assenza su LaunchBox (anche per rete assente) non si ricerca fino al prossimo avvio. + +Punti minori rimandati dalle revisioni, da decidere prima del rilascio: +- Watcher: se la scrittura della configurazione fallisce, resta fermo fino alla scansione successiva; + il callback usa `unsafeBitCast` a `NSArray`. Il solo collegamento di un volume non avvia una scansione: + serve Refresh o una modifica rilevante ai file Steam già osservati. +- Un Refresh manuale non annulla una riscansione in attesa (una scansione in più). +- `openDownloads` ignora gli errori di apertura. +- Achievement: la freccia Su sparisce col focus sulla card; riepilogo ricalcolato a ogni disegno. (Risolti il 16 nov + 2026: ordine «più rari» stabile a parità di percentuale, rarità `nan` scartata, lampo dell’icona allo scorrimento.) +- Il focus dei link Details non viene limitato quando una disinstallazione Steam ne riduce il numero. +- Un errore Wikidata sospende per 60 s anche le richieste degli altri giochi. +- In Change metadata, il nome canonico arrivato da IGDB riavvia le ricerche LaunchBox/TheGamesDB. +- Ore Steam: dopo «nessun account», un errore senza account può ripubblicare le ore precedenti. +- Un catalogo occupato da un’altra istanza viene presentato come installazione fallita. +- La prima conversione scrive il backup prima del principale: un errore del secondo può offrire «Restore backup» + per il catalogo appena convertito, con dati corretti ma un messaggio poco chiaro. + +Revisione del 16 novembre 2026: corretti il focus della card durante lo scroll, il caricamento degli achievement +richiesto prima della configurazione Steam e la disponibilità di Details sotto i pannelli. I lettori di statistiche, +schema, account e ore usano ora `InstallationFileSnapshot`, con limite durante la lettura, rifiuto dei symlink finali +e verifica della stabilità del file. Test Core e controlli delle vere funzioni dell’app con dati sintetici verificano +le regressioni; nessuna finestra viene aperta. **In attesa di validazione umana nella Dev.** + +## Cambiare l’integrazione + +- Un nuovo file di Steam da leggere: un lettore in `Sources/NXLibraryCore/Services/Steam/` che estrae solo i campi + necessari, con limiti di dimensione, test con fixture sintetiche (`SteamTestSupport`) e una riga nella tabella + [File di Steam letti](#file-di-steam-letti). +- Un nuovo stato o campo nel catalogo: decodifica tollerante (`decodeIfPresent`) e nessun nuovo caso persistito che una + versione più vecchia di Arcane non sappia leggere. +- Una nuova animazione su una tile: Core Animation fuori dal `drawingGroup`, ferma con Riduci movimento. +- Testi: sei lingue in `Localizable.xcstrings`. +- Aggiornare questo documento, il riassunto in `architecture.md` e `file-map.md` nello stesso commit. diff --git a/docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md b/docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md new file mode 100644 index 00000000..6ca3e00b --- /dev/null +++ b/docs/upstream-upgrades/2026-11-18-8a5c5e7e-461a5f9f-review.md @@ -0,0 +1,16 @@ +# 2026-11-18 — nxnative 8a5c5e7e → 461a5f9f + +Arcane 0.2.0 pins `461a5f9f95fc9fc40a690bb2a82eb23f1f03bdca` at the maintainer's direction. The previous pin was `8a5c5e7e1ee606c650fe1aef6959a83009b6a2fc`. The upstream range contains 383 commits across 989 files. The narrower range from `a2c731e32ea5124055553aac62ccb10fab34805d`, the commit already tried through **Newest engine**, contains 30 commits. [Upstream comparison](https://github.com/seedds/nxnative/compare/a2c731e3...461a5f9f) + +| Area | Change and Arcane integration | +|---|---| +| Shaders and pipelines | Updated translation tools, resource ordering and prewarm. nxnative manages shader compatibility through its chain ID and builds pipelines through the existing Mac packer. | +| Host, input and audio | NVN texture layout, audio device routes, video decoder recovery, controller trigger thresholds and Joy-Con haptics are handled by the generated Mac host. The account picker is implemented in that host, and Arcane's local backups preserve the user registry. | +| Profiles | Upstream updates game profiles and reports Mac testing for Fast Fusion, Orbitals and Nintendo Switch 2 Welcome Tour. Arcane uses those profiles through the existing porting workflow. | +| Packing and extraction | nxnative handles truncated PFS0 payloads and unreadable optional base lookups. For multiprogram NUPs, the Mac packer bundles the additional RomFS images and Arcane's existing selection passes the requested program explicitly. | +| CLI and runtime | The flags Arcane sends are available. Bundled Python covers the declared dependencies. Xcode 27.2 / Metal 32023.922 remains the certified toolchain. | +| Scope | Diagnostic environment switches, custom iOS lifecycle interfaces and frontend-owned RomFS placement are outside the Arcane Mac workflow. | + +The last commit reduces unnecessary scans in shader rewriting. Upstream reports identical MSL, reflection data and variants for the 2,976 Fast Fusion shaders built on both revisions. [Upstream PR #2897](https://github.com/seedds/nxnative/pull/2897) + +Arcane's actual compatibility checker passes on a clean temporary checkout of the exact commit, with the bundled Python and installed Metal 32023.922. All 1,806 Swift tests pass, including the runtime dependency and porting-error checks against this exact hash. Arcane Dev carries the new pin and passes strict signature verification. The maintainer chose to adopt the pin without repeating a game rebuild. The individual manual checks are recorded in [validation.md](../validation.md). diff --git a/docs/upstream-upgrades/README.md b/docs/upstream-upgrades/README.md index 1d65abde..02d6eaf2 100644 --- a/docs/upstream-upgrades/README.md +++ b/docs/upstream-upgrades/README.md @@ -81,3 +81,4 @@ This directory records the review that must happen before the pin changes, plus - [2026-11-09 — bd979ced → 79741184](2026-11-09-bd979ced-79741184-review.md) (0.1.4.2: 71 commits; adopted at the maintainer's explicit request after automated review/gate checks; exact-hash real game build/launch remains unconfirmed). - [2026-11-12 — 79741184 → 8a5c5e7e](2026-11-12-79741184-8a5c5e7e-review.md) (0.1.4.3: 152 commits; adopted at the maintainer's explicit request; builds need no .NET; build stop and package probe adapted; real build/launch awaiting the maintainer) +- [2026-11-18 — 8a5c5e7e → 461a5f9f](2026-11-18-8a5c5e7e-461a5f9f-review.md) (0.2.0: 383 commits; adopted at the maintainer's explicit request after the certified gate and automated checks) diff --git a/docs/validation.md b/docs/validation.md new file mode 100644 index 00000000..fbdd2dfd --- /dev/null +++ b/docs/validation.md @@ -0,0 +1,88 @@ +# Arcane — stato della validazione + +Questo è l'unico elenco di ciò che il maintainer ha provato nell'app. Una cosa è **validata** solo quando il maintainer conferma di averla provata nell'app (Arcane Dev per il lavoro non pubblicato). Test automatici, compilazione e revisioni degli agenti la sostengono, ma non la sostituiscono (AGENTS.md). + +Come si aggiorna: +- Quando il maintainer conferma, la riga passa a **validato**, con la data e le sue parole se utili. +- Ogni lavoro nuovo aggiunge la sua riga **in attesa**, con le prove manuali da fare. +- Le guide ([architecture.md](architecture.md), [steam.md](steam.md)) descrivono come funziona; lo stato sta solo qui. + +## Lavoro non pubblicato (ramo `bium/library-manager`) + +| Parte | Stato | Prove ancora da fare | +|---|---|---| +| Pulsante di sostegno volontario | in attesa | In Arcane Dev, Settings → About mostra Support Arcane prima dei crediti, con la tazza Buy Me a Coffee e il testo sul contributo facoltativo. Verificare il focus e l’apertura della pagina pubblica con mouse, tastiera e controller. Dopo la pubblicazione, verificare lo stesso indirizzo dal README e dal pulsante Sponsor di GitHub. | +| Candidata 0.2.0 con pin `461a5f9f` | in attesa | Su copie temporanee, l'updater della 0.1.4.3 legge il requisito del nuovo engine, verifica lo ZIP con questo pin e sostituisce il bundle. La rinomina conserva la firma. Prima del passaggio da 0.1.4.3 spostare eventuali copie sorelle `(new)` e `(old)`, che il vecchio updater può cancellare. Resta la prova interattiva dell'aggiornamento con benvenuto, dati conservati e rinomina su Quit. | +| Nome Arcane in ciò che si vede (finestra, menu, Settings, About, testi nelle sei lingue; copia Dev `Arcane Dev.app`) | in attesa | Aprire `~/Applications/Arcane Dev.app` e ritrovare libreria e impostazioni della vecchia Dev; nessun "NX Library" visibile nelle sei lingue | +| Rinomina del file alla chiusura (`NX Library.app` → `Arcane.app`) | in attesa | Con la prova del ponte A → B: dopo l'aggiornamento, chiudere; il file diventa `Arcane.app` e il Dock lo apre. Restart app non rinomina | +| Impostazioni in General, Library, Porting e System (sezioni nuove Games, Keys, Cloud saves, Storage di Porting, Console; Rumble in New games) | gruppi, navigazione con controller, Search e conservazione dei valori confermati il 17 nov 2026 («ho fatto tutte le verifiche e mi sembra che non ci sia niente di sbagliato»); altre varianti in attesa | Changed mostra "Porting · …"; Reset group in Library → Games non tocca Rumble; i link "Settings → …" degli errori aprono la sezione giusta | +| Primo avvio da ciò che è già sul Mac (pagina `found`) | percorso base con profilo vuoto e riavvio validato il 17 nov 2026 («fatto»); interruttore spento e Setup interrotto confermati il 17 nov; altre varianti in attesa | Conteggi e scelte Steam nei diversi casi; interruttore spento → nessuna fonte Steam; card Porting → Get ready, B torna indietro; con l'interruttore acceso e il percorso Porting fino a Your games o Skip, Steam è acceso; caso vuoto con "No games found"; Open library durante la lettura prosegue e le fonti restano aggiungibili dopo; verifiche complete con frecce, mouse e controller | +| Benvenuto in Arcane, una volta, per chi aggiorna | percorso Add Steam → Open library → riavvio validato nella Dev il 17 nov 2026 («fatto»), con flag del benvenuto e fonte Steam salvati; caso Steam già attivo confermato il 17 nov; altre varianti in attesa | Not now; chiusura con B/Esc e diverse modalità di input; gioco già aperto con Play/Resume; Riduci movimento e precedenza del Setup. Il percorso di installazione tramite updater resta nella prova A → B | +| Rifinitura del primo avvio: scelta Steam persistente, cartella personalizzata, Retry e notifiche contestuali | in attesa | Chiudere e riaprire durante Porting con scelta Steam accesa/spenta; nessuna scelta residua dopo il completamento; radice Steam personalizzata sia in scoperta sia dopo Add; lettura incompleta → Retry o continua; nessuna richiesta notifiche all’avvio, richiesta soltanto al primo porting accettato | +| Blu predefinito e superfici Arcane Crystal / Arcane Flow e particelle morbide | in attesa | Menu rapido → Theme: Arcane è il primo tema e conserva il blu originale anche al primo avvio e nel fallback; Arcane Crystal e Arcane Flow sono scelte aggiuntive; provare entrambi per fili sottilissimi piegati da onde lente lungo le curve (senza bordi rigidi), soli filamenti con luce diffusa appena visibile, senza fasci o piani, colore locale stabile; cambio tema immediato senza spostare la card, riavvio e passaggi fra temi, artwork, wallpaper e Mods; senza riga Particles; frecce/controller restano nella griglia e A continua allo sfondo. Nessuna scelta delle particelle in Look/Search/Changed. Preferenze esistenti, riavvio e Reset conservano gli altri valori; wallpaper/video conservati; Riduci movimento e Background motion fermano colori e moti; card Mods mantiene l’oro; ritorno alla home e primo avvio senza lampi | +| Particellare e ritmo dell'entrata della libreria | aspetto validato il 17 nov 2026 («abbiamo risolto la questione particellare») | Riduci movimento prima e durante il volo; avvio con wallpaper e recupero di un errore di preparazione; con entrata spenta il primo input agisce subito, filtri vuoti e righe corte; avvio su macOS 13. Le prove dei dialoghi nativi hanno una riga separata | +| Entrata senza salto; barra in alto e hint dei pulsanti per ultimi | in attesa | All'avvio la barra in alto (tab e orologio) e gli hint in basso compaiono insieme solo dopo tessere e informazioni, con una breve dissolvenza. Durante fullscreen, attesa e volo: frecce, Invio, clic su una tessera o sugli hint, rotella e controller non fanno nulla e non saltano l'entrata; dopo, tutto risponde. ⌘Q e ⌘, funzionano anche durante l'entrata. Ritorno alla home e Riduci movimento: barra e hint subito visibili. | +| Primi cambi gioco in Spotlight | scorrimento e prova di Play confermati dal maintainer il 18 nov 2026 | Apertura con Giù, dissolvenza sotto gli screenshot, ripristino selezione e fascia Mods su due giochi. Nella prova di rilascio isolata resta la riconciliazione di una mod rimossa. | +| Apertura immediata di Settings con ⌘, | correzione del backdrop persistente in attesa di prova umana | Dopo avvio a freddo premere subito ⌘,; verificare scatto o intervallo nero. Ripetere dopo il fullscreen; i log locali Dev `backdrop-transition` devono mostrare lo stesso renderer fra home e Settings con lo stesso wallpaper; controllare anche wallpaper Settings dedicato, Theme e Mods. Nessuna conferma visiva automatica | +| Immagini Spotlight al ritorno da Settings | in attesa | Ripetere Settings → home con icone nxnative automatiche e personali, Steam e card Mods già caricata; nessun passaggio al ripiego. Cambiare/rimuovere un'immagine personale e tornare ad Automatic; aggiornamento Steam nello stesso percorso; badge e cover Mods dopo rimozioni o cambio abbinamento da Collection. Il controllo automatico costruisce i valori delle viste senza finestre, non sostituisce la prova visiva | +| Cartella Game files ricordata senza scansione dei sorgenti all'avvio | avvio e scelta cartella validati il 17 nov 2026 («funziona») | Annullare il selettore senza perdere la bozza; scegliere singoli file da un'altra cartella senza cambiare Game files; rebuild di un gioco dalle sue sorgenti registrate | +| Priorità dei dialoghi nativi su controller, tastiera e menu | selettore cartella, isolamento del controller e ripresa dopo Esc validati il 17 nov 2026 («si funziona») | Invio nel selettore; ripetere con un alert nativo e con un dialogo interno (per esempio il controllo aggiornamenti), che deve continuare a ricevere i suoi comandi quando è in primo piano | +| NUP: programma selezionato, base DLC e rebuild coerenti | in attesa | Con un engine capace: importare un NUP multiprogramma, scegliere update e ricostruire lo stesso programma; record storico mantiene programma zero; checkout precedente blocca selezioni non supportate senza impedire Play | +| Newest engine: build, Play, controller, salvataggio e riapertura | validato il 17 nov 2026 su `a2c731e32ea5124055553aac62ccb10fab34805d` («funziona benissimo tutto»), con record di build riuscita sullo stesso hash | Conferma del percorso provato, non di tutti i giochi o del giroscopio; il pin ufficiale resta distinto. La scelta esplicita Newest engine registra `toolchainVerified=false` | +| Prewarm: attività del primo avvio, tempi e avvisi | build e primo avvio confermati il 17 nov 2026 su `a2c731e3`; il log registra Prewarm pipelines concluso con successo. Altre varianti in attesa | Attività localizzata senza ETA ricavata dal vecchio porting, tempo trascorso aggiornato, Stop e ripresa; warning non fatale → app pronta e spiegazione del primo avvio più lungo; spazio sul volume di destinazione | +| App con bundle dati firmati annidati | build reale e Play confermati il 17 nov 2026 su `a2c731e3`; altre varianti in attesa | Cambio/ripristino icona e relativo Play; ripetere su un volume esterno. Le fixture automatiche con firme reali provano il ramo di copia forzato, non un filesystem esterno | +| Backup locali multiutente e compatibilità dei vecchi backup | creazione del backup con Back up now e apertura di Backup folder confermate il 17 nov 2026 («ho fatto tutte le verifiche»); casi multiutente e restore in attesa | Con gioco chiuso: backup completo e restore di utenti/registro; vecchio backup conserva gli utenti aggiuntivi; import cartella modifica solo User/Device; testi del limite cloud e conferme; fonti/app reali costruite altrove incluse | +| Catalogo comune nella Dev (`CatalogRepository`, conversione da `library.json`, recupero) | in attesa | Prima apertura della Dev con libreria reale, recupero esplicito | +| Updater: copie accanto all’app e guasti di sostituzione | in attesa | Prova A → B isolata: conservare eventuali copie `(new)` / `(old)`, nome dell’app e riavvio; Cestino non disponibile conserva la vecchia app. Le regressioni automatiche usano bundle sintetici, mai la copia pubblicata | +| Conflitto con modifiche della vecchia libreria | in attesa | Su profilo di prova isolato: errore → Mantieni la libreria di Arcane; giochi e fonti invariati, archivio separato e riavvio. Retry dopo una modifica successiva ai file; nessuna fusione automatica. Non alterare il profilo pubblicato per provocare il caso | +| Fonti e libreria mista (Steam + Switch, Manage sources) | in attesa | Attivazione e disattivazione delle fonti, persistenza delle scelte, conservazione delle voci e librerie su disco esterno | +| Steam: metadati store e arte | in attesa | — | +| Steam: pagina condivisa, Opzioni, personalizzazioni | in attesa | — | +| Steam: Play, schermata di lancio, domande di Steam, Steam in background | Play/Resume validati il 17 nov 2026. Correzione dello sfarfallio accettata il 18 nov («Ok, ci siamo»). Varianti a freddo e domande in attesa. | Ripetere Play dopo Quit di Steam e verificare che la copertura resti visibile fino all'apertura del gioco. Verificare che Steam venga mostrato una volta se serve una risposta. | +| Schermata d'attesa Steam e Switch con angolo libero | in attesa | Con Play di un gioco Steam e di un gioco Switch già installato, verificare che l'angolo inferiore destro resti libero durante l'attesa. | +| Steam: ore di gioco | validato il 17 nov 2026 («le ore di Steam funzionano») | — | +| Steam: giochi in download, osservazione dei manifest, ordine della riga | aspetto validato il 15 nov 2026 | Fine del download e controlli di accettazione | +| Achievement Steam: lista, rarità, tier a cristallo, card Details | presenza e consultazione confermate il 17 nov 2026 («gli achievement ci sono»); dettagli in attesa | Rarità, tier e casi privati/offline o senza statistiche | +| More like this nei giochi Steam | in attesa | Scendere sotto About e Details di un gioco Steam senza corrispondenze sulla sua fonte, ma con titoli Switch affini. Con corrispondenze Steam, verificare la precedenza della stessa fonte. Controllare immagini, focus e selezione con tastiera, controller e doppio clic. | +| Achievement: la lista segue la riga scelta dopo chiusura e riapertura rapide | validato il 16 nov 2026 | — | +| Achievement: video Arcane, medaglioni del dettaglio, lucchetto dei segreti, scorrimenti (`GlideGroup`) | in attesa | — | +| Achievement: intestazione senza 100% (percentuale, barra larga e conteggio sotto i quattro trofei, 44 pt / 4) | in attesa | — | +| Correzioni della revisione di sviluppo (focus della card, nuovi tentativi, piattaforma dei loghi, osservazione delle librerie Steam, lettori protetti) | in attesa | — | +| Revisione 0.2.0: letture dal disco e residui | in attesa | Pagina di un gioco con cheat: "Cheats on" giusto; spegnerli in Game options → Cheats e tornare: l'etichetta sparisce. Game options: cambiare lingua, rumble e scala, chiudere e riaprire: valori salvati. Setup check aperto: cambiare Xcode con `xcode-select` e vedere la scheda aggiornarsi entro qualche secondo. Un gioco senza icona: dopo la build la tessera mostra la sua icona. Benvenuto e Setup all'avvio: chiuderli lascia lo stesso sfondo in movimento. | +| Icona dell'app: cristallo nella sfera di vetro con pennellate blu e prugna | scelta dal maintainer il 18 nov 2026 (immagine fornita da lui); resa in attesa | Dock, Finder e Launchpad a dimensione piccola; App icon in Look: Light, Dark e Mono; README su GitHub | +| Posizione condivisa dei comandi: `SeleneHintsBar` a 32 unità dal fondo | in attesa | La posizione dei Settings (`7adc0ad`) è validata; la via di mezzo a 32 no | +| Pannello Details uguale per ogni fonte | validato il 16 nov 2026 | — | +| Voto della critica con Wikidata | validato il 16 nov 2026, abbinamenti compresi | — | +| IGDB facoltativo: credenziali, voti, minimo di 3 recensioni, media utenti come ripiego | in attesa (il ripiego utenti è approvato come scelta) | Ocarina con voto utenti, un gioco con voto della critica, cambio rapido di gioco, rimozione di IGDB | +| Sezione Online services (IGDB e SteamGridDB) | in attesa | — | +| IGDB in Change metadata | in attesa | Un gioco nxnative e uno Steam, scelta, Q/E e controller, Automatic, testo personale, persistenza, offline/retry, chiusura durante il caricamento | +| LaunchBox e TheGamesDB in Change metadata (ambito approvato il 16 nov 2026) | in attesa | Source picker su Switch 2 e Steam, persistenza, righe uguali/assenti, controller, offline/retry, immagini TheGamesDB per Mac/PC | +| Movimento del selettore dei metadati (`SeleneExpandableText`) | in attesa | Su/giù ripetuti fra descrizioni corte e lunghe, scroll fino alla fine, Q/E, Riduci movimento | +| Lingua e regione (sei lingue) | validato nella Dev, compreso il cambio immediato e la sidebar senza spostare il focus | Le traduzioni sono bozze, non revisioni madrelingua; issue #10 aperta | +| Spazio per gioco in Settings → Storage | validato il 9 nov 2026 | — | +| Profilo Dev isolato | avvio e libreria Dev validati il 9 nov 2026 | Non copre ogni azione su giochi, mod o salvataggi reali | + +## Versioni pubblicate + +| Parte | Stato | Note | +|---|---|---| +| 0.1.2: scansione e cursore (revisione 2), menu nativi, dialogo aggiornamenti, avvio a schermo intero, riga di scansione, gate certificato | validato | — | +| 0.1.4.2: tempo della fase e durate oltre i 60 minuti | in attesa | — | +| 0.1.4.2: Play durante la firma dell'icona (Preparing / Cancel) | in attesa | — | +| 0.1.4.2: icona sul Mac, Only here / Use on the Mac | in attesa | — | +| 0.1.4.2: icone automatiche (`AutomaticIconResolver`) | in attesa | Switch Icon Showdown esclude `/images/` ai crawler (9 nov 2026): la fonte non è operativa e la issue #12 non è risolta | +| Prova di aggiornamento A → B con l'app installata | in attesa | Vedi [development.md](development.md#first-installation-and-a--b-update-test) | + +## Pin dell'engine + +Il dettaglio di ogni revisione è in [upstream-upgrades](upstream-upgrades/README.md). + +| Pin | Versione | Stato | +|---|---|---| +| `461a5f9f` (Metal 32023.922, Xcode 27.2) | 0.2.0, attuale | adottato su richiesta del maintainer. Gate certificato e test automatici passati. Rebuild e avvio sull'esatto hash non eseguiti per la decisione del maintainer. | +| `8a5c5e7e` (Metal 32023.922, Xcode 27.2) | 0.1.4.3 | adottato su richiesta del maintainer; build e avvio sull'esatto hash da confermare | +| `79741184` | 0.1.4.2 | gate e test superati; build e avvio sull'esatto hash non confermati | +| `bd979ced` | 0.1.4.1 | — | +| `e5f03403`, `7fe9fc4d` | precedenti | confermati con un rebuild di Ocarina of Time | +| `04df08d4` | precedente | confermato con un build di Ocarina of Time | +| `4a0551e4` | precedente | gate certificato, build di Wonder con archivio pipeline e avvio confermati | diff --git a/scripts/build_app.sh b/scripts/build_app.sh index 43e60c9d..1430156c 100755 --- a/scripts/build_app.sh +++ b/scripts/build_app.sh @@ -3,18 +3,20 @@ # NX_VERSION sets the app version (default: the version in progress, from the VERSION file); NX_RELEASE=1 # marks a release copy, the only kind that updates itself. scripts/release.sh sets both; a plain build sets # neither, so a development copy carries the version being worked on and says it is a development build. -# A development copy is "NX Library Dev" (default ~/Applications/NXLibrary Dev.app), the maintainer's test copy, -# beside the released "NX Library" that updates itself. Both keep the bundle ID local.nxlibrary, so they share the -# library, keys and settings, and macOS runs only one of them at a time. +# A development copy is "Arcane Dev" (default ~/Applications/Arcane Dev.app), the maintainer's test copy, +# beside the released "Arcane" that updates itself. The development marker selects separate launcher +# data/preferences and a distinct bundle ID, so framework-owned preferences are separate too. set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" if [ "${NX_RELEASE:-0}" = "1" ]; then - NAME="NX Library" - APP="${1:-$HOME/Applications/NX Library.app}" + NAME="Arcane" + BUNDLE_ID="local.nxlibrary" + APP="${1:-$HOME/Applications/Arcane.app}" else - NAME="NX Library Dev" - APP="${1:-$HOME/Applications/NXLibrary Dev.app}" + NAME="Arcane Dev" + BUNDLE_ID="local.nxlibrary.development" + APP="${1:-$HOME/Applications/Arcane Dev.app}" fi CONFIG="${NX_BUILD_CONFIG:-release}" VERSION="${NX_VERSION:-$(tr -d '[:space:]' < "$ROOT/VERSION")}" @@ -22,7 +24,7 @@ if ! [[ "$VERSION" =~ ^[0-9]+(\.[0-9]+){1,3}$ ]]; then echo "error: NX_VERSION must be dotted numbers, got '$VERSION'" >&2 exit 1 fi -RELEASE_KEY="" +RELEASE_KEY=" <key>NXLibraryDevelopmentProfile</key><true/>" [ "${NX_RELEASE:-0}" = "1" ] && RELEASE_KEY=" <key>NXLibraryRelease</key><true/>" if [ -z "${DEVELOPER_DIR:-}" ]; then if [ -d "/Applications/Xcode.app/Contents/Developer" ]; then @@ -57,6 +59,7 @@ done [ -f "$ROOT/NOTICE" ] && cp "$ROOT/NOTICE" "$APP/Contents/Resources/NOTICE" cp "$ROOT/scripts/validate_update.py" "$APP/Contents/Resources/validate_update.py" [ -d "$ROOT/Resources/Selene" ] && cp -R "$ROOT/Resources/Selene" "$APP/Contents/Resources/Selene" +[ -d "$ROOT/Resources/Brands" ] && cp -R "$ROOT/Resources/Brands" "$APP/Contents/Resources/Brands" # Python and build tools from scripts/bundle_runtime.sh. Without it, a developer # build falls back to ~/nxnative/.venv and the PATH tools. if [ -d "$ROOT/work/Runtime" ]; then @@ -78,7 +81,7 @@ cat > "$APP/Contents/Info.plist" <<PLIST <key>CFBundleDisplayName</key><string>$NAME</string> <key>CFBundleExecutable</key><string>NXLibrary</string> <key>CFBundleIconFile</key><string>AppIcon</string> - <key>CFBundleIdentifier</key><string>local.nxlibrary</string> + <key>CFBundleIdentifier</key><string>$BUNDLE_ID</string> <key>CFBundleInfoDictionaryVersion</key><string>6.0</string> <key>CFBundleName</key><string>$NAME</string> <key>CFBundlePackageType</key><string>APPL</string> @@ -96,6 +99,15 @@ $RELEASE_KEY </plist> PLIST +# Exercise the real profile/defaults accessor under this bundle identity, without +# opening the app or importing data. Unit-test hosts have a different identity. +PROFILE_PROBE="$STAGE/ProfileCheck.app" +mkdir -p "$PROFILE_PROBE/Contents/MacOS" +cp "$APP/Contents/Info.plist" "$PROFILE_PROBE/Contents/Info.plist" +swiftc -I "$ROOT/.build/$CONFIG" "$ROOT/scripts/check_app_profile.swift" \ + "$ROOT/.build/$CONFIG/NXLibraryCore.o" -o "$PROFILE_PROBE/Contents/MacOS/NXLibrary" +"$PROFILE_PROBE/Contents/MacOS/NXLibrary" + python3 "$ROOT/scripts/check_localizations.py" --app "$APP" codesign --force --deep --sign - "$APP" codesign --verify --deep --strict "$APP" diff --git a/scripts/build_dmg.sh b/scripts/build_dmg.sh index 70b15c86..28105ac3 100755 --- a/scripts/build_dmg.sh +++ b/scripts/build_dmg.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# scripts/build_dmg.sh [app] — packs a built NX Library into dist/NXLibrary.dmg. +# scripts/build_dmg.sh [app] — packs a built Arcane into dist/NXLibrary.dmg. set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" @@ -12,15 +12,15 @@ codesign --verify --deep --strict "$APP" STAGE="$(mktemp -d "${TMPDIR:-/tmp}/nxlibrary-dmg.XXXXXX")" trap 'rm -rf "$STAGE"' EXIT -cp -R "$APP" "$STAGE/NX Library.app" +cp -R "$APP" "$STAGE/Arcane.app" ln -s /Applications "$STAGE/Applications" mkdir -p "$ROOT/dist" rm -f "$OUT" # macOS 26 deprecates `hdiutil create -volname`; `diskutil image` makes the same compressed image (APFS inside). if diskutil image create from --help >/dev/null 2>&1; then - diskutil image create from --format UDZO --volumeName "NX Library" "$STAGE" "$OUT" >/dev/null + diskutil image create from --format UDZO --volumeName "Arcane" "$STAGE" "$OUT" >/dev/null else - hdiutil create -volname "NX Library" -srcfolder "$STAGE" -ov -format UDZO "$OUT" >/dev/null + hdiutil create -volname "Arcane" -srcfolder "$STAGE" -ov -format UDZO "$OUT" >/dev/null fi echo "Built $OUT ($(du -h "$OUT" | awk '{print $1}'))" diff --git a/scripts/check_app_profile.swift b/scripts/check_app_profile.swift new file mode 100644 index 00000000..643ce46e --- /dev/null +++ b/scripts/check_app_profile.swift @@ -0,0 +1,13 @@ +// Run as a headless executable inside a temporary app with the built app's Info.plist. +// Reading the actual defaults accessor catches startup failures hidden by unmarked unit-test hosts. +// This probe never runs the importer or writes preferences or launcher data. +import Foundation +import NXLibraryCore + +try AppData.validateBuildIdentity(Bundle.main.infoDictionary ?? [:]) +let defaults = AppData.preferences +precondition(defaults === UserDefaults.standard, "The distinct bundle ID must select the app's own preferences") +precondition(Bundle.main.bundleIdentifier == AppData.profile.preferencesDomain, "Preferences must belong to this profile") +precondition(AppData.profile.isDevelopment == (AppData.supportRoot.lastPathComponent == "NXLibrary-Development")) +precondition(AppData.profile.isDevelopment == (AppData.cacheRoot.lastPathComponent == "NXLibrary-Development")) +print("Packaged profile identity, preferences and roots verified without UI or data writes.") diff --git a/scripts/check_metadata_text_layout.swift b/scripts/check_metadata_text_layout.swift new file mode 100644 index 00000000..80710827 --- /dev/null +++ b/scripts/check_metadata_text_layout.swift @@ -0,0 +1,133 @@ +import AppKit +import SwiftUI + +// Offscreen geometry regression check (macOS 13+). No UI automation or snapshots. +// xcrun swiftc Sources/NXLibrary/Views/Components/SeleneExpandableText.swift \ +// scripts/check_metadata_text_layout.swift -o /tmp/nxlibrary-text-layout +// /tmp/nxlibrary-text-layout +@main +struct TextRevealProbe { + @MainActor static func main() { + _ = NSApplication.shared + let paragraph = "A long source description has paragraphs, punctuation, and explicit line breaks. Explore the world, restore what has been lost, and find a path through the mountains.\n\n" + let full = String(repeating: paragraph, count: 30) + let preview = String(full.prefix(240)) + "…" + var checks = 0 + for width: CGFloat in [300, 720, 1040] { + func height(_ expanded: Bool) -> CGFloat { + autoreleasepool { + let view = SeleneExpandableText(text: full, preview: preview, expanded: expanded) + .font(.system(size: 15)).frame(width: width) + return NSHostingView(rootView: view).fittingSize.height + } + } + let compact = height(false), expanded = height(true) + let expectedCompact = NSHostingView(rootView: Text(preview).font(.system(size: 15)).frame(width: width)).fittingSize.height + let expectedFull = NSHostingView(rootView: Text(full).font(.system(size: 15)).frame(width: width)).fittingSize.height + precondition(expanded > compact * 5, "Probe must cover a row taller than the viewport") + precondition(abs(compact - expectedCompact) < 1, "Collapsed row must fit the preview") + precondition(abs(expanded - expectedFull) < 1, "Expanded row must fit all text") + checks += 2 + print("width=\(Int(width)): preview=\(Int(compact))pt; full=\(Int(expanded))pt") + } + // Reusing a host after changing both width and content must not retain + // measurements from the previous source or window size. + let host = NSHostingView(rootView: SeleneExpandableText(text: full, preview: preview, expanded: true) + .font(.system(size: 15)).frame(width: 300)) + let longHeight = host.fittingSize.height + host.rootView = SeleneExpandableText(text: "Short source", preview: "Short source", expanded: true) + .font(.system(size: 15)).frame(width: 720) + precondition(host.fittingSize.height < longHeight / 5, "Changed content must invalidate its measurements") + for reducedMotion in [false, true] { + checkScroll(reducedMotion: reducedMotion) + } + print("PASS: \(checks) text endpoints, content changes, repeated focus and reduced motion. No windows displayed.") + } +} + +private final class ScrollProbeState: ObservableObject { + @Published var focus = 0 + var frames: [Int: CGRect] = [:] +} +private struct RowFrames: PreferenceKey { + static var defaultValue: [Int: CGRect] = [:] + static func reduce(value: inout [Int: CGRect], nextValue: () -> [Int: CGRect]) { + value.merge(nextValue(), uniquingKeysWith: { _, new in new }) + } +} +private struct ScrollProbe: View { + @ObservedObject var state: ScrollProbeState + let reducedMotion: Bool + private let full = String(repeating: "A long description about places and quests in the game.\n\n", count: 35) + private var motion: Animation? { reducedMotion ? nil : .timingCurve(0.22, 1, 0.36, 1, duration: 0.18) } + + var body: some View { + ScrollViewReader { proxy in + ScrollView { + VStack(spacing: 8) { + ForEach(0..<5) { index in + VStack(alignment: .leading) { + Text("SOURCE \(index)") + SeleneExpandableText(text: full, preview: String(full.prefix(240)) + "…", expanded: state.focus == index) + } + .frame(maxWidth: .infinity, alignment: .leading).padding(18).id(index) + .background(GeometryReader { geometry in + Color.clear.preference(key: RowFrames.self, value: [index: geometry.frame(in: .named("list"))]) + }) + } + } + .coordinateSpace(name: "list") + .onPreferenceChange(RowFrames.self) { state.frames = $0 } + .animation(motion, value: state.focus) + } + .onChange(of: state.focus) { index in + withAnimation(motion) { proxy.scrollTo(index, anchor: .top) } + } + } + .font(.system(size: 15)).frame(width: 600, height: 500) + } +} + +@MainActor private func checkScroll(reducedMotion: Bool) { + let state = ScrollProbeState() + let host = NSHostingView(rootView: ScrollProbe(state: state, reducedMotion: reducedMotion)) + host.frame = CGRect(x: 0, y: 0, width: 600, height: 500) + let window = NSWindow(contentRect: host.frame, styleMask: [.borderless], backing: .buffered, defer: false) + window.contentView = host + window.layoutIfNeeded() + precondition(!window.isVisible) + func scrollView(_ root: NSView) -> NSScrollView? { + if let scroll = root as? NSScrollView { return scroll } + return root.subviews.lazy.compactMap(scrollView).first + } + func settle() { + for _ in 0..<25 { + RunLoop.main.run(until: Date().addingTimeInterval(0.02)) + host.layoutSubtreeIfNeeded() + } + } + settle() + guard let scroll = scrollView(host), let document = scroll.documentView else { + preconditionFailure("Scroll container did not initialise") + } + precondition(document.frame.height > 500) + for focus in [1, 2, 1, 3, 0] { + state.focus = focus + settle() + guard let target = state.frames[focus] else { preconditionFailure("Missing row geometry") } + let expected = min(target.minY, max(0, document.frame.height - scroll.contentView.bounds.height)) + precondition(abs(scroll.contentView.bounds.minY - expected) < 2, + "Focus \(focus) must scroll to its final top, not the old expanded row position") + } + // An interrupted expansion must also settle on the last requested row. + for focus in [4, 1, 3, 2] { + state.focus = focus + RunLoop.main.run(until: Date().addingTimeInterval(0.03)) + host.layoutSubtreeIfNeeded() + } + settle() + let expected = min(state.frames[2]!.minY, max(0, document.frame.height - scroll.contentView.bounds.height)) + precondition(abs(scroll.contentView.bounds.minY - expected) < 2, "Rapid focus changes must settle on the last row") + print("scroll destinations and interruptions: PASS (reduced motion=\(reducedMotion))") + window.contentView = nil +} diff --git a/scripts/release.sh b/scripts/release.sh index 678bb686..c2837b34 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -52,6 +52,10 @@ fi # Every release is tested from its own tree. DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}" swift test --package-path "$ROOT" \ || fail "swift test failed" +for check in "$ROOT"/Tests/CatalogAppChecks/run_*.py; do + DEVELOPER_DIR="${DEVELOPER_DIR:-/Applications/Xcode.app/Contents/Developer}" python3 "$check" \ + || fail "application regressions failed: ${check##*/}" +done (cd "$ROOT" && python3 -m unittest discover -s Tests/PublicationChecks >/dev/null 2>&1) \ || fail "the publication checks' tests failed (python3 -m unittest discover -s Tests/PublicationChecks)" [ -d "$ROOT/work/Runtime" ] || fail "no work/Runtime: run scripts/bundle_runtime.sh first (a release carries its Python and tools)" @@ -73,6 +77,9 @@ mkdir -p "$OUT" NX_VERSION="$VERSION" NX_RELEASE=1 bash "$ROOT/scripts/build_app.sh" "$APP" codesign --verify --deep --strict "$APP" +if /usr/libexec/PlistBuddy -c 'Print :NXLibraryDevelopmentProfile' "$APP/Contents/Info.plist" >/dev/null 2>&1; then + fail "a release must not select the development data profile" +fi [ "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$APP/Contents/Info.plist")" = "$VERSION" ] \ || fail "the built app does not carry version $VERSION" [ "$(/usr/libexec/PlistBuddy -c 'Print :NXLibraryRelease' "$APP/Contents/Info.plist")" = "true" ] \ @@ -98,7 +105,7 @@ if [ "$PUBLISH" = "1" ]; then git push origin "$TAG" { cat "$NOTES"; printf '\n\n%s\n' "$REQUIRES"; } > "$OUT/notes.md" gh release create "$TAG" "$ZIP" "$DMG" --repo "$REPOSITORY" \ - --title "NX Library $VERSION" --notes-file "$OUT/notes.md" + --title "Arcane $VERSION" --notes-file "$OUT/notes.md" echo "Published $TAG" else echo "Not published (add --publish --notes <file> to create the GitHub release)."