From 33516f2c317ee19fb5899ce806218179ea93f649 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:28 -0500 Subject: [PATCH] pdf-forms-w13: net change of 3 commits - pdf-forms-w13: written from its sheet - pdf-forms-w13: repair 1 - pdf-forms-w13: review fixes (review-1) --- crates/ui-egui/src/dialogs/duplicate_field.rs | 42 ++ crates/ui-egui/src/tools/redact_ui.rs | 620 +++--------------- crates/ui-egui/src/tools/redact_ui/dialogs.rs | 298 +++++++++ crates/ui-egui/src/tools/redact_ui/tool.rs | 171 +++++ crates/ui-egui/tests/it/redact.rs | 22 +- 5 files changed, 629 insertions(+), 524 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/duplicate_field.rs create mode 100644 crates/ui-egui/src/tools/redact_ui/dialogs.rs create mode 100644 crates/ui-egui/src/tools/redact_ui/tool.rs diff --git a/crates/ui-egui/src/dialogs/duplicate_field.rs b/crates/ui-egui/src/dialogs/duplicate_field.rs new file mode 100644 index 0000000000..8c02d7cc44 --- /dev/null +++ b/crates/ui-egui/src/dialogs/duplicate_field.rs @@ -0,0 +1,42 @@ +//! Duplicate Field: copies a form field onto the pages a range names. + +use craft::pages::ui::range::{PageRangeChoices, PageRangeOptions}; +use craft::pages::PageRange; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog}; +use pdfcraft_engine::Edit; + +use crate::PdfCraftApp; + +/// The key the dialog's values hold the field's name under; it has no row. +const FIELD: &str = "field"; + +/// Opens Duplicate Field for the field `name`, over All pages. +pub(crate) fn open(app: &mut PdfCraftApp, name: String) { + let Some((i, id)) = app.active_ids() else { return }; + let Some(doc) = app.session.get(id) else { return }; + let count = doc.info.pages.len(); + let current = app.views.get(i).map_or(0, |v| v.current); + let mut fields = DialogFields::new(); + fields.set("pages", PageRangeOptions::field_value(&PageRange::default())); + fields.set(FIELD, name.clone()); + let line = crate::i18n::fmt(tl!("Duplicate \"{name}\" onto:"), &[("name", &name)]); + let dialog = HostedParamDialog::new(&app.ctx, "form.duplicate_field", fields, move |fields| { + let rows = vec![PageRangeOptions::param("pages", "", count, current, PageRangeChoices::Acrobat)]; + ParamDialog::new("form.duplicate_field", tl!("Duplicate Field"), rows).title_note(line.clone()).values(Bind::bound(fields)) + }); + crate::dialogs::host::open(app, dialog); +} + +/// Duplicate Field was confirmed with `fields`: duplicates the field onto the range's pages. +// PLAN: pdf-hub-w2 routes the "form.duplicate_field" result here. +pub(crate) fn finish(app: &mut PdfCraftApp, fields: &DialogFields) { + let Some(name) = fields.text(FIELD).map(str::to_owned) else { return }; + let Some(range) = PageRangeOptions::value(fields, "pages") else { return }; + let Some((i, id)) = app.active_ids() else { return }; + let Some(doc) = app.session.get(id) else { return }; + let count = doc.info.pages.len(); + let current = app.views.get(i).map_or(0, |v| v.current); + let pages = range.pages(count, current, &[]); + app.apply_edit(Edit::DuplicateField { name, pages }); +} diff --git a/crates/ui-egui/src/tools/redact_ui.rs b/crates/ui-egui/src/tools/redact_ui.rs index a3fc0f5ec3..9ea5066173 100644 --- a/crates/ui-egui/src/tools/redact_ui.rs +++ b/crates/ui-egui/src/tools/redact_ui.rs @@ -3,16 +3,14 @@ //! mark every match, set the default box colour and overlay text, and apply all marks (with a //! confirmation, as Acrobat asks) or clear them. -use egui::{Color32, CornerRadius, Pos2, Rect, Stroke}; -use pdfcraft_engine::{Edit, NewAnnotation, REDACT_PATTERNS, REDACTION_CODE_SETS, RedactPattern, RedactionCodeSet, Rgb, Shape, Style, rect_quad}; -use pdfcraft_render::DocInfo; +use pdfcraft_engine::{Edit, NewAnnotation, REDACTION_CODE_SETS, RedactPattern, RedactionCodeSet, Rgb, Shape, Style, rect_quad}; -use crate::canvas::{DocView, PageToolContext, PageXform}; -use crate::page_cursor::Layer; -use crate::theme::Tokens; -use crate::{PdfCraftApp, widgets}; +use crate::PdfCraftApp; -const MARK_RED: Color32 = Color32::from_rgb(0xE3, 0x22, 0x22); +pub(crate) mod dialogs; +pub(crate) mod tool; + +pub(crate) use tool::RedactTool; /// Redaction Tool Properties: what new marks look like once applied. #[derive(Clone, Debug, PartialEq)] @@ -168,20 +166,6 @@ impl RedactPrefs { } } -/// Redact pages: which pages to mark. -#[derive(Clone, Debug, PartialEq)] -pub struct PagesDraft { - pub current: bool, - pub from: usize, - pub to: usize, -} - -impl Default for PagesDraft { - fn default() -> Self { - Self { current: true, from: 1, to: 1 } - } -} - /// What Find text and redact looks for. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum SearchMode { @@ -223,79 +207,6 @@ impl Default for SearchDraft { /// The largest word list file Import list accepts. pub(crate) const MAX_WORD_LIST_BYTES: usize = 1 << 20; -/// A box being drawn with the Redact tool: (page, start). -pub type AreaDrag = Option<(usize, Pos2)>; - -fn to_user(xf: &PageXform, info: &DocInfo, page: usize, p: Pos2) -> [f64; 2] { - let (vx, vy) = xf.screen_to_view(p); - let u = info.pages[page].view_to_user(vx, vy); - [u[0] as f64, u[1] as f64] -} - -/// Redact tool input on a page. Presses on text are left to text selection (the selection is -/// marked when it ends, see [`after_text`]); presses nobody holds (`free`) elsewhere draw a box. -/// Returns `true` when the gesture is a box. -pub(crate) fn page_input(cx: PageToolContext<'_>, tool: crate::QuickTool, over_text: impl Fn(Pos2) -> bool, free: bool, view: &mut DocView) -> bool { - let PageToolContext { resp, xf, ptr, page, info, .. } = cx; - let pointer = ptr.pos; - if let Some((dp, start)) = view.redact_drag - && dp == page - { - if resp.drag_stopped() || !ptr.primary_down { - view.redact_drag = None; - let end = pointer.unwrap_or(start); - let r = Rect::from_two_pos(start, end).intersect(xf.rect); - if r.width() >= 3.0 && r.height() >= 3.0 { - let (a, b) = (to_user(xf, info, page, r.min), to_user(xf, info, page, r.max)); - view.pending_redaction = Some((tool, vec![(page, vec![rect_quad([a[0], a[1], b[0], b[1]])])], page)); - } - } - return true; - } - // The tool's own press, of the primary button: one nobody holds, which began on this page off - // its text. egui may see the drag only once the pointer is past the page's edge. - if resp.drag_started_by(egui::PointerButton::Primary) - && free - && let Some(origin) = ptr.origin.filter(|o| xf.rect.contains(*o) && !over_text(*o)) - { - view.redact_drag = Some((page, origin)); - return true; - } - if pointer.is_some_and(|p| xf.rect.contains(p) && !over_text(p)) { - view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair); - } - false -} - -/// A finished text selection with the Redact tool becomes a mark. -/// Across pages: a mark on each page it covers, once all are read; refused when one of them could -/// not be read, rather than leave it unmarked. -pub(crate) fn after_text(resp: &egui::Response, page: usize, info: &DocInfo, view: &mut DocView) { - if view.redact_drag.is_some() { - return; - } - let finished = resp.drag_stopped_by(egui::PointerButton::Primary) || resp.double_clicked(); - match view.tool_marks(crate::QuickTool::Redact, finished, Some(page), true, info) { - crate::canvas::ToolMarks::Marks(marks, head) => { - view.clear_selection(); - view.pending_redaction = Some((crate::QuickTool::Redact, marks, head)); - } - crate::canvas::ToolMarks::Unreadable => view.redaction_refused = true, - crate::canvas::ToolMarks::None => {} - } -} - -/// The box being drawn, to the pages' `pointer`. -pub(crate) fn paint(painter: &egui::Painter, page: usize, view: &DocView, pointer: Option) { - if let (Some((dp, start)), Some(p)) = (view.redact_drag, pointer) - && dp == page - { - let r = Rect::from_two_pos(start, p); - painter.rect_filled(r, CornerRadius::ZERO, MARK_RED.gamma_multiply(0.12)); - painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.5, MARK_RED), egui::StrokeKind::Inside); - } -} - impl PdfCraftApp { /// Mark every match of the search draft on every page; returns how many were marked. pub fn redact_search(&mut self) -> usize { @@ -335,19 +246,16 @@ impl PdfCraftApp { n } - /// Mark the pages of the Redact pages draft. - pub fn redact_pages(&mut self) { - let Some((i, id)) = self.active_ids() else { return }; + /// Mark whole `pages` (0-based) with the current redaction properties. + pub fn redact_pages(&mut self, pages: &[usize]) { + let Some((_, id)) = self.active_ids() else { return }; let Some(doc) = self.session.get(id) else { return }; - let n = doc.info.pages.len(); - let d = self.redact_pages_draft.clone(); - let pages: Vec = if d.current { vec![self.views[i].current] } else { (d.from.max(1) - 1..d.to.min(n)).collect() }; let author = self.comment_prefs.author.clone(); let edits: Vec = pages .iter() - .map(|&p| { - let c = doc.info.pages[p].crop; - self.redact_prefs.mark(p, vec![rect_quad([c[0] as f64, c[1] as f64, c[2] as f64, c[3] as f64])], &author) + .filter_map(|&p| { + let c = doc.info.pages.get(p)?.crop; + Some(self.redact_prefs.mark(p, vec![rect_quad([c[0] as f64, c[1] as f64, c[2] as f64, c[3] as f64])], &author)) }) .collect(); match <[Edit; 1]>::try_from(edits) { @@ -362,267 +270,6 @@ impl PdfCraftApp { } } -/// Redact pages ("Mark Page Range"). Returns (apply, cancel). -pub(crate) fn pages_body(ui: &mut egui::Ui, d: &mut PagesDraft, pages: usize, _t: &Tokens) -> (bool, bool) { - ui.label(egui::RichText::new(tl!("Mark Page Range")).font(crate::theme::semibold(18.0))); - ui.add_space(8.0); - widgets::radio_value(ui, &mut d.current, true, tl!("Current page")); - let to_field = ui - .horizontal(|ui| { - let from_label = widgets::radio_value(ui, &mut d.current, false, tl!("Pages from")); - ui.add_enabled(!d.current, egui::DragValue::new(&mut d.from).range(1..=pages)).labelled_by(from_label.id); - let to_label = ui.label(tl!("to")); - let to_field = ui.add_enabled(!d.current, egui::DragValue::new(&mut d.to).range(1..=pages)).labelled_by(to_label.id); - ui.label(crate::i18n::fmt(tl!("of {name}"), &[("name", &pages.to_string())])); - to_field - }) - .inner; - widgets::keep_range_ordered(d.from, &mut d.to, widgets::typing_into(&to_field)); - ui.add_space(12.0); - let (ok, cancel) = buttons(ui, "OK", true); - if ok { - // OK while the end is still being typed (a screen reader can press it). - widgets::keep_range_ordered(d.from, &mut d.to, false); - } - (ok, cancel) -} - -/// Find text and redact. Returns (search, cancel, import a word list). -pub(crate) fn search_body(ui: &mut egui::Ui, d: &mut SearchDraft, t: &Tokens) -> (bool, bool, bool) { - ui.set_width(420.0); - ui.label(egui::RichText::new(tl!("Find text and redact")).font(crate::theme::semibold(18.0))); - ui.add_space(8.0); - widgets::radio_value(ui, &mut d.mode, SearchMode::Phrase, tl!("Single word or phrase")); - let mut enter = false; - ui.add_enabled_ui(d.mode == SearchMode::Phrase, |ui| { - let r = ui.add(crate::widgets::line(&mut d.text).hint_text(tl!("Text to find")).desired_width(380.0)).accessible_name(tl!("Text to find")); - enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); - }); - ui.add_space(6.0); - widgets::radio_value(ui, &mut d.mode, SearchMode::Words, tl!("Multiple words or phrases")); - let mut import = false; - ui.add_enabled_ui(d.mode == SearchMode::Words, |ui| { - egui::ScrollArea::vertical().id_salt("redact-words").max_height(120.0).show(ui, |ui| { - ui.add(egui::TextEdit::multiline(&mut d.words).hint_text(tl!("One word or phrase per line")).desired_width(380.0).desired_rows(4)) - .accessible_name(tl!("Words or phrases to redact")); - }); - ui.horizontal(|ui| { - import = ui.button(tl!("Import list…")).clicked(); - let n = pdfcraft_engine::redact_word_list(&d.words).len(); - ui.label(egui::RichText::new(crate::i18n::fmt(tl!("{n} word(s) or phrase(s)"), &[("n", &n.to_string())])).small().color(t.text_faint)); - }); - }); - ui.add_enabled_ui(d.mode != SearchMode::Patterns, |ui| { - ui.add(widgets::checkbox(&mut d.whole_words, tl!("Whole words only"))); - ui.add(widgets::checkbox(&mut d.case_sensitive, tl!("Case-sensitive"))); - }); - ui.add_space(6.0); - widgets::radio_value(ui, &mut d.mode, SearchMode::Patterns, tl!("Patterns")); - ui.add_enabled_ui(d.mode == SearchMode::Patterns, |ui| { - craft_ui::ComboBox::from_id_salt("redact-pattern").selected_text(tl!(d.pattern.label())).width(240.0).show_ui(ui, |ui| { - for p in REDACT_PATTERNS { - ui.selectable_value(&mut d.pattern, p, tl!(p.label())); - } - }); - }); - ui.add_space(6.0); - ui.label(egui::RichText::new(tl!("Text in images isn't found; recognise text (OCR) first.")).small().color(t.text_faint)); - if let Some(n) = d.found { - ui.label( - egui::RichText::new(if n == 0 { - tl!("No matches.").to_string() - } else { - crate::i18n::fmt(tl!("{n} match(es) marked for redaction."), &[("n", &n.to_string())]) - }) - .color(t.text_muted), - ); - } - ui.add_space(12.0); - let (go, cancel) = buttons(ui, "Mark all", true); - (go || enter, cancel, import) -} - -/// Redaction Tool Properties. Returns (apply, cancel). -pub(crate) fn props_body(ui: &mut egui::Ui, d: &mut RedactPrefs, _t: &Tokens) -> (bool, bool) { - ui.set_width(780.0); - ui.label(egui::RichText::new(tl!("Redaction Tool Properties")).font(crate::theme::semibold(18.0))); - ui.add_space(8.0); - // Two columns, so three colour grids fit a short window: the redacted result and its - // overlay text on the left, the mark's own look (Acrobat's third group) on - // the right. - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - ui.set_width(380.0); - egui::Grid::new("redact-props").num_columns(2).spacing([12.0, 10.0]).show(ui, |ui| { - ui.label(tl!("Redacted area fill colour:")); - ui.horizontal(|ui| { - let mut none = d.fill.is_none(); - if ui.add(widgets::checkbox(&mut none, tl!("No colour"))).changed() { - d.fill = if none { None } else { Some([0.0, 0.0, 0.0]) }; - } - }); - ui.end_row(); - ui.label(""); - if let Some(c) = crate::comments::swatch_grid(ui, d.fill) { - d.fill = Some(c); - } - ui.end_row(); - ui.label(""); - ui.add(widgets::checkbox(&mut d.use_overlay, tl!("Use overlay text"))); - ui.end_row(); - let on = d.use_overlay; - let l = ui.add_enabled(on, widgets::radio(!d.use_code, tl!("Custom text:"))); - if l.clicked() { - d.use_code = false; - } - ui.add_enabled(on && !d.use_code, crate::widgets::line(&mut d.overlay).desired_width(220.0)).labelled_by(l.id); - ui.end_row(); - if ui.add_enabled(on, widgets::radio(d.use_code, tl!("Redaction code:"))).clicked() { - d.use_code = true; - } - let codes_on = on && d.use_code; - ui.add_enabled_ui(codes_on, |ui| { - craft_ui::ComboBox::from_id_salt("redaction-code-set").selected_text(d.code_set.name).show_ui(ui, |ui| { - for set in REDACTION_CODE_SETS { - if ui.selectable_label(d.code_set == set, set.name).clicked() && d.code_set != set { - d.code_set = set; - d.codes.clear(); - } - } - }); - }); - ui.end_row(); - for row in d.code_set.codes.chunks(4) { - ui.label(""); - ui.add_enabled_ui(codes_on, |ui| { - ui.horizontal(|ui| { - for &code in row { - let mut picked = d.codes.contains(&code); - if ui.add_sized([62.0, 18.0], widgets::checkbox(&mut picked, code)).changed() { - d.codes.retain(|c| *c != code); - if picked { - d.codes.push(code); - } - } - } - }); - }); - ui.end_row(); - } - let look = &mut d.look; - ui.label(tl!("Font:")); - ui.add_enabled_ui(on, |ui| { - craft_ui::ComboBox::from_id_salt("overlay-font").selected_text(look.font.name()).show_ui(ui, |ui| { - for f in pdfcraft_engine::OverlayFont::ALL { - ui.selectable_value(&mut look.font, f, f.name()); - } - }); - }); - ui.end_row(); - ui.label(tl!("Font size:")); - ui.add_enabled_ui(on, |ui| { - ui.horizontal(|ui| { - let mut auto = look.size <= 0.0; - if ui.add(widgets::checkbox(&mut auto, tl!("Auto-size text to fit redaction region"))).changed() { - look.size = if auto { 0.0 } else { 10.0 }; - } - if !auto { - ui.add(egui::DragValue::new(&mut look.size).range(2.0..=144.0).suffix(" pt")); - } - }); - }); - ui.end_row(); - ui.label(tl!("Font colour:")); - ui.add_enabled_ui(on, |ui| { - if let Some(c) = crate::comments::swatch_grid(ui, Some(look.color)) { - look.color = c; - } - }); - ui.end_row(); - ui.label(""); - ui.add_enabled(on, widgets::checkbox(&mut look.repeat, tl!("Repeat overlay text"))); - ui.end_row(); - ui.label(tl!("Text alignment:")); - ui.add_enabled_ui(on, |ui| { - ui.horizontal(|ui| { - for (a, label) in [(0u8, tl!("Left")), (1, tl!("Center")), (2, tl!("Right"))] { - widgets::radio_value(ui, &mut look.align, a, label); - } - }); - }); - ui.end_row(); - }); - }); - // No separator here: in a horizontal layout it would stretch to the window's bottom. - ui.add_space(28.0); - ui.vertical(|ui| { - ui.set_width(340.0); - ui.label(egui::RichText::new(tl!("Redaction mark appearance")).strong()); - ui.add_space(6.0); - egui::Grid::new("redact-mark").num_columns(2).spacing([12.0, 10.0]).show(ui, |ui| { - ui.label(tl!("Outline colour:")); - if let Some(c) = crate::comments::swatch_grid(ui, Some(d.outline)) { - d.outline = c; - } - ui.end_row(); - ui.label(tl!("Fill colour:")); - ui.vertical(|ui| { - if let Some(c) = crate::comments::swatch_grid(ui, Some(d.hover_fill)) { - d.hover_fill = c; - } - ui.label(egui::RichText::new(tl!("Shown while the pointer is over a mark.")).weak().size(11.5)); - }); - ui.end_row(); - ui.label(tl!("Opacity:")); - let mut pct = d.opacity * 100.0; - if ui.add(egui::Slider::new(&mut pct, 10.0..=100.0).suffix("%")).changed() { - d.opacity = (pct / 100.0).clamp(0.1, 1.0); - } - ui.end_row(); - ui.label(""); - ui.add(widgets::checkbox(&mut d.remember, tl!("Make properties default"))); - ui.end_row(); - }); - }); - }); - ui.add_space(12.0); - buttons(ui, "OK", true) -} - -/// Apply redactions confirmation. Returns (apply, cancel). -pub(crate) fn apply_body(ui: &mut egui::Ui, marks: usize, t: &Tokens) -> (bool, bool) { - ui.set_width(420.0); - ui.label(egui::RichText::new(tl!("Apply redactions")).font(crate::theme::semibold(18.0))); - ui.add_space(8.0); - ui.label(if marks == 1 { - tl!("You are about to apply 1 redaction mark. Text, images and drawings under the marks, and comments and form fields that overlap them, are removed permanently.").to_string() - } else { - crate::i18n::fmt(tl!("You are about to apply {n} redaction marks. Text, images and drawings under the marks, and comments and form fields that overlap them, are removed permanently."), &[("n", &marks.to_string())]) - }); - ui.add_space(4.0); - ui.label( - egui::RichText::new(tl!("Save the document afterwards: saving rewrites the whole file so no trace of the removed content stays in it.")) - .small() - .color(t.text_muted), - ); - ui.add_space(12.0); - buttons(ui, "Apply", true) -} - -fn buttons(ui: &mut egui::Ui, ok: &str, primary: bool) -> (bool, bool) { - let (mut a, mut c) = (false, false); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // `ok` stays English internally; only the display is translated. - if widgets::pill_button(ui, tl!(ok), primary).clicked() { - a = true; - } - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { - c = true; - } - }); - (a, c) -} - /// Remove Hidden Information: each category with what was found, checked by default when /// something was. #[derive(Clone, Debug, Default, PartialEq)] @@ -634,162 +281,105 @@ impl PdfCraftApp { pub fn open_remove_hidden(&mut self) { let Some((_, id)) = self.active_ids() else { return }; let Some(doc) = self.session.get(id) else { return }; - self.hidden_draft = HiddenDraft { found: doc.hidden_info().into_iter().map(|(h, n)| (h, n, n > 0)).collect() }; - self.dialog = Some(crate::Dialog::RemoveHidden); + self.hidden_draft = Some(HiddenDraft { found: doc.hidden_info().into_iter().map(|(h, n)| (h, n, n > 0)).collect() }); } } -/// Returns (remove, cancel). -pub(crate) fn hidden_body(ui: &mut egui::Ui, d: &mut HiddenDraft, t: &Tokens) -> (bool, bool) { - ui.set_width(440.0); - ui.label(egui::RichText::new(tl!("Remove hidden information")).font(crate::theme::semibold(18.0))); - ui.add_space(4.0); - ui.label(egui::RichText::new(tl!("Select the items to remove from this document.")).color(t.text_muted)); - ui.add_space(8.0); - let total: usize = d.found.iter().map(|f| f.1).sum(); - for (h, n, on) in d.found.iter_mut() { - ui.add_enabled_ui(*n > 0, |ui| { - ui.horizontal(|ui| { - ui.add(widgets::checkbox(on, tl!(h.label()))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(egui::RichText::new(if *n == 0 { tl!("None found").to_string() } else { n.to_string() }).color(t.text_muted)); - }); - }); - }); +/// The Apply redactions prompt was confirmed: apply every mark, count the step for the +/// `_Redacted` save rules, and say what the removed text left behind. +pub(crate) fn finish_apply(app: &mut PdfCraftApp) { + let marks = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks()); + if !app.apply_edit(Edit::ApplyRedactions { pages: None }) { + return; } - ui.add_space(6.0); - ui.label( - egui::RichText::new(tl!("Form fields are flattened: their values stay visible. Saving rewrites the whole file.")).small().color(t.text_faint), - ); - ui.add_space(12.0); - let any = d.found.iter().any(|f| f.2 && f.1 > 0); - let (mut a, mut c) = (false, false); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add_enabled_ui(any && total > 0, |ui| widgets::pill_button(ui, tl!("Remove"), true)).inner.clicked() { - a = true; + if let Some(view) = app.active.and_then(|i| app.views.get_mut(i)) { + let delivered_undone = view.redactions_applied < view.redactions_downloaded; + view.redactions_applied = view.redactions_applied.saturating_add(1); + // A new step clears the redo history, so the undone saved steps can't come back. + if view.redactions_undone_after_save > 0 || delivered_undone { + view.redactions_undone_after_save = 0; + view.saved_redactions_cut_off = true; } - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { - c = true; + } + if let Some((_, id)) = app.active_ids() { + app.renew_recovery(id); + } + let applied = if marks == 1 { + tl!("Applied 1 redaction mark. Save to remove the content from the file.").to_string() + } else { + crate::i18n::fmt(tl!("Applied {n} redaction marks. Save to remove the content from the file."), &[("n", &marks.to_string())]) + }; + // Where the removed text is still held that applying leaves as it is, and what + // became of a PDF/A or PDF/UA claim in the document XMP it removed: said in the + // same notification, so neither can replace the first sentence. + let doc = app.active_ids().and_then(|(_, id)| app.session.get(id)); + let left = doc.and_then(|d| d.redaction_elsewhere()).and_then(|e| still_holding_note(&e)); + let id = doc.and_then(|d| d.redaction_identification()).and_then(|id| identification_note(&id)); + let message = [Some(applied), left, id].into_iter().flatten().collect::>().join(" "); + app.notify(message); +} + +/// The Sanitize prompt was confirmed: remove every kind of hidden information. +pub(crate) fn finish_sanitize(app: &mut PdfCraftApp) { + if app.apply_edit(Edit::Sanitize) { + if let Some((_, id)) = app.active_ids() { + app.renew_recovery(id); } + app.notify_tr("Document sanitized. Save to finish: saving rewrites the whole file."); + } +} + +/// The sentence telling the user where the removed text is still held that applying redactions +/// leaves as it is, or `None` when it is nowhere else. When the text couldn't be searched for, +/// the places are those holding any text, and the sentence says they may hold it. +pub(crate) fn still_holding_note(e: &pdfcraft_engine::RedactionElsewhere) -> Option { + let count = |n: usize, one: &str, many: &str| match n { + 0 => None, + 1 => Some(tl!(one).to_string()), + n => Some(crate::i18n::fmt(tl!(many), &[("n", &n.to_string())])), + }; + let places: Vec = [ + count(e.bookmarks, "1 bookmark title", "{n} bookmark titles"), + count(e.attachments, "1 attachment", "{n} attachments"), + count(e.comments, "1 comment", "{n} comments"), + count(e.xmp, "1 other metadata stream", "{n} other metadata streams"), + ] + .into_iter() + .flatten() + .collect(); + let (last, rest) = places.split_last()?; + let list = if rest.is_empty() { last.clone() } else { crate::i18n::fmt(tl!("{list} and {last}"), &[("list", &rest.join(", ")), ("last", last)]) }; + let template = if e.unsearched { + "The redacted text couldn't be searched for, so {places} may still hold it. Remove hidden information removes them." + } else { + "The redacted text also appears in {places}, which redaction doesn't change. Remove hidden information removes them." + }; + Some(crate::i18n::fmt(tl!(template), &[("places", &list)])) +} + +/// The sentence telling the user what became of the document's PDF/A or PDF/UA identification +/// when applying redactions removed the XMP packet that held it (and the redacted text), or +/// `None` when no such packet was removed. +pub(crate) fn identification_note(id: &pdfcraft_engine::RedactionIdentification) -> Option { + use pdfcraft_engine::RedactionClaim as Claim; + let named = |claim: Claim| -> Option { + match (id.pdfa == claim, id.pdfua == claim) { + (true, true) => Some(tl!("PDF/A and PDF/UA").to_string()), + (true, false) => Some("PDF/A".to_string()), + (false, true) => Some("PDF/UA".to_string()), + (false, false) => None, + } + }; + let kept = named(Claim::Kept).map(|s| crate::i18n::fmt(tl!("Its {standard} identification was written back on its own."), &[("standard", &s)])); + let lost = named(Claim::Lost).map(|s| { + crate::i18n::fmt( + tl!("Its {standard} identification couldn't be kept, so the file no longer says it conforms to {standard}."), + &[("standard", &s)], + ) }); - (a, c) -} - -/// Sanitize Document confirmation. Returns (sanitize, cancel). -pub(crate) fn sanitize_body(ui: &mut egui::Ui, t: &Tokens) -> (bool, bool) { - ui.set_width(440.0); - ui.label(egui::RichText::new(tl!("Sanitize document")).font(crate::theme::semibold(18.0))); - ui.add_space(8.0); - ui.label(tl!("Sanitizing removes hidden information from the document: metadata, file attachments, comments, form fields (flattened), hidden text and layers, bookmarks, links, actions and scripts, and private application data.")); - ui.add_space(4.0); - ui.label( - egui::RichText::new(tl!("Save the document afterwards; saving rewrites the whole file so nothing removed stays in it.")) - .small() - .color(t.text_muted), - ); - ui.add_space(12.0); - buttons(ui, "Sanitize", true) -} - -#[cfg(test)] -mod tests { - use super::*; - use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; - - fn key(key: egui::Key, modifiers: egui::Modifiers) -> egui::Event { - egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } + if kept.is_none() && lost.is_none() { + return None; } - - /// #5574: typing "12" into the end of 5 to 5 came out as 5. The end was raised to the start - /// after every keystroke, so the half-typed "1" was replaced before the "2" arrived. - #[test] - fn typing_the_last_page_keeps_what_is_typed() { - let mut fonts = false; - let mut h = egui_kittest::Harness::new_ui_state( - move |ui, d: &mut PagesDraft| { - // The app's fonts (the semibold heading) take effect from the next frame. - if !fonts { - ui.ctx().set_fonts(crate::theme::font_definitions()); - fonts = true; - return; - } - let t = Tokens::get(ui.ctx()); - pages_body(ui, d, 20, &t); - }, - PagesDraft { current: false, from: 5, to: 5 }, - ); - h.run(); - for (typed, expected) in [("12", 12), ("3", 5)] { - h.get_by_role_and_label(Role::SpinButton, "to").click(); - h.run(); - h.event(key(egui::Key::A, egui::Modifiers::COMMAND)); - for c in typed.chars() { - h.event(egui::Event::Text(c.to_string())); - h.run_steps(2); - } - h.event(key(egui::Key::Enter, egui::Modifiers::NONE)); - h.run_steps(2); - assert_eq!(*h.state(), PagesDraft { current: false, from: 5, to: expected }, "typed {typed:?}"); - } - } - - /// The dialog with its OK result kept: (draft, OK pressed). - fn dialog() -> egui_kittest::Harness<'static, (PagesDraft, bool)> { - let mut fonts = false; - let mut h = egui_kittest::Harness::new_ui_state( - move |ui, (d, ok): &mut (PagesDraft, bool)| { - if !fonts { - ui.ctx().set_fonts(crate::theme::font_definitions()); - fonts = true; - return; - } - let t = Tokens::get(ui.ctx()); - *ok |= pages_body(ui, d, 20, &t).0; - }, - (PagesDraft { current: false, from: 5, to: 5 }, false), - ); - h.run(); - h - } - - fn type_last_page(h: &mut egui_kittest::Harness<'static, (PagesDraft, bool)>, typed: &str) { - h.get_by_role_and_label(Role::SpinButton, "to").click(); - h.run(); - h.event(key(egui::Key::A, egui::Modifiers::COMMAND)); - for c in typed.chars() { - h.event(egui::Event::Text(c.to_string())); - h.run_steps(2); - } - } - - /// OK pressed while the end is still being typed (a screen reader's click leaves the field - /// focused) orders the range, so a reversed one never reaches the edit. - #[test] - fn ok_while_the_last_page_is_typed_orders_the_range() { - let mut h = dialog(); - type_last_page(&mut h, "3"); - assert_eq!(h.state().0.to, 3, "still typing"); - h.get_by_label("OK").click_accesskit(); - h.run_steps(2); - assert_eq!(*h.state(), (PagesDraft { current: false, from: 5, to: 5 }, true)); - } - - /// Switching to another window halfway through "12" leaves the typed "1" alone: the field - /// still has the keyboard when the window comes back. - #[test] - fn switching_windows_mid_number_keeps_what_is_typed() { - let mut h = dialog(); - type_last_page(&mut h, "1"); - h.input_mut().focused = false; - h.run_steps(2); - assert_eq!(h.state().0.to, 1, "the typed 1 stays while the window is in the background"); - h.input_mut().focused = true; - h.run_steps(2); - h.event(egui::Event::Text("2".into())); - h.run_steps(2); - h.event(key(egui::Key::Enter, egui::Modifiers::NONE)); - h.run_steps(2); - assert_eq!(h.state().0.to, 12); - } + let head = tl!("The document's XMP metadata held the redacted text and was removed.").to_string(); + Some([Some(head), kept, lost].into_iter().flatten().collect::>().join(" ")) } diff --git a/crates/ui-egui/src/tools/redact_ui/dialogs.rs b/crates/ui-egui/src/tools/redact_ui/dialogs.rs new file mode 100644 index 0000000000..4ce856641d --- /dev/null +++ b/crates/ui-egui/src/tools/redact_ui/dialogs.rs @@ -0,0 +1,298 @@ +//! The Redact dialogs: Redaction Tool Properties, Mark Page Range, Find text and redact, the +//! Apply and Sanitize prompts and Remove hidden information. + +use craft::pages::ui::range::{PageRangeChoices, PageRangeOptions}; +use craft::pages::{PageRange, PageScope}; +use craft::ui::buttons::Button; +use craft::ui::choice::{Checkbox, Radio, RadioGroup}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::dialog::{PromptChoice, StandardPrompt}; +use craft::ui::display::{Shade, Text}; +use craft::ui::form::{Field, FieldGroup}; +use craft::ui::patterns::form_dialogs::{DialogFields, FormDialog, HostedParamDialog, ParamDialog}; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::UnitKind; +use craft::ui::text::{NumberField, TextField}; +use egui::Ui; +use pdfcraft_engine::{Edit, OverlayFont, REDACT_PATTERNS, REDACTION_CODE_SETS, RedactPattern, Rgb}; + +use super::{HiddenDraft, RedactPrefs, SearchDraft, SearchMode}; +use crate::{FilePurpose, PdfCraftApp}; + +/// A labelled colour row: `palette` over `current`, `Some` when the user picked a colour. +fn colour_row(ui: &mut Ui, label: &'static str, current: Rgb, key: &'static str, enabled: bool) -> Option { + let mut picked = None; + Field::new(label).enabled(enabled).show(ui, |ui, _| { + // PLAN: assumed `comments::palette(&mut Ui, &str, Rgb, &str, &[Rgb]) -> Option` (pdf-comments-w10) + let no_extras: &[Rgb] = &[]; + picked = crate::comments::palette(ui, label, current, key, no_extras); + }); + picked +} + +fn props_rows(ui: &mut Ui, d: &mut RedactPrefs) { + FieldGroup::new(tl!("Redacted area")).show(ui, |ui, _| { + // PLAN: assumed `comments::fill_choice(&mut Ui, &str, Option, &str, &[Rgb]) -> Option>` (pdf-comments-w10) + let no_extras: &[Rgb] = &[]; + if let Some(fill) = crate::comments::fill_choice(ui, tl!("Redacted area fill colour:"), d.fill, "redact.fill", no_extras) { + d.fill = fill; + } + Checkbox::new(Bind::bound(&mut d.use_overlay)).label(tl!("Use overlay text")).show(ui); + let on = d.use_overlay; + RadioGroup::new(tl!("Overlay text source"), Bind::bound(&mut d.use_code)).show(ui, |ui, _| { + Radio::new(false).label(tl!("Custom text:")).enabled(on).show(ui); + Radio::new(true).label(tl!("Redaction code:")).enabled(on).show(ui); + }); + let codes_on = on && d.use_code; + Field::new(tl!("Custom text")).enabled(on && !d.use_code).show(ui, |ui, _| { + TextField::new(tl!("Custom text"), Bind::bound(&mut d.overlay)).show(ui); + }); + let sets: Vec> = REDACTION_CODE_SETS.iter().map(|s| Entry::new(*s, s.name)).collect(); + Field::new(tl!("Code set")).enabled(codes_on).show(ui, |ui, _| { + if let Some(set) = Select::new(tl!("Code set"), Bind::given(d.code_set), &sets).show(ui).value().copied() + && set != d.code_set + { + d.code_set = set; + d.codes.clear(); + } + }); + let set = d.code_set; + for &code in set.codes.iter() { + let was = d.codes.contains(&code); + let mut picked = was; + Checkbox::new(Bind::bound(&mut picked)).label(code).enabled(codes_on).show(ui); + if picked != was { + d.codes.retain(|c| *c != code); + if picked { + d.codes.push(code); + } + } + } + let fonts: Vec> = OverlayFont::ALL.iter().map(|f| Entry::new(*f, f.name())).collect(); + Field::new(tl!("Font:")).enabled(on).show(ui, |ui, _| { + if let Some(font) = Select::new(tl!("Font:"), Bind::given(d.look.font), &fonts).show(ui).value().copied() { + d.look.font = font; + } + }); + let was_auto = d.look.size <= 0.0; + let mut auto = was_auto; + Checkbox::new(Bind::bound(&mut auto)).label(tl!("Auto-size text to fit redaction region")).enabled(on).show(ui); + if auto != was_auto { + d.look.size = if auto { 0.0 } else { 10.0 }; + } + Field::new(tl!("Font size:")).enabled(on && !auto).show(ui, |ui, _| { + let field = NumberField::new(tl!("Font size:"), Bind::given(Some(d.look.size.max(2.0)))).range(2.0..=144.0).unit_kind(UnitKind::Points); + if let Some(Some(size)) = field.show(ui).value().copied() { + d.look.size = size.clamp(2.0, 144.0); + } + }); + if let Some(c) = colour_row(ui, tl!("Font colour:"), d.look.color, "redact.font", on) { + d.look.color = c; + } + Checkbox::new(Bind::bound(&mut d.look.repeat)).label(tl!("Repeat overlay text")).enabled(on).show(ui); + Field::new(tl!("Text alignment:")).enabled(on).show(ui, |ui, _| { + RadioGroup::new(tl!("Text alignment:"), Bind::bound(&mut d.look.align)).show(ui, |ui, _| { + Radio::new(0u8).label(tl!("Left")).show(ui); + Radio::new(1u8).label(tl!("Center")).show(ui); + Radio::new(2u8).label(tl!("Right")).show(ui); + }); + }); + }); + FieldGroup::new(tl!("Redaction mark appearance")).show(ui, |ui, _| { + if let Some(c) = colour_row(ui, tl!("Outline colour:"), d.outline, "redact.outline", true) { + d.outline = c; + } + if let Some(c) = colour_row(ui, tl!("Fill colour:"), d.hover_fill, "redact.hover", true) { + d.hover_fill = c; + } + Text::new(tl!("Shown while the pointer is over a mark.")).shade(Shade::Muted).show(ui); + Field::new(tl!("Opacity:")).show(ui, |ui, _| { + let field = NumberField::new(tl!("Opacity:"), Bind::given(Some(d.opacity * 100.0))).range(10.0..=100.0).commit_decimals(0).unit_kind(UnitKind::Percent); + if let Some(Some(pct)) = field.show(ui).value().copied() { + d.opacity = (pct / 100.0).clamp(0.1, 1.0); + } + }); + Checkbox::new(Bind::bound(&mut d.remember)).label(tl!("Make properties default")).show(ui); + }); +} + +/// Redaction Tool Properties while `app.redact_props` holds the draft: OK keeps it for this run +/// (and as the saved defaults with "Make properties default"), Cancel and Escape drop it. +pub(crate) fn show_props(app: &mut PdfCraftApp, ui: &mut Ui) { + let Some(mut draft) = app.redact_props.take() else { return }; + let mut open = true; + let shown = FormDialog::new(tl!("Redaction Tool Properties"), Bind::bound(&mut draft)).opened(Bind::bound(&mut open)).show(ui, |ui, _, d| { + props_rows(ui, d); + true + }); + match (shown.accepted, shown.closed) { + (Some(prefs), _) => { + if prefs.remember { + app.redact_defaults = prefs.clone(); + } + app.redact_prefs = prefs; + } + (None, Some(_)) => {} + (None, None) => app.redact_props = Some(draft), + } +} + +/// Opens Mark Page Range over the current page. +pub(crate) fn open_pages(app: &mut PdfCraftApp) { + let Some((i, id)) = app.active_ids() else { return }; + let Some(doc) = app.session.get(id) else { return }; + let count = doc.info.pages.len(); + let current = app.views.get(i).map_or(0, |v| v.current); + let range = PageRange { scope: PageScope::Current, ..PageRange::default() }; + let fields = DialogFields::from_pairs([("pages", PageRangeOptions::field_value(&range))]); + let Some(ctx) = app.ctx.clone() else { return }; + let dialog = HostedParamDialog::new(&ctx, "redact.pages", fields, move |fields| { + let rows = vec![PageRangeOptions::param("pages", "", count, current, PageRangeChoices::Current)]; + ParamDialog::new("redact.pages", tl!("Mark Page Range"), rows).values(Bind::bound(fields)) + }); + crate::dialogs::host::open(app, dialog); +} + +/// Mark Page Range was confirmed with `fields`: marks the pages the range names. +// PLAN: pdf-hub-w2 routes the "redact.pages" result here. +pub(crate) fn finish_pages(app: &mut PdfCraftApp, fields: &DialogFields) { + let Some(range) = PageRangeOptions::value(fields, "pages") else { return }; + let Some((i, id)) = app.active_ids() else { return }; + let Some(doc) = app.session.get(id) else { return }; + let count = doc.info.pages.len(); + let current = app.views.get(i).map_or(0, |v| v.current); + let pages = range.pages(count, current, &[]); + app.redact_pages(&pages); +} + +fn search_rows(ui: &mut Ui, d: &mut SearchDraft, import: &mut bool) { + let mode = d.mode; + let patterns: Vec> = REDACT_PATTERNS.iter().map(|p| Entry::new(*p, tl!(p.label()))).collect(); + FieldGroup::new(tl!("Find text and redact")).show(ui, |ui, _| { + RadioGroup::new(tl!("Search for"), Bind::bound(&mut d.mode)).show(ui, |ui, _| { + Radio::new(SearchMode::Phrase).label(tl!("Single word or phrase")).show(ui); + TextField::new(tl!("Text to find"), Bind::bound(&mut d.text)).placeholder(tl!("Text to find")).enabled(mode == SearchMode::Phrase).show(ui); + Radio::new(SearchMode::Words).label(tl!("Multiple words or phrases")).show(ui); + TextField::new(tl!("Words or phrases to redact"), Bind::bound(&mut d.words)) + .placeholder(tl!("One word or phrase per line")) + .lines(4) + .enabled(mode == SearchMode::Words) + .show(ui); + *import = Button::new(tl!("Import list…")).enabled(mode == SearchMode::Words).show(ui).clicked(); + let n = pdfcraft_engine::redact_word_list(&d.words).len(); + Text::new(crate::i18n::fmt(tl!("{n} word(s) or phrase(s)"), &[("n", &n.to_string())])).shade(Shade::Muted).show(ui); + Radio::new(SearchMode::Patterns).label(tl!("Patterns")).show(ui); + Field::new(tl!("Pattern")).enabled(mode == SearchMode::Patterns).show(ui, |ui, _| { + if let Some(p) = Select::new(tl!("Pattern"), Bind::given(d.pattern), &patterns).show(ui).value().copied() { + d.pattern = p; + } + }); + }); + let phrase_or_words = mode != SearchMode::Patterns; + Checkbox::new(Bind::bound(&mut d.whole_words)).label(tl!("Whole words only")).enabled(phrase_or_words).show(ui); + Checkbox::new(Bind::bound(&mut d.case_sensitive)).label(tl!("Case-sensitive")).enabled(phrase_or_words).show(ui); + Text::new(tl!("Text in images isn't found; recognise text (OCR) first.")).shade(Shade::Muted).show(ui); + if let Some(n) = d.found { + let line = if n == 0 { tl!("No matches.").to_string() } else { crate::i18n::fmt(tl!("{n} match(es) marked for redaction."), &[("n", &n.to_string())]) }; + Text::new(line).show(ui); + } + }); +} + +/// Find text and redact while `app.redact_search_open`: OK marks every match and stays open to +/// show the count; Cancel and Escape close it. +pub(crate) fn show_search(app: &mut PdfCraftApp, ui: &mut Ui) { + if !app.redact_search_open { + return; + } + // The draft is the app's, written by the word-list import and read by the search; it is + // lent to the form for the pass. + let mut draft = std::mem::take(&mut app.redact_search); + let mut open = true; + let mut import = false; + let shown = FormDialog::new(tl!("Find text and redact"), Bind::bound(&mut draft)) + .opened(Bind::bound(&mut open)) + .ok_label(tl!("Mark all")) + .accept_stays_open(true) + .show(ui, |ui, _, d| { + search_rows(ui, d, &mut import); + true + }); + app.redact_search = draft; + if shown.accepted.is_some() { + let n = app.redact_search(); + app.redact_search.found = Some(n); + } else if shown.closed.is_some() { + app.redact_search_open = false; + } + if import { + app.pick_files(FilePurpose::RedactWords, false); + } +} + +/// Opens the Apply redactions prompt; the host routes a Proceed to `finish_apply`. +pub(crate) fn open_apply(app: &mut PdfCraftApp) { + let marks = app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks()); + let message = if marks == 1 { + tl!("You are about to apply 1 redaction mark. Text, images and drawings under the marks, and comments and form fields that overlap them, are removed permanently.").to_string() + } else { + crate::i18n::fmt(tl!("You are about to apply {n} redaction marks. Text, images and drawings under the marks, and comments and form fields that overlap them, are removed permanently."), &[("n", &marks.to_string())]) + }; + let prompt = StandardPrompt::custom(message) + .title(tl!("Apply redactions")) + .paragraph(tl!("Save the document afterwards: saving rewrites the whole file so no trace of the removed content stays in it.")) + .button(PromptChoice::Proceed, tl!("Apply")) + .button(PromptChoice::Cancel, tl!("Cancel")) + .tag("redact.apply"); + crate::dialogs::host::open(app, prompt); +} + +/// Opens the Sanitize prompt; the host routes a Proceed to `finish_sanitize`. +pub(crate) fn open_sanitize(app: &mut PdfCraftApp) { + let prompt = StandardPrompt::custom(tl!("Sanitizing removes hidden information from the document: metadata, file attachments, comments, form fields (flattened), hidden text and layers, bookmarks, links, actions and scripts, and private application data.")) + .title(tl!("Sanitize document")) + .paragraph(tl!("Save the document afterwards; saving rewrites the whole file so nothing removed stays in it.")) + .button(PromptChoice::Proceed, tl!("Sanitize")) + .button(PromptChoice::Cancel, tl!("Cancel")) + .tag("redact.sanitize"); + crate::dialogs::host::open(app, prompt); +} + +/// Remove hidden information while `app.hidden_draft` holds the categories found. +pub(crate) fn show_hidden(app: &mut PdfCraftApp, ui: &mut Ui) { + let Some(mut draft) = app.hidden_draft.take() else { return }; + let mut open = true; + let removable = draft.found.iter().any(|f| f.2 && f.1 > 0); + let shown = FormDialog::new(tl!("Remove hidden information"), Bind::bound(&mut draft)) + .opened(Bind::bound(&mut open)) + .ok_label(tl!("Remove")) + .ok_enabled(removable) + .show(ui, |ui, _, d: &mut HiddenDraft| { + Text::new(tl!("Select the items to remove from this document.")).shade(Shade::Muted).show(ui); + for (h, n, on) in d.found.iter_mut() { + Checkbox::new(Bind::bound(on)).label(tl!(h.label())).enabled(*n > 0).show(ui); + let count = if *n == 0 { tl!("None found").to_string() } else { n.to_string() }; + Text::new(count).shade(Shade::Muted).show(ui); + } + Text::new(tl!("Form fields are flattened: their values stay visible. Saving rewrites the whole file.")).shade(Shade::Muted).show(ui); + true + }); + match (shown.accepted, shown.closed) { + (Some(d), _) => { + let which: Vec = d.found.iter().filter(|f| f.2 && f.1 > 0).map(|f| f.0).collect(); + let n: usize = d.found.iter().filter(|f| f.2).map(|f| f.1).sum(); + if app.apply_edit(Edit::RemoveHidden { which }) { + if let Some((_, id)) = app.active_ids() { + app.renew_recovery(id); + } + if n == 1 { + app.notify_tr("Removed 1 hidden item. Save to remove them from the file."); + } else { + app.notify_fmt("Removed {n} hidden items. Save to remove them from the file.", &[("n", &n.to_string())]); + } + } + } + (None, Some(_)) => {} + (None, None) => app.hidden_draft = Some(draft), + } +} diff --git a/crates/ui-egui/src/tools/redact_ui/tool.rs b/crates/ui-egui/src/tools/redact_ui/tool.rs new file mode 100644 index 0000000000..4f0f804866 --- /dev/null +++ b/crates/ui-egui/src/tools/redact_ui/tool.rs @@ -0,0 +1,171 @@ +//! The Redact tool on the pages: a press over text selects it (the selection becomes marks when +//! it ends), a press on free page space draws a box that becomes one mark. + +use craft::behavior::{CancelReason, Cursor, CursorIcon}; +use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; +use craft::ui::primitives::Draw; +use egui::Pos2; +use pdfcraft_engine::rect_quad; +use pdfcraft_render::DocInfo; + +use crate::QuickTool; +use crate::canvas::{DocView, PageBoxDrag, PageSelectTool, PlacedPage, ToolMarks}; +use crate::canvas::PageXform; + +/// The smallest box, in screen points on each side, that counts as a mark. +const LEAST_BOX: f32 = 3.0; + +/// What the pointer's press is doing. +enum Gesture { + Idle, + /// A text selection the select tool runs. + Text, + /// A box being drawn. + Box, +} + +/// What a finished gesture asks the document for. +enum RedactResult { + /// A box on `page`, as a user-space quad. + Area { page: usize, quad: [f64; 8] }, + /// A text selection that ended; the selection holds what to mark. + Text { page: usize }, +} + +/// The Redact tool for one pass. +pub(crate) struct RedactTool<'a> { + select: PageSelectTool<'a>, + drag: PageBoxDrag, + placed: &'a [PlacedPage], + info: &'a DocInfo, + over_text: Box bool + 'a>, + gesture: Gesture, + text_page: Option, + finished: Option, +} + +impl<'a> RedactTool<'a> { + /// The tool over the placed pages, with the select tool that runs text selections and the + /// test of whether a screen point is over text (the same one the I-beam uses). + pub(crate) fn new(select: PageSelectTool<'a>, placed: &'a [PlacedPage], info: &'a DocInfo, over_text: impl Fn(Pos2) -> bool + 'a) -> Self { + Self { select, drag: PageBoxDrag::default(), placed, info, over_text: Box::new(over_text), gesture: Gesture::Idle, text_page: None, finished: None } + } + + /// After the host ran: hands a finished gesture to the view as a pending redaction, or as a + /// refusal when a selected page's text could not be read. + pub(crate) fn finished(self, view: &mut DocView) { + match self.finished { + Some(RedactResult::Area { page, quad }) => { + view.pending_redaction = Some((QuickTool::Redact, vec![(page, vec![quad])], page)); + } + // Across pages: a mark on each page it covers, once all are read; refused when one of + // them could not be read, rather than leave it unmarked. + Some(RedactResult::Text { page }) => match view.tool_marks(QuickTool::Redact, true, Some(page), true, self.info) { + ToolMarks::Marks(marks, head) => { + view.clear_selection(); + view.pending_redaction = Some((QuickTool::Redact, marks, head)); + } + ToolMarks::Unreadable => view.redaction_refused = true, + ToolMarks::None => {} + }, + None => {} + } + } + + fn placed_at(&self, p: Pos2) -> Option<&'a PlacedPage> { + self.placed.iter().find(|placed| placed.rect.contains(p)) + } + + /// A screen point of `placed` in the page's user space. + fn to_user(&self, placed: &PlacedPage, p: Pos2) -> Option<[f64; 2]> { + let xf = PageXform::of(placed, self.info); + let (vx, vy) = xf.screen_to_view(p); + let u = self.info.pages.get(placed.page)?.view_to_user(vx, vy); + Some([u[0] as f64, u[1] as f64]) + } +} + +impl CanvasTool for RedactTool<'_> { + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { + self.select.each_pass(cx); + } + + fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { + let Some(placed) = self.placed_at(pointer.pos) else { return ToolAction::Ignored }; + if (self.over_text)(pointer.pos) { + let action = self.select.press(pointer, cx); + match action { + ToolAction::Claimed => { + self.gesture = Gesture::Text; + self.text_page = Some(placed.page); + } + // A double click selects a word whole: it ends the selection at once. + ToolAction::Done => self.finished = Some(RedactResult::Text { page: placed.page }), + _ => {} + } + return action; + } + self.drag.press(placed, pointer.pos); + self.gesture = Gesture::Box; + ToolAction::Claimed + } + + fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + match self.gesture { + Gesture::Text => self.select.drag(pointer, cx), + Gesture::Box => self.drag.drag(pointer.pos), + Gesture::Idle => {} + } + } + + fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + match std::mem::replace(&mut self.gesture, Gesture::Idle) { + Gesture::Text => { + self.select.release(pointer, cx); + if let Some(page) = self.text_page.take() { + self.finished = Some(RedactResult::Text { page }); + } + } + Gesture::Box => { + self.drag.drag(pointer.pos); + // A click with no drag marks nothing: `release` gives no box below the least size. + if let Some((page, rect)) = self.drag.release(LEAST_BOX) + && let Some(placed) = self.placed.iter().find(|p| p.page == page) + && let (Some(a), Some(b)) = (self.to_user(placed, rect.min), self.to_user(placed, rect.max)) + { + self.finished = Some(RedactResult::Area { page, quad: rect_quad([a[0], a[1], b[0], b[1]]) }); + } + } + Gesture::Idle => {} + } + } + + fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + self.select.hover(pointer, cx); + } + + fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) { + if matches!(std::mem::replace(&mut self.gesture, Gesture::Idle), Gesture::Text) { + self.select.cancel(reason, cx); + } + self.text_page = None; + self.drag = PageBoxDrag::default(); + } + + fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { + self.select.paint(draw, cx); + // PLAN: assumed `PageBoxDrag::paint(&self, &ToolContext)` draws the box with marching ants (pdf-canvas-w18) + self.drag.paint(cx); + } + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Mark Page Range command") + } + + fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + match cx.pointer { + Some(p) if self.placed_at(p.pos).is_some() && !(self.over_text)(p.pos) => Cursor::System(CursorIcon::Crosshair), + _ => self.select.cursor(cx), + } + } +} diff --git a/crates/ui-egui/tests/it/redact.rs b/crates/ui-egui/tests/it/redact.rs index 780b978a2c..edf16fff53 100644 --- a/crates/ui-egui/tests/it/redact.rs +++ b/crates/ui-egui/tests/it/redact.rs @@ -4,7 +4,7 @@ use egui::Pos2; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use pdfcraft_ui_egui::{Dialog, PdfCraftApp, SaveTarget}; +use pdfcraft_ui_egui::{PdfCraftApp, SaveTarget}; fn harness() -> Harness<'static, PdfCraftApp> { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { @@ -65,7 +65,7 @@ fn marking_applying_and_clearing() { // Redact all asks first; Apply removes the marks (and the page's fields under them). h.get_by_label("Redact all").click(); h.run_steps(3); - assert_eq!(h.state().dialog, Some(Dialog::RedactApply)); + h.get_by_label("Apply"); h.get_by_label("Apply").click(); h.run_steps(4); let s = h.state(); @@ -475,7 +475,6 @@ fn reverting_after_apply_redactions_saves_in_place_again() { assert_eq!(h.state().views[0].redactions_applied, 1); assert!(h.state_mut().execute("file.revert")); h.run_steps(2); - assert_eq!(h.state().dialog, Some(Dialog::Revert)); h.get_all_by_label("Revert").last().expect("the button").click(); h.run_steps(3); assert_eq!(h.state().views[0].redactions_applied, 0); @@ -493,7 +492,10 @@ fn redaction_codes_become_the_overlay_text() { h.get_by_label("Redaction Tool Properties"); h.get_by_label("Use overlay text").click(); h.run_steps(2); - h.state_mut().redact_prefs.overlay = "CONFIDENTIAL".into(); + h.get_by_label("Custom text").click(); + h.run_steps(1); + h.get_by_label("Custom text").type_text("CONFIDENTIAL"); + h.run_steps(2); h.get_by_label("Redaction code:").click(); h.run_steps(2); h.get_by_label("(b)(7)(C)").click(); @@ -561,12 +563,14 @@ fn redaction_properties_survive_a_restart() { // dropped, the rest kept. let mut odd = PdfCraftApp::new(); odd.restore( - r#"{"redact_prefs":{"outline":[2,0,0],"opacity":0.7,"code_set":"nope","codes":["(b)(6)","bogus"],"use_overlay":true,"use_code":true}}"#, + r#"{"redact_prefs":{"outline":[2,0,0],"opacity":0.7,"code_set":"nope","codes":["(b)(6)","bogus"],"use_overlay":true,"use_code":true,"size":500,"align":3}}"#, ); let p = &odd.redact_prefs; assert_eq!((p.outline, p.opacity), ([0.89, 0.13, 0.13], 0.7)); assert_eq!(p.code_set.id, pdfcraft_engine::REDACTION_CODE_SETS[0].id); assert_eq!(p.overlay_text(), "(b)(6)"); + let look = pdfcraft_engine::OverlayLook::default(); + assert_eq!((p.look.size, p.look.align), (look.size, look.align), "an out-of-range size and alignment keep the defaults"); } /// "Make properties default" off: OK keeps the values for this run only, the saved defaults @@ -582,8 +586,8 @@ fn redaction_properties_for_this_run_only_and_cancel() { h.get_by_label("Opacity:"); h.get_by_label("Make properties default").click(); h.run_steps(3); - assert!(!h.state().redact_prefs.remember); - h.state_mut().redact_prefs.outline = [0.0, 0.0, 1.0]; + assert!(!h.state().redact_props.as_ref().unwrap().remember); + h.state_mut().redact_props.as_mut().unwrap().outline = [0.0, 0.0, 1.0]; h.get_by_label("OK").click(); h.run_steps(2); assert_eq!(h.state().redact_prefs.outline, [0.0, 0.0, 1.0], "used for this run"); @@ -594,7 +598,7 @@ fn redaction_properties_for_this_run_only_and_cancel() { // Cancel discards the edits made while the dialog was open. assert!(h.state_mut().execute("redact.properties")); h.run_steps(2); - h.state_mut().redact_prefs.opacity = 0.2; + h.state_mut().redact_props.as_mut().unwrap().opacity = 0.2; h.get_by_label("Cancel").click(); h.run_steps(2); assert_eq!(h.state().redact_prefs.opacity, 1.0, "cancelled"); @@ -657,7 +661,7 @@ fn removing_hidden_information_and_sanitizing() { h.run_steps(2); h.get_by_label("Remove hidden information"); { - let d = &h.state().hidden_draft; + let d = h.state().hidden_draft.as_ref().unwrap(); let fields = d.found.iter().find(|f| f.0 == pdfcraft_engine::Hidden::FormFields).unwrap(); assert_eq!((fields.1, fields.2), (5, true), "five fields, checked"); }