Cotton code
450 lines · 20.3 KB · RustRaw
//! `ink.*` — the ink above the fan, read in the core (owner, 5 Nov 2026: the//! core answers what to show, a platform shell only draws). The shell draws//! the strokes, runs the letter model (Core ML on iOS, TFLite on Android) and//! draws what comes back; 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 all `cotton_core::ink`'s.//!//! - `ink.knobs {}` → what the shell draws and gestures with: `{flavours,//!   tap_travel, hold_seconds, ink_width, ink_fade_seconds, doubtful_ink,//!   provisional_ink, keep_groups, samples, classes}`.//! - `ink.stroke {surface, stroke: {points: [[x, y, t]], down, up}, height?,//!   table?, pick?, admits?, narrows?, context: {screen: [w, h], on_card,//!   tool?, view?, tier}}` → a reading (below). `t`, `down` and `up` are seconds on one//!   clock; `height` the page a lone upright line is measured against;//!   `table` the deck's table (what it admits by its columns), `pick` true//!   for a record pick of that table (its title alone); with no table,//!   `admits` ([letter, digit], both when absent) says it outright (a corpus//!   replay reads a letter among letters); `narrows` false when//!   the letters are held (a card opened in place): marks and lines still//!   read, the letters stay as they are.//! - `ink.read {surface, reads: [{key, probabilities: [62]}]}` → a reading://!   the model's answers for what the last reading asked; the call it//!   answers goes on.//! - `ink.due {surface, now}` → a reading: the wait (`wait_ms`) is over and//!   the letter in progress is read as it stands.//! - `ink.edit {surface, edit: backspace|clear}` → `{letters, doubted}`: the//!   readout's tap and hold.//! - `ink.contest {surface, contest, from, to}` → `{step}`, `{ink: true}` or//!   `{}`: on a surface that scrolls under the finger (`ink::contest`, the//!   knobs in `ink.knobs`' `surfaces`), a stroke that never bent, read at//!   the lift: a step to the next or previous chat, the ink's after all (it//!   edits the letters: hand it to `ink.stroke`), or nothing. Asked with//!   `{box: [w, h], travel}` in place of `from` and `to`, mid-stroke →//!   `{claims}`: whether the stroke so far is the ink's (it bent, or a wide//!   one turned back on itself), so no shell holds the rule (Android asks it//!   as the finger moves; the iPhone still reads its twin, `InkContest`).//! - `ink.drop {surface}` → `{letters, doubted}`: the letter in progress let//!   go unread (the ground gone), the letters kept.//! - `ink.clear {surface}` → `{letters, doubted}`: everything let go (another//!   view, another pick step).//!//! A READING is either `{asks: [{key, points: [[x, y, pen_up] × 64],//! strokes}]}` — run the model on each and answer `ink.read` — or the//! outcome: `{stroke?, groups: [{strokes, runs, shows, line}], writing,//! provisional, wait_ms, letters, doubted}`. `stroke` is the id an//! `ink.stroke` gave its stroke; a group's `strokes` and a run's are those//! ids; a run is `{strokes, read: letter|doubtful|clear|line|mark|nothing,//! letter?, score?, from?, to?, mark?, edit?, step?}` (`edit` when it took a letter//! back or cleared them; `step` a level line that edited none, run past//! `page_swipe`: the deck's next card, 1, or the one before, -1); `shows` says its ink stays a moment and fades;//! `line` is the corpus line to keep (`ink::captured`), newline included;//! `writing` the ids of the letter in progress, drawn as written;//! `provisional` its letters as they read now, drawn lighter; `wait_ms` when//! to call `ink.due`, null with nothing in progress.//!//! The state lives here, keyed by surface; the model's answers are kept for//! the letter in progress, so a group is asked once.use std::collections::HashMap;use std::sync::{LazyLock, Mutex};use serde_json::{json, Map, Value};use cotton_core::ink::captured::{Captured, Context};use cotton_core::ink::contest::Lifted;use cotton_core::ink::letters::{Edit, Letters};use cotton_core::ink::stream::{GroupRead, Stream, TimedStroke};use cotton_core::ink::{self, input, Admits, Features, Model, Point, Reader, Reading};use super::MethodError;use crate::handle::CottonHandle;/// How many surfaces are held; the one least lately written on goes.const SURFACES: usize = 32;/// One surface written on: a deck, a pick.struct Surface {    stream: Stream,    letters: Letters,    /// The model's answers for the letter in progress, by group key.    answers: HashMap<String, Vec<f64>>,    /// The call waiting on the model's answers.    pending: Option<Pending>,    /// The strokes lifted and not yet read, by id, and whether each began on    /// the card's paper.    held: Vec<(u64, TimedStroke, bool)>,    next: u64,    /// The table and kind the admits were read for.    admits_for: Option<(String, bool)>,    used: u64,}#[derive(Clone)]enum Pending {    Lift { id: u64, stroke: TimedStroke, on_card: bool, context: Context, narrows: bool },    Due { now: f64, context: Context, narrows: bool },}impl Surface {    fn new() -> Self {        Self {            stream: Stream::new(Reader::shipped(), None, Admits::EVERY),            letters: Letters::default(),            answers: HashMap::new(),            pending: None,            held: Vec::new(),            next: 1,            admits_for: None,            used: 0,        }    }}static HELD: LazyLock<Mutex<(HashMap<String, Surface>, u64)>> = LazyLock::new(|| Mutex::new((HashMap::new(), 0)));/// The model as the shell has answered it: what it has not read is asked.struct Asking<'a> {    answers: &'a HashMap<String, Vec<f64>>,    asks: Vec<(String, Features)>,}impl Model for Asking<'_> {    fn probabilities(&mut self, features: &Features) -> Option<Vec<f64>> {        let key = features.key();        if let Some(answer) = self.answers.get(&key) {            return Some(answer.clone());        }        if !self.asks.iter().any(|(asked, _)| *asked == key) {            self.asks.push((key, features.clone()));        }        None    }}fn bad(why: impl Into<String>) -> MethodError {    MethodError::new("bad_request", why)}fn surface_name(request: &Value) -> Result<String, MethodError> {    request["surface"].as_str().map(str::trim).filter(|name| !name.is_empty()).map(str::to_string).ok_or_else(|| bad("ink takes a surface"))}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    if method == "ink.knobs" {        return Ok(knobs());    }    let name = surface_name(request)?;    // The admits are read before the lock: a deck's columns are definitions.    let admits = match method {        "ink.stroke" => admits(handle, &name, request)?,        _ => None,    };    let mut held = HELD.lock().map_err(|_| MethodError::new("ink", "the ink's state was poisoned"))?;    let (surfaces, clock) = &mut *held;    *clock += 1;    if !surfaces.contains_key(&name) && surfaces.len() >= SURFACES {        if let Some(oldest) = surfaces.iter().min_by_key(|(_, surface)| surface.used).map(|(name, _)| name.clone()) {            surfaces.remove(&oldest);        }    }    let surface = surfaces.entry(name).or_insert_with(Surface::new);    surface.used = *clock;    match method {        "ink.stroke" => stroke(surface, request, admits),        "ink.read" => read(surface, request),        "ink.due" => due(surface, request),        "ink.contest" => contest(surface, request),        "ink.edit" => {            let edit: Edit = serde_json::from_value(request["edit"].clone()).map_err(|_| bad("edit is backspace or clear"))?;            surface.letters = surface.letters.applying(edit);            Ok(letters(surface))        }        "ink.drop" => {            drop_writing(surface);            Ok(letters(surface))        }        "ink.clear" => {            drop_writing(surface);            surface.letters = Letters::default();            Ok(letters(surface))        }        other => Err(MethodError::new("unknown_method", format!("{other} is no ink method"))),    }}/// The letter in progress let go, and whatever waited on the model.fn drop_writing(surface: &mut Surface) {    surface.stream.group.clear();    surface.pending = None;    surface.held.clear();    surface.answers.clear();}fn knobs() -> Value {    let alphabet = ink::shipped();    let knobs = &alphabet.knobs;    json!({        "flavours": alphabet.flavours,        "tap_travel": knobs.tap_travel,        "hold_seconds": knobs.hold_seconds,        "ink_width": knobs.ink_width,        "ink_fade_seconds": knobs.ink_fade_seconds,        "doubtful_ink": knobs.doubtful_ink,        "provisional_ink": knobs.provisional_ink,        "keep_groups": knobs.keep_groups,        "samples": input::SAMPLES,        "classes": input::CLASSES.to_vec(),        "surfaces": alphabet.surfaces,    })}/// `ink.contest {surface, contest, from: [x, y], to: [x, y]}` →/// `{step: 1 | -1}`, `{ink: true}` or `{}`: a stroke that never bent on a/// contested surface, read at the lift (`ink::contest`); with `{box, travel}`/// the stroke so far → `{claims}`, whether it is the ink's yet.fn contest(surface: &Surface, request: &Value) -> Result<Value, MethodError> {    let name = request["contest"].as_str().unwrap_or_default();    let alphabet = ink::shipped();    let rules = alphabet.surfaces.get(name).ok_or_else(|| bad(format!("no contested surface {name}")))?;    if let Some(size) = request.get("box").filter(|given| !given.is_null()) {        let (Some(width), Some(height)) = (size[0].as_f64(), size[1].as_f64()) else { return Err(bad("box is [width, height]")) };        let travel = request["travel"].as_f64().ok_or_else(|| bad("a stroke so far says its travel"))?;        return Ok(json!({"claims": rules.claims(width, height, travel)}));    }    let point = |end: &str| -> Result<Point, MethodError> {        match (request[end][0].as_f64(), request[end][1].as_f64()) {            (Some(x), Some(y)) => Ok(Point::new(x, y)),            _ => Err(bad(format!("{end} is [x, y]"))),        }    };    Ok(match rules.at_lift(point("from")?, point("to")?, !surface.letters.letters.is_empty(), &alphabet.knobs) {        Lifted::Step(step) => json!({"step": step}),        Lifted::Ink => json!({"ink": true}),        Lifted::Nothing => json!({}),    })}/// What the surface admits: its table's deck, or a pick of its rows; every/// symbol with no table named.fn admits(handle: &CottonHandle, name: &str, request: &Value) -> Result<Option<Admits>, MethodError> {    let Some(table) = request["table"].as_str().filter(|table| !table.is_empty()) else {        return match request.get("admits") {            None | Some(Value::Null) => Ok(Some(Admits::EVERY)),            Some(given) => {                let symbols: Vec<ink::Symbol> = serde_json::from_value(given.clone()).map_err(|_| bad("admits is [letter, digit]"))?;                Ok(Some(Admits::of(&symbols)))            }        };    };    let pick = request["pick"].as_bool().unwrap_or(false);    // Read once per surface and table: the definitions are not read per stroke.    if let Ok(held) = HELD.lock() {        if held.0.get(name).and_then(|surface| surface.admits_for.as_ref()).is_some_and(|(held, was)| held == table && *was == pick) {            return Ok(None);        }    }    let tables = super::shell_deck::definitions(&handle.client())?;    let definition = tables.iter().find(|found| found.id == table).ok_or_else(|| bad(format!("No table {table}")))?;    Ok(Some(if pick { ink::admits::pick(definition, ink::shipped()) } else { ink::admits::deck(definition, ink::shipped()) }))}fn context(request: &Value) -> Context {    let given = &request["context"];    let screen = given["screen"].as_array().map(|size| [size.first().and_then(Value::as_f64).unwrap_or(0.0), size.get(1).and_then(Value::as_f64).unwrap_or(0.0)]);    Context {        screen: screen.unwrap_or([0.0, 0.0]),        on_card: given["on_card"].as_bool().unwrap_or(false),        tool: given["tool"].as_str().map(str::to_string),        view: given["view"].as_str().map(str::to_string),        tier: given["tier"].as_str().unwrap_or("deck").to_string(),        letters: String::new(),    }}fn stroke(surface: &mut Surface, request: &Value, admits: Option<Admits>) -> Result<Value, MethodError> {    if surface.pending.is_some() {        return Err(bad("the model's answers for the last call are still owed (ink.read)"));    }    let given = &request["stroke"];    let raw = given["points"].as_array().ok_or_else(|| bad("a stroke is {points: [[x, y, t]], down, up}"))?;    let mut points = Vec::with_capacity(raw.len());    let mut times = Vec::with_capacity(raw.len());    for point in raw {        let (Some(x), Some(y)) = (point[0].as_f64(), point[1].as_f64()) else { return Err(bad("a point is [x, y, t]")) };        points.push(Point::new(x, y));        times.push(point[2].as_f64().unwrap_or(0.0));    }    if points.is_empty() {        return Err(bad("a stroke has points"));    }    let down = given["down"].as_f64().or(times.first().copied()).unwrap_or(0.0);    let up = given["up"].as_f64().or(times.last().copied()).unwrap_or(down).max(down);    if let Some(admits) = admits {        surface.stream.admits = admits;        surface.admits_for = request["table"].as_str().filter(|table| !table.is_empty()).map(|table| (table.to_string(), request["pick"].as_bool().unwrap_or(false)));    }    surface.stream.height = request["height"].as_f64().filter(|height| *height > 0.0);    let id = surface.next;    surface.next += 1;    let context = context(request);    let on_card = context.on_card;    surface.pending = Some(Pending::Lift { id, stroke: TimedStroke { points, times, down, up }, on_card, context, narrows: request["narrows"].as_bool().unwrap_or(true) });    go_on(surface)}fn read(surface: &mut Surface, request: &Value) -> Result<Value, MethodError> {    if surface.pending.is_none() {        return Err(bad("nothing was asked of the model"));    }    let reads = request["reads"].as_array().ok_or_else(|| bad("reads is [{key, probabilities}]"))?;    for answer in reads {        let key = answer["key"].as_str().ok_or_else(|| bad("a read names its key"))?;        let probabilities: Vec<f64> = answer["probabilities"].as_array().map(|values| values.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();        if probabilities.len() != input::CLASSES.len() {            return Err(bad(format!("the model answers {} probabilities, not {}", input::CLASSES.len(), probabilities.len())));        }        surface.answers.insert(key.to_string(), probabilities);    }    go_on(surface)}fn due(surface: &mut Surface, request: &Value) -> Result<Value, MethodError> {    if surface.pending.is_some() {        return Err(bad("the model's answers for the last call are still owed (ink.read)"));    }    let now = request["now"].as_f64().ok_or_else(|| bad("ink.due takes now"))?;    surface.pending = Some(Pending::Due { now, context: context(request), narrows: request["narrows"].as_bool().unwrap_or(true) });    go_on(surface)}/// The waiting call, tried on a copy of the stream: a group the model has not/// read is asked and nothing moves; read through, the copy is the stream.fn go_on(surface: &mut Surface) -> Result<Value, MethodError> {    let pending = surface.pending.clone().ok_or_else(|| bad("nothing waits"))?;    let mut stream = surface.stream.clone();    let mut model = Asking { answers: &surface.answers, asks: Vec::new() };    let groups = match &pending {        Pending::Lift { stroke, .. } => stream.lift(stroke.clone(), &mut model),        Pending::Due { now, .. } => stream.flush(*now, &mut model),    };    let provisional = stream.reading(&mut model);    let wait = stream.wait(&mut model);    if !model.asks.is_empty() {        let asks: Vec<Value> = model            .asks            .iter()            .map(|(key, features)| json!({"key": key, "points": features.points, "strokes": features.strokes}))            .collect();        return Ok(json!({"asks": asks}));    }    surface.stream = stream;    surface.pending = None;    let (context, narrows, lifted) = match pending {        Pending::Lift { id, stroke, on_card, context, narrows } => {            surface.held.push((id, stroke, on_card));            (context, narrows, Some(id))        }        Pending::Due { context, narrows, .. } => (context, narrows, None),    };    let knobs = &surface.stream.reader.knobs;    let mut said = Vec::new();    for group in &groups {        let ids = take_ids(&mut surface.held, group);        let on_card = ids.first().map(|(_, on_card)| *on_card).unwrap_or(false);        let ids: Vec<u64> = ids.into_iter().map(|(id, _)| id).collect();        let mut runs = Vec::new();        for run in &group.runs {            let mut out = Map::new();            out.insert("strokes".into(), json!(run.strokes.iter().filter_map(|at| ids.get(*at)).collect::<Vec<_>>()));            out.insert("read".into(), json!(run.reading.name()));            match &run.reading {                Reading::Letter { letter, score } | Reading::Doubtful { letter, score } => {                    out.insert("letter".into(), json!(letter));                    out.insert("score".into(), json!(score));                    if narrows {                        surface.letters = surface.letters.adding(letter, matches!(run.reading, Reading::Doubtful { .. }));                    }                }                Reading::Clear => {                    if narrows {                        surface.letters = Letters::default();                        out.insert("edit".into(), json!("clear"));                    }                }                Reading::Line { from, to } => {                    out.insert("from".into(), json!([from.x, from.y]));                    out.insert("to".into(), json!([to.x, to.y]));                    if let Some(edit) = narrows.then(|| surface.letters.edit_by_line(*from, *to, knobs)).flatten() {                        surface.letters = surface.letters.applying(edit);                        out.insert("edit".into(), json!(edit));                    } else if let Some(step) = page_step(*from, *to, knobs) {                        out.insert("step".into(), json!(step));                    }                }                Reading::Mark(name) => {                    out.insert("mark".into(), json!(name));                }                Reading::Nothing => {}            }            runs.push(Value::Object(out));        }        let shows = group.runs.iter().any(|run| matches!(run.reading, Reading::Letter { .. } | Reading::Doubtful { .. } | Reading::Clear | Reading::Mark(_)));        let kept = Context { on_card, letters: surface.letters.letters.clone(), ..context.clone() };        said.push(json!({"strokes": ids, "runs": runs, "shows": shows, "line": Captured::of(group, &kept).line()}));    }    if surface.stream.group.is_empty() {        surface.answers.clear();    }    let writing: Vec<u64> = surface.held.iter().map(|(id, _, _)| *id).collect();    let mut reply = json!({        "groups": said,        "writing": writing,        "provisional": provisional.iter().filter_map(|run| run.reading.letter()).collect::<Vec<_>>(),        "wait_ms": wait.filter(|_| !surface.stream.group.is_empty()).map(|seconds| (seconds * 1000.0).round() as u64),        "letters": surface.letters.letters,        "doubted": surface.letters.doubted,    });    if let Some(id) = lifted {        reply["stroke"] = json!(id);    }    Ok(reply)}/// A level line that edited no letters, as the deck's page swipe: the next/// card (1, leftward) or the one before, once it runs `page_swipe`.fn page_step(from: Point, to: Point, knobs: &ink::Knobs) -> Option<i8> {    let (dx, dy) = (to.x - from.x, to.y - from.y);    (dx.abs() > dy.abs() && dx.abs() > knobs.page_swipe).then_some(if dx < 0.0 { 1 } else { -1 })}/// The ids of a group's strokes, in its order, taken from those held.fn take_ids(held: &mut Vec<(u64, TimedStroke, bool)>, group: &GroupRead) -> Vec<(u64, bool)> {    group        .strokes        .iter()        .filter_map(|stroke| {            let at = held.iter().position(|(_, kept, _)| kept == stroke)?;            let (id, _, on_card) = held.remove(at);            Some((id, on_card))        })        .collect()}fn letters(surface: &Surface) -> Value {    json!({"letters": surface.letters.letters, "doubted": surface.letters.doubted})}#[cfg(test)]#[path = "ink_tests.rs"]mod ink_tests;