PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge r2 track t03: viewer-ui
aiongg2bd66fbe9031
diff --cc ROADMAP.mdindex f19c158c4,66da69e4a..338e5f838--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -172,8 -173,11 +174,12 @@@ Ranked; detail and the full milestone t| 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 |## Progress log+- **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.+ - **2026-10-20 (M4, initial view):** Window and interface options read indirect boolean ViewerPreferences values. Synthetic regressions cover true/false, direct/indirect preference dictionaries and save/reopen; malformed entries retain false defaults. Estimates unchanged.+ - **2026-10-20 (M3, #3535):** Escape with a menu open closes the menu and keeps the text selection; the next Escape clears it, as before. One keypress used to do both. A synthetic UI regression checks it. Estimates unchanged.+ - **2026-10-16 (M3, close prompt keyboard):** The "Save changes?" prompt opens with Save chosen (Enter saves, as before) and the arrow keys and Tab / Shift+Tab move the choice to Cancel or Don't save, shown with a focus ring; Enter or Space press the chosen button and Escape still cancels. Before, Enter always saved whatever was Tab-focused. Estimates unchanged.+ - **2026-10-21 (M3, #3808):** Page thumbnails in the Inspector can be resized independently from the document and Organize, with a slider, buttons and `thumbnail-zoom` control option. Selection, page following and reload are covered by regressions. Estimates unchanged.- **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged.- **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged.- **2026-10-19 (M6, renames keep formulas):** Renaming a field renames it in every calculation that reads it, in the same undo step: `AFSimple_Calculate` field lists, simplified field notation (the comment and the JavaScript after it) and `getField` calls naming it in one string literal; the rest of each script is kept as written. A sum used to drop the renamed field, notation read it as 0 and a script kept a stale value. Field Properties says how many formulas changed and `form_set_props` lists them as `formulas_updated`. Names built at run time and other events' scripts are not rewritten. Estimates unchanged.diff --cc crates/automation/tests/automation.rsindex 12e525aa9,60c193c49..cf07add24--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@@ -7094,189 -6976,63 +7096,250 @@@ fn text_box_and_callout_fill_and_border}}+/// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading+/// of #2516. A third Alpha row brings its last baseline within 2.5 × size of Bravo's, so the next+/// read groups the two as one paragraph.+fn three_paragraph_pdf() -> Vec<u8> {+ use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};+ use std::sync::Arc;++ let content = "BT /F1 12 Tf 14.4 TL 1 0 0 1 10 250 Tm (Alpha paragraph, first row.) Tj T* (Alpha paragraph, second row.) Tj ET \+ BT /F1 12 Tf 14.4 TL 1 0 0 1 10 200 Tm (Bravo paragraph, a single row.) Tj ET \+ BT /F1 12 Tf 14.4 TL 1 0 0 1 10 150 Tm (Charlie paragraph, first row.) Tj T* (Charlie paragraph, second row.) Tj ET";+ let mut doc = Document::open(Arc::new(fixture(1))).unwrap();+ doc.set(ObjRef::new(5, 0), Object::Stream(Stream::flate(Dict::new(), content.as_bytes())));+ write_full(&doc, &SaveOptions::default()).unwrap()+}++/// A one-page PDF whose second paragraph is drawn over the first one's box, as an OCR text layer+/// or a stamp would be.+fn overlaid_paragraph_pdf() -> Vec<u8> {+ use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};+ use std::sync::Arc;++ let content = "BT /F1 12 Tf 14.4 TL 1 0 0 1 10 250 Tm (Alpha paragraph, first row.) Tj T* (Alpha paragraph, second row.) Tj ET \+ BT /F1 12 Tf 14.4 TL 1 0 0 1 10 243 Tm (Zulu overlay.) Tj ET";+ let mut doc = Document::open(Arc::new(fixture(1))).unwrap();+ doc.set(ObjRef::new(5, 0), Object::Stream(Stream::flate(Dict::new(), content.as_bytes())));+ write_full(&doc, &SaveOptions::default()).unwrap()+}++/// Emptying a paragraph that another paragraph overlaps must not hand the emptied paragraph's+/// number to the neighbour that took over its box: the next edit by that number would rewrite it.+#[test]+fn an_emptied_paragraph_does_not_pass_its_number_to_an_overlapping_neighbour() {+ let dir = workdir("text-edit-overlap-number");+ std::fs::write(dir.join("p.pdf"), overlaid_paragraph_pdf()).unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({"path":"p.pdf"}))["doc"].as_u64().unwrap();+ let listed = ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ assert_eq!(listed["count"], 2, "{listed}");+ let k = listed["paragraphs"].as_array().unwrap().iter().position(|p| p["text"].as_str().unwrap().starts_with("Alpha")).unwrap() + 1;++ let first = ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":k,"text":""}));+ assert_eq!(first["stale_paragraphs"], json!([k]), "the emptied paragraph's number is gone: {first}");+ let again = a.call("text_edit", &json!({"doc":doc,"page":1,"paragraph":k,"text":"Rewritten."}));+ assert!(matches!(&again, Err(ToolError::InvalidArgs(m)) if m.contains("text_paragraphs")), "{again:?}");+ assert!(page_text(&mut a, doc).join(" ").contains("Zulu overlay."), "the neighbour is untouched");+ std::fs::remove_dir_all(dir).unwrap();+}++/// #2516: a paragraph number names the paragraph `text_paragraphs` listed. When an edit regroups+/// the page so that paragraph no longer exists on its own, the next edit by that number is+/// refused. It used to rewrite whichever paragraph had taken the number, and that text was gone.+#[test]+fn text_edit_refuses_a_paragraph_number_an_earlier_edit_regrouped() {+ let dir = workdir("text-edit-stale-number");+ std::fs::write(dir.join("p.pdf"), three_paragraph_pdf()).unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({"path":"p.pdf"}))["doc"].as_u64().unwrap();+ let listed = ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ assert_eq!(listed["count"], 3);+ assert!(listed["paragraphs"][1]["text"].as_str().unwrap().starts_with("Bravo"));++ // Listing again here would renumber the page, so the first edit's result says what moved.+ let first = ok(+ &mut a,+ "text_edit",+ json!({"doc":doc,"page":1,"paragraph":1,"text":"Alpha paragraph, first row.\nAlpha paragraph, second row.\nAlpha paragraph, a third row."}),+ );+ assert_eq!(first["stale_paragraphs"], json!([1, 2]), "the third row regroups Alpha with Bravo: {first}");++ // Paragraph 2 of the earlier listing was Bravo, which is now part of Alpha's paragraph.+ let stale = a.call("text_edit", &json!({"doc":doc,"page":1,"paragraph":2,"text":"Bravo paragraph, edited."}));+ assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("text_paragraphs")), "{stale:?}");+ let text = page_text(&mut a, doc).join(" ");+ assert!(text.contains("Charlie paragraph, first row."), "Charlie is untouched: {text}");+ assert!(text.contains("Charlie paragraph, second row."), "Charlie is untouched: {text}");+ assert!(!text.contains("Bravo paragraph, edited."), "nothing was rewritten: {text}");++ // After listing again, the number names what the listing says.+ let relisted = ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ assert!(relisted["paragraphs"][1]["text"].as_str().unwrap().starts_with("Charlie"));+ ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":2,"text":"Charlie paragraph, edited."}));+ let text = page_text(&mut a, doc).join(" ");+ assert!(text.contains("Charlie paragraph, edited.") && text.contains("Alpha paragraph, a third row."), "{text}");+ std::fs::remove_dir_all(dir).unwrap();+}++/// An edit that merges its paragraph into a neighbour leaves no paragraph of its own to follow:+/// the merged one holds the edited text too, but rewriting it by the edited paragraph's number+/// would drop the neighbour's text (#2516).+#[test]+fn text_edit_does_not_follow_a_paragraph_into_the_one_it_merged_with() {+ let dir = workdir("text-edit-merged-number");+ std::fs::write(dir.join("p.pdf"), three_paragraph_pdf()).unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({"path":"p.pdf"}))["doc"].as_u64().unwrap();+ ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ let first = ok(+ &mut a,+ "text_edit",+ json!({"doc":doc,"page":1,"paragraph":1,"text":"Alpha paragraph, first row.\nAlpha paragraph, second row.\nAlpha paragraph, a third row."}),+ );+ assert!(first.get("paragraph").is_none(), "the result must not present the merged paragraph as the edited one: {first}");++ // Paragraph 1 was Alpha. Alpha now shares a paragraph with Bravo, so the number is refused.+ let again = a.call("text_edit", &json!({"doc":doc,"page":1,"paragraph":1,"text":"Alpha only."}));+ assert!(matches!(&again, Err(ToolError::InvalidArgs(m)) if m.contains("text_paragraphs")), "{again:?}");+ let text = page_text(&mut a, doc).join(" ");+ assert!(text.contains("Bravo paragraph, a single row."), "Bravo is untouched: {text}");+ assert!(!text.contains("Alpha only."), "nothing was rewritten: {text}");+ std::fs::remove_dir_all(dir).unwrap();+}++/// The editor background preview takes the same paragraph number as `text_edit`, so it hides the+/// paragraph the number named in the listing and refuses a number an edit made stale (#2516).+#[test]+fn page_render_hide_text_block_refuses_a_paragraph_number_an_earlier_edit_regrouped() {+ let dir = workdir("hide-text-block-stale-number");+ std::fs::write(dir.join("p.pdf"), three_paragraph_pdf()).unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({"path":"p.pdf"}))["doc"].as_u64().unwrap();+ ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ ok(+ &mut a,+ "text_edit",+ json!({"doc":doc,"page":1,"paragraph":1,"text":"Alpha paragraph, first row.\nAlpha paragraph, second row.\nAlpha paragraph, a third row."}),+ );++ // Paragraph 2 of the listing was Bravo, now inside Alpha's paragraph; position 2 is Charlie.+ let stale = a.call("page_render", &json!({"doc":doc,"page":1,"dpi":72,"hide_text_block":2}));+ assert!(matches!(&stale, Err(ToolError::InvalidArgs(m)) if m.contains("text_paragraphs")), "{:?}", stale.map(|_| ()));+ // Paragraph 3 of the listing is Charlie, wherever it is now.+ assert!(a.call("page_render", &json!({"doc":doc,"page":1,"dpi":72,"hide_text_block":3})).is_ok());+ std::fs::remove_dir_all(dir).unwrap();+}++/// The listings kept for paragraph numbers are capped. A page whose listing was dropped must not+/// fall back to reading its numbers as positions, which an edit may have regrouped: it is refused+/// until the page is listed again (#2516).+#[test]+fn text_edit_refuses_a_paragraph_number_whose_listing_was_dropped_at_the_cap() {+ let dir = workdir("text-edit-evicted-listing");+ std::fs::write(dir.join("p.pdf"), three_paragraph_pdf()).unwrap();+ let mut a = auto(&dir);+ let open = |a: &mut Automation| ok(a, "doc_open", json!({"path":"p.pdf"}))["doc"].as_u64().unwrap();+ let doc = open(&mut a);+ ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ // 256 more pages fill the cap, so the next new page drops every earlier listing.+ let others: Vec<u64> = (0..256).map(|_| open(&mut a)).collect();+ for &other in &others {+ ok(&mut a, "text_paragraphs", json!({"doc":other,"page":1}));+ }++ let dropped = a.call("text_edit", &json!({"doc":doc,"page":1,"paragraph":2,"text":"Bravo paragraph, edited."}));+ assert!(matches!(&dropped, Err(ToolError::InvalidArgs(m)) if m.contains("text_paragraphs")), "{dropped:?}");+ assert!(!page_text(&mut a, doc).join(" ").contains("Bravo paragraph, edited."), "nothing was rewritten");+ let hidden = a.call("page_render", &json!({"doc":doc,"page":1,"dpi":72,"hide_text_block":2}));+ assert!(matches!(&hidden, Err(ToolError::InvalidArgs(m)) if m.contains("text_paragraphs")), "{:?}", hidden.map(|_| ()));++ // A page listed after the drop keeps its numbers, and so does the page once it is listed again.+ ok(&mut a, "text_edit", json!({"doc":others[255],"page":1,"paragraph":2,"text":"Bravo paragraph, edited."}));+ ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":2,"text":"Bravo paragraph, edited."}));+ assert!(page_text(&mut a, doc).join(" ").contains("Bravo paragraph, edited."));+ std::fs::remove_dir_all(dir).unwrap();+}++/// A number from the listing keeps naming its paragraph while other paragraphs are edited, and+/// a paragraph can be edited twice in a row by the same number.+#[test]+fn text_edit_numbers_survive_edits_that_do_not_regroup() {+ let dir = workdir("text-edit-stable-number");+ std::fs::write(dir.join("p.pdf"), three_paragraph_pdf()).unwrap();+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({"path":"p.pdf"}))["doc"].as_u64().unwrap();+ ok(&mut a, "text_paragraphs", json!({"doc":doc,"page":1}));+ ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":3,"text":"Charlie one.\nCharlie two."}));+ ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":1,"text":"Alpha one.\nAlpha two."}));+ ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":1,"text":"Alpha again.\nAlpha two."}));+ ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":3,"text":"Charlie once more.\nCharlie two."}));+ // A rewrite rewraps at the width of the widest row, so compare without line breaks.+ let text = page_text(&mut a, doc).join(" ").split_whitespace().collect::<Vec<_>>().join(" ");+ for want in ["Alpha again.", "Bravo paragraph, a single row.", "Charlie once more."] {+ assert!(text.contains(want), "{want}: {text}");+ }+ std::fs::remove_dir_all(dir).unwrap();+}+++ /// Where the first bookmark on `path` goes, as `bookmark_list` reports it: points from the+ /// top-left of the displayed page.+ fn bookmark_destination(a: &mut Automation, doc: u64, title: &str) -> Value {+ let list = ok(a, "bookmark_list", json!({ "doc": doc }))["bookmarks"].clone();+ let row = list.as_array().unwrap().iter().find(|r| r["title"] == title).unwrap_or_else(|| panic!("{title} in {list}"));+ row["destination"].clone()+ }++ #[test]+ fn a_bookmark_added_at_a_position_reports_the_same_position_back_on_any_page_rotation() {+ let dir = workdir("bookmark-position");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ ok(&mut a, "page_rotate", json!({ "doc": doc, "pages": [3], "degrees": 90 }));+ let near = |v: &Value, want: Option<f64>, what: &str| match want {+ Some(w) => assert!((v.as_f64().unwrap_or_else(|| panic!("{what}: {v}")) - w).abs() < 0.05, "{what}: {v} vs {w}"),+ None => assert!(v.is_null(), "{what}: {v}"),+ };+ // Page 1 upright, page 3 turned a quarter: a displayed top and left come back as given.+ for (page, title) in [(1, "Upright"), (3, "Turned")] {+ for (suffix, left, top) in [(" both", Some(72.5), Some(120.25)), (" top", None, Some(200.0)), (" left", Some(50.0), None)] {+ let name = format!("{title}{suffix}");+ let mut args = json!({ "doc": doc, "title": name, "page": page });+ if let Some(l) = left {+ args["left"] = json!(l);+ }+ if let Some(t) = top {+ args["top"] = json!(t);+ }+ ok(&mut a, "bookmark_add", args);+ let d = bookmark_destination(&mut a, doc, &name);+ assert_eq!(d["fit"], "XYZ", "{name}");+ near(&d["left"], left, &format!("{name} left"));+ near(&d["top"], top, &format!("{name} top"));+ assert!(d["zoom"].is_null(), "the zoom is kept: {name}");+ }+ }+ // No position is the page top at the reader's zoom, as before.+ ok(&mut a, "bookmark_add", json!({ "doc": doc, "title": "Plain", "page": 2 }));+ let plain = bookmark_destination(&mut a, doc, "Plain");+ assert!(plain["left"].is_null() && plain["top"].is_null() && plain["zoom"].is_null(), "{plain}");++ // A position that is not a usable number is refused and adds nothing.+ let before = ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"].clone();+ for bad in [json!("high"), json!(2_000_000), json!(-2_000_000.5), json!(true)] {+ for key in ["top", "left"] {+ let args = json!({ "doc": doc, "title": "Bad", "page": 1, key: bad });+ assert!(matches!(a.call("bookmark_add", &args), Err(ToolError::InvalidArgs(_))), "{key} {bad}");+ }+ }+ assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], before, "nothing was added");++ // It survives a save and reopen.+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "placed.pdf" }));+ let mut b = auto(&dir);+ let re = ok(&mut b, "doc_open", json!({ "path": "placed.pdf" }))["doc"].as_u64().unwrap();+ let d = bookmark_destination(&mut b, re, "Turned both");+ near(&d["left"], Some(72.5), "reopened left");+ near(&d["top"], Some(120.25), "reopened top");+ }diff --cc crates/engine/src/tests.rsindex 808e8aaa8,a2d06d0b1..90d536264--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@ -6148,109 -6242,36 +6242,143 @@@ fn undo_never_makes_an_unsaved_documentassert!(!s.get(new).unwrap().dirty, "once saved, undo back to the saved state is clean");}+#[test]+fn undo_and_redo_roll_back_on_a_refresh_panic_or_error() {+ let (mut s, id) = session_with(1);+ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();+ let (bytes_90, gen_90) = {+ let d = s.get(id).unwrap();+ (d.bytes.clone(), d.generation)+ };++ // 1. A panic during undo's refresh catches the unwind and rolls back cos, undo/redo, info, and working bytes.+ panic_on_refresh(1);+ let err = s.undo(id).unwrap_err();+ assert_eq!(err, EditError::Reopen("injected refresh panic".into()));+ {+ let d = s.get(id).unwrap();+ let ed = d.editor.as_ref().unwrap();+ assert_eq!(d.info.pages[0].rotation, 90);+ assert_eq!(d.bytes, bytes_90);+ assert_eq!(d.generation, gen_90);+ assert!(d.dirty);+ assert!(ed.cos.is_modified());+ assert_eq!(ed.undo.len(), 1);+ assert!(ed.redo.is_empty());+ }+ let _ = shown(&s, id, 0);++ // 2. If the rollback refresh also panics, `show_released` restores the renderer so the page still draws.+ panic_on_refresh(2);+ assert_eq!(s.undo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().editor.as_ref().unwrap().undo.len(), 1);+ let _ = shown(&s, id, 0);++ // Undo now succeeds cleanly.+ assert_eq!(s.undo(id).unwrap().as_str(), "Rotate page");+ let (bytes_0, gen_0) = {+ let d = s.get(id).unwrap();+ assert_eq!(d.info.pages[0].rotation, 0);+ assert!(!d.dirty);+ (d.bytes.clone(), d.generation)+ };++ // 3. A panic during redo's refresh catches the unwind and rolls back to the undone state.+ panic_on_refresh(1);+ let err = s.redo(id).unwrap_err();+ assert_eq!(err, EditError::Reopen("injected refresh panic".into()));+ {+ let d = s.get(id).unwrap();+ let ed = d.editor.as_ref().unwrap();+ assert_eq!(d.info.pages[0].rotation, 0);+ assert_eq!(d.bytes, bytes_0);+ assert_eq!(d.generation, gen_0);+ assert!(!d.dirty);+ assert!(!ed.cos.is_modified());+ assert!(ed.undo.is_empty());+ assert_eq!(ed.redo.len(), 1);+ }+ let _ = shown(&s, id, 0);++ // 4. If redo's rollback refresh also panics, `show_released` restores the renderer.+ panic_on_refresh(2);+ assert_eq!(s.redo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().editor.as_ref().unwrap().redo.len(), 1);+ let _ = shown(&s, id, 0);++ // Redo now succeeds cleanly.+ assert_eq!(s.redo(id).unwrap().as_str(), "Rotate page");+ assert_eq!(s.get(id).unwrap().info.pages[0].rotation, 90);++ // 5. Metadata scope: a panic after `doc.info.title` was written rolls back `info.title` and keeps `edit_notices`.+ s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Draft".into() }).unwrap();+ let notice = TextNotice { field: None, page: 0, ch: '☺', redrawn_elsewhere: false };+ s.doc_mut(id).unwrap().edit_notices.push(notice.clone());+ panic_on_refresh(1);+ assert_eq!(s.undo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().info.title.as_deref(), Some("Draft"));+ assert_eq!(s.get(id).unwrap().edit_notices, [notice]);+ assert_eq!(s.undo(id).unwrap().as_str(), "Change Title");+ assert_eq!(s.get(id).unwrap().info.title, None);+ assert!(s.get(id).unwrap().edit_notices.is_empty());++ panic_on_refresh(1);+ assert_eq!(s.redo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().info.title, None);+ assert_eq!(s.redo(id).unwrap().as_str(), "Change Title");+ assert_eq!(s.get(id).unwrap().info.title.as_deref(), Some("Draft"));++ // 6. Protection keys: undo/redo rollback restores `editor.keys` and `doc.password` before re-inspecting.+ let protect = Protection { open_password: Some("u".into()), permissions_password: Some("o".into()), ..Protection::default() };+ s.apply(id, Edit::Protect(protect)).unwrap();+ assert!(s.get(id).unwrap().info.encrypted);+ panic_on_refresh(1);+ assert_eq!(s.undo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert!(s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password.as_deref(), Some("u"));+ assert_eq!(s.undo(id).unwrap().as_str(), "Protect with password");+ assert!(!s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password, None);++ panic_on_refresh(1);+ assert_eq!(s.redo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert!(!s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password, None);+ assert_eq!(s.redo(id).unwrap().as_str(), "Protect with password");+ assert!(s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password.as_deref(), Some("u"));+}+++ #[test]+ fn a_bookmark_added_at_a_point_goes_there_through_undo_and_save() {+ use pdfcraft_render::DestView;+ let (mut s, id) = session_with(3);+ let view = |s: &Session, i: usize| s.get(id).unwrap().info.outline.get(i).map(|o| (o.page, o.view));+ let add = |s: &mut Session, title: &str, page: usize, left: Option<f64>, top: Option<f64>| {+ s.apply(id, Edit::AddBookmark { parent: vec![], index: usize::MAX, title: title.into(), page, left, top })+ };+ add(&mut s, "Plain", 0, None, None).unwrap();+ add(&mut s, "Section", 1, None, Some(500.5)).unwrap();+ add(&mut s, "Table", 2, Some(72.0), Some(300.0)).unwrap();+ // The page top (no position) is what it always was; the others carry their place.+ assert_eq!(view(&s, 0), Some((Some(0), DestView::Xyz { left: None, top: None, zoom: None })));+ assert_eq!(view(&s, 1), Some((Some(1), DestView::Xyz { left: None, top: Some(500.5), zoom: None })));+ assert_eq!(view(&s, 2), Some((Some(2), DestView::Xyz { left: Some(72.0), top: Some(300.0), zoom: None })));++ // A position that is not a number fails the edit, which then changes nothing.+ for (left, top) in [(Some(f64::NAN), None), (None, Some(f64::INFINITY))] {+ assert!(matches!(add(&mut s, "Bad", 0, left, top), Err(EditError::Bookmark(_))), "{left:?} {top:?}");+ }+ assert_eq!(s.get(id).unwrap().info.outline.len(), 3);+ assert_eq!(s.get(id).unwrap().can_undo(), Some("Add bookmark"));++ s.undo(id).unwrap();+ assert_eq!(s.get(id).unwrap().info.outline.len(), 2);+ s.redo(id).unwrap();+ let saved = s.save_bytes(id).unwrap();+ let mut again = Session::new();+ let id2 = again.open("again.pdf", None, saved, None).unwrap();+ let outline = &again.get(id2).unwrap().info.outline;+ assert_eq!(outline[2].view, DestView::Xyz { left: Some(72.0), top: Some(300.0), zoom: None });+ assert_eq!(outline[1].view, DestView::Xyz { left: None, top: Some(500.5), zoom: None });+ }diff --cc crates/ui-egui/src/content_ui.rsindex d9bc21d02,e943357ef..997df8141--- a/crates/ui-egui/src/content_ui.rs+++ b/crates/ui-egui/src/content_ui.rs@@@ -523,58 -528,63 +528,65 @@@ pub(crate) fn editor(ctx: &egui::Contexlet (mut commit, mut cancel, mut done) = (false, false, false);let mut undrawable = None;let memo = &view.content.undrawable;- // Shown at once, like the paragraph editor: a fade-in shows the page's copy through it.- let area = egui::Area::new(egui::Id::new(("added-text", view.id.0))).fade_in(false);- area.order(egui::Order::Foreground).fixed_pos(r.min).constrain(false).show(ctx, |ui| {- let Some(t) = view.content.draft.as_mut() else { return };- ui.set_width(r.width() + 64.0);- if let Some(source_rect) = source_rect.filter(|_| !background_ready) {- ui.painter().rect_filled(source_rect.union(r).expand(1.0), CornerRadius::ZERO, Color32::WHITE);- }- // The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).- ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);- let [cr, cg, cb] = t.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);- ui.horizontal_top(|ui| {- ui.spacing_mut().item_spacing.x = 4.0;- let resp = ui.add(- egui::TextEdit::multiline(&mut t.text)- .font(font)- .desired_width(r.width().max(60.0))- .desired_rows(1)- .background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })- .text_color(Color32::from_rgb(cr, cg, cb))- .hint_text(tl!("Type text"))- .id_salt("added-text-edit"),- );- if t.focus {- resp.request_focus();- t.focus = false;- // Over the page, so only where the document shows: text scrolled under the mode bar or a side++ // Shown at once, like the paragraph editor: a fade-in shows the page's copy through it. Over++ // the page, so only where the document shows: text scrolled under the mode bar or a side+ // panel must leave them their pointer (#2755).+ egui::Area::new(egui::Id::new(("added-text", view.id.0)))++ .fade_in(false)+ .order(egui::Order::Foreground)+ .fixed_pos(r.min)+ .constrain_to(view.viewport_rect())+ .constrain(false)+ .show(ctx, |ui| {+ let Some(t) = view.content.draft.as_mut() else { return };+ ui.set_width(r.width() + 64.0);+ if let Some(source_rect) = source_rect.filter(|_| !background_ready) {+ ui.painter().rect_filled(source_rect.union(r).expand(1.0), CornerRadius::ZERO, Color32::WHITE);+ }+ // The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).+ ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);+ let [cr, cg, cb] = t.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);+ ui.horizontal_top(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ let resp = ui.add(+ egui::TextEdit::multiline(&mut t.text)+ .font(font)+ .desired_width(r.width().max(60.0))+ .desired_rows(1)+ .background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })+ .text_color(Color32::from_rgb(cr, cg, cb))+ .hint_text(tl!("Type text"))+ .id_salt("added-text-edit"),+ );+ if t.focus {+ resp.request_focus();+ t.focus = false;+ }+ let buttons = egui::Frame::NONE+ .fill(tokens.card)+ .stroke(Stroke::new(1.0, tokens.border))+ .corner_radius(CornerRadius::same(6))+ .inner_margin(2)+ .show(ui, |ui| {+ ui.spacing_mut().item_spacing = egui::vec2(2.0, 2.0);+ ui.horizontal(|ui| {+ done = crate::icons::button(ui, "check", 24.0, false, tl!("Done adding text")).clicked();+ cancel = crate::icons::button(ui, "x", 24.0, false, tl!("Discard this text (Esc)")).clicked();+ });+ })+ .response+ .rect;+ // Pressing a button takes the focus from the text: that is not a click away.+ let on_buttons = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| buttons.contains(p));+ cancel |= ui.input(|i| i.key_pressed(egui::Key::Escape));+ commit = done || resp.lost_focus() && !on_buttons && !view.objects.hold_editor;+ });+ // Page text is drawn with the standard fonts; anything else would be saved as `?` (#125).+ undrawable = self::undrawable(t, memo);+ if let Some(c) = undrawable {+ ui.label(egui::RichText::new(undrawable_message(c)).small().color(UNDRAWABLE));}- let buttons = egui::Frame::NONE- .fill(tokens.card)- .stroke(Stroke::new(1.0, tokens.border))- .corner_radius(CornerRadius::same(6))- .inner_margin(2)- .show(ui, |ui| {- ui.spacing_mut().item_spacing = egui::vec2(2.0, 2.0);- ui.horizontal(|ui| {- done = crate::icons::button(ui, "check", 24.0, false, tl!("Done adding text")).clicked();- cancel = crate::icons::button(ui, "x", 24.0, false, tl!("Discard this text (Esc)")).clicked();- });- })- .response- .rect;- // Pressing a button takes the focus from the text: that is not a click away.- let on_buttons = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| buttons.contains(p));- cancel |= ui.input(|i| i.key_pressed(egui::Key::Escape));- commit = done || resp.lost_focus() && !on_buttons && !view.objects.hold_editor;});- // Page text is drawn with the standard fonts; anything else would be saved as `?` (#125).- undrawable = self::undrawable(t, memo);- if let Some(c) = undrawable {- ui.label(egui::RichText::new(undrawable_message(c)).small().color(UNDRAWABLE));- }- });if cancel {view.content.draft = None;return (None, false);diff --cc crates/ui-egui/src/edit_text_ui.rsindex 5e0e401dc,ec53a2faf..3a1ab0436--- a/crates/ui-egui/src/edit_text_ui.rs+++ b/crates/ui-egui/src/edit_text_ui.rs@@@ -1560,17 -1329,8 +1564,18 @@@ pub(crate) fn overlay(ctx: &egui::Conte.line_editor.as_ref().is_some_and(|ed| view.text_background.ready(ed.page, ed.block) && !ed.source.as_ref().is_some_and(|(b, _)| b.invisible));- let draft_rect = view.text_background.draft_rect.map(|r| xf.user_rect(info, page, r.map(|v| v as f32)));+ // The measured extent of this paragraph's draft: a click straight from another paragraph+ // opens this one after the frame's measuring, which was the other one's.+ let draft_rect = view+ .line_editor+ .as_ref()+ .and_then(|ed| view.text_background.draft_rect_for(ed.page, ed.block))+ .map(|r| xf.user_rect(info, page, r.map(|v| v as f32)));+ // The editor draws on its page only, as the page itself does: a paragraph running past the+ // page's edge (a converter relying on the page clip) must not cover the next page or the+ // tool bars (#3061).- let page_clip = xf.rect.intersect(view.viewport_rect());+ let viewport = view.viewport_rect();++ let page_clip = xf.rect.intersect(viewport);let ed = view.line_editor.as_mut()?;if hold {ed.focus = true;@@@ -1594,17 -1354,16 +1599,22 @@@ed.source.as_ref().and_then(|(block, lines)| block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.size as f32).reduce(f32::min));let font = editor_font(&ed.look, smallest.map_or(ed.size, |s| (s * scale * 0.5).clamp(1.0, 300.0).min(ed.size)));let text_color = color32(ed.look.color);+ let block = ed.block;let mut done = None;+ let mut reveal = false;+ let mut look = None;+ // No fade-in: while it faded, the page's own copy of the text showed through the cover.+ // Over the page, so only where the document shows: a paragraph scrolled under the mode bar or+ // a side panel must leave them their pointer (#2755). It stays at its paragraph, cut off as+ // the page is, rather than pushed back into the window.egui::Area::new(egui::Id::new("edit-text-line")).order(egui::Order::Foreground)+ .fade_in(false).fixed_pos(Pos2::new(ed.rect.left(), ed.rect.top()))+ .constrain_to(viewport)+ .constrain(false).show(ctx, |ui| {+ ui.set_clip_rect(ui.clip_rect().intersect(page_clip));// The editor opens at the source size. Once text changes, show the real draft// extent: single rows grow toward the page edge, paragraphs rewrap at their// source width, and the visible frame grows/shrinks vertically with their rows.diff --cc crates/ui-egui/src/fill_sign.rsindex 39c687243,6677ab157..acf0bd59b--- a/crates/ui-egui/src/fill_sign.rs+++ b/crates/ui-egui/src/fill_sign.rs@@@ -706,35 -706,41 +706,43 @@@ pub(crate) fn type_box(ctx: &egui::Contlet zoom = xf.rect.width() / xf.pw.max(1.0);let mut commit = false;let mut cancel = false;+ // Shown at once, like the paragraph editor: a fade-in shows the page's copy through it.- let area = egui::Area::new(egui::Id::new(("fill-text", view.id.0))).fade_in(false);- area.order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| {- let Some(t) = view.fill_text.as_mut() else { return };- // The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).- ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);- let width = ((t.text.chars().count().max(8) as f32) * t.size as f32 * 0.6 * zoom).clamp(60.0, 600.0);- // The area's max rect is last frame's size, which caps the edit's width; widen it so the- // box grows as text is typed.- ui.set_min_width(width);- let r = ui.add(- egui::TextEdit::singleline(&mut t.text)- .font(egui::FontId::proportional((t.size as f32 * zoom).max(8.0)))- .desired_width(width)- .background_color(Color32::from_rgba_unmultiplied(255, 255, 255, 230))- .text_color(Color32::BLACK)- .hint_text(tl!("Type text"))- .id_salt("fill-text-edit"),- );- if t.focus {- r.request_focus();- t.focus = false;- }- if ui.input(|i| i.key_pressed(egui::Key::Escape)) {- cancel = true;- } else if r.lost_focus() {- commit = true;- }- });+ // Over the page, so only where the document shows: a box scrolled under the mode bar or a+ // side panel must leave them their pointer (#2755). It stays where it was placed, cut off as+ // the page is, rather than pushed back into the window.+ egui::Area::new(egui::Id::new(("fill-text", view.id.0)))++ .fade_in(false)+ .order(egui::Order::Foreground)+ .fixed_pos(pos)+ .constrain_to(view.viewport_rect())+ .constrain(false)+ .show(ctx, |ui| {+ let Some(t) = view.fill_text.as_mut() else { return };+ // The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).+ ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);+ let width = ((t.text.chars().count().max(8) as f32) * t.size as f32 * 0.6 * zoom).clamp(60.0, 600.0);+ // The area's max rect is last frame's size, which caps the edit's width; widen it so the+ // box grows as text is typed.+ ui.set_min_width(width);+ let r = ui.add(+ egui::TextEdit::singleline(&mut t.text)+ .font(egui::FontId::proportional((t.size as f32 * zoom).max(8.0)))+ .desired_width(width)+ .background_color(Color32::from_rgba_unmultiplied(255, 255, 255, 230))+ .text_color(Color32::BLACK)+ .hint_text(tl!("Type text"))+ .id_salt("fill-text-edit"),+ );+ if t.focus {+ r.request_focus();+ t.focus = false;+ }+ if ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ cancel = true;+ } else if r.lost_focus() {+ commit = true;+ }+ });if cancel {view.fill_text = None;return None;diff --cc crates/ui-egui/src/forms_ui.rsindex 60df5bc19,b09107d67..d5edb214c--- a/crates/ui-egui/src/forms_ui.rs+++ b/crates/ui-egui/src/forms_ui.rs@@@ -503,80 -507,87 +507,89 @@@ pub(crate) fn overlay(ctx: &egui::Contematch f.kind {FormFieldKind::Text => {let multiline = f.has(field_flags::MULTILINE);+ // Shown at once, like the paragraph editor: a fade-in shows the field's value through it.- let area = egui::Area::new(egui::Id::new(("form-editor", view.id.0))).fade_in(false);- area.order(egui::Order::Foreground).fixed_pos(rect.min).show(ctx, |ui| {- ui.set_min_size(rect.size());- let Some(fx) = view.forms.focus.as_mut() else { return };- // Sized from the text being typed, so an auto-sized field shrinks to keep it in view.- let font = (field_text_size(ui.painter(), f, w, &fx.text) * zoom).clamp(3.0, 64.0);- // The field is pale yellow in every theme, so the caret must not follow the theme (pale in dark mode) (#655).- ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(FIELD_FILL);- let mut te = if multiline { egui::TextEdit::multiline(&mut fx.text) } else { egui::TextEdit::singleline(&mut fx.text) };- te = te- // Wraps (inside the 3 px side margins) at the width the size was fitted to:- // the box less 3 pt each side, scaled.- .desired_width((rect.width() - 6.0 * zoom + 6.0).max(1.0))- .font(egui::FontId::proportional(font))- .background_color(FIELD_FILL)- .text_color(Color32::BLACK)- .margin(egui::Margin::symmetric(3, 1))- .password(f.has(field_flags::PASSWORD))- .id(egui::Id::new(("form-field", view.id.0, &f.name, focus.widget)));- if let Some(max) = f.max_len {- te = te.char_limit(max);- }- if multiline {- te = te.desired_rows(((rect.height() / (font * 1.3)).floor() as usize).max(1));- }- let mut laid_out = None;- let r = ui.add_sized(rect.size(), |ui: &mut egui::Ui| {- let out = te.show(ui);- laid_out = Some((out.galley, out.galley_pos));- out.response.response- });- if let Some(press) = fx.press.take()- && let Some((galley, pos)) = laid_out- && let Some(mut st) = egui::TextEdit::load_state(ui.ctx(), r.id)- {- // The press went to the page, not to this editor, which did not exist yet.- let at = galley.cursor_from_pos(press - pos + vec2(galley.rect.left(), 0.0));- st.cursor.set_char_range(Some(egui::text::CCursorRange::one(at)));- st.store(ui.ctx(), r.id);- if ui.input(|i| i.pointer.primary_down()) {- ui.ctx().set_dragged_id(r.id);+ // Over the page, so only where the document shows: a field scrolled under the mode bar+ // or a side panel must leave them their pointer (#2755). It stays on its field, cut off+ // as the page is, rather than pushed back into the window.+ egui::Area::new(egui::Id::new(("form-editor", view.id.0)))++ .fade_in(false)+ .order(egui::Order::Foreground)+ .fixed_pos(rect.min)+ .constrain_to(view.viewport_rect())+ .constrain(false)+ .show(ctx, |ui| {+ ui.set_min_size(rect.size());+ let Some(fx) = view.forms.focus.as_mut() else { return };+ // Sized from the text being typed, so an auto-sized field shrinks to keep it in view.+ let font = (field_text_size(ui.painter(), f, w, &fx.text) * zoom).clamp(3.0, 64.0);+ // The field is pale yellow in every theme, so the caret must not follow the theme (pale in dark mode) (#655).+ ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(FIELD_FILL);+ let mut te = if multiline { egui::TextEdit::multiline(&mut fx.text) } else { egui::TextEdit::singleline(&mut fx.text) };+ te = te+ // Wraps (inside the 3 px side margins) at the width the size was fitted to:+ // the box less 3 pt each side, scaled.+ .desired_width((rect.width() - 6.0 * zoom + 6.0).max(1.0))+ .font(egui::FontId::proportional(font))+ .background_color(FIELD_FILL)+ .text_color(Color32::BLACK)+ .margin(egui::Margin::symmetric(3, 1))+ .password(f.has(field_flags::PASSWORD))+ .id(egui::Id::new(("form-field", view.id.0, &f.name, focus.widget)));+ if let Some(max) = f.max_len {+ te = te.char_limit(max);}- }- if fx.request_focus {- r.request_focus();- fx.request_focus = false;- if std::mem::take(&mut fx.select_all)+ if multiline {+ te = te.desired_rows(((rect.height() / (font * 1.3)).floor() as usize).max(1));+ }+ let mut laid_out = None;+ let r = ui.add_sized(rect.size(), |ui: &mut egui::Ui| {+ let out = te.show(ui);+ laid_out = Some((out.galley, out.galley_pos));+ out.response.response+ });+ if let Some(press) = fx.press.take()+ && let Some((galley, pos)) = laid_out&& let Some(mut st) = egui::TextEdit::load_state(ui.ctx(), r.id){- let n = fx.text.chars().count();- st.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n))));+ // The press went to the page, not to this editor, which did not exist yet.+ let at = galley.cursor_from_pos(press - pos + vec2(galley.rect.left(), 0.0));+ st.cursor.set_char_range(Some(egui::text::CCursorRange::one(at)));st.store(ui.ctx(), r.id);+ if ui.input(|i| i.pointer.primary_down()) {+ ui.ctx().set_dragged_id(r.id);+ }}- }- let (enter, esc, tab, shift) = ui- .input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape), i.key_pressed(egui::Key::Tab), i.modifiers.shift));- if esc {- close = true;- } else if tab {- next = Some(!shift);- } else if r.lost_focus()- && (!multiline || !enter)- && !fx.calendar_rect.is_some_and(|c| ui.input(|i| i.pointer.interact_pos().is_some_and(|p| c.contains(p))))- {- if pressed {- // The field reopened with a refused value; keep it open and focused.- fx.request_focus = true;- } else {- // Enter in a single-line field, or clicking elsewhere, commits.- commit(view, form);+ if fx.request_focus {+ r.request_focus();+ fx.request_focus = false;+ if std::mem::take(&mut fx.select_all)+ && let Some(mut st) = egui::TextEdit::load_state(ui.ctx(), r.id)+ {+ let n = fx.text.chars().count();+ st.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n))));+ st.store(ui.ctx(), r.id);+ }}- }- });+ let (enter, esc, tab, shift) = ui.input(|i| {+ (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape), i.key_pressed(egui::Key::Tab), i.modifiers.shift)+ });+ if esc {+ close = true;+ } else if tab {+ next = Some(!shift);+ } else if r.lost_focus()+ && (!multiline || !enter)+ && !fx.calendar_rect.is_some_and(|c| ui.input(|i| i.pointer.interact_pos().is_some_and(|p| c.contains(p))))+ {+ if pressed {+ // The field reopened with a refused value; keep it open and focused.+ fx.request_focus = true;+ } else {+ // Enter in a single-line field, or clicking elsewhere, commits.+ commit(view, form);+ }+ }+ });// Date fields: a calendar under the field (Acrobat's date picker).if let pdfcraft_engine::form_scripts::Format::Date(fmt) = &f.actions.format&& let Some(picked) = calendar(ctx, view, rect, fmt, today)diff --cc crates/ui-egui/tests/editing.rsindex 03e358c3b,1e76eb2cf..39f6f2b1c--- a/crates/ui-egui/tests/editing.rs+++ b/crates/ui-egui/tests/editing.rs@@@ -5543,122 -5211,99 +5753,219 @@@ fn read_mode_shortcut_applies_the_open_assert_eq!(s.session.get(s.views[0].id).unwrap().text_lines(0)[0].text, "Chapter One", "the edit is applied");}+/// #3061: a paragraph running past its page's bottom edge (an HTML converter relying on the+/// page clip) opens in an editor that draws on its page only. It covered the next page.+#[test]+fn a_paragraph_running_off_its_page_edits_without_covering_the_next_page() {+ let text = |first: &str, count: usize, leading: usize| {+ let mut s = String::from("BT /F1 14 Tf\n");+ for i in 0..count {+ s.push_str(&format!("1 0 0 1 72 {} Tm ({first} line {}: the client may cancel this) Tj\n", 720 - (leading * i) as i64, i + 1));+ }+ s.push_str("ET");+ s.into_bytes()+ };+ // Page 1's single paragraph goes down to y = -270; page 2 is ordinary.+ let (one, two) = (text("Page one", 56, 18), text("PAGE TWO", 3, 40));+ let stream = |d: &[u8]| [format!("<< /Length {} >>\nstream\n", d.len()).into_bytes(), d.to_vec(), b"\nendstream".to_vec()].concat();+ let page = |contents: usize| {+ format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents {contents} 0 R /Resources << /Font << /F1 7 0 R >> >> >>")+ .into_bytes()+ };+ let objs: Vec<Vec<u8>> = vec![+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),+ b"<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>".to_vec(),+ page(4),+ stream(&one),+ page(6),+ stream(&two),+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>".to_vec(),+ ];+ let mut bytes = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(bytes.len());+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());+ bytes.extend_from_slice(o);+ bytes.extend_from_slice(b"\nendobj\n");+ }+ let xref = bytes.len();+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 1400.0)).build_eframe(move |_cc| {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("off-page.pdf", None, bytes).unwrap();+ app+ });+ h.run_steps(4);+ h.state_mut().views[0].fit = pdfcraft_ui_egui::canvas::Fit::Page;+ h.run_steps(4);+ let rects =+ |h: &Harness<'static, PdfCraftApp>| (h.state().views[0].page_screen_rect(0).unwrap(), h.state().views[0].page_screen_rect(1).unwrap());+ // The same pages without Edit text, so without the paragraph's outline: what the gap looks+ // like there, pixel by pixel (review on #3070: it isn't one colour on every platform).+ let (first, second) = rects(&h);+ let plain = h.render().unwrap();+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(4);+ assert_eq!(rects(&h), (first, second), "Edit text keeps the pages where they were");+ let id = h.state().views[0].id;+ let info = h.state().session.get(id).unwrap().info.pages[0].clone();+ shown_on_its_page_only(&mut h, &plain, first, second, "the paragraph's outline");+ let v = info.user_to_view(200.0, 378.0);+ let p = first.min + egui::vec2(v[0], v[1]) * (first.width() / info.width);+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ h.drop_at(p);+ for _ in 0..60 {+ h.run_steps(2);+ if !h.state().render_pending() {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(+ h.state().views[0].line_editor.as_ref().is_some_and(|e| e.page == 0 && e.text.contains("line 50")),+ "the paragraph's off-page lines are in it"+ );+ shown_on_its_page_only(&mut h, &plain, first, second, "the open editor");+ // Scrolled up past the tool bar, the editor stays inside the document area.+ let viewport = h.state().views[0].viewport_rect();+ let above = viewport.top() - 3.0;+ let before = h.render().unwrap();+ h.hover_at(egui::pos2(first.right() - 20.0, first.center().y));+ h.event(egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: egui::vec2(0.0, -300.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ });+ h.run_steps(4);+ let scrolled = h.state().views[0].page_screen_rect(0).unwrap();+ assert!(scrolled.top() < viewport.top() - 100.0, "scrolled: {scrolled:?} in {viewport:?}");+ assert!(h.state().views[0].line_editor.is_some(), "still editing");+ let after = h.render().unwrap();+ for x in (first.left() as u32 + 70)..(first.left() as u32 + 420) {+ assert_eq!(after.get_pixel(x, above as u32), before.get_pixel(x, above as u32), "above the document area at x = {x}");+ }+}++/// Between pages `first` and `second`, and on `second` above its own text, across where page+/// 1's paragraph is: what is there without it (the gap as `plain` shows it without Edit text,+/// white paper).+fn shown_on_its_page_only(h: &mut Harness<'static, PdfCraftApp>, plain: &image::RgbaImage, first: egui::Rect, second: egui::Rect, what: &str) {+ let shot = h.render().unwrap();+ let pixel = |x: f32, y: f32| shot.get_pixel(x as u32, y as u32).0;+ let gap_y = (first.bottom() + second.top()) / 2.0;+ for x in (first.left() as u32 + 70)..(first.left() as u32 + 420) {+ let x = x as f32;+ assert_eq!(pixel(x, gap_y), plain.get_pixel(x as u32, gap_y as u32).0, "{what}: between the pages at x = {x}");+ for dy in [4.0, 20.0, 40.0] {+ let [r, g, b, _] = pixel(x, second.top() + dy);+ assert!(r > 240 && g > 240 && b > 240, "{what}: page 2 at {x}, +{dy}: {r},{g},{b}");+ }+ }+}+++ /// Where a mode bar tab is, by its label.+ fn mode_tab(h: &Harness<'static, PdfCraftApp>, label: &str) -> egui::Rect {+ h.get_all_by_role_and_label(Role::Button, label).map(|n| n.rect()).find(|r| r.bottom() < 120.0).expect("a mode tab")+ }++ /// The cursor over each mode bar tab that page 1's text lies under, once that text is scrolled+ /// up under the bar. With the All tools panel closed it lies under Read, Edit, Convert and E-Sign.+ fn mode_tab_cursors(h: &mut Harness<'static, PdfCraftApp>, text: egui::Rect) -> [(&'static str, egui::CursorIcon); 4] {+ h.state_mut().views[0].goto = Some((0, 0.5));+ h.run_steps(4);+ let offset = h.state().views[0].page_screen_rect(0).expect("on screen").top();+ ["Read", "Edit", "Convert", "E-Sign"].map(|label| {+ let at = mode_tab(h, label).center();+ assert!(text.translate(egui::vec2(0.0, offset)).contains(at), "the text lies under {label}");+ h.hover_at(at);+ h.run_steps(2);+ (label, h.output().platform_output.cursor_icon)+ })+ }++ const HAND_ON_EVERY_TAB: [(&str, egui::CursorIcon); 4] = [+ ("Read", egui::CursorIcon::PointingHand),+ ("Edit", egui::CursorIcon::PointingHand),+ ("Convert", egui::CursorIcon::PointingHand),+ ("E-Sign", egui::CursorIcon::PointingHand),+ ];++ /// Page 1's text block on screen, relative to the page's top edge, in the window as it is now.+ fn page_text(h: &Harness<'static, PdfCraftApp>) -> egui::Rect {+ let id = h.state().views[0].id;+ let block = h.state().session.get(id).unwrap().text_blocks(0)[0].clone();+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let k = r.width() / 200.0;+ let at = |x: f64, y: f64| egui::pos2(r.left() + x as f32 * k, (300.0 - y as f32) * k);+ egui::Rect::from_two_pos(at(block.rect[0], block.rect[1]), at(block.rect[2], block.rect[3]))+ }++ /// Text scrolled up under the mode bar leaves its tabs the hand (#2755). The Select tool's+ /// text layer showed its I-beam there, over chrome that hides the page.+ #[test]+ fn mode_tabs_keep_the_hand_over_page_text_scrolled_under_them() {+ let mut h = harness(2, |app| app.set_option("left", "closed").unwrap());+ let text = page_text(&h);+ // Where the page shows, its text takes the I-beam, once the page's text has arrived.+ h.state_mut().views[0].goto = Some((0, 0.3));+ h.run_steps(4);+ let top = h.state().views[0].page_screen_rect(0).expect("on screen").top();+ let mut cursor = egui::CursorIcon::Default;+ for _ in 0..50 {+ h.hover_at(text.center() + egui::vec2(0.0, top));+ h.run_steps(2);+ cursor = h.output().platform_output.cursor_icon;+ if cursor == egui::CursorIcon::Text {+ break;+ }+ }+ assert_eq!(cursor, egui::CursorIcon::Text);+ assert_eq!(mode_tab_cursors(&mut h, text), HAND_ON_EVERY_TAB);+ }++ /// Edit text, then the All tools panel closed, as reported (#2755): a paragraph scrolled up+ /// under the mode bar gave its tabs the four-way arrow, or the I-beam once a paragraph was open.+ /// The open paragraph's editor also covered the tabs and took their clicks.+ #[test]+ fn mode_tabs_keep_the_hand_over_a_paragraph_scrolled_under_them() {+ let mut h = harness(2, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.state_mut().set_option("left", "closed").unwrap();+ h.run_steps(4);+ let text = page_text(&h);+ assert_eq!(mode_tab_cursors(&mut h, text), HAND_ON_EVERY_TAB, "a closed paragraph under the tabs");+ // Open it, where it shows.+ h.state_mut().views[0].goto = Some((0, 0.3));+ h.run_steps(4);+ let top = h.state().views[0].page_screen_rect(0).expect("on screen").top();+ click_at(&mut h, text.center() + egui::vec2(0.0, top));+ assert!(h.state().views[0].line_editor.is_some());+ assert_eq!(mode_tab_cursors(&mut h, text), HAND_ON_EVERY_TAB, "the open paragraph under the tabs");+ // Nor does the editor's frame, with the paragraph's top edge just under a tab (the frame+ // reaches 2 to 6 points outside it).+ let convert = mode_tab(&h, "Convert").center();+ h.state_mut().views[0].goto = Some((0, 0.0));+ h.run_steps(4);+ let page = h.state().views[0].page_screen_rect(0).expect("on screen");+ h.state_mut().views[0].goto = Some((0, (page.top() - (convert.y + 4.0 - text.top())) / page.height()));+ h.run_steps(4);+ let page = h.state().views[0].page_screen_rect(0).expect("on screen");+ assert!((page.top() + text.top() - convert.y - 4.0).abs() < 1.0, "Convert lies on the paragraph's frame");+ h.hover_at(convert);+ h.run_steps(2);+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "the open paragraph's frame under a tab");+ h.state_mut().views[0].goto = Some((0, 0.5));+ h.run_steps(4);+ click_at(&mut h, convert);+ assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Convert, "the tab takes the click, not the paragraph's editor");+ }