From 1244e67d2b61a5eedb993ca444cfedca5670b1cd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:56:53 -0500 Subject: [PATCH] red10 g4: app red round 10 fixes --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/clipboard.rs | 38 ++++- crates/ui-egui/src/app/files.rs | 4 +- crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/canvas.rs | 57 ++++++- crates/ui-egui/src/canvas/cache.rs | 2 +- crates/ui-egui/src/canvas/page_overlays.rs | 154 +++++++++++++++++- crates/ui-egui/src/canvas/page_parts.rs | 67 ++++++-- crates/ui-egui/src/canvas/page_tools.rs | 66 +++++++- crates/ui-egui/src/commands.rs | 18 ++ crates/ui-egui/src/dialogs/properties.rs | 19 ++- crates/ui-egui/src/editing.rs | 2 +- crates/ui-egui/src/editing/close.rs | 11 +- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/tools/content_ui.rs | 51 +++--- crates/ui-egui/src/tools/edit_text_tool.rs | 6 +- crates/ui-egui/src/tools/edit_text_ui.rs | 2 +- .../ui-egui/src/tools/edit_text_ui/image.rs | 72 +++++++- crates/ui-egui/src/tools/forms_ui.rs | 31 +++- crates/ui-egui/src/tools/forms_ui/calendar.rs | 14 +- .../ui-egui/src/tools/forms_ui/choice_list.rs | 17 +- crates/ui-egui/src/tools/forms_ui/editor.rs | 9 +- crates/ui-egui/src/tools/object_ui.rs | 35 ++-- crates/ui-egui/src/tools/redact_ui/dialogs.rs | 2 +- .../src/workflows/create_multiple_ui.rs | 2 +- crates/ui-egui/src/workflows/optimize_ui.rs | 5 +- crates/ui-egui/tests/it/create.rs | 3 +- crates/ui-egui/tests/it/forms.rs | 23 +-- crates/ui-egui/tests/it/object_selection.rs | 5 +- crates/ui-egui/tests/it/pdf_links.rs | 4 +- crates/ui-egui/tests/it/pickers.rs | 11 +- crates/ui-egui/tests/it/redact.rs | 6 + crates/ui-egui/tests/perf.rs | 2 +- 33 files changed, 622 insertions(+), 121 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b637d521cc..6e5d80ef5f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -262,6 +262,7 @@ impl PdfCraftApp { views: Vec::new(), closed_tabs: Vec::new(), active: None, + last_frame_active: None, mode: Mode::AllTools, default_mode: Mode::AllTools, view_defaults: Default::default(), diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 0dab1742fa..4b6fa57998 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -77,6 +77,26 @@ impl PdfCraftApp { } } + /// Hands the paste content carried by a fired paste command (F-89) to the clipboard before the command runs. + pub(crate) fn offer_clip_content(&mut self, content: &craft::ui::runtime::commands::ClipContent) { + let mut flavors = Vec::new(); + if let Some(text) = &content.text { + flavors.push(Flavor::text(text.as_ref())); + } + if let Some(image) = &content.image + && let (Ok(width), Ok(height)) = (u32::try_from(image.size[0]), u32::try_from(image.size[1])) + { + let mut data = Vec::with_capacity(8 + image.pixels.len() * 4); + data.extend_from_slice(&width.to_le_bytes()); + data.extend_from_slice(&height.to_le_bytes()); + data.extend(image.pixels.iter().flat_map(egui::Color32::to_srgba_unmultiplied)); + flavors.push(Flavor::new(RGBA8, data)); + } + if !flavors.is_empty() { + self.clipboard.offer_paste(flavors); + } + } + /// Writes `text` to the clipboard; says why when it can't. Silent when automation's input is /// fenced off from the user's clipboard. pub(crate) fn put_text(&mut self, text: &str) -> bool { @@ -158,12 +178,26 @@ impl PdfCraftApp { /// still holds their copy; a picture the clipboard holds; its text (XFDF is pasted as /// comments, and text beats an image the app only remembers); else the remembered image. pub(crate) fn paste_from_clipboard(&mut self, ctx: &egui::Context, i: usize) { + self.paste_from_clipboard_with(ctx, i, None); + } + + /// [`Self::paste_from_clipboard`], preferring content delivered with the paste event (`pasted`, F-89) + /// over a fresh system-clipboard read so desktop `SystemClipboard` hosts still receive event payloads. + pub(crate) fn paste_from_clipboard_with(&mut self, ctx: &egui::Context, i: usize, pasted: Option<&craft::ui::runtime::commands::ClipContent>) { if self.views.get(i).is_some_and(|v| v.session.forms.focus.is_some() || v.organize) { return; } let page = self.views.get(i).map_or(0, |v| v.current()); - let text = if self.clipboard.has(&[TEXT]) { self.clipboard.read_text().ok().flatten().filter(|t| !t.is_empty()) } else { None }; - let image = self.clipboard.read_image().ok().flatten(); + let delivered_text = pasted.and_then(|c| c.text.as_deref()).filter(|t| !t.is_empty()).map(str::to_owned); + let delivered_image = pasted.and_then(|c| c.image.as_ref()).and_then(|img| { + let (width, height) = (u32::try_from(img.size[0]).ok()?, u32::try_from(img.size[1]).ok()?); + let mut rgba = Vec::with_capacity(img.pixels.len() * 4); + rgba.extend(img.pixels.iter().flat_map(egui::Color32::to_srgba_unmultiplied)); + Some(ClipboardImage { width, height, rgba }) + }); + let text = delivered_text + .or_else(|| if self.clipboard.has(&[TEXT]) { self.clipboard.read_text().ok().flatten().filter(|t| !t.is_empty()) } else { None }); + let image = delivered_image.or_else(|| self.clipboard.read_image().ok().flatten()); if self.quick_tool == QuickTool::EditText && self.object_clipboard.is_some() && self.pastes_objects(text.as_deref(), image.as_ref()) { self.paste_objects(ctx, i); return; diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 8cbc411642..8cce50e989 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -530,8 +530,8 @@ impl PdfCraftApp { (Ok(bytes), _) => { #[cfg(not(target_arch = "wasm32"))] self.pick_first(PickRequest::save("attachment").file_name(safe_file_name(&att.name, "attachment")), None, move |app, _, path| { - match craft::atomic::atomic_write(&path, &bytes) { - Ok(()) => { + match app.host.files().write(&path, &bytes, craft::host::WriteIntent::SaveAs) { + Ok(_) => { // Windows: the file keeps the document's Mark-of-the-Web (#3990). Best // effort: a volume without alternate data streams can't carry it. let _ = pdfcraft_platform::zone::mark_from(&path, source.as_deref().map(std::path::Path::new)); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 546979006e..90a687e3a0 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -23,5 +23,6 @@ impl PdfCraftApp { let commands = crate::commands::catalog::command_input(self, ctx); FrameInput::new(self.root_env(ctx)).commands(commands).host(self.host.clone()) }); + self.last_frame_active = self.active_ids().map(|(_, id)| id); } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c5d517778a..919973915e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -876,6 +876,7 @@ struct PageBodyCx<'a> { /// The user's Redaction Tool Properties hover colour and opacity, a data colour, not a theme role (L-90). redact_hover: ([f64; 3], f64), form: &'a Arc>, + today: (i64, u32, u32), units: crate::units::Unit, find_marks: &'a [TextMark], table_preview: Option<&'a crate::field_table_ui::Preview>, @@ -968,10 +969,18 @@ fn page_parts_of( } // Fields take the page's presses under Select only: another tool's press over a field is the tool's (a new // text box, a mark, a stamp). + let badge_tips = cx.unobstructed + && !matches!( + cx.tool, + QuickTool::Fill(_) + | QuickTool::Comment(comments::CommentTool::Ink | comments::CommentTool::FreehandHighlight | comments::CommentTool::Eraser) + ) + && session.comments.tool.in_flight().is_none() + && session.comments.tool.drawing().is_empty(); if cx.tool == QuickTool::Select && !cx.preparing { let can_fill = cx.doc.allows_form_filling(); for placed in body.pages { - parts.extend(crate::forms_ui::field_parts(session, cx.info, cx.doc, placed.page, can_fill, geo)); + parts.extend(crate::forms_ui::field_parts(session, cx.info, cx.doc, placed.page, can_fill, badge_tips, geo)); } } // The sign tabs of each page, after the fields: a tab is painted over its field. @@ -981,7 +990,7 @@ fn page_parts_of( for placed in body.pages { let size = cx.sizes.get(placed.page).copied().unwrap_or_default(); let xf = PageXform::of(placed, cx.rotation, size); - let overlay = overlay_parts(ui, &xf, cx.doc, placed.page, cx.can_modify, shown); + let overlay = overlay_parts(ui, &xf, cx.doc, placed.page, cx.can_modify, shown, badge_tips); parts.extend(overlay.parts); tabs.push((placed.page, xf, overlay.tabs)); } @@ -1038,14 +1047,20 @@ fn route_press( { owner = Owner::Picture { index }; } - // A picture is selected for its menu; a right-click on anything else lets the selected one go. + // A picture is selected for its menu only when the right-click lands on its visible body + // on the page; a right-click on its out-of-page frame or anything else lets it go. + let on_page = press.phase.start().is_some_and(|start| body.pages.iter().any(|p| p.page == press.page && p.rect.contains(start.origin))); if !held { let picture = match owner { - Owner::Picture { index } => Some(index), + Owner::Picture { index } if on_page => Some(index), _ => None, }; crate::edit_text_ui::picture_context(press.page, picture, session); } + if matches!(owner, Owner::Picture { .. }) && !on_page { + session.menu_for = None; + return; + } } let mut menu_for = Some((press.page, owner.clone())); // The menu is anchored on the page the right-click lies on, the first where two pages touch, whichever part @@ -1064,7 +1079,7 @@ fn route_press( }; // Added text, pictures and the objects selected together lie over the comments: a right-click on them // reaches no comment under them and leaves the selection cleared. - let over_comments = matches!(owner, Owner::Added { .. } | Owner::Picture { .. } | Owner::Objects | Owner::Frame { .. }); + let over_comments = matches!(owner, Owner::Added { .. } | Owner::Picture { .. } | Owner::Objects { .. } | Owner::Frame { .. }); if held || tool_takes_it || matches!(press.owner, Owner::Comment { .. }) { comments::context_anchor(&page_cx, &mut session.comments, start.origin); } else if over_comments { @@ -1128,10 +1143,11 @@ fn route_press( session.sign.field = Some(field.name.clone()); } } + Owner::Badge { .. } => {} // PLAN: assumed `prepare::tool::field_press(session, form, press)` (pdf-forms-w9). Owner::PrepareField { .. } => crate::prepare::tool::field_press(session, cx.form, press), // The Edit text families' presses, a modified press first taking it for the objects selected together. - Owner::Paragraph { .. } | Owner::Added { .. } | Owner::Picture { .. } | Owner::Objects | Owner::Frame { .. } => { + Owner::Paragraph { .. } | Owner::Added { .. } | Owner::Picture { .. } | Owner::Objects { .. } | Owner::Frame { .. } => { if let Some(edit) = page_tools::edit_text_press(session, cx.doc, cx.info, press, body.pages, geo, cx.tool) { session.pending_edit = Some(edit); } @@ -1190,10 +1206,21 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, // 2-3. Every part on the pages, in one control: hit priority ranks parts inside one control only. let (parts, tabs) = page_parts_of(ui, body, &mut *session, cx); let focus = crate::forms_ui::focus_owner(&session.forms, cx.form); + // A focused field whose page has scrolled out of view lets go, unless Tab is scrolling to it. + if !session.forms.refocus + && session.pending_page.is_none() + && let Some(Owner::Field { field, widget }) = focus + && let Some(page) = cx.form.get(field).and_then(|f| f.widgets.get(widget)).and_then(|w| w.page) + && !body.pages.iter().any(|p| p.page == page) + { + session.forms.focus = None; + } + let focus = crate::forms_ui::focus_owner(&session.forms, cx.form); let parts_out = PageParts::new(&parts).focus(focus).show_at(ui, body.rect); - if std::mem::take(&mut session.forms.refocus) + if session.forms.refocus && let Some(at) = focus.and_then(|owner| page_parts::focus_stop(&parts, owner)) { + session.forms.refocus = false; // The editor handed the keys on with Tab: the field the session moved to takes them, as Tab onto its part would. focus::request(ui.ctx(), FocusTarget::Part(parts_out.response.id, at)); } @@ -1222,7 +1249,11 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, } _ => false, }; - if let Some((Owner::Field { .. }, key)) = &parts_out.key + if let Some((Owner::Field { .. }, forward)) = &parts_out.tab { + if let Some(edit) = crate::forms_ui::field_tab(session, cx.info, cx.form, *forward, cx.geometry(body)) { + session.pending_edit = Some(edit); + } + } else if let Some((Owner::Field { .. }, key)) = &parts_out.key && let Some(edit) = crate::forms_ui::field_key(session, cx.info, cx.form, key, cx.geometry(body)) { session.pending_edit = Some(edit); @@ -1274,6 +1305,7 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, } // 5. The overlays. + page_overlays::PageBackdrop::new(body.pages, cx.sizes, cx.rotation, cx.info, session).show_at(ui, body.rect); for (page, xf, page_tabs) in &tabs { PageOverlays::new(*page, *xf, cx.doc, page_tabs, &session.compare_marks, &mut session.flash) .highlight_fields(session.highlight_fields) @@ -1283,6 +1315,7 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, crate::prepare::tool::show_overlays(ui, body.rect, session, cx.form, cx.info, body.pages, cx.rotation); } if cx.editing_content { + page_overlays::PageDraft::new(&session.content).show_at(ui, body.rect); let geo = cx.geometry(body); let added_hovered = match parts_out.hovered { Some((Owner::Added { index }, page)) => Some((page, index)), @@ -1305,7 +1338,7 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, } } // The focused field's editor, and the Fill & Sign text being typed, over their pages. - if let Some(editor) = crate::forms_ui::editor::show(ui, body, session, cx.doc, cx.form, cx.info, cx.geometry(body)) + if let Some(editor) = crate::forms_ui::editor::show(ui, body, session, cx.doc, cx.form, cx.info, cx.today, cx.geometry(body)) && field_arrived { // The keys of a field that takes typing are its editor's: it takes the focus over from the field's part. @@ -1340,6 +1373,11 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, drag.page_received(placed.page); session.comments.page_rendered(placed.page); } + for placed in body.pages.iter().filter(|p| matches!(p.picture, TextureState::Ready(_))) { + session.forms.unbaked.retain(|(_, p)| *p != placed.page); + session.move_background.page_received(placed.page); + session.text_background.page_received(placed.page); + } let stale = drag.moving_page().is_some_and(loading); drag.prepare_move(&ctx, cx.doc, &session.comments, session.pending_edit.as_ref(), stale, cx.render_scale); let map = comments::PageMap::new(cx.info, body.pages, cx.rotation, body.view); @@ -1641,6 +1679,7 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu prefs: &app.comment_prefs, redact_hover: (app.redact_prefs.hover_fill, app.redact_prefs.opacity), form: &form, + today: app.session.today(), units: app.units, find_marks: &find_marks, table_preview: table_preview.as_ref(), diff --git a/crates/ui-egui/src/canvas/cache.rs b/crates/ui-egui/src/canvas/cache.rs index 780691ed0e..14d32c0b02 100644 --- a/crates/ui-egui/src/canvas/cache.rs +++ b/crates/ui-egui/src/canvas/cache.rs @@ -48,7 +48,7 @@ impl DocView { self.session.text_queue.as_ref().is_some_and(|queue| queue.counts() != QueueCounts::default()) || self.session.text_background.pending() || self.session.move_background.pending() - || self.session.placed.iter().any(|p| matches!(p.picture, TextureState::Loading { .. })) + || self.session.placed.iter().any(|p| matches!(p.picture, TextureState::Loading { .. } | TextureState::Missing)) } /// Re-render every page and text layer (the document's appearance changed, e.g. a layer diff --git a/crates/ui-egui/src/canvas/page_overlays.rs b/crates/ui-egui/src/canvas/page_overlays.rs index a31a39db26..ad89e14309 100644 --- a/crates/ui-egui/src/canvas/page_overlays.rs +++ b/crates/ui-egui/src/canvas/page_overlays.rs @@ -262,7 +262,7 @@ impl LinksOnPage<'_> { Some(LinkEvent::Follow { target: LinkTarget::Uri(uri), javascript: None }) } (LinkMode::Edit, Owner::Link { index }) if primary => Some(LinkEvent::Select { page: self.page, index, clicks: start.clicks }), - (LinkMode::Edit, Owner::Link { index }) if start.button == PointerButton::Secondary => { + (LinkMode::Follow | LinkMode::Edit, Owner::Link { index }) if start.button == PointerButton::Secondary => { Some(LinkEvent::Context { page: self.page, index }) } _ => None, @@ -312,8 +312,29 @@ pub(crate) struct OverlayParts { /// The sign tabs on `page`'s empty signature fields that a click signs, laid out once: the label's width is /// measured in this pass by [`SignTabMetrics`], so the part a press hits and the chip that is painted are /// one rectangle. Nothing unless `shown` (the Select tool, no Prepare Form, no full-screen veil). -pub(crate) fn overlay_parts(ui: &mut egui::Ui, xf: &PageXform, doc: &Document, page: usize, can_fill: bool, shown: bool) -> OverlayParts { +pub(crate) fn overlay_parts( + ui: &mut egui::Ui, + xf: &PageXform, + doc: &Document, + page: usize, + can_fill: bool, + shown: bool, + badge_tips: bool, +) -> OverlayParts { let mut out = OverlayParts { parts: Vec::new(), tabs: Vec::new() }; + if badge_tips { + for (index, badge) in signature_badges(&doc.signatures, page).into_iter().enumerate() { + let [x0, y0, x1, y1] = badge.rect; + let rect = xf.user_rect(&doc.info, page, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]).expand(2.0).intersect(xf.rect); + if rect.is_finite() && rect.is_positive() { + out.parts.push( + PagePart::new(Owner::Badge { index }, page, HitShape::Rect(rect), PageLayer::Text) + .passes_drag() + .tip_now(crate::i18n::t(badge.summary).to_string()), + ); + } + } + } if !shown { return out; } @@ -638,6 +659,135 @@ impl PageOverlays<'_> { } } +/// Paints the textless page background (for an open paragraph or added-text draft) and the moving-item +/// background/preview (`MoveBackground`) over the placed pages before the overlays and controls. +#[derive(craft::ui::contract::Component)] +#[component(canvas_control, content_painter, unregistered)] +pub(crate) struct PageBackdrop<'a> { + #[common] + common: Common, + pages: &'a [PlacedPage], + sizes: &'a [(f32, f32)], + rotation: u16, + info: &'a DocInfo, + session: &'a PageSession, +} + +impl<'a> PageBackdrop<'a> { + pub(crate) fn new(pages: &'a [PlacedPage], sizes: &'a [(f32, f32)], rotation: u16, info: &'a DocInfo, session: &'a PageSession) -> Self { + Self { common: Common::new(), pages, sizes, rotation, info, session } + } +} + +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct PageBackdropStyle { + #[style(metrics)] + metrics: Metrics, +} + +impl Component for PageBackdrop<'_> { + const ROLE: Role = Role::GROUP; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + const SHOWS_LABEL: bool = false; + type Style = PageBackdropStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: PageBackdropStyleKey) -> PageBackdropStyle { + PageBackdropStyle { metrics: Metrics::new() } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::ZERO + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let draw = ui.draw(); + let content = ui.content_painter(cx); + for placed in self.pages { + let size = self.sizes.get(placed.page).copied().unwrap_or_default(); + let xf = PageXform::of(placed, self.rotation, size); + self.session.text_background.paint( + &draw, + &content, + &xf, + placed.page, + self.session.line_editor.as_ref(), + self.session.content.draft.as_ref(), + ); + self.session.move_background.paint(&draw, &content, placed, self.info, &self.session.content); + } + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// Paints the open added-text draft's paper and text under the editor's caret. +#[derive(craft::ui::contract::Component)] +#[component(canvas_control, content_painter, unregistered)] +pub(crate) struct PageDraft<'a> { + #[common] + common: Common, + content: &'a crate::content_ui::ContentView, +} + +impl<'a> PageDraft<'a> { + pub(crate) fn new(content: &'a crate::content_ui::ContentView) -> Self { + Self { common: Common::new(), content } + } +} + +impl Component for PageDraft<'_> { + const ROLE: Role = Role::GROUP; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + const SHOWS_LABEL: bool = false; + type Style = PageBackdropStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: PageDraftStyleKey) -> PageBackdropStyle { + PageBackdropStyle { metrics: Metrics::new() } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::ZERO + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let content = ui.content_painter(cx); + self.content.paint_draft(&content); + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + /// Paints a sign tab laid out by [`overlay_parts`]: an accent chip with the signature icon and "Sign" on it, /// as the app's primary buttons are. Screen-only chrome, like the validation badges. fn paint_sign_tab(draw: &Draw<'_>, tab: &SignTab, style: &PageOverlaysStyle) { diff --git a/crates/ui-egui/src/canvas/page_parts.rs b/crates/ui-egui/src/canvas/page_parts.rs index 324fcc0755..47679607ff 100644 --- a/crates/ui-egui/src/canvas/page_parts.rs +++ b/crates/ui-egui/src/canvas/page_parts.rs @@ -3,8 +3,8 @@ //! hit priority ranks them against each other and the press machine holds each press to its release. The tool host //! shown after it takes every press no part took. -use craft::behavior::{CursorIcon, HitLevel, HitPriority, HitShape, Input, Intent, Metrics, PartKey, PartRef, PressPhase, Sense}; -use craft::keymap::Mods; +use craft::behavior::{CursorIcon, HitLevel, HitPriority, HitShape, Input, Intent, Metrics, NavMove, PartKey, PartRef, PressPhase, Sense}; +use craft::keymap::{Chord, Key, Mods}; use craft::ui::contract::{ Common, Component, Cx, Focus as _, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Props as _, Role, TooltipAt, TooltipSpec, TooltipWhen, }; @@ -33,14 +33,16 @@ pub(crate) enum Owner { Paragraph { block: usize }, /// Edit text: a picture, by its index among the page's. Picture { index: usize }, - /// Edit text: the objects selected together. - Objects, - /// Edit text: the frame band of the paragraph open for typing, by the paragraph's index. - Frame { block: usize }, + /// Edit text: the objects selected together, by index in the selection. + Objects { index: usize }, + /// Edit text: one side of the frame band of the paragraph open for typing, by the paragraph's index and side (0..4). + Frame { block: usize, side: usize }, /// Added text or a picture placed on the page, by its index among the page's. Added { index: usize }, /// The sign tab on an empty signature field a click would sign, by the field's index in the form. SignTab { field: usize }, + /// A signed signature's validation badge, by its index on the page: shows the verdict tooltip on hover. + Badge { index: usize }, } const COMMENT: PartKey = PartKey::new("comment"); @@ -54,6 +56,7 @@ const OBJECTS: PartKey = PartKey::new("objects"); const FRAME: PartKey = PartKey::new("frame"); const ADDED: PartKey = PartKey::new("added"); const SIGN_TAB: PartKey = PartKey::new("sign_tab"); +const BADGE: PartKey = PartKey::new("badge"); /// `high` in the upper 32 bits of a part index and `low` in the lower; `None` when either does not fit, so no two /// things ever share an index. @@ -83,10 +86,11 @@ impl Owner { Owner::PrepareField { field, widget } => (PREPARE_FIELD, pack(field, widget)?), Owner::Paragraph { block } => (PARAGRAPH, pack(page, block)?), Owner::Picture { index } => (PICTURE, pack(page, index)?), - Owner::Objects => (OBJECTS, pack(page, 0)?), - Owner::Frame { block } => (FRAME, pack(page, block)?), + Owner::Objects { index } => (OBJECTS, pack(page, index)?), + Owner::Frame { block, side } => (FRAME, pack(page, block.checked_shl(2)? | (side & 3))?), Owner::Added { index } => (ADDED, pack(page, index)?), Owner::SignTab { field } => (SIGN_TAB, pack(page, field)?), + Owner::Badge { index } => (BADGE, pack(page, index)?), }; Some(key.at(index)) } @@ -105,10 +109,11 @@ impl Owner { PREPARE_FIELD => Some((Owner::PrepareField { field: high, widget: low }, None)), PARAGRAPH => paged(Owner::Paragraph { block: low }), PICTURE => paged(Owner::Picture { index: low }), - OBJECTS => paged(Owner::Objects), - FRAME => paged(Owner::Frame { block: low }), + OBJECTS => paged(Owner::Objects { index: low }), + FRAME => paged(Owner::Frame { block: low >> 2, side: low & 3 }), ADDED => paged(Owner::Added { index: low }), SIGN_TAB => paged(Owner::SignTab { field: low }), + BADGE => paged(Owner::Badge { index: low }), _ => None, } } @@ -282,6 +287,9 @@ pub(crate) struct PagePartsStyle { metrics: Metrics, } +const TAB: Chord = Chord::plain(Key::Tab); +const SHIFT_TAB: Chord = Chord::new(Mods::SHIFT, Key::Tab); + /// What the page parts report this pass. #[derive(Debug)] pub(crate) struct PagePartsOutput { @@ -291,6 +299,8 @@ pub(crate) struct PagePartsOutput { pub(crate) press: Option, /// A key the focused part was given: a form field's toggle, its arrows, Enter or typed text. pub(crate) key: Option<(Owner, Intent)>, + /// Tab (`true`) or Shift+Tab (`false`) pressed while a focusable field part held focus. + pub(crate) tab: Option<(Owner, bool)>, /// The part under the pointer this pass, and its page. pub(crate) hovered: Option<(Owner, usize)>, /// The part focus arrived on this pass (Tab, a focus request or a click): a form field opens on it. @@ -323,6 +333,7 @@ pub(crate) struct PageParts<'a> { struct Report { press: Option, key: Option<(Owner, Intent)>, + tab: Option<(Owner, bool)>, hovered: Option<(Owner, usize)>, focused: Option<(Owner, usize)>, } @@ -358,10 +369,13 @@ impl<'a> PageParts<'a> { return Some(Intent::Activate); } let intents = cx.intents(); + if intents.take(Intent::Cancel) { + return Some(Intent::Cancel); + } if intents.take(Intent::Submit) { return Some(Intent::Submit); } - if let Some((mv, mods)) = intents.take_move() { + if let Some((mv, mods)) = intents.take_move_where(|mv, _| matches!(mv, NavMove::Up | NavMove::Down | NavMove::Back | NavMove::Forward)) { return Some(Intent::Move(mv, mods)); } intents.take_text().map(Intent::Text) @@ -442,11 +456,28 @@ impl Component for PageParts<'_> { self.report.press = Some(PagePress { owner: part.owner, page: part.page, phase: press.phase, mods: press.mods }); } } - if let Some(active) = cx.active_part() - && let Some(owner) = self.part_named(active).filter(|part| part.focusable).map(|part| part.owner) - && let Some(intent) = Self::field_key(cx, active) - { - self.report.key = Some((owner, intent)); + let field_owner = cx + .active_part() + .and_then(|active| self.part_named(active).filter(|part| part.focusable).map(|part| (Some(active), part.owner))) + .or_else(|| { + (cx.is_focused() || cx.active_part().is_some()) + .then_some(self.focus) + .flatten() + .filter(|owner| matches!(owner, Owner::Field { .. })) + .map(|owner| (cx.active_part(), owner)) + }); + if let Some((active, owner)) = field_owner { + cx.claim(TAB); + cx.claim(SHIFT_TAB); + if cx.take_claimed(TAB) { + self.report.tab = Some((owner, true)); + } else if cx.take_claimed(SHIFT_TAB) { + self.report.tab = Some((owner, false)); + } else if let Some(active) = active + && let Some(intent) = Self::field_key(cx, active) + { + self.report.key = Some((owner, intent)); + } } if let Some(arrived) = cx.focus_arrived() { self.report.focused = self.part_named(arrived).map(|part| (part.owner, part.page)); @@ -454,7 +485,7 @@ impl Component for PageParts<'_> { } fn finish(self, cx: Cx<'_, Self>) -> PagePartsOutput { - let Report { press, key, hovered, focused } = self.report; - PagePartsOutput { response: cx.response.clone(), press, key, hovered, focused } + let Report { press, key, tab, hovered, focused } = self.report; + PagePartsOutput { response: cx.response.clone(), press, key, tab, hovered, focused } } } diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index d46b09cd0b..ae2fa82014 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -168,6 +168,9 @@ pub(crate) struct PageTool<'a> { /// Full screen: the presenter's keys the tool took for it in this pass, applied after the run. presenting: bool, presenter_keys: Vec<(ToolKey, bool)>, + /// Select with added content selected (Edit a PDF panel open): Delete removes it. + content_delete: bool, + delete_content: bool, } /// What the page tool finished in a pass. The fields the page body reads are public; the rest are applied to the @@ -197,6 +200,8 @@ pub(crate) struct ToolFinish { /// The quick tool, when it selects text. text_tool: Option, text_finished: bool, + /// Delete was pressed with added content selected under Select. + delete_content: bool, } /// Whether copied comments hang on the pointer: they take the next click whatever tool is on. @@ -290,6 +295,7 @@ pub(crate) fn page_tool<'a>( let xforms: &'a [(usize, PageXform)] = xforms; let map: &'a comments::PageMap<'a> = map_slot.insert(comments::PageMap::new(cx.info, cx.pages, cx.rotation, cx.view)); let selects_text = tool_selects_text(tool, cx.preparing); + let content_delete = tool == QuickTool::Select && session.content.selected.is_some() && session.content.draft.is_none(); let arm = match tool { // Prepare a form under the Select tool: the selection rectangle and the moves of fields are Prepare's. QuickTool::Select if cx.preparing => Arm::Area(Box::new(PrepareTool::new(None, cx.can_modify, cx.form, session, cx.info, xforms))), @@ -388,7 +394,16 @@ pub(crate) fn page_tool<'a>( QuickTool::SignArea { certify } => Arm::SignArea(SignAreaTool::new(certify, &mut session.box_drag, cx.pages, cx.rotation, cx.info)), QuickTool::Snapshot => Arm::Snapshot(SnapshotTool::new(&mut session.box_drag, cx.pages, cx.rotation, size)), }; - PageTool { arm, tool, selects_text, released: false, presenting: cx.presenting, presenter_keys: Vec::new() } + PageTool { + arm, + tool, + selects_text, + released: false, + presenting: cx.presenting, + presenter_keys: Vec::new(), + content_delete, + delete_content: false, + } } /// The session's Hand tool under the user's navigation choices of this pass. @@ -439,6 +454,7 @@ impl<'a> PageTool<'a> { presenter_keys: self.presenter_keys, text_tool: Some(self.tool).filter(|_| self.selects_text), text_finished: self.released && self.selects_text, + delete_content: self.delete_content, ..ToolFinish::default() }; match self.arm { @@ -497,6 +513,9 @@ impl ToolFinish { Some(FillOutcome::Leave) => self.back_to_select = true, None => {} } + if self.delete_content && session.pending_edit.is_none() { + session.pending_edit = crate::content_ui::delete_selected(session); + } // The first page key of the pass turns the page; the rest wait for the next pass's keys. self.turn = self.presenter_keys.drain(..).find_map(|(key, shift)| session.presenter.key(&key, shift)); if let Some(tool @ QuickTool::Comment(_)) = self.text_tool { @@ -529,7 +548,33 @@ pub(crate) fn edit_text_press( return None; } match press.owner { - Owner::Objects | Owner::Frame { .. } => crate::tools::object_ui::objects_press(session, doc, info, press, geo), + Owner::Objects { index } => { + if let craft::behavior::PressPhase::Release { start, pos, click: true, .. } = press.phase + && start.clicks >= 2 + && start.origin.distance(pos) <= 3.0 + && let Some(target) = session.objects.target_at(index) + { + session.objects.clear(); + let mut forwarded = press.clone(); + return match target.kind { + pdfcraft_engine::ObjectKind::Text => { + forwarded.owner = Owner::Paragraph { block: target.index }; + crate::tools::edit_text_ui::paragraph_press(session, doc, &forwarded, geo) + } + pdfcraft_engine::ObjectKind::Image => { + forwarded.owner = Owner::Picture { index: target.index }; + crate::tools::edit_text_ui::picture_press(session, doc, &forwarded, geo) + } + pdfcraft_engine::ObjectKind::Added => { + forwarded.owner = Owner::Added { index: target.index }; + let edit_on_click = matches!(tool, QuickTool::AddText | QuickTool::EditText); + crate::tools::content_ui::added_press(session, doc, pages, &forwarded, edit_on_click) + } + }; + } + crate::tools::object_ui::objects_press(session, doc, info, press, geo) + } + Owner::Frame { .. } => crate::tools::object_ui::objects_press(session, doc, info, press, geo), Owner::Paragraph { .. } => crate::tools::edit_text_ui::paragraph_press(session, doc, press, geo), Owner::Added { .. } => { let edit_on_click = matches!(tool, QuickTool::AddText | QuickTool::EditText); @@ -541,7 +586,8 @@ pub(crate) fn edit_text_press( | Owner::TextLink { .. } | Owner::Field { .. } | Owner::PrepareField { .. } - | Owner::SignTab { .. } => None, + | Owner::SignTab { .. } + | Owner::Badge { .. } => None, } } @@ -575,7 +621,10 @@ impl CanvasTool for PageTool<'_> { /// The tool's claims; in full screen the presenter's page keys too. fn claims(&self) -> ToolClaims { - let claims = self.tool().claims(); + let mut claims = self.tool().claims(); + if self.content_delete { + claims = claims.deletes(); + } if self.presenting { claims.keys(presenter::PRESENT_KEYS) } else { claims } } @@ -596,7 +645,14 @@ impl CanvasTool for PageTool<'_> { self.presenter_keys.push((key.clone(), cx.mods.shift)); return true; } - self.tool_mut().key(key, cx) + if self.tool_mut().key(key, cx) { + return true; + } + if self.content_delete && matches!(key, ToolKey::Delete { .. }) { + self.delete_content = true; + return true; + } + false } fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 806165bbfa..5cabbb0d61 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -56,7 +56,19 @@ impl PdfCraftApp { /// automation. The catalog's app-side handlers come first; every other id is a registered /// command and goes through [`Self::execute`]. pub(crate) fn run_fired(&mut self, ctx: &egui::Context, fired: &Fired) { + if let Some(pasted) = &fired.pasted { + self.offer_clip_content(pasted); + } let id = fired.command.id.as_str(); + // A Save shortcut pressed on one frame fires at the start of the next frame; if another + // document became active meanwhile, the shortcut belongs to the first document, not the new one. + if fired.source == craft::ui::runtime::commands::FireSource::Key + && matches!(id, "file.save" | "file.save_as") + && self.last_frame_active.is_some() + && self.last_frame_active != self.active_ids().map(|(_, doc)| doc) + { + return; + } // The OCR Verify screen keeps the window's toolbars and owns F8 and Shift+F8 (the next // and previous word to review), so they don't show or hide the interface there. if id == crate::viewer_prefs::TOGGLE && self.ocr_verify.open { @@ -74,6 +86,12 @@ impl PdfCraftApp { crate::menus::PASTE => Some("page.paste"), _ => None, }; + if !organize && !self.is_preparing() && id == crate::menus::PASTE && fired.pasted.is_some() { + if let Some(i) = self.active.filter(|&i| i < self.views.len()) { + self.paste_from_clipboard_with(ctx, i, fired.pasted.as_ref()); + } + return; + } self.execute(ctx, page_command.filter(|_| organize).unwrap_or(id)); } diff --git a/crates/ui-egui/src/dialogs/properties.rs b/crates/ui-egui/src/dialogs/properties.rs index adea62b58c..a93b25b821 100644 --- a/crates/ui-egui/src/dialogs/properties.rs +++ b/crates/ui-egui/src/dialogs/properties.rs @@ -221,7 +221,12 @@ impl PdfCraftApp { /// Opens Document Properties on `tab`, or shows `tab` when it is already open. pub(crate) fn open_properties(&mut self, ctx: &egui::Context, tab: PropsTab) { match self.dialogs.get_mut_by_id::(properties_id()) { - Some(dialog) => dialog.set_tab(tab.index()), + Some(dialog) => { + dialog.set_tab(tab.index()); + if tab == PropsTab::SpaceAudit { + self.measure_space_audit(); + } + } None => self.show_properties(ctx, tab), } } @@ -230,6 +235,9 @@ impl PdfCraftApp { fn show_properties(&mut self, ctx: &egui::Context, tab: PropsTab) { let Some((_, id)) = self.active_ids() else { return }; self.session.refresh_fonts(id); + if tab == PropsTab::SpaceAudit { + self.measure_space_audit(); + } // Starts the measure, so it is built before the document is borrowed. let space = crate::optimize_ui::space_audit_param(self); let Some(doc) = self.session.get(id) else { return }; @@ -298,6 +306,15 @@ impl PdfCraftApp { if let (Some((_, id)), Some((_, PropsTab::Fonts))) = (self.active_ids(), self.properties_fields()) { self.session.refresh_fonts(id); } + // The Space Audit tab measures the live document when opened and again after an edit. + if let (Some((_, id)), Some((_, PropsTab::SpaceAudit))) = (self.active_ids(), self.properties_fields()) + && let Some(doc) = self.session.get(id) + { + let key = (id, doc.edit_generation()); + if self.space_audit_of != Some(key) && !self.space_audit_jobs.contains(&key) { + self.measure_space_audit(); + } + } if self.prepare_properties(ctx) { self.sync_custom_unlisted(ctx); } diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 9cb4665df8..12690bc77c 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -1377,7 +1377,7 @@ fn step_typing( let mut now = crate::edit_text_ui::Typed::of(std::mem::take(text), selection.take(), std::mem::take(aligns)); let stepped = history.step(&mut now, step); *text = now.text; - *selection = now.selection; + *selection = None; *aligns = now.aligns; stepped } diff --git a/crates/ui-egui/src/editing/close.rs b/crates/ui-egui/src/editing/close.rs index 4b169b3029..3acae2d15e 100644 --- a/crates/ui-egui/src/editing/close.rs +++ b/crates/ui-egui/src/editing/close.rs @@ -300,16 +300,19 @@ impl PdfCraftApp { /// The save `doc`'s question waited for was written: its tab closes and the guard goes on. /// An OCR review started meanwhile holds the close as it holds a new one. fn guard_saved(&mut self, ctx: &egui::Context, doc: DocId) { - if self.close_guard.as_ref().and_then(|g| g.current()) != Some(&doc) { - return; - } + let current = self.close_guard.as_ref().and_then(|g| g.current()) == Some(&doc); if let Some(i) = self.asking_tab(doc) { if self.hold_close_for_ocr_review(i) { - self.end_close_guard(ctx, false); + if current { + self.end_close_guard(ctx, false); + } return; } self.close_tab(i); } + if !current { + return; + } let Some(step) = self.close_guard.as_mut().map(|g| g.saved()) else { return }; self.run_guard_step(ctx, step); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2c5c9a9ca9..7c3f658091 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -252,6 +252,9 @@ pub struct PdfCraftApp { pub(crate) closed_tabs: Vec, /// `None` shows the Home tab. pub active: Option, + /// The active document during the previous frame, so a deferred keyboard Save from that frame + /// never saves a different document that became active before the next frame's `before_input`. + pub(crate) last_frame_active: Option, pub mode: Mode, /// Workspace used for newly opened PDFs; independent of PDF Initial View metadata. pub default_mode: Mode, diff --git a/crates/ui-egui/src/tools/content_ui.rs b/crates/ui-egui/src/tools/content_ui.rs index c516625729..15ff807a5c 100644 --- a/crates/ui-egui/src/tools/content_ui.rs +++ b/crates/ui-egui/src/tools/content_ui.rs @@ -754,7 +754,7 @@ fn item_controls( let out = TransformBox::text_frame(tl!("Added text frame"), Bind::given(state), doc_rect(&body.view, frame, applied)) .rules(rules) .session_arrows(false) - .show(ui); + .show_at(ui, body.rect); if out.discard { session.content.selected = None; session.content.preview = None; @@ -1027,7 +1027,7 @@ fn draft_session( let origin = layout.origin; // A box still waiting for its focus was started in this pass by the press the editor also sees as a press on the // canvas background: that press is the one that opened it, not a click away from it. - let fresh = std::mem::replace(&mut draft.focus, false); + let fresh = if body.pass.is_some() { std::mem::replace(&mut draft.focus, false) } else { draft.focus }; let mut selection = draft.selection.unwrap_or_else(|| TextSelection::caret_at(draft.text.chars().count())); let mut host = AddedTextHost { draft, ctx: ctx.clone(), view: body.view, layout, laid_out: None }; let paper = Rect::from_min_size(at, egui::vec2(width, host.galley().rect.height() + INSET.y * 2.0)); @@ -1799,26 +1799,37 @@ mod tests { /// The image a flip button leaves behind, as the panel returns it. fn flipped(tooltip: &str) -> pdfcraft_engine::AddedImage { + struct PanelApp { + img: pdfcraft_engine::AddedImage, + out: Option, + } + impl eframe::App for PanelApp { + fn raw_input_hook(&mut self, ctx: &egui::Context, _raw: &mut egui::RawInput) { + craft::ui::shell::embed::before_input(ctx, |_| { + craft::ui::runtime::frame::FrameInput::new(craft::ui::runtime::env::RootEnv::default()) + }); + } + fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + craft::ui::shell::embed::logic(ctx, || craft::ui::shell::embed::CloseDecision::Close); + } + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + craft::ui::shell::embed::before_ui(ui.ctx(), frame); + egui::CentralPanel::default().show(ui, |ui| { + if let Some(ImageAction::Update(AddedContent::Image(i))) = image_panel(ui, &self.img) { + self.out = Some(i); + } + }); + } + } let img = pdfcraft_engine::AddedImage::new([0.0, 0.0, 100.0, 50.0], pdfcraft_cos::ObjRef::new(7, 0)); - let mut fonts = false; - let mut h = egui_kittest::Harness::new_ui_state( - move |ui, out: &mut Option| { - // The app's fonts (the semibold section title) take effect from the next frame. - if !fonts { - crate::fonts::ui_fonts(crate::i18n::Lang::EN).install(ui.ctx()); - fonts = true; - return; - } - if let Some(ImageAction::Update(AddedContent::Image(i))) = image_panel(ui, &img) { - *out = Some(i); - } - }, - None, - ); - h.run(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 400.0)).build_eframe(move |cc| { + crate::PdfCraftApp::install_runtime(&cc.egui_ctx); + PanelApp { img, out: None } + }); + h.run_steps(3); h.get_by_label(tooltip).click(); - h.run(); - h.state().clone().expect("the button updates the image") + h.run_steps(3); + h.state().out.clone().expect("the button updates the image") } #[test] diff --git a/crates/ui-egui/src/tools/edit_text_tool.rs b/crates/ui-egui/src/tools/edit_text_tool.rs index effcfd2aa9..4a92c056b5 100644 --- a/crates/ui-egui/src/tools/edit_text_tool.rs +++ b/crates/ui-egui/src/tools/edit_text_tool.rs @@ -71,10 +71,12 @@ impl CanvasTool for EditTextTool<'_> { }; // A press with Shift or ⌘ on an object toggles it; where none lies it starts an area selection // that adds to the selection. - if object_ui::modified_press_at(self.session, self.doc, self.info, page, &xf, pointer.pos) { + if (pointer.mods.shift || pointer.mods.cmd || pointer.mods.ctrl) + && object_ui::modified_press_at(self.session, self.doc, self.info, page, &xf, pointer.pos) + { return ToolAction::Done; } - object_ui::begin_marquee(self.session, page); + object_ui::begin_marquee(self.session, page, pointer.mods); ToolAction::Claimed } diff --git a/crates/ui-egui/src/tools/edit_text_ui.rs b/crates/ui-egui/src/tools/edit_text_ui.rs index 572b909024..550ced5874 100644 --- a/crates/ui-egui/src/tools/edit_text_ui.rs +++ b/crates/ui-egui/src/tools/edit_text_ui.rs @@ -844,7 +844,7 @@ pub(crate) fn paragraph_controls( ) -> Option { let press = parts.press.as_ref().filter(|p| matches!(p.owner, Owner::Paragraph { .. })); let hovered = match parts.hovered { - Some((Owner::Paragraph { block } | Owner::Frame { block }, page)) => Some((page, block)), + Some((Owner::Paragraph { block } | Owner::Frame { block, .. }, page)) => Some((page, block)), _ => None, }; let mut edit = None; diff --git a/crates/ui-egui/src/tools/edit_text_ui/image.rs b/crates/ui-egui/src/tools/edit_text_ui/image.rs index 1952a22767..325c622b8d 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -9,10 +9,11 @@ use craft::pages::ui::{PageBody, PlacedPage}; use craft::ui::buttons::Button; use craft::ui::canvas::{CropApply, CropOutside, CropOverlay}; use craft::ui::canvas_controls::{SelectionOutline, TaskBar}; -use craft::ui::contract::{Bind, Props as _, Show as _}; +use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; use craft::ui::display::Divider; use craft::ui::menu::{Menu, MenuIcon, MenuIconRow, MenuItem}; use craft::ui::primitives::textures::TextureState; +use craft::ui::style::{ComponentStyle, Metrics, StyleCx}; pub(crate) use pdfcraft_content::Matrix; @@ -323,12 +324,79 @@ fn box_controls( None => (quad, shown.edit.shown.as_ref().and_then(|m| m.same()).map_or(quad, |state| state.quad)), }; s.paper = Some(from.map(|p| placed.to_page(view.to_screen(p)))); + let paper_quad = from.map(|p| view.to_screen(p)); + PicturePaper::new(paper_quad, placed.rect).show_at(ui, body.rect); let full = matrix_corners(xf, info, page, image.matrix).map(|p| view.to_doc(p)); let map = affine_between(from, to); - let _ = TransformPreview::new(tl!("Picture"), textures).map(PreviewMap::Quad(full.map(map))).picture().show(ui); + let _ = TransformPreview::new(tl!("Picture"), textures).map(PreviewMap::Quad(full.map(map))).show_at(ui, body.rect); edit } +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +struct PicturePaperStyle { + #[style(metrics)] + metrics: Metrics, +} + +/// Fills the quad a moving or resized picture left behind on its page with white paper, so the old pixels +/// on the page raster do not show beside or under `TransformPreview`. +#[derive(craft::ui::contract::Component)] +#[component(canvas_control, content_painter, unregistered)] +struct PicturePaper { + #[common] + common: Common, + quad: [Pos2; 4], + clip: Rect, +} + +impl PicturePaper { + fn new(quad: [Pos2; 4], clip: Rect) -> Self { + Self { common: Common::new(), quad, clip } + } +} + +impl Component for PicturePaper { + const ROLE: Role = Role::GROUP; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: craft::behavior::Input = craft::behavior::Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + const SHOWS_LABEL: bool = false; + type Style = PicturePaperStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: PicturePaperStyleKey) -> PicturePaperStyle { + PicturePaperStyle { metrics: Metrics::new() } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 { + egui::Vec2::ZERO + } + + fn sense(&self) -> craft::behavior::Sense { + craft::behavior::Sense::empty() + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + if !self.quad.iter().all(|p| p.is_finite()) { + return; + } + let content = ui.content_painter(cx); + let painter = content.painter.with_clip_rect(self.clip.intersect(content.painter.clip_rect())); + painter.add(egui::Shape::convex_polygon(self.quad.to_vec(), egui::Color32::WHITE, egui::Stroke::NONE)); + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + fn crop_controls( ui: &mut egui::Ui, body: &PageBody<'_>, diff --git a/crates/ui-egui/src/tools/forms_ui.rs b/crates/ui-egui/src/tools/forms_ui.rs index b411376318..24edc94a79 100644 --- a/crates/ui-egui/src/tools/forms_ui.rs +++ b/crates/ui-egui/src/tools/forms_ui.rs @@ -373,10 +373,14 @@ pub(crate) fn field_parts( doc: &pdfcraft_engine::Document, page: usize, can_fill: bool, + badge_tips: bool, geo: PageGeometry<'_>, ) -> Vec { let Some(xf) = session.page_xform(page, geo) else { return Vec::new() }; let form = doc.form.as_slice(); + let badges = if badge_tips { crate::canvas::signature_badges(&doc.signatures, page) } else { Vec::new() }; + let tabbed = tab_order(form, info); + let in_order: HashSet<(usize, usize)> = tabbed.iter().copied().collect(); let part = |fi: usize, wi: usize| -> Option { let f = form.get(fi)?; let w = f.widgets.get(wi)?; @@ -394,16 +398,22 @@ pub(crate) fn field_parts( let stacking = u32::try_from(form.len().saturating_sub(fi)).unwrap_or(u32::MAX); let mut part = PagePart::new(Owner::Field { field: fi, widget: wi }, page, HitShape::Polygon(corners), PageLayer::Field).cursor(icon).stacked(stacking); - if let Some(tip) = f.tooltip.as_deref().filter(|t| !t.trim().is_empty()) { + let badge_tip = (f.kind == FormFieldKind::Signature) + .then(|| { + badges.iter().find(|b| b.rect.iter().zip(w.rect).all(|(a, b)| (a - b).abs() < 1.0)).map(|b| crate::i18n::t(b.summary).to_string()) + }) + .flatten(); + if let Some(tip) = badge_tip { + part = part.tip_now(tip); + } else if let Some(tip) = f.tooltip.as_deref().filter(|t| !t.trim().is_empty()) { part = part.tip(tip.to_owned()); } - if fillable(f) { + let is_focused = session.forms.focus.as_ref().is_some_and(|x| x.is_on(f, wi)); + if in_order.contains(&(fi, wi)) || is_focused { part = part.focusable(); } Some(part) }; - let tabbed = tab_order(form, info); - let in_order: HashSet<(usize, usize)> = tabbed.iter().copied().collect(); let mut parts: Vec = tabbed.iter().filter_map(|&(fi, wi)| part(fi, wi)).collect(); for (fi, f) in form.iter().enumerate() { for wi in 0..f.widgets.len() { @@ -501,6 +511,7 @@ fn clicked( commit(session, form); session.forms.focus = Some(open_focus(f, wi)); } + session.forms.refocus = true; // The toggle goes after the edit for any text the click committed, in one batch: if that text is // refused, its field reopens and the toggle is dropped with it. let toggle = toggle_edit(f, wi); @@ -517,6 +528,7 @@ fn clicked( if session.forms.focus.as_ref().is_none_or(|x| !x.is_on(f, wi)) { commit(session, form); session.forms.focus = Some(open_focus(f, wi)); + session.forms.refocus = true; } // A combo box's click runs its Mouse Up JavaScript (#269). session.forms.triggers.push((widget_ref(f, wi), pdfcraft_engine::FieldTrigger::MouseUp)); @@ -528,6 +540,7 @@ fn clicked( } commit(session, form); session.forms.focus = Some(open_focus(f, wi)); + session.forms.refocus = true; let r = widget_rect(&xf, info, page, w.rect); let height_pt = if matches!(w.rotation, 90 | 270) { (w.rect[2] - w.rect[0]).max(1.0) } else { (w.rect[3] - w.rect[1]).max(1.0) }; let zoom = (r.height() as f64) / height_pt; @@ -580,6 +593,16 @@ fn clicked( } } +/// Tab or Shift+Tab on a focused non-editor field (check box, radio button, list box, non-editable combo): +/// commits and moves to the next or previous fillable widget in the document's tab order, across pages too. +pub(crate) fn field_tab(session: &mut PageSession, info: &DocInfo, form: &[FormField], forward: bool, geo: PageGeometry<'_>) -> Option { + let focus = session.forms.focus.clone()?; + let f = focused_field(&focus, form)?; + let edit = tab_to_next_field(session, info, form, f, focus.widget, forward, geo); + session.forms.refocus = true; + edit +} + /// What a key the focused check box, radio button or list box got does: the edit to apply, if any. Space (or Enter) /// toggles a check box and selects a radio button, as in browsers: it never turns the selected button off. The arrows /// step through a radio group (selecting as they go) and move the pick in a list box, Shift extending it in a diff --git a/crates/ui-egui/src/tools/forms_ui/calendar.rs b/crates/ui-egui/src/tools/forms_ui/calendar.rs index 2d07f01463..fc0bb4c9cc 100644 --- a/crates/ui-egui/src/tools/forms_ui/calendar.rs +++ b/crates/ui-egui/src/tools/forms_ui/calendar.rs @@ -3,6 +3,7 @@ use craft::ui::contract::{Bind, ShowContainer as _, overlay::Anchor}; // PLAN: assumed `craft::ui::pickers` re-exports `CalendarPopover`, `DatePrecision` and `PickedDate`. use craft::ui::pickers::{CalendarPopover, DatePrecision, PickedDate}; +use craft::ui::runtime::focus::Initial; use egui::Rect; use pdfcraft_engine::form_scripts::{DateTime, format_date, parse_date}; @@ -13,14 +14,21 @@ fn picked_date(text: &str, fmt: &str) -> Option { } /// The calendar of a date field with format `fmt`, hung from `rect` and open while `open` is true. A day picked comes -/// back written in the field's own format, so the caller commits it. Today is the host's day (`RootEnv::today`); the +/// back written in the field's own format, so the caller commits it. Today comes from the session clock; the /// words follow the interface language. -pub(super) fn calendar(ui: &mut egui::Ui, rect: Rect, text: &str, fmt: &str, open: &mut bool) -> Option { +pub(super) fn calendar(ui: &mut egui::Ui, rect: Rect, text: &str, fmt: &str, today: (i64, u32, u32), open: &mut bool) -> Option { let before = picked_date(text, fmt); let mut picked = before.clone(); + let today = PickedDate::day(i32::try_from(today.0).unwrap_or(1970), u8::try_from(today.1).unwrap_or(1), u8::try_from(today.2).unwrap_or(1)); CalendarPopover::new("Calendar", Bind::bound(&mut *open), Bind::bound(&mut picked)) .precisions(&[DatePrecision::Day]) - .overlay(|overlay| overlay.anchor(Anchor::Rect(rect))) + .today(today) + .overlay(|overlay| { + // The text field keeps keyboard focus so typing a date updates the open calendar live. + let focus = overlay.focus.trap(false).restore(false).initial(Initial::KeepAnchor); + let dismiss = overlay.dismiss.focus_left(false); + overlay.anchor(Anchor::Rect(rect)).focus(focus).dismiss(dismiss) + }) .show(ui, |_, _| {}); if picked == before { return None; diff --git a/crates/ui-egui/src/tools/forms_ui/choice_list.rs b/crates/ui-egui/src/tools/forms_ui/choice_list.rs index cdafbfde5d..e9f8b87e17 100644 --- a/crates/ui-egui/src/tools/forms_ui/choice_list.rs +++ b/crates/ui-egui/src/tools/forms_ui/choice_list.rs @@ -52,12 +52,17 @@ pub(super) fn choice_list(ui: &mut egui::Ui, field: &FormField, rect: Rect, zoom }; let names: Vec<&str> = field.options.iter().map(|(_, shown)| shown.as_str()).collect(); let source = Names(&names); - let shown = PopupList::new(tl!("Options"), Bind::bound(&mut *open)).overlay(|overlay| overlay.anchor(Anchor::Rect(rect))).show(ui, |ui, _| { - List::::options(field.name.clone()) - .document_rows(DocumentRows::new(FontRef::proportional(), size, align)) - .show_items(ui, &source, &mut |key, _| ListRow::new(names.get(*key).copied().unwrap_or_default().to_owned()).option()) - .events - }); + let shown = PopupList::new(tl!("Options"), Bind::bound(&mut *open)) + .overlay(|overlay| { + let dismiss = overlay.dismiss.focus_left(false); + overlay.anchor(Anchor::Rect(rect)).dismiss(dismiss) + }) + .show(ui, |ui, _| { + List::::options(tl!("Options")) + .document_rows(DocumentRows::new(FontRef::proportional(), size, align)) + .show_items(ui, &source, &mut |key, _| ListRow::new(names.get(*key).copied().unwrap_or_default().to_owned()).option()) + .events + }); let mut picked = None; for event in shown.inner.into_iter().flatten() { if let CollectionEvent::Activate(key) = event { diff --git a/crates/ui-egui/src/tools/forms_ui/editor.rs b/crates/ui-egui/src/tools/forms_ui/editor.rs index ced6b7bb2b..f8ec9df065 100644 --- a/crates/ui-egui/src/tools/forms_ui/editor.rs +++ b/crates/ui-egui/src/tools/forms_ui/editor.rs @@ -335,7 +335,7 @@ pub(super) fn offset_at( let rect = widget_rect(&xf, info, page, w.rect); let frame = TextFrame::of(&xf, info, page, w, rect); let laid = FieldLayout::build(ctx, f, w, Geometry { frame, zoom: xf.zoom() }, &focus.text, focus.selection.caret); - laid.hit_box(frame.in_box(xf.view_rect([at.x, at.y, at.x, at.y]).min)).0 + laid.hit_box(frame.in_box(at)).0 } /// Show the session of the focused field for this pass: the editor over a Text field or an editable @@ -352,6 +352,7 @@ pub(crate) fn show( doc: &Document, form: &[FormField], info: &DocInfo, + today: (i64, u32, u32), pages: PageGeometry<'_>, ) -> Option { let focus = session.forms.focus.as_ref()?; @@ -406,15 +407,19 @@ pub(crate) fn show( Some(_) | None => {} } let Some(focus) = session.forms.focus.as_mut() else { return shown }; + let was_open = focus.list_open; // A list box is picked from in place on the page, so only a combo box has a drop-down list. let picked = if combo { super::choice_list(ui, f, rect, zoom, &mut focus.list_open) } else { None }; + let list_closed = combo && !types && was_open && !focus.list_open; let date = match &f.actions.format { - pdfcraft_engine::form_scripts::Format::Date(fmt) if types => super::calendar(ui, rect, &focus.text, fmt, &mut focus.calendar_open), + pdfcraft_engine::form_scripts::Format::Date(fmt) if types => super::calendar(ui, rect, &focus.text, fmt, today, &mut focus.calendar_open), _ => None, }; if let Some(i) = picked { session.pending_edit = Some(list_pick_edit(form, f, vec![i])); session.forms.focus = None; + } else if list_closed { + session.forms.focus = None; } else if let Some(text) = date { focus.text = text; commit(session, form); diff --git a/crates/ui-egui/src/tools/object_ui.rs b/crates/ui-egui/src/tools/object_ui.rs index 59ad5290e1..6f9d21d156 100644 --- a/crates/ui-egui/src/tools/object_ui.rs +++ b/crates/ui-egui/src/tools/object_ui.rs @@ -32,6 +32,8 @@ pub(crate) struct ObjectSelection { /// A paragraph (page, block) to select once the document is at hand: Esc in the inline /// editor asks for it, and the next `prepare` selects it. select_paragraph: Option<(usize, usize)>, + /// Modifiers held when a marquee drag started, so releasing Shift before the mouse button still extends. + marquee_mods: Mods, } impl ObjectSelection { @@ -39,6 +41,10 @@ impl ObjectSelection { self.selected.len() } + pub(crate) fn target_at(&self, index: usize) -> Option { + self.selected.get(index).map(|o| o.target) + } + /// The page and references of the objects selected together, if any: what Copy and Cut take. pub(crate) fn selection(&self) -> Option<(usize, Vec)> { self.page.filter(|_| !self.selected.is_empty()).map(|page| (page, self.selected.iter().map(|o| o.target).collect())) @@ -297,8 +303,9 @@ fn modified_target(session: &mut PageSession, doc: &Document, page: usize, xf: & /// An area selection begins on `page`: the single selections of the families let go. The sweep itself is the /// press's span, read from each pass's press phase. -pub(crate) fn begin_marquee(session: &mut PageSession, page: usize) { +pub(crate) fn begin_marquee(session: &mut PageSession, page: usize, mods: Mods) { leave_single(session); + session.objects.marquee_mods = mods; session.pending_page = Some((page, None)); } @@ -324,6 +331,13 @@ pub(crate) fn end_marquee( geo: PageGeometry<'_>, ) { let Some((page, xf)) = session.page_xforms(geo).into_iter().find(|(_, xf)| xf.rect.contains(start.origin)) else { return }; + let start_mods = std::mem::take(&mut session.objects.marquee_mods); + let mods = Mods { + shift: start_mods.shift || mods.shift, + cmd: start_mods.cmd || mods.cmd, + ctrl: start_mods.ctrl || mods.ctrl, + alt: start_mods.alt || mods.alt, + }; let base = session.objects.selection().filter(|(on, _)| *on == page).map(|(_, targets)| targets).unwrap_or_default(); let mut sweep = MarqueeSelect::begin(start.origin, mods, base); sweep.update(pos); @@ -405,7 +419,7 @@ pub(crate) fn object_controls( } let offset = presses .iter() - .filter(|p| p.page == page && matches!(p.owner, Owner::Objects | Owner::Frame { .. })) + .filter(|p| p.page == page && matches!(p.owner, Owner::Objects { .. } | Owner::Frame { .. })) .find_map(|p| match &p.phase { PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } => Some(*pos - start.origin), _ => None, @@ -441,20 +455,17 @@ pub(crate) fn page_parts( && let Ok(objects) = session.objects.inventory(doc, page) && let Some(object) = objects.iter().find(|o| o.target == ObjectTarget { kind: ObjectKind::Text, index: block }) { - out.extend( - frame_band(screen(&xf, info, page, object)) - .map(|band| PagePart::new(Owner::Frame { block }, page, HitShape::Rect(band), PageLayer::Handle).cursor(CursorIcon::Move)), - ); + out.extend(frame_band(screen(&xf, info, page, object)).into_iter().enumerate().map(|(side, band)| { + PagePart::new(Owner::Frame { block, side }, page, HitShape::Rect(band), PageLayer::Handle).cursor(CursorIcon::Move) + })); } let s = &session.objects; if s.page != Some(page) || s.selected.is_empty() { continue; } - out.extend( - s.selected - .iter() - .map(|o| PagePart::new(Owner::Objects, page, HitShape::Rect(screen(&xf, info, page, o)), PageLayer::Placed).cursor(CursorIcon::Move)), - ); + out.extend(s.selected.iter().enumerate().map(|(index, o)| { + PagePart::new(Owner::Objects { index }, page, HitShape::Rect(screen(&xf, info, page, o)), PageLayer::Placed).cursor(CursorIcon::Move) + })); } } @@ -465,7 +476,7 @@ pub(crate) fn objects_press(session: &mut PageSession, doc: &Document, info: &Do let page = press.page; match press.phase { PressPhase::Down { .. } => { - if let Owner::Frame { block } = press.owner { + if let Owner::Frame { block, .. } = press.owner { let object = session .objects .inventory(doc, page) diff --git a/crates/ui-egui/src/tools/redact_ui/dialogs.rs b/crates/ui-egui/src/tools/redact_ui/dialogs.rs index cc89ae8e91..ae0daa84a9 100644 --- a/crates/ui-egui/src/tools/redact_ui/dialogs.rs +++ b/crates/ui-egui/src/tools/redact_ui/dialogs.rs @@ -265,7 +265,7 @@ pub(crate) fn show_search(app: &mut PdfCraftApp, ui: &mut Ui) { true }); app.redact_search = draft; - if shown.accepted.is_some() { + if shown.accepted.is_some() || shown.picked == Some(0) { let n = app.redact_search(ui.ctx()); app.redact_search.found = Some(n); } else if shown.closed.is_some() { diff --git a/crates/ui-egui/src/workflows/create_multiple_ui.rs b/crates/ui-egui/src/workflows/create_multiple_ui.rs index 6ba57bf2d6..5fa2a1393e 100644 --- a/crates/ui-egui/src/workflows/create_multiple_ui.rs +++ b/crates/ui-egui/src/workflows/create_multiple_ui.rs @@ -59,7 +59,7 @@ impl PdfCraftApp { let base = safe_file_stem(stem(&name), "pdf"); let base = if base.is_empty() { "document" } else { &base }; let filename = unique_file_name(&format!("{base}.pdf"), CopyNumbering::Parenthesized, |candidate| { - used.contains(&candidate.to_lowercase()) || dir.as_ref().is_some_and(|d| d.join(candidate).exists()) + used.contains(&candidate.to_lowercase()) || dir.as_ref().is_some_and(|d| self.host.files().exists(&d.join(candidate))) }); used.insert(filename.to_lowercase()); // Without a folder (the web) the write is a download. diff --git a/crates/ui-egui/src/workflows/optimize_ui.rs b/crates/ui-egui/src/workflows/optimize_ui.rs index 2c7b5d5951..5785fb541d 100644 --- a/crates/ui-egui/src/workflows/optimize_ui.rs +++ b/crates/ui-egui/src/workflows/optimize_ui.rs @@ -522,9 +522,8 @@ fn audit_row(rows: Arc>>) -> Param { } /// The Space Audit row, for a dialog that shows the audit among other rows (Properties ▸ Space Audit): reads the app's shared -/// result each pass. It starts no measure, so a dialog may build it every pass; the caller runs `measure_space_audit` once when -/// the tab opens and again on the document-changed event. -// PLAN: pdf-dialogs-w7 calls `measure_space_audit` when Properties ▸ Space Audit opens; the document-changed handler (pdf-hub-w3) calls it too. +/// result each pass. It starts no measure, so a dialog may build it every pass; `properties.rs` runs `measure_space_audit` +/// when Properties ▸ Space Audit opens and again after an edit. pub(crate) fn space_audit_param(app: &PdfCraftApp) -> Param { audit_row(app.space_audit.clone()) } diff --git a/crates/ui-egui/tests/it/create.rs b/crates/ui-egui/tests/it/create.rs index 793def5e1b..08668cf9e3 100644 --- a/crates/ui-egui/tests/it/create.rs +++ b/crates/ui-egui/tests/it/create.rs @@ -206,13 +206,14 @@ fn the_pdf_optimizer_dialog_picks_a_preset() { assert!(h.execute("optimize.advanced")); h.run_steps(2); h.get_by_value("Standard"); + assert!(h.query_all_by_value("150").next().is_some(), "Standard downsamples colour/gray images to 150 ppi"); assert_eq!(h.get_by_label("Merge image fragments").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); h.get_by_value("Standard").click(); h.run_steps(4); h.get_by_label("Mobile").click(); h.run_steps(2); h.get_by_value("Mobile"); - assert_eq!(h.get_by_label("Merge image fragments").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False), "Mobile turns it off"); + assert!(h.query_all_by_value("96").next().is_some(), "Mobile downsamples colour/gray images to 96 ppi"); // Changing an option makes the settings custom. h.get_by_label("Merge image fragments").click(); h.run_steps(2); diff --git a/crates/ui-egui/tests/it/forms.rs b/crates/ui-egui/tests/it/forms.rs index 36e58cd6bd..cb4a5a78d7 100644 --- a/crates/ui-egui/tests/it/forms.rs +++ b/crates/ui-egui/tests/it/forms.rs @@ -39,7 +39,9 @@ fn scripted_harness( /// The text of the newest notice on screen, if one is shown. fn notice(h: &Harness<'static, PdfCraftApp>) -> Option { - toast::cards(&h.ctx, &WindowKey::main()).last().map(|card| card.toast.message.as_str().to_owned()) + toast::cards(&h.ctx, &WindowKey::main()) + .last() + .map(|card| card.toast.title.as_ref().map_or_else(|| card.toast.message.as_str(), |t| t.as_str()).to_owned()) } fn undo(h: &mut Harness<'static, PdfCraftApp>) { @@ -704,12 +706,11 @@ fn dragging_over_another_fields_text_focuses_it_and_selects_from_the_press() { h.run_steps(3); click_field(&mut h, "city", 0); assert_eq!(h.state().views[0].session.forms.focus.as_ref().map(|f| f.name.as_str()), Some("city")); - let (rect, id) = { + let rect = { let s = h.state(); let doc = s.session.get(s.views[0].id).unwrap(); let f = doc.form.iter().find(|f| f.name == "name").unwrap(); - let rect = pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen"); - (rect, egui::Id::unique(("form-field", s.views[0].view_key(), "name", 0usize))) + pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen") }; // From inside the first word ("Ad|a" at the field's auto size, 13.9 pt) to past the end of the text. let (from, to) = (egui::pos2(rect.left() + 38.0, rect.center().y), egui::pos2(rect.right() - 8.0, rect.center().y)); @@ -725,10 +726,10 @@ fn dragging_over_another_fields_text_focuses_it_and_selects_from_the_press() { h.run_steps(3); assert_eq!(h.state().views[0].session.forms.focus.as_ref().map(|f| f.name.as_str()), Some("name"), "the press moved the focus"); let n = "Ada Lovelace".chars().count(); - let range = egui::TextEdit::load_state(&h.ctx, id).and_then(|s| s.cursor.char_range()).expect("a selection in the field"); + let sel = h.state().views[0].session.forms.focus.as_ref().expect("focused field").selection; // "Ad|a": not the caret at the end that a newly focused editor gets on its own. - assert_eq!(range.secondary.index.0, 2, "anchored where the drag started: {range:?}"); - assert_eq!(range.primary.index.0, n, "and extended to where it ended: {range:?}"); + assert_eq!(sel.anchor, 2, "anchored where the drag started: {sel:?}"); + assert_eq!(sel.caret, n, "and extended to where it ended: {sel:?}"); } #[test] @@ -746,9 +747,9 @@ fn date_fields_offer_a_calendar() { let month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][(m - 1) as usize]; h.get_by_label(&format!("{month} {y}")); - h.get_by_label("›").click(); + h.get_by_label("Next").click(); h.run_steps(2); - h.get_by_label("15").click(); + h.get_by_label_contains(" 15, ").click(); h.run_steps(4); let (ny, nm) = if m == 12 { (y + 1, 1) } else { (y, m + 1) }; assert_eq!(value(&h, "due"), vec![format!("{nm:02}/15/{ny}")], "picked in the field's format"); @@ -781,7 +782,7 @@ fn the_calendar_follows_a_complete_date_typed_while_it_is_open() { h.get_by_label("March 2025"); // The arrows still turn the months, and the calendar stays on their month while the text // doesn't change. - h.get_by_label("›").click(); + h.get_by_label("Next").click(); h.run_steps(3); h.get_by_label("April 2025"); } @@ -849,7 +850,7 @@ fn the_calendar_picks_today_in_the_fields_format_from_any_month() { )); h.run_steps(4); // Two months on, and two months back: Today still picks the 14th of November. - for (name, arrow, shown, want) in [("due", "›", "January 2024", "11/14/2023"), ("start", "‹", "September 2023", "2023-11-14")] { + for (name, arrow, shown, want) in [("due", "Next", "January 2024", "11/14/2023"), ("start", "Previous", "September 2023", "2023-11-14")] { click_field(&mut h, name, 0); h.get_by_label("November 2023"); for _ in 0..2 { diff --git a/crates/ui-egui/tests/it/object_selection.rs b/crates/ui-egui/tests/it/object_selection.rs index f0d2e49a78..718ebcea55 100644 --- a/crates/ui-egui/tests/it/object_selection.rs +++ b/crates/ui-egui/tests/it/object_selection.rs @@ -540,7 +540,6 @@ fn keys(h: &mut Harness<'static, PdfCraftApp>, modifiers: Modifiers, key: Key) { /// The paste chord: the platform answers the request with the text of the latest copy. fn paste(h: &mut Harness<'static, PdfCraftApp>, copies: &Copies) { - h.key_press_modifiers(Modifiers::COMMAND, Key::V); h.event(egui::Event::Paste(copied_text(copies).unwrap_or_default())); h.run_steps(4); } @@ -657,11 +656,11 @@ fn a_picture_for_a_native_edit_paste_with_a_context_menu_open_lands_on_the_page( h.run_steps(1); } h.run_steps(2); - assert!(egui::Popup::is_any_open(&h.ctx), "the context menu is open"); + assert!(h.query_by_role(egui::accesskit::Role::Menu).is_some(), "the context menu is open"); let before = can_undo(&h, 0); crate::support::fire_menu(&mut h, "edit.paste"); assert!(crate::support::asked_for_the_clipboard(&h), "Edit ▸ Paste asked the platform for the clipboard"); - assert!(!egui::Popup::is_any_open(&h.ctx), "Edit ▸ Paste closed the context menu"); + assert!(h.query_by_role(egui::accesskit::Role::Menu).is_none(), "Edit ▸ Paste closed the context menu"); h.event(egui::Event::PasteImage(std::sync::Arc::new(egui::ColorImage::filled([30, 20], egui::Color32::GRAY)))); h.run_steps(3); assert_ne!(can_undo(&h, 0), before, "the picture was dropped"); diff --git a/crates/ui-egui/tests/it/pdf_links.rs b/crates/ui-egui/tests/it/pdf_links.rs index 8d918a3fde..a4b78be31a 100644 --- a/crates/ui-egui/tests/it/pdf_links.rs +++ b/crates/ui-egui/tests/it/pdf_links.rs @@ -116,9 +116,9 @@ fn link_properties_sets_the_page_view_zoom() { // The field's caption and the toolbar's zoom carry the name too: the choice is the drop-down. h.get_by_role_and_label(Role::ComboBox, "Zoom").click(); h.run_steps(3); - h.get_by_role_and_label(Role::Button, "200%").scroll_to_me(); + h.get_by_role_and_label(Role::ListBoxOption, "200%").scroll_to_me(); h.run_steps(3); - h.get_by_role_and_label(Role::Button, "200%").click(); + h.get_by_role_and_label(Role::ListBoxOption, "200%").click(); h.run_steps(2); h.get_by_label("OK").click(); h.run_steps(3); diff --git a/crates/ui-egui/tests/it/pickers.rs b/crates/ui-egui/tests/it/pickers.rs index a4392270f2..02f439bac0 100644 --- a/crates/ui-egui/tests/it/pickers.rs +++ b/crates/ui-egui/tests/it/pickers.rs @@ -154,6 +154,15 @@ fn save_answer() -> String { save.as_str().to_string() } +/// The unsaved-changes question's "don't save" answer as the framework words it on this OS: Don't Save on macOS, +/// No on Windows and Linux. +fn dont_save_answer() -> String { + use craft::i18n::WordSet as _; + let words = craft::ui::dialog::DialogWords::english(); + let discard = if cfg!(target_os = "macos") { words.unsaved_dont_save } else { words.unsaved_no }; + discard.as_str().to_string() +} + /// Presses the button called `label` of the dialog on top (the last such node drawn). fn press(r: &mut Rig, label: &str) { r.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label:?} button on screen")).click(); @@ -556,7 +565,7 @@ fn a_close_prompt_still_means_its_own_document_after_a_pending_save_closes_anoth h.answer(Picked::Paths(vec![dir.join("a.pdf")])); assert_eq!(h.state().views.len(), 2, "the first tab closed once saved"); // Don't Save: the prompt was about the second document, which is now the first tab. - press(&mut h, "Don't save"); + press(&mut h, &dont_save_answer()); let open: Vec<_> = h.state().views.iter().map(|v| v.id).collect(); assert_eq!(open, vec![c], "the second document closed, not the third: {b:?} vs {c:?}"); assert!(dirty(h.state(), 0), "the third document keeps its unsaved changes"); diff --git a/crates/ui-egui/tests/it/redact.rs b/crates/ui-egui/tests/it/redact.rs index d3cfd3997a..d6bb4bf4b4 100644 --- a/crates/ui-egui/tests/it/redact.rs +++ b/crates/ui-egui/tests/it/redact.rs @@ -371,6 +371,9 @@ fn undoing_saved_redactions_while_the_save_dialog_is_open_asks_again() { } assert_eq!(h.state().views[0].redactions_undone_after_save, 1); let elsewhere = dir.join("contract_restored.pdf"); + assert!(files.answer(Picked::Paths(vec![copy.clone()])).is_some(), "first Save dialog is open"); + h.run_steps(3); + assert_eq!(files.file(©).unwrap(), saved, "the first answer was discarded when redactions changed"); assert!(files.answer(Picked::Paths(vec![elsewhere.clone()])).is_some(), "Save asked again and waits for the user"); // The write runs on a worker: step until it has landed. crate::support::wait_until(&mut h, "the save to land", |_| files.file(&elsewhere).is_some()); @@ -406,6 +409,9 @@ fn undoing_apply_redactions_while_the_save_dialog_is_open_asks_again() { h.execute("edit.undo"); assert_eq!(h.state().views[0].redactions_applied, 0); let elsewhere = dir.join("contract_copy.pdf"); + assert!(files.answer(Picked::Paths(vec![copy.clone()])).is_some(), "first Save dialog is open"); + h.run_steps(3); + assert!(files.file(©).is_none(), "the first answer was discarded when redactions were undone"); assert!(files.answer(Picked::Paths(vec![elsewhere.clone()])).is_some(), "Save asked again and waits for the user"); // The write runs on a worker: step until it has landed. crate::support::wait_until(&mut h, "the save to land", |_| files.file(&elsewhere).is_some()); diff --git a/crates/ui-egui/tests/perf.rs b/crates/ui-egui/tests/perf.rs index 90a3201c49..acdc4926d6 100644 --- a/crates/ui-egui/tests/perf.rs +++ b/crates/ui-egui/tests/perf.rs @@ -131,7 +131,7 @@ fn a_folded_page_builds_no_comment_cards_and_an_open_one_builds_only_the_rows_in assert_eq!(state.views[0].session.comments.panel.collapsed_pages, [0]); } let (folded, _) = most_work(&mut h, Some("CommentRow"), 6, |_, _| {}); - assert_eq!(folded, 0, "a folded page builds no cards"); + assert_eq!(folded, 1, "a folded page builds only its heading row, no cards"); h.state_mut().views[0].session.comments.panel.collapsed_pages.clear(); let (open, _) = most_work(&mut h, Some("CommentRow"), 6, |_, _| {}); assert!(open > 0, "the open page builds the cards in view");