From 5623136018bf6f134e9845c0234e9d9b5053df73 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:29:02 -0500 Subject: [PATCH] compile fix 1 (comments-edit): name resolution after the app-1 combine (swarm/cfix1, report in swarm/cfix1/run); committed by the lead --- crates/ui-egui/src/tools/comments.rs | 13 +++--- crates/ui-egui/src/tools/comments/bridge.rs | 7 ++- crates/ui-egui/src/tools/comments/composer.rs | 3 +- crates/ui-egui/src/tools/comments/menu.rs | 21 +++------ crates/ui-egui/src/tools/comments/overlay.rs | 19 ++++++-- crates/ui-egui/src/tools/comments/popups.rs | 19 +++++--- crates/ui-egui/src/tools/comments/state.rs | 8 ++-- crates/ui-egui/src/tools/comments/tests.rs | 14 ++++-- crates/ui-egui/src/tools/comments/tool.rs | 4 +- crates/ui-egui/src/tools/content_ui.rs | 32 ++++++++----- crates/ui-egui/src/tools/edit_text_ui.rs | 34 +++++++------- .../ui-egui/src/tools/edit_text_ui/image.rs | 37 ++++++++++++--- crates/ui-egui/src/tools/link_ui.rs | 23 ++++++---- crates/ui-egui/src/tools/measure_ui.rs | 45 +++++++------------ 14 files changed, 163 insertions(+), 116 deletions(-) diff --git a/crates/ui-egui/src/tools/comments.rs b/crates/ui-egui/src/tools/comments.rs index 154c8fc66b..d6221c03e0 100644 --- a/crates/ui-egui/src/tools/comments.rs +++ b/crates/ui-egui/src/tools/comments.rs @@ -20,7 +20,6 @@ use craft::review::ui::annotate::{AnnotateCommand, AnnotateIcons}; use craft::review::{AnnotationKind, AnnotationTool}; use crate::canvas::{DocView, PageXform}; -use crate::theme::{self, Tokens}; use crate::{QuickTool, icons}; mod bridge; @@ -33,31 +32,29 @@ mod popups; mod state; mod tool; +#[cfg(test)] +use bridge::hover_tip; pub(crate) use bridge::{ PageMap, annotations, delete_selected, edit, edit_anchor, id_of, key_of, kind_of, markers, parts, pdf_date_seconds, screen_to_user_rect, thread_id, thread_key, tips, tips_shown, }; -#[cfg(test)] -use bridge::hover_tip; -// PLAN: assumed colours exports (pdf-comments-w10): the colour pickers and buttons that `menu` exported before. -pub use colours::{fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid}; -pub(crate) use colours::{border_colour_button, quick_bar_colour}; +pub(crate) use colours::{RecentColours, border_choice, fill_choice, palette, to_rgb}; pub(crate) use composer::composer; #[cfg(test)] use composer::edited_in_view; +pub(crate) use geometry::page_rotation; #[cfg(test)] pub(crate) use geometry::{caret_snap, snapped_caret}; -pub(crate) use geometry::page_rotation; pub use geometry::{drawn_text_box_rect, snug_text_box_rect, text_box_rect}; pub use menu::CanvasAction; pub(crate) use menu::{CommentMenuCx, MenuRights, QuickBarPick, attachment_items, context_rows, quick_bar_controls}; pub(crate) use overlay::show; pub(crate) use popups::note_popups; +pub(crate) use state::PageCx; #[cfg(test)] use state::after_delete; use state::login_name; pub use state::{CommentView, Composer, ComposerKind}; -pub(crate) use state::PageCx; pub(crate) use tool::{CommentsTool, PastePlacement, context_target, page_after_text, part_pressed}; /// Maximum stroke thickness offered by commenting controls, in PDF points. diff --git a/crates/ui-egui/src/tools/comments/bridge.rs b/crates/ui-egui/src/tools/comments/bridge.rs index 138cba6db2..1c3bb936ec 100644 --- a/crates/ui-egui/src/tools/comments/bridge.rs +++ b/crates/ui-egui/src/tools/comments/bridge.rs @@ -15,7 +15,9 @@ use craft::review::{Annotation as Marked, AnnotationEdit, AnnotationId, Annotati use super::geometry::{CARET_SIZE, clamp_to, frame, is_callout, on_text, reshapable, resizable}; use super::popups::has_popup; use super::state::{CommentView, Composer, ComposerKind, PageCx}; -use super::{Annotation, CommentPrefs, CommentTool, DocInfo, DocView, Edit, LineEnding, NewAnnotation, PageInfo, QuickTool, Shape, tool_for}; +use super::{ + Annotation, CommentPrefs, CommentTool, DocInfo, DocView, Edit, LineEnding, NewAnnotation, PageInfo, QuickTool, Shape, tool_for, tool_for_default, +}; // PLAN: assumed `PagePart::new(owner, page, shape: Vec, layer)` with `.passes_drag()`, `.tip(String)` and // `.cursor(CursorIcon)`, and `Owner::Comment { index }` (pdf-canvas-w9, `canvas/page_parts.rs`). use crate::canvas::page_parts::{Owner, PageLayer, PagePart}; @@ -332,7 +334,8 @@ pub(crate) fn parts( let markers = marker_boxes(info, &anns, icon_side); let Some(id) = pick_at(&anns, at, tolerance, icon_side, &markers) else { return Vec::new() }; let Some(found) = anns.iter().find(|a| a.id == id) else { return Vec::new() }; - let mut shapes: Vec = if found.kind.is_markup() { found.points.chunks(4).filter_map(bounds).collect() } else { vec![found.extent(icon_side)] }; + let mut shapes: Vec = + if found.kind.is_markup() { found.points.chunks(4).filter_map(bounds).collect() } else { vec![found.extent(icon_side)] }; shapes.extend(markers.iter().filter(|(m, _)| *m == id).map(|(_, r)| *r)); let screen_shapes: Vec = shapes .iter() diff --git a/crates/ui-egui/src/tools/comments/composer.rs b/crates/ui-egui/src/tools/comments/composer.rs index fb227efded..f7c157a55b 100644 --- a/crates/ui-egui/src/tools/comments/composer.rs +++ b/crates/ui-egui/src/tools/comments/composer.rs @@ -44,7 +44,8 @@ pub(crate) fn composer(ui: &mut egui::Ui, view: &mut DocView, info: &DocInfo, pr ComposerKind::Edit(_) => ComposerDraft::Edit, _ => ComposerDraft::New, }; - let output = CommentComposer::new(anchor, &mut c.text).header(tl!(title), &prefs.author).draft_kind(draft).close(ComposerClose::OnPostOrCancel).show(ui); + let output = + CommentComposer::new(anchor, &mut c.text).header(tl!(title), &prefs.author).draft_kind(draft).close(ComposerClose::OnPostOrCancel).show(ui); if output.cancelled { view.comments.composer = None; return None; diff --git a/crates/ui-egui/src/tools/comments/menu.rs b/crates/ui-egui/src/tools/comments/menu.rs index fe659b3550..702c2841b0 100644 --- a/crates/ui-egui/src/tools/comments/menu.rs +++ b/crates/ui-egui/src/tools/comments/menu.rs @@ -7,11 +7,11 @@ use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Divider; use craft::ui::form::SliderField; +use craft::review::ui::annotate::AnnotateWords; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::popover::Popover; use craft::ui::runtime::env::Env; use craft::ui::runtime::requests::ColorRequest; -use craft::review::ui::annotate::AnnotateWords; // PLAN: `mod colours;` is declared in `tools/comments.rs` (pdf-comments-w7). use super::colours::{self, RecentColours, fill_choice, palette, to_srgba}; @@ -143,7 +143,8 @@ pub(crate) fn context_rows(ui: &mut egui::Ui, cx: CommentMenuCx<'_>) -> Option { /// Paints the page's comments: the annotation overlay over the pages `body` places, the outline of the comment a /// press under the pointer would take, and a redaction mark's fill while the pointer is over it, as Acrobat's does, /// so the marked area reads before anything is applied. -pub(crate) fn show(ui: &mut egui::Ui, body: &PageBody<'_>, view: &DocView, info: &DocInfo, prefs: &CommentPrefs, tool: QuickTool, hover: Hover<'_, '_>) { +pub(crate) fn show( + ui: &mut egui::Ui, + body: &PageBody<'_>, + view: &DocView, + info: &DocInfo, + prefs: &CommentPrefs, + tool: QuickTool, + hover: Hover<'_, '_>, +) { let map = PageMap::new(body.pages, info); let all = bridge::annotations(info, &map, QuickTool::Select, hover.allowed); let reached = bridge::annotations(info, &map, tool, hover.allowed); @@ -191,7 +199,11 @@ fn rect_corners(r: Rect) -> Vec { /// comment's colour, or `fallback` when it has none. fn paint_outline(draw: &Draw<'_>, outline: &O, at: &dyn Fn([f64; 2]) -> Pos2, fallback: StyleColor) { let width = StrokeWidth::Medium; - let own = |c: &Option<[f64; 3]>| c.map(|[r, g, b]| DataColor::new(Color32::from_rgb((r.clamp(0.0, 1.0) * 255.0) as u8, (g.clamp(0.0, 1.0) * 255.0) as u8, (b.clamp(0.0, 1.0) * 255.0) as u8))); + let own = |c: &Option<[f64; 3]>| { + c.map(|[r, g, b]| { + DataColor::new(Color32::from_rgb((r.clamp(0.0, 1.0) * 255.0) as u8, (g.clamp(0.0, 1.0) * 255.0) as u8, (b.clamp(0.0, 1.0) * 255.0) as u8)) + }) + }; let stroke = |shape: PaintShape, c: &Option<[f64; 3]>| match own(c) { Some(color) => draw.stroke(&shape, width, color), None => draw.stroke(&shape, width, fallback), @@ -201,7 +213,8 @@ fn paint_outline(draw: &Draw<'_>, outline: &O, at: &dyn Fn([f64; 2]) -> Pos2, fa let r = Rect::from_two_pos(at([rect[0], rect[1]]), at([rect[2], rect[3]])); if *round { let (c, rx, ry) = (r.center(), r.width() / 2.0, r.height() / 2.0); - let points = (0..48).map(|i| i as f32 / 48.0 * std::f32::consts::TAU).map(|t| Pos2::new(c.x + rx * t.cos(), c.y + ry * t.sin())).collect(); + let points = + (0..48).map(|i| i as f32 / 48.0 * std::f32::consts::TAU).map(|t| Pos2::new(c.x + rx * t.cos(), c.y + ry * t.sin())).collect(); stroke(PaintShape::Polygon(points), color); } else { stroke(PaintShape::Polygon(rect_corners(r)), color); diff --git a/crates/ui-egui/src/tools/comments/popups.rs b/crates/ui-egui/src/tools/comments/popups.rs index 7a6e688ce1..db0af0b5d8 100644 --- a/crates/ui-egui/src/tools/comments/popups.rs +++ b/crates/ui-egui/src/tools/comments/popups.rs @@ -82,7 +82,6 @@ fn flatten<'a>(nodes: &[(&'a Annotation, Vec)], at: usize, depth: usize, } } - /// One message of a window, owned until the window is built. struct Owned { key: (usize, usize), @@ -120,7 +119,12 @@ fn messages( let mut holder = info .annotations .iter() - .find(|r| r.grouped && r.parent == Some(key) && a.contents.as_deref().unwrap_or("").is_empty() && r.contents.as_deref().is_some_and(|c| !c.is_empty())) + .find(|r| { + r.grouped + && r.parent == Some(key) + && a.contents.as_deref().unwrap_or("").is_empty() + && r.contents.as_deref().is_some_and(|c| !c.is_empty()) + }) .cloned() .unwrap_or_else(|| a.clone()); holder.locked |= a.locked; @@ -214,11 +218,12 @@ pub(crate) fn note_popups( let selected = view.comments.is_selected((page, a.index)); // PLAN: A-2 `popup_drafts: HashMap<(usize, usize), NoteDrafts>`, one per open window (lead ruling, review 1). let drafts: &mut NoteDrafts = view.comments.popup_drafts.entry((page, a.index)).or_default(); - let mut window = NotePopup::new(super::bridge::id_of(page, a.index).0, owned.first().map_or("", |m| m.title.as_str()), rect, &msgs, drafts) - .color(color) - .selected(selected) - .now(now) - .allowed(allowed); + let mut window = + NotePopup::new(super::bridge::id_of(page, a.index).0, owned.first().map_or("", |m| m.title.as_str()), rect, &msgs, drafts) + .color(color) + .selected(selected) + .now(now) + .allowed(allowed); if let Some(mark) = mark { window = window.anchor(mark, hovered == Some((page, a.index))); } diff --git a/crates/ui-egui/src/tools/comments/state.rs b/crates/ui-egui/src/tools/comments/state.rs index 6c5813db70..ef0ff7545e 100644 --- a/crates/ui-egui/src/tools/comments/state.rs +++ b/crates/ui-egui/src/tools/comments/state.rs @@ -362,9 +362,11 @@ impl CommentView { .into_iter() .filter_map(|id| moved(bridge::key_of(id)).map(|(p, i)| bridge::id_of(p, i))) .collect(); - let editing = self.panel.editing.take().and_then(|(thread, message, text)| { - moved(bridge::thread_key(thread)).map(|(p, i)| (bridge::thread_id(p, i), message, text)) - }); + let editing = self + .panel + .editing + .take() + .and_then(|(thread, message, text)| moved(bridge::thread_key(thread)).map(|(p, i)| (bridge::thread_id(p, i), message, text))); // What is typed in a pop-up, and a window being dragged or resized, follow theirs too. let drafts = self.popup_drafts.take().and_then(|(p, i, d)| moved((p, i)).map(|(p, i)| (p, i, d))); // Other transient state still needs conservative pruning; refresh the slot snapshot too. diff --git a/crates/ui-egui/src/tools/comments/tests.rs b/crates/ui-egui/src/tools/comments/tests.rs index 63415a4851..0f9931ea93 100644 --- a/crates/ui-egui/src/tools/comments/tests.rs +++ b/crates/ui-egui/src/tools/comments/tests.rs @@ -268,6 +268,7 @@ fn away_from_upright_horizontal_text_the_caret_stays_at_the_click() { fn recent_custom_colours_dedupe_cap_and_skip_swatches() { use super::SWATCHES; use super::colours::{RecentColours, to_srgba}; + use craft::theme::Srgba; let same = |a: &Srgba, b: [f64; 3]| { let b = to_srgba(b); (a.r - b.r).abs() < 1e-3 && (a.g - b.g).abs() < 1e-3 && (a.b - b.b).abs() < 1e-3 @@ -302,7 +303,7 @@ fn tools_round_trip_through_their_commands() { assert_eq!(CommentTool::from_command(t.command()), Some(t)); assert!(pdfcraft_engine::commands::command(t.command()).is_some(), "{} is registered", t.command()); let icon = supplied.icon(craft::review::ui::annotate::AnnotateCommand::of(t.tool())).expect("the app names every tool's icon"); - assert!(icons::exists(icon), "icon {icon}"); + assert!(craft::ui::primitives::has_icon(&craft::behavior::IconId::new(icon)), "icon {icon}"); assert!(GROUPS[t.group()].contains(&t)); } } @@ -338,7 +339,10 @@ fn an_arrow_is_created_as_a_line_with_an_open_arrow_end() { }; assert!(matches!( created(craft::review::AnnotationKind::Arrow), - Some(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { shape: Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. }, .. })) + Some(Edit::AddAnnotation(pdfcraft_engine::NewAnnotation { + shape: Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. }, + .. + })) )); assert!(matches!( created(craft::review::AnnotationKind::Line), @@ -441,7 +445,8 @@ fn stale_comment_state_is_cleared_and_delete_never_hits_non_comment_slots() { ..Default::default() }; let thread = |index: usize| ThreadId(bridge::id_of(0, index).0); - let composer = |index: usize, text: &str| Composer { page: 0, at: [10.0, 10.0], kind: ComposerKind::Edit(index), text: text.into(), focus: false }; + let composer = + |index: usize, text: &str| Composer { page: 0, at: [10.0, 10.0], kind: ComposerKind::Edit(index), text: text.into(), focus: false }; let mut view = DocView::new(pdfcraft_engine::DocId(1), &info, crate::canvas::ViewDefaults::default()); view.comments.select_only((0, 2)); view.comments.panel.editing = Some((thread(2), 0, "draft".into())); @@ -589,7 +594,8 @@ fn an_annotation_round_trips_through_the_page_map_on_turned_and_zoomed_pages() { } let mut view = DocView::new(pdfcraft_engine::DocId(1), &info, crate::canvas::ViewDefaults::default()); let delta = Vec2::new(1.0, 0.0); - let moved = bridge::edit(AnnotationEdit::Move { ids: vec![bridge::id_of(0, 0)], delta }, &map, &mut view.comments, &info, &CommentPrefs::default()); + let moved = + bridge::edit(AnnotationEdit::Move { ids: vec![bridge::id_of(0, 0)], delta }, &map, &mut view.comments, &info, &CommentPrefs::default()); let Some(Edit::MoveAnnotation { dx, dy, .. }) = moved else { panic!("{case}: a move is one MoveAnnotation, got {moved:?}") }; let origin = map.to_doc(0, [50.0, 80.0]); let (from, to) = (map.to_user(0, origin), map.to_user(0, origin + delta)); diff --git a/crates/ui-egui/src/tools/comments/tool.rs b/crates/ui-egui/src/tools/comments/tool.rs index e3ba6a6b29..50649bc774 100644 --- a/crates/ui-egui/src/tools/comments/tool.rs +++ b/crates/ui-egui/src/tools/comments/tool.rs @@ -13,8 +13,8 @@ use egui::Pos2; use super::bridge::{self, PageMap}; use super::state::{Composer, ComposerKind, PageCx}; use super::{CommentPrefs, CommentTool, CommentView, DocInfo, DocView, Edit, MAX_LINE_WIDTH, QuickTool}; -use crate::canvas::PageSelectTool; use crate::canvas::page_parts::{Owner, PagePress}; +use crate::canvas::page_select::PageSelectTool; /// Copied comments hanging on the pointer, waiting for a click to place them. pub(crate) struct PastePlacement { @@ -117,7 +117,7 @@ impl<'a> CommentsTool<'a> { let a = info.user_to_view((paste.bounds[0] + offset[0]) as f32, (paste.bounds[1] + offset[1]) as f32); let b = info.user_to_view((paste.bounds[2] + offset[0]) as f32, (paste.bounds[3] + offset[1]) as f32); let (w, h) = ((a[0] - b[0]).abs(), (a[1] - b[1]).abs()); - if w > info.width + 1.0 || h > info.height + 1.0 + if (w > info.width + 1.0 || h > info.height + 1.0) && let Some(notice) = self.notice.as_deref_mut() { *notice = Some("The copied comments are larger than this page; they were placed as they are"); diff --git a/crates/ui-egui/src/tools/content_ui.rs b/crates/ui-egui/src/tools/content_ui.rs index 03d336eb25..b7124dbf01 100644 --- a/crates/ui-egui/src/tools/content_ui.rs +++ b/crates/ui-egui/src/tools/content_ui.rs @@ -15,7 +15,7 @@ use craft::draw::ui::TransformBox; use craft::pages::ui::{PageBody, PlacedPage}; use craft::platform::clipboard::{BITMAP, ClipboardImage, TEXT}; use craft::text::ui::editor::{CaretLine, EditKind, EditorEnd, HostLine, HostRun, TextEditor, TextEditorHost, TextSelection}; -use craft::theme::Tone; +use craft::theme::variant::Tone; use craft::ui::buttons::IconButton; use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft::ui::canvas_controls::{HoverOutline, HoverShape, TaskBar}; @@ -153,10 +153,7 @@ impl PageFrame { } fn screen(&self, display: [f64; 2]) -> Pos2 { - Pos2::new( - self.origin.x + (display[0] * self.scale) as f32, - self.origin.y + ((self.height - display[1]) * self.scale) as f32, - ) + Pos2::new(self.origin.x + (display[0] * self.scale) as f32, self.origin.y + ((self.height - display[1]) * self.scale) as f32) } fn screen_rect(&self, r: [f64; 4]) -> Rect { @@ -689,7 +686,13 @@ pub(crate) fn after_refresh(view: &mut DocView, added: &[Added]) { /// pass that shows them, and the preview they leave is held fact, never replayed. `hovered` is the /// (page, item) of the added-text part under the pointer, as the page body reads it from the parts. // PLAN: assumed the page body passes `PageParts::hovered`'s `Owner::Added { index }` with its page (pdf-canvas-w9). -pub(crate) fn content_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &Document, hovered: Option<(usize, usize)>) -> Option { +pub(crate) fn content_controls( + ui: &mut egui::Ui, + body: &PageBody<'_>, + view: &mut DocView, + doc: &Document, + hovered: Option<(usize, usize)>, +) -> Option { if view.content.draft.is_none() { view.content.drawn = None; } @@ -718,7 +721,14 @@ fn display_rect(view: &craft::behavior::CanvasView, frame: &PageFrame, state: &B } /// The selected text's frame and the hover outline on one page. -fn item_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &Document, frame: &PageFrame, hovered: Option) -> Option { +fn item_controls( + ui: &mut egui::Ui, + body: &PageBody<'_>, + view: &mut DocView, + doc: &Document, + frame: &PageFrame, + hovered: Option, +) -> Option { let page = frame.page; let items = on_page(doc.added(), page); let draft = view.content.draft.as_ref().filter(|d| d.page == page).and_then(|d| d.index); @@ -855,7 +865,7 @@ impl TextEditorHost for AddedTextHost<'_> { &self.draft.text } - fn replace(&mut self, range: Range, text: &str, kind: EditKind) -> bool { + fn replace(&mut self, range: Range, text: &str, kind: EditKind) -> Option { let before = self.draft.text.clone(); let start = byte_at(&before, range.start); let end = byte_at(&before, range.end).max(start); @@ -867,7 +877,7 @@ impl TextEditorHost for AddedTextHost<'_> { self.draft.selection = Some(TextSelection::caret_at(range.start + text.chars().count())); let now = self.draft.typed(); self.draft.history.record(kind, now); - true + Some(text.chars().count()) } fn hit(&mut self, at: Point) -> (usize, usize) { @@ -1731,7 +1741,7 @@ mod tests { fn review_cut_checks_modify_permission_before_writing_the_clipboard() { let mut app = crate::PdfCraftApp::for_unit_tests(); app.create_blank(); - let png =crate::create_ui::png_from_rgba(1, 1, &[255, 0, 0, 255]).unwrap(); + let png = crate::create_ui::png_from_rgba(1, 1, &[255, 0, 0, 255]).unwrap(); app.add_image("test.png".into(), png); app.apply_edit(Edit::Protect(pdfcraft_engine::Protection { permissions_password: Some("owner".into()), @@ -1771,7 +1781,7 @@ mod tests { move |ui, out: &mut Option| { // The app's fonts (the semibold section title) take effect from the next frame. if !fonts { - ui.ctx().set_fonts(crate::theme::font_definitions()); + crate::fonts::ui_fonts(crate::i18n::Lang::EN).install(ui.ctx()); fonts = true; return; } diff --git a/crates/ui-egui/src/tools/edit_text_ui.rs b/crates/ui-egui/src/tools/edit_text_ui.rs index d00f874378..8e5f3e0cc1 100644 --- a/crates/ui-egui/src/tools/edit_text_ui.rs +++ b/crates/ui-egui/src/tools/edit_text_ui.rs @@ -26,8 +26,8 @@ use egui::{CornerRadius, Pos2, Rect, Vec2, pos2, vec2}; use pdfcraft_engine::{Edit, ObjectKind, ObjectTarget}; use pdfcraft_render::DocInfo; -use crate::canvas::{DocView, PageXform}; use crate::canvas::page_parts::{Owner, PageLayer, PagePart, PagePress}; +use crate::canvas::{DocView, PageXform}; // PLAN: at the base `image.rs` imports `ACCENT`, `Color32`, `Stroke` and `PagePointer` from here; they // leave with the old overlay (pdf-edit-w9's rewrite takes theme roles instead). @@ -40,8 +40,8 @@ pub use image::{CropMode, ImageAction, ImageSelection}; pub(crate) use image::{delete_picture, picture_controls, picture_menu, picture_parts, picture_press, user_to_screen}; #[cfg(test)] use layout::{DARK_EDITOR_FILL, contrast}; -pub(crate) use layout::{editor_fill, editor_font, source_faces}; use layout::{color32, editor_galley, editor_job, look_of, source_look}; +pub(crate) use layout::{editor_fill, editor_font, source_faces}; /// What an edit box shows text for: a page paragraph, or text added in this session. #[derive(Clone, Copy, PartialEq, Eq, Hash)] @@ -725,9 +725,7 @@ pub(crate) fn page_parts(view: &DocView, doc: &pdfcraft_engine::Document, page: .filter(|block| Some(*block) != open) .filter_map(|block| { let reach = reach_of(&boxes, block, upright).intersect(placed.rect); - reach - .is_positive() - .then(|| PagePart::new(Owner::Paragraph { block }, page, HitShape::Rect(reach), PageLayer::Text).cursor(cursor)) + reach.is_positive().then(|| PagePart::new(Owner::Paragraph { block }, page, HitShape::Rect(reach), PageLayer::Text).cursor(cursor)) }) .collect() } @@ -892,7 +890,8 @@ pub(crate) fn paragraph_controls( open_waiting(view, doc, page, &blocks, &boxes); outline_closed(ui, body, view, page, &boxes); draw_move(ui, body, view, page, &boxes, press); - let framed = hovered.filter(|(p, _)| *p == page).and_then(|(_, block)| blocks.get(block).zip(boxes.get(block).copied())); + let framed = + hovered.filter(|(p, _)| *p == page).and_then(|(_, block)| blocks.get(block).zip(boxes.get(block).copied()).map(|(l, b)| (block, l, b))); edit = edit.or_else(|| width_frame(ui, body, view, doc, page, framed)); } edit.or_else(|| editor_session(ui, body, content, view, doc)) @@ -969,7 +968,7 @@ fn width_frame( view: &mut DocView, doc: &pdfcraft_engine::Document, page: usize, - framed: Option<(&pdfcraft_engine::TextBlock, Rect)>, + framed: Option<(usize, &pdfcraft_engine::TextBlock, Rect)>, ) -> Option { let info = &doc.info; let xf = view.page_xform(page)?; @@ -977,7 +976,7 @@ fn width_frame( if open_here || !has_edges(info, page) || view.objects.holds(page) || view.content.moving_on(page) { return None; } - let (l, b) = framed?; + let (block, l, b) = framed?; let start = doc_rect(&body.view, b); let state = BoxState::from_rect(start); // `TransformBox::text_frame`'s rules, showing the left and right handles only. @@ -1005,7 +1004,7 @@ fn width_frame( let style = pdfcraft_engine::BlockStyle { width: Some(width), offset: (shift != 0.0).then_some([shift, 0.0]), ..Default::default() }; // `editor_text` has a newline for every visual row, so a wrap would come back as a hard break and // a wider box would not reflow it. `reflow_text` rejoins a wrap and keeps a newline that was typed. - Some(Edit::EditTextBlock { page, block: framed_block(l, page, view, doc)?, text: l.reflow_text.clone(), style }) + Some(Edit::EditTextBlock { page, block, text: l.reflow_text.clone(), style }) } /// The open paragraph's text for [`TextEditor`]: the editor's text, laid out as the page lays it out @@ -1105,7 +1104,7 @@ impl TextEditorHost for ParagraphHost<'_> { &self.ed.text } - fn replace(&mut self, range: Range, text: &str, kind: EditKind) -> bool { + fn replace(&mut self, range: Range, text: &str, kind: EditKind) -> Option { let before = self.ed.text.clone(); let bytes = byte_of(&before, range.start)..byte_of(&before, range.end); self.ed.text.replace_range(bytes, text); @@ -1120,7 +1119,7 @@ impl TextEditorHost for ParagraphHost<'_> { let now = self.ed.typed(); self.ed.history.record(kind, now); self.galley = None; - true + Some(text.chars().count()) } fn hit(&mut self, at: Point) -> (usize, usize) { @@ -1154,10 +1153,7 @@ impl TextEditorHost for ParagraphHost<'_> { let mut lines = Vec::new(); for (placed, chars) in galley.rows.iter().zip(row_ranges(&galley)) { let line: String = text.chars().skip(chars.start).take(chars.len()).collect(); - let rect = Rect::from_two_pos( - doc_pos(self.to_doc(placed.pos.to_vec2())), - doc_pos(self.to_doc((placed.pos + placed.row.size).to_vec2())), - ); + let rect = Rect::from_two_pos(doc_pos(self.to_doc(placed.pos.to_vec2())), doc_pos(self.to_doc((placed.pos + placed.row.size).to_vec2()))); let baseline = placed.row.glyphs.first().map_or(placed.row.size.y, |g| g.pos.y); let baseline = doc_pos(self.to_doc(vec2(placed.pos.x, placed.pos.y + baseline))).y; let positions = placed.row.glyphs.iter().map(|g| self.view.doc_len(g.pos.x) as f32).collect(); @@ -1192,7 +1188,13 @@ impl TextEditorHost for ParagraphHost<'_> { /// The open paragraph's editor: its changed text over the page without it, and a [`TextEditor`] session /// for the selection, the caret and the keys. Returns the edit once the text is applied. -fn editor_session(ui: &mut egui::Ui, body: &PageBody<'_>, content: &ContentPainterCx<'_>, view: &mut DocView, doc: &pdfcraft_engine::Document) -> Option { +fn editor_session( + ui: &mut egui::Ui, + body: &PageBody<'_>, + content: &ContentPainterCx<'_>, + view: &mut DocView, + doc: &pdfcraft_engine::Document, +) -> Option { let info = &doc.info; let page = view.line_editor.as_ref()?.page; let xf = view.page_xform(page)?; 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 1fa2581f58..2ac36ac10a 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -6,10 +6,10 @@ use craft::behavior::{CursorIcon, EditEvent, HitShape, IconId, PointerButton}; use craft::draw::ui::transform::{RotateZone, TransformBox}; use craft::imaging::ui::transform_preview::{PreviewMap, PreviewPixels, PreviewTextures, TransformPreview}; use craft::pages::ui::{PageBody, PlacedPage}; -use craft::ui::canvas::crop::{CropOutside, CropOverlay}; +use craft::ui::buttons::Button; +use craft::ui::canvas::{CropOutside, CropOverlay}; use craft::ui::canvas_controls::{SelectionOutline, TaskBar}; use craft::ui::contract::{Bind, Props as _, Show as _}; -use craft::ui::buttons::Button; use craft::ui::display::Divider; use craft::ui::menu::{Menu, MenuIcon, MenuIconRow, MenuItem}; @@ -151,7 +151,12 @@ fn least_side(ui: &egui::Ui, placed: &PlacedPage) -> f64 { fn bounds_of(q: &[Point; 4]) -> DocRect { let xs = q.iter().map(|p| p.x); let ys = q.iter().map(|p| p.y); - DocRect::new(xs.clone().fold(f64::INFINITY, f64::min), ys.clone().fold(f64::INFINITY, f64::min), xs.fold(f64::NEG_INFINITY, f64::max), ys.fold(f64::NEG_INFINITY, f64::max)) + DocRect::new( + xs.clone().fold(f64::INFINITY, f64::min), + ys.clone().fold(f64::INFINITY, f64::min), + xs.fold(f64::NEG_INFINITY, f64::max), + ys.fold(f64::NEG_INFINITY, f64::max), + ) } fn corners_of(r: DocRect) -> [Point; 4] { @@ -211,7 +216,13 @@ fn path_of(q: &[Point; 4]) -> BezPath { /// The controls of the selected picture on every page shown, and the faint outlines of the /// pictures beside it. The edit a gesture commits comes back for the caller to queue. -pub(crate) fn picture_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &pdfcraft_engine::Document, info: &DocInfo) -> Option { +pub(crate) fn picture_controls( + ui: &mut egui::Ui, + body: &PageBody<'_>, + view: &mut DocView, + doc: &pdfcraft_engine::Document, + info: &DocInfo, +) -> Option { let mut edit = None; for placed in body.pages { let Some(xf) = view.page_xform(placed.page) else { continue }; @@ -391,7 +402,13 @@ fn picture_edit( Some(Edit::EditPageImage { page, index, change }) } -fn picture_change(matrix: [f64; 6], rect: [f64; 4], start: [Point; 4], end: [Point; 4], to_user: &dyn Fn(Point) -> (f64, f64)) -> Option { +fn picture_change( + matrix: [f64; 6], + rect: [f64; 4], + start: [Point; 4], + end: [Point; 4], + to_user: &dyn Fn(Point) -> (f64, f64), +) -> Option { use pdfcraft_engine::ImageEdit as E; let (s, e) = (start.map(to_user), end.map(to_user)); if s.iter().chain(&e).any(|p| !p.0.is_finite() || !p.1.is_finite()) { @@ -695,8 +712,14 @@ mod screen_orientation_tests { assert!(matches!(change(moved), Some(E::Move(r)) if r == [15.0, 77.0, 35.0, 87.0]), "a translation is a move"); assert!(change(start).is_none(), "no movement is no edit"); assert!(change(quad((10.0, 10.0), 20.0, 10.0, 0.01)).is_none(), "a turn under 0.05 degrees is none"); - assert!(matches!(change(quad((10.0, 10.0), 20.0, 10.0, 30.0)), Some(E::RotateBy(d)) if (d - 30.0).abs() < 1e-6), "a clockwise turn is positive"); - assert!(matches!(change(quad((10.0, 10.0), 40.0, 20.0, 0.0)), Some(E::Move(r)) if r == [10.0, 70.0, 50.0, 90.0]), "an upright resize is a move"); + assert!( + matches!(change(quad((10.0, 10.0), 20.0, 10.0, 30.0)), Some(E::RotateBy(d)) if (d - 30.0).abs() < 1e-6), + "a clockwise turn is positive" + ); + assert!( + matches!(change(quad((10.0, 10.0), 40.0, 20.0, 0.0)), Some(E::Move(r)) if r == [10.0, 70.0, 50.0, 90.0]), + "an upright resize is a move" + ); let turned = quad((10.0, 10.0), 20.0, 10.0, 30.0); let tm = frame(turned); diff --git a/crates/ui-egui/src/tools/link_ui.rs b/crates/ui-egui/src/tools/link_ui.rs index 2472a15824..3fc1fc9008 100644 --- a/crates/ui-egui/src/tools/link_ui.rs +++ b/crates/ui-egui/src/tools/link_ui.rs @@ -5,7 +5,10 @@ use craft::behavior::kurbo::{BezPath, Point}; use craft::behavior::{CancelReason, Cursor, CursorIcon, PointerButton, PressPhase, PressState}; use craft::pages::ui::{PageBody, PlacedPage}; +use craft::theme::Srgba; use craft::ui::canvas::{CanvasTool, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; +use craft::ui::canvas_controls::SelectionOutline; +use craft::ui::choice::{Radio, RadioGroup}; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::form::{Field, FieldGroup, Help}; @@ -13,19 +16,16 @@ use craft::ui::patterns::form_dialogs::FormDialog; use craft::ui::pickers::Select; use craft::ui::primitives::Draw; use craft::ui::runtime::requests::ColorRequest; -use craft::theme::Srgba; use craft::ui::text::{NumberField, TextField}; -use craft::ui::choice::{Radio, RadioGroup}; -use craft::ui::canvas_controls::SelectionOutline; use egui::{Pos2, Rect}; use pdfcraft_engine::{Edit, LinkAction, LinkHighlight, LinkItem, LinkStyle, LinkZoom}; use pdfcraft_render::{DocInfo, LinkTarget}; +use crate::PdfCraftApp; use crate::canvas::DocView; use crate::canvas::page_overlays::LinkEvent; -use crate::PdfCraftApp; use crate::colour_picker::PickerHost; -use crate::colours::{RecentColours, to_rgb}; +use crate::comments::{RecentColours, palette, to_rgb}; /// How far around a link (screen points) the Link tool finds it, so a thin one can be picked. pub(crate) const LINK_TOOL_MARGIN: f32 = 2.0; @@ -318,7 +318,12 @@ fn entries(rows: } /// A row of a labelled select over `rows`: the value picked this pass, if it is not `current`. -fn pick(ui: &mut egui::Ui, label: String, current: T, rows: Vec<(T, String)>) -> Option { +fn pick( + ui: &mut egui::Ui, + label: String, + current: T, + rows: Vec<(T, String)>, +) -> Option { let list = entries(rows); let mut picked = None; Field::new(label.clone()).show(ui, |ui, _| { @@ -364,7 +369,7 @@ fn appearance(ui: &mut egui::Ui, d: &mut LinkDraft, request: &mut Option MeasureTool<'a> { view.cancel(); view.tool = Some(tool); } - view.reads.get_or_insert_with(|| { - JobQueue::new(host.jobs_shared().clone(), wake, QueueOptions { name: "measure-snap", ..QueueOptions::default() }) - }); + view.reads + .get_or_insert_with(|| JobQueue::new(host.jobs_shared().clone(), wake, QueueOptions { name: "measure-snap", ..QueueOptions::default() })); Self { view, doc, pages, info, tool, units, author: author.into(), hover: None, edit: None } } @@ -605,11 +600,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { _ => None, }; let mut tool = None; - let tools = [ - Entry::new(Tool::Distance, tl!("Distance")), - Entry::new(Tool::Perimeter, tl!("Perimeter")), - Entry::new(Tool::Area, tl!("Area")), - ]; + let tools = [Entry::new(Tool::Distance, tl!("Distance")), Entry::new(Tool::Perimeter, tl!("Perimeter")), Entry::new(Tool::Area, tl!("Area"))]; let picked = Segmented::new(tl!("Measure"), Bind::given(current.unwrap_or(Tool::Distance)), &tools).show(ui); if let Some(t) = picked.value().copied() && Some(t) != current @@ -644,10 +635,7 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { .lines([tl!("Shift constrains to 45 degrees. Backspace removes a vertex. Escape cancels.")]) .show(ui); if let Some(reading) = &state.reading { - let mut lines = vec![ - format!("X: {:.3} Y: {:.3}", reading.delta_x, reading.delta_y), - format!("{}: {:.2}°", tl!("Angle"), reading.angle), - ]; + let mut lines = vec![format!("X: {:.3} Y: {:.3}", reading.delta_x, reading.delta_y), format!("{}: {:.2}°", tl!("Angle"), reading.angle)]; if let Some(scale) = &state.scale { lines.push(scale.ratio.clone()); } @@ -727,23 +715,18 @@ pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { match state.listing.as_ref().map(|(_, l)| l) { None => {} Some(Ok(listing)) => { - Notice::new( - Tone::Neutral, - crate::i18n::fmt(tl!("Saved measurements: {n}"), &[("n", &listing.measurements.len().to_string())]), - ) - .show(ui); + Notice::new(Tone::Neutral, crate::i18n::fmt(tl!("Saved measurements: {n}"), &[("n", &listing.measurements.len().to_string())])).show(ui); if !listing.unsupported.is_empty() { let reasons: Vec = listing .unsupported .iter() - .map(|u| crate::i18n::fmt(tl!("Page {page}: {reason}"), &[("page", &u.page.saturating_add(1).to_string()), ("reason", &u.reason)])) + .map(|u| { + crate::i18n::fmt(tl!("Page {page}: {reason}"), &[("page", &u.page.saturating_add(1).to_string()), ("reason", &u.reason)]) + }) .collect(); - Notice::new( - Tone::Warn, - crate::i18n::fmt(tl!("Unsupported measurements: {n}"), &[("n", &listing.unsupported.len().to_string())]), - ) - .lines(reasons) - .show(ui); + Notice::new(Tone::Warn, crate::i18n::fmt(tl!("Unsupported measurements: {n}"), &[("n", &listing.unsupported.len().to_string())])) + .lines(reasons) + .show(ui); } if !listing.measurements.is_empty() { let source = MeasurementRows(listing.measurements.len()); @@ -870,7 +853,9 @@ fn export_csv(app: &mut PdfCraftApp) { let Some(path) = picked.first_path() else { return }; // A browser answers with a name, not a path to write: the files service hands the bytes over as a download. let written = match picked { - Picked::Paths(_) => craft::atomic::atomic_write(&path, csv.as_bytes()).map(|()| tl!("Saved measurements.")).map_err(|e| e.to_string()), + Picked::Paths(_) => { + craft::atomic::atomic_write(&path, csv.as_bytes()).map(|()| tl!("Saved measurements.")).map_err(|e| e.to_string()) + } _ => app .host .files()