diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index a5d450b854..fb28192f05 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -42,7 +42,7 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String { mod system { use super::{Command, PrintJob, Printer}; pub fn printers() -> Vec { - craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect() + craft::print::printers().into_iter().map(Printer::from).collect() } pub fn print(job: &PrintJob) -> Result { if job.direct_pdf { @@ -50,8 +50,8 @@ mod system { } // Copies, layout, marks and colour management are already in the PDF. Preserve its // physical sheet size and the queue's duplex default without printing copies twice. - let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; - craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string()) + let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; + craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string()) } #[cfg(windows)] pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command { @@ -113,14 +113,6 @@ mod tests { assert_eq!(args, ["printui.dll,PrintUIEntry", "/e", "/n", "Office Laser"]); } - #[test] - fn setup_command_falls_back_to_default_printer() { - let cmd = setup_command(None, Some("Default Proofer")); - assert_eq!(cmd.get_program(), "rundll32.exe"); - let args: Vec<&OsStr> = cmd.get_args().collect(); - assert_eq!(args, ["printui.dll,PrintUIEntry", "/e", "/n", "Default Proofer"]); - } - #[test] fn setup_command_trims_whitespace_and_skips_empty() { let cmd = setup_command(Some(" "), Some("Default Proofer")); @@ -140,19 +132,11 @@ mod tests { #[cfg(test)] mod turn_tests { - use super::{SystemPrint, sent}; - use vectorcraft_ui_egui::print::PrintService; - - #[test] - fn the_sent_status_names_the_job_the_printer_and_the_note() { - assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer"); - assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser"); - assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12"); - } + use super::sent; #[test] fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() { - use vectorcraft_ui_egui::i18n::{Lang, message}; + use vectorcraft_ui_egui::i18n::{Lang, LangExt, message}; let Some(de) = Lang::from_code("de") else { panic!("no German catalog") }; let printer = Some("HP LaserJet (Copy 1)"); assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet"); @@ -161,9 +145,4 @@ mod turn_tests { "“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12" ); } - - #[test] - fn only_macos_queues_need_landscape_pages_turned() { - assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos")); - } } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index de04998800..8d9c49f8da 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -1,141 +1,145 @@ -//! File → Print: the Print dialog. The print preset (and Save Preset…) and the printer (and -//! Setup…) on top, then the sections General, -//! Marks and Bleed, Output, Graphics, Color Management, Advanced and Summary, with a preview of the -//! printed page under the section list: the arrows step through the pages, dragging the art moves -//! its placement on the paper. +//! File → Print: the Print dialog, over `craft::print::ui::HostedPrint`. The print preset and the +//! printer on top, then the sections General, Marks and Bleed, Output, Graphics, Color Management, +//! Advanced and Summary, with a preview of the printed page: the arrows step through the pages, +//! dragging the art moves its placement on the paper. //! -//! The fields are the print settings (`print.setup`'s; sections are objects such as `marks`) plus -//! `printer` (a name from `print.printers`, "" the system's default), `toFile` (save the job as a -//! PDF instead) and UI-only `__` keys, so agents fill the dialog with `ui.dialog.set`. Print (OK) -//! keeps the settings with the document (`print.setup`) and prints them (`file.print`); Done -//! (`discard: true`, then confirm) only keeps them. The preview, the inks and the Summary come -//! from `print.preview`: the dialog lays nothing out itself. +//! The values are the print settings (`print.setup`'s; sections are objects such as `marks`), so +//! agents fill the dialog with `ui.dialog.set`. The printer, the copies and the like live in the +//! framework's `Settings`. Print (OK) keeps the settings with the document (`print.setup`) and +//! prints them (`file.print`); Done only keeps them. The preview, the inks and the Summary come +//! from `print.preview`: the dialog lays nothing out itself. OK is held until the pump has run the +//! checks, so a refused print leaves the dialog open with the reason. //! -//! `preset` names the print preset whose settings were loaded last: setting it (the list, or -//! `ui.dialog.set`) loads that preset's settings. Save Preset… names the settings as a preset -//! (`print.presets.save`). The same dialog edits a preset (kind `printPreset`, from Edit → Print -//! Presets): a `name` instead of the preset and printer, and OK saves the preset. +//! The same dialog edits a preset (`open_preset`, from Edit → Print Presets): a name instead of +//! the preset and printer, and OK saves the preset. -use std::sync::{Arc, LazyLock}; +// PLAN: assumed import paths for the framework facade (`craft_ui`) and the `HostedPrint` builders +// (`layout`, `mode`, `header`, `check_name`, `held_ok`, `take_ok`, `answer_ok`, `take_setup`, +// `set_presets`, `set_message`, `set_sheet(Option<_>)`, `set_field`, `sheet_index`); export-w7 writes them. +use std::sync::{Arc, LazyLock, mpsc}; -use serde_json::{Value, json}; +use craft::print::ui::{HostedPrint, PrintAnswer, PrintFinish, PrintLayout, PrintMode, PrintSection, PrintSheet, Printer, State}; +use craft_ui::behavior::{Anchor9, EditEvent, EditEvents, Mixed}; +use craft_ui::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; +use craft_ui::presets::{NamedPresetEvent, PresetRow}; +use craft_ui::units::{LengthUnits, UnitKind}; +use craft_ui::widgets::{LinkMode, LinkedFields, ReferencePoint, ReferencePointLook}; +use serde_json::{Map, Value, json}; use vectorcraft_color::cms::Intent; +use vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET; use vectorcraft_geom::Rect as DRect; use vectorcraft_pdf::{ Choice, Emulsion, FontDownload, Media, Orientation, Origin, OutputMode, PrintArtboards, PrintImage, PrintLayers, PrintOverprints, PrintScaling, PrintSettings, }; -use super::save_pdf::{TOP_LABEL_WIDTH, choice, current_section, flag, get, heading, length, note, number, pick, row, row_with, set, text}; -use super::{DialogSpec, form}; -use crate::state::Dialog; -use crate::theme::{self, Tokens}; +use super::form; use crate::{VectorcraftApp, widgets}; -use vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET; -pub(super) const KIND: &str = "print"; - -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Print").into(), body, confirm, ok: Some("Print"), discard: Some("Done"), ..DialogSpec::FORM }; - -/// The dialog kind of the preset editor (New / Edit in Edit → Print Presets). -pub(super) const PRESET_KIND: &str = "printPreset"; - -pub(super) const PRESET_SPEC: DialogSpec = DialogSpec { - heading: |d| if d.str(EDITING).is_empty() { tl!("New Print Preset") } else { tl!("Edit Print Preset") }.into(), - body, - confirm: confirm_preset, - ok: Some("Save Preset"), - ..DialogSpec::FORM -}; - -/// The preset editor's field holding the name of the saved preset it edits (empty: a new one). -const EDITING: &str = "__editing"; -/// The field holding the name typed for Save Preset… (present while that row shows). -const SAVE_AS: &str = "__savePresetAs"; -/// The preset whose settings were loaded last (`preset` loads its settings when it differs). -const LOADED: &str = "__loaded"; - -pub(super) const SECTIONS: [&str; 7] = ["General", "Marks and Bleed", "Output", "Graphics", "Color Management", "Advanced", "Summary"]; +pub(crate) const SECTIONS: [&str; 7] = ["General", "Marks and Bleed", "Output", "Graphics", "Color Management", "Advanced", "Summary"]; /// The default print settings as JSON: what a field an agent left out reads as. static DEFAULTS: LazyLock = LazyLock::new(|| serde_json::to_value(PrintSettings::default()).unwrap_or_default()); -/// The defaults of the settings a dialog of `kind` edits, when it is a Print dialog. -pub(super) fn defaults(kind: &str) -> Option<&'static Value> { - (kind == KIND || kind == PRESET_KIND).then(|| &*DEFAULTS) -} +/// The rows of every section: the keys `form::fields_of` and `form::json_of` map by. +static KEYS: LazyLock> = LazyLock::new(|| sections(&Lists::default()).into_iter().flat_map(|s| s.params).collect()); /// Set when the Print Tiling tool placed the pages (`tileOrigin`): the placement is ignored. const PLACED: &str = "tileOrigin.placed"; -/// The link between Scale W and H. -const SCALE_LINKED: &str = "scale.linked"; -/// Scale W and H as [`link_scale`] last left them, to tell which one changed since. -const SCALE_SEEN: &str = "__scaleSeen"; - /// The fields that aren't print settings. -const NOT_SETTINGS: [&str; 5] = ["printer", "toFile", "discard", "preset", "name"]; +const NOT_SETTINGS: [&str; 2] = ["name", "directPdf"]; -/// The Printer list's entries besides the system's printers. +/// The Printer list's entries besides the system's printers; `PDF_FILE` is the destination that +/// saves the job as a PDF. const DEFAULT_PRINTER: &str = "Default Printer"; const PDF_FILE: &str = "PDF File"; -/// The preview's size in the section column. -const PREVIEW: egui::Vec2 = egui::vec2(super::save_pdf::LIST_WIDTH - 12.0, 168.0); +/// The Printer Profile entry for no conversion. +const SAME_AS_SOURCE: &str = "Same As Source"; +/// The flattener Preset entry for transparency printed as it is. +const KEEP_TRANSPARENCY: &str = "None (keep transparency)"; + +/// The longest side, in pixels, of the picture of the art in the preview. +const ART_PX: f64 = 1024.0; + +/// The nine points of the Placement picker, in `Origin::ALL`'s order. +const ANCHORS: [Anchor9; 9] = [ + Anchor9::TopLeft, + Anchor9::Top, + Anchor9::TopRight, + Anchor9::Left, + Anchor9::Centre, + Anchor9::Right, + Anchor9::BottomLeft, + Anchor9::Bottom, + Anchor9::BottomRight, +]; + +/// The Print dialog the app has open (`app.print_dialog`). +// PLAN: hub-w1 adds the field `print_dialog: dialogs::print::PrintDialogs` to the app; hub-w2 adds `print::pump` to `dialogs::host::pump`. +#[derive(Default)] +pub(crate) struct PrintDialogs { + open: Option, +} + +/// What the pump keeps of the open dialog: what the answer needs after the framework has answered, and the +/// texture and preview the dialog shows until the document or the settings change. +struct Open { + id: craft_ui::dialogs::DialogId, + mode: PrintMode, + /// The preset the settings were loaded from last (the Print Preset row's selection). + preset: String, + /// The saved preset the editor edits (empty: a new one). + editing: String, + /// The picture of the art, with what it was made for. + art: Option<(ArtKey, egui::TextureHandle)>, + /// `print.preview` of the settings and document it was run for. + preview: Option<(Stamp, Arc>)>, +} + +/// The document (uid, revision) and the settings a cached preview belongs to. +type Stamp = (String, (u64, u64)); + +/// The document (uid, revision), layers, area and size a picture of the art was made for. +type ArtKey = (u64, u64, PrintLayers, [u64; 4], u32); + +/// What the pump took from the dialog this pass. +struct Drained { + refresh: bool, + setup: Option, + moves: EditEvents, + events: Vec>, + ok: Option, + settings: Value, + sheet: usize, +} + +/// The lists the rows offer that the app holds (the profiles, the flattener presets). +#[derive(Default)] +struct Lists { + profiles: Vec, + flatteners: Vec, +} + +impl Lists { + fn of(app: &VectorcraftApp) -> Self { + Self { + profiles: vectorcraft_color::cms::profiles().iter().map(|p| p.name.clone()).collect(), + flatteners: app.session.flattener_presets().iter().map(|p| p.name.clone()).collect(), + } + } +} /// Open the Print dialog on the document's print settings and the system's default printer. pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document")?; // The settings saved with the document, every field filled in (defaults if never set up). let saved: PrintSettings = st.doc.print_setup.clone().and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default(); - let mut fields = fields_of(&saved)?; - let printers = crate::print::printers(app); - let list = printers["printers"].as_array().map(Vec::as_slice).unwrap_or_default(); - let default = list.iter().find(|p| p["default"] == true).or(list.first()).and_then(|p| p["name"].as_str()).unwrap_or_default(); - fields.insert("printer".into(), json!(default)); - fields.insert("toFile".into(), json!(!printers["service"].as_bool().unwrap_or(false))); - fields.insert("__printers".into(), printers); - app.ui.print_direct_pdf = false; - fields.insert("__section".into(), json!(SECTIONS[0])); - fields.insert("__sheet".into(), json!(0)); // The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ). - let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()); - fields.insert("preset".into(), json!(preset)); - fields.insert(LOADED.into(), json!(preset)); - see_scale(&mut fields); - app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); - Ok(Value::Null) -} - -/// The settings as dialog fields. -fn fields_of(set: &PrintSettings) -> Result, String> { - match serde_json::to_value(set).map_err(|e| e.to_string())? { - Value::Object(fields) => Ok(fields), - _ => Err("print settings are not an object".into()), - } -} - -/// Load the settings of the preset `preset` names once it changed (the list, or `ui.dialog.set`). -fn sync_preset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { - let name = d.str("preset"); - if d.kind != KIND || name == d.str(LOADED) { - return Ok(()); - } - d.fields.insert(LOADED.into(), json!(name)); - let set = app.session.print_preset_settings(&name).ok_or_else(|| format!("no print preset named `{name}`"))?; - d.fields.extend(fields_of(&set)?); - see_scale(&mut d.fields); - Ok(()) -} - -/// Save Preset…: save the settings under the typed name and pick that preset. -fn save_preset(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { - let r = app.run("print.presets.save", json!({ "name": d.str(SAVE_AS), "preset": DEFAULT_PRESET, "settings": settings(d) }))?; - d.fields.remove(SAVE_AS); - d.fields.insert("preset".into(), r["name"].clone()); - d.fields.insert(LOADED.into(), r["name"].clone()); - Ok(r) + let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()).to_string(); + let map = fields_of(&saved)?; + start(app, PrintMode::Print, map, preset, String::new()) } /// Open the preset editor on the saved preset `name`, or on a new preset starting from `preset` @@ -151,258 +155,273 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result (s("preset").unwrap_or(DEFAULT_PRESET).to_string(), app.session.new_print_preset_name(), String::new()), }; let set = app.session.print_preset_settings(&base).ok_or_else(|| format!("no print preset named `{base}`"))?; - let mut fields = fields_of(&set)?; - fields.insert("name".into(), json!(name)); - fields.insert(EDITING.into(), json!(editing)); - fields.insert("__section".into(), json!(SECTIONS[0])); - fields.insert("__sheet".into(), json!(0)); - see_scale(&mut fields); - app.ui.dialog = Some(Dialog { kind: PRESET_KIND.into(), fields }); + let mut map = fields_of(&set)?; + map.insert("name".into(), json!(name)); + start(app, PrintMode::PresetEditor, map, base, editing) +} + +/// Host the dialog over the settings `map`. +fn start(app: &mut VectorcraftApp, mode: PrintMode, map: Map, preset: String, editing: String) -> Result { + let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; + let (printers, service) = destinations(app); + let mut state = State::default(); + state.settings.printer = printers + .iter() + .find(|p| p.default) + .or(printers.first().filter(|_| service)) + .map_or_else(|| PDF_FILE.to_string(), |p| p.name.clone()); + state.printers = printers; + let fields = form::fields_of(&KEYS, &map); + let header = if service && cfg!(windows) { + vec![ + Param::new("directPdf", tl!("Send PDF directly (bypass driver)"), ParamKind::bool(false)) + .tooltip(tl!("Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size.")), + ] + } else { + vec![] + }; + let taken: Vec = taken_names(app); + let named = editing.clone(); + let hosted = HostedPrint::new(state, fields, sections(&Lists::of(app))) + .mode(mode) + .layout(PrintLayout::Sections) + .header(header) + .json_form(|fields, out| out.extend(form::json_of(&KEYS, fields))) + .check_name(move |name: &str| refusal(&taken, &named, name).map_or(Ok(()), |m| Err(m.into()))) + .held_ok(); + let id = dialogs.with(|h| h.open(hosted)); + app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None }); Ok(Value::Null) } -/// Save Preset (the preset editor's OK): `print.presets.save`, then back to Edit → Print Presets on -/// it. A new preset may not take the name of another one. -fn confirm_preset(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mut d = d.clone(); - link_scale(&mut d); - let d = &d; - let (name, editing) = (d.str("name"), d.str(EDITING)); - let p = if editing.is_empty() { - if app.session.print_preset_settings(&name).is_some() { - return Err(format!("a preset named `{}` exists", name.trim())); +/// The settings as dialog fields. +fn fields_of(set: &PrintSettings) -> Result, String> { + match serde_json::to_value(set).map_err(|e| e.to_string())? { + Value::Object(fields) => Ok(fields), + _ => Err("print settings are not an object".into()), + } +} + +/// The Printer list: the system's printers, the system's default printer by itself when the service names none, +/// and PDF File last; and whether there is a print service. +fn destinations(app: &mut VectorcraftApp) -> (Vec, bool) { + let service = app.services.print.is_some(); + let mut list: Vec = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default(); + if service && list.is_empty() { + list.push(Printer::new("").label(tl!(DEFAULT_PRINTER))); + } + list.push(Printer::new(PDF_FILE).label(tl!(PDF_FILE))); + (list, service) +} + +/// The names a new preset may not take: [Default] and the saved presets. +fn taken_names(app: &VectorcraftApp) -> Vec { + std::iter::once(DEFAULT_PRESET.to_string()).chain(app.session.prefs.print_presets.iter().map(|p| p.name.clone())).collect() +} + +/// Why the preset editor may not save under `name` (a new preset, `editing` empty, may not take a taken name). +fn refusal(taken: &[String], editing: &str, name: &str) -> Option { + let name = name.trim(); + (editing.is_empty() && taken.iter().any(|t| t.eq_ignore_ascii_case(name))).then(|| format!("a preset named `{name}` exists")) +} + +/// The print settings the fields stand for (`print.setup`'s `settings`). +pub(super) fn settings(fields: &DialogFields) -> Value { + let mut p = form::json_of(&KEYS, fields); + for k in NOT_SETTINGS { + p.remove(k); + } + Value::Object(p) +} + +/// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was +/// dragged to, the presets and OK. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(mut open) = app.print_dialog.open.take() else { return }; + let Some(dialogs) = app.dialogs() else { + app.print_dialog.open = Some(open); + return; + }; + if serve(app, &dialogs, &mut open) { + app.print_dialog.open = Some(open); + } +} + +/// Run `f` on the open dialog. +fn on(dialogs: &craft_ui::dialogs::WindowDialogs, f: impl FnOnce(&mut HostedPrint) -> R) -> Option { + dialogs.with(|h| h.get_mut::().map(f)) +} + +/// One pass of the pump over the open dialog; false once it has closed. +fn serve(app: &mut VectorcraftApp, dialogs: &craft_ui::dialogs::WindowDialogs, open: &mut Open) -> bool { + let Some(mut d) = on(dialogs, |p| Drained { + refresh: p.take_refresh(), + setup: p.take_setup(), + moves: p.take_moves(), + events: p.take_preset_events(), + ok: p.take_ok(), + settings: settings(p.fields_mut()), + sheet: p.sheet_index(), + }) else { + // Closed: its answer was acted on when the OK was held. + let _ = dialogs.with(|h| h.take_by_id::(open.id)); + return false; + }; + if d.refresh { + let (list, _) = destinations(app); + let (tx, rx) = mpsc::channel(); + // The receiver is held by the dialog below, so the send cannot fail. + let _ = tx.send(list); + on(dialogs, |p| p.listen(rx)); + } + if let Some(printer) = d.setup + && let Err(e) = app.run("print.printerSetup", json!({ "printer": printer })) + { + app.status(e); + } + for event in std::mem::take(&mut d.events) { + apply_preset_event(app, dialogs, open, &mut d.settings, event); + } + let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision)); + let stamp = (d.settings.to_string(), doc); + let changed = open.preview.as_ref().is_none_or(|(s, _)| *s != stamp); + if changed { + let r = app.session.execute("print.preview", &json!({ "settings": d.settings })).map_err(|e| e.to_string()); + open.preview = Some((stamp, Arc::new(r))); + } + let Some(pv) = open.preview.as_ref().map(|(_, p)| p.clone()) else { return true }; + let pv: &Result = &pv; + let tiling = serde_json::from_value::(d.settings["scaling"].clone()).is_ok_and(PrintScaling::tiles); + if let (Ok(v), false) = (pv, tiling) + && let Some(sheet) = v["sheets"].as_array().and_then(|s| s.get(d.sheet.min(s.len().saturating_sub(1)))) + { + for delta in drags(std::mem::take(&mut d.moves)) { + on(dialogs, |p| move_placement(p.fields_mut(), sheet, delta)); } - json!({ "name": name, "preset": DEFAULT_PRESET, "settings": settings(d) }) + } + let has_doc = app.session.active().is_some(); + let sheet = pv.as_ref().ok().and_then(|v| print_sheet(app, open, v, d.sheet, &d.settings)); + let message = match pv { + _ if sheet.is_some() => None, + _ if !has_doc => Some(tl!("Open a document to preview its pages")), + Ok(_) => Some(tl!("Nothing to print")), + Err(_) => Some(tl!("Can't print these settings: see the Summary")), + }; + on(dialogs, |p| { + p.set_sheet(sheet); + p.set_message(message.map(Into::into)); + }); + if changed { + let inks = pv.as_ref().ok().and_then(|v| v.get("documentInks")).cloned().unwrap_or(Value::Null); + let [pages, options, warnings] = summary_texts(pv, &d.settings, has_doc); + on(dialogs, |p| { + p.set_field("__summary.pages", pages.into()); + p.set_field("__summary.options", options.into()); + p.set_field("__summary.warnings", warnings.into()); + p.set_field("__inks", FieldValue::Json(inks)); + }); + } + if open.mode == PrintMode::Print { + let same = serde_json::from_value::(d.settings.clone()).ok().is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s)); + let held = same.then(|| open.preset.clone()); + let rows: Vec> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0)) + .chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0))) + .collect(); + on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()])); + } + if let Some(answer) = d.ok { + let result = accept(app, open, &answer); + on(dialogs, |p| p.answer_ok(result.map_err(Into::into))); + } + true +} + +/// A preset the Print Preset row picked or named. +fn apply_preset_event(app: &mut VectorcraftApp, dialogs: &craft_ui::dialogs::WindowDialogs, open: &mut Open, settings: &mut Value, event: NamedPresetEvent) { + match event { + NamedPresetEvent::Apply(key) => { + let loaded = app + .session + .print_preset_settings(&key) + .ok_or_else(|| format!("no print preset named `{key}`")) + .and_then(|set| fields_of(&set)); + match loaded { + Ok(map) => { + let new = form::fields_of(&KEYS, &map); + if let Some(s) = on(dialogs, |p| { + for (k, v) in new.iter() { + p.fields_mut().set(k.to_string(), v.clone()); + } + settings_of(p) + }) { + *settings = s; + } + open.preset = key; + } + Err(e) => app.status(e), + } + } + NamedPresetEvent::Create { name, .. } => match app.run("print.presets.save", json!({ "name": name, "preset": DEFAULT_PRESET, "settings": settings })) { + Ok(r) => open.preset = r["name"].as_str().unwrap_or(&name).to_string(), + Err(e) => app.status(e), + }, + // Rename and Delete are the Print Presets dialog's. + _ => {} + } +} + +fn settings_of(p: &mut HostedPrint) -> Value { + settings(p.fields_mut()) +} + +/// The committed moves of the preview's art, each as the paper points it moved by; a click that moved nothing is none. +fn drags(moves: EditEvents) -> Vec<(f64, f64)> { + moves + .into_iter() + // PLAN: assumed `EditEvents: IntoIterator`; a gesture folded into one `Set` is not matched here. + .filter_map(|e| match e { + EditEvent::Commit { before: Mixed::Same(from), after, .. } => Some((f64::from(after.x - from.x), f64::from(after.y - from.y))), + _ => None, + }) + .filter(|d| *d != (0.0, 0.0)) + .collect() +} + +/// Print, or Done: keep the settings with the document (one undo step when they changed), then print them; settings +/// that can't print are refused, and the dialog stays open. The preset editor saves the preset instead. +fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer) -> Result<(), String> { + let settings = settings(&answer.fields); + if open.mode == PrintMode::PresetEditor { + return save_preset(app, open, &answer.fields, settings); + } + // Laid out first, so a bad range or overlap is refused before anything is kept. + app.session.execute("print.preview", &json!({ "settings": settings })).map_err(|e| e.to_string())?; + app.run("print.setup", json!({ "settings": settings }))?; + match answer.finish { + PrintFinish::Done => Ok(()), + PrintFinish::Print => { + let to_file = answer.settings.printer == PDF_FILE; + let printer = if to_file { "" } else { answer.settings.printer.as_str() }; + let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false); + crate::print::run(app, &json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf })).map(|_| ()) + } + } +} + +/// Save Preset (the preset editor's OK): `print.presets.save`, then back to Edit → Print Presets on it. +fn save_preset(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields, settings: Value) -> Result<(), String> { + let name = fields.text("name").unwrap_or_default().to_string(); + if let Some(why) = refusal(&taken_names(app), &open.editing, &name) { + return Err(why); + } + let p = if open.editing.is_empty() { + json!({ "name": name, "preset": DEFAULT_PRESET, "settings": settings }) } else { - json!({ "name": editing, "newName": name, "settings": settings(d) }) + json!({ "name": open.editing, "newName": name, "settings": settings }) }; let r = app.run("print.presets.save", p)?; super::print_presets::open(app, r["name"].as_str()); - Ok(r) -} - -/// The print settings the dialog stands for (`print.setup`'s `settings`). -pub(super) fn settings(d: &Dialog) -> Value { - let mut p = form::params(d); - if let Some(o) = p.as_object_mut() { - for k in NOT_SETTINGS { - o.remove(k); - } - } - p -} - -/// Print, or Done (`discard`): keep the settings with the document (one undo step when they -/// changed), then print them; settings that can't print keep the dialog open, unchanged. While -/// Save Preset… asks for a name, it saves the preset instead. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mut d = d.clone(); - // Done's flag holds for this press only: the dialog may stay open. - let done = d.fields.remove("discard").is_some_and(|v| v == true); - let synced = sync_preset(app, &mut d); - link_scale(&mut d); - app.ui.dialog = Some(d.clone()); - synced?; - // While Save Preset… asks for a name, OK (and Enter) saves the preset instead. - if d.fields.contains_key(SAVE_AS) { - let r = save_preset(app, &mut d); - app.ui.dialog = Some(d); - return r; - } - let settings = settings(&d); - let p = json!({ "settings": settings }); - // Laid out first, so a bad range or overlap is refused before anything is kept. - app.session.execute("print.preview", &p).map_err(|e| e.to_string())?; - app.run("print.setup", p)?; - if done { - app.ui.dialog = None; - return Ok(json!({ "settings": settings })); - } - let direct_pdf = app.ui.print_direct_pdf; - let r = crate::print::run( - app, - &json!({ - "settings": settings, - "printer": d.str("printer"), - "toFile": d.bool("toFile"), - "directPdf": direct_pdf, - }), - )?; - app.ui.dialog = None; - Ok(r) -} - -// ---------- the dialog ---------- - -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - if let Err(e) = sync_preset(app, d) { - app.status(e); - } - link_scale(d); - if d.kind == PRESET_KIND { - row_with(ui, tl!("Preset name:"), TOP_LABEL_WIDTH, |ui| { - form::text_edit(ui, d, "name", 288.0); - }); - } else { - preset_rows(app, ui, d); - printer_row(app, ui, d); - } - ui.add_space(10.0); - let section = current_section(d, &SECTIONS); - let preview = preview_of(app, ui.ctx(), &settings(d)); - ui.horizontal_top(|ui| { - super::save_pdf::section_frame(ui, |ui| { - super::save_pdf::section_list(ui, d, &SECTIONS, section); - ui.add_space(10.0); - page_preview(app, ui, d, &preview); - }); - ui.add_space(14.0); - ui.vertical(|ui| { - ui.set_width(500.0); - ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - let list_h = super::modal::list_height(ui, 360.0); - egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { - "Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d), - "Output" => output(ui, d, &preview), - "Graphics" => graphics(ui, d), - "Color Management" => color(ui, d), - "Advanced" => advanced(app, ui, d), - "Summary" => summary(ui, d, &preview, app.session.active().is_some()), - _ => general(app, ui, d), - }); - }); - }); - false -} - -/// The Print Preset row ([Default], the saved presets; [Custom] once the settings differ from the -/// preset's) with Save Preset…, and while Save Preset… asks for a name, the row taking it. -fn preset_rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - const CUSTOM: &str = "[Custom]"; - let name = d.str("preset"); - let current = serde_json::from_value::(settings(d)).ok(); - let same = current.is_some() && current == app.session.print_preset_settings(&name); - let names: Vec<&str> = std::iter::once(DEFAULT_PRESET).chain(app.session.prefs.print_presets.iter().map(|p| p.name.as_str())).collect(); - let mut picked = None; - let asking = d.fields.contains_key(SAVE_AS); - let mut ask = false; - row_with(ui, tl!("Print Preset:"), TOP_LABEL_WIDTH, |ui| { - // [Default] is ours (translated); the saved presets are names. - let current = if same { name.as_str() } else { tl!(CUSTOM) }; - picked = super::mixed_dropdown(ui, "print-preset", current, &names, 300.0, |k| k == 0).and_then(|i| names.get(i)).map(|n| n.to_string()); - let save = ui.add_enabled_ui(!asking, |ui| widgets::flat_button(ui, tl!("Save Preset…"), 96.0)).inner; - ask = save.on_hover_text(tl!("Save these settings as a print preset")).clicked(); - }); - if let Some(n) = picked { - // Picking the preset shown again brings its settings back. - d.fields.insert(LOADED.into(), json!("")); - d.fields.insert("preset".into(), json!(n)); - if let Err(e) = sync_preset(app, d) { - app.status(e); - } - } - if ask { - d.fields.insert(SAVE_AS.into(), json!(app.session.new_print_preset_name())); - } - if d.fields.contains_key(SAVE_AS) { - row_with(ui, tl!("Save as preset:"), TOP_LABEL_WIDTH, |ui| { - form::text_edit(ui, d, SAVE_AS, 200.0); - if widgets::flat_button(ui, tl!("Save"), 52.0).clicked() - && let Err(e) = save_preset(app, d) - { - app.status(e); - } - if widgets::flat_button(ui, tl!("Cancel"), 60.0).clicked() { - d.fields.remove(SAVE_AS); - } - }); - } -} - -/// What the Printer list offers. -enum Destination { - Printer(String), - /// The system's default printer (the web: the browser's print dialog). - Default, - File, -} - -/// The Printer row: the system's printers (or its default one), PDF File; Setup…. -fn printer_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - let printers = d.fields.get("__printers"); - let names: Vec = printers - .and_then(|p| p["printers"].as_array()) - .map(|a| a.iter().filter_map(|p| p["name"].as_str().map(str::to_string)).collect()) - .unwrap_or_default(); - let service = printers.and_then(|p| p["service"].as_bool()).unwrap_or(false); - let setup = printers.and_then(|p| p["setup"].as_bool()).unwrap_or(false); - let mut entries: Vec = names.iter().cloned().map(Destination::Printer).collect(); - if service && names.is_empty() { - entries.push(Destination::Default); - } - entries.push(Destination::File); - // The system's printers by their names; the default printer and PDF File are ours. - let options: Vec<&str> = entries - .iter() - .map(|e| match e { - Destination::Printer(name) => name.as_str(), - Destination::Default => tl!(DEFAULT_PRINTER), - Destination::File => tl!(PDF_FILE), - }) - .collect(); - let printer = d.str("printer"); - let current = if d.bool("toFile") { - tl!(PDF_FILE) - } else if printer.is_empty() { - tl!(DEFAULT_PRINTER) - } else { - printer.as_str() - }; - row_with(ui, tl!("Printer:"), TOP_LABEL_WIDTH, |ui| { - match widgets::dropdown_names(ui, "print-printer", current, &options, 300.0).and_then(|i| entries.get(i)) { - Some(Destination::Printer(name)) => { - d.fields.insert("printer".into(), json!(name)); - d.fields.insert("toFile".into(), json!(false)); - } - Some(Destination::Default) => { - d.fields.insert("printer".into(), json!("")); - d.fields.insert("toFile".into(), json!(false)); - } - Some(Destination::File) => { - d.fields.insert("toFile".into(), json!(true)); - } - None => {} - } - let to_file = d.bool("toFile"); - let tip = if setup { tl!("The system's settings of this printer") } else { tl!("No printer settings to open here") }; - if ui.add_enabled_ui(setup && !to_file, |ui| widgets::flat_button(ui, tl!("Setup…"), 72.0)).inner.on_hover_text(tip).clicked() - && let Err(e) = app.run("print.printerSetup", json!({ "printer": d.str("printer") })) - { - app.status(e); - } - }); - if service && cfg!(windows) { - let to_file = d.bool("toFile"); - ui.add_enabled(!to_file, egui::Checkbox::new(&mut app.ui.print_direct_pdf, "Send PDF directly (bypass driver)")); - note(ui, "Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size."); - } -} - -/// `print.preview` of `settings` (an error when they can't print), cached until they or the -/// document change. -fn preview_of(app: &mut VectorcraftApp, ctx: &egui::Context, settings: &Value) -> Arc> { - let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision)); - let stamp = egui::Id::unique((settings.to_string(), doc)); - let key = egui::Id::unique("print-preview"); - if let Some((s, v)) = ctx.data(|m| m.get_temp::<(egui::Id, Arc>)>(key)) - && s == stamp - { - return v; - } - let v = Arc::new(app.session.execute("print.preview", &json!({ "settings": settings })).map_err(|e| e.to_string())); - ctx.data_mut(|m| m.insert_temp(key, (stamp, v.clone()))); - v + Ok(()) } /// A `[x0, y0, x1, y1]` array as a rectangle. @@ -411,114 +430,29 @@ fn rect_of(v: &Value) -> Option { Some(DRect::new(n(0)?, n(1)?, n(2)?, n(3)?)) } -/// The page `__sheet` shows (clamped to the pages there are) and how many there are. -fn current_sheet<'a>(d: &Dialog, pv: &'a Value) -> Option<(usize, usize, &'a Value)> { - let sheets = pv["sheets"].as_array()?; - let i = (d.f64("__sheet", 0.0).max(0.0) as usize).min(sheets.len().checked_sub(1)?); - Some((i, sheets.len(), sheets.get(i)?)) +fn egui_rect(r: &DRect) -> egui::Rect { + egui::Rect::from_min_max(egui::pos2(r.x0 as f32, r.y0 as f32), egui::pos2(r.x1 as f32, r.y1 as f32)) } -/// The preview: the page with its imageable area (dashed) and the art as it prints; ◀ ▶ step -/// through the pages; dragging the art moves the placement (not when tiling). -fn page_preview(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, pv: &Result) { - let t = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(PREVIEW, egui::Sense::drag()); - ui.painter().rect_filled(rect, 3.0, t.pasteboard); - let sheet = pv.as_ref().ok().and_then(|v| current_sheet(d, v)); - let Some((index, count, sheet)) = sheet else { - let text = match pv { - _ if app.session.active().is_none() => tl!("Open a document to preview its pages"), - Ok(_) => tl!("Nothing to print"), - Err(_) => tl!("Can't print these settings: see the Summary"), - }; - let font = egui::FontId::proportional(11.0); - let galley = ui.painter().layout(text.into(), font, t.text_dim, rect.width() - 16.0); - ui.painter().galley(rect.center() - galley.size() / 2.0, galley, t.text_dim); - return; - }; - let size = egui::vec2(sheet["width"].as_f64().unwrap_or(0.0) as f32, sheet["height"].as_f64().unwrap_or(0.0) as f32); - let fit = ((rect.width() - 16.0) / size.x).min((rect.height() - 16.0) / size.y); - if !(fit.is_finite() && fit > 0.0) { - return; +/// The sheet the preview shows: sheet `index` (clamped to the pages there are) of the `print.preview` reply `pv`. +fn print_sheet(app: &mut VectorcraftApp, open: &mut Open, pv: &Value, index: usize, settings: &Value) -> Option { + let sheets = pv["sheets"].as_array()?; + let sheet = sheets.get(index.min(sheets.len().checked_sub(1)?))?; + let paper = egui::vec2(sheet["width"].as_f64().unwrap_or(0.0) as f32, sheet["height"].as_f64().unwrap_or(0.0) as f32); + if !(paper.x.is_finite() && paper.y.is_finite() && paper.x > 0.0 && paper.y > 0.0) { + return None; } - let page = egui::Rect::from_center_size(rect.center(), size * fit); - let to_screen = |x: f64, y: f64| page.min + egui::vec2(x as f32, y as f32) * fit; - let painter = ui.painter(); - painter.rect_filled(page.translate(egui::vec2(2.0, 2.0)), 0.0, egui::Color32::from_black_alpha(60)); - painter.rect_filled(page, 0.0, egui::Color32::WHITE); - // Dragging moves the art (and its trim box) on the paper; the placement changes on release. - let tiling = choice::(d, "scaling").is_some_and(PrintScaling::tiles); - let drag_id = egui::Id::unique("print-preview-drag"); - let mut offset = ui.ctx().data(|m| m.get_temp::(drag_id)).unwrap_or_default(); - if !tiling && resp.dragged() { - offset += resp.drag_delta(); - ui.ctx().data_mut(|m| m.insert_temp(drag_id, offset)); - } - let coeffs: Vec = sheet["transform"].as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); - let clip = ui.painter().with_clip_rect(page); - // With copies per sheet, `copies` holds each copy's artboard on the page, and `moves` holds - // each copy's move on screen from the first. - let copies: Vec = sheet["copies"].as_array().map(|a| a.iter().filter_map(rect_of).collect()).unwrap_or_default(); - let moves: Vec = match copies.first() { - Some(first) => copies.iter().map(|r| egui::vec2((r.x0 - first.x0) as f32, (r.y0 - first.y0) as f32) * fit).collect(), - None => vec![egui::Vec2::ZERO], - }; - if let ([a, b, c, dd, e, f], Some(area)) = (coeffs.as_slice(), rect_of(&sheet["area"])) { - let px = (f64::from(page.width().max(page.height()) * ui.ctx().pixels_per_point())).min(1024.0); - let layers = choice::(d, "printLayers").unwrap_or(PrintLayers::VisiblePrintable); - if let Some(tex) = art_texture(app, ui.ctx(), layers, area, px) { - let at = |x: f64, y: f64| to_screen(a * x + c * y + e, b * x + dd * y + f) + offset; - let mut mesh = egui::Mesh::with_texture(tex.id()); - for m in &moves { - let first = mesh.vertices.len() as u32; - for (p, uv) in [ - ((area.x0, area.y0), (0.0, 0.0)), - ((area.x1, area.y0), (1.0, 0.0)), - ((area.x1, area.y1), (1.0, 1.0)), - ((area.x0, area.y1), (0.0, 1.0)), - ] { - mesh.vertices.push(egui::epaint::Vertex { pos: at(p.0, p.1) + *m, uv: egui::pos2(uv.0, uv.1), color: egui::Color32::WHITE }); - } - mesh.add_triangle(first, first + 1, first + 2); - mesh.add_triangle(first, first + 2, first + 3); - } - clip.add(mesh); - } - } - if resp.drag_stopped() && offset != egui::Vec2::ZERO { - move_placement(d, sheet, (f64::from(offset.x / fit), f64::from(offset.y / fit))); - } - if !resp.dragged() { - ui.ctx().data_mut(|m| m.remove::(drag_id)); - } - // The imageable area inside the device's margin, and the artboard's edge. - let margin = get(d, "margin").as_f64().unwrap_or(0.0) as f32 * fit; - if margin > 0.5 { - let r = page.shrink(margin); - let stroke = egui::Stroke::new(1.0, t.text_dim); - let corners = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()]; - clip.extend(egui::Shape::dashed_line(&corners, stroke, 3.0, 2.0)); - } - // The preview strokes each copy's artboard edge, or the trim box without copies per sheet. - let trims = if copies.is_empty() { rect_of(&sheet["trim"]).into_iter().collect() } else { copies }; - for trim in trims { - let r = egui::Rect::from_min_max(to_screen(trim.x0, trim.y0), to_screen(trim.x1, trim.y1)).translate(offset); - clip.rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Middle); - } - let resp = if tiling { resp } else { resp.on_hover_cursor(egui::CursorIcon::Grab) }; - resp.on_hover_text(if tiling { tl!("The page as it prints") } else { tl!("Drag the art to move it on the paper") }); - // ◀ n of N ▶, then what the page is. - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - if widgets::icon_button_enabled(ui, "chevron-left", tl!("Previous page"), false, index > 0, 20.0).clicked() { - d.fields.insert("__sheet".into(), json!(index - 1)); - } - let text = crate::i18n::fmt(tl!("{page} of {count}"), &[("page", &(index + 1).to_string()), ("count", &count.to_string())]); - ui.add_sized([PREVIEW.x - 44.0, 20.0], egui::Label::new(egui::RichText::new(text).size(11.5).color(t.text))); - if widgets::icon_button_enabled(ui, "chevron-right", tl!("Next page"), false, index + 1 < count, 20.0).clicked() { - d.fields.insert("__sheet".into(), json!(index + 1)); - } - }); + let coeffs: Vec = sheet["transform"].as_array()?.iter().filter_map(Value::as_f64).collect(); + let [a, b, c, d, e, f] = <[f64; 6]>::try_from(coeffs).ok()?; + let area = rect_of(&sheet["area"])?; + let at = |x: f64, y: f64| egui::pos2((a * x + c * y + e) as f32, (b * x + d * y + f) as f32); + let image = egui::Rect::from_points(&[at(area.x0, area.y0), at(area.x1, area.y0), at(area.x1, area.y1), at(area.x0, area.y1)]); + let layers = serde_json::from_value::(settings["printLayers"].clone()).unwrap_or(PrintLayers::VisiblePrintable); + let texture = art_texture(app, open, layers, area)?; + // With copies per sheet, `copies` holds each copy's artboard on the page. + let copies: Vec = sheet["copies"].as_array().map(|a| a.iter().filter_map(rect_of).map(|r| egui_rect(&r)).collect()).unwrap_or_default(); + let count = copies.len().max(1); + let outlines = if copies.is_empty() { rect_of(&sheet["trim"]).map(|r| egui_rect(&r)).into_iter().collect() } else { copies }; let mut what = vec![]; match sheet["artboard"].as_u64() { Some(a) => what.push(crate::i18n::fmt(tl!("Artboard {number}"), &[("number", &(a + 1).to_string())])), @@ -537,15 +471,20 @@ fn page_preview(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, pv: [w, h] => format!("{}% × {}%", round2(*w), round2(*h)), _ => String::new(), }; - let paper = format!("{} × {}", unit.number(f64::from(size.x)), unit.format(f64::from(size.y))); - for line in [what.join(" · "), format!("{paper} · {scale}")] { - ui.label(egui::RichText::new(line).size(11.0).color(t.text_dim)); + let size = format!("{} × {}", unit.number(f64::from(paper.x)), unit.format(f64::from(paper.y))); + let readout = format!("{}\n{size} · {scale}", what.join(" · ")); + let mut out = PrintSheet::new(paper, image, egui::load::SizedTexture::new(texture.id(), texture.size_vec2()), readout.into()).count(count).outlines(outlines); + // The imageable area inside the device's margin. + let margin = settings["margin"].as_f64().unwrap_or(0.0) as f32; + if margin > 0.5 { + out = out.printable(egui::Rect::from_min_max(egui::pos2(margin, margin), egui::pos2(paper.x - margin, paper.y - margin))); } + Some(out) } /// Move the placement so the art of `sheet` moves `(dx, dy)` points on the page: the move turned /// back onto the paper (the page may be turned or mirrored), at the art's scale. -pub(super) fn move_placement(d: &mut Dialog, sheet: &Value, (dx, dy): (f64, f64)) { +pub(super) fn move_placement(fields: &mut DialogFields, sheet: &Value, (dx, dy): (f64, f64)) { let n = |k: &str, i: usize| sheet[k].get(i).and_then(Value::as_f64); let (Some(a), Some(b), Some(c), Some(e)) = (n("transform", 0), n("transform", 1), n("transform", 2), n("transform", 3)) else { return }; let (Some(sx), Some(sy)) = (n("scale", 0), n("scale", 1)) else { return }; @@ -556,339 +495,300 @@ pub(super) fn move_placement(d: &mut Dialog, sheet: &Value, (dx, dy): (f64, f64) // The transform's linear part is the page's turn times the scale, and the turn's inverse is // its transpose: the columns over the scale. let (px, py) = ((a * dx + b * dy) / sx, (c * dx + e * dy) / sy); - if get(d, PLACED).as_bool() == Some(true) { + let num = |fields: &DialogFields, k: &str| fields.number(k).unwrap_or(0.0); + if fields.bool(PLACED) == Some(true) { // Pages the Print Tiling tool placed: their corner moves the other way over the art. - let x = get(d, "tileOrigin.x").as_f64().unwrap_or(0.0) - px / sx; - let y = get(d, "tileOrigin.y").as_f64().unwrap_or(0.0) - py / sy; - set(d, "tileOrigin.x", json!(round2(x))); - set(d, "tileOrigin.y", json!(round2(y))); + let x = num(fields, "tileOrigin.x") - px / sx; + let y = num(fields, "tileOrigin.y") - py / sy; + fields.set("tileOrigin.x", round2(x)); + fields.set("tileOrigin.y", round2(y)); return; } - let x = get(d, "placement.x").as_f64().unwrap_or(0.0) + px; - let y = get(d, "placement.y").as_f64().unwrap_or(0.0) + py; - set(d, "placement.x", json!(round2(x))); - set(d, "placement.y", json!(round2(y))); + let x = num(fields, "placement.x") + px; + let y = num(fields, "placement.y") + py; + fields.set("placement.x", round2(x)); + fields.set("placement.y", round2(y)); } fn round2(v: f64) -> f64 { (v * 100.0).round() / 100.0 } -/// The art of `area` as it prints (only the layers that print), `px` pixels on its longest side; -/// cached until the document, the layers or the size change. -fn art_texture(app: &mut VectorcraftApp, ctx: &egui::Context, layers: PrintLayers, area: DRect, px: f64) -> Option { +/// The art of `area` as it prints (only the layers that print); kept until the document, the layers or the area change. +fn art_texture(app: &mut VectorcraftApp, open: &mut Open, layers: PrintLayers, area: DRect) -> Option { let st = app.session.active()?; - let bits = [area.x0, area.y0, area.x1, area.y1].map(f64::to_bits); - let stamp = egui::Id::unique((st.uid, st.revision, layers, bits, px.round() as u32)); - let key = egui::Id::unique("print-preview-art"); - if let Some((s, tex)) = ctx.data(|m| m.get_temp::<(egui::Id, egui::TextureHandle)>(key)) - && s == stamp + let key: ArtKey = (st.uid, st.revision, layers, [area.x0, area.y0, area.x1, area.y1].map(f64::to_bits), ART_PX as u32); + if let Some((k, tex)) = &open.art + && *k == key { - return Some(tex); + return Some(tex.clone()); } // The artboards' background colors print behind the art. let mut doc = st.doc.with_artboard_fills(0..st.doc.artboards.len()).unwrap_or_else(|| (*st.doc).clone()); vectorcraft_pdf::keep_layers(&mut doc.layers, layers); - let tex = widgets::region_texture(ctx, &mut app.canvas.renderer, "print-preview-art", &doc, area, px); - ctx.data_mut(|m| m.insert_temp(key, (stamp, tex.clone()))); + // PLAN: assumed `widgets::region_image(renderer, doc, area, px) -> impl Into` (widgets-w13). + let image = widgets::region_image(&mut app.canvas.renderer, &doc, area, ART_PX); + let ctx = app.ui_ctx.clone()?; + let tex = ctx.load_texture("print-preview-art", egui::ColorImage::from(image), egui::TextureOptions::LINEAR); + open.art = Some((key, tex.clone())); Some(tex) } // ---------- sections ---------- -/// A whole number at `path` within `range`. -fn whole(ui: &mut egui::Ui, d: &mut Dialog, path: &str, range: std::ops::RangeInclusive, enabled: bool) { - let v = get(d, path).as_f64().unwrap_or(*range.start()); - ui.add_enabled_ui(enabled, |ui| { - if let Some(x) = widgets::range_field(ui, path, v, range, "", 0, 56.0) { - set(d, path, json!(x as u64)); - } - }); +/// A select over the choices of `T`. +fn pick(key: &str, label: &str) -> Param { + Param::new(key, label, ParamKind::choice(T::IDS.iter().zip(T::LABELS).map(|(i, l)| (i.to_string(), tl!(*l).into())).collect(), None)) } -/// A Scale percentage at `path`, 1–1000 %: the value typed, once one was. -fn percent(ui: &mut egui::Ui, d: &mut Dialog, path: &str, enabled: bool) -> Option { - let v = get(d, path).as_f64().unwrap_or(100.0); - let typed = ui.add_enabled_ui(enabled, |ui| widgets::range_field(ui, path, v, 1.0..=1000.0, "%", 3, 64.0)).inner; - if let Some(x) = typed { - set(d, path, json!(x)); - } - typed +fn flag(key: &str, label: &str) -> Param { + Param::new(key, label, ParamKind::bool(false)) } -/// The link after Scale W and H: on, either field sets both, and turning it on sets H to W. With -/// the keyboard on it, Space or Enter toggles it unless it is dimmed. -fn scale_link(ui: &mut egui::Ui, d: &mut Dialog, linked: bool) { - const NAME: &str = "Constrain Width and Height Proportions"; - let size = crate::panels::transform::CONSTRAIN_LINK_SIZE; - let (_, at) = ui.allocate_exact_size(egui::Vec2::splat(size), egui::Sense::click()); - let enabled = ui.is_enabled(); - let keyed = enabled - && at.has_focus() - && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Space) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); - let resp = widgets::paint_icon_button(ui, at, if linked { "link" } else { "link-2-off" }, NAME, linked); - // Off is a state too: screen readers hear the link as off, not as a plain button. - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, linked, tl!(NAME))); - if resp.clicked() || keyed { - set(d, SCALE_LINKED, json!(!linked)); - link_scale(d); - } +fn note(key: &str, text: &str) -> Param { + Param::read_only_text(key, "", text).full_width() } -/// While the Scale link is on, keep H equal to W: the field that changed since the last call (a -/// field typed in, or `ui.dialog.set`) gives its value to the other, and when neither changed H -/// takes W, as turning the link on does. As `print.setup` reads a `scale`: one set with W and H -/// apart and without a `linked` key turns the link off, one that leaves out W, H or `linked` (or -/// gives `null`) keeps it as it was, and one that changes both W and H apart while linked is left -/// as it is (and stays changed on later calls), for confirming to refuse. -fn link_scale(d: &mut Dialog) { - let seen = d.fields.get(SCALE_SEEN).cloned().unwrap_or_default(); - if let Some(Value::Object(s)) = d.fields.get_mut("scale") { - let num = |s: &serde_json::Map, k: &str| s.get(k).and_then(Value::as_f64); - let stated = |s: &serde_json::Map, k: &str| s.get(k).is_some_and(|v| !v.is_null()); - if s.get("linked").is_none() && num(s, "width").zip(num(s, "height")).is_some_and(|(w, h)| w != h) { - s.insert("linked".into(), json!(false)); - } - for (i, k) in ["width", "height", "linked"].into_iter().enumerate() { - if !stated(s, k) && !seen[i].is_null() { - s.insert(k.into(), seen[i].clone()); +/// A length in points, shown in the document's unit. +fn length(key: &str, label: &str) -> Param { + // PLAN: the shown unit is the document's general unit; the framework's env supplies it once `Param::length` is written (wg.W21). + Param::number(key, label, 0.0, 1.0, 2).length(LengthUnits::new(UnitKind::Points, UnitKind::Points, 72.0)) +} + +/// The ids of the scalings that tile (`tiles`), or that don't. +fn scaling_ids(tiles: bool) -> Vec<&'static str> { + // PLAN: assumed `PrintScaling::ALL`. + PrintScaling::ALL.iter().filter(|s| s.tiles() == tiles).map(|s| s.id()).collect() +} + +/// A summary line that the pump fills (`key` is a `__` companion of the fields). +fn shown(key: &'static str) -> Param { + Param::custom(key, "", move |ui, fields, _| ui.label(fields.text(key).unwrap_or_default())) +} + +/// The sections of the dialog, with the rows of each. +fn sections(lists: &Lists) -> Vec { + let tiles = scaling_ids(true); + let flat = scaling_ids(false); + let separations = OutputMode::Separations.id(); + let composite: Vec<&str> = OutputMode::IDS.iter().copied().filter(|i| *i != separations).collect(); + let scaling_on: Vec<&str> = tiles.iter().copied().chain([PrintScaling::Custom.id()]).collect(); + let counts: Vec = (2..=i64::from(vectorcraft_pdf::MAX_COPIES)).collect(); + let artboards = vec![ + (PrintArtboards::All.id().to_string(), tl!("All").into()), + (PrintArtboards::Range.id().to_string(), tl!("Range:").into()), + (PrintArtboards::Ignore.id().to_string(), tl!("Ignore Artboards (all the art as one page)").into()), + ]; + let general = vec![ + Param::new("copies", tl!("Copies:"), ParamKind::int(Some(1), Some(i64::from(vectorcraft_pdf::MAX_COPIES)), 1)), + flag("collate", tl!("Collate")).enabled_when_in("copies", counts), + flag("reverse", tl!("Reverse Order")), + Param::new("artboards", tl!("Artboards"), ParamKind::radio(artboards, None)), + Param::new("range", tl!("Range:"), ParamKind::text("")).hint("1-3, 5").enabled_when("artboards", PrintArtboards::Range.id()), + flag("skipBlank", tl!("Skip Blank Artboards")).enabled_when_in("artboards", [PrintArtboards::All.id(), PrintArtboards::Range.id()]), + Param::section(tl!("Media")), + pick::("media", tl!("Size:")), + length("width", tl!("Width:")).enabled_when("media", "custom"), + length("height", tl!("Height:")).enabled_when("media", "custom"), + Param::section(tl!("Orientation")), + flag("autoRotate", tl!("Auto-Rotate (turn the paper to each artboard)")), + pick::("orientation", tl!("Orientation:")).enabled_when("autoRotate", false), + flag("transverse", tl!("Transverse (the page a quarter turn on the paper)")), + Param::section(tl!("Options")), + pick::("printLayers", tl!("Print Layers:")), + Param::custom("placement.origin", tl!("Placement:"), |ui, fields, _| { + let at = fields.text("placement.origin").and_then(|id| Origin::ALL.iter().position(|o| o.id() == id)).unwrap_or(4); + let mut anchor = ANCHORS[at.min(ANCHORS.len() - 1)]; + // PLAN: assumed builder and show call of `ReferencePoint` (Bind from `&mut`). + let out = ReferencePoint::new(&mut anchor).look(ReferencePointLook::Squares).show(ui); + if let Some(o) = ANCHORS.iter().position(|a| *a == anchor).and_then(|i| Origin::ALL.get(i)) + && ANCHORS.get(at) != Some(&anchor) + { + fields.set("placement.origin", o.id().to_string()); } - } - } - let (w, h) = (get(d, "scale.width").clone(), get(d, "scale.height").clone()); - if get(d, SCALE_LINKED).as_bool() == Some(true) && w.as_f64() != h.as_f64() { - let (w_kept, h_kept) = (seen[0].as_f64() == w.as_f64(), seen[1].as_f64() == h.as_f64()); - if (w_kept && !h_kept) || w.as_f64().is_none() { - set(d, "scale.width", h); - } else if h_kept || seen.is_null() { - set(d, "scale.height", w); - } else { - return; - } - } - see_scale(&mut d.fields); -} - -/// Remember Scale W, H and the link as the fields hold them, for [`link_scale`]. -fn see_scale(fields: &mut serde_json::Map) { - let s = fields.get("scale").cloned().unwrap_or_default(); - fields.insert(SCALE_SEEN.into(), json!([s["width"], s["height"], s["linked"]])); -} - -fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - let unit = app.session.general_unit(); - row(ui, tl!("Copies:"), |ui| { - whole(ui, d, "copies", 1.0..=f64::from(vectorcraft_pdf::MAX_COPIES), true); - ui.add_space(12.0); - let copies = get(d, "copies").as_u64().unwrap_or(1); - flag(ui, d, "collate", tl!("Collate"), copies > 1); - flag(ui, d, "reverse", tl!("Reverse Order"), true); - }); - heading(ui, tl!("Artboards")); - let artboards = choice::(d, "artboards").unwrap_or(PrintArtboards::All); - ui.horizontal(|ui| { - for (a, label) in [(PrintArtboards::All, tl!("All")), (PrintArtboards::Range, tl!("Range:"))] { - if widgets::radio(ui, label, artboards == a, true) { - set(d, "artboards", json!(a.id())); - } - } - let mut range = get(d, "range").as_str().unwrap_or_default().to_string(); - let edit = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(140.0).hint_text("1-3, 5"); - if ui.add_enabled(artboards == PrintArtboards::Range, edit).changed() { - set(d, "range", json!(range)); - } - }); - if widgets::radio(ui, tl!("Ignore Artboards (all the art as one page)"), artboards == PrintArtboards::Ignore, true) { - set(d, "artboards", json!(PrintArtboards::Ignore.id())); - } - flag(ui, d, "skipBlank", tl!("Skip Blank Artboards"), artboards != PrintArtboards::Ignore); - heading(ui, tl!("Media")); - row(ui, tl!("Size:"), |ui| { - pick::(ui, d, "media", 160.0, |_| true); - }); - // A paper size shows its size; Custom takes one. - let media = choice::(d, "media").unwrap_or_default(); - row(ui, tl!("Width:"), |ui| match media.size() { - Some((w, h)) => { - ui.add_enabled_ui(false, |ui| widgets::num_field(ui, "print-media-w", Some(w), unit, 80.0)); - ui.label(tl!("Height:")); - ui.add_enabled_ui(false, |ui| widgets::num_field(ui, "print-media-h", Some(h), unit, 80.0)); - } - None => { - length(ui, d, "width", unit, true); - ui.label(tl!("Height:")); - length(ui, d, "height", unit, true); - } - }); - heading(ui, tl!("Orientation")); - flag(ui, d, "autoRotate", tl!("Auto-Rotate (turn the paper to each artboard)"), true); - let auto = get(d, "autoRotate").as_bool() == Some(true); - row(ui, tl!("Orientation:"), |ui| { - ui.add_enabled_ui(!auto, |ui| pick::(ui, d, "orientation", 160.0, |_| true)); - }); - flag(ui, d, "transverse", tl!("Transverse (the page a quarter turn on the paper)"), true); - heading(ui, tl!("Options")); - row(ui, tl!("Print Layers:"), |ui| { - pick::(ui, d, "printLayers", 220.0, |_| true); - }); - let scaling = choice::(d, "scaling").unwrap_or(PrintScaling::None); - let tiles = scaling.tiles(); - let placed = get(d, PLACED).as_bool() == Some(true); - row(ui, tl!("Placement:"), |ui| { - ui.add_enabled_ui(!tiles && !placed, |ui| { - let origin = choice::(d, "placement.origin").unwrap_or_default(); - let current = Origin::ALL.iter().position(|o| *o == origin).unwrap_or(4); - if let Some(o) = widgets::reference_point_named(ui, current, tl!("Placement:")).and_then(|i| Origin::ALL.get(i)) { - set(d, "placement.origin", json!(o.id())); - } - ui.label("X:"); - length(ui, d, "placement.x", unit, true); - ui.label("Y:"); - length(ui, d, "placement.y", unit, true); - }); - }); - if placed { - row(ui, "", |ui| { - note(ui, tl!("The Print Tiling tool placed the pages.")); - if widgets::flat_button(ui, tl!("Reset"), 56.0).on_hover_text(tl!("Place the pages with the placement again")).clicked() { - set(d, PLACED, json!(false)); - } - }); - } - row(ui, tl!("Scaling:"), |ui| { - pick::(ui, d, "scaling", 180.0, |_| true); - }); - row(ui, tl!("Scale:"), |ui| { - let on = scaling == PrintScaling::Custom || tiles; - let linked = get(d, SCALE_LINKED).as_bool() == Some(true); - ui.label(tl!("W:")); - let w = percent(ui, d, "scale.width", on); - if let Some(w) = w.filter(|_| linked) { - set(d, "scale.height", json!(w)); - } - ui.label(tl!("H:")); - let h = percent(ui, d, "scale.height", on); - if let Some(h) = h.filter(|_| linked) { - set(d, "scale.width", json!(h)); - } - // A typed W or H is what the next `ui.dialog.set` changes from. - if w.is_some() || h.is_some() { - see_scale(&mut d.fields); - } - ui.add_enabled_ui(on, |ui| scale_link(ui, d, linked)); - }); - row(ui, tl!("Overlap:"), |ui| length(ui, d, "overlap", unit, tiles)); - row(ui, tl!("Tile Range:"), |ui| text(ui, d, "tileRange", tiles)); - if tiles { - note(ui, tl!("Tiles are numbered across, then down; leave the range empty for every tile.")); - } - flag(ui, d, "copiesPerSheet", tl!("Copies per Sheet (as many as fit, in a grid)"), !tiles); - let per_sheet = get(d, "copiesPerSheet").as_bool() == Some(true); - row(ui, tl!("Gutter:"), |ui| length(ui, d, "gutter", unit, !tiles && per_sheet)); -} - -fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result) { - row(ui, tl!("Mode:"), |ui| { - pick::(ui, d, "output.mode", 160.0, |_| true); - }); - row(ui, tl!("Emulsion:"), |ui| { - pick::(ui, d, "output.emulsion", 160.0, |_| true); - }); - row(ui, tl!("Image:"), |ui| { - pick::(ui, d, "output.image", 160.0, |_| true); - }); - let separations = choice::(d, "output.mode") == Some(OutputMode::Separations); - flag(ui, d, "output.spotsToProcess", tl!("Convert All Spot Colors to Process"), separations); - flag(ui, d, "output.overprintBlack", tl!("Overprint Black"), separations); - heading(ui, tl!("Document Ink Options")); - // Every ink of the document, the spot inks printing as process (no plate) included. - let inks = pv.as_ref().ok().and_then(|v| v["documentInks"].as_array()).map(Vec::as_slice).unwrap_or_default(); - if !separations || inks.is_empty() { - note(ui, tl!("Separations list the document's inks here: one page per ink that prints.")); - return; - } - let all_spots = get(d, "output.spotsToProcess").as_bool() == Some(true); - let t = Tokens::get(ui.ctx()); - egui::Grid::new("print-inks").num_columns(4).spacing([12.0, 4.0]).show(ui, |ui| { - for h in [tl!("Print"), tl!("Ink"), tl!("Frequency"), tl!("Angle")] { - ui.label(egui::RichText::new(h).size(11.5).color(t.text_dim)); - } - ui.end_row(); - for ink in inks { - let name = ink["name"].as_str().unwrap_or_default(); - // A spot ink printing as process has no plate: its plate options wait, dimmed, for it - // to print as a spot ink again. - let process = ink["convertToProcess"] == true; - let on = ink["print"].as_bool().unwrap_or(true); - if widgets::check_box(ui, name, on, !process) { - set_ink(d, name, "print", json!(!on)); - } - ui.horizontal(|ui| { - if ink["spot"] == true { - if ink_kind_button(ui, name, process, !all_spots) { - set_ink(d, name, "convertToProcess", json!(!process)); - } - } else { - ui.add_space(INK_KIND); + out.response + }) + .enabled_when_in("scaling", flat.clone()), + length("placement.x", "X:").enabled_when_in("scaling", flat.clone()), + length("placement.y", "Y:").enabled_when_in("scaling", flat.clone()), + flag(PLACED, tl!("The Print Tiling tool placed the pages (uncheck to place them with the placement again)")).visible_when(PLACED, true), + length("tileOrigin.x", "X:").visible_when(PLACED, true), + length("tileOrigin.y", "Y:").visible_when(PLACED, true), + pick::("scaling", tl!("Scaling:")), + Param::custom("scale", tl!("Scale:"), |ui, fields, _| { + let mut parts = [fields.number("scale.width"), fields.number("scale.height")]; + let mut linked = fields.bool("scale.linked").unwrap_or(false); + // PLAN: assumed `LinkedFields::new(&mut parts, &mut linked)` and `.show(ui)`; the link's name is the framework's. + let out = LinkedFields::<2>::new(&mut parts, &mut linked).mode(LinkMode::Equal).ranges([1.0..=1000.0, 1.0..=1000.0]).show(ui); + for (key, part) in ["scale.width", "scale.height"].into_iter().zip(parts) { + if let Some(v) = part.filter(|v| fields.number(key) != Some(*v)) { + fields.set(key, v); } - let spot = if ink["spot"] == true { format!(" ({})", tl!("spot")) } else { String::new() }; - ui.label(egui::RichText::new(format!("{name}{spot}")).color(t.text)); - }); - for (k, suffix) in [("frequency", " lpi"), ("angle", "°")] { - let v = ink[k].as_f64().unwrap_or(0.0); - let heading = if k == "frequency" { tl!("Frequency") } else { tl!("Angle") }; - let field_name = format!("{heading} {name}"); - let typed = - ui.add_enabled_ui(!process, |ui| widgets::plain_field_named(ui, ("print-ink", name, k), Some(&field_name), v, suffix, 2, 72.0)); - if let Some(x) = typed.inner { - set_ink(d, name, k, json!(x)); + } + if fields.bool("scale.linked").unwrap_or(false) != linked { + fields.set("scale.linked", linked); + } + out.response + }) + // PLAN: assumed `Param::on_set(|fields, incoming: &Map|)` on custom rows (forms-w1, q336): a value set from outside. + .on_set(|fields: &mut DialogFields, incoming: &Map| { + let current: Map = ["width", "height", "linked"] + .into_iter() + .filter_map(|k| { + let key = format!("scale.{k}"); + let v = if k == "linked" { fields.bool(&key).map(Value::from) } else { fields.number(&key).map(Value::from) }; + v.map(|v| (k.to_string(), v)) + }) + .collect(); + for (k, v) in merge_scale(¤t, incoming) { + match v { + Value::Bool(b) => fields.set(format!("scale.{k}"), b), + Value::Number(n) => fields.set(format!("scale.{k}"), n.as_f64().unwrap_or(100.0)), + _ => {} } } + }) + .enabled_when_in("scaling", scaling_on), + length("overlap", tl!("Overlap:")).enabled_when_in("scaling", tiles.clone()), + Param::new("tileRange", tl!("Tile Range:"), ParamKind::text("")).enabled_when_in("scaling", tiles.clone()), + note("tilesNote", tl!("Tiles are numbered across, then down; leave the range empty for every tile.")).visible_when_in("scaling", tiles), + flag("copiesPerSheet", tl!("Copies per Sheet (as many as fit, in a grid)")).enabled_when_in("scaling", flat), + length("gutter", tl!("Gutter:")).enabled_when("copiesPerSheet", true), + ]; + let marks = marks_and_bleed(); + let output = vec![ + pick::("output.mode", tl!("Mode:")), + pick::("output.emulsion", tl!("Emulsion:")), + pick::("output.image", tl!("Image:")), + flag("output.spotsToProcess", tl!("Convert All Spot Colors to Process")).enabled_when("output.mode", separations), + flag("output.overprintBlack", tl!("Overprint Black")).enabled_when("output.mode", separations), + Param::section(tl!("Document Ink Options")), + Param::custom("output.inks", "", ink_table), + ]; + let graphics = vec![ + Param::section(tl!("Paths")), + flag("graphics.autoFlatness", tl!("Automatic flatness")), + Param::number("graphics.flatness", tl!("Flatness:"), 1.0, 0.1, 1) + .bounds(Some(0.2), Some(100.0)) + .tooltip(tl!("0.2 (quality) to 100 (speed)")) + .enabled_when("graphics.autoFlatness", false), + Param::section(tl!("Fonts")), + pick::("graphics.fonts", tl!("Download:")), + ]; + let profiles: Vec<(String, _)> = + std::iter::once((String::new(), tl!(SAME_AS_SOURCE).into())).chain(lists.profiles.iter().map(|p| (p.clone(), p.as_str().into()))).collect(); + let intents = Intent::ALL.iter().map(|i| (serde_json::to_value(i).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), tl!(i.label()).into())).collect(); + let color = vec![ + Param::new("color.profile", tl!("Printer profile:"), ParamKind::choice(profiles, None)), + note("profileNote", tl!("Composite colours are converted to it; separations separate with it when it is a CMYK profile.")), + Param::new("color.intent", tl!("Rendering intent:"), ParamKind::choice(intents, None)), + note("intentNote", tl!("How colours outside the press's gamut are separated.")), + flag("color.preserveNumbers", tl!("Preserve CMYK Numbers")), + note("preserveNote", tl!("CMYK colours print with their own values; off, they go through the colour settings too.")), + ]; + let flatteners: Vec<(String, _)> = + std::iter::once((String::new(), tl!(KEEP_TRANSPARENCY).into())).chain(lists.flatteners.iter().map(|p| (p.clone(), p.as_str().into()))).collect(); + let advanced = vec![ + Param::section(tl!("Printer")), + length("margin", tl!("Unprintable margin:")), + note("marginNote", tl!("The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed.")), + flag("advanced.printAsBitmap", tl!("Print as Bitmap")).enabled_when_in("output.mode", composite.clone()), + note("bitmapNote", tl!("Each page prints as one image, at the document's raster effects resolution.")), + Param::section(tl!("Overprint and Transparency Flattener Options")), + pick::("advanced.overprints", tl!("Overprints:")).enabled_when_in("output.mode", composite), + Param::new("advanced.flattenerPreset", tl!("Preset:"), ParamKind::choice(flatteners, None)), + note( + "flattenerNote", + tl!( + "Simulate prints overprints as Overprint Preview shows them; separations always keep them. A preset flattens transparency before printing (PostScript files always flatten it)." + ), + ), + ]; + let summary = vec![ + Param::section(tl!("Pages")), + shown("__summary.pages"), + Param::section(tl!("Options")), + shown("__summary.options"), + Param::section(tl!("Warnings")), + shown("__summary.warnings"), + ]; + [general, marks, output, graphics, color, advanced, summary].into_iter().zip(SECTIONS).map(|(params, title)| PrintSection::new(tl!(title), params)).collect() +} + +/// The Marks and Bleed rows: no link between the bleed sides. +fn marks_and_bleed() -> Vec { + // PLAN: the marks' option rows follow the Save PDF dialog's `marks_and_bleeds` (export-w17 deletes it): the kinds, the weights and the bleed. + let weights: Vec<(String, _)> = [0.125, 0.25, 0.5, 0.75, 1.0].iter().map(|w| (w.to_string(), format!("{w} pt").into())).collect(); + vec![ + Param::section(tl!("Marks")), + flag("marks.trim", tl!("Trim Marks")), + flag("marks.registration", tl!("Registration Marks")), + flag("marks.colorBars", tl!("Color Bars")), + flag("marks.pageInfo", tl!("Page Information")), + pick::("marks.kind", tl!("Printer's Marks Type:")), + Param::new("marks.weight", tl!("Trim Mark Weight:"), ParamKind::choice(weights, None)), + length("marks.offset", tl!("Offset:")), + Param::section(tl!("Bleeds")), + flag("bleed.useDocument", tl!("Use document bleed settings")), + length("bleed.top", tl!("Top:")).enabled_when("bleed.useDocument", false), + length("bleed.bottom", tl!("Bottom:")).enabled_when("bleed.useDocument", false), + length("bleed.left", tl!("Left:")).enabled_when("bleed.useDocument", false), + length("bleed.right", tl!("Right:")).enabled_when("bleed.useDocument", false), + ] +} + +/// The Document Ink table: every ink of the document (the pump writes them into `__inks` from the preview), the spot +/// inks printing as process included. Nothing but a note unless the output is separations and there are inks. +fn ink_table(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut craft_ui::form_dialogs::CustomContext) -> egui::Response { + let inks = match fields.get("__inks") { + Some(FieldValue::Json(v)) => v.as_array().cloned().unwrap_or_default(), + _ => Vec::new(), + }; + if fields.text("output.mode") != Some(OutputMode::Separations.id()) || inks.is_empty() { + return ui.label(tl!("Separations list the document's inks here: one page per ink that prints.")); + } + let all_spots = fields.bool("output.spotsToProcess") == Some(true); + ui.vertical(|ui| { + // PLAN: port to the framework's `Table` with `ToggleCell` check and icon faces (spot/process glyph assets) once its row API is in the tree. + egui::Grid::new("print-inks").num_columns(5).show(ui, |ui| { + for h in [tl!("Print"), tl!("Process"), tl!("Ink"), tl!("Frequency"), tl!("Angle")] { + ui.label(h); + } ui.end_row(); - } - }); - note(ui, tl!("Frequencies and angles are the output device's to apply.")); -} - -/// The size of the spot or process icon before a spot ink's name. -const INK_KIND: f32 = 18.0; - -/// The icon before spot ink `name`'s name: a spot icon while it prints as a spot ink, the four -/// process inks while it prints as process (`process`). A click switches it; dimmed (`enabled` -/// off) while Convert All Spot Colors to Process converts every spot ink. Whether it was clicked. -fn ink_kind_button(ui: &mut egui::Ui, name: &str, process: bool, enabled: bool) -> bool { - let label = if process { - crate::i18n::fmt(tl!("Keep {name} as spot"), &[("name", name)]) - } else { - crate::i18n::fmt(tl!("Convert {name} to process"), &[("name", name)]) - }; - let sense = if enabled { egui::Sense::click() } else { egui::Sense::hover() }; - let (rect, resp) = ui.allocate_exact_size(egui::Vec2::splat(INK_KIND), sense); - let t = Tokens::get(ui.ctx()); - if enabled && resp.hovered() { - ui.painter().rect_filled(rect, 3.0, t.hover); - } - let icon = rect.shrink(4.0); - if process { - let q = icon.size() / 2.0; - for (i, c) in crate::panels::swatches::CMYK_INKS.into_iter().enumerate() { - let c = if enabled { c } else { c.gamma_multiply(0.4) }; - let at = icon.min + egui::vec2((i % 2) as f32 * q.x, (i / 2) as f32 * q.y); - ui.painter().rect_filled(egui::Rect::from_min_size(at, q), 0.0, c); - } - } else { - let color = if enabled { t.icon } else { t.text_disabled }; - ui.painter().circle_stroke(icon.center(), icon.width() / 2.0, egui::Stroke::new(1.0, color)); - ui.painter().circle_filled(icon.center(), icon.width() / 5.0, color); - } - resp.widget_info(|| widgets::icon_button_info(enabled, false, &label)); - let resp = resp.on_hover_text(label); - enabled && resp.clicked() + for ink in &inks { + let name = ink["name"].as_str().unwrap_or_default(); + let spot = ink["spot"] == true; + // A spot ink printing as process has no plate: its plate options wait for it to print as a spot ink again. + let process = ink["convertToProcess"] == true; + let mut on = ink["print"].as_bool().unwrap_or(true); + if ui.add_enabled(!process, egui::Checkbox::without_text(&mut on)).changed() { + set_ink(fields, name, "print", json!(on)); + } + let mut as_process = process; + if ui.add_enabled(spot && !all_spots, egui::Checkbox::without_text(&mut as_process)).changed() { + set_ink(fields, name, "convertToProcess", json!(as_process)); + } + ui.label(if spot { format!("{name} ({})", tl!("spot")) } else { name.to_string() }); + for (k, suffix) in [("frequency", " lpi"), ("angle", "°")] { + let mut v = ink[k].as_f64().unwrap_or(0.0); + if ui.add_enabled(!process, egui::DragValue::new(&mut v).suffix(suffix).fixed_decimals(2)).changed() { + set_ink(fields, name, k, json!(v)); + } + } + ui.end_row(); + } + }); + ui.label(tl!("Frequencies and angles are the output device's to apply.")); + }) + .response } /// Set option `key` of ink `name` in `output.inks` (the ink gets its own entry the first time). -fn set_ink(d: &mut Dialog, name: &str, key: &str, value: Value) { - let mut inks = get(d, "output.inks").as_array().cloned().unwrap_or_default(); +fn set_ink(fields: &mut DialogFields, name: &str, key: &str, value: Value) { + let mut inks = match fields.get("output.inks") { + Some(FieldValue::Json(Value::Array(a))) => a.clone(), + _ => Vec::new(), + }; match inks.iter_mut().find(|i| i["name"] == name) { Some(ink) => ink[key] = value, None => { @@ -897,69 +797,42 @@ fn set_ink(d: &mut Dialog, name: &str, key: &str, value: Value) { inks.push(ink); } } - set(d, "output.inks", Value::Array(inks)); + fields.set("output.inks", FieldValue::Json(Value::Array(inks))); } -fn graphics(ui: &mut egui::Ui, d: &mut Dialog) { - heading(ui, tl!("Paths")); - flag(ui, d, "graphics.autoFlatness", tl!("Automatic flatness"), true); - let auto = get(d, "graphics.autoFlatness").as_bool() == Some(true); - row(ui, tl!("Flatness:"), |ui| { - number(ui, d, "graphics.flatness", "", !auto); - ui.label(egui::RichText::new(tl!("0.2 (quality) to 100 (speed)")).size(11.5).color(Tokens::get(ui.ctx()).text_dim)); - }); - heading(ui, tl!("Fonts")); - row(ui, tl!("Download:"), |ui| { - pick::(ui, d, "graphics.fonts", 160.0, |_| true); - }); -} - -fn color(ui: &mut egui::Ui, d: &mut Dialog) { - let profiles = vectorcraft_color::cms::profiles(); - let names: Vec<&str> = std::iter::once(SAME_AS_SOURCE).chain(profiles.iter().map(|p| p.name.as_str())).collect(); - row(ui, tl!("Printer profile:"), |ui| super::save_pdf::profile_pick(ui, d, "color.profile", &names, 1, true)); - note(ui, tl!("Composite colours are converted to it; separations separate with it when it is a CMYK profile.")); - row(ui, tl!("Rendering intent:"), |ui| { - let current = serde_json::from_value::(get(d, "color.intent").clone()).unwrap_or_default(); - let labels: Vec<&str> = Intent::ALL.iter().map(Intent::label).collect(); - if let Some(i) = widgets::dropdown(ui, "color.intent", current.label(), &labels, 200.0).and_then(|i| Intent::ALL.get(i)) { - set(d, "color.intent", serde_json::to_value(i).unwrap_or_default()); +/// The Scale object after a value was set from outside (`ui.dialog.set`), from the one it was: an object with W and H +/// apart and no `linked` turns the link off; a missing or `null` W, H or `linked` keeps the current value; with the +/// link on, a changed W (or H) gives its value to the other; both changed apart while linked is kept as sent, for +/// `print.preview` to refuse. +fn merge_scale(current: &Map, incoming: &Map) -> Map { + let num = |m: &Map, k: &str| m.get(k).and_then(Value::as_f64); + let mut out = current.clone(); + for k in ["width", "height", "linked"] { + if let Some(v) = incoming.get(k).filter(|v| !v.is_null()) { + out.insert(k.into(), v.clone()); } - }); - note(ui, tl!("How colours outside the press's gamut are separated.")); - flag(ui, d, "color.preserveNumbers", tl!("Preserve CMYK Numbers"), true); - note(ui, tl!("CMYK colours print with their own values; off, they go through the colour settings too.")); + } + if incoming.get("linked").is_none() && num(incoming, "width").zip(num(incoming, "height")).is_some_and(|(w, h)| w != h) { + out.insert("linked".into(), json!(false)); + } + let (w, h) = (num(&out, "width"), num(&out, "height")); + if out.get("linked") == Some(&json!(true)) && w != h { + let (w_moved, h_moved) = (w != num(current, "width"), h != num(current, "height")); + if w.is_none() || (!w_moved && h_moved) { + if let Some(h) = h { + out.insert("width".into(), json!(h)); + } + } else if !(w_moved && h_moved) + && let Some(w) = w + { + out.insert("height".into(), json!(w)); + } else if let (false, Some(w)) = (h_moved, w) { + out.insert("height".into(), json!(w)); + } + } + out } -fn advanced(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - heading(ui, tl!("Printer")); - row(ui, tl!("Unprintable margin:"), |ui| length(ui, d, "margin", app.session.general_unit(), true)); - note(ui, tl!("The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed.")); - let composite = choice::(d, "output.mode") != Some(OutputMode::Separations); - flag(ui, d, "advanced.printAsBitmap", tl!("Print as Bitmap"), composite); - note(ui, tl!("Each page prints as one image, at the document's raster effects resolution.")); - heading(ui, tl!("Overprint and Transparency Flattener Options")); - row(ui, tl!("Overprints:"), |ui| { - ui.add_enabled_ui(composite, |ui| pick::(ui, d, "advanced.overprints", 160.0, |_| true)); - }); - let presets = app.session.flattener_presets(); - let names: Vec<&str> = std::iter::once(KEEP_TRANSPARENCY).chain(presets.iter().map(|p| p.name.as_str())).collect(); - // None and the built-in presets are ours; the saved presets are names. - let builtins = names.len().saturating_sub(app.session.prefs.flattener_presets.len()); - row(ui, tl!("Preset:"), |ui| super::save_pdf::profile_pick(ui, d, "advanced.flattenerPreset", &names, builtins, true)); - note( - ui, - tl!( - "Simulate prints overprints as Overprint Preview shows them; separations always keep them. A preset flattens transparency before printing (PostScript files always flatten it)." - ), - ); -} - -/// The Printer Profile entry for no conversion. -const SAME_AS_SOURCE: &str = "Same As Source"; -/// The flattener Preset entry for transparency printed as it is. -const KEEP_TRANSPARENCY: &str = "None (keep transparency)"; - /// The section an option is set in, and whether its first key is the section's own object /// (`output.mode` → Output › Mode). pub(super) fn section_of(option: &str) -> (usize, bool) { @@ -1011,38 +884,45 @@ pub(super) fn labelled(changed: &mut [Value]) { } } -fn summary(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result, has_doc: bool) { - let t = Tokens::get(ui.ctx()); - match pv { +/// A line per changed option (`{option, value}`, after [`labelled`]): "Section › Option: value". +pub(super) fn changed_lines(changed: &[Value]) -> Vec { + changed + .iter() + .map(|c| { + let value = match &c["value"] { + Value::Bool(b) => if *b { tl!("On") } else { tl!("Off") }.to_string(), + Value::String(s) => s.clone(), + other => other.to_string(), + }; + format!("{} {value}", crate::i18n::colon(&option_label(c["option"].as_str().unwrap_or_default()))) + }) + .collect() +} + +/// The Summary's pages, options and warnings texts for the preview `pv` of `settings`. +fn summary_texts(pv: &Result, settings: &Value, has_doc: bool) -> [String; 3] { + let lang = crate::i18n::current(); + let warn = |w: &str| format!("⚠ {}", crate::i18n::message(lang, w)); + let pages = match pv { Ok(v) => { - heading(ui, tl!("Pages")); let per_copy = v["sheets"].as_array().map_or(0, Vec::len); - ui.label( - egui::RichText::new(crate::i18n::fmt( - tl!("{pages} in all, {count} per copy"), - &[("pages", &v["pages"].to_string()), ("count", &per_copy.to_string())], - )) - .color(t.text), - ); + crate::i18n::fmt(tl!("{pages} in all, {count} per copy"), &[("pages", &v["pages"].to_string()), ("count", &per_copy.to_string())]) } // A preset edited without a document has no pages to count. - Err(_) if !has_doc => {} - Err(e) => { - heading(ui, tl!("Error")); - ui.label(egui::RichText::new(super::save_pdf::warning_line(crate::i18n::current(), e)).color(t.text)); - } - } - heading(ui, tl!("Options")); + Err(_) if !has_doc => String::new(), + Err(e) => warn(e), + }; let mut changed = vec![]; - vectorcraft_engine::cmd::fileio::pdf::changed("", &settings(d), &DEFAULTS, &mut changed); + vectorcraft_engine::cmd::fileio::pdf::changed("", settings, &DEFAULTS, &mut changed); changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default()).0); labelled(&mut changed); - if changed.is_empty() { - note(ui, tl!("Every option is at its default.")); - } - super::save_pdf::option_rows(ui, &changed, option_label); - if let Ok(v) = pv { - heading(ui, tl!("Warnings")); - super::save_pdf::warning_rows(ui, v["warnings"].as_array().map(Vec::as_slice).unwrap_or_default()); - } + let options = if changed.is_empty() { tl!("Every option is at its default.").to_string() } else { changed_lines(&changed).join("\n") }; + let warnings = match pv { + Ok(v) => { + let lines: Vec = v["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(warn).collect(); + if lines.is_empty() { tl!("None.").to_string() } else { lines.join("\n") } + } + Err(_) => String::new(), + }; + [pages, options, warnings] } diff --git a/crates/ui-egui/src/dialogs/print_presets.rs b/crates/ui-egui/src/dialogs/print_presets.rs index 3ad798d998..ccf9d7146d 100644 --- a/crates/ui-egui/src/dialogs/print_presets.rs +++ b/crates/ui-egui/src/dialogs/print_presets.rs @@ -1,171 +1,97 @@ //! Edit → Print Presets: every preset in a list ([Default], protected, then the saved ones) with //! how the selected one differs from [Default] beside it; New… (a preset starting from the //! selected one), Edit… (saved presets), Delete, Import… and Export… (the selected preset) under -//! the list. New… and Edit… open the preset editor (the Print dialog, kind `printPreset`), whose OK -//! comes back here. -//! -//! Field: `selected` (a preset's name). +//! the list. New… and Edit… open the preset editor (the Print dialog in its editor mode), whose OK +//! comes back here. The manager is the shared presets manager (`preset_manager`); this module is +//! what is particular to print presets. +// PLAN: assumed `preset_manager` API (export-w19): `PresetManager::new(key, title, rows, actions).selected(name)`, +// `ManagerRow::new(key, label).protected()`, `Detail::{Title, Heading, Line, Note}`, `ManagerAction::{New, Edit, Delete, +// Import, Export}`, `ManagerEvent::{Select(name), Action(ManagerAction)}`. +use craft::host::files::PickRequest; use serde_json::{Value, json}; use vectorcraft_engine::cmd::printpresets::{DEFAULT_PRESET, PRESET_EXTS, PRESET_FORMAT, changes}; -use super::DialogSpec; -use super::print::{open_preset, option_label, section_of}; -use super::save_pdf::option_rows; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::{VectorcraftApp, widgets}; +use super::preset_manager::{Detail, ManagerAction, ManagerEvent, ManagerRow, PresetManager}; +use super::print::{changed_lines, open_preset, section_of}; +use crate::VectorcraftApp; +use crate::file_asks::{Owner, ask}; -/// The dialog kind of Print Presets. -pub const KIND: &str = "printPresets"; - -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Print Presets").into(), - body, - confirm: |app, _| { - app.ui.dialog = None; - Ok(Value::Null) - }, - ok: None, - min_width: 620.0, - ..DialogSpec::FORM -}; +/// The key of the Print Presets dialog. +pub(super) const KEY: &str = "printPresets"; /// Open the presets manager on `selected` (default: [Default]). pub fn open(app: &mut VectorcraftApp, selected: Option<&str>) { - app.ui.dialog = Some(Dialog::new(KIND, json!({ "selected": selected.unwrap_or(DEFAULT_PRESET) }))); + let Some(dialogs) = app.dialogs() else { return }; + let actions = vec![ManagerAction::New, ManagerAction::Edit, ManagerAction::Delete, ManagerAction::Import, ManagerAction::Export]; + let manager = PresetManager::new(KEY, tl!("Print Presets"), rows(app), actions).selected(selected.unwrap_or(DEFAULT_PRESET)); + dialogs.with(|h| h.open(manager)); } -/// What a button asked for, done once the list and the details are drawn. -pub(super) enum Action { - Select(String), - New, - Edit, - Delete, - Import, - Export, +/// The list: [Default] (protected, translated), then the saved presets. +pub(super) fn rows(app: &VectorcraftApp) -> Vec { + std::iter::once(ManagerRow::new(DEFAULT_PRESET, tl!(DEFAULT_PRESET)).protected()) + .chain(app.session.prefs.print_presets.iter().map(|p| ManagerRow::new(p.name.as_str(), p.name.as_str()))) + .collect() } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - let saved = &app.session.prefs.print_presets; - let selected = d.str("selected"); - // 0 is [Default]; saved presets follow. - let i = saved.iter().position(|p| p.name.eq_ignore_ascii_case(selected.trim())).map_or(0, |i| i + 1); - let name = i.checked_sub(1).and_then(|k| saved.get(k)).map_or(DEFAULT_PRESET, |p| p.name.as_str()).to_string(); - let builtin = i == 0; - let mut act = None; - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - ui.set_width(280.0); - widgets::dim_label(ui, tl!("Presets:")); - widgets::list_box(ui, |ui| { - egui::ScrollArea::vertical().id_salt("print-presets").min_scrolled_height(240.0).max_height(240.0).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.set_min_height(240.0); - for (k, n) in std::iter::once(DEFAULT_PRESET).chain(saved.iter().map(|p| p.name.as_str())).enumerate() { - if ui.selectable_label(k == i, if k == 0 { tl!(n) } else { n }).clicked() { - act = Some(Action::Select(n.to_string())); - } - } - }); - }); - ui.add_space(6.0); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - if widgets::flat_button(ui, tl!("New…"), 48.0).on_hover_text(tl!("A new preset starting from the selected one")).clicked() { - act = Some(Action::New); - } - if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Edit…"), 48.0)).inner.clicked() { - act = Some(Action::Edit); - } - if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Delete"), 52.0)).inner.clicked() { - act = Some(Action::Delete); - } - if widgets::flat_button(ui, tl!("Import…"), 60.0).clicked() { - act = Some(Action::Import); - } - if widgets::flat_button(ui, tl!("Export…"), 60.0).on_hover_text(tl!("Save the selected preset to a file")).clicked() { - act = Some(Action::Export); - } - }); - }); - ui.add_space(18.0); - ui.vertical(|ui| { - ui.set_width(300.0); - ui.label(egui::RichText::new(&name).color(t.text_strong).strong()); - ui.add_space(8.0); - widgets::dim_label(ui, &crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)])); - let settings = i.checked_sub(1).and_then(|k| saved.get(k)).map(|p| &p.settings); - let mut changed = settings.map(|s| changes(s, &Default::default())).unwrap_or_default(); - changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default()).0); - egui::ScrollArea::vertical().id_salt("print-preset-details").max_height(200.0).show(ui, |ui| { - if changed.is_empty() { - ui.label(egui::RichText::new(tl!("None.")).color(t.text_dim).size(11.5)); - } - option_rows(ui, &changed, option_label); - }); - if builtin { - ui.add_space(6.0); - ui.label(egui::RichText::new(tl!("[Default] is protected: New… starts an editable copy.")).color(t.text_dim).size(11.5)); - } - }); - }); - if let Some(a) = act { - let r = match a { - // Their file dialogs, shown off the UI thread, import into or export from the dialog - // as it is then. - Action::Import | Action::Export => { - let (current, export) = (name.clone(), matches!(a, Action::Export)); - crate::picks::in_dialog(app, d, move |app, d| run(app, d, if export { Action::Export } else { Action::Import }, ¤t)) - } - a => run(app, d, a, &name), - }; - if let Err(e) = r { - app.status(e); - } +/// What the manager shows beside the list for the preset `name`: how it differs from [Default]. +pub(super) fn detail(app: &VectorcraftApp, name: &str) -> Vec { + let builtin = name == DEFAULT_PRESET; + let title = if builtin { tl!(DEFAULT_PRESET).to_string() } else { name.to_string() }; + let mut out = vec![Detail::Title(title), Detail::Heading(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]))]; + let settings = app.session.prefs.print_presets.iter().find(|p| p.name == name).map(|p| &p.settings); + let mut changed = settings.map(|s| changes(s, &Default::default())).unwrap_or_default(); + changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default()).0); + let lines = changed_lines(&changed); + if lines.is_empty() { + out.push(Detail::Note(tl!("None.").to_string())); } - false + out.extend(lines.into_iter().map(Detail::Line)); + if builtin { + out.push(Detail::Note(tl!("[Default] is protected: New… starts an editable copy.").to_string())); + } + out } -fn select(d: &mut Dialog, name: &str) { - d.fields.insert("selected".into(), json!(name)); -} - -pub(super) fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> Result<(), String> { - match act { - Action::Select(name) => select(d, &name), - // The editor replaces this dialog; its OK comes back here. - Action::New => { - open_preset(app, &json!({ "preset": current }))?; - *d = app.ui.dialog.take().ok_or("no preset editor")?; +/// Do what a manager event asks of the preset `current`; the preset to select afterwards, when it changes. +pub(super) fn run(app: &mut VectorcraftApp, event: &ManagerEvent, current: &str) -> Result, String> { + let action = match event { + ManagerEvent::Select(name) => return Ok(Some(name.clone())), + ManagerEvent::Action(action) => action, + }; + match action { + // The editor replaces the manager; its OK comes back here. + ManagerAction::New | ManagerAction::Edit => { + let params = if matches!(action, ManagerAction::New) { json!({ "preset": current }) } else { json!({ "name": current }) }; + open_preset(app, ¶ms)?; + // PLAN: assumed `app.ui_ctx: Option` (lib.rs:203). + if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { + dialogs.with(|h| h.cancel::(&ctx)); + } + Ok(None) } - Action::Edit => { - open_preset(app, &json!({ "name": current }))?; - *d = app.ui.dialog.take().ok_or("no preset editor")?; - } - Action::Delete => { + ManagerAction::Delete => { let i = app.session.prefs.print_presets.iter().position(|p| p.name == current); app.run("print.presets.delete", json!({ "name": current }))?; // The one above it takes its place ([Default] above the first saved one). let next = i.and_then(|i| i.checked_sub(1)).and_then(|i| app.session.prefs.print_presets.get(i)).map(|p| p.name.clone()); - select(d, next.as_deref().unwrap_or(DEFAULT_PRESET)); + Ok(Some(next.unwrap_or_else(|| DEFAULT_PRESET.to_string()))) } - Action::Import => { - // On the web the picked file arrives later and imports through `io::open_bytes`. - if crate::picks::open_async(app) { - return Ok(()); - } - let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Print presets", PRESET_EXTS)], ..Default::default() }; - let path = crate::picks::open(app, &pick).ok_or("cancelled")?; - let r = app.run("print.presets.import", json!({ "path": path }))?; - if let Some(first) = r["imported"].get(0).and_then(Value::as_str) { - select(d, first); - } + ManagerAction::Import => { + let request = PickRequest::open("print-presets").filter("Print presets", PRESET_EXTS); + // PLAN: assumed `Picked::path(&self) -> Option`. + ask(app, request, Owner::Free, |app, picked| { + let path = picked.path().ok_or("cancelled")?; + let r = app.run("print.presets.import", json!({ "path": path }))?; + open(app, r["imported"].get(0).and_then(Value::as_str)); + Ok(r) + }); + Ok(None) } - Action::Export => { + ManagerAction::Export => { crate::io::save_command_output(app, "print.presets.export", PRESET_FORMAT, json!({ "names": [current] }))?; + Ok(None) } } - Ok(()) } diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 6c94e0cad8..1ac384ec7d 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -5,19 +5,12 @@ //! PostScript file (`format: "postscript"`, or a `.ps` path) is always saved. `print.printers` //! lists the printers. -use serde::Serialize; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; use crate::{VectorcraftApp, io}; -/// A printer the system knows. -#[derive(Clone, Debug, PartialEq, Serialize)] -pub struct Printer { - pub name: String, - /// The system's default printer. - pub default: bool, -} +pub use craft::print::ui::Printer; /// A print job: a print-ready PDF, every copy and page in it. pub struct PrintJob<'a> { @@ -64,6 +57,7 @@ pub trait PrintService { /// `print.printers`: the system's printers, and what the print service offers. pub fn printers(app: &mut VectorcraftApp) -> Value { let (printers, setup) = app.services.print.as_mut().map(|s| (s.printers(), s.has_setup())).unwrap_or_default(); + let printers: Vec = printers.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect(); json!({ "printers": printers, "service": app.services.print.is_some(), "setup": setup }) } diff --git a/crates/ui-egui/src/tests/printps.rs b/crates/ui-egui/src/tests/printps.rs index a3aef360fd..9ccd32ba5e 100644 --- a/crates/ui-egui/src/tests/printps.rs +++ b/crates/ui-egui/src/tests/printps.rs @@ -17,7 +17,7 @@ struct Counting(Rc>); impl PrintService for Counting { fn printers(&mut self) -> Vec { - vec![Printer { name: "Office".into(), default: true }] + vec![Printer::new("Office").is_default(true)] } fn print(&mut self, _: &PrintJob) -> Result {