From effa71b837b2e08fa76c668312147077cffe54b7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:56:58 -0500 Subject: [PATCH] red10 g6: app red round 10 fixes --- crates/ui-egui/src/app.rs | 9 +- crates/ui-egui/src/app/control.rs | 3 + crates/ui-egui/src/app/reload.rs | 8 ++ crates/ui-egui/src/canvas.rs | 40 ++++-- crates/ui-egui/src/canvas/image_pick.rs | 3 + crates/ui-egui/src/canvas/navigation.rs | 6 +- crates/ui-egui/src/canvas/organize.rs | 1 + crates/ui-egui/src/canvas/page_tools.rs | 106 +++++++++++++++- crates/ui-egui/src/commands.rs | 16 ++- crates/ui-egui/src/control.rs | 5 +- .../ui-egui/src/dialogs/bookmark_styles_ui.rs | 17 ++- crates/ui-egui/src/dialogs/pageboxes.rs | 12 +- crates/ui-egui/src/dialogs/properties.rs | 4 +- crates/ui-egui/src/editing.rs | 19 ++- crates/ui-egui/src/hotbar.rs | 14 +++ crates/ui-egui/src/panels/bookmarks.rs | 15 ++- crates/ui-egui/src/panels/pages.rs | 5 + crates/ui-egui/src/panels/side_panels.rs | 20 +-- crates/ui-egui/src/persist/recovery.rs | 5 + crates/ui-egui/src/tools/comments/tool.rs | 2 +- crates/ui-egui/src/tools/forms_ui/calendar.rs | 11 +- crates/ui-egui/src/tools/measure_ui.rs | 6 +- crates/ui-egui/src/tools/prepare.rs | 12 +- crates/ui-egui/src/tools/prepare/tool.rs | 116 ++++++++++-------- crates/ui-egui/src/workflows/optimize_ui.rs | 6 +- crates/ui-egui/tests/it/bookmarks.rs | 23 ++-- crates/ui-egui/tests/it/comment_pin.rs | 18 ++- crates/ui-egui/tests/it/control.rs | 24 +++- crates/ui-egui/tests/it/pageboxes.rs | 1 + crates/ui-egui/tests/it/prepare.rs | 32 +++-- crates/ui-egui/tests/it/reading_colors.rs | 33 +++-- crates/ui-egui/tests/it/reload.rs | 6 +- crates/ui-egui/tests/it/theme.rs | 56 ++++----- crates/ui-egui/tests/it/viewer.rs | 36 +++--- 34 files changed, 487 insertions(+), 203 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b637d521cc..b7e1bc2a2f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -539,7 +539,7 @@ impl PdfCraftApp { /// A dialog or prompt is open over the window: the keyboard is its own, and nothing may act /// on the document underneath it. pub(crate) fn modal_open(&self) -> bool { - !self.dialogs.is_empty() + self.has_non_recovery_dialog() || self.password_prompt.is_some() || self.unlock_prompt.is_some() || self.pending_link.is_some() @@ -724,13 +724,12 @@ impl PdfCraftApp { // Scrolling and group-drag previews are transient: never resume after changing tabs, // opening a modal/palette, or returning to a window that lost focus. let blocked = self.modal_open() || self.palette_open || !ctx.input(|i| i.focused); - if blocked { - let thread = std::thread::current(); - let name = thread.name().unwrap_or("").rsplit("::").next().unwrap_or(""); - } for (index, view) in self.views.iter_mut().enumerate() { let shut = blocked || self.active != Some(index); view.session.objects.set_input_blocked(shut); + if shut { + view.left_screen(); + } // Edit text and Add text's drags end while their input is blocked rather than wait, to // land wherever the pointer is once it opens again. if shut && matches!(self.quick_tool, QuickTool::EditText | QuickTool::AddText) { diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index efd6a3d5fd..eb45296c9f 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -499,6 +499,9 @@ impl PdfCraftApp { "page-properties" => { self.execute(ctx, "page.properties"); } + "page.rotate_dialog" => { + self.execute(ctx, "page.rotate_dialog"); + } "comment-props" => { let (page, index) = self .active diff --git a/crates/ui-egui/src/app/reload.rs b/crates/ui-egui/src/app/reload.rs index 7f7ace861c..e85b09816f 100644 --- a/crates/ui-egui/src/app/reload.rs +++ b/crates/ui-egui/src/app/reload.rs @@ -57,7 +57,15 @@ impl PdfCraftApp { if self.holds_reload() { return; } + let mut latest: Vec> = Vec::new(); for change in self.watch.take_changes() { + if let Some(slot) = latest.iter_mut().find(|c| c.key == change.key) { + *slot = change; + } else { + latest.push(change); + } + } + for change in latest { self.file_changed(ctx, change); } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c5d517778a..bd2ae2a1de 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -247,6 +247,10 @@ pub struct DocView { pub(crate) pages_focus_id: Option, /// Scale of the thumbnails in the Pages inspector, independent of document and grid zoom. thumbnail_zoom: f32, + /// The current page the Pages panel last scrolled into view. + pub(crate) panel_followed: Option, + /// The thumbnail zoom the Pages panel last scrolled for. + pub(crate) panel_zoom_followed: f32, /// The page the grid scrolls into view on its next pass (Organize just opened on it). grid_reveal: Option, /// The bookmarks open in the Bookmarks panel, by their path in the outline. @@ -607,6 +611,8 @@ impl DocView { dropped_files: None, pages_focus_id: None, thumbnail_zoom: 1.0, + panel_followed: None, + panel_zoom_followed: 1.0, grid_reveal: None, bookmarks_open: crate::panels::bookmarks::opened_as_filed(&info.outline), redactions_applied: 0, @@ -924,6 +930,8 @@ struct BodyOut { /// A part of the page (a link, a field, a comment…) is under the pointer: in full screen a click there is the /// part's and turns no page. over_part: bool, + /// The page a primary press started on in this pass, so clicking a page in continuous view makes it current. + pressed_page: Option, } /// The part list of a pass, in paint order: pictures, paragraphs and added items, links and text links (only under @@ -1230,9 +1238,12 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, // 4. The tool host, in the real run only: a measuring run has no tool pass. if let Some(pass) = body.pass { - if matches!(pass.press.phase, PressPhase::Down { .. }) { + if let PressPhase::Down { start, .. } = &pass.press.phase { // A press nobody's part took, on the page or the gap between pages, ends Select All of the document. session.all_text = false; + if start.button == PointerButton::Primary { + out.pressed_page = body.pages.iter().find(|p| p.rect.contains(start.origin)).map(|p| p.page); + } } let button_held = ui.input(|i| i.pointer.any_down()); let tool_cx = PageToolCx { pages: body.pages, viewport: body.rect, view: body.view, button_held, ..cx.tools }; @@ -1268,7 +1279,10 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, } out.turn = finish.turn; out.open_signature = finish.open_signature; - let outcome = session.prepare.take_outcome(); + let mut outcome = session.prepare.take_outcome(); + if let Some(edit) = outcome.edit.take() { + session.pending_edit = Some(edit); + } out.back_to_select |= outcome.placed; out.prepare = Some(outcome); } @@ -1280,7 +1294,7 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, .show_at(ui, body.rect); } if cx.preparing { - crate::prepare::tool::show_overlays(ui, body.rect, session, cx.form, cx.info, body.pages, cx.rotation); + crate::prepare::tool::show_overlays(ui, body.rect, body.view, session, cx.form, cx.info, body.pages, cx.rotation); } if cx.editing_content { let geo = cx.geometry(body); @@ -1647,14 +1661,24 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu }; let source = DocPages::new(&app.session, doc_id).rotated(state.rotation).revisions(revisions).reports(reports); // A modal over the pages blocks the canvas's keys and presses in the framework, so the view needs no gate here. - let out = PageView::new(tl!("Pages"), &source, state, DataColor::new(paper)).navigation(navigation).border(border).keep(&keep).show_at( - ui, - rect, - |ui, body| page_body(ui, body, session, momentary, &cx, &mut body_out), - ); + // Scope each tab's PageView by its view key so per-canvas gestures (like middle-button autoscroll) stay tab-local. + let out = ui + .push_id(view_key, |ui| { + PageView::new(tl!("Pages"), &source, state, DataColor::new(paper)).navigation(navigation).border(border).keep(&keep).show_at( + ui, + rect, + |ui, body| page_body(ui, body, session, momentary, &cx, &mut body_out), + ) + }) + .inner; if let Some(canvas) = &body_out.view { out.adopt(&mut view.view, canvas); } + if view.view.continuous + && let Some(page) = body_out.pressed_page + { + view.view.current = page; + } if out.scrolled { view.end_find_following(); } diff --git a/crates/ui-egui/src/canvas/image_pick.rs b/crates/ui-egui/src/canvas/image_pick.rs index c8c97ffbf9..26c6b3edb1 100644 --- a/crates/ui-egui/src/canvas/image_pick.rs +++ b/crates/ui-egui/src/canvas/image_pick.rs @@ -60,6 +60,9 @@ pub(crate) fn resolve_pending( }) }); let Some(picked) = answer else { return }; + if picked.is_some() { + session.text.selection = None; + } session.picked_image = picked; session.pending_pick = None; } diff --git a/crates/ui-egui/src/canvas/navigation.rs b/crates/ui-egui/src/canvas/navigation.rs index f37760a7e9..806f178b7a 100644 --- a/crates/ui-egui/src/canvas/navigation.rs +++ b/crates/ui-egui/src/canvas/navigation.rs @@ -64,8 +64,10 @@ impl DocView { let top = self.viewport_rect().top(); let xforms = self.page_xforms(); // A page showing less than a sliver is rounding, not what the reader is looking at: a jump - // to the next page leaves the previous one's bottom edge within a pixel of the top. Such a + // to the next page leaves the previous one's bottom edge within a pixel of the top (or, + // when `PageView`'s top margin exceeds its page gap, peeking into that top margin). Such a // sliver still counts when nothing else shows (the last page at the very end). + let peek = self.spacing.as_ref().map_or(0.0, |s| (s.margin - s.gap).max(0.0) as f32); let pick = |slack: f32| { let showing = || xforms.iter().filter(move |(_, xf)| xf.rect.bottom() > top + slack); showing() @@ -73,7 +75,7 @@ impl DocView { .min_by_key(|(p, _)| *p) .or_else(|| showing().min_by(|a, b| a.1.rect.top().total_cmp(&b.1.rect.top()).then(a.0.cmp(&b.0)))) }; - let (page, xf) = pick(SLIVER).or_else(|| pick(0.0))?; + let (page, xf) = pick(peek + SLIVER).or_else(|| pick(SLIVER)).or_else(|| pick(0.0))?; let p = info.pages.get(*page)?; // Above the page (in the gap before it) is the page's own top. The window's vertical is // the view's y, or its x when the view is turned a quarter. diff --git a/crates/ui-egui/src/canvas/organize.rs b/crates/ui-egui/src/canvas/organize.rs index bbfce5c43c..b2fdde1e99 100644 --- a/crates/ui-egui/src/canvas/organize.rs +++ b/crates/ui-egui/src/canvas/organize.rs @@ -227,6 +227,7 @@ pub(super) fn organize_grid(view: &mut DocView, doc: &pdfcraft_engine::Document, .invert_middle(cx.invert_middle) .reveal(reveal) .show(cx.ui); + view.middle_scrolling = out.auto_scrolling; // The menu is open from the request until a row runs or it is dismissed. // PLAN: assumed the open anchor needs a remembered slot; egui's temp data keyed by the grid stands in for it. diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index d46b09cd0b..e22cbf36ca 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -292,7 +292,9 @@ pub(crate) fn page_tool<'a>( let selects_text = tool_selects_text(tool, cx.preparing); 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))), + QuickTool::Select if cx.preparing => { + Arm::Area(Box::new(PrepareTool::new(None, cx.can_modify, cx.form, &mut session.prepare, &session.placed, cx.info, xforms))) + } QuickTool::Select | QuickTool::ColumnSelect | QuickTool::Comment(_) | QuickTool::Redact => { let texts: &'a DocTexts<'a> = texts_slot.insert(DocTexts::new(&session.texts, &session.text_failed, cx.rotation, cx.sizes)); let picks = PickSlots::new(&mut session.pending_pick, &mut session.picked_image, &mut session.actions_dismissed); @@ -324,7 +326,12 @@ pub(crate) fn page_tool<'a>( None => annotate, }; let annotate = if selects_text { annotate.over(select) } else { annotate }; - Arm::Area(Box::new(annotate)) + if cx.preparing && matches!(tool, QuickTool::Comment(_)) { + let prepare = PrepareTool::new(None, cx.can_modify, cx.form, &mut session.prepare, &session.placed, cx.info, xforms); + Arm::Area(Box::new(PrepareWithComment { prepare, comments: Box::new(annotate) })) + } else { + Arm::Area(Box::new(annotate)) + } } } } @@ -364,7 +371,9 @@ pub(crate) fn page_tool<'a>( .over(place); Arm::Area(Box::new(annotate)) } - QuickTool::Field(field_tool) => Arm::Area(Box::new(PrepareTool::new(Some(field_tool), cx.can_modify, cx.form, session, cx.info, xforms))), + QuickTool::Field(field_tool) => { + Arm::Area(Box::new(PrepareTool::new(Some(field_tool), cx.can_modify, cx.form, &mut session.prepare, &session.placed, cx.info, xforms))) + } QuickTool::AddText => Arm::Area(Box::new(crate::tools::content_ui::AddTextTool::new(session, cx.doc, cx.pages, cx.text_style))), QuickTool::EditText => { Arm::Area(Box::new(EditTextTool::new(session, cx.doc, cx.info, cx.pages, press, cx.geometry()).button_held(cx.button_held))) @@ -471,6 +480,11 @@ impl ToolFinish { if let Some(edit) = self.edit.take() { session.pending_edit = Some(edit); } + if let Some(done) = self.crop.take() + && let Some(edit) = super::crop::crop_edit(cx.info, &done) + { + session.pending_edit = Some(edit); + } if let Some(page) = self.camera_page.take() && let Some(placed) = cx.pages.iter().find(|placed| placed.page == page) { @@ -635,3 +649,89 @@ impl CanvasTool for PageTool<'_> { self.tool().command_form() } } + +/// While Prepare a form is open with a comment tool active: Prepare takes press-and-drag on the +/// empty page (marquee selection, field moves), while plain clicks reach the comment tool (L-258). +struct PrepareWithComment<'a> { + prepare: PrepareTool<'a>, + comments: Box, +} + +impl CanvasTool for PrepareWithComment<'_> { + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { + self.prepare.each_pass(cx); + self.comments.each_pass(cx); + } + + fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { + let action = self.prepare.press(pointer, cx); + if action != ToolAction::Ignored { + return action; + } + self.comments.press(pointer, cx) + } + + fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + if self.prepare.has_gesture() { + self.prepare.drag(pointer, cx); + } else { + self.comments.drag(pointer, cx); + } + } + + fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + if self.prepare.is_click_marquee() { + self.prepare.release(pointer, cx); + if self.comments.press(pointer, cx) == ToolAction::Claimed { + self.comments.release(pointer, cx); + } + } else if self.prepare.has_gesture() { + self.prepare.release(pointer, cx); + } else { + self.comments.release(pointer, cx); + } + } + + fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + self.prepare.hover(pointer, cx); + self.comments.hover(pointer, cx); + } + + fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) { + if self.prepare.has_gesture() { + self.prepare.cancel(reason, cx); + } else { + self.comments.cancel(reason, cx); + } + } + + fn claims(&self) -> ToolClaims { + let prep = self.prepare.claims(); + if prep != ToolClaims::NONE { prep } else { self.comments.claims() } + } + + fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool { + self.prepare.key(key, cx) || self.comments.key(key, cx) + } + + fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { + self.comments.paint(draw, cx); + self.prepare.paint(draw, cx); + } + + fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + self.comments.cursor(cx) + } + + fn takes(&self, button: PointerButton, mods: Mods) -> bool { + self.prepare.takes(button, mods) || self.comments.takes(button, mods) + } + + fn access(&self, cx: &ToolContext<'_>) -> Option { + self.comments.access(cx) + } + + fn command_form(&self) -> ToolPath { + self.comments.command_form() + } +} diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs index 806165bbfa..f75cf831f5 100644 --- a/crates/ui-egui/src/commands.rs +++ b/crates/ui-egui/src/commands.rs @@ -142,7 +142,14 @@ impl PdfCraftApp { self.open_preferences_at(page); } } - "app.theme" => self.toggle_theme(ctx), + "app.theme" => { + let next = match self.theme_preference { + ModeChoice::System => ModeChoice::Light, + ModeChoice::Light => ModeChoice::Dark, + ModeChoice::Dark => ModeChoice::System, + }; + self.set_theme_preference(next); + } "tools.expand" => self.expand_all_tools(ctx), "tools.collapse" => self.all_tools_full = false, "tools.all" => { @@ -434,11 +441,8 @@ impl PdfCraftApp { // Navigation and this command can arrive before the next rail frame. view.page_input = view.current_page_label(doc.info.pages.get(view.current()).map(|p| p.label.as_str())); } - ctx.memory_mut(|m| m.request_focus(id)); - let mut state = egui::TextEdit::load_state(ctx, id).unwrap_or_default(); - let len = view.page_input.chars().count(); - state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(len)))); - state.store(ctx, id); + craft::ui::runtime::focus::request(ctx, craft::ui::runtime::focus::FocusTarget::Id(id)); + view.page_input_reselect = true; } } "view.palette" => self.palette_open = !self.palette_open, diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 76fa32273f..026bc24539 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -121,7 +121,10 @@ impl PdfCraftApp { let host = WindowHost::of(ctx); if let Some(queued) = input_method(method, params, &host, ViewportId::ROOT, &|_| None) { return match queued { - Ok(()) => Reply::AfterInput, + Ok(()) => { + self.control_epoch = self.capture_epoch(); + Reply::AfterInput + } Err(e) => Reply::from_result(Err(e)), }; } diff --git a/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs b/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs index 23fb777911..26a14b4cb9 100644 --- a/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs +++ b/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs @@ -79,14 +79,27 @@ impl PdfCraftApp { if level == 0 { param } else { param.enabled_when_in(level_key(level - 1), style_ids.clone()) } }) .collect(); - let dialog = HostedParamDialog::new(ctx, KEY, DialogFields::new(), move |_| { - ParamDialog::new(KEY, tl!("New bookmarks from text styles"), params.clone()).ok_label(tl!("Create").into()) + let mut fields = DialogFields::new(); + for (level, slot) in draft.levels.iter().enumerate() { + let value = slot.map_or_else(|| NONE.to_string(), |i| i.to_string()); + fields.set(level_key(level), value); + } + let dialog = HostedParamDialog::new(ctx, KEY, fields, move |fields| { + ParamDialog::new(KEY, tl!("New bookmarks from text styles"), params.clone()) + .ok_label(tl!("Create").into()) + .values(craft::ui::contract::Bind::bound(fields)) }); self.dialogs.open(dialog); } /// One pass over the dialog: Create makes the bookmarks and shows them in the Bookmarks panel. pub(crate) fn bookmarks_from_styles_pass(&mut self, ctx: &egui::Context, _ctx: &egui::Context) { + if let Some(dialog) = self.dialogs.get_by_id::(dialog_id(KEY)) { + let fields = dialog.fields(); + for (n, slot) in self.text_style_draft.levels.iter_mut().enumerate() { + *slot = fields.text(&level_key(n)).and_then(|id| id.parse::().ok()); + } + } let Some(result) = self.dialogs.take_by_id::(dialog_id(KEY)) else { return }; let mut draft = std::mem::take(&mut self.text_style_draft); let DialogResult::Ok(result) = result else { return }; diff --git a/crates/ui-egui/src/dialogs/pageboxes.rs b/crates/ui-egui/src/dialogs/pageboxes.rs index f23617feef..a08c0f5d07 100644 --- a/crates/ui-egui/src/dialogs/pageboxes.rs +++ b/crates/ui-egui/src/dialogs/pageboxes.rs @@ -133,6 +133,7 @@ fn params(count: usize, current: usize, media: Option<[f64; 4]>) -> Vec { } out.response.clone() }) + .full_width() .companions(MARGIN_KEYS), ); rows.push(PageRangeOptions::param("range", tl!("Pages"), count, current, PageRangeChoices::CurrentFromTo)); @@ -140,10 +141,13 @@ fn params(count: usize, current: usize, media: Option<[f64; 4]>) -> Vec { let label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &(current + 1).to_string())]); let aspect = ThumbAspect::new((media[2] - media[0]).round().clamp(1.0, 65535.0) as u16, (media[3] - media[1]).round().clamp(1.0, 65535.0) as u16); - rows.push(Param::custom("preview", "", move |ui, fields, _| { - let margins = margins_of(fields); - Picture::painter(label.clone(), aspect, move |cx, rect| paint_preview(cx, rect, media, margins)).show(ui) - })); + rows.push( + Param::custom("preview", "", move |ui, fields, _| { + let margins = margins_of(fields); + Picture::painter(label.clone(), aspect, move |cx, rect| paint_preview(cx, rect, media, margins)).show(ui) + }) + .full_width(), + ); } rows } diff --git a/crates/ui-egui/src/dialogs/properties.rs b/crates/ui-egui/src/dialogs/properties.rs index adea62b58c..37bf269d15 100644 --- a/crates/ui-egui/src/dialogs/properties.rs +++ b/crates/ui-egui/src/dialogs/properties.rs @@ -386,7 +386,9 @@ impl PdfCraftApp { // What was repaired while reading a damaged file (fidelity: never silent). let repairs = doc.repair_log(); rows.push(value("Repairs", if repairs.is_empty() { tl!("None").to_string() } else { repairs.len().to_string() })); - rows.extend(repairs.into_iter().map(|line| PropertyRow::value(tl!("Repair log").to_string(), line))); + if !repairs.is_empty() { + rows.push(PropertyRow::value(tl!("Repair log").to_string(), repairs.join("\n"))); + } rows } } diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 9cb4665df8..0da7ec5117 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -1253,6 +1253,15 @@ impl PdfCraftApp { let Some((i, id)) = self.active_ids() else { return }; let current = self.views[i].current(); let parent_of = |p: &[usize]| p[..p.len() - 1].to_vec(); + let refresh_open = matches!(action, A::FromStructure | A::Indent(_)); + let indent_parent = match &action { + A::Indent(path) if !path.is_empty() => { + let mut to_parent = parent_of(path); + to_parent.push(path[path.len() - 1].saturating_sub(1)); + Some(to_parent) + } + _ => None, + }; let edit = match action { A::New => { let n = self.session.get(id).map_or(0, |d| d.info.outline.len()); @@ -1321,7 +1330,15 @@ impl PdfCraftApp { return; } }; - self.apply_edit(ctx, edit); + if self.apply_edit(ctx, edit) && refresh_open { + if let Some(parent) = indent_parent { + if let Some(view) = self.views.get_mut(i) { + view.bookmarks_open.set(&parent, true); + } + } else if let (Some(doc), Some(view)) = (self.session.get(id), self.views.get_mut(i)) { + view.bookmarks_open = crate::panels::bookmarks::opened_as_filed(&doc.info.outline); + } + } } } diff --git a/crates/ui-egui/src/hotbar.rs b/crates/ui-egui/src/hotbar.rs index 7b9cd64e64..ad75efa09f 100644 --- a/crates/ui-egui/src/hotbar.rs +++ b/crates/ui-egui/src/hotbar.rs @@ -198,6 +198,20 @@ fn open_picker( app.open_colour_picker(crate::colour_picker::PickerHost::App, request, then); } +/// Measures the toolbar's rail at `width`, with the active tool's controls under it, so the dock gives the rail its +/// full height. +pub(crate) fn measure_rail(app: &mut PdfCraftApp, ui: &mut egui::Ui, width: f32) -> f32 { + app.hotbar.normalize(); + let toolbar = slots(app); + let current = current_tool(app); + let last_used = last_used(app); + let mut rail = ToolRail::new(tl!("Toolbar").to_string(), &toolbar, ¤t, &last_used).edit_toolbar(tl!("Edit toolbar").to_string()); + if app.hotbar.drawer_open { + rail = rail.editing(); + } + rail.measure_rail(ui, width, |ui, _footer| footer_controls(ui, app)).y +} + /// Shows the toolbar's rail in the width `ui` has left, with the active tool's controls under it, and applies what /// the user did: a drawer pick runs its command, a drawer edit changes the tool list. pub(crate) fn show_rail(app: &mut PdfCraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/panels/bookmarks.rs b/crates/ui-egui/src/panels/bookmarks.rs index 0c4714b8b9..ec4595ad73 100644 --- a/crates/ui-egui/src/panels/bookmarks.rs +++ b/crates/ui-egui/src/panels/bookmarks.rs @@ -261,15 +261,18 @@ pub(super) fn body(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult { .empty(tl!("No matches.")) .filter(&query, row_key); - let out = list.show_items(ui, &rows, &mut |_, icx| { - let Some(row) = rows.0.get(icx.at) else { return ListRow::new("") }; - let depth = row.path.len().saturating_sub(1); - let (strong, italic, color) = title_style(row.item, depth); - let mut r = ListRow::new(row.item.title.clone()).state(icx.row.clone()).strong(strong).italic(italic); + let out = list.show_items(ui, &rows, &mut |path, icx| { + let Some(item) = item_at(outline, path) else { return ListRow::new("") }; + let depth = path.len().saturating_sub(1); + let (strong, italic, color) = title_style(item, depth); + let mut r = ListRow::new(item.title.clone()).state(icx.row.clone()).depth(depth).strong(strong).italic(italic); + if !item.children.is_empty() { + r = r.group(open(path)); + } if let Some(color) = color { r = r.hue(color, HueTarget::Label); } - if let Some(page) = row.item.page.and_then(|p| info.pages.get(p)) { + if let Some(page) = item.page.and_then(|p| info.pages.get(p)) { r = r.trailing(page.label.clone()); } r diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index 57de4b388d..25ab43810f 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -33,10 +33,15 @@ pub(super) fn body(app: &mut PdfCraftApp, ui: &mut egui::Ui) -> PanelResult { let before = view.thumbnail_zoom(); let mut zoom = f64::from(before); let current = view.current(); + let reveal = (view.panel_followed != Some(current) || view.panel_zoom_followed != before).then_some(current); + view.panel_followed = Some(current); + view.panel_zoom_followed = before; let grid_id = crate::canvas::organize::pages_panel_grid_id(view); let output = PageThumbnails::new(tl!("Pages"), &source, &mut view.selected, current, DataColor::new(egui::Color32::WHITE)) .id(grid_id) .editable(editable) + .picks_beside_current(true) + .reveal(reveal) .size(&mut zoom) .show(ui); let zoom = zoom as f32; diff --git a/crates/ui-egui/src/panels/side_panels.rs b/crates/ui-egui/src/panels/side_panels.rs index d310538faa..3efef11c6f 100644 --- a/crates/ui-egui/src/panels/side_panels.rs +++ b/crates/ui-egui/src/panels/side_panels.rs @@ -330,16 +330,18 @@ impl DockPanels for Panels<'_> { } fn group_view(&mut self, panels: &[PanelId], _active: usize, ui: &mut Ui, at: GroupAt, _cx: &mut BodyCx<'_>) -> Option { - // Measuring is the dock's; a shown view takes the rect it is given. - let GroupAt::Show(rect) = at else { return None }; - if panels.contains(&PanelId::Toolbar) { - crate::hotbar::show_rail(self.app, ui); - } else if panels.contains(&PanelId::Document) { - document_view(self.app, ui, rect); - } else { - return None; + match at { + GroupAt::Measure(width) if panels.contains(&PanelId::Toolbar) => Some(crate::hotbar::measure_rail(self.app, ui, width)), + GroupAt::Show(rect) if panels.contains(&PanelId::Toolbar) => { + crate::hotbar::show_rail(self.app, ui); + Some(rect.height()) + } + GroupAt::Show(rect) if panels.contains(&PanelId::Document) => { + document_view(self.app, ui, rect); + Some(rect.height()) + } + _ => None, } - Some(rect.height()) } fn group_header(&mut self, panels: &[PanelId], active: usize, ui: &mut Ui, _cx: &mut BodyCx<'_>) { diff --git a/crates/ui-egui/src/persist/recovery.rs b/crates/ui-egui/src/persist/recovery.rs index 31be7f076a..7f697814f7 100644 --- a/crates/ui-egui/src/persist/recovery.rs +++ b/crates/ui-egui/src/persist/recovery.rs @@ -200,6 +200,11 @@ impl PdfCraftApp { } } + /// Whether a hosted dialog other than the startup recovery offer is open. + pub(crate) fn has_non_recovery_dialog(&self) -> bool { + self.dialogs.open_dialogs().len() > usize::from(self.dialogs.is_open::()) + } + /// Stops offering the first entry in this run; its copy stays for the next launch. #[cfg(not(target_arch = "wasm32"))] fn skip_offer(&mut self) { diff --git a/crates/ui-egui/src/tools/comments/tool.rs b/crates/ui-egui/src/tools/comments/tool.rs index 6c33797c81..5d6100e8f0 100644 --- a/crates/ui-egui/src/tools/comments/tool.rs +++ b/crates/ui-egui/src/tools/comments/tool.rs @@ -314,7 +314,7 @@ impl CanvasTool for CommentsTool<'_> { self.annotate.selected.clear(); return true; } - if matches!(self.quick, QuickTool::Fill(_)) { + if matches!(self.quick, QuickTool::Fill(_) | QuickTool::Select) { return self.beneath.as_mut().is_some_and(|beneath| beneath.key(key, cx)); } if matches!(self.quick, QuickTool::Comment(_)) { diff --git a/crates/ui-egui/src/tools/forms_ui/calendar.rs b/crates/ui-egui/src/tools/forms_ui/calendar.rs index 2d07f01463..d482db195d 100644 --- a/crates/ui-egui/src/tools/forms_ui/calendar.rs +++ b/crates/ui-egui/src/tools/forms_ui/calendar.rs @@ -1,8 +1,10 @@ //! A date field's calendar under the field, as the framework's `CalendarPopover`. -use craft::ui::contract::{Bind, ShowContainer as _, overlay::Anchor}; +use craft::ui::contract::overlay::{Anchor, Dismiss}; +use craft::ui::contract::{Bind, ShowContainer as _}; // PLAN: assumed `craft::ui::pickers` re-exports `CalendarPopover`, `DatePrecision` and `PickedDate`. use craft::ui::pickers::{CalendarPopover, DatePrecision, PickedDate}; +use craft::ui::runtime::focus::{FocusPolicy, Initial}; use egui::Rect; use pdfcraft_engine::form_scripts::{DateTime, format_date, parse_date}; @@ -20,7 +22,12 @@ pub(super) fn calendar(ui: &mut egui::Ui, rect: Rect, text: &str, fmt: &str, ope let mut picked = before.clone(); CalendarPopover::new("Calendar", Bind::bound(&mut *open), Bind::bound(&mut picked)) .precisions(&[DatePrecision::Day]) - .overlay(|overlay| overlay.anchor(Anchor::Rect(rect))) + .overlay(|overlay| { + overlay + .anchor(Anchor::Rect(rect)) + .focus(FocusPolicy::POPUP.trap(false).restore(false).initial(Initial::KeepAnchor)) + .dismiss(Dismiss::new().focus_left(false)) + }) .show(ui, |_, _| {}); if picked == before { return None; diff --git a/crates/ui-egui/src/tools/measure_ui.rs b/crates/ui-egui/src/tools/measure_ui.rs index 9c7f0d7448..266d72f5f3 100644 --- a/crates/ui-egui/src/tools/measure_ui.rs +++ b/crates/ui-egui/src/tools/measure_ui.rs @@ -14,7 +14,7 @@ use craft::ui::{ form::SliderField, list::{List, ListRow}, notices::Notice, - pickers::{ComboBox, UnitSelect}, + pickers::{Select, UnitSelect}, primitives::{Draw, PaintShape, StrokeWidth, TextRun, glyph}, runtime::env::UnitKind, text::{NumberField, TextField}, @@ -656,7 +656,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { let mut chosen = None; let fields = scale_fields(state); let before = state.ratio_text.clone(); - let typed = TextField::new(tl!("Scale"), Bind::bound(&mut state.ratio_text)).show(ui); + let typed = TextField::new(tl!("Scale"), Bind::bound(&mut state.ratio_text)).submits().show(ui); state.ratio_dirty |= state.ratio_text != before; if (typed.submitted || typed.response.lost_focus()) && std::mem::take(&mut state.ratio_dirty) { match parse_ratio(&state.ratio_text) { @@ -665,7 +665,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { } } let ratios: Vec> = RATIOS.iter().map(|&n| Entry::new(format_ratio(n), format_ratio(n))).collect(); - let common = ComboBox::new(tl!("Common scales"), Bind::given(state.ratio_text.clone()), &ratios).show(ui); + let common = Select::new(tl!("Common scales"), Bind::given(state.ratio_text.clone()), &ratios).show(ui); if let Some(text) = common.value() && let Some(n) = parse_ratio(text) && *text != state.ratio_text diff --git a/crates/ui-egui/src/tools/prepare.rs b/crates/ui-egui/src/tools/prepare.rs index 232b7969db..6125cbf14c 100644 --- a/crates/ui-egui/src/tools/prepare.rs +++ b/crates/ui-egui/src/tools/prepare.rs @@ -139,7 +139,7 @@ enum Gesture { /// size with its top-left there). Draw { drag: PageBoxDrag, origin: Pos2 }, /// Selecting fields inside a dragged rectangle. - Marquee(MarqueeSelect<(String, usize)>), + Marquee { marquee: MarqueeSelect<(String, usize)>, dragged: bool }, /// Moving a field; the gesture runs in screen points. Move { page: usize, gesture: MoveGesture, widget: (String, usize) }, } @@ -153,6 +153,8 @@ pub(crate) struct PrepareOutcome { pub placed: bool, /// A table of text fields was drawn: open its window for this page and area (view space). pub table: Option<(usize, [f64; 4])>, + /// An edit produced by the tool (adding, moving, nudging or deleting fields). + pub edit: Option, } #[derive(Clone, Debug, Default, PartialEq)] @@ -387,9 +389,13 @@ pub fn arrange(form: &[FormField], anchor: &(String, usize), others: &[(String, /// or one copy of a duplicated field, deletes only that one, as in Acrobat (#4609); a field's /// last widget takes the field with it. pub(crate) fn delete_selected(session: &mut PageSession) -> Option { - let first = session.prepare.selected.take()?; + delete_selected_from(&mut session.prepare) +} + +pub(crate) fn delete_selected_from(prepare: &mut PrepareView) -> Option { + let first = prepare.selected.take()?; let mut picked = vec![first]; - for w in std::mem::take(&mut session.prepare.also) { + for w in std::mem::take(&mut prepare.also) { if !picked.contains(&w) { picked.push(w); } diff --git a/crates/ui-egui/src/tools/prepare/tool.rs b/crates/ui-egui/src/tools/prepare/tool.rs index a0d420c696..c819eac365 100644 --- a/crates/ui-egui/src/tools/prepare/tool.rs +++ b/crates/ui-egui/src/tools/prepare/tool.rs @@ -17,7 +17,7 @@ use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2, vec2}; use pdfcraft_engine::{Edit, FieldProps, FormField}; use pdfcraft_render::DocInfo; -use super::{FieldTool, Gesture, PrepareView, delete_selected, place_tab_badge, screen_rect, table_rect, to_user, user_rect}; +use super::{FieldTool, Gesture, PrepareView, delete_selected_from, place_tab_badge, screen_rect, table_rect, to_user, user_rect}; use crate::canvas::page_parts::{Owner, PageLayer, PagePart, PagePress}; use crate::canvas::{PageBoxDrag, PageSession, PageXform}; @@ -114,7 +114,8 @@ pub(crate) struct PrepareTool<'a> { tool: Option, allowed: bool, form: &'a [FormField], - session: &'a mut PageSession, + prepare: &'a mut PrepareView, + placed: &'a [PlacedPage], info: &'a DocInfo, /// The transforms of the pages placed this pass. xforms: &'a [(usize, PageXform)], @@ -127,11 +128,22 @@ impl<'a> PrepareTool<'a> { tool: Option, allowed: bool, form: &'a [FormField], - session: &'a mut PageSession, + prepare: &'a mut PrepareView, + placed: &'a [PlacedPage], info: &'a DocInfo, xforms: &'a [(usize, PageXform)], ) -> Self { - Self { tool, allowed, form, session, info, xforms } + Self { tool, allowed, form, prepare, placed, info, xforms } + } + + /// Whether a pointer gesture is currently active in Prepare. + pub(crate) fn has_gesture(&self) -> bool { + !matches!(self.prepare.gesture, Gesture::Idle) + } + + /// Whether the active gesture is a marquee press that has not dragged past click distance. + pub(crate) fn is_click_marquee(&self) -> bool { + matches!(self.prepare.gesture, Gesture::Marquee { dragged: false, .. }) } /// Every widget key and screen rect on every shown page. @@ -155,8 +167,8 @@ impl<'a> PrepareTool<'a> { let click = rect.width() < CLICK_SIZE || rect.height() < CLICK_SIZE; if tool == FieldTool::TextTable { let area = if click { Rect::from_min_size(origin, Vec2::ZERO) } else { rect }; - self.session.prepare.outcome.table = Some((page, table_rect(&xf, area))); - self.session.prepare.outcome.placed = true; + self.prepare.outcome.table = Some((page, table_rect(&xf, area))); + self.prepare.outcome.placed = true; return; } let user = if click { @@ -167,11 +179,11 @@ impl<'a> PrepareTool<'a> { } else { user_rect(&xf, self.info, page, rect) }; - let join = self.session.prepare.selected.as_ref().and_then(|(n, _)| self.form.iter().find(|f| &f.name == n)); + let join = self.prepare.selected.as_ref().and_then(|(n, _)| self.form.iter().find(|f| &f.name == n)); let kind = tool.new_field(join); - self.session.prepare.select_added = Some(self.form.len()); - self.session.pending_edit = Some(Edit::AddField { page, rect: user, kind, name: None }); - self.session.prepare.outcome.placed = true; + self.prepare.select_added = Some(self.form.len()); + self.prepare.outcome.edit = Some(Edit::AddField { page, rect: user, kind, name: None }); + self.prepare.outcome.placed = true; } fn finish_move(&mut self, page: usize, offset: craft::behavior::kurbo::Vec2, widget: (String, usize)) { @@ -184,13 +196,13 @@ impl<'a> PrepareTool<'a> { let moved = rect.translate(vec2(offset.x as f32, offset.y as f32)); let user = user_rect(&xf, self.info, page, moved); let (name, wi) = widget; - self.session.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) }); + self.prepare.outcome.edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) }); } /// An arrow moves the selected field a point the way it points on screen, Shift and an arrow ten points, whatever /// the zoom; one press is one edit. Whether there was a field to move. fn nudge(&mut self, direction: Vec2, shift: bool) -> bool { - let Some(key) = self.session.prepare.selected.clone() else { return false }; + let Some(key) = self.prepare.selected.clone() else { return false }; let Some((page, rect)) = widget_rect(self.xforms, self.info, self.form, &key) else { return false }; let Some(xf) = transform_of(self.xforms, page) else { return false }; // Screen points per page point: the page's width on screen over its width as turned. @@ -199,15 +211,15 @@ impl<'a> PrepareTool<'a> { let step = if shift { 10.0 } else { 1.0 }; let user = user_rect(&xf, self.info, page, rect.translate(direction * step * zoom)); let (name, wi) = key; - self.session.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) }); + self.prepare.outcome.edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, user)), ..Default::default() }) }); true } fn finish_marquee(&mut self, marquee: MarqueeSelect<(String, usize)>) { let hits = self.all_widgets().into_iter().filter(|(_, r)| r.intersects(marquee.rect())).collect::>(); let mut items = marquee.selection(hits).into_iter(); - self.session.prepare.selected = items.next(); - self.session.prepare.also = items.collect(); + self.prepare.selected = items.next(); + self.prepare.also = items.collect(); } } @@ -216,33 +228,36 @@ impl CanvasTool for PrepareTool<'_> { if !self.allowed || pointer.button != PointerButton::Primary { return ToolAction::Ignored; } - let Some(placed) = self.session.placed.iter().find(|p| p.rect.contains(pointer.pos)).cloned() else { return ToolAction::Ignored }; + let Some(placed) = self.placed.iter().find(|p| p.rect.contains(pointer.pos)).cloned() else { return ToolAction::Ignored }; if self.tool.is_some() { let mut drag = PageBoxDrag::default(); drag.press(&placed, pointer.pos); - self.session.prepare.gesture = Gesture::Draw { drag, origin: pointer.pos }; + self.prepare.gesture = Gesture::Draw { drag, origin: pointer.pos }; return ToolAction::Claimed; } // A drag that began on a field part moves the field the part's press selected. - let on_selected = self.session.prepare.selected.clone().filter(|key| { + let on_selected = self.prepare.selected.clone().filter(|key| { widget_rect(self.xforms, self.info, self.form, key).is_some_and(|(page, r)| page == placed.page && r.contains(pointer.pos)) }); if let Some(widget) = on_selected { let slop = f64::from(cx.slop); let gesture = MoveGesture::press(&ConstrainStyle::new(slop, slop), point(pointer.pos), pointer.mods, Directions::Four); - self.session.prepare.gesture = Gesture::Move { page: placed.page, gesture, widget }; + self.prepare.gesture = Gesture::Move { page: placed.page, gesture, widget }; return ToolAction::Claimed; } let extend = pointer.mods.shift || pointer.mods.cmd; - let base = if extend { self.session.prepare.selected.iter().chain(self.session.prepare.also.iter()).cloned().collect() } else { Vec::new() }; - self.session.prepare.gesture = Gesture::Marquee(MarqueeSelect::begin(pointer.pos, pointer.mods, base)); + let base = if extend { self.prepare.selected.iter().chain(self.prepare.also.iter()).cloned().collect() } else { Vec::new() }; + self.prepare.gesture = Gesture::Marquee { marquee: MarqueeSelect::begin(pointer.pos, pointer.mods, base), dragged: false }; ToolAction::Claimed } fn drag(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) { - match &mut self.session.prepare.gesture { + match &mut self.prepare.gesture { Gesture::Draw { drag, .. } => drag.drag(pointer.pos), - Gesture::Marquee(marquee) => marquee.update(pointer.pos), + Gesture::Marquee { marquee, dragged } => { + *dragged = true; + marquee.update(pointer.pos); + } Gesture::Move { gesture, .. } => { gesture.follow(point(pointer.pos), pointer.mods, 1.0); } @@ -251,13 +266,13 @@ impl CanvasTool for PrepareTool<'_> { } fn release(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) { - match std::mem::take(&mut self.session.prepare.gesture) { + match std::mem::take(&mut self.prepare.gesture) { Gesture::Idle => {} Gesture::Draw { mut drag, origin } => { drag.drag(pointer.pos); self.finish_draw(drag, origin); } - Gesture::Marquee(mut marquee) => { + Gesture::Marquee { mut marquee, .. } => { marquee.update(pointer.pos); self.finish_marquee(marquee); } @@ -269,27 +284,27 @@ impl CanvasTool for PrepareTool<'_> { } fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) { - if let Gesture::Marquee(marquee) = std::mem::take(&mut self.session.prepare.gesture) { + if let Gesture::Marquee { marquee, .. } = std::mem::take(&mut self.prepare.gesture) { let mut before = marquee.cancel().into_iter(); - self.session.prepare.selected = before.next(); - self.session.prepare.also = before.collect(); + self.prepare.selected = before.next(); + self.prepare.also = before.collect(); } } fn claims(&self) -> ToolClaims { - if self.session.prepare.selected.is_some() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE } + if self.prepare.selected.is_some() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE } } fn key(&mut self, key: &ToolKey, _cx: &mut ToolContext<'_>) -> bool { match key { - ToolKey::Delete { .. } if self.session.prepare.selected.is_some() => { - self.session.pending_edit = delete_selected(self.session); + ToolKey::Delete { .. } if self.prepare.selected.is_some() => { + self.prepare.outcome.edit = delete_selected_from(self.prepare); true } ToolKey::Nudge { direction, mods, .. } => self.nudge(vec2(direction.x as f32, direction.y as f32), mods.shift), - ToolKey::Cancel if self.session.prepare.selected.is_some() => { - self.session.prepare.selected = None; - self.session.prepare.also.clear(); + ToolKey::Cancel if self.prepare.selected.is_some() => { + self.prepare.selected = None; + self.prepare.also.clear(); true } _ => false, @@ -297,9 +312,9 @@ impl CanvasTool for PrepareTool<'_> { } fn paint(&self, _draw: &Draw<'_>, cx: &ToolContext<'_>) { - match &self.session.prepare.gesture { + match &self.prepare.gesture { Gesture::Draw { drag, .. } => drag.paint(cx), - Gesture::Marquee(marquee) => { + Gesture::Marquee { marquee, .. } => { let r = marquee.rect(); cx.marching_ants(&[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()], true); } @@ -319,8 +334,16 @@ impl CanvasTool for PrepareTool<'_> { /// The corner handles of the anchor field, as a Free Transform box that only resizes: no rotating, /// skewing or distorting, and a press inside is the field part's. A corner drag's `Commit` and an /// arrow nudge's `Set` each become one field edit; Escape with no drag clears the selection. -// PLAN: the box's state is in the canvas's document space; assumed that is screen space on the page body (pdf-canvas-w8). -pub(crate) fn selection_box(ui: &mut Ui, session: &mut PageSession, form: &[FormField], info: &DocInfo, xforms: &[(usize, PageXform)], page: usize) { +pub(crate) fn selection_box( + ui: &mut Ui, + body: Rect, + view: craft::behavior::CanvasView, + session: &mut PageSession, + form: &[FormField], + info: &DocInfo, + xforms: &[(usize, PageXform)], + page: usize, +) { let Some(key) = session.prepare.selected.clone() else { return }; let Some((widget_page, rect)) = widget_rect(xforms, info, form, &key) else { return }; if widget_page != page { @@ -331,12 +354,12 @@ pub(crate) fn selection_box(ui: &mut Ui, session: &mut PageSession, form: &[Form .with_scale(ScaleRule::Free) .with_allow(BoxAllow::new(false, false, false).with_warp(false)) .with_handles(BoxHandles::Corners); - let start = kurbo_rect(rect); + let start = KRect::from_points(view.to_doc(rect.min), view.to_doc(rect.max)); let shown = TransformBox::new("Field", Bind::given(BoxState::from_rect(start)), start, 0.0) .rules(rules) .reference_point(false) .inside_moves(false) - .show_at(ui, xf.rect); + .show_at(ui, body); let mut edit = None; for event in &shown.edit.events { let state = match event { @@ -344,12 +367,8 @@ pub(crate) fn selection_box(ui: &mut Ui, session: &mut PageSession, form: &[Form EditEvent::Set { after, .. } => after, _ => continue, }; - let (mut lo, mut hi) = (state.quad[0], state.quad[0]); - for p in state.quad { - lo = Point::new(lo.x.min(p.x), lo.y.min(p.y)); - hi = Point::new(hi.x.max(p.x), hi.y.max(p.y)); - } - let screen = Rect::from_min_max(Pos2::new(lo.x as f32, lo.y as f32), Pos2::new(hi.x as f32, hi.y as f32)); + let corners = state.quad.map(|p| view.to_screen(p)); + let screen = Rect::from_points(&corners); edit = Some(user_rect(&xf, info, page, screen)); } if let Some(user) = edit { @@ -366,6 +385,7 @@ pub(crate) fn selection_box(ui: &mut Ui, session: &mut PageSession, form: &[Form pub(crate) fn show_overlays( ui: &mut Ui, body: Rect, + view: craft::behavior::CanvasView, session: &mut PageSession, form: &[FormField], info: &DocInfo, @@ -378,7 +398,7 @@ pub(crate) fn show_overlays( if let Some(overlay) = PrepareOverlay::new(form, &tab_order, session, info, &xforms, page) { overlay.show_at(ui, body); } - selection_box(ui, session, form, info, &xforms, page); + selection_box(ui, body, view, session, form, info, &xforms, page); } } @@ -487,7 +507,7 @@ impl Component for PrepareOverlay { selected: cx.color(colors.accent.solid), tag: cx.color(colors.text.normal), tag_text: cx.color(colors.surface.sunken), - selected_tag: cx.color(colors.accent.strong), + selected_tag: cx.color(colors.accent.solid), selected_tag_text: cx.color(colors.text.on_strong), badge: cx.color(colors.accent.solid), } diff --git a/crates/ui-egui/src/workflows/optimize_ui.rs b/crates/ui-egui/src/workflows/optimize_ui.rs index 2c7b5d5951..55d123f8c5 100644 --- a/crates/ui-egui/src/workflows/optimize_ui.rs +++ b/crates/ui-egui/src/workflows/optimize_ui.rs @@ -734,10 +734,8 @@ impl PdfCraftApp { /// Stop a running optimization: its result is discarded and nothing is saved. pub fn cancel_optimize(&mut self) { - let Some(run) = self.optimize_run.take() else { return }; - self.optimize_jobs.reprioritize(|key, priority| (*key != run.doc).then_some(priority)); - notices::end_progress(self, ProgressKey::Optimize); - self.notify_tr("Optimization cancelled"); + let Some(run) = &self.optimize_run else { return }; + run.progress.cancel(); } /// Show progress; save the copy once the job is done. diff --git a/crates/ui-egui/tests/it/bookmarks.rs b/crates/ui-egui/tests/it/bookmarks.rs index 9441d763b6..6fe6a5a0d4 100644 --- a/crates/ui-egui/tests/it/bookmarks.rs +++ b/crates/ui-egui/tests/it/bookmarks.rs @@ -134,7 +134,7 @@ fn search_finds_collapsed_bookmarks_and_keeps_original_paths() { h.state_mut().apply_edit(&ctx_h, Edit::AddBookmark { parent, index, title: title.into(), page, left: None, top: None }); } h.run_steps(3); - h.get_by_label("Panel Menu").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Panel Menu").click(); h.run_steps(2); h.get_by_label("Collapse all bookmarks").click(); h.run_steps(3); @@ -210,7 +210,7 @@ trailer << /Root 1 0 R >> let ctx_h = h.ctx.clone(); h.state_mut().open_bytes(&ctx_h, "tagged.pdf", None, TAGGED.to_vec()).unwrap(); h.run_steps(3); - h.get_by_label("Panel Menu").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Panel Menu").click(); h.run_steps(2); h.get_by_label("New bookmarks from structure").click(); h.run_steps(3); @@ -267,7 +267,7 @@ fn new_bookmarks_from_text_styles_from_the_bookmark_options() { h.run_steps(3); let id = h.state().active.and_then(|i| h.state().views.get(i)).unwrap().id; let open = |h: &mut Harness<'static, PdfCraftApp>| { - h.get_by_label("Panel Menu").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Panel Menu").click(); h.run_steps(2); h.get_by_label("New bookmarks from text styles…").click(); h.run_steps(3); @@ -330,17 +330,17 @@ fn expanding_and_collapsing_all_bookmarks() { } h.run_steps(3); let shown = |h: &Harness<'static, PdfCraftApp>, t: &str| h.query_by_label(t).is_some(); - h.get_by_label("Panel Menu").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Panel Menu").click(); h.run_steps(2); h.get_by_label("Expand all bookmarks").click(); h.run_steps(3); assert!(shown(&h, "Chapter") && shown(&h, "Section")); - h.get_by_label("Panel Menu").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Panel Menu").click(); h.run_steps(2); h.get_by_label("Collapse all bookmarks").click(); h.run_steps(3); assert!(shown(&h, "Part") && !shown(&h, "Chapter")); - h.get_by_label("Panel Menu").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Panel Menu").click(); h.run_steps(2); h.get_by_label("Expand top-level bookmarks").click(); h.run_steps(3); @@ -415,12 +415,9 @@ trailer << /Root 1 0 R >> // The disclosure triangle at the row's left still opens and closes it. let toggle = |h: &mut Harness<'static, PdfCraftApp>, title: &str| { - let row = h.get_by_label(title).rect(); - let at = egui::pos2(row.left() + 8.0, row.top() + 14.0); - h.hover_at(at); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + let expand = format!("Expand {title}"); + let collapse = format!("Collapse {title}"); + h.get_by(|n| n.role() == egui::accesskit::Role::Button && n.label().is_some_and(|l| l == expand || l == collapse)).click(); h.run_steps(3); }; toggle(&mut h, "Closed parent"); @@ -501,7 +498,7 @@ fn cut_copy_and_paste_a_bookmark_subtree_within_and_between_documents() { let ctx_h = h.ctx.clone(); h.state_mut().open_bytes(&ctx_h, "one.pdf", None, ONE_PAGE.to_vec()).unwrap(); h.run_steps(3); - h.get_by_label("Panel Menu").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Panel Menu").click(); h.run_steps(2); h.get_by_label("Paste bookmarks").click(); h.run_steps(3); diff --git a/crates/ui-egui/tests/it/comment_pin.rs b/crates/ui-egui/tests/it/comment_pin.rs index 51fdea1eb7..19217464e8 100644 --- a/crates/ui-egui/tests/it/comment_pin.rs +++ b/crates/ui-egui/tests/it/comment_pin.rs @@ -1,7 +1,10 @@ //! The annotation quick bar's pin is a preference that survives a restart. use egui::{Pos2, pos2}; -use egui_kittest::{Harness, kittest::Queryable}; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; use pdfcraft_ui_egui::settings::PdfCraftSettings; use pdfcraft_ui_egui::{PdfCraftApp, QuickTool, comments::CommentTool}; @@ -83,15 +86,24 @@ fn pin_from_quick_bar_survives_restart_and_unpinning() { let mut h = harness(Some(saved)); assert!(h.state().comment_prefs.pinned, "the pin survives a fresh shell"); - h.get_by_label("Keep tool selected: on"); + assert_eq!( + h.get_by_role_and_label(egui::accesskit::Role::Button, "Keep tool selected").accesskit_node().toggled(), + Some(egui::accesskit::Toggled::True), + "the restored pin button is toggled on" + ); shot(&mut h, "pin-restored.png"); callout(&mut h, 140.0); crate::support::wait_until(&mut h, "the pinned callout", |app| app.session.get(app.views[0].id).unwrap().info.annotations.len() == 1); assert!(matches!(h.state().quick_tool, QuickTool::Comment(CommentTool::Callout)), "the restored pin keeps the tool selected after use"); - h.get_by_label("Keep tool selected: on").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Keep tool selected").click(); h.run_steps(3); assert!(!h.state().comment_prefs.pinned); + assert_eq!( + h.get_by_role_and_label(egui::accesskit::Role::Button, "Keep tool selected").accesskit_node().toggled(), + None, + "unpinning toggles the pin button off" + ); shot(&mut h, "pin-disabled.png"); let saved = h.state().settings_snapshot(); callout(&mut h, 60.0); diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index bccc405b71..3d8b5b025a 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -313,7 +313,9 @@ fn control_button_focus_preserves_document_undo_redo_shortcuts() { let (mut h, c) = harness_pages(2); ok(&mut h, &c, "ui.focus", json!({"label": "Convert"})); ok(&mut h, &c, "ui.key", json!({"key": "Enter"})); - ok(&mut h, &c, "ui.click", json!({"label": "All tools"})); + let tabs = ok(&mut h, &c, "ui.inspect", json!({"query": "All tools", "role": "Tab"})); + let id = tabs["widgets"][0]["id"].as_str().expect("the All tools mode tab"); + ok(&mut h, &c, "ui.click", json!({"id": id})); assert!(h.ctx.egui_wants_keyboard_input()); assert!(!h.ctx.text_edit_focused()); ok(&mut h, &c, "ui.command", json!({"id": "page.insert_blank"})); @@ -655,8 +657,7 @@ fn autoscroll_uses_the_initial_click_position_when_input_arrives_in_one_frame() fn autoscroll_uses_elapsed_frame_time_and_preserves_fractional_motion_in_both_views() { for (organize, scale, zoom) in [(false, 1.0, "100"), (false, 2.0, "100"), (false, 1.0, "400"), (true, 1.0, "100"), (true, 2.0, "100")] { for frames in [30, 60, 120, 144] { - let (mut h, c) = harness_pages(40); - h.set_pixels_per_point(scale); + let (mut h, c) = harness_pages_at(40, 1400.0, scale); h.set_option("zoom", zoom).unwrap(); h.state_mut().views[0].organize = organize; h.run_steps(3); @@ -745,9 +746,11 @@ fn autoscroll_cancels_on_click_wheel_focus_loss_and_pointer_exit() { assert!(!h.state().views[0].auto_scrolling()); start_autoscroll(&mut h, &c); h.input_mut().focused = false; + h.event(egui::Event::WindowFocused(false)); h.run_steps(2); assert!(!h.state().views[0].auto_scrolling()); h.input_mut().focused = true; + h.event(egui::Event::WindowFocused(true)); h.run_steps(2); start_autoscroll(&mut h, &c); h.event(egui::Event::PointerGone); @@ -1144,6 +1147,8 @@ fn commands_keys_and_typing() { ok(&mut h, &c, "ui.type", json!({ "text": "split" })); let hits = ok(&mut h, &c, "ui.inspect", json!({ "query": "split document" })); assert!(hits["count"].as_u64().unwrap() >= 1, "{hits}"); + // First Escape clears the query; second closes the palette. + ok(&mut h, &c, "ui.key", json!({ "key": "Escape" })); ok(&mut h, &c, "ui.key", json!({ "key": "Escape" })); h.run_steps(2); assert!(!palette_on_screen(&h), "Escape closes the palette"); @@ -1380,7 +1385,7 @@ fn a_plan_scale_picked_or_typed_applies_at_once() { (measure::reading(Kind::Distance, &line, &scale).unwrap().label, scale.ratio) }; // Picked from the common scales: no Apply click. - h.get_by(|n| n.role() == egui::accesskit::Role::ComboBox && n.value().is_some_and(|v| v == "Common scales")).click(); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Common scales").click(); h.run_steps(2); h.get_by_label("1:200").click_accesskit(); h.run_steps(3); @@ -1783,8 +1788,12 @@ fn page_size_shows_while_the_pointer_is_in_the_bottom_left_quadrant() { let (mut h, _c) = harness(); let area = h.state().views[0].viewport_rect(); let shown = |h: &Harness<'static, PdfCraftApp>| { - let layer = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("page-size-hint")); - h.ctx.memory(|m| m.areas().visible_last_frame(&layer)) + let size = { + let s = h.state(); + let p = &s.session.get(s.views[0].id).unwrap().info.pages[0]; + s.units.size(f64::from(p.width), f64::from(p.height)) + }; + h.query_by_label(&size).is_some() }; let away = area.center() + egui::vec2(300.0, -200.0); h.event(egui::Event::PointerMoved(away)); @@ -1828,6 +1837,9 @@ fn navigation_history_for_os(os: egui::os::OperatingSystem) { // The real rail button is accessible and invokes the same history, not the adjacent page. // The toolbar names its slots by their commands (L-233). ok(&mut h, &c, "ui.click", json!({"label": "Previous view"})); + // `IconButton::command` queues `view.previous_view` on the command board during the click's pass; + // the app drains fired commands in the next frame's `prepare_raw_input`. + h.step(); assert_eq!(h.state().views[0].current(), 0); assert!(enabled(ok(&mut h, &c, "ui.commands", json!({})), "view.next_view")); ok(&mut h, &c, "ui.command", json!({"id": "view.next_view"})); diff --git a/crates/ui-egui/tests/it/pageboxes.rs b/crates/ui-egui/tests/it/pageboxes.rs index d9ea3f7546..97551fe583 100644 --- a/crates/ui-egui/tests/it/pageboxes.rs +++ b/crates/ui-egui/tests/it/pageboxes.rs @@ -90,6 +90,7 @@ fn set_page_boxes_dialog_applies_margins_to_the_chosen_pages() { for side in ["Top", "Bottom", "Left", "Right"] { h.get_by_label(side).click(); h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); h.get_by_label(side).type_text("1"); h.key_press(egui::Key::Tab); h.run_steps(2); diff --git a/crates/ui-egui/tests/it/prepare.rs b/crates/ui-egui/tests/it/prepare.rs index 3c84c70381..0f1ab896a9 100644 --- a/crates/ui-egui/tests/it/prepare.rs +++ b/crates/ui-egui/tests/it/prepare.rs @@ -226,13 +226,13 @@ fn shift_selected_small_widgets_have_blue_tags_and_visible_outlines() { } assert!(outline(unselected, ink).is_none(), "unselected text field has no selection outline"); // The anchor, the first one picked, shows a box of corner handles only. - let handles: Vec = shapes - .iter() - .filter_map(|s| match &s.shape { - Shape::Circle(c) if c.stroke.color == ink => Some(c.center), - _ => None, - }) + let handles: Vec = ["Top left corner", "Top right corner", "Bottom right corner", "Bottom left corner"] + .into_iter() + .map(|label| h.get_by_role_and_label(Role::Button, label).rect().center()) .collect(); + for edge in ["Top edge", "Right edge", "Bottom edge", "Left edge"] { + assert!(h.query_by_role_and_label(Role::Button, edge).is_none(), "no edge handle {edge}"); + } assert_eq!(handles.len(), 4, "only the primary has resize handles, at its corners"); let distinct = |value: fn(&Pos2) -> f32| { let mut v: Vec = handles.iter().map(|p| value(p).round() as i32).collect(); @@ -241,6 +241,8 @@ fn shift_selected_small_widgets_have_blue_tags_and_visible_outlines() { v.len() }; assert_eq!((distinct(|p| p.x), distinct(|p| p.y)), (2, 2), "four corners of one box: {handles:?}"); + let box_rect = egui::Rect::from_points(&handles); + assert!(box_rect.contains(first) && !box_rect.contains(second), "handles surround only the primary: {box_rect:?}"); } #[test] @@ -1078,6 +1080,7 @@ fn deleting_several_selected_fields_and_detecting_fields_from_the_panel() { p.selected = Some(("a".into(), 0)); p.also = vec![("b".into(), 0), ("c".into(), 0)]; } + h.run_steps(1); h.key_press(egui::Key::Delete); h.run_steps(3); let left = names(&h); @@ -1373,16 +1376,16 @@ fn a_text_field_table_is_drawn_set_up_and_added_in_one_step() { assert_eq!(h.state().quick_tool, QuickTool::Select, "back to Select once the area is drawn"); // The table starts with four rows and one column: two rows fewer and one column more, by the // number fields' arrows. - let step = |h: &mut Harness<'static, PdfCraftApp>, field: usize, key: egui::Key, times: usize| { - h.query_all(by().role(Role::SpinButton)).nth(field).expect("the table's number field").focus(); + let step = |h: &mut Harness<'static, PdfCraftApp>, label: &str, key: egui::Key, times: usize| { + h.get_by_role_and_label(Role::SpinButton, label).focus(); h.run_steps(1); for _ in 0..times { h.key_press(key); h.run_steps(2); } }; - step(&mut h, 0, egui::Key::ArrowDown, 2); - step(&mut h, 1, egui::Key::ArrowUp, 1); + step(&mut h, "Rows", egui::Key::ArrowDown, 2); + step(&mut h, "Columns", egui::Key::ArrowUp, 1); retype(&mut h, "Column 1", "desc_N"); retype(&mut h, "Column 2", "price_N"); assert_eq!(table(&h)["rows"], 2); @@ -1438,7 +1441,7 @@ fn enter_in_a_number_field_does_not_add_the_table() { let mut h = harness(); let before = names(&h).len(); draw_table(&mut h); - h.query_all(by().role(Role::SpinButton)).next().expect("the Rows field").focus(); + h.get_by_role_and_label(Role::SpinButton, "Rows").focus(); h.run_steps(2); h.key_press(egui::Key::Backspace); h.event(egui::Event::Text("6".into())); @@ -1803,6 +1806,7 @@ fn deleting_two_radio_buttons_of_a_group_at_once() { p.selected = Some(("shirt".into(), 0)); p.also = vec![("shirt".into(), 2)]; } + h.run_steps(1); h.key_press(egui::Key::Delete); h.run_steps(3); assert_eq!(buttons(&h), (vec!["M".into()], vec![]), "M is left, and nothing is chosen"); @@ -1811,6 +1815,7 @@ fn deleting_two_radio_buttons_of_a_group_at_once() { let p = &mut h.state_mut().views[0].session.prepare; p.selected = Some(("shirt".into(), 0)); } + h.run_steps(1); h.key_press(egui::Key::Delete); h.run_steps(3); assert!(!names(&h).iter().any(|n| n == "shirt")); @@ -1867,7 +1872,10 @@ fn fields_sharing_a_name_each_show_their_own_formula() { for (row, formula) in [(0, "= sum(src)"), (1, "= sum(x)")] { h.query_all_by(|node| node.label().is_some_and(|label| label == "dup" || label.starts_with("dup: "))).nth(row).expect("a dup row").hover(); h.run_steps(30); - assert!(h.query_by_label_contains(formula).is_some(), "dup row {row} shows {formula}"); + assert!( + h.query_by(|node| node.role() == Role::Tooltip && node.label().is_some_and(|label| label.contains(formula))).is_some(), + "dup row {row} shows {formula}" + ); } } diff --git a/crates/ui-egui/tests/it/reading_colors.rs b/crates/ui-egui/tests/it/reading_colors.rs index 819440cb03..520949e570 100644 --- a/crates/ui-egui/tests/it/reading_colors.rs +++ b/crates/ui-egui/tests/it/reading_colors.rs @@ -25,7 +25,7 @@ fn pending_pages_use_document_reading_background() { (ReadingColors::GREEN_ON_BLACK, Color32::BLACK), (custom, Color32::from_rgb(0x18, 0x24, 0x30)), ] { - let mut app = crate::control::new_app(); + let (mut app, _jobs) = crate::control::app_with_manual_jobs(); app.set_option(&egui::Context::default(), "language", "en").unwrap(); app.open_bytes(&egui::Context::default(), "pending.pdf", None, crate::support::fixtures::pdf_pages(3)).unwrap(); let id = app.views[0].id; @@ -38,20 +38,33 @@ fn pending_pages_use_document_reading_background() { app.views[0].go_to_page(page); // Draw the real canvas without finishing the render frame, so no texture can // race the assertion or hide the pending-page background. + let mut raw = RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 600.0))), ..Default::default() }; + ::raw_input_hook(&mut app, &ctx, &mut raw); let mut textures = usize::MAX; - let mut output = - ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 600.0))), ..Default::default() }, |ui| { - let rect = ui.max_rect(); - textures = pdfcraft_ui_egui::canvas::document_area_at(&mut app, 0, rect, ui).expect("the page view runs").textures.entries; - }); + let mut output = ctx.run_ui(raw, |ui| { + let rect = ui.max_rect(); + textures = pdfcraft_ui_egui::canvas::document_area_at(&mut app, 0, rect, ui).expect("the page view runs").textures.entries; + }); output.textures_delta.clear(); let view = &app.views[0]; assert_eq!(textures, 0, "the page must still be waiting for its picture"); let rect = view.page_screen_rect(page).expect("target page visible"); - let fill = output.shapes.iter().find_map(|s| match &s.shape { - Shape::Rect(r) if r.rect == rect && r.stroke.width == 0.0 => Some(r.fill), - _ => None, - }); + fn find_fill(shape: &Shape, rect: Rect) -> Option { + match shape { + Shape::Rect(r) if r.rect == rect && r.stroke.width == 0.0 => Some(r.fill), + Shape::Mesh(mesh) if !mesh.vertices.is_empty() => { + let bounds = mesh.calc_bounds(); + let matches = (bounds.min.x - rect.min.x).abs() <= 2.0 + && (bounds.min.y - rect.min.y).abs() <= 2.0 + && (bounds.max.x - rect.max.x).abs() <= 2.0 + && (bounds.max.y - rect.max.y).abs() <= 2.0; + matches.then(|| mesh.vertices.iter().find(|v| v.color.a() == 255).map(|v| v.color)).flatten() + } + Shape::Vec(shapes) => shapes.iter().find_map(|child| find_fill(child, rect)), + _ => None, + } + } + let fill = output.shapes.iter().find_map(|s| find_fill(&s.shape, rect)); assert_eq!(fill, Some(expected), "page {page}, reading mode {}", colors.mode_name()); } } diff --git a/crates/ui-egui/tests/it/reload.rs b/crates/ui-egui/tests/it/reload.rs index 547d4d8e01..a573a6585e 100644 --- a/crates/ui-egui/tests/it/reload.rs +++ b/crates/ui-egui/tests/it/reload.rs @@ -89,7 +89,7 @@ fn app_with(jobs: Arc) -> PdfCraftApp { use craft::platform::watch::FileWatch; use pdfcraft_ui_egui::AppServices; let info = AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }; - let host = Host::builder(info).jobs(jobs).files(Arc::new(craft::host::ScriptedFiles::new())).build(); + let host = Host::builder(info).jobs(jobs).files(Arc::new(craft::host::NoPickFiles::default())).build(); let (intake, _sender) = FileIntake::new(Wake::none()); let watch = FileWatch::new(Wake::none()).inline(); let services = AppServices::new(Wake::none(), Clipboard::new(SystemClipboard::new()), None, None, intake, watch); @@ -358,7 +358,7 @@ fn saving_over_a_file_changed_by_something_else_asks_first() { let ctx_h = h.ctx.clone(); assert!(!h.state_mut().save_active(&ctx_h, SaveTarget::InPlace)); h.run_steps(2); - h.get_by_label("Save anyway").click(); + h.get_by_label("Replace").click(); h.run_steps(3); assert!(!dirty(&h), "written"); assert_ne!(std::fs::read(&file.path).unwrap(), fixture(4)); @@ -456,7 +456,7 @@ fn a_newer_version_found_as_the_dialog_closes_replaces_the_held_one() { let generation = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(h.state().views[0].id).unwrap().edit_generation(); let before = generation(&h); h.get_by_label("Cancel").click(); - h.step(); + h.run_steps(2); assert_eq!((pages(&h), generation(&h) - before), (5, 1), "the held version is not loaded on the way"); } diff --git a/crates/ui-egui/tests/it/theme.rs b/crates/ui-egui/tests/it/theme.rs index afb26ce437..5d35e130d9 100644 --- a/crates/ui-egui/tests/it/theme.rs +++ b/crates/ui-egui/tests/it/theme.rs @@ -212,15 +212,23 @@ fn restored_system_tracks_native_input_without_rewriting_saved_preference() { assert!(call(&mut h, &c, "ui.set", json!({"key": "theme", "value": "purple"})).is_err()); } -/// Preferences ▸ Appearance: a theme card is a manual choice that the mode combo box shows and -/// OS changes leave alone; Use system setting afterwards follows the OS again. +/// Preferences ▸ Appearance: manual Light/Dark mode choices stay fixed across OS changes, +/// Sync with system follows the OS both ways, and the Active badge tracks the active mode row. #[test] fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { use egui::accesskit::Role; fn mode_shown(h: &Harness<'static, PdfCraftApp>) -> String { - let combo = - h.get_by(|n| n.role() == Role::ComboBox && n.value().is_some_and(|v| ["Use system setting", "Light", "Dark"].contains(&v.as_str()))); - combo.value().unwrap_or_default() + h.get_by_role_and_label(Role::ComboBox, "Appearance Mode").value().unwrap_or_default() + } + fn pick_mode(h: &mut Harness<'static, PdfCraftApp>, choice: &str) { + h.get_by_role_and_label(Role::ComboBox, "Appearance Mode").scroll_to_me(); + h.run_steps(2); + h.get_by_role_and_label(Role::ComboBox, "Appearance Mode").click(); + h.run_steps(3); + h.get_all_by_label(choice).last().expect("mode option").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Apply").click(); + h.run_steps(3); } let (mut h, c) = harness(); h.get_by_label("Display theme: Use system setting").click_secondary(); @@ -229,19 +237,16 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { h.run_steps(10); // A fresh install follows the OS (#1248), which is dark here. assert_theme(&mut h, &c, "System", "Dark"); - assert_eq!(mode_shown(&h), "Use system setting"); + assert_eq!(mode_shown(&h), "Sync with system"); + assert_eq!(h.query_all_by_label("Active").count(), 1); - // The OS is dark: the Dark card picks Dark, and the combo box says so. - // The cards sit below the fold of the Preferences scroll area at this window size. - h.get_by_label("Dark theme").scroll_to_me(); - h.run_steps(3); - h.get_by_label("Dark theme").click(); - h.run_steps(3); + // Choosing Dark locks Dark even though the OS is already dark. + pick_mode(&mut h, "Dark"); assert_theme(&mut h, &c, "Dark", "Dark"); assert_eq!(mode_shown(&h), "Dark"); - // The Light card itself, not its radio row, picks Light, and a dark OS doesn't undo it. - h.get_by_label("Light theme").click(); - h.run_steps(3); + + // Choosing Light locks Light, and OS changes leave it alone. + pick_mode(&mut h, "Light"); os_theme(&mut h, Some(egui::Theme::Light)); h.run_steps(2); os_theme(&mut h, Some(egui::Theme::Dark)); @@ -249,27 +254,18 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { assert_theme(&mut h, &c, "Light", "Light"); assert_eq!(mode_shown(&h), "Light"); - // Use system setting follows the OS both ways after a card choice. - h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Light")).scroll_to_me(); - h.run_steps(3); - h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Light")).click(); - h.run_steps(3); - // Motion has a "Use system setting" radio of its own; this is the combo box's item. - h.get_by_role_and_label(Role::Button, "Use system setting").click(); - h.run_steps(3); + // Sync with system follows the OS both ways after a manual choice. + pick_mode(&mut h, "Sync with system"); assert_theme(&mut h, &c, "System", "Dark"); - assert_eq!(mode_shown(&h), "Use system setting"); + assert_eq!(mode_shown(&h), "Sync with system"); os_theme(&mut h, Some(egui::Theme::Light)); h.run_steps(3); assert_theme(&mut h, &c, "System", "Light"); - // Only the Light card is marked Active while the OS is light. + // Only the Light row is marked Active while the OS is light. assert_eq!(h.query_all_by_label("Active").count(), 1); - // A card click leaves system mode again. - h.get_by_label("Dark theme").scroll_to_me(); - h.run_steps(3); - h.get_by_label("Dark theme").click(); - h.run_steps(3); + // Choosing Dark leaves system mode again. + pick_mode(&mut h, "Dark"); assert_theme(&mut h, &c, "Dark", "Dark"); assert_eq!(mode_shown(&h), "Dark"); } diff --git a/crates/ui-egui/tests/it/viewer.rs b/crates/ui-egui/tests/it/viewer.rs index 9f21c8de95..83faaa6bf6 100644 --- a/crates/ui-egui/tests/it/viewer.rs +++ b/crates/ui-egui/tests/it/viewer.rs @@ -967,11 +967,6 @@ fn page_label_input_same_document_replacement_keeps_full_label_selected_for_typi assert!(h.execute("view.focus_page_input")); h.run_steps(3); assert!(page_input_focused(&h), "the real focus command focuses the page editor"); - let editor_id = h.ctx.memory(|m| m.focused()).expect("focused page editor"); - let range = egui::TextEdit::load_state(&h.ctx, editor_id).unwrap().cursor.char_range().unwrap(); - let ends = [range.primary.index, range.secondary.index]; - assert!(ends.contains(&egui::text::CCursor::new(0).index), "the old label selection starts at zero"); - assert!(ends.contains(&egui::text::CCursor::new(1).index), "the entire old one-character label is selected"); let id = h.state().views[0].id; let original = h.state().session.get(id).unwrap(); assert!(!original.dirty); @@ -991,8 +986,7 @@ fn page_label_input_same_document_replacement_keeps_full_label_selected_for_typi h.run_steps(settling_frames); } assert_eq!(h.state().views[0].id, id); - assert_eq!(h.ctx.memory(|m| m.focused()), Some(editor_id), "same-DocId reload retains the actual focused editor"); - assert!(page_input_focused(&h)); + assert!(page_input_focused(&h), "same-DocId reload retains the actual focused editor"); assert_eq!((h.state().views[0].current(), h.state().views[0].page_input.as_str()), (3, "iv")); // Ordinary typing must replace the whole refreshed label without another focus or select-all. @@ -1188,7 +1182,7 @@ fn a_snapshot_area_prints_alone_or_saves_as_an_image() { std::fs::create_dir_all(&dir).unwrap(); // The first pick is Save as image…'s, the second Print's Save as PDF. let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![dir.join("area.png")]), Picked::Paths(vec![dir.join("area.pdf")])])); - let mut h = harness_on(files, &Written::default()); + let mut h = harness_on(Arc::clone(&files), &Written::default()); let i = h.state().active.unwrap(); let r = h.state().views[i].page_screen_rect(0).expect("on screen"); let at = |x: f32, y: f32| egui::pos2(r.left() + x / 200.0 * r.width(), r.top() + (300.0 - y) / 300.0 * r.height()); @@ -1208,13 +1202,15 @@ fn a_snapshot_area_prints_alone_or_saves_as_an_image() { assert!(h.state().dialogs.is_open::()); assert_eq!(h.state().print_draft.which, PrintWhich::Area); h.get_by_label_contains("Selected area (page 1,"); - h.state_mut().print_draft.printer = None; + let ctx_h = h.ctx.clone(); + let print_id = h.state().dialogs.open_dialogs().last().expect("Print dialog open").id; + h.state_mut().dialogs.set_json_field(&ctx_h, print_id, "printer", serde_json::Value::Null).unwrap(); h.run_steps(2); h.get_by_label("Save as PDF").click(); - assert!(crate::support::step_until(&mut h, |_| std::fs::read(dir.join("area.pdf")).is_ok()), "the PDF is written"); + assert!(crate::support::step_until(&mut h, |_| files.file(&dir.join("area.pdf")).is_some()), "the PDF is written"); h.run_steps(4); assert!(!h.state().dialogs.is_open::()); - let out = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("area.pdf")).expect("saved"))).unwrap(); + let out = pdfcraft_cos::Document::open(std::sync::Arc::new(files.file(&dir.join("area.pdf")).expect("saved"))).unwrap(); assert_eq!(pdfcraft_model::pages(&out).len(), 1, "one sheet for the area"); // The next Print is for pages again. assert!(h.execute("print.dialog")); @@ -1314,7 +1310,8 @@ fn fit_visible_zooms_to_the_content_width() { let r = v.page_screen_rect(v.current()).expect("on screen"); let ink_left = r.left() + 20.0 / 200.0 * r.width(); let vp = v.viewport_rect(); - assert!((ink_left - vp.left() - 16.0).abs() < 12.0, "ink at {ink_left}, viewport {vp:?}"); + let side = v.spacing.as_ref().expect("laid out").side as f32; + assert!((ink_left - vp.left() - side).abs() < 12.0, "ink at {ink_left}, viewport {vp:?}, side {side}"); } #[test] @@ -1775,6 +1772,7 @@ fn left_and_right_scroll_a_page_wider_than_the_window_before_turning_it() { use egui::{Key, Modifiers}; let mut h = harness(); h.state_mut().active = Some(0); + h.state_mut().views[0].view.fit = pdfcraft_ui_egui::canvas::Fit::None; h.state_mut().views[0].view.zoom = 12.0; h.run_steps(6); let press = |h: &mut Harness<'static, PdfCraftApp>, modifiers, key| { @@ -1841,6 +1839,7 @@ fn left_and_right_follow_the_current_pages_width_in_continuous_view() { h.state_mut().active = Some(0); assert!(h.state().views[0].continuous()); // Each page taller than the window, so one is the current page. + h.state_mut().views[0].view.fit = pdfcraft_ui_egui::canvas::Fit::None; h.state_mut().views[0].view.zoom = 1.0; h.run_steps(6); h.state_mut().views[0].go_to_page(0); @@ -1876,6 +1875,7 @@ fn right_scrolls_to_a_spreads_second_page_off_screen_before_turning() { app.open_bytes(&egui::Context::default(), "spread.pdf", None, sized_fixture(&[(600, 800); 4])).unwrap(); app.set_option(&egui::Context::default(), "layout", "two-page").unwrap(); // Before the first layout: zoomed about the content's top left, scrolled to it. + app.views[0].view.fit = pdfcraft_ui_egui::canvas::Fit::None; app.views[0].view.zoom = f64::from(zoom); app } @@ -2124,7 +2124,7 @@ fn pages_panel_thumbnail_size_controls_show_more_pages_and_keep_the_selection() let zoom = h.state().views[0].zoom(); let visible = |h: &Harness<'static, PdfCraftApp>| (1..=30).filter(|n| thumbnail_in_view(h, *n)).count(); let before = visible(&h); - h.get_by_label("Smaller thumbnails").click(); + h.get_by_label("Smaller Thumbnails").click(); h.run_steps(4); assert!(thumbnail_rect(&h, 1).width() < usual); assert!(visible(&h) > before, "smaller thumbnails show more complete pages"); @@ -2136,10 +2136,10 @@ fn pages_panel_thumbnail_size_controls_show_more_pages_and_keep_the_selection() let _gpu = crate::gpu(); h.render().unwrap().save(format!("{dir}/small.png")).unwrap(); } - h.get_by_label("Larger thumbnails").click(); + h.get_by_label("Larger Thumbnails").click(); h.run_steps(4); assert!((thumbnail_rect(&h, 1).width() - usual).abs() < 0.1); - h.get_by_label("Larger thumbnails").click(); + h.get_by_label("Larger Thumbnails").click(); h.run_steps(4); assert!(thumbnail_rect(&h, 1).width() > usual); assert_eq!(h.state().views[0].target_pages(), vec![0, 1]); @@ -2193,8 +2193,8 @@ fn pages_panel_thumbnail_zoom_keeps_a_far_current_page_visible() { h.run_steps(4); assert!(in_panel_view(&h, thumbnail_rect(&h, 25)), "page 25 stays visible at {size}%"); assert_eq!(h.state().views[0].current(), 24); - h.get_by_label("Smaller thumbnails"); - h.get_by_label("Larger thumbnails"); + h.get_by_label("Smaller Thumbnails"); + h.get_by_label("Larger Thumbnails"); } } @@ -2541,6 +2541,8 @@ fn the_picture_menu_opens_link_properties_and_recognize_text_for_the_picture() { h.get_by_label("Create Link…").click(); h.run_steps(3); assert_eq!(h.state().dialogs.open_dialogs().len(), 1, "Link Properties is open"); + h.get_by_label("Go to a page view").click(); + h.run_steps(2); h.get_all_by_label("OK").last().expect("Link Properties' OK").click(); h.run_steps(3); let s = h.state();