//! WHAT THE PHONE KEEPS OF THE INK (owner, 3 Nov 2026: get the letters //! "really right … do a few iterations"): every group of strokes the ink //! reads, as one JSON object on a line of its own, so the owner's own writing //! becomes the corpus the recogniser is measured and tuned against. One //! shape, shared by every lane that writes or reads a corpus: //! //! strokes each stroke's points, [x, y, t]: pt in the writing's space, t //! in ms from the group's first touch //! label the letter meant: null as the phone writes it //! read what the group read as: a letter, `clear`, `line`, a mark by its //! name (`check`) or `nothing`; several letters in one group joined //! by `+` ("s+h"); a letter the model doubted is a letter too (its //! run says `doubtful`); a scratch-out's run says how often it //! turned back (`reversals`) //! score the reading's score (the lowest of its letters'); null for none //! runners the letters next best, [letter, score], where the doubt was //! gaps seconds from each lift to the next stroke's touch //! box the strokes' box, [x, y, width, height] pt //! screen the writing's space, [width, height] pt //! where `card` or `ground`: where the first touch came down //! at the first touch, ISO 8601 with milliseconds //! //! and, beside those, what the phone knows that a replay can use: `lifts` //! (each stroke's touch and lift, ms from the first touch), `height` (the //! page a lone upright line was measured against), `tool`, `view` and //! `tier`, `runs` (each letter or mark in the group, by its strokes) and //! `letters` (the letters written after it). A reader needs only `strokes`. //! //! The core writes the line (`Captured::of`); the shell appends it to the //! phone's file, never synced. use serde::{Deserialize, Serialize}; use super::marks; use super::stream::{GroupRead, TimedStroke}; use super::{Point, Reading}; /// One letter or mark of the group: the strokes it took and what they read as. #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] pub struct CapturedRun { /// A letter the model doubted: shown lighter, narrowing all the same. #[serde(skip_serializing_if = "Option::is_none")] pub doubtful: Option, pub read: String, /// A scratch-out's turns back along its axis (`marks::turns`). #[serde(skip_serializing_if = "Option::is_none")] pub reversals: Option, pub runners: Vec<(String, f64)>, #[serde(skip_serializing_if = "Option::is_none")] pub score: Option, pub strokes: Vec, } /// One kept group, keys in a steady (alphabetical) order. #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] #[serde(default)] pub struct Captured { pub at: String, #[serde(rename = "box")] pub bounds: Vec, pub gaps: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub height: Option, pub label: Option, #[serde(skip_serializing_if = "Option::is_none")] pub letters: Option, #[serde(skip_serializing_if = "Option::is_none")] pub lifts: Option>>, pub read: String, pub runners: Vec<(String, f64)>, #[serde(skip_serializing_if = "Option::is_none")] pub runs: Option>, pub score: Option, pub screen: Vec, pub strokes: Vec>>, #[serde(skip_serializing_if = "Option::is_none")] pub tier: Option, #[serde(skip_serializing_if = "Option::is_none")] pub tool: Option, #[serde(skip_serializing_if = "Option::is_none")] pub view: Option, #[serde(rename = "where")] pub place: String, } /// Where and after what a group was read: what the shell knows of it. #[derive(Debug, Clone, PartialEq, Default)] pub struct Context { /// The writing's space, [width, height] pt. pub screen: [f64; 2], /// Whether the group's first touch was on the card's paper. pub on_card: bool, pub tool: Option, pub view: Option, pub tier: String, /// The letters written after it. pub letters: String, } fn rounded(score: f64) -> f64 { (score * 1000.0).round() / 1000.0 } fn pt(value: f64) -> f64 { (value * 10.0).round() / 10.0 } impl Captured { /// `group` as the phone keeps it. pub fn of(group: &GroupRead, context: &Context) -> Captured { let start = group.strokes.first().map(|stroke| stroke.down).unwrap_or(group.read); let ms = |seconds: f64| ((seconds - start) * 1000.0).round(); let runs: Vec = group .runs .iter() .map(|run| { let runners: Vec<(String, f64)> = run.runners.iter().map(|runner| (runner.letter.clone(), rounded(runner.score))).collect(); let mut kept = CapturedRun { strokes: run.strokes.clone(), runners, ..Default::default() }; match &run.reading { Reading::Letter { letter, score } => { kept.read = letter.clone(); kept.score = Some(rounded(*score)); } Reading::Doubtful { letter, score } => { kept.read = letter.clone(); kept.score = Some(rounded(*score)); kept.doubtful = Some(true); } Reading::Clear => { kept.read = "clear".into(); kept.reversals = run.strokes.iter().filter_map(|at| group.strokes.get(*at)).map(|stroke| marks::turns(&stroke.points).reversals).max(); } Reading::Line { .. } => kept.read = "line".into(), Reading::Mark(name) => kept.read = name.clone(), Reading::Nothing => kept.read = "nothing".into(), } kept }) .collect(); let read = if runs.is_empty() { "nothing".to_string() } else { runs.iter().map(|run| run.read.as_str()).collect::>().join("+") }; let mut doubt: Option<&CapturedRun> = None; for run in runs.iter().filter(|run| run.score.is_some()) { if doubt.is_none_or(|held| run.score < held.score) { doubt = Some(run); } } let doubt = doubt.or(runs.first()); let points: Vec = group.strokes.iter().flat_map(|stroke| stroke.points.iter().copied()).collect(); let held = marks::bounds(&points); Captured { strokes: group .strokes .iter() .map(|stroke| stroke.points.iter().zip(&stroke.times).map(|(point, time)| vec![pt(point.x), pt(point.y), ms(*time)]).collect()) .collect(), label: None, read, score: doubt.and_then(|run| run.score), runners: doubt.map(|run| run.runners.clone()).unwrap_or_default(), gaps: group.strokes.windows(2).map(|pair| ((pair[1].down - pair[0].up) * 1000.0).round() / 1000.0).collect(), bounds: vec![pt(held.x), pt(held.y), pt(held.width), pt(held.height)], screen: vec![pt(context.screen[0]), pt(context.screen[1])], place: if context.on_card { "card" } else { "ground" }.to_string(), at: iso(start), lifts: Some(group.strokes.iter().map(|stroke| vec![ms(stroke.down), ms(stroke.up)]).collect()), height: group.height.map(pt), tool: context.tool.clone(), view: context.view.clone(), tier: Some(context.tier.clone()), runs: Some(runs), letters: Some(context.letters.clone()), } } /// One JSON line, keys in a steady order, its newline included. pub fn line(&self) -> String { let mut line = serde_json::to_string(self).expect("a captured group always serialises"); line.push('\n'); line } /// The strokes as they were written, on the stream's clock (seconds since /// 1970), for a replay: each touch and lift as kept, else its first and /// last point's. A line with no `at` starts at `or_else`. pub fn timed(&self, or_else: f64) -> Vec { let start = seconds(&self.at).unwrap_or(or_else); self.strokes .iter() .enumerate() .map(|(index, points)| { let first = points.first().and_then(|point| point.get(2)).copied().unwrap_or(0.0); let last = points.last().and_then(|point| point.get(2)).copied().unwrap_or(first); let lift = self.lifts.as_ref().and_then(|lifts| lifts.get(index)).filter(|lift| lift.len() == 2).cloned().unwrap_or(vec![first, last]); TimedStroke { points: points.iter().filter(|point| point.len() >= 2).map(|point| Point::new(point[0], point[1])).collect(), times: points.iter().map(|point| start + point.get(2).copied().unwrap_or(0.0) / 1000.0).collect(), down: start + lift[0] / 1000.0, up: start + lift[1] / 1000.0, } }) .collect() } } /// `seconds` since 1970 as ISO 8601 with milliseconds, in UTC. pub fn iso(seconds: f64) -> String { let millis = (seconds * 1000.0).round() as i64; chrono::DateTime::from_timestamp_millis(millis) .map(|time| time.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()) .unwrap_or_default() } /// An ISO 8601 time as seconds since 1970, with or without its fraction; /// None when it is none. pub fn seconds(iso: &str) -> Option { chrono::DateTime::parse_from_rfc3339(iso).ok().map(|time| time.timestamp_millis() as f64 / 1000.0) } #[cfg(test)] #[path = "captured_tests.rs"] mod captured_tests;