From 1be78cc0dee4c2b17e9a6e8074ccf4d62ac576b6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:28 -0500 Subject: [PATCH] pdf-workflows-w13: net change of 2 commits - pdf-workflows-w13: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot) - pdf-workflows-w13: review fixes (review-1) --- crates/engine/Cargo.toml | 1 + crates/engine/src/text_fonts.rs | 65 +- .../src/workflows/create_multiple_ui.rs | 38 +- crates/ui-egui/src/workflows/files.rs | 1015 ++++++----------- 4 files changed, 360 insertions(+), 759 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index c059a256f3..3a964c64e4 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-docpath = { workspace = true } +craft-font-catalog = { workspace = true } craft-image-codecs = { workspace = true } pdfcraft-measure = { workspace = true } image = { version = "0.25", default-features = false } diff --git a/crates/engine/src/text_fonts.rs b/crates/engine/src/text_fonts.rs index e2b413d88d..a5aa2e5cb7 100644 --- a/crates/engine/src/text_fonts.rs +++ b/crates/engine/src/text_fonts.rs @@ -8,28 +8,10 @@ pub struct FontFile { pub face: String, } -/// Standard user-installed font folders; discovery is performed only on request. +/// The font folders of this platform, the system's and the user's, as the font catalogue lists +/// them; discovery is performed only on request. pub fn installed_directories() -> Vec { - let home = std::env::var_os("HOME").map(PathBuf::from); - if cfg!(target_os = "macos") { - let mut dirs = vec![PathBuf::from("/Library/Fonts")]; - if let Some(home) = home { - dirs.push(home.join("Library/Fonts")); - } - dirs - } else if cfg!(windows) { - let mut dirs = std::env::var_os("WINDIR").map(|p| PathBuf::from(p).join("Fonts")).into_iter().collect::>(); - if let Some(local) = std::env::var_os("LOCALAPPDATA") { - dirs.push(PathBuf::from(local).join("Microsoft/Windows/Fonts")); - } - dirs - } else { - let mut dirs = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")]; - if let Some(home) = home { - dirs.extend([home.join(".local/share/fonts"), home.join(".fonts")]); - } - dirs - } + craft_font_catalog::font_dirs(&craft_font_catalog::FontEnv::from_process()) } /// Bounded scan with resolved roots and no descendant symlinks. @@ -148,47 +130,6 @@ mod tests { assert_eq!(found.len(), 501, "do not silently discard accepted fonts after sorting"); } - #[test] - fn test_installed_directories() { - let dirs = installed_directories(); - assert!(!dirs.is_empty()); - } - - #[test] - fn test_font_extension() { - assert!(font_extension(Path::new("Arial.ttf"))); - assert!(font_extension(Path::new("Noto.otf"))); - assert!(font_extension(Path::new("CUSTOM.TTF"))); - assert!(font_extension(Path::new("ROBOTO.OTF"))); - assert!(!font_extension(Path::new("document.pdf"))); - assert!(!font_extension(Path::new("font.woff"))); - assert!(!font_extension(Path::new("font.woff2"))); - assert!(!font_extension(Path::new("no_extension"))); - } - - #[test] - fn test_font_content_key() { - let empty = font_content_key(&[]); - assert_eq!(empty.0, 0); - - let a = font_content_key(b"TrueType font sample data bytes"); - let b = font_content_key(b"TrueType font sample data bytes"); - let c = font_content_key(b"Different font sample data bytes"); - - assert_eq!(a, b, "identical bytes must produce identical keys"); - assert_ne!(a, c, "differing bytes must produce distinct keys"); - assert_eq!(a.0, b"TrueType font sample data bytes".len()); - } - - #[test] - fn test_discover_empty_and_nonexistent_roots() { - let empty = discover(&[]); - assert!(empty.is_empty()); - - let nonexistent = discover(&[PathBuf::from("Z:\\nonexistent_font_path_xyz_12345")]); - assert!(nonexistent.is_empty()); - } - #[test] fn test_discover_deduplicates_non_adjacent_same_content() { let root = std::env::temp_dir().join(format!("pdfcraft-font-dedup-test-{}", std::process::id())); diff --git a/crates/ui-egui/src/workflows/create_multiple_ui.rs b/crates/ui-egui/src/workflows/create_multiple_ui.rs index 03fd3e1eaa..6ba57bf2d6 100644 --- a/crates/ui-egui/src/workflows/create_multiple_ui.rs +++ b/crates/ui-egui/src/workflows/create_multiple_ui.rs @@ -5,6 +5,8 @@ use std::collections::HashSet; use std::path::PathBuf; use std::sync::Arc; +use craft::docpath::names::{CopyNumbering, safe_file_stem, unique_file_name}; +use craft::host::WriteIntent; use pdfcraft_engine::{EditError, SourceKind}; use crate::PdfCraftApp; @@ -54,34 +56,16 @@ impl PdfCraftApp { refused.push(format!("{name} ({})", tl!("already a PDF"))); continue; } - let base = crate::files::file_stem_from_user(stem(&name)); + let base = safe_file_stem(stem(&name), "pdf"); let base = if base.is_empty() { "document" } else { &base }; - let mut output = None; - for number in 1..10_000 { - let filename = if number == 1 { format!("{base}.pdf") } else { format!("{base} ({number}).pdf") }; - let candidate = dir.as_ref().map(|d| d.join(&filename)); - if !used.contains(&filename.to_lowercase()) && !candidate.as_ref().is_some_and(|path| path.exists()) { - used.insert(filename.to_lowercase()); - output = Some((filename, candidate)); - break; - } - } - let Some((filename, target)) = output else { - refused.push(format!("{name} ({})", tl!("no unused output name"))); - continue; - }; - #[cfg(not(target_arch = "wasm32"))] - let result = match target { - Some(path) => crate::editing::write_atomically(&path.to_string_lossy(), &pdf).map_err(|e| e.to_string()), - None => Err(tl!("no output folder was chosen").to_string()), - }; - #[cfg(target_arch = "wasm32")] - let result = { - let _ = target; - crate::editing::download(&filename, &pdf) - }; - match result { - Ok(()) => made += 1, + let filename = unique_file_name(&format!("{base}.pdf"), CopyNumbering::Parenthesized, |candidate| { + used.contains(&candidate.to_lowercase()) || dir.as_ref().is_some_and(|d| d.join(candidate).exists()) + }); + used.insert(filename.to_lowercase()); + // Without a folder (the web) the write is a download. + let path = dir.as_ref().map_or_else(|| PathBuf::from(&filename), |d| d.join(&filename)); + match self.host.files().write(&path, &pdf, WriteIntent::SaveAs) { + Ok(_) => made += 1, Err(error) => refused.push(format!("{filename} ({error})")), } } diff --git a/crates/ui-egui/src/workflows/files.rs b/crates/ui-egui/src/workflows/files.rs index 82057ecc55..23f3b1a8d2 100644 --- a/crates/ui-egui/src/workflows/files.rs +++ b/crates/ui-egui/src/workflows/files.rs @@ -1,11 +1,13 @@ //! Multi-document page operations: Combine Files, Insert Pages from File, Extract Pages, Split. //! -//! Files are picked asynchronously and used on a later frame: desktop builds through `pickers` -//! (a blocking picker crashes the app on macOS), browsers through `requests`. +//! Files are picked and written through the host's `Files` service on every target: a pick is +//! asked for now and used on a later frame, once `process_picks` hands its answer back. -use crate::file_filter::AddFilterAnyCase as _; use std::sync::Arc; +use craft::docpath::names::{CopyNumbering as _, is_plain_file_name, safe_file_stem}; +use craft::host::{PickRequest, Picked, WriteIntent}; +use craft::ui::contract::OsFile; use pdfcraft_engine::{DocId, Edit, SplitBy}; use crate::PdfCraftApp; @@ -27,83 +29,59 @@ pub enum FilePurpose { CreateMultipleSeparate, /// Find text and redact ▸ Import list: a text file with one word or phrase per line. RedactWords, + /// Sign ▸ the Digital ID file to use or export. + DigitalId, + /// Sign ▸ the picture used as a signature's graphic. + SignGraphic, + /// Sign ▸ where the signed copy is saved. + SignedCopy, } -#[cfg(not(target_arch = "wasm32"))] -fn discover_fonts_safely( - discover: impl FnOnce() -> Vec + std::panic::UnwindSafe, -) -> Vec { - std::panic::catch_unwind(discover).unwrap_or_default() -} - -#[cfg(not(target_arch = "wasm32"))] -#[derive(Default)] -struct FontScanCache { - files: Option>, - loading: bool, -} - -#[cfg(not(target_arch = "wasm32"))] -impl FontScanCache { - fn begin(&mut self, reload: bool) -> bool { - if self.loading || (!reload && self.files.is_some()) { - return false; - } - self.loading = true; - self.files = None; - true - } - - fn finish(&mut self, files: Vec) { - self.files = Some(files); - self.loading = false; - } -} - -/// Discover installed document fonts off the GUI thread. Reload permits retrying a -/// failed scan or discovering newly installed fonts without restarting the app. -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn installed_font_files(ctx: &egui::Context, reload: bool) -> Option> { - use std::sync::{Mutex, OnceLock}; - type Files = Arc>; - static CACHE: OnceLock = OnceLock::new(); - let files = CACHE.get_or_init(|| Arc::new(Mutex::new(FontScanCache::default()))); - let start = files.lock().is_ok_and(|mut state| state.begin(reload)); - if start { - let result = files.clone(); - let ctx = ctx.clone(); - if std::thread::Builder::new() - .name("document-font-discovery".into()) - .spawn(move || { - let fonts = discover_fonts_safely(|| pdfcraft_engine::text_fonts::discover(&pdfcraft_engine::text_fonts::installed_directories())); - if let Ok(mut result) = result.lock() { - result.finish(fonts); - } - ctx.request_repaint(); - }) - .is_err() - && let Ok(mut result) = files.lock() - { - result.finish(Vec::new()); +impl FilePurpose { + /// The purpose string of a pick: picks of one purpose share a remembered folder. + pub fn key(self) -> &'static str { + match self { + Self::TextFont { .. } => "text.font", + Self::Combine => "combine", + Self::InsertPages => "insert.pages", + Self::ReplacePages => "replace.pages", + Self::Ocr => "ocr", + Self::CreateMultiple => "create.multiple", + Self::CreateMultipleSeparate => "create.separate", + Self::RedactWords => "redact.words", + Self::DigitalId => "sign.digital_id", + Self::SignGraphic => "sign.graphic", + Self::SignedCopy => "sign.signed_copy", } } - files.lock().ok().and_then(|f| f.files.clone()) + + /// Insert and Replace edit the active document, at its selection. + pub(crate) fn edits_active_document(self) -> bool { + matches!(self, Self::InsertPages | Self::ReplacePages | Self::TextFont { .. }) + } +} + +/// The fonts installed on this machine that documents may use, and the catalogue over them. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) struct InstalledFonts { + /// The scanned font files. + pub files: Vec, + /// A catalogue of exactly those files, built once when the scan arrives. + pub catalog: Arc, } /// The picker for `purpose`: PDFs, and for Create and Insert also what they convert. -fn files_picker(purpose: FilePurpose) -> rfd::AsyncFileDialog { - let dialog = rfd::AsyncFileDialog::new(); - if matches!(purpose, FilePurpose::TextFont { .. }) { - return dialog.add_filter_any_case("TrueType / OpenType font", &["ttf", "otf"]); +fn picker_request(purpose: FilePurpose, multiple: bool) -> PickRequest { + let request = if multiple { PickRequest::open_many(purpose.key()) } else { PickRequest::open(purpose.key()) }; + match purpose { + FilePurpose::TextFont { .. } => request.filter("TrueType / OpenType font", &["ttf", "otf"]), + FilePurpose::RedactWords => request.filter(tl!("Text"), &["txt"]), + FilePurpose::CreateMultiple | FilePurpose::CreateMultipleSeparate | FilePurpose::InsertPages | FilePurpose::Combine => { + let all: Vec<&str> = std::iter::once("pdf").chain(pdfcraft_engine::CONVERTIBLE).collect(); + request.filter(tl!("PDF, images and text"), &all).filter("PDF", &["pdf"]) + } + _ => request.filter("PDF", &["pdf"]), } - if purpose == FilePurpose::RedactWords { - return dialog.add_filter_any_case(tl!("Text"), &["txt"]); - } - if !matches!(purpose, FilePurpose::CreateMultiple | FilePurpose::CreateMultipleSeparate | FilePurpose::InsertPages | FilePurpose::Combine) { - return dialog.add_filter_any_case("PDF", &["pdf"]); - } - let all: Vec<&str> = std::iter::once("pdf").chain(pdfcraft_engine::CONVERTIBLE).collect(); - dialog.add_filter_any_case(tl!("PDF, images and text"), &all).add_filter_any_case("PDF", &["pdf"]) } /// The Replace Pages dialog: the chosen file and the ranges (1-based, inclusive). @@ -125,13 +103,6 @@ pub struct ReplaceDraft { pub(crate) target: Option, } -impl FilePurpose { - /// Insert and Replace edit the active document, at its selection. - pub(crate) fn edits_active_document(self) -> bool { - matches!(self, Self::InsertPages | Self::ReplacePages | Self::TextFont { .. }) - } -} - /// The document a pick edits, as it was when the picker opened. Page positions captured then /// are only valid while it is unchanged, and the pick acts on the active document; so a pick /// that arrives after the document was edited, or stopped being the active one, is refused @@ -142,46 +113,6 @@ pub struct PickTarget { generation: Option, } -/// Files picked asynchronously in a browser, waiting for the next frame (see -/// [`PdfCraftApp::file_request`]). -#[derive(Debug)] -pub struct FileRequest { - purpose: FilePurpose, - target: Option, - files: Vec<(String, Vec)>, - /// Dropped on the Combine files tab rather than picked: what Combine can't take is left out. - dropped: bool, -} - -/// Files picked asynchronously (web), waiting to be used. -pub type Requests = Arc>>; - -/// Settings for the Split dialog. -#[derive(Clone, Debug, PartialEq)] -pub struct SplitDraft { - /// Pages per file. - pub every: usize, - pub mode: SplitMode, - /// The largest part, in megabytes (File size mode). - pub size_mb: f64, -} - -impl Default for SplitDraft { - fn default() -> Self { - SplitDraft { every: 1, mode: SplitMode::Pages, size_mb: 2.0 } - } -} - -/// Acrobat's Split by: number of pages, file size, top-level bookmarks (and PdfCraft's -/// before-selected-pages). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SplitMode { - Pages, - Selection, - Size, - Bookmarks, -} - /// What Split does once confirmed. #[derive(Clone, Debug, PartialEq)] pub enum SplitPlan { @@ -192,7 +123,7 @@ pub enum SplitPlan { /// Organize ▸ Extract options. #[derive(Clone, Debug, Default, PartialEq)] -pub struct ExtractDraft { +pub struct ExtractOptions { /// Each page as its own file. pub separate: bool, /// Delete the pages after extracting them. @@ -206,106 +137,32 @@ pub struct ExtractDraft { pub pages: String, } -impl ExtractDraft { - /// The pages to extract (0-based, in the order typed, each once) from a document of `count` - /// pages: the typed [`Self::pages`] ranges, or `selected` when none are typed. Says what is - /// wrong with a range that can't be read or takes no page. - pub fn pages_to_extract(&self, selected: Vec, count: usize) -> Result, String> { - if self.pages.trim().is_empty() { - return Ok(selected); - } - match pdfcraft_engine::print::select_pages(count, Some(&self.pages), &[], pdfcraft_engine::print::Subset::All, false) { - Ok(p) if p.is_empty() => Err(tl!("No pages selected").to_string()), - Ok(p) => { - let mut seen = std::collections::HashSet::new(); - Ok(p.into_iter().filter(|page| seen.insert(*page)).collect()) - } - Err(e) => Err(e.to_string()), +/// The pages to extract (0-based, in the order typed, each once) from a document of `count` +/// pages: the typed ranges in `text`, or `selected` when none are typed. Says what is wrong with +/// a range that can't be read or takes no page. +pub(crate) fn pages_to_extract(text: &str, selected: Vec, count: usize) -> Result, String> { + if text.trim().is_empty() { + return Ok(selected); + } + match pdfcraft_engine::print::select_pages(count, Some(text), &[], pdfcraft_engine::print::Subset::All, false) { + Ok(p) if p.is_empty() => Err(tl!("No pages selected").to_string()), + Ok(p) => { + let mut seen = std::collections::HashSet::new(); + Ok(p.into_iter().filter(|page| seen.insert(*page)).collect()) } + Err(e) => Err(e.to_string()), } } -/// `name` made safe as a file name on every platform: no path separators, reserved or control -/// characters, no trailing dots or spaces (Windows drops them), no `.pdf` (added back on -/// writing), at most 200 characters. Empty when nothing usable is left. -pub(crate) fn file_stem_from_user(name: &str) -> String { - let name = name.trim(); - // Any case of ".pdf": it's added back on writing. - let name = - name.len().checked_sub(4).and_then(|i| name.get(i..).filter(|ext| ext.eq_ignore_ascii_case(".pdf")).and(name.get(..i))).unwrap_or(name); - let cleaned: String = - name.chars().map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect(); - // At most 200 bytes, so " (page N).pdf" still fits the usual 255-byte file name limit. - let mut end = cleaned.len().min(200); - while !cleaned.is_char_boundary(end) { - end -= 1; - } - let cleaned = cleaned.get(..end).unwrap_or_default(); - // Trimming trailing dots also leaves "." and ".." empty. - let stem = cleaned.trim().trim_end_matches(['.', ' ']).trim_start(); - // Windows reserves these device names whatever the extension: "NUL.pdf" writes nowhere. - let device = stem.split('.').next().unwrap_or_default().to_ascii_uppercase(); - let reserved = matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") - || (device.len() == 4 - && (device.starts_with("COM") || device.starts_with("LPT")) - && device.as_bytes().get(3).is_some_and(|d| (b'1'..=b'9').contains(d))); - if reserved { format!("_{stem}") } else { stem.to_string() } -} - -/// A plain file name for a PDF-supplied attachment name: the Save suggestion, and the tab name -/// (which later names files written from that tab). It never changes the stored name or a -/// destination the user selected. -pub(crate) fn attachment_file_name(name: &str) -> String { - let cleaned: String = name - .chars() - .filter(|c| !c.is_control() && !matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) - .map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }) - .collect(); - let name = cleaned.trim_start().trim_end_matches(|c: char| c == '.' || c.is_whitespace()); - if name.is_empty() { - return "attachment".into(); - } - let device = name.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); - let reserved = matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") - || device - .strip_prefix("COM") - .or_else(|| device.strip_prefix("LPT")) - .is_some_and(|number| matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³")); - if reserved { format!("_{name}") } else { name.to_string() } -} - -/// Whether `name` names a file directly inside a folder: not empty, with no `/` or `\\`, no drive -/// (`C:`), and not ending in `.` or a space (which also rules out `.` and `..`): Windows drops a -/// trailing dot or space, so `report.` would write `report`. On Windows any `:` is refused, which -/// also rules out alternate data streams. -pub(crate) fn is_plain_file_name(name: &str) -> bool { - let drive = matches!(name.as_bytes(), [letter, b':', ..] if letter.is_ascii_alphabetic()); - !(name.is_empty() || name.ends_with(['.', ' ']) || name.contains(['/', '\\']) || drive || (cfg!(windows) && name.contains(':'))) -} - -/// Pages ▸ Rotate Pages. -#[derive(Clone, Debug, PartialEq)] -pub struct RotateDraft { - /// Degrees clockwise: 90, 180 or 270. - pub degrees: i64, - /// 0 all pages, 1 the selection, 2 the range below. - pub which: u8, - pub from: usize, - pub to: usize, - pub parity: pdfcraft_engine::PageParity, - pub orientation: pdfcraft_engine::PageOrientation, -} - -impl Default for RotateDraft { - fn default() -> Self { - RotateDraft { degrees: 90, which: 0, from: 1, to: 1, parity: Default::default(), orientation: Default::default() } - } +/// A file name's last component ("file.pdf" when the path has none). +fn name_of(path: &std::path::Path) -> String { + path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file.pdf".into()) } /// A picked file's name and bytes, or its name and why it can't be read. #[cfg(not(target_arch = "wasm32"))] fn read_named(path: &std::path::Path) -> Result<(String, Vec), (String, String)> { - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file.pdf".into()); + let name = name_of(path); match std::fs::read(path) { Ok(bytes) => Ok((name, bytes)), Err(e) => Err((name, e.to_string())), @@ -313,8 +170,8 @@ fn read_named(path: &std::path::Path) -> Result<(String, Vec), (String, Stri } /// The name of a file dropped on the window ("dropped.pdf" when it has none). -pub(crate) fn dropped_name(f: &egui::DroppedFileHandle) -> String { - f.path().file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "dropped.pdf".into()) +pub(crate) fn dropped_name(f: &OsFile) -> String { + if f.name.is_empty() { "dropped.pdf".into() } else { f.name.clone() } } impl PdfCraftApp { @@ -356,39 +213,31 @@ impl PdfCraftApp { self.pick_files(FilePurpose::InsertPages, true); } + /// Ask for files for `purpose`; they are used when the pick is answered. pub(crate) fn pick_files(&mut self, purpose: FilePurpose, multiple: bool) { - #[cfg(not(target_arch = "wasm32"))] - self.pick(crate::pickers::PickFor::Files(purpose), files_picker(purpose), multiple); - #[cfg(target_arch = "wasm32")] - { - let requests = self.requests.clone(); - let ctx = self.ctx.clone(); - // The document to insert into is the one active now, not whichever is active when - // the browser has finished reading the file (#167). - let request = self.file_request(purpose, Vec::new()); - wasm_bindgen_futures::spawn_local(async move { - let dialog = files_picker(purpose); - let handles = if multiple { dialog.pick_files().await.unwrap_or_default() } else { dialog.pick_file().await.into_iter().collect() }; - let mut files = Vec::new(); - for h in handles { - files.push((h.file_name(), h.read().await)); - } - if !files.is_empty() - && let Ok(mut q) = requests.lock() - { - q.push(FileRequest { files, ..request }); - } - // The read may finish while the app is idle: wake it to use the files. - if let Some(ctx) = ctx { - ctx.request_repaint(); - } - }); + // The document to edit is the one active now, not whichever is active when the pick is + // answered (#167). + let target = purpose.edits_active_document().then(|| self.pick_target(self.active_ids().map(|(_, id)| id))).flatten(); + self.pick_file(picker_request(purpose, multiple), target, move |app, picked| app.use_picked(purpose, picked)); + } + + /// Use what a pick for `purpose` answered. A cancelled or unavailable picker changes nothing + /// (`process_picks` reports it). + pub(crate) fn use_picked(&mut self, purpose: FilePurpose, picked: Picked) { + match picked { + #[cfg(not(target_arch = "wasm32"))] + Picked::Paths(paths) => self.use_paths(purpose, &paths), + Picked::Contents(files) if !files.is_empty() => self.use_files(purpose, files), + _ => {} } } /// Read the picked files and use them. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn use_paths(&mut self, purpose: FilePurpose, paths: &[std::path::PathBuf]) { + if matches!(purpose, FilePurpose::DigitalId | FilePurpose::SignGraphic | FilePurpose::SignedCopy) { + return; + } if purpose == FilePurpose::CreateMultiple { // Each file is read when its turn comes, so the selection's bytes are not all held at once. if !paths.is_empty() { @@ -398,27 +247,14 @@ impl PdfCraftApp { } if purpose == FilePurpose::CreateMultipleSeparate { if !paths.is_empty() { - let paths = paths.to_vec(); - let convert = move |app: &mut Self, dir: std::path::PathBuf| { - app.stage_create_separate(paths.iter().map(|p| read_named(p)), Some(dir)); - }; - match self.export_dir_override.clone() { - Some(dir) => convert(self, std::path::PathBuf::from(dir)), - None => { - self.ask_one( - crate::pickers::Ask::Folder(rfd::AsyncFileDialog::new().set_title(tl!("Choose a folder for the exported files"))), - None, - convert, - ); - } - } + self.ask_separate_folder(paths.to_vec().into_iter().map(|p| read_named(&p))); } return; } let mut files = Vec::new(); let mut modified = Vec::new(); for p in paths { - let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file.pdf".into()); + let name = name_of(p); if purpose == FilePurpose::RedactWords && std::fs::metadata(p).is_ok_and(|m| m.len() > crate::redact_ui::MAX_WORD_LIST_BYTES as u64) { self.notify_fmt("{name} is too large for a word list (at most 1 MB).", &[("name", &name)]); return; @@ -458,64 +294,51 @@ impl PdfCraftApp { } } - /// Files dropped on the Combine files tab join its list in the order dropped (see - /// [`Self::add_dropped_to_combine`]); a folder adds the files in it and its subfolders. - #[cfg(not(target_arch = "wasm32"))] - pub(crate) fn drop_into_combine(&mut self, dropped: Vec, _ctx: &egui::Context) { - let mut files = Vec::new(); - for f in dropped { - let path = f.path(); - if path.is_absolute() && path.is_dir() { - // After the files dropped before it. - self.add_dropped_to_combine(std::mem::take(&mut files)); - self.add_folder_to_combine(path, true); - continue; - } - let name = dropped_name(&f); - // A file on disk is read from there, with when it was last modified; a drop that - // carries only bytes (no path) as it is. - let (read, modified) = if path.is_absolute() { - (std::fs::read(path).map_err(|e| e.to_string()), std::fs::metadata(path).and_then(|m| m.modified()).ok()) - } else { - (f.bytes(), None) - }; - match read { - Ok(bytes) => files.push(crate::combine_ui::Incoming { modified, ..crate::combine_ui::Incoming::new(name, bytes) }), - Err(e) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e)]), - } - } - self.add_dropped_to_combine(files); - } - - /// Browsers read dropped files asynchronously; they join the Combine files list next frame. - #[cfg(target_arch = "wasm32")] - pub(crate) fn drop_into_combine(&mut self, dropped: Vec, ctx: &egui::Context) { - let requests = self.requests.clone(); - let request = FileRequest { dropped: true, ..self.file_request(FilePurpose::Combine, Vec::new()) }; - let ctx = ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - // One after another, so they join the list in the order dropped. - let mut files = Vec::new(); - for f in dropped { - if let Ok(bytes) = f.bytes_async().await { - files.push((dropped_name(&f), bytes)); - } - } - if !files.is_empty() - && let Ok(mut q) = requests.lock() - { - q.push(FileRequest { files, ..request }); - ctx.request_repaint(); + /// Ask for the folder the separate PDFs go to, then convert `sources` into it. Where there + /// is no folder to choose (the web) they are downloaded at once. + pub(crate) fn ask_separate_folder(&mut self, sources: I) + where + I: IntoIterator), (String, String)>> + 'static, + { + #[cfg(not(target_arch = "wasm32"))] + self.pick_file(PickRequest::folder("export.separate").title(tl!("Choose a folder for the exported files")), None, move |app, picked| { + if let Some(dir) = picked.first_path() { + app.stage_create_separate(sources, Some(dir)); } }); + #[cfg(target_arch = "wasm32")] + self.stage_create_separate(sources, None); } - /// A request to use `files` for `purpose`, bound to the document it will edit: the active - /// one now, for Insert and Replace. Browsers make it when the picker opens and queue it on - /// `requests` once the files are read; it is used on a later frame. - pub fn file_request(&self, purpose: FilePurpose, files: Vec<(String, Vec)>) -> FileRequest { - let target = if purpose.edits_active_document() { self.pick_target(self.active_ids().map(|(_, id)| id)) } else { None }; - FileRequest { purpose, target, files, dropped: false } + /// Files dropped on the Combine files tab join its list in the order dropped (see + /// [`Self::add_dropped_to_combine`]); a folder adds the files in it and its subfolders. + pub(crate) fn drop_into_combine(&mut self, files: Vec) { + let mut incoming = Vec::new(); + for f in files { + let name = dropped_name(&f); + // A file on disk is read from there, with when it was last modified. + #[cfg(not(target_arch = "wasm32"))] + if let Some(path) = f.path.as_deref().filter(|p| p.is_absolute()) { + if path.is_dir() { + // After the files dropped before it. + self.add_dropped_to_combine(std::mem::take(&mut incoming)); + self.add_folder_to_combine(path, true); + continue; + } + let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok(); + match std::fs::read(path) { + Ok(bytes) => incoming.push(crate::combine_ui::Incoming { modified, ..crate::combine_ui::Incoming::new(name, bytes) }), + Err(e) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]), + } + continue; + } + // A drop that carries only bytes (no path) is taken as it is. + match &f.bytes { + Some(bytes) => incoming.push(crate::combine_ui::Incoming::new(name, bytes.to_vec())), + None => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", tl!("the file has no content"))]), + } + } + self.add_dropped_to_combine(incoming); } /// `doc` as it is now, for a pick that will edit it. @@ -536,27 +359,6 @@ impl PdfCraftApp { false } - /// Handle files picked asynchronously. - pub(crate) fn process_file_requests(&mut self) { - let pending: Vec<_> = self.requests.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default(); - for FileRequest { purpose, target, files, dropped } in pending { - if !self.still_pick_target(target) { - continue; - } - // Last-resort guard (AGENTS.md §4), as for desktop picks and commands. - let used = pdfcraft_engine::guard(|| { - if dropped { - self.add_dropped_to_combine(files.into_iter().map(|(name, bytes)| crate::combine_ui::Incoming::new(name, bytes)).collect()); - } else { - self.use_files(purpose, files); - } - }); - if let Err(m) = used { - self.notify_fmt("That didn't work: an internal error stopped it ({m}).", &[("m", m.as_str())]); - } - } - } - /// Use picked files (also the entry point for tests and automation). pub fn use_files(&mut self, purpose: FilePurpose, files: Vec<(String, Vec)>) { match purpose { @@ -567,21 +369,15 @@ impl PdfCraftApp { return; } let Some((index, id)) = self.active_ids() else { return }; - let Some(mut ed) = self.views[index].line_editor.clone().filter(|ed| ed.page == page) else { return }; + let Some(mut ed) = self.views.get(index).and_then(|v| v.line_editor.clone()).filter(|ed| ed.page == page) else { return }; // The font just loaded is the one the user wants: apply it to the paragraph, as // choosing it from the document-font menu does, instead of only registering it (#2591). let resource = self.session.get(id).and_then(|doc| { doc.text_editor_fonts(page).into_iter().find(|f| f.bytes == *bytes && !f.resource.starts_with("PCApproved")).map(|f| f.resource) }); - let ctx = self.ctx.clone(); if resource.is_some() { ed.font_resource = resource; - self.apply_line_format(index, ed, ctx.as_ref()); - } else if let Some(doc) = self.session.get(id) - && let Some(ctx) = ctx - { - ed.fonts = crate::edit_text_ui::install_source_fonts(&ctx, doc, page); - self.views[index].line_editor = Some(ed); + self.apply_line_format(index, ed); } } FilePurpose::Combine => self.stage_combine(files), @@ -593,10 +389,7 @@ impl PdfCraftApp { } FilePurpose::Ocr => self.ocr_files(files), FilePurpose::CreateMultiple => self.stage_create_multiple(files.into_iter().map(Ok)), - FilePurpose::CreateMultipleSeparate => { - let dir = self.export_dir_override.as_ref().map(std::path::PathBuf::from); - self.stage_create_separate(files.into_iter().map(Ok), dir); - } + FilePurpose::CreateMultipleSeparate => self.ask_separate_folder(files.into_iter().map(Ok)), FilePurpose::RedactWords => { let Some((name, bytes)) = files.into_iter().next() else { return }; if bytes.len() > crate::redact_ui::MAX_WORD_LIST_BYTES { @@ -606,6 +399,8 @@ impl PdfCraftApp { self.redact_search.words = pdfcraft_engine::redact_word_list(&pdfcraft_engine::decode_text(&bytes)).join("\n"); self.redact_search.mode = crate::redact_ui::SearchMode::Words; } + // Picked by the signing tools with their own requests. + FilePurpose::DigitalId | FilePurpose::SignGraphic | FilePurpose::SignedCopy => {} } } @@ -617,29 +412,6 @@ impl PdfCraftApp { self.pick_files(FilePurpose::ReplacePages, false); } - /// Open the Replace Pages dialog for `bytes`, replacing the selection (or the current page). - pub fn start_replace(&mut self, name: String, bytes: Vec) { - let Some((i, id)) = self.active_ids() else { return }; - let bytes = Arc::new(bytes); - let src_pages = match self.session.replace_source(id, &name, &bytes) { - Ok(n) => n, - Err(e) => { - self.notify_fmt("Couldn't use {name}: {e}", &[("name", &name), ("e", &e.to_string())]); - return; - } - }; - let pages = self.views[i].target_pages(); - let (from, to) = (pages.first().map_or(1, |p| p + 1), pages.last().map_or(1, |p| p + 1)); - let target = self.pick_target(self.active_ids().map(|(_, id)| id)); - self.replace_draft = Some(ReplaceDraft { name, bytes, src_pages, from, to, src_from: 1, pages, range_edited: false, target }); - self.dialog = Some(crate::Dialog::ReplacePages); - } - - /// Insert all pages of a file after the organize selection (or the current page). - pub fn insert_pages_from(&mut self, name: &str, bytes: Vec) { - self.insert_files(vec![(name.to_string(), bytes)]); - } - /// Insert the pages of `files` (PDFs, images, text), in order, at the gap a "+" in the page /// grid chose, or else after the selection (or the current page); then select them. pub fn insert_files(&mut self, files: Vec<(String, Vec)>) { @@ -688,25 +460,15 @@ impl PdfCraftApp { } } - /// Show Extract pages, its file name filled in with the active document's (#737) and no - /// page ranges typed, so it takes the selected pages until some are (#3593). - pub fn open_extract_dialog(&mut self) { - self.extract_draft.name = - self.active_ids().and_then(|(_, id)| self.session.get(id)).map(|d| strip_pdf(&d.name).to_string()).unwrap_or_default(); - self.extract_draft.pages.clear(); - self.dialog = Some(crate::Dialog::Extract); - } - /// Copy the pages typed in Extract pages, else the selected pages (or the current page), into /// a new unsaved document tab. - pub fn extract_selection(&mut self) { + pub fn extract_selection(&mut self, opts: ExtractOptions) { // What's typed in a form field is part of the document (#166). if !self.commit_form_typing() { return; } let Some((i, id)) = self.active_ids() else { return }; - let opts = self.extract_draft.clone(); - let pages = match opts.pages_to_extract(self.views[i].target_pages(), self.views[i].page_count()) { + let pages = match pages_to_extract(&opts.pages, self.views[i].target_pages(), self.views[i].page_count()) { Ok(pages) => pages, Err(e) => { self.notify_fmt("Couldn't extract pages: {e}", &[("e", &e)]); @@ -718,8 +480,8 @@ impl PdfCraftApp { doomed.sort_unstable(); let stem = self.session.get(id).map(|d| strip_pdf(&d.name).to_string()).unwrap_or_default(); // The name typed in the dialog (#737), else the document's. - let chosen = file_stem_from_user(&opts.name); - let renamed = !chosen.is_empty() && chosen != file_stem_from_user(&stem); + let chosen = safe_file_stem(&opts.name, "pdf"); + let renamed = !chosen.is_empty() && chosen != safe_file_stem(&stem, "pdf"); let base = if chosen.is_empty() { stem.clone() } else { chosen }; if opts.separate { // Each page as its own file, in a chosen folder. @@ -783,17 +545,19 @@ impl PdfCraftApp { /// [`Self::write_files`], then `after` once every file is written: now, or on a later frame /// when the user chooses the folder. `after` never runs when writing fails or is cancelled. - /// Every name must be a plain file name ([`is_plain_file_name`]); otherwise nothing is written. - pub(crate) fn write_files_then(&mut self, named: Vec<(String, Arc>)>, title: &str, after: impl FnOnce(&mut Self) + Send + 'static) { + /// Every name must be a plain file name ([`is_plain_file_name`]); otherwise nothing is written + /// and no folder is asked for. + pub(crate) fn write_files_then(&mut self, named: Vec<(String, Arc>)>, title: &str, after: impl FnOnce(&mut Self) + 'static) { if let Some((name, _)) = named.iter().find(|(name, _)| !is_plain_file_name(name)) { self.notify_fmt("Couldn't write {name}: {e}", &[("name", name), ("e", tl!("the name is not a plain file name"))]); return; } #[cfg(not(target_arch = "wasm32"))] { - let write = move |app: &mut Self, dir: std::path::PathBuf| { + let write = move |app: &mut Self, picked: Picked| { + let Some(dir) = picked.first_path() else { return }; for (name, bytes) in &named { - if let Err(e) = crate::editing::write_atomically(&dir.join(name).to_string_lossy(), bytes) { + if let Err(e) = app.host.files().write(&dir.join(name), bytes, WriteIntent::SaveAs) { app.notify_fmt("Couldn't write {name}: {e}", &[("name", name), ("e", &e.to_string())]); return; } @@ -805,18 +569,13 @@ impl PdfCraftApp { } after(app); }; - match &self.export_dir_override { - Some(d) => write(self, std::path::PathBuf::from(d)), - None => { - self.ask_one(crate::pickers::Ask::Folder(rfd::AsyncFileDialog::new().set_title(title)), None, write); - } - } + self.pick_file(PickRequest::folder("export.folder").title(title), None, write); } + // The web has no folder to ask for: each file is a download. #[cfg(target_arch = "wasm32")] { - let _ = title; for (name, bytes) in &named { - if let Err(e) = crate::editing::download(name, bytes) { + if let Err(e) = self.host.files().write(std::path::Path::new(name), bytes, WriteIntent::SaveAs) { self.notify_fmt("Couldn't download {name}: {e}", &[("name", name), ("e", &e.to_string())]); return; } @@ -825,23 +584,17 @@ impl PdfCraftApp { } } - /// Pages ▸ Rotate Pages with the dialog's range and filters. - pub fn rotate_with_draft(&mut self) { - let Some((i, id)) = self.active_ids() else { return }; + /// Pages ▸ Rotate Pages: rotate the pages of `base` that pass the parity and orientation + /// filters. + pub fn rotate_pages(&mut self, degrees: i64, base: Vec, parity: pdfcraft_engine::PageParity, orientation: pdfcraft_engine::PageOrientation) { + let Some((_, id)) = self.active_ids() else { return }; let Some(doc) = self.session.get(id) else { return }; - let n = doc.info.pages.len(); - let d = self.rotate_draft.clone(); - let base: Vec = match d.which { - 1 => self.views[i].target_pages(), - 2 => (d.from.max(1) - 1..d.to.min(n)).collect(), - _ => (0..n).collect(), - }; - let pages = pdfcraft_engine::filter_pages(&doc.info, &base, d.parity, d.orientation); + let pages = pdfcraft_engine::filter_pages(&doc.info, &base, parity, orientation); if pages.is_empty() { self.notify_tr("No pages match those choices"); return; } - self.apply_edit(pdfcraft_engine::Edit::RotatePages { pages, degrees: d.degrees }); + self.apply_edit(pdfcraft_engine::Edit::RotatePages { pages, degrees }); } /// Split the active document and write the parts: into a chosen folder (desktop, written on @@ -905,30 +658,68 @@ impl PdfCraftApp { } } + /// Open `bytes` as a new unsaved document named `name` and say `message`. pub(crate) fn open_created(&mut self, name: &str, bytes: Arc>, message: &str) { - match self.session.open_new(name, bytes) { - Ok(id) => { - // The reading-colours preference is app-wide: the newly created document starts with it. - self.session.set_reading_colors(id, self.reading_colors); - let Some(doc) = self.session.get(id) else { return }; - let mut view = crate::DocView::new(id, &doc.info, self.view_defaults); - if self.full_screen { - view.enter_presentation(); - } - self.views.push(view); - self.active = Some(self.views.len() - 1); - self.notify_tr(message); - } - Err(e) => self.notify_fmt("Couldn't open the result: {e}", &[("e", &e.to_string())]), + match self.open_new_document(name, bytes) { + Ok(()) => self.notify_tr(message), + Err(e) => self.notify_fmt("Couldn't open the result: {e}", &[("e", &e)]), } } + + /// The fonts installed on this machine, scanned off the UI thread: `None` while the scan + /// runs (and it is started if none is). `reload` rescans to find newly installed fonts or to + /// retry a failed scan. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn installed_document_fonts(&mut self, reload: bool) -> Option<&InstalledFonts> { + use pdfcraft_engine::text_fonts; + if let Some(done) = self.font_scan.try_recv() { + let catalog = Arc::new(craft::font_catalog::Catalog::of_files(done.result.iter().map(|f| f.path.clone()).collect())); + self.document_fonts = Some(InstalledFonts { files: done.result, catalog }); + } + if reload { + self.document_fonts = None; + } + if self.document_fonts.is_none() && !self.font_scan.contains(&()) { + self.submit_scan(|| text_fonts::discover(&text_fonts::installed_directories())); + } + self.document_fonts.as_ref() + } + + /// Run `scan` as the font scan job. A scan that panics ends as an empty list: the queue + /// delivers nothing for a panicked job, which would leave the menu waiting for ever. + #[cfg(not(target_arch = "wasm32"))] + fn submit_scan(&mut self, scan: impl FnOnce() -> Vec + Send + 'static) { + use craft::host::queue::Priority; + self.font_scan.submit((), Priority::BACKGROUND, move |_| pdfcraft_engine::guard(scan).unwrap_or_default()); + } } pub(crate) fn strip_pdf(name: &str) -> &str { name.strip_suffix(".pdf").or_else(|| name.strip_suffix(".PDF")).unwrap_or(name) } +/// The folder holding the document at `path`, where a save picker starts the first time. +fn document_folder(path: Option<&str>) -> Option { + path.and_then(|p| std::path::Path::new(p).parent()).map(std::path::Path::to_path_buf) +} + impl PdfCraftApp { + /// The files a pick answered, read: paths through the host's file service, browser contents + /// as they are. A file that can't be read gives its name and why. + fn read_picked(&self, picked: Picked) -> Result)>, (String, String)> { + match picked { + Picked::Paths(paths) => paths + .iter() + .map(|p| { + let name = name_of(p); + self.host.files().read(p).map(|bytes| (name.clone(), bytes)).map_err(|e| (name, e.to_string())) + }) + .collect(), + Picked::Contents(files) => Ok(files), + _ => Ok(Vec::new()), + } + } + /// Prepare a form ▸ Import data: XFDF, FDF, XML, CSV or text. pub fn import_data_dialog(&mut self) { self.import_dialog(false); @@ -941,40 +732,23 @@ impl PdfCraftApp { } fn import_dialog(&mut self, pdf: bool) { - #[cfg(not(target_arch = "wasm32"))] - { - let mut extensions = vec!["xfdf", "fdf", "xml", "xdp", "csv", "txt"]; - if pdf { - extensions.insert(2, "pdf"); - } - let import = |app: &mut Self, path: std::path::PathBuf| match std::fs::read(&path) { - Ok(bytes) => { - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - app.apply_edit(pdfcraft_engine::Edit::ImportData { name, bytes: std::sync::Arc::new(bytes) }); - } - Err(e) => app.notify_fmt("Couldn't read {name}: {e}", &[("name", &path.display().to_string()), ("e", &e.to_string())]), - }; - match self.save_override.clone() { - Some(p) if extensions.iter().any(|e| p.ends_with(&format!(".{e}"))) => import(self, p.into()), - Some(_) => {} - None => { - let dialog = rfd::AsyncFileDialog::new() - .add_filter_any_case(tl!("Comment and form data").to_string(), &extensions) - .set_title(tl!("Import data").to_string()); - let target = self.active_ids().map(|(_, id)| id); - self.ask_one(crate::pickers::Ask::File(dialog), target, import); + let mut extensions = vec!["xfdf", "fdf", "xml", "xdp", "csv", "txt"]; + if pdf { + extensions.insert(2, "pdf"); + } + let request = PickRequest::open("import.data").title(tl!("Import data")).filter(tl!("Comment and form data"), &extensions); + let target = self.pick_target(self.active_ids().map(|(_, id)| id)); + self.pick_file(request, target, |app, picked| match app.read_picked(picked) { + Ok(files) => { + for (name, bytes) in files { + app.apply_edit(pdfcraft_engine::Edit::ImportData { name, bytes: Arc::new(bytes) }); } } - } - #[cfg(target_arch = "wasm32")] - { - let _ = pdf; - self.notify_tr("Importing data arrives on the web with file pickers for data files"); - } + Err((name, e)) => app.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e)]), + }); } - /// Export all comments / form data: the format follows the file name's extension. - /// Export a PDF ▸ Word, HTML or RTF: ask where (`save_override` in tests), then write. + /// Export a PDF ▸ Word, HTML or RTF: ask where, then write. pub fn export_office_dialog(&mut self, format: pdfcraft_engine::compare::OfficeFormat) { // What's typed in a form field is part of the document (#166). if !self.commit_form_typing() { @@ -987,94 +761,54 @@ impl PdfCraftApp { let Some(doc) = self.session.get(id) else { return }; let stem = doc.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_string(); let ext = format.extension(); - let folder = doc.path.clone(); + let folder = document_folder(doc.path.as_deref()); let bytes = doc.export_office(format); - #[cfg(not(target_arch = "wasm32"))] - { - let write = move |app: &mut Self, path: std::path::PathBuf| match crate::editing::write_atomically(&path.to_string_lossy(), &bytes) { - Ok(()) => app.notify_fmt("Exported to {path}", &[("path", &path.display().to_string())]), + let mut request = + PickRequest::save("export.office").title(tl!("Export")).filter(ext.to_uppercase(), &[ext]).file_name(format!("{stem}.{ext}")); + if let Some(folder) = folder { + request = request.default_directory(folder); + } + self.pick_file(request, None, move |app, picked| { + let Some(path) = picked.first_path() else { return }; + match app.host.files().write(&path, &bytes, WriteIntent::SaveAs) { + Ok(_) => app.notify_fmt("Exported to {path}", &[("path", &path.display().to_string())]), Err(e) => app.notify_fmt("Couldn't write {name}: {e}", &[("name", &path.display().to_string()), ("e", &e.to_string())]), - }; - match self.save_override.clone() { - Some(p) => write(self, p.into()), - None => { - let dialog = rfd::AsyncFileDialog::new() - .set_title(tl!("Export").to_string()) - .add_filter_any_case(ext.to_uppercase(), &[ext]) - .set_file_name(format!("{stem}.{ext}")); - let dialog = crate::editing::in_document_folder(dialog, folder.as_deref()); - self.ask_one(crate::pickers::Ask::Save(dialog), None, write); - } } - } - #[cfg(target_arch = "wasm32")] - if let Err(e) = crate::editing::download(&format!("{stem}.{ext}"), &bytes) { - self.notify_error(e); - } + }); } /// Forms ▸ Merge data files into spreadsheet: choose data files (FDF, XFDF or filled-in PDF /// forms), then where to save the CSV. pub fn merge_data_dialog(&mut self) { - #[cfg(not(target_arch = "wasm32"))] - { - let dialog = rfd::AsyncFileDialog::new() - .set_title(tl!("Select data files to merge").to_string()) - .add_filter_any_case(tl!("Form data and PDF forms").to_string(), &["fdf", "xfdf", "pdf"]); - self.ask(crate::pickers::Ask::Files(dialog), None, |app, paths| { - let mut files = Vec::new(); - for p in paths { - let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - match std::fs::read(&p) { - Ok(b) => files.push((name, b)), - Err(e) => return app.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]), - } - } - if !files.is_empty() { - // Asks where to save: a second picker, now that the first one has closed. - app.merge_data_files(files); - } - }); - } - #[cfg(target_arch = "wasm32")] - self.notify_tr("Merging data files needs the desktop app"); + let request = + PickRequest::open_many("merge.data").title(tl!("Select data files to merge")).filter(tl!("Form data and PDF forms"), &["fdf", "xfdf", "pdf"]); + self.pick_file(request, None, |app, picked| match app.read_picked(picked) { + // Asks where to save: a second picker, now that the first one has closed. + Ok(files) if !files.is_empty() => app.merge_data_files(files), + Ok(_) => {} + Err((name, e)) => app.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e)]), + }); } - /// Merge the given data files and save the spreadsheet (asks where; `save_override` in tests). + /// Merge the given data files and save the spreadsheet (asks where). pub fn merge_data_files(&mut self, files: Vec<(String, Vec)>) { let csv = match pdfcraft_engine::merge_data_files(&files) { Ok(c) => c, Err(e) => return self.notify_error(e), }; - #[cfg(not(target_arch = "wasm32"))] - { - let count = files.len(); - let write = - move |app: &mut Self, path: std::path::PathBuf| match crate::editing::write_atomically(&path.to_string_lossy(), csv.as_bytes()) { - Ok(()) => { - if count == 1 { - app.notify_fmt("Merged 1 file into {path}", &[("path", &path.display().to_string())]); - } else { - app.notify_fmt("Merged {n} files into {path}", &[("n", &count.to_string()), ("path", &path.display().to_string())]); - } - } - Err(e) => app.notify_fmt("Couldn't write {name}: {e}", &[("name", &path.display().to_string()), ("e", &e.to_string())]), - }; - match self.save_override.clone() { - Some(p) => write(self, p.into()), - None => { - let dialog = rfd::AsyncFileDialog::new() - .set_title(tl!("Save the spreadsheet").to_string()) - .add_filter_any_case("CSV", &["csv"]) - .set_file_name("report.csv"); - self.ask_one(crate::pickers::Ask::Save(dialog), None, write); - } + let count = files.len(); + let request = PickRequest::save("export.data").title(tl!("Save the spreadsheet")).filter("CSV", &["csv"]).file_name("report.csv"); + self.pick_file(request, None, move |app, picked| { + let Some(path) = picked.first_path() else { return }; + match app.host.files().write(&path, csv.as_bytes(), WriteIntent::SaveAs) { + Ok(_) if count == 1 => app.notify_fmt("Merged 1 file into {path}", &[("path", &path.display().to_string())]), + Ok(_) => app.notify_fmt("Merged {n} files into {path}", &[("n", &count.to_string()), ("path", &path.display().to_string())]), + Err(e) => app.notify_fmt("Couldn't write {name}: {e}", &[("name", &path.display().to_string()), ("e", &e.to_string())]), } - } - #[cfg(target_arch = "wasm32")] - let _ = crate::editing::download("report.csv", csv.as_bytes()); + }); } + /// Export all comments / form data: the format follows the file name's extension. pub fn export_data_dialog(&mut self, comments: bool, fields: bool) { // What's typed in a form field is part of the document (#166). if !self.commit_form_typing() { @@ -1083,183 +817,124 @@ impl PdfCraftApp { let Some((_, id)) = self.active_ids() else { return }; let Some(doc) = self.session.get(id) else { return }; let stem = doc.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_string(); - #[cfg(not(target_arch = "wasm32"))] - { - let folder = doc.path.clone(); - let xfa = doc.info.xfa.is_some(); - let write = move |app: &mut Self, path: std::path::PathBuf| { - // Include what was typed while the save panel was open (#166). - if !app.commit_typing_in(id) { - return; - } - let ext = path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); - let format = pdfcraft_engine::DataFormat::from_extension(&ext).unwrap_or(pdfcraft_engine::DataFormat::Xfdf); - match app.session.export_data(id, format, comments, fields) { - Ok(bytes) => match crate::editing::write_atomically(&path.to_string_lossy(), &bytes) { - Ok(()) => app.notify_fmt("Exported to {path}", &[("path", &path.display().to_string())]), - Err(e) => app.notify_fmt("Couldn't write {name}: {e}", &[("name", &path.display().to_string()), ("e", &e.to_string())]), - }, - Err(e) => app.notify_error(e), - } - }; - match self.save_override.clone() { - Some(p) => write(self, p.into()), - None => { - let title = if comments { tl!("Export comments") } else { tl!("Export form data") }; - let d = rfd::AsyncFileDialog::new().set_title(title).set_file_name(format!("{stem}.xfdf")); - let d = if comments { - d.add_filter_any_case("XFDF", &["xfdf"]).add_filter_any_case("FDF", &["fdf"]) - } else if xfa { - // An XFA form's data, as Acrobat exports it, first. - d.set_file_name(format!("{stem}.xml")) - .add_filter_any_case("XML", &["xml"]) - .add_filter_any_case("XDP", &["xdp"]) - .add_filter_any_case("XFDF", &["xfdf"]) - .add_filter_any_case("FDF", &["fdf"]) - .add_filter_any_case("CSV", &["csv"]) - .add_filter_any_case(tl!("Text").to_string(), &["txt"]) - } else { - d.add_filter_any_case("XFDF", &["xfdf"]) - .add_filter_any_case("FDF", &["fdf"]) - .add_filter_any_case("XML", &["xml"]) - .add_filter_any_case("CSV", &["csv"]) - .add_filter_any_case(tl!("Text").to_string(), &["txt"]) - }; - let d = crate::editing::in_document_folder(d, folder.as_deref()); - self.ask_one(crate::pickers::Ask::Save(d), None, write); - } - } + let folder = document_folder(doc.path.as_deref()); + let xfa = doc.info.xfa.is_some(); + let title = if comments { tl!("Export comments") } else { tl!("Export form data") }; + let mut request = PickRequest::save("export.data").title(title).file_name(format!("{stem}.xfdf")); + request = if comments { + request.filter("XFDF", &["xfdf"]).filter("FDF", &["fdf"]) + } else if xfa { + // An XFA form's data, as Acrobat exports it, first. + request + .file_name(format!("{stem}.xml")) + .filter("XML", &["xml"]) + .filter("XDP", &["xdp"]) + .filter("XFDF", &["xfdf"]) + .filter("FDF", &["fdf"]) + .filter("CSV", &["csv"]) + .filter(tl!("Text"), &["txt"]) + } else { + request.filter("XFDF", &["xfdf"]).filter("FDF", &["fdf"]).filter("XML", &["xml"]).filter("CSV", &["csv"]).filter(tl!("Text"), &["txt"]) + }; + if let Some(folder) = folder { + request = request.default_directory(folder); } - #[cfg(target_arch = "wasm32")] - match self.session.export_data(id, pdfcraft_engine::DataFormat::Xfdf, comments, fields) { - Ok(bytes) => { - let _ = crate::editing::download(&format!("{stem}.xfdf"), &bytes); + self.pick_file(request, None, move |app, picked| { + let Some(path) = picked.first_path() else { return }; + // Include what was typed while the save panel was open (#166). + if !app.commit_typing_in(id) { + return; } - Err(e) => self.notify_error(e), - } + let ext = path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default(); + let format = pdfcraft_engine::DataFormat::from_extension(&ext).unwrap_or(pdfcraft_engine::DataFormat::Xfdf); + match app.session.export_data(id, format, comments, fields) { + Ok(bytes) => match app.host.files().write(&path, &bytes, WriteIntent::SaveAs) { + Ok(_) => app.notify_fmt("Exported to {path}", &[("path", &path.display().to_string())]), + Err(e) => app.notify_fmt("Couldn't write {name}: {e}", &[("name", &path.display().to_string()), ("e", &e.to_string())]), + }, + Err(e) => app.notify_error(e), + } + }); } } #[cfg(test)] -mod stem_tests { - use super::{attachment_file_name, file_stem_from_user, is_plain_file_name}; +mod tests { + use std::path::PathBuf; + use std::sync::Arc; - #[test] - fn user_file_names_stay_inside_the_folder_and_writable_everywhere() { - assert_eq!(file_stem_from_user("../../etc/passwd"), ".._.._etc_passwd"); - assert_eq!(file_stem_from_user(".."), ""); - assert_eq!(file_stem_from_user("Report.PDF"), "Report"); - // Windows device names, in any case and with any extension, get a prefix. - assert_eq!(file_stem_from_user("nul"), "_nul"); - assert_eq!(file_stem_from_user("COM1.pdf"), "_COM1"); - assert_eq!(file_stem_from_user("lpt9.tar"), "_lpt9.tar"); - assert_eq!(file_stem_from_user("COM10"), "COM10"); - assert_eq!(file_stem_from_user("Console"), "Console"); - // At most 200 bytes, cut on a character boundary. - let long = file_stem_from_user(&"文".repeat(300)); - assert!(long.len() <= 200 && long.chars().all(|c| c == '文'), "{}", long.len()); - } - #[test] - fn attachment_save_name_removes_bidi_without_hiding_the_extension() { - assert_eq!(attachment_file_name("invoice\u{202e}fdp.exe"), "invoicefdp.exe"); - for c in [ - '\u{061c}', '\u{200e}', '\u{200f}', '\u{202a}', '\u{202b}', '\u{202c}', '\u{202d}', '\u{202e}', '\u{2066}', '\u{2067}', '\u{2068}', - '\u{2069}', - ] { - assert_eq!(attachment_file_name(&format!("a{c}b.pdf")), "ab.pdf"); - } - } - #[test] - fn attachment_save_name_preserves_ordinary_unicode_and_extensions() { - for name in ["report.pdf", "archive.tar.gz", "مرحبا.pdf", "שלום.txt", "資料.pdf", "می\u{200c}روم.txt", "👩\u{200d}💻.png", "COM10.txt"] - { - assert_eq!(attachment_file_name(name), name); - } - } - #[test] - fn attachment_save_name_handles_controls_paths_and_device_names() { - assert_eq!(attachment_file_name("a\u{0}\n\u{85}b.pdf"), "ab.pdf"); - assert_eq!(attachment_file_name("../a\\b:c*?\"<>|.pdf"), ".._a_b_c______.pdf"); - for name in ["NUL.tar.gz", "con.txt", "COM1.exe", "LPT9.txt", "COM¹.txt", "LPT³.pdf"] { - assert_eq!(attachment_file_name(name), format!("_{name}")); - } - } - #[test] - fn attachment_save_name_has_a_stable_nonempty_fallback() { - for name in ["", " ", ".", "..", " . . ", "\u{202e}", "\u{0}\n"] { - assert_eq!(attachment_file_name(name), "attachment"); - } - assert_eq!(attachment_file_name(" report.pdf . \u{2003}."), "report.pdf"); - for name in ["invoice\u{202e}fdp.exe", "../a.pdf", "NUL.txt", " . . ", "report.pdf . ", "資料.pdf"] { - let once = attachment_file_name(name); - assert_eq!(attachment_file_name(&once), once); - } - } + use craft::host::{AppInfo, Host, ManualJobs, Picked, ScriptedFiles, Wake}; + use craft::platform::clipboard::{Clipboard, EventClipboard}; + use craft::platform::open::FileIntake; + use craft::platform::watch::FileWatch; - #[test] - fn plain_file_names_do_not_end_in_a_dot_or_a_space() { - for good in ["report.pdf", "report", ".hidden", "a b.pdf", "資料.pdf"] { - assert!(is_plain_file_name(good), "{good}"); - } - for bad in ["report.", "report.pdf.", "report.pdf ", "report. . ", " ", "...", ". "] { - assert!(!is_plain_file_name(bad), "{bad:?}"); - } + use crate::{AppServices, PdfCraftApp}; + + fn app_with(files: Arc, jobs: Arc) -> PdfCraftApp { + let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).jobs(jobs).build(); + let wake = Wake::none(); + let clipboard = Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0))); + let (intake, _) = FileIntake::new(wake.clone()); + let watch = FileWatch::new(wake.clone()).inline(); + let services = AppServices::new(wake, clipboard, None, None, intake, watch); + // PLAN: assumed `with_host(Arc, AppServices)` and `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (pdf-hub-w1, L-207) + let mut app = PdfCraftApp::with_host(Arc::new(host), services); + app.set_option("language", "en").unwrap(); + app } #[test] fn write_files_refuses_names_that_leave_the_folder() { - let dir = std::env::temp_dir().join(format!("pdfcraft-write-files-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let out = dir.join("a").join("out"); - std::fs::create_dir_all(&out).unwrap(); - let absolute = dir.join("abs.pdf").to_string_lossy().into_owned(); - let mut app = crate::PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.export_dir_override = Some(out.to_string_lossy().into_owned()); - for bad in ["../x.pdf", "..", ".", "", "sub/x.pdf", "sub\\x.pdf", "C:x.pdf", "x.pdf.", absolute.as_str()] { - assert!(!is_plain_file_name(bad), "{bad}"); + let out = PathBuf::from("/scripted/out"); + let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![out.clone()])])); + let mut app = app_with(files.clone(), Arc::new(ManualJobs::new())); + let absolute = "/scripted/abs.pdf"; + let pdf = || Arc::new(b"%PDF".to_vec()); + for bad in ["../x.pdf", "..", ".", "", "sub/x.pdf", "sub\\x.pdf", "C:x.pdf", "x.pdf.", absolute] { // A plain name first: nothing is written when any name in the batch is refused. - app.write_files(&[("ok.pdf".into(), std::sync::Arc::new(b"%PDF".to_vec())), (bad.into(), std::sync::Arc::new(b"%PDF".to_vec()))], "t"); + app.write_files(&[("ok.pdf".into(), pdf()), (bad.into(), pdf())], "t"); assert!(app.toast.as_ref().is_some_and(|t| t.0.contains("not a plain file name")), "{bad}"); } - let names: Vec<_> = walk(&dir); - assert!(names.is_empty(), "{names:?}"); - app.write_files(&[("x.pdf".into(), std::sync::Arc::new(b"%PDF".to_vec()))], "t"); - assert_eq!(walk(&dir), vec![out.join("x.pdf")]); - let _ = std::fs::remove_dir_all(&dir); + assert!(files.requests().is_empty(), "no folder is asked for"); + assert!(files.file(&out.join("ok.pdf")).is_none()); + app.write_files(&[("x.pdf".into(), pdf())], "t"); + // PLAN: assumed `process_picks(&mut self)` (pdf-shell-w14) hands the answer to the continuation + app.process_picks(); + assert_eq!(files.requests().len(), 1); + assert_eq!(files.file(&out.join("x.pdf")).as_deref(), Some(&b"%PDF"[..])); } - fn walk(dir: &std::path::Path) -> Vec { - let mut out = Vec::new(); - for entry in std::fs::read_dir(dir).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { out.extend(walk(&path)) } else { out.push(path) } - } - out + fn font(name: &str) -> pdfcraft_engine::text_fonts::FontFile { + pdfcraft_engine::text_fonts::FontFile { path: format!("{name}.ttf").into(), family: name.into(), face: name.into() } } -} -#[cfg(all(test, not(target_arch = "wasm32")))] -mod font_scan_tests { #[test] - fn completed_and_failed_font_scans_can_be_reloaded_without_duplicate_workers() { - let mut cache = super::FontScanCache::default(); - assert!(cache.begin(false)); - assert!(!cache.begin(true), "a reload during discovery must not start another worker"); - cache.finish(Vec::new()); - assert!(!cache.begin(false), "reuse a finished scan until explicitly reloaded"); - assert!(cache.begin(true), "an empty or failed scan can be retried"); - cache.finish(vec![pdfcraft_engine::text_fonts::FontFile { - path: "installed.ttf".into(), - family: "Installed".into(), - face: "Installed".into(), - }]); - assert!(cache.begin(true), "a populated scan can discover newly installed fonts"); - assert!(cache.files.is_none()); + fn installed_fonts_are_listed_once_and_a_reload_lists_them_again() { + let jobs = Arc::new(ManualJobs::new()); + let mut app = app_with(Arc::new(ScriptedFiles::new()), jobs.clone()); + assert!(app.installed_document_fonts(false).is_none()); + assert_eq!(jobs.waiting(), 1, "the first call starts one scan"); + assert!(app.installed_document_fonts(false).is_none()); + assert_eq!(jobs.waiting(), 1, "a second call while it waits starts no other"); + jobs.run_all(); + // The scan this test controls replaces the real one's result. + app.submit_scan(|| vec![font("Test")]); + jobs.run_all(); + let listed = app.installed_document_fonts(false); + assert!(listed.is_some()); + let _ = listed; + assert!(app.installed_document_fonts(true).is_none(), "a reload clears the list"); + assert_eq!(jobs.waiting(), 1, "and starts one more scan"); } #[test] fn a_panicking_font_scan_finishes_with_an_empty_list() { - assert!(super::discover_fonts_safely(|| panic!("synthetic font scan failure")).is_empty()); + let jobs = Arc::new(ManualJobs::new()); + let mut app = app_with(Arc::new(ScriptedFiles::new()), jobs.clone()); + app.submit_scan(|| panic!("synthetic font scan failure")); + jobs.run_all(); + let listed = app.installed_document_fonts(false).expect("the scan ended"); + assert!(listed.files.is_empty()); + assert_eq!(jobs.waiting(), 0, "no second scan is started"); } }