Cotton code
446 lines · 27.9 KB · RustRaw
//! The reader answered by the core: `reader.open`'s effect, `shell.reader`'s//! open book, the place a move writes and when, the first open's Reading,//! highlights, and the face and knobs on the synced `reader` row. Every book,//! passage and file here is synthetic.use std::io::Write;use serde_json::json;use super::*;use crate::shell::client::phone_tests::{attached, attached_on_a_clock};// RULE: a Locator is an object with a non-empty href, given as itself or as JSON text, and it crosses as compact JSON text.#[test]fn a_locator_is_an_object_with_its_href() {    let at = json!({"href": "OEBPS/ch01.xhtml", "type": "application/xhtml+xml", "locations": {"progression": 0.25}});    let compact = locator(&at).expect("an object");    assert_eq!(serde_json::from_str::<Value>(&compact).unwrap(), at);    assert!(!compact.contains(' ') && !compact.contains('\n'), "compact: {compact}");    assert_eq!(locator(&Value::from(at.to_string())).expect("as text"), compact);    for refused in [json!({"type": "x"}), json!({"href": " "}), json!(["href"]), json!("not json"), json!("[]"), json!(3)] {        assert_eq!(locator(&refused).expect_err("not a Locator").code, "bad_request", "{refused}");    }}// RULE: reader.open answers the open_reader effect for a book this database holds, with where to open or null, and refuses any other id or an unknown field.#[test]fn reader_open_names_a_book_this_database_holds() {    let (_dir, client) = attached();    let id_of = |made: Value| -> String {        ["/record/id", "/id", "/after/id", "/change/after/id"]            .iter()            .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str))            .unwrap_or_else(|| panic!("the id: {made}"))            .to_string()    };    let id = id_of(crate::phone::records::call(&client, "records.create", &json!({"table": "book", "data": {"title": "Dune"}})).expect("a book"));    let answer = open(&client, &json!({"id": id})).expect("opens");    assert_eq!(answer, json!({"platform_action": "open_reader", "table": "book", "id": id, "at": null}));    let at = json!({"href": "ch01.xhtml"});    let answer = open(&client, &json!({"id": id, "at": at.to_string()})).expect("opens there");    assert_eq!(answer["at"], json!("{\"href\":\"ch01.xhtml\"}"));    assert!(open(&client, &json!({"id": "no-such-book"})).is_err());    let todo = id_of(crate::phone::records::call(&client, "records.create", &json!({"table": "todo", "data": {"title": "Not a book"}})).expect("a todo"));    assert!(open(&client, &json!({"id": todo})).is_err(), "only a book");    assert_eq!(open(&client, &json!({"id": id, "method": "books.remove"})).expect_err("closed").code, "bad_request");    assert_eq!(open(&client, &json!({"id": id, "at": {"page": 3}})).expect_err("no href").code, "bad_request");}// RULE: the four book methods are on every build and in both method tables, and reader.open is a method a command may run.#[test]fn the_book_methods_are_in_the_method_tables() {    for method in super::super::books::METHODS.iter().chain(METHODS.iter()) {        assert!(crate::methods::CLIENT_METHODS.contains(method), "{method}");        assert!(crate::methods::ALL_METHODS.contains(method), "{method}");        assert!(crate::methods::methods().iter().any(|name| name == method), "{method}");    }    assert!(cotton_core::definitions::COMMAND_METHODS.contains(&"reader.open"));    assert!(crate::phone::records::method_module("reader.open").is_some());}/// What a command's `reader.open` runs on: this module, as on the phone.struct Reader<'a>(&'a ClientController);impl crate::phone::records::AppMethods for Reader<'_> {    fn call(&self, method: &str, request: &Value) -> Result<Value, MethodError> {        assert_eq!(method, "reader.open");        open(self.0, request)    }}// RULE: a highlight's Open in book (`go_to`) opens the reader on its own book at its passage: the kit's command binds the highlight's book and locator to reader.open, which answers the open_reader effect.#[test]fn a_highlights_open_in_book_opens_its_book_at_the_passage() {    let (_dir, client) = attached();    let id_of = |made: Value| -> String {        ["/record/id", "/id", "/after/id", "/change/after/id"]            .iter()            .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str))            .unwrap_or_else(|| panic!("the id: {made}"))            .to_string()    };    let book = id_of(crate::phone::records::call(&client, "records.create", &json!({"table": "book", "data": {"title": "Synthetic Book"}})).expect("a book"));    let at = json!({"href": "OEBPS/ch02.xhtml", "type": "application/xhtml+xml", "locations": {"progression": 0.5}}).to_string();    // The reader writes a highlight whole; no record write may set its passage.    let highlight = "highlight-1";    client        .with_writer(|replica| {            replica                .driver                .run(                    "INSERT INTO cotton_highlight (id, workspace_id, book, text, locator, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",                    &[highlight, replica.workspace_id, &book, "An invented line.", &at, "2026-11-04T10:00:00.000Z", "2026-11-04T10:00:00.000Z"]                        .map(|text| rusqlite::types::Value::Text(text.to_string())),                )                .map(|_| ())                .map_err(|error| error.to_string())        })        .expect("a highlight");    let definition: cotton_core::definitions::TableDefinition =        serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/highlight.json")).expect("the kit's highlight");    let ran = crate::phone::records::run_command_with(&client, &definition, highlight, "go_to", None, &Reader(&client)).expect("Open in book runs");    let answer = ran.answer.expect("the method's answer");    assert_eq!(answer["platform_action"], "open_reader");    assert_eq!(answer["id"], json!(book));    assert_eq!(serde_json::from_str::<Value>(answer["at"].as_str().expect("a place")).unwrap(), serde_json::from_str::<Value>(&at).unwrap());}// MARK: - shell.reader and its writesfn id_of(made: Value) -> String {    ["/record/id", "/id", "/after/id", "/change/after/id"]        .iter()        .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str))        .unwrap_or_else(|| panic!("the id: {made}"))        .to_string()}/// A book with a file, in `format`, at `status`.fn a_book(client: &ClientController, format: &str, status: &str) -> String {    let key = format!("{}/books/{}.{format}", crate::fixture::WORKSPACE, "c".repeat(64));    id_of(crate::phone::records::call(client, "records.create", &json!({"table": "book", "data": {"title": "The Lantern Orchard", "format": format, "status": status, "file": key}})).expect("a book"))}fn book_of(client: &ClientController, id: &str) -> Value {    crate::phone::records::call(client, "records.get", &json!({"table": "book", "id": id})).expect("the book")["data"].clone()}fn ask(client: &ClientController, method: &str, request: Value) -> Value {    call_on(client, method, &request).unwrap_or_else(|error| panic!("{method}: {error:?}"))}fn at(href: &str, total: f64, position: i64) -> Value {    json!({"href": href, "type": "application/xhtml+xml", "locations": {"progression": 0.1, "totalProgression": total, "position": position}})}/// The book writes this phone holds for the object.fn book_writes(client: &ClientController) -> i64 {    client        .with_file(|file| {            file.driver                .get("SELECT COUNT(*) AS n FROM _outbox WHERE tbl = 'cotton_book'", &[])                .map_err(|error| error.to_string())                .map(|row| row.and_then(|row| row.int("n")).unwrap_or(0))        })        .expect("the outbox")}// RULE: shell.reader answers a fresh book whole — its file and format, no place yet (the beginning), the face and knobs at their defaults, the fan's tiers in the kit's words, no highlights, and start_on_open while it is only wanted; its first reported place starts it (status reading, started today) and is written, so the next open stands there.#[test]fn a_fresh_book_opens_at_its_beginning_and_its_first_page_starts_it() {    let (_dir, client, _clock) = attached_on_a_clock();    let book = a_book(&client, "epub", "want_to_read");    let opened = ask(&client, "shell.reader", json!({"book": book}));    assert_eq!(opened["format"], "epub");    assert!(opened["file"].as_str().unwrap().ends_with(".epub"));    assert_eq!(opened["at"], Value::Null);    assert_eq!(opened["start_on_open"], true);    assert_eq!(opened["settings"]["face"], "paper");    assert_eq!(opened["settings"]["worn"], "paper");    assert_eq!(opened["settings"]["knobs"]["size"], json!(1.0));    assert_eq!(opened["settings"]["knobs"]["publisher_styles"], true);    assert_eq!(opened["highlights"], json!([]));    let faces: Vec<&str> = opened["fan"]["faces"]["cards"].as_array().unwrap().iter().map(|card| card["label"].as_str().unwrap()).collect();    assert_eq!(faces, ["Paper", "Sepia", "Night"]);    assert_eq!(opened["fan"]["faces"]["raised"], "face-paper");    // The hand opens one flat tier: the faces, then the knobs, resting on the face chosen.    let hand: Vec<&str> = opened["fan"]["hand"]["cards"].as_array().unwrap().iter().map(|card| card["id"].as_str().unwrap()).collect();    assert_eq!(hand, ["face-paper", "face-sepia", "face-night", "knob-size", "knob-line_height", "knob-margins", "knob-typeface", "knob-layout", "knob-follow"]);    assert_eq!(opened["fan"]["hand"]["raised"], "face-paper");    assert_eq!(opened["fan"]["hand"]["cards"][0], opened["fan"]["faces"]["cards"][0]);    assert_eq!(opened["fan"]["hand"]["cards"][3]["label"], "Type size");    assert_eq!(opened["fan"]["hand"]["cards"][3]["words"], "100%");    assert_eq!(opened["fan"]["hand"]["cards"][3]["choices"]["raised"], "choice-1");    assert_eq!(opened["fan"]["hand"]["cards"][3]["choices"]["cards"][3], json!({"id": "choice-3", "label": "145%", "value": 1.45}));    assert_eq!(opened["fan"]["knobs"], Value::Null, "the knobs are no tier of their own");    assert_eq!(opened["fan"]["note_hint"], "Why you marked it");    let marked: Vec<&str> = opened["fan"]["highlight"]["cards"].as_array().unwrap().iter().map(|card| card["label"].as_str().unwrap()).collect();    assert_eq!(marked, ["Red", "Yellow", "Teal", "Note", "Remove"]);    assert_eq!(opened["fan"]["highlight"]["cards"][4]["red"], true);    assert_eq!(opened["fan"]["selection"]["raised"], "pencil-yellow");    assert_eq!(opened["refusals"]["locked"], "This book is locked by its seller and cannot open here.");    let first = at("OEBPS/ch01.xhtml", 0.034, 3);    let answer = ask(&client, "reader.moved", json!({"book": book, "at": first, "active": true}));    assert_eq!(answer["wrote"], true);    assert_eq!(answer["progress_words"], "3%");    assert_eq!(answer["at"]["page_label"], "3", "an EPUB's page is Readium's position");    let data = book_of(&client, &book);    assert_eq!(data["status"], "reading");    assert_eq!(data["started_on"].as_str().map(str::len), Some(10));    assert_eq!(data["progress"], json!(3));    assert_eq!(serde_json::from_str::<Value>(data["position"].as_str().unwrap()).unwrap(), first);    assert!(data["position_at"].as_str().is_some());    assert!(data["file"].is_string() && data["format"] == "epub", "{data}");    ask(&client, "reader.moved", json!({"book": book, "active": true, "closing": true}));    let again = ask(&client, "shell.reader", json!({"book": book}));    assert_eq!(again["start_on_open"], false);    assert_eq!(serde_json::from_str::<Value>(again["at"]["locator"].as_str().unwrap()).unwrap(), first);    assert_eq!(again["at"]["progress"], json!(3));    assert_eq!(again["progress_words"], "3%");    // A place asked (a highlight's Open in book) stands before the stopped one.    let asked = at("OEBPS/ch09.xhtml", 0.8, 90);    let there = ask(&client, "shell.reader", json!({"book": book, "at": asked.to_string()}));    assert_eq!(serde_json::from_str::<Value>(there["at"]["locator"].as_str().unwrap()).unwrap(), asked);    // A book being read is never started again, and a finished one is not either.    let finished = a_book(&client, "epub", "finished");    ask(&client, "reader.moved", json!({"book": finished, "at": first, "active": true, "closing": true}));    assert_eq!(book_of(&client, &finished)["status"], "finished");}// RULE: a turn at a reader's pace is written as it is made; moves within two seconds of a write coalesce into one write of the newest place, written once two seconds have passed (again_ms says when to ask), at once when the app leaves the foreground or the reader closes, never while the app is inactive, and a place reported while inactive is dropped when it is active again.#[test]fn moves_within_two_seconds_coalesce_to_one_write() {    let (_dir, client, clock) = attached_on_a_clock();    let book = a_book(&client, "epub", "reading");    let position = |client: &ClientController| serde_json::from_str::<Value>(book_of(client, &book)["position"].as_str().unwrap_or("null")).unwrap();    let base = book_writes(&client);    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "at": at("c1.xhtml", 0.10, 1), "active": true}))["wrote"], true);    // A page read and turned: written as it is turned.    clock.advance(chrono::Duration::seconds(30));    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "at": at("c1.xhtml", 0.105, 2), "active": true}))["wrote"], true);    assert_eq!(book_writes(&client) - base, 2, "each turn at a reader's pace is its own write");    // Skimmed: the turns inside two seconds wait.    clock.advance(chrono::Duration::milliseconds(500));    let second = ask(&client, "reader.moved", json!({"book": book, "at": at("c1.xhtml", 0.11, 3), "active": true}));    assert_eq!(second["wrote"], false);    assert_eq!(second["again_ms"], json!(1_500));    assert_eq!(second["progress_words"], "11%", "the bar says where the page is, written or not");    clock.advance(chrono::Duration::milliseconds(700));    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "at": at("c1.xhtml", 0.12, 4), "active": true}))["wrote"], false);    assert_eq!(position(&client), at("c1.xhtml", 0.105, 2));    clock.advance(chrono::Duration::milliseconds(700));    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "active": true}))["wrote"], false, "1.9 seconds is not two");    clock.advance(chrono::Duration::milliseconds(100));    let tick = ask(&client, "reader.moved", json!({"book": book, "active": true}));    assert_eq!(tick["wrote"], true);    assert_eq!(tick["again_ms"], Value::Null);    assert_eq!(position(&client), at("c1.xhtml", 0.12, 4), "the newest place");    assert_eq!(book_writes(&client) - base, 3, "two skimmed moves, one write in the window");    // Leaving the foreground writes what waits at once.    clock.advance(chrono::Duration::milliseconds(500));    ask(&client, "reader.moved", json!({"book": book, "at": at("c2.xhtml", 0.20, 9), "active": true}));    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "active": false}))["wrote"], true);    assert_eq!(position(&client), at("c2.xhtml", 0.20, 9));    // Inactive, Readium's stale place is never taken; active again, it is gone.    clock.advance(chrono::Duration::seconds(30));    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "at": at("c1.xhtml", 0.10, 1), "active": false}))["wrote"], false);    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "active": true}))["wrote"], false);    assert_eq!(position(&client), at("c2.xhtml", 0.20, 9));    // Closing writes what waits at once, inside the window.    ask(&client, "reader.moved", json!({"book": book, "at": at("c2.xhtml", 0.21, 10), "active": true}));    ask(&client, "reader.moved", json!({"book": book, "at": at("c2.xhtml", 0.22, 11), "active": true}));    assert_eq!(ask(&client, "reader.moved", json!({"book": book, "active": true, "closing": true}))["wrote"], true);    assert_eq!(position(&client), at("c2.xhtml", 0.22, 11));    assert_eq!(call_on(&client, "reader.moved", &json!({"book": book, "at": at("c1.xhtml", 0.1, 1)})).expect_err("no app state").code, "bad_request");    assert_eq!(call_on(&client, "reader.moved", &json!({"book": book, "active": true, "at": {"page": 2}})).expect_err("no href").code, "bad_request");}// RULE: a highlight is made at its place in a pencil with the words selected, its chapter and page the page's own; it is recoloured, given a note, and removed; shell.reader lists the book's highlights as the page draws them; a pencil no reader has, or a change to a made highlight's place, is refused.#[test]fn a_highlight_is_made_recoloured_noted_and_removed() {    let (_dir, client, _clock) = attached_on_a_clock();    let book = a_book(&client, "epub", "reading");    let contents = json!({"toc": [{"title": "One", "href": "c1.xhtml"}, {"title": "Two", "href": "c2.xhtml#start"}], "reading_order": ["c1.xhtml", "c2.xhtml"]});    let moved = ask(&client, "reader.moved", json!({"book": book, "at": at("c2.xhtml", 0.5, 40), "contents": contents, "active": true}));    assert_eq!(moved["at"]["chapter"], "Two");    let passage = json!({"href": "c2.xhtml", "locations": {"totalProgression": 0.505}, "text": {"highlight": "An invented line."}});    let made = ask(&client, "reader.highlight", json!({"book": book, "at": passage, "pencil": "teal", "words": "An invented line."}));    let id = made["id"].as_str().expect("its id").to_string();    assert_eq!(made["pencil"], "teal");    assert_eq!(made["words"], "An invented line.");    assert_eq!(made["chapter"], "Two");    let row = crate::phone::records::call(&client, "records.get", &json!({"table": "highlight", "id": id})).unwrap()["data"].clone();    assert_eq!(row["book"], json!(book));    assert_eq!(row["progress"], json!(50));    assert_eq!(row["page_label"], "40");    assert_eq!(row["colour"], "teal");    assert_eq!(ask(&client, "reader.highlight", json!({"id": id, "pencil": "red"}))["pencil"], "red");    let noted = ask(&client, "reader.highlight", json!({"id": id, "note": "  Why it matters  "}));    assert_eq!(noted["note"], "Why it matters");    assert_eq!(noted["pencil"], "red");    let opened = ask(&client, "shell.reader", json!({"book": book}));    let listed = opened["highlights"].clone();    assert!(listed.is_array(), "{opened}");    assert_eq!(listed.as_array().map(Vec::len), Some(1));    assert_eq!(listed[0]["id"], json!(id));    assert_eq!(listed[0]["note"], "Why it matters");    assert_eq!(serde_json::from_str::<Value>(listed[0]["at"].as_str().unwrap()).unwrap(), passage);    // Note on a selection names no pencil: it is made in yellow.    let second = ask(&client, "reader.highlight", json!({"book": book, "at": passage, "words": "Another.", "note": "Mine"}));    assert_eq!(second["note"], "Mine");    assert_eq!(second["pencil"], "yellow");    assert_eq!(ask(&client, "reader.highlight", json!({"id": id, "remove": true})), json!({"id": id, "removed": true}));    let left = ask(&client, "shell.reader", json!({"book": book}))["highlights"].clone();    assert_eq!(left.as_array().map(Vec::len), Some(1));    assert_eq!(left[0]["id"], second["id"]);    for refused in [        json!({"book": book, "at": passage, "pencil": "green", "words": "x"}),        json!({"book": book, "pencil": "red", "words": "x"}),        json!({"id": second["id"], "words": "changed"}),        json!({"id": second["id"]}),        json!({"id": second["id"], "remove": true, "pencil": "red"}),    ] {        assert_eq!(call_on(&client, "reader.highlight", &refused).expect_err("refused").code, "bad_request", "{refused}");    }}// RULE: the face and the knobs are written to the face_settings row keyed reader (the face riding with every write), line height and margins set the book's own styles aside, a choice no knob offers is refused, a choice already worn writes nothing, and the row as written is what every open reads; following the phone wears Night while the phone is dark.#[test]fn the_face_and_knobs_persist_on_the_reader_row() {    let (_dir, client, _clock) = attached_on_a_clock();    let book = a_book(&client, "epub", "reading");    let set = ask(&client, "reader.settings", json!({"knob": "size", "value": 1.2}));    assert_eq!(set["settings"]["knobs"]["size"], json!(1.2));    assert_eq!(set["fan"]["hand"]["cards"][3]["words"], "120%");    let row = || crate::phone::records::call(&client, "records.get", &json!({"table": "face_settings", "id": "reader"})).expect("the reader row")["data"].clone();    assert_eq!(row()["font_size"], json!(1.2));    assert_eq!(row()["face"], "paper", "the face rides with every write");    ask(&client, "reader.settings", json!({"knob": "line_height", "value": 1.8}));    assert_eq!(row()["line_height"], json!(1.8));    assert_eq!(row()["publisher_styles"], false);    let night = ask(&client, "reader.settings", json!({"face": "night"}));    assert_eq!(night["settings"]["worn"], "night");    assert_eq!(night["fan"]["faces"]["raised"], "face-night");    assert_eq!(night["fan"]["hand"]["raised"], "face-night");    ask(&client, "reader.settings", json!({"knob": "typeface", "value": "dyslexic"}));    let opened = ask(&client, "shell.reader", json!({"book": book}));    assert_eq!(opened["settings"]["face"], "night");    assert_eq!(opened["settings"]["knobs"]["size"], json!(1.2));    assert_eq!(opened["settings"]["knobs"]["line_height"], json!(1.8));    assert_eq!(opened["settings"]["knobs"]["typeface"], "dyslexic");    assert_eq!(opened["fan"]["hand"]["cards"][4]["words"], "Open");    assert_eq!(opened["fan"]["hand"]["cards"][4]["choices"]["raised"], "choice-2");    ask(&client, "reader.settings", json!({"face": "sepia"}));    ask(&client, "reader.settings", json!({"knob": "follow", "value": true}));    assert_eq!(ask(&client, "shell.reader", json!({"book": book, "dark": true}))["settings"]["worn"], "night");    assert_eq!(ask(&client, "shell.reader", json!({"book": book, "dark": false}))["settings"]["worn"], "sepia");    let before = client.with_file(|file| file.driver.get("SELECT COUNT(*) AS n FROM _outbox WHERE tbl = 'cotton_face_settings'", &[]).map_err(|error| error.to_string()).map(|row| row.and_then(|row| row.int("n")).unwrap_or(0))).unwrap();    ask(&client, "reader.settings", json!({"face": "sepia"}));    let after = client.with_file(|file| file.driver.get("SELECT COUNT(*) AS n FROM _outbox WHERE tbl = 'cotton_face_settings'", &[]).map_err(|error| error.to_string()).map(|row| row.and_then(|row| row.int("n")).unwrap_or(0))).unwrap();    assert_eq!(before, after, "the face already worn writes nothing");    for refused in [json!({"knob": "size", "value": 3.0}), json!({"knob": "weight", "value": "bold"}), json!({"face": "green"}), json!({"face": "night", "knob": "size", "value": 1.0}), json!({})] {        assert_eq!(call_on(&client, "reader.settings", &refused).expect_err("refused").code, "bad_request", "{refused}");    }}/// An EPUB's bytes on this phone, its container holding `entries`.fn epub_here(client: &ClientController, book: &str, entries: &[(&str, &str)]) {    let key = book_of(client, book)["file"].as_str().expect("a file").to_string();    let path = client.layout().client_media_dir().join(crate::fixture::WORKSPACE).join(key.rsplit('/').next().expect("a name"));    std::fs::create_dir_all(path.parent().expect("a folder")).expect("the media folder");    let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).expect("the file"));    let options = zip::write::SimpleFileOptions::default();    for (name, text) in [("mimetype", "application/epub+zip"), ("META-INF/container.xml", "<container/>")].iter().chain(entries) {        zip.start_file(*name, options).expect("an entry");        zip.write_all(text.as_bytes()).expect("its bytes");    }    zip.finish().expect("the archive");    let size = std::fs::metadata(&path).expect("its size").len() as i64;    client        .with_writer(|replica| {            cotton_store::media_ledger::enqueue_media(                replica.driver,                &cotton_store::media_ledger::MediaEnqueueInput {                    key: key.clone(),                    workspace_id: replica.workspace_id.to_string(),                    sha256: "c".repeat(64),                    content_type: "application/epub+zip".to_string(),                    size_bytes: size,                    local_path: Some(path.to_string_lossy().to_string()),                    state: Some("synced".to_string()),                    after: None,                    after_row_id: None,                    tier: None,                    captured_here: false,                    now: "2026-11-05T10:00:00.000Z".to_string(),                },            )            .map(|_| ())            .map_err(|error| error.to_string())        })        .expect("the ledger row");}// RULE: a locked book answers its refusal line and nothing more: an EPUB on this phone whose container holds an LCP licence or Adobe's rights, or names its text encrypted under a scheme nothing here decrypts; font obfuscation is not a lock; a book with no file the reader opens answers the could-not-open line.#[test]fn a_locked_book_answers_its_refusal_line() {    let (_dir, client, _clock) = attached_on_a_clock();    let locked_line = json!("This book is locked by its seller and cannot open here.");    let encrypted = r#"<encryption><EncryptedData><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/></EncryptedData></encryption>"#;    let obfuscated = r#"<encryption><EncryptedData><EncryptionMethod Algorithm='http://www.idpf.org/2008/embedding'/></EncryptedData></encryption>"#;    for entries in [vec![("META-INF/encryption.xml", encrypted)], vec![("META-INF/license.lcpl", "{}")], vec![("META-INF/rights.xml", "<rights/>")]] {        let book = a_book(&client, "epub", "reading");        epub_here(&client, &book, &entries);        let answer = ask(&client, "shell.reader", json!({"book": book}));        assert_eq!(answer, json!({"book": book, "refusal": locked_line}), "{entries:?}");    }    let open = a_book(&client, "epub", "reading");    epub_here(&client, &open, &[("META-INF/encryption.xml", obfuscated), ("OEBPS/c1.xhtml", "<html/>")]);    assert!(ask(&client, "shell.reader", json!({"book": open})).get("refusal").is_none(), "font obfuscation opens");    let empty = id_of(crate::phone::records::call(&client, "records.create", &json!({"table": "book", "data": {"title": "No file yet"}})).expect("a book"));    assert_eq!(ask(&client, "shell.reader", json!({"book": empty})), json!({"book": empty, "refusal": "This book could not be opened"}));}// RULE: a PDF's page is its printed label (iv, 12) where the page has one, else Readium's position; its chapter is the last contents entry at or before the page.#[test]fn a_pdf_says_its_printed_page_label() {    let (_dir, client, _clock) = attached_on_a_clock();    let book = a_book(&client, "pdf", "reading");    let contents = json!({"toc": [{"title": "Preface", "href": "doc.pdf#page=1"}, {"title": "Chapter 1", "href": "doc.pdf#page=5"}], "reading_order": ["doc.pdf"]});    let page = |position: i64| json!({"href": "doc.pdf", "type": "application/pdf", "locations": {"position": position, "totalProgression": position as f64 / 100.0}});    let answer = ask(&client, "reader.moved", json!({"book": book, "at": page(4), "page_label": "iv", "contents": contents, "active": true}));    assert_eq!(answer["at"]["page_label"], "iv");    assert_eq!(answer["at"]["chapter"], "Preface");    let answer = ask(&client, "reader.moved", json!({"book": book, "at": page(7), "page_label": null, "active": true}));    assert_eq!(answer["at"]["page_label"], "7", "a page with no label says its position");    assert_eq!(answer["at"]["chapter"], "Chapter 1");    let answer = ask(&client, "reader.moved", json!({"book": book, "at": page(8), "page_label": "3", "active": true}));    assert_eq!(answer["at"]["page_label"], "3");}// RULE: shell.reader only reads: it is said away and retried as a read.#[test]fn shell_reader_is_a_read() {    assert!(crate::methods::read_only("shell.reader"));    for write in ["reader.moved", "reader.highlight", "reader.settings"] {        assert!(!crate::methods::read_only(write), "{write}");    }}