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 8a70686d9c..50ef23c24e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -61,7 +61,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). 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/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/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/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/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/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 b31290ec4f..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,7 +239,6 @@ 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. @@ -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 adfc3c5fbd..f2f48ae76f 100644 --- a/crates/ui-egui/src/panels/side_panels.rs +++ b/crates/ui-egui/src/panels/side_panels.rs @@ -405,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) { 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 72be1e27b2..bc76b87d3e 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::{RecentColours, border_choice, fill_choice, palette}; +pub(crate) use colours::{RecentColours, border_choice, fill_choice, palette, to_rgb}; pub(crate) use colours::{border_colour_button, quick_bar_colour}; pub(crate) use composer::composer; #[cfg(test)] 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 {