PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Keep document view state consistent when closing tabs and reverting (#439)
sanyamsingh001561377eb1f45
diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rsindex e8b9aad57..1d1b69025 100644--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@ -427,7 +427,13 @@ impl PdfCraftApp {if let Some(i) = self.active&& let Some(d) = self.session.get(id){- self.views[i].document_changed(&d.info);+ let view = &mut self.views[i];+ view.document_changed(&d.info);+ // Revert discards this source's uncommitted typing as well as model edits.+ // Otherwise a later Save could write a rejected draft back into the file.+ view.forms.focus = None;+ view.forms.committed = None;+ view.pending_edit = None;}self.notify_tr("Reverted to the last saved version");}@@ -796,3 +802,95 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}}++#[cfg(test)]+mod revert_draft_tests {+ use super::*;+ use crate::forms_ui::Focus;+ use pdfcraft_engine::FieldValue;++ fn focus(text: &str) -> Focus {+ Focus {+ name: "name".into(),+ widget: 0,+ text: text.into(),+ picked: Vec::new(),+ request_focus: false,+ select_all: false,+ calendar: None,+ calendar_rect: None,+ }+ }++ fn app() -> PdfCraftApp {+ let mut app = PdfCraftApp::new();+ app.open_bytes("source.pdf", None, include_bytes!("../tests/data/form.pdf").to_vec()).unwrap();+ app+ }++ fn queue_draft(app: &mut PdfCraftApp, index: usize, text: &str) {+ app.views[index].forms.focus = Some(focus(text));+ let form = app.session.get(app.views[index].id).unwrap().form.clone();+ crate::forms_ui::commit(&mut app.views[index], &form);+ assert!(app.views[index].forms.committed.is_some() && app.views[index].pending_edit.is_some());+ }++ #[test]+ fn successful_revert_clears_focused_or_queued_drafts_only_on_its_document() {+ for queued in [false, true] {+ let mut app = app();+ let source = app.views[0].id;+ assert!(app.apply_edit(Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("Committed change".into()) }));+ if queued {+ queue_draft(&mut app, 0, "Queued source draft");+ } else {+ app.views[0].forms.focus = Some(focus("Focused source draft"));+ }+ app.open_bytes("other.pdf", None, include_bytes!("../tests/data/form.pdf").to_vec()).unwrap();+ let other = app.views[1].id;+ assert!(app.apply_edit(Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("Other committed value".into()) }));+ queue_draft(&mut app, 1, "Other queued draft");+ app.views[1].forms.focus = Some(focus("Other focused draft"));+ let other_bytes = app.session.get(other).unwrap().bytes.clone();+ let other_generation = app.session.get(other).unwrap().edit_generation();+ let source_generation = app.session.get(source).unwrap().edit_generation();+ app.active = Some(0);+ app.revert_active();+ let reverted = app.session.get(source).unwrap();+ assert!(!reverted.dirty);+ assert_eq!(reverted.edit_generation(), source_generation + 1);+ assert!(reverted.form.iter().find(|field| field.name == "name").unwrap().value.is_empty());+ assert!(app.views[0].forms.focus.is_none() && app.views[0].forms.committed.is_none() && app.views[0].pending_edit.is_none());+ assert!(!app.has_unsaved_work(0));+ assert_eq!(app.views[1].forms.focus.as_ref().unwrap().text, "Other focused draft");+ assert_eq!(app.views[1].forms.committed.as_ref().unwrap().text, "Other queued draft");+ assert!(+ matches!(&app.views[1].pending_edit, Some(Edit::SetFieldValue { name, value: FieldValue::Text(text) }) if name == "name" && text == "Other queued draft")+ );+ let untouched = app.session.get(other).unwrap();+ assert_eq!(untouched.bytes, other_bytes);+ assert_eq!(untouched.edit_generation(), other_generation);+ assert!(untouched.dirty && app.has_unsaved_work(1));+ assert_eq!(app.active_ids(), Some((0, source)));+ }+ }++ #[test]+ fn failed_revert_preserves_focused_and_queued_drafts() {+ let mut app = app();+ let source = app.views[0].id;+ queue_draft(&mut app, 0, "Queued draft");+ app.views[0].forms.focus = Some(focus("Focused draft"));+ // Exercise the ordinary NoDocument error boundary without a corrupt fixture.+ // This verifies UI failure preservation, not other engine refresh failures.+ app.session.close(source);+ app.revert_active();+ assert_eq!(app.views[0].forms.focus.as_ref().unwrap().text, "Focused draft");+ assert_eq!(app.views[0].forms.committed.as_ref().unwrap().text, "Queued draft");+ assert!(+ matches!(&app.views[0].pending_edit, Some(Edit::SetFieldValue { name, value: FieldValue::Text(text) }) if name == "name" && text == "Queued draft")+ );+ assert_eq!(app.active_ids(), Some((0, source)));+ assert_eq!(app.toast.as_ref().unwrap().0, pdfcraft_engine::EditError::NoDocument.to_string());+ }+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 91f2edd88..3770168b0 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1036,6 +1036,7 @@ impl PdfCraftApp {self.session.close(id);self.active = match self.active {_ if self.views.is_empty() => None,+ Some(a) if a > index => Some(a - 1),Some(a) if a >= self.views.len() => Some(self.views.len() - 1),other => other,};diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rsindex f4f3552da..57a80dff1 100644--- a/crates/ui-egui/tests/forms.rs+++ b/crates/ui-egui/tests/forms.rs@@ -401,3 +401,77 @@ fn flattening_while_typing_flattens_the_typed_text() {.unwrap_or_default();assert!(text.contains("Flat Ada"), "into the page: {text:?}");}++#[cfg(not(target_arch = "wasm32"))]+mod revert_tests {+ use super::*;+ use egui_kittest::kittest::Queryable;+ use std::path::PathBuf;+ use std::sync::atomic::{AtomicU64, Ordering};++ struct RevertDir(PathBuf);+ impl RevertDir {+ fn new() -> Self {+ static NEXT: AtomicU64 = AtomicU64::new(0);+ for _ in 0..128 {+ let path = std::env::temp_dir().join(format!("pdfcraft-revert-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));+ match std::fs::create_dir(&path) {+ Ok(()) => return Self(path),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,+ Err(error) => panic!("creating Revert test directory: {error}"),+ }+ }+ panic!("no unused Revert test directory after 128 attempts");+ }+ }+ impl Drop for RevertDir {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ #[test]+ fn reverting_rejected_input_saves_the_original_field_and_appearance() {+ let dir = RevertDir::new();+ let path = dir.0.join("saved.pdf");+ let mut h = harness();+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldValue {+ name: "name".into(),+ value: pdfcraft_engine::FieldValue::Text("Saved original".into()),+ }));+ h.state_mut().save_override = Some(path.to_string_lossy().into_owned());+ assert!(h.state_mut().save_active(pdfcraft_ui_egui::SaveTarget::InPlace));+ let saved = std::fs::read(&path).unwrap();+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps {+ name: "name".into(),+ props: Box::new(pdfcraft_engine::FieldProps {+ validate: Some(pdfcraft_engine::form_scripts::Validate::Range { min: Some(0.0), max: Some(10.0) }),+ ..Default::default()+ }),+ }));+ h.run_steps(3);+ click_field(&mut h, "name", 0);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text("99".into()));+ h.run_steps(2);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S);+ h.run_steps(4);+ assert_eq!(h.state().views[0].forms.focus.as_ref().unwrap().text, "99");+ assert_eq!(std::fs::read(&path).unwrap(), saved, "rejection leaves the saved file untouched");+ assert!(h.state_mut().execute("file.revert"));+ h.run_steps(2);+ h.get_all_by_label("Revert").last().expect("confirmation button").click();+ h.run_steps(4);+ assert!(h.state().views[0].forms.focus.is_none() && h.state().views[0].pending_edit.is_none());+ assert_eq!(h.state().first_dirty(), None, "Revert discards rejected typing too");+ assert_eq!(value(&h, "name"), ["Saved original"]);+ assert!(h.state_mut().save_active(pdfcraft_ui_egui::SaveTarget::InPlace));+ assert_eq!(saved_value(&path, "name"), ["Saved original"]);+ let bytes = std::fs::read(&path).unwrap();+ assert_eq!(bytes, saved, "later Save cannot resurrect the discarded draft");+ let mut renderer = pdfcraft_render::PageRenderer::new(std::sync::Arc::new(bytes), Default::default());+ let output = renderer.render(pdfcraft_render::RenderRequest { page: 0, kind: pdfcraft_render::RequestKind::Text, ..Default::default() });+ assert!(output.error.is_none(), "saved appearance is readable: {:?}", output.error);+ assert!(output.text.unwrap().plain_text().contains("Saved original"), "saved AP still draws the original value");+ }+}diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rsindex 2582ce88c..27fa3bc50 100644--- a/crates/ui-egui/tests/ui.rs+++ b/crates/ui-egui/tests/ui.rs@@ -485,3 +485,94 @@ fn opening_a_pdf_keeps_a_closed_left_panel_and_the_chosen_tool() {assert_eq!(app.mode, Mode::AllTools);assert_eq!(app.left, LeftPanel::Tool("export"));}++fn three_tab_harness() -> Harness<'static, PdfCraftApp> {+ harness(|app| {+ for name in ["first.pdf", "middle.pdf", "last.pdf"] {+ app.open_bytes(name, None, FIXTURE.to_vec()).unwrap();+ }+ })+}++fn close_named_tab(h: &mut Harness<'static, PdfCraftApp>, name: &str) {+ // The close button has no separate accessible label. Its centre is defined by+ // chrome::tab relative to the actual accessible tab rectangle, not a viewport guess.+ let pos = h.get_by_label(name).rect().right_center() - egui::vec2(16.0, 0.0);+ h.event(egui::Event::PointerMoved(pos));+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });+ h.run_steps(3);+}++#[test]+fn closing_tabs_keeps_the_selected_document_or_selects_its_neighbor() {+ for removed in [0, 1, 2] {+ let mut h = three_tab_harness();+ let ids: Vec<_> = h.state().views.iter().map(|view| view.id).collect();+ h.get_by_label("middle.pdf").click();+ h.run_steps(3);+ assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[1]));+ close_named_tab(&mut h, ["first.pdf", "middle.pdf", "last.pdf"][removed]);+ let expected = if removed == 1 { ids[2] } else { ids[1] };+ let app = h.state();+ assert_eq!(app.active_ids().map(|(_, id)| id), Some(expected), "removed tab {removed}");+ assert_eq!(+ app.views.iter().map(|view| view.id).collect::<Vec<_>>(),+ ids.iter().copied().enumerate().filter_map(|(i, id)| (i != removed).then_some(id)).collect::<Vec<_>>()+ );+ assert_eq!(app.session.docs().len(), 2);+ assert!(app.session.get(ids[removed]).is_none());+ assert!(app.close_request.is_none(), "clean tabs close without a prompt");+ for doc in app.session.docs() {+ assert_eq!(doc.bytes.as_slice(), FIXTURE);+ assert!(!doc.dirty);+ }+ }+}++#[test]+fn closing_the_last_active_tab_selects_the_previous_one_then_home() {+ let mut h = three_tab_harness();+ let ids: Vec<_> = h.state().views.iter().map(|view| view.id).collect();+ for (removed, name) in [(2usize, "last.pdf"), (1, "middle.pdf"), (0, "first.pdf")] {+ close_named_tab(&mut h, name);+ let app = h.state();+ assert_eq!(app.active_ids().map(|(_, id)| id), removed.checked_sub(1).map(|index| ids[index]));+ assert_eq!(app.views.len(), removed);+ assert_eq!(app.session.docs().len(), removed);+ assert!(app.session.get(ids[removed]).is_none());+ }+ assert_eq!(h.state().active, None);+ h.get_by_label_contains("Welcome to PdfCraft");+}++#[test]+fn cancelling_then_discarding_an_earlier_dirty_tab_preserves_the_selected_document() {+ let mut h = three_tab_harness();+ let ids: Vec<_> = h.state().views.iter().map(|view| view.id).collect();+ h.get_by_label("first.pdf").click();+ h.run_steps(3);+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetInfo { key: "Title".into(), value: "Unsaved title".into() }));+ h.run_steps(3);+ h.get_by_label("middle.pdf").click();+ h.run_steps(3);+ close_named_tab(&mut h, "first.pdf (edited)");+ assert_eq!(h.state().close_request, Some(pdfcraft_ui_egui::CloseRequest::Tab(ids[0])));+ h.get_by_label("Cancel").click();+ h.run_steps(3);+ assert_eq!(h.state().views.len(), 3);+ assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[1]));+ assert!(h.state().session.get(ids[0]).unwrap().dirty);+ close_named_tab(&mut h, "first.pdf (edited)");+ h.get_by_label("Don't save").click();+ h.run_steps(3);+ assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[1]));+ assert_eq!(h.state().views.iter().map(|view| view.id).collect::<Vec<_>>(), [ids[1], ids[2]]);+ assert!(h.state().session.get(ids[0]).is_none());+ assert!(h.state().close_request.is_none());+ for doc in h.state().session.docs() {+ assert_eq!(doc.bytes.as_slice(), FIXTURE);+ assert!(!doc.dirty);+ }+}