Cotton code
377 lines · 17.0 KB · SwiftRaw
// 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)import CottonKitimport Foundationimport SwiftUIimport UIKitstruct LookAnswer: Codable, Equatable, Sendable {    struct Paper: Codable, Equatable, Sendable, Identifiable {        var id: String        var name: String        var light: [String: String]        var dark: [String: String]    }    struct Ink: Codable, Equatable, Sendable, Identifiable {        var id: String        var name: String        var light: String        var dark: String    }    struct Face: Codable, Equatable, Sendable, Identifiable {        var id: String        var name: String        var family: String    }    struct Size: Codable, Equatable, Sendable {        var value: Double        var label: String    }    struct Defaults: Codable, Equatable, Sendable {        var light: String        var dark: String        var ink: String        var face: String        var size: Double    }    struct Colours: 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.    struct Preview: Codable, Equatable, Sendable {        struct Row: Codable, Equatable, Sendable { var time: String; var title: String; var task: Bool? }        struct Bubble: Codable, Equatable, Sendable { var mine: Bool; var text: String }        struct Line: 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.        struct Secret: Codable, Equatable, Sendable { var title: String; var line: String; var mono: Bool; var holds: [String] }        /// Secrets' one revealed value, with its Copy.        struct Shown: 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.        struct Mail: 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.        struct Letter: 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.        struct Site: Codable, Equatable, Sendable { var letter: String; var label: String; var line: String; var stay: Bool? }        struct Bar: 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).        struct DataLine: 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).        struct Field: 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?        private enum Keys: String, CodingKey { case day, rows, name, bubbles, lines, secrets, shown, bar }        init(from decoder: Decoder) throws {            if let text = try? decoder.singleValueContainer().decode(String.self) {                self.text = text                return            }            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 {            if let text {                var one = encoder.singleValueContainer()                try one.encode(text)                return            }            var c = encoder.container(keyedBy: Keys.self)            try c.encodeIfPresent(day, forKey: .day)            if let mail { try c.encode(mail, forKey: .rows) } else if let rows { try c.encode(rows, forKey: .rows) } else if let 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)            if let letter { try c.encode(letter, forKey: .shown) } else if let field { try c.encode(field, forKey: .shown) } else { try c.encodeIfPresent(shown, forKey: .shown) }        }    }    var app: String    var light: String    var dark: String    var ink: String    var face: String    var size: Double    var sizesAre: String    var defaults: Defaults    var isDefault: Bool    var papers: [Paper]    var inks: [Ink]    var faces: [Face]    var sizes: [Size]    var colours: Colours    var 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.    struct Lines: 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: String    var preview: Preview?    var words: [String: String]    enum CodingKeys: String, CodingKey {        case app, light, dark, ink, face, size, defaults, papers, inks, faces, sizes, colours, line, lines, preview, words        case 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)) }    }    static func ui(_ hex: String) -> UIColor {        var digits = hex.trimmingCharacters(in: .whitespaces)        if digits.hasPrefix("#") { digits.removeFirst() }        var value: UInt64 = 0        Scanner(string: digits).scanHexInt64(&value)        let alpha = digits.count == 8 ? CGFloat(value & 0xFF) / 255 : 1        let rgb = digits.count == 8 ? value >> 8 : value        return 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`).enum LookFaces {    /// The core's id for the app's own face.    static let own = "own"    static func 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@Observablefinal class LookModel {    private static var models: [String: LookModel] = [:]    /// The one model for `app` (notes, days, messages, story, keys) in this process.    static func standing(_ app: String) -> LookModel {        if let model = models[app] { return model }        let model = LookModel(app: app)        models[app] = model        return model    }    let app: String    private(set) var answer: LookAnswer?    /// What a refused write said, for the app's own toast.    var refused: String?    private init(app: String) {        self.app = app        if let data = UserDefaults.standard.data(forKey: key), let kept = try? JSONDecoder().decode(LookAnswer.self, from: data) {            answer = kept        }    }    private var key: String { "look.answer.\(app)" }    private struct Ask: Encodable, Sendable {        var app: String        var 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 {        case let .paper(id, dark):            if dark { guard id != answer?.dark else { return }; ask.dark = id } else { guard id != answer?.light else { return }; ask.light = id }        case let .ink(id):            guard id != answer?.ink else { return }            ask.ink = id        case let .face(id):            guard id != answer?.face else { return }            ask.face = id        case let .size(size):            guard size != answer?.size else { return }            ask.size = size        }        await send(core, ask)        if case .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 {        guard let answer else { return }        let d = answer.defaults        var 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 != nil else { return }        await send(core, ask)    }    private func send(_ core: (any CottonCalling)?, _ ask: Ask) async {        guard let 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.        if UserDefaults.standard.bool(forKey: "look-served-before") {            _ = try? await core.callJSON("developer.lookServedBefore")        }        #endif        do {            let read = try await core.call(CottonMethod.look, ask, as: LookAnswer.self)            answer = read            if let 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@Observablefinal class LookAppearance {    static let shared = LookAppearance()    private(set) var systemDark = UIScreen.main.traitCollection.userInterfaceStyle == .dark    @ObservationIgnored private var watched: ObjectIdentifier?    @ObservationIgnored private var 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]) { [weak self] (scene: UIWindowScene, _: UITraitCollection) in            self?.systemDark = scene.traitCollection.userInterfaceStyle == .dark        }    }}extension LookModel {    /// 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]? {        guard let answer else { return nil }        return LookAppearance.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 {        if let hex = tokens?[token] { return Color(uiColor: LookAnswer.ui(hex)) }        return Color(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 {        guard let hex = tokens?["ground"] ?? tokens?["sheet"] else { return true }        var white: CGFloat = 0        LookAnswer.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.struct LookStanding: ViewModifier {    let model: LookModel    func body(content: Content) -> some View {        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.private struct LookSceneProbe: UIViewRepresentable {    final class Probe: UIView {        override func didMoveToWindow() {            super.didMoveToWindow()            if let scene = window?.windowScene { MainActor.assumeIsolated { LookAppearance.shared.watch(scene) } }        }    }    func makeUIView(context: Context) -> Probe { Probe() }    func updateUIView(_ view: Probe, context: Context) {}}extension View {    /// The app's standing look on this screen (`LookStanding`).    func lookStanding(_ model: LookModel) -> some View { modifier(LookStanding(model: model)) }}#endif