From ef297889fd66a0b1e13fd54c467cbbdb0c8efa8c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:29:01 -0500 Subject: [PATCH] compile fix 1 (shell): name resolution after the app-1 combine (swarm/cfix1, report in swarm/cfix1/run); committed by the lead --- crates/ui-egui/Cargo.toml | 4 +- crates/ui-egui/src/app.rs | 18 ++-- crates/ui-egui/src/app/clipboard.rs | 3 +- crates/ui-egui/src/app/control.rs | 2 +- crates/ui-egui/src/app/files.rs | 55 +++++------ crates/ui-egui/src/app/links.rs | 11 +-- crates/ui-egui/src/app/picks.rs | 14 ++- crates/ui-egui/src/app/prefs.rs | 17 +--- crates/ui-egui/src/app/settings.rs | 65 +++++++++---- crates/ui-egui/src/bidi/tests.rs | 2 +- crates/ui-egui/src/brand.rs | 2 +- crates/ui-egui/src/canvas.rs | 57 +++++++---- crates/ui-egui/src/canvas/bars.rs | 3 +- crates/ui-egui/src/canvas/cache.rs | 7 +- crates/ui-egui/src/canvas/crop.rs | 2 +- crates/ui-egui/src/canvas/image_pick.rs | 18 +++- crates/ui-egui/src/canvas/navigation.rs | 10 +- crates/ui-egui/src/canvas/page_menu.rs | 9 +- crates/ui-egui/src/canvas/page_overlays.rs | 12 ++- crates/ui-egui/src/canvas/page_parts.rs | 10 +- crates/ui-egui/src/canvas/page_tools.rs | 7 +- crates/ui-egui/src/canvas/signature_drag.rs | 3 +- crates/ui-egui/src/control/host.rs | 7 +- crates/ui-egui/src/dialogs.rs | 12 +-- .../ui-egui/src/dialogs/bookmark_styles_ui.rs | 3 +- crates/ui-egui/src/dialogs/comment_props.rs | 18 ++-- .../ui-egui/src/dialogs/convert_colours_ui.rs | 2 +- crates/ui-egui/src/dialogs/duplicate_field.rs | 2 +- crates/ui-egui/src/dialogs/hairlines_ui.rs | 7 +- crates/ui-egui/src/dialogs/host.rs | 1 - crates/ui-egui/src/dialogs/marks_ui.rs | 50 ++++++---- crates/ui-egui/src/dialogs/page_dialogs.rs | 18 +--- crates/ui-egui/src/dialogs/pageboxes.rs | 5 +- crates/ui-egui/src/dialogs/pin_tools.rs | 19 ++-- crates/ui-egui/src/dialogs/preferences.rs | 40 ++++++-- .../ui-egui/src/dialogs/printer_marks_ui.rs | 2 +- crates/ui-egui/src/dialogs/prompts.rs | 6 +- crates/ui-egui/src/dialogs/properties.rs | 7 +- crates/ui-egui/src/dialogs/protect.rs | 4 +- crates/ui-egui/src/dialogs/standards_ui.rs | 12 +-- crates/ui-egui/src/dialogs/summarize.rs | 6 +- crates/ui-egui/src/dialogs/word_count_ui.rs | 96 +++++++++---------- crates/ui-egui/src/editing/close.rs | 8 +- crates/ui-egui/src/lib.rs | 43 +++++---- crates/ui-egui/src/panels/side_panels.rs | 40 ++++++-- crates/ui-egui/src/persist/recovery.rs | 7 +- crates/ui-egui/src/platform/open_worker.rs | 11 ++- .../ui-egui/src/platform/open_worker/tests.rs | 61 ++++++------ crates/ui-egui/src/tools/comments.rs | 2 +- crates/ui-egui/src/workflows/actions_ui.rs | 4 +- crates/ui-egui/src/workflows/combine_ui.rs | 3 +- .../src/workflows/combine_ui/actions.rs | 2 +- .../ui-egui/src/workflows/combine_ui/table.rs | 33 ++++++- .../ui-egui/src/workflows/combine_ui/tests.rs | 7 +- .../ui-egui/src/workflows/combine_ui/view.rs | 11 ++- crates/ui-egui/src/workflows/export_ui.rs | 10 +- crates/ui-egui/src/workflows/optimize_ui.rs | 22 ++++- 57 files changed, 524 insertions(+), 388 deletions(-) diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 27d1dbe98b..51a0f9326a 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,7 +11,7 @@ workspace = true [dependencies] # The framework facade with the crates the UI uses (owed by pdf-hub-w1, which owns this manifest). -craft = { workspace = true, features = ["ui", "draw", "pages", "print", "review", "dialogs", "docpath", "font-catalog", "text", "text-font-picker", "text-find", "font-manager", "theme-store", "imaging", "window", "settings", "platform", "platform-clipboard", "atomic", "automation", "keymap", "menu", "quit", "web-host"] } +craft = { workspace = true, features = ["ui", "ui-app","draw", "pages", "print", "review", "dialogs", "docpath", "font-catalog", "text", "text-font-picker", "text-find", "font-manager", "theme-store", "imaging", "window", "settings", "platform", "platform-clipboard", "atomic", "automation", "keymap", "menu", "quit", "web-host"] } edit-session = { workspace = true } craft-ui = { workspace = true } # The menus: native on macOS, an egui bar elsewhere, from one definition (menus.rs). @@ -91,7 +91,7 @@ web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlE [dev-dependencies] # The fixture and suite runner the component trials drive the app's components with. -craft = { workspace = true, features = ["ui-testing"] } +craft = { workspace = true, features = ["ui-testing", "zip"] } pdfcraft-xfa = { workspace = true } # A content stream that inflates past the renderer's limits, for the cut-content notice test. flate2 = { workspace = true } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index aa861bd8dd..04fdd95251 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -23,14 +23,13 @@ mod frame; mod input; mod keys; mod links; -mod prefs; -mod window; pub(crate) mod picks; +mod prefs; pub(crate) mod reload; pub mod settings; +mod window; pub(crate) use clipboard::{ObjectClipMark, copy_refused, print_refused}; -#[cfg(not(target_arch = "wasm32"))] pub(crate) use files::same_file; pub(crate) use prefs::{MAX_AUTHOR_CHARS, date_text_for_pdf}; @@ -79,12 +78,11 @@ impl AppServices { /// `intake`. pub fn system(ctx: &egui::Context, intake: FileIntake) -> Self { let wake = wake_of(ctx); - // PLAN: assumed settings::recovery_dir() -> Option, the data folder's recovery folder (pdf-shell-w9). #[cfg(not(target_arch = "wasm32"))] { let clipboard = Clipboard::new(craft::platform::clipboard::SystemClipboard::new()); let watch = craft::platform::watch::FileWatch::new(wake.clone()); - Self::new(wake, clipboard, settings::recovery_dir(), None, intake, watch) + Self::new(wake, clipboard, recovery::prepare_platform_recovery_dir(), None, intake, watch) } // PLAN: assumed clipboard::web_clipboard(&egui::Context) -> Clipboard, the browser's event clipboard (pdf-shell-w17). #[cfg(target_arch = "wasm32")] @@ -208,6 +206,8 @@ impl PdfCraftApp { opens: open_worker::queue(&host, wake.clone()), #[cfg(not(target_arch = "wasm32"))] named_destinations: queue(&host, &wake, "pdfcraft-destinations"), + #[cfg(not(target_arch = "wasm32"))] + pending_destinations: Vec::new(), pinned_jobs: queue(&host, &wake, "pdfcraft-pinned-folders"), recent_check: persist::recent_check::RecentCheck::new(queue(&host, &wake, "pdfcraft-recent-check")), text_copies: queue(&host, &wake, "pdfcraft-copy-text"), @@ -232,8 +232,8 @@ impl PdfCraftApp { preferences: None, shortcuts: None, panes: Default::default(), - dock: side_panels::default_workspace(), - rail_side: Default::default(), + dock: side_panels::default_workspace(craft::behavior::DockSide::End), + rail_side: craft::behavior::DockSide::End, session: Session::new(), status_captions_lang: None, views: Vec::new(), @@ -655,9 +655,8 @@ impl PdfCraftApp { self.control_logic(ctx); self.autosave_tick(ctx, web_time::Instant::now()); // Reload documents whose files a build rewrote (#431). - // PLAN: assumed reload::watch_files(&mut PdfCraftApp, &egui::Context) at crate::platform::reload (pdf-shell-w14). #[cfg(not(target_arch = "wasm32"))] - crate::platform::reload::watch_files(self, ctx); + self.watch_files(); if self.host_dirty.is_some() { // An OCR review not yet accepted or rejected is work the page would lose, too. let dirty = self.work_at_risk(); @@ -773,7 +772,6 @@ impl PdfCraftApp { self.window_preferences_frame(&ctx); self.process_pending_edits(); } - palette::show(self, &ctx); } // Dialogs and notices show in full screen too: a refused field value or a failed save must be seen. dialogs::show(self, ui); diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 2d1714b8f4..f4a31491b7 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -126,7 +126,8 @@ impl PdfCraftApp { } // A selection across pages still being read has no text yet, but is selected all the // same: its copy starts rather than copying the selected comments. - let text_selected = self.views.get(i).is_some_and(|v| v.selection_waits_for_text().is_some() || v.selected_text().is_some_and(|t| !t.is_empty())); + let text_selected = + self.views.get(i).is_some_and(|v| v.selection_waits_for_text().is_some() || v.selected_text().is_some_and(|t| !t.is_empty())); if (text_selected || !self.copy_selected_comments(i)) && !self.copy_selected_text(i) && let Some(sel) = self.views.get(i).and_then(|v| v.image_selection.clone()) diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 54af7bcf63..be7440afd0 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -478,7 +478,7 @@ impl PdfCraftApp { Some(name) => (name.to_string(), 0), None => self.views[i].prepare.selected.clone().ok_or("select a field first, or name one: field-properties:NAME")?, }; - prepare::dialog::open(self, &name, widget, prepare::dialog::FieldTab::General); + prepare::dialog::open(self, &name, widget, prepare::FieldTab::General); } "none" => { self.cancel_dialogs(); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 1f09219697..37f203ccc8 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -18,6 +18,11 @@ fn asks_for_password(kind: &open_worker::ResultKind) -> bool { ) } +/// Whether two paths name the same file: equal, or the same once resolved on disk. +pub(crate) fn same_file(open: &str, path: &str) -> bool { + craft::platform::open::same_file(std::path::Path::new(open), std::path::Path::new(path), None) +} + impl PdfCraftApp { /// Shows `panel` as the right panel, or closes the one showing for `None`. fn set_right(&mut self, panel: Option) { @@ -64,15 +69,15 @@ impl PdfCraftApp { match v.layout { // The view opened in Default page display already. L::Default => {} - L::SinglePage => (view.layout, view.continuous) = (canvas::PageLayout::Single, false), - L::SinglePageContinuous => (view.layout, view.continuous) = (canvas::PageLayout::Single, true), - L::TwoUp => (view.layout, view.continuous) = (canvas::PageLayout::TwoUp, false), - L::TwoUpContinuous => (view.layout, view.continuous) = (canvas::PageLayout::TwoUp, true), + L::SinglePage => (view.view.display, view.view.continuous) = (canvas::PageDisplay::Single, false), + L::SinglePageContinuous => (view.view.display, view.view.continuous) = (canvas::PageDisplay::Single, true), + L::TwoUp => (view.view.display, view.view.continuous) = (canvas::PageDisplay::TwoUp, false), + L::TwoUpContinuous => (view.view.display, view.view.continuous) = (canvas::PageDisplay::TwoUp, true), L::TwoUpCoverPage => { - (view.layout, view.continuous, view.cover) = (canvas::PageLayout::TwoUp, false, true); + (view.view.display, view.view.continuous, view.view.cover) = (canvas::PageDisplay::TwoUp, false, true); } L::TwoUpContinuousCoverPage => { - (view.layout, view.continuous, view.cover) = (canvas::PageLayout::TwoUp, true, true); + (view.view.display, view.view.continuous, view.view.cover) = (canvas::PageDisplay::TwoUp, true, true); } } match v.magnification { @@ -131,7 +136,8 @@ impl PdfCraftApp { // A new document opens with the remembered Highlight fields, which its scripts read; the // session keeps the document in front's. let context = self.session.open_context().with_highlight(self.highlight_fields); // PLAN: `highlight_fields` on the app (pdf-canvas-w8) - let job = open_worker::Job { context, name: request.name.clone(), path: request.path.clone(), password: request.password, input: request.input }; + let job = + open_worker::Job { context, name: request.name.clone(), path: request.path.clone(), password: request.password, input: request.input }; self.opens.submit(token, request.priority, move |cancel| open_worker::run(job, cancel)); self.pending_opens.push(PendingOpen { token, @@ -513,10 +519,8 @@ impl PdfCraftApp { } (Ok(bytes), _) => { #[cfg(not(target_arch = "wasm32"))] - self.pick_first( - PickRequest::save("attachment").file_name(safe_file_name(&att.name, "attachment")), - None, - move |app, path| match craft::atomic::atomic_write(&path, &bytes) { + self.pick_first(PickRequest::save("attachment").file_name(safe_file_name(&att.name, "attachment")), None, move |app, path| { + match craft::atomic::atomic_write(&path, &bytes) { Ok(()) => { // Windows: the file keeps the document's Mark-of-the-Web (#3990). Best // effort: a volume without alternate data streams can't carry it. @@ -524,8 +528,8 @@ impl PdfCraftApp { app.notify_fmt("Saved {name}", &[("name", &path.display().to_string())]) } Err(e) => app.notify_fmt("Couldn't save: {e}", &[("e", &e.to_string())]), - }, - ); + } + }); #[cfg(target_arch = "wasm32")] self.notify_fmt("Downloading attachments on the web arrives with M3.10 ({n} bytes ready)", &[("n", &bytes.len().to_string())]); } @@ -768,12 +772,7 @@ impl PdfCraftApp { /// The tab already showing the file at `path` (the same path, or one that names the same /// file once made absolute). pub(crate) fn tab_showing(&self, path: &str) -> Option { - self.views.iter().position(|v| { - self.session - .get(v.id) - .and_then(|d| d.path.as_deref()) - .is_some_and(|p| craft::platform::open::same_file(std::path::Path::new(p), std::path::Path::new(path), None)) - }) + self.views.iter().position(|v| self.session.get(v.id).and_then(|d| d.path.as_deref()).is_some_and(|p| same_file(p, path))) } /// Open a file from a recent list: focus the tab already showing it, else open it (File ▸ @@ -803,7 +802,7 @@ impl PdfCraftApp { } #[cfg(not(target_arch = "wasm32"))] - fn open_path_request(&mut self, path: &str, then: Option<&'static str>, display_override: Option<(canvas::PageLayout, bool)>) -> OpenOutcome { + fn open_path_request(&mut self, path: &str, then: Option<&'static str>, display_override: Option<(canvas::PageDisplay, bool)>) -> OpenOutcome { // `manual.pdf#nameddest=Intro`, as a help system starts a PDF reader (#3425): the file, // shown at that destination once open. A path that names a file is never split. match pdfcraft_engine::open_parameters::split(path, |p| std::path::Path::new(p).is_file()) { @@ -820,7 +819,7 @@ impl PdfCraftApp { path: &str, after_open: Option, then: Option<&'static str>, - display_override: Option<(canvas::PageLayout, bool)>, + display_override: Option<(canvas::PageDisplay, bool)>, ) -> OpenOutcome { // One file, one tab (#2166): a file that is open already comes to the front instead, // and the tool it was opened for runs on it. One still being opened is left to that. @@ -841,11 +840,7 @@ impl PdfCraftApp { } return OpenOutcome::Focused; } - if let Some(pending) = self - .pending_opens - .iter_mut() - .find(|p| p.path.as_deref().is_some_and(|p| craft::platform::open::same_file(std::path::Path::new(p), std::path::Path::new(path), None))) - { + if let Some(pending) = self.pending_opens.iter_mut().find(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) { if display_override.is_some() { pending.display_override = display_override; } @@ -858,11 +853,7 @@ impl PdfCraftApp { // The same file named again while its password is being asked for joins that prompt // instead of queuing a second one; a display override, a place to open at or a tool it // brings is kept. - if let Some(prompt) = self - .password_prompt - .as_mut() - .filter(|p| p.path.as_deref().is_some_and(|p| craft::platform::open::same_file(std::path::Path::new(p), std::path::Path::new(path), None))) - { + if let Some(prompt) = self.password_prompt.as_mut().filter(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) { if display_override.is_some() { prompt.display_override = display_override; } @@ -924,7 +915,7 @@ impl PdfCraftApp { /// Open one native file with a transient display override, including after a password prompt. #[cfg(not(target_arch = "wasm32"))] - pub fn open_path_with_display(&mut self, path: &str, layout: canvas::PageLayout, continuous: bool) { + pub fn open_path_with_display(&mut self, path: &str, layout: canvas::PageDisplay, continuous: bool) { self.open_path_request(path, None, Some((layout, continuous))); } diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 22e9abfdd7..3823dfd0d3 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -77,12 +77,10 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] self.pending_destinations.retain(|pending| pending.doc != id); let destination = match destination { - pdfcraft_render::RemoteDestination::Named(name) => { - match self.look_up_named_destination(id, name) { - Some(destination) => destination, - None => return, - } - } + pdfcraft_render::RemoteDestination::Named(name) => match self.look_up_named_destination(id, name) { + Some(destination) => destination, + None => return, + }, other => other, }; self.show_destination_at(index, destination); @@ -111,7 +109,6 @@ impl PdfCraftApp { /// Show each named destination whose lookup has finished, in its document's tab. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn poll_pending_destinations(&mut self) { - // PLAN: `named_destinations` is `JobQueue>` (pdf-hub-w1) while let Some(done) = self.named_destinations.try_recv() { let Some(at) = self.pending_destinations.iter().position(|pending| pending.doc == done.key) else { continue }; let pending = self.pending_destinations.remove(at); diff --git a/crates/ui-egui/src/app/picks.rs b/crates/ui-egui/src/app/picks.rs index a9e0a1ad3d..92f735e2a0 100644 --- a/crates/ui-egui/src/app/picks.rs +++ b/crates/ui-egui/src/app/picks.rs @@ -38,7 +38,12 @@ impl PdfCraftApp { /// longer the active one, or has been edited, is dropped and the user is told /// ([`Self::still_pick_target`]): use it whenever `then` edits the active document or refers /// to its pages or objects by position. A cancelled answer reaches `then` whatever the target. - pub(crate) fn pick_file(&mut self, request: PickRequest, target: Option, then: impl FnOnce(&mut PdfCraftApp, Picked) + 'static) -> PickId { + pub(crate) fn pick_file( + &mut self, + request: PickRequest, + target: Option, + then: impl FnOnce(&mut PdfCraftApp, Picked) + 'static, + ) -> PickId { let id = self.host.files().pick(request); self.picks.waiting.insert(id, (target, Box::new(then))); id @@ -46,7 +51,12 @@ impl PdfCraftApp { /// [`Self::pick_file`] for one path: `then` gets the first chosen path, and nothing runs when /// the picker is cancelled. On the web the path is the browser's file name. - pub(crate) fn pick_first(&mut self, request: PickRequest, target: Option, then: impl FnOnce(&mut PdfCraftApp, PathBuf) + 'static) -> PickId { + pub(crate) fn pick_first( + &mut self, + request: PickRequest, + target: Option, + then: impl FnOnce(&mut PdfCraftApp, PathBuf) + 'static, + ) -> PickId { self.pick_file(request, target, move |app, picked| { if let Some(path) = picked.first_path() { then(app, path); diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 17c0faa7b5..6fb750c908 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -41,18 +41,10 @@ fn from_name(name: &str) -> Option { } impl PdfCraftApp { - /// Sets the user's interface theme preference (Light, Dark, or System). + /// Sets the user's interface theme preference (Light, Dark, or System); the next frame's + /// [`Self::root_env`] carries it. pub fn set_theme_preference(&mut self, preference: ModeChoice) { self.theme_preference = preference; - if let Some(ctx) = self.ctx.clone() { - self.sync_theme(&ctx); - theme::apply(&ctx, self.theme); - } else { - self.theme = match preference { - ModeChoice::Dark => ThemeKind::Dark, - _ => ThemeKind::Light, - }; - } } /// The app-wide reading-colours preference: sets it and applies it to every open document, @@ -194,10 +186,7 @@ impl PdfCraftApp { // PLAN: assumed app field `hotbar_tools: Vec` (chrome-w18) let hotbar = settings::Hotbar { tools: Some(self.hotbar_tools.clone()) }; // Kept only while the preference is on. - let session = settings::Session { - - last_session: self.reopen_last_session.then(|| json_text(&self.session_to_save())).flatten(), - }; + let session = settings::Session { last_session: self.reopen_last_session.then(|| json_text(&self.session_to_save())).flatten() }; PdfCraftSettings { layout, print, behavior, view, comment, signature, dock, recent, hotbar, session } } diff --git a/crates/ui-egui/src/app/settings.rs b/crates/ui-egui/src/app/settings.rs index 5a06f96721..d78c8a37ce 100644 --- a/crates/ui-egui/src/app/settings.rs +++ b/crates/ui-egui/src/app/settings.rs @@ -242,25 +242,29 @@ impl Settings for PdfCraftSettings { const PORTABLE_DIR: &'static str = "PdfCraftData"; } +/// The settings store the app reads its preferences from and writes them to. +pub type Store = craft::settings::SettingsStore; + +/// How the data folder was chosen (portable marker, environment, platform folder). Resolved once: +/// it is a fact of how the app was installed, and the settings store opens at the same folder. +/// Native only: the web has no folder rules. +#[cfg(not(target_arch = "wasm32"))] +pub fn resolution() -> &'static craft::settings::Resolved { + use craft::settings::paths::{self, Portable, Probe}; + static RESOLVED: std::sync::OnceLock = std::sync::OnceLock::new(); + RESOLVED.get_or_init(|| { + let portable = Portable { markers: PdfCraftSettings::PORTABLE_MARKERS, dir: PdfCraftSettings::PORTABLE_DIR }; + paths::resolve_named(PdfCraftSettings::APP_ID, PdfCraftSettings::FOLDER_NAME, &portable, &craft::settings::Location::Auto, &Probe::default()) + }) +} + /// The data folder beside the executable, when a portable marker sits there and the folder can be -/// written; `None` otherwise, and always on the web. Resolved once: it is a fact of how the app -/// was installed, and the settings store opens at the same folder. +/// written; `None` otherwise, and always on the web. pub fn portable_dir() -> Option { #[cfg(not(target_arch = "wasm32"))] { - use craft::settings::paths::{self, Portable, Probe, Resolved, Rule}; - static RESOLVED: std::sync::OnceLock = std::sync::OnceLock::new(); - let resolved = RESOLVED.get_or_init(|| { - let portable = Portable { markers: PdfCraftSettings::PORTABLE_MARKERS, dir: PdfCraftSettings::PORTABLE_DIR }; - paths::resolve_named( - PdfCraftSettings::APP_ID, - PdfCraftSettings::FOLDER_NAME, - &portable, - &craft::settings::Location::Auto, - &Probe::default(), - ) - }); - if resolved.rule == Rule::Portable { resolved.dir.clone() } else { None } + let resolved = resolution(); + if resolved.rule == craft::settings::Rule::Portable { resolved.dir.clone() } else { None } } #[cfg(target_arch = "wasm32")] { @@ -268,6 +272,29 @@ pub fn portable_dir() -> Option { } } +/// Opens the settings store at the folder [`resolution`] chose (in memory when it chose none), +/// importing the last release's `app.ron` on first run; on the web, over the browser's storage. +pub fn open() -> Store { + #[cfg(not(target_arch = "wasm32"))] + let options = { + let location = match &resolution().dir { + Some(dir) => craft::settings::Location::Dir(dir.clone()), + None => craft::settings::Location::Memory, + }; + craft::settings::OpenOptions::new(location).legacy(legacy_files()) + }; + #[cfg(target_arch = "wasm32")] + let options = craft::settings::OpenOptions::new(craft::settings::Location::Dir(PathBuf::from(PdfCraftSettings::APP_ID))) + .files(std::sync::Arc::new(craft::settings::BrowserFiles)); + Store::open_with(options).0 +} + +/// The OCR Verify screen's user dictionary folder: the portable data folder's, else the +/// platform's per-user one; `None` where files are not kept (the web). +pub fn dictionary_dir() -> Option { + crate::recovery::default_dictionary_dir() +} + /// The folders the last releases kept `app.ron` in, nearest first. fn legacy_folders() -> Vec { #[cfg(not(target_arch = "wasm32"))] @@ -459,7 +486,6 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec) { } motion }); - // PLAN: assumed `combine_ui::columns_from_legacy(&Value) -> Option` (workflows-w6): the last release kept `{order, widths}` by sort key let combine_columns = r.value("combine_columns").and_then(crate::combine_ui::columns_from_legacy); Layout { reopen_last_session: r.bool("reopen_last_session"), @@ -622,11 +648,14 @@ fn session_text(value: &Value) -> Option { } else { let files = value.get("files").and_then(Value::as_array).cloned().unwrap_or_default(); let active = match &value["active"] { - Value::Number(n) => n.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| files.get(i)).and_then(|f| f["path"].as_str()).map(str::to_string), + Value::Number(n) => { + n.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| files.get(i)).and_then(|f| f["path"].as_str()).map(str::to_string) + } Value::String(path) => Some(path.clone()), _ => None, }; - let documents: Vec = files.iter().map(|f| serde_json::json!({ "path": f["path"], "view": f.get("view").cloned().unwrap_or(Value::Null) })).collect(); + let documents: Vec = + files.iter().map(|f| serde_json::json!({ "path": f["path"], "view": f.get("view").cloned().unwrap_or(Value::Null) })).collect(); Session::from_json(&serde_json::json!({ "documents": documents, "active": active })) }; serde_json::to_string(&session).ok() diff --git a/crates/ui-egui/src/bidi/tests.rs b/crates/ui-egui/src/bidi/tests.rs index f6993bb61e..585b966302 100644 --- a/crates/ui-egui/src/bidi/tests.rs +++ b/crates/ui-egui/src/bidi/tests.rs @@ -87,7 +87,7 @@ fn wrapping_handles_odd_widths_and_input() { /// ones left out, with the interface fonts. fn on_screen(text: &str) -> Vec { let ctx = egui::Context::default(); - ctx.set_fonts(crate::theme::font_definitions()); + crate::fonts::ui_fonts(crate::i18n::Lang::EN).install(&ctx); let mut shown = Vec::new(); let output = ctx.run_ui(egui::RawInput::default(), |ui| { for line in wrap(text, |_| true) { diff --git a/crates/ui-egui/src/brand.rs b/crates/ui-egui/src/brand.rs index b42601f0bc..f48ff01a95 100644 --- a/crates/ui-egui/src/brand.rs +++ b/crates/ui-egui/src/brand.rs @@ -7,7 +7,7 @@ use craft::theme::Mode; use craft::ui::display::{Picture, PictureSize}; use craft::ui::list::ThumbAspect; -use craft::ui::runtime::Env; +use craft::ui::runtime::env::Env; const MARK: &[u8] = include_bytes!("../../../docs/brand/artcraft-mark.svg"); const LOGO: &[u8] = include_bytes!("../../../docs/brand/artcraft-logo.svg"); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d0cdf9a0af..58a754cc44 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -8,8 +8,8 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use craft::behavior::{CanvasView, PointerButton, PressPhase, Selection}; -use craft::pages::ui::{PageBody, PageView, PageViewOutput, PageViewState, PlacedPage, TextMark, TextMarks, TextSelectState, TextSelection}; use craft::host::queue::{JobQueue, QueueOptions}; +use craft::pages::ui::{PageBody, PageView, PageViewOutput, PageViewState, PlacedPage, TextMark, TextMarks, TextSelectState, TextSelection}; use craft::ui::canvas::{ContextRequest, Momentary, NavigationOptions, PageBorder, ToolHost}; use craft::ui::contract::Show as _; use craft::ui::display::Text; @@ -60,7 +60,7 @@ use page_overlays::{LinkEvent, LinkMode, PageLinks, PageOverlays, overlay_parts} use page_parts::{Owner, PagePart, PageParts, PagePress}; use page_tools::{PageToolCx, page_tool}; use pictures::{DocPages, PageRevisions, RenderReports}; -pub(crate) use selection::ToolMarks; +pub(crate) use selection::{TextSpan, ToolMarks}; pub use xform::PageXform; /// Logical pixels per PDF point at 100% (96 dpi, like browsers). @@ -866,7 +866,12 @@ struct BodyOut { /// Select and Link), comments (only under Select), fields, sign tabs (painted over their fields), then prepare fields, /// selected objects and the frame band. A later part outranks an earlier one of the same layer, so this order is the /// stacking order hit testing ranks on. -fn page_parts_of(ui: &mut egui::Ui, body: &PageBody<'_>, session: &PageSession, cx: &PageBodyCx<'_>) -> (Vec, Vec<(usize, PageXform, Vec)>) { +fn page_parts_of( + ui: &mut egui::Ui, + body: &PageBody<'_>, + session: &PageSession, + cx: &PageBodyCx<'_>, +) -> (Vec, Vec<(usize, PageXform, Vec)>) { let mut parts = Vec::new(); // PLAN: assumed `edit_text_ui::picture_parts(out, session, doc, pages, rotation)`, `edit_text_ui::page_parts` and // `content_ui::page_parts` with the same shape (pdf-edit-w7, w8, w9 give no argument list). @@ -1053,8 +1058,16 @@ fn page_body(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSession, let selected = session.prepare.selected.as_ref().map(|(name, _)| name.as_str()); // PLAN: assumed `CalcOrderOverlay::new(&CalcOrderView, pages, rotation, generation, selected, hovered, // viewport)` (pdf-forms-w12 gives `new(.., viewport: body.rect)`). - crate::calc_order_ui::CalcOrderOverlay::new(&session.calc_order, body.pages, cx.rotation, cx.doc.edit_generation(), selected, hovered, body.rect) - .show_at(ui, body.rect); + crate::calc_order_ui::CalcOrderOverlay::new( + &session.calc_order, + body.pages, + cx.rotation, + cx.doc.edit_generation(), + selected, + hovered, + body.rect, + ) + .show_at(ui, body.rect); } if let Some(preview) = cx.table_preview { // PLAN: assumed `field_table_ui::TablePreview::new(&Preview, pages, rotation)` (pdf-forms-w11). @@ -1148,8 +1161,10 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu let show_secured_notice = app.show_secured_notice; // Offer to lock a just-placed signature (#2149) on the same terms the save-time question // asks: one is still there, saving doesn't lock it anyway, and the document isn't signed. - let lock_offer = - !app.flatten_fill_sign_on_save && app.placed_signatures.contains(&doc_id) && doc.info.annotations.iter().any(|a| a.fill_sign) && !doc.is_signed(); + let lock_offer = !app.flatten_fill_sign_on_save + && app.placed_signatures.contains(&doc_id) + && doc.info.annotations.iter().any(|a| a.fill_sign) + && !doc.is_signed(); 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 ▸ @@ -1182,8 +1197,8 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu // Prepare a form ▸ Calculation order: the order's steps and links on the page. let calc_order = preparing && crate::side_panels::panel_visible(app, crate::LeftPanel::CalculationOrder); // Edit a PDF: added text and images can be selected, moved and edited. - let editing_content = crate::side_panels::panel_visible(app, crate::LeftPanel::Tool("edit")) - || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText); + let editing_content = + crate::side_panels::panel_visible(app, crate::LeftPanel::Tool("edit")) || matches!(app.quick_tool, QuickTool::AddText | QuickTool::EditText); let chosen = app.quick_tool; let navigation = app.navigation_options(); let presenting = app.views[index].presenting(); @@ -1217,7 +1232,8 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu view.session.move_background.prepare(ui.ctx(), doc, &view.session.content, scale); let find_marks: Vec = view.find.as_ref().map(Find::marks).unwrap_or_default(); - let present_at = presenting.then_some(presenter::PresentAt { current: view.view.current, display: view.view.display, rotation: view.view.rotation }); + let present_at = + presenting.then_some(presenter::PresentAt { current: view.view.current, display: view.view.display, rotation: view.view.rotation }); let border = if view.view.page_gaps { PageBorder::DropShadow } else { PageBorder::None }; let keep = view.session.presenter.keep_pages(); if view.momentary_options != navigation { @@ -1286,11 +1302,11 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu }; let source = DocPages::new(&app.session, doc_id).rotated(state.rotation).revisions(revisions).reports(reports); // A modal over the pages blocks the canvas's keys and presses in the framework, so the view needs no gate here. - let out = PageView::new(tl!("Pages"), &source, state, DataColor::new(paper)) - .navigation(navigation) - .border(border) - .keep(&keep) - .show_at(ui, rect, |ui, body| page_body(ui, body, session, momentary, &cx, &mut body_out)); + let out = PageView::new(tl!("Pages"), &source, state, DataColor::new(paper)).navigation(navigation).border(border).keep(&keep).show_at( + ui, + rect, + |ui, body| page_body(ui, body, session, momentary, &cx, &mut body_out), + ); if let Some(canvas) = &body_out.view { out.adopt(&mut view.view, canvas); } @@ -1301,10 +1317,8 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu // double-click time has passed with no object clicked and no selection made (#2070). let now = ui.input(|i| i.time); let has_selection = view.session.text.selection.is_some(); - let click = (presenting && matches!(out.canvas.press.phase, PressPhase::Release { click: true, .. })).then(|| presenter::PresentClick { - forward: !out.canvas.press.mods.shift, - clicks: if out.canvas.press.double_pressed() { 2 } else { 1 }, - }); + let click = (presenting && matches!(out.canvas.press.phase, PressPhase::Release { click: true, .. })) + .then(|| presenter::PresentClick { forward: !out.canvas.press.mods.shift, clicks: if out.canvas.press.double_pressed() { 2 } else { 1 } }); let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay); let cancels = body_out.link.is_some() || has_selection; let click_turn = if presenting { view.session.presenter.click_turn(ui.ctx(), click, cancels, now, delay) } else { None }; @@ -1328,7 +1342,8 @@ pub fn document_area_at(app: &mut PdfCraftApp, index: usize, rect: Rect, ui: &mu if view.session.text_queue.is_none() { let ctx = ui.ctx().clone(); let wake = craft::host::Wake::new(move || ctx.request_repaint()); - view.session.text_queue = Some(JobQueue::new(app.host.jobs_shared().clone(), wake, QueueOptions { name: "text-layers", ..QueueOptions::default() })); + view.session.text_queue = + Some(JobQueue::new(app.host.jobs_shared().clone(), wake, QueueOptions { name: "text-layers", ..QueueOptions::default() })); } let (visible_pages, rest_pages) = text_demand(view, out.visible.clone(), chosen == QuickTool::Hand); view.want_text(&app.session, &visible_pages, &rest_pages); @@ -1710,11 +1725,11 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, requests: FrameRequ } } +pub(crate) mod page_box_drag; #[cfg(test)] mod sign_tab_tests; #[cfg(test)] mod tests; -pub(crate) mod page_box_drag; pub(crate) use page_box_drag::PageBoxDrag; pub(crate) mod page_menu; pub(crate) mod page_select; diff --git a/crates/ui-egui/src/canvas/bars.rs b/crates/ui-egui/src/canvas/bars.rs index 47b37c8356..a685bdd4b4 100644 --- a/crates/ui-egui/src/canvas/bars.rs +++ b/crates/ui-egui/src/canvas/bars.rs @@ -127,7 +127,8 @@ pub(super) fn notices( } } if let Some((icon, tone, template, arg)) = signed { - let out = bar(tone, icon, crate::i18n::fmt(tl!(template), &[("by", &arg)])).action(NoticeAction::new(tl!("Signature panel").to_string())).show(ui); + let out = + bar(tone, icon, crate::i18n::fmt(tl!(template), &[("by", &arg)])).action(NoticeAction::new(tl!("Signature panel").to_string())).show(ui); return (out.action == Some(0)).then_some(Notice::Signatures); } if view.notice_dismissed { diff --git a/crates/ui-egui/src/canvas/cache.rs b/crates/ui-egui/src/canvas/cache.rs index 82dc57397e..92110f3cc3 100644 --- a/crates/ui-egui/src/canvas/cache.rs +++ b/crates/ui-egui/src/canvas/cache.rs @@ -175,11 +175,7 @@ impl DocView { } let mut renderer = pdfcraft_render::PageRenderer::new(bytes, config); let out = renderer.render(RenderRequest { page, kind: RequestKind::Text, scale: 1.0, ..Default::default() }); - TextOutcome { - cut: out.warnings.contains(&pdfcraft_render::RenderWarning::ContentTruncated), - text: out.text, - error: out.error, - } + TextOutcome { cut: out.warnings.contains(&pdfcraft_render::RenderWarning::ContentTruncated), text: out.text, error: out.error } }); } } @@ -210,7 +206,6 @@ impl DocView { self.texts.retain(|p, _| keep.contains(p)); } - /// Device scale of a page raster: exactly the device scale, as a raster at any other scale is /// resampled on screen, which blurs every line and glyph (#260). pub(super) fn render_scale(&self, ppp: f32) -> f32 { diff --git a/crates/ui-egui/src/canvas/crop.rs b/crates/ui-egui/src/canvas/crop.rs index 29ffdac84c..65704038dd 100644 --- a/crates/ui-egui/src/canvas/crop.rs +++ b/crates/ui-egui/src/canvas/crop.rs @@ -2,11 +2,11 @@ //! rectangle; double-click a page to open Set Page Boxes for it. use craft::behavior::{CancelReason, Cursor, CursorIcon}; +use craft::pages::ui::PlacedPage; use craft::ui::canvas::crop::{CropShield, paint_outside}; use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft::ui::primitives::Draw; use craft::ui::style::DataColor; -use craft::pages::ui::PlacedPage; use pdfcraft_engine::{BoxSpec, Edit, PageBox}; use pdfcraft_render::DocInfo; diff --git a/crates/ui-egui/src/canvas/image_pick.rs b/crates/ui-egui/src/canvas/image_pick.rs index 1077b95b0f..cdde3a17b4 100644 --- a/crates/ui-egui/src/canvas/image_pick.rs +++ b/crates/ui-egui/src/canvas/image_pick.rs @@ -8,9 +8,9 @@ use std::sync::Arc; use craft::behavior::kurbo::BezPath; use craft::host::queue::{JobQueue, Priority, QueueOptions}; use craft::host::{Jobs, Wake}; +use craft::pages::ui::PageBody; #[cfg(not(target_arch = "wasm32"))] use craft::platform::clipboard::Flavor; -use craft::pages::ui::PageBody; use craft::ui::canvas_controls::SelectionOutline; use craft::ui::contract::Show as _; @@ -80,7 +80,13 @@ impl PagePictures { /// The pictures on `page`, or `None` while they are being found (the queue's `wake` repaints on the answer). // PLAN: the decisions give `get(ctx, host, wake, doc, page)`; the queue needs the host's jobs and the wake only. - pub(crate) fn get(&mut self, jobs: &Arc, wake: &Wake, doc: &pdfcraft_engine::Document, page: usize) -> Option<&[pdfcraft_engine::PagePicture]> { + pub(crate) fn get( + &mut self, + jobs: &Arc, + wake: &Wake, + doc: &pdfcraft_engine::Document, + page: usize, + ) -> Option<&[pdfcraft_engine::PagePicture]> { let key = (page, doc.edit_generation()); self.poll(); let known = self.ready.as_ref().is_some_and(|(k, _)| *k == key); @@ -96,7 +102,13 @@ impl PagePictures { self.ready.as_ref().filter(|(k, _)| *k == key).map(|(_, pictures)| pictures.as_slice()) } - fn start(&mut self, jobs: &Arc, wake: &Wake, key: PictureKey, work: impl FnOnce() -> Vec + Send + 'static) { + fn start( + &mut self, + jobs: &Arc, + wake: &Wake, + key: PictureKey, + work: impl FnOnce() -> Vec + Send + 'static, + ) { let queue = self.queue.get_or_insert_with(|| { let mut options = QueueOptions::default(); // One search at a time: each is a full read of a page. The web has no lanes; `poll` runs the job. diff --git a/crates/ui-egui/src/canvas/navigation.rs b/crates/ui-egui/src/canvas/navigation.rs index bc5c671769..c57f707904 100644 --- a/crates/ui-egui/src/canvas/navigation.rs +++ b/crates/ui-egui/src/canvas/navigation.rs @@ -1,6 +1,6 @@ +use craft::behavior::kurbo::{Point, Rect}; use craft::pages::Fit; use craft::pages::ui::view::GoTo; -use craft::behavior::kurbo::{Point, Rect}; use super::{DestView, DocInfo, DocView, pos2}; @@ -175,12 +175,8 @@ impl DocView { let (dw, dh) = size; let (w, h) = ((ax - bx).abs() * dw, (ay - by).abs() * dh); if w >= 1.0 && h >= 1.0 { - let rect = Rect::new( - f64::from(ax.min(bx) * dw), - f64::from(ay.min(by) * dh), - f64::from(ax.max(bx) * dw), - f64::from(ay.max(by) * dh), - ); + let rect = + Rect::new(f64::from(ax.min(bx) * dw), f64::from(ay.min(by) * dh), f64::from(ax.max(bx) * dw), f64::from(ay.max(by) * dh)); self.view.go_to = Some(GoTo::Rect { page, rect, margin: 0.0 }); } return; diff --git a/crates/ui-egui/src/canvas/page_menu.rs b/crates/ui-egui/src/canvas/page_menu.rs index b962f39791..979671ea48 100644 --- a/crates/ui-egui/src/canvas/page_menu.rs +++ b/crates/ui-egui/src/canvas/page_menu.rs @@ -2,8 +2,8 @@ use craft::behavior::IconId; use craft::ui::canvas::ContextRequest; -use craft::ui::contract::overlay::Anchor; use craft::ui::contract::Show as _; +use craft::ui::contract::overlay::Anchor; use craft::ui::display::Divider; use craft::ui::menu::{Menu, MenuIcon, MenuIconRow, MenuItem}; use pdfcraft_engine::Edit; @@ -343,10 +343,9 @@ fn rows(ui: &mut egui::Ui, view: &mut DocView, cx: &PageMenuCx<'_>, menu_for: Op } let (page, at) = view.comments.context_at.unwrap_or((view.current, [0.0, 0.0])); // On a page still being read, the picture rows appear when the answer comes. - let picture_under = view - .comments - .context_at - .and_then(|(page, at)| view.pictures.get(ui.ctx(), cx.doc, page).and_then(|pictures| pdfcraft_engine::picture_at(pictures, at)).map(|(index, _)| *index)); + let picture_under = view.comments.context_at.and_then(|(page, at)| { + view.pictures.get(ui.ctx(), cx.doc, page).and_then(|pictures| pdfcraft_engine::picture_at(pictures, at)).map(|(index, _)| *index) + }); // A text selection whose pages are still being read copies once they are. let has_text = view.selected_text().is_some() || view.selection_waits_for_text().is_some(); let can_copy_items = cx.can_copy && (view.image_selection.is_some() || has_text || picture_under.is_some()); diff --git a/crates/ui-egui/src/canvas/page_overlays.rs b/crates/ui-egui/src/canvas/page_overlays.rs index 19df4816fa..7b7b7e4db9 100644 --- a/crates/ui-egui/src/canvas/page_overlays.rs +++ b/crates/ui-egui/src/canvas/page_overlays.rs @@ -127,7 +127,10 @@ impl PageLinks<'_> { } let tip = self.unobstructed.then(|| link.uri.clone()); for r in &link.rects { - let rect = Rect::from_two_pos(self.xf.norm_to_screen(r[0] / self.xf.pw, r[1] / self.xf.ph), self.xf.norm_to_screen(r[2] / self.xf.pw, r[3] / self.xf.ph)); + let rect = Rect::from_two_pos( + self.xf.norm_to_screen(r[0] / self.xf.pw, r[1] / self.xf.ph), + self.xf.norm_to_screen(r[2] / self.xf.pw, r[3] / self.xf.ph), + ); if rect.is_finite() { out.push(link_part(Owner::TextLink { index }, self.page, HitShape::Rect(rect), tip.clone())); } @@ -266,7 +269,9 @@ pub(crate) fn overlay_parts(ui: &mut egui::Ui, xf: &PageXform, doc: &Document, p let Some(field) = form.iter().position(|f| f.name == name) else { continue }; let on_screen = xf.user_rect(info, page, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]); let Some(tab) = sign_tab_on_page(on_screen, xf.rect, width) else { continue }; - out.parts.push(PagePart::new(Owner::SignTab { field }, page, HitShape::Rect(tab.rect), PageLayer::Field).cursor(CursorIcon::PointingHand).passes_drag()); + out.parts.push( + PagePart::new(Owner::SignTab { field }, page, HitShape::Rect(tab.rect), PageLayer::Field).cursor(CursorIcon::PointingHand).passes_drag(), + ); out.tabs.push(tab); } out @@ -434,7 +439,8 @@ impl Component for PageOverlays<'_> { fn style(cx: &StyleCx<'_>, _: PageOverlaysStyleKey) -> PageOverlaysStyle { let tokens = cx.tokens; let colors = &tokens.color; - let tones = [Tone::Neutral, Tone::Accent, Tone::Info, Tone::Good, Tone::Warn, Tone::Bad].into_iter().map(|tone| (tone, cx.tone(tone))).collect(); + let tones = + [Tone::Neutral, Tone::Accent, Tone::Info, Tone::Good, Tone::Warn, Tone::Bad].into_iter().map(|tone| (tone, cx.tone(tone))).collect(); PageOverlaysStyle { metrics: Metrics::new(), field_fill: cx.color(colors.status.info.bg), diff --git a/crates/ui-egui/src/canvas/page_parts.rs b/crates/ui-egui/src/canvas/page_parts.rs index 1d35112c40..410d507b3e 100644 --- a/crates/ui-egui/src/canvas/page_parts.rs +++ b/crates/ui-egui/src/canvas/page_parts.rs @@ -367,9 +367,11 @@ impl Component for PageParts<'_> { /// Reads the press, the hover, the focused part's key and the focus that arrived. The press machine reports a /// press's phases one per pass, so a second pass of a frame reads only its own phase. fn update(&mut self, cx: &mut Cx<'_, Self>) { - let pressed = self.parts.iter().filter_map(|part| part.owner.part_ref(part.page)).any(|at| { - cx.part_if_declared(at).is_some_and(|result| result.press.phase.is_press()) - }); + let pressed = self + .parts + .iter() + .filter_map(|part| part.owner.part_ref(part.page)) + .any(|at| cx.part_if_declared(at).is_some_and(|result| result.press.phase.is_press())); if let Some(owner) = self.focus && (cx.is_focused() || pressed) && let Some(at) = self.parts.iter().filter(|part| part.focusable && part.owner == owner).find_map(|part| part.owner.part_ref(part.page)) @@ -403,5 +405,3 @@ impl Component for PageParts<'_> { PagePartsOutput { response: cx.response.clone(), press, key, hovered, focused } } } - - diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index 59f467dbe6..17c43c4135 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -9,8 +9,7 @@ use craft::keymap::Mods; use craft::pages::ui::{PageTexts, PlacedPage, TextSelectState}; use craft::review::SavedSignature; use craft::ui::canvas::{ - CanvasTool, HandTool, NavigationOptions, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer, ToolRegion, - ZoomTool, + CanvasTool, HandTool, NavigationOptions, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer, ToolRegion, ZoomTool, }; use craft::ui::primitives::Draw; use pdfcraft_engine::{Document, Edit, FormField}; @@ -295,9 +294,7 @@ pub(crate) fn page_tool<'a>( }; Arm::Area(Box::new(FillSignTool::new(&cx, input, fill))) } - QuickTool::Field(field_tool) => { - Arm::Area(Box::new(PrepareTool::new(Some(field_tool), cx.can_modify, cx.form, session))) - } + QuickTool::Field(field_tool) => Arm::Area(Box::new(PrepareTool::new(Some(field_tool), cx.can_modify, cx.form, session))), // PLAN: assumed `AddTextTool::new(session, doc, info)` in `content_ui` (pdf-edit-w7 gives no argument list). QuickTool::AddText => Arm::Area(Box::new(crate::tools::content_ui::AddTextTool::new(session, cx.doc, cx.info))), // PLAN: pdf-edit-w10's `EditTextTool::new(view, doc, info)` takes no placed pages, which the review asked to hand over. diff --git a/crates/ui-egui/src/canvas/signature_drag.rs b/crates/ui-egui/src/canvas/signature_drag.rs index 3992008cf5..2626518ccf 100644 --- a/crates/ui-egui/src/canvas/signature_drag.rs +++ b/crates/ui-egui/src/canvas/signature_drag.rs @@ -344,7 +344,8 @@ impl SignatureDrag { // The box it is drawn in: a comment kept upright on a turned page (NoRotate) // isn't drawn in its /Rect, and the frame it follows is that box too. let rotation = doc.info.pages.get(page).map_or(0, |p| p.rotation); - let layer = StampLayer { renderer: alone.renderer(), from: a.shown_rect(rotation), tag: None, pixels: None, failed: None, stored: None }; + let layer = + StampLayer { renderer: alone.renderer(), from: a.shown_rect(rotation), tag: None, pixels: None, failed: None, stored: None }; self.moving = Some((key, Moving { layer, settling: false })); } _ => self.no_layer = Some(key), diff --git a/crates/ui-egui/src/control/host.rs b/crates/ui-egui/src/control/host.rs index e4730a07e0..4faea6be66 100644 --- a/crates/ui-egui/src/control/host.rs +++ b/crates/ui-egui/src/control/host.rs @@ -1,4 +1,6 @@ -use super::{Reply, Value, json}; +use serde_json::json; + +use super::{Reply, Value}; impl crate::PdfCraftApp { /// Cancel any in-progress pointer gesture in every open view. @@ -78,7 +80,8 @@ impl crate::PdfCraftApp { let cards = craft::ui::runtime::toast::cards(ctx, &craft::ui::runtime::env::WindowKey::main()); let notice = cards.last().map(|card| card.toast.message.as_str().to_string()); // PLAN: assumed `card.toast.progress: Option` is readable; L-206(2) names `Notices::progress(key)` as the reader (pdf-chrome-w19). - let progress = cards.iter().rev().find_map(|card| card.toast.progress.map(|f| json!({ "label": card.toast.message.as_str(), "fraction": f }))); + let progress = + cards.iter().rev().find_map(|card| card.toast.progress.map(|f| json!({ "label": card.toast.message.as_str(), "fraction": f }))); let dock = crate::side_panels::state(self); json!({ "side_panels": dock.clone(), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ce35e4b520..48a1d79ec9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4,7 +4,7 @@ use crate::PdfCraftApp; mod about; -mod attachment_description; +pub(crate) mod attachment_description; pub mod bookmark_styles_ui; pub(super) mod comment_props; pub(super) mod convert_colours_ui; @@ -12,20 +12,20 @@ pub(crate) mod duplicate_field; pub(super) mod hairlines_ui; pub(crate) mod host; pub(super) mod marks_ui; -mod page_dialogs; +pub(crate) mod page_dialogs; pub(crate) mod page_props; pub(super) mod pageboxes; mod pin_tools; pub(super) mod preferences; pub(super) mod printer_marks_ui; -mod properties; -mod prompts; +pub(crate) mod prompts; +pub(crate) mod properties; pub(super) mod protect; -mod shortcuts; +pub(crate) mod shortcuts; pub(crate) mod signature; pub(super) mod standards_ui; -pub(super) mod word_count_ui; pub(crate) mod summarize; +pub(super) mod word_count_ui; pub(crate) use prompts::shorten_middle; pub(crate) use properties::PropsTab; diff --git a/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs b/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs index aa54359eb3..d606e1d059 100644 --- a/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs +++ b/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs @@ -62,7 +62,8 @@ impl PdfCraftApp { let draft = &self.text_style_draft; if draft.styles.is_empty() { // A form dialog always has two buttons; a notice with only Close is an alert. - let alert = Alert::new(tl!("New bookmarks from text styles"), tl!("This document has no text to make bookmarks from.")).ok_label(tl!("Close")); + let alert = + Alert::new(tl!("New bookmarks from text styles"), tl!("This document has no text to make bookmarks from.")).ok_label(tl!("Close")); self.dialogs.open(HostedAlert::new(alert)); return; } diff --git a/crates/ui-egui/src/dialogs/comment_props.rs b/crates/ui-egui/src/dialogs/comment_props.rs index 91514dc9f8..62bcd2ac4c 100644 --- a/crates/ui-egui/src/dialogs/comment_props.rs +++ b/crates/ui-egui/src/dialogs/comment_props.rs @@ -4,16 +4,16 @@ //! is a tabbed parameter dialog the app's dialog host shows; [`edited`] maps its values back to //! the comment's properties. +use craft::host::{PickRequest, Picked}; +use craft::theme::Srgba; use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; +use craft::ui::dialog::DialogResult; use craft::ui::patterns::form_dialogs::{ DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, SharedRows, }; use craft::ui::runtime::env::UnitKind; use craft::ui::value_drag::SliderScale; -use craft::theme::Srgba; -use craft::host::{PickRequest, Picked}; -use craft::ui::dialog::DialogResult; use pdfcraft_engine::{BorderShape, CommentProps, Edit, LineEnding, NoteIcon}; use crate::PdfCraftApp; @@ -194,7 +194,8 @@ fn colour_row(key: &'static str, label: &'static str, optional: Optional, recent pick.request } Optional::Border | Optional::Fill => { - let shown = if optional == Optional::Border { border_choice(ui, current, key, &recent) } else { fill_choice(ui, current, key, &recent) }; + let shown = + if optional == Optional::Border { border_choice(ui, current, key, &recent) } else { fill_choice(ui, current, key, &recent) }; if let Some(choice) = shown.choice { set_optional(fields, key, choice); } @@ -287,15 +288,12 @@ fn comment_props_dialog<'b>( } for i in 0..o.endings.as_ref().map_or(0, Vec::len) { let options = LineEnding::ALL.into_iter().map(|l| (l.name().to_string(), ending_label(l).into())).collect(); - let label = if i == 0 { - tl!("Line ending").to_string() - } else { - crate::i18n::fmt(tl!("Line ending {n}"), &[("n", &(i + 1).to_string())]) - }; + let label = if i == 0 { tl!("Line ending").to_string() } else { crate::i18n::fmt(tl!("Line ending {n}"), &[("n", &(i + 1).to_string())]) }; rows.push(PropertyRow::field(Param::new(ending_key(i), label, ParamKind::choice(options, None)))); } let appearance = PropertiesTab::new(tl!("Appearance"), rows); - let appearance = if o.restylable { appearance } else { appearance.read_only(Some(tl!("This comment's appearance can't be changed yet.").into())) }; + let appearance = + if o.restylable { appearance } else { appearance.read_only(Some(tl!("This comment's appearance can't be changed yet.").into())) }; let modified = o.modified.as_deref().map(pdfcraft_render::pretty_date).unwrap_or_else(|| "—".into()); let general = PropertiesTab::new( diff --git a/crates/ui-egui/src/dialogs/convert_colours_ui.rs b/crates/ui-egui/src/dialogs/convert_colours_ui.rs index 36701749bd..9217e91e0f 100644 --- a/crates/ui-egui/src/dialogs/convert_colours_ui.rs +++ b/crates/ui-egui/src/dialogs/convert_colours_ui.rs @@ -7,8 +7,8 @@ use craft::pages::PageRange; use craft::pages::ui::{PageRangeChoices, PageRangeOptions}; use craft::ui::contract::Bind; use craft::ui::dialog::dialog_id; -use craft::ui::runtime::env::Label; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::Label; use crate::PdfCraftApp; diff --git a/crates/ui-egui/src/dialogs/duplicate_field.rs b/crates/ui-egui/src/dialogs/duplicate_field.rs index 8c02d7cc44..cfc236dff5 100644 --- a/crates/ui-egui/src/dialogs/duplicate_field.rs +++ b/crates/ui-egui/src/dialogs/duplicate_field.rs @@ -1,7 +1,7 @@ //! Duplicate Field: copies a form field onto the pages a range names. -use craft::pages::ui::range::{PageRangeChoices, PageRangeOptions}; use craft::pages::PageRange; +use craft::pages::ui::range::{PageRangeChoices, PageRangeOptions}; use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog}; use pdfcraft_engine::Edit; diff --git a/crates/ui-egui/src/dialogs/hairlines_ui.rs b/crates/ui-egui/src/dialogs/hairlines_ui.rs index 4bd41dcb93..524dbe2b92 100644 --- a/crates/ui-egui/src/dialogs/hairlines_ui.rs +++ b/crates/ui-egui/src/dialogs/hairlines_ui.rs @@ -8,8 +8,8 @@ use craft::pages::PageRange; use craft::pages::ui::{PageRangeChoices, PageRangeOptions}; use craft::ui::contract::Bind; use craft::ui::dialog::dialog_id; -use craft::ui::runtime::env::Label; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::Label; use crate::PdfCraftApp; use crate::pageboxes::unit_kind; @@ -89,7 +89,10 @@ impl PdfCraftApp { let dialog = HostedParamDialog::new(ctx, KEY, fields, move |fields| { let pages = PageRangeOptions::value(fields, "range").unwrap_or_default().pages(count, current, &[]); let ready = !pages.is_empty() && fields.number("width").is_some_and(|w| w > 0.0); - ParamDialog::new(KEY, tl!("Fix hairlines"), params(count, current, unit)).values(Bind::bound(fields)).ok_label(Label::from(tl!("Fix"))).ok_enabled(ready) + ParamDialog::new(KEY, tl!("Fix hairlines"), params(count, current, unit)) + .values(Bind::bound(fields)) + .ok_label(Label::from(tl!("Fix"))) + .ok_enabled(ready) }); crate::dialogs::host::open(self, dialog); } diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs index 1d981f072d..7cb1dca95e 100644 --- a/crates/ui-egui/src/dialogs/host.rs +++ b/crates/ui-egui/src/dialogs/host.rs @@ -116,4 +116,3 @@ fn param_ok(app: &mut PdfCraftApp, key: &str) -> Option { let result = app.dialogs.take_by_id::(dialog_id(key))?; result.ok().map(|r| r.fields) } - diff --git a/crates/ui-egui/src/dialogs/marks_ui.rs b/crates/ui-egui/src/dialogs/marks_ui.rs index d7e77dd866..2a193ee18b 100644 --- a/crates/ui-egui/src/dialogs/marks_ui.rs +++ b/crates/ui-egui/src/dialogs/marks_ui.rs @@ -14,10 +14,11 @@ use craft::ui::contract::Show; use craft::ui::dialog::{DialogResult, dialog_id}; use craft::ui::display::Text; use craft::ui::patterns::form_dialogs::{ - DialogFields, FieldValue, HostedParamDialog, PagerStep, PagerUnit, PanePager, Param, ParamDialog, ParamKind, ParamResult, PreviewState, SharedOverlay, + DialogFields, FieldValue, HostedParamDialog, PagerStep, PagerUnit, PanePager, Param, ParamDialog, ParamKind, ParamResult, PreviewState, + SharedOverlay, }; use craft::ui::primitives::ContentPainterCx; -use craft::ui::primitives::textures::{ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, TextureState}; +use craft::ui::primitives::textures::{TextureState, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails}; use craft::ui::runtime::env::UnitKind; use craft::ui::runtime::requests::PathKind; use craft::ui::style::DataColor; @@ -528,7 +529,11 @@ fn boxes_row() -> Param { let key = format!("hf.text.{k}"); let before = fields.text(&key).unwrap_or_default().to_owned(); let mut text = before.clone(); - let r = ui.push_id(("hf-box", k), |ui| TextField::new(tl!(BOX_NAMES[k]), craft::ui::contract::Bind::bound(&mut text)).lines(2).show(ui).response).inner; + let r = ui + .push_id(("hf-box", k), |ui| { + TextField::new(tl!(BOX_NAMES[k]), craft::ui::contract::Bind::bound(&mut text)).lines(2).show(ui).response + }) + .inner; if r.gained_focus() || r.has_focus() { fields.set("hf.focused", FieldValue::Int(k as i64)); } @@ -572,10 +577,16 @@ fn rows(kind: MarkKind, g: &Geometry) -> Vec { let m = g.units; for (k, label) in [(0, tl!("Top margin")), (1, tl!("Bottom margin")), (2, tl!("Left margin")), (3, tl!("Right margin"))] { // Up to 10 inches, whatever the unit. - rows.push(Param::number(format!("hf.margin.{k}"), label, 0.0, m.kind.step(), m.decimals).unit(m.kind).bounds(Some(0.0), Some(720.0 * m.per))); + rows.push( + Param::number(format!("hf.margin.{k}"), label, 0.0, m.kind.step(), m.decimals) + .unit(m.kind) + .bounds(Some(0.0), Some(720.0 * m.per)), + ); } rows.push(boxes_row()); - let list = |formats: &[&str]| formats.iter().enumerate().map(|(k, f)| (k.to_string(), f.trim_matches(['<', '>']).to_string())).collect::>(); + let list = |formats: &[&str]| { + formats.iter().enumerate().map(|(k, f)| (k.to_string(), f.trim_matches(['<', '>']).to_string())).collect::>() + }; rows.push(Param::new("page_format", tl!("Page number format"), choice(list(&PAGE_FORMATS), "0"))); rows.push(Param::new("date_format", tl!("Date format"), choice(list(&DATE_FORMATS), "0"))); rows.push(Param::new("hf.start", tl!("Start page number"), ParamKind::int(Some(1), Some(999_999), 1))); @@ -585,18 +596,19 @@ fn rows(kind: MarkKind, g: &Geometry) -> Vec { let source = [("text".to_string(), tl!("Text").to_string()), ("file".to_string(), tl!("File").to_string())]; rows.push(Param::new("source", tl!("Source"), ParamKind::radio(source.map(|(i, l)| (i, l.into())).to_vec(), Some("text".into())))); file_rows(&mut rows); - rows.push( - Param::new("wm.text", tl!("Text"), ParamKind::text("")).multiline(2).hint("CONFIDENTIAL").enabled_when("source", "text"), - ); + rows.push(Param::new("wm.text", tl!("Text"), ParamKind::text("")).multiline(2).hint("CONFIDENTIAL").enabled_when("source", "text")); rows.push(Param::new("wm.fit", tl!("Fit to page"), ParamKind::bool(true)).enabled_when("source", "text")); rows.push(Param::number("wm.size", tl!("Size"), 72.0, 1.0, 0).bounds(Some(6.0), Some(300.0)).enabled_when("wm.fit", false)); rows.push(Param::new("marks.wm.colour", tl!("Colour"), ParamKind::color(None))); rows.push(Param::new("wm.rotation", tl!("Rotation"), ParamKind::angle(0.0))); rows.push(percent("wm.opacity", tl!("Opacity"), 100.0)); - let place = [("behind".to_string(), tl!("Appear behind page").to_string()), ("above".to_string(), tl!("Appear on top of page").to_string())]; + let place = + [("behind".to_string(), tl!("Appear behind page").to_string()), ("above".to_string(), tl!("Appear on top of page").to_string())]; rows.push(Param::new("wm.behind", tl!("Location"), ParamKind::radio(place.map(|(i, l)| (i, l.into())).to_vec(), Some("behind".into())))); for (k, label) in [(0, tl!("Horizontal offset from centre")), (1, tl!("Vertical offset from centre"))] { - rows.push(Param::number(format!("wm.offset.{k}"), label, 0.0, 1.0, 1).unit(UnitKind::Points).bounds(Some(-MAX_OFFSET), Some(MAX_OFFSET))); + rows.push( + Param::number(format!("wm.offset.{k}"), label, 0.0, 1.0, 1).unit(UnitKind::Points).bounds(Some(-MAX_OFFSET), Some(MAX_OFFSET)), + ); } } MarkKind::Background => { @@ -897,10 +909,7 @@ impl PdfCraftApp { .previews(true) .ok_enabled(notes.ready) .extra_buttons(if kind == MarkKind::HeaderFooter { - vec![ - ("insert.page".to_string(), tl!("Insert Page Number").into()), - ("insert.date".to_string(), tl!("Insert Date").into()), - ] + vec![("insert.page".to_string(), tl!("Insert Page Number").into()), ("insert.date".to_string(), tl!("Insert Date").into())] } else { Vec::new() }) @@ -1030,8 +1039,8 @@ impl PdfCraftApp { Some(state) => state, None => thumbnail_picture(ctx, &source, target, &near), }; - let tint = (kind == MarkKind::Background && !d.use_file) - .then(|| DataColor::new(background_tint(d, d.backdrops.found(doc, target).flatten()))); + let tint = + (kind == MarkKind::Background && !d.use_file).then(|| DataColor::new(background_tint(d, d.backdrops.found(doc, target).flatten()))); let pager = PanePager { shown: target + 1, count, shown_label: None, back: back.is_some(), next: next.is_some(), unit: PagerUnit::Page }; let overlay = size.map(|size| overlay(kind, d, size)); @@ -1074,7 +1083,14 @@ impl PdfCraftApp { impl MarksPreview { /// [`Self::unmarked_picture`] when the dialog is Update. - fn unmarked_picture_for(&mut self, ctx: &egui::Context, doc: &pdfcraft_engine::Document, replace: bool, page: usize, near: &[usize]) -> Option { + fn unmarked_picture_for( + &mut self, + ctx: &egui::Context, + doc: &pdfcraft_engine::Document, + replace: bool, + page: usize, + near: &[usize], + ) -> Option { if replace { self.unmarked_picture(ctx, doc, page, near) } else { None } } } diff --git a/crates/ui-egui/src/dialogs/page_dialogs.rs b/crates/ui-egui/src/dialogs/page_dialogs.rs index bf573e8ffd..a5ad12d688 100644 --- a/crates/ui-egui/src/dialogs/page_dialogs.rs +++ b/crates/ui-egui/src/dialogs/page_dialogs.rs @@ -179,19 +179,12 @@ fn rotate_dialog<'b>(fields: &'b mut DialogFields, count: usize, current: usize) "orientation", tl!("Rotate:"), ParamKind::choice( - options(&[ - ("both", tl!("Landscape and Portrait Pages")), - ("landscape", tl!("Landscape Pages")), - ("portrait", tl!("Portrait Pages")), - ]), + options(&[("both", tl!("Landscape and Portrait Pages")), ("landscape", tl!("Landscape Pages")), ("portrait", tl!("Portrait Pages"))]), Some("both".into()), ), ), ]; - ParamDialog::new(ROTATE, tl!("Rotate Pages"), params) - .ok_enabled(valid) - .remember(SaveKey::new("pdfcraft.page_rotate")) - .values(Bind::bound(fields)) + ParamDialog::new(ROTATE, tl!("Rotate Pages"), params).ok_enabled(valid).remember(SaveKey::new("pdfcraft.page_rotate")).values(Bind::bound(fields)) } /// The label styles Number pages offers. @@ -374,11 +367,8 @@ impl PdfCraftApp { let opening = (pages.first().map_or(1, |p| p + 1), pages.last().map_or(1, |p| p + 1)); let target = self.pick_target(Some(id)); let source = Arc::new(ReplaceSource { name, bytes, src_pages, count, pages, opening, target }); - let seeds = vec![ - ("from", FieldValue::from(opening.0 as i64)), - ("to", FieldValue::from(opening.1 as i64)), - ("src_from", FieldValue::from(1i64)), - ]; + let seeds = + vec![("from", FieldValue::from(opening.0 as i64)), ("to", FieldValue::from(opening.1 as i64)), ("src_from", FieldValue::from(1i64))]; self.replace_source = Some(source.clone()); self.open_page_dialog(ctx, REPLACE, seeds, move |fields| source.dialog(fields)); } diff --git a/crates/ui-egui/src/dialogs/pageboxes.rs b/crates/ui-egui/src/dialogs/pageboxes.rs index f9386b5e66..eb832437f9 100644 --- a/crates/ui-egui/src/dialogs/pageboxes.rs +++ b/crates/ui-egui/src/dialogs/pageboxes.rs @@ -3,8 +3,8 @@ //! Choose a box (crop, trim, bleed, art, media), margins from the media box in points, inches, //! millimetres or centimetres, and the pages. A preview shows the current page's media box and the new box. -use craft::pages::{PageRange, PageScope}; use craft::pages::ui::{PageRangeChoices, PageRangeOptions}; +use craft::pages::{PageRange, PageScope}; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Show as _}; use craft::ui::dialog::dialog_id; @@ -138,7 +138,8 @@ fn params(count: usize, current: usize, media: Option<[f64; 4]>) -> Vec { rows.push(PageRangeOptions::param("range", tl!("Pages"), count, current, PageRangeChoices::CurrentFromTo)); if let Some(media) = media { let label = crate::i18n::fmt(tl!("Page {label}"), &[("label", &(current + 1).to_string())]); - let aspect = ThumbAspect::new((media[2] - media[0]).round().clamp(1.0, 65535.0) as u16, (media[3] - media[1]).round().clamp(1.0, 65535.0) as u16); + let aspect = + ThumbAspect::new((media[2] - media[0]).round().clamp(1.0, 65535.0) as u16, (media[3] - media[1]).round().clamp(1.0, 65535.0) as u16); rows.push(Param::custom("preview", "", move |ui, fields, _| { let margins = margins_of(fields); Picture::painter(label.clone(), aspect, move |cx, rect| paint_preview(cx, rect, media, margins)).show(ui) diff --git a/crates/ui-egui/src/dialogs/pin_tools.rs b/crates/ui-egui/src/dialogs/pin_tools.rs index 1a54bbf54b..045f1afec0 100644 --- a/crates/ui-egui/src/dialogs/pin_tools.rs +++ b/crates/ui-egui/src/dialogs/pin_tools.rs @@ -71,11 +71,7 @@ impl PinTools { icon: g.icon, hue: g.hue, label: tl!(g.label).to_string(), - detail: g - .sections - .first() - .map(|s| s.items.iter().take(4).map(|i| tl!(i.label)).collect::>().join(" • ")) - .unwrap_or_default(), + detail: g.sections.first().map(|s| s.items.iter().take(4).map(|i| tl!(i.label)).collect::>().join(" • ")).unwrap_or_default(), }) .collect(); PinTools { id: dialog_id("pin-tool"), rows, query: String::new(), pinned, toggled: None } @@ -103,10 +99,12 @@ impl StackDialog for PinTools { let texts = |i: &usize| { rows.get(*i).map(|r| vec![Label::from(r.label.clone()), Label::from(r.detail.clone()), Label::from(r.id)]).unwrap_or_default() }; - List::::new(tl!("Tools")).select(SelectMode::Single).sizing(Sizing::Content).max_rows(8).filter(query.trim(), texts).show_items( - ui, - &Listed(rows), - &mut |key, _| { + List::::new(tl!("Tools")) + .select(SelectMode::Single) + .sizing(Sizing::Content) + .max_rows(8) + .filter(query.trim(), texts) + .show_items(ui, &Listed(rows), &mut |key, _| { let Some(row) = rows.get(*key) else { return ListRow::new(""); }; @@ -124,8 +122,7 @@ impl StackDialog for PinTools { pressed.set(Some(at)); } }) - }, - ); + }); }); }); if let Some(at) = pressed.get() { diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index 6e505131af..1ffeb0a3e2 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -215,7 +215,9 @@ impl Texts { String::new() } else { i18n::fmt( - tl!("{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy."), + tl!( + "{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy." + ), &[("chars", &bad)], ) }; @@ -459,7 +461,8 @@ impl PreferencesModel for Prefs<'_> { let suite = self.app.suite_view(); let favorites = self.app.favorite_themes(); let system_dark = self.app.system_dark(); - let shown = AppearancePage::new(&suite, Bind::bound(&mut *self.selection)).favorites(&favorites).text_size(false).system_dark(system_dark).show(ui); + let shown = + AppearancePage::new(&suite, Bind::bound(&mut *self.selection)).favorites(&favorites).text_size(false).system_dark(system_dark).show(ui); if let Some(theme) = shown.favorite_toggled { self.app.toggle_favorite_theme(theme); } @@ -611,7 +614,9 @@ impl Prefs<'_> { let language = if Lang::from_code(&d.language).is_some() { d.language.as_str() } else { i18n::AUTO }; let mut scales = vec![Entry::new(AUTO_ID, t.auto_scale.as_str())]; scales.extend(t.scale_ids.iter().map(|(id, label)| Entry::new(id.as_str(), label.as_str()))); - let scale = d.ui_scale.map_or(AUTO_ID, |f| t.scale_ids.iter().find(|(id, _)| id.parse::().is_ok_and(|p| p == ui_scale::percent(f))).map_or(AUTO_ID, |(id, _)| id.as_str())); + let scale = d.ui_scale.map_or(AUTO_ID, |f| { + t.scale_ids.iter().find(|(id, _)| id.parse::().is_ok_and(|p| p == ui_scale::percent(f))).map_or(AUTO_ID, |(id, _)| id.as_str()) + }); let mut rows = vec![ RowSpec::new("general.language", tl!("Interface language"), RowKind::choice(language, languages)), RowSpec::new("general.scale", tl!("Interface size"), RowKind::choice(scale, scales)) @@ -622,7 +627,11 @@ impl Prefs<'_> { ]; #[cfg(not(target_arch = "wasm32"))] { - rows.push(RowSpec::new("general.reopen", tl!("Reopen the files that were open when PdfCraft last closed"), RowKind::Bool(d.reopen_last_session))); + rows.push(RowSpec::new( + "general.reopen", + tl!("Reopen the files that were open when PdfCraft last closed"), + RowKind::Bool(d.reopen_last_session), + )); rows.push(RowSpec::new( "general.restore_view", tl!("Restore the last view (page, zoom and page display) when a document is opened again"), @@ -655,13 +664,16 @@ impl Prefs<'_> { let mut modes: Vec<_> = presets.iter().map(|(id, label, _)| Entry::new(*id, *label)).collect(); modes.push(Entry::new("custom", tl!("Custom"))); let custom = mode == "custom"; - let (text, background, only_black, line_art) = d.reading_colors.params.map_or(([0, 0, 0], [255, 255, 255], false, true), |p| (p.text, p.background, p.only_black, p.line_art)); + let (text, background, only_black, line_art) = + d.reading_colors.params.map_or(([0, 0, 0], [255, 255, 255], false, true), |p| (p.text, p.background, p.only_black, p.line_art)); let reading = vec![ RowSpec::new("appearance.reading.mode", tl!("Reading colours"), RowKind::choice(mode, modes)), RowSpec::new("appearance.reading.text", tl!("Text"), RowKind::Color(rgb(text))).enabled(custom), RowSpec::new("appearance.reading.background", tl!("Page background"), RowKind::Color(rgb(background))).enabled(custom), - RowSpec::new("appearance.reading.only_black", tl!("Only change the colour of black text or line art"), RowKind::Bool(only_black)).enabled(custom), - RowSpec::new("appearance.reading.line_art", tl!("Change the colour of line art as well as text"), RowKind::Bool(line_art)).enabled(custom), + RowSpec::new("appearance.reading.only_black", tl!("Only change the colour of black text or line art"), RowKind::Bool(only_black)) + .enabled(custom), + RowSpec::new("appearance.reading.line_art", tl!("Change the colour of line art as well as text"), RowKind::Bool(line_art)) + .enabled(custom), ]; let display = vec![ RowSpec::new("appearance.edge_shadows", tl!("Show Page Edge Shadows"), RowKind::Bool(d.show_page_edge_shadows)), @@ -701,7 +713,11 @@ impl Prefs<'_> { let d = &*self.draft; let rows = vec![ RowSpec::new("comment.author", tl!("Name on new comments"), RowKind::Text(d.author.as_str())), - RowSpec::new("comment.hide_hover", tl!("Hide hover previews for highlights without comment text"), RowKind::Bool(d.hide_empty_highlight_hover)), + RowSpec::new( + "comment.hide_hover", + tl!("Hide hover previews for highlights without comment text"), + RowKind::Bool(d.hide_empty_highlight_hover), + ), ]; PageSpec::new("comment", tl!("Comment"), rows) } @@ -719,8 +735,12 @@ impl Prefs<'_> { let rows = vec![ RowSpec::new("fill.flatten", tl!("Flatten Fill & Sign when saving"), RowKind::Bool(d.flatten_fill_sign_on_save)) .help(tl!("Text, marks and signatures become part of the page. Other comments stay editable.")), - RowSpec::new("fill.ask_lock", tl!("Otherwise, ask on the first save after a signature is placed"), RowKind::Bool(d.ask_to_lock_signatures)) - .enabled(!d.flatten_fill_sign_on_save), + RowSpec::new( + "fill.ask_lock", + tl!("Otherwise, ask on the first save after a signature is placed"), + RowKind::Bool(d.ask_to_lock_signatures), + ) + .enabled(!d.flatten_fill_sign_on_save), RowSpec::new("fill.date_preset", tl!("Fill & Sign dates"), RowKind::choice(preset, presets)).keywords(tl!("Date format")), RowSpec::new("fill.date_pattern", tl!("Pattern"), RowKind::Custom).keywords(tl!("Date format")).help(t.date_help.as_str()), RowSpec::new("fill.date_language", tl!("Language"), RowKind::choice(language, languages)).keywords(tl!("Date format")), diff --git a/crates/ui-egui/src/dialogs/printer_marks_ui.rs b/crates/ui-egui/src/dialogs/printer_marks_ui.rs index 5f7408c90b..234d0d45a7 100644 --- a/crates/ui-egui/src/dialogs/printer_marks_ui.rs +++ b/crates/ui-egui/src/dialogs/printer_marks_ui.rs @@ -7,8 +7,8 @@ use craft::pages::ui::{PageRangeChoices, PageRangeOptions}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _}; use craft::ui::dialog::dialog_id; -use craft::ui::runtime::env::Label; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::Label; use pdfcraft_engine::{Edit, PrinterMarks}; use crate::PdfCraftApp; diff --git a/crates/ui-egui/src/dialogs/prompts.rs b/crates/ui-egui/src/dialogs/prompts.rs index 023358e1bc..3d40bdeb43 100644 --- a/crates/ui-egui/src/dialogs/prompts.rs +++ b/crates/ui-egui/src/dialogs/prompts.rs @@ -92,10 +92,8 @@ impl PdfCraftApp { if let Some(host) = pdfcraft_engine::links::display_host(&pending.url) { prompt = prompt.paragraph(host.ascii.clone()); if host.mixed_scripts { - prompt = prompt.tone( - Tone::Bad, - tl!("This web address mixes letters from different alphabets, a common way to imitate another site's name."), - ); + prompt = prompt + .tone(Tone::Bad, tl!("This web address mixes letters from different alphabets, a common way to imitate another site's name.")); } else if host.international { prompt = prompt.tone(Tone::Warn, tl!("This web address uses letters from another alphabet, which can look like familiar ones.")); } diff --git a/crates/ui-egui/src/dialogs/properties.rs b/crates/ui-egui/src/dialogs/properties.rs index a32d13106c..9408f50439 100644 --- a/crates/ui-egui/src/dialogs/properties.rs +++ b/crates/ui-egui/src/dialogs/properties.rs @@ -443,8 +443,11 @@ fn security_rows(doc: &Document) -> Vec { } else { tl!("User password") }; - let mut rows = - vec![value("Security method", tl!("Password security").to_string()), value("Encryption", sec.method.clone()), value("Opened with", opened.to_string())]; + let mut rows = vec![ + value("Security method", tl!("Password security").to_string()), + value("Encryption", sec.method.clone()), + value("Opened with", opened.to_string()), + ]; // A restricted document asks for its permissions password first. if doc.allows_security_change() || doc.can_unlock() { let mut actions = Vec::new(); diff --git a/crates/ui-egui/src/dialogs/protect.rs b/crates/ui-egui/src/dialogs/protect.rs index 39ffd9c17f..2d7adc31a4 100644 --- a/crates/ui-egui/src/dialogs/protect.rs +++ b/crates/ui-egui/src/dialogs/protect.rs @@ -181,9 +181,7 @@ fn advanced_rows(ui: &mut Ui, d: &mut ProtectDraft) { } }); Checkbox::new(Bind::bound(&mut p.copy)).label(text("Enable copying of text, images, and other content")).show(ui); - Checkbox::new(Bind::bound(&mut p.accessibility)) - .label(text("Enable text access for screen reader devices for the visually impaired")) - .show(ui); + Checkbox::new(Bind::bound(&mut p.accessibility)).label(text("Enable text access for screen reader devices for the visually impaired")).show(ui); } impl StackDialog for ProtectDialog { diff --git a/crates/ui-egui/src/dialogs/standards_ui.rs b/crates/ui-egui/src/dialogs/standards_ui.rs index 2a450c2843..ea153a3f4e 100644 --- a/crates/ui-egui/src/dialogs/standards_ui.rs +++ b/crates/ui-egui/src/dialogs/standards_ui.rs @@ -85,12 +85,7 @@ impl PdfCraftApp { /// Opens the PDF/A dialog on the remembered level, with nothing verified yet. pub(crate) fn open_pdfa(&mut self) { - let dialog = PdfaDialog { - id: dialog_id("pdfa"), - form: LevelForm { level: self.pdfa.level }, - shown: self.pdfa_declared(), - action: None, - }; + let dialog = PdfaDialog { id: dialog_id("pdfa"), form: LevelForm { level: self.pdfa.level }, shown: self.pdfa_declared(), action: None }; // PLAN: assumed `fn open(app: &mut PdfCraftApp, dialog: D)` (pdf-hub-w2) crate::dialogs::host::open(self, dialog); } @@ -191,9 +186,8 @@ impl StackDialog for PdfaDialog { Some(v) => { let findings: Vec = v.iter().enumerate().map(|(n, i)| finding(n as u64, i)).collect(); FindingsSummary::new(&findings).show(ui); - FindingsList::new(tl!("PDF/A problems").to_string()).show_items(ui, &Findings::new(&findings), &mut |key, icx| { - findings[*key as usize].row(&icx.words::()) - }); + FindingsList::new(tl!("PDF/A problems").to_string()) + .show_items(ui, &Findings::new(&findings), &mut |key, icx| findings[*key as usize].row(&icx.words::())); } } true diff --git a/crates/ui-egui/src/dialogs/summarize.rs b/crates/ui-egui/src/dialogs/summarize.rs index f634b94cf0..042b69191c 100644 --- a/crates/ui-egui/src/dialogs/summarize.rs +++ b/crates/ui-egui/src/dialogs/summarize.rs @@ -18,10 +18,8 @@ const SORT: &str = "sort"; fn build(fields: &mut DialogFields) -> ParamDialog<'_> { let layout = ParamKind::radio(vec![(COMMENTS_ONLY.to_string(), tl!("Comments only").into())], Some(COMMENTS_ONLY.to_string())); let sorts = SummarySort::ALL.into_iter().map(|s| (s.name().to_string(), tl!(s.name()).into())).collect(); - let params = vec![ - Param::new(LAYOUT, tl!("Choose a layout:"), layout), - Param::new(SORT, tl!("Sort comments by:"), ParamKind::choice(sorts, None)), - ]; + let params = + vec![Param::new(LAYOUT, tl!("Choose a layout:"), layout), Param::new(SORT, tl!("Sort comments by:"), ParamKind::choice(sorts, None))]; ParamDialog::command(KEY, tl!("Summarize Options"), params).values(Bind::bound(fields)).ok_label(tl!("Create PDF Comment Summary")) } diff --git a/crates/ui-egui/src/dialogs/word_count_ui.rs b/crates/ui-egui/src/dialogs/word_count_ui.rs index ed2f9d0722..16ce7439bc 100644 --- a/crates/ui-egui/src/dialogs/word_count_ui.rs +++ b/crates/ui-egui/src/dialogs/word_count_ui.rs @@ -9,13 +9,13 @@ use std::sync::{ use craft::host::Wake; use craft::host::queue::{Cancel, JobQueue, Priority, QueueOptions}; use craft::theme::variant::Tone; +use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::display::{Shade, Spinner, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::notices::{Notice, NoticeLayout}; -use craft::ui::choice::Checkbox; use craft::ui::patterns::form_dialogs::FormDialog; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::style::TypeRole; @@ -62,16 +62,7 @@ pub(crate) struct WordCountDialog { impl WordCountDialog { fn new(options: WordCountOptions, queue: JobQueue>, wake: Wake) -> Self { - WordCountDialog { - id: dialog_id("word-count"), - options, - key: None, - queue, - serial: 0, - wake, - done: Arc::new(AtomicUsize::new(0)), - shown: None, - } + WordCountDialog { id: dialog_id("word-count"), options, key: None, queue, serial: 0, wake, done: Arc::new(AtomicUsize::new(0)), shown: None } } /// Whether the count for the current key has finished (with a report or an error). @@ -125,49 +116,49 @@ impl StackDialog for WordCountDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let WordCountDialog { options, shown, done, .. } = self; let close = FooterButton::new(tl!("Close").to_string(), DialogRole::Cancel); - let out = FormDialog::new(tl!("Word count").to_string(), Bind::bound(options)) - .shaped(|d| d.buttons([close])) - .show(ui, |ui, _, o| { - Checkbox::new(Bind::bound(&mut o.current_page)).label(tl!("Current page only").to_string()).show(ui); - Checkbox::new(Bind::bound(&mut o.options.exclude_tables)).label(tl!("Exclude tagged tables").to_string()).show(ui); - Checkbox::new(Bind::bound(&mut o.options.exclude_code)).label(tl!("Exclude tagged code blocks").to_string()).show(ui); - Checkbox::new(Bind::bound(&mut o.options.exclude_images)).label(tl!("Exclude image/OCR text").to_string()).show(ui); - Text::new(tl!("Exclusions use PDF tags. Untagged tables and code remain included. Image exclusion also removes invisible text.").to_string()) - .role(TypeRole::Caption) - .shade(Shade::Muted) - .show(ui); - match shown { - Some(Ok(report)) => { - for (label, value) in [ - (tl!("Words"), report.total.words), - (tl!("Characters"), report.total.characters), - (tl!("Characters without spaces"), report.total.characters_without_spaces), - (tl!("Pages counted"), report.pages.len()), - ] { - Field::new(label.to_string()).show(ui, |ui, _| { - Text::new(value.to_string()).show(ui); - }); - } - if report.pages_without_text > 0 { - Text::new(tl!("Some pages contain no countable text. Scanned images need OCR first.").to_string()).show(ui); - } - if report.unclassified_structure { - Text::new(tl!("Some content could not be classified safely and was kept in the count.").to_string()).show(ui); - } - } - Some(Err(error)) => { - Notice::new(Tone::Bad, error.clone()).layout(NoticeLayout::Inline).show(ui); - } - None => { - Row::new().show(ui, |ui, _| { - Spinner::new().show(ui); - let n = done.load(Ordering::Relaxed); - Text::new(crate::i18n::fmt(tl!("Counting words… {n} pages read"), &[("n", &n.to_string())])).show(ui); + let out = FormDialog::new(tl!("Word count").to_string(), Bind::bound(options)).shaped(|d| d.buttons([close])).show(ui, |ui, _, o| { + Checkbox::new(Bind::bound(&mut o.current_page)).label(tl!("Current page only").to_string()).show(ui); + Checkbox::new(Bind::bound(&mut o.options.exclude_tables)).label(tl!("Exclude tagged tables").to_string()).show(ui); + Checkbox::new(Bind::bound(&mut o.options.exclude_code)).label(tl!("Exclude tagged code blocks").to_string()).show(ui); + Checkbox::new(Bind::bound(&mut o.options.exclude_images)).label(tl!("Exclude image/OCR text").to_string()).show(ui); + Text::new( + tl!("Exclusions use PDF tags. Untagged tables and code remain included. Image exclusion also removes invisible text.").to_string(), + ) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); + match shown { + Some(Ok(report)) => { + for (label, value) in [ + (tl!("Words"), report.total.words), + (tl!("Characters"), report.total.characters), + (tl!("Characters without spaces"), report.total.characters_without_spaces), + (tl!("Pages counted"), report.pages.len()), + ] { + Field::new(label.to_string()).show(ui, |ui, _| { + Text::new(value.to_string()).show(ui); }); } + if report.pages_without_text > 0 { + Text::new(tl!("Some pages contain no countable text. Scanned images need OCR first.").to_string()).show(ui); + } + if report.unclassified_structure { + Text::new(tl!("Some content could not be classified safely and was kept in the count.").to_string()).show(ui); + } } - true - }); + Some(Err(error)) => { + Notice::new(Tone::Bad, error.clone()).layout(NoticeLayout::Inline).show(ui); + } + None => { + Row::new().show(ui, |ui, _| { + Spinner::new().show(ui); + let n = done.load(Ordering::Relaxed); + Text::new(crate::i18n::fmt(tl!("Counting words… {n} pages read"), &[("n", &n.to_string())])).show(ui); + }); + } + } + true + }); out.closed.map(|_| DialogResult::Cancel) } } @@ -177,7 +168,8 @@ impl PdfCraftApp { pub(crate) fn open_word_count(&mut self) { // PLAN: assumed `self.wake: Wake` (pdf-hub-w1, `AppServices::wake`) let wake = self.wake.clone(); - let queue = JobQueue::new(self.host.jobs_shared().clone(), wake.clone(), QueueOptions { lanes: 1, name: "word-count", ..QueueOptions::default() }); + let queue = + JobQueue::new(self.host.jobs_shared().clone(), wake.clone(), QueueOptions { lanes: 1, name: "word-count", ..QueueOptions::default() }); let dialog = WordCountDialog::new(self.word_count_options, queue, wake); crate::dialogs::host::open(self, dialog); } diff --git a/crates/ui-egui/src/editing/close.rs b/crates/ui-egui/src/editing/close.rs index f022002971..6907d9448f 100644 --- a/crates/ui-egui/src/editing/close.rs +++ b/crates/ui-egui/src/editing/close.rs @@ -5,7 +5,7 @@ use craft::ui::shell::embed::CloseDecision; use pdfcraft_engine::DocId; use super::PdfCraftApp; -use super::save::SaveTarget; +use super::SaveTarget; /// Closes the root window once the app allows it; the close reaches [`PdfCraftApp::close_requested`]. fn close_root_window(ctx: &egui::Context) { @@ -315,7 +315,6 @@ impl PdfCraftApp { self.run_guard_step(step); } - /// Closes `doc`'s tab without saving (a revert keeps the tab and goes back to the saved file). /// Whether an OCR review held it. fn discard_for_guard(&mut self, doc: DocId) -> bool { @@ -370,9 +369,8 @@ mod tests { let info = AppInfo { id: "pdfcraft", name: "PdfCraft", version: env!("CARGO_PKG_VERSION") }; let host = Host::builder(info).jobs(Arc::new(ManualJobs::new())).files(Arc::new(ScriptedFiles::new())).build(); let wake = craft::host::Wake::none(); - // PLAN: assumed `crate::{Clipboard, FileIntake}` and `Clipboard::new(SystemClipboard::new())` as in `AppServices::system` (pdf-hub-w1) - let clipboard = crate::Clipboard::new(craft::platform::clipboard::SystemClipboard::new()); - let (intake, _) = crate::FileIntake::new(wake.clone()); + let clipboard = craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::SystemClipboard::new()); + let (intake, _) = craft::platform::open::FileIntake::new(wake.clone()); let watch = craft::platform::watch::FileWatch::new(wake.clone()); PdfCraftApp::with_host(Arc::new(host), crate::AppServices::new(wake, clipboard, None, None, intake, watch)) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 254a5f2b0a..02ae951a63 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -104,7 +104,6 @@ pub(crate) mod icons; pub(crate) mod notices; pub use app::settings; -#[cfg(not(target_arch = "wasm32"))] pub(crate) use app::same_file; pub(crate) use app::{MAX_AUTHOR_CHARS, copy_refused, date_text_for_pdf, print_refused}; use canvas::crop; @@ -113,14 +112,12 @@ use canvas::page_parts; pub use canvas::scroll_speed; use canvas::signature_drag; use canvas::zoom_snap; -use dialogs::appearance; pub use dialogs::bookmark_styles_ui; use dialogs::comment_props; use dialogs::convert_colours_ui; use dialogs::hairlines_ui; use dialogs::marks_ui; use dialogs::pageboxes; -use dialogs::palette; use dialogs::printer_marks_ui; use dialogs::protect; use dialogs::standards_ui; @@ -139,7 +136,6 @@ pub use persist::last_view; pub use persist::paper; use persist::recovery; pub use persist::units; -use platform::file_filter; #[cfg(target_os = "macos")] use platform::macos_association; #[cfg(not(target_arch = "wasm32"))] @@ -179,6 +175,7 @@ use workflows::compare_ui; use workflows::create_ui; use workflows::export_ui; use workflows::files; +pub(crate) use workflows::job_count::JobCount; use workflows::js_dialogs; use workflows::js_ui; #[cfg(target_arch = "wasm32")] @@ -213,6 +210,13 @@ struct PendingOpen { ready: Option, } +/// A named destination being looked up in a document. +#[cfg(not(target_arch = "wasm32"))] +struct PendingDestination { + doc: DocId, + name: String, +} + pub struct PdfCraftApp { /// The app's services: jobs, files, settings sections, commands. Every queue is built from it. pub(crate) host: std::sync::Arc, @@ -223,7 +227,6 @@ pub struct PdfCraftApp { /// The native file panels the host's file service asks through; pumped every pass. #[cfg(not(target_arch = "wasm32"))] file_panels: Option, - // PLAN: assumed settings::Store, the opened settings store, and PdfCraftApp::{apply_settings, attach_settings, save_settings} (pdf-shell-w9). /// The settings store the preferences are read from and written to. pub(crate) settings: Option, /// The dialogs, prompts and notices the app has open, and their results. @@ -236,11 +239,10 @@ pub struct PdfCraftApp { pub(crate) shortcuts: Option, /// Split view (`panes`); which pane shows each tab is its view's. pub panes: panes::Panes, - // PLAN: assumed side_panels::{PanelId, RailSide, default_workspace, right_of} (pdf-chrome-w1, L-136). /// Where the side panels are docked, their sizes and which are open. pub dock: craft::behavior::dock::Workspace, /// The side the rail of panel buttons sits on. - pub rail_side: side_panels::RailSide, + pub rail_side: craft::behavior::DockSide, pub session: Session, /// The interface language signature status captions were last drawn in. pub(crate) status_captions_lang: Option, @@ -292,7 +294,7 @@ pub struct PdfCraftApp { /// Comment author, per-tool colours and widths, pin. pub comment_prefs: comments::CommentPrefs, /// The colours picked last in the comment tools' colour pickers. - pub(crate) recent_colours: crate::colour_picker::RecentColours, + pub(crate) recent_colours: comments::RecentColours, pub(crate) hotbar: hotbar::Hotbar, /// Preferences ▸ Appearance: light, dark, or as the system says. pub theme_preference: craft::theme::ModeChoice, @@ -425,7 +427,10 @@ pub struct PdfCraftApp { /// Named destinations being looked up off the UI thread: reading a large document's name tree /// takes a noticeable moment. #[cfg(not(target_arch = "wasm32"))] - pub(crate) named_destinations: Queue<(DocId, String), Option<(usize, pdfcraft_render::DestView)>>, + pub(crate) named_destinations: Queue>, + /// The documents a lookup in `named_destinations` is for, and the name asked. + #[cfg(not(target_arch = "wasm32"))] + pending_destinations: Vec, #[cfg(not(target_arch = "wasm32"))] next_open_token: u64, /// Explicit CLI layout waits for flagged launch opens, never targeting restored tabs. @@ -433,11 +438,10 @@ pub struct PdfCraftApp { launch_layout: Option, #[cfg(not(target_arch = "wasm32"))] launch_display_target: Option, - // PLAN: assumed HashMap and editing::save::{SaveFlow, PendingSave} (pdf-shell-w14). /// The file picks asked of the host's file service, by ticket, with what each is for. pub(crate) picks: std::collections::HashMap, /// Where a save that asks first (Save As, a replace question) stands. - pub(crate) save_flow: editing::save::SaveFlow, + pub(crate) save_flow: craft::dialogs::save::SaveFlow, /// A save waiting for the answer to a question it asked. pub(crate) pending_save: Option, /// Folders pinned to Home, and what they held when last listed. @@ -489,8 +493,7 @@ pub struct PdfCraftApp { /// Scan & OCR: the Recognize Text choices and the running job. pub ocr_draft: ocr_ui::OcrDraft, pub ocr_run: Option, - // PLAN: assumed workflows::JobCount, a batch's shared done/total count (pdf-workflows-w14, pdf-print-ocr-w6). - pub ocr_batch: Option>, + pub ocr_batch: Option>, /// Pages being recognized, by document. pub(crate) ocr_runs: Queue, String>>, /// Recognize Text in Multiple Files: the batch's summary. @@ -518,8 +521,7 @@ pub struct PdfCraftApp { panic_next: Option, /// Action Wizard: the user's actions and the running action. pub custom_actions: Vec, - pub action_run: Option>, - // PLAN: assumed the queue aliases actions_ui::ActionJobs, export_ui::ExportJobs, optimize_ui::{OptimizeJobs, SpaceAuditJobs} (pdf-workflows-w14). + pub action_run: Option>, pub(crate) action_jobs: actions_ui::ActionJobs, /// Standards ▸ PDF/A: the level. pub pdfa: standards_ui::PdfaState, @@ -553,7 +555,7 @@ pub struct PdfCraftApp { /// The Combine files tab: whether it is open, shown, its selection and undo history. pub combine_tab: combine_ui::CombineTab, /// The Combine files table's column order and widths (kept in the settings). - pub combine_columns: craft::ui::contract::collection::ColumnLayout, + pub combine_columns: craft::ui::contract::ColumnLayout, /// Combine files as thumbnails or as the table (kept in the settings). pub combine_view: combine_ui::CombineView, /// How large the Combine grid draws its cards (1.0 = the usual; kept in the settings). @@ -573,7 +575,7 @@ pub struct PdfCraftApp { /// Scan & OCR ▸ Enhance scanned file: the dialog's choices and the running clean-up. pub scan_clean_draft: scan_clean_ui::ScanCleanDraft, pub scan_clean_run: Option, - pub(crate) scan_cleans: Queue>, + pub(crate) scan_cleans: Queue>, /// Pages copied or cut in Organize Pages, ready to paste (into any document). pub page_clipboard: Option, /// Copied comments (XFDF), to paste into this or another document (M14). @@ -644,7 +646,7 @@ pub struct PdfCraftApp { /// Export dialog settings. pub export_draft: export_ui::ExportDraft, /// A running export's progress. - export_status: Option>, + export_status: Option>, pub(crate) export_jobs: export_ui::ExportJobs, /// The saved Fill & Sign signature and initials (drawn, typed or an image). pub signature: Option, @@ -669,14 +671,13 @@ pub struct PdfCraftApp { pub text_style: pdfcraft_engine::AddedText, /// Edit a PDF shows its More tools. pub(crate) edit_more: bool, - // PLAN: assumed files::{ReplaceSource, InstalledFonts, FontFile} (pdf-workflows-w13). /// The file Replace pages takes its pages from, once picked. - pub(crate) replace_source: Option>, + pub(crate) replace_source: Option>, /// The fonts installed on this machine, for Add text and font embedding (desktop). #[cfg(not(target_arch = "wasm32"))] pub(crate) document_fonts: Option, /// The installed fonts being listed off the UI thread. - pub(crate) font_scan: Queue<(), Vec>, + pub(crate) font_scan: Queue<(), Vec>, /// The last web link the app asked the system to open (tests and automation). pub last_opened_url: Option, /// The home screen's community card was closed; it comes back next launch (not remembered). diff --git a/crates/ui-egui/src/panels/side_panels.rs b/crates/ui-egui/src/panels/side_panels.rs index f58ef2dcb4..59dcbba88f 100644 --- a/crates/ui-egui/src/panels/side_panels.rs +++ b/crates/ui-egui/src/panels/side_panels.rs @@ -5,8 +5,8 @@ //! by earlier versions (`side_panels`, `docking`) are read once by [`migrate`]. use craft::automation::dock as dock_rpc; -use craft::behavior::{Axis, DockSide}; use craft::behavior::dock::{Action, Column, DockEdge, DockPlacement, Group, Layout, Location, Node, Permissions, SplitSize, Target, Workspace}; +use craft::behavior::{Axis, DockSide}; use craft::keymap::CommandRef; use craft::ui::contract::{Bind, BodyCx}; use craft::ui::docking::{DockConfig, DockPanels, GroupAt, HidePanels, PanelSpec}; @@ -113,7 +113,6 @@ impl PanelId { Self::Tools | Self::Toolbar | Self::Document => return None, }) } - } impl From for PanelId { @@ -406,6 +405,11 @@ fn show_panel(app: &mut PdfCraftApp, panel: PanelId, visible: bool) -> Result<() app.dock.set_visible(panel, visible, fallback, false, permissions).map_err(|_| refused()) } +/// The side panel `workspace` has open, `None` when every side panel is closed. +pub(crate) fn right_of(workspace: &Workspace) -> Option { + SIDE.iter().find(|panel| workspace.layout.contains(panel)).and_then(|panel| panel.side()) +} + /// Opens or closes `panel`, telling the user when the dock refuses. pub(crate) fn set_panel_visible(app: &mut PdfCraftApp, panel: PanelId, visible: bool) { if let Err(error) = show_panel(app, panel, visible) { @@ -458,7 +462,9 @@ pub fn command(app: &mut PdfCraftApp, reset: bool, params: &Value) -> Result None, - Some(Value::String(side)) if side == "toggle" => Some(if rail_edge(app.rail_side) == DockEdge::Start { DockSide::End } else { DockSide::Start }), + Some(Value::String(side)) if side == "toggle" => { + Some(if rail_edge(app.rail_side) == DockEdge::Start { DockSide::End } else { DockSide::Start }) + } Some(value) => { let edge = edge_param(value.as_str().unwrap_or_default(), "rail_side")?; Some(if edge == DockEdge::Start { DockSide::Start } else { DockSide::End }) @@ -717,7 +723,11 @@ mod tests { "docked default", with_side( workspace( - split(json!({"FixedFirst": 300.0}), tabs(&["tools"]), split(json!({"FixedSecond": 400.0}), tabs(&["canvas"]), tabs(&["inspector"]))), + split( + json!({"FixedFirst": 300.0}), + tabs(&["tools"]), + split(json!({"FixedSecond": 400.0}), tabs(&["canvas"]), tabs(&["inspector"])), + ), json!([]), json!([]), ), @@ -730,7 +740,11 @@ mod tests { ( "tools on the right", workspace( - split(json!({"FixedSecond": 330.0}), tabs(&["canvas"]), split(json!({"FixedSecond": 290.0}), tabs(&["inspector"]), tabs(&["tools"]))), + split( + json!({"FixedSecond": 330.0}), + tabs(&["canvas"]), + split(json!({"FixedSecond": 290.0}), tabs(&["inspector"]), tabs(&["tools"])), + ), json!([]), json!([]), ), @@ -751,7 +765,10 @@ mod tests { ), ( "tools tabbed with the inspector", - with_side(workspace(split(json!({"FixedSecond": 350.0}), tabs(&["canvas"]), tabs(&["inspector", "tools"])), json!([]), json!([])), "Pages"), + with_side( + workspace(split(json!({"FixedSecond": 350.0}), tabs(&["canvas"]), tabs(&["inspector", "tools"])), json!([]), json!([])), + "Pages", + ), true, DockEdge::Start, true, @@ -759,7 +776,11 @@ mod tests { ( "hidden inspector and tools", with_side( - workspace(tabs(&["canvas"]), json!([]), json!([["inspector", hidden_place("Right", 380.0)], ["tools", hidden_place("Right", 300.0)]])), + workspace( + tabs(&["canvas"]), + json!([]), + json!([["inspector", hidden_place("Right", 380.0)], ["tools", hidden_place("Right", 300.0)]]), + ), "Bookmarks", ), false, @@ -768,7 +789,10 @@ mod tests { ), ( "version 1 value", - with_side(json!({"side_panels": {"version": 1, "tools_side": "right", "tools_open": true, "tools_width": 300.0, "side_width": 400.0}}), "Pages"), + with_side( + json!({"side_panels": {"version": 1, "tools_side": "right", "tools_open": true, "tools_width": 300.0, "side_width": 400.0}}), + "Pages", + ), true, DockEdge::End, true, diff --git a/crates/ui-egui/src/persist/recovery.rs b/crates/ui-egui/src/persist/recovery.rs index ba32402c9e..cc1fd975f9 100644 --- a/crates/ui-egui/src/persist/recovery.rs +++ b/crates/ui-egui/src/persist/recovery.rs @@ -356,9 +356,8 @@ mod idle_tests { let info = AppInfo { id: "pdfcraft", name: "PdfCraft", version: env!("CARGO_PKG_VERSION") }; let host = Host::builder(info).jobs(jobs.clone()).files(files.clone()).build(); let wake = craft::host::Wake::none(); - // PLAN: assumed `crate::{Clipboard, FileIntake}` and `Clipboard::new(SystemClipboard::new())` as in `AppServices::system` (pdf-hub-w1) - let clipboard = crate::Clipboard::new(craft::platform::clipboard::SystemClipboard::new()); - let (intake, _) = crate::FileIntake::new(wake.clone()); + let clipboard = craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::SystemClipboard::new()); + let (intake, _) = craft::platform::open::FileIntake::new(wake.clone()); let watch = craft::platform::watch::FileWatch::new(wake.clone()); let services = crate::AppServices::new(wake, clipboard, recovery.map(Path::to_path_buf), None, intake, watch); let mut app = PdfCraftApp::with_host(Arc::new(host), services); @@ -415,7 +414,6 @@ mod idle_tests { let (tx, rx) = std::sync::mpsc::channel(); let path = entry.path.clone(); std::thread::spawn(move || { - // PLAN: assumed `open_worker::read_recovery_copy(&Path) -> io::Result>`, the read `prepare` makes of `Input::Recovery` (pdf-shell-w13) let _ = tx.send(crate::open_worker::read_recovery_copy(&path).map(|b| b.len())); }); let read = rx.recv_timeout(Duration::from_secs(5)).expect("the read returned instead of waiting on the FIFO"); @@ -499,6 +497,7 @@ mod sidecar_tests { use crate::SaveTarget; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; + use std::time::Duration; /// #3923: a sidecar names a file the user can write (here, one that is not the document's). /// After Recover, Save asks where instead of writing that file; the file the user picks is diff --git a/crates/ui-egui/src/platform/open_worker.rs b/crates/ui-egui/src/platform/open_worker.rs index 6ffe5ac465..9d0ee77d7a 100644 --- a/crates/ui-egui/src/platform/open_worker.rs +++ b/crates/ui-egui/src/platform/open_worker.rs @@ -52,6 +52,15 @@ pub(crate) fn run(job: Job, cancel: &Cancel) -> ResultKind { pdfcraft_engine::guard(|| prepare(job, cancel)).unwrap_or_else(|_| ResultKind::Failed("opening failed unexpectedly in the background".into())) } +/// The bytes of a recovery copy. Only a regular file is read: a FIFO planted in the recovery +/// folder would block the worker forever, and a folder has nothing to read. +pub(crate) fn read_recovery_copy(path: &std::path::Path) -> std::io::Result> { + if !std::fs::symlink_metadata(path)?.file_type().is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "a recovery copy is a regular file")); + } + std::fs::read(path) +} + fn prepare(job: Job, cancel: &Cancel) -> ResultKind { let bytes = match &job.input { Input::Path(path) => match std::fs::read(path) { @@ -62,7 +71,7 @@ fn prepare(job: Job, cancel: &Cancel) -> ResultKind { Ok(bytes) => Arc::new(bytes), Err(error) => return ResultKind::RemoteFailed(error.to_string()), }, - Input::Recovery(path) => match std::fs::read(path) { + Input::Recovery(path) => match read_recovery_copy(path) { Ok(bytes) => Arc::new(bytes), Err(error) => return ResultKind::RecoveryFailed(error.to_string()), }, diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index b607637a60..09d416ef43 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -16,8 +16,8 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; -use crate::canvas::PageLayout; use crate::PdfCraftApp; +use crate::canvas::PageDisplay; fn fixture(pages: usize) -> Vec { let mut objects = vec!["<< /Type /Catalog /Pages 2 0 R >>".to_string()]; @@ -98,7 +98,8 @@ impl Rig { let (host_jobs, host_files) = (jobs.clone(), files.clone()); let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(move |_cc| { let (rx, slot) = parts.lock().expect("setup slot").take().expect("built once"); - let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(host_jobs.clone()).files(host_files.clone()).build(); + let host = + Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(host_jobs.clone()).files(host_files.clone()).build(); let mut app = PdfCraftApp::with_host(Arc::new(host)); *slot.lock().expect("sender slot") = Some(app.intake.sender()); app.set_option("language", "en").expect("language preference"); @@ -178,9 +179,9 @@ impl Rig { self.h.run_steps(2); } - fn layout_of(&self, name: &str) -> Option<(PageLayout, bool)> { + fn layout_of(&self, name: &str) -> Option<(PageDisplay, bool)> { let app = self.h.state(); - app.views.iter().find(|v| app.session.get(v.id).is_some_and(|d| d.name == name)).map(|v| (v.layout, v.continuous)) + app.views.iter().find(|v| app.session.get(v.id).is_some_and(|d| d.name == name)).map(|v| (v.view.display, v.view.continuous)) } } @@ -468,7 +469,9 @@ fn tool_picker_keeps_picked_recipient_when_other_open_is_ready() { /// A tool chosen for a file opens with it whether the file is a PDF, text, or locked. #[test] fn inline_tool_open_keeps_its_command_for_pdf_conversion_and_password_retry() { - for (extension, bytes, locked) in [("pdf", fixture(2), false), ("txt", b"Synthetic text for the tool".to_vec(), false), ("pdf", encrypted_fixture(), true)] { + for (extension, bytes, locked) in + [("pdf", fixture(2), false), ("txt", b"Synthetic text for the tool".to_vec(), false), ("pdf", encrypted_fixture(), true)] + { let mut rig = Rig::empty(); let file = TempFile::new("table", extension, &bytes); rig.choose("export.text", &file); @@ -530,23 +533,23 @@ fn launch_layout_waits_for_cli_opens_and_preserves_restored_tabs() { if layout_first { rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); } - rig.h.state_mut().open_path_with_display(&a.path(), PageLayout::Single, false); - rig.h.state_mut().open_path_with_display(&b.path(), PageLayout::Single, false); + rig.h.state_mut().open_path_with_display(&a.path(), PageDisplay::Single, false); + rig.h.state_mut().open_path_with_display(&b.path(), PageDisplay::Single, false); if !layout_first { rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); } rig.release(); assert_eq!(rig.layout_of("existing.pdf"), Some(restored), "the restored tab is not targeted"); - assert_ne!(rig.layout_of(&b.name()), Some((PageLayout::TwoUp, false)), "the layout waits for the last flagged open"); + assert_ne!(rig.layout_of(&b.name()), Some((PageDisplay::TwoUp, false)), "the layout waits for the last flagged open"); rig.release(); - assert_eq!(rig.layout_of(&b.name()), Some((PageLayout::TwoUp, false)), "the last settled open gets the layout"); - assert_eq!(rig.layout_of(&a.name()), Some((PageLayout::Single, false))); + assert_eq!(rig.layout_of(&b.name()), Some((PageDisplay::TwoUp, false)), "the last settled open gets the layout"); + assert_eq!(rig.layout_of(&a.name()), Some((PageDisplay::Single, false))); assert_eq!(rig.layout_of("existing.pdf"), Some(restored)); // A later open does not inherit it. let c = TempFile::new("layout-c", "pdf", &fixture(1)); rig.h.state_mut().open_path(&c.path()); rig.release(); - assert_ne!(rig.layout_of(&c.name()), Some((PageLayout::TwoUp, false))); + assert_ne!(rig.layout_of(&c.name()), Some((PageDisplay::TwoUp, false))); } } @@ -557,13 +560,13 @@ fn launch_layout_failed_or_cancelled_opens_do_not_target_existing_documents() { rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); // A read that fails. let missing = std::env::temp_dir().join(format!("pdfcraft-missing-{}.pdf", std::process::id())); - rig.h.state_mut().open_path_with_display(&missing.to_string_lossy(), PageLayout::Single, false); + rig.h.state_mut().open_path_with_display(&missing.to_string_lossy(), PageDisplay::Single, false); rig.release(); assert_eq!(rig.layout_of("existing.pdf"), Some(restored)); // A password prompt that is cancelled. rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); let locked = TempFile::new("layout-locked", "pdf", &encrypted_fixture()); - rig.h.state_mut().open_path_with_display(&locked.path(), PageLayout::Single, false); + rig.h.state_mut().open_path_with_display(&locked.path(), PageDisplay::Single, false); rig.release(); assert!(rig.password_dialog()); rig.press("Cancel"); @@ -572,7 +575,7 @@ fn launch_layout_failed_or_cancelled_opens_do_not_target_existing_documents() { let next = TempFile::new("layout-next", "pdf", &fixture(1)); rig.h.state_mut().open_path(&next.path()); rig.release(); - assert_ne!(rig.layout_of(&next.name()), Some((PageLayout::TwoUp, false))); + assert_ne!(rig.layout_of(&next.name()), Some((PageDisplay::TwoUp, false))); } #[test] @@ -581,10 +584,10 @@ fn flagged_startup_opens_wait_for_password_ownership_before_the_first_frame() { rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); let locked = TempFile::new("flag-locked", "pdf", &encrypted_fixture()); let plain = TempFile::new("flag-plain", "pdf", &fixture(1)); - rig.h.state_mut().open_path_with_display(&locked.path(), PageLayout::Single, false); + rig.h.state_mut().open_path_with_display(&locked.path(), PageDisplay::Single, false); // Naming the locked file again joins its open instead of queuing a second one. - rig.h.state_mut().open_path_with_display(&locked.path(), PageLayout::Single, false); - rig.h.state_mut().open_path_with_display(&plain.path(), PageLayout::Single, false); + rig.h.state_mut().open_path_with_display(&locked.path(), PageDisplay::Single, false); + rig.h.state_mut().open_path_with_display(&plain.path(), PageDisplay::Single, false); assert_eq!(rig.jobs.waiting(), 2); rig.release(); assert!(rig.password_dialog()); @@ -599,8 +602,8 @@ fn flagged_startup_opens_wait_for_password_ownership_before_the_first_frame() { rig.h.run_steps(2); assert_eq!(rig.tabs(), 2); assert!(!rig.password_dialog(), "no second prompt appears"); - assert_eq!(rig.layout_of(&locked.name()), Some((PageLayout::Single, false))); - assert_eq!(rig.layout_of(&plain.name()), Some((PageLayout::TwoUp, false)), "the layout lands on the last settled open"); + assert_eq!(rig.layout_of(&locked.name()), Some((PageDisplay::Single, false))); + assert_eq!(rig.layout_of(&plain.name()), Some((PageDisplay::TwoUp, false)), "the layout lands on the last settled open"); } #[test] @@ -652,18 +655,20 @@ fn file_open_converts_an_office_document_on_the_worker() { } fn synthetic_docx() -> Vec { - let mut zip = Vec::new(); + let mut writer = craft::zip::Writer::new(); { - let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut zip)); - let options = zip::write::SimpleFileOptions::default(); for (name, body) in [ - ("[Content_Types].xml", ""), - ("word/document.xml", "Synthetic"), + ( + "[Content_Types].xml", + "", + ), + ( + "word/document.xml", + "Synthetic", + ), ] { - writer.start_file(name, options).expect("start zip entry"); - std::io::Write::write_all(&mut writer, body.as_bytes()).expect("write zip entry"); + writer.add(name, body.as_bytes(), craft::zip::Compression::Deflated).expect("add zip entry"); } - writer.finish().expect("finish zip"); } - zip + writer.finish().expect("finish zip") } diff --git a/crates/ui-egui/src/tools/comments.rs b/crates/ui-egui/src/tools/comments.rs index 154c8fc66b..feae1f75c2 100644 --- a/crates/ui-egui/src/tools/comments.rs +++ b/crates/ui-egui/src/tools/comments.rs @@ -41,7 +41,7 @@ pub(crate) use bridge::{ use bridge::hover_tip; // PLAN: assumed colours exports (pdf-comments-w10): the colour pickers and buttons that `menu` exported before. pub use colours::{fill_picker, recent_custom_colours, remember_custom_colour, status_badge, swatch_grid}; -pub(crate) use colours::{border_colour_button, quick_bar_colour}; +pub(crate) use colours::{RecentColours, border_colour_button, quick_bar_colour, to_rgb}; pub(crate) use composer::composer; #[cfg(test)] use composer::edited_in_view; diff --git a/crates/ui-egui/src/workflows/actions_ui.rs b/crates/ui-egui/src/workflows/actions_ui.rs index 108054f060..d41baced21 100644 --- a/crates/ui-egui/src/workflows/actions_ui.rs +++ b/crates/ui-egui/src/workflows/actions_ui.rs @@ -29,6 +29,9 @@ pub struct ActionOutcome { pub message: String, } +/// The queue of Action Wizard runs: one at a time, each answering with its summary. +pub(crate) type ActionJobs = craft::host::queue::JobQueue<(), ActionOutcome>; + /// An action being created or edited, and the step the Add Step choice offers. #[derive(Clone, Default, PartialEq)] struct ActionDraft { @@ -260,7 +263,6 @@ impl PdfCraftApp { #[cfg(target_arch = "wasm32")] self.run_action_into(action, files, PathBuf::new()); #[cfg(not(target_arch = "wasm32"))] - self.pick_first(PickRequest::folder("action.results").title(tl!("Choose a folder for the results")), None, move |app, dir| { app.run_action_into(action, files, dir) }); diff --git a/crates/ui-egui/src/workflows/combine_ui.rs b/crates/ui-egui/src/workflows/combine_ui.rs index b67104b5f9..d227eb446d 100644 --- a/crates/ui-egui/src/workflows/combine_ui.rs +++ b/crates/ui-egui/src/workflows/combine_ui.rs @@ -20,15 +20,16 @@ mod session; mod table; mod view; +use files::CombineList; pub(crate) use files::Incoming; pub use files::{CombineFile, CombineView, ConflictPreview, Lock, SortKey}; pub(crate) use files::{CombineKey, Preview, RowAction, UnlockAsk}; -use files::CombineList; pub(crate) use parts::range_of; #[cfg(test)] pub(crate) use parts::{Part, moved_order, moved_pages, removed_pages}; #[cfg(test)] use parts::{title_of, utc_stamp}; +pub(crate) use table::columns_from_legacy; pub(crate) use view::page; /// Same reds and ambers as the signature status (`sign_ui`). diff --git a/crates/ui-egui/src/workflows/combine_ui/actions.rs b/crates/ui-egui/src/workflows/combine_ui/actions.rs index cd953374fe..a711f7756f 100644 --- a/crates/ui-egui/src/workflows/combine_ui/actions.rs +++ b/crates/ui-egui/src/workflows/combine_ui/actions.rs @@ -1,7 +1,7 @@ +use super::BTreeSet; use super::files::{CombineKey, Preview, RowAction}; use super::parts::{moved_pages, removed_pages}; use super::view::expandable; -use super::BTreeSet; use crate::PdfCraftApp; use craft::behavior::selection::Selection; diff --git a/crates/ui-egui/src/workflows/combine_ui/table.rs b/crates/ui-egui/src/workflows/combine_ui/table.rs index dc2c5f7a57..d9b10fda27 100644 --- a/crates/ui-egui/src/workflows/combine_ui/table.rs +++ b/crates/ui-egui/src/workflows/combine_ui/table.rs @@ -3,7 +3,9 @@ use std::time::SystemTime; use craft::behavior::{Codec, ColumnKey, ColumnWidth, DisplayOrder, EditEvent, ItemSource, NotAValue, ReorderKeys}; use craft::theme::Tone; -use craft::ui::contract::{Bind, CollectionEvent, ColumnEvent, ColumnLayout, ColumnSort, ColumnSpec, Props as _, ReorderMove, ReorderRule, ShowCollection as _, SpaceAction}; +use craft::ui::contract::{ + Bind, CollectionEvent, ColumnEvent, ColumnLayout, ColumnSort, ColumnSpec, Props as _, ReorderMove, ReorderRule, ShowCollection as _, SpaceAction, +}; use craft::ui::list::{CellStatus, ListRow, RowEvent}; use craft::ui::table::Table; use craft::ui::text::TextField; @@ -34,6 +36,35 @@ fn sort_key_of(column: &ColumnKey) -> Option { SortKey::ALL.into_iter().find(|key| column_of(*key) == *column) } +/// The layout the last release kept in its settings: `order`, every sort key once by its name, and +/// optionally `widths`, one number per key in the keys' own order. `None` for anything else (a +/// repeated key, a wrong count, a width that is not a positive number), which leaves the default. +pub(crate) fn columns_from_legacy(value: &serde_json::Value) -> Option { + let object = value.as_object()?; + let order = + object.get("order")?.as_array()?.iter().map(|name| serde_json::from_value::(name.clone()).ok()).collect::>>()?; + let complete = order.len() == SortKey::ALL.len() && SortKey::ALL.iter().all(|key| order.contains(key)); + if !complete { + return None; + } + let widths = match object.get("widths") { + None | Some(serde_json::Value::Null) => Vec::new(), + Some(widths) => { + let widths = widths.as_array()?; + if widths.len() != SortKey::ALL.len() { + return None; + } + let mut pairs = Vec::new(); + for (key, width) in SortKey::ALL.into_iter().zip(widths) { + let width = width.as_f64().filter(|w| w.is_finite() && *w > 0.0)?; + pairs.push((column_of(key), width as f32)); + } + pairs + } + }; + Some(ColumnLayout { order: order.into_iter().map(column_of).collect(), widths, hidden: Vec::new() }) +} + /// A Pages cell's text: kept as typed (Combine takes pages in the order given, with repeats), refused when the /// range can't be taken from a file of `count` pages. #[derive(Clone)] diff --git a/crates/ui-egui/src/workflows/combine_ui/tests.rs b/crates/ui-egui/src/workflows/combine_ui/tests.rs index 84daeff592..757504411a 100644 --- a/crates/ui-egui/src/workflows/combine_ui/tests.rs +++ b/crates/ui-egui/src/workflows/combine_ui/tests.rs @@ -22,8 +22,11 @@ fn utc_stamp_is_utc_minutes_and_clamps_pre_epoch() { } // Past chrono's range every time gives one stamp, whatever the distance, and never panics. // (Windows' SystemTime can't hold the largest, so each is checked where it exists.) - let far: Vec = - [10_000_000_000_000u64, u64::MAX / 2].into_iter().filter_map(|s| SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(s))).map(utc_stamp).collect(); + let far: Vec = [10_000_000_000_000u64, u64::MAX / 2] + .into_iter() + .filter_map(|s| SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(s))) + .map(utc_stamp) + .collect(); assert!(far.windows(2).all(|w| w[0] == w[1]), "{far:?}"); assert!(far.iter().all(|s| s.ends_with(" UTC")), "{far:?}"); } diff --git a/crates/ui-egui/src/workflows/combine_ui/view.rs b/crates/ui-egui/src/workflows/combine_ui/view.rs index af1bda677c..66bf844e33 100644 --- a/crates/ui-egui/src/workflows/combine_ui/view.rs +++ b/crates/ui-egui/src/workflows/combine_ui/view.rs @@ -162,8 +162,11 @@ pub(crate) fn page(app: &mut PdfCraftApp, ui: &mut egui::Ui) { .collect::>() .len(); if bad > 0 { - let text = - if bad == 1 { tl!("1 file needs attention").to_string() } else { crate::i18n::fmt(tl!("{n} files need attention"), &[("n", &bad.to_string())]) }; + let text = if bad == 1 { + tl!("1 file needs attention").to_string() + } else { + crate::i18n::fmt(tl!("{n} files need attention"), &[("n", &bad.to_string())]) + }; Text::new(text).tone(Tone::Bad).show(ui); } } @@ -216,7 +219,8 @@ fn add_files(app: &mut PdfCraftApp, ui: &mut egui::Ui) { /// The open documents as files to combine: the main part adds every one, the menu one document. fn add_open_documents(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let open: Vec<(usize, String)> = app.views.iter().enumerate().filter_map(|(i, _)| crate::canvas::tab_label(app, i).map(|name| (i, name))).collect(); + let open: Vec<(usize, String)> = + app.views.iter().enumerate().filter_map(|(i, _)| crate::canvas::tab_label(app, i).map(|name| (i, name))).collect(); // `None` is every open document. let mut entries: Vec>> = vec![Entry::new(None, tl!("All open documents"))]; entries.extend(open.iter().map(|(i, name)| Entry::new(Some(*i), name.clone()))); @@ -248,7 +252,6 @@ fn skip_prompt(app: &mut PdfCraftApp, ui: &mut egui::Ui) { lines.push(crate::i18n::fmt(tl!("and {n} more"), &[("n", &more)])); } let out = Prompt::new(tl!("Leave out files that can't be read?"), tl!("These files can't be read, so they won't be in the combined PDF:")) - .lines(lines.into_iter().map(Into::into)) .answers([FooterButton::new(tl!("Combine the rest"), DialogRole::Accept), FooterButton::new(tl!("Cancel"), DialogRole::Cancel)]) .show(ui); diff --git a/crates/ui-egui/src/workflows/export_ui.rs b/crates/ui-egui/src/workflows/export_ui.rs index 2a2322a95b..b89ffe701c 100644 --- a/crates/ui-egui/src/workflows/export_ui.rs +++ b/crates/ui-egui/src/workflows/export_ui.rs @@ -20,6 +20,9 @@ use pdfcraft_engine::export::{ExportSource, Exporter, ImageFormat}; use crate::notices::{self, ProgressKey, ProgressNotice}; use crate::{JobCount, PdfCraftApp}; +/// The queue of exports, keyed by document, each answering with its summary line. +pub(crate) type ExportJobs = craft::host::queue::JobQueue; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExportKind { Image, @@ -77,10 +80,8 @@ fn params(kind: ExportKind, count: usize, current: usize) -> Vec { let mut rows = Vec::new(); match kind { ExportKind::Image => { - let dpis = DPIS - .iter() - .map(|n| (n.to_string(), Label::from(crate::i18n::fmt(tl!("{dpi} pixels/inch"), &[("dpi", &n.to_string())])))) - .collect(); + let dpis = + DPIS.iter().map(|n| (n.to_string(), Label::from(crate::i18n::fmt(tl!("{dpi} pixels/inch"), &[("dpi", &n.to_string())])))).collect(); rows.push(Param::new("dpi", tl!("Resolution"), ParamKind::choice(dpis, Some("150".into())))); let formats = ["png", "jpeg", "tiff"] .iter() @@ -307,7 +308,6 @@ impl PdfCraftApp { #[cfg(target_arch = "wasm32")] task(self, PathBuf::new()); #[cfg(not(target_arch = "wasm32"))] - self.pick_first(PickRequest::folder("export.folder").title(tl!("Choose a folder for the exported files")), None, task); } diff --git a/crates/ui-egui/src/workflows/optimize_ui.rs b/crates/ui-egui/src/workflows/optimize_ui.rs index e673cda90d..3a608a3f69 100644 --- a/crates/ui-egui/src/workflows/optimize_ui.rs +++ b/crates/ui-egui/src/workflows/optimize_ui.rs @@ -15,7 +15,9 @@ use craft::ui::display::Text; use craft::ui::list::ListRow; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamTab, SharedRows}; use craft::ui::table::Table; -use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, MonoSettings, Preset, QUALITIES, Settings, SpaceCategory, SpaceUse}; +use pdfcraft_engine::optimize::{ + Compatibility, Compression, ImageSettings, MonoCompression, MonoSettings, Preset, QUALITIES, Settings, SpaceCategory, SpaceUse, +}; use pdfcraft_engine::optimizer::{OptimizeStage, Optimized}; use pdfcraft_engine::{DocId, EditError, Hidden, OptimizeReport}; @@ -76,7 +78,12 @@ struct Toggle { } static TOGGLES: [Toggle; 20] = [ - Toggle { tab: 1, key: "linksactionsscripts", label: "Discard all links, actions and JavaScript", effect: Effect::Discard(Hidden::LinksActionsScripts) }, + Toggle { + tab: 1, + key: "linksactionsscripts", + label: "Discard all links, actions and JavaScript", + effect: Effect::Discard(Hidden::LinksActionsScripts), + }, Toggle { tab: 1, key: "discard_alternate_images", @@ -451,8 +458,11 @@ fn audit_lines(rows: &[SpaceUse]) -> Vec { .filter(|r| r.bytes > 0) .map(|r| { // "Patterns" also names the redaction search patterns ("模式"); the audit's PDF graphics objects need their own key. - let description = - if r.category == SpaceCategory::Patterns { tl!("Patterns (graphics objects)").to_string() } else { tl!(r.category.label()).to_string() }; + let description = if r.category == SpaceCategory::Patterns { + tl!("Patterns (graphics objects)").to_string() + } else { + tl!(r.category.label()).to_string() + }; AuditLine { description, bytes: r.bytes.to_string(), percentage: format!("{:.2}%", r.percent) } }) .collect(); @@ -526,7 +536,6 @@ pub(crate) fn open_space_audit(app: &mut PdfCraftApp, ctx: &egui::Context, from_ ParamDialog::new(key, tl!("Space Audit"), vec![audit_row(rows.clone())]).read_only(true).values(Bind::bound(fields)) }); if from_optimizer { - crate::dialogs::host::open_over(app, dialog.instance(AUDIT_INSTANCE), dialog_id(OPTIMIZE_KEY)); } else { crate::dialogs::host::open(app, dialog); @@ -596,6 +605,9 @@ pub struct OptimizeRun { /// The queue of optimization runs, keyed by document: one run per document, and one at a time by the app's own rule. pub(crate) type OptimizeJobs = JobQueue>; +/// The queue of space audits, keyed by document and edit generation (a newer edit supersedes an older audit). +pub(crate) type SpaceAuditJobs = JobQueue<(DocId, u64), Vec>; + /// The notice's text for a stage. fn stage_label(stage: OptimizeStage) -> String { match stage {