diff --git a/crates/ui-egui/src/tools/bulk_fields.rs b/crates/ui-egui/src/tools/bulk_fields.rs index d41962b89c..4b1780a52a 100644 --- a/crates/ui-egui/src/tools/bulk_fields.rs +++ b/crates/ui-egui/src/tools/bulk_fields.rs @@ -23,7 +23,7 @@ use egui::{Context, Ui}; use pdfcraft_engine::{BorderStyle, CheckStyle, DocId, Edit, FieldFont, FieldLookPatch, FieldProps, FormFieldKind, field_flags}; use serde_json::{Value as Json, json}; -use crate::colours::{self, RecentColours}; +use crate::comments::colours::{self, RecentColours}; use crate::{PdfCraftApp, prepare}; /// One property shown by the dialog. `apply` is explicit: merely opening the dialog, or @@ -424,13 +424,7 @@ fn apply(app: &mut PdfCraftApp, draft: &Draft) -> Result<(), Label> { /// One property: a group box whose check box is `apply`, enclosing the control, which binds the value as a `Mixed`. /// An edit makes a mixed value concrete. `unknown` shows the control as mixed while the row is not applied, for a value the /// control cannot show. -fn row( - ui: &mut Ui, - label: &str, - c: &mut Change, - unknown: bool, - control: impl FnOnce(&mut Ui, &mut Mixed), -) { +fn row(ui: &mut Ui, label: &str, c: &mut Change, unknown: bool, control: impl FnOnce(&mut Ui, &mut Mixed)) { let Change { value, mixed, apply } = c; let hidden = unknown && !*apply; GroupBox::apply(tl!(label).to_owned(), Bind::bound(apply)).show(ui, |ui, _| { @@ -599,7 +593,8 @@ fn appearance(ui: &mut Ui, d: &mut Draft, recent: &RecentColours, request: &mut /// The Options tab: what applies to the kind of field selected. fn options(ui: &mut Ui, d: &mut Draft) { if d.text_fields || d.choice_fields { - let aligns: Vec> = [(0, "Left"), (1, "Center"), (2, "Right")].into_iter().map(|(v, label)| Entry::new(v, tl!(label).to_owned())).collect(); + let aligns: Vec> = + [(0, "Left"), (1, "Center"), (2, "Right")].into_iter().map(|(v, label)| Entry::new(v, tl!(label).to_owned())).collect(); choose(ui, "Alignment:", &mut d.align, &aligns); } if d.text_fields { diff --git a/crates/ui-egui/src/tools/comments.rs b/crates/ui-egui/src/tools/comments.rs index 154c8fc66b..8720611b22 100644 --- a/crates/ui-egui/src/tools/comments.rs +++ b/crates/ui-egui/src/tools/comments.rs @@ -24,7 +24,7 @@ use crate::theme::{self, Tokens}; use crate::{QuickTool, icons}; mod bridge; -mod colours; +pub(crate) mod colours; mod composer; mod geometry; mod menu; diff --git a/crates/ui-egui/src/tools/fill_sign.rs b/crates/ui-egui/src/tools/fill_sign.rs index 27ce3d90b6..4ade5cc0c4 100644 --- a/crates/ui-egui/src/tools/fill_sign.rs +++ b/crates/ui-egui/src/tools/fill_sign.rs @@ -4,14 +4,14 @@ //! can be moved, deleted and undone like any comment. use base64::Engine as _; -use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId, keyed}; use craft::behavior::selection::Selection; +use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId, keyed}; use craft::keymap::CommandRef; use craft::review::ui::signature::{SignatureSettings, paint_signature}; use craft::review::{SavedSignature, SignatureImage as SavedImage}; use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; -use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Show as _, ShowCollection as _}; -use craft::ui::list::{SelectMode, ThumbAspect}; +use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, SelectMode, Show as _, ShowCollection as _}; +use craft::ui::list::ThumbAspect; use craft::ui::primitives::Draw; use craft::ui::style::DataColor; use craft::ui::tile_grid::{Tile, TileActionPlace, TileGrid}; @@ -19,7 +19,8 @@ use egui::Pos2; use pdfcraft_engine::{BorderShape, Edit, FillMark, NewAnnotation, Rgb, Shape, Style}; use pdfcraft_render::{DocInfo, PageInfo}; -use crate::canvas::{PageToolCx, PageXform}; +use crate::canvas::PageXform; +use crate::canvas::page_tools::PageToolCx; use crate::comments::CommentView; pub(crate) mod scan; diff --git a/crates/ui-egui/src/tools/fill_sign/scan.rs b/crates/ui-egui/src/tools/fill_sign/scan.rs index 75f360a144..7754b15a2a 100644 --- a/crates/ui-egui/src/tools/fill_sign/scan.rs +++ b/crates/ui-egui/src/tools/fill_sign/scan.rs @@ -5,8 +5,8 @@ use craft::behavior::kurbo::{Point, Rect as DocRect, Size}; use craft::behavior::{CanvasView, EditEvent, PixelSize}; use craft::host::queue::{JobQueue, Priority, QueueOptions}; use craft::host::{Host, PickId, PickRequest, Picked, Wake}; -use craft::review::{SignatureDraft, SignatureImage as PadImage}; use craft::review::ui::signature::DrawPad; +use craft::review::{SignatureDraft, SignatureImage as PadImage}; use craft::theme::variant::Tone; use craft::ui::buttons::{Button, IconButton}; use craft::ui::canvas::{Canvas, CropOutside, CropOverlay, PixelRect, RasterDisplay, RasterSource}; @@ -333,18 +333,10 @@ impl ScanTabState { let mut crop = crop_of(scan.frame); let bounds = DocRect::new(0.0, 0.0, pw, ph); let corners = [Point::new(0.0, 0.0), Point::new(pw, 0.0), Point::new(pw, ph), Point::new(0.0, ph)]; - let shown = Canvas::new(tl!("Photo")) - .view(Bind::bound(&mut self.view)) - - .document(Size::new(pw, ph)) - .show_at(ui, room, |ui, body| { - RasterDisplay::new(tl!("Signature photo"), &source).show_at(ui, body.rect); - CropOverlay::new(tl!("Frame"), Bind::bound(&mut crop)) - .outside(CropOutside::NewFrame) - .area(corners) - .bounds(bounds) - .show_at(ui, body.rect) - }); + let shown = Canvas::new(tl!("Photo")).view(Bind::bound(&mut self.view)).document(Size::new(pw, ph)).show_at(ui, room, |ui, body| { + RasterDisplay::new(tl!("Signature photo"), &source).show_at(ui, body.rect); + CropOverlay::new(tl!("Frame"), Bind::bound(&mut crop)).outside(CropOutside::NewFrame).area(corners).bounds(bounds).show_at(ui, body.rect) + }); let Some(overlay) = shown.inner else { return }; let mut commit = false; for event in overlay.edit.events.iter() { diff --git a/crates/ui-egui/src/tools/fill_sign/type_box.rs b/crates/ui-egui/src/tools/fill_sign/type_box.rs index a25d605dc0..60db39aed8 100644 --- a/crates/ui-egui/src/tools/fill_sign/type_box.rs +++ b/crates/ui-egui/src/tools/fill_sign/type_box.rs @@ -3,16 +3,16 @@ use std::ops::Range; use craft::behavior::kurbo::Point; -use craft::text::ui::{CaretLine, EditKind, EditorEnd, HostLine, HostRun, TextEditor, TextEditorHost, TextSelection}; // PLAN: assumed facade path craft::text -use craft::ui::contract::{Bind, Show as _}; // PLAN: assumed +use craft::pages::ui::PageBody; +use craft::text::ui::editor::{CaretLine, EditKind, EditorEnd, HostLine, HostRun, TextEditor, TextEditorHost, TextSelection}; +use craft::ui::contract::{Bind, Show as _}; use egui::{Color32, FontId, Pos2, Rect, Stroke, vec2}; use pdfcraft_engine::{BorderShape, Edit}; use pdfcraft_render::DocInfo; use super::{TypedLook, typed_with}; -// PLAN: assumed `PageBody` (pdf-canvas-w4) and `PageSession { fill_text, fill_selection, .. }` (L-171) under `crate::canvas`. -use crate::canvas::{PageBody, PageSession}; +use crate::canvas::PageSession; /// Line height over font size, as the typewriter annotation lays its text out. const LINE: f32 = 1.2; @@ -81,11 +81,7 @@ impl TypeBoxHost<'_> { let ranges = self.line_ranges(); let Some(range) = ranges.get(line.min(ranges.len().saturating_sub(1))).cloned() else { return 0 }; let columns = self.columns(range.clone()); - let at = columns - .iter() - .enumerate() - .min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())) - .map_or(0, |(i, _)| i); + let at = columns.iter().enumerate().min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())).map_or(0, |(i, _)| i); range.start + at } @@ -118,12 +114,12 @@ impl TextEditorHost for TypeBoxHost<'_> { self.text } - fn replace(&mut self, range: Range, text: &str, _kind: EditKind) -> bool { + fn replace(&mut self, range: Range, text: &str, _kind: EditKind) -> Option { let count = self.text.chars().count(); let (start, end) = (range.start.min(count), range.end.clamp(range.start.min(count), count)); let (a, b) = (self.byte_of(start), self.byte_of(end)); self.text.replace_range(a..b, text); - true + Some(text.chars().count()) } fn hit(&mut self, at: Point) -> (usize, usize) { diff --git a/crates/ui-egui/src/tools/forms_ui/editor.rs b/crates/ui-egui/src/tools/forms_ui/editor.rs index 0ca1ce271a..deaed82c0f 100644 --- a/crates/ui-egui/src/tools/forms_ui/editor.rs +++ b/crates/ui-egui/src/tools/forms_ui/editor.rs @@ -206,9 +206,7 @@ struct FieldHost<'a> { impl FieldHost<'_> { /// Run `read` on the layout of the draft as it is and the canvas view. fn with(&mut self, read: impl FnOnce(&FieldLayout, &CanvasView) -> R) -> R { - let laid = self - .laid - .get_or_insert_with(|| FieldLayout::build(&self.ctx, self.field, self.widget, self.geo, self.text.as_str(), self.caret)); + let laid = self.laid.get_or_insert_with(|| FieldLayout::build(&self.ctx, self.field, self.widget, self.geo, self.text.as_str(), self.caret)); read(laid, &self.view) } @@ -223,10 +221,10 @@ impl TextEditorHost for FieldHost<'_> { self.text } - fn replace(&mut self, range: Range, text: &str, _kind: EditKind) -> bool { + fn replace(&mut self, range: Range, text: &str, _kind: EditKind) -> Option { let len = self.text.chars().count(); if range.start > range.end || range.end > len { - return false; + return None; } let byte = |s: &str, at: usize| s.char_indices().nth(at).map_or(s.len(), |(b, _)| b); // The framework drops a refused replace whole, so a paste keeps the part that fits here. @@ -241,12 +239,13 @@ impl TextEditorHost for FieldHost<'_> { after = room.fitted_edit(&before, &after).0; } if after == before && insert.chars().count() < text.chars().count() { - return false; + return None; } - // PLAN: framework gap F-13: the editor puts the caret after the whole `text` it gave, so a trimmed insert leaves it past the kept part. + // The editor puts the caret after the chars kept, not after the whole `text` it gave. + let kept = after.chars().count().saturating_sub(len - range.len()).min(text.chars().count()); *self.text = after; self.laid = None; - true + Some(kept) } fn hit(&mut self, at: Point) -> (usize, usize) { @@ -266,10 +265,7 @@ impl TextEditorHost for FieldHost<'_> { fn underline_segments(&mut self, range: Range) -> Vec<[Point; 2]> { self.with(|laid, view| { - laid.quads(range) - .into_iter() - .map(|[_, _, right, left]| [Self::doc(laid, view, left), Self::doc(laid, view, right)]) - .collect() + laid.quads(range).into_iter().map(|[_, _, right, left]| [Self::doc(laid, view, left), Self::doc(laid, view, right)]).collect() }) } @@ -366,13 +362,10 @@ pub(crate) fn show(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, d let types = f.kind == FormFieldKind::Text || (combo && editable_combo(f)); let mut ended = None; if types { - let room = (f.kind == FormFieldKind::Text && f.has(field_flags::DO_NOT_SCROLL)) - .then(|| doc.field_text_box(&focus.name, widget)) - .flatten(); + let room = (f.kind == FormFieldKind::Text && f.has(field_flags::DO_NOT_SCROLL)).then(|| doc.field_text_box(&focus.name, widget)).flatten(); let Some(focus) = view.forms.focus.as_mut() else { return }; let Focus { text, selection, .. } = focus; - let mut host = - FieldHost { ctx: ui.ctx().clone(), view: body.view, field: f, widget: w, geo, room, text, caret: selection.caret, laid: None }; + let mut host = FieldHost { ctx: ui.ctx().clone(), view: body.view, field: f, widget: w, geo, room, text, caret: selection.caret, laid: None }; // PLAN: paints through an egui `Painter` with black text, as pdf-forms-w7's `paint_page` does; both move to the `Draw` tokens and the field's `/DA` colour together. let painter = ui.painter_at(rect.intersect(body.rect)); painter.rect_filled(rect, CornerRadius::ZERO, PAPER); @@ -405,4 +398,3 @@ pub(crate) fn show(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, d commit(view, form); } } - diff --git a/crates/ui-egui/src/tools/prepare/dialog.rs b/crates/ui-egui/src/tools/prepare/dialog.rs index 22b76cdb81..1a0ea73290 100644 --- a/crates/ui-egui/src/tools/prepare/dialog.rs +++ b/crates/ui-egui/src/tools/prepare/dialog.rs @@ -104,7 +104,7 @@ pub(crate) fn finish(app: &mut PdfCraftApp) { let key = request.key.clone(); app.open_colour_picker(&mut app.dialogs, request, move |app, colour: Srgba| { if let Some(dialog) = app.dialogs.get_mut::() { - dialog.set_colour(&key, crate::comments::to_rgb(colour)); + dialog.set_colour(&key, crate::comments::colours::to_rgb(colour)); } }); } @@ -126,9 +126,8 @@ pub(crate) fn finish(app: &mut PdfCraftApp) { let prefix = field.rsplit_once('.').filter(|_| !typed.contains('.')).map(|(p, _)| format!("{p}.")).unwrap_or_default(); let name = format!("{prefix}{typed}"); let after = form(app); - let index = object - .and_then(|obj| after.as_ref()?.iter().find(|f| f.name == name)?.widgets.iter().position(|w| w.obj == obj)) - .unwrap_or(widget); + let index = + object.and_then(|obj| after.as_ref()?.iter().find(|f| f.name == name)?.widgets.iter().position(|w| w.obj == obj)).unwrap_or(widget); if let (Some(before), Some(after)) = (before, after) { let n = pdfcraft_engine::form_calculations_changed(&before, &after).iter().filter(|f| **f != name).count(); if n > 0 { @@ -198,7 +197,9 @@ impl StackDialog for FieldPropsDialog { return None; } match out.closed { - Some(CloseReason::Activated) if finish_held && out.picked != Some(CANCEL_BUTTON) => Some(self.held.finish().map_or(DialogResult::Cancel, DialogResult::Ok)), + Some(CloseReason::Activated) if finish_held && out.picked != Some(CANCEL_BUTTON) => { + Some(self.held.finish().map_or(DialogResult::Cancel, DialogResult::Ok)) + } Some(_) => Some(DialogResult::Cancel), None => None, } diff --git a/crates/ui-egui/src/tools/prepare/tool.rs b/crates/ui-egui/src/tools/prepare/tool.rs index 8f13996c95..6ac850a857 100644 --- a/crates/ui-egui/src/tools/prepare/tool.rs +++ b/crates/ui-egui/src/tools/prepare/tool.rs @@ -9,10 +9,10 @@ use craft::behavior::press::{PointerButton, PressPhase}; use craft::behavior::{CancelReason, Cursor, CursorIcon, EditEvent, Input, Metrics}; use craft::draw::ui::transform::TransformBox; use craft::ui::canvas::{CanvasTool, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; -use craft::ui::contract::{Bind, Common, Component, Cx, MeasureCx, PaintUi, Props, Role, Ui}; +use craft::ui::contract::{Bind, Common, Component, Cx, MeasureCx, PaintUi, Props, Role}; use craft::ui::primitives::{Draw, PaintShape, StrokeWidth, TextRun}; use craft::ui::style::{ComponentStyle, StyleColor, StyleCx, TypeRole}; -use egui::{CornerRadius, Pos2, Rect, Response, Vec2, vec2}; +use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2, vec2}; use pdfcraft_engine::{Edit, FieldProps, FormField}; use super::{FieldTool, Gesture, PrepareView, delete_selected, place_tab_badge, screen_rect, table_rect, to_user, user_rect}; @@ -175,9 +175,12 @@ impl CanvasTool for PrepareTool<'_> { return ToolAction::Claimed; } // A drag that began on a field part moves the field the part's press selected. - let on_selected = self.view.prepare.selected.clone().filter(|key| { - widget_rect(self.view, self.form, key).is_some_and(|(page, r)| page == placed.page && r.contains(pointer.pos)) - }); + let on_selected = self + .view + .prepare + .selected + .clone() + .filter(|key| widget_rect(self.view, self.form, key).is_some_and(|(page, r)| page == placed.page && r.contains(pointer.pos))); if let Some(widget) = on_selected { let slop = f64::from(cx.slop); let gesture = MoveGesture::press(&ConstrainStyle::new(slop, slop), point(pointer.pos), pointer.mods, Directions::Four); diff --git a/crates/ui-egui/src/tools/redact_ui/dialogs.rs b/crates/ui-egui/src/tools/redact_ui/dialogs.rs index 4ce856641d..978f46a53b 100644 --- a/crates/ui-egui/src/tools/redact_ui/dialogs.rs +++ b/crates/ui-egui/src/tools/redact_ui/dialogs.rs @@ -3,6 +3,7 @@ use craft::pages::ui::range::{PageRangeChoices, PageRangeOptions}; use craft::pages::{PageRange, PageScope}; +use craft::theme::Srgba; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; @@ -12,31 +13,51 @@ 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::runtime::requests::ColorRequest; 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::comments::colours::{self, RecentColours}; 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 { +const FILL_KEY: &str = "redact.fill"; +const FONT_KEY: &str = "redact.font"; +const OUTLINE_KEY: &str = "redact.outline"; +const HOVER_KEY: &str = "redact.hover"; + +/// A labelled colour row: `palette` over `current`, `Some` when the user picked a colour. An "Other colour…" request +/// goes to `request`, which the dialog's owner answers with the app's picker. +fn colour_row( + ui: &mut Ui, + label: &'static str, + current: Rgb, + key: &'static str, + enabled: bool, + recent: &RecentColours, + request: &mut Option, +) -> 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); + let pick = colours::palette(ui, label, Some(current), key, recent); + picked = pick.picked; + if pick.request.is_some() { + *request = pick.request; + } }); picked } -fn props_rows(ui: &mut Ui, d: &mut RedactPrefs) { +fn props_rows(ui: &mut Ui, d: &mut RedactPrefs, recent: &RecentColours, request: &mut Option) { 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) { + let choice = colours::fill_choice(ui, d.fill, FILL_KEY, recent); + if let Some(fill) = choice.choice { d.fill = fill; } + if choice.request.is_some() { + *request = choice.request; + } 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, _| { @@ -86,7 +107,7 @@ fn props_rows(ui: &mut Ui, d: &mut RedactPrefs) { 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) { + if let Some(c) = colour_row(ui, tl!("Font colour:"), d.look.color, FONT_KEY, on, recent, request) { d.look.color = c; } Checkbox::new(Bind::bound(&mut d.look.repeat)).label(tl!("Repeat overlay text")).enabled(on).show(ui); @@ -99,15 +120,18 @@ fn props_rows(ui: &mut Ui, d: &mut RedactPrefs) { }); }); FieldGroup::new(tl!("Redaction mark appearance")).show(ui, |ui, _| { - if let Some(c) = colour_row(ui, tl!("Outline colour:"), d.outline, "redact.outline", true) { + if let Some(c) = colour_row(ui, tl!("Outline colour:"), d.outline, OUTLINE_KEY, true, recent, request) { d.outline = c; } - if let Some(c) = colour_row(ui, tl!("Fill colour:"), d.hover_fill, "redact.hover", true) { + if let Some(c) = colour_row(ui, tl!("Fill colour:"), d.hover_fill, HOVER_KEY, true, recent, request) { 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); + 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); } @@ -121,10 +145,26 @@ fn props_rows(ui: &mut Ui, d: &mut RedactPrefs) { 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 recent = app.recent_colours.clone(); + let mut request = None; 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); + props_rows(ui, d, &recent, &mut request); true }); + if let Some(request) = request { + let key = request.key.clone(); + app.open_colour_picker(crate::colour_picker::PickerHost::App, request, move |app: &mut PdfCraftApp, colour: Srgba| { + let Some(draft) = app.redact_props.as_mut() else { return }; + let colour = colours::to_rgb(colour); + match key.as_str() { + FILL_KEY => draft.fill = Some(colour), + FONT_KEY => draft.look.color = colour, + OUTLINE_KEY => draft.outline = colour, + HOVER_KEY => draft.hover_fill = colour, + _ => {} + } + }); + } match (shown.accepted, shown.closed) { (Some(prefs), _) => { if prefs.remember { @@ -171,7 +211,10 @@ fn search_rows(ui: &mut Ui, d: &mut SearchDraft, import: &mut bool) { 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); + 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")) @@ -193,7 +236,11 @@ fn search_rows(ui: &mut Ui, d: &mut SearchDraft, import: &mut bool) { 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())]) }; + 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); } }); @@ -236,7 +283,12 @@ pub(crate) fn open_apply(app: &mut PdfCraftApp) { 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())]) + 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")) diff --git a/crates/ui-egui/src/tools/redact_ui/tool.rs b/crates/ui-egui/src/tools/redact_ui/tool.rs index 4f0f804866..aef193b75f 100644 --- a/crates/ui-egui/src/tools/redact_ui/tool.rs +++ b/crates/ui-egui/src/tools/redact_ui/tool.rs @@ -2,6 +2,7 @@ //! it ends), a press on free page space draws a box that becomes one mark. use craft::behavior::{CancelReason, Cursor, CursorIcon}; +use craft::pages::ui::PlacedPage; use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft::ui::primitives::Draw; use egui::Pos2; @@ -9,8 +10,9 @@ use pdfcraft_engine::rect_quad; use pdfcraft_render::DocInfo; use crate::QuickTool; -use crate::canvas::{DocView, PageBoxDrag, PageSelectTool, PlacedPage, ToolMarks}; use crate::canvas::PageXform; +use crate::canvas::page_select::PageSelectTool; +use crate::canvas::{DocView, PageBoxDrag, ToolMarks}; /// The smallest box, in screen points on each side, that counts as a mark. const LEAST_BOX: f32 = 3.0; @@ -48,7 +50,16 @@ 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 } + 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 diff --git a/crates/ui-egui/src/tools/sign_ui.rs b/crates/ui-egui/src/tools/sign_ui.rs index 2a3e479e01..f0862720db 100644 --- a/crates/ui-egui/src/tools/sign_ui.rs +++ b/crates/ui-egui/src/tools/sign_ui.rs @@ -9,21 +9,21 @@ use craft::review::{SavedSignature, SignatureImage}; use pdfcraft_engine::sign::{self, Appearance, AppearanceLabels, Certificate, DigitalId, Name, PrivateKey}; use pdfcraft_engine::{SignOptions, SignatureInfo, SignatureStatus, StatusCaptions}; +use crate::FilePurpose; use crate::PdfCraftApp; use crate::canvas::{DocView, Snapshot, SnapshotKind}; -use crate::workflows::FilePurpose; +pub(crate) mod cert_viewer; pub(crate) mod dialog; mod panel; pub(crate) mod tool; -pub(crate) mod cert_viewer; #[cfg(test)] use dialog::detail_lines; use dialog::graphic_of; pub(crate) use dialog::{appearance_labels, status_captions}; -pub(crate) use panel::{banner, panel, status_tone}; pub use panel::{CertTab, CertViewer, PanelAction, certificate_pem}; +pub(crate) use panel::{banner, panel, status_tone}; /// A digital ID the app knows about (Acrobat: Digital ID files). The file stays where it is; /// its password is asked for at each signing. @@ -186,7 +186,7 @@ pub struct SignView { /// Where new digital IDs are saved: next to the recovery folder (`…/PdfCraft/Digital IDs`, or /// `PdfCraftData/Digital IDs` in portable mode). fn id_dir() -> Option { - crate::platform::portable::data_dir().map(|d| d.join("Digital IDs")) + crate::recovery::default_dir().and_then(|d| d.parent().map(|p| p.join("Digital IDs"))) } /// Save a new digital ID as `.p12`, or ` 2.p12`, … when the name is taken. The file @@ -266,8 +266,7 @@ fn entry_unusable(u: &sign::windows::Unusable) -> DigitalIdEntry { impl PdfCraftApp { /// Export certificate: write `c` as PEM into a chosen folder, named after its subject. pub(crate) fn export_certificate(&mut self, c: &Certificate) { - // PLAN: assumed `safe_file_name(&str, &str) -> String` (pdf-shell-w13). - let name = format!("{}.cer", crate::files::safe_file_name(&c.display_name(), "attachment")); + let name = format!("{}.cer", craft::docpath::names::safe_file_name(&c.display_name(), "attachment")); self.write_files(&[(name, std::sync::Arc::new(certificate_pem(c).into_bytes()))], "Export certificate"); } @@ -792,7 +791,6 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - #[test] fn a_language_change_leaves_documents_without_a_drawn_state_alone() { if !crate::i18n::needs_catalogs() { diff --git a/crates/ui-egui/src/tools/sign_ui/cert_viewer.rs b/crates/ui-egui/src/tools/sign_ui/cert_viewer.rs index 2a2f28feea..dce6d1dcda 100644 --- a/crates/ui-egui/src/tools/sign_ui/cert_viewer.rs +++ b/crates/ui-egui/src/tools/sign_ui/cert_viewer.rs @@ -134,7 +134,10 @@ fn body(ui: &mut egui::Ui, v: &mut CertViewer, trusted: &[Certificate], trust: & } let Some(c) = v.chain.get(v.selected).cloned() else { return }; Stack::new().show(ui, |ui, _| { - let out = TabStrip::new(tl!("Certificate details")).kind(TabKind::Text).shown(v.tab).show_items(ui, &Tabs, &mut |tab, _| Tab::new(tab_label(*tab))); + let out = TabStrip::new(tl!("Certificate details")) + .kind(TabKind::Text) + .shown(v.tab) + .show_items(ui, &Tabs, &mut |tab, _| Tab::new(tab_label(*tab))); for event in out.response.events { if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event && let Some(tab) = keys.into_iter().last() diff --git a/crates/ui-egui/src/tools/sign_ui/dialog.rs b/crates/ui-egui/src/tools/sign_ui/dialog.rs index 14816fb7d8..71ef85adeb 100644 --- a/crates/ui-egui/src/tools/sign_ui/dialog.rs +++ b/crates/ui-egui/src/tools/sign_ui/dialog.rs @@ -16,15 +16,17 @@ use craft::ui::form::Field; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize}; use craft::ui::notices::{Notice, NoticeAction}; -use craft::ui::patterns::FormDialog; +use craft::ui::patterns::form_dialogs::FormDialog; use craft::ui::pickers::Select; use craft::ui::primitives::PaintShape; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::style::DataColor; use craft::ui::text::TextField; -use super::{Appearance, AppearanceLabels, DigitalIdEntry, KEY_ALGORITHMS, NewIdDraft, PdfCraftApp, SignDraft, SignGraphic, SignStep, StatusCaptions, sign}; -use crate::workflows::FilePurpose; +use super::{ + Appearance, AppearanceLabels, DigitalIdEntry, KEY_ALGORITHMS, NewIdDraft, PdfCraftApp, SignDraft, SignGraphic, SignStep, StatusCaptions, sign, +}; +use crate::FilePurpose; /// A line of explanatory text. fn caption(text: impl Into) -> impl Show { @@ -254,17 +256,18 @@ fn choose(ui: &mut egui::Ui, d: &mut SignDraft, ids: &[DigitalIdEntry], asked: & } else { let source = IdRows(ids); let mut selection = d.selected.map_or_else(Selection::default, Selection::single); - let out = List::::new(tl!("Digital IDs")) - .select(SelectMode::Single) - .selection(Bind::bound(&mut selection)) - .show_items(ui, &source, &mut |_, icx| match ids.get(icx.at) { + let out = List::::new(tl!("Digital IDs")).select(SelectMode::Single).selection(Bind::bound(&mut selection)).show_items( + ui, + &source, + &mut |_, icx| match ids.get(icx.at) { Some(e) => { let sub = details(e); // Names are as long as their owners made them: the row cuts them and the tip says them whole. ListRow::new(e.name.clone()).tooltip(format!("{}\n{sub}", e.name)).below(caption(sub), |_| {}) } None => ListRow::new(String::new()), - }); + }, + ); for event in out.events { match event { CollectionEvent::Selection(SelectionChange::Set(keys)) => { diff --git a/crates/ui-egui/src/tools/sign_ui/panel.rs b/crates/ui-egui/src/tools/sign_ui/panel.rs index ab3f52884b..ff36f771fe 100644 --- a/crates/ui-egui/src/tools/sign_ui/panel.rs +++ b/crates/ui-egui/src/tools/sign_ui/panel.rs @@ -195,14 +195,12 @@ fn line_row<'a>(s: &SignatureInfo, child: &Child, action: &'a RefCell row( - match s.status { - SignatureStatus::Valid => tl!("Signature is valid:"), - SignatureStatus::Unknown => tl!("Signature validity is UNKNOWN:"), - SignatureStatus::Invalid => tl!("Signature is INVALID:"), - } - .into(), - ) + Child::Status => row(match s.status { + SignatureStatus::Valid => tl!("Signature is valid:"), + SignatureStatus::Unknown => tl!("Signature validity is UNKNOWN:"), + SignatureStatus::Invalid => tl!("Signature is INVALID:"), + } + .into()) .strong(true), Child::Detail(line) => row(format!("• {line}").into()).ink(RowInk::Muted), Child::Heading => row(tl!("Signature Details").into()).section_heading(), diff --git a/crates/ui-egui/src/tools/sign_ui/tool.rs b/crates/ui-egui/src/tools/sign_ui/tool.rs index 16c80ad520..f54cde9723 100644 --- a/crates/ui-egui/src/tools/sign_ui/tool.rs +++ b/crates/ui-egui/src/tools/sign_ui/tool.rs @@ -1,12 +1,13 @@ //! The Digitally sign and Certify (visible signature) page tool: drag a rectangle on a page. use craft::behavior::{CancelReason, Cursor, CursorIcon}; +use craft::pages::ui::PlacedPage; use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft::ui::primitives::Draw; use egui::Pos2; use pdfcraft_render::DocInfo; -use crate::canvas::{PageBoxDrag, PageXform, PlacedPage}; +use crate::canvas::{PageBoxDrag, PageXform}; /// The least side, in screen points, of a drawn signature area. const LEAST_SIDE: f32 = 8.0; diff --git a/crates/ui-egui/src/workflows.rs b/crates/ui-egui/src/workflows.rs index ec68c47536..f0d12128b9 100644 --- a/crates/ui-egui/src/workflows.rs +++ b/crates/ui-egui/src/workflows.rs @@ -7,6 +7,7 @@ pub(super) mod create_multiple_ui; pub(super) mod create_ui; pub(super) mod export_ui; pub(super) mod files; +pub(crate) mod job_count; pub(super) mod js_dialogs; pub(super) mod js_ui; #[cfg(any(target_arch = "wasm32", test))] @@ -20,4 +21,4 @@ pub(super) mod print_paper; pub(super) mod print_ui; pub(super) mod scan_clean_ui; pub(super) mod web_print; -pub(crate) mod job_count; +pub(crate) use job_count::JobCount; diff --git a/crates/ui-egui/src/workflows/a11y_ui.rs b/crates/ui-egui/src/workflows/a11y_ui.rs index 849ff9a92b..9d619b6c7a 100644 --- a/crates/ui-egui/src/workflows/a11y_ui.rs +++ b/crates/ui-egui/src/workflows/a11y_ui.rs @@ -146,7 +146,8 @@ fn options_dialog(fields: &mut DialogFields, pages: usize, current: usize) -> Pa Param::new("category", tl!("Category:"), ParamKind::choice(categories, Some(category_id(Category::Document)))), ]; for rule in Rule::ALL { - params.push(Param::new(rule_key(rule), tl!(rule.description()), ParamKind::bool(true)).visible_when("category", category_id(rule.category()))); + params + .push(Param::new(rule_key(rule), tl!(rule.description()), ParamKind::bool(true)).visible_when("category", category_id(rule.category()))); } params.push( Param::custom("rules.all", tl!("Rules"), |ui, fields, _| { @@ -310,11 +311,7 @@ fn result_lines(report: &Report, collapsed: &BTreeSet, expanded: &BTre /// What opening a finding does: its tag when it has one, else its page. fn finding_action(report: &Report, rule: Rule, index: usize) -> Option { let f = report.result(rule)?.findings.get(index)?; - if let Some(object) = f.object { - Some(PanelAction::GoToTag(object, f.page, f.bbox)) - } else { - f.page.map(|p| PanelAction::GoTo(p, f.bbox)) - } + if let Some(object) = f.object { Some(PanelAction::GoToTag(object, f.page, f.bbox)) } else { f.page.map(|p| PanelAction::GoTo(p, f.bbox)) } } /// The summary line over the results. diff --git a/crates/ui-egui/src/workflows/actions_ui.rs b/crates/ui-egui/src/workflows/actions_ui.rs index 108054f060..8b73747422 100644 --- a/crates/ui-egui/src/workflows/actions_ui.rs +++ b/crates/ui-egui/src/workflows/actions_ui.rs @@ -20,8 +20,9 @@ use craft::ui::text::TextField; use egui::Ui; use pdfcraft_engine::actions::{Action, Step, builtin}; +use super::job_count::JobCount; +use crate::PdfCraftApp; use crate::notices::{self, ProgressKey, ProgressNotice}; -use crate::{JobCount, PdfCraftApp}; /// What a finished run reports: its summary, in the UI's language. pub struct ActionOutcome { @@ -260,7 +261,6 @@ impl PdfCraftApp { #[cfg(target_arch = "wasm32")] self.run_action_into(action, files, PathBuf::new()); #[cfg(not(target_arch = "wasm32"))] - self.pick_first(PickRequest::folder("action.results").title(tl!("Choose a folder for the results")), None, move |app, dir| { app.run_action_into(action, files, dir) }); diff --git a/crates/ui-egui/src/workflows/combine_grid.rs b/crates/ui-egui/src/workflows/combine_grid.rs index 7379950c5e..5633b96688 100644 --- a/crates/ui-egui/src/workflows/combine_grid.rs +++ b/crates/ui-egui/src/workflows/combine_grid.rs @@ -22,15 +22,14 @@ use crate::combine_ui::{CombineFile, CombineKey, CombineTab, RowAction}; mod card; mod source; -use card::{Act, Pictures}; pub(crate) use card::preview; +use card::{Act, Pictures}; use source::CombineThumbs; pub(crate) use source::OpenDocuments; /// The most pages one file can be spread out into (each is a tile, laid out every frame). pub(crate) const MAX_EXPAND: usize = 2000; - /// The pages an expanded file shows, in its range's order. #[derive(Clone, Debug)] pub(crate) struct PageList { @@ -197,7 +196,6 @@ fn delete_action(selection: &Selection, keys: &[CombineKey]) -> Opti }) } - /// The grid of files, in the card that holds the list. `checks` is what each entry's range takes and /// `twice` whether its file is in the list again, both in list order. Returns what the user did, in order. // PLAN: the signature is `(app, ui, checks, twice) -> Vec`: the table's colours and selection @@ -209,7 +207,8 @@ pub(crate) fn grid(app: &mut PdfCraftApp, ui: &mut egui::Ui, checks: &[Result::new(tl!("Files").to_string()) @@ -364,7 +363,11 @@ impl PdfCraftApp { let Some(f) = self.combine_draft.get(file).filter(|f| self.combine_tab.expanded.contains(&f.id)) else { return Vec::new() }; let source = self.combine_thumb_source(); let pages = f.pages_taken().unwrap_or_default(); - pages.into_iter().enumerate().map(|(nth, page)| (page, self.combine_thumb_state(ctx, &source, CombineKey::Page(f.id, nth), request))).collect() + pages + .into_iter() + .enumerate() + .map(|(nth, page)| (page, self.combine_thumb_state(ctx, &source, CombineKey::Page(f.id, nth), request))) + .collect() } /// Each listed file's grid thumbnail, in list order (tests and the control channel). diff --git a/crates/ui-egui/src/workflows/combine_grid/card.rs b/crates/ui-egui/src/workflows/combine_grid/card.rs index 8fb65c74bc..cc15372f9c 100644 --- a/crates/ui-egui/src/workflows/combine_grid/card.rs +++ b/crates/ui-egui/src/workflows/combine_grid/card.rs @@ -63,7 +63,6 @@ impl Act { Act::Remove => "trash", }) } - } /// The page a file's tile shows, when one can be drawn: the first the range takes, in the file, with a size. diff --git a/crates/ui-egui/src/workflows/combine_grid/source.rs b/crates/ui-egui/src/workflows/combine_grid/source.rs index 17c4ca435e..d501afe47a 100644 --- a/crates/ui-egui/src/workflows/combine_grid/source.rs +++ b/crates/ui-egui/src/workflows/combine_grid/source.rs @@ -32,7 +32,6 @@ pub(super) fn thumbnails(ctx: &egui::Context) -> Thumbnails { Thumbnails::::in_context(ctx, SALT, ThumbnailOptions::new().max_side(MAX_SIDE)) } - /// Page `page`'s size in points when it is one a picture can be drawn at. pub(super) fn page_size(sizes: &[(f32, f32)], page: usize) -> Option<(f32, f32)> { sizes.get(page).copied().filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0) @@ -122,7 +121,14 @@ impl OpenDocuments { } /// The job that renders `page` of `bytes` at `scale` pixels per point. -pub(super) fn page_job(documents: Arc>, bytes: Arc>, auth: u64, password: Option>, page: usize, scale: f32) -> ThumbJob { +pub(super) fn page_job( + documents: Arc>, + bytes: Arc>, + auth: u64, + password: Option>, + page: usize, + scale: f32, +) -> ThumbJob { Box::new(move |cancel| render_page(&documents, &bytes, auth, password, page, scale, cancel)) } @@ -137,9 +143,8 @@ fn render_page( cancel: &Cancel, ) -> Result { let source = Arc::as_ptr(bytes) as usize; - let pool = lock(documents).take_or_open(source, auth, Instant::now(), || { - RenderPool::new(bytes.clone(), 1, thumbnail_config(password)).without_replacements() - }); + let pool = lock(documents) + .take_or_open(source, auth, Instant::now(), || RenderPool::new(bytes.clone(), 1, thumbnail_config(password)).without_replacements()); pool.set_queue(vec![RenderRequest { page, scale, tag: 1, ..Default::default() }]); // Poll the pool: its worker is the one that can be given up on (the watchdog answers an error), // so a page that never finishes holds no queue lane for good. A pool without threads renders diff --git a/crates/ui-egui/src/workflows/combine_ui.rs b/crates/ui-egui/src/workflows/combine_ui.rs index b67104b5f9..eaa45fbbfe 100644 --- a/crates/ui-egui/src/workflows/combine_ui.rs +++ b/crates/ui-egui/src/workflows/combine_ui.rs @@ -20,10 +20,10 @@ mod session; mod table; mod view; +use files::CombineList; pub(crate) use files::Incoming; pub use files::{CombineFile, CombineView, ConflictPreview, Lock, SortKey}; pub(crate) use files::{CombineKey, Preview, RowAction, UnlockAsk}; -use files::CombineList; pub(crate) use parts::range_of; #[cfg(test)] pub(crate) use parts::{Part, moved_order, moved_pages, removed_pages}; diff --git a/crates/ui-egui/src/workflows/combine_ui/actions.rs b/crates/ui-egui/src/workflows/combine_ui/actions.rs index cd953374fe..a711f7756f 100644 --- a/crates/ui-egui/src/workflows/combine_ui/actions.rs +++ b/crates/ui-egui/src/workflows/combine_ui/actions.rs @@ -1,7 +1,7 @@ +use super::BTreeSet; use super::files::{CombineKey, Preview, RowAction}; use super::parts::{moved_pages, removed_pages}; use super::view::expandable; -use super::BTreeSet; use crate::PdfCraftApp; use craft::behavior::selection::Selection; diff --git a/crates/ui-egui/src/workflows/combine_ui/table.rs b/crates/ui-egui/src/workflows/combine_ui/table.rs index dc2c5f7a57..cd0c7042d9 100644 --- a/crates/ui-egui/src/workflows/combine_ui/table.rs +++ b/crates/ui-egui/src/workflows/combine_ui/table.rs @@ -2,8 +2,10 @@ use std::cell::RefCell; use std::time::SystemTime; use craft::behavior::{Codec, ColumnKey, ColumnWidth, DisplayOrder, EditEvent, ItemSource, NotAValue, ReorderKeys}; -use craft::theme::Tone; -use craft::ui::contract::{Bind, CollectionEvent, ColumnEvent, ColumnLayout, ColumnSort, ColumnSpec, Props as _, ReorderMove, ReorderRule, ShowCollection as _, SpaceAction}; +use craft::theme::variant::Tone; +use craft::ui::contract::{ + Bind, CollectionEvent, ColumnEvent, ColumnLayout, ColumnSort, ColumnSpec, Props as _, ReorderMove, ReorderRule, ShowCollection as _, SpaceAction, +}; use craft::ui::list::{CellStatus, ListRow, RowEvent}; use craft::ui::table::Table; use craft::ui::text::TextField; diff --git a/crates/ui-egui/src/workflows/combine_ui/tests.rs b/crates/ui-egui/src/workflows/combine_ui/tests.rs index 84daeff592..757504411a 100644 --- a/crates/ui-egui/src/workflows/combine_ui/tests.rs +++ b/crates/ui-egui/src/workflows/combine_ui/tests.rs @@ -22,8 +22,11 @@ fn utc_stamp_is_utc_minutes_and_clamps_pre_epoch() { } // Past chrono's range every time gives one stamp, whatever the distance, and never panics. // (Windows' SystemTime can't hold the largest, so each is checked where it exists.) - let far: Vec = - [10_000_000_000_000u64, u64::MAX / 2].into_iter().filter_map(|s| SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(s))).map(utc_stamp).collect(); + let far: Vec = [10_000_000_000_000u64, u64::MAX / 2] + .into_iter() + .filter_map(|s| SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(s))) + .map(utc_stamp) + .collect(); assert!(far.windows(2).all(|w| w[0] == w[1]), "{far:?}"); assert!(far.iter().all(|s| s.ends_with(" UTC")), "{far:?}"); } diff --git a/crates/ui-egui/src/workflows/combine_ui/view.rs b/crates/ui-egui/src/workflows/combine_ui/view.rs index af1bda677c..639485c816 100644 --- a/crates/ui-egui/src/workflows/combine_ui/view.rs +++ b/crates/ui-egui/src/workflows/combine_ui/view.rs @@ -1,7 +1,7 @@ use std::collections::BTreeSet; use craft::behavior::IconId; -use craft::theme::{Tone, Variant}; +use craft::theme::variant::{Tone, Variant}; use craft::ui::bars::{Bar, BarKind}; use craft::ui::buttons::{Button, IconButton, SplitButton}; use craft::ui::choice::Segmented; @@ -162,8 +162,11 @@ pub(crate) fn page(app: &mut PdfCraftApp, ui: &mut egui::Ui) { .collect::>() .len(); if bad > 0 { - let text = - if bad == 1 { tl!("1 file needs attention").to_string() } else { crate::i18n::fmt(tl!("{n} files need attention"), &[("n", &bad.to_string())]) }; + let text = if bad == 1 { + tl!("1 file needs attention").to_string() + } else { + crate::i18n::fmt(tl!("{n} files need attention"), &[("n", &bad.to_string())]) + }; Text::new(text).tone(Tone::Bad).show(ui); } } @@ -216,7 +219,8 @@ fn add_files(app: &mut PdfCraftApp, ui: &mut egui::Ui) { /// The open documents as files to combine: the main part adds every one, the menu one document. fn add_open_documents(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let open: Vec<(usize, String)> = app.views.iter().enumerate().filter_map(|(i, _)| crate::canvas::tab_label(app, i).map(|name| (i, name))).collect(); + let open: Vec<(usize, String)> = + app.views.iter().enumerate().filter_map(|(i, _)| crate::canvas::tab_label(app, i).map(|name| (i, name))).collect(); // `None` is every open document. let mut entries: Vec>> = vec![Entry::new(None, tl!("All open documents"))]; entries.extend(open.iter().map(|(i, name)| Entry::new(Some(*i), name.clone()))); @@ -248,7 +252,6 @@ fn skip_prompt(app: &mut PdfCraftApp, ui: &mut egui::Ui) { lines.push(crate::i18n::fmt(tl!("and {n} more"), &[("n", &more)])); } let out = Prompt::new(tl!("Leave out files that can't be read?"), tl!("These files can't be read, so they won't be in the combined PDF:")) - .lines(lines.into_iter().map(Into::into)) .answers([FooterButton::new(tl!("Combine the rest"), DialogRole::Accept), FooterButton::new(tl!("Cancel"), DialogRole::Cancel)]) .show(ui); diff --git a/crates/ui-egui/src/workflows/compare_ui.rs b/crates/ui-egui/src/workflows/compare_ui.rs index 22842ddd02..0031b25f22 100644 --- a/crates/ui-egui/src/workflows/compare_ui.rs +++ b/crates/ui-egui/src/workflows/compare_ui.rs @@ -5,7 +5,7 @@ use craft::behavior::{IconId, Selection, keyed}; use craft::pages::ui::{Lead, PageRangeField, SyncedViews, SyncedViewsState}; use craft::pages::{format_pages, parse_pages}; -use craft::theme::Tone; +use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Segmented}; use craft::ui::contract::{Bind, Entry, Pad, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; @@ -187,11 +187,20 @@ pub(crate) fn panel(ui: &mut egui::Ui, state: &Option, id: DocId) let order: Vec = (0..c.changes.len()).filter(|_| s.show_text).take(2000).collect(); let mut selection = Selection::new(s.selected.into_iter().collect(), s.selected, s.selected); let rows = keyed(&order, |i| *i); - List::new(tl!("Differences").to_string()).select(SelectMode::Single).selection(Bind::bound(&mut selection)).show_items(ui, &rows, &mut |key, item| { - let Some(ch) = c.changes.get(*key) else { return ListRow::new(String::new()) }; - let detail = crate::i18n::fmt(tl!("{kind} · page {p}"), &[("kind", kind_label(ch.kind).as_str()), ("p", &(ch.new.page + 1).to_string())]); - ListRow::new(change_text(ch)).detail(detail).hue(DataColor::new(colour(ch.kind)), HueTarget::Icon).icon(IconSpec::svg(IconId::new("square"))).state(item.row.clone()) - }); + List::new(tl!("Differences").to_string()).select(SelectMode::Single).selection(Bind::bound(&mut selection)).show_items( + ui, + &rows, + &mut |key, item| { + let Some(ch) = c.changes.get(*key) else { return ListRow::new(String::new()) }; + let detail = + crate::i18n::fmt(tl!("{kind} · page {p}"), &[("kind", kind_label(ch.kind).as_str()), ("p", &(ch.new.page + 1).to_string())]); + ListRow::new(change_text(ch)) + .detail(detail) + .hue(DataColor::new(colour(ch.kind)), HueTarget::Icon) + .icon(IconSpec::svg(IconId::new("square"))) + .state(item.row.clone()) + }, + ); if let Some(picked) = selection.items.first().copied().filter(|p| Some(*p) != s.selected) { action = Some(PanelAction::Select(picked)); } @@ -379,18 +388,22 @@ pub(crate) fn compare_area(app: &mut PdfCraftApp, old: usize, new: usize, ui: &m let Some(mut pair) = app.compare.as_mut().map(|c| std::mem::take(&mut c.views)) else { return }; let left = crate::i18n::fmt(tl!("Old file: {name}"), &[("name", &names[0])]); let right = crate::i18n::fmt(tl!("New file: {name}"), &[("name", &names[1])]); - SyncedViews::new(tl!("Comparison").to_string(), &mut pair).captions(left, right).halves(ui, (&mut states.0, &mut states.1), |ui, rect, state, half| { - let index = if half == Lead::Left { old } else { new }; - // The app draws through its own view state: the pair's state for this half stands in for it during the draw. - if let Some(v) = app.views.get_mut(index) { - std::mem::swap(&mut v.view, state); - } - let output = crate::canvas::document_area_at(app, index, rect, ui); - if let Some(v) = app.views.get_mut(index) { - std::mem::swap(&mut v.view, state); - } - output - }); + SyncedViews::new(tl!("Comparison").to_string(), &mut pair).captions(left, right).halves( + ui, + (&mut states.0, &mut states.1), + |ui, rect, state, half| { + let index = if half == Lead::Left { old } else { new }; + // The app draws through its own view state: the pair's state for this half stands in for it during the draw. + if let Some(v) = app.views.get_mut(index) { + std::mem::swap(&mut v.view, state); + } + let output = crate::canvas::document_area_at(app, index, rect, ui); + if let Some(v) = app.views.get_mut(index) { + std::mem::swap(&mut v.view, state); + } + output + }, + ); // A half can close its own tab while it draws (#3915): each is found again by id. for (id, state) in ids.into_iter().zip([states.0, states.1]) { if let Some(v) = app.views.iter_mut().find(|v| v.id == id) { diff --git a/crates/ui-egui/src/workflows/create_ui.rs b/crates/ui-egui/src/workflows/create_ui.rs index c842dc0408..b51b17461d 100644 --- a/crates/ui-egui/src/workflows/create_ui.rs +++ b/crates/ui-egui/src/workflows/create_ui.rs @@ -62,11 +62,7 @@ fn image_import_dialog(ctx: &egui::Context, count: usize) -> HostedParamDialog { ("custom".to_string(), tl!("Use custom DPI").into()), ]; let params = vec![ - Param::read_only_text( - "count", - tl!("Images"), - crate::i18n::fmt(tl!("Selected image files: {count}"), &[("count", &count.to_string())]), - ), + Param::read_only_text("count", tl!("Images"), crate::i18n::fmt(tl!("Selected image files: {count}"), &[("count", &count.to_string())])), Param::new("resolution", tl!("Resolution"), ParamKind::radio(options, Some("image".to_string()))), Param::read_only_text("embedded", tl!("Image resolution"), tl!("Use each image's embedded DPI; use 72 DPI when it is absent.")), Param::new("dpi", tl!("DPI"), ParamKind::int(Some(1), Some(1200), 300)).enabled_when("resolution", FieldValue::Text("custom".into())), @@ -355,7 +351,13 @@ impl PdfCraftApp { /// Ask where an optimized copy goes and write it there, asking again until it is written or /// the question is cancelled. - fn ask_where_to_save_optimized(&mut self, name: String, folder: Option, bytes: Arc>, saved: impl FnOnce(&mut Self, String) + 'static) { + fn ask_where_to_save_optimized( + &mut self, + name: String, + folder: Option, + bytes: Arc>, + saved: impl FnOnce(&mut Self, String) + 'static, + ) { let mut request = PickRequest::save("reduce").file_name(name.clone()).filter("PDF", &["pdf"]); if let Some(folder) = &folder { request = request.default_directory(folder.clone()); diff --git a/crates/ui-egui/src/workflows/export_ui.rs b/crates/ui-egui/src/workflows/export_ui.rs index 2a2322a95b..904b9255a7 100644 --- a/crates/ui-egui/src/workflows/export_ui.rs +++ b/crates/ui-egui/src/workflows/export_ui.rs @@ -17,8 +17,9 @@ use craft::ui::runtime::env::Label; use craft::ui::value_drag::SliderScale; use pdfcraft_engine::export::{ExportSource, Exporter, ImageFormat}; +use super::job_count::JobCount; +use crate::PdfCraftApp; use crate::notices::{self, ProgressKey, ProgressNotice}; -use crate::{JobCount, PdfCraftApp}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExportKind { @@ -77,10 +78,8 @@ fn params(kind: ExportKind, count: usize, current: usize) -> Vec { let mut rows = Vec::new(); match kind { ExportKind::Image => { - let dpis = DPIS - .iter() - .map(|n| (n.to_string(), Label::from(crate::i18n::fmt(tl!("{dpi} pixels/inch"), &[("dpi", &n.to_string())])))) - .collect(); + let dpis = + DPIS.iter().map(|n| (n.to_string(), Label::from(crate::i18n::fmt(tl!("{dpi} pixels/inch"), &[("dpi", &n.to_string())])))).collect(); rows.push(Param::new("dpi", tl!("Resolution"), ParamKind::choice(dpis, Some("150".into())))); let formats = ["png", "jpeg", "tiff"] .iter() @@ -307,7 +306,6 @@ impl PdfCraftApp { #[cfg(target_arch = "wasm32")] task(self, PathBuf::new()); #[cfg(not(target_arch = "wasm32"))] - self.pick_first(PickRequest::folder("export.folder").title(tl!("Choose a folder for the exported files")), None, task); } diff --git a/crates/ui-egui/src/workflows/files.rs b/crates/ui-egui/src/workflows/files.rs index 23f3b1a8d2..f701efadbf 100644 --- a/crates/ui-egui/src/workflows/files.rs +++ b/crates/ui-egui/src/workflows/files.rs @@ -586,7 +586,13 @@ impl PdfCraftApp { /// Pages ▸ Rotate Pages: rotate the pages of `base` that pass the parity and orientation /// filters. - pub fn rotate_pages(&mut self, degrees: i64, base: Vec, parity: pdfcraft_engine::PageParity, orientation: pdfcraft_engine::PageOrientation) { + pub fn rotate_pages( + &mut self, + degrees: i64, + base: Vec, + parity: pdfcraft_engine::PageParity, + orientation: pdfcraft_engine::PageOrientation, + ) { let Some((_, id)) = self.active_ids() else { return }; let Some(doc) = self.session.get(id) else { return }; let pages = pdfcraft_engine::filter_pages(&doc.info, &base, parity, orientation); @@ -780,8 +786,9 @@ impl PdfCraftApp { /// Forms ▸ Merge data files into spreadsheet: choose data files (FDF, XFDF or filled-in PDF /// forms), then where to save the CSV. pub fn merge_data_dialog(&mut self) { - let request = - PickRequest::open_many("merge.data").title(tl!("Select data files to merge")).filter(tl!("Form data and PDF forms"), &["fdf", "xfdf", "pdf"]); + let request = PickRequest::open_many("merge.data") + .title(tl!("Select data files to merge")) + .filter(tl!("Form data and PDF forms"), &["fdf", "xfdf", "pdf"]); self.pick_file(request, None, |app, picked| match app.read_picked(picked) { // Asks where to save: a second picker, now that the first one has closed. Ok(files) if !files.is_empty() => app.merge_data_files(files), diff --git a/crates/ui-egui/src/workflows/job_count.rs b/crates/ui-egui/src/workflows/job_count.rs index bdea63976c..118edf37a8 100644 --- a/crates/ui-egui/src/workflows/job_count.rs +++ b/crates/ui-egui/src/workflows/job_count.rs @@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use craft::host::Cancel; +use craft::host::queue::Cancel; /// Items done and total of a running job, and its cancel request. The job calls [`set`](Self::set) /// as it goes (and wakes the app, since the queue's own wake fires only when a job finishes); the @@ -47,5 +47,3 @@ impl JobCount { self.cancel.is_cancelled() } } - - diff --git a/crates/ui-egui/src/workflows/js_dialogs.rs b/crates/ui-egui/src/workflows/js_dialogs.rs index 1dfe63bd34..6910ae0e55 100644 --- a/crates/ui-egui/src/workflows/js_dialogs.rs +++ b/crates/ui-egui/src/workflows/js_dialogs.rs @@ -139,13 +139,14 @@ fn document_scripts(app: &mut PdfCraftApp, ui: &mut egui::Ui, open: &mut bool, d let before = scripts.iter().position(|(n, _)| *n == draft.name); let mut selection = before.map_or_else(Selection::default, Selection::single); let source = ScriptRows(scripts.len()); - let out = List::new(tl!("Document JavaScripts")) - .select(SelectMode::Single) - .selection(Bind::bound(&mut selection)) - .show_items(ui, &source, &mut |&at, icx| { + let out = List::new(tl!("Document JavaScripts")).select(SelectMode::Single).selection(Bind::bound(&mut selection)).show_items( + ui, + &source, + &mut |&at, icx| { let name = scripts.get(at).map(|(n, _)| n.clone()).unwrap_or_default(); ListRow::new(name).striped(icx.at % 2 == 1) - }); + }, + ); // Only the pass's own pick copies; a drained event list is empty on a second pass. if out.events.iter().any(|e| !matches!(e, CollectionEvent::Column(_))) && selection.lead != before { if let Some((name, script)) = selection.lead.and_then(|at| scripts.get(at)) { diff --git a/crates/ui-egui/src/workflows/js_ui.rs b/crates/ui-egui/src/workflows/js_ui.rs index d3e1fdae1a..9e2dbf3c27 100644 --- a/crates/ui-egui/src/workflows/js_ui.rs +++ b/crates/ui-egui/src/workflows/js_ui.rs @@ -456,5 +456,3 @@ impl PdfCraftApp { } } } - - diff --git a/crates/ui-egui/src/workflows/ocr_ui.rs b/crates/ui-egui/src/workflows/ocr_ui.rs index 8853a13732..e99460536c 100644 --- a/crates/ui-egui/src/workflows/ocr_ui.rs +++ b/crates/ui-egui/src/workflows/ocr_ui.rs @@ -16,8 +16,8 @@ use pdfcraft_engine::ocr::{EngineChoice, LANGUAGES, MergeStrategy, OcrGuard, Ocr use super::job_count::JobCount; // PLAN: assumed `crate::notices::{set_progress, end_progress, ProgressKey, ProgressNotice}` from pdf-chrome-w19 (free functions taking the app). -use crate::notices::{self, ProgressKey, ProgressNotice}; use crate::PdfCraftApp; +use crate::notices::{self, ProgressKey, ProgressNotice}; /// Which pages to read. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -268,8 +268,10 @@ fn engine_unavailable_text(engine: EngineChoice) -> Option { let why = pdfcraft_engine::ocr::engine_unavailable_reason(engine)?; Some(match engine { EngineChoice::Tesseract => crate::i18n::t(&why).to_string(), - _ => tl!("Text recognition isn't installed: its model files are missing. Reinstall PdfCraft, or set PDFCRAFT_MODELS to the folder that holds them.") - .to_string(), + _ => tl!( + "Text recognition isn't installed: its model files are missing. Reinstall PdfCraft, or set PDFCRAFT_MODELS to the folder that holds them." + ) + .to_string(), }) } @@ -357,8 +359,12 @@ fn recognize_dialog(fields: &mut DialogFields, count: usize, current: usize) -> EngineChoice::Ocrs => tl!("Built-in"), EngineChoice::Tesseract => tl!("Tesseract"), }; - let mut engine_row = Param::new("engine", tl!("Engine"), ParamKind::choice(ENGINES.iter().map(|&c| (c.name().to_string(), engine_names(c).into())).collect(), None)) - .option_description(EngineChoice::Auto.name(), tl!("Both engines, combined as the Strategy says")); + let mut engine_row = Param::new( + "engine", + tl!("Engine"), + ParamKind::choice(ENGINES.iter().map(|&c| (c.name().to_string(), engine_names(c).into())).collect(), None), + ) + .option_description(EngineChoice::Auto.name(), tl!("Both engines, combined as the Strategy says")); for choice in ENGINES { if let Some(why) = engine_unavailable_text(choice) { engine_row = engine_row.disabled_option(choice.name(), why); @@ -400,7 +406,11 @@ fn recognize_dialog(fields: &mut DialogFields, count: usize, current: usize) -> ParamKind::choice(strategies.iter().map(|(s, name)| (strategy_id(*s).to_string(), (*name).into())).collect(), None), ), output_row, - Param::new("dpi", tl!("Downsample to"), ParamKind::choice(DPI_CHOICES.iter().map(|v| (v.to_string(), format!("{v} dpi").into())).collect(), None)), + Param::new( + "dpi", + tl!("Downsample to"), + ParamKind::choice(DPI_CHOICES.iter().map(|v| (v.to_string(), format!("{v} dpi").into())).collect(), None), + ), flag( "text_pages", tl!("Also recognize pages that already have text"), @@ -411,13 +421,21 @@ fn recognize_dialog(fields: &mut DialogFields, count: usize, current: usize) -> flag("denoise", tl!("Remove scan speckle"), None), flag("binarize", tl!("Black and white (binarize)"), None), Param::section(tl!("Skip")), - flag("skip_text_pages", tl!("Skip pages that already have text"), Some(tl!("Pages with renderable text are left alone and reported as skipped"))), + flag( + "skip_text_pages", + tl!("Skip pages that already have text"), + Some(tl!("Pages with renderable text are left alone and reported as skipped")), + ), flag( "skip_text_files", tl!("Skip files that already have text"), Some(tl!("In multiple files: a file with any text is its own skipped bucket, and nothing is written for it")), ), - flag("force_ocr", tl!("Force OCR (override skip options)"), Some(tl!("Reads pages and files even where the skip options would leave them alone"))), + flag( + "force_ocr", + tl!("Force OCR (override skip options)"), + Some(tl!("Reads pages and files even where the skip options would leave them alone")), + ), Param::custom("output_folder", tl!("Output folder"), |ui, fields, cx| { let folder = fields.text("output_folder").unwrap_or_default().to_string(); ui.horizontal(|ui| { @@ -436,12 +454,13 @@ fn recognize_dialog(fields: &mut DialogFields, count: usize, current: usize) -> // The web build has no model files: it downloads the models the first time they're needed. #[cfg(target_arch = "wasm32")] - let download_notice = (engine != EngineChoice::Tesseract && pdfcraft_engine::ocr::engine_unavailable_reason(EngineChoice::Ocrs).is_some()).then(|| { - match crate::ocr_web::state() { - crate::ocr_web::State::Failed(e) => crate::i18n::fmt(tl!("Couldn't download the text recognition models: {e}"), &[("e", &e)]), - _ => tl!("Downloading the text recognition models…").to_string(), - } - }); + let download_notice = + (engine != EngineChoice::Tesseract && pdfcraft_engine::ocr::engine_unavailable_reason(EngineChoice::Ocrs).is_some()).then(|| { + match crate::ocr_web::state() { + crate::ocr_web::State::Failed(e) => crate::i18n::fmt(tl!("Couldn't download the text recognition models: {e}"), &[("e", &e)]), + _ => tl!("Downloading the text recognition models…").to_string(), + } + }); #[cfg(not(target_arch = "wasm32"))] let download_notice: Option = None; @@ -1411,20 +1430,22 @@ mod tests { let recognizers = Recognizers { primary: Arc::new(Fake { confidence: 95.0 }), secondary: None }; let writes = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let w = writes.clone(); - let msg = run_batch_files(files, OcrSettings { skip_text_files: true, ..Default::default() }, &recognizers, true, &count, &wake, move |_, _| { - w.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(()) - }); + let msg = + run_batch_files(files, OcrSettings { skip_text_files: true, ..Default::default() }, &recognizers, true, &count, &wake, move |_, _| { + w.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(()) + }); assert_eq!(writes.load(std::sync::atomic::Ordering::SeqCst), 0, "nothing is written for skipped files, and the cancel came first"); assert!(msg.contains("cancelled — 2 files were not run"), "{msg}"); // Without the cancel, the skipped bucket is named and still nothing is written. let files = vec![("a.pdf".into(), pdf.to_vec()), ("b.pdf".into(), pdf.to_vec())]; let count = JobCount::default(); let w = writes.clone(); - let msg = run_batch_files(files, OcrSettings { skip_text_files: true, ..Default::default() }, &recognizers, true, &count, &wake, move |_, _| { - w.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(()) - }); + let msg = + run_batch_files(files, OcrSettings { skip_text_files: true, ..Default::default() }, &recognizers, true, &count, &wake, move |_, _| { + w.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(()) + }); assert_eq!(writes.load(std::sync::atomic::Ordering::SeqCst), 0); assert!(msg.contains("; 2 files already had text"), "{msg}"); assert!(msg.contains("Recognized 0 words in 0 files"), "{msg}"); diff --git a/crates/ui-egui/src/workflows/ocr_verify.rs b/crates/ui-egui/src/workflows/ocr_verify.rs index bd3d08cc42..bd73af7a42 100644 --- a/crates/ui-egui/src/workflows/ocr_verify.rs +++ b/crates/ui-egui/src/workflows/ocr_verify.rs @@ -1412,7 +1412,7 @@ fn save_editable(app: &mut PdfCraftApp, bytes: Arc>, name: String, doc: #[cfg(not(target_arch = "wasm32"))] { // PLAN: assumed `PdfCraftApp::pick_file(&mut self, PickRequest, Option, impl FnOnce(&mut PdfCraftApp, PathBuf) + 'static)` (pdf-shell-w14 `app/picks.rs`). - let request = craft::host::files::PickRequest::save("export").filter("PDF", &["pdf"]).file_name(name.clone()); + let request = craft::host::PickRequest::save("export").filter("PDF", &["pdf"]).file_name(name.clone()); app.pick_file(request, None, move |app, picked: std::path::PathBuf| { if is_source(&picked, &source) { app.notify_tr("That is the source file; choose another destination"); @@ -1447,7 +1447,7 @@ fn save_editable(app: &mut PdfCraftApp, bytes: Arc>, name: String, doc: fn write_editable(app: &mut PdfCraftApp, target: &std::path::Path, bytes: Arc>) { with_state(app, |v, _| v.phase = Phase::Saving); // PLAN: assumed `PdfCraftApp::host: Arc` (pdf-hub-w1). - match app.host.files().write(target, &bytes, craft::host::files::WriteIntent::SaveAs) { + match app.host.files().write(target, &bytes, craft::host::WriteIntent::SaveAs) { Ok(_) => { with_state(app, |v, _| v.finish()); app.notify(crate::i18n::fmt(tl!("Wrote {name}"), &[("name", &target.to_string_lossy())])); @@ -1471,8 +1471,8 @@ fn refresh_view(app: &mut PdfCraftApp, doc: DocId) { #[cfg(test)] mod tests { use super::*; + use craft::host::Picked; use pdfcraft_engine::Session; - use craft::host::files::Picked; use pdfcraft_engine::ocr::EngineChoice; /// A word box that sits where a real placed word would (high on the page, reading left @@ -1968,7 +1968,7 @@ mod tests { #[test] fn editable_save_lands_and_a_failed_or_cancelled_one_keeps_the_review() { // PLAN: assumed `PdfCraftApp::with_files(Arc)`, an app on a host whose files are the script (pdf-shell-w13/w14); the process-wide `process_picks` is pdf-shell-w14's. - let files = Arc::new(craft::host::files::ScriptedFiles::new()); + let files = Arc::new(craft::host::ScriptedFiles::new()); let mut app = PdfCraftApp::with_files(files.clone()); let text = app.session.create_from_text("t", "Recognize these scanned words").expect("fixture"); let id = app.session.open("t.pdf", None, text, None).expect("fixture"); diff --git a/crates/ui-egui/src/workflows/ocr_verify/panes.rs b/crates/ui-egui/src/workflows/ocr_verify/panes.rs index 258d65a737..3a92b45516 100644 --- a/crates/ui-egui/src/workflows/ocr_verify/panes.rs +++ b/crates/ui-egui/src/workflows/ocr_verify/panes.rs @@ -4,16 +4,16 @@ use std::borrow::Cow; use craft::behavior::{DisplayOrder, ItemSource, Selection, SelectionChange}; +use craft::theme::TypeRole; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Picture, Shade, Text}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbAspect}; -use craft::ui::patterns::Inspector; +use craft::ui::patterns::panels::Inspector; use craft::ui::primitives::textures::TextureState; use craft::ui::text::{RunWord, TextField, WordRun, WordState}; -use craft::theme::TypeRole; use egui::Rect; use pdfcraft_engine::ocr::{OcrPage, is_suspect}; @@ -50,10 +50,10 @@ impl ItemSource for PageRows<'_> {} pub(super) fn pages(app: &PdfCraftApp, ui: &mut egui::Ui, n: &mut Intents) { let v = &app.ocr_verify; let rows = PageRows(&v.pages); - let out = List::::new(tl!("Pages")) - .select(SelectMode::Single) - .selection(Bind::given(Selection::single(v.current))) - .show_items(ui, &rows, &mut |key, _| { + let out = List::::new(tl!("Pages")).select(SelectMode::Single).selection(Bind::given(Selection::single(v.current))).show_items( + ui, + &rows, + &mut |key, _| { let Some(pg) = v.pages.iter().find(|pg| pg.page == *key) else { return ListRow::spacer() }; let live = pg.words.iter().filter(|w| !w.text.trim().is_empty()).count(); let suspects = pg.words.iter().filter(|w| !w.text.trim().is_empty() && is_suspect(w.confidence)).count(); @@ -65,12 +65,9 @@ pub(super) fn pages(app: &PdfCraftApp, ui: &mut egui::Ui, n: &mut Intents) { String::new() }; let row = ListRow::new(format!("{} {}{} · {live}", tl!("Page"), pg.page + 1, marked)); - if suspects > 0 { - row.detail(crate::i18n::fmt(tl!("{n} word(s) to review"), &[("n", &suspects.to_string())])) - } else { - row - } - }); + if suspects > 0 { row.detail(crate::i18n::fmt(tl!("{n} word(s) to review"), &[("n", &suspects.to_string())])) } else { row } + }, + ); for event in out.events { if let CollectionEvent::Selection(change) = event { match change { @@ -178,7 +175,8 @@ pub(super) fn inspector(app: &mut PdfCraftApp, ui: &mut egui::Ui, n: &mut Intent } Text::new(readout.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); // Enter commits; an empty commit removes the word, and the box never moves. - let field = TextField::new(tl!("Corrected text"), Bind::bound(correction)).placeholder(tl!("Corrected text (Enter commits)")).submits().show(ui); + let field = + TextField::new(tl!("Corrected text"), Bind::bound(correction)).placeholder(tl!("Corrected text (Enter commits)")).submits().show(ui); submitted |= field.submitted; Row::new().show(ui, |ui, _| { if Button::new(tl!("Remove")).show(ui).clicked() { diff --git a/crates/ui-egui/src/workflows/ocr_verify/screen.rs b/crates/ui-egui/src/workflows/ocr_verify/screen.rs index 44cfcedf78..f7f171f1e6 100644 --- a/crates/ui-egui/src/workflows/ocr_verify/screen.rs +++ b/crates/ui-egui/src/workflows/ocr_verify/screen.rs @@ -54,7 +54,7 @@ pub(super) struct Intents { /// The keys of the screen. They reach it while focus is inside it; a focused text field keeps /// Ctrl+T and Ctrl+Z (the typing scope), and F8 is the screen's either way. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] -#[command(prefix = "ocr_verify", scope = "ocr_verify")] +#[command(prefix = "ocrVerify", scope = "ocr_verify")] pub(super) enum OcrVerifyCommands { /// The next word that asks for review. #[command(label = "Next uncertain", default = "F8")] @@ -93,7 +93,6 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) { } } Grid::new(COLUMNS).fill().show(ui, |ui, _| { - Panel::new(tl!("Pages")).id(pages_id).least_width(LeastWidth::DockColumn).selected(focus_within(&ctx, pages_id)).show(ui, |ui, _| { panes::pages(app, ui, &mut n); }); @@ -269,7 +268,11 @@ fn options_bar(app: &mut PdfCraftApp, ui: &mut Ui, n: &mut Intents) { n.reject = true; } Divider::vertical().show(ui); - Checkbox::new(Bind::bound(&mut verified)).label(tl!("Page verified")).tooltip(tl!("Mark this page as reviewed (Ctrl+T)")).enabled(review).show(ui); + Checkbox::new(Bind::bound(&mut verified)) + .label(tl!("Page verified")) + .tooltip(tl!("Mark this page as reviewed (Ctrl+T)")) + .enabled(review) + .show(ui); if Button::new(tl!("Next uncertain")) .variant(Variant::GHOST) .icon(craft::behavior::IconId::new("chevron_right")) diff --git a/crates/ui-egui/src/workflows/ocr_verify/source.rs b/crates/ui-egui/src/workflows/ocr_verify/source.rs index 24213eaf07..621cae370b 100644 --- a/crates/ui-egui/src/workflows/ocr_verify/source.rs +++ b/crates/ui-egui/src/workflows/ocr_verify/source.rs @@ -8,12 +8,16 @@ use craft::behavior::kurbo::{Point, Size}; use craft::behavior::{CancelReason, CanvasView, PixelSize}; use craft::theme::variant::{Emphasis, Tone}; use craft::theme::{TypeRole, Variant}; -use craft::ui::canvas::{AppPaint, Canvas, CanvasTool, RasterDisplay, ToolAction, ToolContext, ToolHost, ToolPointer, ViewTarget, tool_pass}; +use craft::ui::canvas::{ + AppPaint, Canvas, CanvasTool, RasterDisplay, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer, ViewTarget, tool_pass, +}; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::{Badge, Divider, Shade, Text}; use craft::ui::layout_components::Row; use craft::ui::menu::{Menu, MenuItem}; -use craft::ui::primitives::textures::{Priority, StateLook, TextureState, TextureStoreOptions, ThumbPaint, ThumbRequest, ThumbnailOptions, Thumbnails, texture_side}; +use craft::ui::primitives::textures::{ + Priority, StateLook, TextureState, TextureStoreOptions, ThumbPaint, ThumbRequest, ThumbnailOptions, Thumbnails, texture_side, +}; use craft::ui::primitives::{Draw, PaintShape, StrokeWidth}; use craft::ui::runtime::memory::Remember as _; use egui::{Pos2, Rect, Ui}; @@ -80,7 +84,12 @@ fn word_shapes(app: &PdfCraftApp, info: &pdfcraft_render::PageInfo, page: usize) let (o, a, u) = (w.origin, w.across, w.up); WordShape { key, - quad: [to_view(o), to_view([o[0] + a[0], o[1] + a[1]]), to_view([o[0] + a[0] + u[0], o[1] + a[1] + u[1]]), to_view([o[0] + u[0], o[1] + u[1]])], + quad: [ + to_view(o), + to_view([o[0] + a[0], o[1] + a[1]]), + to_view([o[0] + a[0] + u[0], o[1] + a[1] + u[1]]), + to_view([o[0] + u[0], o[1] + u[1]]), + ], band: w.confidence.map(band_for), removed: v.is_removed(key), selected: v.selected == Some(key), @@ -238,6 +247,10 @@ impl CanvasTool for RegionTool { draw.stroke(&PaintShape::Rect(rect, egui::CornerRadius::ZERO), StrokeWidth::Medium, style.color(style.tokens.color.accent.solid)); } } + + fn command_form(&self) -> ToolPath { + ToolPath::Freehand("the region is dragged on the page; no command takes its numbers") + } } /// The source pane: the page picture, the word boxes and the region over it, and the context menu. @@ -293,7 +306,10 @@ pub(super) fn show(app: &mut PdfCraftApp, ui: &mut Ui, n: &mut Intents) { n.reject_page = true; } Divider::horizontal().show(ui); - Text::new(tl!("Click a word to inspect it; drag a rectangle to re-read part of the page")).role(TypeRole::Caption).shade(Shade::Faint).show(ui); + Text::new(tl!("Click a word to inspect it; drag a rectangle to re-read part of the page")) + .role(TypeRole::Caption) + .shade(Shade::Faint) + .show(ui); }); } @@ -366,7 +382,8 @@ mod tests { for (width, height) in [(612.0, 792.0), (792.0, 612.0)] { let page = Size::new(width, height); let zoom = 0.5; - let view = CanvasView::new(Rect::from_min_size(egui::pos2(10.0, 20.0), egui::vec2(500.0, 400.0)), Point::new(width / 2.0, height / 2.0), zoom); + let view = + CanvasView::new(Rect::from_min_size(egui::pos2(10.0, 20.0), egui::vec2(500.0, 400.0)), Point::new(width / 2.0, height / 2.0), zoom); let tool = RegionTool::new(Vec::new(), Some(region), page); let outline = tool.outline(&view).expect("the region lies on the page"); let on_page = tool.page_on_screen(&view); diff --git a/crates/ui-egui/src/workflows/optimize_ui.rs b/crates/ui-egui/src/workflows/optimize_ui.rs index e673cda90d..35c06e595f 100644 --- a/crates/ui-egui/src/workflows/optimize_ui.rs +++ b/crates/ui-egui/src/workflows/optimize_ui.rs @@ -15,15 +15,18 @@ use craft::ui::display::Text; use craft::ui::list::ListRow; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamTab, SharedRows}; use craft::ui::table::Table; -use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, MonoSettings, Preset, QUALITIES, Settings, SpaceCategory, SpaceUse}; +use pdfcraft_engine::optimize::{ + Compatibility, Compression, ImageSettings, MonoCompression, MonoSettings, Preset, QUALITIES, Settings, SpaceCategory, SpaceUse, +}; use pdfcraft_engine::optimizer::{OptimizeStage, Optimized}; use pdfcraft_engine::{DocId, EditError, Hidden, OptimizeReport}; // PLAN: assumed `crate::JobCount` (pdf-print-ocr-w6), `crate::notices::{ProgressKey, ProgressNotice, set_progress, end_progress}` (pdf-chrome-w19), // `crate::dialogs::host::{open, open_over}(app, dialog[, parent])` (pdf-hub-w2) and the facade paths above (`craft::ui::patterns::form_dialogs`, `craft::ui::table`, // `craft::ui::display::Text::show`, `Table::show_items(..).response`). +use super::job_count::JobCount; +use crate::PdfCraftApp; use crate::notices::{self, ProgressKey, ProgressNotice}; -use crate::{JobCount, PdfCraftApp}; /// The dialog's key; its answer is read back by [`pass`]. pub(crate) const OPTIMIZE_KEY: &str = "optimize"; @@ -76,7 +79,12 @@ struct Toggle { } static TOGGLES: [Toggle; 20] = [ - Toggle { tab: 1, key: "linksactionsscripts", label: "Discard all links, actions and JavaScript", effect: Effect::Discard(Hidden::LinksActionsScripts) }, + Toggle { + tab: 1, + key: "linksactionsscripts", + label: "Discard all links, actions and JavaScript", + effect: Effect::Discard(Hidden::LinksActionsScripts), + }, Toggle { tab: 1, key: "discard_alternate_images", @@ -451,8 +459,11 @@ fn audit_lines(rows: &[SpaceUse]) -> Vec { .filter(|r| r.bytes > 0) .map(|r| { // "Patterns" also names the redaction search patterns ("模式"); the audit's PDF graphics objects need their own key. - let description = - if r.category == SpaceCategory::Patterns { tl!("Patterns (graphics objects)").to_string() } else { tl!(r.category.label()).to_string() }; + let description = if r.category == SpaceCategory::Patterns { + tl!("Patterns (graphics objects)").to_string() + } else { + tl!(r.category.label()).to_string() + }; AuditLine { description, bytes: r.bytes.to_string(), percentage: format!("{:.2}%", r.percent) } }) .collect(); @@ -526,7 +537,6 @@ pub(crate) fn open_space_audit(app: &mut PdfCraftApp, ctx: &egui::Context, from_ ParamDialog::new(key, tl!("Space Audit"), vec![audit_row(rows.clone())]).read_only(true).values(Bind::bound(fields)) }); if from_optimizer { - crate::dialogs::host::open_over(app, dialog.instance(AUDIT_INSTANCE), dialog_id(OPTIMIZE_KEY)); } else { crate::dialogs::host::open(app, dialog); diff --git a/crates/ui-egui/src/workflows/print_ui.rs b/crates/ui-egui/src/workflows/print_ui.rs index 5e50126822..cabdef9727 100644 --- a/crates/ui-egui/src/workflows/print_ui.rs +++ b/crates/ui-egui/src/workflows/print_ui.rs @@ -5,9 +5,9 @@ use std::sync::Arc; -use craft::host::{Jobs, Wake}; #[cfg(not(target_arch = "wasm32"))] use craft::host::queue::{JobQueue, Priority, QueueOptions}; +use craft::host::{Jobs, Wake}; #[cfg(not(target_arch = "wasm32"))] use craft::print::ui::HostedPrint; use pdfcraft_engine::print::{self, Binding, BookletSubset, Content, Layout, Orientation, PageOrder, SizeMode, Subset, spool}; @@ -83,7 +83,7 @@ pub(crate) struct RunningPrint { /// The printer the job goes to. pub(crate) printer: String, /// `(sent, sheets)`, set by the job as the spooler takes each sheet. - pub(crate) count: Arc, + pub(crate) count: Arc, } /// The Print dialog's work in the background: the printer list, the per-printer reads and the @@ -156,13 +156,7 @@ impl PrintTasks { { // A browser has no threads to queue on. let _ = jobs; - Self { - listed: Vec::new(), - wake, - web_job: None, - web_failed: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())), - web_last: None, - } + Self { listed: Vec::new(), wake, web_job: None, web_failed: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())), web_last: None } } } } @@ -484,7 +478,11 @@ impl PdfCraftApp { } _ => (crate::i18n::fmt(tl!("Sending to {printer}…"), &[("printer", printer)]), 0.0), }; - crate::notices::set_progress(self, crate::notices::ProgressKey::Print, crate::notices::ProgressNotice { label, fraction, cancellable: false }); + crate::notices::set_progress( + self, + crate::notices::ProgressKey::Print, + crate::notices::ProgressNotice { label, fraction, cancellable: false }, + ); } /// Pick up two-sided answers that arrived, and ask for the picked printer's when the list @@ -585,7 +583,7 @@ impl PdfCraftApp { fn send_to_printer(&mut self, printer: String, bytes: Vec, mut job: spool::Job) -> Result { let ticket = self.print_tasks.next_ticket; self.print_tasks.next_ticket = ticket.wrapping_add(1); - let count = Arc::new(crate::JobCount::default()); + let count = Arc::new(super::job_count::JobCount::default()); let progress = count.clone(); let wake = self.print_tasks.wake.clone(); let spooler = self.spooler.clone(); @@ -676,7 +674,9 @@ impl PdfCraftApp { // PLAN: assumed `Files::write(&self, path: &Path, bytes: &[u8]) -> Result<(), E: Display>` (SH-C35; a browser downloads under the file name). match self.host.files().write(std::path::Path::new(&file), &pdf, craft::host::WriteIntent::SaveAs) { // `false`: no host page took the bytes, so the browser downloaded them. - Ok(false) => self.notify_fmt("Couldn't print from the browser ({e}); downloaded {name} to print instead", &[("e", error), ("name", &file)]), + Ok(false) => { + self.notify_fmt("Couldn't print from the browser ({e}); downloaded {name} to print instead", &[("e", error), ("name", &file)]) + } Ok(true) | Err(_) => self.notify_error(error), } } @@ -937,7 +937,7 @@ mod tests { // PLAN: assumed `Notices::progress(&self, ProgressKey) -> Option` and `Notices::posted(&self) -> Vec` (the posted messages, oldest first), read through `app.notices` (pdf-chrome-w19, L-206). let card = |app: &PdfCraftApp| app.notices.progress(crate::notices::ProgressKey::Print); - let count = Arc::new(crate::JobCount::default()); + let count = Arc::new(super::job_count::JobCount::default()); app.print_tasks.running.push(RunningPrint { ticket: 0, printer: "Office".into(), count: count.clone() }); app.show_print_progress("Office", None); let started = card(&app).expect("a card shows while the job runs"); @@ -964,7 +964,7 @@ mod tests { assert!(posted.last().is_some_and(|m| m.contains("Office")), "it names the printer: {posted:?}"); // A job the spooler refuses ends its card too, and says why. - app.print_tasks.running.push(RunningPrint { ticket: 1, printer: "Office".into(), count: Arc::new(crate::JobCount::default()) }); + app.print_tasks.running.push(RunningPrint { ticket: 1, printer: "Office".into(), count: Arc::new(super::job_count::JobCount::default()) }); app.print_tasks.jobs.submit(1, Priority::VISIBLE, |_| Err("the spooler refused the job".into())); jobs.run_all(); app.poll_print(); diff --git a/crates/ui-egui/src/workflows/print_ui/body.rs b/crates/ui-egui/src/workflows/print_ui/body.rs index 0bdfa965f6..a721b310bc 100644 --- a/crates/ui-egui/src/workflows/print_ui/body.rs +++ b/crates/ui-egui/src/workflows/print_ui/body.rs @@ -19,8 +19,13 @@ use crate::units::Unit; const WHICH: [(Which, &str); 5] = [(Which::All, "all"), (Which::Current, "current"), (Which::Range, "range"), (Which::Area, "area"), (Which::Selected, "selected")]; -const HANDLING: [(Handling, &str); 5] = - [(Handling::Size, "size"), (Handling::Poster, "poster"), (Handling::Multiple, "multiple"), (Handling::Booklet, "booklet"), (Handling::Label, "label")]; +const HANDLING: [(Handling, &str); 5] = [ + (Handling::Size, "size"), + (Handling::Poster, "poster"), + (Handling::Multiple, "multiple"), + (Handling::Booklet, "booklet"), + (Handling::Label, "label"), +]; const SUBSET: [(Subset, &str); 3] = [(Subset::All, "all"), (Subset::Odd, "odd"), (Subset::Even, "even")]; const ORIENTATION: [(Orientation, &str); 3] = [(Orientation::Auto, "auto"), (Orientation::Portrait, "portrait"), (Orientation::Landscape, "landscape")]; @@ -138,10 +143,8 @@ fn handling_tabs(d: &PrintDraft) -> Param { let name = lbl(tl!("Page Sizing & Handling")); Param::custom("handling", name.clone(), move |ui, fields, _| { let now = fields.text("handling").unwrap_or("size").to_owned(); - let entries: Vec> = tabs - .iter() - .map(|(h, text)| Entry::new(id_of(&HANDLING, *h).to_owned(), text.clone()).enabled(!area || *h == Handling::Size)) - .collect(); + let entries: Vec> = + tabs.iter().map(|(h, text)| Entry::new(id_of(&HANDLING, *h).to_owned(), text.clone()).enabled(!area || *h == Handling::Size)).collect(); let shown = Segmented::new(name.clone(), Bind::given(now.clone()), &entries).show(ui); if let Some(picked) = shown.value().cloned() && picked != now @@ -277,9 +280,11 @@ fn driver_section(d: &PrintDraft) -> Option { let title = lbl(tl!("Printer properties")); let loading = d.driver_options.is_none() && d.driver_options_loading.is_some(); let section = |params: Vec| { - PrintSection::new(title.clone(), params) - .button("driver.done", lbl(tl!("Done")), true) - .button("driver.reset", lbl(tl!("Reset to printer defaults")), !d.driver_choices.is_empty()) + PrintSection::new(title.clone(), params).button("driver.done", lbl(tl!("Done")), true).button( + "driver.reset", + lbl(tl!("Reset to printer defaults")), + !d.driver_choices.is_empty(), + ) }; if loading { return Some(section(vec![note("note.driver_loading", tl!("Reading the printer's settings…"))])); @@ -325,11 +330,7 @@ fn pages_section(d: &PrintDraft, count: usize, units: Unit, has_area: bool) -> P } let subset = options( &SUBSET, - vec![ - (Subset::All, lbl(tl!("All pages in range"))), - (Subset::Odd, lbl(tl!("Odd pages only"))), - (Subset::Even, lbl(tl!("Even pages only"))), - ], + vec![(Subset::All, lbl(tl!("All pages in range"))), (Subset::Odd, lbl(tl!("Odd pages only"))), (Subset::Even, lbl(tl!("Even pages only")))], ); PrintSection::new( lbl(tl!("Pages to Print")), @@ -356,7 +357,9 @@ fn sizing_section(d: &PrintDraft) -> PrintSection { ]; params.push(size(radio("size", lbl(tl!("Size")), sizing, print::names::size_mode(d.size)))); let scale = (*CUSTOM_SCALE.start(), *CUSTOM_SCALE.end()); - params.push(size(number("custom_scale", lbl(tl!("Custom scale")), scale, d.custom_scale, 1.0, 0, UnitKind::Percent).enabled_when("size", "custom"))); + params.push(size( + number("custom_scale", lbl(tl!("Custom scale")), scale, d.custom_scale, 1.0, 0, UnitKind::Percent).enabled_when("size", "custom"), + )); params.push(label(note( "note.label", diff --git a/crates/ui-egui/src/workflows/print_ui/dialog.rs b/crates/ui-egui/src/workflows/print_ui/dialog.rs index c9d737c18b..2af9e7698a 100644 --- a/crates/ui-egui/src/workflows/print_ui/dialog.rs +++ b/crates/ui-egui/src/workflows/print_ui/dialog.rs @@ -2,16 +2,15 @@ use craft::print::ui::{Destination, DriverControls, Duplex as UiDuplex, HostedPrint, PrintLayout, Settings, State}; use craft_ui::patterns::form_dialogs::PagerStep; -use craft_ui::runtime::env::Label; use craft_ui::primitives::{ThumbnailOptions, Thumbnails}; +use craft_ui::runtime::env::Label; use pdfcraft_engine::print::{self, spool}; use super::draft::{Handling, PrintDraft, Which}; use super::sheet::SheetInput; use super::{PREVIEW_MAX_SIDE, PrintStart, body, default_printer, listed_printers, offered, offered_printers, sheet, still_looking}; use crate::PdfCraftApp; -// PLAN: assumed `DocPages` and `PrintPage { page, grayscale }` (pdf-canvas-w10) -use crate::canvas::{DocPages, PrintPage}; +use crate::canvas::pictures::{DocPages, PrintPage}; fn duplex_to_ui(duplex: Option) -> Option { duplex.map(|d| match d { diff --git a/crates/ui-egui/src/workflows/print_ui/sheet.rs b/crates/ui-egui/src/workflows/print_ui/sheet.rs index 7818e02311..ee9a069abe 100644 --- a/crates/ui-egui/src/workflows/print_ui/sheet.rs +++ b/crates/ui-egui/src/workflows/print_ui/sheet.rs @@ -12,8 +12,7 @@ use pdfcraft_engine::print::{self, Sheet}; use super::draft::{Handling, PrintDraft}; use super::preview_rasters; -// PLAN: assumed `PrintPage { page, grayscale }` (pdf-canvas-w10) -use crate::canvas::PrintPage; +use crate::canvas::pictures::PrintPage; fn lbl(text: impl AsRef) -> Label { Label::from(text.as_ref().to_owned()) @@ -47,14 +46,7 @@ pub(super) fn build( ) -> (PrintSheet, Option) { let SheetInput { d, sizes, labels, settings, sheets, too_much_creep } = input; let count = sheets.len(); - let pager = PanePager { - shown: d.sheet + 1, - count, - shown_label: None, - back: d.sheet > 0, - next: d.sheet + 1 < count, - unit: PagerUnit::Sheet, - }; + let pager = PanePager { shown: d.sheet + 1, count, shown_label: None, back: d.sheet > 0, next: d.sheet + 1 < count, unit: PagerUnit::Sheet }; let paper = vec2(d.paper_size().0 as f32, d.paper_size().1 as f32); let sheet = match (settings, sheets.get(d.sheet)) { (Err(e), _) => PrintSheet::message(paper, lbl(tl!(e.as_str())), Label::default()), diff --git a/crates/ui-egui/src/workflows/scan_clean_ui.rs b/crates/ui-egui/src/workflows/scan_clean_ui.rs index b8d4d84a69..2b4dac399f 100644 --- a/crates/ui-egui/src/workflows/scan_clean_ui.rs +++ b/crates/ui-egui/src/workflows/scan_clean_ui.rs @@ -13,10 +13,10 @@ use craft::ui::value_drag::SliderScale; use pdfcraft_engine::scan_clean::{ScanCleanReport, ScanCleanSettings, ScanCleaned}; use pdfcraft_engine::{DocId, EditError}; -use crate::notices::{self, ProgressKey}; use super::job_count::JobCount; use crate::PdfCraftApp; use crate::notices::ProgressNotice; +use crate::notices::{self, ProgressKey}; /// The key the dialog and its result share. const DIALOG_KEY: &str = "enhance-scan";