//! THE INK (owner, 2 Nov 2026): a letter written with a finger anywhere //! above the fan narrows what is showing by its leading letters; a //! scratch-out clears them; a check acts on the card it is drawn over. The //! reading rules live here, once, for every shell (owner, 5 Nov 2026: the //! core answers what to show, a platform shell only draws): which strokes //! are one letter's and when the letter in progress is read (`stream`), the //! marks read by rule (`marks`), the letter model's input contract //! (`input`, the twin of `scripts/ink/ink_input.py`), how a group of strokes //! is cut into the letters it makes (`reader`), what a surface admits by its //! columns' types (`admits`), the letters written (`letters`) and the line //! the phone keeps of every group read (`captured`). //! //! Pure: points and times in, readings out. The letter model itself is the //! platform's (Core ML on iOS, TFLite on Android): the reader asks it //! through [`Model`], and a model that has not read a group yet answers //! nothing, which the shell's boundary (`cotton-ffi`'s `ink.*`) turns into //! the groups it asks the shell to read. //! //! The knobs are data (`alphabet.json`), never literals. pub mod admits; pub mod captured; pub mod contest; pub mod input; pub mod letters; pub mod marks; pub mod reader; pub mod replay; pub mod stream; #[cfg(test)] pub(crate) mod testing; use std::collections::BTreeMap; use std::sync::LazyLock; use serde::{Deserialize, Serialize}; pub use input::Features; pub use reader::{Model, Reader}; /// A point in the writing's space, in screen points, y down. #[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)] pub struct Point { pub x: f64, pub y: f64, } impl Point { pub fn new(x: f64, y: f64) -> Self { Self { x, y } } } /// A box: its corner and size. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Rect { pub x: f64, pub y: f64, pub width: f64, pub height: f64, } impl Rect { pub fn min_x(&self) -> f64 { self.x } pub fn max_x(&self) -> f64 { self.x + self.width } pub fn min_y(&self) -> f64 { self.y } pub fn max_y(&self) -> f64 { self.y + self.height } pub fn mid_x(&self) -> f64 { self.x + self.width / 2.0 } pub fn mid_y(&self) -> f64 { self.y + self.height / 2.0 } /// Grown by `by` on every side (shrunk when negative). pub fn outset(&self, by: f64) -> Rect { Rect { x: self.x - by, y: self.y - by, width: self.width + 2.0 * by, height: self.height + 2.0 * by } } /// Whether the two boxes overlap, as Core Graphics says it: boxes that /// only share an edge do not. pub fn intersects(&self, other: &Rect) -> bool { self.min_x() < other.max_x() && other.min_x() < self.max_x() && self.min_y() < other.max_y() && other.min_y() < self.max_y() } pub fn contains(&self, point: Point) -> bool { point.x >= self.min_x() && point.x < self.max_x() && point.y >= self.min_y() && point.y < self.max_y() } } /// What a reading is: a letter or a digit. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Symbol { Letter, Digit, } impl Symbol { /// Every symbol: what the model reads with nothing to admit by. pub const EVERY: [Symbol; 2] = [Symbol::Letter, Symbol::Digit]; /// The class of `symbol` as the model names it: a digit 0–9, else a letter. pub fn of(symbol: &str) -> Symbol { if !symbol.is_empty() && symbol.chars().all(|ch| ch.is_ascii_digit()) { Symbol::Digit } else { Symbol::Letter } } } /// What a surface admits: letters, digits, both or neither. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct Admits { pub letters: bool, pub digits: bool, } impl Admits { pub const EVERY: Admits = Admits { letters: true, digits: true }; pub const LETTERS: Admits = Admits { letters: true, digits: false }; pub const DIGITS: Admits = Admits { letters: false, digits: true }; pub fn contains(&self, symbol: Symbol) -> bool { match symbol { Symbol::Letter => self.letters, Symbol::Digit => self.digits, } } pub fn union(self, other: Admits) -> Admits { Admits { letters: self.letters || other.letters, digits: self.digits || other.digits } } pub fn of(symbols: &[Symbol]) -> Admits { symbols.iter().fold(Admits::default(), |held, symbol| match symbol { Symbol::Letter => Admits { letters: true, ..held }, Symbol::Digit => Admits { digits: true, ..held }, }) } /// The symbols, letters first: what the shell is told. pub fn symbols(&self) -> Vec { Symbol::EVERY.into_iter().filter(|symbol| self.contains(*symbol)).collect() } } /// A letter or digit and what it scored. #[derive(Debug, Clone, PartialEq)] pub struct Score { pub letter: String, pub score: f64, } /// What a stroke, or a run of strokes, read as. #[derive(Debug, Clone, PartialEq)] pub enum Reading { /// A letter, lower case, or a digit, and the model's probability for it. Letter { letter: String, score: f64 }, /// A letter the model doubts — its best under `letter_confidence`, at or /// over `letter_floor` — shown lighter and narrowing like any other. Doubtful { letter: String, score: f64 }, /// A scratch-out: the letters written are cleared. Clear, /// A straight line that is no letter, from its first point to its last. Line { from: Point, to: Point }, /// A mark that acts on the card it is drawn over, by its name (`check`). Mark(String), /// No letter: too short, too small, or below `letter_floor`. Nothing, } impl Reading { /// The letter of a letter or a doubtful one. pub fn letter(&self) -> Option<&str> { match self { Reading::Letter { letter, .. } | Reading::Doubtful { letter, .. } => Some(letter), _ => None, } } /// The name the corpus line and the shell give it. pub fn name(&self) -> &str { match self { Reading::Letter { .. } => "letter", Reading::Doubtful { .. } => "doubtful", Reading::Clear => "clear", Reading::Line { .. } => "line", Reading::Mark(_) => "mark", Reading::Nothing => "nothing", } } } /// The marks a table may bind to its acts (`marks` in its definition). pub const CHECK: &str = "check"; /// One letter's worth of a group of strokes: which strokes (their places in /// the group) were read together, what they read as, and the letters next /// best, best first. #[derive(Debug, Clone, PartialEq)] pub struct Run { pub strokes: Vec, pub reading: Reading, pub runners: Vec, } /// The knobs the marks, the model's reading, the grouping and the shell's /// drawing read (`alphabet.json`, its `_` says what each is). #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct Knobs { pub letter_confidence: f64, pub letter_floor: f64, pub doubt_cut: f64, pub read_turns: Vec, pub turn_under: f64, pub shortest: f64, pub smallest: f64, pub dot: f64, pub straightness: f64, pub thin: f64, pub thin_straightness: f64, pub vertical_slope: f64, pub scratch_reversals: i64, pub scratch_travel: f64, pub scratch_tilt: f64, pub scratch_never: i64, pub scratch_flat: f64, pub check_ratio: f64, pub check_straight: f64, pub check_angle: Vec, pub angle_range: f64, pub tap_travel: f64, pub hold_seconds: f64, pub ink_width: f64, pub ink_fade_seconds: f64, pub doubtful_ink: f64, pub provisional_ink: f64, pub pick_rows: i64, pub group_seconds: f64, pub group_near_seconds: f64, pub group_near: f64, pub opens_after: Vec, pub group_overlap: f64, pub group_touch: f64, pub vertical_short: f64, pub most_strokes: usize, pub swipe_at_once: f64, /// A level line that edited no letters is the deck's page swipe once it /// runs this far: `ink.stroke`'s run says its `step`. pub page_swipe: f64, /// A stroke this fast (points a second, on average), its ends /// `flick_chord` of its travel apart and rising no more than /// `flick_level` of its run, is a swipe: the line from its first point /// to its last, never a letter (`marks::flick`). pub flick_speed: f64, pub flick_chord: f64, pub flick_level: f64, pub keep_groups: i64, } /// The shipped alphabet. #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct Alphabet { /// The flavours that read ink. pub flavours: Vec, /// Words a letter never narrows by (`rules::ink_match`). pub stop_words: Vec, /// What a column of each type can hold, by the type's name. pub admits: BTreeMap>, pub knobs: Knobs, /// The surfaces where a stroke is contested with a scroll under the /// finger, by name, and each one's knobs (`contest`). A surface not named /// gives every travelling stroke to the ink. #[serde(default)] pub surfaces: BTreeMap, } impl Alphabet { /// What a column of `type` (the format's name for it) can hold: a type /// not named holds neither. pub fn admits(&self, column_type: &str) -> Admits { Admits::of(self.admits.get(column_type).map(Vec::as_slice).unwrap_or(&[])) } /// The alphabet with some knobs changed (a test's, a corpus sweep's). pub fn with(&self, knobs: &serde_json::Value) -> Result { let mut raw: serde_json::Value = serde_json::from_str(ALPHABET).map_err(|error| error.to_string())?; if let (Some(held), Some(changed)) = (raw["knobs"].as_object_mut(), knobs.as_object()) { for (knob, value) in changed { if !held.contains_key(knob) { return Err(format!("the ink alphabet has no knob {knob}")); } held.insert(knob.clone(), value.clone()); } } serde_json::from_value(raw).map_err(|error| error.to_string()) } } const ALPHABET: &str = include_str!("alphabet.json"); static SHIPPED: LazyLock = LazyLock::new(|| serde_json::from_str(ALPHABET).expect("crates/cotton-core/src/ink/alphabet.json reads as the ink alphabet")); /// The alphabet this build ships. pub fn shipped() -> &'static Alphabet { &SHIPPED } #[cfg(test)] #[path = "ink_tests.rs"] mod ink_tests;