PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
refactor(ui-egui): split print_ui.rs into print_ui/
aiongg06b905412ca6
diff --git a/crates/ui-egui/src/print_ui.rs b/crates/ui-egui/src/print_ui.rsindex 5bf8737fc..914525629 100644--- a/crates/ui-egui/src/print_ui.rs+++ b/crates/ui-egui/src/print_ui.rs@@ -9,6 +9,12 @@ use pdfcraft_engine::print::{self, Binding, BookletSubset, Content, Layout, Orieuse crate::theme::{self, Tokens};use crate::{PdfCraftApp, widgets};+mod body;+mod draft;++pub(crate) use body::body;+pub use draft::{Handling, PrintDraft, Which};+/// The preview pane, and the paper inside it (12 pt inset on each side).const PREVIEW_W: f32 = 320.0;const PREVIEW_H: f32 = 380.0;@@ -18,243 +24,6 @@ pub(crate) const PREVIEW_BOX: (f32, f32) = (PREVIEW_W - 2.0 * PREVIEW_INSET, PRE/// the UI thread); further pages print whole.pub(crate) const LABEL_CROP_PAGES: usize = 50;-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum Which {- All,- Current,- Range,- /// The pages picked in the Pages panel or the organize grid when the dialog opened.- Selected,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum Handling {- Size,- Poster,- Multiple,- Booklet,- /// Shipping label: cut to the printed area, turned upright, one per sheet.- Label,-}--#[derive(Clone, Debug, PartialEq)]-pub struct PrintDraft {- pub printers: Vec<spool::Printer>,- /// The unit the sheet size is shown in (Preferences).- pub units: crate::units::Unit,- /// The printers are still being listed in the background (see [`PrinterSource`]).- pub printers_loading: bool,- /// The user chose the printer, so a list arriving late doesn't move it to the default.- pub printer_picked: bool,- /// `None` = Save as PDF.- pub printer: Option<String>,- pub copies: u32,- pub collate: bool,- pub grayscale: bool,- /// `None` = the printer's own default (its Properties), as Acrobat does.- pub duplex: Option<spool::Duplex>,- pub which: Which,- pub range: String,- /// The pages `Which::Selected` prints (0-based, in page order); empty when none were picked.- pub selected: Vec<usize>,- pub subset: Subset,- pub reverse: bool,- pub handling: Handling,- pub size: SizeMode,- pub custom_scale: f64,- pub per_sheet: usize,- pub order: PageOrder,- pub border: bool,- pub auto_rotate: bool,- pub booklet_subset: BookletSubset,- pub binding: Binding,- pub poster_scale: f64,- pub overlap: f64,- pub cut_marks: bool,- pub orientation: Orientation,- pub content: Content,- /// Print as image (Acrobat's Advanced Print Setup) at `dpi`.- pub as_image: bool,- pub dpi: f64,- pub paper: usize,- /// The paper chosen before Label put label stock in, so leaving Label gives it back (#3564).- pub paper_before_label: Option<usize>,- /// The sheet shown in the preview (0-based).- pub sheet: usize,- pub current_page: usize,- /// The printer driver's own options and the printer they were read for (Properties…, CUPS).- pub driver_options: Option<(String, Vec<spool::PrinterOption>)>,- /// Driver options set away from the printer's defaults, for `driver_options`' printer.- pub driver_choices: std::collections::BTreeMap<String, String>,- pub show_driver_options: bool,- /// Why the printer's preferences window didn't open (Windows).- pub driver_error: Option<String>,- /// Label: turn a further 180°.- pub label_flip: bool,- /// Label: each page's printed area and text direction, read when Label is chosen- /// ([`PdfCraftApp::read_label_crops`]); empty until then.- pub crops: Vec<Option<print::Crop>>,- /// The pages `crops` were read for, so a changed page selection reads them again.- pub crop_pages: Option<Vec<usize>>,- /// The printer whose options are being read in the background (CUPS runs `lpoptions`,- /// which a stuck CUPS can hold up; #1818). The panel says so meanwhile.- pub driver_options_loading: Option<String>,- /// Properties… asked for this printer's options; the app starts the read on the next frame.- pub read_options_for: Option<String>,-}--impl Default for PrintDraft {- fn default() -> Self {- PrintDraft {- printers: Vec::new(),- units: Default::default(),- printers_loading: false,- printer_picked: false,- printer: None,- copies: 1,- collate: true,- grayscale: false,- duplex: None,- which: Which::All,- range: String::new(),- selected: Vec::new(),- subset: Subset::All,- reverse: false,- handling: Handling::Size,- size: SizeMode::Fit,- custom_scale: 100.0,- per_sheet: 2,- order: PageOrder::Horizontal,- border: false,- auto_rotate: true,- booklet_subset: BookletSubset::BothSides,- binding: Binding::Left,- poster_scale: 200.0,- overlap: 18.0,- cut_marks: true,- orientation: Orientation::Auto,- content: Content::DocumentAndMarkups,- as_image: false,- dpi: 300.0,- paper: 0,- paper_before_label: None,- sheet: 0,- current_page: 0,- driver_options: None,- driver_choices: Default::default(),- show_driver_options: false,- driver_error: None,- label_flip: false,- crops: Vec::new(),- crop_pages: None,- driver_options_loading: None,- read_options_for: None,- }- }-}--impl PrintDraft {- /// Choose Page Sizing & Handling. Label loads label stock and remembers the paper it- /// replaced; leaving Label gives that paper back, unless another one was picked meanwhile.- pub fn set_handling(&mut self, handling: Handling) {- let leaving_label = self.handling == Handling::Label && handling != Handling::Label;- self.handling = handling;- self.sheet = 0;- if handling == Handling::Label {- // A label goes on label stock.- if self.paper != print::LABEL_PAPER {- self.paper_before_label = Some(self.paper);- self.paper = print::LABEL_PAPER;- }- } else if leaving_label- && let Some(paper) = self.paper_before_label.take()- && self.paper == print::LABEL_PAPER- {- self.paper = paper;- }- }-- /// The engine settings for this draft (page count and labels from the document).- pub fn settings(&self, count: usize, labels: &[String]) -> Result<print::Settings, String> {- if self.cut_and_stack() && matches!(self.duplex, Some(spool::Duplex::LongEdge | spool::Duplex::ShortEdge)) {- return Err("Cut and stack needs Two-sided: Off. Print single-sided sheets.".into());- }- let range = match self.which {- Which::All | Which::Selected | Which::Current => None,- Which::Range => Some(self.range.clone()),- };- // Selected and Current are positions, not a typed range: a range would read numbers as- // page labels first.- let pages = match self.which {- Which::Selected => print::select_listed(count, &self.selected, self.subset, self.reverse),- Which::Current => print::select_listed(count, &[self.current_page], self.subset, self.reverse),- Which::All | Which::Range => print::select_pages(count, range.as_deref(), labels, self.subset, self.reverse),- }- // What the person got wrong about what to print is said in their language: the engine hands- // the wording over whole and the page numbers apart from it.- .map_err(|e| e.said(&crate::i18n::words))?;- let layout = match self.handling {- Handling::Size => Layout::Size(match self.size {- SizeMode::Custom(_) => SizeMode::Custom(self.custom_scale),- m => m,- }),- Handling::Multiple => match Layout::multiple(self.per_sheet) {- Layout::Multiple { cols, rows, per_sheet, .. } => {- Layout::Multiple { cols, rows, per_sheet, order: self.order, border: self.border, auto_rotate: self.auto_rotate }- }- other => other,- },- Handling::Booklet => Layout::Booklet { subset: self.booklet_subset, binding: self.binding },- Handling::Poster => Layout::Poster { scale: self.poster_scale, overlap: self.overlap, cut_marks: self.cut_marks },- Handling::Label => Layout::Label { flip: self.label_flip },- };- Ok(print::Settings {- pages,- paper: PAPERS[self.paper.min(PAPERS.len() - 1)].1,- orientation: self.orientation,- layout,- content: self.content,- raster: self.as_image.then_some(print::Raster { dpi: self.dpi, grayscale: self.grayscale }),- crops: self.crops.clone(),- })- }-- fn cut_and_stack(&self) -> bool {- self.handling == Handling::Multiple && self.order == PageOrder::CutStack- }-- /// The spooler job for this print: the dialog's copies, two-sided and colour settings, the- /// driver options changed from the printer's defaults, and the chosen paper.- pub fn job(&self, title: &str) -> spool::Job {- spool::Job {- printer: self.printer.clone(),- copies: self.copies.max(1),- collate: self.collate,- // Cut and stack needs single-sided sheets, whatever the printer's default; a booklet- // decides two-sided itself (#2707), leaving the Two-sided choice as it was.- duplex: if self.cut_and_stack() {- Some(spool::Duplex::Off)- } else if self.handling == Handling::Booklet {- Some(print::booklet_duplex(self.booklet_subset))- } else {- self.duplex- },- scaling: spool::Scaling::Exact,- grayscale: self.grayscale,- title: title.to_string(),- // Only for the printer the options were read from.- options: match (&self.printer, &self.driver_options) {- (Some(p), Some((read_for, _))) if p == read_for => self.driver_choices.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),- _ => Vec::new(),- }- .into_iter()- // The sheet the PDF was laid out on, not the queue's default paper.- .chain(print::media_option(self.paper))- .collect(),- }- }-}-/// Lists the printers off the UI thread (the desktop app sets [`PdfCraftApp::printer_source`]):/// on Windows each driver's capabilities are read for its two-sided support, and CUPS' driverless discovery can wait on/// the network. Without a source the dialog reads them as it opens, so tests stay deterministic.@@ -863,549 +632,6 @@ pub(crate) fn preview_rasters(d: &PrintDraft, sizes: &[(f64, f64)], labels: &[Stout.into_iter().map(|(page, scale, _)| (page, scale)).collect()}-/// Properties… on CUPS: the driver's options for this print, grouped as the driver groups them.-/// Only choices away from the printer's defaults are kept, and sent with the job.-fn driver_options_panel(ui: &mut egui::Ui, d: &mut PrintDraft, t: &Tokens) {- let PrintDraft { driver_options: Some((_, options)), driver_choices: choices, show_driver_options: show, .. } = d else { return };- egui::Frame::new().fill(t.hover).corner_radius(egui::CornerRadius::same(6)).inner_margin(egui::Margin::same(10)).show(ui, |ui| {- ui.set_width(ui.available_width());- ui.horizontal(|ui| {- ui.label(egui::RichText::new(tl!("Printer properties")).font(theme::semibold(13.0)));- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if ui.button(tl!("Done")).clicked() {- *show = false;- }- if ui.add_enabled(!choices.is_empty(), egui::Button::new(tl!("Reset to printer defaults"))).clicked() {- choices.clear();- }- });- });- if options.is_empty() {- ui.label(egui::RichText::new(tl!("This printer offers no settings of its own.")).small().color(t.text_muted));- return;- }- egui::ScrollArea::vertical().id_salt("driver-options").max_height(240.0).show(ui, |ui| {- for (n, chunk) in options.chunk_by(|a, b| a.group == b.group).enumerate() {- let group = chunk.first().map_or("", |o| o.group.as_str());- if !group.is_empty() {- ui.add_space(4.0);- // Option and group names are the driver's own text.- ui.label(egui::RichText::new(group).small().color(t.text_muted));- }- egui::Grid::new(("driver-group", n)).num_columns(2).spacing([10.0, 4.0]).show(ui, |ui| {- for o in chunk {- let current = choices.get(&o.key).cloned().unwrap_or_else(|| o.default.clone());- let label_of = |c: &str| o.choices.iter().find(|(k, _)| k == c).map_or_else(|| c.to_string(), |(_, l)| l.clone());- let mut pick = current.clone();- let option_label = ui.label(&o.label);- egui::ComboBox::from_id_salt(("driver-option", &o.key))- .selected_text(label_of(¤t))- .width(200.0)- .show_ui(ui, |ui| {- for (k, l) in &o.choices {- ui.selectable_value(&mut pick, k.clone(), l.as_str());- }- })- .response- .labelled_by(option_label.id);- if pick != current {- if pick == o.default {- choices.remove(&o.key);- } else {- choices.insert(o.key.clone(), pick);- }- }- ui.end_row();- }- });- }- });- });-}--/// Draw a combo box whose accessible name does not depend on the selected value.-fn combo<T: PartialEq + Copy>(ui: &mut egui::Ui, id: &str, name: &str, value: &mut T, choices: &[(T, &str)], width: f32) {- let shown = choices.iter().find(|c| c.0 == *value).map_or("", |c| c.1);- egui::ComboBox::from_id_salt(id)- .selected_text(shown)- .width(width)- .show_ui(ui, |ui| {- for (v, label) in choices {- ui.selectable_value(value, *v, *label);- }- })- .response- .accessible_name(name);-}--/// Draw the dialog. `thumb` gives a page's thumbnail texture when there is one. Returns-/// (print, cancel).-pub(crate) fn body(- ui: &mut egui::Ui,- d: &mut PrintDraft,- t: &Tokens,- sizes: &[(f64, f64)],- labels: &[String],- thumb: &mut dyn FnMut(usize) -> Option<egui::TextureId>,-) -> (bool, bool) {- ui.set_width(820.0);- ui.label(egui::RichText::new(tl!("Print")).font(theme::semibold(18.0)));- ui.add_space(8.0);- let settings = d.settings(sizes.len(), labels);- let sheets = settings.as_ref().ok().and_then(|s| print::layout(sizes, s).ok()).unwrap_or_default();- d.sheet = d.sheet.min(sheets.len().saturating_sub(1));- ui.horizontal_top(|ui| {- // Settings.- ui.vertical(|ui| {- ui.set_width(470.0);- egui::Grid::new("print-top").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| {- let printer_caption = ui.label(tl!("Printer:"));- let before = d.printer.clone();- // The browser's print dialog sets copies, two-sided printing and colour itself.- let browser = d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER);- ui.horizontal(|ui| {- let shown = match d.printer.as_deref() {- Some(p) => printer_label(p),- None if still_looking(d) => tl!("Looking for printers…").to_string(),- None => tl!("Save as PDF").to_string(),- };- egui::ComboBox::from_id_salt("printer").selected_text(shown).width(260.0).show_ui(ui, |ui| {- if d.printers_loading {- ui.add_enabled(false, egui::Label::new(tl!("Looking for printers…")));- }- for p in &d.printers {- let name = printer_label(&p.name);- let label = if p.default && p.name != crate::web_print::BROWSER_PRINTER {- crate::i18n::fmt(tl!("{name} (default)"), &[("name", &name)])- } else {- name- };- ui.selectable_value(&mut d.printer, Some(p.name.clone()), label);- }- // Chosen even when it was already the selection, so the list arriving- // later doesn't replace it with the default printer.- if ui.selectable_value(&mut d.printer, None, tl!("Save as PDF")).clicked() {- d.printer_picked = true;- }- })- .response- .labelled_by(printer_caption.id);- let tip = if spool::HAS_PRINTER_PREFERENCES {- tl!("Opens the printer driver's preferences. They are saved for every print from this computer; the copies, two-sided, grayscale and paper chosen here still apply.")- } else {- tl!("The printer driver's own settings for this print: paper tray, paper type, finishing and more.")- };- let properties = ui.add_enabled(d.printer.is_some() && !browser, egui::Button::new(tl!("Properties…"))).on_hover_text(tip);- if properties.clicked()- && let Some(p) = d.printer.clone()- {- if spool::HAS_PRINTER_PREFERENCES {- d.driver_error = spool::open_printer_preferences(&p).err().map(|e| e.to_string());- } else {- if d.driver_options.as_ref().is_none_or(|(read_for, _)| *read_for != p) && d.driver_options_loading.as_deref() != Some(p.as_str()) {- // Read off the GUI thread (#1818): `poll_print` starts it next frame.- d.driver_options = None;- d.driver_choices.clear();- d.driver_options_loading = Some(p.clone());- d.read_options_for = Some(p);- }- d.show_driver_options = !d.show_driver_options;- }- }- });- if d.printer != before {- d.printer_picked = true;- d.show_driver_options = false;- d.driver_error = None;- }- ui.end_row();- // The spooler answered with no printer at all (#160): say so, rather than- // leaving Save as PDF looking like the only thing PdfCraft can do.- if !d.printers_loading && d.printers.is_empty() {- ui.label("");- ui.label(- egui::RichText::new(tl!("No printers were found. Check that the printer is installed and the print spooler is running, then open Print again."))- .small()- .color(t.text_muted),- );- ui.end_row();- }- let copies_label = ui.label(tl!("Copies:"));- ui.add_enabled_ui(!browser, |ui| {- ui.horizontal(|ui| {- ui.add(egui::DragValue::new(&mut d.copies).range(1..=999)).labelled_by(copies_label.id);- ui.add(widgets::checkbox(&mut d.collate, tl!("Collate")));- ui.add(widgets::checkbox(&mut d.grayscale, tl!("Print in grayscale")));- });- });- ui.end_row();- // A booklet decides two-sided itself (#2707), so the choice is hidden meanwhile, as- // in Acrobat's Print dialog; it is kept for the other layouts.- if d.handling != Handling::Booklet {- ui.label(tl!("Two-sided:"));- ui.add_enabled_ui(!browser, |ui| {- combo(- ui,- "duplex",- tl!("Two-sided:"),- &mut d.duplex,- &[- (None, tl!("Printer default")),- (Some(spool::Duplex::Off), tl!("Off")),- (Some(spool::Duplex::LongEdge), tl!("Flip on long edge")),- (Some(spool::Duplex::ShortEdge), tl!("Flip on short edge")),- ],- 160.0,- );- });- ui.end_row();- }- let paper_label = ui.label(tl!("Paper:"));- let paper_name = PAPERS.get(d.paper).map_or("US Letter", |p| p.0);- let before = d.paper;- egui::ComboBox::from_id_salt("paper").selected_text(tl!(paper_name)).width(260.0).show_ui(ui, |ui| {- for (i, (name, _)) in PAPERS.iter().enumerate() {- ui.selectable_value(&mut d.paper, i, tl!(name));- }- })- .response- .labelled_by(paper_label.id);- // Label stock gets the label layout (cut, turned upright, fitted).- if d.paper != before && d.paper == print::LABEL_PAPER {- d.paper_before_label = Some(before);- d.handling = Handling::Label;- d.sheet = 0;- }- ui.end_row();- });- // Windows says which drivers can't print two-sided as they're asked; they keep their- // own setting, even when Two-sided is Off.- if let Some(p) = d.printers.iter().find(|p| d.printer.as_ref() == Some(&p.name))- && p.two_sided == Some(false)- {- ui.label(egui::RichText::new(tl!("This printer's driver doesn't take two-sided settings from other programs, so its own setting applies. Change it in Properties…")).small().color(t.text_muted));- }- if d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER) {- ui.label(egui::RichText::new(tl!("Copies, two-sided printing and colour are chosen in the browser's print dialog.")).small().color(t.text_muted));- }- if let Some(e) = &d.driver_error {- ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Couldn't open the printer's preferences: {e}"), &[("e", e)])).small().color(t.text_muted));- }- if d.show_driver_options {- if d.driver_options.is_none() && d.driver_options_loading.is_some() {- ui.label(egui::RichText::new(tl!("Reading the printer's settings…")).small().color(t.text_muted));- } else {- driver_options_panel(ui, d, t);- }- }- if let Some(&source) = sizes.get(d.current_page) {- ui.horizontal_wrapped(|ui| {- ui.label(crate::i18n::fmt(tl!("PDF page: {size}"), &[("size", &d.units.size(source.0, source.1))]));- let matched = print::matching_paper(source);- if ui.add_enabled(matched.is_some(), egui::Button::new(tl!("Match page at 100%"))).clicked()- && let Some(paper) = matched- {- d.paper = paper;- // A paper picked outright: nothing for leaving Label to give back.- d.paper_before_label = None;- d.handling = Handling::Size;- d.size = SizeMode::Actual;- d.orientation = Orientation::Auto;- d.sheet = 0;- }- });- }- ui.add_space(6.0);- widgets::section_title(ui, tl!("Pages to Print"));- ui.horizontal(|ui| {- widgets::radio_value(ui, &mut d.which, Which::All, tl!("All"));- widgets::radio_value(ui, &mut d.which, Which::Current, tl!("Current page"));- let pages = widgets::radio_value(ui, &mut d.which, Which::Range, tl!("Pages"));- let r = ui.add_enabled(- d.which == Which::Range,- crate::widgets::line(&mut d.range).hint_text(format!("1-{}", sizes.len())).desired_width(110.0),- ).labelled_by(pages.id);- if r.gained_focus() {- d.which = Which::Range;- }- });- // Offered only when pages were picked before the dialog opened.- if !d.selected.is_empty() {- let label = format!("{} ({})", tl!("Selected pages"), d.selected.len());- widgets::radio_value(ui, &mut d.which, Which::Selected, label);- }- ui.horizontal(|ui| {- ui.label(tl!("More options:"));- combo(- ui,- "subset",- tl!("More options:"),- &mut d.subset,- &[(Subset::All, tl!("All pages in range")), (Subset::Odd, tl!("Odd pages only")), (Subset::Even, tl!("Even pages only"))],- 150.0,- );- ui.add(widgets::checkbox(&mut d.reverse, tl!("Reverse pages")));- });- ui.add_space(6.0);- widgets::section_title(ui, tl!("Page Sizing & Handling"));- ui.horizontal_wrapped(|ui| {- for (h, label) in [- (Handling::Size, tl!("Size")),- (Handling::Poster, tl!("Poster")),- (Handling::Multiple, tl!("Multiple")),- (Handling::Booklet, tl!("Booklet")),- (Handling::Label, tl!("Label")),- ] {- if widgets::mode_tab(ui, label, d.handling == h).clicked() {- d.set_handling(h);- }- }- });- ui.add_space(4.0);- match d.handling {- Handling::Size => {- ui.horizontal(|ui| {- widgets::radio_value(ui, &mut d.size, SizeMode::Fit, tl!("Fit"));- widgets::radio_value(ui, &mut d.size, SizeMode::Actual, tl!("Actual size"));- widgets::radio_value(ui, &mut d.size, SizeMode::Shrink, tl!("Shrink oversized pages"));- });- ui.horizontal(|ui| {- let custom = matches!(d.size, SizeMode::Custom(_));- if ui.add(widgets::radio(custom, tl!("Custom scale:"))).clicked() {- d.size = SizeMode::Custom(d.custom_scale);- }- ui.add_enabled(custom, egui::DragValue::new(&mut d.custom_scale).range(1.0..=1000.0).suffix(" %"))- .accessible_name(tl!("Custom scale"));- });- }- Handling::Label => {- ui.add(widgets::checkbox(&mut d.label_flip, tl!("Turn upside down (180°)")));- ui.label(- egui::RichText::new(tl!("Cuts each page to its printed area, turns it upright and fits it to the sheet without stretching. One label per sheet."))- .small()- .color(t.text_muted),- );- }- Handling::Poster => {- ui.horizontal(|ui| {- let scale_label = ui.label(tl!("Tile scale:"));- ui.add(egui::DragValue::new(&mut d.poster_scale).range(10.0..=1000.0).suffix(" %")).labelled_by(scale_label.id);- let overlap_label = ui.label(tl!("Overlap:"));- ui.add(egui::DragValue::new(&mut d.overlap).range(0.0..=144.0).suffix(" pt")).labelled_by(overlap_label.id);- ui.add(widgets::checkbox(&mut d.cut_marks, tl!("Cut marks")));- });- }- Handling::Multiple => {- ui.horizontal(|ui| {- ui.label(tl!("Pages per sheet:"));- combo(ui, "per-sheet", tl!("Pages per sheet:"), &mut d.per_sheet, &[(2, "2"), (4, "4"), (6, "6"), (9, "9"), (16, "16")], 60.0);- ui.label(tl!("Page order:"));- combo(- ui,- "order",- tl!("Page order:"),- &mut d.order,- &[- (PageOrder::Horizontal, tl!("Horizontal")),- (PageOrder::HorizontalReversed, tl!("Horizontal reversed")),- (PageOrder::Vertical, tl!("Vertical")),- (PageOrder::VerticalReversed, tl!("Vertical reversed")),- (PageOrder::CutStack, tl!("Cut and stack")),- ],- 150.0,- );- });- ui.horizontal(|ui| {- ui.add(widgets::checkbox(&mut d.border, tl!("Print page border")));- ui.add(widgets::checkbox(&mut d.auto_rotate, tl!("Auto-rotate pages")));- });- if d.order == PageOrder::CutStack {- ui.label(tl!(- "Print single-sided. Keep the sheets in order, cut at the marks, then stack the piles left to right, top to bottom."- ));- }- }- Handling::Booklet => {- ui.horizontal(|ui| {- ui.label(tl!("Booklet subset:"));- combo(- ui,- "booklet",- tl!("Booklet subset:"),- &mut d.booklet_subset,- &[- (BookletSubset::BothSides, tl!("Both sides")),- (BookletSubset::FrontOnly, tl!("Front side only")),- (BookletSubset::BackOnly, tl!("Back side only")),- ],- 130.0,- );- ui.label(tl!("Binding:"));- combo(ui, "binding", tl!("Binding:"), &mut d.binding, &[(Binding::Left, tl!("Left")), (Binding::Right, tl!("Right"))], 80.0);- });- }- }- ui.add_space(6.0);- ui.horizontal(|ui| {- ui.label(tl!("Orientation:"));- widgets::radio_value(ui, &mut d.orientation, Orientation::Auto, tl!("Auto portrait/landscape"));- widgets::radio_value(ui, &mut d.orientation, Orientation::Portrait, tl!("Portrait"));- widgets::radio_value(ui, &mut d.orientation, Orientation::Landscape, tl!("Landscape"));- });- ui.add_space(6.0);- widgets::section_title(ui, tl!("Comments & Forms"));- combo(- ui,- "content",- tl!("Comments & Forms"),- &mut d.content,- &[- (Content::Document, tl!("Document")),- (Content::DocumentAndMarkups, tl!("Document and markups")),- (Content::DocumentAndStamps, tl!("Document and stamps")),- (Content::FormFieldsOnly, tl!("Form fields only")),- ],- 220.0,- );- // Advanced (Acrobat's Advanced Print Setup): print as image. Folded unless it is on.- ui.add_space(6.0);- egui::CollapsingHeader::new(egui::RichText::new(crate::i18n::upper_label("Advanced")).font(theme::semibold(10.5)).color(t.text_faint))- .id_salt("print-advanced")- .default_open(d.as_image)- .show(ui, |ui| {- ui.horizontal(|ui| {- ui.add(widgets::checkbox(&mut d.as_image, tl!("Print as image")));- ui.add_enabled_ui(d.as_image, |ui| {- ui.label(tl!("Resolution:"));- let mut dpi = d.dpi.round() as u32;- combo(ui, "print-dpi", tl!("Resolution:"), &mut dpi, &[(150, "150 dpi"), (300, "300 dpi"), (600, "600 dpi")], 100.0);- d.dpi = f64::from(dpi);- });- });- ui.label(- egui::RichText::new(tl!(- "Use it when a printer skips text, shading or transparency. The print is no longer searchable text; with Print in grayscale, the pictures are grey."- ))- .small()- .color(t.text_muted),- );- });- });- ui.add_space(12.0);- // Preview.- ui.vertical(|ui| {- ui.set_width(PREVIEW_W);- let (area, _) = ui.allocate_exact_size(vec2(PREVIEW_W, PREVIEW_H), egui::Sense::hover());- ui.painter().rect_filled(area, 6.0, t.hover);- match (&settings, sheets.get(d.sheet)) {- (Err(e), _) => {- ui.put(area.shrink(16.0), egui::Label::new(egui::RichText::new(tl!(e)).color(t.text_muted)).wrap());- }- (Ok(_), Some(sheet)) => {- let k = (PREVIEW_BOX.0 / sheet.size.0 as f32).min(PREVIEW_BOX.1 / sheet.size.1 as f32);- let paper = Rect::from_center_size(area.center(), vec2(sheet.size.0 as f32 * k, sheet.size.1 as f32 * k));- ui.painter().rect_filled(paper, 0.0, Color32::WHITE);- ui.painter().rect_stroke(paper, 0.0, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);- let to_screen = |x: f64, y: f64| -> Pos2 { pos2(paper.left() + x as f32 * k, paper.bottom() - y as f32 * k) };- let painter = ui.painter().with_clip_rect(paper);- for pl in &sheet.placed {- let (dw, dh) = sizes[pl.page];- let [x0, y0, x1, y1] = pl.clip;- let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| {- let (sx, sy) = pl.matrix.apply(x, y);- to_screen(sx, sy)- });- // UVs of the visible part (texture y runs down from the page top).- let uv = |x: f64, y: f64| pos2((x / dw) as f32, (1.0 - y / dh) as f32);- let uvs = [uv(x0, y0), uv(x1, y0), uv(x1, y1), uv(x0, y1)];- match thumb(pl.page) {- Some(tex) => {- let mut mesh = egui::Mesh::with_texture(tex);- for (p, u) in corners.iter().zip(uvs) {- mesh.vertices.push(egui::epaint::Vertex {- pos: *p,- uv: u,- color: if d.grayscale { Color32::from_gray(235) } else { Color32::WHITE },- });- }- mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]);- painter.add(egui::Shape::mesh(mesh));- }- None => {- painter.add(egui::Shape::convex_polygon(- corners.to_vec(),- Color32::from_gray(245),- Stroke::new(0.5, Color32::from_gray(180)),- ));- let c = corners.iter().fold(vec2(0.0, 0.0), |a, p| a + p.to_vec2()) / 4.0;- painter.text(- c.to_pos2(),- egui::Align2::CENTER_CENTER,- (pl.page + 1).to_string(),- theme::regular(11.0),- Color32::from_gray(120),- );- }- }- }- for b in &sheet.borders {- painter.rect_stroke(- Rect::from_two_pos(to_screen(b[0], b[1]), to_screen(b[2], b[3])),- 0.0,- Stroke::new(0.6, Color32::BLACK),- egui::StrokeKind::Middle,- );- }- for l in &sheet.lines {- painter.line_segment([to_screen(l[0], l[1]), to_screen(l[2], l[3])], Stroke::new(0.6, Color32::BLACK));- }- }- _ => {}- }- ui.horizontal(|ui| {- let n = sheets.len();- if ui.add_enabled(d.sheet > 0, egui::Button::new("‹")).on_hover_text(tl!("Previous sheet")).clicked() {- d.sheet -= 1;- }- ui.label(if n == 0 {- tl!("No sheets").to_string()- } else {- crate::i18n::fmt(tl!("Sheet {s} of {n}"), &[("s", &(d.sheet + 1).to_string()), ("n", &n.to_string())])- });- if ui.add_enabled(d.sheet + 1 < n, egui::Button::new("›")).on_hover_text(tl!("Next sheet")).clicked() {- d.sheet += 1;- }- });- if let Some(s) = sheets.get(d.sheet) {- ui.label(egui::RichText::new(d.units.size(s.size.0, s.size.1)).small().color(t.text_muted));- if d.handling == Handling::Size- && let Some(p) = s.placed.first()- {- let scale = p.matrix.0[0].hypot(p.matrix.0[1]) * 100.0;- ui.label(crate::i18n::fmt(tl!("PDF scale: {scale}%"), &[("scale", &format!("{scale:.2}"))]));- ui.label(egui::RichText::new(tl!("Printer paper and scaling may differ. Check driver settings.")).small().color(t.text_muted));- if (scale - 100.0).abs() > 0.01 {- ui.label(egui::RichText::new(tl!("Drawing scale changes. Use Actual size for full-scale plans.")).small().color(t.text_muted));- }- }- }- });- });- ui.add_space(12.0);- let (mut go, mut cancel) = (false, false);- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- let looking = still_looking(d);- let label = if d.printer.is_some() || looking { tl!("Print") } else { tl!("Save as PDF") };- if ui.add_enabled_ui(settings.is_ok() && !sheets.is_empty() && !looking, |ui| widgets::pill_button(ui, label, true)).inner.clicked() {- go = true;- }- if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {- cancel = true;- }- });- (go, cancel)-}-#[cfg(test)]mod tests {use super::*;diff --git a/crates/ui-egui/src/print_ui/body.rs b/crates/ui-egui/src/print_ui/body.rsnew file mode 100644index 000000000..baf5c02db--- /dev/null+++ b/crates/ui-egui/src/print_ui/body.rs@@ -0,0 +1,545 @@+use super::draft::{Handling, PrintDraft, Which};+use super::*;++/// Properties… on CUPS: the driver's options for this print, grouped as the driver groups them.+/// Only choices away from the printer's defaults are kept, and sent with the job.+fn driver_options_panel(ui: &mut egui::Ui, d: &mut PrintDraft, t: &Tokens) {+ let PrintDraft { driver_options: Some((_, options)), driver_choices: choices, show_driver_options: show, .. } = d else { return };+ egui::Frame::new().fill(t.hover).corner_radius(egui::CornerRadius::same(6)).inner_margin(egui::Margin::same(10)).show(ui, |ui| {+ ui.set_width(ui.available_width());+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new(tl!("Printer properties")).font(theme::semibold(13.0)));+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if ui.button(tl!("Done")).clicked() {+ *show = false;+ }+ if ui.add_enabled(!choices.is_empty(), egui::Button::new(tl!("Reset to printer defaults"))).clicked() {+ choices.clear();+ }+ });+ });+ if options.is_empty() {+ ui.label(egui::RichText::new(tl!("This printer offers no settings of its own.")).small().color(t.text_muted));+ return;+ }+ egui::ScrollArea::vertical().id_salt("driver-options").max_height(240.0).show(ui, |ui| {+ for (n, chunk) in options.chunk_by(|a, b| a.group == b.group).enumerate() {+ let group = chunk.first().map_or("", |o| o.group.as_str());+ if !group.is_empty() {+ ui.add_space(4.0);+ // Option and group names are the driver's own text.+ ui.label(egui::RichText::new(group).small().color(t.text_muted));+ }+ egui::Grid::new(("driver-group", n)).num_columns(2).spacing([10.0, 4.0]).show(ui, |ui| {+ for o in chunk {+ let current = choices.get(&o.key).cloned().unwrap_or_else(|| o.default.clone());+ let label_of = |c: &str| o.choices.iter().find(|(k, _)| k == c).map_or_else(|| c.to_string(), |(_, l)| l.clone());+ let mut pick = current.clone();+ let option_label = ui.label(&o.label);+ egui::ComboBox::from_id_salt(("driver-option", &o.key))+ .selected_text(label_of(¤t))+ .width(200.0)+ .show_ui(ui, |ui| {+ for (k, l) in &o.choices {+ ui.selectable_value(&mut pick, k.clone(), l.as_str());+ }+ })+ .response+ .labelled_by(option_label.id);+ if pick != current {+ if pick == o.default {+ choices.remove(&o.key);+ } else {+ choices.insert(o.key.clone(), pick);+ }+ }+ ui.end_row();+ }+ });+ }+ });+ });+}++/// Draw a combo box whose accessible name does not depend on the selected value.+fn combo<T: PartialEq + Copy>(ui: &mut egui::Ui, id: &str, name: &str, value: &mut T, choices: &[(T, &str)], width: f32) {+ let shown = choices.iter().find(|c| c.0 == *value).map_or("", |c| c.1);+ egui::ComboBox::from_id_salt(id)+ .selected_text(shown)+ .width(width)+ .show_ui(ui, |ui| {+ for (v, label) in choices {+ ui.selectable_value(value, *v, *label);+ }+ })+ .response+ .accessible_name(name);+}++/// Draw the dialog. `thumb` gives a page's thumbnail texture when there is one. Returns+/// (print, cancel).+pub(crate) fn body(+ ui: &mut egui::Ui,+ d: &mut PrintDraft,+ t: &Tokens,+ sizes: &[(f64, f64)],+ labels: &[String],+ thumb: &mut dyn FnMut(usize) -> Option<egui::TextureId>,+) -> (bool, bool) {+ ui.set_width(820.0);+ ui.label(egui::RichText::new(tl!("Print")).font(theme::semibold(18.0)));+ ui.add_space(8.0);+ let settings = d.settings(sizes.len(), labels);+ let sheets = settings.as_ref().ok().and_then(|s| print::layout(sizes, s).ok()).unwrap_or_default();+ d.sheet = d.sheet.min(sheets.len().saturating_sub(1));+ ui.horizontal_top(|ui| {+ // Settings.+ ui.vertical(|ui| {+ ui.set_width(470.0);+ egui::Grid::new("print-top").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| {+ let printer_caption = ui.label(tl!("Printer:"));+ let before = d.printer.clone();+ // The browser's print dialog sets copies, two-sided printing and colour itself.+ let browser = d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER);+ ui.horizontal(|ui| {+ let shown = match d.printer.as_deref() {+ Some(p) => printer_label(p),+ None if still_looking(d) => tl!("Looking for printers…").to_string(),+ None => tl!("Save as PDF").to_string(),+ };+ egui::ComboBox::from_id_salt("printer").selected_text(shown).width(260.0).show_ui(ui, |ui| {+ if d.printers_loading {+ ui.add_enabled(false, egui::Label::new(tl!("Looking for printers…")));+ }+ for p in &d.printers {+ let name = printer_label(&p.name);+ let label = if p.default && p.name != crate::web_print::BROWSER_PRINTER {+ crate::i18n::fmt(tl!("{name} (default)"), &[("name", &name)])+ } else {+ name+ };+ ui.selectable_value(&mut d.printer, Some(p.name.clone()), label);+ }+ // Chosen even when it was already the selection, so the list arriving+ // later doesn't replace it with the default printer.+ if ui.selectable_value(&mut d.printer, None, tl!("Save as PDF")).clicked() {+ d.printer_picked = true;+ }+ })+ .response+ .labelled_by(printer_caption.id);+ let tip = if spool::HAS_PRINTER_PREFERENCES {+ tl!("Opens the printer driver's preferences. They are saved for every print from this computer; the copies, two-sided, grayscale and paper chosen here still apply.")+ } else {+ tl!("The printer driver's own settings for this print: paper tray, paper type, finishing and more.")+ };+ let properties = ui.add_enabled(d.printer.is_some() && !browser, egui::Button::new(tl!("Properties…"))).on_hover_text(tip);+ if properties.clicked()+ && let Some(p) = d.printer.clone()+ {+ if spool::HAS_PRINTER_PREFERENCES {+ d.driver_error = spool::open_printer_preferences(&p).err().map(|e| e.to_string());+ } else {+ if d.driver_options.as_ref().is_none_or(|(read_for, _)| *read_for != p) && d.driver_options_loading.as_deref() != Some(p.as_str()) {+ // Read off the GUI thread (#1818): `poll_print` starts it next frame.+ d.driver_options = None;+ d.driver_choices.clear();+ d.driver_options_loading = Some(p.clone());+ d.read_options_for = Some(p);+ }+ d.show_driver_options = !d.show_driver_options;+ }+ }+ });+ if d.printer != before {+ d.printer_picked = true;+ d.show_driver_options = false;+ d.driver_error = None;+ }+ ui.end_row();+ // The spooler answered with no printer at all (#160): say so, rather than+ // leaving Save as PDF looking like the only thing PdfCraft can do.+ if !d.printers_loading && d.printers.is_empty() {+ ui.label("");+ ui.label(+ egui::RichText::new(tl!("No printers were found. Check that the printer is installed and the print spooler is running, then open Print again."))+ .small()+ .color(t.text_muted),+ );+ ui.end_row();+ }+ let copies_label = ui.label(tl!("Copies:"));+ ui.add_enabled_ui(!browser, |ui| {+ ui.horizontal(|ui| {+ ui.add(egui::DragValue::new(&mut d.copies).range(1..=999)).labelled_by(copies_label.id);+ ui.add(widgets::checkbox(&mut d.collate, tl!("Collate")));+ ui.add(widgets::checkbox(&mut d.grayscale, tl!("Print in grayscale")));+ });+ });+ ui.end_row();+ // A booklet decides two-sided itself (#2707), so the choice is hidden meanwhile, as+ // in Acrobat's Print dialog; it is kept for the other layouts.+ if d.handling != Handling::Booklet {+ ui.label(tl!("Two-sided:"));+ ui.add_enabled_ui(!browser, |ui| {+ combo(+ ui,+ "duplex",+ tl!("Two-sided:"),+ &mut d.duplex,+ &[+ (None, tl!("Printer default")),+ (Some(spool::Duplex::Off), tl!("Off")),+ (Some(spool::Duplex::LongEdge), tl!("Flip on long edge")),+ (Some(spool::Duplex::ShortEdge), tl!("Flip on short edge")),+ ],+ 160.0,+ );+ });+ ui.end_row();+ }+ let paper_label = ui.label(tl!("Paper:"));+ let paper_name = PAPERS.get(d.paper).map_or("US Letter", |p| p.0);+ let before = d.paper;+ egui::ComboBox::from_id_salt("paper").selected_text(tl!(paper_name)).width(260.0).show_ui(ui, |ui| {+ for (i, (name, _)) in PAPERS.iter().enumerate() {+ ui.selectable_value(&mut d.paper, i, tl!(name));+ }+ })+ .response+ .labelled_by(paper_label.id);+ // Label stock gets the label layout (cut, turned upright, fitted).+ if d.paper != before && d.paper == print::LABEL_PAPER {+ d.paper_before_label = Some(before);+ d.handling = Handling::Label;+ d.sheet = 0;+ }+ ui.end_row();+ });+ // Windows says which drivers can't print two-sided as they're asked; they keep their+ // own setting, even when Two-sided is Off.+ if let Some(p) = d.printers.iter().find(|p| d.printer.as_ref() == Some(&p.name))+ && p.two_sided == Some(false)+ {+ ui.label(egui::RichText::new(tl!("This printer's driver doesn't take two-sided settings from other programs, so its own setting applies. Change it in Properties…")).small().color(t.text_muted));+ }+ if d.printer.as_deref() == Some(crate::web_print::BROWSER_PRINTER) {+ ui.label(egui::RichText::new(tl!("Copies, two-sided printing and colour are chosen in the browser's print dialog.")).small().color(t.text_muted));+ }+ if let Some(e) = &d.driver_error {+ ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Couldn't open the printer's preferences: {e}"), &[("e", e)])).small().color(t.text_muted));+ }+ if d.show_driver_options {+ if d.driver_options.is_none() && d.driver_options_loading.is_some() {+ ui.label(egui::RichText::new(tl!("Reading the printer's settings…")).small().color(t.text_muted));+ } else {+ driver_options_panel(ui, d, t);+ }+ }+ if let Some(&source) = sizes.get(d.current_page) {+ ui.horizontal_wrapped(|ui| {+ ui.label(crate::i18n::fmt(tl!("PDF page: {size}"), &[("size", &d.units.size(source.0, source.1))]));+ let matched = print::matching_paper(source);+ if ui.add_enabled(matched.is_some(), egui::Button::new(tl!("Match page at 100%"))).clicked()+ && let Some(paper) = matched+ {+ d.paper = paper;+ // A paper picked outright: nothing for leaving Label to give back.+ d.paper_before_label = None;+ d.handling = Handling::Size;+ d.size = SizeMode::Actual;+ d.orientation = Orientation::Auto;+ d.sheet = 0;+ }+ });+ }+ ui.add_space(6.0);+ widgets::section_title(ui, tl!("Pages to Print"));+ ui.horizontal(|ui| {+ widgets::radio_value(ui, &mut d.which, Which::All, tl!("All"));+ widgets::radio_value(ui, &mut d.which, Which::Current, tl!("Current page"));+ let pages = widgets::radio_value(ui, &mut d.which, Which::Range, tl!("Pages"));+ let r = ui.add_enabled(+ d.which == Which::Range,+ crate::widgets::line(&mut d.range).hint_text(format!("1-{}", sizes.len())).desired_width(110.0),+ ).labelled_by(pages.id);+ if r.gained_focus() {+ d.which = Which::Range;+ }+ });+ // Offered only when pages were picked before the dialog opened.+ if !d.selected.is_empty() {+ let label = format!("{} ({})", tl!("Selected pages"), d.selected.len());+ widgets::radio_value(ui, &mut d.which, Which::Selected, label);+ }+ ui.horizontal(|ui| {+ ui.label(tl!("More options:"));+ combo(+ ui,+ "subset",+ tl!("More options:"),+ &mut d.subset,+ &[(Subset::All, tl!("All pages in range")), (Subset::Odd, tl!("Odd pages only")), (Subset::Even, tl!("Even pages only"))],+ 150.0,+ );+ ui.add(widgets::checkbox(&mut d.reverse, tl!("Reverse pages")));+ });+ ui.add_space(6.0);+ widgets::section_title(ui, tl!("Page Sizing & Handling"));+ ui.horizontal_wrapped(|ui| {+ for (h, label) in [+ (Handling::Size, tl!("Size")),+ (Handling::Poster, tl!("Poster")),+ (Handling::Multiple, tl!("Multiple")),+ (Handling::Booklet, tl!("Booklet")),+ (Handling::Label, tl!("Label")),+ ] {+ if widgets::mode_tab(ui, label, d.handling == h).clicked() {+ d.set_handling(h);+ }+ }+ });+ ui.add_space(4.0);+ match d.handling {+ Handling::Size => {+ ui.horizontal(|ui| {+ widgets::radio_value(ui, &mut d.size, SizeMode::Fit, tl!("Fit"));+ widgets::radio_value(ui, &mut d.size, SizeMode::Actual, tl!("Actual size"));+ widgets::radio_value(ui, &mut d.size, SizeMode::Shrink, tl!("Shrink oversized pages"));+ });+ ui.horizontal(|ui| {+ let custom = matches!(d.size, SizeMode::Custom(_));+ if ui.add(widgets::radio(custom, tl!("Custom scale:"))).clicked() {+ d.size = SizeMode::Custom(d.custom_scale);+ }+ ui.add_enabled(custom, egui::DragValue::new(&mut d.custom_scale).range(1.0..=1000.0).suffix(" %"))+ .accessible_name(tl!("Custom scale"));+ });+ }+ Handling::Label => {+ ui.add(widgets::checkbox(&mut d.label_flip, tl!("Turn upside down (180°)")));+ ui.label(+ egui::RichText::new(tl!("Cuts each page to its printed area, turns it upright and fits it to the sheet without stretching. One label per sheet."))+ .small()+ .color(t.text_muted),+ );+ }+ Handling::Poster => {+ ui.horizontal(|ui| {+ let scale_label = ui.label(tl!("Tile scale:"));+ ui.add(egui::DragValue::new(&mut d.poster_scale).range(10.0..=1000.0).suffix(" %")).labelled_by(scale_label.id);+ let overlap_label = ui.label(tl!("Overlap:"));+ ui.add(egui::DragValue::new(&mut d.overlap).range(0.0..=144.0).suffix(" pt")).labelled_by(overlap_label.id);+ ui.add(widgets::checkbox(&mut d.cut_marks, tl!("Cut marks")));+ });+ }+ Handling::Multiple => {+ ui.horizontal(|ui| {+ ui.label(tl!("Pages per sheet:"));+ combo(ui, "per-sheet", tl!("Pages per sheet:"), &mut d.per_sheet, &[(2, "2"), (4, "4"), (6, "6"), (9, "9"), (16, "16")], 60.0);+ ui.label(tl!("Page order:"));+ combo(+ ui,+ "order",+ tl!("Page order:"),+ &mut d.order,+ &[+ (PageOrder::Horizontal, tl!("Horizontal")),+ (PageOrder::HorizontalReversed, tl!("Horizontal reversed")),+ (PageOrder::Vertical, tl!("Vertical")),+ (PageOrder::VerticalReversed, tl!("Vertical reversed")),+ (PageOrder::CutStack, tl!("Cut and stack")),+ ],+ 150.0,+ );+ });+ ui.horizontal(|ui| {+ ui.add(widgets::checkbox(&mut d.border, tl!("Print page border")));+ ui.add(widgets::checkbox(&mut d.auto_rotate, tl!("Auto-rotate pages")));+ });+ if d.order == PageOrder::CutStack {+ ui.label(tl!(+ "Print single-sided. Keep the sheets in order, cut at the marks, then stack the piles left to right, top to bottom."+ ));+ }+ }+ Handling::Booklet => {+ ui.horizontal(|ui| {+ ui.label(tl!("Booklet subset:"));+ combo(+ ui,+ "booklet",+ tl!("Booklet subset:"),+ &mut d.booklet_subset,+ &[+ (BookletSubset::BothSides, tl!("Both sides")),+ (BookletSubset::FrontOnly, tl!("Front side only")),+ (BookletSubset::BackOnly, tl!("Back side only")),+ ],+ 130.0,+ );+ ui.label(tl!("Binding:"));+ combo(ui, "binding", tl!("Binding:"), &mut d.binding, &[(Binding::Left, tl!("Left")), (Binding::Right, tl!("Right"))], 80.0);+ });+ }+ }+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ ui.label(tl!("Orientation:"));+ widgets::radio_value(ui, &mut d.orientation, Orientation::Auto, tl!("Auto portrait/landscape"));+ widgets::radio_value(ui, &mut d.orientation, Orientation::Portrait, tl!("Portrait"));+ widgets::radio_value(ui, &mut d.orientation, Orientation::Landscape, tl!("Landscape"));+ });+ ui.add_space(6.0);+ widgets::section_title(ui, tl!("Comments & Forms"));+ combo(+ ui,+ "content",+ tl!("Comments & Forms"),+ &mut d.content,+ &[+ (Content::Document, tl!("Document")),+ (Content::DocumentAndMarkups, tl!("Document and markups")),+ (Content::DocumentAndStamps, tl!("Document and stamps")),+ (Content::FormFieldsOnly, tl!("Form fields only")),+ ],+ 220.0,+ );+ // Advanced (Acrobat's Advanced Print Setup): print as image. Folded unless it is on.+ ui.add_space(6.0);+ egui::CollapsingHeader::new(egui::RichText::new(crate::i18n::upper_label("Advanced")).font(theme::semibold(10.5)).color(t.text_faint))+ .id_salt("print-advanced")+ .default_open(d.as_image)+ .show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.add(widgets::checkbox(&mut d.as_image, tl!("Print as image")));+ ui.add_enabled_ui(d.as_image, |ui| {+ ui.label(tl!("Resolution:"));+ let mut dpi = d.dpi.round() as u32;+ combo(ui, "print-dpi", tl!("Resolution:"), &mut dpi, &[(150, "150 dpi"), (300, "300 dpi"), (600, "600 dpi")], 100.0);+ d.dpi = f64::from(dpi);+ });+ });+ ui.label(+ egui::RichText::new(tl!(+ "Use it when a printer skips text, shading or transparency. The print is no longer searchable text; with Print in grayscale, the pictures are grey."+ ))+ .small()+ .color(t.text_muted),+ );+ });+ });+ ui.add_space(12.0);+ // Preview.+ ui.vertical(|ui| {+ ui.set_width(PREVIEW_W);+ let (area, _) = ui.allocate_exact_size(vec2(PREVIEW_W, PREVIEW_H), egui::Sense::hover());+ ui.painter().rect_filled(area, 6.0, t.hover);+ match (&settings, sheets.get(d.sheet)) {+ (Err(e), _) => {+ ui.put(area.shrink(16.0), egui::Label::new(egui::RichText::new(tl!(e)).color(t.text_muted)).wrap());+ }+ (Ok(_), Some(sheet)) => {+ let k = (PREVIEW_BOX.0 / sheet.size.0 as f32).min(PREVIEW_BOX.1 / sheet.size.1 as f32);+ let paper = Rect::from_center_size(area.center(), vec2(sheet.size.0 as f32 * k, sheet.size.1 as f32 * k));+ ui.painter().rect_filled(paper, 0.0, Color32::WHITE);+ ui.painter().rect_stroke(paper, 0.0, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);+ let to_screen = |x: f64, y: f64| -> Pos2 { pos2(paper.left() + x as f32 * k, paper.bottom() - y as f32 * k) };+ let painter = ui.painter().with_clip_rect(paper);+ for pl in &sheet.placed {+ let (dw, dh) = sizes[pl.page];+ let [x0, y0, x1, y1] = pl.clip;+ let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| {+ let (sx, sy) = pl.matrix.apply(x, y);+ to_screen(sx, sy)+ });+ // UVs of the visible part (texture y runs down from the page top).+ let uv = |x: f64, y: f64| pos2((x / dw) as f32, (1.0 - y / dh) as f32);+ let uvs = [uv(x0, y0), uv(x1, y0), uv(x1, y1), uv(x0, y1)];+ match thumb(pl.page) {+ Some(tex) => {+ let mut mesh = egui::Mesh::with_texture(tex);+ for (p, u) in corners.iter().zip(uvs) {+ mesh.vertices.push(egui::epaint::Vertex {+ pos: *p,+ uv: u,+ color: if d.grayscale { Color32::from_gray(235) } else { Color32::WHITE },+ });+ }+ mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]);+ painter.add(egui::Shape::mesh(mesh));+ }+ None => {+ painter.add(egui::Shape::convex_polygon(+ corners.to_vec(),+ Color32::from_gray(245),+ Stroke::new(0.5, Color32::from_gray(180)),+ ));+ let c = corners.iter().fold(vec2(0.0, 0.0), |a, p| a + p.to_vec2()) / 4.0;+ painter.text(+ c.to_pos2(),+ egui::Align2::CENTER_CENTER,+ (pl.page + 1).to_string(),+ theme::regular(11.0),+ Color32::from_gray(120),+ );+ }+ }+ }+ for b in &sheet.borders {+ painter.rect_stroke(+ Rect::from_two_pos(to_screen(b[0], b[1]), to_screen(b[2], b[3])),+ 0.0,+ Stroke::new(0.6, Color32::BLACK),+ egui::StrokeKind::Middle,+ );+ }+ for l in &sheet.lines {+ painter.line_segment([to_screen(l[0], l[1]), to_screen(l[2], l[3])], Stroke::new(0.6, Color32::BLACK));+ }+ }+ _ => {}+ }+ ui.horizontal(|ui| {+ let n = sheets.len();+ if ui.add_enabled(d.sheet > 0, egui::Button::new("‹")).on_hover_text(tl!("Previous sheet")).clicked() {+ d.sheet -= 1;+ }+ ui.label(if n == 0 {+ tl!("No sheets").to_string()+ } else {+ crate::i18n::fmt(tl!("Sheet {s} of {n}"), &[("s", &(d.sheet + 1).to_string()), ("n", &n.to_string())])+ });+ if ui.add_enabled(d.sheet + 1 < n, egui::Button::new("›")).on_hover_text(tl!("Next sheet")).clicked() {+ d.sheet += 1;+ }+ });+ if let Some(s) = sheets.get(d.sheet) {+ ui.label(egui::RichText::new(d.units.size(s.size.0, s.size.1)).small().color(t.text_muted));+ if d.handling == Handling::Size+ && let Some(p) = s.placed.first()+ {+ let scale = p.matrix.0[0].hypot(p.matrix.0[1]) * 100.0;+ ui.label(crate::i18n::fmt(tl!("PDF scale: {scale}%"), &[("scale", &format!("{scale:.2}"))]));+ ui.label(egui::RichText::new(tl!("Printer paper and scaling may differ. Check driver settings.")).small().color(t.text_muted));+ if (scale - 100.0).abs() > 0.01 {+ ui.label(egui::RichText::new(tl!("Drawing scale changes. Use Actual size for full-scale plans.")).small().color(t.text_muted));+ }+ }+ }+ });+ });+ ui.add_space(12.0);+ let (mut go, mut cancel) = (false, false);+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ let looking = still_looking(d);+ let label = if d.printer.is_some() || looking { tl!("Print") } else { tl!("Save as PDF") };+ if ui.add_enabled_ui(settings.is_ok() && !sheets.is_empty() && !looking, |ui| widgets::pill_button(ui, label, true)).inner.clicked() {+ go = true;+ }+ if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {+ cancel = true;+ }+ });+ (go, cancel)+}diff --git a/crates/ui-egui/src/print_ui/draft.rs b/crates/ui-egui/src/print_ui/draft.rsnew file mode 100644index 000000000..1609262ab--- /dev/null+++ b/crates/ui-egui/src/print_ui/draft.rs@@ -0,0 +1,238 @@+use super::*;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Which {+ All,+ Current,+ Range,+ /// The pages picked in the Pages panel or the organize grid when the dialog opened.+ Selected,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Handling {+ Size,+ Poster,+ Multiple,+ Booklet,+ /// Shipping label: cut to the printed area, turned upright, one per sheet.+ Label,+}++#[derive(Clone, Debug, PartialEq)]+pub struct PrintDraft {+ pub printers: Vec<spool::Printer>,+ /// The unit the sheet size is shown in (Preferences).+ pub units: crate::units::Unit,+ /// The printers are still being listed in the background (see [`PrinterSource`]).+ pub printers_loading: bool,+ /// The user chose the printer, so a list arriving late doesn't move it to the default.+ pub printer_picked: bool,+ /// `None` = Save as PDF.+ pub printer: Option<String>,+ pub copies: u32,+ pub collate: bool,+ pub grayscale: bool,+ /// `None` = the printer's own default (its Properties), as Acrobat does.+ pub duplex: Option<spool::Duplex>,+ pub which: Which,+ pub range: String,+ /// The pages `Which::Selected` prints (0-based, in page order); empty when none were picked.+ pub selected: Vec<usize>,+ pub subset: Subset,+ pub reverse: bool,+ pub handling: Handling,+ pub size: SizeMode,+ pub custom_scale: f64,+ pub per_sheet: usize,+ pub order: PageOrder,+ pub border: bool,+ pub auto_rotate: bool,+ pub booklet_subset: BookletSubset,+ pub binding: Binding,+ pub poster_scale: f64,+ pub overlap: f64,+ pub cut_marks: bool,+ pub orientation: Orientation,+ pub content: Content,+ /// Print as image (Acrobat's Advanced Print Setup) at `dpi`.+ pub as_image: bool,+ pub dpi: f64,+ pub paper: usize,+ /// The paper chosen before Label put label stock in, so leaving Label gives it back (#3564).+ pub paper_before_label: Option<usize>,+ /// The sheet shown in the preview (0-based).+ pub sheet: usize,+ pub current_page: usize,+ /// The printer driver's own options and the printer they were read for (Properties…, CUPS).+ pub driver_options: Option<(String, Vec<spool::PrinterOption>)>,+ /// Driver options set away from the printer's defaults, for `driver_options`' printer.+ pub driver_choices: std::collections::BTreeMap<String, String>,+ pub show_driver_options: bool,+ /// Why the printer's preferences window didn't open (Windows).+ pub driver_error: Option<String>,+ /// Label: turn a further 180°.+ pub label_flip: bool,+ /// Label: each page's printed area and text direction, read when Label is chosen+ /// ([`PdfCraftApp::read_label_crops`]); empty until then.+ pub crops: Vec<Option<print::Crop>>,+ /// The pages `crops` were read for, so a changed page selection reads them again.+ pub crop_pages: Option<Vec<usize>>,+ /// The printer whose options are being read in the background (CUPS runs `lpoptions`,+ /// which a stuck CUPS can hold up; #1818). The panel says so meanwhile.+ pub driver_options_loading: Option<String>,+ /// Properties… asked for this printer's options; the app starts the read on the next frame.+ pub read_options_for: Option<String>,+}++impl Default for PrintDraft {+ fn default() -> Self {+ PrintDraft {+ printers: Vec::new(),+ units: Default::default(),+ printers_loading: false,+ printer_picked: false,+ printer: None,+ copies: 1,+ collate: true,+ grayscale: false,+ duplex: None,+ which: Which::All,+ range: String::new(),+ selected: Vec::new(),+ subset: Subset::All,+ reverse: false,+ handling: Handling::Size,+ size: SizeMode::Fit,+ custom_scale: 100.0,+ per_sheet: 2,+ order: PageOrder::Horizontal,+ border: false,+ auto_rotate: true,+ booklet_subset: BookletSubset::BothSides,+ binding: Binding::Left,+ poster_scale: 200.0,+ overlap: 18.0,+ cut_marks: true,+ orientation: Orientation::Auto,+ content: Content::DocumentAndMarkups,+ as_image: false,+ dpi: 300.0,+ paper: 0,+ paper_before_label: None,+ sheet: 0,+ current_page: 0,+ driver_options: None,+ driver_choices: Default::default(),+ show_driver_options: false,+ driver_error: None,+ label_flip: false,+ crops: Vec::new(),+ crop_pages: None,+ driver_options_loading: None,+ read_options_for: None,+ }+ }+}++impl PrintDraft {+ /// Choose Page Sizing & Handling. Label loads label stock and remembers the paper it+ /// replaced; leaving Label gives that paper back, unless another one was picked meanwhile.+ pub fn set_handling(&mut self, handling: Handling) {+ let leaving_label = self.handling == Handling::Label && handling != Handling::Label;+ self.handling = handling;+ self.sheet = 0;+ if handling == Handling::Label {+ // A label goes on label stock.+ if self.paper != print::LABEL_PAPER {+ self.paper_before_label = Some(self.paper);+ self.paper = print::LABEL_PAPER;+ }+ } else if leaving_label+ && let Some(paper) = self.paper_before_label.take()+ && self.paper == print::LABEL_PAPER+ {+ self.paper = paper;+ }+ }++ /// The engine settings for this draft (page count and labels from the document).+ pub fn settings(&self, count: usize, labels: &[String]) -> Result<print::Settings, String> {+ if self.cut_and_stack() && matches!(self.duplex, Some(spool::Duplex::LongEdge | spool::Duplex::ShortEdge)) {+ return Err("Cut and stack needs Two-sided: Off. Print single-sided sheets.".into());+ }+ let range = match self.which {+ Which::All | Which::Selected | Which::Current => None,+ Which::Range => Some(self.range.clone()),+ };+ // Selected and Current are positions, not a typed range: a range would read numbers as+ // page labels first.+ let pages = match self.which {+ Which::Selected => print::select_listed(count, &self.selected, self.subset, self.reverse),+ Which::Current => print::select_listed(count, &[self.current_page], self.subset, self.reverse),+ Which::All | Which::Range => print::select_pages(count, range.as_deref(), labels, self.subset, self.reverse),+ }+ // What the person got wrong about what to print is said in their language: the engine hands+ // the wording over whole and the page numbers apart from it.+ .map_err(|e| e.said(&crate::i18n::words))?;+ let layout = match self.handling {+ Handling::Size => Layout::Size(match self.size {+ SizeMode::Custom(_) => SizeMode::Custom(self.custom_scale),+ m => m,+ }),+ Handling::Multiple => match Layout::multiple(self.per_sheet) {+ Layout::Multiple { cols, rows, per_sheet, .. } => {+ Layout::Multiple { cols, rows, per_sheet, order: self.order, border: self.border, auto_rotate: self.auto_rotate }+ }+ other => other,+ },+ Handling::Booklet => Layout::Booklet { subset: self.booklet_subset, binding: self.binding },+ Handling::Poster => Layout::Poster { scale: self.poster_scale, overlap: self.overlap, cut_marks: self.cut_marks },+ Handling::Label => Layout::Label { flip: self.label_flip },+ };+ Ok(print::Settings {+ pages,+ paper: PAPERS[self.paper.min(PAPERS.len() - 1)].1,+ orientation: self.orientation,+ layout,+ content: self.content,+ raster: self.as_image.then_some(print::Raster { dpi: self.dpi, grayscale: self.grayscale }),+ crops: self.crops.clone(),+ })+ }++ fn cut_and_stack(&self) -> bool {+ self.handling == Handling::Multiple && self.order == PageOrder::CutStack+ }++ /// The spooler job for this print: the dialog's copies, two-sided and colour settings, the+ /// driver options changed from the printer's defaults, and the chosen paper.+ pub fn job(&self, title: &str) -> spool::Job {+ spool::Job {+ printer: self.printer.clone(),+ copies: self.copies.max(1),+ collate: self.collate,+ // Cut and stack needs single-sided sheets, whatever the printer's default; a booklet+ // decides two-sided itself (#2707), leaving the Two-sided choice as it was.+ duplex: if self.cut_and_stack() {+ Some(spool::Duplex::Off)+ } else if self.handling == Handling::Booklet {+ Some(print::booklet_duplex(self.booklet_subset))+ } else {+ self.duplex+ },+ scaling: spool::Scaling::Exact,+ grayscale: self.grayscale,+ title: title.to_string(),+ // Only for the printer the options were read from.+ options: match (&self.printer, &self.driver_options) {+ (Some(p), Some((read_for, _))) if p == read_for => self.driver_choices.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),+ _ => Vec::new(),+ }+ .into_iter()+ // The sheet the PDF was laid out on, not the queue's default paper.+ .chain(print::media_option(self.paper))+ .collect(),+ }+ }+}