PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Reconcile typed font sizes and Fill & Sign colours with current UI
FredApps6b38a5ab47e5
diff --cc ROADMAP.mdindex b217ea8f5,f5de8044e..be3171bb9--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -1,10 -1,40 +1,42 @@@# PdfCraft roadmap+> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (typed small Edit font sizes and Fill & Sign text/date colour, #2444/#2496; estimates unchanged)+**Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away+ > **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged)+ > **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)+ > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)+ > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)+ > **Last reviewed:** 2026-10-23 | **Last updated:** 2026-10-23 | **Change:** minor (M10: Word table cells use the widths of their own grid columns; estimates unchanged)+ > **Last reviewed:** 2026-10-23 | **Last updated:** 2026-10-23 | **Change:** minor (M10: table spans retain text from covered slots in Office exports; estimates unchanged)+ > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M10: image export preserves soft-mask Decode opacity ranges; estimates unchanged)+ > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M10: vector printing preserves existing page XObjects when adding annotation appearances; estimates unchanged)+ > **Last reviewed:** 2026-10-21 · **Last updated:** 2026-10-21 · **Change:** minor (M3, #3808: the Pages inspector has an independent 50–150% thumbnail size slider and buttons; selection and current-page following are retained, with headless ui.set coverage. Estimates unchanged.)+ > **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M11 #3507: image merging preserves content stream boundaries; estimates unchanged)+ > **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M10, #3532 partial: vector printing retains existing appearances with absent Subtype; estimates unchanged)+ > **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-17 · **Change:** minor (M8, gap 6 #2662: the redaction audit counts a cover over one word of a long line; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-20 · **Last updated:** 2026-10-20 · **Change:** minor (M12 #3673: Character encoding accepts Identity-H/V with Adobe CJK collections; estimates unchanged)+ > **Last reviewed:** 2026-10-20 · **Last updated:** 2026-10-20 · **Change:** minor (M2, #3601: missing spacing glyphs in non-embedded Japanese CID substitutes draw as blanks while PDF widths and Unicode stay unchanged; estimates unchanged)+ > **Last reviewed:** 2026-10-20 · **Last updated:** 2026-10-20 · **Change:** minor (M3, #3541/#3620: comment hover follows individual marked lines and original annotation paint order; estimates unchanged)+ > **Last reviewed:** 2026-10-20 - **Last updated:** 2026-10-20 - **Change:** minor (M6, #3502: form detection uses the existing content-stream boundary policy; estimates unchanged)+ > **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M2, #3574: named form properties retain page origin and own dictionary boundaries; estimates unchanged)+ > **Last reviewed:** 2026-10-20 · **Last updated:** 2026-10-20 · **Change:** minor (M4: initial-view options resolve indirect boolean preferences; estimates unchanged)+ > **Last reviewed:** 2026-10-16; **Last updated:** 2026-10-16; **Change:** minor (M5 #2669, item 5: reply groups and page root counts per frame; estimates unchanged)+ > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M7: the Edit text caret is as tall as the row it is on; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M6: CSV tab-containing headers; estimates unchanged)+ > **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (M3, #3149: discard render demand after page geometry changes and check the GPU texture limit before upload; estimates unchanged)+ > **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (M4, #1919: repeated page indices accumulate rotations; M3, #3149: discard render demand after page geometry changes and check the GPU texture limit before upload; estimates unchanged)+ > **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (M8, #1350: named replacement descriptions retired during Sanitize and across shared resources; estimates unchanged)+ > **Last reviewed:** 2026-10-17 · **Last updated:** 2026-10-17 · **Change:** minor (M4 #2997: Ctrl-drag (Option on macOS) in the Organize grid copies the pages into the drop gap; `page_duplicate` takes `at`; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M6: AcroForm XML text; estimates unchanged)> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M2/gap 12: the Annex D.2 alias codes read as the ink they draw in both tables; the text oracle scores reading order; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M14/#2383 GPU-limit candidate; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (M4: indirect page rotations; M13: CLI check visits each directory once through aliases and cycles; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (M6: preserve XML/XFDF attribute whitespace; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** minor (M1: raw-deflate fallback preserves decoding-limit errors; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-16 | **Last updated:** 2026-10-16 | **Change:** minor (M10 #1201 partial: lossless image Decode; estimates unchanged) | **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)+ > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-16 · **Change:** minor (M14: Czech catalog completed and reviewed; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-14 · **Change:** minor (M14: the Italian catalog has every entry the other catalogs had and the code looks up; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** minor (M3 #2080 candidate: explicit search jumps join per-tab history; rail and control-channel Back/Forward; estimates unchanged)> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (M4 #1910: Organize Pages opens on the current page; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)diff --cc crates/automation/src/comments.rsindex 481d75f74,015000109..f87fd0b58--- a/crates/automation/src/comments.rs+++ b/crates/automation/src/comments.rs@@@ -555,14 -576,10 +580,13 @@@ impl Automation"line" => FillMark::Line,other => return Err(ToolError::InvalidArgs(format!("unknown type {other:?}"))),};- let (w, h) = if mark == FillMark::Line { (36.0, 4.0) } else { (12.0, 12.0) };- (Shape::Mark { rect: [at[0] - w / 2.0, at[1] - h / 2.0, at[0] + w / 2.0, at[1] + h / 2.0], mark }, String::new())+ (Shape::Mark { rect: mark.rect_at(at, i64::from(info.rotation)), mark }, String::new())}};- let style = Style::default_for(&shape);+ let mut style = Style::default_for(&shape);+ if let Some(color) = requested_color {+ style.color = color;+ }self.apply(a, Edit::AddAnnotation(NewAnnotation { page, shape, style, contents, author }))}diff --cc crates/ui-egui/src/app.rsindex 000000000,23bee9bab..946491c02mode 000000,100644..100644--- a/crates/ui-egui/src/app.rs+++ b/crates/ui-egui/src/app.rs@@@ -1,0 -1,622 +1,623 @@@+ use super::hooks::OsEvent;+ use super::state::{+ Dialog, DocumentCopyJob, GridFile, LeftPanel, LinkOrigin, Mode, NumberDraft, PasswordPrompt, PendingLink, PropsTab, QuickTool, RecentFile,+ RightPanel, UnlockPrompt,+ };+ #[cfg(not(target_arch = "wasm32"))]+ use super::state::{OpenOutcome, OpenRequest, PendingRemoteLink};+ use super::*;++ mod clipboard;+ mod commands;+ mod control;+ mod files;+ mod frame;+ mod input;+ mod keys;+ mod links;+ mod prefs;+ mod window;++ pub(crate) use clipboard::{copy_refused, print_refused};+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) use files::same_file;+ use frame::migrate_panel_state;+ pub(crate) use prefs::{MAX_AUTHOR_CHARS, date_text_for_pdf};++ impl Default for PdfCraftApp {+ fn default() -> Self {+ Self::new()+ }+ }++ impl PdfCraftApp {+ /// Construct an application with the default session, panels, theme and control state.+ pub fn new() -> Self {+ Self {+ session: Session::new(),+ views: Vec::new(),+ closed_tabs: Vec::new(),+ active: None,+ mode: Mode::AllTools,+ default_mode: Mode::AllTools,+ view_defaults: Default::default(),+ units: Default::default(),+ date_format_draft: None,+ mode_override: None,+ left: LeftPanel::AllTools,+ side_panels: Default::default(),+ left_open: true,+ right: None,+ last_right: RightPanel::Comments,+ right_before_read: None,+ comments_panel_closed: false,+ right_panel_closed: false,+ quick_tool: QuickTool::Select,+ space_hand: None,+ full_screen_tool: None,+ comment_prefs: Default::default(),+ theme: ThemeKind::Light,+ // A fresh install follows the desktop's appearance (#1248); saved settings override.+ theme_preference: ThemePreference::System,+ reading_colors: Default::default(),+ #[cfg(target_os = "linux")]+ desktop_theme: None,+ #[cfg(target_os = "linux")]+ desktop_theme_enabled: false,+ scroll_speed: scroll_speed::ScrollSpeed::default(),+ animation_effects: motion::AnimationEffects::default(),+ motion: motion::Motion::default(),+ language: i18n::AUTO.to_string(),+ ui_scale: None,+ system_text_scale: 1.0,+ ui_scale_applied: None,+ flatten_fill_sign_on_save: false,+ fill_text_size: fill_sign::TEXT_SIZE,++ fill_text_color: [0.0; 3],+ dialog: None,+ updates: updates::Updates::default(),+ printer_source: None,+ options_source: None,+ print_tasks: print_ui::PrintTasks::default(),+ palette_open: false,+ palette_query: String::new(),+ all_tools_expanded: false,+ all_tools_full: false,+ all_tools_query: String::new(),+ all_tools_tab: (None, false),+ recent: Vec::new(),+ reopen_last_session: false,+ restore_last_view: true,+ last_views: Vec::new(),+ last_session: Default::default(),+ quit_session: None,+ reload_changed_files: true,+ show_secured_notice: true,+ always_default_view: false,+ #[cfg(not(target_arch = "wasm32"))]+ watch: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ open_worker: None,+ #[cfg(not(target_arch = "wasm32"))]+ pending_opens: Vec::new(),+ #[cfg(not(target_arch = "wasm32"))]+ next_open_token: 0,+ #[cfg(all(test, not(target_arch = "wasm32")))]+ open_prepare_gate: None,+ pinned: Default::default(),+ toast: None,+ toast_script: None,+ script_messages: std::collections::VecDeque::new(),+ script_messages_dropped: 0,+ toast_dropped: 0,+ integrated_titlebar: false,+ window_controls: None,+ system_title_bar: false,+ app_frame_shown: None,+ password_prompt: None,+ document_copy: None,+ unlock_prompt: None,+ full_screen: false,+ inbox: Default::default(),+ startup_inbox: Default::default(),+ startup_superseded: false,+ failed_inbox: Default::default(),+ unsaved_flag: Default::default(),+ os_events: None,+ host_save: None,+ host_dirty: None,+ close_request: None,+ save_prompt_button: Default::default(),+ save_prompt_seen: false,+ save_prompt_attention: false,+ #[cfg(not(target_arch = "wasm32"))]+ pending_overwrite: None,+ save_override: None,+ props_draft: None,+ view_draft: None,+ custom_draft: None,+ requests: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ pickers: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ pick_override: None,+ export_dir_override: None,+ split_draft: SplitDraft::default(),+ extract_draft: ExtractDraft::default(),+ rotate_draft: RotateDraft::default(),+ summary_sort: Default::default(),+ sign_draft: None,+ digital_ids: Vec::new(),+ sig_expanded: Vec::new(),+ a11y_options: a11y_ui::A11yOptions::default(),+ ocr_draft: ocr_ui::OcrDraft::default(),+ ocr_run: None,+ ocr_batch: None,+ run_inline: false,+ custom_actions: Vec::new(),+ wizard: Default::default(),+ action_run: None,+ action_files_override: None,+ pdfa: Default::default(),+ compare_old: None,+ compare: None,+ js_console: Default::default(),+ doc_js: Default::default(),+ a11y: a11y_ui::A11yState::default(),+ tags_state: Default::default(),+ a11y_skipped: Default::default(),+ alt_draft: Default::default(),+ os_key_store_ids: false,+ cert_viewer: None,+ space_audit: Vec::new(),+ space_audit_of: None,+ combine_draft: Vec::new(),+ combine_conflicts: Default::default(),+ combine_tab: Default::default(),+ combine_columns: Default::default(),+ combine_view: Default::default(),+ combine_zoom: 1.0,+ organize_zoom: 1.0,+ combine_thumbs: Default::default(),+ image_import: None,+ custom_stamps: Vec::new(),+ stamp_draft: Default::default(),+ optimize_draft: OptimizeDraft::default(),+ optimize_run: None,+ progress_notice: None,+ page_clipboard: None,+ grid_drop: None,+ last_snapshot: None,+ last_copied_image: None,+ last_copied_file: None,+ system_clipboard: true,+ clipboard_override: None,+ v_pressed: false,+ attach_override: None,+ duplicate_draft: None,+ page_props_draft: None,+ field_table_draft: None,+ form_preview: false,+ window_title: String::new(),+ recovery: None,+ recoverable: Vec::new(),+ recovery_keys: Default::default(),+ last_autosave: None,+ allow_quit: false,+ deferred_commands: Vec::new(),+ native_menu: None,+ menu_input: Vec::new(),+ dialog_seen: None,+ dialog_epoch: 0,+ ctx: None,+ #[cfg(not(target_arch = "wasm32"))]+ window_state: Default::default(),+ styled: false,+ fonts_ready: false,+ fonts_cjk: theme::CjkPreference::Default,+ control: None,+ bookmark_rename: None,+ last_opened_url: None,+ community_card_closed: false,+ pending_link: None,+ pending_full_screen: None,+ pending_remote_link: None,+ protect_draft: Default::default(),+ text_style_draft: Default::default(),+ boxes_draft: Default::default(),+ marks_draft: Default::default(),+ unmarked_page: Default::default(),+ export_draft: Default::default(),+ export_status: None,+ signature: None,+ initials: None,+ signature_draft: Default::default(),+ signature_preview: None,+ signature_photo: None,+ saved_signature_previews: [None, None],+ sign_graphic: sign_ui::SignGraphic::Name,+ sign_graphic_preview: None,+ #[cfg(target_arch = "wasm32")]+ signature_images: Default::default(),+ comment_props: None,+ field_props: None,+ bulk_field_props: None,+ redact_prefs: RedactPrefs::default(),+ redact_defaults: RedactPrefs::default(),+ redact_before: None,+ redact_pages_draft: RedactPagesDraft::default(),+ redact_search: RedactSearchDraft::default(),+ hidden_draft: HiddenDraft::default(),+ print_draft: PrintDraft::default(),+ link_draft: None,+ text_style: content_ui::default_style(),+ replace_draft: None,+ number_draft: NumberDraft { from: 1, to: 1, style: pdfcraft_engine::LabelStyle::Decimal, prefix: String::new(), start: 1 },+ word_count_draft: word_count_ui::Draft::default(),+ }+ }++ /// Fields are being edited (Prepare a form or its Calculation order is open, or a field tool+ /// is picked), unless the form is being previewed.+ pub fn is_preparing(&self) -> bool {+ ((self.left_open && matches!(self.left, LeftPanel::Tool("form") | LeftPanel::CalculationOrder))+ || matches!(self.quick_tool, QuickTool::Field(_)))+ && !self.form_preview+ }++ /// A number that changes whenever the open dialog changes (opened, closed or replaced by+ /// another), checked every frame. A picker started from a dialog's Browse… button answers+ /// only into the same showing of that dialog.+ pub(crate) fn dialog_epoch(&mut self) -> u64 {+ if self.dialog != self.dialog_seen {+ self.dialog_seen = self.dialog;+ self.dialog_epoch = self.dialog_epoch.wrapping_add(1);+ }+ self.dialog_epoch+ }++ pub fn active_ids(&self) -> Option<(usize, DocId)> {+ self.active.and_then(|i| self.views.get(i).map(|v| (i, v.id)))+ }++ /// 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.dialog.is_some()+ || self.close_request.is_some()+ || self.password_prompt.is_some()+ || self.unlock_prompt.is_some()+ || self.pending_link.is_some()+ || self.pending_remote_link.is_some()+ || self.updates.open+ }++ /// Show `msg` in the toast now, in place of whatever it showed. Script messages still waiting+ /// show after it.+ pub fn notify(&mut self, msg: impl Into<String>) {+ // A left-out count it replaces is said again once the toast is free.+ self.script_messages_dropped = self.script_messages_dropped.saturating_add(std::mem::take(&mut self.toast_dropped));+ self.toast = Some((msg.into(), 0.0));+ self.toast_script = None;+ }++ /// Notify with a static message in the UI language.+ pub fn notify_tr(&mut self, text: &str) {+ self.notify(tl!(text).to_string());+ }++ /// Notify with an error's own text. Engine and OS messages are not translated: matching their+ /// English wording would break silently whenever it changes.+ pub fn notify_error(&mut self, error: impl std::fmt::Display) {+ self.notify(error.to_string());+ }++ /// Notify with a `{name}`-style template in the UI language (placeholders filled once).+ pub fn notify_fmt(&mut self, template: &str, args: &[(&str, &str)]) {+ self.notify(i18n::fmt(tl!(template), args));+ }++ /// `true` while any open document still waits for page renders (used by headless capture).+ pub fn render_pending(&self) -> bool {+ self.views.iter().any(|v| v.render_pending())+ }+ }++ impl eframe::App for PdfCraftApp {+ /// While files are dragged over the window the system sends no pointer moves, so egui+ /// would keep the place the pointer entered at: tell it where the pointer really is, so the+ /// page grid can show (and use) the gap under it.+ fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {+ // The button's release a window move or resize kept from egui.+ window_controls::release_after_desktop_grab(ctx, raw);+ self.prepare_raw_input(ctx, raw);+ if raw.hovered_files.is_empty() && raw.dropped_files.is_empty() {+ return;+ }+ if let Some(pos) = drag_pointer::in_window(ctx) {+ raw.events.push(egui::Event::PointerMoved(pos));+ }+ ctx.request_repaint();+ }++ fn save(&mut self, storage: &mut dyn eframe::Storage) {+ // eframe has just stored the window as it is now: not while it is minimized.+ #[cfg(not(target_arch = "wasm32"))]+ {+ let minimized = self.ctx.as_ref().is_some_and(|c| c.input(|i| i.viewport().minimized == Some(true)));+ self.window_state.keep(storage, minimized);+ }+ storage.set_string("pdfcraft", self.persist());+ }++ /// Each frame's work before drawing: opens, operating-system and control-channel requests,+ /// the quit guard, shortcuts, and the background jobs' results.+ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {+ self.ctx = Some(ctx.clone());+ #[cfg(not(target_arch = "wasm32"))]+ self.window_state.repair(ctx);+ self.dialog_epoch();+ // Notices raised outside `ui` (opened files, OS events, the control channel) translate too.+ let lang = i18n::Lang::from_pref(&self.language);+ i18n::set_current(lang);+ #[cfg(not(target_arch = "wasm32"))]+ {+ if let Some(worker) = &self.open_worker {+ worker.set_context(ctx);+ }+ self.poll_pending_opens();+ }+ // Chinese wants its own faces before the Japanese ones (one baseline per line).+ let cjk = theme::CjkPreference::for_language(lang.code());+ if !self.styled {+ egui_extras::install_image_loaders(ctx);+ theme::install_fonts_for(ctx, cjk);+ self.fonts_cjk = cjk;+ theme::apply(ctx, self.theme);+ self.styled = true;+ } else {+ self.fonts_ready = true;+ if cjk != self.fonts_cjk {+ // Same family names as before, so named fonts stay valid while the new set loads.+ theme::install_fonts_for(ctx, cjk);+ self.fonts_cjk = cjk;+ }+ }+ self.sync_theme(ctx);+ let native = ctx.native_pixels_per_point().unwrap_or(1.0);+ ui_scale::sync(ctx, ui_scale::zoom(self.ui_scale, self.system_text_scale, native), &mut self.ui_scale_applied);+ // Remember user work even if its tab is subsequently closed or Home is selected.+ self.startup_superseded |= !self.views.is_empty() || self.combine_showing() || self.dialog.is_some() || self.password_prompt.is_some();+ // Also done in `raw_input_hook`, before input; here for hosts that don't call the hook.+ self.scroll_speed.set_line_speed(ctx);+ // Motion reads this frame's wheel input, so it begins in `ui`, in a known UI phase:+ // `logic` also runs alone while hidden, where the input events and time are stale.+ // Before taking this frame's drop: the grid must be drawn once with the pointer where+ // the files were let go before the gap is read.+ self.finish_grid_drop(ctx);+ // Showing a document hides the Combine files tab.+ if self.active.is_some() {+ self.combine_tab.focused = false;+ }+ #[cfg(target_arch = "wasm32")]+ self.process_signature_images();+ let dropped = ctx.input(|i| i.raw.dropped_files.clone());+ #[cfg(not(target_arch = "wasm32"))]+ let dropped = self.drop_on_signature_pad(dropped);+ #[cfg(not(target_arch = "wasm32"))]+ let dropped = self.drop_on_grid(dropped, ctx);+ for f in dropped {+ // Files dropped on the Combine files tab join its list instead of opening.+ if self.combine_showing() {+ self.drop_into_combine(f, ctx);+ } else {+ self.open_dropped(f, ctx);+ }+ }+ let arrived: Vec<(String, Vec<u8>)> = self.inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, bytes) in arrived {+ if let Err(e) = self.open_bytes(&name, None, bytes) {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e.to_string())]);+ }+ }+ // Don't replace a pending prompt or import. A startup file may need its own password+ // prompt, so its bytes stay queued until the current interaction finishes.+ #[cfg(not(target_arch = "wasm32"))]+ let opening = !self.pending_opens.is_empty();+ #[cfg(target_arch = "wasm32")]+ let opening = false;+ if !opening+ && self.password_prompt.is_none()+ && self.image_import.is_none()+ && self.dialog.is_none()+ && self.close_request.is_none()+ && self.pending_link.is_none()+ && self.pending_remote_link.is_none()+ {+ let startup = self.startup_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, bytes) in startup {+ let activate = !self.startup_superseded;+ if let Err(e) = self.open_bytes_with_focus(&name, None, bytes, activate) {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);+ }+ }+ }+ let failed: Vec<(String, String)> = self.failed_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, e) in failed {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);+ }+ let os_events = self.os_events.as_mut().map(|poll| poll()).unwrap_or_default();+ for e in os_events {+ match e {+ #[cfg(not(target_arch = "wasm32"))]+ OsEvent::Open(paths) => {+ paths.iter().for_each(|p| {+ self.open_path(p);+ });+ // Files handed to the running app (Finder, or another launch): bring its+ // window to the front, also when minimized or full screen on another Space.+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));+ ctx.send_viewport_cmd(egui::ViewportCommand::Focus);+ }+ #[cfg(target_arch = "wasm32")]+ OsEvent::Open(_) => {}+ // Like closing the window: `guard_quit` asks about unsaved changes.+ OsEvent::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),+ }+ }+ if let Some((_, id)) = self.active_ids() {+ let out = self.session.take_js_output(id);+ self.handle_js(id, out);+ }+ if let Some(mut control) = self.control.take() {+ control.tick(ctx, self);+ self.control = Some(control);+ }+ self.guard_quit(ctx);+ // macOS: quit through `terminate:` instead of dropping the window (Touch Bar crash, #1136).+ #[cfg(target_os = "macos")]+ craft_quit::on_close_request(ctx);+ self.autosave_tick(ctx, web_time::Instant::now());+ // Reload documents whose files a build rewrote (#431).+ #[cfg(not(target_arch = "wasm32"))]+ self.watch_files();+ if self.host_dirty.is_some() {+ let dirty = self.first_dirty().is_some();+ if let Some(report) = self.host_dirty.as_mut() {+ report(dirty);+ }+ }+ self.poll_updates();+ self.poll_print();+ // Shortcuts deferred last frame: the text field has taken that frame's typing since.+ let deferred = std::mem::take(&mut self.deferred_commands);+ self.native_menu_clicks(ctx);+ // The keys a menu click stands for (⌘C, Delete…), before anything reads this frame's keys.+ if !self.menu_input.is_empty() {+ let events = std::mem::take(&mut self.menu_input);+ ctx.input_mut(|i| i.events.extend(events));+ }+ self.shortcuts(ctx);+ // 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);+ for (index, view) in self.views.iter_mut().enumerate() {+ view.objects.set_input_blocked(blocked || self.active != Some(index));+ if blocked || self.active != Some(index) {+ view.auto_scroll.cancel();+ }+ }+ // A field that refused its value this frame keeps the shortcut from saving or printing+ // behind the user's back; so does a save prompt opened since.+ if self.process_pending_edits() && self.close_request.is_none() {+ for (id, doc) in deferred {+ // Only in the document the shortcut was pressed in.+ if self.active_ids().map(|(_, active)| active) == doc {+ self.execute(id);+ }+ }+ }+ self.poll_export();+ self.auto_ocr_scanned_page();+ self.poll_ocr();+ self.poll_optimize();+ self.poll_action();+ self.process_file_requests();+ #[cfg(not(target_arch = "wasm32"))]+ self.process_picked();+ // Last, after everything that can open or answer the "save changes?" question.+ self.attend_save_prompt(ctx);+ self.sync_native_menu(ctx);+ }++ fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {+ let ctx = ui.ctx().clone();+ i18n::set_current(i18n::Lang::from_pref(&self.language));+ // A language change switches stock chrome between LTR and RTL before anything is drawn.+ theme::sync_direction(&ctx);+ // Fonts registered via set_fonts only take effect next frame; named families would panic now.+ if !self.fonts_ready {+ ctx.request_repaint();+ return;+ }+ // Before any widget reads this frame's wheel input or draws.+ self.motion.begin_pass(&ctx, self.animation_effects);+ // One-time 0.36 -> 0.37 panel persistence migration, before any panel stores or reads state.+ migrate_panel_state(ui);+ for view in &mut self.views {+ view.begin_render_frame();+ }+ // The window shows the active document's name (or title, if it asks for that).+ let title = self+ .active+ .and_then(|i| crate::canvas::tab_label(self, i))+ .or_else(|| self.combine_showing().then(|| tl!("Combine files").to_owned()))+ .map_or_else(|| "PdfCraft".to_owned(), |name| format!("{name} — PdfCraft"));+ if title != self.window_title {+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));+ self.window_title = title;+ }+ // The accessible window takes the same name, so a screen reader (AT-SPI on Linux, UIA on+ // Windows) can tell it apart (#4614). egui builds the root node afresh every pass.+ ctx.accesskit_node_builder(egui::accesskit_root_id(), |root| root.set_label(self.window_title.as_str()));+ if self.full_screen && self.active.is_some() {+ // Full screen: the page on black, nothing else, as Acrobat's Full Screen Mode (Esc+ // or ⌘L to leave).+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(egui::Color32::BLACK)).show(ui, |ui| {+ if let Some(i) = self.active {+ match compare_ui::side_by_side(self, i) {+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),+ None => canvas::document_area(self, i, ui),+ }+ }+ });+ dialogs::show(self, &ctx);+ // Notices too: a refused field value or a failed save must be seen in full screen.+ self.show_progress(&ctx);+ widgets::toast(self, &ctx);+ self.finish_render_frame(&ctx);+ if let Some(mut control) = self.control.take() {+ control.finish_frame(&ctx, self);+ self.control = Some(control);+ }+ return;+ }+ self.sync_window_frame(&ctx);+ if self.draws_window_frame() {+ window_controls::resize_edges(&ctx);+ }+ chrome::tab_strip(self, ui);+ chrome::mode_bar(self, ui);+ // Whichever way another tab came to the front, it shows instead of the expanded view.+ if self.all_tools_full && self.all_tools_tab != self.shown_tab() {+ self.all_tools_full = false;+ }+ side_panels::show(self, ui);+ let t = theme::Tokens::get(&ctx);+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| {+ if self.mode == Mode::AllTools && self.all_tools_full {+ all_tools_ui::show(self, ui);+ } else {+ match self.active {+ None if self.combine_showing() => combine_ui::page(self, ui),+ None => home::show(self, ui),+ Some(index) => match compare_ui::side_by_side(self, index) {+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),+ None => canvas::document_area(self, index, ui),+ },+ }+ }+ });+ self.process_pending_edits();+ palette::show(self, &ctx);+ dialogs::show(self, &ctx);+ self.show_progress(&ctx);+ widgets::toast(self, &ctx);+ self.finish_render_frame(&ctx);+ // Screenshots are issued only after a settled pass that really drew the window.+ if let Some(mut control) = self.control.take() {+ control.finish_frame(&ctx, self);+ self.control = Some(control);+ }+ }+ }diff --cc crates/ui-egui/src/app/prefs.rsindex 000000000,f64ba6d89..e5eaae586mode 000000,100644..100644--- a/crates/ui-egui/src/app/prefs.rs+++ b/crates/ui-egui/src/app/prefs.rs@@@ -1,0 -1,362 +1,368 @@@+ use super::*;++ /// [`PdfCraftApp::date_text`] for callers that already borrow other parts of the app.+ pub(crate) fn date_text(session: &Session, fmt: Option<&str>) -> Result<String, String> {+ let lang = session.date_language().unwrap_or(i18n::current().code());+ session.today_text(fmt, Some(lang))+ }++ /// Today in Preferences ▸ Date format for stamping into a PDF; refused when it has characters+ /// Fill & Sign can't write yet (see [`pdfcraft_engine::dates::unwritable`]).+ pub(crate) fn date_text_for_pdf(session: &Session) -> Result<String, String> {+ let lang = session.date_language().unwrap_or(i18n::current().code());+ session.today_text_for_pdf(None, Some(lang))+ }++ /// The longest author name kept (Preferences ▸ Identity, restored settings).+ pub(crate) const MAX_AUTHOR_CHARS: usize = 200;++ /// A restored colour: an `[r, g, b]` array of finite numbers, each clamped to 0–1 (restored+ /// settings are untrusted). Anything else (a string, a wrong length, a null or a non-finite+ /// number) is refused whole, so the caller keeps its default.+ fn rgb_triple(v: &serde_json::Value) -> Option<[f64; 3]> {+ let a = v.as_array()?;+ if a.len() != 3 {+ return None;+ }+ let mut out = [0.0f64; 3];+ for (slot, x) in out.iter_mut().zip(a.iter()) {+ let n = x.as_f64()?;+ if !n.is_finite() {+ return None;+ }+ *slot = n.clamp(0.0, 1.0);+ }+ Some(out)+ }++ impl PdfCraftApp {+ pub fn set_theme_preference(&mut self, preference: ThemePreference) {+ self.theme_preference = preference;+ if let Some(ctx) = self.ctx.clone() {+ self.sync_theme(&ctx);+ theme::apply(&ctx, self.theme);+ } else {+ self.theme = preference.resolve(None, ThemeKind::Light);+ }+ }++ /// The app-wide reading-colours preference: sets it and applies it to every open document,+ /// not just the active one (Preferences ▸ Reading colours, Acrobat's Replace Document+ /// Colors). A document the change actually touches re-renders.+ pub fn set_reading_colors(&mut self, colors: pdfcraft_render::ReadingColors) {+ self.reading_colors = colors;+ for i in 0..self.views.len() {+ // Idempotent per document: the engine says whether anything changed.+ if self.session.set_reading_colors(self.views[i].id, colors) {+ self.views[i].invalidate_content();+ }+ }+ }++ /// Enable the Linux desktop portal in a native window. Headless contexts keep+ /// their supplied input and never connect to the user's session bus.+ #[cfg(target_os = "linux")]+ pub fn enable_desktop_theme(&mut self) {+ self.desktop_theme_enabled = true;+ }++ /// Today in `fmt` (or Preferences ▸ Date format), with month and weekday names in the date+ /// language, or the interface language when it follows that.+ pub fn date_text(&self, fmt: Option<&str>) -> Result<String, String> {+ date_text(&self.session, fmt)+ }++ /// Serialize the user's persistent state (recent files, theme). Local only.+ pub fn persist(&self) -> String {+ let trusted: Vec<String> = self.session.trusted_certificates().iter().map(pdfcraft_engine::sign::x509::to_pem).collect();+ let mut v = serde_json::json!({+ "side_panels": self.side_panels.to_json(self.left_open),+ "docking_right": self.right,+ "recent": self.recent,+ "reopen_last_session": self.reopen_last_session,+ "restore_last_view": self.restore_last_view,+ "last_views": self.last_views_to_save(),+ // Kept only while the preference is on.+ "last_session": self.reopen_last_session.then(|| self.session_to_save()),+ "reload_changed_files": self.reload_changed_files,+ "system_title_bar": self.system_title_bar,+ "pinned_folders": self.pinned.folders,+ "theme": self.theme_preference,+ "scroll_speed": self.scroll_speed,+ "animation_effects": self.animation_effects,+ "default_mode": self.default_mode,+ "default_layout": canvas::display_token(self.view_defaults.layout, self.view_defaults.continuous),+ "default_zoom": self.view_defaults.zoom_name(),+ "always_default_view": self.always_default_view,+ "highlight_fields": self.view_defaults.highlight_fields,+ "units": self.units,+ "language": self.language,+ "reading_colors": self.reading_colors,+ // Null follows the system's text scaling.+ "ui_scale": self.ui_scale,+ "flatten_fill_sign": self.flatten_fill_sign_on_save,+ "fill_text_size": self.fill_text_size,+ "date_format": self.session.date_format(),+ // Null follows the interface language.+ "date_language": self.session.date_language(),+ "author": self.comment_prefs.author,+ // Per-tool comment defaults (colours, opacity, widths), so Make Current+ // Properties Default survives a restart (#340).+ "comment_styles": self+ .comment_prefs+ .styles()+ .map(|(t, s)| serde_json::json!({+ "tool": t.command(),+ "color": s.color,+ "opacity": s.opacity,+ "width": s.width,+ "fill": s.fill,+ }))+ .collect::<Vec<_>>(),+ // Drawn signatures keep their original form (older settings read the same).+ "signature": match &self.signature { Some(fill_sign::SavedSig::Drawn(s)) => Some(s), _ => None },+ "signature_text": match &self.signature { Some(fill_sign::SavedSig::Typed(t)) => Some(t), _ => None },+ "signature_image": match &self.signature { Some(s @ fill_sign::SavedSig::Image(_)) => Some(s), _ => None },+ "initials": self.initials,+ "sign_graphic": self.sign_graphic,+ // macOS Keychain and Windows store identities are read from their OS key stores each time.+ "digital_ids": self.digital_ids.iter().filter(|e| !e.path.starts_with("keychain:") && !e.path.starts_with("windows:")).collect::<Vec<_>>(),+ "trusted": trusted,+ "custom_stamps": stamps_ui::encode(&self.custom_stamps),+ "javascript": self.session.javascript(),+ "actions": actions_ui::encode(&self.custom_actions),+ "combine_columns": self.combine_columns.to_json(),+ "combine_view": self.combine_view.as_str(),+ "combine_zoom": self.combine_zoom,+ "comments_panel_closed": self.comments_panel_closed,+ "right_panel_closed": self.right_panel_closed,+ });+ // Set apart: one more key inside the macro above passes serde_json's recursion limit.+ v["default_page_gaps"] = serde_json::Value::Bool(self.view_defaults.show_page_gaps);++ v["fill_text_color"] = serde_json::json!(self.fill_text_color);+ v["redact_prefs"] = self.redact_defaults.to_json();+ // Set outside json! above, which is at serde_json's macro recursion limit.+ v["hide_empty_highlight_hover"] = serde_json::Value::Bool(self.comment_prefs.hide_empty_highlight_hover);+ v["comment_tool_pinned"] = serde_json::Value::Bool(self.comment_prefs.pinned);+ v["show_secured_notice"] = serde_json::Value::Bool(self.show_secured_notice);+ v["organize_zoom"] = serde_json::json!(self.organize_zoom);+ // Canonical names survive changes to the order of PAPERS and do not depend on UI language.+ v["print_paper"] = serde_json::json!(pdfcraft_engine::print::PAPERS.get(self.print_draft.paper).map(|(name, _)| *name));+ v.to_string()+ }++ /// Restore state written by `persist`. Unknown or malformed data is ignored.+ pub fn restore(&mut self, json: &str) {+ let Ok(v) = serde_json::from_str::<serde_json::Value>(json) else { return };+ let panels = side_panels::restore(&v);+ self.side_panels = panels.panels;+ if let Some(open) = panels.tools_open {+ self.left_open = open;+ }+ if let Some(right) = v.get("docking_right") {+ self.right = serde_json::from_value(right.clone()).ok().flatten().filter(|_| !panels.side_closed);+ }+ self.combine_columns = combine_ui::Columns::from_json(&v["combine_columns"]);+ if let Some(view) = v["combine_view"].as_str().and_then(combine_ui::CombineView::parse) {+ self.combine_view = view;+ }+ if let Some(zoom) = v["combine_zoom"].as_f64() {+ self.set_combine_zoom(zoom as f32);+ }+ // Clamped like any grid zoom when the grid next shows; nonsense keeps the usual size.+ if let Some(zoom) = v["organize_zoom"].as_f64().map(|z| z as f32).filter(|z| z.is_finite()) {+ self.organize_zoom = zoom.clamp(*canvas::GRID_ZOOM_RANGE.start(), *canvas::GRID_ZOOM_RANGE.end());+ }+ if let Ok(r) = serde_json::from_value::<Vec<RecentFile>>(v["recent"].clone()) {+ // Only keep entries whose files still exist.+ #[cfg(not(target_arch = "wasm32"))]+ let r: Vec<RecentFile> = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect();+ self.recent = r;+ }+ self.restore_layout_prefs(&v);+ self.restore_behavior_prefs(&v);+ self.restore_view_prefs(&v);+ self.restore_comment_prefs(&v);+ self.restore_signature_prefs(&v);+ }++ /// The panels, combine view, zoom and recent files.+ fn restore_layout_prefs(&mut self, v: &serde_json::Value) {+ if let Some(on) = v["reopen_last_session"].as_bool() {+ self.reopen_last_session = on;+ }+ if let Some(on) = v["restore_last_view"].as_bool() {+ self.restore_last_view = on;+ }+ self.restore_last_views(&v["last_views"]);+ self.last_session = last_session::LastSession::from_json(&v["last_session"]);+ if let Some(on) = v["system_title_bar"].as_bool() {+ self.system_title_bar = on;+ }+ if let Some(on) = v["reload_changed_files"].as_bool() {+ self.reload_changed_files = on;+ }+ if let Some(on) = v["show_secured_notice"].as_bool() {+ self.show_secured_notice = on;+ }+ self.pinned.restore(&v["pinned_folders"]);+ if let Ok(preference) = serde_json::from_value::<ThemePreference>(v["theme"].clone()) {+ self.set_theme_preference(preference);+ }+ if let Ok(speed) = serde_json::from_value::<scroll_speed::ScrollSpeed>(v["scroll_speed"].clone()) {+ self.scroll_speed = speed;+ }+ if let Ok(effects) = serde_json::from_value::<motion::AnimationEffects>(v["animation_effects"].clone()) {+ self.animation_effects = effects;+ }+ if let Ok(mode) = serde_json::from_value::<Mode>(v["default_mode"].clone()) {+ self.default_mode = mode;+ }+ if let Some((layout, continuous)) = v["default_layout"].as_str().and_then(canvas::parse_display_token) {+ (self.view_defaults.layout, self.view_defaults.continuous) = (layout, continuous);+ }+ }++ /// Switches for reopening, window chrome and file watching.+ fn restore_behavior_prefs(&mut self, v: &serde_json::Value) {+ if let Some(show) = v["default_page_gaps"].as_bool() {+ self.view_defaults.show_page_gaps = show;+ }+ if let Ok(units) = serde_json::from_value::<units::Unit>(v["units"].clone()) {+ self.units = units;+ }+ if let Some(on) = v["always_default_view"].as_bool() {+ self.always_default_view = on;+ }+ if let Some(paper) = v+ .get("print_paper")+ .and_then(serde_json::Value::as_str)+ .and_then(|name| pdfcraft_engine::print::PAPERS.iter().position(|(canonical, _)| *canonical == name))+ {+ self.print_draft.paper = paper;+ }+ if let Some(on) = v["highlight_fields"].as_bool() {+ self.view_defaults.highlight_fields = on;+ }+ if let Some(closed) = v["comments_panel_closed"].as_bool() {+ self.comments_panel_closed = closed;+ }+ if let Some(closed) = v["right_panel_closed"].as_bool() {+ self.right_panel_closed = closed;+ }+ if let Some(defaults) = v["default_zoom"].as_str().and_then(|zoom| self.view_defaults.with_zoom(zoom)) {+ self.view_defaults = defaults;+ }+ if let Some(language) = v["language"].as_str().and_then(i18n::normalize_pref) {+ self.language = language.to_string();+ }+ if let Some(on) = v["flatten_fill_sign"].as_bool() {+ self.flatten_fill_sign_on_save = on;+ }+ if let Some(size) = v["fill_text_size"].as_f64().and_then(fill_sign::valid_text_size) {+ self.fill_text_size = size;+ }++ if let Ok(color) = serde_json::from_value::<[f64; 3]>(v["fill_text_color"].clone())++ && let Some(color) = fill_sign::valid_text_color(color)++ {++ self.fill_text_color = color;++ }+ if let Some(prefs) = RedactPrefs::from_json(&v["redact_prefs"]) {+ self.redact_prefs = prefs.clone();+ self.redact_defaults = prefs;+ }+ }++ /// Display defaults, units, language and sign-in details.+ fn restore_view_prefs(&mut self, v: &serde_json::Value) {+ // Settings are untrusted: an unreadable value (a colour that isn't three bytes, say)+ // fails to deserialize and keeps Off.+ if let Ok(colors) = serde_json::from_value::<pdfcraft_render::ReadingColors>(v["reading_colors"].clone()) {+ self.reading_colors = colors;+ }+ // Settings are untrusted: a size out of range follows the system instead.+ self.ui_scale = v["ui_scale"].as_f64().and_then(ui_scale::valid);+ // Settings are untrusted: an unusable pattern keeps the default.+ if let Some(f) = v["date_format"].as_str() {+ let _ = self.session.set_date_format(f);+ }+ if let Some(l) = v["date_language"].as_str() {+ let _ = self.session.set_date_language(Some(l));+ }+ // An empty or missing name keeps the login-name default; settings are untrusted, so the+ // name is cut to a sane length.+ if let Some(author) = v["author"].as_str().map(str::trim).filter(|a| !a.is_empty()) {+ self.comment_prefs.author = author.chars().take(MAX_AUTHOR_CHARS).collect();+ }+ if let Some(hide) = v["hide_empty_highlight_hover"].as_bool() {+ self.comment_prefs.hide_empty_highlight_hover = hide;+ }+ if let Some(pinned) = v["comment_tool_pinned"].as_bool() {+ self.comment_prefs.pinned = pinned;+ }+ }++ /// The author and per-tool comment styles.+ fn restore_comment_prefs(&mut self, v: &serde_json::Value) {+ // Per-tool comment styles (#340): each field goes through its clamping setter, so a+ // malformed or hostile entry is clamped or ignored rather than trusted.+ if let Some(styles) = v["comment_styles"].as_array() {+ for e in styles {+ let Some(tool) = e["tool"].as_str().and_then(crate::comments::CommentTool::from_command) else { continue };+ if let Some(c) = rgb_triple(&e["color"]) {+ self.comment_prefs.set_color(tool, c);+ }+ if let Some(o) = e["opacity"].as_f64() {+ self.comment_prefs.set_opacity(tool, o);+ }+ if let Some(w) = e["width"].as_f64() {+ self.comment_prefs.set_width(tool, w);+ }+ // `"fill": null` is a saved "no fill", which clears a tool's default fill; a+ // missing or malformed fill keeps it.+ let fill = match e.get("fill") {+ Some(serde_json::Value::Null) => Some(None),+ Some(v) => rgb_triple(v).map(Some),+ None => None,+ };+ if let Some(fill) = fill {+ let mut s = self.comment_prefs.style(tool);+ s.fill = fill;+ self.comment_prefs.set_style(tool, s);+ }+ }+ }+ }++ /// Saved signatures, stamps, actions and trusted certificates.+ fn restore_signature_prefs(&mut self, v: &serde_json::Value) {+ if let Ok(s) = serde_json::from_value::<Vec<Vec<[f32; 2]>>>(v["signature"].clone())+ && s.iter().all(|st| st.iter().all(|p| p.iter().all(|x| x.is_finite())))+ {+ self.signature = Some(fill_sign::SavedSig::Drawn(s));+ }+ if let Some(t) = v["signature_text"].as_str().filter(|t| !t.trim().is_empty()) {+ self.signature = Some(fill_sign::SavedSig::Typed(t.to_string()));+ }+ if let Ok(s @ fill_sign::SavedSig::Image(_)) = serde_json::from_value::<fill_sign::SavedSig>(v["signature_image"].clone()) {+ self.signature = Some(s);+ }+ if let Ok(i) = serde_json::from_value::<fill_sign::SavedSig>(v["initials"].clone()) {+ self.initials = Some(i);+ }+ // An unreadable choice (a damaged image) falls back to the name.+ self.sign_graphic = serde_json::from_value(v["sign_graphic"].clone()).unwrap_or_default();+ if let Ok(ids) = serde_json::from_value::<Vec<DigitalIdEntry>>(v["digital_ids"].clone()) {+ self.digital_ids = ids;+ }+ self.custom_stamps = stamps_ui::decode(&v["custom_stamps"]);+ self.custom_actions = actions_ui::decode(&v["actions"]);+ if let Some(on) = v["javascript"].as_bool() {+ self.session.set_javascript(on);+ }+ if let Ok(pems) = serde_json::from_value::<Vec<String>>(v["trusted"].clone()) {+ let certs = pems.iter().filter_map(|p| pdfcraft_engine::sign::x509::load_certificates(p.as_bytes()).ok()).flatten().collect();+ self.apply_trusted_certificates(certs);+ }+ }+ }diff --cc crates/ui-egui/src/canvas.rsindex 82d7a6753,91d2c4136..ba7d150f4--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -878,219 -803,559 +803,562 @@@ impl DocViewself.page_count}- pub fn select_pages(&mut self, pages: &[usize]) {- self.selected = pages.iter().copied().filter(|p| *p < self.page_count).collect();- if let Some(first) = self.selected.first() {- self.current = *first;- }+ /// Drops wheel state after a discontinuous jump so the destination cannot+ /// inherit momentum from the previous viewport.+ fn reset_coarse_state(&mut self) {+ self.wheel.clear_motion();+ self.wheel_boost_x.reset();+ self.wheel_boost_y.reset();}+ }- /// A click on page `i`'s thumbnail, in the organize grid or the Pages panel. ⇧ selects the- /// range from the anchor (or the current page); ⌘/Ctrl toggles the page; a plain click- /// selects only it. `seed_current` is for the Pages panel, where an empty selection means- /// the current page: the first ⌘-click on another page keeps the current one selected too.- pub fn click_page(&mut self, i: usize, modifiers: egui::Modifiers, seed_current: bool) {- if i >= self.page_count {- return;- }- if modifiers.shift {- let a = self.select_anchor.unwrap_or(self.current);- self.selected = (a.min(i)..=a.max(i)).collect();- } else if modifiers.command {- if seed_current && self.selected.is_empty() && i != self.current {- self.selected.insert(self.current);- }- if !self.selected.remove(&i) {- self.selected.insert(i);- }- self.select_anchor = Some(i);- } else {- self.selected = [i].into();- self.select_anchor = Some(i);- }- }+ /// The renders a frame wants (page, scale, tag, tile), and the pages visible.+ type PageRenders = (Vec<(usize, f32, u64, Option<Tile>)>, Vec<usize>);- /// Drop the page selection; a later ⇧-click ranges from `anchor`.- pub fn clear_page_selection(&mut self, anchor: Option<usize>) {- self.selected.clear();- self.select_anchor = anchor.filter(|a| *a < self.page_count);- }+ /// What the page-scroll closure reads: this frame's zoom, scrolling, tool and document state.+ #[derive(Clone, Copy)]+ struct PageEnv<'a> {+ added: &'a Vec<pdfcraft_engine::Added>,+ allowed: bool,+ author: &'a String,+ auto_delta: Vec2,+ avail: Rect,+ boost_extra: Vec2,+ by_line: &'a String,+ calc_order: bool,+ can_copy: bool,+ can_crop: bool,+ can_fill: bool,+ can_modify: bool,+ comments_hidden: bool,+ content_h: f32,+ content_w: f32,+ custom_stamp: &'a Option<crate::stamps_ui::CustomStamp>,+ date_text: &'a Result<String, String>,+ doc: &'a pdfcraft_engine::Document,+ doc_links: &'a Vec<pdfcraft_engine::LinkItem>,+ edge_delta: Vec2,+ editing_content: bool,+ form: &'a Arc<Vec<pdfcraft_engine::FormField>>,+ generation: u64,+ glide: Vec2,+ hand: bool,+ info: &'a DocInfo,+ initials: &'a Option<crate::fill_sign::SavedSig>,+ key_scroll: f32,+ middle_gesture: bool,+ modal: bool,+ navigation_enabled: bool,+ paper: Color32,+ ppp: f32,+ precise_scroll: Vec2,+ prefs: &'a comments::CommentPrefs,+ preparing: bool,+ rects: &'a Vec<Rect>,+ redact_mark: ([f64; 3], f64),+ scale: f32,+ selection_wheel: bool,+ selects_text: bool,+ signature: &'a Option<crate::fill_sign::SavedSig>,+ single_paging: bool,+ t: &'a Tokens,+ table_preview: &'a Option<crate::field_table_ui::Preview>,+ tag: u64,+ text_style: &'a pdfcraft_engine::AddedText,+ tool: QuickTool,+ units: crate::units::Unit,+ unobstructed: bool,+ visible_pages: &'a Vec<usize>,+ y_shift: f32,+ fill_text_size: f64,++ fill_text_color: [f64; 3],+ today: (i64, u32, u32),+ }- pub fn render_pending(&self) -> bool {- !self.last_queue.is_empty() || self.text_background.pending() || self.move_background.pending()- }+ /// What the page-scroll closure produces for the rest of the frame.+ #[derive(Default)]+ struct PageOut {+ canvas_action: Option<comments::CanvasAction>,+ clicked_link: Option<LinkTarget>,+ copy_selected: bool,+ field_menu: Option<FieldMenu>,+ field_placed: bool,+ field_props: bool,+ hover_text: Option<(Pos2, String)>,+ image_action: Option<crate::edit_text_ui::ImageAction>,+ open_boxes: bool,+ open_initials: bool,+ open_signature: bool,+ open_table: Option<(usize, [f64; 4])>,+ primary_down: bool,+ refused: Option<String>,+ stamp_placed: bool,+ }- /// The cached tile keys of a page, as (scale tag, tile x, tile y) (diagnostics and tests).- pub fn tiles_debug(&self, page: usize) -> Vec<(u64, u32, u32)> {- let mut k: Vec<(u64, u32, u32)> = self.tiles.keys().filter(|key| key.0 == page).map(|key| (key.1, key.2, key.3)).collect();- k.sort_unstable();- k- }+ /// The page-scroll closure's body: lays out and draws the visible pages, their tools and overlays, and+ /// returns the renders wanted and the pages visible.+ /// The state of one pass over the visible pages: what is read, and what the pages add up to.+ struct PageFrame<'a> {+ env: PageEnv<'a>,+ resp: &'a egui::Response,+ ptr: &'a PagePointer,+ origin: Pos2,+ visible: Rect,+ pressed: bool,+ pointer: Option<Pos2>,+ signature_preview: &'a mut Option<(crate::fill_sign::SavedSig, egui::TextureHandle)>,+ out: PageOut,+ wanted: Vec<(usize, f32, u64, Option<Tile>)>,+ visible_now: Vec<usize>,+ current: usize,+ best_overlap: f32,+ current_overlap: f32,+ current_height: f32,+ pressed_page: Option<usize>,+ calc_hover: Option<String>,+ }- /// Re-render every page and text layer (the document's appearance changed, e.g. a layer- /// was toggled). Out-of-date rasters stay on screen until their replacements arrive, so the- /// view never flashes blank.- pub fn invalidate_content(&mut self) {- // Undo, redo and other document-wide changes: a released drawing's preview would be a ghost.- self.comments.settling.clear();- for p in self.pages.values_mut() {- p.tag = STALE_TAG;- }- self.stale_thumbs.extend(self.thumbs.keys().copied());- for slot in self.print_pages.values_mut() {- slot.0 = STALE_TAG;- }- // Pages may have moved: a sharp render of another page would be worse than a soft one.- self.grid_pages.clear();- self.tiles.clear();- self.stale_tiles.clear();- self.forms.unbaked.clear();- self.texts.clear();- self.text_failed.clear();- self.errors.clear();- self.slow_pages.clear();- self.waiting_since.clear();- self.last_queue.clear();- self.selection = None;- if let Some(f) = self.find.as_mut() {- f.matches.clear();- f.current = None;- }- }+ /// Visible heights (points) closer than this are equal: one page size can meet the viewport a+ /// fraction of a point differently once the scroll offset is applied.+ const PAGE_TIE: f32 = 0.5;- /// Only `page` changed (a comment was added, edited or removed): re-render that page and- /// re-read its text, keep everything else. Out-of-date tiles stay on screen until replacements arrive.- pub fn page_changed(&mut self, page: usize) {- if let Some(p) = self.pages.get_mut(&page) {- p.tag = STALE_TAG;- }- if self.thumbs.contains_key(&page) {- self.stale_thumbs.insert(page);- }- if let Some(slot) = self.print_pages.get_mut(&page) {- slot.0 = STALE_TAG;- }- let current_tag = if self.current_scale_tag != 0 {- self.current_scale_tag+ /// Draws page `i` of the visible pages: its raster, the tools' input and overlays.+ /// One visible page: its index, its rectangle on screen and the transform to and from the page.+ #[derive(Clone, Copy)]+ struct PageSlot {+ i: usize,+ r: Rect,+ xf: PageXform,+ }++ /// Paints the page's paper, shadow and raster (or why it can't be shown), and asks for the renders+ /// it wants.+ fn paint_page_surface(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot) {+ let PageEnv { paper, ppp, scale, t, tag, .. } = frame.env;+ let PageSlot { i, r, xf } = *slot;+ let visible = frame.visible;+ let info = frame.env.info;+ let painter = ui.painter();+ // Shadows would darken the preceding page when pages touch.+ if view.show_page_gaps {+ painter.add(egui::epaint::Shadow { offset: [0, 3], blur: 14, spread: 0, color: t.page_shadow }.as_shape(r, CornerRadius::ZERO));+ }+ painter.rect_filled(r, CornerRadius::ZERO, paper);+ if let Some(err) = view.errors.get(&i) {+ painter.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0xFB, 0xF4, 0xF4));+ icons::paint(+ ui,+ Rect::from_center_size(r.center() - vec2(0.0, 26.0), vec2(28.0, 28.0)),+ "triangle-alert",+ 26.0,+ Color32::from_rgb(0xC8, 0x3A, 0x3A),+ );+ let message = crate::i18n::fmt(tl!("This page couldn't be displayed.\n{e}"), &[("e", err)]);+ let msg = ui.fonts_mut(|f| f.layout(message, theme::regular(12.5), Color32::from_rgb(0x6A, 0x2A, 0x2A), (r.width() - 40.0).max(80.0)));+ painter.galley(pos2(r.center().x - msg.size().x / 2.0, r.center().y), msg, Color32::BLACK);+ } else {+ let (pw_pt, ph_pt) = (info.pages[i].width.max(1.0), info.pages[i].height.max(1.0));+ // A GPU may take smaller textures than these (OpenGL drivers report as little as+ // 2048 pixels, and uploading a bigger one aborts), so both stay within its limit.+ let max_side = ui.ctx().input(|inp| inp.max_texture_side) as f32;+ let tiled = pw_pt.max(ph_pt) * scale > TILE_THRESHOLD.min(max_side);+ // Whole-page raster: sharp when small, a low-res backdrop when tiled.+ let (want_scale, want_tag) = if tiled {+ let bs = BASE_SIDE.min(max_side) / pw_pt.max(ph_pt);+ (bs, scale_tag(bs))} else {- self.tiles.keys().filter(|k| k.0 == page).map(|k| k.1).max().unwrap_or(0)+ (scale, tag)};- self.tiles.retain(|key, _| key.0 != page || key.1 == current_tag);- self.stale_tiles.retain(|key| key.0 != page || key.1 == current_tag);- for &key in self.tiles.keys() {- if key.0 == page && key.1 == current_tag {- self.stale_tiles.insert(key);+ // Under tiles, a whole-page raster sharper than the backdrop (from before the page+ // grew past the tiling size) is a better backdrop: keep demanding it as it is.+ match view.pages.get(&i).filter(|p| tiled && p.tag != STALE_TAG && tag_scale(p.tag) >= want_scale) {+ Some(p) => frame.wanted.push((i, tag_scale(p.tag), p.tag, None)),+ None => frame.wanted.push((i, want_scale, want_tag, None)),+ }+ match view.pages.get(&i) {+ Some(p) => {+ if !tiled && p.tag == want_tag {+ xf.texel_aligned(p.tex.size(), ppp).paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);+ } else {+ // A backdrop, or a raster at an older scale until the new one arrives.+ xf.paint_image(painter, p.tex.id(), 0.0, 0.0, 1.0, 1.0);+ }+ }+ None => {+ let now = ui.input(|inp| inp.time);+ let since = *view.waiting_since.entry(i).or_insert(now);+ let msg = if now - since > 6.0 { "Still rendering — this page is unusually complex…" } else { "Rendering…" };+ painter.text(r.center(), Align2::CENTER_CENTER, tl!(msg), theme::regular(12.0), t.text_faint);}}- self.slow_pages.remove(&page);- self.texts.remove(&page);- self.text_failed.remove(&page);- self.errors.remove(&page);- self.last_queue.clear();- if self.selection.is_some_and(|s| s.page == page) {- self.selection = None;+ if tiled && r.intersects(visible) {+ paint_page_tiles(ui, view, frame, slot, (pw_pt, ph_pt, max_side));}}+ }- /// Pages drawn last frame and their screen rectangles.- pub fn visible_page_rects(&self) -> Vec<(usize, Rect)> {- self.screen_xforms.iter().map(|(p, xf)| (*p, xf.rect)).collect()+ /// Paints the tiles of a page too big to draw whole: the tiles of earlier zooms first, stretched,+ /// then the visible tiles of this one, nearest the viewport centre first, asking for those missing.+ fn paint_page_tiles(ui: &egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, (pw_pt, ph_pt, max_side): (f32, f32, f32)) {+ let PageEnv { ppp, scale, tag, .. } = frame.env;+ let PageSlot { i, r, xf } = *slot;+ let visible = frame.visible;+ let painter = ui.painter();+ // Device-pixel geometry of the scaled page, and the visible part of it+ // (found by mapping the visible screen corners back into the page). Sides round+ // up as whole-page rasters do, so the last partial row and column get tiles.+ let (dw, dh) = (device_pixels(pw_pt, scale), device_pixels(ph_pt, scale));+ // Adaptive tile side for this zoom and page, within the GPU texture limit:+ // a zoomed viewport or a giant sheet is covered by a few large tiles+ // instead of many small ones, and each tile costs one full page interpret.+ // Never zero (u32 division below).+ let ts = tile_side(scale, dw.max(dh)).min(max_side as u32).max(64);+ let vis = r.intersect(visible);+ let corners = [vis.left_top(), vis.right_top(), vis.right_bottom(), vis.left_bottom()].map(|c| xf.screen_to_norm(c));+ let (u0, u1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.0), b.max(c.0)));+ let (v0, v1) = corners.iter().fold((1.0f32, 0.0f32), |(a, b), c| (a.min(c.1), b.max(c.1)));+ let (vx0, vy0) = ((u0.max(0.0) * dw as f32) as u32, (v0.max(0.0) * dh as f32) as u32);+ let (vx1, vy1) = (((u1.min(1.0) * dw as f32).ceil() as u32).min(dw), ((v1.min(1.0) * dh as f32).ceil() as u32).min(dh));+ // Tiles of earlier zooms first, stretched, the nearest scale last (on top):+ // until the current tiles arrive, a zoom shows them rather than the backdrop.+ let mut older: Vec<(f32, u32, u32, &TextureHandle)> =+ view.tiles.iter().filter(|((p, t, _, _), _)| *p == i && *t != tag).map(|((_, t, ox, oy), tex)| (tag_scale(*t), *ox, *oy, tex)).collect();+ older.sort_by(|a, b| (b.0 / scale).ln().abs().total_cmp(&(a.0 / scale).ln().abs()));+ for (s, ox, oy, tex) in older {+ let (ow, oh) = (device_pixels(pw_pt, s) as f32, device_pixels(ph_pt, s) as f32);+ let [w, h] = tex.size();+ let (x, y) = (ox as f32, oy as f32);+ xf.paint_image(painter, tex.id(), x / ow, y / oh, (x + w as f32) / ow, (y + h as f32) / oh);+ }+ // Visible tiles, nearest the viewport centre first: each tile costs a full+ // page interpret, so the workers sharpen what is looked at before the edges.+ let (vcx, vcy) = ((vx0 + vx1) as f32 / 2.0, (vy0 + vy1) as f32 / 2.0);+ let mut coords: Vec<(u32, u32)> = Vec::new();+ for ty in vy0 / ts..=(vy1.saturating_sub(1)) / ts {+ for tx in vx0 / ts..=(vx1.saturating_sub(1)) / ts {+ coords.push((tx, ty));+ }+ }+ coords.sort_by(|a, b| {+ let da = ((a.0 * ts + ts / 2) as f32 - vcx).abs() + ((a.1 * ts + ts / 2) as f32 - vcy).abs();+ let db = ((b.0 * ts + ts / 2) as f32 - vcx).abs() + ((b.1 * ts + ts / 2) as f32 - vcy).abs();+ da.total_cmp(&db)+ });+ for (tx, ty) in coords {+ let (x, y) = (tx * ts, ty * ts);+ let (w, h) = (ts.min(dw.saturating_sub(x)), ts.min(dh.saturating_sub(y)));+ if w == 0 || h == 0 {+ continue;+ }+ frame.wanted.push((i, scale, tag, Some(Tile { x, y, w, h })));+ if let Some(tex) = view.tiles.get(&(i, tag, x, y)) {+ let (fw, fh) = (dw as f32, dh as f32);+ xf.texel_aligned([dw as usize, dh as usize], ppp).paint_image(+ painter,+ tex.id(),+ x as f32 / fw,+ y as f32 / fh,+ (x + w) as f32 / fw,+ (y + h) as f32 / fh,+ );+ }}+ }- /// Where `page` is drawn this frame, with its coordinate mapping.- pub(crate) fn page_xform(&self, page: usize) -> Option<PageXform> {- self.screen_xforms.iter().find(|(p, _)| *p == page).map(|(_, xf)| *xf)- }+ /// What the page's tools did with the pointer this frame.+ struct PageInput {+ /// A tool, a field or a comment took the pointer: text selection must leave it alone.+ consumed: bool,+ /// Redact or Highlight draws boxes off text.+ area_tool: bool,+ }- /// The text selection as markup quadrilaterals in user space: (page, quads).- pub(crate) fn selection_quads(&self, info: &DocInfo) -> Option<(usize, Vec<[f64; 8]>)> {- let s = self.selection?;- let text = self.texts.get(&s.page)?;- let page = info.pages.get(s.page)?;- let quads: Vec<[f64; 8]> = s.rects(text).into_iter().map(|r| page.view_rect_to_quad(r)).collect();- (!quads.is_empty()).then_some((s.page, quads))- }+ /// Common geometry and pointer state for a tool acting on one page.+ #[derive(Clone, Copy)]+ pub(crate) struct PageToolContext<'a> {+ pub ui: &'a egui::Ui,+ pub resp: &'a egui::Response,+ pub xf: &'a PageXform,+ pub ptr: &'a PagePointer,+ pub page: usize,+ pub doc: &'a pdfcraft_engine::Document,+ pub info: &'a DocInfo,+ }- /// A page's thumbnail texture, when rendered.- pub(crate) fn thumb_id(&self, page: usize) -> Option<egui::TextureId> {- self.thumbs.get(&page).map(|t| t.tex.id())+ /// Comments: tools, selection, moving and resizing come before text selection. Form fields take+ /// clicks first with the Select tool (as Acrobat fills fields in every viewing mode); then+ /// comments; then text selection.+ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot) -> PageInput {+ let PageEnv {+ added,+ allowed,+ author,+ by_line,+ can_crop,+ can_fill,+ can_modify,+ comments_hidden,+ custom_stamp,+ date_text,+ doc,+ doc_links,+ editing_content,+ form,+ info,+ initials,+ prefs,+ preparing,+ redact_mark,+ signature,+ table_preview,+ text_style,+ tool,+ units,+ fill_text_size,++ fill_text_color,+ ..+ } = frame.env;+ let PageSlot { i, xf, .. } = *slot;+ let PageFrame { resp, ptr, pointer, .. } = *frame;+ let cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info };+ let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark };+ if let QuickTool::Measure(measure_tool) = tool {+ crate::measure_ui::page_input(ui, resp, doc, view, &pcx, measure_tool, units);+ }++ // Form fields take clicks first with the Select tool (as Acrobat fills fields in+ // every viewing mode); then comments; then text selection.+ if let QuickTool::Stamp(kind) = tool+ && allowed+ && let Some(p) = ptr.within(xf.rect)+ {+ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ if resp.clicked() {+ // Centred on the click, upright as the page is shown.+ let (vx, vy) = xf.screen_to_view(p);+ let (w, h) = kind.size();+ let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];+ let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();+ let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];+ let by = (kind.group() == pdfcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());+ let shape = pdfcraft_engine::Shape::Stamp { rect, stamp: kind, by };+ view.pending_edit = Some(pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {+ page: i,+ style: pdfcraft_engine::Style::default_for(&shape),+ shape,+ contents: String::new(),+ author: author.clone(),+ }));+ frame.out.stamp_placed = true;+ }}-- /// The whole-page raster on screen for `page` (the low-res backdrop of a tiled page), if any.- pub(crate) fn page_raster(&self, page: usize) -> Option<egui::TextureId> {- self.pages.get(&page).map(|p| p.tex.id())+ if let Some(cs) = custom_stamp.as_ref()+ && allowed+ && let Some(p) = ptr.within(xf.rect)+ {+ view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);+ if resp.clicked() {+ // Centred on the click at its natural size (the engine sizes it).+ let (vx, vy) = xf.screen_to_view(p);+ let u = info.pages[i].view_to_user(vx, vy);+ let (x, y) = (u[0] as f64, u[1] as f64);+ view.pending_edit = Some(pdfcraft_engine::Edit::AddCustomStamp {+ page: i,+ rect: [x, y, x, y],+ name: cs.name.clone(),+ file: pdfcraft_engine::MarkFile { name: cs.file.clone(), bytes: cs.data.clone(), page: cs.page },+ author: author.clone(),+ });+ frame.out.stamp_placed = true;+ }}-- /// The print preview's picture of `page`: the sheet raster when it has arrived, otherwise the- /// thumbnail.- pub(crate) fn page_preview(&self, page: usize) -> Option<egui::TextureId> {- self.print_pages.get(&page).map(|(_, tex)| tex.id()).or_else(|| self.thumb_id(page))+ // Over a mark already placed, the Fill & Sign tool picks it up (comments, below).+ if let QuickTool::Fill(ft) = tool+ && allowed+ && !comments::fill_grabs(&pcx, view)+ {+ match crate::fill_sign::page_input(+ cx,+ crate::fill_sign::PageInput {+ tool: ft,+ text_size: fill_text_size,++ text_color: fill_text_color,+ signature: signature.as_ref(),+ initials: initials.as_ref(),+ preview: frame.signature_preview,+ author,+ date_text,+ },+ view,+ ) {+ Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e),+ Some(crate::fill_sign::FillAction::Signature(e)) => {+ view.pending_edit = Some(*e);+ view.fill_signature_page = Some(i);+ }+ Some(crate::fill_sign::FillAction::CreateSignature) => frame.out.open_signature = true,+ Some(crate::fill_sign::FillAction::CreateInitials) => frame.out.open_initials = true,+ Some(crate::fill_sign::FillAction::Refused(why)) => frame.out.refused = Some(why),+ None => {}+ }}-- pub(crate) fn page_text(&self, page: usize) -> Option<Arc<PageText>> {- self.texts.get(&page).cloned()+ if matches!(tool, QuickTool::SignArea { .. }) {+ crate::sign_ui::page_input(ui, resp, &xf, ptr, i, info, view);}-- pub(crate) fn clear_selection(&mut self) {- self.selection = None;+ if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) {+ crate::zoom_snap::page_input(ui, resp, &xf, ptr, i, view);}-- /// Select text on `page` from glyph `from` to glyph `to` (tests and automation).- pub fn select_text(&mut self, page: usize, from: usize, to: usize) {- self.selection = Some(Selection::run(page, from, to));+ if tool == QuickTool::EnhanceCamera {+ crate::camera_ui::page_input(resp, &xf, ptr, i, view, can_modify);}-- /// Open the find bar (or focus it if already open).- pub fn open_find(&mut self) {- let f = self.find.get_or_insert_with(Find::default);- f.focus = true;+ if tool == QuickTool::Crop+ && crate::crop::page_input(ui, crate::crop::CropPageInput { resp, xf: &xf, ptr, page: i, info, view, allowed: can_crop })+ {+ view.current = i;+ frame.out.open_boxes = true;}-- /// Re-run the search on all pages whose text is known (after the query changed).- pub fn rerun_find(&mut self) {- let Some(f) = self.find.as_mut() else { return };- f.case_query = f.query.clone();- f.matches.clear();- f.current = None;- if f.case_query.trim().is_empty() {- return;- }- let mut pages: Vec<usize> = self.texts.keys().copied().collect();- pages.sort();- for &p in &pages {- if let Some(text) = self.texts.get(&p) {- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (p, r)));+ let on_field = if preparing {+ let field_tool = match tool {+ QuickTool::Field(f) => Some(f),+ _ => None,+ };+ // While a table is being set up, nothing else is drawn or moved.+ let allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none();+ let o = crate::prepare::page_input(cx, form, field_tool, allowed, view);+ frame.out.field_props |= o.properties;+ frame.out.field_placed |= o.placed;+ frame.out.open_table = frame.out.open_table.or(o.table);+ o.consumed || field_tool.is_some()+ } else {+ tool == QuickTool::Select+ && !(editing_content && can_modify && crate::content_ui::select_grabs(&xf, ptr, i, info, added, view))+ && !comments::select_grabs(&pcx, view)+ && crate::forms_ui::page_input(cx, form, can_fill, view)+ };+ // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat).+ let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed;+ let boxing = area_tool && {+ let text = view.page_text(i);+ let over_text = |p: Pos2| {+ let (vx, vy) = xf.screen_to_view(p);+ text.as_ref().is_some_and(|t| t.glyphs.iter().any(|g| vx >= g.rect[0] && vx <= g.rect[2] && vy >= g.rect[1] && vy <= g.rect[3]))+ };+ crate::redact_ui::page_input(cx, over_text, view)+ };+ let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, ptr, i, info, view);+ let on_objects = !image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(cx, view);+ let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {+ let generation = doc.edit_generation();+ match view.edit_lines.get(&i) {+ Some((g, l)) if *g == generation => l.clone(),+ _ => {+ let l = doc.text_blocks(i);+ view.edit_lines.insert(i, (generation, l.clone()));+ l}}- f.matches.sort_by_key(|(p, r)| (*p, r.start));- if !f.matches.is_empty() {- // First match at or after the page being viewed.- let cur = self.current;- let i = f.matches.iter().position(|(p, _)| *p >= cur).unwrap_or(0);- f.current = Some(i);- let (p, _) = f.matches[i];- self.flash_match(p);+ } else {+ Vec::new()+ };+ let over_source = tool == QuickTool::AddText+ && pointer.is_some_and(|p| {+ !crate::content_ui::hits_added(&xf, info, i, added, p)+ && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))+ });+ let source_blocked = over_source && view.content.hold_blocked();+ if over_source && resp.clicked() && !source_blocked {+ if let Some(edit) = view.content.finish_draft(added) {+ view.pending_edit = Some(edit);}+ view.content.selected = None;+ }+ let on_content = !on_objects && editing_content && can_modify && {+ source_blocked+ || crate::content_ui::page_input(+ cx,+ added,+ tool == QuickTool::AddText && !over_source,+ matches!(tool, QuickTool::AddText | QuickTool::EditText),+ text_style,+ view,+ )+ || tool == QuickTool::AddText && !over_source+ };+ // Added content owns its gesture; its source text must not queue a second edit.+ // Edit text & images boxes every paragraph and image whenever the tool is on. Only the+ // input waits while selected objects or added content own the pointer, or while page+ // input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn+ // instead of vanishing until the pointer comes back.+ let others_own_pointer = on_objects || on_content;+ let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {+ let generation = doc.edit_generation();+ let images = match view.edit_images.get(&i) {+ Some((g, l)) if *g == generation => l.clone(),+ _ => {+ let l = doc.page_images(i);+ view.edit_images.insert(i, (generation, l.clone()));+ l+ }+ };+ // Editable text takes precedence over background/overlapping artwork. Both+ // inventories are painted every frame, even when text owns the pointer.+ let text_used = crate::edit_text_ui::page_input(cx, &lines, view, !others_own_pointer && !image_owns_pointer);+ let image_cx = crate::edit_text_ui::ImageCx {+ ui,+ resp,+ xf: &xf,+ ptr,+ page: i,+ info,+ allow_interaction: !others_own_pointer && (image_owns_pointer || !text_used),+ };+ let image_used = crate::edit_text_ui::image_input(&image_cx, &images, view, &mut frame.out.image_action);+ !others_own_pointer && (text_used || image_used)+ };+ let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(cx, doc_links, view);+ if tool == QuickTool::Select+ && resp.secondary_clicked()+ && can_modify+ && let Some(p) = pointer.filter(|p| xf.rect.contains(*p))+ && let Some(l) = doc.links().iter().find(|l| l.page == i && crate::link_ui::screen_rect(&xf, info, i, l.rect).expand(2.0).contains(p))+ {+ view.links.context = Some((i, l.index));}+ let consumed = on_objects || on_edit_text || on_link || on_content || boxing || on_field || comments::page_input(ui, resp, &pcx, view);+ PageInput { consumed, area_tool }+ }- fn refresh_find_page(&mut self, page: usize) {- let (Some(f), Some(text)) = (self.find.as_mut(), self.texts.get(&page)) else { return };- if f.case_query.trim().is_empty() {- return;+ /// Text layer: find matches, selection, I-beam and drag-to-select.+ fn text_layer(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) {+ let PageEnv { info, selects_text, tool, .. } = frame.env;+ let PageSlot { i, r, xf } = *slot;+ let PageFrame { resp, ptr, pointer, .. } = *frame;+ if let Some(text) = view.texts.get(&i).cloned() {+ paint_text_marks(ui, view, &text, i, xf, resp.dragged());+ if selects_text+ && !input.consumed+ && let Some(p) = pointer.filter(|p| r.contains(*p))+ {+ text_pointer_input(ui, view, &text, TextPointer { page: i, xf, rect: r, info, tool, resp, ptr: ptr.clone(), pointer: p });}- let current_key = f.current.and_then(|c| f.matches.get(c).cloned());- f.matches.retain(|(p, _)| *p != page);- f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (page, r)));- f.matches.sort_by_key(|(p, r)| (*p, r.start));- f.current = current_key.as_ref().and_then(|k| f.matches.iter().position(|m| m == k));- if f.current.is_none() && !f.matches.is_empty() {- // First match at or after the page being viewed.- let cur = self.current;- let i = f.matches.iter().position(|(p, _)| *p >= cur).unwrap_or(0);- f.current = Some(i);- let (p, _) = f.matches[i];- if current_key.is_none() {- self.flash_match(p);+ }+ }++ fn paint_text_marks(ui: &egui::Ui, view: &DocView, text: &PageText, page: usize, xf: PageXform, dragging: bool) {+ let painter = ui.painter();+ let to_screen = |g: [f32; 4]| xf.view_rect(g);+ if let Some(find) = &view.find {+ for (index, (match_page, range)) in find.matches.iter().enumerate() {+ if *match_page != page {+ continue;+ }+ let fill = if find.current == Some(index) {+ Color32::from_rgba_unmultiplied(255, 140, 0, 110)+ } else {+ Color32::from_rgba_unmultiplied(255, 214, 0, 90)+ };+ for line_rect in text.line_rects(range.clone()) {+ painter.rect_filled(to_screen(line_rect).expand(1.0), CornerRadius::same(2), fill);}}}@@@ -4777,1364 -2688,615 +2691,616 @@@ fn auto_scroll_deltas(ui: &egui::Ui, viview.auto_scroll.cancel();Vec2::ZERO};- let middle_gesture = view.auto_scroll.blocks_input();- let mut cells: Vec<(usize, Rect)> = Vec::new();- // The pages in view that are drawn larger than their thumbnails, and those of them that- // need a sharper render than they have. The width is the size drawn, in device pixels.- let (mut in_view, mut sharper): (Vec<(usize, f32)>, Vec<RenderRequest>) = (Vec::new(), Vec::new());- // The source cell can scroll out of the virtualized rows during a drag.- let mut drop = view.org_drag.is_some() && ui.input(|i| i.pointer.primary_released());- egui::ScrollArea::vertical().auto_shrink([false, false]).show_viewport(ui, |ui, clip| {- if middle_gesture {- let opacity = ui.opacity();- ui.disable();- ui.set_opacity(opacity);- }- if auto_delta != Vec2::ZERO {- ui.scroll_with_delta_animation(auto_delta, egui::style::ScrollAnimation::none());- }- ui.add_space(20.0);- let cols = ((ui.available_width() - 40.0) / cell.x).floor().max(1.0) as usize;- let rows = info.pages.len().div_ceil(cols);- let left = (ui.available_width() - cols as f32 * cell.x) / 2.0;- let (grid, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows as f32 * cell.y), Sense::hover());- // The page Organize opened on may lie in a row the virtualized grid has not laid out,- // so its cell is computed rather than found.- if let Some(page) = reveal.filter(|p| *p < info.pages.len()) {- let row = page / cols;- let col = page % cols;- let c = Rect::from_min_size(pos2(grid.left() + left + col as f32 * cell.x, grid.top() + row as f32 * cell.y), cell);- ui.scroll_to_rect_animation(c, Some(egui::Align::Center), egui::style::ScrollAnimation::none());- }- for row in thumbnail_rows(clip.top() - 20.0, clip.bottom() - 20.0, cell.y, rows) {- let row_rect = Rect::from_min_size(grid.min + vec2(0.0, row as f32 * cell.y), vec2(grid.width(), cell.y));- for col in 0..cols {- let i = row * cols + col;- let Some(p) = info.pages.get(i) else { break };- let c = Rect::from_min_size(pos2(row_rect.left() + left + col as f32 * cell.x, row_rect.top()), cell);- view.need_thumbnail(i, c.intersects(ui.clip_rect()));- let resp = ui.interact(c, ui.id().with(("org", i)), if editable { Sense::click_and_drag() } else { Sense::click() });- cells.push((i, c));- if let Some((_, above)) = anchor.filter(|(page, _)| *page == i) {- ui.scroll_to_rect_animation(c.translate(vec2(0.0, -above)), Some(egui::Align::Min), egui::style::ScrollAnimation::none());- }- // Drag pages to move them (the selection, or the page grabbed).- if resp.drag_started() {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.select_anchor = Some(i);- }- let mut pages: Vec<usize> = view.selected.iter().copied().collect();- pages.sort_unstable();- view.org_drag = Some(pages);- }- if resp.drag_stopped() {- drop = true;- }- let page_label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &p.label)]);- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, view.selected.contains(&i), page_label.clone()));- let pr = grid_page_rect(c, vec2(p.width, p.height));- let size = pr.size();- let selected = view.selected.contains(&i) || (view.selected.is_empty() && i == view.current);- if selected || resp.hovered() {- ui.painter().rect_filled(c.shrink(6.0), CornerRadius::same(8), if selected { t.accent_soft } else { t.hover });- }- if view.selected.contains(&i) {- ui.painter().rect_stroke(c.shrink(6.0), CornerRadius::same(8), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);- }- ui.painter().rect_filled(pr.translate(vec2(0.0, 1.5)), CornerRadius::same(1), t.page_shadow);- ui.painter().rect_filled(pr, CornerRadius::ZERO, Color32::WHITE);- // A page drawn larger than its thumbnail gets a render at the size drawn, while- // it is in view; until that arrives the thumbnail stands in.- let want = size.x * ppp;- let thumb = view.thumbs.get(&i).map(|t| &t.tex);- let thumb_ok = thumb.is_some_and(|t| t.size()[0] as f32 >= want * GRID_SHARP.start());- let sharp = view.grid_pages.get(&i).filter(|_| !thumb_ok);- if !thumb_ok && ui.is_rect_visible(c) {- in_view.push((i, want));- if !sharp.is_some_and(|(w, _)| sharp_enough(*w, want)) && !view.errors.contains_key(&i) {- sharper.push(RenderRequest {- page: i,- kind: RequestKind::Pixels,- tile: None,- scale: want / p.width.max(1.0),- tag: GRID_TAG,- // Grid cells are previews: tiny images are skipped for them.- preview: true,- });- }- }- if let Some(tex) = sharp.map(|(_, t)| t).or(thumb) {- ui.painter().image(tex.id(), pr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);- }- ui.painter().rect_stroke(pr, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);- let label_font = theme::medium(12.0);- let label_w = (c.width() - 12.0).max(0.0);- let page_label = crate::widgets::fit_line(&p.label, label_w, |s| crate::widgets::text_width(ui, s, &label_font));- let label_pos = pos2(c.center().x, c.bottom() - 48.0);- ui.painter().with_clip_rect(Rect::from_center_size(label_pos, vec2(label_w, 18.0))).text(- label_pos,- Align2::CENTER_CENTER,- page_label,- label_font,- t.text_muted,- );- // The checkbox toggles just this page without requiring a modifier. Keep it- // outside the page image, including on very tall or wide pages.- let mut checked = view.selected.contains(&i);- let check_rect = Rect::from_min_size(c.min + vec2(8.0, 8.0), Vec2::splat(20.0));- let check = ui.push_id(("org-check", i), |ui| ui.put(check_rect, widgets::checkbox_without_text(&mut checked))).inner;- let label = crate::i18n::fmt(tl!("Select page {label}"), &[("label", &p.label)]);- check.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, checked, label.clone()));- if check.on_hover_text(label).changed() {- view.click_page(i, egui::Modifiers::COMMAND, false);- // The document shows the page picked here when the grid closes, as after a- // Pages-panel click, so reopening the grid keeps the pick (issue #1910).- view.go_to_page(i);- }- // Local actions always target the labelled page. The toolbar above the grid- // remains the place for actions on the whole selection.- if selected || resp.contains_pointer() || resp.has_focus() {- let actions = Rect::from_center_size(pos2(c.center().x, c.bottom() - 24.0), vec2(84.0, 26.0));- ui.scope_builder(- egui::UiBuilder::new().id_salt(("org-actions", i)).max_rect(actions).layout(egui::Layout::left_to_right(egui::Align::Center)),- |ui| {- ui.spacing_mut().item_spacing.x = 3.0;- ui.add_enabled_ui(editable, |ui| {- for (icon, degrees, key) in- [("rotate-ccw", -90, "Rotate page {label} counterclockwise"), ("rotate-cw", 90, "Rotate page {label} clockwise")]- {- let label = crate::i18n::fmt(tl!(key), &[("label", &p.label)]);- if icons::button(ui, icon, 26.0, false, &label).clicked() {- view.pending_edit = Some(Edit::RotatePages { pages: vec![i], degrees });- }- }- let label = crate::i18n::fmt(tl!("Delete page {label}"), &[("label", &p.label)]);- if ui.add_enabled_ui(info.pages.len() > 1, |ui| icons::button(ui, "trash-2", 26.0, false, &label)).inner.clicked() {- view.pending_edit = Some(Edit::DeletePages { pages: vec![i] });- }- });- },- );- }- if resp.clicked() {- let m = ui.input(|i| i.modifiers);- view.click_page(i, m, false);- view.go_to_page(i);- }- if resp.double_clicked() {- open_page = Some(i);- }- // Right-click: Extract, Replace, Cut, Copy, Paste (on the selection, or this page).- resp.context_menu(|ui| {- if !view.selected.contains(&i) {- view.selected = [i].into();- view.go_to_page(i);- }- if ui.button(tl!("Extract pages")).clicked() {- view.pending_action = Some(ViewAction::Extract);- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Replace pages…"))).clicked() {- view.pending_action = Some(ViewAction::ReplacePages);- ui.close();- }- ui.separator();- if ui.add_enabled(editable, egui::Button::new(tl!("Cut"))).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: true });- ui.close();- }- if ui.button(tl!("Copy")).clicked() {- view.pending_action = Some(ViewAction::CopyPages { cut: false });- ui.close();- }- if ui.add_enabled(editable, egui::Button::new(tl!("Paste after"))).clicked() {- view.pending_action = Some(ViewAction::PastePages);- ui.close();- }- });- }- }- // Between pages (and at both ends): insert files right there.- if editable && !middle_gesture && view.org_drag.is_none() {- let mid = |r: &Rect| r.top() + 16.0 + (cell.y - 88.0) / 2.0;- for (i, c) in &cells {- let label = info- .pages- .get(*i)- .map(|p| crate::i18n::fmt(tl!("Insert a file before page {label}"), &[("label", &p.label)]))- .unwrap_or_default();- if gap_button(ui, *i, pos2(c.left(), mid(c)), cell.y - 88.0, label, t) {- view.pending_action = Some(ViewAction::InsertFromFileAt(*i));- }- }- if let Some((i, c)) = cells.last()- && i + 1 == info.pages.len()- && gap_button(ui, i + 1, pos2(c.right(), mid(c)), cell.y - 88.0, tl!("Insert a file at the end").to_string(), t)- {- view.pending_action = Some(ViewAction::InsertFromFileAt(i + 1));- }- }- // While dragging: the gap the pages would go to, drawn as a bar.- if let (Some(pages), Some(p)) = (view.org_drag.clone(), ui.input(|i| i.pointer.hover_pos())) {- if let Some(gap) = drop_gap(&cells, p) {- let x = match cells.iter().find(|(i, _)| *i == gap) {- Some((_, r)) => r.left() + 3.0,- None => cells.last().map_or(0.0, |(_, r)| r.right() - 3.0),- };- let row = cells.iter().find(|(i, _)| *i == gap).or(cells.last()).map(|(_, r)| r.y_range()).unwrap_or(egui::Rangef::new(0.0, 0.0));- ui.painter().line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- ui.painter().text(- p + vec2(14.0, 14.0),- Align2::LEFT_TOP,- if pages.len() == 1 { tl!("1 page").to_string() } else { crate::i18n::fmt(tl!("{n} pages"), &[("n", &pages.len().to_string())]) },- theme::medium(12.0),- t.accent_text,- );- }- if drop {- view.org_drag = None;- if let Some(gap) = drop_gap(&cells, p) {- // `to` counts positions without the moving pages.- let to = gap - pages.iter().filter(|x| **x < gap).count();- let first = pages[0];- let contiguous = pages.windows(2).all(|w| w[1] == w[0] + 1);- if !(contiguous && to == first) {- view.pending_edit = Some(Edit::MovePages { pages: pages.clone(), to });- view.selected = (to..to + pages.len()).collect();- }- }- }- } else if drop {- view.org_drag = None;- }- });- // Files dragged in from outside go to the gap under the pointer. Some platforms don't say- // where the pointer is until the files are dropped; then the whole grid is the target.- let pointer = ui.input(|i| i.pointer.hover_pos()).filter(|p| viewport.contains(*p));- view.grid_gap = pointer.filter(|_| editable && view.org_drag.is_none()).and_then(|p| drop_gap(&cells, p));- if editable && ui.input(|i| !i.raw.hovered_files.is_empty()) {- let painter = ui.painter().with_clip_rect(viewport);- painter.rect_stroke(viewport.shrink(2.0), CornerRadius::same(6), Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);- if let Some(gap) = view.grid_gap {- let at = cells.iter().find(|(i, _)| *i == gap).map(|(_, r)| (r.left() + 3.0, r.y_range()));- if let Some((x, row)) = at.or(cells.last().map(|(_, r)| (r.right() - 3.0, r.y_range()))) {- painter.line_segment([pos2(x, row.min + 10.0), pos2(x, row.max - 10.0)], Stroke::new(3.0, t.accent));- }- }- // A "+" that follows the pointer.- if let Some(p) = pointer {- let at = p + vec2(16.0, 16.0);- painter.circle_filled(at, 9.0, t.accent);- painter.line_segment([at - vec2(4.0, 0.0), at + vec2(4.0, 0.0)], Stroke::new(1.5, Color32::WHITE));- painter.line_segment([at - vec2(0.0, 4.0), at + vec2(0.0, 4.0)], Stroke::new(1.5, Color32::WHITE));- }- }- view.auto_scroll.paint(ui, viewport);- // Pinch, or Ctrl/⌘ with the wheel, zooms the grid about the page under the pointer.- let pinch = crate::motion::zoom_delta(ui.ctx());- if (pinch - 1.0).abs() > 0.001 && pointer.is_some() && !middle_gesture {- view.grid_zoom_request = Some(view.grid_zoom * pinch);- }- if let Some(zoom) = view.grid_zoom_request.take() {- let before = view.grid_zoom;- view.set_grid_zoom(zoom);- if view.grid_zoom != before {- // Keep the page under the pointer (or else the first one in view) where it is.- let under = pointer.and_then(|p| cells.iter().find(|(_, r)| r.contains(p)));- let anchor = under.or_else(|| cells.iter().find(|(_, r)| r.bottom() > viewport.top()));- view.grid_anchor = anchor.map(|(i, r)| (*i, r.top() - viewport.top()));- ui.ctx().request_repaint();- }- }- // When this frame's thumbnail will cover the cell, drop the sharp render without waiting- // for that texture to arrive.- let density = thumbnail_density(view.thumb_demand.len(), ppp);- in_view.retain(|&(page, want)| {- info.pages.get(page).is_none_or(|p| (device_pixels(p.width, thumbnail_scale(p.width, p.height, density)) as f32) < want * GRID_SHARP.start())- });- sharper.retain(|req| in_view.iter().any(|(page, _)| *page == req.page));- view.grid_pages.retain(|page, _| in_view.iter().any(|(kept, _)| kept == page));- // Sharp renders of the pages in view join this frame's demand ahead of the thumbnails.- view.frame_queue.extend(sharper);- if let Some(p) = open_page {- view.organize = false;- view.go_to_page(p);++ // Drawing a comment: the pointer in a band along any edge (or just past it) scrolls the view+ // that way, so a point beyond what is shown can be reached without letting go of the tool.+ let edge_delta = if unobstructed && matches!(view.comments.gesture, Some(comments::Gesture::Draw { .. })) {+ let (pointer, dt) = drawing_edge_pointer(ui);+ crate::autoscroll::edge_scroll(pointer, avail, dt)+ } else {+ Vec2::ZERO+ };+ if edge_delta != Vec2::ZERO {+ ui.ctx().request_repaint();}+ (auto_delta, edge_delta)}- /// A rendered raster as texture data. Its words are premultiplied RGBA bytes, exactly- /// `Color32`s, so the renderer's buffer becomes the image without a copy on the UI thread.- pub(crate) fn texture_image(size: [usize; 2], pixels: pdfcraft_render::Pixels) -> egui::ColorImage {- match bytemuck::allocation::try_cast_vec::<u32, Color32>(pixels.into_words()) {- Ok(px) if px.len() == size[0].saturating_mul(size[1]) => egui::ColorImage::new(size, px),- Ok(px) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&px)),- Err((_, words)) => egui::ColorImage::from_rgba_premultiplied(size, bytemuck::cast_slice(&words)),- }+ /// What decides whether touchpad momentum goes on.+ #[derive(Clone, Copy)]+ struct GlideCx {+ now: f64,+ may_glide: bool,+ key_scroll: f32,+ auto_delta: Vec2,+ zoom_delta: f32,+ edge_delta: Vec2,+ wheel_scrolled: bool,}- /// A luminance preview for a monochrome print. `Color32` stores premultiplied pixels, so a- /// non-opaque colour's alpha is restored after multiplying the unmultiplied RGB by its- /// luminance. This uses the display gamma-space weights users expect in editors/print dialogs,- /// not the linear-light coefficients of a colour-managed render.- fn grayscale(mut img: egui::ColorImage) -> egui::ColorImage {- for c in img.pixels.iter_mut() {- let a = c.a();- let luminance = f32::from(c.r()) * 0.299_f32 + f32::from(c.g()) * 0.587_f32 + f32::from(c.b()) * 0.114_f32;- let gray = if a == 0 || a == 255 {- luminance.round() as u8- } else {- // Unmultiply first, so translucent content keeps its paper-relative luminance.- let f = f32::from(a) / 255.0;- let un = [f32::from(c.r()) / f, f32::from(c.g()) / f, f32::from(c.b()) / f];- let l = un[0] * 0.299_f32 + un[1] * 0.587_f32 + un[2] * 0.114_f32;- (f * l).round() as u8- };- *c = Color32::from_rgba_premultiplied(gray, gray, gray, a);+ /// Touchpad momentum (#531): a swipe over the page lifted at speed glides on and slows to a stop,+ /// through the same un-eased path. Never while the pager owns the wheel, a gesture or dialog has+ /// the input, or animations are off; any click, key, zoom or other scrolling ends it. Any+ /// reader-owned motion ends automatic search following, even when it stays on the same page; the+ /// automatic flash uses `goto`, not these deltas, so its programmatic scroll is never mistaken for+ /// a reader action. Returns this frame's glide.+ fn step_glide(ui: &egui::Ui, view: &mut DocView, avail: Rect, cx: &GlideCx) -> Vec2 {+ let GlideCx { now, may_glide, key_scroll, auto_delta, zoom_delta, edge_delta, wheel_scrolled } = *cx;+ let over_page = ui.rect_contains_pointer(avail);+ ui.input(|i| view.fling.read(&i.events, now, may_glide && over_page));+ let interrupted = glide_interrupted(ui);+ if !may_glide || interrupted || key_scroll != 0.0 || auto_delta != Vec2::ZERO || zoom_delta != 1.0 {+ view.fling.stop();+ }+ let glide = view.fling.step(now);+ if view.fling.gliding() {+ ui.ctx().request_repaint();+ }+ if wheel_scrolled || auto_delta != Vec2::ZERO || edge_delta != Vec2::ZERO || glide != Vec2::ZERO {+ view.end_find_following();}- img+ glide}- #[cfg(test)]- mod tests {- #[test]- fn page_size_hint_zone_is_the_bottom_left_quadrant() {- let area = Rect::from_min_max(pos2(100.0, 50.0), pos2(500.0, 450.0));- assert!(in_size_hint_zone(area, pos2(110.0, 440.0)));- assert!(!in_size_hint_zone(area, pos2(110.0, 100.0)), "top-left");- assert!(!in_size_hint_zone(area, pos2(400.0, 440.0)), "bottom-right");- assert!(!in_size_hint_zone(area, pos2(50.0, 440.0)), "outside");- assert!(!in_size_hint_zone(area, pos2(f32::NAN, 440.0)));+ /// Text selection runs for the Select tool and for the markup tools (highlight…).+ fn tool_selects_text(tool: QuickTool, preparing: bool) -> bool {+ match tool {+ QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText,+ QuickTool::Select => !preparing,+ QuickTool::Redact | QuickTool::ColumnSelect => true,+ QuickTool::Hand+ | QuickTool::Measure(_)+ | QuickTool::Crop+ | QuickTool::EnhanceCamera+ | QuickTool::Fill(_)+ | QuickTool::Field(_)+ | QuickTool::AddText+ | QuickTool::EditText+ | QuickTool::Stamp(_)+ | QuickTool::CustomStamp(_)+ | QuickTool::Link+ | QuickTool::SignArea { .. }+ | QuickTool::MarqueeZoom+ | QuickTool::Snapshot => false,}+ }- use super::*;-- /// A rotated (landscape) page is drawn as wide as the cell allows and centred in the picture- /// area, as Acrobat draws it, not as a small strip pinned to the top; a portrait page still- /// fills the area's height; neither covers the checkbox corner or the label below.- #[test]- fn grid_pages_are_centred_and_as_large_as_the_cell_allows() {- let cell = Rect::from_min_size(pos2(100.0, 50.0), vec2(190.0, 282.0));- let area = Rect::from_min_max(pos2(cell.left(), cell.top() + 16.0), pos2(cell.right(), cell.bottom() - 72.0));- let checkbox = Rect::from_min_size(cell.min + vec2(8.0, 8.0), Vec2::splat(20.0));- let landscape = grid_page_rect(cell, vec2(842.0, 595.0));- assert!((landscape.center().y - area.center().y).abs() < 0.01, "centred vertically: {landscape:?}");- assert!((landscape.center().x - cell.center().x).abs() < 0.01);- assert!((landscape.width() - (cell.width() - 32.0)).abs() < 0.01, "as wide as the cell allows: {landscape:?}");- assert!(!landscape.intersects(checkbox));- let portrait = grid_page_rect(cell, vec2(595.0, 842.0));- assert!(area.contains_rect(portrait), "inside the picture area: {portrait:?}");- assert!((portrait.center().y - area.center().y).abs() < 0.01);- assert!(portrait.left() >= checkbox.right(), "clear of the checkbox: {portrait:?}");- // Degenerate sizes still give a finite rectangle inside the cell.- for page in [vec2(0.0, 0.0), vec2(1e9, 1.0), vec2(1.0, 1e9), vec2(f32::NAN, 10.0), vec2(f32::INFINITY, 10.0)] {- let r = grid_page_rect(cell, page);- assert!(r.is_finite() && cell.contains_rect(r), "{page:?} -> {r:?}");- }+ /// Holds sharp re-renders while the zoom is still moving: a new scale every frame would cancel the+ /// in-flight full-page interpret and restart it, so on a heavy page (a CAD plot with ~1000 images+ /// renders for seconds) the sharp raster never arrives and the view looks stuck on a soft image.+ /// The stale raster stays stretched meanwhile; the sharp request goes out once the zoom settles.+ fn hold_sharp_renders(ui: &egui::Ui, view: &mut DocView, scale: f32) -> bool {+ let now_scale = ui.input(|i| i.time);+ if (scale - view.last_scale).abs() > f32::EPSILON {+ view.last_scale = scale;+ view.sharp_hold_until = now_scale + 0.35;+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(380));}+ now_scale < view.sharp_hold_until+ }- fn annotation(fill_sign: bool) -> pdfcraft_render::Annotation {- pdfcraft_render::Annotation {- page: 0,- subtype: "FreeText".into(),- author: None,- contents: Some("Hello".into()),- modified: None,- name: None,- in_reply_to: None,- rect: [0.0; 4],- color: None,- index: 0,- state: None,- quads: Vec::new(),- locked: false,- intent: None,- fill_sign,+ /// A destination's position (bookmarks, links) refines `goto`: its point at the window's top-left,+ /// or the centre of a /FitR rectangle at the window's centre.+ fn refine_goto_point(mut scroll: egui::ScrollArea, view: &mut DocView, geometry: &ScrollGeometry<'_>) -> egui::ScrollArea {+ let ScrollGeometry { rects, y_shift, content_w, content_h, avail, .. } = *geometry;+ if let Some((page, fx, fy, rel)) = view.goto_point.take() {+ let r = rects[page.min(rects.len() - 1)];+ // Within the content, so an unreachable point never shows a frame scrolled past the end.+ let (max_x, max_y) = ((content_w - avail.width()).max(0.0), (content_h - avail.height()).max(0.0));+ if let Some(fx) = fx {+ scroll = scroll.horizontal_scroll_offset((r.left() + fx * r.width() - rel.x).clamp(0.0, max_x));+ }+ if let Some(fy) = fy {+ scroll = scroll.vertical_scroll_offset((r.top() - y_shift + fy * r.height() - rel.y).clamp(0.0, max_y));}}+ scroll+ }- #[test]- fn hover_popup_skips_fill_and_sign_marks() {- assert_eq!(annotation_hover_text(&annotation(false)).as_deref(), Some("FreeText\nHello"));- assert_eq!(annotation_hover_text(&annotation(true)), None);+ /// Draws the document tab at `index`: its notice bars, then its pages (or the Organize grid) in a+ /// scroll area with this frame's zoom, scrolling, tool input, overlays and render requests.+ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ // Keyboard scrolling applies to this frame's page view only, never later.+ let key_scroll = std::mem::take(&mut app.views[index].key_scroll);+ if key_scroll != 0.0 {+ app.views[index].end_find_following();}-- fn signature(signed: bool, visible: bool, page: Option<usize>, rect: Option<[f64; 4]>) -> pdfcraft_engine::SignatureInfo {- pdfcraft_engine::SignatureInfo {- field: "Signature1".into(),- signed,- page,- rect,- visible,- signer: None,- certificate: None,- chain: Vec::new(),- date: None,- signing_time: None,- reason: None,- location: None,- contact: None,- sub_filter: None,- doc_timestamp: false,- certify: None,- revision: 1,- signed_len: 0,- digest: None,- algorithm: None,- timestamp: false,- timestamp_time: None,- status: pdfcraft_engine::SignatureStatus::Valid,- modification: pdfcraft_engine::sign::Modification::None,- details: Vec::new(),- }+ // The Search panel closed: its search moves to the find bar.+ let search_open = app.right == Some(crate::RightPanel::Search);+ if let Some(f) = app.views[index].find.as_mut()+ && f.in_panel+ && !search_open+ {+ f.in_panel = false;}-- #[test]- fn signature_badges_keep_signed_visible_widgets_on_the_page() {- let rect = [10.0, 10.0, 100.0, 50.0];- let signatures =- vec![signature(true, true, Some(0), Some(rect)), signature(true, true, Some(1), Some(rect)), signature(true, true, Some(0), Some(rect))];- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 2);- assert_eq!(badges[0].rect, rect);+ if close_requested_tab(app, index) {+ return;}-- #[test]- fn signature_badges_skip_unsigned_invisible_and_unplaced_fields() {- let rect = [10.0, 10.0, 100.0, 50.0];- let signatures = vec![- signature(false, true, Some(0), Some(rect)),- signature(true, false, Some(0), Some(rect)),- signature(true, true, Some(0), None),- signature(true, true, Some(0), Some(rect)),- ];- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 1);- assert_eq!(badges[0].rect, rect);+ let Some(doc) = app.session.get(app.views[index].id) else { return };+ let info = &doc.info;+ let paper = app.session.reading_colors(app.views[index].id).and_then(|c| c.params).map_or(Color32::WHITE, |p| {+ let [r, g, b] = p.background;+ Color32::from_rgb(r, g, b)+ });+ if info.pages.is_empty() {+ app.views[index].auto_scroll.cancel();+ ui.centered_and_justified(|ui| ui.label(tl!("This document has no pages.")));+ return;}-- #[test]- fn signature_badges_skip_rectangles_that_cannot_reach_the_screen() {- let hostile = vec![- [f64::NAN, 10.0, 100.0, 50.0],- [10.0, f64::INFINITY, 100.0, 50.0],- [10.0, 10.0, f64::NEG_INFINITY, 50.0],- [10.0, 10.0, 1e300, 50.0],- [10.0, 10.0, 100.0, 50.0],- ];- let signatures: Vec<_> = hostile.into_iter().map(|rect| signature(true, true, Some(0), Some(rect))).collect();- let badges = signature_badges(&signatures, 0);- assert_eq!(badges.len(), 1);+ // The print dialog queues its own rasters later in the frame. Closing it drops them.+ if app.dialog != Some(crate::Dialog::Print) {+ app.views[index].print_pages.clear();+ }+ // The Prepare a form panel is open (or a field tool is picked): fields are edited, not filled.+ let preparing = app.is_preparing();+ // Prepare a form ▸ Calculation order: the order's steps and links on the page.+ let calc_order = preparing && app.left_open && app.left == crate::LeftPanel::CalculationOrder;+ // Edit a PDF: added text and images can be selected, moved and edited.+ let editing_content =+ (app.left_open && app.left == crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText);+ let text_style = app.text_style.clone();+ let show_secured_notice = app.show_secured_notice;+ let view = &mut app.views[index];+ // Opened without the owner password and something is restricted. The notice says so unless+ // the user turned it off (#4035): the restrictions themselves, and Document Properties ▸+ // Security, stay as they are.+ let secured = show_secured_notice && doc.security_summary().is_some_and(|s| !(s.owner || (s.permissions.modify() && s.permissions.assemble())));+ let repaired = !doc.repair_log().is_empty();+ let notice = notices(view, doc, secured, repaired, crate::sign_ui::banner(&doc.signatures), ui, &t);+ apply_notice(app, index, notice);+ let Some(doc) = app.session.get(app.views[index].id) else { return };+ let info = &doc.info;+ // No dialog, close prompt or palette over the page: only then does page input count.+ let modal = app.modal_open();+ let unobstructed = !modal && !app.palette_open;+ let organize_zoom = app.organize_zoom;+ let view = &mut app.views[index];+ if view.organize {+ // One remembered grid size for every document, kept in the settings.+ view.set_grid_zoom(organize_zoom);+ organize_grid(view, info, doc.allows_assembly(), doc.dirty, unobstructed, ui, &t);+ app.organize_zoom = view.grid_zoom();+ return;}- #[test]- fn snapshot_tabs_read_like_their_source_plus_the_suffix() {- let snap = Snapshot { kind: SnapshotKind::SignedVersion, revision: 1, from: "report.pdf".into() };- assert_eq!(snapshot_tab_name("Report", "report.pdf", &snap), "Report (signed version)");- let rev = Snapshot { kind: SnapshotKind::Revision, revision: 2, from: "report.pdf".into() };- assert_eq!(snapshot_tab_name("Report", "report.pdf", &rev), "Report (revision 2)");- assert_eq!(snapshot_tab_name("report.pdf", "report.pdf", &snap), "report.pdf");- assert_eq!(snapshot_tab_name("report (revision 2).pdf", "report (revision 2).pdf", &rev), "report (revision 2).pdf");+ let avail = ui.available_rect_before_wrap();+ view.viewport_w = avail.width();+ view.viewport_h = avail.height();+ let old_zoom = view.zoom;+ view.fit_zoom(info);+ anchor_zoom_change(view, avail.width(), old_zoom);++ // Pinch / ctrl+scroll zoom, anchored on the current page.+ let zoom_delta = crate::motion::zoom_delta(ui.ctx());+ // Exclude the previous frame's scrollbar tracks from gesture activation.+ let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail };+ let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused);+ let present = presentation_click_state(ui, view, navigation_rect, navigation_enabled && app.quick_tool == QuickTool::Select);+ pinch_zoom(ui, view, zoom_delta, navigation_rect, navigation_enabled);+ view.viewport_screen = avail;+ let (auto_delta, edge_delta) = auto_scroll_deltas(ui, view, avail, unobstructed);++ let content_w = view.content_width(info, avail.width());+ let rects = view.layout(info, content_w, ui.ctx().pixels_per_point());+ // When not scrolling continuously, only one row is shown at a time: the current page, or the+ // current two-page spread (with the cover rule). These indices drive paging, which pages are+ // drawn, and the content height (#752). Empty for a document with no pages.+ let row = shown_row(view, &rects);+ let middle_gesture = view.auto_scroll.blocks_input();+ // Not scrolling: when the whole page or spread fits, the wheel would do nothing, so it turns+ // pages instead; zoomed in far enough to pan, it pans, and at the edge it turns the page on+ // (#1924, `single_page_wheel_edge`). Touch drags are untouched: with+ // nothing to pan, touch users turn pages with the rail buttons, the page box and the arrow+ // keys. Runs before `visible_pages` so the frame that turns the page draws it.+ let (single_paging, edge_turned) = single_page_paging(ui, view, &PagingCx { row: &row, rects: &rects, avail, middle_gesture, unobstructed });+ // Point input bypasses egui smoothing for 1:1 motion. Line input keeps egui's configured,+ // smoothed base and adds only the accelerated surplus. While point suppression is active,+ // reconstruct line and page input here so current coarse events survive without exposing an+ // older eased tail.+ let now = ui.input(|i| i.time);+ let Wheel { precise_scroll, line_base, boost_extra, has_page, paging_owns_vertical } = read_wheel(ui, view, avail, single_paging, edge_turned);+ let animates = app.animation_effects.animates(app.motion.reduced);+ let may_glide = !paging_owns_vertical && !middle_gesture && navigation_enabled && unobstructed && animates;+ let wheel_scrolled = precise_scroll != Vec2::ZERO || line_base != Vec2::ZERO || boost_extra != Vec2::ZERO || has_page;+ let motion = GlideCx { now, may_glide, key_scroll, auto_delta, zoom_delta, edge_delta, wheel_scrolled };+ let glide = step_glide(ui, view, avail, &motion);+ // The wheel may have turned the page above: draw the row it turned to. Measured from the old+ // row, the jump to the new page scrolled both out of view, a blank frame on every turn forward.+ let row = shown_row(view, &rects);+ let visible_pages: Vec<usize> = if view.continuous { (0..rects.len()).collect() } else { row.clone() };+ let (y_shift, content_h) = if view.continuous {+ (0.0, rects.iter().map(|r| r.bottom()).reduce(f32::max).map(|bottom| bottom + MARGIN).unwrap_or(0.0))+ } else {+ // Only the current row scrolls into view; the content is its bounding box plus margins.+ match row.iter().filter_map(|&i| rects.get(i)).copied().reduce(Rect::union) {+ Some(r) => (r.top() - MARGIN, r.height() + 2.0 * MARGIN),+ None => (0.0, 0.0),+ }+ };++ let mut scroll = page_scroll_area(+ ui,+ view,+ &ScrollGeometry { rects: &rects, y_shift, content_w, content_h, avail, middle_gesture, hand: app.quick_tool == QuickTool::Hand },+ );+ let ppp = ui.ctx().pixels_per_point();+ let scale = view.render_scale(ppp);+ let tag = scale_tag(scale);+ // Hold sharp re-renders while the zoom is still moving: a new scale every frame would+ // cancel the in-flight full-page interpret and restart it, so on a heavy page (a CAD+ // plot with ~1000 images renders for seconds) the sharp raster never arrives and the+ // view looks stuck on a soft image. The stale raster stays stretched meanwhile; the+ // sharp request goes out once the zoom settles.+ let sharp_held = hold_sharp_renders(ui, view, scale);+ view.current_scale_tag = tag;+ let hand = app.quick_tool == QuickTool::Hand;+ let tool = app.quick_tool;+ // Text selection runs for the Select tool and for the markup tools (highlight…).+ let selects_text = tool_selects_text(tool, preparing);+ let prefs = &app.comment_prefs;+ let redact_mark = (app.redact_prefs.hover_fill, app.redact_prefs.opacity);+ let units = app.units;+ let allowed = doc.allows_annotation();+ let can_copy = doc.allows_copying();+ let comments_hidden = doc.comments_hidden();+ let form = doc.form.clone();+ let generation = doc.edit_generation();+ let can_fill = doc.allows_form_filling();+ let can_crop = doc.allows_assembly();+ let signature = app.signature.clone();+ let initials = app.initials.clone();+ let author = app.comment_prefs.author.clone();+ let today = app.session.today();+ // In Preferences ▸ Date format, or why it can't be stamped into the PDF.+ let date_text = crate::date_text_for_pdf(&app.session);+ let by_line = app.session.stamp_by_line(&author);+ let custom_stamp = match app.quick_tool {+ QuickTool::CustomStamp(i) => app.custom_stamps.get(i).cloned(),+ _ => None,+ };+ let mut open_props: Option<(usize, usize)> = None;+ // The table being set up in its window, shown on its own document's page.+ let table_preview = app.field_table_draft.as_mut().filter(|d| d.doc == view.id).and_then(|d| Some(d.preview(info.pages.get(d.page)?, &form)));+ let can_modify = doc.allows_modification();+ if preparing {+ crate::prepare::after_refresh(view, &form);+ } else {+ view.prepare.selected = None;}-- #[test]- fn grayscale_converts_colours_to_their_luminance() {- let img = egui::ColorImage::new([2, 1], vec![Color32::from_rgb(255, 0, 0), Color32::from_rgba_premultiplied(0, 51, 102, 128)]);- let gray = grayscale(img);- let opaque = gray.pixels[0];- assert_eq!(opaque.to_array(), [76, 76, 76, 255]);- // Unmultiply RGB first, so a translucent colour keeps its paper-relative luminance.- let translucent = gray.pixels[1];- assert_eq!(translucent.to_array(), [42, 42, 42, 128]);+ view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());+ view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);+ let added = if editing_content { doc.added().to_vec() } else { Vec::new() };+ let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };+ if editing_content {+ crate::content_ui::after_refresh(view, &added);+ } else {+ view.content.selected = None;}+ view.move_background.prepare(ui.ctx(), doc, &view.content, scale);- #[test]- fn black_white_and_transparents_are_preserved_by_grayscale() {- let img = egui::ColorImage::new([3, 1], vec![Color32::BLACK, Color32::WHITE, Color32::TRANSPARENT]);- let gray = grayscale(img);- assert_eq!(gray.pixels[0].to_array(), [0, 0, 0, 255]);- assert_eq!(gray.pixels[1].to_array(), [255, 255, 255, 255]);- assert_eq!(gray.pixels[2].to_array(), [0, 0, 0, 0]);- }+ scroll = refine_goto_point(scroll, view, &ScrollGeometry { rects: &rects, y_shift, content_w, content_h, avail, middle_gesture, hand });+ let selection_wheel = view.selection_drag && navigation_enabled && unobstructed && !single_paging && ui.rect_contains_pointer(avail);+ let env = PageEnv {+ added: &added,+ allowed,+ author: &author,+ auto_delta,+ avail,+ boost_extra,+ by_line: &by_line,+ calc_order,+ can_copy,+ can_crop,+ can_fill,+ can_modify,+ comments_hidden,+ content_h,+ content_w,+ custom_stamp: &custom_stamp,+ date_text: &date_text,+ doc,+ doc_links: &doc_links,+ edge_delta,+ editing_content,+ form: &form,+ generation,+ glide,+ hand,+ info,+ initials: &initials,+ key_scroll,+ middle_gesture,+ modal,+ navigation_enabled,+ paper,+ ppp,+ precise_scroll,+ prefs,+ preparing,+ rects: &rects,+ redact_mark,+ scale,+ selection_wheel,+ selects_text,+ signature: &signature,+ single_paging,+ t: &t,+ table_preview: &table_preview,+ tag,+ text_style: &text_style,+ tool,+ units,+ unobstructed,+ visible_pages: &visible_pages,+ y_shift,+ fill_text_size: app.fill_text_size,++ fill_text_color: app.fill_text_color,+ today,+ };+ let mut page_out = PageOut::default();+ let out = page_scroll(ui, scroll, egui::Id::unique(("page-view-scope", view.id)), |ui, viewport| {+ draw_pages(ui, viewport, view, &env, &mut page_out, &mut app.signature_preview)+ });+ let PageOut {+ canvas_action,+ clicked_link,+ mut copy_selected,+ field_menu,+ field_placed,+ mut field_props,+ hover_text,+ mut image_action,+ open_boxes,+ open_initials,+ open_signature,+ open_table,+ primary_down,+ mut refused,+ stamp_placed,+ } = page_out;+ view.single_edges = visible_pages.first().copied().filter(|_| !view.continuous).map(|page| {+ // At the top once the page's top edge shows where going to a page puts it (a gap+ // below the window's top). Within a point, as for wheel paging, so layout rounding+ // can't hide an edge.+ let max_y = (out.content_size.y - out.inner_rect.height()).max(0.0);+ (page, out.state.clamped_offset().y <= MARGIN - view.page_gap() + 1.0, out.state.clamped_offset().y >= max_y - 1.0)+ });- #[test]- fn rendered_rasters_become_texture_images_without_a_copy() {- let pdf = b"%PDF-1.4- 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj- 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj- 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 50] /Contents 4 0 R >> endobj- 4 0 obj << /Length 35 >> stream- 0 0 1 rg 10 10 30 20 re f- endstream endobj- trailer << /Root 1 0 R >>- %%EOF";- let mut r = pdfcraft_render::PageRenderer::new(Arc::new(pdf.to_vec()), Default::default());- let out = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.5, tag: 0, preview: false });- assert!(out.error.is_none(), "{:?}", out.error);- let size = [out.width as usize, out.height as usize];- let copied = egui::ColorImage::from_rgba_premultiplied(size, &out.rgba);- let at = out.rgba.as_ptr();- let img = texture_image(size, out.rgba);- assert_eq!(img, copied);- assert_eq!(img.pixels.as_ptr().cast::<u8>(), at, "the renderer's own buffer");+ view.viewport_screen = out.inner_rect;+ view.auto_scroll.paint(ui, avail);+ if unobstructed && matches!(tool, QuickTool::Select | QuickTool::ColumnSelect) {+ copy_selected |= selection_actions(ui, avail, view, info, prefs, allowed && !comments_hidden, can_copy);}- #[test]- fn tiles_stay_granular_up_close_and_cover_giant_sheets_in_a_handful() {- // Ordinary zooms keep 1024 px tiles; degenerate scales fall back to it, never zero.- assert_eq!(tile_side(1.0, 2000), TILE);- assert_eq!(tile_side(4.0, 2000), TILE);- assert_eq!(tile_side(f32::NAN, 2000), TILE);- assert_eq!(tile_side(f32::INFINITY, 2000), TILE);- assert_eq!(tile_side(0.0, 2000), TILE);- // Zoomed viewports need a few large tiles instead of many small ones.- assert_eq!(tile_side(12.0, 2000), 2048);- assert_eq!(tile_side(20.0, 2000), 3413);- assert_eq!(tile_side(100.0, 2000), 4096);- // A giant sheet at fit width (6740 px long side) is covered four tiles a side.- assert_eq!(tile_side(96.0 / 72.0, 6740), 1685);- // The backend clamps tile sides at 4096.- assert_eq!(tile_side(20.0, 100_000), 4096);- }+ // Collect all main-page demand, including cached surfaces, for byte admission later.+ // Pan-settle debounce for tiled pages: each tile costs a full page interpret, so holding+ // fresh tiles back while the scroll offset is still moving keeps a drag on the stretched+ // backdrop/older tiles instead of queueing a storm of interprets (one per frame) that+ // the workers cannot cancel mid-operator. Fresh tiles go out once the pan settles;+ // pages with nothing on screen yet still queue.+ let pan_held = track_scroll(ui, view, &out, glide);+ plan_renders(ui, view, info, out.inner, &RenderPlan { visible_pages: &visible_pages, tag, scale, sharp_held, pan_held, hand });- #[test]- fn grid_zoom_is_clamped_and_sharp_renders_tolerate_a_pinch() {- assert!(sharp_enough(900, 876.0) && sharp_enough(800, 876.0) && sharp_enough(1300, 876.0));- assert!(!sharp_enough(264, 876.0), "a thumbnail stretched over a zoomed page");- assert!(!sharp_enough(876, 200.0), "far larger than drawn: wasteful");- assert!(!sharp_enough(100, 0.0) && !sharp_enough(100, f32::NAN));- let mut v = view(3, PageLayout::Single, true);- for odd in [f32::NAN, f32::INFINITY] {- v.set_grid_zoom(odd);- assert_eq!(v.grid_zoom(), 1.0);- }- v.set_grid_zoom(99.0);- assert_eq!(v.grid_zoom(), 3.0);- v.set_grid_zoom(-4.0);- assert_eq!(v.grid_zoom(), 0.5);+ let text_done = frame_overlays(ui, view, &env, primary_down, hover_text);+ if let Some(why) = view.objects.notice.take() {+ refused = Some(why);}-- fn view(pages: usize, layout: PageLayout, continuous: bool) -> DocView {- let info = pdfcraft_render::DocInfo {- pages: (0..pages)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- DocView::new(DocId(1), &info, ViewDefaults { layout, continuous, ..Default::default() })+ let form_notice = view.forms.notice.take();+ // One crop, then back to selecting (as Acrobat does).+ let cropped = view.pending_edit.as_ref().is_some_and(|e| matches!(e, pdfcraft_engine::Edit::SetPageBox { .. }));+ let mut tool = app.quick_tool;+ comments::keys(ui.ctx(), view, &mut tool, allowed);+ if preparing {+ crate::prepare::keys(ui.ctx(), view);}-- fn history_search_view() -> DocView {- let mut v = view(5, PageLayout::Single, true);- v.texts.insert(- 3,- pdfcraft_render::PageText {- glyphs: vec![pdfcraft_render::TextGlyph {- text: "match".into(),- rect: [20.0, 260.0, 60.0, 280.0],- quad: [[20.0, 260.0], [60.0, 260.0], [60.0, 280.0], [20.0, 280.0]],- direction: [1.0, 0.0],- }],- line_of: vec![0],- space_before: vec![false],- }- .into(),- );- v.find = Some(Find { matches: vec![(3, 0..1), (3, 0..1), (1, 0..1)], current: Some(2), ..Default::default() });- v+ if editing_content {+ crate::content_ui::keys(ui.ctx(), view);}-- #[test]- fn explicit_search_jumps_record_history_and_keep_match_destination() {- for step in [None, Some(true), Some(false)] {- let mut v = history_search_view();- v.page_input = "draft in progress".into();- v.goto_point = Some((3, Some(0.8), Some(0.9), Vec2::ZERO));- if let Some(forward) = step {- v.find_step(forward);- } else {- v.go_to_match(0);- }- assert_eq!(v.back, vec![0], "explicit search jump must remember its origin");- assert_eq!(v.goto, Some((3, 0.5)), "keep the match offset instead of the page top");- assert_eq!(v.current, 3);- assert_eq!(v.current_page_label(None), "4");- // Chrome refreshes the idle page box; navigation must not overwrite a draft- // that may still be focused. DocView does not own the editor's focus state.- assert_eq!(v.page_input, "draft in progress");- assert!(v.goto_point.is_none(), "an earlier link destination cannot override the search offset");- v.go_to_match(1);- assert_eq!(v.back, vec![0], "same-page matches do not duplicate history");- assert!(v.view_history(false));- assert_eq!(v.current, 0);- assert!(v.view_history(true));- assert_eq!(v.current, 3);- assert!(v.view_history(false));- v.go_to_match(2);- assert!(v.forward.is_empty(), "a new explicit jump discards Forward");- assert_eq!(v.back, vec![0]);- }+ if tool == QuickTool::Link {+ crate::link_ui::keys(ui.ctx(), view);+ } else {+ view.links.selected = None;}-- #[test]- fn automatic_search_updates_do_not_record_history_or_discard_forward() {- let mut v = history_search_view();- v.forward = vec![4];- v.find = Some(Find { query: "match".into(), ..Default::default() });- v.rerun_find();- assert_eq!(v.current, 3);- assert_eq!(v.goto, Some((3, 0.5)));- assert!(v.back.is_empty());- assert_eq!(v.forward, vec![4]);- v.current = 0;- v.find.as_mut().unwrap().current = None;- v.refresh_find_page(3);- assert_eq!(v.current, 3);- assert!(v.back.is_empty());- assert_eq!(v.forward, vec![4]);+ if stamp_placed {+ tool = QuickTool::Select;}-- #[test]- fn text_layers_evict_far_pages_but_keep_visible_and_matches() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.current = 50;- v.frame_visible = HashSet::from([50, 51]);- for p in 0..100 {- v.texts.insert(p, Arc::new(PageText::default()));- }- v.text_failed.insert(0);- v.text_failed.insert(99);- v.find = Some(Find { matches: vec![(0, 0..1)], ..Default::default() });- let _ = v.prepare_render_queue(&info, 1.0);- assert!(v.texts.contains_key(&50) && v.texts.contains_key(&51), "visible pages stay");- assert!(v.texts.contains_key(&0), "matched pages stay");- assert!(v.texts.contains_key(&49), "nearest prefetch window stays");- assert!(!v.texts.contains_key(&99), "far pages go");- assert_eq!(v.texts.len(), 2 + 1 + MAX_CACHED_TEXT_PAGES, "visible + matched + prefetch window");- assert!(v.text_failed.contains(&0) && v.text_failed.contains(&99), "failures are bytes-free: never evict");+ // Text: each click on the page starts a box (#74); Done in the editor goes back to selecting.+ if text_done && tool == QuickTool::AddText {+ tool = QuickTool::Select;}-- #[test]- fn text_layers_keep_the_selection_page() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let text = PageText {- glyphs: vec![pdfcraft_render::TextGlyph { text: "x".into(), rect: [0.0, 0.0, 10.0, 10.0], quad: [[0.0, 0.0]; 4], direction: [1.0, 0.0] }],- line_of: vec![0],- space_before: vec![false],- };- for p in 0..100 {- v.texts.insert(p, Arc::new(text.clone()));- }- v.select_text(0, 0, 0);- v.current = 90;- v.frame_visible = HashSet::from([90, 91]);- let _ = v.prepare_render_queue(&info, 1.0);- assert_eq!(v.selected_text().as_deref(), Some("x"), "stale selections still copy");+ // One field, then back to selecting (Acrobat's default without "Keep tools pinned").+ if field_placed {+ tool = QuickTool::Select;}-- #[test]- fn text_layers_stay_while_a_search_is_active() {- let info = thumbnail_info(100);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.current = 50;- v.frame_visible = HashSet::from([50]);- for p in 0..100 {- v.texts.insert(p, Arc::new(PageText::default()));- }- v.find = Some(Find { query: "dup".into(), case_query: "dup".into(), matches: vec![(0, 0..1)], ..Default::default() });- let _ = v.prepare_render_queue(&info, 1.0);- assert_eq!(v.texts.len(), 100, "evicting mid-search would churn the workers");+ if matches!(field_menu, Some(FieldMenu::Properties)) {+ field_props = true;}-- fn thumbnail_info(count: usize) -> DocInfo {- DocInfo {- pages: (0..count)- .map(|i| {- let (width, height) = match i % 3 {- 0 => (612.0, 792.0),- 1 => (200.0, 4000.0),- _ => (4000.0, 200.0),- };- pdfcraft_render::PageInfo { width, height, label: (i + 1).to_string(), crop: [0.0, 0.0, width, height], rotation: 0 }- })- .collect(),- ..Default::default()+ let field_props = field_props.then(|| view.prepare.selected.clone()).flatten();+ match canvas_action {+ Some(comments::CanvasAction::Edit(e)) => view.pending_edit = Some(*e),+ // `choose_right_panel` would borrow all of `app` while `view` is held; same effect.+ Some(comments::CanvasAction::OpenComments) => {+ app.right = Some(RightPanel::Comments);+ app.comments_panel_closed = false;}+ Some(comments::CanvasAction::Properties(p, i)) => open_props = Some((p, i)),+ Some(comments::CanvasAction::CopyImage(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::Copy(p, i)),+ Some(comments::CanvasAction::CopyImageFile(p, i)) => image_action = Some(crate::edit_text_ui::ImageAction::CopyFile(p, i)),+ None => {}}-- #[test]- fn ten_thousand_pages_only_demand_viewport_and_prefetch_at_both_densities() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let cols = 4;- let rows = info.pages.len().div_ceil(cols);- for ppp in [1.0, 2.0] {- for row in [0, 1234, rows - 1] {- v.begin_render_frame();- let range = thumbnail_rows(row as f32 * 250.0, row as f32 * 250.0 + 750.0, 250.0, rows);- for p in range.start * cols..(range.end * cols).min(info.pages.len()) {- v.need_thumbnail(p, p / cols == row);- }- let queue = v.prepare_render_queue(&info, ppp);- assert!(queue.len() <= 5 * cols, "only three visible rows and two prefetch rows");- assert_eq!(queue.first().unwrap().page / cols, row, "visible cells precede prefetch");- let bytes: usize = queue- .iter()- .map(|r| {- let p = &info.pages[r.page];- let (w, h) = (device_pixels(p.width, r.scale), device_pixels(p.height, r.scale));- assert!(w <= (THUMB_W * ppp).ceil() as u32);- assert!(h <= (THUMB_H * ppp).ceil() as u32);- rgba_bytes(w as usize, h as usize)- })- .sum();- assert!(bytes <= THUMB_BYTES);- assert_eq!(queue, v.prepare_render_queue(&info, ppp), "unchanged demand reconstructs the same work");- }- }+ schedule_presentation_turn(ui, view, present, clicked_link.is_some());+ let remote_open = follow_link(app, index, clicked_link);+ if tool == QuickTool::Crop && cropped {+ tool = QuickTool::Select;}+ let tool = finish_sign_requests(app, index, tool);+ app.quick_tool = tool;+ let requests = FrameRequests {+ open_props,+ field_props,+ field_menu,+ image_action,+ refused,+ open_signature,+ open_initials,+ open_boxes,+ open_table,+ form_notice,+ copy_selected,+ remote_open,+ form,+ generation,+ avail,+ };+ apply_frame_requests(app, index, ui, requests);+ }- #[test]- fn oversized_thumbnail_viewport_scales_all_admitted_cells_to_one_budget() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- for page in 0..MAX_THUMB_DEMAND {- v.need_thumbnail(page, true);- }- let queue = v.prepare_render_queue(&info, 2.0);- assert_eq!(queue.len(), MAX_THUMB_DEMAND);- let bytes: usize = queue- .iter()- .map(|r| {- let p = &info.pages[r.page];- rgba_bytes(device_pixels(p.width, r.scale) as usize, device_pixels(p.height, r.scale) as usize)- })- .sum();- assert!(bytes <= THUMB_BYTES);- }+ /// What the frame's input asked the app to do, once the document is no longer borrowed.+ struct FrameRequests {+ open_props: Option<(usize, usize)>,+ field_props: Option<(String, usize)>,+ field_menu: Option<FieldMenu>,+ image_action: Option<crate::edit_text_ui::ImageAction>,+ refused: Option<String>,+ open_signature: bool,+ open_initials: bool,+ open_boxes: bool,+ open_table: Option<(usize, [f64; 4])>,+ form_notice: Option<crate::forms_ui::FormNotice>,+ copy_selected: bool,+ remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)>,+ form: Arc<Vec<pdfcraft_engine::FormField>>,+ generation: u64,+ avail: Rect,+ }- fn solid_result(request: RenderRequest, w: u32, h: u32) -> pdfcraft_render::RenderedPage {- pdfcraft_render::RenderedPage {- request,- width: w,- height: h,- rgba: pdfcraft_render::Pixels::from(vec![u32::MAX; rgba_bytes(w as usize, h as usize) / 4]),- text: None,- error: None,- warnings: Vec::new(),- millis: 0,- }+ /// Opens the dialogs and runs the app commands the frame asked for.+ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, requests: FrameRequests) {+ let FrameRequests {+ open_props,+ field_props,+ field_menu,+ image_action,+ refused,+ open_signature,+ open_initials,+ open_boxes,+ open_table,+ form_notice,+ copy_selected,+ remote_open,+ form,+ generation,+ avail,+ } = requests;+ if let Some((page, at)) = app.views[index].comments.attach_at.take() {+ app.attach_file_comment(page, at);}-- #[test]- fn thumbnails_release_on_scroll_panel_close_and_request_again_after_eviction() {- let ctx = egui::Context::default();- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let first = v.prepare_render_queue(&info, 1.0);- v.last_queue = first.clone();- assert_eq!(v.receive_result(&ctx, solid_result(first[0], 132, 171)), 132 * 171 * 4);- assert!(v.prepare_render_queue(&info, 1.0).is_empty());- v.begin_render_frame();- v.need_thumbnail(9999, true);- v.prepare_render_queue(&info, 1.0);- assert!(v.thumbs.is_empty(), "jump releases old handles");- v.begin_render_frame();- v.need_thumbnail(0, true);- assert_eq!(v.prepare_render_queue(&info, 1.0), first, "an evicted result must be requested again");- v.begin_render_frame();- assert!(v.prepare_render_queue(&info, 1.0).is_empty(), "closing consumers cancels thumbnail work");+ if let Some((p, i)) = open_props {+ app.open_comment_props(p, i);}-- #[test]- fn stale_results_are_rejected_before_conversion_after_dpi_invalidation_and_suspend() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let first = v.prepare_render_queue(&info, 1.0)[0];- v.last_queue = v.prepare_render_queue(&info, 2.0);- // Valid pixels: only the request gate can keep these out (a size check can't).- let obsolete = || solid_result(first, 132, 171);- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "a result for the old DPI is not uploaded");- // The same result is uploaded while its request is current.- v.last_queue = vec![first];- assert_eq!(v.receive_result(&ctx, obsolete()), 132 * 171 * 4);- v.thumbs.clear();- v.invalidate_content();- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "nor after the content changed");- let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());- v.last_queue = vec![first];- v.suspend_rendering(&pool);- assert_eq!(v.receive_result(&ctx, obsolete()), 0);- assert!(v.thumbs.is_empty(), "nor after the tab was suspended");+ if let Some((p, i)) = app.views[index].comments.default_request.take() {+ app.make_comment_default(p, i);}-- #[test]- fn editing_after_layout_preserves_stale_page_until_replacement() {- let ctx = egui::Context::default();- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = RenderRequest { scale: 1.0, tag: 1000, ..Default::default() };- v.last_queue = vec![req];- v.receive_result(&ctx, solid_result(req, 10, 10));- v.frame_queue = vec![req];- v.page_changed(0);- assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req]);- assert_eq!(v.pages.get(&0).unwrap().tag, STALE_TAG);+ if let Some((p, i, open)) = app.views[index].comments.attachment_request.take() {+ let doc = app.views[index].id;+ app.comment_attachment_action(doc, p, i, open);}-- #[test]- fn page_and_tile_admission_accounts_for_bytes_before_count_limits() {- let mut info = thumbnail_info(40);- for p in &mut info.pages {- p.width = 4000.0;- p.height = 4000.0;- }- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();- let queue = v.prepare_render_queue(&info, 1.0);- assert_eq!(queue.len(), 2, "128 MiB admits two 4000-square pages, not 24");- v.frame_queue = (0..40)- .map(|page| RenderRequest { page, scale: 1.0, tag: 1000, tile: Some(Tile { x: 0, y: 0, w: 1024, h: 1024 }), ..Default::default() })- .collect();- assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 32);- assert!(!v.admit_texture(RenderRequest::default(), PAGE_BYTES + 1));+ if let Some((name, w)) = field_props {+ app.open_field_props(&name, w);}-- #[test]- fn on_screen_pages_and_tiles_are_admitted_beyond_the_prefetch_allowance() {- let ctx = egui::Context::default();- let mut info = thumbnail_info(40);- for p in &mut info.pages {- p.width = 2000.0;- p.height = 2000.0;- }- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- // Ten 16 MB pages on screen (a zoomed-out HiDPI view) exceed the 128 MiB allowance.- v.frame_visible = (0..10).collect();- v.frame_queue = (0..40).map(|page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() }).collect();- let queue = v.prepare_render_queue(&info, 1.0);- let pages: Vec<usize> = queue.iter().map(|r| r.page).collect();- assert_eq!(pages, (0..10).collect::<Vec<_>>(), "every on-screen page, and no prefetch past the allowance");- v.last_queue = queue.clone();- for req in &queue {- assert!(v.receive_result(&ctx, solid_result(*req, 2000, 2000)) > 0, "on-screen page {} uploaded", req.page);- }- assert_eq!(v.pages.len(), 10, "none evicted another on-screen page");- // A 5K viewport needs more 1024-pixel tiles than the tile allowance holds.- v.frame_queue = (0..40)- .map(|x| RenderRequest { page: 0, scale: 1.0, tag: 1000, tile: Some(Tile { x: x * TILE, y: 0, w: 1024, h: 1024 }), ..Default::default() })- .collect();- assert_eq!(v.prepare_render_queue(&info, 1.0).len(), 40);+ if let Some(FieldMenu::Duplicate(name)) = field_menu {+ let pages = app.session.get(app.views[index].id).map_or(1, |d| d.info.pages.len());+ app.duplicate_draft = Some(crate::DuplicateDraft { name, all: true, from: 1, to: pages });+ app.dialog = Some(crate::Dialog::DuplicateField);}-- #[test]- fn a_page_turned_back_to_is_still_cached() {- let ctx = egui::Context::default();- let info = thumbnail_info(10);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let req = |page| RenderRequest { page, scale: 1.0, tag: 1000, ..Default::default() };- v.frame_visible = [0].into();- v.frame_queue = vec![req(0)];- v.last_queue = v.prepare_render_queue(&info, 1.0);- v.receive_result(&ctx, solid_result(req(0), 100, 130));- // Single-page view moves on to page 1: page 0 is no longer demanded.- v.begin_render_frame();- v.current = 1;- v.frame_visible = [1].into();- v.frame_queue = vec![req(1)];- assert_eq!(v.prepare_render_queue(&info, 1.0), vec![req(1)]);- assert!(v.pages.contains_key(&0), "kept while the allowance has room");- // And back: nothing to render.- v.begin_render_frame();- v.current = 0;- v.frame_visible = [0].into();- v.frame_queue = vec![req(0)];- assert!(v.prepare_render_queue(&info, 1.0).is_empty());+ if let Some((page, rect)) = app.views[index].links.open_new.take() {+ app.open_link_props(page, Some(rect), None);}-- #[test]- fn visible_pages_render_before_thumbnails_and_text() {- let ctx = egui::Context::default();- let info = thumbnail_info(4);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let main = RenderRequest { page: 0, scale: 1.0, tag: 1000, ..Default::default() };- let text = RenderRequest { page: 0, kind: RequestKind::Text, scale: 1.0, tag: TEXT_TAG, ..Default::default() };- // Opening page 0 queues its pixels and text alongside Pages-panel thumbnails.- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![main, text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert_eq!(queue, vec![main], "visible pixels first: no thumbnails or text yet");- // Once the visible raster arrives, background work is admitted.- v.last_queue = queue;- assert!(v.receive_result(&ctx, solid_result(main, 100, 130)) > 0);- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted after pixels");- assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails admitted after pixels");- assert!(!queue.iter().any(|r| r.kind == RequestKind::Pixels && r.tag & THUMB_TAG == 0), "no main pixels re-requested");- // An errored visible page never holds background work back.- v.errors.insert(0, "gone".to_string());- v.begin_render_frame();- v.frame_visible = [0].into();- v.frame_queue = vec![main, text];- for p in 1..4 {- v.need_thumbnail(p, true);- }- let queue = v.prepare_render_queue(&info, 1.0);- assert!(queue.iter().any(|r| r.kind == RequestKind::Text), "text admitted despite the error");- assert!(queue.iter().any(|r| r.tag & THUMB_TAG != 0), "thumbnails still admitted");+ if let Some((page, i)) = app.views[index].links.open_existing.take() {+ app.open_link_props(page, None, Some(i));}-- #[test]- fn thumbnail_tags_do_not_change_as_a_row_scrolls_in_or_out() {- let info = thumbnail_info(10_000);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- let tags = |v: &mut DocView, cells: usize| {- v.begin_render_frame();- for page in 0..cells {- v.need_thumbnail(page, true);- }- v.thumbnail_requests(&info, 2.0).into_iter().map(|r| (r.page, r.tag)).collect::<HashMap<_, _>>()- };- // 2x on a large screen: about 70 cells, give or take a row of six.- let (a, b) = (tags(&mut v, 70), tags(&mut v, 76));- assert!((0..70).all(|p| a[&p] == b[&p]), "a row more or less re-renders nothing");+ if let Some((page, quads)) = app.views[index].pending_redaction.take() {+ let author = app.comment_prefs.author.clone();+ app.views[index].pending_edit = Some(if app.quick_tool == QuickTool::Comment(comments::CommentTool::Highlight) {+ // An area highlight: a highlight over the box.+ let style = app.comment_prefs.style(comments::CommentTool::Highlight);+ pdfcraft_engine::Edit::AddAnnotation(pdfcraft_engine::NewAnnotation {+ page,+ shape: pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, quads },+ style,+ contents: String::new(),+ author,+ })+ } else {+ app.redact_prefs.mark(page, quads, &author)+ });}-- #[test]- fn many_open_documents_share_one_raster_allowance_and_close_releases_handles() {- let ctx = egui::Context::default();- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(612.0, 792.0, 1).unwrap();- let mut expected = Vec::new();- for index in 0..6 {- app.open_bytes(&format!("synthetic-{index}.pdf"), None, bytes.as_ref().clone()).unwrap();- let info = app.session.get(app.views.last().unwrap().id).unwrap().info.clone();- let view = app.views.last_mut().unwrap();- view.begin_render_frame();- view.need_thumbnail(0, true);- let request = view.thumbnail_requests(&info, ctx.pixels_per_point()).into_iter().next().unwrap();- let page = info.pages.get(request.page).unwrap();- let dimensions = (device_pixels(page.width, request.scale), device_pixels(page.height, request.scale));- view.last_queue = vec![request];- assert_eq!(- view.receive_result(&ctx, solid_result(request, dimensions.0, dimensions.1)),- rgba_bytes(dimensions.0 as usize, dimensions.1 as usize)- );- assert_eq!(view.thumbs.get(&0).unwrap().tag, request.tag);- assert_eq!(view.thumbs.get(&0).unwrap().tex.size(), [dimensions.0 as usize, dimensions.1 as usize]);-- view.begin_render_frame();- view.need_thumbnail(0, true);- let queue = view.prepare_render_queue(&info, ctx.pixels_per_point());- assert!(queue.is_empty(), "the synthetic thumbnail satisfies current demand");- view.last_queue = queue;- expected.push((request, dimensions));+ match image_action {+ Some(crate::edit_text_ui::ImageAction::Replace(page, index)) => app.replace_page_image_dialog(page, index),+ Some(crate::edit_text_ui::ImageAction::Save(page, index)) => app.save_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Copy(page, index)) => {+ app.copy_page_image(page, index);}- assert_eq!(app.views.len(), 6, "all six documents were opened");- assert_eq!(app.active_ids().map(|(index, _)| index), Some(5));- assert!(app.views.iter().zip(&expected).all(|(view, (request, dimensions))| {- view.thumbs.len() == 1- && view- .thumbs- .get(&0)- .is_some_and(|thumb| thumb.tag == request.tag && thumb.tex.size() == [dimensions.0 as usize, dimensions.1 as usize])- }));-- app.finish_render_frame(&ctx);- let total: usize = app.views.iter().map(|v| v.thumbs.values().map(|p| texture_bytes(&p.tex)).sum::<usize>()).sum();- let (active_request, active_dimensions) = expected.last().unwrap();- let active_bytes = rgba_bytes(active_dimensions.0 as usize, active_dimensions.1 as usize);- assert_eq!(total, active_bytes, "only the active view retains a thumbnail");- assert!(total <= THUMB_BYTES, "retained thumbnails stay within the existing allowance");- assert!(app.views.iter().take(5).all(|v| v.thumbs.is_empty() && v.last_queue.is_empty()));- let active = app.views.last().unwrap();- assert_eq!(active.thumbs.len(), 1);- assert_eq!(active.thumbs.get(&0).unwrap().tag, active_request.tag);- assert!(active.last_queue.is_empty(), "the current thumbnail is already cached");- for view in &app.views {- let doc = app.session.get(view.id).unwrap();- assert_eq!(doc.renderer.stats().render_requests, 0, "the fixture must not launch a native render");+ Some(crate::edit_text_ui::ImageAction::CopyFile(page, index)) => app.copy_page_image_file(page, index),+ Some(crate::edit_text_ui::ImageAction::Cut(page, image)) => {+ app.views[index].image_selection = None;+ app.cut_page_image(page, image);}-- app.close_tab(5);- assert_eq!(app.views.len(), 5, "closing the active tab drops its owning view");- assert!(app.views.iter().all(|v| v.thumbs.is_empty()));- }-- #[test]- fn suspended_signature_preview_releases_layers_and_rebuilds_without_editing() {- let ctx = egui::Context::default();- let mut png = std::io::Cursor::new(Vec::new());- image::RgbaImage::from_pixel(12, 4, image::Rgba([20, 30, 40, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();- let image = pdfcraft_engine::SignatureImage::from_bytes(png.get_ref()).unwrap();- let mut session = pdfcraft_engine::Session::new();- let blank = session.create_blank(300.0, 400.0, 1).unwrap();- let id = session.open_new("signature-preview.pdf", blank).unwrap();- let info = session.get(id).unwrap().info.pages[0].clone();- session.apply(id, image.edit(0, &info, [20.0, 100.0], false, "Test").unwrap()).unwrap();- let doc = session.get(id).unwrap();- let bytes = doc.bytes.clone();- let generation = doc.edit_generation();- let mut v = DocView::new(id, &doc.info, ViewDefaults::default());- v.comments.selected = Some((0, 0));- v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);- assert!(v.signature_drag.contains(0, 0));-- v.suspend_rendering(&doc.renderer);- assert!(!v.signature_drag.contains(0, 0), "inactive tabs release the preview pool and textures");- assert_eq!(v.comments.selected, Some((0, 0)), "the user's selection survives suspension");- v.signature_drag.prepare(&ctx, doc, v.comments.selected, 1.0);- assert!(v.signature_drag.contains(0, 0), "reactivating the view rebuilds the selected image's preview");- assert!(Arc::ptr_eq(&bytes, &doc.bytes));- assert_eq!(doc.edit_generation(), generation);- assert_eq!(doc.can_undo(), Some("Add signature"));- assert!(doc.dirty);- }-- #[test]- fn suspending_a_view_releases_owned_raster_textures_and_queue_state() {- let ctx = egui::Context::default();- let mut view = view(2, PageLayout::Single, true);- let texture = |name| ctx.load_texture(name, egui::ColorImage::filled([1, 1], Color32::WHITE), TextureOptions::LINEAR);- let request = RenderRequest { page: 0, scale: 1.0, tag: 1, ..Default::default() };- view.pages.insert(0, PageTex { tag: request.tag, tex: texture("suspended-page") });- view.thumbs.insert(1, PageTex { tag: THUMB_TAG, tex: texture("suspended-thumbnail") });- view.tiles.insert((0, request.tag, 0, 0), texture("suspended-tile"));- view.grid_pages.insert(1, (1, texture("suspended-grid-page")));- view.print_pages.insert(1, (PRINT_TAG, texture("suspended-print-page")));- view.stale_thumbs.insert(1);- view.waiting_since.insert(0, 1.0);- view.last_queue = vec![request];- view.frame_queue = vec![request];- view.frame_visible.insert(0);- view.need_thumbnail(1, true);-- let pool = RenderPool::new_inline(Arc::new(Vec::new()), Default::default());- view.suspend_rendering(&pool);-- assert!(view.pages.is_empty(), "page handles are released");- assert!(view.thumbs.is_empty(), "thumbnail handles are released");- assert!(view.tiles.is_empty(), "tile handles are released");- assert!(view.grid_pages.is_empty(), "organize-grid handles are released");- assert!(view.print_pages.is_empty(), "print-preview handles are released");- assert!(view.stale_thumbs.is_empty(), "stale thumbnail bookkeeping is cleared");- assert!(view.waiting_since.is_empty(), "waiting bookkeeping is cleared");- assert!(view.last_queue.is_empty() && !view.render_pending(), "queued demand is retired");- assert!(view.frame_queue.is_empty() && view.frame_visible.is_empty() && view.thumb_demand.is_empty());- }-- /// Edit text & images keeps its boxes while page input is blocked (the window unfocused, a- /// dialog or the palette open): the page's paragraphs are still measured for the latest edit- /// and drawn, instead of vanishing until the pointer comes back.- #[test]- fn edit_text_boxes_stay_drawn_while_page_input_is_blocked() {- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(300.0, 400.0, 1).unwrap();- app.open_bytes("blank.pdf", None, bytes.as_ref().clone()).unwrap();- app.quick_tool = QuickTool::EditText;- app- });- h.run_steps(3);- // Block page input the way the window losing focus does.- h.state_mut().palette_open = true;- h.run_steps(2);- assert!(h.state_mut().apply_edit(Edit::RotatePages { pages: vec![0], degrees: 90 }));- h.run_steps(3);- let app = h.state();- let generation = app.session.get(app.views[0].id).unwrap().edit_generation();- assert_eq!(app.views[0].edit_lines.get(&0).map(|(g, _)| *g), Some(generation), "the boxes follow the edit while input is blocked");- }-- #[test]- fn virtualized_organizer_keeps_insert_gaps_at_document_positions() {- use egui_kittest::kittest::Queryable;-- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(300.0, 400.0, 100).unwrap();- app.open_bytes("organize-gaps.pdf", None, bytes.as_ref().clone()).unwrap();- app.views[0].organize = true;- app- });- h.run_steps(4);- assert!(h.state().views[0].thumb_demand.len() < 50);- assert_eq!(h.query_all_by_label("Insert a file at the end").count(), 0, "the last virtualized cell is not the final page");- let center = h.state().views[0].viewport_rect().center();- h.hover_at(center);- h.event(egui::Event::MouseWheel {- unit: egui::MouseWheelUnit::Point,- delta: vec2(0.0, -100_000.0),- phase: egui::TouchPhase::Move,- modifiers: egui::Modifiers::NONE,- });- // Well past egui's longest scroll animation (about 0.3 s).- h.run_steps(40);- h.get_by_label("Insert a file at the end");- let before_last = h.get_by_label("Insert a file before page 100").rect().center();- h.hover_at(before_last);- h.run_steps(2);- assert_eq!(h.state().views[0].grid_gap, Some(99), "external drops use the document index after virtualized scrolling");- assert!(h.state().views[0].thumb_demand.len() < 50);- }-- #[test]- fn real_shell_pages_organizer_and_print_only_collect_current_thumbnail_consumers() {- let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| {- let mut app = PdfCraftApp::new();- let bytes = app.session.create_blank(612.0, 792.0, 10_000).unwrap();- app.open_bytes("synthetic-ten-thousand.pdf", None, bytes.as_ref().clone()).unwrap();- app.right = Some(RightPanel::Pages);- app- });- h.run_steps(4);- assert!((1..20).contains(&h.state().views[0].thumb_demand.len()));- h.state_mut().right = None;- h.state_mut().views[0].organize = true;- h.run_steps(2);- assert!((1..50).contains(&h.state().views[0].thumb_demand.len()));- h.state_mut().views[0].organize = false;- h.state_mut().dialog = Some(crate::Dialog::Print);- h.state_mut().print_draft.sheet = 9999;- h.run_steps(2);- assert_eq!(h.state().views[0].thumb_demand.keys().copied().collect::<Vec<_>>(), vec![9999]);- h.state_mut().print_draft.handling = crate::PrintHandling::Booklet;- h.state_mut().print_draft.sheet = 0;- h.run_steps(2);- assert_eq!(h.state().views[0].thumb_demand.len(), 2, "booklet only needs its two placed pages");- h.state_mut().dialog = None;- h.run_steps(2);- assert!(h.state().views[0].thumb_demand.is_empty());- assert!(h.state().views[0].thumbs.is_empty());+ Some(crate::edit_text_ui::ImageAction::Redact(page, index)) => app.redact_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Link(page, index)) => app.link_page_image(page, index),+ Some(crate::edit_text_ui::ImageAction::Recognize(page)) => app.recognize_text_on_page(page),+ None => {}}-- /// One mouse-wheel notch (a line) at `at` seconds.- fn notch(v: &mut DocView, dy: f32, at: f64) -> bool {- v.single_page_wheel(egui::MouseWheelUnit::Line, dy, egui::TouchPhase::Move, at, true)+ if let Some(why) = refused {+ app.notify_error(why);}-- #[test]- fn thumbnails_cover_the_panel_on_a_high_dpi_screen() {- // Pages panel slot is at most 150 logical points. At 2 px/pt a letter page's thumbnail- // must be at least that wide, so the panel samples it down instead of stretching it.- let info = thumbnail_info(1);- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- v.need_thumbnail(0, true);- let queue = v.prepare_render_queue(&info, 2.0);- let scale = queue.first().expect("one thumbnail").scale;- assert!(612.0 * scale >= 150.0 * 2.0, "{scale}");+ if open_signature || open_initials {+ app.signature_draft = crate::fill_sign::SigDraft::new(open_initials, &app.comment_prefs.author);+ app.dialog = Some(crate::Dialog::Signature);}-- #[test]- fn notches_turn_pages_and_stop_at_the_ends() {- let mut v = view(3, PageLayout::Single, false);- assert!(notch(&mut v, -1.0, 1.0) && notch(&mut v, -1.0, 1.05));- assert_eq!(v.current, 2);- assert!(!notch(&mut v, -1.0, 1.1), "nothing turns past the last page");- assert!(notch(&mut v, 1.0, 1.2));- assert_eq!(v.current, 1);+ if open_boxes {+ app.boxes_draft.range = crate::pageboxes::Range::Current;+ app.boxes_draft.seeded = None;+ app.dialog = Some(crate::Dialog::PageBoxes);}-- #[test]- fn notches_turn_two_page_spreads() {- // Two-page view, shown one spread at a time (not continuous): a notch turns a whole- // spread at once, not a single page (#752).- let mut v = view(4, PageLayout::TwoUp, false);- assert!(notch(&mut v, -1.0, 1.0));- assert_eq!(v.current, 2, "a notch turns from the first spread to the second");- assert!(notch(&mut v, 1.0, 1.1));- assert_eq!(v.current, 0, "a notch back turns to the previous spread");+ if let Some((page, rect)) = open_table {+ app.field_table_draft = Some(crate::field_table_ui::FieldTableDraft::new(app.views[index].id, page, rect, &form, generation));+ app.dialog = Some(crate::Dialog::FieldTable);+ // The window lasts while the form is prepared. Drawn with the tool picked but its panel+ // closed, the tool goes back to Select above, so the panel opens to keep it prepared.+ app.left = crate::LeftPanel::Tool("form");+ app.reveal_tools();}-- #[test]- fn continuous_views_ignore_the_wheel_for_paging() {- // Scrolling views let the ScrollArea handle the wheel; it never turns pages.- for layout in [PageLayout::Single, PageLayout::TwoUp] {- let mut v = view(3, layout, true);- assert!(!notch(&mut v, -1.0, 1.0), "{layout:?} continuous ignores the wheel");- assert_eq!(v.current, 0);+ if let Some(n) = form_notice {+ match n {+ crate::forms_ui::FormNotice::Security => app.notify_tr("The document's security settings don't allow filling in form fields"),+ crate::forms_ui::FormNotice::ReadOnly(name) => app.notify_fmt("{name} is read-only", &[("name", &name)]),+ crate::forms_ui::FormNotice::NoAction(name) => app.notify_fmt("{name} has no action", &[("name", &name)]),}}-- #[test]- fn navigation_drops_partial_wheel_motion() {- use egui::{MouseWheelUnit::Point, TouchPhase::Move, TouchPhase::Start};- let mut v = view(3, PageLayout::Single, false);- assert!(!v.single_page_wheel(Point, 0.0, Start, 1.0, true));- assert!(!v.single_page_wheel(Point, -30.0, Move, 1.02, true));- v.go_to_page(1);- // The same touch has to move a full notch's worth again before it turns.- assert!(!v.single_page_wheel(Point, -30.0, Move, 1.04, true));- assert!(v.single_page_wheel(Point, -30.0, Move, 1.06, true));- assert_eq!(v.current, 2);- }-- #[test]- fn reselecting_the_layout_does_not_scroll_to_top() {- let mut v = view(3, PageLayout::Single, true);- v.goto = None;- v.set_layout(PageLayout::Single);- assert!(v.goto.is_none(), "re-selecting the current layout is a no-op");- v.set_continuous(true);- assert!(v.goto.is_none(), "re-selecting the current continuity is a no-op");- v.set_layout(PageLayout::TwoUp);- assert_eq!(v.goto, Some((0, 0.0)), "switching the base layout aligns the current page");- v.goto = None;- v.set_continuous(false);- assert_eq!(v.goto, Some((0, 0.0)), "toggling continuous scrolling aligns the current page");- }-- #[test]- fn fit_page_and_height_hold_still_while_mixed_page_sizes_scroll_past() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 800.0)], ..Default::default() };- for fit in [Fit::Page, Fit::Height] {- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.fit, v.viewport_w, v.viewport_h) = (fit, 1000.0, 800.0);- v.fit_zoom(&info);- let zoom = v.zoom;- v.current = 1;- v.fit_zoom(&info);- assert_eq!(v.zoom, zoom, "{fit:?}: scrolling onto a bigger page keeps the zoom");- // A single page shown on its own (not scrolling) fits each one.- (v.layout, v.continuous) = (PageLayout::Single, false);- v.fit_zoom(&info);- let big = v.zoom;- v.current = 0;- v.fit_zoom(&info);- assert!(v.zoom > big, "{fit:?}: single-page view fits the page it shows");- }+ if let Some((name, action)) = app.views[index].forms.button.take() {+ run_button(app, index, &name, action);}-- #[test]- fn fit_width_fits_the_shown_page_in_single_page_view_only() {- let page =- |width: f32, height: f32| pdfcraft_render::PageInfo { width, height, label: String::new(), crop: [0.0, 0.0, width, height], rotation: 0 };- let info = DocInfo { pages: vec![page(300.0, 400.0), page(600.0, 400.0)], ..Default::default() };- let mut v = DocView::new(DocId(1), &info, ViewDefaults::default());- (v.fit, v.viewport_w, v.viewport_h) = (Fit::Width, 1000.0, 800.0);- v.layout = PageLayout::Single;- v.continuous = false;- v.fit_zoom(&info);- let narrow = v.zoom;- // The shown page fills the width between the side gutters, not centred for the wide page.- let shown = v.layout(&info, v.content_width(&info, 1000.0))[0];- assert!((shown.left() - SIDE).abs() < 1e-2 && (shown.width() - 860.0).abs() < 1e-2, "{shown:?}");- v.current = 1;- v.fit_zoom(&info);- assert!((narrow / v.zoom - 2.0).abs() < 1e-3, "the narrow page gets twice the zoom of the wide one");- // Scrolling views keep one zoom for the whole document.- v.continuous = true;- v.fit_zoom(&info);- let wide = v.zoom;- v.current = 0;- v.fit_zoom(&info);- assert_eq!(v.zoom, wide, "continuous fit width holds still across page sizes");+ if copy_selected {+ app.execute("edit.copy");}-- #[test]- fn layouts_match_their_commands_and_names() {- for l in PageLayout::ORDER {- let spec = pdfcraft_engine::commands::command(l.command()).expect("registered");- assert_eq!((l.label(), l.icon()), (spec.label, spec.icon), "{l:?}");- assert_eq!(PageLayout::from_command(l.command()), Some(l));- assert_eq!(PageLayout::try_parse(l.as_str()), Some(l));- }- assert_eq!(PageLayout::try_parse(" Two-Up "), Some(PageLayout::TwoUp));- assert_eq!(PageLayout::try_parse("facing"), None);+ // Read mode hides the tools (#2646), and full screen is the page and nothing else (#1459);+ // the quick tools come back with the window.+ if app.mode != crate::Mode::Read && !app.full_screen {+ quick_bar(app, avail, ui);}-- #[test]- fn destinations_set_the_zoom_mode_and_the_point_to_show() {- let info = pdfcraft_render::DocInfo {- pages: (0..3)- .map(|_| pdfcraft_render::PageInfo { width: 300.0, height: 400.0, label: String::new(), crop: [0.0, 0.0, 300.0, 400.0], rotation: 0 })- .collect(),- ..Default::default()- };- let mut v = view(3, PageLayout::Single, true);- v.fit = Fit::Width;- // No position (or a malformed one): the top of the page, zoom as it was.- v.go_to_dest(1, DestView::Top, &info);- assert_eq!((v.current, v.goto, v.goto_point, v.fit), (1, Some((1, 0.0)), None, Fit::Width));- // /XYZ with a null zoom keeps the zoom mode; its point is a quarter down page 3.- v.go_to_dest(2, DestView::Xyz { left: None, top: Some(300.0), zoom: None }, &info);- assert_eq!((v.current, v.fit, v.goto_point), (2, Fit::Width, Some((2, None, Some(0.25), vec2(SIDE, 0.0)))));- v.go_to_dest(0, DestView::Xyz { left: Some(150.0), top: None, zoom: Some(2.5) }, &info);- assert_eq!((v.fit, v.zoom, v.goto_point), (Fit::None, 2.5, Some((0, Some(0.5), None, vec2(SIDE, 0.0)))));- // A zoom beyond the view's range is clamped to it.- v.go_to_dest(0, DestView::Xyz { left: None, top: None, zoom: Some(1e30) }, &info);- assert_eq!((v.zoom, v.goto_point), (64.0, None));- v.go_to_dest(0, DestView::Fit, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Page, None));- v.go_to_dest(0, DestView::FitH { top: Some(100.0) }, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Width, Some((0, None, Some(0.75), vec2(SIDE, 0.0)))));- v.go_to_dest(0, DestView::FitV { left: Some(75.0) }, &info);- assert_eq!((v.fit, v.goto_point), (Fit::Height, Some((0, Some(0.25), None, vec2(SIDE, 0.0)))));- // /FitR: the zoom that fits a 100×50 pt rectangle in an 800×600 window, centred.- (v.viewport_w, v.viewport_h) = (800.0, 600.0);- v.go_to_dest(0, DestView::FitR { rect: [0.0, 300.0, 100.0, 350.0] }, &info);- assert_eq!(v.fit, Fit::None);- assert!((v.zoom - 8.0 / PT).abs() < 1e-4, "{}", v.zoom);- let (page, fx, fy, rel) = v.goto_point.expect("a point to show");- assert_eq!((page, rel), (0, vec2(400.0, 300.0)));- assert!((fx.unwrap_or(-1.0) - 50.0 / 300.0).abs() < 1e-4 && (fy.unwrap_or(-1.0) - 75.0 / 400.0).abs() < 1e-4, "{fx:?} {fy:?}");- // A page past the end goes to the last page; a page the document info lacks, to its top.- v.go_to_dest(usize::MAX, DestView::FitH { top: Some(100.0) }, &info);- assert_eq!((v.current, v.goto_point.map(|g| g.0)), (2, Some(2)));- let empty = pdfcraft_render::DocInfo::default();- v.go_to_dest(1, DestView::FitH { top: Some(100.0) }, &empty);- assert_eq!((v.current, v.goto_point), (1, None));+ if let Some((source, file, destination)) = remote_open {+ app.open_remote_link(source, file, destination);}+ }- #[test]- fn page_text_failure_preserves_valid_search_match_without_jitter() {- let mut v = view(3, PageLayout::Single, true);- v.current = 1;- v.find = Some(Find {- query: "test".into(),- case_query: "test".into(),- matches: vec![(0, 0..4), (1, 5..9)],- current: Some(0),- ..Default::default()- });- let req = RenderRequest { page: 0, kind: RequestKind::Text, ..Default::default() };- v.last_queue = vec![req];- let ctx = egui::Context::default();- v.receive_result(- &ctx,- pdfcraft_render::RenderedPage {- request: req,- width: 0,- height: 0,- rgba: Default::default(),- error: Some("extraction failed".into()),- text: None,- warnings: Vec::new(),- millis: 0,- },- );- // Active match was on page 0 which failed: current should fall back to match on page 1 without jitter- assert_eq!(v.find.as_ref().unwrap().current, Some(0));- assert_eq!(v.find.as_ref().unwrap().matches, vec![(1, 5..9)]);- assert!(v.goto.is_none());- }+ /// The prepare-mode field menu's choices.+ enum FieldMenu {+ Properties,+ Duplicate(String),}++ #[cfg(test)]+ mod tests;diff --cc crates/ui-egui/src/canvas/bars.rsindex 000000000,b48027ae3..247236667mode 000000,100644..100644--- a/crates/ui-egui/src/canvas/bars.rs+++ b/crates/ui-egui/src/canvas/bars.rs@@@ -1,0 -1,490 +1,498 @@@+ use super::{+ Color32, CornerRadius, DocInfo, DocView, Edit, PdfCraftApp, Pos2, QuickTool, Rect, Sense, SnapshotKind, Stroke, Tokens, comments, icons, theme,+ vec2,+ };++ /// Whether `p` lies in the bottom-left quadrant of `area`, where the page size shows (#1855).+ pub(super) fn in_size_hint_zone(area: Rect, p: Pos2) -> bool {+ p.x >= area.min.x && p.x < area.center().x && p.y > area.center().y && p.y <= area.max.y+ }++ /// The current page's size, floating at the bottom-left of the document area while the pointer is+ /// in that quadrant, as Acrobat does. Same formatter and unit as Document Properties.+ pub(super) fn page_size_hint(+ view: &DocView,+ info: &DocInfo,+ units: crate::units::Unit,+ area: Rect,+ unobstructed: bool,+ ui: &mut egui::Ui,+ t: &Tokens,+ ) {+ let Some(page) = info.pages.get(view.current) else { return };+ let inside = unobstructed && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| in_size_hint_zone(area, p));+ if !inside {+ return;+ }+ let text = units.size(f64::from(page.width), f64::from(page.height));+ egui::Area::new(egui::Id::unique("page-size-hint"))+ .order(egui::Order::Foreground)+ .interactable(false)+ .pivot(egui::Align2::LEFT_BOTTOM)+ .fixed_pos(area.left_bottom() + vec2(14.0, -14.0))+ .show(ui.ctx(), |ui| {+ egui::Frame::NONE+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.border))+ .corner_radius(CornerRadius::same(6))+ .inner_margin(egui::Margin::symmetric(8, 4))+ .show(ui, |ui| {+ ui.add(egui::Label::new(egui::RichText::new(text).color(t.text)).selectable(false));+ });+ });+ }++ /// What the notice bar's buttons ask for.+ pub(super) enum Notice {+ /// Reload the file that changed on disk, dropping unsaved changes.+ Reload,+ Security,+ Signatures,+ Repairs,+ /// Highlight fields was turned on or off.+ FieldHighlights(bool),+ /// Open the JavaScript console (the form's scripts were turned off; the error is there).+ Console,+ /// Unlock… (enter the permissions password).+ Unlock,+ /// Close this historical snapshot tab (View signed version / View revision).+ Close,+ /// Stop showing the secured-document notice, in every document (#4035).+ HideSecured,+ }++ /// The notice bar above the pages: a file changed on disk first, then what a historical+ /// snapshot is, then the signature status bar, a form's scripts having been turned+ /// off, security, forms and warnings.+ pub(super) fn notices(+ view: &mut DocView,+ doc: &pdfcraft_engine::Document,+ secured: bool,+ repaired: bool,+ signed: Option<(&str, Color32, &str, String)>,+ ui: &mut egui::Ui,+ t: &Tokens,+ ) -> Option<Notice> {+ let info = &doc.info;+ let xfa = doc.xfa.as_ref();+ // The file changed on disk while this document has unsaved changes (#431): ask before+ // replacing it, ahead of every other notice.+ if view.disk_changed {+ let mut reload = false;+ egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.add(icons::image("rotate-cw", 16.0, t.accent_text));+ ui.label(+ egui::RichText::new(tl!(+ "This file changed on disk. Reload shows the new version and drops your unsaved changes; Save replaces it with this version."+ ))+ .color(t.text),+ );+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {+ view.disk_changed = false;+ }+ reload = crate::widgets::pill_button(ui, tl!("Reload"), false).clicked();+ });+ });+ });+ return reload.then_some(Notice::Reload);+ }+ // A historical snapshot (View signed version / View revision): what it is, above the+ // signature and security bars, so the tab is never mistaken for the live document.+ if let Some(snap) = view.snapshot.as_ref() {+ let mut close = false;+ let text = if snap.kind == SnapshotKind::SignedVersion {+ crate::i18n::fmt(+ tl!("You are viewing the signed version of “{from}” (revision {rev}). It is a snapshot: changes here won't affect the original."),+ &[("from", &snap.from), ("rev", &snap.revision.to_string())],+ )+ } else {+ crate::i18n::fmt(+ tl!("You are viewing revision {rev} of “{from}”. It is a snapshot: changes here won't affect the original."),+ &[("rev", &snap.revision.to_string()), ("from", &snap.from)],+ )+ };+ notice_bar(ui, t, "clock", t.accent_text, text, |ui| {+ if crate::widgets::pill_button(ui, tl!("Close"), true).clicked() {+ close = true;+ }+ });+ if close {+ return Some(Notice::Close);+ }+ }+ if let Some((icon, color, template, arg)) = signed {+ let mut open = false;+ notice_bar(ui, t, icon, color, crate::i18n::fmt(tl!(template), &[("by", &arg)]), |ui| {+ if crate::widgets::pill_button(ui, tl!("Signature panel"), false).clicked() {+ open = true;+ }+ });+ return open.then_some(Notice::Signatures);+ }+ if view.notice_dismissed {+ return None;+ }+ let mut open_security = false;+ let mut unlock = false;+ let mut hide_secured = false;+ let mut open_repairs = false;+ let mut open_console = false;+ let mut toggled = None;+ // A form whose scripts were turned off no longer calculates or answers its buttons: that+ // comes before what else there is to say about the document.+ let scripts_off = doc.xfa_scripts_off();+ // What the document is as a form, if it is one: what the bar says first, secured or not.+ let form = if let Some(x) = xfa {+ let lang = crate::i18n::current();+ let pages = crate::i18n::trn(lang, x.pages as u64, "{n} page", "{n} pages");+ let fields = crate::i18n::trn(lang, x.fields as u64, "{n} field", "{n} fields");+ let mut text =+ crate::i18n::fmt(tl!("Dynamic XFA form laid out from its template: {pages}, {fields}."), &[("pages", &pages), ("fields", &fields)]);+ if !x.warnings.is_empty() {+ // The notes are clauses ("a picture is left out"); the first starts a sentence here.+ let notes = x.warnings.join("; ");+ let mut chars = notes.chars();+ text.push(' ');+ text.extend(chars.next().into_iter().flat_map(char::to_uppercase));+ text.push_str(chars.as_str());+ text.push('.');+ }+ Some(("text-cursor-input", text, true))+ } else if info.xfa == Some(pdfcraft_render::Xfa::Dynamic) {+ Some((+ "triangle-alert",+ tl!("This is a dynamic XFA form, which PdfCraft can't display yet. What you see is the file's placeholder page.").to_string(),+ false,+ ))+ } else if info.xfa == Some(pdfcraft_render::Xfa::Static) {+ Some((+ "text-cursor-input",+ tl!("XFA form: its fields and its XFA data are kept in step, so other viewers show what you fill in.").to_string(),+ true,+ ))+ } else if info.fields.iter().any(|f| f.kind != pdfcraft_render::FieldKind::PushButton) {+ // Push buttons alone (LaTeX `animate` frames, navigation buttons) leave nothing to fill in.+ Some((+ "text-cursor-input",+ crate::i18n::fmt(tl!("This document contains {n} interactive form fields."), &[("n", &info.fields.len().to_string())]),+ true,+ ))+ } else {+ None+ };+ let msg = if scripts_off {+ Some(("triangle-alert", crate::js_ui::scripts_off_notice(), true))+ } else if secured {+ // A secured form still says what it is, and keeps Highlight fields: the security+ // sentence follows the form's.+ let security = tl!("This document is secured. Some changes are restricted by its security settings.");+ Some(match form {+ Some((icon, text, fields)) => (icon, format!("{text} {security}"), fields),+ None => ("lock", security.to_string(), false),+ })+ } else if form.is_some() {+ form+ } else if repaired {+ Some(("bandage", tl!("This file was damaged and has been repaired. Saving keeps the repaired version.").to_string(), false))+ } else if !info.warnings.is_empty() {+ Some(("triangle-alert", info.warnings[0].clone(), false))+ } else {+ None+ };+ let (icon, text, fields) = msg?;+ notice_bar(ui, t, icon, t.accent_text, text, |ui| {+ if icons::button(ui, "x", 22.0, false, tl!("Dismiss")).clicked() {+ view.notice_dismissed = true;+ }+ if fields {+ let label = if view.highlight_fields { tl!("Hide field highlights") } else { tl!("Highlight fields") };+ if crate::widgets::pill_button(ui, label, view.highlight_fields).clicked() {+ view.highlight_fields = !view.highlight_fields;+ toggled = Some(Notice::FieldHighlights(view.highlight_fields));+ }+ }+ if scripts_off && crate::widgets::pill_button(ui, tl!("JavaScript Console"), false).clicked() {+ open_console = true;+ }+ if secured && crate::widgets::pill_button(ui, tl!("Security settings"), false).clicked() {+ open_security = true;+ }+ if secured && doc.can_unlock() && crate::widgets::pill_button(ui, tl!("Unlock…"), true).clicked() {+ unlock = true;+ }+ // Only when the bar shows the security message: a form's stopped scripts come first.+ if secured && !scripts_off && crate::widgets::pill_button(ui, tl!("Don't show again"), false).clicked() {+ hide_secured = true;+ }+ if repaired && !secured && info.fields.is_empty() && crate::widgets::pill_button(ui, tl!("Details"), false).clicked() {+ open_repairs = true;+ }+ });+ if open_repairs {+ return Some(Notice::Repairs);+ }+ if open_console {+ return Some(Notice::Console);+ }+ if unlock {+ return Some(Notice::Unlock);+ }+ if hide_secured {+ return Some(Notice::HideSecured);+ }+ open_security.then_some(Notice::Security).or(toggled)+ }++ /// One notice bar: an icon and a message on the left, `buttons` (added right to left) on the+ /// right. The buttons are laid out first, so the message only gets the width they leave: it+ /// wraps there (or, when very little is left, is cut short with the full text on hover) instead+ /// of running under the buttons and past the document area into the side panel (#785). The+ /// buttons are centred on a row of button height, and the message's first line is centred on+ /// the same row; a wrapped message grows the bar downwards.+ fn notice_bar(ui: &mut egui::Ui, t: &Tokens, icon: &str, icon_color: Color32, text: String, buttons: impl FnOnce(&mut egui::Ui)) {+ const ROW: f32 = 28.0;+ const ICON: f32 = 16.0;+ egui::Frame::NONE.fill(t.accent_soft).inner_margin(egui::Margin::symmetric(14, 7)).show(ui, |ui| {+ let width = ui.available_width();+ ui.allocate_ui_with_layout(vec2(width, ROW), egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.set_min_height(ROW);+ buttons(ui);+ let rest = ui.available_width().max(0.0);+ ui.allocate_ui_with_layout(vec2(rest, ROW), egui::Layout::top_down(egui::Align::Min), |ui| {+ let font = egui::TextStyle::Body.resolve(ui.style());+ let line = ui.fonts_mut(|f| f.row_height(&font)).max(ICON);+ ui.add_space(((ROW - line) / 2.0).max(0.0));+ ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {+ let (slot, _) = ui.allocate_exact_size(vec2(ICON, line), Sense::hover());+ icons::paint(ui, Rect::from_center_size(slot.center(), vec2(ICON, ICON)), icon, ICON, icon_color);+ let label = egui::Label::new(egui::RichText::new(text).color(t.text));+ // Wrapping into a sliver would stack the message a few letters per line.+ ui.add(if ui.available_width() >= 120.0 { label.wrap() } else { label.truncate() });+ });+ });+ });+ });+ }++ /// The floating quick-action bar at the left edge of the document area.+ pub(super) fn quick_bar(app: &mut PdfCraftApp, area: Rect, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let pos = area.left_top() + vec2(14.0, 14.0);+ egui::Area::new(egui::Id::unique("quick-bar")).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {+ egui::Frame::NONE+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.border))+ .corner_radius(CornerRadius::same(12))+ .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 100 } else { 28 }) })+ .inner_margin(egui::Margin::same(6))+ .show(ui, |ui| {+ ui.spacing_mut().item_spacing.y = 2.0;+ ui.vertical(|ui| {+ if icons::button(ui, "mouse-pointer-2", 32.0, app.quick_tool == QuickTool::Select, tl!("Select (V)")).clicked() {+ app.quick_tool = QuickTool::Select;+ }+ if icons::button(ui, "hand", 32.0, app.quick_tool == QuickTool::Hand, tl!("Hand (H)")).clicked() {+ app.quick_tool = QuickTool::Hand;+ }+ // Comment ▸, Highlight ▸, Draw ▸ (Acrobat's comment toolbar groups). Clicking a+ // group selects its last-used tool; clicking it again opens the flyout.+ for g in 0..comments::GROUPS.len() {+ let current = app.comment_prefs.group_tool[g];+ let active = matches!(app.quick_tool, QuickTool::Comment(t) if t.group() == g);+ let resp = icons::button(ui, current.icon(), 32.0, active, tl!(current.label()));+ // A small corner triangle marks the flyout.+ let r = resp.rect;+ let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];+ ui.painter().add(egui::Shape::convex_polygon(tri.to_vec(), if active { t.accent } else { t.text_faint }, Stroke::NONE));+ let open = (resp.clicked() && active) || resp.secondary_clicked();+ if resp.clicked() && !active {+ app.execute(current.command());+ }+ egui::Popup::menu(&resp)+ .open_memory(open.then_some(egui::SetOpenCommand::Toggle))+ .align(egui::RectAlign::RIGHT_START)+ .gap(6.0)+ .show(|ui| {+ for tool in comments::GROUPS[g] {+ let on = app.quick_tool == QuickTool::Comment(*tool);+ let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());+ let press = theme::Press::track(ui, &click);+ press.wash(ui, row, 4, on);+ let body = row.translate(press.offset());+ icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);+ let reserve = if on { 28.0 } else { 8.0 };+ crate::widgets::paint_left(+ ui,+ body.left_center() + vec2(34.0, 0.0),+ tl!(tool.label()),+ theme::regular(13.0),+ t.text,+ (row.width() - 34.0 - reserve).max(0.0),+ );+ if on {+ icons::paint(+ ui,+ Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),+ "check",+ 14.0,+ t.accent,+ );+ }+ let click = theme::hand(click);+ let info = tl!(tool.label()).to_string();+ click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));+ if click.clicked() {+ app.execute(tool.command());+ ui.close();+ }+ }+ });+ }+ // Edit text & images, while the Edit workspace is open (Acrobat's Edit toolbar)+ // or the tool is in use.+ if app.mode == crate::Mode::Edit || app.quick_tool == QuickTool::EditText {+ let on = app.quick_tool == QuickTool::EditText;+ if icons::button(ui, "text-cursor-input", 32.0, on, tl!("Edit text & images")).clicked() {+ if on {+ app.put_down_edit_text();+ } else {+ app.quick_tool = QuickTool::EditText;+ }+ }+ }+ // Fill & Sign ▸ (text, marks, date, signature).+ let current_fill = match app.quick_tool {+ QuickTool::Fill(f) => Some(f),+ _ => None,+ };+ let shown = current_fill.unwrap_or(crate::fill_sign::FillTool::Text);+ let resp = icons::button(+ ui,+ if current_fill.is_some() { shown.icon() } else { "pen-line" },+ 32.0,+ current_fill.is_some(),+ tl!("Fill & Sign"),+ );+ let r = resp.rect;+ let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)];+ ui.painter().add(egui::Shape::convex_polygon(+ tri.to_vec(),+ if current_fill.is_some() { t.accent } else { t.text_faint },+ Stroke::NONE,+ ));+ if resp.clicked() && current_fill.is_none() {+ app.execute(shown.command());+ }+ let open = (resp.clicked() && current_fill.is_some()) || resp.secondary_clicked();+ egui::Popup::menu(&resp)+ .open_memory(open.then_some(egui::SetOpenCommand::Toggle))+ .align(egui::RectAlign::RIGHT_START)+ .gap(6.0)+ .show(|ui| {+ for tool in crate::fill_sign::FILL_TOOLS {+ if matches!(tool, crate::fill_sign::FillTool::Signature | crate::fill_sign::FillTool::Initials) {+ continue;+ }+ let on = current_fill == Some(tool);+ let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click());+ let press = theme::Press::track(ui, &click);+ press.wash(ui, row, 4, on);+ let body = row.translate(press.offset());+ icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text);+ let reserve = if on { 28.0 } else { 8.0 };+ crate::widgets::paint_left(+ ui,+ body.left_center() + vec2(34.0, 0.0),+ tl!(tool.label()),+ theme::regular(13.0),+ t.text,+ (row.width() - 34.0 - reserve).max(0.0),+ );+ if on {+ icons::paint(+ ui,+ Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)),+ "check",+ 14.0,+ t.accent,+ );+ }+ let click = theme::hand(click);+ let info = tl!(tool.label()).to_string();+ click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone()));+ if click.clicked() {+ app.execute(tool.command());+ ui.close();+ }+ }+ ui.separator();+ if let Some(command) = crate::fill_sign::signature_entries(ui, app, &t) {+ app.execute(command);+ ui.close();+ }+ });+ if matches!(current_fill, Some(crate::fill_sign::FillTool::Text | crate::fill_sign::FillTool::Date)) {+ ui.label(tl!("Font size:"));+ let size = ui.add(+ egui::DragValue::new(&mut app.fill_text_size)+ .range(crate::fill_sign::MIN_TEXT_SIZE..=crate::fill_sign::MAX_TEXT_SIZE)+ .speed(0.25)+ .suffix(" pt"),+ );+ // #1274: the size also applies to the Fill & Sign text that is selected,+ // once per change (a typed value, or the end of a drag), so a drag adds+ // one undo step and not one per frame.+ if ((size.changed() && !size.dragged()) || size.drag_stopped())+ && let Some((index, id)) = app.active_ids()+ && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)+ && app.session.get(id).is_some_and(|doc| {+ doc.allows_annotation()+ && doc+ .info+ .annotations+ .iter()+ .any(|a| a.page == page && a.index == annotation && a.fill_sign && a.subtype == "FreeText" && !a.locked)+ })+ {+ app.apply_edit(Edit::FontSizeAnnotation { page, index: annotation, size: app.fill_text_size });+ }+ }++ if matches!(current_fill, Some(crate::fill_sign::FillTool::Text | crate::fill_sign::FillTool::Date)) {++ ui.menu_button(tl!("Colour"), |ui| {++ if let Some(color) = comments::swatch_grid(ui, Some(app.fill_text_color)) {++ app.fill_text_color = color;++ ui.close();++ }++ });++ }+ if let QuickTool::Comment(tool) = app.quick_tool {+ let (r, _) = ui.allocate_exact_size(vec2(32.0, 9.0), Sense::hover());+ ui.painter().hline(r.x_range().shrink(6.0), r.center().y, Stroke::new(1.0, t.divider));+ if let Some(color) = comments::quick_bar_controls(ui, tool, &mut app.comment_prefs)+ && let Some((index, id)) = app.active_ids()+ && let Some((page, annotation)) = app.views.get(index).and_then(|view| view.comments.selected)+ && app.session.get(id).is_some_and(|doc| {+ doc.allows_annotation()+ && doc+ .info+ .annotations+ .iter()+ .any(|a| a.page == page && a.index == annotation && !a.is_reply() && comments::made_by(a, tool))+ })+ {+ app.apply_edit(Edit::StyleAnnotation {+ page,+ index: annotation,+ color: Some(color),+ opacity: None,+ width: None,+ endings: None,+ });+ }+ }+ });+ });+ });+ }diff --cc crates/ui-egui/src/lib.rsindex eb5af5fd5,440c0d13c..c2ba05ad9--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -550,11 -314,8 +314,10 @@@ pub struct PdfCraftApppub flatten_fill_sign_on_save: bool,/// Point size for new Fill & Sign text and dates, kept across launches.pub fill_text_size: f64,+ /// Colour for new Fill & Sign text and dates, kept across launches.+ pub fill_text_color: [f64; 3],pub dialog: Option<Dialog>,/// How to ask for the latest release (the desktop app sets it; see `updates`).- pub update_source: Option<updates::UpdateSource>,pub(crate) updates: updates::Updates,/// Lists the Print dialog's printers in the background (the desktop app sets it; see/// [`PrinterSource`]).diff --cc crates/ui-egui/src/panels/format_text_ui.rsindex 000000000,6cf07ce05..4645ca367mode 000000,100644..100644--- a/crates/ui-egui/src/panels/format_text_ui.rs+++ b/crates/ui-egui/src/panels/format_text_ui.rs@@@ -1,0 -1,339 +1,451 @@@+ //! Format text, laid out as Acrobat's panel: the font across the panel; size, colour, lists and+ //! alignment; bold, italic, underline, superscript and subscript; line and paragraph spacing;+ //! horizontal scale and character spacing. One panel serves a paragraph being edited (with the+ //! fonts already on its page and the spacing controls) and added text (the standard families,+ //! size, colour, style, alignment and character spacing). What PdfCraft can't apply yet (lists,+ //! superscript and subscript, paragraph spacing, or line spacing and scale for added text) is shown+ //! disabled and says so.+ //!+ //! The icons are Lucide's (AGENTS.md §1); only the arrangement follows Acrobat.++ use egui::{Align, Color32, CornerRadius, Layout, Rect, Sense, Stroke, vec2};+ use pdfcraft_engine::{AddedText, FontFamily, TextAlign};++ use crate::edit_text_ui::Extras;+ use crate::theme::Tokens;+ use crate::{icons, widgets};++ /// A font picked from the font list. The caller applies it, since keeping the paragraph's own+ /// font also means restoring the family it started with.+ #[derive(Clone, Debug, PartialEq)]+ pub(crate) enum FontChoice {+ /// The fonts the paragraph already uses.+ KeepSource,+ /// One of the page's fonts, by resource name.+ Resource(String),+ /// A standard family.+ Family(FontFamily),+ /// Load font…: pick a font file.+ Load,+ /// A font file installed on this computer.+ Installed(std::path::PathBuf),+ }++ /// What the font list offers and shows.+ pub(crate) struct Fonts<'a> {+ /// The fonts on the paragraph's page (resource, face); `None` for added text, which has the+ /// standard families only.+ pub sources: Option<&'a [(String, String)]>,+ /// The name the list shows for the current choice.+ pub shown: String,+ }++ /// What the panel changed: the style (in place) and a font picked from the list.+ #[derive(Default)]+ pub(crate) struct Outcome {+ pub changed: bool,+ pub font: Option<FontChoice>,+ }+-const SIZES: [f64; 14] = [8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 24.0, 28.0, 36.0, 48.0, 72.0];++const SIZES: [f64; 16] = [4.0, 6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 24.0, 28.0, 36.0, 48.0, 72.0];+ const LINE_SPACINGS: [f64; 7] = [1.0, 1.15, 1.2, 1.5, 2.0, 2.5, 3.0];+ const SCALES: [f64; 8] = [50.0, 75.0, 90.0, 100.0, 110.0, 125.0, 150.0, 200.0];+ const CHAR_SPACINGS: [f64; 8] = [-1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0, 5.0];+ /// A row's height: the tallest control in it (the 30 pt icon buttons). Every control is centred+ /// on the row, whatever its own height, so lists, swatches and buttons line up (#3037).+ const ROW: f32 = 30.0;+ /// The gap between a row's controls.+ const GAP: f32 = 6.0;+ /// The icon naming a list or field ([`labelled_icon`]).+ const LABEL_ICON: f32 = 22.0;+ /// The button beside a number field that opens its list of common values: just an arrow, so the+ /// field keeps the room its value needs.+ const PRESET_LIST: f32 = 22.0;+ /// What can be typed: horizontal scale in percent, character spacing in points.+ const SCALE_RANGE: std::ops::RangeInclusive<f64> = 10.0..=400.0;+ const CHAR_SPACING_RANGE: std::ops::RangeInclusive<f64> = -5.0..=50.0;++ /// A number as the lists show it: no trailing zeros ("1.2", "100", "-0.5").+ fn number(v: f64) -> String {+ let s = format!("{v:.2}");+ s.trim_end_matches('0').trim_end_matches('.').to_string()+ }++ pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, look: &mut AddedText, extras: Option<&mut Extras>, fonts: Fonts) -> Outcome {+ let before = (look.clone(), extras.as_deref().copied());+ let mut out = Outcome::default();+ widgets::section_title(ui, tl!("Format text"));++ // The font, across the panel.+ let width = ui.available_width();+ craft_ui::ComboBox::from_id_salt("format-font")+ .selected_text(fonts.shown.as_str())+ .width(width)+ .show_ui(ui, |ui| {+ if let Some(sources) = fonts.sources {+ if ui.selectable_label(false, tl!("Keep source fonts")).clicked() {+ out.font = Some(FontChoice::KeepSource);+ }+ for (resource, face) in sources.iter().filter(|(r, _)| !r.starts_with("PCApproved")) {+ if ui.selectable_label(false, face).clicked() {+ out.font = Some(FontChoice::Resource(resource.clone()));+ }+ }+ ui.separator();+ }+ for f in [FontFamily::Helvetica, FontFamily::Times, FontFamily::Courier] {+ if ui.selectable_label(fonts.sources.is_none() && look.family == f, f.label()).clicked() {+ out.font = Some(FontChoice::Family(f));+ }+ }+ if fonts.sources.is_some() {+ ui.separator();+ if ui.selectable_label(false, tl!("Load font…")).clicked() {+ out.font = Some(FontChoice::Load);+ }+ #[cfg(not(target_arch = "wasm32"))]+ ui.menu_button(tl!("Installed fonts…"), |ui| match crate::files::installed_font_files(ui.ctx()) {+ Some(list) if list.is_empty() => {+ ui.label(tl!("No openly licensed document fonts found. Load a font file."));+ }+ Some(list) => {+ for font in list {+ if ui.button(&font.face).clicked() {+ out.font = Some(FontChoice::Installed(font.path));+ ui.close();+ }+ }+ }+ None => {+ ui.label(tl!("Finding document fonts…"));+ }+ });+ }+ })+ .response+ .on_hover_text(format!("{}\n{}", tl!("Font"), tl!("Thai and Arabic use regular fallback fonts when available.")));+ ui.add_space(4.0);++ // Size and colour | bullets, numbering and alignment.+ row(ui, |ui| {- let _ = craft_ui::ComboBox::from_id_salt("format-size")- .selected_text(number(look.size))- .width(64.0)- .show_ui(ui, |ui| {- for size in SIZES {- ui.selectable_value(&mut look.size, size, number(size));- }- })- .response- .on_hover_text(tl!("Font size"));++ font_size_input(ui, &mut look.size);+ let swatch = colour_button(ui, t, look.color);+ egui::Popup::menu(&swatch).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ if let Some(picked) = crate::comments::swatch_grid(ui, Some(look.color)) {+ look.color = picked;+ ui.close();+ }+ });+ let (sep, _) = ui.allocate_exact_size(vec2(9.0, 26.0), Sense::hover());+ ui.painter().vline(sep.center().x, sep.y_range().shrink(3.0), Stroke::new(1.0, t.divider));+ planned(ui, "list", tl!("Bulleted list"));+ planned(ui, "list-ordered", tl!("Numbered list"));+ let current = match look.align {+ TextAlign::Left => "align-left",+ TextAlign::Center => "align-center",+ TextAlign::Right => "align-right",+ TextAlign::Justify => "align-justify",+ };+ let align = icons::button(ui, current, 30.0, false, tl!("Alignment"));+ let align = flyout(ui, t, align);+ egui::Popup::menu(&align).show(|ui| {+ ui.horizontal(|ui| {+ for (a, icon, tip) in [+ (TextAlign::Left, "align-left", tl!("Align left")),+ (TextAlign::Center, "align-center", tl!("Centre")),+ (TextAlign::Right, "align-right", tl!("Align right")),+ (TextAlign::Justify, "align-justify", tl!("Justify")),+ ] {+ if icons::button(ui, icon, 30.0, look.align == a, tip).clicked() {+ look.align = a;+ ui.close();+ }+ }+ });+ });+ });++ // Bold, italic, underline, superscript, subscript.+ let mut extras = extras;+ row(ui, |ui| {+ if icons::button(ui, "bold", 30.0, look.bold, tl!("Bold")).clicked() {+ look.bold = !look.bold;+ }+ if icons::button(ui, "italic", 30.0, look.italic, tl!("Italic")).clicked() {+ look.italic = !look.italic;+ }+ match extras.as_deref_mut() {+ Some(e) => {+ if icons::button(ui, "underline", 30.0, e.underline, tl!("Underline")).clicked() {+ e.underline = !e.underline;+ }+ }+ None => planned(ui, "underline", tl!("Underline")),+ }+ planned(ui, "superscript", tl!("Superscript"));+ planned(ui, "subscript", tl!("Subscript"));+ });++ // Line and paragraph spacing; horizontal scale and character spacing: two columns, each an+ // icon and its control, `half` wide.+ let half = ((ui.available_width() - 2.0 * LABEL_ICON - 8.0 - 3.0 * GAP) / 2.0).max(40.0);+ let editing = extras.is_some();+ let mut fallback = Extras::default();+ let e = extras.as_deref_mut().unwrap_or(&mut fallback);+ ui.add_enabled_ui(editing, |ui| {+ row(ui, |ui| {+ labelled_icon(ui, t, "arrow-up-down", tl!("Line spacing"));+ let own = tl!("Auto").to_string();+ let shown = if e.line_spacing == 0.0 { own.clone() } else { number(e.line_spacing) };+ craft_ui::ComboBox::from_id_salt("format-line-spacing").selected_text(shown).width(half).show_ui(ui, |ui| {+ ui.selectable_value(&mut e.line_spacing, 0.0, own.as_str());+ for v in LINE_SPACINGS {+ ui.selectable_value(&mut e.line_spacing, v, number(v));+ }+ });+ ui.add_space(8.0);+ ui.add_enabled_ui(false, |ui| {+ labelled_icon(ui, t, "pilcrow", tl!("Paragraph spacing"));+ let tip = format!("{} — {}", tl!("Paragraph spacing"), tl!("Planned"));+ let _ = craft_ui::ComboBox::from_id_salt("format-paragraph-spacing")+ .selected_text("0")+ .width(half)+ .show_ui(ui, |_| {})+ .response+ .on_disabled_hover_text(tip);+ });+ });+ });+ // Any value the engine takes can be typed; the lists hold the common ones. Added text has+ // character spacing of its own (#4245), but no scale yet.+ row(ui, |ui| {+ ui.add_enabled_ui(editing, |ui| {+ let label = labelled_icon(ui, t, "move-horizontal", tl!("Horizontal scale"));+ let scale = Number { value: &mut e.scale, range: SCALE_RANGE, speed: 1.0, suffix: " %" };+ number_with_presets(ui, scale, &SCALES, half, (label.id, tl!("Horizontal scale")));+ });+ ui.add_space(8.0);+ let label = labelled_icon(ui, t, "arrow-left-right", tl!("Character spacing"));+ let value = if editing { &mut e.char_spacing } else { &mut look.char_spacing };+ let spacing = Number { value, range: CHAR_SPACING_RANGE, speed: 0.1, suffix: " pt" };+ number_with_presets(ui, spacing, &CHAR_SPACINGS, half, (label.id, tl!("Character spacing")));+ });++ out.changed = (look.clone(), extras.as_deref().copied()) != before;+ ui.add_space(6.0);+ ui.separator();+ out+ }++ /// One row of the panel, [`ROW`] high, its controls [`GAP`] apart and centred on it.+ fn row<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {+ let size = vec2(ui.available_width(), ROW);+ ui.allocate_ui_with_layout(size, Layout::left_to_right(Align::Center), |ui| {+ ui.spacing_mut().item_spacing.x = GAP;+ // A list lays itself out from the default control height and grows downward, which leaves+ // it below the row's middle; at a list's own height it is centred like the rest.+ let list = ui.text_style_height(&egui::TextStyle::Button) + 2.0 * ui.spacing().button_padding.y;+ ui.spacing_mut().interact_size.y = ui.spacing().interact_size.y.max(list);+ add(ui)+ })+ .inner+ }++ /// A control PdfCraft doesn't have yet: its icon, disabled, saying so when hovered.+ fn planned(ui: &mut egui::Ui, icon: &str, label: &str) {+ let _ = ui+ .add_enabled_ui(false, |ui| icons::button(ui, icon, 30.0, false, label))+ .inner+ .on_disabled_hover_text(format!("{label} — {}", tl!("Planned")));+ }++ /// The small corner mark Acrobat puts on a button that opens a menu.+ fn flyout(ui: &egui::Ui, t: &Tokens, resp: egui::Response) -> egui::Response {+ let r = resp.rect;+ let tri = vec![r.right_bottom() + vec2(-3.0, -3.0), r.right_bottom() + vec2(-8.0, -3.0), r.right_bottom() + vec2(-3.0, -8.0)];+ ui.painter().add(egui::Shape::convex_polygon(tri, t.text_faint, Stroke::NONE));+ resp+ }++ /// An icon naming the list beside it, for screen readers too. Returns it, for the control it+ /// labels.+ fn labelled_icon(ui: &mut egui::Ui, t: &Tokens, icon: &str, label: &str) -> egui::Response {+ let (rect, resp) = ui.allocate_exact_size(vec2(LABEL_ICON, 26.0), Sense::hover());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), label));+ let tint = if ui.is_enabled() { t.icon } else { t.text_faint };+ icons::paint(ui, Rect::from_center_size(rect.center(), vec2(18.0, 18.0)), icon, 17.0, tint);+ resp.on_hover_text(label)+ }++ /// A value typed in a number field: what it edits, what may be typed, and how it reads.+ struct Number<'a> {+ value: &'a mut f64,+ range: std::ops::RangeInclusive<f64>,+ speed: f64,+ suffix: &'static str,+ }++ /// A number field with an arrow beside it that lists common values, in `width` all told: type any+ /// value in its range, or pick one. Both are named by `label`: the icon before them and its text.+ fn number_with_presets(ui: &mut egui::Ui, n: Number<'_>, presets: &[f64], width: f32, label: (egui::Id, &str)) {+ ui.scope(|ui| {+ ui.spacing_mut().item_spacing.x = 2.0;+ let field = egui::DragValue::new(&mut *n.value).range(n.range).speed(n.speed).max_decimals(2).suffix(n.suffix);+ let height = ui.spacing().interact_size.y;+ ui.add_sized([(width - PRESET_LIST - 2.0).max(30.0), height], field).labelled_by(label.0);+ let list = icons::button(ui, "chevron-down", PRESET_LIST, false, label.1);+ egui::Popup::menu(&list).show(|ui| {+ for &v in presets {+ if ui.selectable_label(*n.value == v, number(v)).clicked() {+ *n.value = v;+ ui.close();+ }+ }+ });+ });+ }++ /// The text colour as a square swatch that opens the palette.+ fn colour_button(ui: &mut egui::Ui, t: &Tokens, color: [f64; 3]) -> egui::Response {+ let (rect, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Colour")));+ let [r, g, b] = color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);+ let fill = rect.shrink(4.0);+ ui.painter().rect_filled(fill, CornerRadius::same(2), Color32::from_rgb(r, g, b));+ let stroke = if resp.hovered() { t.text } else { t.border };+ ui.painter().rect_stroke(fill, CornerRadius::same(2), Stroke::new(1.0, stroke), egui::StrokeKind::Outside);+ crate::theme::hand(resp).on_hover_text(tl!("Colour"))+ }+++/// Commit a typed size once (Enter or leaving the field), rather than one undo step per key.++/// The bounds match AddedText validation, so the panel also accepts coloured text below 8 pt.++fn font_size_input(ui: &mut egui::Ui, size: &mut f64) {++ let id = ui.make_persistent_id("font-size-input");++ let (previous, mut text) = ui.data(|d| d.get_temp::<(u64, String)>(id)).unwrap_or_else(|| (size.to_bits(), size.to_string()));++ if previous != size.to_bits() {++ text = size.to_string();++ }++ let response = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(44.0)).accessible_name(tl!("Font size:"));++ let cancel = (response.has_focus() || response.lost_focus()) && ui.input(|i| i.key_pressed(egui::Key::Escape));++ if cancel {++ text = size.to_string();++ response.surrender_focus();++ } else if response.lost_focus() || (response.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) {++ if let Some(value) = typed_font_size(&text) {++ *size = value;++ }++ text = size.to_string();++ }++ let before = *size;++ craft_ui::ComboBox::from_id_salt("font-size").selected_text("pt").width(28.0).show_ui(ui, |ui| {++ for value in SIZES {++ ui.selectable_value(size, value, format!("{value} pt"));++ }++ });++ if *size != before {++ text = size.to_string();++ }++ ui.data_mut(|d| d.insert_temp(id, (size.to_bits(), text)));++}++++fn typed_font_size(text: &str) -> Option<f64> {++ let value = text.trim().parse::<f64>().ok()?;++ (value.is_finite() && (1.0..=500.0).contains(&value)).then_some(value)++}+++++++ #[cfg(test)]+ mod tests {+ #[test]+ fn numbers_read_like_the_lists() {+ assert_eq!(super::number(1.2), "1.2");+ assert_eq!(super::number(100.0), "100");+ assert_eq!(super::number(-0.5), "-0.5");+ assert_eq!(super::number(0.0), "0");+ assert_eq!(super::number(1.15), "1.15");+ }+ }++++#[cfg(test)]++mod typed_size_tests {++ use super::*;++ use egui_kittest::kittest::Queryable;++++ #[test]++ fn typed_sizes_accept_small_fractional_values_and_reject_invalid_input() {++ for value in ["1", "4", "6.5", " 13.25 ", "500"] {++ assert_eq!(typed_font_size(value), Some(value.trim().parse().unwrap()));++ }++ for value in ["", "0", "-1", "0.5", "501", "NaN", "inf", "1e999", "small"] {++ assert_eq!(typed_font_size(value), None, "{value}");++ }++ }++++ #[test]++ fn typed_size_commits_once_and_invalid_input_preserves_the_style() {++ let mut h = egui_kittest::Harness::new_ui_state(++ |ui, state: &mut (f64, usize)| {++ let before = state.0;++ ui.horizontal(|ui| font_size_input(ui, &mut state.0));++ if state.0 != before {++ state.1 += 1;++ }++ },++ (12.0, 0),++ );++ h.run();++ let enter = || egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };++ let select_all =++ || egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };++ for (text, expected, changes) in [("6.5", 6.5, 1), ("NaN", 6.5, 1), ("0", 6.5, 1), ("13.25", 13.25, 2)] {++ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Font size:").click();++ h.run();++ h.event(select_all());++ h.event(egui::Event::Text(text.into()));++ h.run_steps(2);++ assert_eq!(h.state().1, changes - usize::from(text == "6.5" || text == "13.25"), "typing alone does not commit");++ h.event(enter());++ h.run_steps(2);++ assert_eq!(*h.state(), (expected, changes));++ }++ }++++ #[test]++ fn typed_size_commits_on_focus_loss_and_escape_discards_the_draft() {++ let mut h = egui_kittest::Harness::new_ui_state(++ |ui, state: &mut (f64, usize)| {++ let before = state.0;++ ui.horizontal(|ui| font_size_input(ui, &mut state.0));++ let _ = ui.button("Other control");++ if state.0 != before {++ state.1 += 1;++ }++ },++ (12.0, 0),++ );++ h.run();++ let select_all =++ || egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND };++ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Font size:").click();++ h.run();++ h.event(select_all());++ h.event(egui::Event::Text("6.5".into()));++ h.run_steps(2);++ assert_eq!(*h.state(), (12.0, 0));++ h.get_by_label("Other control").click();++ h.run_steps(2);++ assert_eq!(*h.state(), (6.5, 1));++ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Font size:").click();++ h.run();++ h.event(select_all());++ h.event(egui::Event::Text("13.25".into()));++ h.run_steps(2);++ h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });++ h.run_steps(2);++ assert_eq!(*h.state(), (6.5, 1), "Escape must not commit the draft");++ h.get_by_label("Other control").click();++ h.run_steps(2);++ assert_eq!(*h.state(), (6.5, 1), "later focus loss must not revive the cancelled draft");++ }++}diff --cc crates/ui-egui/src/tools/fill_sign.rsindex 084b5290f,486194482..045bb6497--- a/crates/ui-egui/src/tools/fill_sign.rs+++ b/crates/ui-egui/src/tools/fill_sign.rs@@@ -623,28 -429,22 +442,23 @@@ pub(crate) fn paint_saved(ui: &egui::Ui}}+ /// Values that shape how Fill & Sign handles this page's input.+ pub(crate) struct PageInput<'a> {+ pub(crate) tool: FillTool,+ pub(crate) text_size: f64,++ pub(crate) text_color: [f64; 3],+ pub(crate) signature: Option<&'a SavedSig>,+ pub(crate) initials: Option<&'a SavedSig>,+ pub(crate) preview: &'a mut Option<(SavedSig, egui::TextureHandle)>,+ pub(crate) author: &'a str,+ pub(crate) date_text: &'a Result<String, String>,+ }+/// Preview and clicks with a Fill & Sign tool on one page.- #[allow(clippy::too_many_arguments)]- pub(crate) fn page_input(- ui: &egui::Ui,- resp: &egui::Response,- xf: &PageXform,- page: usize,- info: &DocInfo,- tool: FillTool,- text_size: f64,- text_color: [f64; 3],- view: &mut DocView,- signature: Option<&SavedSig>,- initials: Option<&SavedSig>,- preview: &mut Option<(SavedSig, egui::TextureHandle)>,- author: &str,- date_text: &Result<String, String>,- ) -> Option<FillAction> {- let pointer = ui.input(|i| i.pointer.hover_pos())?;- if !resp.contains_pointer() || !xf.rect.contains(pointer) {- return None;- }+ pub(crate) fn page_input(cx: PageToolContext<'_>, input: PageInput<'_>, view: &mut DocView) -> Option<FillAction> {+ let PageToolContext { ui, resp, xf, ptr, page, info, .. } = cx;- let PageInput { tool, text_size, signature, initials, preview, author, date_text } = input;++ let PageInput { tool, text_size, text_color, signature, initials, preview, author, date_text } = input;+ let pointer = ptr.within(xf.rect)?;let p = info.pages.get(page)?;let at = to_user(xf, info, page, pointer);let saved = match tool {@@@ -725,36 -516,48 +538,48 @@@ pub(crate) fn type_box(ctx: &egui::Contlet xf = view.page_xform(tb.page)?;let v = info.pages.get(tb.page)?.user_to_view(tb.at[0] as f32, tb.at[1] as f32);let pos = xf.norm_to_screen(v[0] / xf.pw, v[1] / xf.ph);- let zoom = xf.rect.width() / xf.pw.max(1.0);+ let zoom = xf.zoom();let mut commit = false;let mut cancel = false;- egui::Area::new(egui::Id::new(("fill-text", view.id.0))).order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| {- let Some(t) = view.fill_text.as_mut() else { return };- // The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).- ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);- let width = ((t.text.chars().count().max(8) as f32) * t.size as f32 * 0.6 * zoom).clamp(60.0, 600.0);- // The area's max rect is last frame's size, which caps the edit's width; widen it so the- // box grows as text is typed.- ui.set_min_width(width);- let r = ui.add(- egui::TextEdit::singleline(&mut t.text)- .font(egui::FontId::proportional((t.size as f32 * zoom).max(8.0)))- .desired_width(width)- .background_color(Color32::from_rgba_unmultiplied(255, 255, 255, 230))- .text_color(crate::comments::color32(t.color))- .hint_text(tl!("Type text"))- .id_salt("fill-text-edit"),- );- if t.focus {- r.request_focus();- t.focus = false;- }- if ui.input(|i| i.key_pressed(egui::Key::Escape)) {- cancel = true;- } else if r.lost_focus() {- commit = true;- }- });+ // Shown at once, like the paragraph editor: a fade-in shows the page's copy through it.+ // Over the page, so only where the document shows: a box scrolled under the mode bar or a+ // side panel must leave them their pointer (#2755). It stays where it was placed, cut off as+ // the page is, rather than pushed back into the window.+ egui::Area::new(egui::Id::unique(("fill-text", view.id.0)))+ .fade_in(false)+ .order(egui::Order::Foreground)+ .fixed_pos(pos)+ .constrain_to(view.viewport_rect())+ .constrain(false)+ .show(ctx, |ui| {+ let Some(t) = view.fill_text.as_mut() else { return };+ // The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).+ ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);+ let width = ((t.text.chars().count().max(8) as f32) * t.size as f32 * 0.6 * zoom).clamp(60.0, 600.0);+ // The area's max rect is last frame's size, which caps the edit's width; widen it so the+ // box grows as text is typed.+ ui.set_min_width(width);+ let r = ui+ .add(+ egui::TextEdit::singleline(&mut t.text)+ .font(egui::FontId::proportional((t.size as f32 * zoom).max(8.0)))+ .desired_width(width)+ .background_color(Color32::from_rgba_unmultiplied(255, 255, 255, 230))- .text_color(Color32::BLACK)++ .text_color(crate::comments::color32(t.color))+ .hint_text(tl!("Type text"))+ .id_salt("fill-text-edit"),+ )+ .accessible_name(tl!("Text to place"));+ if t.focus {+ r.request_focus();+ t.focus = false;+ }+ if ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ cancel = true;+ } else if r.lost_focus() {+ commit = true;+ }+ });if cancel {view.fill_text = None;return None;diff --cc crates/ui-egui/tests/it/editing.rsindex 4a3178424,0d44f9106..0dc4914b1--- a/crates/ui-egui/tests/it/editing.rs+++ b/crates/ui-egui/tests/it/editing.rs@@@ -2876,41 -4090,62 +4090,97 @@@ fn the_format_panel_restyles_the_paragrassert!(s.views[0].line_editor.as_ref().is_some_and(|e| e.extras.underline));}+ /// Horizontal scale and Character spacing take any value in their ranges, not only the listed+ /// ones: values between the listed ones and beyond them, typed in Format text, reach the saved+ /// file as the engine writes them.+ #[test]+ fn the_format_panel_takes_any_scale_and_character_spacing() {+ let mut h = harness(1, |_| {});+ let id = h.state().views[0].id;+ let width = |h: &Harness<'static, PdfCraftApp>, view: usize| {+ let s = h.state();+ let r = s.session.get(s.views[view].id).unwrap().text_blocks(0)[0].rect;+ r[2] - r[0]+ };+ let plain = width(&h, 0);+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let at = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());+ h.hover_at(at);+ h.run_steps(1);+ h.drag_at(at);+ h.run_steps(1);+ h.drop_at(at);+ h.run_steps(3);+ assert!(h.state().views[0].line_editor.is_some());+ // Typed the way a person does: click the field, type, Enter.+ let type_in = |h: &mut Harness<'static, PdfCraftApp>, label: &str, value: &str| {+ h.get_by_role_and_label(Role::SpinButton, label).click();+ h.run_steps(2);+ h.event(egui::Event::Text(value.into()));+ h.run_steps(1);+ h.key_press(Key::Enter);+ h.run_steps(4);+ };+ let extras = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].line_editor.as_ref().map(|e| (e.extras.scale, e.extras.char_spacing));+ // Between the listed values (50…200 %, −1…5 pt) and beyond them, within what was always allowed.+ type_in(&mut h, "Horizontal scale", "80");+ assert_eq!(extras(&h), Some((80.0, 0.0)));+ type_in(&mut h, "Horizontal scale", "250");+ assert_eq!(extras(&h), Some((250.0, 0.0)));+ type_in(&mut h, "Character spacing", "0.25");+ assert_eq!(extras(&h), Some((250.0, 0.25)));+ type_in(&mut h, "Character spacing", "-2");+ assert_eq!(extras(&h), Some((250.0, -2.0)));+ assert_eq!(h.state().session.get(id).unwrap().can_undo(), Some("Edit text"));+ // Saved and reopened, the paragraph is as wide as the engine draws it with those values.+ let bytes = h.state().session.save_bytes(id).unwrap();+ h.state_mut().open_bytes("reference.pdf", None, fixture(1)).expect("opens");+ let style = pdfcraft_engine::BlockStyle { scale: Some(250.0), char_spacing: Some(-2.0), ..Default::default() };+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::EditTextBlock { page: 0, block: 0, text: "Page 1".into(), style }));+ h.state_mut().open_bytes("saved.pdf", None, bytes.as_ref().clone()).expect("the saved file opens");+ h.run_steps(3);+ let (reference, saved) = (width(&h, 1), width(&h, 2));+ assert!(saved > plain * 1.5, "250 % widens it: {plain} → {saved}");+ assert!((saved - reference).abs() < 0.5, "saved {saved}, the engine's own {reference}");+ }++#[test]+fn typed_small_coloured_text_size_survives_save_and_reopen() {+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ let r = h.state().views[0].page_screen_rect(0).unwrap();+ let at = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());+ h.hover_at(at);+ h.run_steps(1);+ h.drag_at(at);+ h.run_steps(1);+ h.drop_at(at);+ h.run_steps(3);+ assert!(h.state().views[0].line_editor.is_some());+ h.get_by_label("Font size:").click();+ h.run_steps(1);+ h.key_press_modifiers(Modifiers::COMMAND, Key::A);+ h.event(egui::Event::Text("6.5".into()));+ h.key_press(Key::Enter);+ h.run_steps(4);+ h.get_by_label("Blue").click();+ h.run_steps(4);+ let id = h.state().views[0].id;+ let lines = h.state().session.get(id).unwrap().text_lines(0);+ assert!(!lines.is_empty());+ for line in &lines {+ assert!((line.size - 6.5).abs() < 0.01, "{line:?}");+ assert!(line.color[2] > line.color[0], "the small text stays blue: {line:?}");+ }+ let saved = h.state().session.save_bytes(id).unwrap();+ let mut reopened = pdfcraft_engine::Session::new();+ let rid = reopened.open("small-blue.pdf", None, saved, None).unwrap();+ assert_eq!(reopened.get(rid).unwrap().text_lines(0), lines);+}+#[test]fn selected_text_formatting_keeps_the_rest_of_the_paragraph_and_reopens() {let mut h = harness(1, |_| {});diff --cc crates/ui-egui/tests/it/fill_sign.rsindex b888e1e23,566a14f18..ce21bd9f7--- a/crates/ui-egui/tests/it/fill_sign.rs+++ b/crates/ui-egui/tests/it/fill_sign.rs@@@ -168,53 -183,105 +183,152 @@@ fn fill_text_size_controls_new_text_andassert_eq!(restored.fill_text_size, 24.0, "invalid settings do not change the size");}+ /// #1274: with a placed Fill & Sign text selected, the Font size control resizes that text,+ /// not only text typed afterwards; with nothing selected it changes nothing on the page.+ #[test]+ fn fill_text_size_resizes_the_selected_text() {+ let mut h = harness();+ h.state_mut().execute("sign.fill.text");+ click(&mut h, 50.0, 250.0);+ h.event(egui::Event::Text("Resize me".into()));+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let height = |h: &Harness<'static, PdfCraftApp>| {+ let s = h.state();+ let a = s.session.get(s.views[0].id).unwrap().info.annotations.iter().find(|a| a.contents.as_deref() == Some("Resize me")).cloned().unwrap();+ a.rect[3] - a.rect[1]+ };+ let before = height(&h);+ let set_size = |h: &mut Harness<'static, PdfCraftApp>, value: &str| {+ h.query_all_by_role(egui::accesskit::Role::SpinButton)+ .find(|n| n.value().is_some_and(|v| v.ends_with(" pt")))+ .expect("the Font size control")+ .click();+ h.run_steps(2);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text(value.into()));+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(4);+ };+ // Nothing selected: only the size for new text changes.+ h.state_mut().views[0].comments.selected = None;+ set_size(&mut h, "18");+ assert_eq!(h.state().fill_text_size, 18.0);+ assert_eq!(height(&h), before, "an unselected placed text keeps its size");+ // The placed text picked up with the Add text tool, then resized.+ let annotation = {+ let s = h.state();+ s.session+ .get(s.views[0].id)+ .unwrap()+ .info+ .annotations+ .iter()+ .find(|a| a.contents.as_deref() == Some("Resize me"))+ .map(|a| (a.page, a.index))+ .unwrap()+ };+ h.state_mut().views[0].comments.selected = Some(annotation);+ set_size(&mut h, "36");+ assert_eq!(h.state().fill_text_size, 36.0);+ let after = height(&h);+ assert!(after > before * 2.0, "36 pt text has a taller box than 10 pt text: {before} -> {after}");+ }++ /// The font sizes of the texts `text` drawn in the last frame.+ fn drawn_sizes(h: &Harness<'static, PdfCraftApp>, text: &str) -> Vec<f32> {+ fn walk(shape: &egui::Shape, text: &str, out: &mut Vec<f32>) {+ match shape {+ egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, text, out)),+ egui::Shape::Text(t) if t.galley.text() == text => {+ out.extend(t.galley.job.sections.first().map(|s| s.format.font_id.size));+ }+ _ => {}+ }+ }+ let mut out = Vec::new();+ for clipped in &h.output().shapes {+ walk(&clipped.shape, text, &mut out);+ }+ out+ }++ /// The type box draws its text at the page's zoom whichever way the view is turned. With the+ /// view turned a quarter, the page's width runs down the screen: reading the zoom off the screen+ /// rectangle's width instead made the typed text a height-over-width too large (here 4/3).+ #[test]+ fn the_type_box_text_matches_the_page_zoom_in_a_turned_view() {+ for rotate in ["0", "90"] {+ let mut h = harness();+ h.state_mut().set_option("rotate", rotate).unwrap();+ h.run_steps(3);+ h.state_mut().execute("sign.fill.text");+ click(&mut h, 50.0, 250.0);+ h.event(egui::Event::Text("Ada".into()));+ h.run_steps(2);+ let s = h.state();+ let page = &s.session.get(s.views[0].id).unwrap().info.pages[0];+ let rect = s.views[0].page_screen_rect(0).expect("on screen");+ // Screen pixels per page point: the page's width lies across, or down when turned.+ let zoom = if rotate == "90" { rect.height() } else { rect.width() } / page.width;+ let size = s.views[0].fill_text.as_ref().expect("an open type box").size as f32;+ let drawn = drawn_sizes(&h, "Ada");+ assert!(!drawn.is_empty(), "{rotate}°: the typed text is drawn");+ for d in drawn {+ assert!((d - size * zoom).abs() < 0.5, "{rotate}°: drawn at {d}, the page shows it at {}", size * zoom);+ }+ }+ }++#[test]+fn fill_text_colour_survives_preview_commit_settings_and_save() {+ let mut h = harness();+ h.state_mut().execute("sign.fill.text");+ h.run_steps(2);+ h.get_by_label("Colour").click();+ h.run_steps(2);+ h.get_by_label("Blue").click();+ h.run_steps(2);+ let color = h.state().fill_text_color;+ assert!(color[2] > color[0], "blue was selected: {color:?}");+ click(&mut h, 50.0, 250.0);+ assert_eq!(h.state().views[0].fill_text.as_ref().unwrap().color, color, "the editor uses the selected colour");+ h.event(egui::Event::Text("Blue form text".into()));+ h.run_steps(2);+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let id = h.state().views[0].id;+ let expected = color.map(|v| v as f32);+ let annotation = h.state().session.get(id).unwrap().info.annotations.iter().find(|a| a.contents.as_deref() == Some("Blue form text")).unwrap();+ assert_eq!(annotation.color, Some(expected));+ let bytes = h.state().session.save_bytes(id).unwrap();+ let reopened = harness_bytes(&bytes);+ let saved = reopened+ .state()+ .session+ .get(reopened.state().views[0].id)+ .unwrap()+ .info+ .annotations+ .iter()+ .find(|a| a.contents.as_deref() == Some("Blue form text"))+ .unwrap();+ assert_eq!(saved.color, Some(expected));+ let mut restored = PdfCraftApp::new();+ restored.restore(&h.state().persist());+ assert_eq!(restored.fill_text_color, color);+ restored.restore(r#"{"fill_text_color":[2,0,0]}"#);+ assert_eq!(restored.fill_text_color, color, "invalid saved colours are ignored");+ h.state_mut().execute("edit.undo");+ h.run_steps(2);+ assert!(!items(&h).iter().any(|(_, text)| text.as_deref() == Some("Blue form text")));+ h.state_mut().execute("edit.redo");+ h.run_steps(2);+ assert!(items(&h).iter().any(|(_, text)| text.as_deref() == Some("Blue form text")));+}+#[test]fn the_type_box_grows_as_text_is_typed() {let mut h = harness();diff --cc parity/acrobat-features.tomlindex dcbcf2d88,3b8dba920..8383b2a29--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@@ -1926,8 -1938,8 +1938,8 @@@ milestone = "M7status = "shipped"commands = ["edit.edit_text", "edit.text"]tools = ["text_edit", "content_update"]- evidence = ["crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/ui-egui/tests/editing.rs::the_format_panel_restyles_the_paragraph_being_edited", "crates/automation/tests/automation.rs::editing_existing_text_through_tools", "crates/ui-egui/src/content_ui.rs::typed_sizes_accept_small_fractional_values_and_reject_invalid_input", "crates/ui-egui/src/content_ui.rs::typed_size_commits_once_and_invalid_input_preserves_the_style", "crates/ui-egui/tests/editing.rs::typed_small_coloured_text_size_survives_save_and_reopen"]- notes = "existing paragraphs and added text: font family (Helvetica, Times, Courier) with bold and italic, size, colour; existing paragraphs are rewrapped; the Edit font-size field accepts typed fractional values from 1–500 pt, including below 8 pt; Enter/focus loss commits once and invalid input preserves the previous value"-evidence = ["crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited", "crates/automation/tests/it/automation.rs::editing_existing_text_through_tools"]-notes = "existing paragraphs and added text: font family (Helvetica, Times, Courier) with bold and italic, size, colour; existing paragraphs are rewrapped"++evidence = ["crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited", "crates/automation/tests/it/automation.rs::editing_existing_text_through_tools", "crates/ui-egui/src/panels/format_text_ui.rs::typed_sizes_accept_small_fractional_values_and_reject_invalid_input", "crates/ui-egui/src/panels/format_text_ui.rs::typed_size_commits_once_and_invalid_input_preserves_the_style", "crates/ui-egui/tests/it/editing.rs::typed_small_coloured_text_size_survives_save_and_reopen"]++notes = "existing paragraphs and added text: font family (Helvetica, Times, Courier) with bold and italic, size, colour; existing paragraphs are rewrapped; typed fractional font sizes commit once; Fill & Sign text/date colour is remembered and preserved in preview and saved appearances (#2444)"[[feature]]id = "edit.text-format-style"@@@ -5268,8 -5356,8 +5356,8 @@@ milestone = "M5status = "shipped"commands = ["sign.fill.text"]tools = ["fill_sign_add"]- evidence = ["crates/ui-egui/tests/fill_sign.rs::text_marks_and_date", "crates/annot/src/tests.rs::fill_and_sign_items_are_drawn", "crates/automation/tests/automation.rs::fill_and_sign_through_tools", "crates/engine/src/tests.rs::typed_text_reads_across_as_displayed_on_rotated_pages", "crates/ui-egui/tests/fill_sign.rs::fill_text_colour_survives_preview_commit_settings_and_save", "crates/automation/tests/automation.rs::fill_sign_text_and_date_colours_are_saved_and_validated"]- notes = "typewriter FreeText, 10 pt Helvetica. Reads across as displayed on pages with /Rotate (sideways-stored scans): the box follows the displayed axes and the appearance is turned back (PdfCraft key /PCTextRotate); other apps that regenerate the appearance from /DA draw it unturned. A later page rotation does not re-turn it. Field detection does not work on scanned (image-only) forms yet; text/date colour is selectable, remembered and preserved in saved appearances; fill_sign_add exposes color and font_size"-evidence = ["crates/ui-egui/tests/it/fill_sign.rs::text_marks_and_date", "crates/annot/src/tests.rs::fill_and_sign_items_are_drawn", "crates/automation/tests/it/automation.rs::fill_and_sign_through_tools", "crates/engine/src/tests.rs::typed_text_reads_across_as_displayed_on_rotated_pages"]-notes = "typewriter FreeText, 10 pt Helvetica. Reads across as displayed on pages with /Rotate (sideways-stored scans): the box follows the displayed axes and the appearance is turned back (PdfCraft key /PCTextRotate); other apps that regenerate the appearance from /DA draw it unturned. A later page rotation does not re-turn it. Field detection does not work on scanned (image-only) forms yet"++evidence = ["crates/ui-egui/tests/it/fill_sign.rs::text_marks_and_date", "crates/annot/src/tests.rs::fill_and_sign_items_are_drawn", "crates/automation/tests/it/automation.rs::fill_and_sign_through_tools", "crates/engine/src/tests.rs::typed_text_reads_across_as_displayed_on_rotated_pages", "crates/ui-egui/tests/it/fill_sign.rs::fill_text_colour_survives_preview_commit_settings_and_save", "crates/automation/tests/it/automation.rs::fill_sign_text_and_date_colours_are_saved_and_validated"]++notes = "typewriter FreeText, 10 pt Helvetica. Reads across as displayed on pages with /Rotate (sideways-stored scans): the box follows the displayed axes and the appearance is turned back (PdfCraft key /PCTextRotate); other apps that regenerate the appearance from /DA draw it unturned. A later page rotation does not re-turn it. Field detection does not work on scanned (image-only) forms yet; typed fractional font sizes commit once; Fill & Sign text/date colour is remembered and preserved in preview and saved appearances (#2444)"[[feature]]id = "form.fill-sign-marks"@@@ -5292,8 -5380,8 +5380,8 @@@ milestone = "M5status = "shipped"commands = ["sign.fill.date"]tools = ["fill_sign_add", "fill_sign_date_format"]- evidence = ["crates/ui-egui/tests/fill_sign.rs::text_marks_and_date", "crates/automation/tests/automation.rs::fill_and_sign_through_tools", "crates/ui-egui/tests/date_format.rs::fill_and_sign_dates_follow_the_date_format_preference_and_it_is_remembered", "crates/engine/src/dates.rs::presets_write_the_day_in_their_own_order", "crates/engine/src/dates.rs::names_follow_the_date_language", "crates/ui-egui/tests/date_format.rs::month_names_follow_the_date_language_or_else_the_interface_language", "crates/ui-egui/tests/date_format.rs::a_date_the_pdf_cannot_hold_is_refused_with_a_warning_first", "crates/automation/tests/automation.rs::fill_sign_text_and_date_colours_are_saved_and_validated"]- notes = "local date in Preferences ▸ Date format (default m/d/yyyy; 12 presets or any pattern in Acrobat date letters with \\ escapes, checked and previewed as typed, remembered; only whole date codes accepted; month and weekday names in the interface languages, Czech months in the genitive after a day, following the interface language unless one is picked; fill_sign_add takes a one-off format and language). Beyond Acrobat: its Fill & Sign has no format setting (only Acrobat Sign accounts do). Missing: Fill & Sign text is Helvetica/WinAnsi, so a date with letters outside Western European (Czech ř, Japanese, Chinese names) is refused with a warning instead of being saved as ?; the OS locale's format isn't offered as a preset; names in languages without an interface translation; shares the Fill & Sign text colour preference and tool argument"-evidence = ["crates/ui-egui/tests/it/fill_sign.rs::text_marks_and_date", "crates/automation/tests/it/automation.rs::fill_and_sign_through_tools", "crates/ui-egui/tests/it/date_format.rs::fill_and_sign_dates_follow_the_date_format_preference_and_it_is_remembered", "crates/engine/src/dates.rs::presets_write_the_day_in_their_own_order", "crates/engine/src/dates.rs::names_follow_the_date_language", "crates/ui-egui/tests/it/date_format.rs::month_names_follow_the_date_language_or_else_the_interface_language", "crates/ui-egui/tests/it/date_format.rs::a_date_the_pdf_cannot_hold_is_refused_with_a_warning_first"]-notes = "local date in Preferences ▸ Date format (default m/d/yyyy; 14 presets, year-first slash forms included, or any pattern in Acrobat date letters with \\ escapes, checked and previewed as typed, remembered; only whole date codes accepted; month and weekday names in the interface languages, Czech months in the genitive after a day, following the interface language unless one is picked; fill_sign_add takes a one-off format and language). Beyond Acrobat: its Fill & Sign has no format setting (only Acrobat Sign accounts do). Missing: Fill & Sign text is Helvetica/WinAnsi, so a date with letters outside Western European (Czech ř, Japanese, Chinese names) is refused with a warning instead of being saved as ?; the OS locale's format isn't offered as a preset; names in languages without an interface translation"++evidence = ["crates/ui-egui/tests/it/fill_sign.rs::text_marks_and_date", "crates/automation/tests/it/automation.rs::fill_and_sign_through_tools", "crates/ui-egui/tests/it/date_format.rs::fill_and_sign_dates_follow_the_date_format_preference_and_it_is_remembered", "crates/engine/src/dates.rs::presets_write_the_day_in_their_own_order", "crates/engine/src/dates.rs::names_follow_the_date_language", "crates/ui-egui/tests/it/date_format.rs::month_names_follow_the_date_language_or_else_the_interface_language", "crates/ui-egui/tests/it/date_format.rs::a_date_the_pdf_cannot_hold_is_refused_with_a_warning_first", "crates/automation/tests/it/automation.rs::fill_sign_text_and_date_colours_are_saved_and_validated"]++notes = "local date in Preferences ▸ Date format (default m/d/yyyy; 14 presets, year-first slash forms included, or any pattern in Acrobat date letters with \\ escapes, checked and previewed as typed, remembered; only whole date codes accepted; month and weekday names in the interface languages, Czech months in the genitive after a day, following the interface language unless one is picked; fill_sign_add takes a one-off format and language). Beyond Acrobat: its Fill & Sign has no format setting (only Acrobat Sign accounts do). Missing: Fill & Sign text is Helvetica/WinAnsi, so a date with letters outside Western European (Czech ř, Japanese, Chinese names) is refused with a warning instead of being saved as ?; the OS locale's format isn't offered as a preset; names in languages without an interface translation; typed fractional font sizes commit once; Fill & Sign text/date colour is remembered and preserved in preview and saved appearances (#2444)"[[feature]]id = "form.fill-sign-signature"