# SPEC — scorpiox-scorpioplayer-template-parse

SCORPIO PLAYER 2027 engine #1: the dynamic UI template engine. The server sends `SetttingsGroup` JSON
templates (settings, context menus, onboarding, paywall, add-server, and the settings screens of dozens of Store apps).
Legacy shells run two passes over each template: `ApplyPlatform<P>` then `Clean`. After that, a hand-written
renderer draws about 23 widget types.
This engine turns a template into a flat render list for one platform, one language and one
set of runtime flags. It works offline and does no rendering or behaviour of its own.

**Legacy code is the spec, not the source.** The C was written from this document. This document
was written from the code and its history, and every rule below was **measured** against the real
`TableView.cs`. `tests/oracle/` compiles that file unmodified against Newtonsoft.Json 13.0.3, and
`tests/diff.sh` compares the two engines on every template.

| Spec source (read-only) | Revision |
|---|---|
| `bosxixi.toolkit/bosxixi.ScorpioPlayer.Core/Toolkit14/TableView.cs` (623 lines, 39 commits) | `820d6c0` (2024-07-24, "2.0.562") |
| `tplayer/TPlayer/Adapters/Utils.cs:678` `CleanGroupInApp` | `71ca80f` |
| `tplayer/TPlayer/App.xaml.cs:371` `Initializer.Run(HasFeatureFlag)` / `Services/RuntimeService.cs` | `71ca80f` |
| `Platform/IOSLegacy/.../IOSMainPage.xaml.cs:210` `CreateContextMenu`, `Adapters/Class1.cs:1829` `GetGroup` | frozen |
| `bosxixi.ScorpioPlayer.Core/Localization/Tool.cs` (`Get`), `TPlayer/Extensions/Extension.cs:33` (`Translate`) | `820d6c0` |
| `bosxixi.ScorpioPlayer.Core/System.cs:414` `FromJSONObject<T>` (Newtonsoft settings) | `820d6c0` |
| Live bundle `POST gcp.scorpioplayer.com/api/AAA/RuntimeTemplates?zip=true` | 2026-09-25: 301 entries / 126 `.json` / 16 languages × 2,799 keys |
| Shipped bundle `TPlayer/Assets/package/runtimetemplatebundle.txt` | 180 entries / 55 `.json` |

---

## 1. Bundle

R1. A bundle is zlib (RFC 1950, wbits 15) or plain JSON: `{ "<file name>": "<content string>" }`. Entries
include `.json` templates, `.html` pages and base64 `.png`s. **Templates are entries whose name ends in `.json`.**
Not every `.json` is a `SetttingsGroup` (`gptmodels.json`, `deviceicons.json`, `strings.json`...). Those
parse as groups with no `Settings` and render empty, exactly as `FromJSONObject<SetttingsGroup>` does.

R2. Any entry whose value is not a string means this is not a bundle (it is probably a single template):
`sptpl_load_bundle_*` returns 1 and **keeps the previous bundle**. Use `sptpl_add_template`.

R3. zlib is detected by header (`CM=8`, `(CMF·256+FLG) % 31 == 0`), inflated with vendored miniz `tinfl`
(adler-32 checked, output capped at 512 MB).

## 2. Data model (verbatim names — the misspellings are load-bearing)

```
SetttingsGroup   Key DisplayName Type UseGrid  Settings[]  Extension  RuntimeSettings{} RuntimeFlags{}
 └ Setting       Key DisplayName DefaultValue  Items[]     Extension
    └ Item       Key DisplayName Type DefaultValue  Group(SetttingsGroup, recursive)  Values[](Item)
                 AdvanceMenu  PlaceHolder{Key,DisplayName}  SubtitleText{Key,DisplayName}  Extension  RuntimeSettings{}
PlatformExtension  Common iOS tvOS UWP Droid SkiaMacOS (PlatformConfigBase)  FallbackIconUrl FallbackIconBase64 FeatureFlag Clean(bool)
PlatformConfigBase Enabled MinVersion MaxVersion Icon TextColor ... (+ UWP: Plat PlatEdition; iOS/tvOS: ~45 UIKit hints)
AdvanceMenu        Url UseWebView UseLanucher AttachUserInfo AttachItemInfo NativeHandlerCode OrderIndex Group IOSIcon ...
```

`SetttingsGroup` (three t's), `UseLanucher`, `MaxMinVerionCapping` and the `Bookmard`/`Graghic` string keys are
spelled that way in shipped data. Never "fix" them.

Live measurements (126 templates): 3,067 items, max nesting depth 3. Extension slot use: iOS 7,581 · UWP 1,547 ·
tvOS 871 · Droid 147 · SkiaMacOS 61 · FeatureFlag 53.

## 3. Tolerance

The engine never fails a whole template because of one bad node. Every tolerated oddity is a warning
(`sptpl_warning*`):

| Input | Legacy (measured) | Here |
|---|---|---|
| `Type` not a widget: `WhisperUI.Apps.Downloader.Aria2NgPage` (9), `Rating:dioButton` (6), `""` (12) | passes through | passed through verbatim |
| `Settings`/`Items`/`Values`/`Group` absent, `null` or `""` | null | null (absent ≠ empty is kept: see R22) |
| `Items: ["UpdateNotesItems"]` (**live `worldssettings.json`**), `Values: ["WhisperSourceLanguages"]` (**live `transcribeprosettings.json`**). Server-side placeholders that `runtimeconfig/SFSymbolsToSegoeMDL2.cs` failed to substitute | **throws: the whole template fails to load in every legacy client** | element skipped, warning, rest renders. Report finding F1 |
| `null` element in `Settings`/`Items` | NullReferenceException in `Clean` | skipped + warning |
| object/array where a string is expected; non-empty string where an object/list is expected | throws | treated as null + warning |
| invalid JSON, trailing garbage, BOM, NaN/Infinity | throws | invalid → `-1`; the rest tolerated + warning |
| `"$ref"`/`"$id"`/`"$type"` properties | Newtonsoft metadata | ignored (none in either bundle) |
| nesting > 256 levels | Newtonsoft `MaxDepth` 64 throws | truncated at 256 + warning |

## 4. Parsing = Newtonsoft population semantics (measured, 90+ probes in `tests/diff_corpus` + unit tests)

R4. Property names bind **exact first, then ASCII case-insensitive** (`settings`, `ITEMS`, `key` all bind).
There is **no non-ASCII folding**: `ſettings` (U+017F), `Kelvin K` (U+212A), `ıtems` (U+0131) do not bind.

R5. Duplicate properties: a scalar is **last-wins**. An object that already holds an object is **merged**
(Newtonsoft populates the existing instance). A list that already holds a list is **appended to**. An
explicit `null` resets either one, and `""` does the same for object and list properties.

R6. Numbers and booleans read into string properties **keep their JSON text**: `"Key": 1.0` → `"1.0"`,
`1e2` → `"1e2"`, `true` → `"true"`. Big numbers are kept verbatim (`NUMBER_AS_RAW`).
Consequence: `"Enabled": true` is `"true"`, which is not `"True"`, so the item is **hidden** (R16).

R7. `RuntimeSettings`/`RuntimeFlags` are `Dictionary<string,string>`: keys are **ordinal (case-sensitive)**
and values keep their raw JSON text.

R8. JSON5-ish input is accepted like Newtonsoft accepts it: comments, single quotes, unquoted keys and trailing
commas. Empty or whitespace text and the literal `null` give "not a template" (`-1`), as `FromJSONObject`
returns null.

## 5. Visibility — the algorithm (TableView.cs @ 820d6c0)

Legacy mutates the tree. Each pass writes its verdict into **`Extension.iOS.Enabled` on every platform**, and
the final test reads that slot. Here the verdict `V` is computed per item without touching the tree:

R10. **Seed.** `V := item.Extension.iOS.Enabled` from the template itself, which may be null. The iOS slot
does double duty: it is the template's iOS setting *and* the scratch slot. So **an iOS `"False"` hides the item
on UWP, tvOS, Droid and Skia too**, unless something later overwrites `V`. (95 live items set only
`iOS.Enabled="False"`.)

R11. **Platform pass, UWP** (`ApplyPlatformUWP(device, edition, appVersion)`, :14–79). Here `E` is `Extension.UWP`:
1. `E.Enabled == "False"` → `V := "False"` (`EnabledCapping` :154)
2. `E.Enabled == "True"` → `V := "True"`; then `E.Plat != null && E.Plat != device` → `"False"`;
   `E.PlatEdition != null && E.PlatEdition != edition` → `"False"` (:30–48)
3. version capping (R14) with `E.MinVersion`/`E.MaxVersion`
4. `V == "True"` → the Plat/PlatEdition checks again (:52–71). Version capping can revive an item, and this
   re-hides it on the wrong device.

TPlayer calls it as `ApplyPlatformUWP(DeviceFamily, XboxEdition.IsActive ? "XboxEdition" : null,
PackageVersionNumber)` (`Utils.cs:689`).

R12. **Platform pass, tvOS/Droid/SkiaMacOS** (:80, :129, :104): `EnabledCapping` with that platform's `Enabled`,
then version capping with its Min/Max. **There is no `"True"` branch**, so `tvOS.Enabled="True"` never revives
an iOS `"False"`. `Droid.Plat`/`SkiaMacOS.Plat` are **never read**.

R13. **Platform pass, iOS** (:208): version capping only. There is no `EnabledCapping`, because the slot *is*
iOS's own `Enabled`.

R14. **Version capping** (`MaxMinVerionCapping` :166). This only runs if `appVersion` is non-empty **and** parses (R15):
- `MinVersion` non-empty and parseable → `V := app < min ? "False" : "True"`
- **then** `MaxVersion` non-empty and parseable → `V := app > max ? "False" : "True"`

  Consequences, reproduced exactly (see Findings):
  - a satisfied Min/Max **overwrites an explicit `Enabled:"False"`** (50 live UWP items combine version +
    `Enabled:"False"`)
  - when both are present, **Max alone decides** and Min is ignored (live: `settings.json` `FFmpegVersion` ×2,
    `FFMPEG3xAdvanceDecodingSetting`)
  - an unparseable bound is ignored entirely, and so is an unparseable app version

R15. **`System.Version.TryParse`** (.NET 8, 60 probes, table in `tests/test_sptpl.c:test_version`):
- the string has 2–4 components separated by `.`
- each component is `int.TryParse(Integer, Invariant)`: optional `[\t\n\v\f\r ]`, an optional sign, digits,
  optional whitespace, optional trailing `\0`s. The value must be 0 to 2^31−1, and `-0` is valid.
- missing components are **−1**, and comparison is component-wise. So `1.2 < 1.2.0`, `3.3900 > 3.3835`, and
  `" 1.2"`, `"1. 2"`, `"+1.2"`, `"01.02"` all parse.
- `"1"`, `"1.2."`, `"1..2"`, `"1,2"`, NBSP, full-width digits and `2147483648.x` all fail.

R16. **Final verdict** (:282): visible ⇔ `V == "True" || V == null`. **Absent is visible, and anything else hides.**
That covers `"False"`, `"Flase"` (8 live items), `"false"` (2 live), `""`, `"true"` and `"TRUE"`.

R17. **Feature flags** (`Clean` :244–283). These run after the platform pass and **overwrite `V` unconditionally**:
1. if `Extension.FeatureFlag` is non-empty **and** a global predicate is installed
   (`Initializer.CurrentOption.HasFeatureFlag != null`): `V := predicate(ff) ? "True" : "False"`
2. then, if the runtime flag dictionary is non-empty: `V := HasFeatureFlag(ff, runtimeFlags) ? "True" : "False"`

  So a flag **revives a platform-disabled item** (38 live `contextmenu.json` items carry both
  `iOS.Enabled:"False"` and a flag, and the flag is the real switch). Step 2 also **replaces** step 1 whenever
  any runtime flag exists. TPlayer always passes at least `ENDPAD`, so a bare flag like `"SA"` or `"Xbox"` is
  **always hidden in TPlayer**, whatever the global predicate says. Commit history: `26fc044` (2022-10-29)
  introduced `runtimeFlags`. `7a03f8f`/`aebff72`/`52e5dc8`/`f1eb843` (same day) removed the
  `iOS.Enabled == "True"` precondition and made both steps assign True/False rather than only False.

R18. **`HasFeatureFlag(flag, container)`** (:232): the flag is non-empty, `flag.Split(':')` has **exactly 2**
parts, the container is non-empty, and `container.TryGetValue(part0) == part1` is an ordinal, case-sensitive
comparison. `TryGetValue` returns null for a missing or empty key, and null never equals a string. So:
`"SA:true"` ≠ `SA=True`, `":True"` → false, `"a:b:c"` → false, `"K:"` matches only a **present** `K=""`.

R19. **Global predicate.** TPlayer (`App.xaml.cs:373`) answers true for `"Xbox"` on an Xbox, or when
`ConstantValues.FeatureFlags[flag].Value == "true"` (case-insensitive), or when `ffsp.json`'s
`Settings.First(Key==flag).DefaultValue` passes `bool.TryParse`. In C that becomes a set of names
(`sptpl_set_global_flag`), plus `sptpl_use_bundle_feature_flags()` which loads the ffsp part. Clients that do
not install the predicate map to `sptpl_set_global_flags_enabled(0)`; the IOSLegacy `GetGroup` paths are one
example. Default is **on**, matching every legacy app.

R20. **Recursion.** Both passes recurse into `Item.Group` of **every** item, hidden ones included. A hidden
item's group is simply not reachable. `Values` are **not** processed by either pass: shells show `Values` as-is.
The engine returns them unfiltered, with each value's own `enabled` field.

R21. **Empty sections** (:286): with `cleanEmptyContainer` (default true), a Setting whose visible item list is
empty is dropped. That includes `Items` null, `[]` or `""`. Nested groups receive the same flag (`3dfc0df`).

R22. **`Setting` order and item order are preserved.** `AdvanceMenu.OrderIndex` is **not** a sort key in
`TableView.cs`.

## 6. The three mutation defects — decisions

| Legacy behaviour | Decision |
|---|---|
| Both passes **mutate the parsed tree** and return it. Rendering twice gives a different answer (the second `ApplyPlatform` reads the first one's scratch values), so callers `Clone()` with a JSON round-trip | ❌ **not reproduced.** The tree is parsed once and is immutable. `sptpl_render` computes `V` locally and emits a fresh list. Proven by the "render is pure" unit test and by the differential test (which renders every template 16× in one process) |
| `Extension.iOS.Enabled` is the scratch slot for every platform | storage ❌ not reproduced; **outcome ✅ reproduced**, including R10 (an iOS value seeds every platform) |
| Tri-state stringly booleans, null = visible | ✅ reproduced exactly (R16) |

## 7. Translation

R23. `strings.json` in the bundle is `{lang: {key: text}}` (16 languages).

R24. **What is translated is the `Key`, not the `DisplayName`** (`ITranslatable.Translate`, `Extension.cs:33`):
`tl = Key.Translate(); tl != Key ? tl : (DisplayName ?? Key)`. Live data: 3,847 of 9,366 translatables have a
`Key` in `strings.json`. The task draft assumed DisplayName; that was corrected here.

R25. `Key.Translate()` = `Tool.Get(key)`, measured from `Tool.cs`:
`lang` → base of `lang` (`zh-Hant` → `zh`) → **`en-US`** → `en` → the key itself. A present but **empty** text
counts as missing. Platform resource fallbacks (`RL.GetString`, `NSBundle`) are out of scope; they return the
key.

R26. Field `text` = R24 applied to the node. `display` = raw DisplayName. `subtitle`/`placeholder` = R24 applied
to `SubtitleText`/`PlaceHolder`.

## 8. Render list (the contract every shell binds to)

R27. `sptpl_render(template, page)` emits the visible tree **depth-first, in document order**, flattened:
a `section` node for each surviving Setting, followed by its `item` nodes. After each item with a `Group`
come that group's nodes at `depth+1` (`sptpl_set_max_depth` limits this; 0 = page only).
Each node carries `parent` (the index of the owning item, −1 at the page root) and `path`
(`Key/Key/...`, used as the `page_key` to open that sub-page).

R28. `page_key` walks the **raw** tree (the first item with that `Key` and a `Group` at each level), the way
IOSLegacy does it (`Items.FirstOrDefault(c => c.Key == "IMDbId").Group`). If the item is hidden it still
renders, with a warning. The live `contextmenu.json` root item `IMDbId` is `iOS.Enabled:"False"`, and every
client opens it anyway. `sptpl_render_section` keeps only the named Setting(s): this is
`CreateMenusByNode(group, nodeName)`.

R29. `handler`: for `Type` starting with `NativeHandler`, it is `DefaultValue` (`Utils.cs:262`
`ConstantValues.NativeHandlers[selectedItem.DefaultValue]`). Otherwise it is `AdvanceMenu.NativeHandlerCode`.
The engine names handlers and never invokes them; that is row 22, `native-handler-registry`.

R30. `icon` = `Extension.<current platform>.Icon`. Every other hint is available raw through `ext.<P>.<Name>`,
`am.<Name>` and `rs.<Name>`.

## 9. Findings (legacy defects, reproduced unless stated)

| # | Finding | Impact |
|---|---|---|
| F1 | Live `worldssettings.json` and `transcribeprosettings.json` **do not deserialize in any legacy client**: `Items:["UpdateNotesItems"]` and `Values:["WhisperSourceLanguages"]` are unsubstituted placeholders from `runtimeconfig` (`SFSymbolsToSegoeMDL2.cs:153,295`) | those two screens are blank or crash in production. The C engine renders the rest and warns. Fix it in the `runtimeconfig` sync (out of scope, backend) |
| F2 | `MaxMinVerionCapping` Max overrides Min (R14) | an item limited to "2.10.1186–2.10.1211" is visible on **every** version ≤ 2.10.1211, including older than 1186 |
| F3 | Version capping revives explicit `Enabled:"False"` (R14) | 50 live UWP items. `Enabled:"False"` plus a MinVersion means "on from version X", which may be intended |
| F4 | Runtime flags silently replace the global predicate (R17) | a bare `"SA"` flag can never show in TPlayer (it always passes `ENDPAD`) |
| F5 | `"Flase"` ×8, `"false"` ×2, `true` → hidden (R16) | they happen to mean "hidden", so it works by accident |
| F6 | `iOS.Enabled` seeds every platform (R10) | 95 items set only iOS `"False"` and are therefore hidden on UWP/Android too; this looks intended ("False everywhere unless the platform says True") |
| F7 | Plat/PlatEdition are ignored when `UWP.Enabled` is absent and the slot is null (R11) | `{"UWP":{"Plat":"Xbox"}}` shows on Desktop. There are no live occurrences |

## 10. Open questions (not settled by the code — written down, not guessed)

- Q1. Should a native shell honour `Extension.Clean` (IOSLegacy `SettingsUINavigationController.cs:557` runs
  `Clean()` again with **no flags** when opening a PageGroup whose group has `Clean:true`)? Only 2 live uses.
  For now it is exposed as `ext.Clean` and the shell decides.
- Q2. `OrderIndex` on AdvanceMenu (live values 1..n) looks like it was meant to sort menu buttons, but no
  code sorts by it. It is exposed as `am.OrderIndex`.
- Q3. `ENDPAD` (`{device}{!china}{!xbox}`, `Utils.cs:687`) is TPlayer-specific. Shells compute it and pass it
  as a runtime flag. The engine does not know about China or Xbox.
