Cotton code
986 lines · 44.5 KB · RustRaw
//! THE BOOK READER, ANSWERED BY THE CORE (move 6 of the shell boundary): the//! shell (Readium on iOS, Readium Kotlin on Android) draws the file at the//! place this says and reports where the person is; every decision — where//! it opens, when a place is written, the first open's Reading, the faces//! and knobs, the highlights and their acts — is made here.//!//! - `reader.open { id, at? }` → `{ platform_action: "open_reader", table://!   "book", id, at }`: a book's Read act (`book.json`), run as a command.//!//! - `shell.reader { book, at?, dark? }` → the open book://!//!   ```json//!   { "book", "title", "file", "format": "epub|pdf",//!     "at": { "locator", "chapter", "progress", "page_label" } | null,//!     "progress_words",//!     "settings": { "face": "paper|sepia|night", "worn",//!                   "knobs": { "size", "line_height", "margins", "typeface",//!                              "layout", "follow", "weight", "justify",//!                              "publisher_styles", "pdf_fit" } },//!     "fan": { "hand":   { "cards": [{ "id", "label" } |//!                                     { "id", "label", "words",//!                                       "choices": { "cards": [{ "id", "label", "value" }], "raised" } }],//!                          "raised" },//!              "faces":  { "cards": [{ "id", "label" }], "raised" },//!              "selection": { "cards": [{ "id", "label", "red" }], "raised" },//!              "highlight": { "cards": [{ "id", "label", "red" }] },//!              "note_hint" },//!     "highlights": [{ "id", "at", "chapter", "words", "pencil", "note" }],//!     "refusals": { "locked", "unopened" },//!     "start_on_open" }//!   ```//!//!   `fan.hand` is the one tier the hand opens, flat: the faces (`face-…`)//!   then the knobs (`knob-…`, each with its words and its choices), resting//!   on the face chosen. `fan.faces` is the faces alone, a reading page's//!   (`shell.reading`).//!//!   `at` is the place asked (a highlight's Open in book) else where the//!   person stopped, else null (the beginning). `worn` is the face the page//!   wears: Night while the phone is `dark` and the person follows it. A book//!   with no file the reader opens answers `{ book, refusal }` and nothing//!   more; so does an EPUB on this phone whose container says it is locked//!   (an LCP licence, Adobe's rights, or text encrypted under a scheme//!   nothing here decrypts — the font obfuscations Readium undoes are not a//!   lock). A lock found only by opening (a PDF behind a password) is the//!   renderer's to find; it shows `refusals.locked`. A lock is never stripped.//!//! - `reader.moved { book, at?, page_label?, contents?, active, closing? }` →//!   `{ at, progress_words, wrote, again_ms }`: the navigator's place (a//!   Readium Locator), the PDF page's printed label, the book's contents once//!   the publication is open (`{ toc: [{title, href}], reading_order: [href],//!   starts?, pages? }`, children after their parent; `starts` is where each//!   resource of the reading order begins as a share of the book, 0…1, and//!   `pages` the book's page count where it has page numbers — a PDF's — for//!   the seek line, `reader::seek`), and whether the app is active. A place is//!   written at once at a reader's pace, at most every two seconds while//!   pages are skimmed (books-android-leftovers, 6 Nov 2026: fifteen seconds//!   lost every turn of that window to a killed app), at once when the app//!   leaves the foreground or the reader closes, and never while the app is//!   inactive (Readium reports a stale place then,//!   readium/swift-toolkit#841). `again_ms` is when to report again with no//!   place, so what waited out its two seconds is written. The first//!   place of a book only wanted is its Start reading (`start_book`). It//!   also answers `back`, the seek line's Back as it now stands (a page//!   turned after a jump counts toward retiring it).//!//! - `reader.seek`, `reader.seek.say`, `reader.seek.go`, `reader.seek.back`://!   the seek line at the page's edge, its slip, its jumps and its one Back//!   (`reader_seek.rs`).//!//! - `reader.highlight { book, at, pencil?, words, note? }` makes a highlight//!   row (with no pencil, Note's: yellow); `{ id, pencil? , note? }` recolours it or writes its note;//!   `{ id, remove: true }` deletes it. Answers the highlight as//!   `shell.reader` lists it (`{ id, removed: true }` once removed).//!//! - `reader.settings { face? | knob + value, dark? }` writes the//!   `face_settings` row keyed `reader` (the face rides with every write) and//!   answers `{ settings, fan }` as they now stand. Line height and margins//!   set the book's own styles aside, as they bite only with them off.use std::collections::BTreeMap;use std::sync::{Mutex, MutexGuard};use serde_json::{json, Map, Value};use cotton_core::rules::shell_lines::{self, LineRow};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 9] = [    "reader.open",    "shell.reader",    "reader.moved",    "reader.highlight",    "reader.settings",    "reader.seek",    "reader.seek.say",    "reader.seek.go",    "reader.seek.back",];/// How long a place waits before the next is written while the person/// reads: a turn at a reader's pace is written as it is made, and a skim/// writes its newest place once it has rested this long.pub const WRITE_EVERY_MS: i64 = 2_000;const BOOK: &str = super::books::BOOK_TABLE;const HIGHLIGHT: &str = "highlight";/// The face choices' row the reader keeps its face and knobs in.const SETTINGS_ROW: &str = "reader";const LINES: &str = "cards";pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    call_on(&handle.client(), method, request)}pub(crate) fn call_on(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "reader.open" => open(client, request),        "shell.reader" => reader(client, request),        "reader.moved" => moved(client, request),        "reader.highlight" => highlight(client, request),        "reader.settings" => settings_write(client, request),        "reader.seek" | "reader.seek.say" | "reader.seek.go" | "reader.seek.back" => seek::call(client, method, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a reader method"))),    }}fn bad(why: impl Into<String>) -> MethodError {    MethodError::new("bad_request", why.into())}/// The request's fields, none but `allowed`.fn fields<'a>(request: &'a Value, method: &str, allowed: &[&str]) -> Result<&'a Map<String, Value>, MethodError> {    let fields = request.as_object().ok_or_else(|| bad(format!("{method} takes an object")))?;    if let Some(unknown) = fields.keys().find(|key| !allowed.contains(&key.as_str())) {        return Err(bad(format!("{method} has an unknown field `{unknown}`")));    }    Ok(fields)}fn named<'a>(fields: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    fields.get(key).and_then(Value::as_str).map(str::trim).filter(|text| !text.is_empty())}fn open(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.open", &["id", "at"])?;    let id = named(fields, "id").ok_or_else(|| bad("reader.open names the book's id"))?;    let at = match fields.get("at") {        None | Some(Value::Null) => Value::Null,        Some(at) => Value::from(locator(at)?),    };    // Only a book this database holds opens.    book_data(client, id)?;    Ok(json!({        "platform_action": "open_reader",        "table": BOOK,        "id": id,        "at": at,    }))}/// A Locator as compact JSON text: an object, or text holding one, with a/// non-empty `href`.pub(crate) fn locator(at: &Value) -> Result<String, MethodError> {    Place::read(at).map(|place| place.locator)}// MARK: - Linesstruct Lines(Vec<LineRow>);impl Lines {    fn read(client: &ClientController) -> Lines {        Lines(            client                .with_file(|file| Ok(cotton_tools::presentation::line_rows(file.driver, file.workspace_id)))                .unwrap_or_default(),        )    }    fn say(&self, line: &str, fills: &[(&str, &str)]) -> String {        shell_lines::resolve(LINES, line, &self.0, fills).unwrap_or_default()    }}// MARK: - A place/// One place in a book: Readium's Locator as JSON text, and what the core/// reads off it (the navigator alone reads the rest).#[derive(Debug, Clone, PartialEq)]struct Place {    locator: String,    href: String,    /// `locations.totalProgression`, 0…1.    total: Option<f64>,    /// `locations.position`: Readium's page of the publication (a PDF's page).    position: Option<i64>,}impl Place {    fn read(at: &Value) -> Result<Place, MethodError> {        let refused = || bad("`at` is a Locator: an object with its href");        let parsed;        let object = match at {            Value::Object(_) => at,            Value::String(text) => {                parsed = serde_json::from_str::<Value>(text).map_err(|_| refused())?;                &parsed            }            _ => return Err(refused()),        };        let href = object.get("href").and_then(Value::as_str).map(str::trim).filter(|href| !href.is_empty()).ok_or_else(refused)?;        let locations = &object["locations"];        Ok(Place {            locator: object.to_string(),            href: href.to_string(),            total: locations["totalProgression"].as_f64().filter(|total| total.is_finite()),            position: locations["position"].as_i64(),        })    }    /// A stored Locator read back; none when it holds no place.    fn stored(text: Option<&str>) -> Option<Place> {        text.filter(|text| !text.trim().is_empty()).and_then(|text| Place::read(&Value::from(text)).ok())    }    /// The book's `progress`: whole percent, rounded down, so a book reads    /// 100% only on its very end (finishing is the person's own act).    fn percent(&self) -> Option<i64> {        self.total.map(percent)    }}fn percent(total: f64) -> i64 {    (total.clamp(0.0, 1.0) * 100.0).floor() as i64}// MARK: - The contents/// The book's contents in reading order, to say which chapter a place/// stands in: the entry of the contents that holds it.#[derive(Debug, Clone, Default, PartialEq)]struct Contents {    entries: Vec<Entry>,    reading_order: Vec<String>,    /// Where each resource of the reading order begins, 0…1, where the    /// shell said.    starts: Option<Vec<f64>>,    /// The book's page count, where it has page numbers (a PDF).    pages: Option<i64>,}#[derive(Debug, Clone, PartialEq)]struct Entry {    title: String,    /// Its resource's index in the reading order.    resource: usize,    /// The PDF page it starts on (`#page=N`), where its link says.    page: Option<i64>,    /// The anchor its link names in its resource (`#id`), not a page.    fragment: Option<String>,}impl Contents {    /// `toc` each entry's title and href as the contents list them, children    /// after their parent; an entry whose resource is not in the reading    /// order is left out.    fn read(value: &Value) -> Result<Contents, MethodError> {        let refused = || bad("`contents` is { toc: [{title, href}], reading_order: [href] }");        let reading_order: Vec<String> = value["reading_order"]            .as_array()            .ok_or_else(refused)?            .iter()            .map(|href| href.as_str().map(str::to_string).ok_or_else(refused))            .collect::<Result<_, _>>()?;        let paths: Vec<&str> = reading_order.iter().map(|href| path(href)).collect();        let mut entries = Vec::new();        for entry in value["toc"].as_array().ok_or_else(refused)? {            let (Some(title), Some(href)) = (entry["title"].as_str(), entry["href"].as_str()) else { return Err(refused()) };            let Some(resource) = paths.iter().position(|known| *known == path(href)) else { continue };            if title.is_empty() {                continue;            }            let fragment = href.split_once('#').map(|(_, fragment)| fragment).filter(|fragment| !fragment.is_empty() && page(href).is_none());            entries.push(Entry { title: title.to_string(), resource, page: page(href), fragment: fragment.map(str::to_string) });        }        let starts = match &value["starts"] {            Value::Null => None,            Value::Array(starts) => {                let starts: Vec<f64> = starts.iter().map(|start| start.as_f64().filter(|start| (0.0..=1.0).contains(start)).ok_or_else(refused)).collect::<Result<_, _>>()?;                if starts.len() != reading_order.len() || starts.windows(2).any(|pair| pair[1] < pair[0]) {                    return Err(bad("`contents.starts` is where each resource of the reading order begins, 0…1, in order"));                }                Some(starts)            }            _ => return Err(refused()),        };        let pages = match &value["pages"] {            Value::Null => None,            pages => Some(pages.as_i64().filter(|pages| *pages > 0).ok_or_else(|| bad("`contents.pages` is the book's page count"))?),        };        Ok(Contents { entries, reading_order, starts, pages })    }    /// The chapter at a place: in its own resource, the entry whose page is    /// the last at or before the place's (a PDF), else that resource's first    /// entry (an EPUB, whose anchors a place cannot be compared with); with    /// none there, the last entry before the resource. None before the first    /// entry, or in a book with no contents.    fn title(&self, place: &Place, pdf: bool) -> Option<String> {        let resource = self.reading_order.iter().position(|href| path(href) == path(&place.href))?;        let before = || self.entries.iter().rev().find(|entry| entry.resource < resource).map(|entry| entry.title.clone());        let here: Vec<&Entry> = self.entries.iter().filter(|entry| entry.resource == resource).collect();        if here.is_empty() {            return before();        }        if let (true, Some(page)) = (pdf, place.position) {            if here.iter().any(|entry| entry.page.is_some()) {                return here.iter().rev().find(|entry| entry.page.unwrap_or(0) <= page).map(|entry| entry.title.clone()).or_else(before);            }        }        here.first().map(|entry| entry.title.clone())    }}/// An href without its fragment.fn path(href: &str) -> &str {    href.split('#').next().unwrap_or_default()}/// The page an href's fragment names (`#page=12`).fn page(href: &str) -> Option<i64> {    let fragment = href.split_once('#')?.1;    fragment.split('&').find_map(|part| part.strip_prefix("page=")).and_then(|page| page.parse().ok())}// MARK: - The open book, as this phone holds it/// What the core keeps of a book open on this phone between its moves: the/// write gate, the contents, and where the page stands. Kept in memory: a/// reader that closes drops it, and where the person stopped is the/// record's own `position`.#[derive(Debug, Default)]struct Session {    /// Whether the app was active at the last report; none before the first.    active: Option<bool>,    /// The newest place not yet written.    pending: Option<Place>,    written: Option<Place>,    written_at: Option<i64>,    contents: Option<Contents>,    /// Where the page stands, and the printed label of a PDF page.    place: Option<Place>,    page_label: Option<String>,    /// The first place has been seen (and a book only wanted started).    started: bool,    /// The seek line's one Back, while it stands.    back: Option<seek::Back>,}static SESSIONS: Mutex<BTreeMap<String, Session>> = Mutex::new(BTreeMap::new());fn sessions() -> MutexGuard<'static, BTreeMap<String, Session>> {    SESSIONS.lock().unwrap_or_else(|poisoned| poisoned.into_inner())}/// One open book's key: this phone's own folder and the book, so two cores/// in one process (a test, a share extension) never share a gate.fn session_key(client: &ClientController, book: &str) -> String {    format!("{}\u{0}{book}", client.layout().client_dir().display())}// MARK: - shell.reader/// A book's record, as `records.get` reads it.fn book_data(client: &ClientController, id: &str) -> Result<Map<String, Value>, MethodError> {    let read = crate::phone::records::call(client, "records.get", &json!({"table": BOOK, "id": id}))?;    Ok(read["data"].as_object().cloned().unwrap_or_default())}fn reader(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "shell.reader", &["book", "at", "dark"])?;    let book = named(fields, "book").ok_or_else(|| bad("shell.reader names the book"))?;    let dark = fields.get("dark").and_then(Value::as_bool).unwrap_or(false);    let asked = match fields.get("at") {        None | Some(Value::Null) => None,        Some(at) => Some(Place::read(at)?),    };    let data = book_data(client, book)?;    let lines = Lines::read(client);    let file = data.get("file").and_then(Value::as_str).filter(|file| !file.is_empty());    let format = data.get("format").and_then(Value::as_str).filter(|format| matches!(*format, "epub" | "pdf"));    let (Some(file), Some(format)) = (file, format) else {        return Ok(json!({ "book": book, "refusal": lines.say("book.could_not_open", &[]) }));    };    if format == "epub" && epub_locked(client, file) {        return Ok(json!({ "book": book, "refusal": lines.say("book.locked", &[]) }));    }    let at = asked.or_else(|| Place::stored(data.get("position").and_then(Value::as_str)));    let (chapter, page_label) = {        let sessions = sessions();        let session = sessions.get(&session_key(client, book));        let chapter = at.as_ref().and_then(|at| session.and_then(|session| session.contents.as_ref()).and_then(|contents| contents.title(at, format == "pdf")));        (chapter, session.and_then(|session| session.page_label.clone()))    };    let settings = Settings::read(client)?;    Ok(json!({        "book": book,        "title": data.get("title").and_then(Value::as_str).unwrap_or_default(),        "file": file,        "format": format,        "at": at.as_ref().map(|at| place_answer(at, chapter, page_label)),        "progress_words": progress_words(&lines, at.as_ref()),        "settings": settings.answer(dark),        "fan": fan(&lines, &settings),        "highlights": highlights(client, book)?,        "refusals": { "locked": lines.say("book.locked", &[]), "unopened": lines.say("book.could_not_open", &[]) },        "start_on_open": data.get("status").and_then(Value::as_str) == Some("want_to_read"),    }))}fn place_answer(place: &Place, chapter: Option<String>, page_label: Option<String>) -> Value {    json!({ "locator": place.locator, "chapter": chapter, "progress": place.percent(), "page_label": page_label })}fn progress_words(lines: &Lines, place: Option<&Place>) -> Option<String> {    let percent = place?.percent()?.to_string();    Some(lines.say("reader.progress", &[("percent", &percent)]))}/// The algorithms an EPUB may name that Readium undoes itself: font/// obfuscation, never a lock on the text.const OBFUSCATIONS: [&str; 2] = ["http://www.idpf.org/2008/embedding", "http://ns.adobe.com/pdf/enc#RC"];/// An EPUB on this phone whose container says it is locked: an LCP licence,/// Adobe's rights, or a resource encrypted under a scheme nothing here/// decrypts. A file not here yet, or one that is not a zip, is the/// renderer's to open (and to refuse).fn epub_locked(client: &ClientController, key: &str) -> bool {    let Some(path) = client.with_file(|file| Ok(super::media::local_path_of(file.driver, key))).ok().flatten() else { return false };    let Ok(ranges) = super::whatsapp_import::FileRanges::open(&path, "the book") else { return false };    let Ok(entries) = cotton_core::import::zip::list_zip_entries_ranged(&ranges) else { return false };    if entries.iter().any(|entry| matches!(entry.name.as_str(), "META-INF/license.lcpl" | "META-INF/rights.xml")) {        return true;    }    let Some(encryption) = entries.iter().find(|entry| entry.name == "META-INF/encryption.xml") else { return false };    let Ok(bytes) = cotton_core::import::zip::read_zip_entry_ranged(&ranges, encryption) else { return false };    let text = String::from_utf8_lossy(&bytes);    text.split("EncryptionMethod").skip(1).filter_map(|method| {        let rest = method.split_once("Algorithm")?.1.trim_start().strip_prefix('=')?.trim_start();        let quote = rest.chars().next().filter(|quote| *quote == '"' || *quote == '\'')?;        rest[1..].split(quote).next()    }).any(|algorithm| !OBFUSCATIONS.contains(&algorithm))}// MARK: - reader.movedfn moved(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.moved", &["book", "at", "page_label", "contents", "active", "closing"])?;    let book = named(fields, "book").ok_or_else(|| bad("reader.moved names the book"))?.to_string();    let active = fields.get("active").and_then(Value::as_bool).ok_or_else(|| bad("reader.moved says whether the app is active"))?;    let closing = fields.get("closing").and_then(Value::as_bool).unwrap_or(false);    let at = match fields.get("at") {        None | Some(Value::Null) => None,        Some(at) => Some(Place::read(at)?),    };    let contents = match fields.get("contents") {        None | Some(Value::Null) => None,        Some(contents) => Some(Contents::read(contents)?),    };    let data = book_data(client, &book)?;    let pdf = data.get("format").and_then(Value::as_str) == Some("pdf");    let now = client.clock().now().timestamp_millis();    let key = session_key(client, &book);    // The gate decides under the lock; the writes are made after it.    let (due, start, again_ms, answer_place, chapter, page_label, back) = {        let mut sessions = sessions();        let session = sessions.entry(key.clone()).or_default();        if let Some(contents) = contents {            session.contents = Some(contents);        }        if let Some(label) = fields.get("page_label") {            session.page_label = label.as_str().map(str::trim).filter(|label| !label.is_empty()).map(str::to_string);        }        let was = session.active.replace(active);        let mut due = None;        match (was, active) {            // Leaving the foreground, or closing: what is pending is written            // now, and nothing more until the app is active again.            (Some(true), false) => due = session.pending.take(),            // Active again: a place reported while inactive is never written.            (Some(false), true) => session.pending = None,            _ => {}        }        let mut start = false;        if let Some(place) = at {            if !session.started {                session.started = true;                start = true;            }            if let Some(back) = &mut session.back {                back.moved(&place);            }            session.place = Some(place.clone());            if active && session.written.as_ref() != Some(&place) {                session.pending = Some(place);            }        }        if active && due.is_none() {            let waited = session.written_at.is_none_or(|at| now - at >= WRITE_EVERY_MS);            if waited {                due = session.pending.take();            }        }        if closing && active {            due = due.or_else(|| session.pending.take());        }        if let Some(place) = &due {            session.written = Some(place.clone());            session.written_at = Some(now);        }        let again_ms = match (&session.pending, session.written_at) {            (Some(_), Some(at)) if active && !closing => Some((at + WRITE_EVERY_MS - now).max(0)),            _ => None,        };        let place = session.place.clone();        let chapter = place.as_ref().and_then(|place| session.contents.as_ref().and_then(|contents| contents.title(place, pdf)));        let page_label = page_words(pdf, session.page_label.as_deref(), place.as_ref());        let back = seek::standing(session, now);        if closing {            sessions.remove(&key);        }        (due, start, again_ms, place, chapter, page_label, back)    };    // A book only wanted is being read from its first page: its Start reading.    if start && data.get("status").and_then(Value::as_str) == Some("want_to_read") {        super::book_acts::run(client, "start_book", &json!({ "book": book }))?;    }    let wrote = due.is_some();    if let Some(place) = due {        write_place(client, &book, &place, now)?;    }    let lines = Lines::read(client);    Ok(json!({        "at": answer_place.as_ref().map(|place| place_answer(place, chapter, page_label)),        "progress_words": progress_words(&lines, answer_place.as_ref()),        "wrote": wrote,        "again_ms": again_ms,        "back": back.map(|back| back.answer(&lines)),    }))}/// The page number at the foot: a PDF's printed label, else Readium's/// position in the publication.fn page_words(pdf: bool, label: Option<&str>, place: Option<&Place>) -> Option<String> {    match label {        Some(label) if pdf => Some(label.to_string()),        _ => place.and_then(|place| place.position).map(|position| position.to_string()),    }}/// The place written to the book's record: the Locator, the percent, and when.fn write_place(client: &ClientController, book: &str, place: &Place, now: i64) -> Result<(), MethodError> {    let when = cotton_store::protocol::js::to_iso_string(now).ok_or_else(|| MethodError::new("unwritable", "the clock is out of range"))?;    let mut patch = json!({ "position": place.locator, "position_at": when });    if let Some(percent) = place.percent() {        patch["progress"] = json!(percent);    }    crate::phone::records::call(client, "records.update", &json!({ "table": BOOK, "id": book, "patch": patch }))?;    Ok(())}// MARK: - Highlights/// The pencils a passage is underlined in, in the order the tiers deal them.const PENCILS: [&str; 3] = ["red", "yellow", "teal"];/// The pencil a note's highlight is made in, and the one a selection rests on.const NOTE_PENCIL: &str = "yellow";fn highlights(client: &ClientController, book: &str) -> Result<Vec<Value>, MethodError> {    let mut rows = Vec::new();    let mut page = 0u64;    loop {        let answer = crate::phone::records::call(client, "records.list", &json!({"table": HIGHLIGHT, "where": {"book": book}, "page": page}))?;        rows.extend(answer["records"].as_array().into_iter().flatten().filter_map(highlight_answer));        match answer["next_page"].as_u64() {            Some(next) if next > page => page = next,            _ => break,        }    }    Ok(rows)}/// A highlight row as the page draws it; none when it holds no place. A/// colour no pencil draws is drawn in the note's pencil.fn highlight_answer(record: &Value) -> Option<Value> {    let data = &record["data"];    let at = data["locator"].as_str().filter(|at| !at.is_empty())?;    let pencil = data["colour"].as_str().filter(|colour| PENCILS.contains(colour)).unwrap_or(NOTE_PENCIL);    Some(json!({        "id": record["id"],        "at": at,        "chapter": data["chapter"],        "words": data["text"],        "pencil": pencil,        "note": data["note"],    }))}fn pencil_of(fields: &Map<String, Value>) -> Result<Option<&str>, MethodError> {    match fields.get("pencil") {        None | Some(Value::Null) => Ok(None),        Some(Value::String(pencil)) if PENCILS.contains(&pencil.as_str()) => Ok(Some(pencil.as_str())),        Some(_) => Err(bad("a pencil is red, yellow or teal")),    }}fn highlight(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.highlight", &["book", "id", "at", "pencil", "words", "note", "remove"])?;    let pencil = pencil_of(fields)?;    let note = match fields.get("note") {        None => None,        Some(Value::Null) => Some(Value::Null),        Some(Value::String(note)) => Some(if note.trim().is_empty() { Value::Null } else { Value::from(note.trim()) }),        Some(_) => return Err(bad("a highlight's note is words")),    };    if let Some(id) = named(fields, "id") {        if fields.contains_key("book") || fields.contains_key("at") || fields.contains_key("words") {            return Err(bad("a highlight made already keeps its book, place and words"));        }        if fields.get("remove").and_then(Value::as_bool) == Some(true) {            if pencil.is_some() || note.is_some() {                return Err(bad("a highlight removed takes no pencil or note"));            }            crate::phone::records::call(client, "records.delete", &json!({"table": HIGHLIGHT, "id": id}))?;            return Ok(json!({ "id": id, "removed": true }));        }        let mut patch = Map::new();        if let Some(pencil) = pencil {            patch.insert("colour".into(), json!(pencil));        }        if let Some(note) = note {            patch.insert("note".into(), note);        }        if patch.is_empty() {            return Err(bad("reader.highlight on a highlight changes its pencil, its note, or removes it"));        }        let answer = crate::phone::records::call(client, "records.update", &json!({"table": HIGHLIGHT, "id": id, "patch": patch}))?;        return highlight_of(client, answer, id);    }    if fields.contains_key("remove") {        return Err(bad("only a highlight made already is removed, by its id"));    }    let book = named(fields, "book").ok_or_else(|| bad("reader.highlight names the book, or the highlight's id"))?;    let at = Place::read(fields.get("at").ok_or_else(|| bad("a highlight is made at its place"))?)?;    let words = named(fields, "words").ok_or_else(|| bad("a highlight holds the words selected"))?;    // Note on a selection names no pencil: it is made in the note's.    let pencil = pencil.unwrap_or(NOTE_PENCIL);    let data = book_data(client, book)?;    let pdf = data.get("format").and_then(Value::as_str) == Some("pdf");    let now = client.clock().now().timestamp_millis();    let made_at = cotton_store::protocol::js::to_iso_string(now).ok_or_else(|| MethodError::new("unwritable", "the clock is out of range"))?;    // Its chapter and page are the page's own as it stands.    let (chapter, page_label) = {        let sessions = sessions();        let session = sessions.get(&session_key(client, book));        let chapter = session.and_then(|session| session.contents.as_ref()).and_then(|contents| contents.title(&at, pdf));        let page = session.and_then(|session| page_words(pdf, session.page_label.as_deref(), session.place.as_ref()));        (chapter, page)    };    let mut row = json!({ "book": book, "text": words, "colour": pencil, "locator": at.locator, "made_at": made_at });    if let Some(percent) = at.percent() {        row["progress"] = json!(percent);    }    if let Some(page_label) = page_label {        row["page_label"] = json!(page_label);    }    if let Some(chapter) = chapter {        row["chapter"] = json!(chapter);    }    if let Some(Value::String(note)) = &note {        row["note"] = json!(note);    }    let made = crate::phone::records::call(client, "records.create", &json!({"table": HIGHLIGHT, "data": row}))?;    let id = made.pointer("/record/id").and_then(Value::as_str).ok_or_else(|| MethodError::new("unwritable", "the highlight was made with no id"))?.to_string();    highlight_of(client, made, &id)}/// The highlight a write answered, as `shell.reader` lists it.fn highlight_of(client: &ClientController, answer: Value, id: &str) -> Result<Value, MethodError> {    let record = match answer.get("record") {        Some(record) if record["data"].is_object() => record.clone(),        _ => crate::phone::records::call(client, "records.get", &json!({"table": HIGHLIGHT, "id": id}))?,    };    let mut record = record;    if record.get("id").is_none() {        record["id"] = json!(id);    }    highlight_answer(&record).ok_or_else(|| MethodError::new("unreadable", "the highlight holds no place"))}// MARK: - The face and the knobsconst FACES: [&str; 3] = ["paper", "sepia", "night"];const SIZES: [f64; 5] = [0.85, 1.0, 1.2, 1.45, 1.75];const LINE_HEIGHTS: [f64; 3] = [1.25, 1.5, 1.8];const LINE_HEIGHT_WORDS: [&str; 3] = ["tight", "even", "open"];const MARGINS: [f64; 3] = [0.75, 1.0, 1.5];const MARGIN_WORDS: [&str; 3] = ["narrow", "even", "wide"];const TYPEFACES: [&str; 4] = ["publisher", "serif", "sans", "dyslexic"];const LAYOUTS: [&str; 2] = ["pages", "scroll"];/// The knobs the hand's tier deals after the faces, in order, and the row's column each writes.const KNOBS: [(&str, &str); 6] = [    ("size", "font_size"),    ("line_height", "line_height"),    ("margins", "margins"),    ("typeface", "font"),    ("layout", "layout"),    ("follow", "follow_device"),];/// The `reader` row, read; a column it leaves empty is the reader's default,/// and a face or a typeface no build knows reads as the first.#[derive(Debug, Clone, PartialEq)]struct Settings {    /// The table the database keeps face choices in, and its row key.    table: Option<(String, String)>,    face: String,    size: f64,    line_height: Option<f64>,    margins: Option<f64>,    typeface: String,    bold: bool,    justify: bool,    publisher_styles: bool,    scroll: bool,    follow: bool,    pdf_whole_page: bool,}impl Settings {    fn read(client: &ClientController) -> Result<Settings, MethodError> {        let mut table = None;        client            .read_rows("shell.reader", &mut |ctx| {                let listed = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?;                table = super::catalogue::FaceChoiceTable::of(&listed.definitions).map(|choices| (choices.table, choices.row_key));                Ok(Value::Null)            })            .map_err(|why| MethodError::new("unreadable", why))?;        let row = match &table {            Some((id, _)) => match crate::phone::records::call(client, "records.get", &json!({"table": id, "id": SETTINGS_ROW})) {                Ok(read) => read["data"].as_object().cloned().unwrap_or_default(),                Err(error) if crate::phone::copy_standing::absent(&error.code) => Map::new(),                Err(error) => return Err(error),            },            None => Map::new(),        };        Ok(Settings::of(table, &row))    }    fn of(table: Option<(String, String)>, row: &Map<String, Value>) -> Settings {        let text = |key: &str| row.get(key).and_then(Value::as_str);        let flag = |key: &str| row.get(key).and_then(Value::as_bool);        Settings {            table,            face: text("face").filter(|face| FACES.contains(face)).unwrap_or(FACES[0]).to_string(),            size: row.get("font_size").and_then(Value::as_f64).unwrap_or(1.0),            line_height: row.get("line_height").and_then(Value::as_f64),            margins: row.get("margins").and_then(Value::as_f64),            typeface: text("font").filter(|font| TYPEFACES.contains(font)).unwrap_or(TYPEFACES[0]).to_string(),            bold: text("weight") == Some("bold"),            justify: flag("justify").unwrap_or(false),            publisher_styles: flag("publisher_styles").unwrap_or(true),            scroll: text("layout") == Some("scroll"),            follow: flag("follow_device").unwrap_or(false),            pdf_whole_page: text("pdf_fit") == Some("page"),        }    }    /// The face the page wears: Night while the phone is dark and the person    /// asked to follow it, else the face chosen.    fn worn(&self, dark: bool) -> &str {        if self.follow && dark { "night" } else { &self.face }    }    fn answer(&self, dark: bool) -> Value {        json!({            "face": self.face,            "worn": self.worn(dark),            "knobs": {                "size": self.size,                "line_height": self.line_height,                "margins": self.margins,                "typeface": self.typeface,                "layout": if self.scroll { "scroll" } else { "pages" },                "follow": self.follow,                "weight": if self.bold { "bold" } else { "regular" },                "justify": self.justify,                "publisher_styles": self.publisher_styles,                "pdf_fit": if self.pdf_whole_page { "page" } else { "width" },            },        })    }    /// What a knob holds now, as its choices say it.    fn value(&self, knob: &str) -> Value {        match knob {            "size" => json!(self.size),            "line_height" => json!(self.line_height.unwrap_or(LINE_HEIGHTS[1])),            "margins" => json!(self.margins.unwrap_or(MARGINS[1])),            "typeface" => json!(self.typeface),            "layout" => json!(if self.scroll { "scroll" } else { "pages" }),            _ => json!(self.follow),        }    }}/// What a knob may be set to, in the order its tier deals them.fn choices(knob: &str) -> Vec<Value> {    match knob {        "size" => SIZES.iter().map(|size| json!(size)).collect(),        "line_height" => LINE_HEIGHTS.iter().map(|height| json!(height)).collect(),        "margins" => MARGINS.iter().map(|margin| json!(margin)).collect(),        "typeface" => TYPEFACES.iter().map(|face| json!(face)).collect(),        "layout" => LAYOUTS.iter().map(|layout| json!(layout)).collect(),        _ => vec![json!(true), json!(false)],    }}fn same(left: &Value, right: &Value) -> bool {    match (left.as_f64(), right.as_f64()) {        (Some(left), Some(right)) => (left - right).abs() < 1e-9,        _ => left == right,    }}/// One choice's words on its card.fn choice_words(lines: &Lines, knob: &str, value: &Value) -> String {    let step = |steps: &[f64], words: &[&str]| {        let at = value.as_f64().and_then(|value| steps.iter().position(|step| (step - value).abs() < 1e-9)).unwrap_or(1);        words[at].to_string()    };    match knob {        "size" => {            let percent = ((value.as_f64().unwrap_or(1.0)) * 100.0).round().to_string();            lines.say("reader.size", &[("percent", &percent)])        }        "line_height" => lines.say(&format!("reader.line_height.{}", step(&LINE_HEIGHTS, &LINE_HEIGHT_WORDS)), &[]),        "margins" => lines.say(&format!("reader.margins.{}", step(&MARGINS, &MARGIN_WORDS)), &[]),        "typeface" => lines.say(&format!("reader.typeface.{}", value.as_str().unwrap_or(TYPEFACES[0])), &[]),        "layout" => lines.say(&format!("reader.layout.{}", value.as_str().unwrap_or(LAYOUTS[0])), &[]),        _ => lines.say(if value.as_bool() == Some(true) { "reader.on" } else { "reader.off" }, &[]),    }}/// The reader's fan: the one tier the HAND opens (the faces, then the knobs,/// each knob with its CHOICES), the FACES alone (a reading page's), the/// SELECTION tier (the pencils and Note) and a drawn HIGHLIGHT's (the/// pencils, Note, and Remove, last and red).fn fan(lines: &Lines, settings: &Settings) -> Value {    let faces: Vec<Value> = FACES.iter().map(|face| json!({ "id": format!("face-{face}"), "label": lines.say(&format!("reader.face.{face}"), &[]) })).collect();    let knobs: Vec<Value> = KNOBS        .iter()        .map(|(knob, _)| {            let now = settings.value(knob);            let offered = choices(knob);            let cards: Vec<Value> = offered                .iter()                .enumerate()                .map(|(at, value)| json!({ "id": format!("choice-{at}"), "label": choice_words(lines, knob, value), "value": value }))                .collect();            let raised = offered.iter().position(|value| same(value, &now)).map(|at| format!("choice-{at}"));            json!({                "id": format!("knob-{knob}"),                "label": lines.say(&format!("reader.knob.{knob}"), &[]),                "words": choice_words(lines, knob, &now),                "choices": { "cards": cards, "raised": raised },            })        })        .collect();    let pencils = || -> Vec<Value> {        PENCILS.iter().map(|pencil| json!({ "id": format!("pencil-{pencil}"), "label": lines.say(&format!("reader.pencil.{pencil}"), &[]), "red": false })).collect()    };    let note = json!({ "id": "note", "label": lines.say("reader.note", &[]), "red": false });    let remove = json!({ "id": "remove", "label": lines.say("reader.remove", &[]), "red": true });    let mut selection = pencils();    selection.push(note.clone());    let mut marked = pencils();    marked.push(note);    marked.push(remove);    let raised = format!("face-{}", settings.face);    let hand: Vec<Value> = faces.iter().chain(knobs.iter()).cloned().collect();    json!({        "hand": { "cards": hand, "raised": raised },        "faces": { "cards": faces, "raised": raised },        "selection": { "cards": selection, "raised": format!("pencil-{NOTE_PENCIL}") },        "highlight": { "cards": marked },        "note_hint": lines.say("reader.note_hint", &[]),    })}/// The reader's face as the `reader` row holds it and its FACES tier: what/// a reading page (`shell.reading`) wears beside the book reader.pub(crate) fn look(client: &ClientController, dark: bool) -> Result<(Value, Value), MethodError> {    let settings = Settings::read(client)?;    let fan = fan(&Lines::read(client), &settings);    Ok((settings.answer(dark), fan["faces"].clone()))}fn settings_write(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, "reader.settings", &["face", "knob", "value", "dark"])?;    let dark = fields.get("dark").and_then(Value::as_bool).unwrap_or(false);    let mut patch = Map::new();    match (named(fields, "face"), named(fields, "knob")) {        (Some(face), None) => {            if !FACES.contains(&face) {                return Err(bad("a reader's face is paper, sepia or night"));            }            patch.insert("face".into(), json!(face));        }        (None, Some(knob)) => {            let column = KNOBS.iter().find(|(name, _)| *name == knob).map(|(_, column)| *column).ok_or_else(|| bad(format!("the reader has no knob `{knob}`")))?;            let value = fields.get("value").ok_or_else(|| bad("a knob is set to a value"))?;            let value = choices(knob).into_iter().find(|offered| same(offered, value)).ok_or_else(|| bad(format!("`{knob}` is not set to that")))?;            patch.insert(column.into(), value);            // Line height and margins bite only with the book's own styles off.            if matches!(knob, "line_height" | "margins") {                patch.insert("publisher_styles".into(), json!(false));            }        }        _ => return Err(bad("reader.settings sets a face, or a knob to a value")),    }    let settings = Settings::read(client)?;    let mut row = settings_row(&settings);    for (key, value) in &patch {        row.insert(key.clone(), value.clone());    }    let next = Settings::of(settings.table.clone(), &row);    let lines = Lines::read(client);    // The setting already worn is no change: nothing is written.    if next != settings {        let (table, row_key) = settings.table.clone().ok_or_else(|| MethodError::new("unwritable", "this database keeps no face choices"))?;        // Create is the object's upsert by the row's key; the face rides with        // every write, as a screen's row is kept only with its face.        let mut data = patch;        data.insert(row_key, json!(SETTINGS_ROW));        data.insert("face".into(), json!(next.face));        crate::phone::records::call(client, "records.create", &json!({"table": table, "data": data}))?;    }    Ok(json!({ "settings": next.answer(dark), "fan": fan(&lines, &next) }))}/// The row's columns, as the settings stand.fn settings_row(settings: &Settings) -> Map<String, Value> {    let mut row = Map::new();    row.insert("face".into(), json!(settings.face));    row.insert("font_size".into(), json!(settings.size));    row.insert("font".into(), json!(settings.typeface));    row.insert("weight".into(), json!(if settings.bold { "bold" } else { "regular" }));    row.insert("justify".into(), json!(settings.justify));    row.insert("publisher_styles".into(), json!(settings.publisher_styles));    row.insert("layout".into(), json!(if settings.scroll { "scroll" } else { "pages" }));    row.insert("follow_device".into(), json!(settings.follow));    row.insert("pdf_fit".into(), json!(if settings.pdf_whole_page { "page" } else { "width" }));    if let Some(height) = settings.line_height {        row.insert("line_height".into(), json!(height));    }    if let Some(margins) = settings.margins {        row.insert("margins".into(), json!(margins));    }    row}#[path = "reader_seek.rs"]mod seek;#[cfg(test)]#[path = "reader_tests.rs"]mod tests;