dialogs-w16: net change of 8 commits

- dialogs-w16: written from its sheet
- dialogs-w16: repair 1
- dialogs-w16: review fixes (review-1)
- dialogs-w16: review fixes (item 1, 6)
- dialogs-w16: review fixes (item 6)
- dialogs-w16: the print preview's style is as visible as the preview (combine)
- dialogs-w16: the preview's release ends only a running drag; its output reports its edits to the suite (dialogs run round)
- dialogs-w16: the print preview's value is the image box position, which a drag moves from the gesture's start and a host check can refuse (dialogs run round)
This commit is contained in:
aiongg
2026-11-15 04:46:07 +00:00
parent d3257f265a
commit 2fde380ed6
6 changed files with 648 additions and 54 deletions
+10 -2
View File
@@ -234,8 +234,16 @@ plus discovery and submission receivers. Hosts supply `Discover` and `Submit` wo
the state nor the controls invokes an OS spooler or generates PDF content. Apps map `Settings`
to ``Job`` and own the Print action, page selection, preview and export behavior.
`State::show` takes a stable `egui::Id` and app-localized `Labels`. It draws the settings only;
apps render typed `Feedback` using their own translations. `poll` requests occasional repaints
`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,
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.
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.
An empty or failed discovery cannot leave a stale printer ready to submit.
+416 -44
View File
@@ -1,20 +1,28 @@
//! `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`.
#![allow(clippy::todo)] // P3(dialogs-w16): dl.K44 bodies.
use std::sync::mpsc::Receiver;
use craft_behavior::{EditEvent, EditEvents};
use craft_ui::contract::{Bind, NoValue, Outcome};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::patterns::form_dialogs::{DialogFields, HostRequests, Param};
use craft_ui::runtime::env::Label;
use craft_behavior::{CursorIcon, EditEvent, EditEvents, Metrics, Mixed, PartKey, PointerButton, PressPhase, Sense};
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 _,
};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::display::Text;
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::runtime::env::{Env, Label};
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};
use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleCx, SurfaceKind};
use egui::load::SizedTexture;
use egui::{Response, Ui};
use egui::{Pos2, Rect, Response, Ui, Vec2, pos2, vec2};
use super::{Printer, Settings, State};
use super::panel::{MOST_COPIES, PrintPanel};
use super::{Duplex, Printer, Settings, State};
craft_ui::words! {
/// The words of the print dialog.
@@ -23,9 +31,20 @@ craft_ui::words! {
print: "printDialog.print" = "Print";
done: "printDialog.done" = "Done";
preview: "printDialog.preview" = "Print preview";
image_box: "printDialog.imageBox" = "Image box";
}
}
/// The index `FormOutput::picked` gives the Done button: Print is 0, Cancel 1, and the extra buttons start at 2.
const DONE_BUTTON: usize = 2;
/// The image box of the preview.
const IMAGE: PartKey = PartKey::new("image");
/// How far a crop or registration mark stands from the image box, and how long it is, in screen points.
const MARK_GAP: f32 = 4.0;
const MARK_LEN: f32 = 10.0;
/// Which marks the preview draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PrintMarks {
@@ -62,26 +81,22 @@ pub struct PrintSheet {
impl PrintSheet {
/// A sheet of `paper` with the image box `image` holding `picture`, `readout` under the preview, no printable area
/// and no marks.
// P3(dialogs-w16): dl.K44 `PrintSheet::new`
pub fn new(paper: egui::Vec2, image: egui::Rect, picture: SizedTexture, readout: Label) -> Self {
let _ = (paper, image, picture, readout);
todo!("dl.K44")
PrintSheet { paper, printable: None, image, picture, marks: PrintMarks::default(), readout }
}
/// The printable area of the paper.
// P3(dialogs-w16): dl.K44 builder
#[must_use]
pub fn printable(self, area: egui::Rect) -> Self {
let _ = (self, area);
todo!("dl.K44")
pub fn printable(mut self, area: egui::Rect) -> Self {
self.printable = Some(area);
self
}
/// The marks to draw.
// P3(dialogs-w16): dl.K44 builder
#[must_use]
pub fn marks(self, marks: PrintMarks) -> Self {
let _ = (self, marks);
todo!("dl.K44")
pub fn marks(mut self, marks: PrintMarks) -> Self {
self.marks = marks;
self
}
}
@@ -103,6 +118,217 @@ pub enum PrintFinish {
Done,
}
/// Where the paper stands in the preview's room: the paper's top-left corner and the screen points per paper point.
#[derive(Clone, Copy)]
struct Placement {
origin: Pos2,
scale: f32,
}
impl Placement {
/// The screen rect of `paper`, a rect in paper points.
fn rect(self, paper: Rect) -> Rect {
Rect::from_min_size(self.origin + paper.min.to_vec2() * self.scale, paper.size() * self.scale)
}
}
/// The style of the preview: the room it asks for.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub(super) struct PrintPreviewStyle {
#[style(metrics)]
metrics: Metrics,
}
/// The paper, its printable area, the picture in its box and the marks. The value is where the image box's top-left
/// corner stands on the paper, in paper points; a drag of the image box reports the positions it moves the box to as
/// one gesture, and a host check can refuse a position.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(content_painter)]
pub(super) struct PrintPreview<'a> {
#[common]
common: Common,
sheet: &'a PrintSheet,
/// The image box's top-left corner on the paper, in paper points.
position: Bind<'a, Pos2>,
}
impl<'a> PrintPreview<'a> {
pub(super) fn new(label: impl Into<Label>, sheet: &'a PrintSheet, position: Bind<'a, Pos2>) -> Self {
PrintPreview { common: Common::new(), sheet, position }.label(label)
}
/// The paper fitted in `room`, centred; none while the paper has no area.
fn place(&self, room: Rect) -> Option<Placement> {
let paper = self.sheet.paper;
if !(paper.x > 0.0 && paper.y > 0.0) {
return None;
}
let scale = (room.width() / paper.x).min(room.height() / paper.y);
if !(scale.is_finite() && scale > 0.0) {
return None;
}
Some(Placement { origin: room.center() - paper * scale / 2.0, scale })
}
}
impl Component for PrintPreview<'_> {
const ROLE: Role = Role::GROUP;
const OVERLAYS: bool = false;
/// One image box: its position has no mixed state.
const SINGLE_VALUE: bool = true;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
type Style = PrintPreviewStyle;
type Output = PrintPreviewOutput;
fn style(_: &StyleCx<'_>, _: PrintPreviewStyleKey) -> PrintPreviewStyle {
PrintPreviewStyle { metrics: Metrics::new() }
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let width = cx.tokens.size.plot.width;
let paper = self.sheet.paper;
let aspect = if paper.x > 0.0 && paper.y > 0.0 { paper.y / paper.x } else { 1.0 };
Vec2::new(width, width * aspect)
}
fn bind(&mut self) -> Option<BindMut<'_, Pos2>> {
Some(self.position.reborrow())
}
/// The image box stays where the sheet puts it while it is dragged: the picture follows the pointer, the part does
/// not, so the press keeps its hit.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let Some(place) = self.place(rect) else { return };
let part = cx.part(IMAGE, place.rect(self.sheet.image)).sense(Sense::DRAG).pointer_only("the Position and Size rows place the image");
part.cursor(CursorIcon::Move);
}
/// Every phase of a press carries the press point and the gesture keeps the position it began from, so the drag
/// reads both, keeping nothing across passes. Only a running drag takes the release: a part that senses no click
/// reports `click: false` within the slop too.
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let Some(place) = self.place(cx.rect) else { return };
let Some(result) = cx.part_if_declared(IMAGE) else { return };
let phase = result.press.phase;
let moved = |cx: &Cx<'_, Self>, start: craft_behavior::PressStart, pos: Pos2| match cx.gesture_before()? {
Mixed::Same(from) => Some(from + (pos - start.origin) / place.scale),
Mixed::Mixed => None,
};
match phase {
PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => {
cx.begin();
if let Some(at) = moved(cx, start, pos) {
cx.propose(at);
}
}
PressPhase::Drag { start, pos, .. } | PressPhase::Release { start, pos, .. } if start.button == PointerButton::Primary => {
if let Some(at) = moved(cx, start, pos) {
cx.propose(at);
if matches!(phase, PressPhase::Release { .. }) {
cx.commit();
}
}
}
_ => {}
}
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let words = cx.words::<PrintDialogWords>();
let node = access.node(IMAGE, Role::BUTTON);
node.name = Name::Text(words.image_box.as_str().to_owned());
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(place) = self.place(cx.rect) else { return };
let sheet = self.sheet;
let position = cx.value().copied().unwrap_or(sheet.image.min);
let painter = ui.content_painter(cx);
let rule = |kind: RuleKind, from: Pos2, to: Pos2| painter.with_draw(|draw| draw.rule(kind, from, to));
let outline = |kind: RuleKind, rect: Rect| {
rule(kind, rect.left_top(), rect.right_top());
rule(kind, rect.right_top(), rect.right_bottom());
rule(kind, rect.right_bottom(), rect.left_bottom());
rule(kind, rect.left_bottom(), rect.left_top());
};
let paper = place.rect(Rect::from_min_size(Pos2::ZERO, sheet.paper));
painter.surface(cx.rect, SurfaceKind::Well, Corners::None);
painter.surface(paper, SurfaceKind::Canvas, Corners::None);
let image = place.rect(Rect::from_min_size(position, sheet.image.size()));
let visible = image.intersect(paper);
if image.width() > 0.0 && image.height() > 0.0 && visible.width() > 0.0 && visible.height() > 0.0 {
let uv = Rect::from_min_max(
pos2((visible.min.x - image.min.x) / image.width(), (visible.min.y - image.min.y) / image.height()),
pos2((visible.max.x - image.min.x) / image.width(), (visible.max.y - image.min.y) / image.height()),
);
painter.picture(sheet.picture.id, visible, uv, 0.0);
}
if let Some(area) = sheet.printable {
outline(RuleKind::Grid, place.rect(area));
}
outline(RuleKind::Edge, paper);
outline(RuleKind::DropMark, image);
let marks = sheet.marks;
let sides = [(image.center_top(), vec2(0.0, -1.0)), (image.center_bottom(), vec2(0.0, 1.0)), (image.left_center(), vec2(-1.0, 0.0)), (image.right_center(), vec2(1.0, 0.0))];
if marks.corner_crop {
let corners = [(image.left_top(), -1.0, -1.0), (image.right_top(), 1.0, -1.0), (image.left_bottom(), -1.0, 1.0), (image.right_bottom(), 1.0, 1.0)];
for (corner, sx, sy) in corners {
rule(RuleKind::Edge, corner + vec2(sx * MARK_GAP, 0.0), corner + vec2(sx * (MARK_GAP + MARK_LEN), 0.0));
rule(RuleKind::Edge, corner + vec2(0.0, sy * MARK_GAP), corner + vec2(0.0, sy * (MARK_GAP + MARK_LEN)));
}
}
if marks.center_crop {
for (middle, out) in sides {
rule(RuleKind::Edge, middle + out * MARK_GAP, middle + out * (MARK_GAP + MARK_LEN));
}
}
if marks.registration {
let half = MARK_LEN / 2.0;
for (middle, out) in sides {
let at = middle + out * (MARK_GAP * 2.0 + MARK_LEN * 1.5);
rule(RuleKind::Edge, at - vec2(half, 0.0), at + vec2(half, 0.0));
rule(RuleKind::Edge, at - vec2(0.0, half), at + vec2(0.0, half));
}
}
// The description and the labels are text of the printed page; the preview shows where each stands.
if marks.description {
let from = paper.left_bottom() + vec2(MARK_GAP, -MARK_GAP);
rule(RuleKind::Edge, from, from + vec2(MARK_LEN * 3.0, 0.0));
}
if marks.labels {
let from = paper.left_top() + vec2(MARK_GAP, MARK_GAP);
rule(RuleKind::Edge, from, from + vec2(MARK_LEN * 3.0, 0.0));
}
}
fn finish(self, cx: Cx<'_, Self>) -> PrintPreviewOutput {
PrintPreviewOutput { edit: cx.edit_response() }
}
}
/// What the preview reports.
#[derive(Debug)]
pub(super) struct PrintPreviewOutput {
/// The image box drag: `Begin` at the first move past the click slop, `Update` with the image box's position on the
/// paper in paper points, `Commit` at the release.
edit: EditResponse<Pos2>,
}
impl Outcome for PrintPreviewOutput {
type Value = Pos2;
fn response(&self) -> &Response {
&self.edit.response
}
#[cfg(feature = "screen-testing")]
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
self.edit.story_facts()
}
}
/// 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.
@@ -125,6 +351,9 @@ pub struct PrintDialog<'a> {
/// Printer discovery is running.
#[prop]
discovering: bool,
/// A job can start: the caller's `State::ready`, the one rule for it. Print is disabled while it is false.
#[prop]
ready: bool,
/// The host's answers to the dialog's requests.
#[prop]
answers: Vec<HostAnswer>,
@@ -141,9 +370,8 @@ pub struct PrintDialogOutput {
pub closed: Option<CloseReason>,
/// Print or Done was chosen.
pub finish: Option<PrintFinish>,
/// The image box drag as total travel in paper points since the press.
// P3(dialogs-w16): dl.K44 `EditEvents`
pub moved: EditEvents<egui::Vec2>,
/// The image box drag as the box's top-left corner on the paper, in paper points.
pub moved: EditEvents<egui::Pos2>,
/// The panel's Refresh was pressed.
pub refresh: bool,
/// The dialog's requests of the host.
@@ -162,14 +390,64 @@ impl<'a> PrintDialog<'a> {
/// The dialog over `settings`, the `printers` found, the sections' `fields` and this pass's
/// `sheet`.
pub fn new(settings: Bind<'a, Settings>, printers: &'a [Printer], fields: Bind<'a, DialogFields>, sheet: &'a PrintSheet) -> Self {
PrintDialog { settings, printers, fields, sheet, sections: &[], opened: None, busy: false, discovering: false, answers: Vec::new() }
PrintDialog { settings, printers, fields, sheet, sections: &[], opened: None, busy: false, discovering: false, ready: false, answers: Vec::new() }
}
/// Draws the dialog.
/// 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.
pub fn show(self, ui: &mut Ui) -> PrintDialogOutput {
let PrintDialog { settings, printers, fields, sheet, sections, opened, busy, discovering, answers } = self;
let _ = (ui, settings, printers, fields, sheet, sections, opened, busy, discovering, answers);
todo!("dl.K44")
let PrintDialog { mut settings, printers, fields, sheet, sections, opened, busy, discovering, ready, answers } = self;
let env = Env::of(ui);
let words = env.words::<PrintDialogWords>();
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)])
.answers(answers);
if let Some(opened) = opened {
form = form.opened(opened);
}
let mut moved = EditEvents::new();
let mut refresh = false;
let shown = form.show(ui, |ui, form, values| {
moved = EditEvents::new();
refresh = false;
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);
}
}
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, _| {
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);
});
Stack::new().show(ui, |ui, _| {
let panel = PrintPanel::new(settings.reborrowed(), printers).discovering(discovering).busy(busy).show(ui);
refresh |= panel.refresh;
for section in sections {
let mut rows = ParamRows::new(section.title.clone(), &section.params, Bind::bound(&mut *values)).show(ui);
form.requests().absorb(&mut rows);
}
});
});
ready && !busy
});
let finish = if shown.accepted.is_some() {
Some(PrintFinish::Print)
} else if shown.picked == Some(DONE_BUTTON) {
Some(PrintFinish::Done)
} else {
None
};
PrintDialogOutput { response: shown.response, closed: shown.closed, finish, moved, refresh, requests: shown.requests }
}
}
@@ -194,25 +472,26 @@ pub struct HostedPrint {
fields: DialogFields,
sections: Vec<PrintSection>,
sheet: Option<PrintSheet>,
moves: Vec<EditEvent<egui::Vec2>>,
moves: Vec<EditEvent<egui::Pos2>>,
refresh: bool,
requests: HostRequests,
}
impl HostedPrint {
/// The dialog over `state`, the sections' `fields` and the `sections`.
pub fn new(state: State, fields: DialogFields, sections: Vec<PrintSection>) -> Self {
HostedPrint { id: dialog_id("print"), state, fields, sections, sheet: None, moves: Vec::new(), refresh: true }
HostedPrint { id: dialog_id("print"), state, fields, sections, sheet: None, moves: Vec::new(), refresh: true, requests: HostRequests::new() }
}
/// Whether the app should send a printer list: once on the first pass and on each Refresh.
/// Whether the app should send a printer list: once on the first pass and on each Refresh. It answers once: a
/// second pass of the same frame gets `false`, the app having answered in the first.
pub fn take_refresh(&mut self) -> bool {
todo!("dl.K44")
std::mem::take(&mut self.refresh)
}
/// Takes the printer list the app sends; `false` while a discovery or a job runs.
pub fn listen(&mut self, printers: Receiver<Vec<Printer>>) -> bool {
let _ = printers;
todo!("dl.K44")
self.state.listen(printers)
}
/// This pass's layout, from the app.
@@ -221,8 +500,7 @@ impl HostedPrint {
}
/// The image box drags since the last call.
// P3(dialogs-w16): dl.K44 `EditEvents`
pub fn take_moves(&mut self) -> EditEvents<egui::Vec2> {
pub fn take_moves(&mut self) -> EditEvents<egui::Pos2> {
std::mem::take(&mut self.moves).into_iter().collect()
}
@@ -230,6 +508,40 @@ impl HostedPrint {
pub fn fields_mut(&mut self) -> &mut DialogFields {
&mut self.fields
}
/// The colour, Browse and eyedropper requests the sections filed, and where the app answers them.
pub fn requests_mut(&mut self) -> &mut HostRequests {
&mut self.requests
}
/// The answer of the dialog as it stands.
fn answer(&self, finish: PrintFinish) -> PrintAnswer {
PrintAnswer { finish, settings: self.state.settings.clone(), fields: self.fields.clone() }
}
}
/// The automation name of a duplex mode.
fn duplex_json(duplex: Option<Duplex>) -> serde_json::Value {
match duplex {
None => serde_json::Value::Null,
Some(Duplex::Off) => "off".into(),
Some(Duplex::LongEdge) => "long_edge".into(),
Some(Duplex::ShortEdge) => "short_edge".into(),
}
}
/// The duplex mode an automation value names; `None` when it names none.
fn duplex_from_json(value: &serde_json::Value) -> Option<Option<Duplex>> {
match value {
serde_json::Value::Null => Some(None),
serde_json::Value::String(name) => match name.as_str() {
"off" => Some(Some(Duplex::Off)),
"long_edge" => Some(Some(Duplex::LongEdge)),
"short_edge" => Some(Some(Duplex::ShortEdge)),
_ => None,
},
_ => None,
}
}
impl StackDialog for HostedPrint {
@@ -239,22 +551,82 @@ 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.
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<PrintAnswer>> {
let _ = (ui, &self.state, &self.sections, self.refresh);
todo!("dl.K44")
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 (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)
.sections(&self.sections)
.busy(busy)
.discovering(discovering)
.ready(ready)
.answers(answers)
.show(ui);
let PrintDialogOutput { closed, finish, moved, refresh, mut requests, .. } = shown;
self.moves.extend(moved);
self.refresh |= refresh;
if let Some(request) = requests.take_color() {
self.requests.request_color(request);
}
if let Some(request) = requests.take_path() {
self.requests.request_path(request);
}
if let Some(request) = requests.take_eyedropper() {
self.requests.request_eyedropper(request);
}
if let Some(point) = requests.take_preview_click() {
self.requests.request_preview_click(point);
}
match (finish, closed) {
(Some(finish), _) => Some(DialogResult::Ok(self.answer(finish))),
(None, Some(_)) => Some(DialogResult::Cancel),
(None, None) => None,
}
}
fn confirm(&mut self, ctx: &egui::Context) -> Option<PrintAnswer> {
let _ = ctx;
todo!("dl.K44")
/// Answers Print as the button does: none while a job cannot start.
fn confirm(&mut self, _: &egui::Context) -> Option<PrintAnswer> {
self.state.ready().then(|| self.answer(PrintFinish::Print))
}
/// The `Settings` keys (`printer`, `copies`, `duplex`, `grayscale`) and each section parameter's value as
/// [`DialogFields`] serializes it.
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K44")
let mut map = match serde_json::to_value(&self.fields).ok()? {
serde_json::Value::Object(map) => map,
_ => serde_json::Map::new(),
};
let settings = &self.state.settings;
map.insert("printer".to_owned(), settings.printer.clone().into());
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());
Some(serde_json::Value::Object(map))
}
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let _ = (ctx, field, value);
todo!("dl.K44")
/// Sets a `Settings` key, 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" => {
let name = value.as_str().filter(|name| self.state.printers.iter().any(|printer| printer.name == *name));
let name = name.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.state.settings.printer = name.to_owned();
}
"copies" => {
let copies = value.as_u64().and_then(|copies| u32::try_from(copies).ok()).filter(|copies| (1..=MOST_COPIES).contains(copies));
self.state.settings.copies = copies.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
}
"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))?,
_ => {
let section = self.sections.iter().find(|section| section.params.iter().any(|param| param.key == field || param.unit_key() == Some(field)));
let section = section.ok_or_else(|| FieldRefusal::Unknown.message(field))?;
return set_param_field(&section.params, &mut self.fields, field, value);
}
}
Ok(())
}
}
+59 -4
View File
@@ -3,6 +3,7 @@
use super::{Duplex, Printer, Settings, shown_names};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::display::Text;
use craft_ui::contract::{Bind, Entry, Held, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::Row;
@@ -12,7 +13,7 @@ use craft_ui::text::NumberField;
use egui::{Response, Ui};
/// The most copies one job may ask for.
const MOST_COPIES: u32 = 999;
pub(super) const MOST_COPIES: u32 = 999;
craft_ui::words! {
/// The words of the print panel.
@@ -28,6 +29,11 @@ craft_ui::words! {
long_edge: "printPanel.longEdge" = "Long edge";
short_edge: "printPanel.shortEdge" = "Short edge";
grayscale: "printPanel.grayscale" = "Grayscale";
print_settings: "printPanel.printSettings" = "Print Settings…";
orientation: "printPanel.orientation" = "Orientation";
portrait: "printPanel.portrait" = "Portrait";
landscape: "printPanel.landscape" = "Landscape";
page_in_driver: "printPanel.pageInDriver" = "set in Print Settings…";
}
}
@@ -39,6 +45,12 @@ pub struct PrintPanelOutput {
pub response: Response,
/// The Refresh button was pressed this pass: the caller starts printer discovery again.
pub refresh: bool,
/// A printer was chosen this pass: its name. The caller takes the paper from the new printer's driver.
pub printer_chosen: Option<String>,
/// Print Settings… was pressed this pass: the caller opens the driver's own dialog.
pub settings_clicked: bool,
/// Portrait (`false`) or Landscape (`true`) was pressed this pass: the caller turns the driver settings.
pub turned: Option<bool>,
}
impl Outcome for PrintPanelOutput {
@@ -55,6 +67,8 @@ impl Outcome for PrintPanelOutput {
/// - The printer list shows each printer's label, or its name, and edits the printer's name.
/// - Refresh is disabled while printers are being found, and the whole panel while a job runs.
/// - Copies step with the arrow keys, by ten with Shift.
/// - With `driver`, Print Settings… and Portrait/Landscape press into the output; the page line shows `page` and
/// `page_error`, which the caller keeps.
#[must_use = "show the panel with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
pub struct PrintPanel<'a> {
@@ -66,17 +80,27 @@ pub struct PrintPanel<'a> {
/// A job is running: the panel is disabled.
#[prop]
busy: bool,
/// The driver controls (Print Settings…, Portrait and Landscape, the page line) are shown: the caller can ask a
/// printer driver for its page.
#[prop]
driver: bool,
/// The driver's paper in points, as the caller last took it.
#[prop]
page: Option<egui::Vec2>,
/// Why the driver gave no page.
#[prop]
page_error: Option<String>,
}
impl<'a> PrintPanel<'a> {
/// The panel over `settings`, offering `printers`.
pub fn new(settings: Bind<'a, Settings>, printers: &'a [Printer]) -> Self {
PrintPanel { settings, printers, discovering: false, busy: false }
PrintPanel { settings, printers, discovering: false, busy: false, driver: false, page: None, page_error: None }
}
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> PrintPanelOutput {
let PrintPanel { settings, printers, discovering, busy } = self;
let PrintPanel { settings, printers, discovering, busy, driver, page, page_error } = self;
let env = Env::of(ui);
let words = env.words::<PrintWords>();
let queues: Vec<Entry<String>> =
@@ -89,6 +113,9 @@ impl<'a> PrintPanel<'a> {
];
let mut held = Held::new(settings);
let mut refresh = false;
let mut printer_chosen = None;
let mut settings_clicked = false;
let mut turned = None;
let mut shown = FieldGroup::new(words.title.clone()).enabled(!busy).show(ui, |ui, cx| {
let before = held.read(cx)?;
let mut now = before.clone();
@@ -99,6 +126,9 @@ impl<'a> PrintPanel<'a> {
.id_salt("queue")
.show(ui);
if let Some(name) = picked.value() {
if *name != now.printer {
printer_chosen = Some(name.clone());
}
now.printer.clone_from(name);
}
let button = Button::new(words.refresh.clone()).enabled(!discovering).id_salt("refresh").show(ui);
@@ -117,6 +147,31 @@ impl<'a> PrintPanel<'a> {
now.duplex = duplex;
}
});
if driver {
Field::new(words.print_settings.clone()).id_salt("driver").show(ui, |ui, _| {
let button = Button::new(words.print_settings.clone()).id_salt("print-settings").show(ui);
settings_clicked |= clicked(&button);
});
Field::new(words.orientation.clone()).id_salt("orientation").show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let wide = page.is_some_and(|paper| paper.x > paper.y);
for (landscape, word) in [(false, &words.portrait), (true, &words.landscape)] {
let button = Button::new(word.clone()).enabled(wide != landscape).id_salt(word.as_str()).show(ui);
if clicked(&button) {
turned = Some(landscape);
}
}
});
if let Some(paper) = page {
let mm = |points: f32| points / 72.0 * 25.4;
let line = format!("{:.0} × {:.0} mm · {}", mm(paper.x), mm(paper.y), words.page_in_driver.as_str());
Text::new(line).show(ui);
}
if let Some(error) = &page_error {
Text::new(error.clone()).show(ui);
}
});
}
Field::new(words.grayscale.clone()).id_salt("grayscale").show(ui, |ui, _| {
if let Some(on) =
Checkbox::new(Bind::given(now.grayscale)).label(words.grayscale.clone()).id_salt("grayscale").show(ui).value().copied()
@@ -132,7 +187,7 @@ impl<'a> PrintPanel<'a> {
held.write(cx, &before, now, words.title.as_str());
}
});
PrintPanelOutput { response: shown.output, refresh }
PrintPanelOutput { response: shown.output, refresh, printer_chosen, settings_clicked, turned }
}
}
+75 -4
View File
@@ -1,9 +1,15 @@
//! Stories of `PrintPanel`.
//! Stories of `PrintPanel` and `PrintDialog`.
use super::{Duplex, PrintPanel, Printer, Settings};
use craft_ui::contract::Bind;
use super::dialog::PrintPreview;
use super::{Duplex, PrintDialog, PrintMarks, PrintPanel, PrintSheet, Printer, Settings};
use craft_ui::contract::{Bind, Show as _, Validity};
use craft_ui::patterns::form_dialogs::DialogFields;
use craft_ui::primitives::TextureCache;
use craft_ui::runtime::env::Message;
use craft_ui::testing::pictures::sample_picture;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use egui::load::SizedTexture;
use egui::{Color32, ColorImage, Pos2, Rect, Ui, Vec2, pos2};
fn printers() -> Vec<Printer> {
vec![
@@ -24,3 +30,68 @@ fn print_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
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()
}
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
/// marks.
fn sheet(ui: &Ui, marks: bool) -> PrintSheet {
let id = TextureCache::texture(ui.ctx(), "print-dialog-story", || ColorImage::filled(PICTURE, Color32::from_rgb(0x4a, 0x7f, 0xc1)));
let picture = SizedTexture::new(id, Vec2::new(PICTURE[0] as f32, PICTURE[1] as f32));
let image = Rect::from_min_size(pos2(72.0, 72.0), Vec2::new(468.0, 312.0));
let sheet = PrintSheet::new(Vec2::new(612.0, 792.0), image, picture, "468 × 312 pt".into())
.printable(Rect::from_min_size(pos2(18.0, 18.0), Vec2::new(576.0, 756.0)));
if marks { sheet.marks(PrintMarks { corner_crop: true, registration: true, ..PrintMarks::default() }) } else { sheet }
}
/// The sheet of the preview story: Letter paper, the image box centred over a sample photo.
fn preview_sheet(ui: &Ui) -> PrintSheet {
let id = TextureCache::texture(ui.ctx(), "print-preview-story", || sample_picture(1, [240, 320]));
let image = Rect::from_center_size(pos2(306.0, 396.0), Vec2::new(360.0, 480.0));
PrintSheet::new(Vec2::new(612.0, 792.0), image, SizedTexture::new(id, Vec2::new(240.0, 320.0)), "360 × 480 pt".into())
}
#[story(PrintPreview<'static>, covers = [Default])]
fn print_preview(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let sheet = preview_sheet(ui);
let position = data.value("position", sheet.image.min);
PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into()
}
/// The image box hangs over the paper's right edge, a position the host refuses.
#[story(PrintPreview<'static>, covers = [Invalid], drive = Drive::Never)]
fn print_preview_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let sheet = preview_sheet(ui);
let paper = Rect::from_min_size(pos2(0.0, 0.0), sheet.paper);
let size = sheet.image.size();
let on_paper = move |at: &Pos2| {
if paper.contains_rect(Rect::from_min_size(*at, size)) { Validity::Ok } else { Validity::Refuse(Message::new("Off the paper")) }
};
let position = data.value("position", pos2(400.0, 156.0));
PrintPreview::new("Print preview", &sheet, Bind::bound(position).check(on_paper)).show(ui).into()
}
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = Settings { printer: "Office_1".to_owned(), duplex: Some(Duplex::LongEdge), ..Settings::default() };
let printers = printers();
let sheet = sheet(ui, true);
PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet).ready(true).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)
.discovering(true)
.show(ui)
.into()
}
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_busy(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = Settings { printer: "Office_1".to_owned(), ..Settings::default() };
let printers = printers();
let sheet = sheet(ui, false);
PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet).busy(true).show(ui).into()
}
+87
View File
@@ -0,0 +1,87 @@
//! The print dialog's preview: the image box drag.
use std::cell::RefCell;
use std::rc::Rc;
use craft_behavior::EditEvent;
use craft_print::ui::{PrintDialog, PrintSheet, Printer, Settings};
use craft_ui::contract::Bind;
use craft_ui::patterns::form_dialogs::DialogFields;
use craft_ui::primitives::TextureCache;
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
use egui::{Color32, ColorImage, Pos2, Rect, Ui, Vec2, pos2, vec2};
/// The image box's size in paper points.
const IMAGE_SIZE: Vec2 = Vec2::new(200.0, 300.0);
/// Where the sheet puts the image box, in paper points.
const IMAGE_AT: Pos2 = Pos2::new(72.0, 72.0);
type Log = Rc<RefCell<Vec<EditEvent<Pos2>>>>;
fn picture(ui: &Ui) -> SizedTexture {
let id = TextureCache::texture(ui.ctx(), "print-dialog-trial", || ColorImage::filled([20, 30], Color32::from_rgb(0x4a, 0x7f, 0xc1)));
SizedTexture::new(id, Vec2::new(20.0, 30.0))
}
/// A print dialog over a fixed sheet of `paper` points; the events of the image box drag land in the log.
fn rig(paper: Vec2) -> (Fixture, Log) {
let log: Log = Rc::default();
let seen = log.clone();
let mut settings = Settings::default();
let mut fields = DialogFields::default();
let printers = vec![Printer::new("Office")];
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).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 {
ui.ctx().request_discard("the frame runs twice");
}
});
fixture.room(Vec2::new(1400.0, 1000.0));
fixture.settle();
(fixture, log)
}
/// One drag gesture on a sheet of `paper` points: the preview scale differs with the paper.
fn check(paper: Vec2) {
let (mut fixture, log) = rig(paper);
let image = fixture.by_label("Image box").expect("the image box is in the access tree");
let scale = image.rect.width() / IMAGE_SIZE.x;
let from = image.center();
let by = vec2(40.0, 20.0);
// A click with no drag begins nothing, and neither does a press beside the image box.
fixture.click_at(from);
assert!(log.borrow().is_empty(), "a click moves nothing: {:?}", log.borrow());
fixture.drag_at(pos2(image.rect.min.x - 4.0, image.center().y), by);
assert!(log.borrow().is_empty(), "a press outside the image box moves nothing: {:?}", log.borrow());
fixture.drag_hold_at(from, by);
{
let log = log.borrow();
assert!(matches!(log.first(), Some(EditEvent::Begin { .. })), "the drag begins a gesture: {log:?}");
let Some(EditEvent::Update { value, .. }) = log.last() else { panic!("the drag updates: {log:?}") };
let expected = IMAGE_AT + by / scale;
assert!((*value - expected).length() < 0.01, "position {value:?} should be {expected:?} at scale {scale}");
let shown: Vec<String> = log.iter().map(|event| format!("{event:?}")).collect();
assert!(shown.windows(2).all(|pair| pair[0] != pair[1]), "a rerun pass repeated an event: {log:?}");
}
fixture.release_at(from + by);
let log = log.borrow();
let Some(EditEvent::Commit { after, .. }) = log.last() else { panic!("the release commits: {log:?}") };
assert!((*after - (IMAGE_AT + by / scale)).length() < 0.01, "committed position {after:?} should be {:?}", IMAGE_AT + by / scale);
}
/// The image box drag reports the box's new position on the paper in paper points, where the sheet put it plus the
/// travel from the press, at two preview scales (screen points are divided by the scale); a click and a press outside
/// the box report nothing.
#[trial]
fn the_image_box_drag_reports_the_new_position() {
check(vec2(612.0, 792.0));
check(vec2(306.0, 396.0));
}
+1
View File
@@ -2,4 +2,5 @@
// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod dialog;
mod print;