diff --git a/crates/ui-egui/src/dialogs/protect.rs b/crates/ui-egui/src/dialogs/protect.rs index cc79f3c82c..7c5e4b8ed6 100644 --- a/crates/ui-egui/src/dialogs/protect.rs +++ b/crates/ui-egui/src/dialogs/protect.rs @@ -2,11 +2,21 @@ //! Password Security settings behind "Advanced Options" (compatibility, what to encrypt, //! printing, changes, copying, screen readers). Execution plan M8.1. -use egui::{Align, Color32, Layout}; -use pdfcraft_engine::{Changes, Edit, Printing, Protection}; +use craft::ui::choice::{Checkbox, Radio, RadioGroup}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::controls::disclosure::Disclosure; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft::ui::display::{Shade, Text}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row; +use craft::ui::patterns::form_dialogs::{FormDialog, PasswordFields}; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::Label; +use craft::ui::style::TypeRole; +use egui::Ui; +use pdfcraft_engine::{Algorithm, Changes, Edit, Printing, Protection}; -use crate::theme::{self, Tokens}; -use crate::{PdfCraftApp, widgets}; +use crate::PdfCraftApp; /// The dialog's state while it is open. #[derive(Clone, Debug, PartialEq)] @@ -67,181 +77,159 @@ impl ProtectDraft { } } -/// A rough password strength, as Acrobat's meter shows (Weak / Medium / Strong). -pub fn strength(pw: &str) -> (&'static str, Color32) { - let classes = [ - pw.chars().any(char::is_lowercase), - pw.chars().any(char::is_uppercase), - pw.chars().any(|c| c.is_ascii_digit()), - pw.chars().any(|c| !c.is_alphanumeric()), - ] - .iter() - .filter(|b| **b) - .count(); - let n = pw.chars().count(); - if n >= 12 && classes >= 3 { - ("Strong", Color32::from_rgb(0x2D, 0x9D, 0x5B)) - } else if n >= 8 && classes >= 2 { - ("Medium", Color32::from_rgb(0xE8, 0x8A, 0x1A)) - } else { - ("Weak", Color32::from_rgb(0xD3, 0x2F, 0x2F)) +/// Protect Using Password, owned by the dialog host. The draft, passwords included, dies with the dialog. +pub(crate) struct ProtectDialog { + id: DialogId, + draft: ProtectDraft, +} + +impl ProtectDialog { + fn new() -> Self { + ProtectDialog { id: dialog_id("protect"), draft: ProtectDraft::default() } } } -/// A radio button drawn like Acrobat's: an outlined circle, filled blue with a white dot when on. -fn radio(ui: &mut egui::Ui, t: &Tokens, on: bool, label: &str) -> egui::Response { - let (rect, resp) = ui.allocate_exact_size(egui::vec2(220.0, 26.0), egui::Sense::click()); - let c = egui::pos2(rect.left() + 9.0, rect.center().y); - if on { - ui.painter().circle_filled(c, 8.0, t.accent); - ui.painter().circle_filled(c, 3.0, Color32::WHITE); - } else { - ui.painter().circle_stroke(c, 7.5, egui::Stroke::new(1.5, t.text_muted)); - } - ui.painter().text(egui::pos2(rect.left() + 26.0, rect.center().y), egui::Align2::LEFT_CENTER, tl!(label), theme::regular(14.0), t.text); - let info = tl!(label).to_string(); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, info.clone())); - resp.on_hover_cursor(egui::CursorIcon::PointingHand) +fn text(s: &str) -> String { + tl!(s).to_string() } -/// Draw the dialog body; returns (apply, cancel). -pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (bool, bool) { - use pdfcraft_engine::Algorithm as A; - let d = &mut app.protect_draft; - ui.label(egui::RichText::new(tl!("Protect Using Password")).font(theme::semibold(18.0))); - ui.add_space(4.0); - ui.separator(); - ui.add_space(6.0); - ui.label(tl!("Requires user to enter a password for:")); - ui.add_space(4.0); - if radio(ui, t, d.viewing, "Viewing").clicked() { - d.viewing = true; - } - if radio(ui, t, !d.viewing, "Editing").clicked() { - d.viewing = false; - } - ui.add_space(10.0); - let field = |ui: &mut egui::Ui, label: &str, text: &mut String, id: &str| { - let l = ui.label(tl!(label)); - ui.add(crate::widgets::line(text).password(true).desired_width(290.0).id_salt(id)).labelled_by(l.id) - }; - let r = field(ui, "Type Password", &mut d.password, "protect-pw"); - if r.changed() || !d.password.is_empty() { - let (s, c) = strength(&d.password); - if !d.password.is_empty() { - ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Strength: {s}"), &[("s", tl!(s))])).font(theme::medium(11.5)).color(c)); - } - } - ui.add_space(6.0); - field(ui, "Re-type Password", &mut d.confirm, "protect-pw2"); - ui.add_space(6.0); - let chevron = if d.advanced { "⌃" } else { "⌄" }; - if ui - .add( - egui::Button::new( - egui::RichText::new(crate::i18n::fmt(tl!("Advanced Options {chevron}"), &[("chevron", chevron)])).font(theme::semibold(13.0)), - ) - .frame(false), - ) - .clicked() - { - d.advanced = !d.advanced; - } - if d.advanced { - let p = &mut d.protection; - egui::Grid::new("protect-advanced").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - ui.label(tl!("Compatibility")); - let algos = [ - (A::Aes256, tl!("Acrobat X and later (256-bit AES)")), - (A::Aes128, tl!("Acrobat 7.0 and later (128-bit AES)")), - (A::Rc4_128, tl!("Acrobat 5.0 and later (128-bit RC4)")), - (A::Rc4_40, tl!("Acrobat 3.0 and later (40-bit RC4)")), - ]; - let cur = algos.iter().find(|(a, _)| *a == p.algorithm).map_or(algos[0].1, |(_, l)| *l); - craft_ui::ComboBox::from_id_salt("protect-algo").width(300.0).selected_text(cur).show_ui(ui, |ui| { - for (a, l) in algos { - ui.selectable_value(&mut p.algorithm, a, l); - } - }); - ui.end_row(); - ui.label(tl!("Encrypt")); - ui.vertical(|ui| { - widgets::radio_value(ui, &mut p.encrypt_metadata, true, tl!("All document contents")); - // Unencrypted metadata needs crypt filters (Acrobat 6.0 and later). - ui.add_enabled_ui(p.algorithm != A::Rc4_40 && p.algorithm != A::Rc4_128, |ui| { - widgets::radio_value(ui, &mut p.encrypt_metadata, false, tl!("All document contents except metadata")); - }); - }); - ui.end_row(); - if !d.viewing { - ui.label(tl!("Printing allowed")); - let opts = - [(Printing::None, tl!("None")), (Printing::Low, tl!("Low Resolution (150 dpi)")), (Printing::High, tl!("High Resolution"))]; - let cur = opts.iter().find(|(o, _)| *o == p.printing).map_or(tl!("High Resolution"), |(_, l)| *l); - craft_ui::ComboBox::from_id_salt("protect-print").width(300.0).selected_text(cur).show_ui(ui, |ui| { - for (o, l) in opts { - ui.selectable_value(&mut p.printing, o, l); - } - }); - ui.end_row(); - ui.label(tl!("Changes allowed")); - let opts = [ - (Changes::None, tl!("None")), - (Changes::Pages, tl!("Inserting, deleting, and rotating pages")), - (Changes::FillSign, tl!("Filling in form fields and signing existing signature fields")), - (Changes::CommentFillSign, tl!("Commenting, filling in form fields, and signing existing signature fields")), - (Changes::AnyExceptExtract, tl!("Any except extracting pages")), - ]; - let cur = opts.iter().find(|(o, _)| *o == p.changes).map_or(tl!("None"), |(_, l)| *l); - craft_ui::ComboBox::from_id_salt("protect-changes").width(300.0).selected_text(cur).show_ui(ui, |ui| { - for (o, l) in opts { - ui.selectable_value(&mut p.changes, o, l); - } - }); - ui.end_row(); - ui.label(""); - ui.vertical(|ui| { - ui.add(widgets::checkbox(&mut p.copy, tl!("Enable copying of text, images, and other content"))); - ui.add(widgets::checkbox(&mut p.accessibility, tl!("Enable text access for screen reader devices for the visually impaired"))); - }); - ui.end_row(); - } +/// The dialog's rows; returns whether Apply can be pressed. +fn body(ui: &mut Ui, d: &mut ProtectDraft) -> bool { + let error = d.problem().filter(|_| !d.password.is_empty() || !d.confirm.is_empty()).map(|p| Label::from(text(p))); + let requires = text("Requires user to enter a password for:"); + Field::new(requires.clone()).show(ui, |ui, _| { + RadioGroup::new(requires.clone(), Bind::bound(&mut d.viewing)).show(ui, |ui, _| { + Radio::new(true).label(text("Viewing")).show(ui); + Radio::new(false).label(text("Editing")).show(ui); }); - if p.algorithm == A::Rc4_40 || p.algorithm == A::Rc4_128 { - p.encrypt_metadata = true; - } + }); + PasswordFields::new(text("Type Password"), Bind::bound(&mut d.password)).confirm(Bind::bound(&mut d.confirm)).error(error).show(ui); + let advanced = text("Advanced Options"); + Row::new().show(ui, |ui, _| { + Disclosure::new(Bind::bound(&mut d.advanced)).label(advanced.clone()).show(ui); + Text::new(advanced.clone()).show(ui); + }); + if d.advanced { + advanced_rows(ui, d); } - ui.add_space(8.0); - if let Some(problem) = d.problem().filter(|_| !d.password.is_empty() || !d.confirm.is_empty()) { - // problem() stays English (tested); only the display translates. - ui.label(egui::RichText::new(tl!(problem)).color(t.text_muted).font(theme::regular(12.0))); - } - ui.label( - egui::RichText::new(if d.viewing { - tl!("Anyone opening the document will need this password. It's applied when you save.") - } else { - tl!("The document opens without a password; this password is needed to change the restrictions. It's applied when you save.") - }) - .color(t.text_faint) - .font(theme::regular(11.5)), - ); - ui.add_space(12.0); - let (mut apply, mut cancel) = (false, false); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let ok = d.problem().is_none(); - if ui.add_enabled_ui(ok, |ui| widgets::pill_button(ui, tl!("Apply"), true)).inner.clicked() { - apply = true; - } - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { - cancel = true; + let note = if d.viewing { + text("Anyone opening the document will need this password. It's applied when you save.") + } else { + text("The document opens without a password; this password is needed to change the restrictions. It's applied when you save.") + }; + Text::new(note).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + d.problem().is_none() +} + +/// The classic Password Security settings. +fn advanced_rows(ui: &mut Ui, d: &mut ProtectDraft) { + use Algorithm as A; + let viewing = d.viewing; + let p = &mut d.protection; + let algos = [ + Entry::new(A::Aes256, text("Acrobat X and later (256-bit AES)")), + Entry::new(A::Aes128, text("Acrobat 7.0 and later (128-bit AES)")), + Entry::new(A::Rc4_128, text("Acrobat 5.0 and later (128-bit RC4)")), + Entry::new(A::Rc4_40, text("Acrobat 3.0 and later (40-bit RC4)")), + ]; + let label = text("Compatibility"); + Field::new(label.clone()).show(ui, |ui, _| { + if let Some(a) = Select::new(label.clone(), Bind::given(p.algorithm), &algos).show(ui).value().copied() { + p.algorithm = a; } }); - (apply, cancel) + // Unencrypted metadata needs crypt filters (Acrobat 6.0 and later), which RC4 lacks. + let rc4 = p.algorithm == A::Rc4_40 || p.algorithm == A::Rc4_128; + if rc4 { + p.encrypt_metadata = true; + } + let mut what = vec![Entry::new(true, text("All document contents"))]; + if !rc4 { + what.push(Entry::new(false, text("All document contents except metadata"))); + } + let label = text("Encrypt"); + Field::new(label.clone()).show(ui, |ui, _| { + if let Some(all) = Select::new(label.clone(), Bind::given(p.encrypt_metadata), &what).show(ui).value().copied() { + p.encrypt_metadata = all; + } + }); + if viewing { + return; + } + let printing = [ + Entry::new(Printing::None, text("None")), + Entry::new(Printing::Low, text("Low Resolution (150 dpi)")), + Entry::new(Printing::High, text("High Resolution")), + ]; + let label = text("Printing allowed"); + Field::new(label.clone()).show(ui, |ui, _| { + if let Some(v) = Select::new(label.clone(), Bind::given(p.printing), &printing).show(ui).value().copied() { + p.printing = v; + } + }); + let changes = [ + Entry::new(Changes::None, text("None")), + Entry::new(Changes::Pages, text("Inserting, deleting, and rotating pages")), + Entry::new(Changes::FillSign, text("Filling in form fields and signing existing signature fields")), + Entry::new(Changes::CommentFillSign, text("Commenting, filling in form fields, and signing existing signature fields")), + Entry::new(Changes::AnyExceptExtract, text("Any except extracting pages")), + ]; + let label = text("Changes allowed"); + Field::new(label.clone()).show(ui, |ui, _| { + if let Some(v) = Select::new(label.clone(), Bind::given(p.changes), &changes).show(ui).value().copied() { + p.changes = v; + } + }); + Checkbox::new(Bind::bound(&mut p.copy)).label(text("Enable copying of text, images, and other content")).show(ui); + Checkbox::new(Bind::bound(&mut p.accessibility)) + .label(text("Enable text access for screen reader devices for the visually impaired")) + .show(ui); +} + +impl StackDialog for ProtectDialog { + type Result = ProtectDraft; + + fn id(&self) -> DialogId { + self.id + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let problem = self.draft.problem(); + let mut form = FormDialog::new(text("Protect Using Password"), Bind::bound(&mut self.draft)).ok_label(text("Apply")); + if let Some(problem) = problem { + form = form.ok_reason(text(problem)); + } + let shown = form.show(ui, |ui, _, draft| body(ui, draft)); + match (shown.accepted, shown.closed) { + (Some(draft), _) => Some(DialogResult::Ok(draft)), + (None, Some(_)) => Some(DialogResult::Cancel), + (None, None) => None, + } + } +} + +impl PdfCraftApp { + /// Opens Protect Using Password with an empty draft. + pub(crate) fn open_protect(&mut self) { + // PLAN: assumed `fn open(app: &mut PdfCraftApp, dialog: D)` (pdf-hub-w2) + crate::dialogs::host::open(self, ProtectDialog::new()); + } + + /// Applies the draft of a Protect dialog that finished with Apply. + pub(crate) fn protect_pass(&mut self) { + // PLAN: assumed `self.dialogs: DialogHost` with `fn take(&mut self) -> Option>` (pdf-hub-w1 field, pdf-hub-w2 host) + if let Some(DialogResult::Ok(draft)) = self.dialogs.take::() + && self.apply_edit(draft.edit()) + { + self.notify_tr("Password protection will be applied when you save"); + } + } } #[cfg(test)] mod tests { use super::*; + use egui_kittest::{Harness, kittest::Queryable}; #[test] fn drafts_validate_and_map_to_the_right_password() { @@ -261,44 +249,54 @@ mod tests { Edit::Protect(p) => assert_eq!((p.open_password, p.permissions_password.as_deref()), (None, Some("abc"))), other => panic!("{other:?}"), } - assert_eq!(strength("abc").0, "Weak"); - assert_eq!(strength("Abcdefg1").0, "Medium"); - assert_eq!(strength("Correct-Horse-9").0, "Strong"); + } + + fn type_into(h: &mut Harness<'static, PdfCraftApp>, label: &str, text: &str) { + h.get_by_label(label).click(); + h.run_steps(2); + h.get_by_label(label).type_text(text); + h.run_steps(2); + } + + fn open_and_fill(h: &mut Harness<'static, PdfCraftApp>, password: &str) { + h.state_mut().open_protect(); + h.run_steps(2); + type_into(h, "Type Password", password); + type_into(h, "Re-type Password", password); + assert!(h.query_by(|n| n.label().as_deref() == Some("Apply") && !n.is_disabled()).is_some(), "matching passwords enable Apply"); + } + + fn assert_fresh(h: &mut Harness<'static, PdfCraftApp>) { + h.state_mut().open_protect(); + h.run_steps(2); + assert!( + h.query_by(|n| n.label().as_deref() == Some("Apply") && n.is_disabled()).is_some(), + "a reopened dialog starts with empty passwords, so Apply is disabled" + ); } #[test] fn closing_the_protect_dialog_clears_the_password_draft() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_| { let mut app = PdfCraftApp::new(); app.set_option("language", "en").unwrap(); - app.dialog = Some(crate::Dialog::Protect); - app.protect_draft.password = "TopSecret123!".into(); - app.protect_draft.confirm = "TopSecret123!".into(); app }); - h.run_steps(2); - // Clicking Cancel closes Dialog::Protect and clears the draft passwords. + open_and_fill(&mut h, "TopSecret123!"); h.get_by_label("Cancel").click(); h.run_steps(2); - assert_eq!(h.state().dialog, None); - assert!(h.state().protect_draft.password.is_empty(), "password must not linger after cancelling Dialog::Protect"); - assert!(h.state().protect_draft.confirm.is_empty(), "confirm must not linger after cancelling Dialog::Protect"); + assert!(h.query_by_label("Apply").is_none(), "Cancel closes the dialog"); + assert_fresh(&mut h); - // Pressing Escape on Dialog::Protect also clears the draft passwords. - { - let app = h.state_mut(); - app.dialog = Some(crate::Dialog::Protect); - app.protect_draft.password = "AnotherSecret!".into(); - app.protect_draft.confirm = "AnotherSecret!".into(); - } - h.run_steps(2); h.key_press(egui::Key::Escape); h.run_steps(2); - assert_eq!(h.state().dialog, None); - assert!(h.state().protect_draft.password.is_empty(), "password must not linger after closing Dialog::Protect"); - assert!(h.state().protect_draft.confirm.is_empty(), "confirm must not linger after closing Dialog::Protect"); + assert!(h.query_by_label("Apply").is_none(), "Escape closes the dialog"); + + open_and_fill(&mut h, "AnotherSecret!"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.query_by_label("Apply").is_none()); + assert_fresh(&mut h); } } diff --git a/crates/ui-egui/src/dialogs/standards_ui.rs b/crates/ui-egui/src/dialogs/standards_ui.rs index de6052b05c..2a450c2843 100644 --- a/crates/ui-egui/src/dialogs/standards_ui.rs +++ b/crates/ui-egui/src/dialogs/standards_ui.rs @@ -1,139 +1,226 @@ //! Standards ▸ PDF/A: what the document declares, verifying it against PDF/A-2b or 3b, and //! fixing what can be fixed (Save as PDF/A). -use egui::{Align, Layout}; +use craft::ui::buttons::Button; +use craft::ui::contract::{Bind, Entry, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft::ui::display::{Shade, Text}; +use craft::ui::form::Field; +use craft::ui::list::{Finding, Findings, FindingsList, FindingsSummary, FindingsWords, Severity}; +use craft::ui::patterns::form_dialogs::FormDialog; +use craft::ui::pickers::Select; +use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::style::TypeRole; +use egui::Ui; use pdfcraft_engine::pdfa::{Issue, Level}; -use crate::theme::{self, Tokens}; -use crate::{PdfCraftApp, widgets}; +use crate::PdfCraftApp; -/// The dialog's state: the chosen level and the last result. +/// The dialog's remembered choice: the level. #[derive(Clone, Debug, PartialEq)] pub struct PdfaState { pub level: Level, - pub issues: Option>, - pub fixed: Vec, } impl Default for PdfaState { fn default() -> Self { - PdfaState { level: Level::A2b, issues: None, fixed: Vec::new() } + PdfaState { level: Level::A2b } } } +/// The level as the value the form binds, which a form needs a default for. +#[derive(Clone, Debug, PartialEq)] +struct LevelForm { + level: Level, +} + +impl Default for LevelForm { + fn default() -> Self { + LevelForm { level: PdfaState::default().level } + } +} + +/// What a footer or body button asked for; `pdfa_pass` runs it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Action { + Verify, + Convert, + Remove, +} + +/// What the dialog shows of the document, which only the app can read. +#[derive(Clone, Debug, Default)] +struct Shown { + declared: String, + /// The label of the button that removes the PDF/A identification, when one is declared. + remove: Option, + intents: Vec, + /// The last verification; `None` until Verify runs and after the level changes. + issues: Option>, +} + +/// Standards ▸ PDF/A, owned by the dialog host. Save as PDF/A and Verify keep it open. +pub(crate) struct PdfaDialog { + id: DialogId, + form: LevelForm, + shown: Shown, + action: Option, +} + +fn removal() -> pdfcraft_engine::Edit { + pdfcraft_engine::Edit::RemoveStandardId { standard: pdfcraft_engine::Standard::PdfA } +} + impl PdfCraftApp { - pub fn pdfa_verify(&mut self) { - let Some((_, id)) = self.active_ids() else { return }; - let level = self.pdfa.level; - self.pdfa.issues = self.session.get(id).map(|d| d.pdfa_verify(level)); - self.pdfa.fixed.clear(); + /// What the active document declares: the text, the removal button's label and the output intents. + fn pdfa_declared(&self) -> Shown { + let declared = self.active_ids().and_then(|(_, id)| self.session.get(id)).map(|d| d.standards()).unwrap_or_default(); + let mut standards: Vec = declared.pdfa.iter().map(|(p, c)| format!("PDF/A-{p}{}", c.to_lowercase())).collect(); + standards.extend(declared.pdfua.map(|p| format!("PDF/UA-{p}"))); + let text = if standards.is_empty() { tl!("none").to_string() } else { standards.join(", ") }; + // Worded as Edit ▸ Undo will name it. + let remove = declared.pdfa.is_some().then(|| crate::i18n::edit_label(&removal().label())); + Shown { declared: text, remove, intents: declared.output_intents.clone(), issues: None } } - pub fn pdfa_convert(&mut self) { + /// Opens the PDF/A dialog on the remembered level, with nothing verified yet. + pub(crate) fn open_pdfa(&mut self) { + let dialog = PdfaDialog { + id: dialog_id("pdfa"), + form: LevelForm { level: self.pdfa.level }, + shown: self.pdfa_declared(), + action: None, + }; + // PLAN: assumed `fn open(app: &mut PdfCraftApp, dialog: D)` (pdf-hub-w2) + crate::dialogs::host::open(self, dialog); + } + + /// What PdfCraft's checks find in the active document at the chosen level. + fn pdfa_verify(&self) -> Option> { + let (_, id) = self.active_ids()?; let level = self.pdfa.level; - if self.apply_edit(pdfcraft_engine::Edit::ConvertPdfA { level }) { - self.pdfa_verify(); - let left = self.pdfa.issues.as_ref().map_or(0, Vec::len); - self.notify(if left == 0 { - crate::i18n::fmt( - tl!("PdfCraft's checks now find no problems for {level}. This is not a validator result. Save to keep the changes."), - &[("level", level.label())], - ) - } else if left == 1 { - crate::i18n::fmt(tl!("Fixed what could be fixed; 1 problem remains"), &[]) - } else { - crate::i18n::fmt(tl!("Fixed what could be fixed; {n} problems remain"), &[("n", &left.to_string())]) - }); + self.session.get(id).map(|d| d.pdfa_verify(level)) + } + + /// Converts, then what is left to fix; `None` when the conversion did not apply. + fn pdfa_convert(&mut self) -> Option> { + let level = self.pdfa.level; + if !self.apply_edit(pdfcraft_engine::Edit::ConvertPdfA { level }) { + return None; + } + let issues = self.pdfa_verify().unwrap_or_default(); + let left = issues.len(); + self.notify(if left == 0 { + crate::i18n::fmt( + tl!("PdfCraft's checks now find no problems for {level}. This is not a validator result. Save to keep the changes."), + &[("level", level.label())], + ) + } else if left == 1 { + crate::i18n::fmt(tl!("Fixed what could be fixed; 1 problem remains"), &[]) + } else { + crate::i18n::fmt(tl!("Fixed what could be fixed; {n} problems remain"), &[("n", &left.to_string())]) + }); + Some(issues) + } + + /// Runs what the open PDF/A dialog asked for and refreshes what it shows of the document. + pub(crate) fn pdfa_pass(&mut self) { + // PLAN: assumed `self.dialogs: DialogHost` with `fn get_mut(&mut self) -> Option<&mut D>` (pdf-hub-w1 field, pdf-hub-w2 host) + let Some((level, action)) = self.dialogs.get_mut::().map(|d| (d.form.level, d.action.take())) else { return }; + self.pdfa.level = level; + // `Some(x)` replaces the shown issues with `x`. + let issues = match action { + Some(Action::Verify) => Some(self.pdfa_verify()), + Some(Action::Convert) => self.pdfa_convert().map(Some), + Some(Action::Remove) => self.apply_edit(removal()).then_some(None), + None => None, + }; + let current = self.pdfa_declared(); + if let Some(d) = self.dialogs.get_mut::() { + let kept = d.shown.issues.take(); + d.shown = Shown { issues: issues.unwrap_or(kept), ..current }; } } } -/// Returns `true` to close. -pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool { - ui.label(egui::RichText::new("PDF/A").font(theme::semibold(18.0))); - ui.add_space(6.0); - let declared = app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|d| d.standards()).unwrap_or_default(); - let mut standards: Vec = declared.pdfa.iter().map(|(p, c)| format!("PDF/A-{p}{}", c.to_lowercase())).collect(); - standards.extend(declared.pdfua.map(|p| format!("PDF/UA-{p}"))); - let shown = if standards.is_empty() { tl!("none").to_string() } else { standards.join(", ") }; - let removal = pdfcraft_engine::Edit::RemoveStandardId { standard: pdfcraft_engine::Standard::PdfA }; - let mut remove = false; - ui.horizontal(|ui| { - ui.label(crate::i18n::fmt(tl!("Declared conformance: {shown}"), &[("shown", &shown)])); - // Worded as Edit ▸ Undo will name it. - remove = declared.pdfa.is_some() && widgets::pill_button(ui, &crate::i18n::edit_label(&removal.label()), false).clicked(); - }); - if remove && app.apply_edit(removal) { - app.pdfa.issues = None; +impl StackDialog for PdfaDialog { + type Result = (); + + fn id(&self) -> DialogId { + self.id } - if !declared.output_intents.is_empty() { - ui.label( - egui::RichText::new(crate::i18n::fmt(tl!("Output intent: {list}"), &[("list", &declared.output_intents.join(", "))])).color(t.text_muted), - ); - } - ui.add_space(6.0); - let before = app.pdfa.level; - ui.horizontal(|ui| { - ui.label(tl!("Conformance level:")); - craft_ui::ComboBox::from_id_salt("pdfa-level").selected_text(app.pdfa.level.label()).show_ui(ui, |ui| { - for l in [Level::A2b, Level::A3b] { - ui.selectable_value(&mut app.pdfa.level, l, l.label()); - } - }); - }); - if app.pdfa.level != before { - app.pdfa.issues = None; - } - ui.add_space(6.0); - egui::Frame::new().fill(t.hover).corner_radius(egui::CornerRadius::same(6)).inner_margin(egui::Margin::same(8)).show(ui, |ui| { - ui.set_width(ui.available_width()); - egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { - ui.set_min_height(120.0); - match &app.pdfa.issues { - None => { - ui.label(egui::RichText::new(tl!("Verify to see what the document needs.")).color(t.text_muted)); + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let PdfaDialog { form, shown, action, .. } = self; + let before = form.level; + let out = FormDialog::new("PDF/A", Bind::bound(&mut *form)) + .ok_label(tl!("Save as PDF/A").to_string()) + .accept_stays_open(true) + .cancel_label(tl!("Close").to_string()) + .alt_resets(false) + .extra_buttons([FooterButton::new(tl!("Verify").to_string(), DialogRole::Other)]) + .show(ui, |ui, _, f| { + Text::new(crate::i18n::fmt(tl!("Declared conformance: {shown}"), &[("shown", &shown.declared)])).show(ui); + if let Some(label) = &shown.remove + && Button::new(label.clone()).show(ui).clicks > 0 + { + *action = Some(Action::Remove); } - Some(v) if v.is_empty() => { - ui.label(crate::i18n::fmt( - tl!("PdfCraft's checks found no problems for {level}. This is not a validator result."), - &[("level", app.pdfa.level.label())], - )); + if !shown.intents.is_empty() { + let list = shown.intents.join(", "); + Text::new(crate::i18n::fmt(tl!("Output intent: {list}"), &[("list", &list)])).shade(Shade::Muted).show(ui); } - Some(v) => { - for i in v { - let page = i.page.map(|p| crate::i18n::fmt(tl!(" (page {p})"), &[("p", &(p + 1).to_string())])).unwrap_or_default(); - let fix = if i.fixable { String::new() } else { tl!(" · not fixable here").to_string() }; - // The verifier hands the wording over whole, with the document's own name - // apart from it, so the problem reads in this language and the name as it is. - ui.label(format!("{}{page}", i.said(&crate::i18n::words))); - ui.label(egui::RichText::new(format!("ISO 19005 {}{fix}", i.clause)).small().color(t.text_muted)); + let levels = [Level::A2b, Level::A3b].map(|l| Entry::new(l, l.label().to_string())); + let caption = tl!("Conformance level:").to_string(); + Field::new(caption.clone()).show(ui, |ui, _| { + if let Some(l) = Select::new(caption.clone(), Bind::given(f.level), &levels).show(ui).value().copied() { + f.level = l; + } + }); + match &shown.issues { + None => { + Text::new(tl!("Verify to see what the document needs.").to_string()).shade(Shade::Muted).show(ui); + } + Some(v) if v.is_empty() => { + Text::new(crate::i18n::fmt( + tl!("PdfCraft's checks found no problems for {level}. This is not a validator result."), + &[("level", f.level.label())], + )) + .show(ui); + } + Some(v) => { + let findings: Vec = v.iter().enumerate().map(|(n, i)| finding(n as u64, i)).collect(); + FindingsSummary::new(&findings).show(ui); + FindingsList::new(tl!("PDF/A problems").to_string()).show_items(ui, &Findings::new(&findings), &mut |key, icx| { + findings[*key as usize].row(&icx.words::()) + }); } } - } - }); - }); - ui.add_space(10.0); - let mut close = false; - let mut action = None; - ui.horizontal(|ui| { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if widgets::pill_button(ui, tl!("Save as PDF/A"), true).clicked() { - action = Some(true); - } - if widgets::pill_button(ui, tl!("Verify"), false).clicked() { - action = Some(false); - } - if widgets::pill_button(ui, tl!("Close"), false).clicked() { - close = true; - } - }); - }); - match action { - Some(true) => app.pdfa_convert(), - Some(false) => app.pdfa_verify(), - None => {} + true + }); + if form.level != before { + shown.issues = None; + } + match out.picked { + Some(0) => *action = Some(Action::Convert), + Some(2) => *action = Some(Action::Verify), + _ => {} + } + if out.accepted.is_some() { + *action = Some(Action::Convert); + None + } else { + out.closed.map(|_| DialogResult::Cancel) + } } - close +} + +/// An issue as a finding. The verifier hands the wording over whole, with the document's own name apart from it, so +/// the problem reads in this language and the name as it is. +fn finding(id: u64, i: &Issue) -> Finding { + let page = i.page.map(|p| crate::i18n::fmt(tl!(" (page {p})"), &[("p", &(p + 1).to_string())])).unwrap_or_default(); + let fix = if i.fixable { String::new() } else { tl!(" · not fixable here").to_string() }; + Finding::new(id, Severity::Error, format!("{}{page}", i.said(&crate::i18n::words))).detail(format!("ISO 19005 {}{fix}", i.clause)) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/word_count_ui.rs b/crates/ui-egui/src/dialogs/word_count_ui.rs index 1aa999c496..ed2f9d0722 100644 --- a/crates/ui-egui/src/dialogs/word_count_ui.rs +++ b/crates/ui-egui/src/dialogs/word_count_ui.rs @@ -1,20 +1,34 @@ -//! Read-only statistics for a document snapshot. At most one worker per dialog, with cancellation -//! between pages and no stale results after edits, page changes or changed exclusions. +//! Read-only statistics for a document snapshot. The count runs on the host's job queue; changing the page choice, +//! the exclusions or the document cancels the running count, and closing the dialog drops the queue. use std::sync::{ Arc, - atomic::{AtomicBool, AtomicUsize, Ordering}, - mpsc, + atomic::{AtomicUsize, Ordering}, }; +use craft::host::Wake; +use craft::host::queue::{Cancel, JobQueue, Priority, QueueOptions}; +use craft::theme::variant::Tone; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft::ui::display::{Shade, Spinner, Text}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row; +use craft::ui::notices::{Notice, NoticeLayout}; +use craft::ui::choice::Checkbox; +use craft::ui::patterns::form_dialogs::FormDialog; +use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::style::TypeRole; +use egui::Ui; use pdfcraft_engine::{ DocId, export::ExportSource, word_count::{self, Options, Report}, }; -use crate::{PdfCraftApp, widgets}; +use crate::PdfCraftApp; +/// What the dialog counted for: a change in any part starts a new count. #[derive(Clone, Copy, PartialEq, Eq)] struct Key { doc: DocId, @@ -23,203 +37,227 @@ struct Key { options: Options, } -struct Job { - key: Key, - receiver: mpsc::Receiver>, - cancel: Arc, - done: Arc, +/// The choices the dialog remembers across openings. +#[derive(Clone, Copy, Default, PartialEq)] +pub(crate) struct WordCountOptions { + pub options: Options, + pub current_page: bool, } -impl Drop for Job { - fn drop(&mut self) { - self.cancel.store(true, Ordering::Relaxed); - } -} - -#[derive(Default)] -pub(crate) struct Draft { - options: Options, - current_page: bool, +/// Word count, owned by the dialog host. +pub(crate) struct WordCountDialog { + id: DialogId, + options: WordCountOptions, + /// What the running or finished count is for. key: Option, - job: Option, - result: Option>, + // PLAN: `JobQueue` keys must be `Hash`, which `Options` is not known to be: jobs are keyed by `serial`. + queue: JobQueue>, + /// The serial of the count for `key`; a result of any other serial is stale. + serial: u64, + wake: Wake, + /// Pages the running count has read. + done: Arc, + shown: Option>, } -impl Draft { - pub(crate) fn cancel(&mut self) { - if let Some(job) = &self.job { - job.cancel.store(true, Ordering::Relaxed); +impl WordCountDialog { + fn new(options: WordCountOptions, queue: JobQueue>, wake: Wake) -> Self { + WordCountDialog { + id: dialog_id("word-count"), + options, + key: None, + queue, + serial: 0, + wake, + done: Arc::new(AtomicUsize::new(0)), + shown: None, } + } + + /// Whether the count for the current key has finished (with a report or an error). + pub(crate) fn finished(&self) -> bool { + self.shown.is_some() + } + + /// Shows `message` in place of a count and cancels any running one. + fn refuse(&mut self, message: String) { + self.queue.reprioritize(|_, _| None); self.key = None; - self.result = None; + self.shown = Some(Err(message)); } - fn update(&mut self, key: Key, source: impl FnOnce() -> ExportSource, ctx: &egui::Context, inline: bool) { + /// Starts a count when `key` is not the one counted, cancelling the old one, and takes the result that arrived + /// for the current count. + fn update(&mut self, key: Key, source: impl FnOnce() -> ExportSource) { if self.key != Some(key) { - self.cancel(); + self.queue.reprioritize(|_, _| None); self.key = Some(key); - } - if let Some(job) = &self.job { - let received = match job.receiver.try_recv() { - Ok(result) => Some(result), - Err(mpsc::TryRecvError::Empty) => None, - Err(mpsc::TryRecvError::Disconnected) => Some(Err(tl!("Word counting stopped unexpectedly.").into())), - }; - if let Some(result) = received { - if job.key == key && !job.cancel.load(Ordering::Relaxed) { - self.result = Some(result); - } - self.job = None; - } - } - if self.job.is_some() || self.result.is_some() { - return; - } - let source = source(); - let pages: Vec<_> = key.page.map_or_else(|| (0..source.pages).collect(), |page| vec![page]); - let (sender, receiver) = mpsc::channel(); - let cancel = Arc::new(AtomicBool::new(false)); - let done = Arc::new(AtomicUsize::new(0)); - self.job = Some(Job { key, receiver, cancel: cancel.clone(), done: done.clone() }); - let ctx = ctx.clone(); - let work = move || { - let result = word_count::count(source, &pages, key.options, |n| { - done.store(n, Ordering::Relaxed); - ctx.request_repaint(); - !cancel.load(Ordering::Relaxed) + self.shown = None; + self.serial += 1; + let source = source(); + let pages: Vec = key.page.map_or_else(|| (0..source.pages).collect(), |page| vec![page]); + let done = Arc::new(AtomicUsize::new(0)); + self.done = done.clone(); + let wake = self.wake.clone(); + self.queue.submit(self.serial, Priority::VISIBLE, move |cancel: &Cancel| { + word_count::count(source, &pages, key.options, |n| { + done.store(n, Ordering::Relaxed); + wake.wake(); + !cancel.is_cancelled() + }) }); - let _ = sender.send(result); - ctx.request_repaint(); - }; - #[cfg(not(target_arch = "wasm32"))] - if !inline { - if let Err(error) = std::thread::Builder::new().name("word-count".into()).spawn(work) { - self.job = None; - self.result = Some(Err(error.to_string())); - } - return; } - let _ = inline; - work(); + while let Some(finished) = self.queue.try_recv() { + if finished.key == self.serial { + self.shown = Some(finished.result); + } + } } } -pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp) -> bool { - ui.heading(tl!("Word count")); - let Some((view, id)) = app.active_ids() else { return true }; - let Some(doc) = app.session.get(id) else { return true }; - if let Err(error) = doc.check_copying() { - app.word_count_draft.cancel(); - ui.label(error.to_string()); - return false; +impl StackDialog for WordCountDialog { + type Result = (); + + fn id(&self) -> DialogId { + self.id } - let draft = &mut app.word_count_draft; - ui.add(widgets::checkbox(&mut draft.current_page, tl!("Current page only"))); - ui.separator(); - ui.add(widgets::checkbox(&mut draft.options.exclude_tables, tl!("Exclude tagged tables"))); - ui.add(widgets::checkbox(&mut draft.options.exclude_code, tl!("Exclude tagged code blocks"))); - ui.add(widgets::checkbox(&mut draft.options.exclude_images, tl!("Exclude image/OCR text"))); - ui.label(tl!("Exclusions use PDF tags. Untagged tables and code remain included. Image exclusion also removes invisible text.")); - let key = Key { doc: id, generation: doc.edit_generation(), page: draft.current_page.then_some(app.views[view].current), options: draft.options }; - draft.update(key, || doc.export_source(), ui.ctx(), app.run_inline); - ui.separator(); - match &draft.result { - Some(Ok(report)) => { - egui::Grid::new("word-count-totals").show(ui, |ui| { - for (label, value) in [ - (tl!("Words"), report.total.words), - (tl!("Characters"), report.total.characters), - (tl!("Characters without spaces"), report.total.characters_without_spaces), - (tl!("Pages counted"), report.pages.len()), - ] { - ui.label(label); - ui.strong(value.to_string()); - ui.end_row(); + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let WordCountDialog { options, shown, done, .. } = self; + let close = FooterButton::new(tl!("Close").to_string(), DialogRole::Cancel); + let out = FormDialog::new(tl!("Word count").to_string(), Bind::bound(options)) + .shaped(|d| d.buttons([close])) + .show(ui, |ui, _, o| { + Checkbox::new(Bind::bound(&mut o.current_page)).label(tl!("Current page only").to_string()).show(ui); + Checkbox::new(Bind::bound(&mut o.options.exclude_tables)).label(tl!("Exclude tagged tables").to_string()).show(ui); + Checkbox::new(Bind::bound(&mut o.options.exclude_code)).label(tl!("Exclude tagged code blocks").to_string()).show(ui); + Checkbox::new(Bind::bound(&mut o.options.exclude_images)).label(tl!("Exclude image/OCR text").to_string()).show(ui); + Text::new(tl!("Exclusions use PDF tags. Untagged tables and code remain included. Image exclusion also removes invisible text.").to_string()) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); + match shown { + Some(Ok(report)) => { + for (label, value) in [ + (tl!("Words"), report.total.words), + (tl!("Characters"), report.total.characters), + (tl!("Characters without spaces"), report.total.characters_without_spaces), + (tl!("Pages counted"), report.pages.len()), + ] { + Field::new(label.to_string()).show(ui, |ui, _| { + Text::new(value.to_string()).show(ui); + }); + } + if report.pages_without_text > 0 { + Text::new(tl!("Some pages contain no countable text. Scanned images need OCR first.").to_string()).show(ui); + } + if report.unclassified_structure { + Text::new(tl!("Some content could not be classified safely and was kept in the count.").to_string()).show(ui); + } + } + Some(Err(error)) => { + Notice::new(Tone::Bad, error.clone()).layout(NoticeLayout::Inline).show(ui); + } + None => { + Row::new().show(ui, |ui, _| { + Spinner::new().show(ui); + let n = done.load(Ordering::Relaxed); + Text::new(crate::i18n::fmt(tl!("Counting words… {n} pages read"), &[("n", &n.to_string())])).show(ui); + }); + } } + true }); - if report.pages_without_text > 0 { - ui.label(tl!("Some pages contain no countable text. Scanned images need OCR first.")); - } - if report.unclassified_structure { - ui.label(tl!("Some content could not be classified safely and was kept in the count.")); - } + out.closed.map(|_| DialogResult::Cancel) + } +} + +impl PdfCraftApp { + /// Opens Word count on the options the last one left, with its own one-lane queue on the host's jobs. + pub(crate) fn open_word_count(&mut self) { + // PLAN: assumed `self.wake: Wake` (pdf-hub-w1, `AppServices::wake`) + let wake = self.wake.clone(); + let queue = JobQueue::new(self.host.jobs_shared().clone(), wake.clone(), QueueOptions { lanes: 1, name: "word-count", ..QueueOptions::default() }); + let dialog = WordCountDialog::new(self.word_count_options, queue, wake); + crate::dialogs::host::open(self, dialog); + } + + /// Feeds the open Word count dialog the active document and takes the count's result. + pub(crate) fn word_count_pass(&mut self, ctx: &egui::Context) { + let Some(options) = self.dialogs.get::().map(|d| d.options) else { return }; + self.word_count_options = options; + let Some((view, id)) = self.active_ids() else { + self.dialogs.cancel::(ctx); + return; + }; + let current = self.views[view].current; + let Some(doc) = self.session.get(id) else { + self.dialogs.cancel::(ctx); + return; + }; + let Some(dialog) = self.dialogs.get_mut::() else { return }; + if let Err(error) = doc.check_copying() { + dialog.refuse(error.to_string()); + return; } - Some(Err(error)) => { - ui.colored_label(ui.visuals().error_fg_color, error); - } - None => { - ui.spinner(); - let done = draft.job.as_ref().map_or(0, |job| job.done.load(Ordering::Relaxed)); - ui.label(crate::i18n::fmt(tl!("Counting words… {n} pages read"), &[("n", &done.to_string())])); - } + let key = Key { doc: id, generation: doc.edit_generation(), page: options.current_page.then_some(current), options: options.options }; + dialog.update(key, || doc.export_source()); } - false } #[cfg(test)] mod tests { use super::*; - use crate::Dialog; + use craft::host::ManualJobs; use egui_kittest::{Harness, kittest::Queryable}; + /// An app whose background jobs wait on `jobs` until the test runs them. + fn app_on(jobs: Arc) -> PdfCraftApp { + let info = craft::host::AppInfo { id: "pdfcraft", name: "PdfCraft", version: env!("CARGO_PKG_VERSION") }; + let host = craft::host::Host::builder(info).jobs(jobs).build(); + let (intake, _) = craft::platform::open::FileIntake::new(Wake::none()); + let clipboard = craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::EventClipboard::new(|| 0, |_| Ok(0))); + let watch = craft::platform::watch::FileWatch::new(Wake::none()); + let services = crate::AppServices::new(Wake::none(), clipboard, None, None, intake, watch); + PdfCraftApp::with_host(Arc::new(host), services) + } + + /// The figure in the Words row of the open dialog: the value beside the row's label. + fn words_shown(h: &Harness<'_, PdfCraftApp>) -> String { + let row = h.get_by_label("Words").parent().expect("the Words label sits in its row"); + row.children_recursive().filter_map(|n| n.label()).find(|l| l.chars().all(|c| c.is_ascii_digit())).expect("the row shows a figure") + } + #[test] fn word_count_dialog_counts_changes_pages_and_closes() { - for inline in [true, false] { - let bytes = pdfcraft_engine::Session::new().create_from_text("Words", "Hello world\u{c}Another three words").unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_eframe(|_| { - let mut app = PdfCraftApp::new(); - app.run_inline = inline; - app.set_option("language", "en").unwrap(); - app.open_bytes("words.pdf", None, bytes.as_ref().clone()).unwrap(); - app.run_command("file.word_count"); - app - }); - let wait = |h: &mut Harness<'_, PdfCraftApp>| { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while h.state().word_count_draft.result.is_none() { - assert!(std::time::Instant::now() < deadline, "word-count worker timed out"); - h.run_steps(1); - std::thread::sleep(std::time::Duration::from_millis(1)); - } - h.run_steps(2); - }; - wait(&mut h); - assert_eq!(h.state().dialog, Some(Dialog::WordCount)); - assert_eq!(h.state().word_count_draft.result.as_ref().unwrap().as_ref().unwrap().total.words, 5); - h.get_by_label("Current page only").click(); + let jobs = Arc::new(ManualJobs::new()); + let bytes = pdfcraft_engine::Session::new().create_from_text("Words", "Hello world\u{c}Another three words").unwrap(); + let build_jobs = jobs.clone(); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_eframe(move |_| { + let mut app = app_on(build_jobs); + app.set_option("language", "en").unwrap(); + app.open_bytes("words.pdf", None, bytes.as_ref().clone()).unwrap(); + app.run_command("file.word_count"); + app + }); + // One frame submits the count, the job runs, the next frames take its result. + let settle = |h: &mut Harness<'_, PdfCraftApp>| { h.run_steps(1); - wait(&mut h); - assert_eq!(h.state().word_count_draft.result.as_ref().unwrap().as_ref().unwrap().total.words, 2); - h.state_mut().apply_edit(pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); - h.run_steps(1); - wait(&mut h); - assert_eq!(h.state().word_count_draft.result.as_ref().unwrap().as_ref().unwrap().total.words, 3); - h.get_by_label("Close").click(); + jobs.run_all(); h.run_steps(2); - assert!(h.state().dialog.is_none()); - assert!(h.state().word_count_draft.result.is_none()); - } - } - - #[test] - fn word_count_cancelled_worker_cannot_publish_an_old_result() { - let key = Key { doc: DocId(1), generation: 0, page: None, options: Options::default() }; - let (tx, rx) = mpsc::channel(); - let cancel = Arc::new(AtomicBool::new(false)); - let mut draft = Draft { - key: Some(key), - job: Some(Job { key, receiver: rx, cancel: cancel.clone(), done: Arc::new(AtomicUsize::new(0)) }), - ..Draft::default() + assert!(h.state().dialogs.get::().is_some_and(WordCountDialog::finished), "the count finished"); }; - draft.cancel(); - assert!(cancel.load(Ordering::Relaxed)); - let bytes = pdfcraft_engine::Session::new().create_blank(200.0, 300.0, 1).unwrap(); - let source = || ExportSource { bytes: bytes.clone(), pages: 1, sizes: vec![(200.0, 300.0)], config: Default::default() }; - draft.update(key, source, &egui::Context::default(), true); - assert!(draft.result.is_none()); // still one worker, no competing replacement - tx.send(Ok(Report { total: word_count::Counts { words: 999, ..Default::default() }, ..Default::default() })).unwrap(); - draft.update(key, source, &egui::Context::default(), true); - draft.update(key, source, &egui::Context::default(), true); - assert_eq!(draft.result.unwrap().unwrap().total.words, 0); + settle(&mut h); + assert_eq!(words_shown(&h), "5"); + h.get_by_label("Current page only").click(); + settle(&mut h); + assert_eq!(words_shown(&h), "2"); + h.state_mut().apply_edit(pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); + settle(&mut h); + assert_eq!(words_shown(&h), "3"); + h.get_by_label("Close").click(); + h.run_steps(2); + assert!(!h.state().modal_open()); + assert!(h.state().dialogs.get::().is_none(), "closing drops the dialog and its queue"); } } diff --git a/crates/ui-egui/tests/it/protect.rs b/crates/ui-egui/tests/it/protect.rs index 903b15105b..8490570e65 100644 --- a/crates/ui-egui/tests/it/protect.rs +++ b/crates/ui-egui/tests/it/protect.rs @@ -2,7 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use pdfcraft_ui_egui::{Dialog, PdfCraftApp}; +use pdfcraft_ui_egui::PdfCraftApp; const FIXTURE: &[u8] = b"%PDF-1.7 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj @@ -34,17 +34,15 @@ fn protecting_for_viewing_requires_matching_passwords_and_saves_encrypted() { let mut h = harness(); assert!(h.state_mut().execute("protect.password")); h.run_steps(2); - assert_eq!(h.state().dialog, Some(Dialog::Protect)); h.get_by_label("Viewing"); type_into(&mut h, "Type Password", "Open-Sesame-42"); type_into(&mut h, "Re-type Password", "Open-Sesame-4"); - h.get_by_label_contains("don't match"); - assert!(h.query_by(|n| n.label().as_deref() == Some("Apply") && n.is_disabled()).is_some(), "Apply is disabled"); + assert!(h.query_by(|n| n.label().as_deref() == Some("Apply") && n.is_disabled()).is_some(), "Apply is disabled while the passwords differ"); type_into(&mut h, "Re-type Password", "2"); - h.get_by_label("Strength: Strong"); + assert!(h.query_by(|n| n.label().as_deref() == Some("Apply") && !n.is_disabled()).is_some(), "Apply is enabled once they match"); h.get_by_label("Apply").click(); h.run_steps(3); - assert_eq!(h.state().dialog, None); + assert!(h.query_by_label("Apply").is_none(), "Apply closes the dialog"); let id = h.state().views[0].id; let doc = h.state().session.get(id).unwrap(); assert!(doc.info.encrypted && doc.dirty); @@ -68,7 +66,7 @@ fn editing_restrictions_via_advanced_options() { h.run_steps(2); h.get_by_label("Editing").click(); h.run_steps(2); - h.get_by_label("Advanced Options ⌄").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Advanced Options").click(); h.run_steps(2); h.get_by_label("Enable copying of text, images, and other content").click(); h.run_steps(1);