PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge main into fix/undo-in-open-text-editor
RiceDee86e61bd669b0
diff --cc crates/ui-egui/src/content_ui.rsindex 66ff781bb,d966b04a5..9ebe009af--- a/crates/ui-egui/src/content_ui.rs+++ b/crates/ui-egui/src/content_ui.rs@@@ -571,20 -570,34 +581,36 @@@ pub(crate) fn editor(ctx: &egui::Contex// 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);+ // Laid out as the page draws it, so opening the box doesn't show it realigned.+ // shortcut: justified text is shown left-aligned here (TextEdit can't justify), until the editor gets its own layouter.+ let halign = match t.style.align {+ pdfcraft_engine::TextAlign::Center => egui::Align::Center,+ pdfcraft_engine::TextAlign::Right => egui::Align::Max,+ pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify => egui::Align::Min,+ };+ // Character spacing shows as the page will draw it, scaled like the font.+ let letter_spacing = (t.style.char_spacing * f64::from(zoom)) as f32;+ let mut spaced = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {+ let job = spaced_job(text.as_str(), &font, Color32::from_rgb(cr, cg, cb), letter_spacing, wrap_width, halign);+ ui.fonts_mut(|f| f.layout_job(job))+ };+ let input = input_id();+ crate::edit_text_ui::forget_typing_before(ui.ctx(), input, doc_id, &mut t.typing_from, &t.style.text);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(input),- );+ let mut edit = egui::TextEdit::multiline(&mut t.text)+ .font(font.clone())+ .desired_width(width)+ .desired_rows(1)+ .horizontal_align(halign)+ .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");++ .id(input);+ if letter_spacing != 0.0 {+ edit = edit.layouter(&mut spaced);+ }+ let resp = ui.add(edit);if t.focus {resp.request_focus();t.focus = false;diff --cc crates/ui-egui/src/edit_text_ui.rsindex 8e5bf8d36,65c7bd780..d72931fa1--- a/crates/ui-egui/src/edit_text_ui.rs+++ b/crates/ui-egui/src/edit_text_ui.rs@@@ -1870,6 -1838,57 +1870,58 @@@ mod testsassert!(app.views[0].line_editor.is_some(), "the paragraph stays open for editing");}+ #[test]+ fn save_applies_the_paragraph_open_in_the_editor() {+ // Save wrote the file without the paragraph still open in the editor (#3496).+ let (mut app, mut ed) = preview_app();+ ed.text = "Text preview".into();+ app.views[0].line_editor = Some(ed);+ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-paragraph-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned());++ assert!(app.save_active(crate::SaveTarget::InPlace));+ assert!(app.views[0].line_editor.is_none());+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_refused_text_box_does_not_lose_the_open_paragraph() {+ let (mut app, mut ed) = preview_app();+ ed.text = "Text preview".into();+ app.views[0].line_editor = Some(ed);+ let draft = crate::content_ui::TextDraft {+ page: 9,+ index: None,+ rect: [20.0, 20.0, 120.0, 40.0],+ text: "Typed text".into(),+ style: crate::content_ui::default_style(),+ focus: true,++ typing_from: None,+ };+ app.views[0].content.draft = Some(draft.clone());++ assert!(!app.commit_typing_in(app.views[0].id));+ assert_eq!(app.views[0].content.draft, Some(draft), "the refused text box stays open");+ assert!(app.views[0].line_editor.is_none(), "the paragraph was applied");+ let doc = app.session.get(app.views[0].id).unwrap();+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");+ }++ #[test]+ fn a_refused_paragraph_stays_open_with_its_text() {+ let (mut app, mut ed) = preview_app();+ ed.text = "Text preview".into();+ ed.page = 9;+ app.views[0].line_editor = Some(ed.clone());++ assert!(!app.commit_typing_in(app.views[0].id));+ assert_eq!(app.views[0].line_editor, Some(ed), "the paragraph keeps its unsaved text");+ }+#[test]fn text_background_is_cached_without_editing_and_released_on_cancel() {let (app, ed) = preview_app();diff --cc crates/ui-egui/src/editing.rsindex 99cd53eff,7ed6e0795..455f8db4c--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@@ -1238,21 -1233,33 +1329,45 @@@ fn bookmark_at<'a>(items: &'a [pdfcraftif rest.is_empty() { Some(item) } else { bookmark_at(&item.children, rest) }}+/// The box's own Redo, as the key does it: the typing Undo took back, put back in the box's text,+/// with the box's history and cursor moved along. None when the box has nothing to redo.+fn redo_typing(ctx: &egui::Context, id: egui::Id, text: &str) -> Option<String> {+ let mut state = egui::TextEdit::load_state(ctx, id)?;+ let mut undoer = state.undoer();+ let (range, redone) = undoer.redo(&(state.cursor.char_range()?, text.to_owned()))?.clone();+ state.set_undoer(undoer);+ state.cursor.set_char_range(Some(range));+ egui::TextEdit::store_state(ctx, id, state);+ Some(redone)+}+#[cfg(test)]mod tests {- use super::{SaveTarget, is_mail_temp_copy, write_atomically, write_atomically_syncing, write_atomically_with};+ use super::{SaveTarget, is_mail_temp_copy, save_dialog_folder, write_atomically, write_atomically_syncing, write_atomically_with};++ #[test]+ fn save_dialogs_open_in_the_documents_folder() {+ use std::path::PathBuf;+ assert_eq!(save_dialog_folder(Some("/home/a/plans/f.pdf")), Some(PathBuf::from("/home/a/plans")));+ // A new document has no folder yet; a bare name has an empty parent; the root has none.+ assert_eq!(save_dialog_folder(None), None);+ assert_eq!(save_dialog_folder(Some("f.pdf")), None);+ assert_eq!(save_dialog_folder(Some("/")), None);+ // An email attachment's temporary copy is not offered.+ assert_eq!(save_dialog_folder(Some("C:\\Users\\a\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Outlook\\AB12\\f.pdf")), None);+ assert_eq!(save_dialog_folder(Some("/Users/a/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/UUID/f.pdf")), None);+ }++ /// The Windows rules for `Path::parent` (UNC share roots included) only apply on Windows.+ #[cfg(windows)]+ #[test]+ fn save_dialog_folder_handles_unc_paths() {+ use std::path::PathBuf;+ assert_eq!(save_dialog_folder(Some(r"\\nas\projets\2026\f.pdf")), Some(PathBuf::from(r"\\nas\projets\2026")));+ assert_eq!(save_dialog_folder(Some(r"\\nas\projets\f.pdf")), Some(PathBuf::from(r"\\nas\projets\")));+ assert_eq!(save_dialog_folder(Some(r"\\nas\projets")), None);+ assert_eq!(save_dialog_folder(Some(r"C:\Users\a\f.pdf")), Some(PathBuf::from(r"C:\Users\a")));+ }use pdfcraft_platform::staging::{STAGING_ATTEMPTS, staging_suffixes};use std::path::{Path, PathBuf};@@@ -1526,45 -1536,32 +1644,72 @@@out}+ /// `one_page_pdf`, opening without a password, whose permissions refuse changes.+ fn no_changes_pdf() -> Vec<u8> {+ let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(one_page_pdf())).unwrap();+ let encryption = pdfcraft_cos::NewEncryption {+ algorithm: pdfcraft_cos::Algorithm::Aes256,+ user_password: "",+ owner_password: "owner",+ permissions: -1 ^ 8,+ encrypt_metadata: true,+ seed: [4; 32],+ };+ doc.set_encryption(&encryption).unwrap();+ pdfcraft_cos::write_full(&doc, &Default::default()).unwrap()+ }++ /// Undo with a new text box open on a document that refuses changes: the box is put back as+ /// it was. Finishing it had asked for the new item to be selected, and that request stayed+ /// behind once the add was refused.+ #[test]+ fn a_refused_text_box_is_put_back_whole() {+ let mut app = crate::PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("a.pdf", None, no_changes_pdf()).unwrap();+ let style = crate::content_ui::default_style();+ app.views[0].content.draft = Some(crate::content_ui::TextDraft {+ page: 0,+ index: None,+ rect: [20.0, 20.0, 120.0, 40.0],+ text: "Typed".into(),+ style,+ focus: false,+ typing_from: None,+ });+ app.undo();+ let content = &app.views[0].content;+ assert_eq!(content.draft.as_ref().map(|d| d.text.as_str()), Some("Typed"), "the refused box stays open");+ assert_eq!(content.select_added, None, "nothing was added to select");+ }++ #[test]+ fn save_commits_the_open_text_box() {+ let dir = staging_dir("open-text-box");+ let dest = dir.join("out.pdf");+ let mut app = crate::PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("a.pdf", None, one_page_pdf()).unwrap();+ app.save_override = Some(dest.to_string_lossy().into_owned());+ let style = crate::content_ui::default_style();+ app.views[0].content.draft = Some(crate::content_ui::TextDraft {+ page: 0,+ index: None,+ rect: [20.0, 20.0, 120.0, 40.0],+ text: "Typed text".into(),+ style,+ focus: true,++ typing_from: None,+ });++ assert!(app.save_active(SaveTarget::InPlace));+ let id = app.views[0].id;+ let added = app.session.get(id).unwrap().added();+ assert_eq!(added.len(), 1, "the open text box was committed before the save");+ assert!(app.views[0].content.draft.is_none());+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn save_asks_where_to_keep_an_email_attachment_and_leaves_the_temporary_copy_alone() {let dir = staging_dir("mail-temp");diff --cc crates/ui-egui/tests/it/editing.rsindex dd6300365,75afd2a01..4b26d26d2--- a/crates/ui-egui/tests/it/editing.rs+++ b/crates/ui-egui/tests/it/editing.rs@@@ -5981,167 -6256,32 +6256,197 @@@ fn mode_tabs_keep_the_hand_over_a_paragassert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Convert, "the tab takes the click, not the paragraph's editor");}+/// The paragraph opened for typing, as a person opens it: a click on its text.+fn open_paragraph(h: &mut Harness<'static, PdfCraftApp>) {+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let at = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());+ click_at(h, at);+ assert!(h.state().views[0].line_editor.is_some(), "the paragraph opens for typing");+}++/// Ctrl+Z after a formatting change, with the paragraph still open: the change is undone and+/// the editor closes. The box's own Undo used to take the key, putting back the text it had+/// before the change into a box laid out for the page after it, and the document kept the change.+#[test]+fn undo_with_the_paragraph_open_undoes_the_formatting() {+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ open_paragraph(&mut h);+ h.get_by_label("Bold").click();+ h.run_steps(4);+ {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ assert_eq!(doc.can_undo(), Some("Edit text"));+ assert_eq!(doc.text_blocks(0)[0].base_font, "Helvetica-Bold");+ assert!(s.views[0].line_editor.is_some(), "still editing");+ }+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(4);+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ assert_eq!(doc.can_undo(), None, "the formatting is undone");+ assert_eq!(doc.text_blocks(0)[0].base_font, "Helvetica");+ assert!(s.views[0].line_editor.is_none(), "the editor closed with the step it showed");+}++/// Undo while typing takes back the typing in the box first; the document is left alone.+#[test]+fn undo_while_typing_takes_back_the_typing_first() {+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ open_paragraph(&mut h);+ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+ h.event(egui::Event::Text(" more".into()));+ h.run_steps(2);+ assert_ne!(h.state().views[0].line_editor.as_ref().unwrap().text, original);+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(3);+ let s = h.state();+ let ed = s.views[0].line_editor.as_ref().expect("still typing");+ assert_eq!(ed.text, original, "the typing is taken back");+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "the document is untouched");+}++/// Redo after Undo in the box puts the typing back, in the box: it doesn't reach the document,+/// whose own Redo (a formatting change waiting here) must stay waiting.+#[test]+fn redo_after_undoing_typing_puts_the_typing_back() {+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ open_paragraph(&mut h);+ h.get_by_label("Bold").click();+ h.run_steps(4);+ // Undo the bold (closing the editor), so the document has it to redo.+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(4);+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_redo(), Some("Edit text"));+ open_paragraph(&mut h);+ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+ h.event(egui::Event::Text(" more".into()));+ h.run_steps(2);+ let typed = h.state().views[0].line_editor.as_ref().unwrap().text.clone();+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(3);+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the typing is taken back");+ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);+ h.run_steps(3);+ let s = h.state();+ let ed = s.views[0].line_editor.as_ref().expect("still typing");+ assert_eq!(ed.text, typed, "Redo puts the typing back");+ let doc = s.session.get(s.views[0].id).unwrap();+ assert_eq!((doc.can_redo(), doc.text_blocks(0)[0].base_font.as_str()), (Some("Edit text"), "Helvetica"), "the document's Redo still waits");+}++/// Redo from the menu or toolbar with typing in the box the page doesn't have yet. Closing the+/// box first applied the typing, a new edit that dropped the document's waiting Redo, and the+/// Redo itself then failed: the step was gone. The typing now stays in the box and the Redo+/// waits; once Undo in the box takes the typing back, Redo from the menu puts it back there.+#[test]+fn redo_from_the_menu_with_typing_in_the_box_keeps_the_documents_redo() {+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ open_paragraph(&mut h);+ h.get_by_label("Bold").click();+ h.run_steps(4);+ // Undo the bold (closing the editor), so the document has it to redo.+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(4);+ open_paragraph(&mut h);+ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+ h.event(egui::Event::Text(" more".into()));+ h.run_steps(2);+ let typed = h.state().views[0].line_editor.as_ref().unwrap().text.clone();+ assert!(h.state_mut().execute("edit.redo"));+ h.run_steps(3);+ {+ let s = h.state();+ let ed = s.views[0].line_editor.as_ref().expect("the box stays open");+ assert_eq!(ed.text, typed, "the typing stays in the box, unapplied");+ let doc = s.session.get(s.views[0].id).unwrap();+ assert_eq!((doc.can_redo(), doc.text_blocks(0)[0].base_font.as_str()), (Some("Edit text"), "Helvetica"), "the document's Redo still waits");+ }+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(3);+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "Undo takes the typing back in the box");+ assert!(h.state_mut().execute("edit.redo"));+ h.run_steps(3);+ let s = h.state();+ assert_eq!(s.views[0].line_editor.as_ref().expect("still open").text, typed, "Redo from the menu puts the typing back");+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_redo(), Some("Edit text"), "the document's Redo still waits");+}++/// Two copies of a document, the same paragraph open in each. The paragraph boxes share one text+/// box, and so one Undo history: a box opened on the same text as another tab's didn't clear it.+/// Typing in one tab, taken back with Undo, then came back with Redo in the other tab.+#[test]+fn typing_in_one_tab_never_reaches_another_tabs_paragraph() {+ let mut h = harness(1, |app| {+ app.open_bytes("copy.pdf", None, fixture(1)).expect("the copy opens");+ });+ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {+ h.state_mut().active = Some(tab);+ h.run_steps(2);+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");+ click_at(h, egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height()));+ assert!(h.state().views[tab].line_editor.is_some(), "the paragraph opens for typing");+ };+ open_in(&mut h, 1);+ let original = h.state().views[1].line_editor.as_ref().unwrap().text.clone();+ open_in(&mut h, 0);+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the same paragraph");+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+ h.event(egui::Event::Text(" secret".into()));+ h.run_steps(2);+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(3);+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "taken back");+ // The copy, its paragraph still open: Redo there has nothing of its own to put back.+ h.state_mut().active = Some(1);+ h.run_steps(3);+ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);+ h.run_steps(3);+ let s = h.state();+ let text = s.views[1].line_editor.as_ref().map(|ed| ed.text.clone());+ assert!(!text.as_deref().unwrap_or_default().contains("secret"), "the other tab's typing came in: {text:?}");+ assert_eq!(s.session.get(s.views[1].id).unwrap().text_blocks(0)[0].text, s.session.get(s.views[0].id).unwrap().text_blocks(0)[0].text);+}+++ /// A paragraph selected by its frame goes with one Delete (or Backspace), as in Acrobat, instead+ /// of being emptied a typed character at a time, and undo brings it back.+ #[test]+ fn a_paragraph_selected_by_its_frame_deletes_with_one_key() {+ for key in [Key::Delete, Key::Backspace] {+ let mut h = harness(2, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ let id = h.state().views[0].id;+ let blocks = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(id).unwrap().text_blocks(0);+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let k = r.width() / 200.0;+ let screen = |x: f64, y: f64| egui::pos2(r.left() + x as f32 * k, r.top() + (300.0 - y as f32) * k);+ let b = blocks(&h)[0].clone();+ click_at(&mut h, screen((b.rect[0] + b.rect[2]) / 2.0, (b.rect[1] + b.rect[3]) / 2.0));+ assert!(h.state().views[0].line_editor.is_some(), "a click on the text opens it for typing");+ click_at(&mut h, screen((b.rect[0] + b.rect[2]) / 2.0, b.rect[3]) - egui::vec2(0.0, 4.0));+ assert!(h.state().views[0].line_editor.is_none(), "the frame selects the box");+ press(&mut h, Modifiers::NONE, key);+ assert!(blocks(&h).is_empty(), "{key:?} deletes the whole paragraph: {:?}", blocks(&h));+ assert!(h.state().views[0].line_editor.is_none(), "no empty editor is left behind");+ assert!(h.query_all_by_label_contains("object selected").next().is_none(), "the deleted paragraph is no longer selected");+ assert_eq!(h.state().session.get(id).unwrap().text_blocks(1)[0].text, "Page 2", "the next page keeps its text");+ assert_eq!(h.state().session.get(id).unwrap().info.pages.len(), 2, "Delete removed the paragraph, not a page");+ assert!(h.state_mut().execute("edit.undo"));+ h.run_steps(2);+ assert_eq!(blocks(&h).iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Page 1"], "undo restores it");+ }+ }