diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 71a8bb1280..8beaaaea9c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -664,13 +664,16 @@ impl PdfCraftApp { self.poll_pending_destinations(); } self.check_restored_recent(); - // Showing a document hides the Combine files tab. - if self.active.is_some() { + // Showing a document hides the Combine files tab, and ends its preview. + if self.active.is_some() && self.combine_tab.focused { self.combine_tab.focused = false; + self.close_combine_preview(); } + // The picks first: a file the user picked opens ahead of a startup file that arrived with it, which then waits + // for that open and goes to a background tab. + self.process_picks(ctx); // PLAN: assumed PdfCraftApp::open_intake(&mut self, &egui::Context), which opens what the intake holds (pdf-shell-w13). self.open_intake(ctx); - self.process_picks(ctx); self.present_portfolios(ctx); if let Some((_, id)) = self.active_ids() { let out = self.session.take_js_output(id); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f91ff3bdc4..8e1a3bbd99 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -184,6 +184,9 @@ pub struct DocView { middle_scrolling: bool, pub organize: bool, pub page_input: String, + /// Text was typed into the page box since it last showed a page's label: while the box keeps the focus, + /// navigation leaves that text alone. + pub(crate) page_input_draft: bool, /// Select the replacement page label once if its editor remains focused. pub(crate) page_input_reselect: bool, pub notice_dismissed: bool, @@ -380,9 +383,11 @@ pub struct PageSession { /// The caret and selection in the Fill & Sign text being typed. pub fill_selection: craft::text::ui::editor::TextSelection, pub(crate) signature_drag: crate::signature_drag::SignatureDrag, - /// The rectangle being dragged on a page by Snapshot, Crop or a signature area: the page tools are built each - /// pass, so the drag lives here from its press to its release. + /// The rectangle being dragged on a page by Snapshot, Crop, Redact or a signature area: the page tools are built + /// each pass, so the drag lives here from its press to its release. pub(crate) box_drag: PageBoxDrag, + /// What the Redact tool's press is doing, from the press to its release. + pub(crate) redact_gesture: crate::tools::redact_ui::tool::RedactGesture, /// What the last secondary press on a page went to, and on which page (`None` off the pages): the page's menu /// shows its entries when it has a menu and is the one selected, or else the page's own. pub(crate) menu_for: Option<(usize, Owner)>, @@ -438,6 +443,7 @@ impl PageSession { fill_selection: Default::default(), signature_drag: Default::default(), box_drag: PageBoxDrag::default(), + redact_gesture: Default::default(), menu_for: None, } } @@ -555,6 +561,7 @@ impl DocView { middle_scrolling: false, organize: false, page_input: "1".into(), + page_input_draft: false, page_input_reselect: false, notice_dismissed: false, scripts_off_noted: false, @@ -979,17 +986,25 @@ fn route_press(ui: &egui::Ui, session: &mut PageSession, press: &PagePress, cx: { session.comments.select(Some((press.page, index))); } + // Editing, the picture right-clicked is selected for its menu; a right-click on anything else lets go of it. + if cx.tool == QuickTool::EditText { + let picture = if let Owner::Picture { index, .. } = press.owner { Some(index) } else { None }; + crate::edit_text_ui::picture_context(press.page, picture, session); + } + if let Some(origin) = press.phase.start().map(|start| start.origin) { + session.comments.context_at = session.user_point_at(geo, cx.info, origin); + } session.menu_for = Some((press.page, press.owner.clone())); return; } let clicked = matches!(press.phase, PressPhase::Release { click: true, .. }); + // A press a part takes is no picture pick, and takes back an earlier click whose picture is still being found. + session.pending_pick = None; match &press.owner { Owner::Link { .. } | Owner::TextLink { .. } => { // Read before acting: the links borrow the session. let event = links_of(session, cx, body).read(press); if let Some(event) = event { - // A click on a link is not a picture pick (pdf-canvas-w12 note 5). - session.pending_pick = None; match event { LinkEvent::Follow { target, javascript } => out.link = Some((target, javascript)), LinkEvent::Select { .. } | LinkEvent::Context { .. } => crate::link_ui::link_edit_press(&mut session.links, &event), @@ -1087,6 +1102,10 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, session.objects.notice = Some(why.into()); } out.view = reply.view; + // The page menu hangs where the request is: Paste, Copy Image and a comment added there read the point. + if let Some(request) = &reply.context { + session.comments.context_at = session.user_point_at(cx.geometry(body), cx.info, request.at); + } out.context = reply.context; out.back_to_select = finish.back_to_select; out.snapshot = finish.snapshot; diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index 831c5dbb3b..0755b946cf 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -303,7 +303,8 @@ pub(crate) fn page_tool<'a>( .find(|placed| placed.rect.contains(at)) .is_some_and(|placed| texts.app(placed.page).is_some_and(|layer| layer.glyph_box_at(placed.to_page(at)).is_some())) }; - Arm::Redact(RedactTool::new(select, cx.pages, cx.rotation, cx.info, over_text)) + let (drag, gesture) = (&mut session.box_drag, &mut session.redact_gesture); + Arm::Redact(RedactTool::new(select, drag, gesture, cx.pages, cx.rotation, cx.info, over_text)) } // Select runs the comments tool too: a hanging paste is placed by its press, and a press no comment // part took goes on to the text. @@ -472,6 +473,7 @@ impl ToolFinish { Some(FillOutcome::CreateSignature) => self.open_signature = Some(false), Some(FillOutcome::CreateInitials) => self.open_signature = Some(true), Some(FillOutcome::Refused(why)) => self.refused = Some(why), + Some(FillOutcome::Leave) => self.back_to_select = true, None => {} } // The first page key of the pass turns the page; the rest wait for the next pass's keys. diff --git a/crates/ui-egui/src/canvas/xform.rs b/crates/ui-egui/src/canvas/xform.rs index c097973061..b4643c77b5 100644 --- a/crates/ui-egui/src/canvas/xform.rs +++ b/crates/ui-egui/src/canvas/xform.rs @@ -36,6 +36,14 @@ impl PageSession { pub(crate) fn page_xforms(&self, geo: PageGeometry<'_>) -> Vec<(usize, PageXform)> { self.placed.iter().map(|p| (p.page, geo.xform_of(p))).collect() } + + /// The page drawn under the screen point `at` in the last pass, and the point in that page's user space. + pub(crate) fn user_point_at(&self, geo: PageGeometry<'_>, info: &DocInfo, at: Pos2) -> Option<(usize, [f64; 2])> { + let (page, xf) = self.page_xforms(geo).into_iter().find(|(_, xf)| xf.rect.contains(at))?; + let (vx, vy) = xf.screen_to_view(at); + let u = info.pages.get(page)?.view_to_user(vx, vy); + Some((page, [f64::from(u[0]), f64::from(u[1])])) + } } impl DocView { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 7857f9ae6c..5884b7957b 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -80,6 +80,9 @@ fn title_bar(app: &mut PdfCraftApp, ui: &mut egui::Ui) { |ui, _| { let home = app.active.is_none() && !app.combine_showing(); if IconButton::new(IconId::new("house")).label(tl!("Home")).selected(home).show(ui).clicked() { + if app.combine_showing() { + app.close_combine_preview(); + } app.active = None; app.combine_tab.focused = false; } diff --git a/crates/ui-egui/src/chrome/doc_tabs.rs b/crates/ui-egui/src/chrome/doc_tabs.rs index ebafdb4f18..72e261db15 100644 --- a/crates/ui-egui/src/chrome/doc_tabs.rs +++ b/crates/ui-egui/src/chrome/doc_tabs.rs @@ -26,7 +26,8 @@ pub(crate) fn strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place) { for index in app.tabs_in(place) { let Some(view) = app.views.get(index) else { continue }; let Some(doc) = app.session.get(view.id) else { continue }; - let mut tab = DocumentTab::new(StripTab::View(view.pane.key), doc.name.clone()).modified(doc.dirty).closable(true); + let name = crate::canvas::tab_label(app, index).unwrap_or_else(|| doc.name.clone()); + let mut tab = DocumentTab::new(StripTab::View(view.pane.key), name).modified(doc.dirty).closable(true); if let Some(path) = &doc.path && std::path::Path::new(path).file_name().is_some_and(|file| file.to_string_lossy() != doc.name.as_str()) { diff --git a/crates/ui-egui/src/chrome/view_rail.rs b/crates/ui-egui/src/chrome/view_rail.rs index 57995bea6a..7a2463bfc5 100644 --- a/crates/ui-egui/src/chrome/view_rail.rs +++ b/crates/ui-egui/src/chrome/view_rail.rs @@ -9,6 +9,7 @@ use craft::ui::buttons::IconButton; use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Text; use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::runtime::focus; use craft::ui::text::{TextField, ZoomField, ZoomScale}; use egui::Ui; @@ -72,19 +73,26 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) { let of = crate::i18n::fmt(crate::i18n::t("Page {p} of {n}"), &[("p", &shown.to_string()), ("n", &page_count.to_string())]); Text::new(super::page_position(current, page_count, label)).role(TypeRole::Caption).tooltip(of).show(ui); - let current_label = view.current_page_label(labels.get(current).map(String::as_str)); // Taken once, in the pass that shows the field, also while the field is not focused. let reselect = std::mem::take(&mut view.page_input_reselect); let input_id = view.page_input_id(); let edit = TextField::new("Current page", Bind::bound(&mut view.page_input)).id(input_id).select_on_focus().select_all(reselect).submits().show(ui); + if !edit.events.is_empty() { + view.page_input_draft = true; + } if edit.submitted { let typed = view.page_input.clone(); view.go_to_typed(&typed, &labels); - view.page_input = current_label.clone(); + view.page_input_draft = false; } - // Navigation updates the idle box, never the text being edited. - if !edit.response.has_focus() { + if edit.escaped { + view.page_input_draft = false; + } + // Navigation updates the box, never text being typed into it: the field keeps the focus after Enter, and its + // focus is on its text part, which counts as the field. + if !(view.page_input_draft && focus::is_focused(ui.ctx(), edit.response.id)) { + view.page_input_draft = false; view.page_input = view.current_page_label(labels.get(view.current()).map(String::as_str)); } } diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 7ceb2c19b8..6cfaab1a1a 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -392,7 +392,8 @@ impl PdfCraftApp { if let Some(view) = active.and_then(|i| self.views.get_mut(i)) { // The page box in the toolbar (chrome.rs); select its label so typing replaces it. let id = view.page_input_id(); - if !ctx.memory(|m| m.has_focus(id)) + // Text being typed into the box stays; else it shows the current page's label. + if !view.page_input_draft && let Some(doc) = self.session.get(view.id) { // Navigation and this command can arrive before the next rail frame. @@ -714,10 +715,12 @@ impl PdfCraftApp { self.notify_tr("Drag a rectangle around the area to copy"); } "edit.copy" => { - if let Some(i) = active { - return Some(self.copy_selected_text(i)); + let Some(i) = active else { return Some(false) }; + // With no text selected, a picked picture is copied in its original format. + if self.views.get(i).is_some_and(|v| v.selected_text().is_none_or(|t| t.is_empty())) && self.copy_picked_image(i) { + return Some(true); } - return Some(false); + return Some(self.copy_selected_text(i)); } "comment.copy" => { let Some(i) = active else { return Some(false) }; diff --git a/crates/ui-egui/src/tools/edit_text_ui.rs b/crates/ui-egui/src/tools/edit_text_ui.rs index 9ae43bf05a..6878b74fef 100644 --- a/crates/ui-egui/src/tools/edit_text_ui.rs +++ b/crates/ui-egui/src/tools/edit_text_ui.rs @@ -38,7 +38,7 @@ mod layout; pub(crate) use background::TextBackground; use draft::{ParagraphCover, ParagraphText}; pub use image::{CropMode, ImageAction, ImageSelection}; -pub(crate) use image::{PictureMenu, delete_picture, picture_controls, picture_menu, picture_parts, picture_press, user_to_screen}; +pub(crate) use image::{PictureMenu, delete_picture, picture_context, picture_controls, picture_menu, picture_parts, picture_press, user_to_screen}; pub(crate) use layout::editor_font; #[cfg(test)] use layout::{DARK_EDITOR_FILL, contrast, editor_fill, editor_job}; diff --git a/crates/ui-egui/src/tools/fill_sign.rs b/crates/ui-egui/src/tools/fill_sign.rs index 4f8b5d14e7..072ae41a7a 100644 --- a/crates/ui-egui/src/tools/fill_sign.rs +++ b/crates/ui-egui/src/tools/fill_sign.rs @@ -9,7 +9,7 @@ use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId, keyed}; use craft::keymap::CommandRef; use craft::review::ui::signature::{SignatureSettings, paint_signature}; use craft::review::{SavedSignature, SignatureImage as SavedImage}; -use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; +use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, SelectMode, Show as _, ShowCollection as _}; use craft::ui::list::ThumbAspect; use craft::ui::primitives::Draw; @@ -316,6 +316,8 @@ pub enum FillOutcome { CreateInitials, /// Nothing placed, and why (today's date can't be written into the PDF yet). Refused(String), + /// Escape with nothing left to close: the tool goes back to Select. + Leave, } /// Values that shape how Fill & Sign handles a pass's input, with the two session fields its text @@ -438,6 +440,18 @@ impl CanvasTool for FillSignTool<'_> { self.dragged = false; } + /// Escape steps back one thing per press, as a comment tool's does: the open type box, then the tool, so the Text + /// tool does not open a box at every click with no way out by the keyboard. + fn key(&mut self, key: &ToolKey, _cx: &mut ToolContext<'_>) -> bool { + if !matches!(key, ToolKey::Cancel) { + return false; + } + if self.input.fill_text.take().is_none() { + *self.outcome = Some(FillOutcome::Leave); + } + true + } + // PLAN: framework gap: `ToolContext` and `Draw` give a tool no `egui::Context`, which `TextureCache::texture` // needs for the saved image's ghost turned by page and view rotation (`image_signature_box` holds its box); the // ghost, and the cursor that hides over it, wait for that accessor. diff --git a/crates/ui-egui/src/tools/redact_ui/tool.rs b/crates/ui-egui/src/tools/redact_ui/tool.rs index 48ffac3b83..a3647a2ac7 100644 --- a/crates/ui-egui/src/tools/redact_ui/tool.rs +++ b/crates/ui-egui/src/tools/redact_ui/tool.rs @@ -17,11 +17,14 @@ use crate::canvas::{PageBoxDrag, PageGeometry, PageSession, ToolMarks}; /// The smallest box, in screen points on each side, that counts as a mark. const LEAST_BOX: f32 = 3.0; -/// What the pointer's press is doing. -enum Gesture { +/// What the pointer's press is doing. The tool is built each pass, so the session holds this from the press to the +/// release. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) enum RedactGesture { + #[default] Idle, - /// A text selection the select tool runs. - Text, + /// A text selection the select tool runs, begun on this page. + Text { page: usize }, /// A box being drawn. Box, } @@ -59,38 +62,29 @@ impl RedactResult { /// The Redact tool for one pass. pub(crate) struct RedactTool<'a> { select: PageSelectTool<'a>, - drag: PageBoxDrag, + drag: &'a mut PageBoxDrag, + gesture: &'a mut RedactGesture, placed: &'a [PlacedPage], /// The view's rotation, in degrees clockwise. rotation: u16, info: &'a DocInfo, over_text: Box bool + 'a>, - gesture: Gesture, - text_page: Option, finished: Option, } impl<'a> RedactTool<'a> { - /// The tool over the placed pages, with the select tool that runs text selections and the - /// test of whether a screen point is over text (the same one the I-beam uses). + /// The tool over the placed pages, with the select tool that runs text selections, the session's box drag and + /// gesture, and the test of whether a screen point is over text (the same one the I-beam uses). pub(crate) fn new( select: PageSelectTool<'a>, + drag: &'a mut PageBoxDrag, + gesture: &'a mut RedactGesture, placed: &'a [PlacedPage], rotation: u16, info: &'a DocInfo, over_text: impl Fn(Pos2) -> bool + 'a, ) -> Self { - Self { - select, - drag: PageBoxDrag::default(), - placed, - rotation, - info, - over_text: Box::new(over_text), - gesture: Gesture::Idle, - text_page: None, - finished: None, - } + Self { select, drag, gesture, placed, rotation, info, over_text: Box::new(over_text), finished: None } } /// After the host ran: the gesture the pass finished, which [`RedactResult::land`] applies once the tool's @@ -123,10 +117,7 @@ impl CanvasTool for RedactTool<'_> { if (self.over_text)(pointer.pos) { let action = self.select.press(pointer, cx); match action { - ToolAction::Claimed => { - self.gesture = Gesture::Text; - self.text_page = Some(placed.page); - } + ToolAction::Claimed => *self.gesture = RedactGesture::Text { page: placed.page }, // A double click selects a word whole: it ends the selection at once. ToolAction::Done => self.finished = Some(RedactResult::Text { page: placed.page }), _ => {} @@ -134,27 +125,25 @@ impl CanvasTool for RedactTool<'_> { return action; } self.drag.press(placed, pointer.pos); - self.gesture = Gesture::Box; + *self.gesture = RedactGesture::Box; ToolAction::Claimed } fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { - match self.gesture { - Gesture::Text => self.select.drag(pointer, cx), - Gesture::Box => self.drag.drag(pointer.pos), - Gesture::Idle => {} + match *self.gesture { + RedactGesture::Text { .. } => self.select.drag(pointer, cx), + RedactGesture::Box => self.drag.drag(pointer.pos), + RedactGesture::Idle => {} } } fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { - match std::mem::replace(&mut self.gesture, Gesture::Idle) { - Gesture::Text => { + match std::mem::take(self.gesture) { + RedactGesture::Text { page } => { self.select.release(pointer, cx); - if let Some(page) = self.text_page.take() { - self.finished = Some(RedactResult::Text { page }); - } + self.finished = Some(RedactResult::Text { page }); } - Gesture::Box => { + RedactGesture::Box => { self.drag.drag(pointer.pos); // A click with no drag marks nothing: `release` gives no box below the least size. if let Some((page, rect)) = self.drag.release(LEAST_BOX) @@ -164,7 +153,7 @@ impl CanvasTool for RedactTool<'_> { self.finished = Some(RedactResult::Area { page, quad: rect_quad([a[0], a[1], b[0], b[1]]) }); } } - Gesture::Idle => {} + RedactGesture::Idle => {} } } @@ -173,11 +162,10 @@ impl CanvasTool for RedactTool<'_> { } fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) { - if matches!(std::mem::replace(&mut self.gesture, Gesture::Idle), Gesture::Text) { + if matches!(std::mem::take(self.gesture), RedactGesture::Text { .. }) { self.select.cancel(reason, cx); } - self.text_page = None; - self.drag = PageBoxDrag::default(); + *self.drag = PageBoxDrag::default(); } fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { diff --git a/crates/ui-egui/src/workflows/combine_grid.rs b/crates/ui-egui/src/workflows/combine_grid.rs index 5633b96688..2135c9fb70 100644 --- a/crates/ui-egui/src/workflows/combine_grid.rs +++ b/crates/ui-egui/src/workflows/combine_grid.rs @@ -184,15 +184,12 @@ fn act_action(act: Act, key: CombineKey) -> RowAction { } } -/// What Delete removes: the selection when the keys are the selected tiles, else the one tile. -fn delete_action(selection: &Selection, keys: &[CombineKey]) -> Option { - let first = *keys.first()?; - let selected = keys.iter().all(|k| selection.items.contains(k)); - Some(match (first, selected) { - (CombineKey::File(_), true) => RowAction::Remove, - (CombineKey::Page(..), true) => RowAction::RemovePages(None), - (CombineKey::File(id), false) => RowAction::RemoveFile(id), - (CombineKey::Page(id, nth), false) => RowAction::RemovePages(Some((id, nth))), +/// What Delete removes: the selection, whichever tile the keyboard is on; nothing while nothing is selected (a page +/// let go of when its file collapsed or an undo took it, files picked through automation). +fn delete_action(selection: &Selection) -> Option { + Some(match selection.items.first()? { + CombineKey::File(_) => RowAction::Remove, + CombineKey::Page(..) => RowAction::RemovePages(None), }) } @@ -250,7 +247,7 @@ pub(crate) fn grid(app: &mut PdfCraftApp, ui: &mut egui::Ui, checks: &[Result None, }); } - CollectionEvent::Delete(keys) => actions.extend(delete_action(&app.combine_tab.selection, &keys)), + CollectionEvent::Delete(_) => actions.extend(delete_action(&app.combine_tab.selection)), CollectionEvent::Preview(CombineKey::File(id)) => actions.push(RowAction::Preview(id)), CollectionEvent::Preview(CombineKey::Page(id, nth)) => actions.push(RowAction::PreviewAt(id, nth)), // PLAN: framework gap F-5: the tile's context menu (Preview, Expand/Collapse, Remove, Unlock…) needs a diff --git a/crates/ui-egui/tests/it/export.rs b/crates/ui-egui/tests/it/export.rs index 4b9f3055aa..76b72e347a 100644 --- a/crates/ui-egui/tests/it/export.rs +++ b/crates/ui-egui/tests/it/export.rs @@ -13,7 +13,7 @@ const FIXTURE: &[u8] = b"%PDF-1.7 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj 2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 200 100] >> endobj 3 0 obj << /Type /Page /Parent 2 0 R >> endobj -4 0 obj << /Type /Page /Parent 2 0 R >> endobj +4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 200] >> endobj trailer << /Root 1 0 R >> %%EOF"; diff --git a/crates/ui-egui/tests/it/pickers.rs b/crates/ui-egui/tests/it/pickers.rs index 9fd1b1041e..381a56f6fe 100644 --- a/crates/ui-egui/tests/it/pickers.rs +++ b/crates/ui-egui/tests/it/pickers.rs @@ -235,13 +235,13 @@ fn save_as_writes_on_a_later_frame_including_edits_made_meanwhile() { let mut h = harness(&[3]); assert!(h.execute("file.save_as")); h.steps(2); - assert!(!out.exists(), "the command must not wait for the picker"); + assert!(h.files.file(&out).is_none(), "the command must not wait for the picker"); assert_eq!(h.files.open(), 1, "the Save picker is open"); // The user keeps working while the panel is open. let ctx_h = h.ctx.clone(); h.state_mut().apply_edit(&ctx_h, pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); h.answer(Picked::Paths(vec![out.clone()])); - assert_eq!(page_count(std::fs::read(&out).unwrap()), 2, "the edit made while choosing is saved too"); + assert_eq!(page_count(h.files.file(&out).unwrap()), 2, "the edit made while choosing is saved too"); assert!(!dirty(h.state(), 0)); assert!(matches!(h.files.requests().first().map(|r| r.kind), Some(PickKind::Save))); let _ = std::fs::remove_dir_all(&dir); @@ -260,7 +260,7 @@ fn save_on_close_closes_the_tab_only_once_the_file_is_written() { assert_eq!(h.state().views.len(), 1, "the tab stays open until the save is written"); assert_eq!(h.files.open(), 1, "the Save picker is open"); h.answer(Picked::Paths(vec![out.clone()])); - assert!(out.exists()); + assert!(h.files.file(&out).is_some()); assert!(h.state().views.is_empty(), "then it closes"); let _ = std::fs::remove_dir_all(&dir); } @@ -296,8 +296,8 @@ fn close_all_saves_each_untitled_document_in_turn() { let asked = h.files.requests(); assert_eq!(asked.len(), 2, "one Save pick per untitled document"); assert!(asked.iter().all(|r| r.kind == PickKind::Save)); - assert_eq!(page_count(std::fs::read(dir.join("first.pdf")).unwrap()), 2); - assert_eq!(page_count(std::fs::read(dir.join("second.pdf")).unwrap()), 3); + assert_eq!(page_count(h.files.file(&dir.join("first.pdf")).unwrap()), 2); + assert_eq!(page_count(h.files.file(&dir.join("second.pdf")).unwrap()), 3); let _ = std::fs::remove_dir_all(&dir); } @@ -366,7 +366,7 @@ fn extract_and_delete_deletes_the_pages_only_after_their_files_are_written() { assert_eq!(h.files.open(), 1, "the folder picker is open"); assert_eq!(pages(h.state(), 0), 3, "nothing is deleted while the folder picker is open"); h.answer(Picked::Paths(vec![dir.clone()])); - assert!(dir.join("doc0 (page 1).pdf").exists()); + assert!(h.files.file(&dir.join("doc0 (page 1).pdf")).is_some()); assert_eq!(pages(h.state(), 0), 2, "the extracted page is deleted once written"); let _ = std::fs::remove_dir_all(&dir); } @@ -389,26 +389,27 @@ fn extract_pages_saves_under_the_file_name_typed_in_the_dialog() { ); confirm_extract(&mut h); h.answer(Picked::Paths(vec![dir.clone()])); - assert!(dir.join("doc0 (page 1).pdf").exists()); + let written = |h: &Rig, name: &str| h.files.file(&dir.join(name)).is_some(); + assert!(written(&h, "doc0 (page 1).pdf")); // A name with nothing usable falls back to the document's. h.state_mut().views[0].select_pages(&[1]); open_extract(&mut h, separate(Some(" .. "))); confirm_extract(&mut h); h.answer(Picked::Paths(vec![dir.clone()])); - assert!(dir.join("doc0 (page 2).pdf").exists()); + assert!(written(&h, "doc0 (page 2).pdf")); // Several pages as separate files: each is " (page N).pdf". h.state_mut().views[0].select_pages(&[0, 2]); open_extract(&mut h, separate(Some("Invoices.pdf"))); confirm_extract(&mut h); h.answer(Picked::Paths(vec![dir.clone()])); - assert!(dir.join("Invoices (page 1).pdf").exists() && dir.join("Invoices (page 3).pdf").exists()); + assert!(written(&h, "Invoices (page 1).pdf") && written(&h, "Invoices (page 3).pdf")); // One renamed page as a separate file is saved under exactly that name; characters a file // name can't hold become "_". h.state_mut().views[0].select_pages(&[1]); open_extract(&mut h, separate(Some(" March: 2026/receipt "))); confirm_extract(&mut h); h.answer(Picked::Paths(vec![dir.clone()])); - assert!(dir.join("March_ 2026_receipt.pdf").exists()); + assert!(written(&h, "March_ 2026_receipt.pdf")); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 5, "nothing written outside those names"); // Into a new tab: the tab, and so Save As, has the typed name. open_extract(&mut h, Extract { name: Some("Chapter 2"), ..Default::default() }); @@ -516,7 +517,7 @@ fn extracted_pages_are_not_deleted_if_the_document_was_edited_while_choosing_the let ctx_h = h.ctx.clone(); h.state_mut().apply_edit(&ctx_h, pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); h.answer(Picked::Paths(vec![dir.clone()])); - assert!(dir.join("doc0 (page 1).pdf").exists(), "the extracted file is still written"); + assert!(h.files.file(&dir.join("doc0 (page 1).pdf")).is_some(), "the extracted file is still written"); assert_eq!(pages(h.state(), 0), 2, "nothing more is deleted"); assert!(support::shown_notice(&mut h).is_some(), "the user is told"); let _ = std::fs::remove_dir_all(&dir); @@ -684,7 +685,7 @@ fn a_late_startup_url_preserves_the_current_edit_workspace_and_save_target() { assert!(h.execute("file.save")); h.steps(2); h.answer(Picked::Paths(vec![path.clone()])); - let saved = PageRenderer::new(std::sync::Arc::new(std::fs::read(&path).unwrap()), Default::default()); + let saved = PageRenderer::new(std::sync::Arc::new(h.files.file(&path).unwrap()), Default::default()); assert_eq!(saved.page_count(), 2, "the saved file contains the local deletion"); assert!(!dirty(h.state(), 0), "the local document was saved, not the startup document"); diff --git a/crates/ui-egui/tests/it/viewer.rs b/crates/ui-egui/tests/it/viewer.rs index 0b993d0b52..d737250758 100644 --- a/crates/ui-egui/tests/it/viewer.rs +++ b/crates/ui-egui/tests/it/viewer.rs @@ -135,7 +135,7 @@ fn close_all_asks_only_for_changed_documents() { h.run_steps(2); assert_eq!(h.state().views.len(), 1, "the clean document closed at once"); // b.pdf asks to be saved: the close dialog is on screen. - h.get_by_label_contains("Save changes"); + h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Unsaved changes"); } #[test] @@ -1641,9 +1641,10 @@ fn a_new_document_opens_at_the_top_after_a_relaunch() { let memory: egui::Memory = eframe::get_value(&settings, "egui").expect("egui's memory round-trips"); // Next launch: a document never seen before, which gets a.pdf's old id. let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|cc| { + // eframe restores the memory before it calls the app's creator, which installs the runtime. + cc.egui_ctx.memory_mut(|m| *m = memory); crate::support::install_runtime(&cc.egui_ctx); { - cc.egui_ctx.memory_mut(|m| *m = memory); let mut app = crate::control::new_app(); app.set_option(&egui::Context::default(), "language", "en").unwrap(); app.open_bytes(&egui::Context::default(), "c.pdf", None, fixture(5)).unwrap(); @@ -1910,11 +1911,24 @@ fn v_h_and_space_pick_the_quick_tools() { // V leaves any other tool too, as the toolbar button does. h.state_mut().quick_tool = QuickTool::Crop; assert_eq!(press(&mut h, Key::V), QuickTool::Select); - // Holding Space pans with the Hand for as long as it is held, then gives the tool back. + // Holding Space pans with the Hand for as long as it is held (the tool host's momentary Hand), then gives the + // tool back: a drag while it is held moves the page, as the Hand's does, and draws no crop box. h.state_mut().quick_tool = QuickTool::Crop; h.key_down(Key::Space); h.run_steps(4); - assert_eq!(h.state().quick_tool, QuickTool::Hand, "Space held"); + let top = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].page_screen_rect(0).map(|r| r.top()); + let before = top(&h); + let from = h.state().views[0].viewport_rect().center(); + h.hover_at(from); + h.run_steps(1); + h.drag_at(from); + h.run_steps(1); + h.hover_at(from - egui::vec2(0.0, 120.0)); + h.run_steps(1); + h.drop_at(from - egui::vec2(0.0, 120.0)); + h.run_steps(2); + assert!(before.zip(top(&h)).is_some_and(|(b, a)| a < b - 60.0), "Space held: the drag pans ({before:?} -> {:?})", top(&h)); + assert_eq!(h.state().quick_tool, QuickTool::Crop, "the tool waits under the held Space"); h.key_up(Key::Space); h.run_steps(2); assert_eq!(h.state().quick_tool, QuickTool::Crop, "Space released");