From 3964cc87a5a3e9693ea99fd3a5da118f56cace8a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:28 -0500 Subject: [PATCH] pdf-workflows-w10: net change of 2 commits - pdf-workflows-w10: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot) - pdf-workflows-w10: review fixes (review-1) --- crates/engine/src/document.rs | 20 + crates/ui-egui/src/workflows/optimize_ui.rs | 1037 +++++++++++-------- crates/ui-egui/tests/it/optimize.rs | 66 ++ 3 files changed, 711 insertions(+), 412 deletions(-) create mode 100644 crates/ui-egui/tests/it/optimize.rs diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 8a166330b9..ae374f6c53 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -193,6 +193,21 @@ pub struct TextNotice { pub redrawn_elsewhere: bool, } +/// A measurement of how the file's bytes are spent, owning what it reads so it can run off the UI thread +/// ([`Document::space_audit_job`]). +pub struct SpaceAuditJob { + /// The document as the editor holds it; `None` when the document can't be read for editing. + cos: Option, + size: u64, +} + +impl SpaceAuditJob { + /// The measurement [`Document::audit_space`] makes; empty when the document can't be read for editing. + pub fn run(self) -> Vec { + self.cos.map(|cos| optimize::audit_space(&cos, self.size)).unwrap_or_default() + } +} + impl std::fmt::Display for TextNotice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let ch = format!("\"{}\" (U+{:04X})", self.ch.escape_debug(), u32::from(self.ch)); @@ -290,6 +305,11 @@ impl Document { self.editor.as_ref().map(|e| optimize::audit_space(&e.cos, self.bytes.len() as u64)).unwrap_or_default() } + /// [`Self::audit_space`] as a job over a copy of the document's state, to run in the background. + pub fn space_audit_job(&self) -> SpaceAuditJob { + SpaceAuditJob { cos: self.editor.as_ref().map(|e| e.cos.clone()), size: self.bytes.len() as u64 } + } + /// The backdrop `page` (0-based) paints itself, which hides a background (Add Background). pub fn page_backdrop(&self, page: usize) -> Option { self.editor.as_ref().and_then(|e| pdfcraft_edit::page_backdrop(&e.cos, page).ok().flatten()) diff --git a/crates/ui-egui/src/workflows/optimize_ui.rs b/crates/ui-egui/src/workflows/optimize_ui.rs index 3df48f777e..16e5b31aa8 100644 --- a/crates/ui-egui/src/workflows/optimize_ui.rs +++ b/crates/ui-egui/src/workflows/optimize_ui.rs @@ -1,51 +1,564 @@ //! Optimize PDF ▸ Advanced optimization (Acrobat's PDF Optimizer): Images, Discard Objects, //! Discard User Data and Clean Up panels. The result is saved as a copy, like Reduce File Size. //! -//! The optimization (this dialog's, or Reduce File Size's fixed choices) runs on a worker thread -//! and shows its progress in a notice with a bar and a Cancel button; the copy is saved once it -//! is done. +//! The optimization (this dialog's, or Reduce File Size's fixed choices) runs on the host's job +//! queue and shows its progress in a notice with a bar and a Cancel button; the copy is saved once +//! it is done. -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, PoisonError, RwLock}; -use egui::{Align, Layout, RichText}; -use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, MonoSettings, Preset, QUALITIES, Settings}; +use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, ItemSource}; +use craft::host::queue::{JobQueue, Priority}; +use craft::ui::contract::{Bind, ColumnSpec, Props as _, SelectMode, Show as _, ShowCollection as _, Sizing}; +use craft::ui::dialog::{DialogResult, dialog_id}; +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::optimizer::{OptimizeStage, Optimized}; use pdfcraft_engine::{DocId, EditError, Hidden, OptimizeReport}; -use crate::theme::{self, Tokens}; -use crate::{PdfCraftApp, widgets}; +// PLAN: assumed `crate::JobCount` (pdf-print-ocr-w6), `crate::notices::{ProgressKey, ProgressNotice, set_progress, end_progress}` (pdf-chrome-w19), +// `crate::dialogs::host::{open, open_over}(app, dialog[, parent])` (pdf-hub-w2) and the facade paths above (`craft::ui::patterns::form_dialogs`, `craft::ui::table`, +// `craft::ui::display::Text::show`, `Table::show_items(..).response`). +use crate::notices::{self, ProgressKey, ProgressNotice}; +use crate::{JobCount, PdfCraftApp}; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum OptimizeTab { - Images, - DiscardObjects, - DiscardUserData, - CleanUp, +/// The dialog's key; its answer is read back by [`pass`]. +pub(crate) const OPTIMIZE_KEY: &str = "optimize"; +/// The key of the Space Audit stand-alone dialog. +pub(crate) const SPACE_AUDIT_KEY: &str = "space-audit"; +/// The key of the Space Audit opened from the Optimizer. +pub(crate) const OPTIMIZER_AUDIT_KEY: &str = "optimize.audit"; +/// The instance that keeps the Optimizer's audit apart from the Optimizer, which has the same dialog type. +const AUDIT_INSTANCE: &str = "audit"; +/// The footer button that opens the audit. +const AUDIT_ACTION: &str = "audit"; + +/// Field keys: the image blocks and their fields join as `color.downsample`. +pub(crate) const COLOR: &str = "color"; +pub(crate) const GRAY: &str = "gray"; +pub(crate) const MONO: &str = "mono"; +pub(crate) const DOWNSAMPLE: &str = "downsample"; +pub(crate) const TARGET_PPI: &str = "target_ppi"; +pub(crate) const ABOVE_PPI: &str = "above_ppi"; +pub(crate) const COMPRESSION: &str = "compression"; +pub(crate) const QUALITY: &str = "quality"; +pub(crate) const MERGE_FRAGMENTS: &str = "merge_fragments"; +pub(crate) const COMPATIBILITY: &str = "compatibility"; +pub(crate) const PRESET: &str = "preset"; +pub(crate) const OBJECT_STREAMS: &str = "object_streams"; +/// The preset the settings match none of. +const CUSTOM: &str = "custom"; +/// Remove unused objects: always on, shown disabled. +const UNUSED_OBJECTS: &str = "unused_objects"; + +/// The key of `field` in the image block `block`. +pub(crate) fn key(block: &str, field: &str) -> String { + format!("{block}.{field}") } +/// What a toggle on the Discard and Clean Up tabs sets. +enum Effect { + /// A flag of the settings. + Setting(fn(&Settings) -> bool, fn(&mut Settings, bool)), + /// A Remove Hidden Information category. + Discard(Hidden), +} + +/// A check box of the Discard Objects (1), Discard User Data (2) or Clean Up (3) tab. +struct Toggle { + tab: usize, + key: &'static str, + label: &'static str, + effect: Effect, +} + +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: "discard_alternate_images", + label: "Discard alternate images", + effect: Effect::Setting(|s| s.discard_alternate_images, |s, on| s.discard_alternate_images = on), + }, + Toggle { + tab: 1, + key: "discard_thumbnails", + label: "Discard embedded page thumbnails", + effect: Effect::Setting(|s| s.discard_thumbnails, |s, on| s.discard_thumbnails = on), + }, + Toggle { tab: 1, key: "discard_tags", label: "Discard document tags", effect: Effect::Setting(|s| s.discard_tags, |s, on| s.discard_tags = on) }, + Toggle { + tab: 1, + key: "discard_search_index", + label: "Discard embedded search index", + effect: Effect::Setting(|s| s.discard_search_index, |s, on| s.discard_search_index = on), + }, + Toggle { + tab: 1, + key: "discard_print_settings", + label: "Discard embedded print settings", + effect: Effect::Setting(|s| s.discard_print_settings, |s, on| s.discard_print_settings = on), + }, + Toggle { + tab: 1, + key: "discard_form_actions", + label: "Discard all form submission, import and reset actions", + effect: Effect::Setting(|s| s.discard_form_actions, |s, on| s.discard_form_actions = on), + }, + Toggle { tab: 1, key: "bookmarks", label: "Discard bookmarks", effect: Effect::Discard(Hidden::Bookmarks) }, + Toggle { tab: 1, key: "formfields", label: "Flatten form fields", effect: Effect::Discard(Hidden::FormFields) }, + Toggle { tab: 1, key: "hiddenlayers", label: "Discard hidden layer content", effect: Effect::Discard(Hidden::HiddenLayers) }, + Toggle { tab: 2, key: "comments", label: "Discard all comments, forms and multimedia", effect: Effect::Discard(Hidden::Comments) }, + Toggle { tab: 2, key: "metadata", label: "Discard document information and metadata", effect: Effect::Discard(Hidden::Metadata) }, + Toggle { tab: 2, key: "attachments", label: "Discard all object data (file attachments)", effect: Effect::Discard(Hidden::Attachments) }, + Toggle { + tab: 2, + key: "discard_external_refs", + label: "Discard external cross-references", + effect: Effect::Setting(|s| s.discard_external_refs, |s, on| s.discard_external_refs = on), + }, + Toggle { tab: 2, key: "privatedata", label: "Discard private data of other applications", effect: Effect::Discard(Hidden::PrivateData) }, + Toggle { tab: 2, key: "hiddentext", label: "Discard hidden text", effect: Effect::Discard(Hidden::HiddenText) }, + Toggle { + tab: 3, + key: "flate_unencoded", + label: "Use Flate to encode streams that are not encoded", + effect: Effect::Setting(|s| s.flate_unencoded, |s, on| s.flate_unencoded = on), + }, + Toggle { + tab: 3, + key: "lzw_to_flate", + label: "In streams that use LZW encoding, use Flate instead", + effect: Effect::Setting(|s| s.lzw_to_flate, |s, on| s.lzw_to_flate = on), + }, + Toggle { + tab: 3, + key: "remove_invalid_links", + label: "Remove invalid links and bookmarks", + effect: Effect::Setting(|s| s.remove_invalid_links, |s, on| s.remove_invalid_links = on), + }, + Toggle { + tab: 3, + key: "remove_unreferenced_dests", + label: "Remove unreferenced named destinations", + effect: Effect::Setting(|s| s.remove_unreferenced_dests, |s, on| s.remove_unreferenced_dests = on), + }, +]; + +/// Compress document structure: its shown value is the effective one, which a PDF 1.4 target forces off. +static OBJECT_STREAMS_TOGGLE: Toggle = Toggle { + tab: 3, + key: OBJECT_STREAMS, + label: "Compress document structure (object streams)", + effect: Effect::Setting(|s| s.effective_object_streams(), |s, on| s.object_streams = on), +}; + +fn toggles() -> impl Iterator { + TOGGLES.iter().chain(std::iter::once(&OBJECT_STREAMS_TOGGLE)) +} + +/// What the dialog chooses: the settings and the Remove Hidden Information categories to discard. #[derive(Clone, Debug, PartialEq)] pub struct OptimizeDraft { - pub tab: OptimizeTab, pub settings: Settings, /// Remove Hidden Information categories to discard. pub discard: Vec, - /// "Audit space usage…" was pressed. - pub audit: bool, } impl Default for OptimizeDraft { fn default() -> Self { - Self { tab: OptimizeTab::Images, settings: Settings::default(), discard: Vec::new(), audit: false } + Self { settings: Settings::default(), discard: Vec::new() } } } -/// Progress of a background optimization: the stage, the result once finished, and a cancel -/// request. -#[derive(Default)] -pub struct OptimizeProgress { - pub stage: OptimizeStage, - pub result: Option>, - pub cancel: bool, +fn quality_id(compression: Compression) -> String { + let q = match compression { + Compression::Jpeg(q) => q, + _ => 60, + }; + QUALITIES.iter().min_by_key(|(_, v)| (*v as i32 - q as i32).abs()).map_or(60, |(_, v)| *v).to_string() +} + +fn set_image(fields: &mut DialogFields, block: &str, s: &ImageSettings) { + fields.set(key(block, DOWNSAMPLE), s.downsample); + fields.set(key(block, TARGET_PPI), s.target_ppi.round() as i64); + fields.set(key(block, ABOVE_PPI), s.above_ppi.round() as i64); + fields.set( + key(block, COMPRESSION), + FieldValue::Text( + match s.compression { + Compression::Jpeg(_) => "jpeg", + Compression::Flate => "flate", + Compression::Retain => "retain", + } + .into(), + ), + ); + fields.set(key(block, QUALITY), FieldValue::Text(quality_id(s.compression))); +} + +fn set_mono(fields: &mut DialogFields, m: &MonoSettings) { + fields.set(key(MONO, DOWNSAMPLE), m.downsample); + fields.set(key(MONO, TARGET_PPI), m.target_ppi.round() as i64); + fields.set(key(MONO, ABOVE_PPI), m.above_ppi.round() as i64); + let id = match m.compression { + MonoCompression::CcittG4 => "ccitt", + MonoCompression::Jbig2 => "jbig2", + MonoCompression::Retain => "retain", + }; + fields.set(key(MONO, COMPRESSION), FieldValue::Text(id.into())); +} + +fn read_image(fields: &DialogFields, block: &str, s: &mut ImageSettings) { + if let Some(on) = fields.bool(&key(block, DOWNSAMPLE)) { + s.downsample = on; + } + if let Some(v) = fields.int(&key(block, TARGET_PPI)) { + s.target_ppi = v as f64; + } + if let Some(v) = fields.int(&key(block, ABOVE_PPI)) { + s.above_ppi = v as f64; + } + let quality = fields.text(&key(block, QUALITY)).and_then(|q| q.parse::().ok()).unwrap_or(60); + match fields.text(&key(block, COMPRESSION)) { + Some("jpeg") => s.compression = Compression::Jpeg(quality), + Some("flate") => s.compression = Compression::Flate, + Some("retain") => s.compression = Compression::Retain, + _ => {} + } +} + +fn read_mono(fields: &DialogFields, m: &mut MonoSettings) { + if let Some(on) = fields.bool(&key(MONO, DOWNSAMPLE)) { + m.downsample = on; + } + if let Some(v) = fields.int(&key(MONO, TARGET_PPI)) { + m.target_ppi = v as f64; + } + if let Some(v) = fields.int(&key(MONO, ABOVE_PPI)) { + m.above_ppi = v as f64; + } + match fields.text(&key(MONO, COMPRESSION)) { + Some("ccitt") => m.compression = MonoCompression::CcittG4, + Some("jbig2") => m.compression = MonoCompression::Jbig2, + Some("retain") => m.compression = MonoCompression::Retain, + _ => {} + } +} + +impl OptimizeDraft { + /// The dialog's values for this draft, Preset included. + fn to_fields(&self) -> DialogFields { + let s = &self.settings; + let mut fields = DialogFields::new(); + fields.set(PRESET, FieldValue::Text(Preset::of(s).map_or(CUSTOM, Preset::name).into())); + fields.set(COMPATIBILITY, FieldValue::Text(s.compatibility.name().into())); + fields.set(MERGE_FRAGMENTS, s.merge_fragments); + set_image(&mut fields, COLOR, &s.color); + set_image(&mut fields, GRAY, &s.gray); + set_mono(&mut fields, &s.mono); + for toggle in toggles() { + let on = match &toggle.effect { + Effect::Setting(get, _) => get(s), + Effect::Discard(h) => self.discard.contains(h), + }; + fields.set(toggle.key, on); + } + fields + } + + /// The draft the dialog's values stand for; a value the dialog lacks keeps the default. + pub(crate) fn from_fields(fields: &DialogFields) -> Self { + let mut s = Settings::default(); + if let Some(c) = fields.text(COMPATIBILITY).and_then(|n| Compatibility::ALL.into_iter().find(|c| c.name() == n)) { + s.compatibility = c; + } + if let Some(on) = fields.bool(MERGE_FRAGMENTS) { + s.merge_fragments = on; + } + read_image(fields, COLOR, &mut s.color); + read_image(fields, GRAY, &mut s.gray); + read_mono(fields, &mut s.mono); + let mut discard = Vec::new(); + for toggle in toggles() { + let Some(on) = fields.bool(toggle.key) else { continue }; + match &toggle.effect { + Effect::Setting(_, set) => set(&mut s, on), + Effect::Discard(h) if on => discard.push(*h), + Effect::Discard(_) => {} + } + } + Self { settings: s, discard } + } +} + +/// A resolution to downsample "for images above" is never below the target. +fn raise_above_ppi(s: &mut Settings) { + s.color.above_ppi = s.color.above_ppi.max(s.color.target_ppi); + s.gray.above_ppi = s.gray.above_ppi.max(s.gray.target_ppi); + s.mono.above_ppi = s.mono.above_ppi.max(s.mono.target_ppi); +} + +/// Applies the dialog's own rules to its values: a Preset pick replaces every setting, any other edit moves Preset to the +/// preset the settings now match (Custom when none), and the resolutions and object streams stay consistent. +fn follow_edits(dialog: &mut HostedParamDialog) { + let edited = dialog.take_edited(); + let fields = dialog.fields(); + let mut draft = OptimizeDraft::from_fields(fields); + if edited.iter().any(|k| k == PRESET) + && let Some(preset) = fields.text(PRESET).and_then(Preset::from_name) + { + draft.settings = preset.settings(); + } + raise_above_ppi(&mut draft.settings); + let next = draft.to_fields(); + let changes: Vec<(String, FieldValue)> = + next.iter().filter(|(k, v)| dialog.fields().get(k) != Some(*v)).map(|(k, v)| (k.to_string(), v.clone())).collect(); + for (k, v) in changes { + dialog.set_field(k, v); + } +} + +fn bool_row(key: impl Into, label: &str, default: bool) -> Param { + Param::new(key, tl!(label), ParamKind::bool(default)) +} + +fn ppi_row(block: &str, field: &str, label: &str, default: f64) -> Param { + Param::new(key(block, field), tl!(label), ParamKind::int(Some(9), Some(2400), default.round() as i64)).enabled_when(key(block, DOWNSAMPLE), true) +} + +fn choice(options: Vec<(String, String)>, default: &str) -> ParamKind { + ParamKind::choice(options.into_iter().map(|(id, label)| (id, label.into())).collect(), Some(default.to_string())) +} + +/// The Color or Grayscale Images block. +fn image_rows(block: &str, title: &str, defaults: &ImageSettings) -> Vec { + let jpeg = FieldValue::Text("jpeg".into()); + let options = [("jpeg", "JPEG"), ("flate", tl!("ZIP")), ("retain", tl!("Retain existing"))]; + vec![ + Param::section(tl!(title)), + bool_row(key(block, DOWNSAMPLE), "Bicubic downsampling to", defaults.downsample), + ppi_row(block, TARGET_PPI, "Resolution (ppi)", defaults.target_ppi), + ppi_row(block, ABOVE_PPI, "For images above (ppi)", defaults.above_ppi), + Param::new( + key(block, COMPRESSION), + tl!("Compression"), + choice(options.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect(), "jpeg"), + ), + Param::new( + key(block, QUALITY), + tl!("Quality"), + choice(QUALITIES.iter().map(|(n, v)| (v.to_string(), tl!(n).to_string())).collect(), &quality_id(defaults.compression)), + ) + .visible_when(key(block, COMPRESSION), jpeg), + ] +} + +/// The Monochrome Images block. +fn mono_rows(defaults: &MonoSettings) -> Vec { + let options = [("ccitt", tl!("CCITT Group 4")), ("jbig2", tl!("JBIG2 (lossless)")), ("retain", tl!("Retain existing"))]; + vec![ + Param::section(tl!("Monochrome Images")), + bool_row(key(MONO, DOWNSAMPLE), "Downsample to", defaults.downsample), + ppi_row(MONO, TARGET_PPI, "Resolution (ppi)", defaults.target_ppi), + ppi_row(MONO, ABOVE_PPI, "For images above (ppi)", defaults.above_ppi), + Param::new( + key(MONO, COMPRESSION), + tl!("Compression"), + choice(options.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect(), "ccitt"), + ), + ] +} + +fn toggle_rows(tab: usize) -> Vec { + let defaults = Settings::default(); + let mut rows: Vec = toggles() + .filter(|t| t.tab == tab) + .map(|t| { + let on = match &t.effect { + Effect::Setting(get, _) => get(&defaults), + Effect::Discard(_) => false, + }; + let row = bool_row(t.key, t.label, on); + if t.key == OBJECT_STREAMS { + let allowed = Compatibility::ALL.into_iter().filter(|c| *c != Compatibility::Pdf1_4).map(|c| FieldValue::Text(c.name().into())); + row.enabled_when_in(COMPATIBILITY, allowed) + } else { + row + } + }) + .collect(); + if tab == 3 { + rows.push(bool_row(UNUSED_OBJECTS, "Remove unused objects and merge identical ones", true).disabled()); + } + rows +} + +/// The Optimizer's dialog over its values: Preset and Compatibility above four tabs. +fn build_optimizer(fields: &mut DialogFields) -> ParamDialog<'_> { + let defaults = Settings::default(); + let preset = [("standard", tl!("Standard")), ("mobile", tl!("Mobile")), (CUSTOM, tl!("Custom"))]; + let compatibility: Vec<(String, String)> = Compatibility::ALL + .into_iter() + .map(|c| (c.name().to_string(), if c == Compatibility::Retain { tl!("Retain existing").to_string() } else { format!("PDF {}", c.name()) })) + .collect(); + let shared = vec![ + Param::new(PRESET, tl!("Settings"), choice(preset.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect(), "standard")), + Param::new(COMPATIBILITY, tl!("Compatibility"), choice(compatibility, Compatibility::Retain.name())), + ]; + let mut images = vec![bool_row(MERGE_FRAGMENTS, "Merge image fragments", defaults.merge_fragments)]; + images.extend(image_rows(COLOR, "Color Images", &defaults.color)); + images.extend(image_rows(GRAY, "Grayscale Images", &defaults.gray)); + images.extend(mono_rows(&defaults.mono)); + let tabs = vec![ + ParamTab::new(tl!("Images"), images), + ParamTab::new(tl!("Discard Objects"), toggle_rows(1)), + ParamTab::new(tl!("Discard User Data"), toggle_rows(2)), + ParamTab::new(tl!("Clean Up"), toggle_rows(3)), + ]; + ParamDialog::new(OPTIMIZE_KEY, tl!("PDF Optimizer"), shared) + .tabs(tabs) + .shared_rows(SharedRows::Above) + .extra_buttons(vec![(AUDIT_ACTION.to_string(), tl!("Audit space usage…").into())]) + .footer_note(tl!("Each image is measured where pages draw it; an image is replaced only if the result is smaller.")) + .values(Bind::bound(fields)) +} + +/// Opens PDF Optimizer over the defaults. +pub(crate) fn open_optimizer(app: &mut PdfCraftApp, ctx: &egui::Context) { + let dialog = HostedParamDialog::new(ctx, OPTIMIZE_KEY, OptimizeDraft::default().to_fields(), build_optimizer); + crate::dialogs::host::open(app, dialog); +} + +const DESCRIPTION: ColumnKey = ColumnKey::new("description"); +const BYTES: ColumnKey = ColumnKey::new("bytes"); +const PERCENTAGE: ColumnKey = ColumnKey::new("percentage"); + +/// One row of the audit table. +struct AuditLine { + description: String, + bytes: String, + percentage: String, +} + +/// The audit's rows: each kind that takes bytes, then the total. +fn audit_lines(rows: &[SpaceUse]) -> Vec { + let mut lines: Vec = rows + .iter() + .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() }; + AuditLine { description, bytes: r.bytes.to_string(), percentage: format!("{:.2}%", r.percent) } + }) + .collect(); + let total: u64 = rows.iter().map(|r| r.bytes).sum(); + lines.push(AuditLine { description: tl!("Total").to_string(), bytes: total.to_string(), percentage: "100.00%".to_string() }); + lines +} + +struct AuditRows<'a>(&'a [AuditLine]); + +impl DisplayOrder for AuditRows<'_> { + fn len(&self) -> usize { + self.0.len() + } + + fn key(&self, at: usize) -> usize { + at + } + + fn index_of(&self, key: &usize) -> Option { + (*key < self.0.len()).then_some(*key) + } + + fn text(&self, at: usize) -> Option> { + self.0.get(at).map(|line| std::borrow::Cow::Borrowed(line.description.as_str())) + } +} + +impl ItemSource for AuditRows<'_> {} + +/// The audit's explanation over its table, read from `rows` each pass. No rows show until the measure result arrives. +fn audit_row(rows: Arc>>) -> Param { + Param::custom("space-audit", tl!("Space Audit"), move |ui, _fields, _cx| { + let lines = audit_lines(&rows.read().unwrap_or_else(PoisonError::into_inner)); + Text::new(tl!("What takes up the space in this file, by kind of content.")).show(ui); + let columns = vec![ + ColumnSpec::new(DESCRIPTION, tl!("Description"), ColumnWidth::Content), + ColumnSpec::new(BYTES, tl!("Bytes"), ColumnWidth::Content).numeric(), + ColumnSpec::new(PERCENTAGE, tl!("Percentage"), ColumnWidth::Content).numeric(), + ]; + Table::::new(tl!("Space Audit"), columns) + .select(SelectMode::None) + .sizing(Sizing::Content) + .striped(true) + .show_items(ui, &AuditRows(&lines), &mut |at, icx| { + let Some(line) = lines.get(*at) else { return ListRow::new("") }; + ListRow::new(line.description.clone()) + .cells(icx.cells()) + .striped(icx.row.striped) + .cell(BYTES, line.bytes.clone()) + .cell(PERCENTAGE, line.percentage.clone()) + }) + .response + }) +} + +/// The Space Audit row, for a dialog that shows the audit among other rows (Properties ▸ Space Audit): reads the app's shared +/// result each pass. It starts no measure, so a dialog may build it every pass; the caller runs `measure_space_audit` once when +/// the tab opens and again on the document-changed event. +// PLAN: pdf-dialogs-w7 calls `measure_space_audit` when Properties ▸ Space Audit opens; the document-changed handler (pdf-hub-w3) calls it too. +pub(crate) fn space_audit_param(app: &PdfCraftApp) -> Param { + audit_row(app.space_audit.clone()) +} + +/// Opens the audit dialog: over the Optimizer when `from_optimizer`, so its values survive, else alone. +pub(crate) fn open_space_audit(app: &mut PdfCraftApp, ctx: &egui::Context, from_optimizer: bool) { + app.measure_space_audit(); + let key = if from_optimizer { OPTIMIZER_AUDIT_KEY } else { SPACE_AUDIT_KEY }; + let rows = app.space_audit.clone(); + let dialog = HostedParamDialog::new(ctx, key, DialogFields::new(), move |fields| { + 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); + } +} + +/// The dialogs' side of a frame: applies the Optimizer's rules to its edits, opens the audit it asks for, runs the optimization it +/// answers with, and takes in the measure's result. +pub(crate) fn pass(app: &mut PdfCraftApp, ctx: &egui::Context) { + let optimizer = dialog_id(OPTIMIZE_KEY); + let mut audit = false; + if let Some(dialog) = app.dialogs.get_mut_by_id::(optimizer) { + follow_edits(dialog); + audit = dialog.take_action().as_deref() == Some(AUDIT_ACTION); + } + if audit { + open_space_audit(app, ctx, true); + } + if let Some(DialogResult::Ok(result)) = app.dialogs.take_by_id::(optimizer) { + app.optimize_with_draft(&OptimizeDraft::from_fields(&result.fields)); + } + // The audit only reads: its answer, OK or Cancel, closes it and nothing else. + // The Optimizer's audit is an instance, whose id differs from its key's. + for id in [dialog_id((OPTIMIZER_AUDIT_KEY, AUDIT_INSTANCE)), dialog_id(SPACE_AUDIT_KEY)] { + let _ = app.dialogs.take_by_id::(id); + } + #[cfg(target_arch = "wasm32")] + app.space_audit_jobs.run_inline(1); + while let Some(done) = app.space_audit_jobs.try_recv() { + *app.space_audit.write().unwrap_or_else(PoisonError::into_inner) = done.result; + app.space_audit_of = Some(done.key); + } } /// Which command started an optimization: they save under different names, and only the @@ -68,14 +581,21 @@ impl OptimizeKind { } } +/// A running optimization: what the job reports while it runs. pub struct OptimizeRun { pub doc: DocId, pub kind: OptimizeKind, /// Where the copy goes, if the command asked first. Otherwise it asks when the run is done. pub destination: Option, - pub progress: Arc>, + /// The page or image count the job has reached; its changes move the progress card. + pub progress: Arc, + /// The stage the job is in, which names the card's text (`JobCount` carries a count only). + pub stage: Arc>, } +/// 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 notice's text for a stage. fn stage_label(stage: OptimizeStage) -> String { match stage { @@ -96,6 +616,14 @@ fn stage_label(stage: OptimizeStage) -> String { } } +/// The count a stage has reached, for the run's `JobCount`. +fn stage_counts(stage: OptimizeStage) -> (usize, usize) { + match stage { + OptimizeStage::Reading { done, total } | OptimizeStage::Images { done, total } => (done, total), + _ => (0, 0), + } +} + /// What the saved notice adds after the size: images optimized and items discarded. fn summary(r: &OptimizeReport) -> String { let o = &r.optimize; @@ -112,281 +640,27 @@ fn summary(r: &OptimizeReport) -> String { if parts.is_empty() { String::new() } else { format!("; {}", parts.join(", ")) } } -fn image_row(ui: &mut egui::Ui, id: &str, title: &str, s: &mut ImageSettings) { - ui.label(egui::RichText::new(tl!(title)).font(theme::semibold(13.0))); - ui.horizontal(|ui| { - ui.add(widgets::checkbox(&mut s.downsample, tl!("Bicubic downsampling to"))); - ui.add_enabled(s.downsample, egui::DragValue::new(&mut s.target_ppi).range(9.0..=2400.0).suffix(" ppi")); - ui.label(tl!("for images above")); - ui.add_enabled(s.downsample, egui::DragValue::new(&mut s.above_ppi).range(9.0..=2400.0).suffix(" ppi")); - }); - s.above_ppi = s.above_ppi.max(s.target_ppi); - ui.horizontal(|ui| { - ui.label(tl!("Compression")); - let label = match s.compression { - Compression::Jpeg(_) => "JPEG", - Compression::Flate => tl!("ZIP"), - Compression::Retain => tl!("Retain existing"), - }; - craft_ui::ComboBox::from_id_salt((id, "compression")).selected_text(label).show_ui(ui, |ui| { - let q = match s.compression { - Compression::Jpeg(q) => q, - _ => 60, - }; - ui.selectable_value(&mut s.compression, Compression::Jpeg(q), "JPEG"); - ui.selectable_value(&mut s.compression, Compression::Flate, tl!("ZIP")); - ui.selectable_value(&mut s.compression, Compression::Retain, tl!("Retain existing")); - }); - if let Compression::Jpeg(q) = &mut s.compression { - ui.label(tl!("Quality")); - let name = QUALITIES.iter().min_by_key(|(_, v)| (*v as i32 - *q as i32).abs()).map_or(tl!("Medium"), |(n, _)| tl!(n)); - craft_ui::ComboBox::from_id_salt((id, "quality")).selected_text(name).show_ui(ui, |ui| { - for (n, v) in QUALITIES { - ui.selectable_value(q, v, tl!(n)); - } - }); - } - }); - ui.add_space(8.0); -} - -/// Monochrome Images: how black-and-white images and image masks are resampled and stored. -fn mono_row(ui: &mut egui::Ui, m: &mut MonoSettings) { - ui.label(egui::RichText::new(tl!("Monochrome Images")).font(theme::semibold(13.0))); - ui.horizontal(|ui| { - ui.add(widgets::checkbox(&mut m.downsample, tl!("Downsample to"))); - ui.add_enabled(m.downsample, egui::DragValue::new(&mut m.target_ppi).range(9.0..=2400.0).suffix(" ppi")); - ui.label(tl!("for images above")); - ui.add_enabled(m.downsample, egui::DragValue::new(&mut m.above_ppi).range(9.0..=2400.0).suffix(" ppi")); - }); - m.above_ppi = m.above_ppi.max(m.target_ppi); - ui.horizontal(|ui| { - ui.label(tl!("Compression")); - let label = match m.compression { - MonoCompression::CcittG4 => tl!("CCITT Group 4"), - MonoCompression::Jbig2 => tl!("JBIG2 (lossless)"), - MonoCompression::Retain => tl!("Retain existing"), - }; - craft_ui::ComboBox::from_id_salt(("mono", "compression")).selected_text(label).show_ui(ui, |ui| { - ui.selectable_value(&mut m.compression, MonoCompression::CcittG4, tl!("CCITT Group 4")); - ui.selectable_value(&mut m.compression, MonoCompression::Jbig2, tl!("JBIG2 (lossless)")); - ui.selectable_value(&mut m.compression, MonoCompression::Retain, tl!("Retain existing")); - }); - }); - ui.add_space(8.0); -} - -fn discard_box(ui: &mut egui::Ui, list: &mut Vec, h: Hidden, label: &str) { - let mut on = list.contains(&h); - if ui.add(widgets::checkbox(&mut on, tl!(label))).changed() { - if on { - list.push(h); - } else { - list.retain(|x| *x != h); - } - } -} - -/// Draw the dialog; returns (ok, cancel). -pub(crate) fn body(ui: &mut egui::Ui, d: &mut OptimizeDraft, t: &Tokens) -> (bool, bool) { - ui.label(egui::RichText::new(tl!("PDF Optimizer")).font(theme::semibold(18.0))); - ui.add_space(6.0); - ui.horizontal(|ui| { - ui.label(tl!("Settings")); - let name = |p: Preset| match p { - Preset::Standard => tl!("Standard"), - Preset::Mobile => tl!("Mobile"), - }; - let current = Preset::of(&d.settings); - craft_ui::ComboBox::from_id_salt("optimize-preset").selected_text(current.map_or(tl!("Custom"), name)).show_ui(ui, |ui| { - for p in Preset::ALL { - if ui.selectable_label(current == Some(p), name(p)).clicked() { - d.settings = p.settings(); - } - } - }); - ui.add_space(8.0); - ui.label(tl!("Compatibility")); - let compat_label = |c: Compatibility| match c { - Compatibility::Retain => tl!("Retain existing").to_string(), - _ => format!("PDF {}", c.name()), - }; - craft_ui::ComboBox::from_id_salt("optimize-compatibility").selected_text(compat_label(d.settings.compatibility)).show_ui(ui, |ui| { - for c in Compatibility::ALL { - ui.selectable_value(&mut d.settings.compatibility, c, compat_label(c)); - } - }); - }); - ui.add_space(6.0); - ui.horizontal_wrapped(|ui| { - for (tab, label) in [ - (OptimizeTab::Images, tl!("Images")), - (OptimizeTab::DiscardObjects, tl!("Discard Objects")), - (OptimizeTab::DiscardUserData, tl!("Discard User Data")), - (OptimizeTab::CleanUp, tl!("Clean Up")), - ] { - if widgets::mode_tab(ui, label, d.tab == tab).clicked() { - d.tab = tab; - } - } - }); - ui.separator(); - ui.add_space(6.0); - let s = &mut d.settings; - match d.tab { - OptimizeTab::Images => { - ui.add(widgets::checkbox(&mut s.merge_fragments, tl!("Merge image fragments"))); - image_row(ui, "color", "Color Images", &mut s.color); - image_row(ui, "gray", "Grayscale Images", &mut s.gray); - mono_row(ui, &mut s.mono); - ui.label( - egui::RichText::new(tl!("Each image is measured where pages draw it; an image is replaced only if the result is smaller.")) - .small() - .color(t.text_muted), - ); - } - OptimizeTab::DiscardObjects => { - discard_box(ui, &mut d.discard, Hidden::LinksActionsScripts, "Discard all links, actions and JavaScript"); - ui.add(widgets::checkbox(&mut s.discard_alternate_images, tl!("Discard alternate images"))); - ui.add(widgets::checkbox(&mut s.discard_thumbnails, tl!("Discard embedded page thumbnails"))); - ui.add(widgets::checkbox(&mut s.discard_tags, tl!("Discard document tags"))); - ui.add(widgets::checkbox(&mut s.discard_search_index, tl!("Discard embedded search index"))); - ui.add(widgets::checkbox(&mut s.discard_print_settings, tl!("Discard embedded print settings"))); - ui.add(widgets::checkbox(&mut s.discard_form_actions, tl!("Discard all form submission, import and reset actions"))); - discard_box(ui, &mut d.discard, Hidden::Bookmarks, "Discard bookmarks"); - discard_box(ui, &mut d.discard, Hidden::FormFields, "Flatten form fields"); - discard_box(ui, &mut d.discard, Hidden::HiddenLayers, "Discard hidden layer content"); - } - OptimizeTab::DiscardUserData => { - discard_box(ui, &mut d.discard, Hidden::Comments, "Discard all comments, forms and multimedia"); - discard_box(ui, &mut d.discard, Hidden::Metadata, "Discard document information and metadata"); - discard_box(ui, &mut d.discard, Hidden::Attachments, "Discard all object data (file attachments)"); - ui.add(widgets::checkbox(&mut s.discard_external_refs, tl!("Discard external cross-references"))); - discard_box(ui, &mut d.discard, Hidden::PrivateData, "Discard private data of other applications"); - discard_box(ui, &mut d.discard, Hidden::HiddenText, "Discard hidden text"); - } - OptimizeTab::CleanUp => { - ui.add(widgets::checkbox(&mut s.flate_unencoded, tl!("Use Flate to encode streams that are not encoded"))); - ui.add(widgets::checkbox(&mut s.lzw_to_flate, tl!("In streams that use LZW encoding, use Flate instead"))); - ui.add(widgets::checkbox(&mut s.remove_invalid_links, tl!("Remove invalid links and bookmarks"))); - ui.add(widgets::checkbox(&mut s.remove_unreferenced_dests, tl!("Remove unreferenced named destinations"))); - let mut object_streams = s.effective_object_streams(); - if ui - .add_enabled( - s.compatibility != Compatibility::Pdf1_4, - widgets::checkbox(&mut object_streams, tl!("Compress document structure (object streams)")), - ) - .changed() - { - s.object_streams = object_streams; - } - ui.add_enabled(false, widgets::checkbox(&mut true, tl!("Remove unused objects and merge identical ones"))); - } - } - ui.add_space(12.0); - let (mut ok, mut cancel) = (false, false); - ui.horizontal(|ui| { - if widgets::pill_button(ui, tl!("Audit space usage…"), false).clicked() { - d.audit = true; - } - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if widgets::pill_button(ui, tl!("OK"), true).clicked() { - ok = true; - } - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { - cancel = true; - } - }); - }); - (ok, cancel) -} - -/// Audit Space Usage: how the file's bytes are spent now, by kind of content (not what -/// optimizing would save). -pub(crate) fn audit_body(ui: &mut egui::Ui, rows: &[pdfcraft_engine::optimize::SpaceUse], t: &Tokens) -> bool { - ui.label(RichText::new(tl!("Space Audit")).font(crate::theme::semibold(18.0))); - ui.add_space(4.0); - audit_table(ui, rows, t); - ui.add_space(12.0); - let mut ok = false; - ui.horizontal(|ui| ui.with_layout(Layout::right_to_left(Align::Center), |ui| ok = widgets::pill_button(ui, tl!("OK"), true).clicked())); - ok -} - -/// The audit's explanation and its table: bytes and share of the file per kind of content. -/// Shared by the Optimizer's Audit Space Usage and Properties ▸ Space Audit. -pub(crate) fn audit_table(ui: &mut egui::Ui, rows: &[pdfcraft_engine::optimize::SpaceUse], t: &Tokens) { - use egui::{TextWrapMode, WidgetText}; - ui.label(RichText::new(tl!("What takes up the space in this file, by kind of content.")).color(t.text_muted)); - ui.add_space(8.0); - // Every cell is laid out first so each column can be exactly as wide as its widest cell. A - // right-to-left layout in a grid's last column takes the rest of the window instead, which - // drew the percentages at the dialog's far edge, away from their rows. - let text = |s: RichText| WidgetText::from(s).into_galley(ui, Some(TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body); - let header = |s: &str| text(RichText::new(s).color(t.text_muted)); - let mut table = vec![[header(tl!("Description")), header(tl!("Bytes")), header(tl!("Percentage"))]]; - for r in rows.iter().filter(|r| r.bytes > 0) { - // "Patterns" also names the redaction search patterns ("模式"); the audit's PDF - // graphics objects need their own key. - let category = if r.category == pdfcraft_engine::optimize::SpaceCategory::Patterns { - tl!("Patterns (graphics objects)") - } else { - tl!(r.category.label()) - }; - table.push([text(RichText::new(category)), text(RichText::new(r.bytes.to_string())), text(RichText::new(format!("{:.2}%", r.percent)))]); - } - let total: u64 = rows.iter().map(|r| r.bytes).sum(); - table.push([ - text(RichText::new(tl!("Total")).strong()), - text(RichText::new(total.to_string()).strong()), - text(RichText::new("100.00%").strong()), - ]); - let gap = 24.0; - let width = |column: usize| table.iter().filter_map(|row| row.get(column)).map(|g| g.size().x).fold(0.0, f32::max); - // The description takes what the numbers leave, so the striped rows span the dialog. - let numbers = width(1) + width(2) + 2.0 * gap; - let widths = [width(0).max(ui.available_width() - numbers), width(1), width(2)]; - let height = table.iter().flatten().map(|g| g.size().y).fold(ui.spacing().interact_size.y, f32::max); - // No minimum column width: egui's default widened a narrow Bytes column past `widths` and - // pushed the table beyond the dialog's padding. - egui::Grid::new("space-audit").num_columns(3).striped(true).spacing([gap, 4.0]).min_col_width(0.0).show(ui, |ui| { - for row in table { - for (column, (cell, width)) in row.into_iter().zip(widths).enumerate() { - // Numbers line up on their last digit. - let layout = if column == 0 { Layout::left_to_right(Align::Center) } else { Layout::right_to_left(Align::Center) }; - let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover()); - ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(layout)).label(cell); - } - ui.end_row(); - } - }); -} - impl PdfCraftApp { - /// Measure the active document's space use, unless `space_audit` already describes it as - /// it is now. With no document the audit is empty. - pub(crate) fn refresh_space_audit(&mut self) { + /// Measure the active document's space use in the background. With no document the audit is empty. + pub(crate) fn measure_space_audit(&mut self) { let Some((_, id)) = self.active_ids() else { - self.space_audit.clear(); + self.space_audit.write().unwrap_or_else(PoisonError::into_inner).clear(); self.space_audit_of = None; return; }; let Some(doc) = self.session.get(id) else { return }; let key = (id, doc.edit_generation()); - if self.space_audit_of != Some(key) { - self.space_audit = doc.audit_space(); - self.space_audit_of = Some(key); - } + let job = doc.space_audit_job(); + self.space_audit_jobs.submit(key, Priority::BACKGROUND, move |_| job.run()); } - /// Optimize PDF with the dialog's choices on a worker thread; the copy is saved when done. - pub fn optimize_with_draft(&mut self) { - let (settings, discard) = (self.optimize_draft.settings.clone(), self.optimize_draft.discard.clone()); - self.start_optimize(OptimizeKind::Advanced, &settings, &discard); + /// Optimize PDF with the dialog's choices in the background; the copy is saved when done. + pub(crate) fn optimize_with_draft(&mut self, draft: &OptimizeDraft) { + self.start_optimize(OptimizeKind::Advanced, &draft.settings, &draft.discard); } - /// Run an optimization of the active document on a worker thread (inline in tests and on - /// the web), showing its progress; the copy is saved when it is done. + /// Run an optimization of the active document in the background, showing its progress; the + /// copy is saved when it is done. pub(crate) fn start_optimize(&mut self, kind: OptimizeKind, settings: &Settings, discard: &[Hidden]) { let Some((_, id)) = self.active_ids() else { return }; self.run_optimize(id, kind, settings, discard, None); @@ -411,79 +685,64 @@ impl PdfCraftApp { Ok(job) => job, Err(e) => return self.save_optimized(id, kind, Err(e), destination), }; - let progress = Arc::new(Mutex::new(OptimizeProgress::default())); - let p = progress.clone(); - let work = move || { - let result = job.run(|stage| { - let Ok(mut s) = p.lock() else { return false }; - s.stage = stage; - !s.cancel - }); - if let Ok(mut s) = p.lock() { - s.result = Some(result); - } - }; - #[cfg(not(target_arch = "wasm32"))] - if self.run_inline { - work(); - } else if let Err(e) = std::thread::Builder::new().name("pdfcraft-optimize".into()).spawn(move || { + let progress = Arc::new(JobCount::default()); + let stage = Arc::new(Mutex::new(OptimizeStage::default())); + let (count, shown) = (progress.clone(), stage.clone()); + self.optimize_jobs.submit(id, Priority::BACKGROUND, move |cancel| { + #[cfg(not(target_arch = "wasm32"))] pdfcraft_engine::optimize::give_way_to_other_programs(); - work(); - }) { - // No worker: report the failure instead of waiting for a result that never comes. - if let Ok(mut s) = progress.lock() { - s.result = Some(Err(EditError::Optimize(e.to_string()))); - } - } - #[cfg(target_arch = "wasm32")] - work(); - self.optimize_run = Some(OptimizeRun { doc: id, kind, destination, progress }); - self.poll_optimize(); + job.run(|now| { + *shown.lock().unwrap_or_else(PoisonError::into_inner) = now; + let (done, total) = stage_counts(now); + count.set(done, total); + !cancel.is_cancelled() + }) + }); + self.optimize_run = Some(OptimizeRun { doc: id, kind, destination, progress, stage }); + self.show_optimize_stage(); } - /// Stop a running optimization (nothing is saved). - pub fn cancel_optimize(&mut self) { - if let Some(r) = &self.optimize_run - && let Ok(mut s) = r.progress.lock() - { - s.cancel = true; - } - } - - /// Show progress; save the copy once the worker is done. - pub(crate) fn poll_optimize(&mut self) { + /// Puts the run's stage on the progress card. + fn show_optimize_stage(&mut self) { let Some(run) = self.optimize_run.as_ref() else { return }; - let (doc, kind, destination, progress) = (run.doc, run.kind, run.destination.clone(), run.progress.clone()); - let Ok(mut s) = progress.lock() else { - // The worker panicked while holding the lock: it will never report back. + let stage = *run.stage.lock().unwrap_or_else(PoisonError::into_inner); + let notice = ProgressNotice { label: stage_label(stage), fraction: stage.fraction(), cancellable: true }; + notices::set_progress(self, ProgressKey::Optimize, notice); + } + + /// Stop a running optimization: its result is discarded and nothing is saved. + pub fn cancel_optimize(&mut self) { + let Some(run) = self.optimize_run.take() else { return }; + self.optimize_jobs.reprioritize(|key, priority| (*key != run.doc).then_some(priority)); + notices::end_progress(self, ProgressKey::Optimize); + self.notify_tr("Optimization cancelled"); + } + + /// Show progress; save the copy once the job is done. + pub(crate) fn poll_optimize(&mut self) { + // Without lanes (wasm32) the owner runs one job per pass. + #[cfg(target_arch = "wasm32")] + self.optimize_jobs.run_inline(1); + while let Some(done) = self.optimize_jobs.try_recv() { + let Some(run) = self.optimize_run.as_ref().filter(|run| run.doc == done.key) else { continue }; + let (doc, kind, destination) = (run.doc, run.kind, run.destination.clone()); self.optimize_run = None; - self.progress_notice = None; - self.notify_tr("Couldn't optimize the file"); - return; - }; - let Some(result) = s.result.take() else { - let cancelling = s.cancel; - let stage = s.stage; - drop(s); - let label = if cancelling { tl!("Cancelling…").to_string() } else { stage_label(stage) }; - self.progress_notice = Some(crate::widgets::ProgressNotice { label, fraction: stage.fraction(), cancellable: !cancelling }); - if let Some(ctx) = &self.ctx { - ctx.request_repaint_after(std::time::Duration::from_millis(50)); + notices::end_progress(self, ProgressKey::Optimize); + match done.result { + Err(EditError::Cancelled) => self.notify_tr("Optimization cancelled"), + result => { + let result = result.map(|(b, r)| { + let detail = if kind == OptimizeKind::Advanced { summary(&r) } else { String::new() }; + (b, detail) + }); + self.save_optimized(doc, kind, result, destination); + } } return; - }; - drop(s); - self.optimize_run = None; - self.progress_notice = None; - match result { - Err(EditError::Cancelled) => self.notify_tr("Optimization cancelled"), - result => { - let result = result.map(|(b, r)| { - let detail = if kind == OptimizeKind::Advanced { summary(&r) } else { String::new() }; - (b, detail) - }); - self.save_optimized(doc, kind, result, destination); - } + } + let Some(run) = self.optimize_run.as_ref() else { return }; + if run.progress.take_change().is_some() { + self.show_optimize_stage(); } } } @@ -497,76 +756,30 @@ mod tests { #[test] fn the_progress_card_shows_the_stage_and_cancels() { - let progress = Arc::new(Mutex::new(OptimizeProgress { stage: OptimizeStage::Images { done: 3, total: 10 }, ..Default::default() })); - let p = progress.clone(); + let progress = Arc::new(JobCount::default()); + progress.set(3, 10); + let stage = Arc::new(Mutex::new(OptimizeStage::Images { done: 3, total: 10 })); + let (p, s) = (progress.clone(), stage.clone()); let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { let mut app = PdfCraftApp::new(); app.set_option("language", "en").unwrap(); app.open_bytes("notes.txt", None, b"hello".to_vec()).unwrap(); let (_, doc) = app.active_ids().unwrap(); - app.optimize_run = Some(OptimizeRun { doc, kind: OptimizeKind::Advanced, destination: None, progress: p }); - app.notify("Saved notes.pdf"); + app.optimize_run = Some(OptimizeRun { doc, kind: OptimizeKind::Advanced, destination: None, progress: p, stage: s }); app }); - // 1.5 s (kittest steps a quarter second): the bar has eased in, the toast still shows. + // 1.5 s (kittest steps a quarter second): the bar has eased in. h.run_steps(6); if let Ok(path) = std::env::var("PDFCRAFT_OPTIMIZE_PROGRESS_SHOT") { h.render().unwrap().save(path).unwrap(); } h.get_by_label("Optimizing… image 4 of 10"); - let shown = h.state().progress_notice.clone().unwrap(); - assert!((shown.fraction - 0.415).abs() < 1e-4, "{shown:?}"); - assert!(shown.cancellable); h.get_by_label("Cancel").click(); h.run_steps(2); - assert!(progress.lock().unwrap().cancel, "the worker is asked to stop"); - h.get_by_label("Cancelling…"); - assert!(h.query_by_label("Cancel").is_none(), "Cancel is not offered twice"); - - // The worker stops and reports back. - progress.lock().unwrap().result = Some(Err(EditError::Cancelled)); - h.run_steps(2); - assert!(h.state().optimize_run.is_none() && h.state().progress_notice.is_none()); - assert_eq!(h.state().toast.as_ref().map(|t| t.0.as_str()), Some("Optimization cancelled")); - } - - #[test] - fn the_progress_card_says_what_is_happening() { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - assert_eq!(stage_label(OptimizeStage::default()), "Optimizing… reading the pages"); - assert_eq!(stage_label(OptimizeStage::Reading { done: 11, total: 51 }), "Optimizing… reading page 12 of 51"); - assert_eq!(stage_label(OptimizeStage::Reading { done: 51, total: 51 }), "Optimizing… reading page 51 of 51"); - assert_eq!(stage_label(OptimizeStage::Discarding), "Optimizing… removing user data"); - } - - #[test] - fn a_second_run_is_refused_while_one_is_going() { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.open_bytes("notes.txt", None, b"hello".to_vec()).unwrap(); - let (_, doc) = app.active_ids().unwrap(); - app.optimize_run = Some(OptimizeRun { doc, kind: OptimizeKind::Reduce, destination: None, progress: Arc::default() }); - app.optimize_with_draft(); - assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Optimization is already running")); - } - - #[test] - fn optimize_and_enhance_scanned_file_do_not_run_at_once() { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.open_bytes("notes.txt", None, b"hello".to_vec()).unwrap(); - let (_, doc) = app.active_ids().unwrap(); - app.scan_clean_run = Some(crate::scan_clean_ui::ScanCleanRun { doc, progress: Arc::default() }); - app.optimize_with_draft(); - assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Scanned pages are already being enhanced")); - assert!(app.optimize_run.is_none()); - - app.scan_clean_run = None; - app.optimize_run = Some(OptimizeRun { doc, kind: OptimizeKind::Reduce, destination: None, progress: Arc::default() }); - app.start_scan_clean(); - assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Optimization is already running")); - assert!(app.scan_clean_run.is_none()); + assert!(h.state().optimize_run.is_none(), "the run ended"); + assert!(h.query_by_label("Cancel").is_none(), "the card and its Cancel are gone"); + assert!(h.query_by_label("Optimizing… image 4 of 10").is_none()); + h.get_by_label("Optimization cancelled"); } } diff --git a/crates/ui-egui/tests/it/optimize.rs b/crates/ui-egui/tests/it/optimize.rs new file mode 100644 index 0000000000..ce8e3495b8 --- /dev/null +++ b/crates/ui-egui/tests/it/optimize.rs @@ -0,0 +1,66 @@ +//! The app's rules for one optimization at a time and the exclusion with Enhance scanned file, driven as a user fires the commands. +//! +//! PLAN: `mod optimize;` belongs in `tests/it/main.rs` (pdf-shell-w9's hunk). The held host is assumed +//! `support::held_app(jobs: Arc) -> PdfCraftApp` (a `PdfCraftApp::with_host` over a host with `ManualJobs`, pdf-hub-w1 L-71) and +//! `support::shown_notice(&Harness) -> Option` (pdf-chrome-w9). + +use std::sync::Arc; + +use craft::host::ManualJobs; +use egui_kittest::Harness; +use pdfcraft_ui_egui::PdfCraftApp; + +use crate::support; + +/// A harness whose jobs wait until the test steps them, with a document open and the answer to Reduce's "where to save" given. +fn held() -> (Arc, Harness<'static, PdfCraftApp>) { + let jobs = Arc::new(ManualJobs::new()); + let queue = jobs.clone(); + let out = std::env::temp_dir().join(format!("pdfcraft-optimize-held-{}.pdf", std::process::id())); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { + let mut app = support::held_app(queue); + app.set_option("language", "en").unwrap(); + app.open_bytes("notes.txt", None, b"hello".to_vec()).unwrap(); + app.save_override = Some(out.to_string_lossy().into_owned()); + app + }); + h.run_steps(2); + (jobs, h) +} + +#[test] +fn a_second_run_is_refused_while_one_is_going() { + let (jobs, mut h) = held(); + assert!(h.state_mut().execute("optimize.reduce")); + h.run_steps(2); + assert!(h.state().optimize_run.is_some(), "the first run is going"); + assert!(h.state_mut().execute("optimize.reduce")); + h.run_steps(2); + assert!(support::shown_notice(&h).is_some(), "the second run is refused with a notice"); + assert!(jobs.run_next(), "the first run's job is kept"); + assert!(!jobs.run_next(), "and no second job was queued"); +} + +#[test] +fn enhancing_scans_refuses_optimizing() { + let (_jobs, mut h) = held(); + h.state_mut().start_scan_clean(); + h.run_steps(2); + assert!(h.state().scan_clean_run.is_some(), "the enhancement is going"); + assert!(h.state_mut().execute("optimize.reduce")); + h.run_steps(2); + assert!(support::shown_notice(&h).is_some()); + assert!(h.state().optimize_run.is_none()); +} + +#[test] +fn optimizing_refuses_enhancing_scans() { + let (_jobs, mut h) = held(); + assert!(h.state_mut().execute("optimize.reduce")); + h.run_steps(2); + assert!(h.state().optimize_run.is_some(), "the run is going"); + h.state_mut().start_scan_clean(); + h.run_steps(2); + assert!(support::shown_notice(&h).is_some()); + assert!(h.state().scan_clean_run.is_none()); +}