docs/plans/2026-10-14-themes-and-icons.md

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/docs/plans/2026-10-14-themes-and-icons.md rendered · source · history · blame · raw

1604 lines · 77043 bytes

16 symbols in this file
   1# Built-in Themes and Alternate App Icons Implementation Plan
   2
   3> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
   4
   5**Goal:** Users pick a built-in light theme and dark theme, and an app icon, in Settings on the Mac and on iOS.
   6
   7**Architecture:** Palettes are Swift values in `OrgPresentation`: the two Default palettes are today's `ThemeSpec.default` colors, the 14 others are 12 named colors each, mapped onto every slot by one table. Two new `[theme]` settings choose them; `UserConfig.theme` puts them under `theme-file` and `config.toml`'s colors. Icons are drawn by `scripts/make-icon.swift` from a variant table into committed asset catalogs: iOS alternate app icons with dark and tinted appearances, and on the Mac an `actool`-compiled `AppIcon` plus Dock previews set with `NSApp.applicationIconImage`.
   8
   9**Tech Stack:** Swift 6, SwiftUI, AppKit, UIKit, Swift Testing, `actool`, `xcodebuild`.
  10
  11**Spec:** `docs/plans/2026-10-14-themes-and-icons-design.md`
  12
  13## Global constraints
  14
  15- macOS 26 and iOS 26 only.
  16- No hand-written Swift file over 1,000 lines (`scripts/check-file-sizes.sh`). `Sources/Orgstar/OrgstarApp.swift` is at 956, so new Mac settings UI goes in new files.
  17- No SwiftPM resources in `OrgPresentation`: it is linked into app extensions that don't carry resource bundles.
  18- With `light-theme` and `dark-theme` at their defaults and no other theme settings, every color is what it is today.
  19- The icon choice is per device, in `UserDefaults` (Mac) or `UIApplication.alternateIconName` (iOS), never in `config.toml`.
  20- `ios/Orgstar.xcodeproj/project.pbxproj` has uncommitted changes in the working tree that predate this plan. Before Task 8, ask whether to commit or stash them; do not mix them into this branch's commits.
  21- Commit messages: plain, no trailers.
  22- Every task ends with `swift build` and `swift test` green, and `scripts/check-file-sizes.sh` passing.
  23
  24## Decisions
  25
  26| Question | Decision | Reason |
  27| --- | --- | --- |
  28| Palette storage | Swift values in `Sources/OrgPresentation/Palettes.swift` | No resource bundle in extensions; type-checked |
  29| Ported palettes | 12 named colors through `ThemeSpec.Roles.slots` | A dozen hex values per palette; new slots stay in step |
  30| Default palettes | `ThemeSpec.default.light` / `.dark` as they are | Zero change to the default look |
  31| Where the theme ids are read | `UserDefaults` keys `themeLight` / `themeDark`, passed into `UserConfig.theme` like `themeFile` | `UserConfig.apply` has already copied the file into defaults; iOS without a config folder still works |
  32| Accent fallback | Mac `.controlAccentColor`, iOS `.systemBlue` per appearance | A theme set for one appearance only leaves the other to the system |
  33| Mac bundle icon | `Assets.car` from `actool`, `CFBundleIconName` | The system's dark and tinted icon styles need a catalog |
  34| Mac alternate icon | `NSApp.applicationIconImage` from preview PNGs | The only supported way; Dock only, while running |
  35| Icon PNG check | None | PNG bytes vary with the ImageIO version; the generator is the source |
  36
  37## Review focus
  38
  39- A `config.toml` from 0.5.0 with `theme-file` and `[theme.dark]` colors must look the same after upgrading: the layering order is palettes, then `theme-file`, then `config.toml`. Test in Task 4.
  40- `light-theme = "nord"` (a dark palette in the light key) must report a problem and use Default, not apply Nord to light. Test in Task 4.
  41- An iOS device with no config folder chosen must still apply a picked theme. Test in Task 4 (`ThemeSpec.base`), used in Task 7.
  42- Copy to Config Folder must never overwrite an existing `my-theme.toml`. Test in Task 6.
  43- A Dock icon set at launch must follow a light/dark appearance change while the app runs, and `default` must restore the bundle's icon (`nil`), not a preview PNG. Test in Task 10.
  44
  45---
  46
  47### Task 1: Icon pipeline for the default icon (risk check)
  48
  49Settles both risks in the spec before anything else is drawn: dark and tinted appearances from an `actool`-compiled catalog on macOS 26, and on iOS 26.
  50
  51**Files:**
  52- Modify: `scripts/make-icon.swift` (whole file)
  53- Create: `packaging/AppIcons.xcassets/Contents.json`, `packaging/AppIcons.xcassets/AppIcon.appiconset/*`
  54- Modify: `ios/Orgstar/Assets.xcassets/AppIcon.appiconset/Contents.json`, add `AppIcon-dark.png`, `AppIcon-tinted.png`
  55- Modify: `scripts/build-app.sh:60-62`, its Info.plist heredoc (`CFBundleIconFile` → `CFBundleIconName`)
  56
  57**Interfaces:**
  58- Produces: `swift scripts/make-icon.swift` with no arguments regenerates every committed icon file. A `Variant` struct and `variants` array that Task 8 extends.
  59
  60- [ ] **Step 1: Rewrite `make-icon.swift` around a variant table**
  61
  62```swift
  63// Draws orgstar's app icons from the variant table below into the committed asset catalogs:
  64// ios/Orgstar/Assets.xcassets (iOS app icons and their previews), packaging/AppIcons.xcassets
  65// (the Mac's icon) and packaging/IconPreviews (the Mac's Dock icons).
  66// Usage: swift scripts/make-icon.swift
  67import AppKit
  68
  69struct Variant {
  70    enum Style { case filled, outline, unicorn }
  71    let id: String
  72    /// The gradient, top-left to bottom-right.
  73    let top: NSColor, bottom: NSColor
  74    let glyph: NSColor
  75    let bars: NSColor
  76    var style: Style = .filled
  77}
  78
  79func rgb(_ hex: UInt32) -> NSColor {
  80    NSColor(srgbRed: CGFloat(hex >> 16 & 0xFF) / 255, green: CGFloat(hex >> 8 & 0xFF) / 255, blue: CGFloat(hex & 0xFF) / 255, alpha: 1)
  81}
  82
  83let variants: [Variant] = [
  84    Variant(id: "default", top: NSColor(srgbRed: 0.13, green: 0.20, blue: 0.55, alpha: 1), bottom: NSColor(srgbRed: 0.40, green: 0.22, blue: 0.70, alpha: 1),
  85            glyph: NSColor(srgbRed: 1, green: 0.78, blue: 0.30, alpha: 1), bars: NSColor(white: 1, alpha: 0.92)),
  86]
  87
  88enum Look { case light, dark, tinted }
  89
  90/// The macOS icon grid: an 824-point rounded square in a 1024 canvas; `fullBleed` fills the
  91/// canvas, as iOS wants. Dark and tinted leave the background clear (dark) or black (tinted)
  92/// for the system to fill.
  93func draw(_ v: Variant, _ size: CGFloat, look: Look = .light, fullBleed: Bool = false) -> NSBitmapImageRep {
  94    let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size), pixelsHigh: Int(size), bitsPerSample: 8,
  95                               samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
  96    NSGraphicsContext.saveGraphicsState()
  97    NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
  98    let s = size / 1024
  99    if fullBleed {
 100        let transform = NSAffineTransform()
 101        transform.scale(by: 1024 / 824)
 102        transform.translateX(by: -100 * s, yBy: -100 * s)
 103        transform.concat()
 104    }
 105    let square = NSRect(x: 100 * s, y: 100 * s, width: 824 * s, height: 824 * s)
 106    let shape = fullBleed ? NSBezierPath(rect: square) : NSBezierPath(roundedRect: square, xRadius: 185 * s, yRadius: 185 * s)
 107    switch look {
 108    case .light: NSGradient(colors: [v.top, v.bottom])!.draw(in: shape, angle: -60)
 109    case .dark: break
 110    case .tinted: NSColor.black.setFill(); shape.fill()
 111    }
 112    let glyph = look == .tinted ? NSColor(white: 0.95, alpha: 1) : v.glyph
 113    let bars = look == .tinted ? NSColor(white: 0.75, alpha: 1) : v.bars
 114    switch v.style {
 115    case .filled: drawOutline(s, glyph: glyph, bars: bars, filled: true)
 116    case .outline: drawOutline(s, glyph: glyph, bars: bars, filled: false)
 117    case .unicorn: drawUnicorn(s, glyph: glyph, head: bars)
 118    }
 119    NSGraphicsContext.restoreGraphicsState()
 120    return rep
 121}
 122
 123/// The heading star over three outline lines, indented like a heading's children.
 124func drawOutline(_ s: CGFloat, glyph: NSColor, bars: NSColor, filled: Bool) {
 125    let star = NSAttributedString(string: "✱", attributes: [
 126        .font: NSFont.systemFont(ofSize: 330 * s, weight: filled ? .heavy : .light), .foregroundColor: glyph,
 127    ])
 128    star.draw(at: NSPoint(x: 190 * s, y: 520 * s))
 129    for (i, (x, width)) in [(470.0, 330.0), (300.0, 500.0), (380.0, 420.0)].enumerated() {
 130        let y = (650 - Double(i) * 150) * s
 131        let line = NSRect(x: x * s, y: y, width: width * s, height: (i == 0 ? 70 : 56) * s)
 132        let path = NSBezierPath(roundedRect: line, xRadius: 28 * s, yRadius: 28 * s)
 133        if filled {
 134            bars.setFill(); path.fill()
 135        } else {
 136            bars.setStroke(); path.lineWidth = 10 * s; path.stroke()
 137        }
 138    }
 139}
 140
 141/// Task 8 draws the unicorn.
 142func drawUnicorn(_ s: CGFloat, glyph: NSColor, head: NSColor) {
 143    drawOutline(s, glyph: glyph, bars: head, filled: true)
 144}
 145
 146func png(_ rep: NSBitmapImageRep) -> Data { rep.representation(using: .png, properties: [:])! }
 147
 148/// Without an alpha channel, as the App Store requires for the light icon.
 149func opaque(_ rep: NSBitmapImageRep) -> NSBitmapImageRep {
 150    let size = rep.pixelsWide
 151    let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: 0,
 152                            space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
 153    context.draw(rep.cgImage!, in: CGRect(x: 0, y: 0, width: size, height: size))
 154    return NSBitmapImageRep(cgImage: context.makeImage()!)
 155}
 156
 157func write(_ data: Data, _ path: String) throws {
 158    let url = URL(fileURLWithPath: path)
 159    try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
 160    try data.write(to: url)
 161}
 162
 163func json(_ object: Any, _ path: String) throws {
 164    try write(JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]), path)
 165}
 166
 167let info = ["author": "xcode", "version": 1] as [String: Any]
 168let appearances: [(Look, String, [[String: String]])] = [
 169    (.light, "", []),
 170    (.dark, "-dark", [["appearance": "luminosity", "value": "dark"]]),
 171    (.tinted, "-tinted", [["appearance": "luminosity", "value": "tinted"]]),
 172]
 173
 174for v in variants {
 175    // iOS: one set per icon, named AppIcon for the default and AppIcon-<Id> for the others.
 176    let setName = v.id == "default" ? "AppIcon" : "AppIcon-" + v.id.split(separator: "-").map(\.capitalized).joined()
 177    let set = "ios/Orgstar/Assets.xcassets/\(setName).appiconset"
 178    var images: [[String: Any]] = []
 179    for (look, suffix, appearance) in appearances {
 180        let rep = draw(v, 1024, look: look, fullBleed: true)
 181        try write(png(look == .light ? opaque(rep) : rep), "\(set)/AppIcon\(suffix).png")
 182        var image: [String: Any] = ["filename": "AppIcon\(suffix).png", "idiom": "universal", "platform": "ios", "size": "1024x1024"]
 183        if !appearance.isEmpty { image["appearances"] = appearance }
 184        images.append(image)
 185    }
 186    try json(["images": images, "info": info], "\(set)/Contents.json")
 187
 188    // Previews for the iOS picker, light and dark.
 189    let preview = "ios/Orgstar/Assets.xcassets/IconPreview-\(v.id).imageset"
 190    try write(png(draw(v, 256, fullBleed: true)), "\(preview)/light.png")
 191    try write(png(draw(v, 256, look: .dark, fullBleed: true)), "\(preview)/dark.png")
 192    try json(["images": [
 193        ["filename": "light.png", "idiom": "universal"],
 194        ["filename": "dark.png", "idiom": "universal", "appearances": [["appearance": "luminosity", "value": "dark"]]],
 195    ], "info": info], "\(preview)/Contents.json")
 196
 197    // The Mac's Dock icons and picker previews.
 198    try write(png(draw(v, 512)), "packaging/IconPreviews/\(v.id)-light.png")
 199    try write(png(draw(v, 512, look: .dark)), "packaging/IconPreviews/\(v.id)-dark.png")
 200}
 201
 202// The Mac's bundle icon: the default variant at the Mac's sizes, in each appearance.
 203let mac = "packaging/AppIcons.xcassets/AppIcon.appiconset"
 204var macImages: [[String: Any]] = []
 205for base in [16, 32, 128, 256, 512] {
 206    for scale in [1, 2] {
 207        for (look, suffix, appearance) in appearances {
 208            let name = "icon_\(base)x\(base)\(scale == 2 ? "@2x" : "")\(suffix).png"
 209            try write(png(draw(variants[0], CGFloat(base * scale), look: look)), "\(mac)/\(name)")
 210            var image: [String: Any] = ["filename": name, "idiom": "mac", "scale": "\(scale)x", "size": "\(base)x\(base)"]
 211            if !appearance.isEmpty { image["appearances"] = appearance }
 212            macImages.append(image)
 213        }
 214    }
 215}
 216try json(["images": macImages, "info": info], "\(mac)/Contents.json")
 217try json(["info": info], "packaging/AppIcons.xcassets/Contents.json")
 218```
 219
 220- [ ] **Step 2: Generate and check the default icon is unchanged**
 221
 222Run: `swift scripts/make-icon.swift && git diff --stat ios/Orgstar/Assets.xcassets/AppIcon.appiconset/AppIcon.png`
 223Then open the old and new `AppIcon.png` side by side (`git show HEAD:ios/Orgstar/Assets.xcassets/AppIcon.appiconset/AppIcon.png > /tmp/old.png; open /tmp/old.png ios/Orgstar/Assets.xcassets/AppIcon.appiconset/AppIcon.png`).
 224Expected: they look the same. The bytes may differ.
 225
 226- [ ] **Step 3: Compile the Mac catalog in `build-app.sh`**
 227
 228Replace lines 60–62 (`iconset=…` through `rm -rf "$(dirname "$iconset")"`) with:
 229
 230```sh
 231# The icon, in the system's default, dark and tinted styles, and the Dock icons Settings offers.
 232work="$(mktemp -d)"
 233xcrun actool packaging/AppIcons.xcassets --compile "$app/Contents/Resources" --platform macosx \
 234    --minimum-deployment-target 26.0 --app-icon AppIcon --output-partial-info-plist "$work/icon.plist" > /dev/null
 235rm -rf "$work"
 236mkdir -p "$app/Contents/Resources/IconPreviews"
 237cp packaging/IconPreviews/*.png "$app/Contents/Resources/IconPreviews/"
 238```
 239
 240In the Info.plist heredoc, replace
 241
 242```
 243    <key>CFBundleIconFile</key>
 244    <string>AppIcon</string>
 245```
 246
 247with
 248
 249```
 250    <key>CFBundleIconName</key>
 251    <string>AppIcon</string>
 252```
 253
 254- [ ] **Step 4: Check on macOS 26**
 255
 256Run: `scripts/build-app.sh && ls .build/*.app/Contents/Resources/Assets.car && open -R .build/*.app`
 257In System Settings ▸ Appearance ▸ Icon & widget style, switch between Default, Dark and Tinted, and look at the app in Finder and in the Dock after launching it.
 258Expected: Dark shows the star and bars on the system's dark background; Tinted shows them tinted.
 259If Dark and Tinted show the same image as Default, delete the `-dark`/`-tinted` entries from the Mac set in `make-icon.swift` (keep only `look == .light` in the Mac loop), regenerate, and record under Decisions: "Mac bundle icon: default variant only; macOS derives dark and tinted."
 260
 261- [ ] **Step 5: Check on iOS 26**
 262
 263Build and run the `Orgstar` scheme from `ios/Orgstar.xcodeproj` on a device or the iOS 26 Simulator. On the home screen, long-press ▸ Edit ▸ Customize, and switch between Dark and Tinted.
 264Expected: the dark and tinted images show. If not, record that in Decisions and stop before Task 8; ask how to proceed.
 265
 266- [ ] **Step 6: Commit**
 267
 268```bash
 269git add scripts/make-icon.swift scripts/build-app.sh packaging/AppIcons.xcassets packaging/IconPreviews ios/Orgstar/Assets.xcassets
 270git commit -m "Icons from a variant table, with dark and tinted styles; Mac icon from an asset catalog"
 271```
 272
 273---
 274
 275### Task 2: Palettes, the Default palettes and the accent slot
 276
 277**Files:**
 278- Create: `Sources/OrgPresentation/Palettes.swift`
 279- Modify: `Sources/OrgPresentation/ThemeSpec.swift` (`slots`, `systemDefaults`, `typeKeys`)
 280- Modify: `Sources/Orgstar/ThemeColors.swift` (`systemColor`)
 281- Test: `Tests/OrgPresentationTests/PaletteTests.swift`
 282
 283**Interfaces:**
 284- Produces:
 285  - `public struct Palette: Sendable, Equatable { public enum Appearance: String, Sendable { case light, dark }; public let id: String; public let name: String; public let appearance: Appearance; public let colors: [String: RGBA] }`
 286  - `extension ThemeSpec { public static func palettes(_ appearance: Palette.Appearance) -> [Palette]; public static func palette(_ id: String, _ appearance: Palette.Appearance) -> Palette?; public static func defaultPaletteID(_ appearance: Palette.Appearance) -> String }`
 287  - Theme slot `accent`, in `systemDefaults`.
 288
 289- [ ] **Step 1: Write the failing tests**
 290
 291```swift
 292import OrgPresentation
 293import Testing
 294
 295struct PaletteTests {
 296    @Test func defaultPalettesAreTheDefaultTheme() throws {
 297        let light = try #require(ThemeSpec.palette("default-light", .light))
 298        let dark = try #require(ThemeSpec.palette("default-dark", .dark))
 299        #expect(light.colors == ThemeSpec.default.light && dark.colors == ThemeSpec.default.dark)
 300        #expect(light.name == "Default" && ThemeSpec.palettes(.light).first == light && ThemeSpec.palettes(.dark).first == dark)
 301        #expect(ThemeSpec.defaultPaletteID(.light) == "default-light" && ThemeSpec.defaultPaletteID(.dark) == "default-dark")
 302    }
 303
 304    @Test func aPaletteIsFoundOnlyInItsAppearance() {
 305        #expect(ThemeSpec.palette("default-light", .dark) == nil)
 306        #expect(ThemeSpec.palette("nope", .light) == nil)
 307    }
 308
 309    @Test func accentIsASlotTheDefaultLeavesToTheSystem() {
 310        #expect(ThemeSpec.slots.contains { $0.key == "accent" })
 311        #expect(ThemeSpec.systemDefaults.contains("accent"))
 312        #expect(ThemeSpec.default.light["accent"] == nil && ThemeSpec.default.dark["accent"] == nil)
 313    }
 314
 315    @Test func everyPaletteHasExactlyTheSlotKeys() {
 316        let all = Set(ThemeSpec.slots.map(\.key))
 317        for palette in ThemeSpec.palettes(.light) + ThemeSpec.palettes(.dark) {
 318            let expected = palette.id.hasPrefix("default-") ? all.subtracting(ThemeSpec.systemDefaults) : all
 319            #expect(Set(palette.colors.keys) == expected, "\(palette.id): \(expected.symmetricDifference(palette.colors.keys))")
 320        }
 321    }
 322}
 323```
 324
 325- [ ] **Step 2: Run them to see them fail**
 326
 327Run: `swift test --filter PaletteTests`
 328Expected: compile error, `Palette` not found.
 329
 330- [ ] **Step 3: Add the slot**
 331
 332In `ThemeSpec.slots`, after `("selection", "selected text's background"),` add:
 333
 334```swift
 335        ("accent", "buttons, toggles and selection in lists; unset: the system's"),
 336```
 337
 338In `systemDefaults` add `"accent"`. In `typeKeys` add `"light-theme", "dark-theme"` (Task 4 uses them; adding them now keeps `[theme] light-theme = …` from being read as a color).
 339
 340In `Sources/Orgstar/ThemeColors.swift` `systemColor`, add a case before `default`:
 341
 342```swift
 343        case "accent": .controlAccentColor
 344```
 345
 346- [ ] **Step 4: Write `Palettes.swift`**
 347
 348```swift
 349/// A built-in theme for one appearance, chosen with `light-theme` or `dark-theme`.
 350public struct Palette: Sendable, Equatable {
 351    public enum Appearance: String, Sendable { case light, dark }
 352
 353    public let id: String
 354    public let name: String
 355    public let appearance: Appearance
 356    public let colors: [String: RGBA]
 357
 358    public init(id: String, name: String, appearance: Appearance, colors: [String: RGBA]) {
 359        self.id = id
 360        self.name = name
 361        self.appearance = appearance
 362        self.colors = colors
 363    }
 364}
 365
 366extension ThemeSpec {
 367    /// The built-in palettes of `appearance`, Default first.
 368    public static func palettes(_ appearance: Palette.Appearance) -> [Palette] {
 369        appearance == .light ? lightPalettes : darkPalettes
 370    }
 371
 372    public static func palette(_ id: String, _ appearance: Palette.Appearance) -> Palette? {
 373        palettes(appearance).first { $0.id == id }
 374    }
 375
 376    public static func defaultPaletteID(_ appearance: Palette.Appearance) -> String {
 377        "default-" + appearance.rawValue
 378    }
 379
 380    static let lightPalettes: [Palette] = [
 381        Palette(id: "default-light", name: "Default", appearance: .light, colors: ThemeSpec.default.light),
 382    ]
 383
 384    static let darkPalettes: [Palette] = [
 385        Palette(id: "default-dark", name: "Default", appearance: .dark, colors: ThemeSpec.default.dark),
 386    ]
 387}
 388```
 389
 390- [ ] **Step 5: Run the tests**
 391
 392Run: `swift test --filter PaletteTests && swift test`
 393Expected: PASS. Existing tests that print `default-theme.toml` gain a commented `# accent = "#rrggbb"` line; if a test compares that text exactly, update its expected text to include the line.
 394
 395- [ ] **Step 6: Commit**
 396
 397```bash
 398git add Sources/OrgPresentation Sources/Orgstar/ThemeColors.swift Tests/OrgPresentationTests/PaletteTests.swift
 399git commit -m "Palettes, with the default theme as Default; accent theme color"
 400```
 401
 402---
 403
 404### Task 3: The ported palettes
 405
 406**Files:**
 407- Modify: `Sources/OrgPresentation/Palettes.swift`
 408- Modify: `THIRD_PARTY.org`
 409- Test: `Tests/OrgPresentationTests/PaletteTests.swift`
 410
 411**Interfaces:**
 412- Consumes: `Palette`, `ThemeSpec.palettes` (Task 2).
 413- Produces: `public struct ThemeSpec.Roles` with `public func colors(dark: Bool) -> [String: RGBA]`; 14 more palettes with the ids in the spec.
 414
 415- [ ] **Step 1: Write the failing tests**
 416
 417Add to `PaletteTests`:
 418
 419```swift
 420    @Test func theCatalogIsInOrder() {
 421        #expect(ThemeSpec.palettes(.light).map(\.id) == ["default-light", "solarized-light", "gruvbox-light", "modus-operandi", "catppuccin-latte", "tomorrow", "paper"])
 422        #expect(ThemeSpec.palettes(.dark).map(\.id) == ["default-dark", "solarized-dark", "gruvbox-dark", "modus-vivendi", "catppuccin-mocha", "nord", "dracula", "tokyo-night", "doom-one"])
 423    }
 424
 425    /// WCAG 2 contrast ratio.
 426    static func contrast(_ a: RGBA, _ b: RGBA) -> Double {
 427        func luminance(_ c: RGBA) -> Double {
 428            func channel(_ v: Double) -> Double { v <= 0.03928 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4) }
 429            return 0.2126 * channel(c.red) + 0.7152 * channel(c.green) + 0.0722 * channel(c.blue)
 430        }
 431        let (x, y) = (luminance(a), luminance(b))
 432        return (max(x, y) + 0.05) / (min(x, y) + 0.05)
 433    }
 434
 435    @Test func textReadsOnTheBackground() throws {
 436        let body = ["foreground", "table"]
 437        let marks = ["heading-1", "heading-2", "heading-3", "heading-4", "todo", "todo-next", "todo-waiting", "done", "link", "timestamp", "code",
 438                     "syntax-keyword", "syntax-string", "syntax-function", "syntax-type", "syntax-number", "syntax-property", "syntax-label"]
 439        for palette in ThemeSpec.palettes(.light) + ThemeSpec.palettes(.dark) {
 440            let background = try #require(palette.colors["background"])
 441            for key in body {
 442                let ratio = Self.contrast(try #require(palette.colors[key]), background)
 443                #expect(ratio >= 4.5, "\(palette.id) \(key): \(ratio)")
 444            }
 445            for key in marks {
 446                let ratio = Self.contrast(try #require(palette.colors[key]), background)
 447                #expect(ratio >= 3, "\(palette.id) \(key): \(ratio)")
 448            }
 449        }
 450    }
 451```
 452
 453Add `import Foundation` at the top of the file for `pow`.
 454
 455- [ ] **Step 2: Run them to see them fail**
 456
 457Run: `swift test --filter PaletteTests`
 458Expected: `theCatalogIsInOrder` fails. `textReadsOnTheBackground` passes for Default; if it fails for Default, stop and report the key and ratio: the threshold or the default needs a decision.
 459
 460- [ ] **Step 3: Add `Roles` and the palettes**
 461
 462Append to `Palettes.swift`:
 463
 464```swift
 465extension ThemeSpec {
 466    /// A palette's named colors, from which every slot is set.
 467    public struct Roles: Sendable {
 468        public var bg, alt, fg, dim, red, orange, yellow, green, cyan, blue, purple, accent: String
 469
 470        /// Slot → role. `selection` and `inline-background` are translucent roles.
 471        static let slots: [String: KeyPath<Roles, String>] = [
 472            "background": \.bg, "foreground": \.fg, "cursor": \.accent, "accent": \.accent,
 473            "heading-1": \.blue, "heading-2": \.purple, "heading-3": \.green, "heading-4": \.orange,
 474            "heading-5": \.blue, "heading-6": \.purple, "heading-7": \.green, "heading-8": \.orange,
 475            "todo": \.red, "todo-next": \.blue, "todo-waiting": \.yellow, "done": \.green, "todo-cancelled": \.dim,
 476            "priority": \.orange, "priority-a": \.red, "priority-b": \.orange, "priority-c": \.dim,
 477            "tags": \.dim, "link": \.blue, "timestamp": \.purple, "code": \.orange, "verbatim": \.cyan,
 478            "markup": \.dim, "comment": \.dim, "keyword": \.dim, "metadata": \.dim, "special": \.cyan,
 479            "block-background": \.alt, "block-delimiter": \.dim, "table": \.fg,
 480            "line-number": \.dim, "line-number-current": \.fg,
 481            "syntax-keyword": \.purple, "syntax-string": \.green, "syntax-comment": \.dim, "syntax-function": \.blue,
 482            "syntax-type": \.yellow, "syntax-number": \.orange, "syntax-property": \.cyan, "syntax-label": \.purple,
 483            "sidebar-background": \.alt, "sidebar-foreground": \.fg, "sidebar-header": \.dim,
 484            "modeline-background": \.alt, "modeline-foreground": \.fg, "modeline-highlight": \.accent,
 485            "state-normal": \.blue, "state-insert": \.green, "state-visual": \.orange,
 486            "agenda-background": \.bg, "agenda-date": \.fg, "agenda-today": \.accent, "agenda-time": \.dim, "agenda-category": \.dim,
 487            "agenda-overdue": \.red, "agenda-due-soon": \.orange, "agenda-event": \.purple,
 488            "habit-clear": \.blue, "habit-ready": \.green, "habit-alert": \.yellow, "habit-overdue": \.red,
 489        ]
 490
 491        /// Alphas are whole bytes (`#…33`, `#…59`), so a palette written out as a theme file
 492        /// reads back equal.
 493        public func colors(dark: Bool) -> [String: RGBA] {
 494            var out = Self.slots.compactMapValues { RGBA(hex: self[keyPath: $0]) }
 495            if var selection = RGBA(hex: accent) {
 496                selection.alpha = (dark ? 0x59 : 0x33) / 255
 497                out["selection"] = selection
 498            }
 499            if var inline = RGBA(hex: dim) {
 500                inline.alpha = 0x33 / 255
 501                out["inline-background"] = inline
 502            }
 503            return out
 504        }
 505    }
 506
 507    private static func ported(_ id: String, _ name: String, _ appearance: Palette.Appearance, _ roles: Roles) -> Palette {
 508        Palette(id: id, name: name, appearance: appearance, colors: roles.colors(dark: appearance == .dark))
 509    }
 510}
 511```
 512
 513Replace `lightPalettes` and `darkPalettes` with:
 514
 515```swift
 516    // Upstream palettes; see THIRD_PARTY.org. Colors darkened from upstream to read at 3:1 on
 517    // the background: Solarized Light yellow, green and cyan; Catppuccin Latte orange, yellow
 518    // and green; Tomorrow orange and yellow.
 519    static let lightPalettes: [Palette] = [
 520        Palette(id: "default-light", name: "Default", appearance: .light, colors: ThemeSpec.default.light),
 521        ported("solarized-light", "Solarized Light", .light, Roles(
 522            bg: "#fdf6e3", alt: "#eee8d5", fg: "#586e75", dim: "#93a1a1", red: "#dc322f", orange: "#cb4b16", yellow: "#a57c00",
 523            green: "#738a05", cyan: "#258f86", blue: "#268bd2", purple: "#6c71c4", accent: "#268bd2")),
 524        ported("gruvbox-light", "Gruvbox Light", .light, Roles(
 525            bg: "#fbf1c7", alt: "#ebdbb2", fg: "#3c3836", dim: "#928374", red: "#9d0006", orange: "#af3a03", yellow: "#b57614",
 526            green: "#79740e", cyan: "#427b58", blue: "#076678", purple: "#8f3f71", accent: "#076678")),
 527        ported("modus-operandi", "Modus Operandi", .light, Roles(
 528            bg: "#ffffff", alt: "#f2f2f2", fg: "#000000", dim: "#595959", red: "#a60000", orange: "#972500", yellow: "#6f5500",
 529            green: "#006800", cyan: "#005e8b", blue: "#0031a9", purple: "#721045", accent: "#0031a9")),
 530        ported("catppuccin-latte", "Catppuccin Latte", .light, Roles(
 531            bg: "#eff1f5", alt: "#e6e9ef", fg: "#4c4f69", dim: "#8c8fa1", red: "#d20f39", orange: "#d0590a", yellow: "#b06f13",
 532            green: "#388c24", cyan: "#179299", blue: "#1e66f5", purple: "#8839ef", accent: "#8839ef")),
 533        ported("tomorrow", "Tomorrow", .light, Roles(
 534            bg: "#ffffff", alt: "#efefef", fg: "#4d4d4c", dim: "#8e908c", red: "#c82829", orange: "#c76b17", yellow: "#a87e00",
 535            green: "#718c00", cyan: "#3e999f", blue: "#4271ae", purple: "#8959a8", accent: "#4271ae")),
 536        // orgstar's own: warm paper and ink, for long reading.
 537        ported("paper", "Paper", .light, Roles(
 538            bg: "#f8f3e6", alt: "#efe8d6", fg: "#3b3428", dim: "#7d7262", red: "#a8322d", orange: "#a85a1f", yellow: "#8a6d1a",
 539            green: "#4d6b2f", cyan: "#2f6b6b", blue: "#2f5486", purple: "#6b4a85", accent: "#a85a1f")),
 540    ]
 541
 542    static let darkPalettes: [Palette] = [
 543        Palette(id: "default-dark", name: "Default", appearance: .dark, colors: ThemeSpec.default.dark),
 544        ported("solarized-dark", "Solarized Dark", .dark, Roles(
 545            bg: "#002b36", alt: "#073642", fg: "#93a1a1", dim: "#586e75", red: "#dc322f", orange: "#cb4b16", yellow: "#b58900",
 546            green: "#859900", cyan: "#2aa198", blue: "#268bd2", purple: "#6c71c4", accent: "#268bd2")),
 547        ported("gruvbox-dark", "Gruvbox Dark", .dark, Roles(
 548            bg: "#282828", alt: "#3c3836", fg: "#ebdbb2", dim: "#928374", red: "#fb4934", orange: "#fe8019", yellow: "#fabd2f",
 549            green: "#b8bb26", cyan: "#8ec07c", blue: "#83a598", purple: "#d3869b", accent: "#83a598")),
 550        ported("modus-vivendi", "Modus Vivendi", .dark, Roles(
 551            bg: "#000000", alt: "#1e1e1e", fg: "#ffffff", dim: "#989898", red: "#ff5f59", orange: "#fec43f", yellow: "#d0bc00",
 552            green: "#44bc44", cyan: "#00d3d0", blue: "#2fafff", purple: "#b6a0ff", accent: "#2fafff")),
 553        ported("catppuccin-mocha", "Catppuccin Mocha", .dark, Roles(
 554            bg: "#1e1e2e", alt: "#181825", fg: "#cdd6f4", dim: "#7f849c", red: "#f38ba8", orange: "#fab387", yellow: "#f9e2af",
 555            green: "#a6e3a1", cyan: "#94e2d5", blue: "#89b4fa", purple: "#cba6f7", accent: "#cba6f7")),
 556        ported("nord", "Nord", .dark, Roles(
 557            bg: "#2e3440", alt: "#3b4252", fg: "#d8dee9", dim: "#616e88", red: "#bf616a", orange: "#d08770", yellow: "#ebcb8b",
 558            green: "#a3be8c", cyan: "#8fbcbb", blue: "#88c0d0", purple: "#b48ead", accent: "#88c0d0")),
 559        ported("dracula", "Dracula", .dark, Roles(
 560            bg: "#282a36", alt: "#44475a", fg: "#f8f8f2", dim: "#6272a4", red: "#ff5555", orange: "#ffb86c", yellow: "#f1fa8c",
 561            green: "#50fa7b", cyan: "#8be9fd", blue: "#8be9fd", purple: "#bd93f9", accent: "#bd93f9")),
 562        ported("tokyo-night", "Tokyo Night", .dark, Roles(
 563            bg: "#1a1b26", alt: "#16161e", fg: "#c0caf5", dim: "#565f89", red: "#f7768e", orange: "#ff9e64", yellow: "#e0af68",
 564            green: "#9ece6a", cyan: "#7dcfff", blue: "#7aa2f7", purple: "#bb9af7", accent: "#7aa2f7")),
 565        ported("doom-one", "doom-one", .dark, Roles(
 566            bg: "#282c34", alt: "#21242b", fg: "#bbc2cf", dim: "#5b6268", red: "#ff6c6b", orange: "#da8548", yellow: "#ecbe7b",
 567            green: "#98be65", cyan: "#46d9ff", blue: "#51afef", purple: "#c678dd", accent: "#51afef")),
 568    ]
 569```
 570
 571- [ ] **Step 4: Run the tests**
 572
 573Run: `swift test --filter PaletteTests`
 574Expected: PASS. If `everyPaletteHasExactlyTheSlotKeys` names a key, add it to `Roles.slots`.
 575
 576- [ ] **Step 5: Record the sources in `THIRD_PARTY.org`**
 577
 578Add a heading `* Color themes` listing, one line each, the palette, its upstream URL and license:
 579
 580```org
 581* Color themes
 582The built-in palettes in =Sources/OrgPresentation/Palettes.swift= take their colors from:
 583- Solarized, https://ethanschoonover.com/solarized/, MIT
 584- Gruvbox, https://github.com/morhetz/gruvbox, MIT
 585- Modus themes, https://protesilaos.com/emacs/modus-themes, GPL-3.0-or-later (colors only)
 586- Catppuccin, https://github.com/catppuccin/catppuccin, MIT
 587- Tomorrow, https://github.com/chriskempson/tomorrow-theme, MIT
 588- Nord, https://www.nordtheme.com, MIT
 589- Dracula, https://draculatheme.com, MIT
 590- Tokyo Night, https://github.com/folke/tokyonight.nvim, Apache-2.0
 591- doom-one, https://github.com/doomemacs/themes, MIT
 592```
 593
 594Check each license on the upstream page before committing; if any differs, correct the line, and if one is not MIT, Apache or BSD, stop and report it.
 595
 596- [ ] **Step 6: Commit**
 597
 598```bash
 599git add Sources/OrgPresentation/Palettes.swift Tests/OrgPresentationTests/PaletteTests.swift THIRD_PARTY.org
 600git commit -m "Fourteen built-in palettes, with a contrast test"
 601```
 602
 603---
 604
 605### Task 4: `light-theme` and `dark-theme`
 606
 607**Files:**
 608- Modify: `Sources/OrgPresentation/Palettes.swift`
 609- Modify: `Sources/OrgApp/UserConfig.swift:29-49` (`theme`), the `settings` array after `theme-file`
 610- Modify: `Sources/OrgApp/ConfigSync.swift` (`readTheme`)
 611- Modify: `Sources/OrgstarMobile/MobileModel.swift` (`readConfig`)
 612- Test: `Tests/OrgPresentationTests/PaletteTests.swift`, `Tests/OrgAppTests/UserConfigTests.swift`
 613
 614**Interfaces:**
 615- Consumes: `ThemeSpec.palette`, `defaultPaletteID` (Task 2).
 616- Produces:
 617  - `extension ThemeSpec { public static func base(light: String?, dark: String?) -> (ThemeSpec, [String]) }`
 618  - `UserConfig.theme(config:themeFile:lightTheme:darkTheme:in:read:)`, both new parameters `String?`, defaulting to `nil`.
 619  - Settings with defaults keys `themeLight` and `themeDark`.
 620
 621- [ ] **Step 1: Write the failing tests**
 622
 623In `PaletteTests`:
 624
 625```swift
 626    @Test func baseTakesEachAppearanceFromItsPalette() throws {
 627        let (spec, problems) = ThemeSpec.base(light: "paper", dark: "nord")
 628        #expect(problems.isEmpty)
 629        #expect(spec.light == ThemeSpec.palette("paper", .light)?.colors && spec.dark == ThemeSpec.palette("nord", .dark)?.colors)
 630        #expect(ThemeSpec.base(light: nil, dark: nil).0 == ThemeSpec.default)
 631        #expect(ThemeSpec.base(light: "", dark: "").0 == ThemeSpec.default)
 632    }
 633
 634    @Test func aPaletteOfTheOtherAppearanceIsAProblem() {
 635        let (spec, problems) = ThemeSpec.base(light: "nord", dark: "unknown")
 636        #expect(spec == ThemeSpec.default)
 637        #expect(problems == ["config.toml: unknown light-theme nord", "config.toml: unknown dark-theme unknown"])
 638    }
 639```
 640
 641In `UserConfigTests`:
 642
 643```swift
 644    @Test func chosenPalettesSitUnderTheThemeFileAndConfig() throws {
 645        let name = "orgstar-palette-\(UUID().uuidString)"
 646        let defaults = UserDefaults(suiteName: name)!
 647        defer { defaults.removePersistentDomain(forName: name) }
 648        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(name)
 649        defer { try? FileManager.default.removeItem(at: folder) }
 650        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 651        try "[theme.dark]\nlink = \"#000001\"\n".write(to: folder.appendingPathComponent("mine.toml"), atomically: true, encoding: .utf8)
 652        try "[theme]\nlight-theme = \"paper\"\ndark-theme = \"nord\"\ntheme-file = \"mine.toml\"\n[theme.dark]\ntodo = \"#000002\"\n"
 653            .write(to: folder.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
 654        let sync = ConfigSync(url: folder.appendingPathComponent("config.toml"), defaults: defaults)
 655        sync.start(watch: false)
 656        #expect(sync.problems.isEmpty, "\(sync.problems)")
 657        #expect(defaults.string(forKey: "themeLight") == "paper" && defaults.string(forKey: "themeDark") == "nord")
 658        let nord = try #require(ThemeSpec.palette("nord", .dark))
 659        #expect(sync.theme.light["background"] == ThemeSpec.palette("paper", .light)?.colors["background"])
 660        #expect(sync.theme.dark["background"] == nord.colors["background"])
 661        #expect(sync.theme.dark["link"]?.hex == "#000001")
 662        #expect(sync.theme.dark["todo"]?.hex == "#000002")
 663    }
 664
 665    @Test func noThemeSettingsGiveTheDefaultTheme() throws {
 666        let folder = FileManager.default.temporaryDirectory
 667        let theme = try #require(UserConfig.theme(config: "", themeFile: nil, lightTheme: nil, darkTheme: nil, in: folder))
 668        #expect(theme.theme == ThemeSpec.default && theme.problems.isEmpty)
 669    }
 670```
 671
 672- [ ] **Step 2: Run them to see them fail**
 673
 674Run: `swift test --filter "PaletteTests|UserConfigTests"`
 675Expected: compile errors for `base` and the new `theme` parameters.
 676
 677- [ ] **Step 3: Implement `ThemeSpec.base`**
 678
 679Append to the first `extension ThemeSpec` in `Palettes.swift`:
 680
 681```swift
 682    /// The default theme with each appearance's colors from the palette `light-theme` and
 683    /// `dark-theme` name; Default where one is unset or unknown, with a problem for unknown.
 684    public static func base(light: String?, dark: String?) -> (ThemeSpec, [String]) {
 685        var spec = ThemeSpec.default
 686        var problems: [String] = []
 687        for (id, appearance) in [(light, Palette.Appearance.light), (dark, .dark)] {
 688            guard let id, !id.isEmpty, id != defaultPaletteID(appearance) else { continue }
 689            guard let palette = palette(id, appearance) else {
 690                problems.append("config.toml: unknown \(appearance.rawValue)-theme \(id)")
 691                continue
 692            }
 693            if appearance == .light { spec.light = palette.colors } else { spec.dark = palette.colors }
 694        }
 695        return (spec, problems)
 696    }
 697```
 698
 699- [ ] **Step 4: Use it in `UserConfig.theme`**
 700
 701Change the signature and body:
 702
 703```swift
 704    public static func theme(
 705        config text: String, themeFile name: String?, lightTheme: String? = nil, darkTheme: String? = nil, in folder: URL,
 706        read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }
 707    ) -> (theme: ThemeSpec, problems: [String])? {
 708        guard let tables = try? TOML.parse(text) else { return nil }
 709        var (spec, problems) = ThemeSpec.base(light: lightTheme, dark: darkTheme)
 710        if let name, !name.isEmpty {
 711            if let themeText = read(folder.appendingPathComponent(name)) {
 712                do {
 713                    let (read, more) = ThemeSpec.reading(try TOML.parse(themeText), over: spec, file: name)
 714                    spec = read
 715                    problems += more
 716                } catch {
 717                    problems.append("\(name): \(error)")
 718                }
 719            } else {
 720                problems.append("config.toml: theme-file \(name) can't be read")
 721            }
 722        }
 723        let (merged, more) = ThemeSpec.reading(tables, over: spec)
 724        return (merged, problems + more)
 725    }
 726```
 727
 728Update the doc comment above it to: "The theme `config.toml` (`text`) sets: its `[theme]` tables' colors over those of `theme-file` (a path relative to `folder`), over the palettes `light-theme` and `dark-theme` name; with problems in all three. Nil when `text` isn't TOML."
 729
 730After the `theme-file` entry in `settings`, add:
 731
 732```swift
 733        Setting(section: "theme", key: "light-theme", defaultsKey: "themeLight", kind: .string, fallback: .string("default-light"),
 734                comment: "the built-in theme for the light appearance: default-light, solarized-light, gruvbox-light, modus-operandi, catppuccin-latte, tomorrow or paper", legacy: ""),
 735        Setting(section: "theme", key: "dark-theme", defaultsKey: "themeDark", kind: .string, fallback: .string("default-dark"),
 736                comment: "the built-in theme for the dark appearance: default-dark, solarized-dark, gruvbox-dark, modus-vivendi, catppuccin-mocha, nord, dracula, tokyo-night or doom-one", legacy: ""),
 737```
 738
 739- [ ] **Step 5: Pass the settings from both callers**
 740
 741`ConfigSync.readTheme`:
 742
 743```swift
 744        guard let text, let read = UserConfig.theme(
 745            config: text, themeFile: defaults.string(forKey: "themeFile"),
 746            lightTheme: defaults.string(forKey: "themeLight"), darkTheme: defaults.string(forKey: "themeDark"),
 747            in: url.deletingLastPathComponent()
 748        ) else { return }
 749```
 750
 751`MobileModel.readConfig`, so a device without a config folder still applies a chosen palette:
 752
 753```swift
 754    private static func readConfig(_ folder: URL?) -> ([String], ThemeSpec) {
 755        let defaults = UserDefaults.standard
 756        guard let folder else {
 757            let (base, problems) = ThemeSpec.base(light: defaults.string(forKey: "themeLight"), dark: defaults.string(forKey: "themeDark"))
 758            return (problems, base)
 759        }
 760        guard let text = read(folder.appendingPathComponent("config.toml")) else {
 761            return (["No config.toml in \(folder.lastPathComponent); the defaults apply."], .default)
 762        }
 763        let problems = UserConfig.apply(text, to: defaults)
 764        guard let theme = UserConfig.theme(
 765            config: text, themeFile: defaults.string(forKey: "themeFile"),
 766            lightTheme: defaults.string(forKey: "themeLight"), darkTheme: defaults.string(forKey: "themeDark"), in: folder, read: read
 767        ) else {
 768            return (problems, .default)
 769        }
 770        return (problems + theme.problems, theme.theme)
 771    }
 772```
 773
 774- [ ] **Step 6: Run the tests**
 775
 776Run: `swift test && xcodebuild -scheme OrgstarMobile -destination 'generic/platform=iOS Simulator' -derivedDataPath .build/ios build -quiet`
 777Expected: PASS and the iOS build succeeds. A test that compares the full `config.toml` template text gains the two new lines; update its expected text.
 778
 779- [ ] **Step 7: Commit**
 780
 781```bash
 782git add Sources/OrgPresentation/Palettes.swift Sources/OrgApp Sources/OrgstarMobile/MobileModel.swift Tests
 783git commit -m "light-theme and dark-theme settings, under theme-file and config.toml colors"
 784```
 785
 786---
 787
 788### Task 5: Accent tint
 789
 790**Files:**
 791- Modify: `Sources/Orgstar/OrgstarApp.swift:339,353,361,368` (scene roots)
 792- Modify: `Sources/OrgstarMobile/MobileTheme.swift` (append extension)
 793- Modify: `Sources/OrgstarMobile/OrgstarMobileApp.swift` (root `TabView`)
 794
 795**Interfaces:**
 796- Consumes: `accent` slot (Task 2); Mac `ThemeSpec.color(_:) -> Color?` in `ThemeColors.swift`.
 797- Produces: iOS `extension ThemeSpec { var accentColor: Color? }`.
 798
 799- [ ] **Step 1: Mac**
 800
 801On each of the four lines `.environment(\.orgTheme, ConfigSync.shared.theme)` at OrgstarApp.swift:339, 353, 361, 368, add on the following line:
 802
 803```swift
 804                    .tint(ConfigSync.shared.theme.color("accent"))
 805```
 806
 807`color` returns nil when no palette sets `accent`, which leaves the system's tint.
 808
 809- [ ] **Step 2: iOS**
 810
 811Append to `MobileTheme.swift`, inside `#if os(iOS)`:
 812
 813```swift
 814extension ThemeSpec {
 815    /// `accent` for `.tint`, the system's blue in an appearance the theme leaves it unset; nil
 816    /// when neither appearance sets it.
 817    var accentColor: Color? {
 818        let (light, dark) = (light["accent"], dark["accent"])
 819        guard light != nil || dark != nil else { return nil }
 820        return Color(uiColor: UIColor { traits in
 821            guard let c = traits.userInterfaceStyle == .dark ? dark : light else { return .systemBlue }
 822            return UIColor(red: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
 823        })
 824    }
 825}
 826```
 827
 828In `OrgstarMobileApp.swift`, after `.clockAccessory(model.clock, perform: clock)` on the root `TabView`, add:
 829
 830```swift
 831        .tint(model.theme.accentColor)
 832```
 833
 834- [ ] **Step 3: Check by hand**
 835
 836Run: `swift build && scripts/build-app.sh`, open the app, set `dark-theme = "dracula"` under `[theme]` in `~/.config/orgstar/config.toml`, switch to dark appearance.
 837Expected: toggles and the sidebar's selection turn Dracula purple; in light appearance they stay the system accent.
 838
 839- [ ] **Step 4: Commit**
 840
 841```bash
 842git add Sources/Orgstar/OrgstarApp.swift Sources/OrgstarMobile/MobileTheme.swift Sources/OrgstarMobile/OrgstarMobileApp.swift
 843git commit -m "Theme accent tints controls"
 844```
 845
 846---
 847
 848### Task 6: Mac theme picker and Copy to Config Folder
 849
 850**Files:**
 851- Create: `Sources/Orgstar/ThemePickerSection.swift`
 852- Modify: `Sources/OrgPresentation/Palettes.swift` (`themeFile(light:dark:)`)
 853- Modify: `Sources/Orgstar/OrgstarApp.swift:776-778` (first section of `appearance`)
 854- Test: `Tests/OrgPresentationTests/PaletteTests.swift`
 855
 856**Interfaces:**
 857- Consumes: `ThemeSpec.palettes`, `palette`, `defaultPaletteID`; settings `themeLight`, `themeDark`, `themeFile`.
 858- Produces: `extension ThemeSpec { public static func themeFile(light: Palette, dark: Palette) -> String }`; `struct ThemePickerSection: View`.
 859
 860- [ ] **Step 1: Write the failing test**
 861
 862```swift
 863    @Test func aCopiedThemeReadsBackAsThePalettes() throws {
 864        let light = try #require(ThemeSpec.palette("paper", .light))
 865        let dark = try #require(ThemeSpec.palette("nord", .dark))
 866        let text = ThemeSpec.themeFile(light: light, dark: dark)
 867        #expect(text.hasPrefix("# Paper and Nord, copied from orgstar's built-in themes."))
 868        let (spec, problems) = ThemeSpec.reading(try TOML.parse(text))
 869        #expect(problems.isEmpty, "\(problems)")
 870        #expect(spec.light.filter { light.colors[$0.key] != nil } == light.colors && spec.dark.filter { dark.colors[$0.key] != nil } == dark.colors)
 871    }
 872```
 873
 874Add `import OrgCore` to the test file for `TOML`.
 875
 876- [ ] **Step 2: Run it to see it fail**
 877
 878Run: `swift test --filter PaletteTests/aCopiedThemeReadsBackAsThePalettes`
 879Expected: compile error, `themeFile(light:dark:)` not found.
 880
 881- [ ] **Step 3: Implement `themeFile`**
 882
 883Append to `Palettes.swift`:
 884
 885```swift
 886extension ThemeSpec {
 887    /// Two palettes as a theme file, every color written out, in slot order.
 888    public static func themeFile(light: Palette, dark: Palette) -> String {
 889        var out = "# \(light.name) and \(dark.name), copied from orgstar's built-in themes. Used with\n"
 890            + "# theme-file = \"my-theme.toml\" under [theme] in config.toml; colors there apply on top.\n"
 891        for (table, palette) in [("theme.light", light), ("theme.dark", dark)] {
 892            out += "\n[\(table)]\n"
 893            for slot in slots {
 894                if let color = palette.colors[slot.key] { out += "\(slot.key) = \"\(color.hex)\"\n" }
 895            }
 896        }
 897        return out
 898    }
 899}
 900```
 901
 902- [ ] **Step 4: Run the test**
 903
 904Run: `swift test --filter PaletteTests`
 905Expected: PASS.
 906
 907- [ ] **Step 5: Write `ThemePickerSection.swift`**
 908
 909```swift
 910import AppKit
 911import OrgApp
 912import OrgPresentation
 913import SwiftUI
 914
 915/// Settings ▸ Appearance ▸ Theme: the built-in palette for each appearance.
 916struct ThemePickerSection: View {
 917    @AppStorage("themeLight") private var themeLight = "default-light"
 918    @AppStorage("themeDark") private var themeDark = "default-dark"
 919    @AppStorage("themeFile") private var themeFile = ""
 920    @State private var message: String?
 921
 922    var body: some View {
 923        Section {
 924            picker("Light", .light, $themeLight)
 925            picker("Dark", .dark, $themeDark)
 926            LabeledContent("Starting point") {
 927                Button("Copy to Config Folder") { copy() }
 928            }
 929        } header: {
 930            Text("Theme")
 931        } footer: {
 932            Text(message ?? "Colors set in config.toml or in the theme file apply on top of these.")
 933                .settingsFooter()
 934        }
 935    }
 936
 937    private func picker(_ title: LocalizedStringKey, _ appearance: Palette.Appearance, _ selection: Binding<String>) -> some View {
 938        Picker(title, selection: selection) {
 939            ForEach(ThemeSpec.palettes(appearance), id: \.id) { palette in
 940                Label { Text(palette.name) } icon: { Image(nsImage: Self.swatch(palette)) }.tag(palette.id)
 941            }
 942            if ThemeSpec.palette(selection.wrappedValue, appearance) == nil {
 943                Text(selection.wrappedValue).tag(selection.wrappedValue)
 944            }
 945        }
 946    }
 947
 948    /// Background, text, heading, TODO and accent, side by side.
 949    static func swatch(_ palette: Palette) -> NSImage {
 950        let keys = ["background", "foreground", "heading-1", "todo", "accent"]
 951        return NSImage(size: NSSize(width: 40, height: 12), flipped: false) { rect in
 952            for (i, key) in keys.enumerated() {
 953                let c = palette.colors[key] ?? palette.colors["cursor"] ?? RGBA(red: 0.5, green: 0.5, blue: 0.5)
 954                NSColor(srgbRed: c.red, green: c.green, blue: c.blue, alpha: 1).setFill()
 955                NSRect(x: CGFloat(i) * 8, y: 0, width: 8, height: rect.height).fill()
 956            }
 957            NSColor.separatorColor.setStroke()
 958            NSBezierPath(rect: rect.insetBy(dx: 0.5, dy: 0.5)).stroke()
 959            return true
 960        }
 961    }
 962
 963    private func copy() {
 964        let file = UserConfig.directory.appendingPathComponent("my-theme.toml")
 965        guard !FileManager.default.fileExists(atPath: file.path) else {
 966            message = String(localized: "my-theme.toml is already in the config folder; it was left as it is.")
 967            return
 968        }
 969        let light = ThemeSpec.palette(themeLight, .light) ?? ThemeSpec.palettes(.light)[0]
 970        let dark = ThemeSpec.palette(themeDark, .dark) ?? ThemeSpec.palettes(.dark)[0]
 971        do {
 972            try ThemeSpec.themeFile(light: light, dark: dark).write(to: file, atomically: true, encoding: .utf8)
 973            themeFile = "my-theme.toml"
 974            message = String(localized: "Copied to my-theme.toml, now the theme file.")
 975        } catch {
 976            message = error.localizedDescription
 977        }
 978    }
 979}
 980```
 981
 982If `settingsFooter()` is `private` in `OrgstarApp.swift`, make it `internal` (drop `private`) so this file can use it.
 983
 984- [ ] **Step 6: Insert the section**
 985
 986In `OrgstarApp.swift`, in `private var appearance: some View`, make the first line inside `Form {`:
 987
 988```swift
 989            ThemePickerSection()
 990```
 991
 992- [ ] **Step 7: Check by hand**
 993
 994Run: `scripts/check-file-sizes.sh && scripts/build-app.sh`, open Settings ▸ Appearance.
 995Expected: Light and Dark menus list the palettes with swatches; choosing one recolors the open editor at once and writes `light-theme`/`dark-theme` into `config.toml`; Copy to Config Folder writes `my-theme.toml` once and on the second press shows the "already in the config folder" message without changing the file.
 996
 997- [ ] **Step 8: Commit**
 998
 999```bash
1000git add Sources/Orgstar Sources/OrgPresentation/Palettes.swift Tests/OrgPresentationTests/PaletteTests.swift
1001git commit -m "Theme pickers in Settings ▸ Appearance; Copy to Config Folder"
1002```
1003
1004---
1005
1006### Task 7: iOS theme picker
1007
1008**Files:**
1009- Create: `Sources/OrgstarMobile/ThemePickerScreen.swift`
1010- Modify: `Sources/OrgstarMobile/SettingsScreen.swift` (new section before `calendarSection`; "In use ▸ Theme")
1011
1012**Interfaces:**
1013- Consumes: `ThemeSpec.palettes`, `palette`; `MobileModel.set(_:to:)`, `model.settingsVersion`.
1014- Produces: `struct ThemePickerScreen: View { init(model: MobileModel, appearance: Palette.Appearance) }`; `ThemePickerScreen.current(_:) -> Palette`.
1015
1016- [ ] **Step 1: Write `ThemePickerScreen.swift`**
1017
1018```swift
1019#if os(iOS)
1020import OrgCore
1021import OrgPresentation
1022import SwiftUI
1023
1024/// The built-in palettes of one appearance, each as a few lines of Org in its colors.
1025struct ThemePickerScreen: View {
1026    let model: MobileModel
1027    let appearance: Palette.Appearance
1028
1029    var body: some View {
1030        let _ = model.settingsVersion
1031        let current = Self.current(appearance).id
1032        List(ThemeSpec.palettes(appearance), id: \.id) { palette in
1033            Button {
1034                model.set(appearance == .light ? "themeLight" : "themeDark", to: .string(palette.id))
1035            } label: {
1036                HStack {
1037                    VStack(alignment: .leading, spacing: 6) {
1038                        Text(palette.name).foregroundStyle(.primary)
1039                        Self.sample(palette)
1040                    }
1041                    Spacer()
1042                    if palette.id == current { Image(systemName: "checkmark").foregroundStyle(.tint) }
1043                }
1044            }
1045        }
1046        .navigationTitle(appearance == .light ? "Light Theme" : "Dark Theme")
1047    }
1048
1049    /// The palette `light-theme` or `dark-theme` names, Default when unknown.
1050    static func current(_ appearance: Palette.Appearance) -> Palette {
1051        let id = UserDefaults.standard.string(forKey: appearance == .light ? "themeLight" : "themeDark") ?? ""
1052        return ThemeSpec.palette(id, appearance) ?? ThemeSpec.palettes(appearance)[0]
1053    }
1054
1055    private static func sample(_ palette: Palette) -> some View {
1056        func color(_ key: String) -> Color {
1057            guard let c = palette.colors[key] else { return .primary }
1058            return Color(.sRGB, red: c.red, green: c.green, blue: c.blue, opacity: c.alpha)
1059        }
1060        let font = Font.system(.footnote, design: .monospaced)
1061        return VStack(alignment: .leading, spacing: 2) {
1062            (Text("* ").foregroundColor(color("heading-1")) + Text("TODO ").foregroundColor(color("todo")).bold()
1063                + Text("Plan the trip ").foregroundColor(color("heading-1")).bold() + Text(":travel:").foregroundColor(color("tags")))
1064            (Text("  SCHEDULED: ").foregroundColor(color("metadata")) + Text("<2026-10-20 Tue>").foregroundColor(color("timestamp")))
1065            (Text("  Book via ").foregroundColor(color("foreground")) + Text("the site").foregroundColor(color("link")).underline()
1066                + Text(", ").foregroundColor(color("foreground")) + Text("~code~").foregroundColor(color("code")))
1067            (Text("** ").foregroundColor(color("heading-2")) + Text("DONE ").foregroundColor(color("done")).bold()
1068                + Text("Passport").foregroundColor(color("heading-2")).bold())
1069        }
1070        .font(font)
1071        .padding(8)
1072        .frame(maxWidth: .infinity, alignment: .leading)
1073        .background(color("background"), in: RoundedRectangle(cornerRadius: 8))
1074    }
1075}
1076#endif
1077```
1078
1079- [ ] **Step 2: Add the section to `SettingsScreen`**
1080
1081Before `calendarSection` in `body`:
1082
1083```swift
1084            Section("Appearance") {
1085                let _ = model.settingsVersion
1086                NavigationLink {
1087                    ThemePickerScreen(model: model, appearance: .light)
1088                } label: {
1089                    LabeledContent("Light Theme", value: ThemePickerScreen.current(.light).name)
1090                }
1091                NavigationLink {
1092                    ThemePickerScreen(model: model, appearance: .dark)
1093                } label: {
1094                    LabeledContent("Dark Theme", value: ThemePickerScreen.current(.dark).name)
1095                }
1096            }
1097```
1098
1099Replace the "In use" Theme row with:
1100
1101```swift
1102                LabeledContent("Theme", value: themeInUse)
1103```
1104
1105and add to `SettingsScreen`:
1106
1107```swift
1108    /// The two palettes' names, and the theme file's when there is one.
1109    private var themeInUse: String {
1110        let names = "\(ThemePickerScreen.current(.light).name) / \(ThemePickerScreen.current(.dark).name)"
1111        guard let file = UserDefaults.standard.string(forKey: "themeFile"), !file.isEmpty else { return names }
1112        return "\(names), \(file)"
1113    }
1114```
1115
1116- [ ] **Step 3: Build and check**
1117
1118Run: `xcodebuild -scheme OrgstarMobile -destination 'generic/platform=iOS Simulator' -derivedDataPath .build/ios build -quiet && scripts/build-ios-app.sh && xcrun simctl install booted .build/ios-app/orgstar.app`
1119Open Settings ▸ Light Theme, pick Paper, go back to an open file.
1120Expected: the file shows Paper's colors; with a config folder set, its `config.toml` has `light-theme = "paper"`; without one, the choice still applies.
1121
1122- [ ] **Step 4: Commit**
1123
1124```bash
1125git add Sources/OrgstarMobile
1126git commit -m "Theme pickers in the iOS Settings tab"
1127```
1128
1129---
1130
1131### Task 8: The other twelve icons, as iOS alternates
1132
1133Before this task: ask about the pre-existing uncommitted change to `project.pbxproj` (Global constraints).
1134
1135**Files:**
1136- Modify: `scripts/make-icon.swift` (`variants`, `drawUnicorn`)
1137- Modify: `ios/Orgstar.xcodeproj/project.pbxproj` (the `Orgstar` app target's Debug and Release build settings, beside `ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;` at lines 792 and 816; confirm those two belong to the `Orgstar` target, not the Watch)
1138- Generated: `ios/Orgstar/Assets.xcassets/AppIcon-*.appiconset`, `IconPreview-*.imageset`, `packaging/IconPreviews/*`
1139
1140**Interfaces:**
1141- Consumes: `Variant`, `draw` (Task 1).
1142- Produces: icon ids `default midnight paper org sunset forest mono rainbow outline terminal unicorn unicorn-night unicorn-pastel`; iOS alternate names `AppIcon-<Id>` with the id in CamelCase (`AppIcon-UnicornNight`).
1143
1144- [ ] **Step 1: Add the variants**
1145
1146Append to `variants`:
1147
1148```swift
1149    Variant(id: "midnight", top: rgb(0x1a1d24), bottom: rgb(0x0b0c10), glyph: rgb(0xffc74d), bars: NSColor(white: 1, alpha: 0.85)),
1150    Variant(id: "paper", top: rgb(0xfbf8f1), bottom: rgb(0xece4d2), glyph: rgb(0x3b3428), bars: rgb(0x7d7262)),
1151    Variant(id: "org", top: rgb(0x77aa99), bottom: rgb(0x3e7a6a), glyph: rgb(0xffc74d), bars: NSColor(white: 1, alpha: 0.92)),
1152    Variant(id: "sunset", top: rgb(0xff9a3c), bottom: rgb(0xe23e7a), glyph: .white, bars: NSColor(white: 1, alpha: 0.85)),
1153    Variant(id: "forest", top: rgb(0x2f5d3a), bottom: rgb(0x173322), glyph: rgb(0xf4ecd0), bars: NSColor(white: 1, alpha: 0.8)),
1154    Variant(id: "mono", top: rgb(0x5a5d63), bottom: rgb(0x2c2e33), glyph: .white, bars: NSColor(white: 1, alpha: 0.8)),
1155    Variant(id: "rainbow", top: rgb(0xe40303), bottom: rgb(0x732982), glyph: .white, bars: NSColor(white: 1, alpha: 0.9)),
1156    Variant(id: "outline", top: .white, bottom: rgb(0xf2f2f2), glyph: rgb(0x2f5486), bars: rgb(0x2f5486), style: .outline),
1157    Variant(id: "terminal", top: rgb(0x0a0f0a), bottom: .black, glyph: rgb(0x39ff6a), bars: rgb(0x2bcc55)),
1158    Variant(id: "unicorn", top: rgb(0x77aa99), bottom: rgb(0x3e7a6a), glyph: rgb(0xffc74d), bars: .white, style: .unicorn),
1159    Variant(id: "unicorn-night", top: rgb(0x2b2a6b), bottom: rgb(0x14133a), glyph: rgb(0xd8dde6), bars: rgb(0xeae8ff), style: .unicorn),
1160    Variant(id: "unicorn-pastel", top: rgb(0xffc6dd), bottom: rgb(0xc7b8ff), glyph: rgb(0xffc74d), bars: .white, style: .unicorn),
1161```
1162
1163For `rainbow`, the two-color gradient is a placeholder for the stripes; in `draw`, `case .light:`, draw stripes when `v.id == "rainbow"`:
1164
1165```swift
1166    case .light where v.id == "rainbow":
1167        NSGraphicsContext.saveGraphicsState()
1168        shape.addClip()
1169        let stripes = [0xe40303, 0xff8c00, 0xffed00, 0x008026, 0x004dff, 0x750787].map(rgb)
1170        let band = square.height / CGFloat(stripes.count)
1171        for (i, color) in stripes.enumerated() {
1172            color.setFill()
1173            NSRect(x: square.minX, y: square.maxY - band * CGFloat(i + 1), width: square.width, height: band).fill()
1174        }
1175        NSGraphicsContext.restoreGraphicsState()
1176```
1177
1178Put this case before the plain `case .light:`.
1179
1180- [ ] **Step 2: Draw the unicorn**
1181
1182Replace `drawUnicorn` with a head in profile facing left, its horn rising to the upper left, the ✱ at the horn's tip. Coordinates are on the 1024 grid, origin bottom-left:
1183
1184```swift
1185/// A unicorn's head in profile, facing left, with a mane; its horn ends in the heading star.
1186func drawUnicorn(_ s: CGFloat, glyph: NSColor, head: NSColor) {
1187    func p(_ x: CGFloat, _ y: CGFloat) -> NSPoint { NSPoint(x: x * s, y: y * s) }
1188    let face = NSBezierPath()
1189    face.move(to: p(640, 200))                                                    // neck, back
1190    face.curve(to: p(600, 560), controlPoint1: p(700, 330), controlPoint2: p(690, 480))
1191    face.curve(to: p(470, 640), controlPoint1: p(560, 610), controlPoint2: p(520, 640))  // crown
1192    face.line(to: p(440, 690))                                                    // ear
1193    face.line(to: p(410, 620))
1194    face.curve(to: p(250, 470), controlPoint1: p(340, 590), controlPoint2: p(270, 530))  // brow to nose
1195    face.curve(to: p(290, 400), controlPoint1: p(235, 430), controlPoint2: p(250, 400))  // muzzle
1196    face.curve(to: p(430, 430), controlPoint1: p(340, 400), controlPoint2: p(390, 410))  // jaw
1197    face.curve(to: p(450, 200), controlPoint1: p(470, 360), controlPoint2: p(440, 280))  // throat
1198    face.close()
1199    head.setFill()
1200    face.fill()
1201
1202    let mane = NSBezierPath()
1203    mane.move(to: p(600, 560))
1204    mane.curve(to: p(760, 220), controlPoint1: p(720, 520), controlPoint2: p(800, 360))
1205    mane.line(to: p(690, 210))
1206    mane.curve(to: p(600, 520), controlPoint1: p(730, 330), controlPoint2: p(680, 470))
1207    mane.close()
1208    glyph.withAlphaComponent(0.85).setFill()
1209    mane.fill()
1210
1211    let horn = NSBezierPath()
1212    horn.move(to: p(440, 640))
1213    horn.line(to: p(300, 790))
1214    horn.line(to: p(475, 660))
1215    horn.close()
1216    head.blended(withFraction: 0.25, of: glyph)?.setFill()
1217    horn.fill()
1218
1219    let eye = NSBezierPath(ovalIn: NSRect(x: 360 * s, y: 520 * s, width: 28 * s, height: 28 * s))
1220    NSColor(white: 0.15, alpha: 1).setFill()
1221    eye.fill()
1222
1223    let star = NSAttributedString(string: "✱", attributes: [.font: NSFont.systemFont(ofSize: 190 * s, weight: .heavy), .foregroundColor: glyph])
1224    star.draw(at: p(205, 700))
1225}
1226```
1227
1228- [ ] **Step 3: Generate and look at every icon**
1229
1230Run: `swift scripts/make-icon.swift && open packaging/IconPreviews`
1231Expected: 26 previews. Check each at Finder's largest icon size and at 64 pixels: the star reads in every one; the unicorn reads as a unicorn's head with the star at the horn's tip. Adjust the unicorn's control points in Step 2 until it does, keeping the shape inside the 100–924 square with margin.
1232
1233- [ ] **Step 4: Make every `AppIcon-*` set an alternate**
1234
1235In `project.pbxproj`, in the `Orgstar` target's Debug and Release `buildSettings`, add beside `ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;`:
1236
1237```
1238				ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
1239```
1240
1241- [ ] **Step 5: Build and check the alternates compile in**
1242
1243Run: `xcodebuild -project ios/Orgstar.xcodeproj -scheme Orgstar -destination 'generic/platform=iOS Simulator' -derivedDataPath .build/ios-xc build -quiet && /usr/libexec/PlistBuddy -c 'Print :CFBundleIcons~ipad:CFBundleAlternateIcons' .build/ios-xc/Build/Products/Debug-iphonesimulator/Orgstar.app/Info.plist`
1244Expected: 12 entries, `AppIcon-Midnight` through `AppIcon-UnicornPastel`. If the product's path or name differs, find it with `find .build/ios-xc -name Info.plist -path '*Orgstar.app/*' -maxdepth 6`.
1245
1246- [ ] **Step 6: Commit**
1247
1248```bash
1249git add scripts/make-icon.swift ios/Orgstar/Assets.xcassets packaging/IconPreviews ios/Orgstar.xcodeproj/project.pbxproj
1250git commit -m "Twelve more app icons, three of them unicorns; iOS alternate icons"
1251```
1252
1253Stage only this task's hunks of `project.pbxproj` (`git add -p`) if the earlier uncommitted change is still in the file.
1254
1255---
1256
1257### Task 9: iOS icon picker
1258
1259**Files:**
1260- Create: `Sources/OrgPresentation/AppIcons.swift`
1261- Create: `Sources/OrgstarMobile/AppIconScreen.swift`
1262- Modify: `Sources/OrgstarMobile/SettingsScreen.swift` ("Appearance" section)
1263- Test: `Tests/OrgPresentationTests/PaletteTests.swift`
1264
1265**Interfaces:**
1266- Produces: `public enum AppIcons { public static let ids: [String]; public static func name(_ id: String) -> String; public static func alternateName(_ id: String) -> String?; public static func id(alternateName: String?) -> String }`
1267
1268- [ ] **Step 1: Write the failing test**
1269
1270```swift
1271    @Test func iconIdsMapToAlternateNames() {
1272        #expect(AppIcons.ids.first == "default" && AppIcons.ids.count == 13)
1273        #expect(AppIcons.alternateName("default") == nil)
1274        #expect(AppIcons.alternateName("unicorn-night") == "AppIcon-UnicornNight")
1275        #expect(AppIcons.id(alternateName: "AppIcon-UnicornNight") == "unicorn-night")
1276        #expect(AppIcons.id(alternateName: nil) == "default" && AppIcons.id(alternateName: "AppIcon-Gone") == "default")
1277        #expect(AppIcons.name("unicorn-pastel") == "Unicorn Pastel")
1278    }
1279```
1280
1281- [ ] **Step 2: Run it to see it fail**
1282
1283Run: `swift test --filter PaletteTests/iconIdsMapToAlternateNames`
1284Expected: compile error, `AppIcons` not found.
1285
1286- [ ] **Step 3: Write `AppIcons.swift`**
1287
1288```swift
1289/// The app icons `scripts/make-icon.swift` draws, by id, in its order.
1290public enum AppIcons {
1291    public static let ids = [
1292        "default", "midnight", "paper", "org", "sunset", "forest", "mono", "rainbow", "outline", "terminal",
1293        "unicorn", "unicorn-night", "unicorn-pastel",
1294    ]
1295
1296    private static func words(_ id: String) -> [String] { id.split(separator: "-").map { $0.prefix(1).uppercased() + $0.dropFirst() } }
1297
1298    public static func name(_ id: String) -> String { words(id).joined(separator: " ") }
1299
1300    /// The iOS alternate icon's name; nil for the primary icon.
1301    public static func alternateName(_ id: String) -> String? {
1302        id == "default" ? nil : "AppIcon-" + words(id).joined()
1303    }
1304
1305    public static func id(alternateName: String?) -> String {
1306        ids.first { self.alternateName($0) == alternateName && alternateName != nil } ?? "default"
1307    }
1308}
1309```
1310
1311- [ ] **Step 4: Run the test**
1312
1313Run: `swift test --filter PaletteTests`
1314Expected: PASS.
1315
1316- [ ] **Step 5: Write `AppIconScreen.swift`**
1317
1318```swift
1319#if os(iOS)
1320import OrgPresentation
1321import SwiftUI
1322import UIKit
1323
1324/// The app icons, as previews; tapping one makes it the home screen's icon.
1325struct AppIconScreen: View {
1326    @State private var current = AppIcons.id(alternateName: UIApplication.shared.alternateIconName)
1327    @State private var failure: String?
1328
1329    var body: some View {
1330        ScrollView {
1331            LazyVGrid(columns: [GridItem(.adaptive(minimum: 88), spacing: 16)], spacing: 20) {
1332                ForEach(AppIcons.ids, id: \.self) { id in
1333                    Button { choose(id) } label: {
1334                        VStack(spacing: 6) {
1335                            Image("IconPreview-\(id)")
1336                                .resizable()
1337                                .frame(width: 72, height: 72)
1338                                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
1339                                .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous)
1340                                    .strokeBorder(id == current ? Color.accentColor : .clear, lineWidth: 3).padding(-4))
1341                            Text(AppIcons.name(id)).font(.caption).foregroundStyle(.primary)
1342                        }
1343                    }
1344                    .buttonStyle(.plain)
1345                    .accessibilityAddTraits(id == current ? .isSelected : [])
1346                }
1347            }
1348            .padding()
1349            if let failure { Text(failure).foregroundStyle(.red).padding(.horizontal) }
1350        }
1351        .navigationTitle("App Icon")
1352    }
1353
1354    private func choose(_ id: String) {
1355        guard id != current, UIApplication.shared.supportsAlternateIcons else { return }
1356        Task {
1357            do {
1358                try await UIApplication.shared.setAlternateIconName(AppIcons.alternateName(id))
1359                current = id
1360                failure = nil
1361            } catch {
1362                failure = error.localizedDescription
1363            }
1364        }
1365    }
1366}
1367#endif
1368```
1369
1370`Image("IconPreview-<id>")` reads from the app's asset catalog, which the Xcode project builds; the SwiftPM simulator build (`build-ios-app.sh`) has no catalog, so the previews are blank there. Check this screen through the Xcode project.
1371
1372- [ ] **Step 6: Add the row**
1373
1374In `SettingsScreen`'s "Appearance" section, after the Dark Theme link:
1375
1376```swift
1377                NavigationLink {
1378                    AppIconScreen()
1379                } label: {
1380                    LabeledContent("App Icon", value: AppIcons.name(AppIcons.id(alternateName: UIApplication.shared.alternateIconName)))
1381                }
1382```
1383
1384- [ ] **Step 7: Check on iOS 26**
1385
1386Run the `Orgstar` scheme from Xcode on a device or simulator; Settings ▸ App Icon ▸ Unicorn.
1387Expected: the system alert names the change, the home screen shows the unicorn, and the grid marks Unicorn after reopening the screen. In Customize ▸ Dark and Tinted, the unicorn's dark and tinted versions show.
1388
1389- [ ] **Step 8: Commit**
1390
1391```bash
1392git add Sources/OrgPresentation/AppIcons.swift Sources/OrgstarMobile Tests/OrgPresentationTests/PaletteTests.swift
1393git commit -m "App icon picker in the iOS Settings tab"
1394```
1395
1396---
1397
1398### Task 10: Mac icon picker and Dock icon
1399
1400**Files:**
1401- Create: `Sources/Orgstar/DockIcon.swift`
1402- Create: `Sources/Orgstar/AppIconSection.swift`
1403- Modify: `Sources/Orgstar/OrgstarApp.swift` (`AppDelegate.applicationDidFinishLaunching`, `appearance` form)
1404- Test: `Tests/OrgAppTests/DockIconTests.swift` (only if `DockIcon`'s pure part lives in `OrgApp`; see Step 1)
1405
1406**Interfaces:**
1407- Consumes: `AppIcons` (Task 9); `Contents/Resources/IconPreviews/<id>-light.png` / `-dark.png` (Task 1).
1408- Produces: `@MainActor enum DockIcon { static func previewName(_ id: String, dark: Bool) -> String?; static func apply(); static func start() }`, defaults key `appIcon`.
1409
1410- [ ] **Step 1: Write the failing test**
1411
1412`Orgstar` is an executable target that tests can't import, so the choice of file goes in `OrgPresentation` beside `AppIcons`, and is tested there. Add to `AppIcons.swift`:
1413
1414```swift
1415extension AppIcons {
1416    /// The Mac's Dock icon file for `id` in an appearance, in `Contents/Resources/IconPreviews`;
1417    /// nil for the default, which is the bundle's own icon.
1418    public static func dockFile(_ id: String, dark: Bool) -> String? {
1419        guard id != "default", ids.contains(id) else { return nil }
1420        return "\(id)-\(dark ? "dark" : "light")"
1421    }
1422}
1423```
1424
1425and first the test in `PaletteTests`:
1426
1427```swift
1428    @Test func dockFilesFollowTheAppearance() {
1429        #expect(AppIcons.dockFile("default", dark: true) == nil)
1430        #expect(AppIcons.dockFile("gone", dark: false) == nil)
1431        #expect(AppIcons.dockFile("unicorn", dark: false) == "unicorn-light")
1432        #expect(AppIcons.dockFile("unicorn", dark: true) == "unicorn-dark")
1433    }
1434```
1435
1436- [ ] **Step 2: Run it to see it fail, then add the extension and see it pass**
1437
1438Run: `swift test --filter PaletteTests/dockFilesFollowTheAppearance` (fails: no `dockFile`), add the extension, run again.
1439Expected: PASS.
1440
1441- [ ] **Step 3: Write `DockIcon.swift`**
1442
1443```swift
1444import AppKit
1445import OrgPresentation
1446
1447/// The icon chosen in Settings ▸ Appearance, shown in the Dock while orgstar runs, in the
1448/// variant for the current appearance.
1449@MainActor
1450enum DockIcon {
1451    private static var observation: NSKeyValueObservation?
1452
1453    static func apply() {
1454        let id = UserDefaults.standard.string(forKey: "appIcon") ?? "default"
1455        let dark = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
1456        guard let file = AppIcons.dockFile(id, dark: dark),
1457              let url = Bundle.main.url(forResource: file, withExtension: "png", subdirectory: "IconPreviews") else {
1458            NSApp.applicationIconImage = nil
1459            return
1460        }
1461        NSApp.applicationIconImage = NSImage(contentsOf: url)
1462    }
1463
1464    /// Applies now, and again whenever the appearance changes.
1465    static func start() {
1466        apply()
1467        observation = NSApp.observe(\.effectiveAppearance) { _, _ in
1468            Task { @MainActor in apply() }
1469        }
1470    }
1471}
1472```
1473
1474- [ ] **Step 4: Start it at launch**
1475
1476In `AppDelegate.applicationDidFinishLaunching`, add as its first line:
1477
1478```swift
1479        DockIcon.start()
1480```
1481
1482- [ ] **Step 5: Write `AppIconSection.swift`**
1483
1484```swift
1485import AppKit
1486import OrgPresentation
1487import SwiftUI
1488
1489/// Settings ▸ Appearance ▸ App Icon: the icon the Dock shows while orgstar runs.
1490struct AppIconSection: View {
1491    @AppStorage("appIcon") private var appIcon = "default"
1492
1493    var body: some View {
1494        Section {
1495            LazyVGrid(columns: [GridItem(.adaptive(minimum: 72), spacing: 12)], spacing: 12) {
1496                ForEach(AppIcons.ids, id: \.self) { id in
1497                    Button {
1498                        appIcon = id
1499                        DockIcon.apply()
1500                    } label: {
1501                        VStack(spacing: 4) {
1502                            preview(id)
1503                                .resizable()
1504                                .frame(width: 56, height: 56)
1505                                .padding(4)
1506                                .background(id == appIcon ? Color.accentColor.opacity(0.25) : .clear, in: RoundedRectangle(cornerRadius: 10))
1507                            Text(AppIcons.name(id)).font(.caption)
1508                        }
1509                    }
1510                    .buttonStyle(.plain)
1511                    .accessibilityAddTraits(id == appIcon ? .isSelected : [])
1512                }
1513            }
1514        } header: {
1515            Text("App Icon")
1516        } footer: {
1517            Text("The icon shows in the Dock while orgstar runs. Finder, and the Dock after orgstar quits, show the default icon.")
1518                .settingsFooter()
1519        }
1520    }
1521
1522    private func preview(_ id: String) -> Image {
1523        let url = Bundle.main.url(forResource: "\(id)-light", withExtension: "png", subdirectory: "IconPreviews")
1524        return url.flatMap { NSImage(contentsOf: $0) }.map { Image(nsImage: $0) } ?? Image(nsImage: NSApp.applicationIconImage)
1525    }
1526}
1527```
1528
1529- [ ] **Step 6: Insert the section**
1530
1531In `OrgstarApp.swift`'s `appearance` form, after `ThemePickerSection()`:
1532
1533```swift
1534            AppIconSection()
1535```
1536
1537The Appearance tab's `.frame(height: 380)` is now too short; change it to `.frame(height: 620)` and check it scrolls rather than clips.
1538
1539- [ ] **Step 7: Check by hand**
1540
1541Run: `scripts/check-file-sizes.sh && scripts/build-app.sh`, open the app, Settings ▸ Appearance ▸ App Icon ▸ Unicorn Night.
1542Expected: the Dock icon changes at once; switching the system appearance swaps the light and dark previews while running; Default restores the bundle's icon (its dark and tinted styles included); after quitting and reopening, the chosen icon comes back once the app has launched.
1543
1544- [ ] **Step 8: Commit**
1545
1546```bash
1547git add Sources/Orgstar Sources/OrgPresentation/AppIcons.swift Tests/OrgPresentationTests/PaletteTests.swift
1548git commit -m "App icon picker in Settings ▸ Appearance; Dock icon follows the appearance"
1549```
1550
1551---
1552
1553### Task 11: Manual and strings
1554
1555**Files:**
1556- Modify: `docs/manual/guide/02-the-editor.org:33,341`
1557- Modify: `docs/manual/guide/13-configuration.org` (the theme section)
1558- Modify: `docs/manual/guide/14-ios.org:83,398`
1559- Modify: `l10n/Localizable.xcstrings`
1560
1561- [ ] **Step 1: Manual**
1562
1563`02-the-editor.org:341`, replace the paragraph with:
1564
1565```org
1566Settings ▸ Appearance ▸ Theme chooses a built-in theme for the light appearance and one for the dark: Default, Solarized Light, Gruvbox Light, Modus Operandi, Catppuccin Latte, Tomorrow or Paper; and Default, Solarized Dark, Gruvbox Dark, Modus Vivendi, Catppuccin Mocha, Nord, Dracula, Tokyo Night or doom-one. They are =light-theme= and =dark-theme= under =[theme]= in =config.toml=. Colours set in =config.toml=, under =[theme]= for both appearances, =[theme.light]= and =[theme.dark]= for one and =[theme.todo]= for TODO keywords, apply on top, as do those of a theme file named by =theme-file=. Copy to Config Folder writes the two chosen themes, every colour, into =my-theme.toml= and makes it the theme file, to start a theme of your own. Show Default Theme opens =default-theme.toml=, which lists every colour with its default value. Changes apply while orgstar runs. See [[file:13-configuration.org][Configuration]].
1567
1568Settings ▸ Appearance ▸ App Icon chooses the icon the Dock shows while orgstar runs. Finder, and the Dock once orgstar has quit, show the default icon; it follows the system's icon style (Default, Dark or Tinted).
1569```
1570
1571`13-configuration.org`: in the section on themes, add `light-theme`, `dark-theme` and `accent` with the stacking order "the chosen palettes, then the theme file, then =config.toml=". Read the section first and match its table or list form.
1572
1573`14-ios.org:83`, replace "stacked as on the Mac: the default theme, then the theme file" with "stacked as on the Mac: the themes chosen with =light-theme= and =dark-theme=, then the theme file". After that paragraph add:
1574
1575```org
1576Settings ▸ Light Theme and Dark Theme choose the built-in themes, shown as a few lines of Org in each theme's colours; the choice is written to the configuration folder's =config.toml=, so the Mac uses it too. Settings ▸ App Icon chooses the home screen icon from the same thirteen as the Mac; iOS confirms the change. The icon is chosen per device.
1577```
1578
1579`14-ios.org:398`: replace "the theme (=Default=, or the theme file's name)" with "the light and dark themes, and the theme file's name when there is one".
1580
1581- [ ] **Step 2: Strings**
1582
1583Run: `scripts/sync-strings.sh`
1584Then add German translations in `l10n/Localizable.xcstrings` for each new key (as commit 880a7cf did for the October 13 strings): Theme → Design, Light → Hell, Dark → Dunkel, Light Theme → Helles Design, Dark Theme → Dunkles Design, App Icon → App-Symbol, Starting point → Ausgangspunkt, Copy to Config Folder → In den Konfigurationsordner kopieren, and the footers and messages in full sentences. Palette and icon names stay untranslated.
1585
1586- [ ] **Step 3: Check**
1587
1588Run: `swift test && scripts/check-file-sizes.sh && scripts/build-app.sh`
1589Open Settings with the system language set to German and check the new rows.
1590Expected: all green; German labels show.
1591
1592- [ ] **Step 4: Commit**
1593
1594```bash
1595git add docs/manual l10n
1596git commit -m "Manual and German strings for themes and app icons"
1597```
1598
1599---
1600
1601### Finish
1602
1603- [ ] Run `swift test`, `scripts/check-file-sizes.sh`, `scripts/build-app.sh` and the iOS Xcode build once more.
1604- [ ] Push the branch and open the merge request: `git push -u origin themes-and-icons && gitbay mr create --source themes-and-icons --target main --title "Built-in themes and alternate app icons"`.