Cotton code
232 lines · 9.2 KB · SwiftRaw
// THE INK, READ IN THE CORE (owner, 5 Nov 2026: the core answers what to// show, a platform shell only draws). Which strokes are one letter's, when// the letter in progress is read, the marks, the cut into letters, the// letters written and the line the phone keeps are `cotton_core::ink`'s,// asked through `ink.*` (`cotton-ffi/src/methods/ink.rs`). The shell draws// the strokes, runs the letter model when the core asks (`InkModel`, Core ML;// Android's TFLite answers the same asks) and draws what comes back.//// A call the model must answer comes back as asks: the shell runs the model// on each and answers `ink.read`, until the reading itself comes (`read`).import CottonKitimport Foundation/// What the core reads a call to: the groups read, the letter in progress,/// the wait, the letters.struct InkReply: Decodable, Equatable, Sendable {    struct Ask: Decodable, Equatable, Sendable {        let key: String        /// 64 samples [x, y, pen_up], the model's input.        let points: [[Double]]        let strokes: Double    }    /// A group read: its strokes by id, each letter or mark in it, whether    /// its ink stays a moment, and the line the phone keeps of it.    struct Group: Decodable, Equatable, Sendable {        let strokes: [Int]        let runs: [Run]        let shows: Bool        let line: String    }    /// One letter or mark: its strokes by id, what it read as, and what it    /// did to the letters (`edit`).    struct Run: Decodable, Equatable, Sendable {        let strokes: [Int]        /// letter, doubtful, clear, line, mark or nothing.        let read: String        var letter: String? = nil        var score: Double? = nil        var from: [Double]? = nil        var to: [Double]? = nil        var mark: String? = nil        var edit: String? = nil    }    var asks: [Ask]? = nil    var stroke: Int? = nil    var groups: [Group] = []    var writing: [Int] = []    var provisional: [String] = []    var waitMs: Int? = nil    var letters: String = ""    var doubted: [Bool] = []    enum CodingKeys: String, CodingKey {        case asks, stroke, groups, writing, provisional, letters, doubted        case waitMs = "wait_ms"    }    init(from decoder: Decoder) throws {        let keys = try decoder.container(keyedBy: CodingKeys.self)        asks = try keys.decodeIfPresent([Ask].self, forKey: .asks)        stroke = try keys.decodeIfPresent(Int.self, forKey: .stroke)        groups = try keys.decodeIfPresent([Group].self, forKey: .groups) ?? []        writing = try keys.decodeIfPresent([Int].self, forKey: .writing) ?? []        provisional = try keys.decodeIfPresent([String].self, forKey: .provisional) ?? []        waitMs = try keys.decodeIfPresent(Int.self, forKey: .waitMs)        letters = try keys.decodeIfPresent(String.self, forKey: .letters) ?? ""        doubted = try keys.decodeIfPresent([Bool].self, forKey: .doubted) ?? []    }    /// The letters after it.    var written: InkLetters { InkLetters(letters: letters, doubted: doubted) }}/// The letters written, as the core holds them: drawn by the readout, the/// model's doubted ones lighter.struct InkLetters: Equatable, Sendable, Decodable {    var letters = ""    var doubted: [Bool] = []    var isEmpty: Bool { letters.isEmpty }    /// Whether the letter at `place` was doubted.    func doubts(_ place: Int) -> Bool { doubted.indices.contains(place) && doubted[place] }}/// The readout's two edits: its tap takes the last letter back, its hold/// clears them (`ink.edit`).enum InkEdit: String, Equatable, Sendable {    case backspace, clear}/// What the ink is written on, as the core keys it: the surface, what it/// admits (its table, a pick of its rows), whether the letters move, and/// where it is for the line the phone keeps.struct InkSurface: Equatable, Sendable {    let name: String    var table: String? = nil    var pick = false    /// False while the letters are held (a card opened in place).    var narrows = true    var tool: String? = nil    var view: String? = nil    var tier = "deck"}enum InkReader {    /// A call the core refused, or asks that never ended.    enum Failed: Error, Equatable {        case refused(method: String, code: String, message: String)        case keptAsking(rounds: Int)    }    /// `method` asked of the core for `surface`, the model run on whatever    /// it asks until the reading comes. Off the main thread: the model runs    /// here.    @concurrent    static func read(_ core: any CottonCalling, _ method: String, surface: String, json: String, model: InkModel = .shipped) async throws -> InkReply {        var reply = try await ask(core, method, json: json)        var rounds = 0        while let asks = reply.asks, !asks.isEmpty {            rounds += 1            guard rounds <= 8 else { throw Failed.keptAsking(rounds: rounds) }            let reads: [[String: Any]] = asks.map { ask in                ["key": ask.key, "probabilities": model.classify(points: ask.points, strokes: ask.strokes)]            }            reply = try await ask(core, "ink.read", json: try body(["surface": surface, "reads": reads]))        }        return reply    }    /// A request as the core reads it.    static func body(_ request: [String: Any]) throws -> String {        String(decoding: try JSONSerialization.data(withJSONObject: request), as: UTF8.self)    }    /// One call, its answer decoded.    static func ask(_ core: any CottonCalling, _ method: String, json: String) async throws -> InkReply {        let raw = try await core.callRaw(method, requestJSON: json)        struct Envelope: Decodable {            struct Refusal: Decodable { let code: String; let message: String }            let ok: Bool            let data: InkReply?            let error: Refusal?        }        let envelope = try JSONDecoder().decode(Envelope.self, from: Data(raw.utf8))        guard envelope.ok, let data = envelope.data else {            throw Failed.refused(method: method, code: envelope.error?.code ?? "", message: envelope.error?.message ?? raw)        }        return data    }    /// `edit` made to `surface`'s letters (the readout's tap or hold).    static func edit(_ core: any CottonCalling, surface: String, _ edit: InkEdit) async throws -> InkLetters {        try await ask(core, "ink.edit", json: try body(["surface": surface, "edit": edit.rawValue])).written    }    /// The model compiled and loaded off the main thread before the first    /// letter is written, so no stroke waits for it.    static func prepare() {        DispatchQueue.global(qos: .userInitiated).async { InkModel.shipped.load() }    }}/// What the shell draws and gestures with (`ink.knobs`), read once from the/// core; until it is read no ink is read.@MainActor @Observablefinal class InkKnobs {    struct Values: Decodable, Equatable, Sendable {        let flavours: [String]        let tapTravel: Double        let holdSeconds: Double        let inkWidth: Double        let inkFadeSeconds: Double        let doubtfulInk: Double        let provisionalInk: Double        let keepGroups: Int        /// The surfaces that scroll under the finger, by name, and each        /// one's rules (`InkContest`); none on a core that names none.        var surfaces: [String: Contest]? = nil        /// A contested surface's knobs (the core's `ink::contest::Contest`).        struct Contest: Decodable, Equatable, Sendable {            let bend: Double            let bendRatio: Double            let turnBack: Double            enum CodingKeys: String, CodingKey {                case bend                case bendRatio = "bend_ratio"                case turnBack = "turn_back"            }            /// Whether a stroke whose box is `box` so far, `travel` points            /// along, is the ink's (the core's `Contest::claims`): it has            /// bent, its narrower side `bend` points and `bendRatio` of the            /// longer; or it is wider than tall and has turned back on            /// itself, `turnBack` times its width along (a flat scratch-out).            func claims(_ box: CGSize, travel: Double) -> Bool {                let narrow = min(box.width, box.height), long = max(box.width, box.height)                return (narrow >= bend && narrow >= bendRatio * long)                    || (box.width > box.height && box.width >= bend && travel >= turnBack * box.width)            }        }        enum CodingKeys: String, CodingKey {            case flavours, surfaces            case tapTravel = "tap_travel", holdSeconds = "hold_seconds", inkWidth = "ink_width", inkFadeSeconds = "ink_fade_seconds"            case doubtfulInk = "doubtful_ink", provisionalInk = "provisional_ink", keepGroups = "keep_groups"        }    }    static let shared = InkKnobs()    private(set) var values: Values?    @ObservationIgnored private var loading = false    /// The knobs read from `core`, once.    func load(_ core: (any CottonCalling)?) async {        guard values == nil, !loading, let core else { return }        loading = true        defer { loading = false }        do {            values = try await core.call("ink.knobs", as: Values.self)        } catch {            print("ink: the knobs did not read — \(error)")        }    }}