// LOOK, THE CORE'S ANSWER (shared/DECISIONS.md "Look"; crates/cotton-ffi/src/phone/look.rs): one method for every// app, `look { app, light?, dark?, ink?, face?, size?, reset? }`, answering the papers (each its light and dark half,// in the chosen ink), the inks, the faces, the sizes, what stands, the defaults, the colours every screen of the app// draws, the Settings row's line, the preview and the screen's words. `LookModel` asks it, writes a tap, and keeps// the answer for the app's screens: a screen that reads `LookModel.standing(app)` draws again when it changes.//// Only what differs is written: the core refuses a write that changes nothing ("the patch changes nothing"), so Reset// sends each choice that is not its default rather than `reset: true` (which would write an unchanged dark paper too).#if os(iOS)importCottonKitimportFoundationimportSwiftUIimport UIKitstructLookAnswer: Codable, Equatable, Sendable {structPaper: Codable, Equatable, Sendable, Identifiable {var id: Stringvar name: Stringvar light: [String: String]var dark: [String: String] }structInk: Codable, Equatable, Sendable, Identifiable {var id: Stringvar name: Stringvar light: Stringvar dark: String }structFace: Codable, Equatable, Sendable, Identifiable {var id: Stringvar name: Stringvar family: String }structSize: Codable, Equatable, Sendable {var value: Doublevar label: String }structDefaults: Codable, Equatable, Sendable {var light: Stringvar dark: Stringvar ink: Stringvar face: Stringvar size: Double }structColours: Codable, Equatable, Sendable {var light: [String: String]var dark: [String: String] }/// The app's sample, as the look set says it: Words' a note's text; Days' a day's rows; Comms' a few bubbles;/// Story's a few script lines.structPreview: Codable, Equatable, Sendable {structRow: Codable, Equatable, Sendable { var time: String; var title: String; var task: Bool? }structBubble: Codable, Equatable, Sendable { var mine: Bool; var text: String }structLine: Codable, Equatable, Sendable { var kind: String; var text: String }/// Secrets' list row: its name, its second line (a token's tail in the mono face), and who holds it.structSecret: Codable, Equatable, Sendable { var title: String; var line: String; var mono: Bool; var holds: [String] }/// Secrets' one revealed value, with its Copy.structShown: Codable, Equatable, Sendable { var label: String; var value: String; var copy: String }/// Post's inbox row: who, the subject and its line, when, unread, and a person's round face or a machine's square.structMail: Codable, Equatable, Sendable { var from: String; var subject: String; var line: String; var when: String; var unread: Bool; var face: String }/// Post's one open mail, in the reading face.structLetter: Codable, Equatable, Sendable { var from: String; var subject: String; var text: String }/// Sites' list row (its letter, name and second line) and the bar with the thread.structSite: Codable, Equatable, Sendable { var letter: String; var label: String; var line: String; var stay: Bool? }structBar: Codable, Equatable, Sendable { var label: String; var site: String; var thread: Bool? }/// Data's lines: a row line and a table line (`mono`: a table's name and size, in the mono face).structDataLine: Codable, Equatable, Sendable { var title: String; var line: String; var when: String?; var mono: Bool? }/// Data's one field shown: its column as stored, its type, and its value (an amount).structField: Codable, Equatable, Sendable { var column: String; var type: String; var value: String }var text: String?var day: String?var rows: [Row]?var name: String?var bubbles: [Bubble]?var lines: [Line]?var secrets: [Secret]?var shown: Shown?var mail: [Mail]?var letter: Letter?var sites: [Site]?var bar: Bar?var dataRows: [DataLine]?var field: Field?privateenumKeys: String, CodingKey { case day, rows, name, bubbles, lines, secrets, shown, bar }init(from decoder: Decoder) throws {iflet text = try? decoder.singleValueContainer().decode(String.self) {self.text = textreturn }let c = try decoder.container(keyedBy: Keys.self) day = try c.decodeIfPresent(String.self, forKey: .day)// Days' rows, Post's and Sites' share the key: each is read as the shape it is. rows = try? c.decodeIfPresent([Row].self, forKey: .rows) mail = rows == nil ? try? c.decodeIfPresent([Mail].self, forKey: .rows) : nil sites = rows == nil && mail == nil ? try? c.decodeIfPresent([Site].self, forKey: .rows) : nil dataRows = rows == nil && mail == nil && sites == nil ? try? c.decodeIfPresent([DataLine].self, forKey: .rows) : nil bar = try c.decodeIfPresent(Bar.self, forKey: .bar) name = try c.decodeIfPresent(String.self, forKey: .name) bubbles = try c.decodeIfPresent([Bubble].self, forKey: .bubbles) lines = try c.decodeIfPresent([Line].self, forKey: .lines) secrets = try c.decodeIfPresent([Secret].self, forKey: .secrets) shown = try? c.decodeIfPresent(Shown.self, forKey: .shown) letter = shown == nil ? try? c.decodeIfPresent(Letter.self, forKey: .shown) : nil field = shown == nil && letter == nil ? try? c.decodeIfPresent(Field.self, forKey: .shown) : nil }func encode(to encoder: Encoder) throws {iflet text {var one = encoder.singleValueContainer()try one.encode(text)return }var c = encoder.container(keyedBy: Keys.self)try c.encodeIfPresent(day, forKey: .day)iflet mail { try c.encode(mail, forKey: .rows) } elseiflet rows { try c.encode(rows, forKey: .rows) } elseiflet sites { try c.encode(sites, forKey: .rows) } else { try c.encodeIfPresent(dataRows, forKey: .rows) }try c.encodeIfPresent(bar, forKey: .bar)try c.encodeIfPresent(name, forKey: .name)try c.encodeIfPresent(bubbles, forKey: .bubbles)try c.encodeIfPresent(lines, forKey: .lines)try c.encodeIfPresent(secrets, forKey: .secrets)iflet letter { try c.encode(letter, forKey: .shown) } elseiflet field { try c.encode(field, forKey: .shown) } else { try c.encodeIfPresent(shown, forKey: .shown) } } }var app: Stringvar light: Stringvar dark: Stringvar ink: Stringvar face: Stringvar size: Doublevar sizesAre: Stringvar defaults: Defaultsvar isDefault: Boolvar papers: [Paper]var inks: [Ink]var faces: [Face]var sizes: [Size]var colours: Coloursvar line: String/// The row as the screen stands (`lines.light` on a light screen, `lines.dark` on a dark one): the paper on it/// first, and when the other comes. Absent from an older core.structLines: Codable, Equatable, Sendable { var light: String; var dark: String }var lines: Lines?/// The row for the appearance on screen, the plain row when the core gives none.func line(dark: Bool) -> String { lines.map { dark ? $0.dark : $0.light } ?? line }var faceName: Stringvar preview: Preview?var words: [String: String]enumCodingKeys: String, CodingKey {case app, light, dark, ink, face, size, defaults, papers, inks, faces, sizes, colours, line, lines, preview, wordscase sizesAre = "sizes_are"case isDefault = "default"case faceName = "face_name" }func word(_ key: String) -> String { words[key] ?? key }/// The colour `token` in the appearance asked (dark or light), from what the app draws now.func colour(_ token: String, dark: Bool) -> Color? { (dark ? colours.dark : colours.light)[token].map { Color(uiColor: Self.ui($0)) } }staticfunc ui(_ hex: String) -> UIColor {var digits = hex.trimmingCharacters(in: .whitespaces)if digits.hasPrefix("#") { digits.removeFirst() }var value: UInt64 = 0Scanner(string: digits).scanHexInt64(&value)let alpha = digits.count == 8 ? CGFloat(value & 0xFF) / 255 : 1let rgb = digits.count == 8 ? value >> 8 : valuereturn UIColor(red: CGFloat((rgb >> 16) & 0xFF) / 255, green: CGFloat((rgb >> 8) & 0xFF) / 255, blue: CGFloat(rgb & 0xFF) / 255, alpha: alpha) }}/// Look's faces as the phone draws them (`WritingFonts`): `own` is the app's own face, the others the bundled files/// (`assets/fonts/look`).enumLookFaces {/// The core's id for the app's own face.staticlet own = "own"staticfunc drawn(_ id: String, own: String) -> String {switch id {case"serif": "literata"case"typewriter": "courier"case"hyperlegible": "atkinson"case"dyslexic": "opendyslexic"default: own } }}/// One app's look: the core's last answer, asked again on a choice, kept on this phone so the next launch's first frame/// already stands in it (before the core has answered).@MainActor@ObservablefinalclassLookModel {privatestaticvar models: [String: LookModel] = [:]/// The one model for `app` (notes, days, messages, story, keys) in this process.staticfunc standing(_ app: String) -> LookModel {iflet model = models[app] { return model }let model = LookModel(app: app) models[app] = modelreturn model }let app: Stringprivate(set) var answer: LookAnswer?/// What a refused write said, for the app's own toast.var refused: String?privateinit(app: String) {self.app = appiflet data = UserDefaults.standard.data(forKey: key), let kept = try? JSONDecoder().decode(LookAnswer.self, from: data) { answer = kept } }privatevar key: String { "look.answer.\(app)" }privatestructAsk: Encodable, Sendable {var app: Stringvar light: String?var dark: String?var ink: String?var face: String?var size: Double? }/// Reads the look as it stands.func read(_ core: (any CottonCalling)?) async {await send(core, Ask(app: app)) }/// Writes one tap, unless it is what already stands.func choose(_ pick: LookPick, core: (any CottonCalling)?) async {var ask = Ask(app: app)switch pick {caselet .paper(id, dark):if dark { guard id != answer?.dark else { return }; ask.dark = id } else { guard id != answer?.light else { return }; ask.light = id }caselet .ink(id):guard id != answer?.ink else { return } ask.ink = idcaselet .face(id):guard id != answer?.face else { return } ask.face = idcaselet .size(size):guard size != answer?.size else { return } ask.size = size }await send(core, ask)ifcase .ink = pick, let answer { LookIcon.follow(answer.ink, defaultInk: answer.defaults.ink) } }/// Reset to default: each choice that is not its default, written back; the icon back to the primary.func reset(core: (any CottonCalling)?) async {guardlet answer else { return }let d = answer.defaultsvar ask = Ask(app: app)if answer.light != d.light { ask.light = d.light }if answer.dark != d.dark { ask.dark = d.dark }if answer.ink != d.ink { ask.ink = d.ink }if answer.face != d.face { ask.face = d.face }if answer.size != d.size { ask.size = d.size }LookIcon.follow(d.ink, defaultInk: d.ink)guard ask.light != nil || ask.dark != nil || ask.ink != nil || ask.face != nil || ask.size != nilelse { return }await send(core, ask) }privatefunc send(_ core: (any CottonCalling)?, _ ask: Ask) async {guardlet core else { return } #if COTTON_DEV// `-look-served-before YES`: this copy's Look table as a server deployed before Look serves it (no `type_face`),// the owner's live server on 23 Nov 2026, where a face chosen changed nothing.// Before every call: a copy that holds no definition yet (Comms' first frame) takes it before its first write.ifUserDefaults.standard.bool(forKey: "look-served-before") { _ = try? await core.callJSON("developer.lookServedBefore") } #endifdo {let read = tryawait core.call(CottonMethod.look, ask, as: LookAnswer.self) answer = readiflet data = try? JSONEncoder().encode(read) { UserDefaults.standard.set(data, forKey: key) } } catch { refused = ActionRefused.words(for: error)// What was written before a refusal stands: read it back.if ask.light != nil || ask.dark != nil || ask.ink != nil || ask.face != nil || ask.size != nil {await send(core, Ask(app: app)) } } }}#endif#if os(iOS)/// The phone's own appearance, light or dark, whatever an app's screens are set in: read from the window scene,/// which an app's colour scheme does not override, and watched, so an app that draws the paper the person chose for/// the phone's appearance follows it when it changes.@MainActor@ObservablefinalclassLookAppearance {staticlet shared = LookAppearance()private(set) var systemDark = UIScreen.main.traitCollection.userInterfaceStyle == .dark @ObservationIgnored privatevar watched: ObjectIdentifier? @ObservationIgnored privatevar registration: (any UITraitChangeRegistration)?func watch(_ scene: UIWindowScene) {guard watched != ObjectIdentifier(scene) else { return } watched = ObjectIdentifier(scene) systemDark = scene.traitCollection.userInterfaceStyle == .dark registration = scene.registerForTraitChanges([UITraitUserInterfaceStyle.self]) { [weakself] (scene: UIWindowScene, _: UITraitCollection) inself?.systemDark = scene.traitCollection.userInterfaceStyle == .dark } }}extensionLookModel {/// What the app draws now: the chosen paper's half for the phone's appearance, in the chosen ink (nil before the/// core has ever answered on this phone).var tokens: [String: String]? {guardlet answer else { returnnil }returnLookAppearance.shared.systemDark ? answer.colours.dark : answer.colours.light }/// One of the app's colours as it stands, or the app's own value before the core has answered.func colour(_ token: String, _ fallback: UInt32) -> Color {iflet hex = tokens?[token] { returnColor(uiColor: LookAnswer.ui(hex)) }returnColor(uiColor: UIColor(red: CGFloat((fallback >> 16) & 0xFF) / 255, green: CGFloat((fallback >> 8) & 0xFF) / 255, blue: CGFloat(fallback & 0xFF) / 255, alpha: 1)) }/// Whether the standing ground is light: the app's screens, keyboards and bars are set light or dark by it.var groundIsLight: Bool {guardlet hex = tokens?["ground"] ?? tokens?["sheet"] else { returntrue }var white: CGFloat = 0LookAnswer.ui(hex).getWhite(&white, alpha: nil)return white > 0.5 }/// The chosen face (`own`, `serif`, `typewriter`, `hyperlegible`, `dyslexic`).var face: String { answer?.face ?? "own" }/// The chosen size as a share of the app's own sizes (1 before an answer; Words answers points instead).var scale: CGFloat { answer.map { $0.sizesAre == "scale" ? CGFloat($0.size) : 1 } ?? 1 }}/// Sets a screen in its app's standing look: the colour scheme from the standing paper's ground (so a paper light in/// both halves keeps the phone's bars and keyboards light, as before Look), and the phone's appearance watched.structLookStanding: ViewModifier {let model: LookModelfunc body(content: Content) -> someView { content .preferredColorScheme(model.groundIsLight ? .light : .dark) .background(LookSceneProbe().frame(width: 0, height: 0).accessibilityHidden(true)) }}/// Finds the window scene a screen stands in, for `LookAppearance` to watch.privatestructLookSceneProbe: UIViewRepresentable {finalclassProbe: UIView {overridefunc didMoveToWindow() {super.didMoveToWindow()iflet scene = window?.windowScene { MainActor.assumeIsolated { LookAppearance.shared.watch(scene) } } } }func makeUIView(context: Context) -> Probe { Probe() }func updateUIView(_ view: Probe, context: Context) {}}extensionView {/// The app's standing look on this screen (`LookStanding`).func lookStanding(_ model: LookModel) -> someView { modifier(LookStanding(model: model)) }}#endif