Cotton code
417 lines · 18.8 KB · RustRaw
//! THE SEEK LINE at the reader's page edge, answered by the core: the shell//! draws the line, its ticks, the slip above the finger and the Back slip,//! and reports the finger; every rule and word is here.//!//! The line is the whole book, 0 (its start) to 1 (its end): a place's//! `totalProgression`. A book with page numbers (`contents.pages`, a PDF)//! maps a share to a page as Readium's PDF places do, `at = (page − 1) ///! (pages − 1)`, and a place's page is its `position`. The chapter ticks//! stand where the shell said each resource begins (`contents.starts`), or//! at a PDF entry's page.//!//! - `reader.seek { book }` → `{ here, ticks: [{ at, title, here }], pages,//!   back: { at, words, ms_left } | null, words: { here, line, contents },//!   steps: { previous, next } }`: where the page stands, the chapter starts//!   (the one the page is in marked), the page count or null, the Back as it//!   stands, the slip's words for here (also the line's value for TalkBack ///!   VoiceOver, `line` its label, `contents` the contents' heading), and the//!   places one adjustable step moves to (a chapter each way).//! - `reader.seek.say { book, at }` → `{ words }`: the slip's words for a//!   dragged place, the chapter and page (or percent where the book has no//!   page numbers). Memory only: no file is read.//! - `reader.seek.go { book, at, width? } | { book, tick }` → `{ locator,//!   back }`: the Locator (JSON text) the shell hands its reader, and the//!   Back it leaves. `width` (the line's length in points) comes with a tap://!   a tap within `SNAP_POINTS` of a tick lands on its chapter's start, any//!   other place lands exactly. `tick` (an index of `ticks`) is the//!   contents' jump to a chapter.//! - `reader.seek.back { book }` → `{ locator, back: null }`: returns to the//!   Back place and clears it; `locator` is null when no Back stands.//!//! THE BACK RULE: a jump keeps the place it left as the one Back. One level//! only, and the finger stays in the old place: a second jump while Back//! stands keeps the first place left and starts Back's time again. Back//! retires once the person turns two pages after the jump lands (the first//! place `reader.moved` reports after a jump is its landing, not a turn), or//! when `BACK_MS` pass.use serde_json::{json, Value};use super::{bad, book_data, fields, named, percent, session_key, sessions, Contents, Lines, Place, Session};use crate::methods::MethodError;use crate::shell::client::ClientController;/// How near a tap must fall to a tick, in points, to land on its chapter's start.pub const SNAP_POINTS: f64 = 8.0;/// How long Back stands after a jump with fewer than two pages turned.pub const BACK_MS: i64 = 20_000;/// Pages turned after a jump lands that retire Back.pub const BACK_TURNS: u8 = 2;pub(super) fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "reader.seek" => seek(client, request),        "reader.seek.say" => say(client, request),        "reader.seek.go" => go(client, request),        "reader.seek.back" => back(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a seek method"))),    }}// MARK: - Back/// The one Back place, while it stands.#[derive(Debug, Clone)]pub(super) struct Back {    place: Place,    went_at: i64,    /// The jump's landing has been reported.    landed: bool,    turns: u8,    /// The page the last turn (or the landing) stood on.    last: Option<Place>,}impl Back {    /// A place `reader.moved` reported: the jump's landing, or a turn when    /// it is another page than the last.    pub(super) fn moved(&mut self, place: &Place) {        if !self.landed {            self.landed = true;        } else if !self.last.as_ref().is_some_and(|last| same_page(last, place)) {            self.turns = self.turns.saturating_add(1);        }        self.last = Some(place.clone());    }}/// How far apart two reports of one page may stand on the line: a landing/// refined once its page is laid out. A page turned moves further.const SAME_PAGE: f64 = 2.5e-4;/// Two places on one page: the same Readium position and the same spot on/// the line. A position alone is not a page: Readium on iOS numbers an/// EPUB's positions by its text's length, several screens to one, so two/// pages turned inside one position are still two turns (walked 15 Nov/// 2026: Back stood after two turns). A PDF's position is its page, and/// its spot on the line follows from it.fn same_page(left: &Place, right: &Place) -> bool {    let spot = left.total.zip(right.total).map(|(left, right)| (left - right).abs() < SAME_PAGE);    match (left.position, right.position) {        (Some(left), Some(right)) => left == right && spot.unwrap_or(true),        _ => left.href == right.href && spot.unwrap_or(false),    }}/// Back as it stands now, as the slip says it; retired (and dropped) once/// two pages are turned or its time is up.#[derive(Debug, Clone, PartialEq)]pub(super) struct BackView {    at: f64,    page: Option<i64>,    ms_left: i64,}impl BackView {    pub(super) fn answer(&self, lines: &Lines) -> Value {        let words = match self.page {            Some(page) => lines.say("reader.seek.back_page", &[("page", &page.to_string())]),            None => lines.say("reader.seek.back_percent", &[("percent", &percent(self.at).to_string())]),        };        json!({ "at": self.at, "words": words, "ms_left": self.ms_left })    }}pub(super) fn standing(session: &mut Session, now: i64) -> Option<BackView> {    let back = session.back.as_ref()?;    let ms_left = BACK_MS - (now - back.went_at);    if back.turns >= BACK_TURNS || ms_left <= 0 {        session.back = None;        return None;    }    let pages = session.contents.as_ref().and_then(|contents| contents.pages);    let at = back.place.total.unwrap_or(0.0).clamp(0.0, 1.0);    Some(BackView { at, page: place_page(pages, &back.place), ms_left })}// MARK: - The line/// One chapter start on the line.#[derive(Debug, Clone, PartialEq)]struct Tick {    at: f64,    title: String,    resource: usize,    page: Option<i64>,    fragment: Option<String>,}/// The line as the open book's session holds it.#[derive(Debug, Clone, Default)]struct Line {    ticks: Vec<Tick>,    pages: Option<i64>,    starts: Option<Vec<f64>>,    reading_order: Vec<String>,    /// Where the page stands, and its share.    place: Option<Place>,    here: f64,}impl Line {    fn of(session: Option<&Session>, stored: Option<Place>) -> Line {        let contents = session.and_then(|session| session.contents.clone()).unwrap_or_default();        let place = session.and_then(|session| session.place.clone()).or(stored);        // A book with pages stands where its page does on the line: a        // reader's own share of a PDF (Readium on iOS says page − 1 of        // pages) is not the line's (page − 1 of pages − 1).        let paged = contents.pages.zip(place.as_ref().and_then(|place| place.position)).map(|(pages, position)| share_of_page(pages, position.clamp(1, pages)));        let here = paged.or_else(|| place.as_ref().and_then(|place| place.total)).unwrap_or(0.0).clamp(0.0, 1.0);        Line { ticks: ticks(&contents), pages: contents.pages, starts: contents.starts, reading_order: contents.reading_order, place, here }    }    fn page_at(&self, at: f64) -> Option<i64> {        self.pages.map(|pages| page_at(pages, at))    }    /// The tick a place stands in: the last start at or before it (the    /// first of the entries that share that start).    fn tick_at(&self, at: f64) -> Option<usize> {        let start = self.ticks.iter().map(|tick| tick.at).filter(|start| *start <= at + 1e-9).fold(None, |last: Option<f64>, start| Some(last.map_or(start, |last| last.max(start))))?;        self.ticks.iter().position(|tick| tick.at == start)    }    fn words(&self, lines: &Lines, at: f64, page: Option<i64>) -> String {        let chapter = self.tick_at(at).map(|index| self.ticks[index].title.as_str());        let percent = percent(at).to_string();        match (chapter, page) {            (Some(chapter), Some(page)) => lines.say("reader.seek.chapter_page", &[("chapter", chapter), ("page", &page.to_string())]),            (Some(chapter), None) => lines.say("reader.seek.chapter_percent", &[("chapter", chapter), ("percent", &percent)]),            (None, Some(page)) => lines.say("reader.page", &[("page", &page.to_string())]),            (None, None) => lines.say("reader.progress", &[("percent", &percent)]),        }    }    /// The page the person is on: its own position where the book has pages.    fn here_page(&self) -> Option<i64> {        self.place.as_ref().and_then(|place| place_page(self.pages, place)).or_else(|| self.page_at(self.here))    }    /// The Locator the reader goes to for a place on the line.    fn locator_at(&self, at: f64) -> Result<String, MethodError> {        if let Some(page) = self.page_at(at) {            return self.page_locator(page);        }        let starts = self.starts.as_ref().ok_or_else(|| bad("the reader has not said where the book's resources begin (`contents.starts`)"))?;        let resource = starts.iter().rposition(|start| *start <= at).unwrap_or(0);        let start = starts[resource];        let end = starts.get(resource + 1).copied().unwrap_or(1.0);        let progression = if end > start { ((at - start) / (end - start)).clamp(0.0, 1.0) } else { 0.0 };        self.resource_locator(resource, json!({ "progression": progression, "totalProgression": at }))    }    /// The Locator for a chapter's start.    fn locator_of(&self, tick: &Tick) -> Result<String, MethodError> {        if let (Some(_), Some(page)) = (self.pages, tick.page) {            return self.page_locator(page);        }        let mut locations = json!({ "progression": 0.0, "totalProgression": tick.at });        if let Some(fragment) = &tick.fragment {            locations["fragments"] = json!([fragment]);        }        self.resource_locator(tick.resource, locations)    }    fn page_locator(&self, page: i64) -> Result<String, MethodError> {        let pages = self.pages.unwrap_or(1);        let page = page.clamp(1, pages);        let (href, kind) = self.drawn()?;        Ok(json!({ "href": href, "type": kind, "locations": { "position": page, "totalProgression": share_of_page(pages, page) } }).to_string())    }    fn resource_locator(&self, resource: usize, locations: Value) -> Result<String, MethodError> {        let href = self.reading_order.get(resource).ok_or_else(|| bad("the book's contents name no such resource"))?;        let (_, kind) = self.drawn()?;        Ok(json!({ "href": href, "type": kind, "locations": locations }).to_string())    }    /// The href and media type of the place the reader stands on: a jump    /// stays in the kind of resource it is in.    fn drawn(&self) -> Result<(String, String), MethodError> {        let place = self.place.as_ref().ok_or_else(|| bad("the reader has not said where it is"))?;        let parsed: Value = serde_json::from_str(&place.locator).unwrap_or(Value::Null);        let kind = parsed["type"].as_str().filter(|kind| !kind.is_empty()).ok_or_else(|| bad("the reader's place names no media type"))?;        Ok((place.href.clone(), kind.to_string()))    }}/// The chapter starts: each contents entry where its page (a PDF) or its/// resource's start says, in order along the line.fn ticks(contents: &Contents) -> Vec<Tick> {    let mut ticks: Vec<Tick> = contents        .entries        .iter()        .filter_map(|entry| {            let at = match (entry.page, contents.pages) {                (Some(page), Some(pages)) => share_of_page(pages, page),                _ => *contents.starts.as_ref()?.get(entry.resource)?,            };            Some(Tick { at, title: entry.title.clone(), resource: entry.resource, page: entry.page, fragment: entry.fragment.clone() })        })        .collect();    ticks.sort_by(|left, right| left.at.total_cmp(&right.at));    ticks}fn page_at(pages: i64, at: f64) -> i64 {    if pages <= 1 {        return 1;    }    1 + (at.clamp(0.0, 1.0) * (pages - 1) as f64).round() as i64}fn share_of_page(pages: i64, page: i64) -> f64 {    if pages <= 1 { 0.0 } else { ((page - 1) as f64 / (pages - 1) as f64).clamp(0.0, 1.0) }}/// A place's page where the book has pages: its position, else its share's.fn place_page(pages: Option<i64>, place: &Place) -> Option<i64> {    let pages = pages?;    place.position.map(|position| position.clamp(1, pages)).or_else(|| place.total.map(|total| page_at(pages, total)))}// MARK: - The methodsfn share(fields: &serde_json::Map<String, Value>, method: &str) -> Result<f64, MethodError> {    fields.get("at").and_then(Value::as_f64).filter(|at| (0.0..=1.0).contains(at)).ok_or_else(|| bad(format!("{method} names a place on the line, `at`, 0…1")))}/// The line, read under the sessions' lock: the open book's, else the/// stored place's alone.fn line(client: &ClientController, book: &str, now: i64) -> Result<(Line, Option<BackView>), MethodError> {    let data = book_data(client, book)?;    let stored = Place::stored(data.get("position").and_then(Value::as_str));    let mut sessions = sessions();    let session = sessions.get_mut(&session_key(client, book));    Ok(match session {        Some(session) => {            let back = standing(session, now);            (Line::of(Some(session), stored), back)        }        None => (Line::of(None, stored), None),    })}fn seek(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.seek", &["book"])?;    let book = named(fields, "book").ok_or_else(|| bad("reader.seek names the book"))?;    let now = client.clock().now().timestamp_millis();    let (line, back) = line(client, book, now)?;    let lines = Lines::read(client);    let here_tick = line.tick_at(line.here);    let ticks: Vec<Value> = line        .ticks        .iter()        .enumerate()        .map(|(index, tick)| json!({ "at": tick.at, "title": tick.title, "here": Some(index) == here_tick }))        .collect();    // One adjustable step: the chapter start each way, or a tenth of the    // book where it has no chapters.    let previous = if line.ticks.is_empty() { Some((line.here - 0.1).max(0.0)) } else { line.ticks.iter().rev().map(|tick| tick.at).find(|at| *at < line.here - 1e-6) };    let next = if line.ticks.is_empty() { Some((line.here + 0.1).min(1.0)) } else { line.ticks.iter().map(|tick| tick.at).find(|at| *at > line.here + 1e-6) };    Ok(json!({        "here": line.here,        "ticks": ticks,        "pages": line.pages,        "back": back.map(|back| back.answer(&lines)),        "words": {            "here": line.words(&lines, line.here, line.here_page()),            "line": lines.say("reader.seek.line", &[]),            "contents": lines.say("reader.seek.contents", &[]),        },        "steps": { "previous": previous, "next": next },    }))}fn say(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.seek.say", &["book", "at"])?;    let book = named(fields, "book").ok_or_else(|| bad("reader.seek.say names the book"))?;    let at = share(fields, "reader.seek.say")?;    let line = {        let sessions = sessions();        Line::of(sessions.get(&session_key(client, book)), None)    };    let lines = Lines::read(client);    Ok(json!({ "words": line.words(&lines, at, line.page_at(at)) }))}fn go(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.seek.go", &["book", "at", "width", "tick"])?;    let book = named(fields, "book").ok_or_else(|| bad("reader.seek.go names the book"))?;    let tick = match fields.get("tick") {        None | Some(Value::Null) => None,        Some(tick) => Some(tick.as_u64().ok_or_else(|| bad("`tick` is an index of the line's ticks"))? as usize),    };    let at = if tick.is_some() {        if fields.contains_key("at") || fields.contains_key("width") {            return Err(bad("reader.seek.go goes to a tick, or to a place on the line"));        }        None    } else {        Some(share(fields, "reader.seek.go")?)    };    let width = match fields.get("width") {        None | Some(Value::Null) => None,        Some(width) => Some(width.as_f64().filter(|width| *width > 0.0).ok_or_else(|| bad("`width` is the line's length in points"))?),    };    // A book is jumped through only open: the core holds where its page stands.    book_data(client, book)?;    let now = client.clock().now().timestamp_millis();    let key = session_key(client, book);    let (locator, back) = {        let mut sessions = sessions();        let session = sessions.get_mut(&key).filter(|session| session.place.is_some()).ok_or_else(|| bad("reader.seek.go moves an open book: the reader has not said where it is"))?;        let line = Line::of(Some(session), None);        let landing = match (tick, at) {            (Some(index), _) => Some(line.ticks.get(index).ok_or_else(|| bad("the line has no such tick"))?),            (None, Some(at)) => width.and_then(|width| {                line.ticks                    .iter()                    .map(|tick| (tick, (tick.at - at).abs() * width))                    .filter(|(_, points)| *points <= SNAP_POINTS)                    .min_by(|left, right| left.1.total_cmp(&right.1))                    .map(|(tick, _)| tick)            }),            (None, None) => None,        };        let locator = match (landing, at) {            (Some(tick), _) => line.locator_of(tick)?,            (None, Some(at)) => line.locator_at(at)?,            (None, None) => unreachable!("a tick or a place"),        };        // One level: a Back standing keeps its place; its time starts again.        let left = match standing(session, now).and(session.back.take()) {            Some(standing) => standing.place,            None => session.place.clone().expect("an open book's place"),        };        session.back = Some(Back { place: left, went_at: now, landed: false, turns: 0, last: None });        (locator, standing(session, now))    };    let lines = Lines::read(client);    Ok(json!({ "locator": locator, "back": back.map(|back| back.answer(&lines)) }))}fn back(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.seek.back", &["book"])?;    let book = named(fields, "book").ok_or_else(|| bad("reader.seek.back names the book"))?;    let now = client.clock().now().timestamp_millis();    let place = {        let mut sessions = sessions();        sessions.get_mut(&session_key(client, book)).and_then(|session| standing(session, now).and(session.back.take())).map(|back| back.place)    };    Ok(json!({ "locator": place.map(|place| place.locator), "back": null }))}#[cfg(test)]#[path = "reader_seek_tests.rs"]mod tests;