// 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`).importCottonKitimportFoundation/// What the core reads a call to: the groups read, the letter in progress,/// the wait, the letters.structInkReply: Decodable, Equatable, Sendable {structAsk: 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.structGroup: Decodable, Equatable, Sendable {let strokes: [Int]let runs: [Run]let shows: Boollet line: String }/// One letter or mark: its strokes by id, what it read as, and what it/// did to the letters (`edit`).structRun: Decodable, Equatable, Sendable {let strokes: [Int]/// letter, doubtful, clear, line, mark or nothing.let read: Stringvar letter: String? = nilvar score: Double? = nilvar from: [Double]? = nilvar to: [Double]? = nilvar mark: String? = nilvar edit: String? = nil }var asks: [Ask]? = nilvar stroke: Int? = nilvar groups: [Group] = []var writing: [Int] = []var provisional: [String] = []var waitMs: Int? = nilvar letters: String = ""var doubted: [Bool] = []enumCodingKeys: String, CodingKey {case asks, stroke, groups, writing, provisional, letters, doubtedcase 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.structInkLetters: 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`).enumInkEdit: 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.structInkSurface: Equatable, Sendable {let name: Stringvar table: String? = nilvar pick = false/// False while the letters are held (a card opened in place).var narrows = truevar tool: String? = nilvar view: String? = nilvar tier = "deck"}enumInkReader {/// A call the core refused, or asks that never ended.enumFailed: 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. @concurrentstaticfunc read(_ core: any CottonCalling, _ method: String, surface: String, json: String, model: InkModel = .shipped) asyncthrows -> InkReply {var reply = tryawait ask(core, method, json: json)var rounds = 0whilelet asks = reply.asks, !asks.isEmpty { rounds += 1guard rounds <= 8else { throwFailed.keptAsking(rounds: rounds) }let reads: [[String: Any]] = asks.map { ask in ["key": ask.key, "probabilities": model.classify(points: ask.points, strokes: ask.strokes)] } reply = tryawait ask(core, "ink.read", json: try body(["surface": surface, "reads": reads])) }return reply }/// A request as the core reads it.staticfunc body(_ request: [String: Any]) throws -> String {String(decoding: try JSONSerialization.data(withJSONObject: request), as: UTF8.self) }/// One call, its answer decoded.staticfunc ask(_ core: any CottonCalling, _ method: String, json: String) asyncthrows -> InkReply {let raw = tryawait core.callRaw(method, requestJSON: json)structEnvelope: Decodable {structRefusal: Decodable { let code: String; let message: String }let ok: Boollet data: InkReply?let error: Refusal? }let envelope = try JSONDecoder().decode(Envelope.self, from: Data(raw.utf8))guard envelope.ok, let data = envelope.data else {throwFailed.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).staticfunc edit(_ core: any CottonCalling, surface: String, _ edit: InkEdit) asyncthrows -> InkLetters {tryawait 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.staticfunc 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 @ObservablefinalclassInkKnobs {structValues: Decodable, Equatable, Sendable {let flavours: [String]let tapTravel: Doublelet holdSeconds: Doublelet inkWidth: Doublelet inkFadeSeconds: Doublelet doubtfulInk: Doublelet provisionalInk: Doublelet 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`).structContest: Decodable, Equatable, Sendable {let bend: Doublelet bendRatio: Doublelet turnBack: DoubleenumCodingKeys: String, CodingKey {case bendcase 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) } }enumCodingKeys: String, CodingKey {case flavours, surfacescase tapTravel = "tap_travel", holdSeconds = "hold_seconds", inkWidth = "ink_width", inkFadeSeconds = "ink_fade_seconds"case doubtfulInk = "doubtful_ink", provisionalInk = "provisional_ink", keepGroups = "keep_groups" } }staticlet shared = InkKnobs()private(set) var values: Values? @ObservationIgnored privatevar loading = false/// The knobs read from `core`, once.func load(_ core: (any CottonCalling)?) async {guard values == nil, !loading, let core else { return } loading = truedefer { loading = false }do { values = tryawait core.call("ink.knobs", as: Values.self) } catch { print("ink: the knobs did not read — \(error)") } }}