Cotton code
253 lines · 11.2 KB · RustRaw
//! THE STROKES AS THEY COME (owner, 3 Nov 2026: "lower case upper case the//! timings etc … It works at times and doesn't at times"): which strokes are//! one letter's, decided by when and where each was written, and when the//! letter in progress is read.//!//! A stroke joins the letter in progress when its first touch comes within//! `group_seconds` of the last lift, or within `group_near_seconds` and near//! it (`marks::near`); a stroke later than that, or far and not quick, begins//! the next. A stroke that links to none of the letter in progress's strokes//! (`marks::across`) is the next letter written beside it, and closes it at//! once (owner, 3 Nov 2026: "a bit of a lag between writing a letter and//! that getting filled") — but for two lines, which a later stroke may yet//! join (an H's stems, by its bar). The letter in progress waits//! `group_seconds` after a lift when its last stroke reads as a finished//! letter, and `group_near_seconds` when it may be a longer one begun//! (`Reader::opens`). Meanwhile the shell shows it as it reads now//! (`reading`), provisionally. A scratch-out takes the letter in progress//! with it, at once. A check is a group of its own, read at once: the letter//! in progress before it is read as it stands. A lone level line as long as//! `swipe_at_once` is read at once (the page swipe), and so is a quick//! flick (`marks::flick`), as the line it is however it curls. More strokes than one//! letter takes (`most_strokes`) read the first letter among them and hold//! the rest.use super::marks;use super::reader::{Model, Reader};use super::{Admits, Point, Reading, Run};/// A stroke as it was written: its points, when each was laid (seconds, one/// clock for the whole stream), and when the finger came down and lifted.#[derive(Debug, Clone, PartialEq)]pub struct TimedStroke {    pub points: Vec<Point>,    pub times: Vec<f64>,    pub down: f64,    pub up: f64,}/// Strokes read as one group: the strokes, the letters and marks they made/// (by the strokes' places), when it was read, and the page's height the/// strokes were measured against.#[derive(Debug, Clone, PartialEq)]pub struct GroupRead {    pub strokes: Vec<TimedStroke>,    pub runs: Vec<Run>,    pub read: f64,    pub height: Option<f64>,}/// The letter in progress and how it is read.#[derive(Debug, Clone)]pub struct Stream {    pub reader: Reader,    /// The page's height (`vertical_short`), set by the shell.    pub height: Option<f64>,    /// What the surface written on admits: every letter in progress is read    /// among them.    pub admits: Admits,    /// The strokes of the letter in progress.    pub group: Vec<TimedStroke>,}impl Stream {    pub fn new(reader: Reader, height: Option<f64>, admits: Admits) -> Self {        Self { reader, height, admits, group: Vec::new() }    }    /// How long after the last lift the letter in progress waits for another    /// stroke; None with none in progress.    pub fn wait(&self, model: &mut dyn Model) -> Option<f64> {        let last = self.group.iter().rev().find(|stroke| !self.reader.dot(&stroke.points)).or(self.group.last())?;        let knobs = &self.reader.knobs;        Some(if self.reader.opens(&last.points, self.height, self.admits, model) {            knobs.group_seconds.max(knobs.group_near_seconds)        } else {            knobs.group_seconds        })    }    /// When the letter in progress is read if no stroke comes: its last lift    /// and its wait.    pub fn due(&self, model: &mut dyn Model) -> Option<f64> {        let wait = self.wait(model)?;        Some(self.group.last()?.up + wait)    }    /// A stroke lifted: whatever it reads at once (the letter before it,    /// begun again after its wait or far from it; a swipe; a first letter of    /// too many strokes).    pub fn lift(&mut self, stroke: TimedStroke, model: &mut dyn Model) -> Vec<GroupRead> {        let mut read = Vec::new();        let mark = self.reader.mark(&stroke.points, self.height);        // A check acts on what it is drawn over, never a letter's part: the        // letter in progress is read first, and the check alone, at once.        if let Some(Reading::Mark(name)) = &mark {            let mut read = self.flush(stroke.down, model);            read.push(GroupRead {                runs: vec![Run { strokes: vec![0], reading: Reading::Mark(name.clone()), runners: Vec::new() }],                read: stroke.up,                height: self.height,                strokes: vec![stroke],            });            return read;        }        // A quick flick is a swipe, at once, never a letter's stroke: the        // letter in progress is read first, as before a check.        if !matches!(mark, Some(Reading::Line { .. })) {            if let Some(line) = marks::flick(&stroke.points, stroke.up - stroke.down, &self.reader.knobs) {                let mut read = self.flush(stroke.down, model);                read.push(GroupRead {                    runs: vec![Run { strokes: vec![0], reading: line, runners: Vec::new() }],                    read: stroke.up,                    height: self.height,                    strokes: vec![stroke],                });                return read;            }        }        let clears = mark == Some(Reading::Clear);        let due = self.due(model);        match (self.group.last().cloned(), due) {            (Some(last), Some(due)) if stroke.down > due || (!clears && !self.joins(&stroke, &last)) => {                read.extend(self.flush(stroke.down.min(due), model));            }            _ => {                if !clears && self.starts_another(&stroke) {                    read.extend(self.flush(stroke.up, model));                }            }        }        // A scratch-out clears the letter in progress with the letters, at        // once: read as one clear, never the letter first.        if clears {            let mut strokes = std::mem::take(&mut self.group);            let up = stroke.up;            strokes.push(stroke);            read.push(GroupRead {                runs: vec![Run { strokes: (0..strokes.len()).collect(), reading: Reading::Clear, runners: Vec::new() }],                strokes,                read: up,                height: self.height,            });            return read;        }        let up = stroke.up;        self.group.push(stroke);        if self.group.len() == 1 && self.swipes_at_once(&self.group[0].points, model) {            read.extend(self.flush(up, model));        }        while self.group.iter().filter(|stroke| !self.reader.dot(&stroke.points)).count() > self.reader.knobs.most_strokes {            let points: Vec<Vec<Point>> = self.group.iter().map(|stroke| stroke.points.clone()).collect();            let Some(first) = self.reader.runs(&points, self.height, self.admits, model).into_iter().next() else { break };            let Some(end) = first.strokes.last().copied() else { break };            let taken: Vec<TimedStroke> = self.group.drain(..=end).collect();            read.push(GroupRead { strokes: taken, runs: vec![first], read: up, height: self.height });        }        read    }    /// The letter in progress as it reads now, shown provisionally until it    /// is read (`flush`): a bowl's c becomes the a its stem makes in place.    pub fn reading(&self, model: &mut dyn Model) -> Vec<Run> {        if self.group.is_empty() {            return Vec::new();        }        let points: Vec<Vec<Point>> = self.group.iter().map(|stroke| stroke.points.clone()).collect();        self.reader.runs(&points, self.height, self.admits, model)    }    /// Whether `stroke` is the next letter, written beside the letter in    /// progress: no dot, linked to none of its strokes (`marks::across`), as    /// one letter's strokes always are — unless it and the last are both    /// stems, which a stroke still to come may join: an H's two stems, by its    /// bar.    pub fn starts_another(&self, stroke: &TimedStroke) -> bool {        if self.reader.dot(&stroke.points) {            return false;        }        let Some(last) = self.group.iter().rev().find(|held| !self.reader.dot(&held.points)) else { return false };        let held = marks::bounds(&stroke.points);        if self            .group            .iter()            .any(|other| !self.reader.dot(&other.points) && marks::across(&marks::bounds(&other.points), &held, &self.reader.knobs))        {            return false;        }        !(self.stem(&last.points) && self.stem(&stroke.points))    }    /// A line, or a stroke as thin as one (`thin`): a wobbling stem.    fn stem(&self, points: &[Point]) -> bool {        let held = marks::bounds(points);        self.reader.straight(points) || held.width.min(held.height) <= self.reader.knobs.thin * held.width.max(held.height)    }    /// The letter in progress read now (its wait over, or the shell gone).    pub fn flush(&mut self, time: f64, model: &mut dyn Model) -> Vec<GroupRead> {        if self.group.is_empty() {            return Vec::new();        }        let runs = self.reading(model);        let strokes = std::mem::take(&mut self.group);        vec![GroupRead { strokes, runs, read: time, height: self.height }]    }    /// Whether `stroke` belongs to the letter in progress: quick, or soon    /// enough and near it.    fn joins(&self, stroke: &TimedStroke, last: &TimedStroke) -> bool {        let gap = stroke.down - last.up;        let knobs = &self.reader.knobs;        if gap <= knobs.group_seconds {            return true;        }        if gap > knobs.group_near_seconds {            return false;        }        let points: Vec<Point> = self.group.iter().flat_map(|held| held.points.iter().copied()).collect();        marks::near(&marks::bounds(&points), &marks::bounds(&stroke.points), knobs)    }    /// A lone level line as long as `swipe_at_once`: the page swipe now,    /// never a T's bar.    pub fn swipes_at_once(&self, points: &[Point], model: &mut dyn Model) -> bool {        let Reading::Line { from, to } = self.reader.read(points, None, Admits::EVERY, model) else { return false };        (to.x - from.x).abs() >= self.reader.knobs.swipe_at_once && (to.x - from.x).abs() > (to.y - from.y).abs()    }    /// Strokes written at their times, grouped and read as the shell would    /// read them: every group, in order, the last read at its wait.    pub fn replay(strokes: &[TimedStroke], reader: Reader, height: Option<f64>, admits: Admits, model: &mut dyn Model) -> Vec<GroupRead> {        let mut stream = Stream::new(reader, height, admits);        let mut ordered: Vec<&TimedStroke> = strokes.iter().collect();        ordered.sort_by(|a, b| a.down.partial_cmp(&b.down).unwrap_or(std::cmp::Ordering::Equal));        let mut read = Vec::new();        for stroke in ordered {            if let Some(due) = stream.due(model) {                if stroke.down > due {                    read.extend(stream.flush(due, model));                }            }            read.extend(stream.lift(stroke.clone(), model));        }        if let Some(due) = stream.due(model) {            read.extend(stream.flush(due, model));        }        read    }}#[cfg(test)]#[path = "stream_tests.rs"]mod stream_tests;