diff --git a/crates/print/README.md b/crates/print/README.md index 5a92674bc..8e6c32de1 100644 --- a/crates/print/README.md +++ b/crates/print/README.md @@ -236,13 +236,34 @@ to ``Job`` and own the Print action, page selection, preview and export behavior `State::run` polls the workers and draws `PrintPanel` over the settings, starting discovery on the first pass; apps that draw their own dialog around the panel use it. `PrintDialog` is Photoshop's Print Settings: a preview of the -paper, printable area, image box and marks, the panel, and the app's `PrintSection` rows (`ParamRows`), with Print, +paper, printable area, image box and marks (when the app gives a `PrintSheet`; without one the dialog shows its +`message`), the panel, and the app's `PrintSection` rows (`ParamRows`), with Print, Cancel and Done in the footer. Dragging the image box reports its total travel from the press in paper points as `EditEvents`. `HostedPrint` is the same dialog owned by a `DialogHost`. It holds no discovery closure: it asks with `take_refresh` (the first pass and each Refresh) and the app answers with `listen`, passing `discover()` or its own receiver, so a list that needs the app's session works too. `State::listen` takes the receiver and refuses while a discovery or a job runs. +`PrintLayout::Stacked` (the default) stacks the printer panel and every section beside the preview. +`PrintLayout::Sections` puts the preset row, `PrintPanel` in `PrintPanelLayout::PrinterOnly` (the printer, Refresh +and, with `driver`, a Setup… button whose press is `PrintDialogOutput::setup` and `HostedPrint::take_setup`) and the +`header` rows above a list of the sections beside the shown one; the preview, its readout and the sheet step stand +under the list. The shown section is the dialog's memory unless the host binds it with `section`. + +`PrintMode::PresetEditor` replaces the preset, printer and header rows with a Preset name field whose refusal +(`check_name`) shows under it; OK reads "Save Preset" and there is no Done. + +`PrintPresets` fills the preset row: the presets, the held one (`[Custom]` shows while none is) and the built-in +names. The dialog keeps no store: the row's Apply, Create, Rename and Delete go to `PrintDialogOutput::presets` +(`HostedPrint::take_preset_events`) and the host answers with `HostedPrint::set_presets`. + +A `PrintSheet` with `count(n)` more than one shows Previous, "{n} of {count}" and Next under the preview; a step is +`PrintDialogOutput::sheet` and `HostedPrint::sheet_index`. `outlines` draws each sheet's rectangle on the paper. + +Automation lists `section`, `sheet`, `preset` and, in the editor, `name` beside the settings keys. `choice: "done"` +makes the next `confirm` answer Done; any other value is refused. `held_ok` keeps the dialog open until the app +answers its Print with `answer_ok`; an `Err` shows its reason under the sections. + Apps render typed `Feedback` using their own translations. `poll` requests occasional repaints while work is pending. Refresh disables submission until the new printer list arrives, preserves a still-present selection, and otherwise chooses the system default or first available printer. diff --git a/crates/print/src/ui/dialog.rs b/crates/print/src/ui/dialog.rs index 70737494f..099ea8618 100644 --- a/crates/print/src/ui/dialog.rs +++ b/crates/print/src/ui/dialog.rs @@ -1,28 +1,39 @@ //! `PrintDialog`: Photoshop's Print Settings (the preview pane, the printer panel and the app's //! sections), and `HostedPrint`, the same dialog owned by a `DialogHost`. +use std::sync::Arc; use std::sync::mpsc::Receiver; -use craft_behavior::{CursorIcon, EditEvent, EditEvents, Metrics, Mixed, PartKey, PointerButton, PressPhase, Sense}; +use craft_behavior::{ + CursorIcon, EditEvent, EditEvents, IconId, Metrics, Mixed, PartKey, PointerButton, PressPhase, Sense, keyed, +}; +use craft_ui::buttons::IconButton; use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, - Props as _, Role, Show as _, ShowContainer as _, WordSetCx as _, + Props as _, Remember as _, Role, Show as _, ShowContainer as _, Validity, Value, WordSetCx as _, clicked, }; use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; -use craft_ui::display::Text; +use craft_ui::display::{Shade, Text}; +use craft_ui::form::Field; use craft_ui::layout_components::{Row, Stack}; -use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, FormDialog, HostRequests, Param, ParamRows, set_color_field, set_param_field}; -use craft_ui::patterns::presets::{NameCheck, NamedPresetEvent, PresetError, PresetRow}; -use craft_ui::runtime::env::{Env, Label}; +use craft_ui::list::ListRow; +use craft_ui::patterns::form_dialogs::{ + DialogFields, FieldValue, FormDialog, HostRequests, Param, ParamRows, SectionList, set_color_field, set_param_field, +}; +use craft_ui::patterns::presets::{ + NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetPicker, PresetRow, PresetState, PresetWords, +}; +use craft_ui::runtime::env::{Env, Label, Message}; use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse}; use craft_ui::runtime::overlay::CloseReason; use craft_ui::runtime::requests::HostAnswer; use craft_ui::sections::{DialogRole, FooterButton, Section}; -use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleCx, SurfaceKind}; +use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleCx, SurfaceKind, TypeRole}; +use craft_ui::text::TextField; use egui::load::SizedTexture; use egui::{Pos2, Rect, Response, Ui, Vec2, pos2, vec2}; -use super::panel::{MOST_COPIES, PrintPanel}; +use super::panel::{MOST_COPIES, PrintPanel, PrintPanelLayout}; use super::{Duplex, Printer, Settings, State}; craft_ui::words! { @@ -34,6 +45,14 @@ craft_ui::words! { preview: "printDialog.preview" = "Print preview image"; printer_setup: "printDialog.printerSetup" = "Printer Setup"; image_box: "printDialog.imageBox" = "Image box"; + sections: "printDialog.sections" = "Sections"; + preset: "printDialog.preset" = "Print Preset"; + custom: "printDialog.custom" = "[Custom]"; + preset_name: "printDialog.presetName" = "Preset name"; + save_preset: "printDialog.savePreset" = "Save Preset"; + previous: "printDialog.previous" = "Previous"; + next: "printDialog.next" = "Next"; + sheet_of: template "printDialog.sheetOf" = "{n} of {count}"; } } @@ -108,16 +127,16 @@ impl PrintSheet { /// How many sheets the document prints on. #[must_use] - pub fn count(self, count: usize) -> Self { - let _ = count; - todo!("ex.E53") + pub fn count(mut self, count: usize) -> Self { + self.count = count; + self } /// The outline of each sheet on the paper, in paper points. #[must_use] - pub fn outlines(self, outlines: Vec) -> Self { - let _ = outlines; - todo!("ex.E53") + pub fn outlines(mut self, outlines: Vec) -> Self { + self.outlines = outlines; + self } } @@ -155,6 +174,13 @@ pub struct PrintPresets<'a> { pub built_in: &'a [String], } +impl<'a> PrintPresets<'a> { + /// The presets `rows`, the `held` one and the `built_in` names. + pub fn new(rows: &'a [PresetRow], held: Option, built_in: &'a [String]) -> Self { + PrintPresets { rows, held, built_in } + } +} + /// One titled section of the app's rows (Color Management, Position and Size, Printing Marks, /// Functions, Save as PDF). #[non_exhaustive] @@ -331,6 +357,9 @@ impl Component for PrintPreview<'_> { if let Some(area) = sheet.printable { outline(RuleKind::Grid, place.rect(area)); } + for sheet_outline in &sheet.outlines { + outline(RuleKind::Grid, place.rect(*sheet_outline)); + } outline(RuleKind::Edge, paper); outline(RuleKind::DropMark, image); @@ -403,16 +432,157 @@ impl Outcome for PrintPreviewOutput { } } +/// What the dialog keeps between passes for the values the host does not bind. +#[derive(Clone, Debug, Default)] +struct Own { + section: String, + sheet: usize, + name: String, + picker: PresetState, +} + +/// The value `bind` holds this pass; `None` while it holds none (a kept or mixed binding). +fn read(bind: &mut Bind<'_, T>) -> Option { + match bind.reborrow().get() { + Some(Mixed::Same(value)) => Some(value), + _ => None, + } +} + +/// Writes `value` through `bind` as one step. A given binding keeps its value: the host takes the dialog's reports. +// PLAN: form_dialogs' `read_bind` and `write_bind` (form.rs) do the same and are `pub(crate)`; the form_dialogs owner makes them public so this copy goes. +fn write(bind: &mut Bind<'_, T>, value: T) { + let before = bind.reborrow().get().unwrap_or(Mixed::Mixed); + let _ = bind.reborrow().apply(&EditEvent::set(before, value, Arc::from(""), None)); +} + +/// The host's binding when it gave one, else the dialog's own memory. +fn bound_or<'b, T: Value>(host: &'b mut Option>, own: &'b mut T) -> Bind<'b, T> { + match host { + Some(bind) => bind.reborrowed(), + None => Bind::bound(own), + } +} + +/// Whether a preset name can be saved: it says something and the host's check lets it through. The one rule for the +/// dialog's OK and the hosted dialog's `confirm`. +fn usable_name(name: &str, refused: Option) -> bool { + !name.trim().is_empty() && refused.is_none() +} + +/// The preview with its readout and, for a document of several sheets, the step row; with no sheet, the host's message. +fn preview_room( + ui: &mut Ui, + words: &PrintDialogWords, + sheet: Option<&PrintSheet>, + message: Option<&Label>, + index: &mut Bind<'_, usize>, + moved: &mut EditEvents, + stepped: &mut Option, +) { + let Some(sheet) = sheet else { + if let Some(message) = message { + Text::new(message.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + } + return; + }; + let preview = PrintPreview::new(words.preview.clone(), sheet, Bind::given(sheet.image.min)).show(ui); + moved.extend(preview.edit.events); + Text::new(sheet.readout.clone()).show(ui); + if sheet.count > 1 { + step_row(ui, words, sheet.count, index, stepped); + } +} + +/// Previous, "{n} of {count}" and Next. A step writes the index and reports it for this pass. +fn step_row(ui: &mut Ui, words: &PrintDialogWords, count: usize, index: &mut Bind<'_, usize>, stepped: &mut Option) { + let last = count.saturating_sub(1); + let shown = read(index).unwrap_or(0).min(last); + let mut to = None; + Row::new().show(ui, |ui, _| { + if clicked(&IconButton::new(IconId::new("chevron_left")).label(words.previous.clone()).enabled(shown > 0).show(ui)) { + to = Some(shown - 1); + } + let place = words.sheet_of.fill(&[("n", (shown + 1).to_string().as_str()), ("count", count.to_string().as_str())]); + Text::new(Label::from(place)).show(ui); + if clicked(&IconButton::new(IconId::new("chevron_right")).label(words.next.clone()).enabled(shown < last).show(ui)) { + to = Some(shown + 1); + } + }); + if let Some(to) = to { + write(index, to); + *stepped = Some(to); + } +} + +/// The preset row: the picker over the host's presets, `[Custom]` while the settings match none, and the row's events. +fn preset_row( + ui: &mut Ui, + words: &PrintDialogWords, + presets: &PrintPresets<'_>, + check: Option<&NameCheck<'_>>, + picker: &mut PresetState, + events: &mut Vec>, +) { + let mut pick = PresetPicker::new(words.preset.clone(), Bind::given(presets.held.clone()), presets.rows, Bind::bound(picker)) + .field(PickerField::Name); + if presets.held.is_none() { + pick = pick.placeholder(words.custom.clone()); + } + let mut row = NamedPresetRow::new(words.preset.clone(), pick).built_in(|key: &String| presets.built_in.contains(key)); + if let Some(check) = check { + // PLAN: `NameCheck::refuses` is private to presets/named.rs; the presets owner makes it `pub` so a dialog can run the check it was given. + row = row.check_name(|name| check.refuses(name)); + } + events.extend(row.show(ui).events); +} + +/// The preset editor's name field with the host's refusal under it. Returns whether the name can be saved. +fn name_row(ui: &mut Ui, words: &PrintDialogWords, check: Option<&NameCheck<'_>>, name: &mut Bind<'_, String>) -> bool { + let preset_words = Env::of(ui).words::(); + let current = read(name).unwrap_or_default(); + let refused = |text: &str| check.and_then(|check| check.refuses(text)); + let check_text = |text: &String| match refused(text).filter(|_| !text.is_empty()) { + Some(PresetError::NameTaken) => Validity::Refuse(Message::new(preset_words.name_taken.clone())), + Some(_) => Validity::Refuse(Message::new(preset_words.name_invalid.clone())), + None => Validity::Ok, + }; + let mut typed = None; + Field::new(words.preset_name.clone()).id_salt("name").show(ui, |ui, _| { + typed = TextField::new(words.preset_name.clone(), Bind::given(current.clone()).check(check_text)) + .id_salt("name-text") + .select_on_focus() + .show(ui) + .value() + .cloned(); + }); + let shown = match typed { + Some(text) => { + write(name, text.clone()); + text + } + None => current, + }; + usable_name(&shown, refused(&shown)) +} + +/// `params` as rows over `values`; the colour, path and eyedropper requests they file go to `requests`. +fn param_rows(ui: &mut Ui, requests: &mut HostRequests, title: &Label, params: &[Param], values: &mut DialogFields) { + let mut rows = ParamRows::new(title.clone(), params, Bind::bound(values)).show(ui); + requests.absorb(&mut rows); +} + /// Photoshop's Print Settings: the preview at the start edge (paper, printable area, image box, /// marks, readout), the printer panel and the sections at the end edge, and Print, Cancel and Done -/// in the footer. +/// in the footer. With [`PrintLayout::Sections`] the preset row, the printer row and the header rows +/// stand above a list of sections beside the shown one, and the preview sits under the list. #[must_use = "show the dialog with `show`"] #[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)] pub struct PrintDialog<'a> { settings: Bind<'a, Settings>, printers: &'a [Printer], fields: Bind<'a, DialogFields>, - /// This pass's layout, from the app; without one the dialog shows no preview. + /// This pass's layout, from the app; without one the dialog shows no preview, and `message` in its place. #[prop] sheet: Option<&'a PrintSheet>, /// The app's sections under the printer panel. @@ -435,44 +605,41 @@ pub struct PrintDialog<'a> { answers: Vec, /// Binds the number of the sheet the preview shows, for a document that prints on several. #[prop] - #[allow(dead_code)] // P3(export-w7): ex.E52 sheet_index: Option>, /// A line of the host's under the preview. #[prop(into)] - #[allow(dead_code)] // P3(export-w7): ex.E52 message: Option