// WRITING ABOVE THE FAN (owner, 2 Nov 2026): wherever a deck or a tier of // choices is showing, a letter written with a finger anywhere above the fan — // the card included — narrows it: no search box, no keyboard shifting the // layout. // // A surface that scrolls under the finger is contested (Messages' stream of // chats, 15 Nov 2026; `InkContest`, the rules the core's `ink::contest`): the // scroll follows the finger from its first move and is never held back; a // stroke is the ink's only once it bends, drawn then from where it began; one // that never bent is read at the lift (a level one steps to the next chat). // No other surface is contested: a deck reads as it always did. // // Who a touch belongs to. The fan's arc, its hub and the deck's discs keep // theirs: the arc and hub stand outside this region, and a stroke begun where // the deck says it is not read (the discs' strip, a Rolodex's knob) is handed // back unread and undrawn. Everywhere else a touch that stays within // `tap_travel` is the card's or the ground's tap, and one held still for // `hold_seconds` before it moves is a hold — never ink. A touch that travels // belongs to the ink from its first move: nothing under it reacts while it // moves (no page turned, no wheel spun), and it is read on lift (the core's `ink::marks` and `ink::reader`) // and handed to the core — a letter, a scratch-out, or a line (a straight // level one is the page swipe it always was, decided now on lift). Strokes // written one after another, soon or near, are one letter's (the core's // `ink::stream`, asked through `InkReader`): // the letter in progress waits for its next stroke and is read when none // comes, or at once when the next letter begins beside it, split into the // letters it makes (A with its bar, E, F, H, K, T, X); at every lift it is // handed up as it reads so far (the reply's `provisional`), so the pill shows it with // no wait (owner, 3 Nov 2026: "a bit of a lag … I guess that is // unavoidable"); // a long level line swipes at once. When to read the letter in progress is // the core's too (`wait_ms`). While a letter is in progress a tap is // no tap: an i's dot never steps the deck. Every group read is kept on the // phone (`InkCapture`, the line the core wrote), never synced. A face with pages of its own hands // its turn up for that swipe (`deckReadsStrokes`, `facePages`): the deck says // so to its front card's face alone, never to what that card opens over the // page. // // The ink is a plain stroke in the writing's ink on that ground, as wide as // the alphabet says, with round caps — and where it crosses the light record // card, in the card's own ink, the theme's print on its paper (owner, 2 Nov // 2026: a cream stroke on a dark ground was pale on the card); a letter or a scratch-out read stays // a moment and fades. Nothing moves when it appears. Under VoiceOver it is // not there at all (the search disc is), and a flavour the alphabet does not // name never has it (`InkGate`). import CottonKit import SwiftUI /// A letter or mark read, as the stroke it is on the ground: its strokes' /// points joined, and what the core read it as. struct InkStroke { let points: [CGPoint] let run: InkReply.Run } /// A group of strokes the core read, handed up to be acted on — each letter /// or mark in turn (`strokes`) — and the line the phone keeps of it. struct InkGroup { let strokes: [InkStroke] let line: String } /// What one call to the core came to: the groups read, the letter in /// progress as it reads now, and the letters after them, on `surface`. struct InkAnswer { let surface: InkSurface let groups: [InkGroup] let provisional: [String] let letters: InkLetters } extension View { /// The region above the fan a finger writes on, while `owns`: every /// travelling stroke is read by the core on `surface` when `reads` its /// first point (in this view's space), what it came to handed to /// `answered`; a stroke begun elsewhere is handed to `unread` as it was /// drawn. `ink` is the writing's colour on this ground, and over `card` /// the card's. func inkWriting(_ owns: Bool, ink: Color, card: InkCard? = nil, surface: InkSurface, reads: @escaping (CGPoint) -> Bool, contest: InkContest? = nil, answered: @escaping (InkAnswer) -> Void, unread: @escaping ([CGPoint]) -> Void) -> some View { modifier(InkWriting(owns: owns, inks: InkInks(ground: ink, card: card), surface: surface, reads: reads, contest: contest, answered: answered, unread: unread)) } } /// A surface that scrolls under the finger: who a stroke begun over the /// scroll belongs to. The rules are the core's (`ink::contest`): its knobs by /// the surface's name in `ink.knobs`' `surfaces`, and `ink.contest` for the /// stroke that never bent. struct InkContest { /// The surface's name in the alphabet. let name: String /// Whether a stroke begun here is contested: it began over what scrolls. let contested: (CGPoint) -> Bool /// The ink took the ground (a stroke bent, a letter is in progress), or /// gave it back: the scroll stands down and goes back where it was. let holds: (Bool) -> Void /// A level stroke read at the lift: the next chat (1) or the one before (-1). let stepped: (Int) -> Void /// The box of `points`: its width and height. static func box(_ points: [CGPoint]) -> CGSize { guard let first = points.first else { return .zero } var low = first, high = first for point in points.dropFirst() { low = CGPoint(x: min(low.x, point.x), y: min(low.y, point.y)) high = CGPoint(x: max(high.x, point.x), y: max(high.y, point.y)) } return CGSize(width: high.x - low.x, height: high.y - low.y) } /// How far `points` travel, point to point. static func travel(_ points: [CGPoint]) -> Double { zip(points, points.dropFirst()).reduce(0) { $0 + hypot($1.1.x - $1.0.x, $1.1.y - $1.0.y) } } } /// Whether ink is read here at all: a flavour the core names, its knobs read, /// and not under VoiceOver. enum InkReads { @MainActor static func here(voiceOver: Bool) -> Bool { InkGate.open && !voiceOver } } /// The light record card the ink may cross: where its paper lies in the /// writing's space (a card may lay more than one sheet), and the ink written /// on that paper. struct InkCard: Equatable { let papers: [CGRect] let ink: Color } /// The inks a stroke is drawn in: the ground's, and over the card the card's. struct InkInks: Equatable { let ground: Color let card: InkCard? /// The ink at `point`. func ink(at point: CGPoint) -> Color { guard let card, card.papers.contains(where: { $0.contains(point) }) else { return ground } return card.ink } /// The card the stroke changes ink over: none when its ink is the ground's. var crossed: InkCard? { guard let card, card.ink != ground, card.papers.contains(where: { !$0.isEmpty }) else { return nil } return card } } private struct InkWriting: ViewModifier { let owns: Bool let inks: InkInks let surface: InkSurface let reads: (CGPoint) -> Bool let contest: InkContest? let answered: (InkAnswer) -> Void let unread: ([CGPoint]) -> Void @Environment(\.cottonCore) private var core @State private var stroke: [CGPoint] = [] /// When each of the stroke's points was laid, and when it came down /// (seconds since 1970, the stream's clock). @State private var times: [Double] = [] @State private var down = 0.0 /// The letter in progress's strokes, by the ids the core gave them. @State private var drawn: [Int: [CGPoint]] = [:] @State private var writing: [Int] = [] /// Strokes lifted whose reading has not come back yet: drawn as written. @State private var lifted: [[CGPoint]] = [] /// The calls to the core, one after another. @State private var queue: Task? @State private var waiting: Task? @State private var lastUp = 0.0 @State private var fading: InkFading? /// This stroke began from a hold: nobody's. @State private var passed = false /// This stroke began where it is not read: handed back unread. @State private var unreadStroke = false /// This stroke began over the scroll and has not bent yet: the scroll's /// so far, undrawn (`InkContest`). @State private var contending = false /// This stroke bent: the ink took it from the scroll. @State private var claimed = false /// The writing's space: kept with each group, and the page's height when /// no card stands in it. @State private var size: CGSize = .zero /// The knobs, while this ground writes: none until the core has served /// them, none while it does not own the ground. private var live: InkKnobs.Values? { owns ? InkKnobs.shared.values : nil } /// The ink holds a contested ground: a stroke it took from the scroll is /// down, or a letter is in progress. private var holding: Bool { claimed || !writing.isEmpty || !lifted.isEmpty } // One view path whether or not the ground writes: the knobs come in after // the deck stands and a search takes the ground back, and a swapped // wrapper would rebuild the whole deck under it. func body(content: Content) -> some View { let knobs = live content // While a letter is in progress a tap is the letter's (an i's // dot), never the card's: it would step or open the deck. .overlay { if knobs != nil, !writing.isEmpty || !lifted.isEmpty { Color.clear.contentShape(Rectangle()).onTapGesture {} } } .background { Color.clear.contentShape(Rectangle()).allowsHitTesting(knobs != nil) } // Beside the card's gestures, not above them: as a high // priority gesture it waited for the taps under it to fail, // and a tap fails only at the lift — no ink drew while it was // written, and a letter's next stroke seemed to come late // (walk, 2 Nov 2026). Nothing under it acts on a stroke: a // tap or hold fails once the finger travels, and every drag // under it stands down while the ink owns the ground (the // card's swipe, the Rolodex's wheel, a face's pages). Without // knobs it stands down, so its travel is never read. .simultaneousGesture(writing(travel: knobs?.tapTravel ?? 0), including: knobs != nil ? .all : .subviews) .overlay { if let knobs { InkDrawn(strokes: writing.compactMap { drawn[$0] } + lifted + (unreadStroke || contending ? [] : [stroke]), fading: fading, inks: inks, knobs: knobs) .allowsHitTesting(false) } } .onGeometryChange(for: CGSize.self) { $0.size } action: { size = $0 } .onChange(of: knobs != nil, initial: true) { wrote, writes in if writes { InkReader.prepare() } else if wrote { drop() } } .onDisappear { if knobs != nil { drop() } } .onChange(of: holding) { _, holds in contest?.holds(holds) } } /// The letter in progress let go: the ground stopped writing, or went. private func drop() { waiting?.cancel() waiting = nil drawn = [:] writing = [] lifted = [] stroke = [] times = [] passed = false unreadStroke = false contending = false claimed = false call("ink.drop", ["surface": surface.name], lifting: false) } /// The page a lone upright line is measured against: the card's paper, /// else the whole writing space. private var pageHeight: Double? { let papers = inks.card?.papers.filter { !$0.isEmpty } ?? [] if let first = papers.first { let paper = papers.dropFirst().reduce(first) { $0.union($1) } if paper.height > 0 { return paper.height } } return size.height > 0 ? size.height : nil } /// The touch now down rested past the hold before it moved: a hold, not /// ink. Read from the window's one finger watcher (`FingerTravel`), not a /// gesture of its own: a long press riding beside the drag held every /// change back to the lift, so nothing drew while it was written. private func heldFirst(_ knobs: InkKnobs.Values) -> Bool { let finger = FingerTravel.shared guard let down = finger.downAt, let moved = finger.travelledAt else { return false } return moved.timeIntervalSince(down) >= knobs.holdSeconds } private func writing(travel: Double) -> some Gesture { DragGesture(minimumDistance: travel, coordinateSpace: .local) .onChanged { value in guard let knobs = live else { return } if stroke.isEmpty, !passed, !unreadStroke { if heldFirst(knobs) { passed = true } else if !reads(value.startLocation) { unreadStroke = true } // Over the scroll, with no letter in progress, the stroke // is the scroll's until it bends. else if let contest, knobs.surfaces?[contest.name] != nil, !holding, contest.contested(value.startLocation) { contending = true } } guard !passed else { return } if stroke.isEmpty { down = (FingerTravel.shared.downAt ?? value.time).timeIntervalSince1970 stroke = [value.startLocation] times = [down] } stroke.append(value.location) // When the change reached the ground: a simulator's // synthesised touches carry no times of their own (walk, // 3 Nov 2026), and the wait is measured on this clock too. times.append(max(down, Date.now.timeIntervalSince1970)) if contending, let contest, let rules = knobs.surfaces?[contest.name], rules.claims(InkContest.box(stroke), travel: InkContest.travel(stroke)) { contending = false claimed = true } } .onEnded { _ in let points = stroke, laid = times, touched = down let wasPassed = passed, wasUnread = unreadStroke, wasContending = contending stroke = [] times = [] passed = false unreadStroke = false contending = false guard !wasPassed, !points.isEmpty else { return claimed = false } guard !wasUnread else { return unread(points) } if wasContending, let contest { return liftUnbent(points, laid: laid, touched: touched, in: contest) } lift(points, laid: laid, touched: touched) } } /// A stroke that never bent, read at the lift by the core: a step, the /// ink's after all (it edits the letters written), or the scroll's. private func liftUnbent(_ points: [CGPoint], laid: [Double], touched: Double, in contest: InkContest) { guard let core, let first = points.first, let last = points.last else { return } struct Ask: Encodable, Sendable { let surface: String, contest: String, from: [Double], to: [Double] } struct Lifted: Decodable, Sendable { var step: Int?; var ink: Bool? } let ask = Ask(surface: surface.name, contest: contest.name, from: [first.x, first.y], to: [last.x, last.y]) let before = queue Task { @MainActor in await before?.value guard let lifted = try? await core.call("ink.contest", ask, as: Lifted.self) else { return } if let step = lifted.step { contest.stepped(step) } else if lifted.ink == true { lift(points, laid: laid, touched: touched) } } } /// A stroke of the ink's lifted: handed to the core to read. private func lift(_ points: [CGPoint], laid: [Double], touched: Double) { waiting?.cancel() waiting = nil let up = max(touched, Date.now.timeIntervalSince1970) lastUp = up lifted.append(points) claimed = false let onCard = inks.card?.papers.contains { $0.contains(points[0]) } ?? false var request: [String: Any] = [ "surface": surface.name, "stroke": ["points": zip(points, laid).map { [Double($0.x), Double($0.y), $1] }, "down": touched, "up": up], "pick": surface.pick, "narrows": surface.narrows, "context": context(onCard: onCard), ] if let table = surface.table { request["table"] = table } if let height = pageHeight { request["height"] = height } call("ink.stroke", request, lifting: true) } /// Where the ink is, for the line the phone keeps. private func context(onCard: Bool) -> [String: Any] { var context: [String: Any] = ["screen": [Double(size.width), Double(size.height)], "on_card": onCard, "tier": surface.tier] if let tool = surface.tool { context["tool"] = tool } if let view = surface.view { context["view"] = view } return context } /// `method` asked of the core after every call before it; what it comes /// to drawn and handed up. `lifting`: it reads the stroke lifted first. private func call(_ method: String, _ request: [String: Any], lifting: Bool) { let before = queue let surface = surface let json: String do { json = try InkReader.body(request) } catch { print("ink: \(method) did not encode — \(error)") return } queue = Task { @MainActor in await before?.value guard let core else { return } do { let reply = try await InkReader.read(core, method, surface: surface.name, json: json) take(reply, on: surface, lifting: lifting) } catch { if lifting, !lifted.isEmpty { lifted.removeFirst() } print("ink: \(error)") } } } /// A reading drawn: the stroke it read given its id, the groups read /// handed up (and the ink of a letter, a scratch-out or a check left to /// fade), the letter in progress drawn as written, its wait set. private func take(_ reply: InkReply, on surface: InkSurface, lifting: Bool) { if lifting, !lifted.isEmpty { let points = lifted.removeFirst() if let id = reply.stroke { drawn[id] = points } } let groups = reply.groups.map { group in if group.shows { fading = InkFading(strokes: group.strokes.compactMap { drawn[$0] }) } return InkGroup(strokes: group.runs.map { run in InkStroke(points: run.strokes.flatMap { drawn[$0] ?? [] }, run: run) }, line: group.line) } writing = reply.writing drawn = drawn.filter { writing.contains($0.key) } answered(InkAnswer(surface: surface, groups: groups, provisional: reply.provisional, letters: reply.written)) wait(reply.waitMs, on: surface) } /// The letter in progress read when its wait runs out — the core's wait, /// from the last lift. A finger that came down within the wait and is /// still down may be writing the next stroke: wait on for it. private func wait(_ ms: Int?, on surface: InkSurface) { waiting?.cancel() waiting = nil guard let ms else { return } let due = lastUp + Double(ms) / 1000 waiting = Task { @MainActor in var first = true repeat { let left = first ? max(0, due - Date.now.timeIntervalSince1970) : Double(ms) / 1000 first = false try? await Task.sleep(for: .seconds(left)) if Task.isCancelled { return } } while FingerTravel.shared.isDown && (FingerTravel.shared.downAt?.timeIntervalSince1970 ?? 0) > lastUp waiting = nil call("ink.due", ["surface": surface.name, "now": Date.now.timeIntervalSince1970, "narrows": surface.narrows, "context": context(onCard: false)], lifting: false) } } } /// Strokes read and fading. struct InkFading: Equatable { let strokes: [[CGPoint]] let id = UUID() } /// The strokes as they are written, and the last ones read as they fade. private struct InkDrawn: View { let strokes: [[CGPoint]] let fading: InkFading? let inks: InkInks let knobs: InkKnobs.Values var body: some View { ZStack { InkStroked(strokes: strokes, inks: inks, width: knobs.inkWidth) if let fading { InkFadingLine(strokes: fading.strokes, inks: inks, knobs: knobs).id(fading.id) } } .accessibilityHidden(true) } } /// Strokes in the ground's ink, and where they cross the card in the card's. private struct InkStroked: View { let strokes: [[CGPoint]] let inks: InkInks let width: Double var body: some View { let path = InkLine.path(strokes) let style = InkLine.style(width) if let card = inks.crossed { ZStack { path.stroke(inks.ground, style: style) .mask { Rectangle() .overlay { InkLine.papers(card.papers).blendMode(.destinationOut) } .compositingGroup() } path.stroke(card.ink, style: style) .mask { InkLine.papers(card.papers) } } } else { path.stroke(inks.ground, style: style) } } } /// Strokes read: drawn as they were, then gone over the alphabet's fade. private struct InkFadingLine: View { let strokes: [[CGPoint]] let inks: InkInks let knobs: InkKnobs.Values @State private var faded = false var body: some View { InkStroked(strokes: strokes, inks: inks, width: knobs.inkWidth) .opacity(faded ? 0 : 1) .onAppear { withAnimation(.easeOut(duration: knobs.inkFadeSeconds)) { faded = true } } } } private enum InkLine { static func style(_ width: Double) -> StrokeStyle { StrokeStyle(lineWidth: width, lineCap: .round, lineJoin: .round) } /// The card's papers, filled: where the stroke is in the card's ink. static func papers(_ papers: [CGRect]) -> some View { ZStack { ForEach(papers.indices, id: \.self) { Path(papers[$0]).fill(Color.black) } } } static func path(_ strokes: [[CGPoint]]) -> Path { Path { path in for stroke in strokes { guard let first = stroke.first else { continue } path.move(to: first) for point in stroke.dropFirst() { path.addLine(to: point) } } } } } /// Where the ink is read: this build's flavour must be one the core's /// alphabet names (Cotton and Books, owner, 2 and 4 Nov 2026) — Rigby and the /// business apps build it and never turn it on. enum InkGate { static func opens(flavour: String?, flavours: [String]) -> Bool { guard let flavour else { return false } return flavours.contains(flavour) } @MainActor static var open: Bool { opens(flavour: FlavourManifest.current?.flavour, flavours: InkKnobs.shared.values?.flavours ?? []) } }