export-w7: net change of 1 commits

- export-w7: written from its sheet
This commit is contained in:
bflatastic
2026-11-21 21:27:58 +07:00
parent 09c7de6a75
commit 6bd766654a
6 changed files with 679 additions and 128 deletions
+22 -1
View File
@@ -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.
+506 -115
View File
@@ -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<egui::Rect>) -> Self {
let _ = outlines;
todo!("ex.E53")
pub fn outlines(mut self, outlines: Vec<egui::Rect>) -> 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<String>], held: Option<String>, 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<String>,
}
/// The value `bind` holds this pass; `None` while it holds none (a kept or mixed binding).
fn read<T: Value>(bind: &mut Bind<'_, T>) -> Option<T> {
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<T: Value>(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<Bind<'_, T>>, 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<PresetError>) -> 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<Pos2>,
stepped: &mut Option<usize>,
) {
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<usize>) {
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<String>,
events: &mut Vec<NamedPresetEvent<String>>,
) {
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::<PresetWords>();
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<HostAnswer>,
/// 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<Bind<'a, usize>>,
/// A line of the host's under the preview.
#[prop(into)]
#[allow(dead_code)] // P3(export-w7): ex.E52
message: Option<Label>,
/// How the sections are arranged.
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E48
layout: PrintLayout,
/// Binds the shown section, with [`PrintLayout::Sections`].
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E48
section: Option<Bind<'a, String>>,
/// The print presets the preset row lists.
/// The print presets the preset row lists, with [`PrintLayout::Sections`].
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E49
presets: Option<PrintPresets<'a>>,
/// Rows above the sections.
/// Rows above the sections, with [`PrintLayout::Sections`].
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E50
header: &'a [Param],
/// What the dialog is for.
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E51
mode: PrintMode,
/// Binds the preset editor's name.
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E51
preset_name: Option<Bind<'a, String>>,
/// Whether a typed preset name may be used, in the preset editor.
#[prop(func = "Fn(&str) -> Option<PresetError>")]
#[allow(dead_code)] // P3(export-w7): ex.E51
check_name: Option<NameCheck<'a>>,
/// The driver controls (Print Settings…, Portrait and Landscape, the page line) are shown.
/// The driver's Setup… button is shown, with [`PrintLayout::Sections`].
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E56
driver: bool,
/// OK keeps the dialog open and reports `finish`: the host answers it and closes the dialog.
// PLAN: not in the contract rows; a held OK needs the form to stay open until the host answers (export-w20's request).
#[prop]
hold: bool,
/// The host's refusal of the held OK, shown under the sections.
#[prop(into)]
refusal: Option<Label>,
}
/// What [`PrintDialog::show`] returns.
@@ -532,11 +699,13 @@ impl<'a> PrintDialog<'a> {
preset_name: None,
check_name: None,
driver: false,
hold: false,
refusal: None,
}
}
/// Draws the dialog. The body reports the drag events and the Refresh press of its last run only, so a measuring run
/// adds none; a second pass of a frame has no new input and reports none.
/// Draws the dialog. The body reports the drag events, the Refresh and Setup presses, the preset events and the sheet
/// step of its last run only, so a measuring run adds none; a second pass of a frame has no new input and reports none.
pub fn show(self, ui: &mut Ui) -> PrintDialogOutput {
let PrintDialog {
mut settings,
@@ -549,66 +718,129 @@ impl<'a> PrintDialog<'a> {
discovering,
ready,
answers,
sheet_index: _,
message: _,
layout: _,
section: _,
presets: _,
header: _,
mode: _,
preset_name: _,
check_name: _,
driver: _,
} = self; // P3(export-w7): ex.E48
mut sheet_index,
message,
layout,
mut section,
presets,
header,
mode,
mut preset_name,
check_name,
driver,
hold,
refusal,
} = self;
let env = Env::of(ui);
let words = env.words::<PrintDialogWords>();
let editor = mode == PrintMode::PresetEditor;
let titles: Vec<String> = sections.iter().map(|section| section.title.as_str().to_owned()).collect();
let mut form = FormDialog::new(words.title.clone(), fields)
.ok_label(words.print.clone())
.ok_enabled(ready && !busy)
.extra_buttons([FooterButton::new(words.done.clone(), DialogRole::Other)])
.ok_label(if editor { words.save_preset.clone() } else { words.print.clone() })
.ok_enabled(editor || (ready && !busy))
.extra_buttons((!editor).then(|| FooterButton::new(words.done.clone(), DialogRole::Other)))
.accept_stays_open(hold)
.answers(answers);
if let Some(opened) = opened {
form = form.opened(opened);
}
let mut moved = EditEvents::new();
let mut refresh = false;
let mut setup = false;
let mut preset_events: Vec<NamedPresetEvent<String>> = Vec::new();
let mut stepped = None;
let shown = form.show(ui, |ui, form, values| {
moved = EditEvents::new();
refresh = false;
setup = false;
preset_events.clear();
stepped = None;
for answer in form.take_answers() {
match answer {
HostAnswer::Color { key, color } | HostAnswer::Eyedropper { key, color } => {
for section in sections {
set_color_field(&section.params, values, &key, color);
for params in sections.iter().map(|section| section.params.as_slice()).chain([header]) {
set_color_field(params, values, &key, color);
}
}
HostAnswer::Path { key, path } => values.set(&key, FieldValue::Text(path.to_string_lossy().into_owned())),
_ => {}
}
}
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
// P3(export-w7): ex.E52 -- a dialog without a sheet shows no preview.
if let Some(sheet) = sheet {
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);
let mut own = form.memory::<Own>().clone();
let accepted = {
let Own { section: own_section, sheet: own_sheet, name: own_name, picker } = &mut own;
let mut section_bind = bound_or(&mut section, own_section);
let mut index_bind = bound_or(&mut sheet_index, own_sheet);
let mut name_bind = bound_or(&mut preset_name, own_name);
if editor {
name_row(ui, &words, check_name.as_ref(), &mut name_bind)
} else {
let mut preview = |ui: &mut Ui| preview_room(ui, &words, sheet, message.as_ref(), &mut index_bind, &mut moved, &mut stepped);
match layout {
PrintLayout::Stacked => {
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| preview(ui));
Stack::new().show(ui, |ui, _| {
Section::fixed(words.printer_setup.clone()).id_salt("printer").show(ui, |ui, _| {
let panel = PrintPanel::new(settings.reborrowed(), printers).discovering(discovering).busy(busy).show(ui);
refresh |= panel.refresh;
});
for (at, section) in sections.iter().enumerate() {
Section::fixed(section.title.clone()).id_salt(("section", at)).show(ui, |ui, _| {
param_rows(ui, form.requests(), &section.title, &section.params, values);
});
}
});
});
}
PrintLayout::Sections => {
Stack::new().show(ui, |ui, _| {
if let Some(presets) = &presets {
preset_row(ui, &words, presets, check_name.as_ref(), picker, &mut preset_events);
}
let panel = PrintPanel::new(settings.reborrowed(), printers)
.layout(PrintPanelLayout::PrinterOnly)
.driver(driver)
.discovering(discovering)
.busy(busy)
.show(ui);
refresh |= panel.refresh;
setup |= panel.settings_clicked;
if !header.is_empty() {
param_rows(ui, form.requests(), &words.title, header, values);
}
let current = read(&mut section_bind).filter(|title| titles.contains(title)).or_else(|| titles.first().cloned());
let Some(current) = current else {
preview(ui);
return;
};
let source = keyed(&titles, |title: &String| title.clone());
// PLAN: assumes `SectionList::foot(self, impl FnOnce(&mut Ui) + 'a) -> Self` (type-w6 request on ty.X70).
let picked = SectionList::new(words.sections.clone(), &source, current.clone())
.foot(preview)
.show(
ui,
|title| ListRow::new(Label::from(title.clone())),
|ui| {
if let Some(section) = sections.iter().find(|section| section.title.as_str() == current) {
param_rows(ui, form.requests(), &section.title, &section.params, values);
}
},
);
if let Some(title) = picked {
write(&mut section_bind, title);
}
});
}
}
});
Stack::new().show(ui, |ui, _| {
Section::fixed(words.printer_setup.clone()).id_salt("printer").show(ui, |ui, _| {
let panel = PrintPanel::new(settings.reborrowed(), printers).discovering(discovering).busy(busy).show(ui);
refresh |= panel.refresh;
});
for (at, section) in sections.iter().enumerate() {
Section::fixed(section.title.clone()).id_salt(("section", at)).show(ui, |ui, _| {
let mut rows = ParamRows::new(section.title.clone(), &section.params, Bind::bound(&mut *values)).show(ui);
form.requests().absorb(&mut rows);
});
if let Some(reason) = &refusal {
Text::new(reason.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
});
});
ready && !busy
ready && !busy
}
};
*form.memory::<Own>() = own;
accepted
});
let finish = if shown.accepted.is_some() {
Some(PrintFinish::Print)
@@ -624,9 +856,9 @@ impl<'a> PrintDialog<'a> {
moved,
refresh,
requests: shown.requests,
presets: Vec::new(), // P3(export-w7): ex.E54
sheet: None,
setup: false,
presets: preset_events,
sheet: stepped,
setup,
}
}
}
@@ -643,6 +875,16 @@ pub struct PrintAnswer {
pub fields: DialogFields,
}
/// The preset rows the host listed, the one the settings started from and the built-in names.
struct HeldPresets {
rows: Vec<PresetRow<String>>,
held: Option<String>,
built_in: Vec<String>,
}
/// The check on a typed preset name, as the host gave it.
type NameFn = dyn Fn(&str) -> Option<PresetError> + Send;
/// The print dialog owned by a `DialogHost` (not registered). It polls its [`State`] each pass,
/// asks the app for a printer list with [`take_refresh`](Self::take_refresh) and takes the list
/// with [`listen`](Self::listen).
@@ -656,6 +898,23 @@ pub struct HostedPrint {
refresh: bool,
requests: HostRequests,
json_form: Option<Box<JsonForm>>,
layout: PrintLayout,
mode: PrintMode,
header: Vec<Param>,
check_name: Option<Box<NameFn>>,
presets: Option<HeldPresets>,
preset_events: Vec<NamedPresetEvent<String>>,
message: Option<Label>,
/// The title of the shown section; one the list does not have shows the first.
section: String,
sheet_index: usize,
preset_name: String,
driver: bool,
setup: bool,
/// `choice: "done"` came in: the next `confirm` answers Done.
done_chosen: bool,
/// OK files its answer for the host to take instead of closing.
hold: bool,
/// The OK the host holds back until it answers `answer_ok`, and its refusal.
held: HeldAnswer<PrintAnswer>,
}
@@ -676,63 +935,82 @@ impl HostedPrint {
refresh: true,
requests: HostRequests::new(),
json_form: None,
layout: PrintLayout::default(),
mode: PrintMode::default(),
header: Vec::new(),
check_name: None,
presets: None,
preset_events: Vec::new(),
message: None,
section: String::new(),
sheet_index: 0,
preset_name: String::new(),
driver: false,
setup: false,
done_chosen: false,
hold: false,
held: HeldAnswer::new(),
}
}
/// How the sections are arranged.
#[must_use]
pub fn layout(self, layout: PrintLayout) -> Self {
let _ = layout;
todo!("ex.E55")
pub fn layout(mut self, layout: PrintLayout) -> Self {
self.layout = layout;
self
}
/// What the dialog is for.
#[must_use]
pub fn mode(self, mode: PrintMode) -> Self {
let _ = mode;
todo!("ex.E55")
pub fn mode(mut self, mode: PrintMode) -> Self {
self.mode = mode;
self
}
/// Rows above the sections.
#[must_use]
pub fn header(self, header: Vec<Param>) -> Self {
let _ = header;
todo!("ex.E55")
pub fn header(mut self, header: Vec<Param>) -> Self {
self.header = header;
self
}
/// Whether a typed preset name may be used, in the preset editor.
#[must_use]
pub fn check_name(self, check: impl Fn(&str) -> Option<PresetError> + Send + 'static) -> Self {
let _ = check;
todo!("ex.E55")
pub fn check_name(mut self, check: impl Fn(&str) -> Option<PresetError> + Send + 'static) -> Self {
self.check_name = Some(Box::new(check));
self
}
/// Shows the driver's Setup… button in the printer row; [`take_setup`](Self::take_setup) reports its press.
#[must_use]
pub fn driver(mut self, driver: bool) -> Self {
self.driver = driver;
self
}
/// The print presets the preset row lists, the one the settings started from, and the built-in names.
pub fn set_presets(&mut self, rows: Vec<PresetRow<String>>, held: Option<String>, built_in: Vec<String>) {
let _ = (rows, held, built_in);
todo!("ex.E55")
self.presets = Some(HeldPresets { rows, held, built_in });
}
/// What the user did to the print presets since the last call.
pub fn take_preset_events(&mut self) -> Vec<NamedPresetEvent<String>> {
todo!("ex.E55")
std::mem::take(&mut self.preset_events)
}
/// A line of the host's under the preview.
pub fn set_message(&mut self, message: Option<Label>) {
let _ = message;
todo!("ex.E55")
self.message = message;
}
/// The number of the sheet the preview shows.
pub fn sheet_index(&self) -> usize {
todo!("ex.E55")
self.sheet_index
}
/// The preset editor's name.
pub fn preset_name(&self) -> &str {
todo!("ex.E55")
&self.preset_name
}
/// The sections' values.
@@ -740,34 +1018,34 @@ impl HostedPrint {
&self.fields
}
/// Sets the section value `key`.
/// Sets the section value `key`, unchecked: the app writes a value its own custom row holds.
pub fn set_field(&mut self, key: impl Into<String>, value: FieldValue) {
let _ = (key, value);
todo!("ex.E55")
let key: String = key.into();
self.fields.set(&key, value);
}
/// Print Settings… was pressed since the last call: the host opens the driver's own dialog.
pub fn take_setup(&mut self) -> bool {
todo!("ex.E56")
std::mem::take(&mut self.setup)
}
/// Makes OK file its answer for the host to take instead of closing: the host checks it and answers with
/// [`answer_ok`](HostedPrint::answer_ok). OK stays disabled until then.
#[must_use]
pub fn held_ok(self) -> Self {
todo!("ex.E55")
pub fn held_ok(mut self) -> Self {
self.hold = true;
self
}
/// The OK filed by a held dialog, once.
pub fn take_ok(&mut self) -> Option<PrintAnswer> {
todo!("ex.E55")
self.held.take()
}
/// The host's answer to the held OK: `Ok` closes the dialog with the held answer in the next pass; `Err` enables
/// OK again and shows the label until a value changes.
pub fn answer_ok(&mut self, answer: Result<(), Label>) {
let _ = answer;
todo!("ex.E55")
self.held.answer(answer);
}
/// Lists keys the sections' values do not show as they are: `form` gets the values and the listing, and may replace or
@@ -795,7 +1073,7 @@ impl HostedPrint {
self.state.listen(printers)
}
/// This pass's layout, from the app; `None` shows the dialog without a preview.
/// This pass's layout, from the app; `None` shows the dialog without a preview, and the message in its place.
pub fn set_sheet(&mut self, sheet: Option<PrintSheet>) {
self.sheet = sheet;
}
@@ -819,6 +1097,31 @@ impl HostedPrint {
fn answer(&self, finish: PrintFinish) -> PrintAnswer {
PrintAnswer { finish, settings: self.state.settings.clone(), fields: self.fields.clone() }
}
/// Whether the dialog's OK can answer now: a job can start, or in the editor the name can be saved.
fn can_answer(&self) -> bool {
match self.mode {
PrintMode::Print => self.state.ready(),
PrintMode::PresetEditor => usable_name(&self.preset_name, self.check_name.as_ref().and_then(|check| check(&self.preset_name))),
}
}
/// Answers with `finish`: the answer itself, or none while the host holds OK and takes it from `take_ok`.
fn conclude(&mut self, finish: PrintFinish) -> Option<PrintAnswer> {
let answer = self.answer(finish);
if self.hold {
self.held.file(answer);
None
} else {
Some(answer)
}
}
/// The title of the shown section: the one named, else the first.
fn shown_section(&self) -> Option<&str> {
let named = self.sections.iter().map(|section| section.title.as_str()).find(|title| *title == self.section);
named.or_else(|| self.sections.first().map(|section| section.title.as_str()))
}
}
impl HoldsOk for HostedPrint {
@@ -868,24 +1171,58 @@ impl StackDialog for HostedPrint {
self.id
}
/// Polls the state, shows the dialog over the sheet the app set, and keeps the drags, the Refresh press and the
/// sections' requests for the app. A pass before the first `set_sheet` shows nothing.
/// Polls the state, shows the dialog over the sheet the app set (the message without one), and keeps the drags, the
/// presses, the preset events and the sections' requests for the app. A held OK the app accepted closes the dialog
/// in the pass after, never in a measuring run.
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<PrintAnswer>> {
self.state.poll(ui.ctx());
let sheet = self.sheet.as_ref()?;
let answers = if craft_ui::runtime::measure::active(ui.ctx()) { Vec::new() } else { self.requests.take_answers() };
let measuring = craft_ui::runtime::measure::active(ui.ctx());
if !measuring && let Some(answer) = self.held.finish() {
return Some(DialogResult::Ok(answer));
}
let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
let (busy, discovering, ready) = (self.state.busy(), self.state.discovering(), self.state.ready());
let shown = PrintDialog::new(Bind::bound(&mut self.state.settings), &self.state.printers, Bind::bound(&mut self.fields))
.sheet(sheet)
let waiting = self.held.is_waiting();
let refusal = self
.held
.refusal()
.filter(|(_, refused)| refused.fields == self.fields && refused.settings == self.state.settings)
.map(|(reason, _)| reason.clone());
let mut dialog = PrintDialog::new(Bind::bound(&mut self.state.settings), &self.state.printers, Bind::bound(&mut self.fields))
.sections(&self.sections)
.busy(busy)
.discovering(discovering)
.ready(ready)
.ready(ready && !waiting)
.answers(answers)
.show(ui);
let PrintDialogOutput { closed, finish, moved, refresh, mut requests, .. } = shown;
.layout(self.layout)
.mode(self.mode)
.header(&self.header)
.driver(self.driver)
.hold(self.hold)
.sheet_index(Bind::bound(&mut self.sheet_index))
.section(Bind::bound(&mut self.section))
.preset_name(Bind::bound(&mut self.preset_name));
if let Some(sheet) = &self.sheet {
dialog = dialog.sheet(sheet);
}
if let Some(message) = &self.message {
dialog = dialog.message(message.clone());
}
if let Some(reason) = refusal {
dialog = dialog.refusal(reason);
}
if let Some(held) = &self.presets {
dialog = dialog.presets(PrintPresets::new(&held.rows, held.held.clone(), &held.built_in));
}
if let Some(check) = &self.check_name {
dialog = dialog.check_name(move |name| check(name));
}
let shown = dialog.show(ui);
let PrintDialogOutput { closed, finish, moved, refresh, mut requests, presets, setup, .. } = shown;
self.moves.extend(moved);
self.refresh |= refresh;
self.setup |= setup;
self.preset_events.extend(presets);
if let Some(request) = requests.take_color() {
self.requests.request_color(request);
}
@@ -899,7 +1236,7 @@ impl StackDialog for HostedPrint {
self.requests.request_preview_click(point);
}
match (finish, closed) {
(Some(finish), _) => Some(DialogResult::Ok(self.answer(finish))),
(Some(finish), _) => self.conclude(finish).map(DialogResult::Ok),
(None, Some(_)) => Some(DialogResult::Cancel),
(None, None) => None,
}
@@ -909,13 +1246,25 @@ impl StackDialog for HostedPrint {
self.held.state()
}
/// Answers Print as the button does: none while a job cannot start.
/// Answers Done after `choice: "done"`, else Print as the button does: none while a job cannot start (in the preset
/// editor, while the name cannot be saved), and none while the host still holds an answer.
fn confirm(&mut self, _: &egui::Context) -> Option<PrintAnswer> {
self.state.ready().then(|| self.answer(PrintFinish::Print))
if self.held.is_waiting() {
return None;
}
let finish = if std::mem::take(&mut self.done_chosen) {
PrintFinish::Done
} else if self.can_answer() {
PrintFinish::Print
} else {
return None;
};
self.conclude(finish)
}
/// The `Settings` keys (`printer`, `copies`, `duplex`, `grayscale`) and each section parameter's value as
/// [`DialogFields`] serializes it.
/// The `Settings` keys (`printer`, `copies`, `duplex`, `grayscale`), each section parameter's value as
/// [`DialogFields`] serializes it, and the dialog's own: `section` (the shown section), `sheet`, `preset` (the held
/// preset) and, in the preset editor, `name`.
fn json_fields(&self) -> Option<serde_json::Value> {
let mut map = match serde_json::to_value(&self.fields).ok()? {
serde_json::Value::Object(map) => map,
@@ -926,13 +1275,21 @@ impl StackDialog for HostedPrint {
map.insert("copies".to_owned(), settings.copies.into());
map.insert("duplex".to_owned(), duplex_json(settings.duplex));
map.insert("grayscale".to_owned(), settings.grayscale.into());
map.insert("section".to_owned(), self.shown_section().map_or(serde_json::Value::Null, Into::into));
map.insert("sheet".to_owned(), self.sheet_index.into());
let held = self.presets.as_ref().and_then(|presets| presets.held.clone());
map.insert("preset".to_owned(), held.map_or(serde_json::Value::Null, Into::into));
if self.mode == PrintMode::PresetEditor {
map.insert("name".to_owned(), self.preset_name.clone().into());
}
if let Some(form) = &self.json_form {
form(&self.fields, &mut map);
}
Some(serde_json::Value::Object(map))
}
/// Sets a `Settings` key, or a section parameter through the shared parameter-field rule.
/// Sets a `Settings` key, the dialog's own (`section`, `sheet`, `name`, `preset`, and `choice` = `"done"`), or a
/// section parameter through the shared parameter-field rule.
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
match field {
"printer" => {
@@ -946,6 +1303,40 @@ impl StackDialog for HostedPrint {
}
"duplex" => self.state.settings.duplex = duplex_from_json(&value).ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?,
"grayscale" => self.state.settings.grayscale = value.as_bool().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?,
"choice" => {
if self.mode != PrintMode::Print {
return Err(FieldRefusal::Inactive.message(field));
}
if value.as_str() != Some("done") {
return Err(FieldRefusal::Rejects(&value).message(field));
}
self.done_chosen = true;
}
"section" => {
if self.layout != PrintLayout::Sections {
return Err(FieldRefusal::Inactive.message(field));
}
let title = value.as_str().filter(|title| self.sections.iter().any(|section| section.title.as_str() == *title));
self.section = title.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?.to_owned();
}
"sheet" => {
let count = self.sheet.as_ref().map(|sheet| sheet.count).filter(|count| *count > 0);
let count = count.ok_or_else(|| FieldRefusal::Inactive.message(field))?;
let index = value.as_u64().and_then(|index| usize::try_from(index).ok());
self.sheet_index = index.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?.min(count - 1);
}
"name" => {
if self.mode != PrintMode::PresetEditor {
return Err(FieldRefusal::Inactive.message(field));
}
self.preset_name = value.as_str().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?.to_owned();
}
"preset" => {
let known = |name: &str| self.presets.as_ref().is_some_and(|presets| presets.rows.iter().any(|row| !row.is_group() && row.key == name));
let name = value.as_str().filter(|name| known(name));
let name = name.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.preset_events.push(NamedPresetEvent::Apply(name.to_owned()));
}
_ => {
let section =
self.sections.iter().find(|section| section.params.iter().any(|param| param.key == field || param.unit_key() == Some(field)));
+1 -2
View File
@@ -58,8 +58,7 @@ impl Printer {
impl From<crate::Printer> for Printer {
/// The dialog's printer for a discovered one: `name`, the `description` as the label, and `default`.
fn from(printer: crate::Printer) -> Self {
let _ = printer;
todo!("ex.E58")
Printer { name: printer.name, label: printer.description, default: printer.default }
}
}
+9 -2
View File
@@ -34,6 +34,7 @@ craft_ui::words! {
portrait: "printPanel.portrait" = "Portrait";
landscape: "printPanel.landscape" = "Landscape";
page_in_driver: "printPanel.pageInDriver" = "set in Print Settings…";
setup: "printPanel.setup" = "Setup…";
}
}
@@ -103,7 +104,6 @@ pub struct PrintPanel<'a> {
page_error: Option<String>,
/// Which controls the panel shows.
#[prop]
#[allow(dead_code)] // P3(export-w7): ex.E56
layout: PrintPanelLayout,
}
@@ -124,7 +124,7 @@ impl<'a> PrintPanel<'a> {
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> PrintPanelOutput {
let PrintPanel { settings, printers, discovering, busy, driver, page, page_error, layout: _ } = self;
let PrintPanel { settings, printers, discovering, busy, driver, page, page_error, layout } = self;
let env = Env::of(ui);
let words = env.words::<PrintWords>();
let queues: Vec<Entry<String>> =
@@ -157,8 +157,15 @@ impl<'a> PrintPanel<'a> {
}
let button = Button::new(words.refresh.clone()).enabled(!discovering).id_salt("refresh").show(ui);
refresh |= clicked(&button);
if layout == PrintPanelLayout::PrinterOnly && driver {
let button = Button::new(words.setup.clone()).id_salt("setup").show(ui);
settings_clicked |= clicked(&button);
}
});
});
if layout == PrintPanelLayout::PrinterOnly {
return (now != before).then_some((before, now));
}
Field::new(words.copies.clone()).id_salt("copies").show(ui, |ui, _| {
if let Some(copies) = copies_field(&words.copies, now.copies).show(ui).value().copied().flatten() {
now.copies = (copies.round() as u32).clamp(1, MOST_COPIES);
+67 -5
View File
@@ -1,9 +1,10 @@
//! Stories of `PrintPanel` and `PrintDialog`.
use super::dialog::PrintPreview;
use super::{Duplex, PrintDialog, PrintMarks, PrintPanel, PrintSheet, Printer, Settings};
use super::{Duplex, PrintDialog, PrintLayout, PrintMarks, PrintMode, PrintPanel, PrintPanelLayout, PrintPresets, PrintSection, PrintSheet, Printer, Settings};
use craft_ui::contract::{Bind, Show as _, Validity};
use craft_ui::patterns::form_dialogs::DialogFields;
use craft_ui::patterns::form_dialogs::{DialogFields, Param};
use craft_ui::patterns::presets::{PresetError, PresetRow};
use craft_ui::primitives::TextureCache;
use craft_ui::runtime::env::Message;
use craft_ui::testing::pictures::sample_picture;
@@ -31,6 +32,13 @@ fn print_panel_discovering(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
PrintPanel::new(Bind::bound(data.value("settings", Settings::default())), &[]).discovering(true).show(ui).into()
}
#[story(PrintPanel<'static>, covers = [], drive = Drive::Never)]
fn print_panel_printer_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = Settings { printer: "Office_1".to_owned(), ..Settings::default() };
let printers = printers();
PrintPanel::new(Bind::bound(data.value("settings", start)), &printers).layout(PrintPanelLayout::PrinterOnly).driver(true).show(ui).into()
}
const PICTURE: [usize; 2] = [240, 160];
/// A letter sheet with the image box inset one inch, the printable area and, with `marks`, corner crop and registration
@@ -84,14 +92,68 @@ fn print_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.sheet(&sheet)
.ready(true)
.show(ui)
.into() // P3(export-w7): ex.E52
.into()
}
/// The sections beside the shown one, with a preset row, a one-line header and a document on three sheets.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_sections(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = Settings { printer: "Office_1".to_owned(), ..Settings::default() };
let printers = printers();
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
let outlines = vec![Rect::from_min_size(pos2(36.0, 36.0), Vec2::new(540.0, 720.0)), Rect::from_min_size(pos2(72.0, 72.0), Vec2::new(468.0, 312.0))];
let sheet = sheet(ui, true).count(3).outlines(outlines);
let rows = [PresetRow::item("Default".to_owned(), "Default", 0), PresetRow::item("Proof".to_owned(), "Proof", 0)];
let built_in = ["Default".to_owned()];
let header = [Param::number("pagesPerSheet", "Pages per sheet", 1.0, 1.0, 0)];
let sections = [
PrintSection::new("Position and Size", vec![Param::number("scale", "Scale", 100.0, 1.0, 0)]),
PrintSection::new("Printing Marks", vec![Param::number("markWeight", "Mark weight", 0.25, 0.25, 2)]),
];
PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()))
.layout(PrintLayout::Sections)
.sheet(&sheet)
.presets(PrintPresets::new(&rows, Some("Proof".to_owned()), &built_in))
.header(&header)
.sections(&sections)
.driver(true)
.ready(true)
.show(ui)
.into()
}
/// The sections layout while the host has no sheet to show: its message stands where the preview would.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_sections_no_sheet(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sections = [PrintSection::new("Position and Size", vec![Param::number("scale", "Scale", 100.0, 1.0, 0)])];
PrintDialog::new(Bind::bound(data.value("settings", Settings::default())), &printers, Bind::given(DialogFields::default()))
.layout(PrintLayout::Sections)
.message("The document has no printable artwork")
.sections(&sections)
.show(ui)
.into()
}
/// The preset editor: a name field whose refusal shows under it.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_preset_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let sections = [PrintSection::new("Position and Size", vec![Param::number("scale", "Scale", 100.0, 1.0, 0)])];
PrintDialog::new(Bind::bound(data.value("settings", Settings::default())), &[], Bind::given(DialogFields::default()))
.layout(PrintLayout::Sections)
.mode(PrintMode::PresetEditor)
.preset_name(Bind::bound(data.value("name", "Default".to_owned())))
.check_name(|name| name.eq_ignore_ascii_case("Default").then_some(PresetError::NameTaken))
.sections(&sections)
.show(ui)
.into()
}
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_discovering(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let sheet = sheet(ui, false);
PrintDialog::new(Bind::bound(data.value("settings", Settings::default())), &[], Bind::given(DialogFields::default()))
.sheet(&sheet) // P3(export-w7): ex.E52
.sheet(&sheet)
.discovering(true)
.show(ui)
.into()
@@ -106,5 +168,5 @@ fn print_dialog_busy(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.sheet(&sheet)
.busy(true)
.show(ui)
.into() // P3(export-w7): ex.E52
.into()
}
+74 -3
View File
@@ -4,10 +4,11 @@ use std::cell::RefCell;
use std::rc::Rc;
use craft_behavior::EditEvent;
use craft_print::ui::{HostedPrint, PrintDialog, PrintSheet, Printer, Settings, State};
use craft_print::ui::{HostedPrint, PrintDialog, PrintFinish, PrintSheet, Printer, Settings, State};
use craft_ui::contract::Bind;
use craft_ui::dialog::StackDialog as _;
use craft_ui::dialog::{DialogHost, HeldOk, StackDialog as _};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue};
use craft_ui::patterns::presets::{NamedPresetEvent, PresetRow};
use craft_ui::primitives::TextureCache;
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
@@ -36,7 +37,7 @@ fn rig(paper: Vec2) -> (Fixture, Log) {
let mut fixture = Fixture::new(move |ui| {
let image = Rect::from_min_size(IMAGE_AT, IMAGE_SIZE);
let sheet = PrintSheet::new(paper, image, picture(ui), "200 × 300 pt".into());
let out = PrintDialog::new(Bind::bound(&mut settings), &printers, Bind::bound(&mut fields)).sheet(&sheet).ready(true).show(ui); // P3(export-w7): ex.E52
let out = PrintDialog::new(Bind::bound(&mut settings), &printers, Bind::bound(&mut fields)).sheet(&sheet).ready(true).show(ui);
seen.borrow_mut().extend(out.moved);
// Every frame runs twice; the second pass has no new input, and a repeated move would show in the log.
if ui.ctx().current_pass_index() == 0 {
@@ -124,3 +125,73 @@ fn the_json_form_adds_to_the_listing() {
assert_eq!(listed["paper"], serde_json::json!([432.0, 792.0]));
assert!(listed.get("copies").is_some(), "the settings keys stay");
}
/// A hosted print dialog on a three-sheet document, run through a `DialogHost`.
fn hosted() -> (Fixture, Rc<RefCell<DialogHost>>) {
let host = Rc::new(RefCell::new(DialogHost::new()));
host.borrow_mut().open(HostedPrint::new(State::default(), DialogFields::default(), Vec::new()));
let shared = host.clone();
let mut fixture = Fixture::new(move |ui| {
let image = Rect::from_min_size(IMAGE_AT, IMAGE_SIZE);
let sheet = PrintSheet::new(vec2(612.0, 792.0), image, picture(ui), "200 × 300 pt".into()).count(3);
let mut host = shared.borrow_mut();
if let Some(dialog) = host.get_mut::<HostedPrint>() {
dialog.set_sheet(Some(sheet));
}
host.run(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0));
fixture.settle();
(fixture, host)
}
fn shown_sheet(host: &Rc<RefCell<DialogHost>>) -> usize {
host.borrow().get::<HostedPrint>().expect("the dialog is open").sheet_index()
}
/// `choice: "done"` makes the next `confirm` answer Done once, any other choice is refused, and the sheet step moves the
/// shown sheet by its buttons and by the `sheet` field, which clamps to the last sheet.
#[trial]
fn done_by_automation_and_the_sheet_step() {
let (mut fixture, host) = hosted();
let ctx = egui::Context::default();
assert_eq!(shown_sheet(&host), 0);
for expected in [1, 2, 2] {
let next = fixture.by_label("Next").expect("the step row has Next");
fixture.click(&next);
assert_eq!(shown_sheet(&host), expected, "Next steps to the next sheet and stops at the last");
}
let previous = fixture.by_label("Previous").expect("the step row has Previous");
fixture.click(&previous);
assert_eq!(shown_sheet(&host), 1);
let mut host = host.borrow_mut();
let dialog = host.get_mut::<HostedPrint>().expect("the dialog is open");
dialog.set_json_field(&ctx, "sheet", serde_json::json!(9)).expect("an index past the end is clamped");
assert_eq!(dialog.sheet_index(), 2);
assert!(dialog.set_json_field(&ctx, "sheet", serde_json::json!("two")).is_err());
assert!(dialog.set_json_field(&ctx, "choice", serde_json::json!("print")).is_err(), "only done is a choice");
let ready = State::default().ready();
dialog.set_json_field(&ctx, "choice", serde_json::json!("done")).expect("done is a choice");
assert_eq!(dialog.confirm(&ctx).map(|answer| answer.finish), Some(PrintFinish::Done), "Done answers even while a job cannot start");
assert_eq!(dialog.confirm(&ctx).map(|answer| answer.finish), ready.then_some(PrintFinish::Print), "the choice is used up");
}
/// A refused held OK keeps the dialog open with the reason, and a preset the row does not list is refused by name.
#[trial]
fn a_refused_print_keeps_the_dialog_open_and_presets_are_named() {
let ctx = egui::Context::default();
let mut dialog = HostedPrint::new(State::default(), DialogFields::default(), Vec::new()).held_ok();
dialog.set_json_field(&ctx, "choice", serde_json::json!("done")).expect("done is a choice");
assert!(dialog.confirm(&ctx).is_none(), "a held OK files its answer");
assert!(matches!(dialog.held_state(), Some(HeldOk::Waiting)));
assert!(dialog.take_ok().is_some());
dialog.answer_ok(Err("No printer".into()));
assert!(matches!(dialog.held_state(), Some(HeldOk::Refused(_))), "the refusal keeps the dialog open");
dialog.set_presets(vec![PresetRow::item("proof".to_owned(), "Proof", 0)], None, Vec::new());
assert!(dialog.set_json_field(&ctx, "preset", serde_json::json!("missing")).is_err());
dialog.set_json_field(&ctx, "preset", serde_json::json!("proof")).expect("a listed preset applies");
assert_eq!(dialog.take_preset_events(), vec![NamedPresetEvent::Apply("proof".to_owned())]);
}