pdf-print-ocr-w1: net change of 4 commits

- pdf-print-ocr-w1: finished by an agent
- pdf-print-ocr-w1: finished by an agent
- pdf-print-ocr-w1: finished by an agent
- pdf-print-ocr-w1: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 02:28:25 -05:00
parent 1e8f98ba35
commit 00893772d3
12 changed files with 1054 additions and 247 deletions
Generated
+1
View File
@@ -3446,6 +3446,7 @@ name = "craft-print"
version = "0.1.0"
dependencies = [
"craft-behavior",
"craft-theme",
"craft-ui",
"craft-winprint-gdi",
"egui",
+3 -1
View File
@@ -16,12 +16,14 @@ harness = false
[features]
default = []
# The printer and job settings widgets (`craft_print::ui`).
ui = ["dep:craft-behavior", "dep:craft-ui", "dep:egui", "dep:serde_json"]
ui = ["dep:craft-behavior", "dep:craft-theme", "dep:craft-ui", "dep:egui", "dep:serde_json"]
# The stories and the integration binary of the print panel.
screen-testing = ["ui", "craft-ui/testing"]
[dependencies]
craft-behavior = { workspace = true, optional = true }
# `Tone` for the dialog's refusal notice; craft-ui does not re-export it.
craft-theme = { workspace = true, optional = true }
craft-ui = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
egui = { workspace = true, optional = true }
+433 -165
View File
@@ -4,32 +4,38 @@
use std::sync::mpsc::Receiver;
use craft_behavior::{CursorIcon, EditEvent, EditEvents, Metrics, Mixed, PartKey, PointerButton, PressPhase, Sense};
use craft_theme::variant::Tone;
use craft_ui::buttons::Button;
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 _, Role, Scroll, Show as _, ShowContainer as _, WordSetCx as _, clicked,
};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft_ui::display::Text;
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft_ui::display::{Shade, Text};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::patterns::form_dialogs::{
DialogFields, FieldValue, FormDialog, HostRequests, PagerStep, PanePager, Param, ParamRows, set_color_field, set_param_field,
};
use craft_ui::primitives::{ContentPainterCx, TextRun, fill_polygon};
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, Section};
use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleCx, SurfaceKind};
use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleColor, StyleCx, SurfaceKind, TypeRole};
use egui::load::SizedTexture;
use egui::{Pos2, Rect, Response, TextureId, Ui, Vec2, pos2, vec2};
use egui::{Color32, Mesh, Pos2, Rect, Response, Shape, TextureId, Ui, Vec2, pos2, vec2};
use super::panel::{DriverControls, MOST_COPIES, PrintPanel};
use super::{Duplex, Printer, Settings, State};
use super::panel::{Destinations, DriverControls, MOST_COPIES, PrintPanel, PrintWords};
use super::{Destination, Duplex, Printer, Settings, State};
craft_ui::words! {
/// The words of the print dialog.
pub struct PrintDialogWords {
title: "printDialog.title" = "Print Settings";
title_document: "printDialog.titleDocument" = "Print";
print: "printDialog.print" = "Print";
done: "printDialog.done" = "Done";
preview: "printDialog.preview" = "Print preview image";
@@ -38,7 +44,10 @@ craft_ui::words! {
}
}
/// The index `FormOutput::picked` gives the Done button: Print is 0, Cancel 1, and the extra buttons start at 2.
/// The index `FormOutput::picked` gives the Print button: Print is 0, Cancel 1, and the extra buttons start at 2.
const PRINT_BUTTON: usize = 0;
/// The index `FormOutput::picked` gives the Done button of the `Image` layout, its one extra button.
const DONE_BUTTON: usize = 2;
/// The image box of the preview.
@@ -115,10 +124,10 @@ impl SheetPage {
/// The page's picture `id` and the part `uv` of it to draw.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
pub fn picture(self, id: TextureId, uv: egui::Rect) -> Self {
let _ = (id, uv);
todo!("PO-P6")
pub fn picture(mut self, id: TextureId, uv: egui::Rect) -> Self {
self.picture = Some(id);
self.uv = uv;
self
}
}
@@ -130,11 +139,7 @@ pub struct PrintSheet {
pub paper: egui::Vec2,
/// The printable area of the paper, when the printer says.
pub printable: Option<egui::Rect>,
/// The image box on the paper.
pub image: egui::Rect,
/// The picture of the document.
pub picture: SizedTexture,
/// The marks to draw.
/// The marks to draw, around the image box or the pages.
pub marks: PrintMarks,
/// The readout under the preview.
pub readout: Label,
@@ -152,12 +157,25 @@ impl PrintSheet {
/// A sheet of `paper` with the image box `image` holding `picture`, `readout` under the preview, no printable area
/// and no marks.
pub fn new(paper: egui::Vec2, image: egui::Rect, picture: SizedTexture, readout: Label) -> Self {
let content = SheetContent::Image { image, picture };
Self::of(paper, SheetContent::Image { image, picture }, readout)
}
/// A sheet of `paper` holding `pages`, with `readout` under the preview.
pub fn pages(paper: Vec2, pages: Vec<SheetPage>, readout: Label) -> Self {
Self::of(paper, SheetContent::Pages(pages), readout)
}
/// A preview showing `message` instead of a sheet, with `readout` under it. `paper` keeps the preview the size the
/// sheets around it take.
pub fn message(paper: Vec2, message: Label, readout: Label) -> Self {
Self::of(paper, SheetContent::Message(message), readout)
}
/// A sheet of `paper` showing `content`, with no printable area, no marks, borders, cuts or notes.
fn of(paper: Vec2, content: SheetContent, readout: Label) -> Self {
PrintSheet {
paper,
printable: None,
image,
picture,
marks: PrintMarks::default(),
readout,
content,
@@ -167,42 +185,33 @@ impl PrintSheet {
}
}
/// A sheet of `paper` holding `pages`, with `readout` under the preview.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
pub fn pages(paper: Vec2, pages: Vec<SheetPage>, readout: Label) -> Self {
let _ = (paper, pages, readout);
todo!("PO-P6")
}
/// A preview showing `message` instead of a sheet, with `readout` under it.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
pub fn message(paper: Vec2, message: Label, readout: Label) -> Self {
let _ = (paper, message, readout);
todo!("PO-P6")
/// The image box of an `Image` sheet; none for pages or a message.
pub(super) fn image_box(&self) -> Option<Rect> {
match &self.content {
SheetContent::Image { image, .. } => Some(*image),
SheetContent::Pages(_) | SheetContent::Message(_) => None,
}
}
/// The borders drawn around the pages.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
pub fn borders(self, borders: Vec<egui::Rect>) -> Self {
let _ = borders;
todo!("PO-P6")
pub fn borders(mut self, borders: Vec<egui::Rect>) -> Self {
self.borders = borders;
self
}
/// The cut lines.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
pub fn cuts(self, cuts: Vec<[Pos2; 2]>) -> Self {
let _ = cuts;
todo!("PO-P6")
pub fn cuts(mut self, cuts: Vec<[Pos2; 2]>) -> Self {
self.cuts = cuts;
self
}
/// The notes under the readout.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P6
pub fn notes(self, notes: Vec<Label>) -> Self {
let _ = notes;
todo!("PO-P6")
pub fn notes(mut self, notes: Vec<Label>) -> Self {
self.notes = notes;
self
}
/// The printable area of the paper.
@@ -228,28 +237,58 @@ pub struct PrintSection {
pub title: Label,
/// Its rows.
pub params: Vec<Param>,
/// Whether the section can fold, and whether it starts open; `None` is a fixed section.
folded: Option<bool>,
/// The title-row buttons: the id a press files, the label and whether the button is enabled.
buttons: Vec<(String, Label, bool)>,
}
impl PrintSection {
/// The section titled `title` with its `params` rows.
pub fn new(title: impl Into<Label>, params: Vec<Param>) -> Self {
Self { title: title.into(), params }
Self { title: title.into(), params, folded: None, buttons: Vec::new() }
}
/// Collapses the section when `open` is false, through `Section::initially_open`.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P7
pub fn folded(self, open: bool) -> Self {
let _ = open;
todo!("PO-P7")
pub fn folded(mut self, open: bool) -> Self {
self.folded = Some(open);
self
}
/// A title-row button; a press is filed as `HostRequests::request_action(id)`.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P7
pub fn button(self, id: impl Into<String>, label: impl Into<Label>, enabled: bool) -> Self {
let _ = (id.into(), label.into(), enabled);
todo!("PO-P7")
pub fn button(mut self, id: impl Into<String>, label: impl Into<Label>, enabled: bool) -> Self {
self.buttons.push((id.into(), label.into(), enabled));
self
}
/// Shows the section with its rows over `values`. Its rows' requests and a title button's press go into `requests`.
fn show(&self, ui: &mut Ui, at: usize, values: &mut DialogFields, requests: &mut HostRequests) {
let mut section = match self.folded {
Some(open) => Section::new(self.title.clone()).initially_open(open),
None => Section::fixed(self.title.clone()),
};
let mut pressed = None;
if !self.buttons.is_empty() {
let buttons = &self.buttons;
let pressed = &mut pressed;
section = section.controls(move |ui, _| {
for (id, label, enabled) in buttons {
let button = Button::new(label.clone()).enabled(*enabled).id_salt(id.as_str()).show(ui);
if clicked(&button) {
*pressed = Some(id.clone());
}
}
});
}
section.id_salt(("section", at)).show(ui, |ui, _| {
let mut rows = ParamRows::new(self.title.clone(), &self.params, Bind::bound(&mut *values)).show(ui);
requests.absorb(&mut rows);
});
if let Some(id) = pressed {
requests.request_action(id);
}
}
}
@@ -273,16 +312,61 @@ struct Placement {
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)
Rect::from_min_size(self.point(paper.min), paper.size() * self.scale)
}
/// The screen point of `at`, a point in paper points.
fn point(self, at: Pos2) -> Pos2 {
self.origin + at.to_vec2() * self.scale
}
}
/// The style of the preview: the room it asks for.
/// The style of the preview: the room it asks for, the stand-in of a page with no picture and the text it shows.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub(super) struct PrintPreviewStyle {
#[style(metrics)]
metrics: Metrics,
/// The fill of a page with no picture.
stand_in: StyleColor,
/// A stand-in's number and the message shown instead of a sheet.
ink: StyleColor,
}
/// The textured quad of a page: `corners` (screen points) are the picture's top-left, top-right, bottom-right and
/// bottom-left, paired in that order with `uv`'s corners, so a turned placement turns the picture with it.
fn page_quad(texture: TextureId, corners: [Pos2; 4], uv: Rect) -> Mesh {
let mut mesh = Mesh::with_texture(texture);
let uvs = [uv.left_top(), uv.right_top(), uv.right_bottom(), uv.left_bottom()];
for (pos, uv) in corners.into_iter().zip(uvs) {
// White leaves the picture's own colours: the vertex colour multiplies the texture.
mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE });
}
mesh.add_triangle(0, 1, 2);
mesh.add_triangle(0, 2, 3);
mesh
}
/// Paints `run` centred on `centre`.
fn centred_text(painter: &ContentPainterCx<'_>, run: &TextRun<'_>, centre: Pos2, width: f32) {
painter.with_draw(|draw| {
let layout = draw.layout(run, width);
draw.galley(centre - layout.size() / 2.0, &layout);
});
}
/// Paints `page` at `place`: its picture as a textured quad, or a stand-in with its number centred.
fn paint_page(painter: &ContentPainterCx<'_>, style: &PrintPreviewStyle, place: Placement, page: &SheetPage) {
let corners = page.corners.map(|corner| place.point(corner));
match page.picture {
Some(texture) => painter.data_shapes([Shape::mesh(page_quad(texture, corners, page.uv))]),
None => {
painter.data_shapes([Shape::mesh(fill_polygon(&corners, style.stand_in.egui(), 0.0))]);
let centre = Pos2::ZERO + corners.iter().fold(Vec2::ZERO, |sum, corner| sum + corner.to_vec2()) / 4.0;
let run = TextRun::new(page.number.as_str()).role(TypeRole::Caption).color(style.ink);
centred_text(painter, &run, centre, f32::INFINITY);
}
}
}
/// The paper, its printable area, the picture in its box and the marks. The value is where the image box's top-left
@@ -326,8 +410,13 @@ impl Component for PrintPreview<'_> {
type Style = PrintPreviewStyle;
type Output = PrintPreviewOutput;
fn style(_: &StyleCx<'_>, _: PrintPreviewStyleKey) -> PrintPreviewStyle {
PrintPreviewStyle { metrics: Metrics::new() }
fn style(cx: &StyleCx<'_>, _: PrintPreviewStyleKey) -> PrintPreviewStyle {
let tokens = cx.tokens;
PrintPreviewStyle {
metrics: Metrics::new(),
stand_in: cx.color(tokens.color.surface.sunken),
ink: cx.color(tokens.color.text.muted),
}
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
@@ -342,10 +431,11 @@ impl Component for PrintPreview<'_> {
}
/// 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.
/// not, so the press keeps its hit. Only an `Image` sheet has the part: pages and a message are not dragged.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let Some(image) = self.sheet.image_box() else { return };
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");
let part = cx.part(IMAGE, place.rect(image)).sense(Sense::DRAG).pointer_only("the Position and Size rows place the image");
part.cursor(CursorIcon::Move);
}
@@ -380,15 +470,61 @@ impl Component for PrintPreview<'_> {
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
if self.sheet.image_box().is_none() {
return;
}
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 style = &cx.style;
// A message stands in for the whole sheet: no paper, the text centred in the room the sheets take.
if let SheetContent::Message(message) = &sheet.content {
let painter = ui.content_painter(cx);
painter.surface(cx.rect, SurfaceKind::Well, Corners::None);
let shown = cx.env.resolve(message);
let run = TextRun::new(shown.as_str()).color(style.ink);
centred_text(&painter, &run, cx.rect.center(), cx.rect.width());
return;
}
let Some(place) = self.place(cx.rect) else { return };
let paper = place.rect(Rect::from_min_size(Pos2::ZERO, sheet.paper));
{
let painter = ui.content_painter(cx);
painter.surface(cx.rect, SurfaceKind::Well, Corners::None);
painter.surface(paper, SurfaceKind::Canvas, Corners::None);
}
// The box the marks stand around: the image box, or the pages' extent.
let marked = match &sheet.content {
SheetContent::Image { image, picture } => {
let position = cx.value().copied().unwrap_or(image.min);
let image = place.rect(Rect::from_min_size(position, 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()),
);
ui.content_painter(cx).picture(picture.id, visible, uv, 0.0);
}
Some(image)
}
SheetContent::Pages(pages) => {
// A page placed past the paper's edge prints cut there, so the preview cuts it too.
ui.clipped(paper, |ui| {
let painter = ui.content_painter(cx);
for page in pages {
paint_page(&painter, style, place, page);
}
});
let corners = pages.iter().flat_map(|page| page.corners.map(|corner| place.point(corner)));
Some(Rect::from_points(&corners.collect::<Vec<_>>()).intersect(paper)).filter(|extent| extent.is_positive())
}
SheetContent::Message(_) => None,
};
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| {
@@ -397,23 +533,20 @@ impl Component for PrintPreview<'_> {
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);
for border in &sheet.borders {
outline(RuleKind::Edge, place.rect(*border));
}
for [from, to] in &sheet.cuts {
rule(RuleKind::Grid, place.point(*from), place.point(*to));
}
if let Some(area) = sheet.printable {
outline(RuleKind::Grid, place.rect(area));
}
outline(RuleKind::Edge, paper);
outline(RuleKind::DropMark, image);
let Some(image) = marked else { return };
if sheet.image_box().is_some() {
outline(RuleKind::DropMark, image);
}
let marks = sheet.marks;
let sides = [
@@ -487,6 +620,12 @@ impl Outcome for PrintPreviewOutput {
/// 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.
///
/// - [`PrintLayout::Document`] puts Printer Setup and the sections in a scrolling column, then the sheet preview with
/// the pager centred under it, the readout and the notes at the end edge. It has no Done button, the printer list
/// ends with Save as PDF, and Print reads Save as PDF while that is chosen. A pager press is filed with
/// `HostRequests::request_preview_step`.
/// - A section's title buttons and its custom rows' buttons are filed with `HostRequests::request_action`.
#[must_use = "show the dialog with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
pub struct PrintDialog<'a> {
@@ -524,6 +663,15 @@ pub struct PrintDialog<'a> {
/// The pager under the sheet preview in the `Document` layout.
#[prop]
preview_pager: Option<PanePager>,
/// Makes Print keep the dialog open and report its press in `PrintDialogOutput::held`.
#[prop(vis = "pub(crate)")]
hold_ok: bool,
/// Closes the dialog as Print in this pass: the host accepted the held answer.
#[prop(vis = "pub(crate)")]
finish_held: bool,
/// Shows the reason under the rows while the settings and the values are the refused ones.
#[prop(vis = "pub(crate)")]
refusal: Option<(Label, Settings, DialogFields)>,
}
/// What [`PrintDialog::show`] returns.
@@ -545,6 +693,10 @@ pub struct PrintDialogOutput {
pub requests: HostRequests,
/// The pager press made this pass.
pub preview_step: Option<PagerStep>,
/// The destination the user picked in the panel this pass.
pub(crate) printer_chosen: Option<Destination>,
/// Print was pressed on a dialog that holds its OK: the host files the answer.
pub(crate) held: bool,
}
impl Outcome for PrintDialogOutput {
@@ -574,11 +726,15 @@ impl<'a> PrintDialog<'a> {
driver: DriverControls::None,
duplex_by_layout: false,
preview_pager: None,
hold_ok: false,
finish_held: 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, pager and section button presses and the
/// destination picked 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,
@@ -595,23 +751,37 @@ impl<'a> PrintDialog<'a> {
driver,
duplex_by_layout,
preview_pager,
hold_ok,
finish_held,
refusal,
} = self;
let _ = (layout, driver, duplex_by_layout, preview_pager); // P3(pdf-print-ocr-w1): PO-P5
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);
let document = layout == PrintLayout::Document;
let to_file = matches!(settings.reborrow().get(), Some(Mixed::Same(Settings { destination: Destination::File, .. })));
let title = if document { words.title_document.clone() } else { words.title.clone() };
let ok = if document && to_file { env.words::<PrintWords>().save_as_pdf.clone() } else { words.print.clone() };
let destinations = if document { Destinations::PrintersAndFile } else { Destinations::Printers };
let mut form = FormDialog::new(title, fields).ok_label(ok).ok_enabled(ready && !busy).accept_stays_open(hold_ok).answers(answers);
if !document {
form = form.extra_buttons([FooterButton::new(words.done.clone(), DialogRole::Other)]);
}
if let Some(opened) = opened {
form = form.opened(opened);
}
let mut moved = EditEvents::new();
let mut refresh = false;
let mut preview_step = None;
let mut printer_chosen = None;
let shown = form.show(ui, |ui, form, values| {
moved = EditEvents::new();
refresh = false;
preview_step = None;
printer_chosen = None;
// A measuring run closes nothing: the real run of the same pass makes the close.
if finish_held && !craft_ui::runtime::measure::active(ui.ctx()) {
form.request_close_as(CloseReason::Activated);
}
for answer in form.take_answers() {
match answer {
HostAnswer::Color { key, color } | HostAnswer::Eyedropper { key, color } => {
@@ -623,35 +793,85 @@ impl<'a> PrintDialog<'a> {
_ => {}
}
}
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, _| {
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);
});
// Printer Setup and the app's sections.
let mut setup = |ui: &mut Ui, values: &mut DialogFields, requests: &mut HostRequests| {
Section::fixed(words.printer_setup.clone()).id_salt("printer").show(ui, |ui, _| {
let panel = PrintPanel::new(settings.reborrowed(), printers)
.discovering(discovering)
.busy(busy)
.driver(driver)
.destinations(destinations)
.duplex_by_layout(duplex_by_layout)
.show(ui);
refresh |= panel.refresh;
if panel.printer_chosen.is_some() {
printer_chosen = panel.printer_chosen;
}
});
});
for (at, section) in sections.iter().enumerate() {
section.show(ui, at, values, requests);
}
};
// The sheet preview, the pager under it in the `Document` layout, the readout and the notes.
let mut sheet_column = |ui: &mut Ui| {
let position = sheet.image_box().map_or(Pos2::ZERO, |image| image.min);
let preview = PrintPreview::new(words.preview.clone(), sheet, Bind::given(position)).show(ui);
moved.extend(preview.edit.events);
let mut step = None;
if let Some(pager) = preview_pager.as_ref().filter(|_| document) {
Row::new().align(RowAlign::Center).fill_width().show(ui, |ui, _| step = pager.clone().show(ui));
}
Text::new(sheet.readout.clone()).show(ui);
for note in &sheet.notes {
Text::new(note.clone()).shade(Shade::Muted).show(ui);
}
step
};
match layout {
PrintLayout::Image => {
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| preview_step = sheet_column(ui));
Stack::new().show(ui, |ui, _| setup(ui, values, form.requests()));
});
}
PrintLayout::Document => {
Row::new().show(ui, |ui, _| {
Stack::new().scroll(Scroll::vertical()).show(ui, |ui, _| setup(ui, values, form.requests()));
Stack::new().show(ui, |ui, _| preview_step = sheet_column(ui));
});
}
}
if let Some(step) = preview_step {
form.requests().request_preview_step(step);
}
// The host's refusal of the held OK stays until a setting or a value changes.
let now = settings.reborrow().get();
let refused = refusal.as_ref().filter(|(_, refused, fields)| *fields == *values && matches!(&now, Some(Mixed::Same(now)) if now == refused));
if let Some((reason, ..)) = refused {
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
}
ready && !busy
});
let finish = if shown.accepted.is_some() {
Some(PrintFinish::Print)
} else if shown.picked == Some(DONE_BUTTON) {
} else if !document && shown.picked == Some(DONE_BUTTON) {
Some(PrintFinish::Done)
} else {
None
};
PrintDialogOutput { response: shown.response, closed: shown.closed, finish, moved, refresh, requests: shown.requests, preview_step: None }
// `picked` is this pass's press: a second pass of the frame has none, so a held Print is reported once.
let held = hold_ok && shown.picked == Some(PRINT_BUTTON);
PrintDialogOutput {
response: shown.response,
closed: shown.closed,
finish,
moved,
refresh,
requests: shown.requests,
preview_step,
printer_chosen,
held,
}
}
}
@@ -670,6 +890,11 @@ pub struct PrintAnswer {
/// 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).
///
/// With [`held_ok`](Self::held_ok), Print files its answer for the app ([`take_ok`](Self::take_ok)) and waits disabled
/// until [`answer_ok`](Self::answer_ok): `Ok` closes the dialog with the held answer at the next pass, `Err` shows the
/// reason under the rows until a setting or a value changes, and [`release_ok`](Self::release_ok) takes the held answer
/// back without a reason.
pub struct HostedPrint {
id: DialogId,
state: State,
@@ -680,6 +905,16 @@ pub struct HostedPrint {
refresh: bool,
requests: HostRequests,
json_form: Option<Box<JsonForm>>,
layout: PrintLayout,
driver: DriverControls,
duplex_by_layout: bool,
preview_pager: Option<PanePager>,
/// The destination the user picked, or automation set, not taken yet.
printer_chosen: Option<Destination>,
/// Whether Print files its answer for the app instead of closing.
hold: bool,
/// The Print the app holds back until it answers, and its refusal.
held: HeldAnswer<PrintAnswer>,
}
/// Adds the app's own keys to the automation listing of the sections' values.
@@ -698,6 +933,13 @@ impl HostedPrint {
refresh: true,
requests: HostRequests::new(),
json_form: None,
layout: PrintLayout::Image,
driver: DriverControls::None,
duplex_by_layout: false,
preview_pager: None,
printer_chosen: None,
hold: false,
held: HeldAnswer::new(),
}
}
@@ -748,101 +990,83 @@ impl HostedPrint {
/// The dialog's arrangement.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn layout(self, layout: PrintLayout) -> Self {
let _ = layout;
todo!("PO-P8")
pub fn layout(mut self, layout: PrintLayout) -> Self {
self.layout = layout;
self
}
/// Replaces the app's sections.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn set_sections(&mut self, sections: Vec<PrintSection>) {
let _ = sections;
todo!("PO-P8")
self.sections = sections;
}
/// The printer state.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn state(&self) -> &State {
todo!("PO-P8")
&self.state
}
/// The printer state, for the app to change.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn state_mut(&mut self) -> &mut State {
todo!("PO-P8")
&mut self.state
}
/// The printer-driver controls the panel offers.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn set_driver(&mut self, driver: DriverControls) {
let _ = driver;
todo!("PO-P8")
self.driver = driver;
}
/// Whether the layout sets two-sided printing, leaving out the Two-sided row.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn set_duplex_by_layout(&mut self, on: bool) {
let _ = on;
todo!("PO-P8")
self.duplex_by_layout = on;
}
/// The pager under the sheet preview in the `Document` layout.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn set_preview_pager(&mut self, pager: Option<PanePager>) {
let _ = pager;
todo!("PO-P8")
self.preview_pager = pager;
}
/// The pager press since the last call.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn take_preview_step(&mut self) -> Option<PagerStep> {
todo!("PO-P8")
self.requests.take_preview_step()
}
/// The id of the section button pressed since the last call.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn take_action(&mut self) -> Option<String> {
todo!("PO-P8")
self.requests.take_action()
}
/// The destination the user picked in the panel, or a `set_json_field("printer", ..)` write, once; `State::poll`'s
/// replacement of an unlisted name is not reported.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn take_printer_chosen(&mut self) -> Option<super::Destination> {
todo!("PO-P8")
pub fn take_printer_chosen(&mut self) -> Option<Destination> {
self.printer_chosen.take()
}
/// Withdraws a held OK: OK is enabled again, the values are kept and no refusal line shows.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn release_ok(&mut self) {
todo!("PO-P8")
self.held.withdraw();
}
/// The dialog holds OK until the app answers it with `answer_ok`.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn held_ok(self) -> Self {
todo!("PO-P8")
pub fn held_ok(mut self) -> Self {
self.hold = true;
self
}
/// Holds OK until the app answers it with `answer_ok`.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn hold_ok(&mut self) {
todo!("PO-P8")
self.hold = true;
}
/// The held OK's answer when OK was pressed, once.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
pub fn take_ok(&mut self) -> Option<PrintAnswer> {
todo!("PO-P8")
self.held.take()
}
/// Answers the held OK: `Ok` closes the dialog, `Err` keeps it open and shows the refusal.
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P8
/// Answers the held OK: `Ok` closes the dialog, `Err` keeps it open and shows the refusal. Without a held OK it does
/// nothing.
pub fn answer_ok(&mut self, answer: Result<(), Label>) {
let _ = answer;
todo!("PO-P8")
self.held.answer(answer);
}
/// The answer of the dialog as it stands.
@@ -882,56 +1106,91 @@ 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, and keeps the drags, the Refresh, pager and button
/// presses, the destination picked 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>> {
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)
let finish_held = self.held.is_accepted();
// Print waits for the app's answer: a second press cannot file over the held one.
let ready = self.state.ready() && !self.held.is_waiting();
let (busy, discovering) = (self.state.busy(), self.state.discovering());
let refusal = self.held.refusal().map(|(reason, refused)| (reason.clone(), refused.settings.clone(), refused.fields.clone()));
let mut dialog = 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;
.layout(self.layout)
.driver(self.driver)
.duplex_by_layout(self.duplex_by_layout)
.hold_ok(self.hold)
.finish_held(finish_held);
if let Some(pager) = self.preview_pager.clone() {
dialog = dialog.preview_pager(pager);
}
if let Some(refusal) = refusal {
dialog = dialog.refusal(refusal);
}
let shown = dialog.show(ui);
let PrintDialogOutput { closed, finish, moved, refresh, requests, printer_chosen, held, .. } = shown;
self.moves.extend(moved);
self.refresh |= refresh;
if let Some(request) = requests.take_color() {
self.requests.request_color(request);
if printer_chosen.is_some() {
self.printer_chosen = printer_chosen;
}
if let Some(request) = requests.take_path() {
self.requests.request_path(request);
if self.held.refusal().is_some_and(|(_, refused)| refused.settings != self.state.settings || refused.fields != self.fields) {
self.held.clear_refusal();
}
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);
if held {
self.held.file(self.answer(PrintFinish::Print));
}
self.requests.extend(requests);
match (finish, closed) {
(Some(finish), _) => Some(DialogResult::Ok(self.answer(finish))),
(None, Some(CloseReason::Activated)) if finish_held => Some(self.held.finish().map_or(DialogResult::Cancel, DialogResult::Ok)),
(None, Some(_)) => Some(DialogResult::Cancel),
(None, None) => None,
}
}
/// 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))
fn held_state(&self) -> Option<HeldOk> {
self.held.state()
}
/// The `Settings` keys (`printer`, `copies`, `duplex`, `grayscale`) and each section parameter's value as
/// [`DialogFields`] serializes it.
/// Answers Print as the button does: none while a job cannot start. A held dialog files the answer for the app, as
/// its button does, and answers none; once the app accepted the held answer, it answers that.
fn confirm(&mut self, _: &egui::Context) -> Option<PrintAnswer> {
if self.held.is_accepted() {
return self.held.finish();
}
if self.held.is_waiting() || !self.state.ready() {
return None;
}
let answer = self.answer(PrintFinish::Print);
if self.hold {
self.held.file(answer);
return None;
}
Some(answer)
}
/// The `Settings` keys (`printer`, `copies`, `duplex`, `grayscale`, `collate`) and each section parameter's value as
/// [`DialogFields`] serializes it. `printer` is the printer's name, or `null` for Save as PDF.
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,
_ => serde_json::Map::new(),
};
let settings = &self.state.settings;
map.insert("printer".to_owned(), settings.printer.clone().into());
let printer = match &settings.destination {
Destination::Printer(name) => name.clone().into(),
Destination::File => serde_json::Value::Null,
};
map.insert("printer".to_owned(), printer);
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());
@@ -942,13 +1201,22 @@ impl StackDialog for HostedPrint {
Some(serde_json::Value::Object(map))
}
/// Sets a `Settings` key, or a section parameter through the shared parameter-field rule.
/// Sets a `Settings` key, or a section parameter through the shared parameter-field rule. `printer` takes a listed
/// printer's name, or `null` for Save as PDF where the layout offers it; the write is a choice the app takes with
/// [`take_printer_chosen`](HostedPrint::take_printer_chosen).
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();
let destination = match &value {
serde_json::Value::Null if self.layout == PrintLayout::Document => Some(Destination::File),
serde_json::Value::String(name) if self.state.printers.iter().any(|printer| printer.name == *name) => {
Some(Destination::Printer(name.clone()))
}
_ => None,
};
let destination = destination.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.state.settings.destination = destination.clone();
self.printer_chosen = Some(destination);
}
"copies" => {
let copies = value.as_u64().and_then(|copies| u32::try_from(copies).ok()).filter(|copies| (1..=MOST_COPIES).contains(copies));
+22 -14
View File
@@ -25,7 +25,7 @@ const POLL_SECONDS: f64 = 0.1;
#[non_exhaustive]
/// A printer the spooler offers.
pub struct Printer {
/// The spooler's destination: what [`Settings::printer`] and jobs name.
/// The spooler's destination: what [`Settings::destination`] and jobs name.
pub name: String,
/// What the dialog shows; empty shows `name`. CUPS, for one, describes the queue
/// `_192_0_2_15` as `192.0.2.15`, the name the user gave the printer.
@@ -59,10 +59,9 @@ impl Printer {
/// Marks the printer's own dialog as deciding copies, collate, two-sided and colour; the panel disables those
/// controls and shows `note` under them while the printer is chosen.
#[must_use]
#[allow(dead_code)] // P3(pdf-print-ocr-w1): PO-P3
pub fn own_dialog(self, note: impl Into<String>) -> Self {
let _ = note;
todo!("PO-P3")
pub fn own_dialog(mut self, note: impl Into<String>) -> Self {
self.own_dialog = Some(note.into());
self
}
}
@@ -138,15 +137,13 @@ pub enum Destination {
#[non_exhaustive]
/// What the user chose for one print job.
pub struct Settings {
/// The chosen printer's [`Printer::name`].
pub printer: String,
/// Number of copies.
pub copies: u32,
/// None preserves the printer's default instead of forcing simplex.
pub duplex: Option<Duplex>,
/// Print in grayscale.
pub grayscale: bool,
/// Where the job goes.
/// Where the job goes: a printer by its [`Printer::name`], or Save as PDF.
pub destination: Destination,
/// Collate the copies.
pub collate: bool,
@@ -154,7 +151,7 @@ pub struct Settings {
impl Default for Settings {
fn default() -> Self {
Self { printer: String::new(), copies: 1, duplex: None, grayscale: false, destination: Destination::Printer(String::new()), collate: true }
Self { copies: 1, duplex: None, grayscale: false, destination: Destination::Printer(String::new()), collate: true }
}
}
@@ -212,9 +209,18 @@ impl State {
}
/// A refresh invalidates the old list until discovery completes: a removed queue must
/// not remain selectable while the host is checking it.
/// not remain selectable while the host is checking it. Save as PDF needs no queue, so it
/// waits only for a running job.
pub fn ready(&self) -> bool {
!self.busy() && !self.discovering() && self.printers.iter().any(|p| p.name == self.settings.printer)
match &self.settings.destination {
Destination::File => !self.busy(),
Destination::Printer(name) => !self.busy() && !self.discovering() && self.listed(name),
}
}
/// Whether the last discovery found a printer named `name`.
fn listed(&self, name: &str) -> bool {
self.printers.iter().any(|p| p.name == name)
}
/// Refuse replacing an active job's receiver. The caller still owns the refused receiver;
@@ -254,9 +260,11 @@ impl State {
match receiver.try_recv() {
Ok(printers) => {
self.printers = printers;
if !self.printers.iter().any(|p| p.name == self.settings.printer) {
self.settings.printer =
self.printers.iter().find(|p| p.default).or(self.printers.first()).map(|p| p.name.clone()).unwrap_or_default();
// Save as PDF stays whatever the spooler lists; only a printer that is gone is replaced.
let gone = matches!(&self.settings.destination, Destination::Printer(name) if !self.listed(name));
if gone {
let fallback = self.printers.iter().find(|p| p.default).or(self.printers.first());
self.settings.destination = Destination::Printer(fallback.map(|p| p.name.clone()).unwrap_or_default());
}
self.message = self.printers.is_empty().then_some(Feedback::NoPrinters);
self.discovery = None;
+76 -40
View File
@@ -1,10 +1,10 @@
//! `PrintPanel`: the printer, copies, two-sided and grayscale choices of one print job.
//! `PrintPanel`: the destination, copies, collate, grayscale and two-sided choices of one print job.
use super::{Destination, Duplex, Printer, Settings, shown_names};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Entry, Held, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked};
use craft_ui::display::Text;
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::Row;
use craft_ui::pickers::Select;
@@ -74,9 +74,10 @@ 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.
/// A destination was chosen this pass: the printer, or Save as PDF. The caller takes the paper from the new
/// printer's driver.
pub printer_chosen: Option<Destination>,
/// Print Settings… was pressed this pass: the caller opens the driver's own dialog.
/// Print Settings… or Properties… 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>,
@@ -90,14 +91,18 @@ impl Outcome for PrintPanelOutput {
}
}
/// The printer choice with a Refresh button, the number of copies, the two-sided mode and the grayscale option of one
/// print job, over the job's [`Settings`].
/// The destination choice with a Refresh button, the number of copies, collation, the grayscale option and the
/// two-sided mode of one print job, over the job's [`Settings`].
///
/// - The printer list shows each printer's label, or its name, and edits the printer's name.
/// - The list shows each printer's label, or its name, the default marked, and edits [`Settings::destination`]; with
/// `Destinations::PrintersAndFile`, Save as PDF follows the printers.
/// - 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.
/// - Copies, Collate and Grayscale share one row. Copies step with the arrow keys, by ten with Shift.
/// - While the chosen printer has its own dialog ([`Printer::own_dialog`]), Copies, Collate, Grayscale and Two-sided
/// are disabled and its note shows under them.
/// - `DriverControls::Properties` puts Properties… after Refresh; `DriverControls::Page` shows Print Settings…,
/// Portrait/Landscape and the page line with `page` and `page_error`, which the caller keeps. Their presses go into
/// the output.
#[must_use = "show the panel with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
pub struct PrintPanel<'a> {
@@ -109,8 +114,8 @@ 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.
/// Which printer-driver controls are shown: Properties…, or Print Settings… with Portrait and Landscape and the page
/// line, for a caller that can ask a printer driver for its page.
#[prop]
driver: DriverControls,
/// Which destinations the list offers.
@@ -146,12 +151,21 @@ impl<'a> PrintPanel<'a> {
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> PrintPanelOutput {
let PrintPanel { settings, printers, discovering, busy, driver, destinations, duplex_by_layout, page, page_error } = self;
let _ = (destinations, duplex_by_layout); // P3(pdf-print-ocr-w1): PO-P4
let driver = driver == DriverControls::Page; // P3(pdf-print-ocr-w1): PO-P4
let env = Env::of(ui);
let words = env.words::<PrintWords>();
let queues: Vec<Entry<String>> =
printers.iter().zip(shown_names(printers)).map(|(printer, shown)| Entry::new(printer.name.clone(), shown)).collect();
let mut queues: Vec<Entry<Destination>> = printers
.iter()
.zip(shown_names(printers))
.map(|(printer, shown)| {
let shown = if printer.default { format!("{shown} {}", words.default_mark.as_str()) } else { shown };
Entry::new(Destination::Printer(printer.name.clone()), shown)
})
.collect();
if destinations == Destinations::PrintersAndFile {
queues.push(Entry::separator());
queues.push(Entry::new(Destination::File, words.save_as_pdf.clone()));
}
let placeholder = if discovering && printers.is_empty() { &words.finding } else { &words.select_printer };
let duplexes: [Entry<Option<Duplex>>; 4] = [
Entry::new(None, words.printer_default.clone()),
Entry::new(Some(Duplex::Off), words.one_sided.clone()),
@@ -168,33 +182,62 @@ impl<'a> PrintPanel<'a> {
let mut now = before.clone();
Field::new(words.printer.clone()).id_salt("printer").show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let picked = Select::new(words.printer.clone(), Bind::given(now.printer.clone()), &queues)
.placeholder(words.select_printer.clone())
let picked = Select::new(words.printer.clone(), Bind::given(now.destination.clone()), &queues)
.placeholder(placeholder.clone())
.id_salt("queue")
.show(ui);
if let Some(name) = picked.value() {
if *name != now.printer {
printer_chosen = Some(Destination::Printer(name.clone())); // P3(pdf-print-ocr-w1): PO-P4
if let Some(destination) = picked.value() {
if *destination != now.destination {
printer_chosen = Some(destination.clone());
}
now.printer.clone_from(name);
now.destination.clone_from(destination);
}
let button = Button::new(words.refresh.clone()).enabled(!discovering).id_salt("refresh").show(ui);
refresh |= clicked(&button);
if driver == DriverControls::Properties {
let queue = matches!(&now.destination, Destination::Printer(name) if !name.is_empty());
let button = Button::new(words.properties.clone()).enabled(queue).id_salt("properties").show(ui);
settings_clicked |= clicked(&button);
}
});
});
// The chosen printer's own dialog decides the job controls: they show the settings, disabled, with its note.
let own_dialog = match &now.destination {
Destination::Printer(name) => {
printers.iter().find(|printer| printer.name == *name).and_then(|printer| printer.own_dialog.clone())
}
Destination::File => None,
};
let free = own_dialog.is_none();
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);
}
Row::new().show(ui, |ui, _| {
if let Some(copies) = copies_field(&words.copies, now.copies).enabled(free).show(ui).value().copied().flatten() {
now.copies = (copies.round() as u32).clamp(1, MOST_COPIES);
}
let collate = Checkbox::new(Bind::given(now.collate)).label(words.collate.clone()).enabled(free).id_salt("collate").show(ui);
if let Some(on) = collate.value().copied() {
now.collate = on;
}
let grayscale =
Checkbox::new(Bind::given(now.grayscale)).label(words.grayscale.clone()).enabled(free).id_salt("grayscale").show(ui);
if let Some(on) = grayscale.value().copied() {
now.grayscale = on;
}
});
});
Field::new(words.duplex.clone()).id_salt("duplex").show(ui, |ui, _| {
if let Some(duplex) =
Select::new(words.duplex.clone(), Bind::given(now.duplex), &duplexes).id_salt("duplex").show(ui).value().copied()
{
now.duplex = duplex;
}
});
if driver {
if !duplex_by_layout {
Field::new(words.duplex.clone()).id_salt("duplex").show(ui, |ui, _| {
let picked =
Select::new(words.duplex.clone(), Bind::given(now.duplex), &duplexes).enabled(free).id_salt("duplex").show(ui);
if let Some(duplex) = picked.value().copied() {
now.duplex = duplex;
}
});
}
if let Some(note) = own_dialog {
Text::new(note).shade(Shade::Muted).show(ui);
}
if driver == DriverControls::Page {
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);
@@ -219,13 +262,6 @@ impl<'a> PrintPanel<'a> {
}
});
}
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()
{
now.grayscale = on;
}
});
(now != before).then_some((before, now))
});
// Once per pass, after the real run: the edit the body decided is written.
+238 -9
View File
@@ -1,15 +1,17 @@
//! Stories of `PrintPanel` and `PrintDialog`.
use super::dialog::PrintPreview;
use super::{Duplex, PrintDialog, PrintMarks, PrintPanel, PrintSheet, Printer, Settings};
use super::{
Destination, DriverControls, Duplex, PrintDialog, PrintLayout, PrintMarks, PrintPanel, PrintSection, PrintSheet, Printer, Settings, SheetPage,
};
use craft_ui::contract::{Bind, Show as _, Validity};
use craft_ui::patterns::form_dialogs::DialogFields;
use craft_ui::patterns::form_dialogs::{DialogFields, PagerUnit, PanePager, Param, ParamKind};
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::load::SizedTexture;
use egui::{Color32, ColorImage, Pos2, Rect, Ui, Vec2, pos2};
use egui::{Color32, ColorImage, Pos2, Rect, TextureId, Ui, Vec2, pos2};
fn printers() -> Vec<Printer> {
vec![
@@ -19,9 +21,14 @@ fn printers() -> Vec<Printer> {
]
}
/// The settings the stories start from: the Office printer.
fn office() -> Settings {
Settings { destination: Destination::Printer("Office_1".to_owned()), ..Settings::default() }
}
#[story(PrintPanel<'static>, covers = [], drive = Drive::Never)]
fn print_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = Settings { printer: "Office_1".to_owned(), duplex: Some(Duplex::LongEdge), ..Settings::default() };
let start = Settings { duplex: Some(Duplex::LongEdge), ..office() };
let printers = printers();
PrintPanel::new(Bind::bound(data.value("settings", start)), &printers).show(ui).into()
}
@@ -31,6 +38,14 @@ 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()
}
/// Collate unchecked beside Copies, and Properties… after Refresh.
#[story(PrintPanel<'static>, covers = [], drive = Drive::Never)]
fn print_panel_collate_properties(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = Settings { copies: 3, collate: false, ..office() };
let printers = printers();
PrintPanel::new(Bind::bound(data.value("settings", start)), &printers).driver(DriverControls::Properties).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
@@ -55,10 +70,31 @@ fn preview_sheet(ui: &Ui) -> PrintSheet {
PrintSheet::new(Vec2::new(612.0, 792.0), image, SizedTexture::new(id, Vec2::new(240.0, 320.0)), "360 × 480 pt".into())
}
/// The image box of an `Image` sheet; the whole paper for any other.
fn image_box(sheet: &PrintSheet) -> Rect {
sheet.image_box().unwrap_or_else(|| Rect::from_min_size(Pos2::ZERO, sheet.paper))
}
#[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);
let position = data.value("position", image_box(&sheet).min);
PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into()
}
/// Four pages on a sheet with borders and cut lines, one still rendering as a stand-in.
#[story(PrintPreview<'static>, covers = [])]
fn print_preview_pages(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let sheet = four_up_sheet(ui);
let position = data.value("position", image_box(&sheet).min);
PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into()
}
/// A message in place of the sheet.
#[story(PrintPreview<'static>, covers = [])]
fn print_preview_message(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let sheet = PrintSheet::message(LETTER, "The page range selects no pages.".into(), "No pages".into());
let position = data.value("position", image_box(&sheet).min);
PrintPreview::new("Print preview", &sheet, Bind::bound(position)).show(ui).into()
}
@@ -67,7 +103,7 @@ fn print_preview(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
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 size = image_box(&sheet).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")) }
};
@@ -77,7 +113,7 @@ fn print_preview_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
#[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 start = Settings { duplex: Some(Duplex::LongEdge), ..office() };
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()
@@ -94,8 +130,201 @@ fn print_dialog_discovering(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
#[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()
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet).busy(true).show(ui).into()
}
/// Letter paper in points.
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
const LETTER: Vec2 = Vec2::new(612.0, 792.0);
/// The corners of `rect` with the picture upright: top-left, top-right, bottom-right, bottom-left.
fn upright(rect: Rect) -> [Pos2; 4] {
[rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()]
}
/// The whole of a page picture.
fn whole() -> Rect {
Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0))
}
/// The rendered picture of a document page.
fn page_picture(ui: &Ui) -> TextureId {
TextureCache::texture(ui.ctx(), "print-page-story", || sample_picture(2, [170, 220]))
}
/// One Letter page with its picture, inset half an inch, and a note under the readout.
fn document_sheet(ui: &Ui) -> PrintSheet {
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
let page = SheetPage::new(upright(Rect::from_min_size(pos2(36.0, 36.0), Vec2::new(540.0, 720.0))), "1").picture(page_picture(ui), whole());
PrintSheet::pages(LETTER, vec![page], "Letter, 1 page".into())
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
.printable(Rect::from_min_size(pos2(18.0, 18.0), Vec2::new(576.0, 756.0)))
.notes(vec!["Pages are scaled to fit the printable area.".into()])
}
/// Four pages on a Letter sheet with borders and cut lines; the first has its picture, the others are still rendering
/// and show stand-ins.
fn four_up_sheet(ui: &Ui) -> PrintSheet {
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
let cells = [pos2(18.0, 18.0), pos2(324.0, 18.0), pos2(18.0, 414.0), pos2(324.0, 414.0)];
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
let boxes: Vec<Rect> = cells.iter().map(|at| Rect::from_min_size(*at, Vec2::new(270.0, 360.0))).collect();
let pages = boxes
.iter()
.enumerate()
.map(|(at, rect)| {
let page = SheetPage::new(upright(*rect), (at + 1).to_string());
if at == 0 { page.picture(page_picture(ui), whole()) } else { page }
})
.collect();
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
let cuts = vec![[pos2(306.0, 0.0), pos2(306.0, 792.0)], [pos2(0.0, 396.0), pos2(612.0, 396.0)]];
PrintSheet::pages(LETTER, pages, "Letter, 4 pages per sheet".into()).borders(boxes).cuts(cuts)
}
/// A booklet sheet: two pages side by side on landscape Letter, the last page beside the first.
fn booklet_sheet(ui: &Ui) -> PrintSheet {
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
let last = SheetPage::new(upright(Rect::from_min_size(pos2(36.0, 36.0), Vec2::new(342.0, 540.0))), "4");
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
let first = SheetPage::new(upright(Rect::from_min_size(pos2(414.0, 36.0), Vec2::new(342.0, 540.0))), "1").picture(page_picture(ui), whole());
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
PrintSheet::pages(Vec2::new(792.0, 612.0), vec![last, first], "Booklet, sheet 1 of 2, front".into())
// design: allow[literal-size/vec2](page and paper sizes are document points, story data)
.cuts(vec![[pos2(396.0, 0.0), pos2(396.0, 612.0)]])
}
/// The page-handling section of a document print dialog.
fn page_handling() -> PrintSection {
PrintSection::new(
"Page Handling",
vec![Param::new("autoRotate", "Auto-rotate pages", ParamKind::bool(true)), Param::new("reverse", "Reverse pages", ParamKind::bool(false))],
)
}
/// The document layout over one Letter page, printing to the Office printer.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_document(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = document_sheet(ui);
let sections = [page_handling()];
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.sections(&sections)
.ready(true)
.show(ui)
.into()
}
/// Save as PDF chosen: the list ends with it and the accepting button reads Save as PDF.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_to_file(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = document_sheet(ui);
let start = Settings { destination: Destination::File, ..Settings::default() };
PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.ready(true)
.show(ui)
.into()
}
/// A browser printer whose own dialog decides the job: Copies, Collate, Grayscale and Two-sided are disabled under its
/// note.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_browser_printer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut printers = printers();
printers.push(Printer::new("Browser").own_dialog("The browser's print dialog sets copies, collate, two-sided and colour."));
let sheet = document_sheet(ui);
let start = Settings { destination: Destination::Printer("Browser".to_owned()), ..Settings::default() };
PrintDialog::new(Bind::bound(data.value("settings", start)), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.ready(true)
.show(ui)
.into()
}
/// A booklet sets two-sided printing itself: the panel has no Two-sided row.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_booklet(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = booklet_sheet(ui);
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.duplex_by_layout(true)
.ready(true)
.show(ui)
.into()
}
/// Four pages per sheet, three still rendering as stand-ins, with the pager on the first sheet.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_four_up(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = four_up_sheet(ui);
let pager = PanePager { shown: 1, count: 3, back: false, next: true, unit: PagerUnit::Sheet, ..PanePager::default() };
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.preview_pager(pager)
.ready(true)
.show(ui)
.into()
}
/// A message instead of the sheet: the page range selects no pages.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_message(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = PrintSheet::message(LETTER, "The page range selects no pages.".into(), "No pages".into());
let pager = PanePager { shown: 0, count: 0, back: false, next: false, unit: PagerUnit::Sheet, ..PanePager::default() };
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.preview_pager(pager)
.show(ui)
.into()
}
/// The last sheet: the pager's next button is disabled.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_last_sheet(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = four_up_sheet(ui);
let pager = PanePager { shown: 3, count: 3, back: true, next: false, unit: PagerUnit::Sheet, ..PanePager::default() };
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.preview_pager(pager)
.ready(true)
.show(ui)
.into()
}
/// A section that starts folded under one that is open.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_folded_section(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = document_sheet(ui);
let comments = PrintSection::new("Comments and Forms", vec![Param::new("comments", "Print comments", ParamKind::bool(false))]).folded(false);
let sections = [page_handling().folded(true), comments];
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.sections(&sections)
.ready(true)
.show(ui)
.into()
}
/// A section with buttons in its title row, one disabled.
#[story(PrintDialog<'static>, covers = [], drive = Drive::Never)]
fn print_dialog_section_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let printers = printers();
let sheet = document_sheet(ui);
let sections = [page_handling().button("pageSetup", "Page Setup…", true).button("resetPaper", "Reset", false)];
PrintDialog::new(Bind::bound(data.value("settings", office())), &printers, Bind::given(DialogFields::default()), &sheet)
.layout(PrintLayout::Document)
.sections(&sections)
.ready(true)
.show(ui)
.into()
}
+176 -5
View File
@@ -1,17 +1,19 @@
//! The print dialog's preview: the image box drag.
//! The print dialog: the image box drag, the held Print and a sheet of pages.
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::mpsc::channel;
use craft_behavior::EditEvent;
use craft_print::ui::{HostedPrint, PrintDialog, PrintSheet, Printer, Settings, State};
use craft_print::ui::{Destination, HostedPrint, PrintDialog, PrintFinish, PrintLayout, PrintSheet, Printer, Settings, SheetPage, State};
use craft_ui::contract::Bind;
use craft_ui::dialog::StackDialog as _;
use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, StackDialog as _, dialog_id};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue};
use craft_ui::primitives::TextureCache;
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
use egui::{Color32, ColorImage, Pos2, Rect, Ui, Vec2, pos2, vec2};
use egui::{Color32, ColorImage, Pos2, Rect, Shape, TextureId, Ui, Vec2, pos2, vec2};
/// The image box's size in paper points.
const IMAGE_SIZE: Vec2 = Vec2::new(200.0, 300.0);
@@ -124,3 +126,172 @@ 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 held print dialog over the printer "Office", in a `DialogHost` run every pass. While `twice` is on, egui runs each
/// frame twice and gives the frame's input to its first pass only.
fn held_print(twice: &Rc<Cell<bool>>) -> (Fixture, Rc<RefCell<DialogHost>>) {
let host = Rc::new(RefCell::new(DialogHost::new()));
let (shown, again) = (Rc::clone(&host), Rc::clone(twice));
let mut fixture = Fixture::new(move |ui| {
shown.borrow_mut().run(ui);
if again.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the frame runs twice");
}
});
fixture.room(Vec2::new(1400.0, 1000.0));
let mut state = State::default();
state.settings.destination = Destination::Printer("Office".into());
let mut dialog = HostedPrint::new(state, DialogFields::default(), Vec::new()).held_ok();
let picture = SizedTexture::new(TextureId::default(), IMAGE_SIZE);
dialog.set_sheet(PrintSheet::new(vec2(612.0, 792.0), Rect::from_min_size(IMAGE_AT, IMAGE_SIZE), picture, "200 × 300 pt".into()));
let (send, printers) = channel();
send.send(vec![Printer::new("Office")]).expect("the list is sent");
assert!(dialog.listen(printers), "no discovery runs before the dialog opens");
host.borrow_mut().open(dialog);
fixture.idle(10);
(fixture, host)
}
/// `act` on the open `HostedPrint`; `None` when none is open.
fn on_print<T>(host: &Rc<RefCell<DialogHost>>, act: impl FnOnce(&mut HostedPrint) -> T) -> Option<T> {
host.borrow_mut().get_mut::<HostedPrint>().map(act)
}
/// Whether the Print button is disabled.
fn print_disabled(fixture: &Fixture) -> bool {
let print = fixture.by_label("Print").expect("the Print button");
fixture.tree().is_disabled_key(print.node)
}
/// Why the app refuses the held Print.
const REFUSED: &str = "The printer cannot take this paper size.";
/// Print on a held dialog files its answer once, in a frame that runs twice too, and waits disabled; the app's refusal
/// shows under the rows with Print enabled again until a value changes; an accepted Print closes the dialog with the
/// held answer.
#[trial]
fn a_refused_print_keeps_a_held_dialog_open_until_a_value_changes() {
let twice = Rc::new(Cell::new(false));
let (mut fixture, host) = held_print(&twice);
let id = dialog_id("print");
let print = fixture.by_label("Print").expect("the Print button");
twice.set(true);
fixture.click(&print);
assert_eq!(fixture.passes(), 2, "the frame ran a second pass");
twice.set(false);
fixture.idle(4);
let filed = on_print(&host, HostedPrint::take_ok).flatten().expect("Print files the held answer");
assert_eq!(filed.settings.destination, Destination::Printer("Office".into()));
assert!(on_print(&host, HostedPrint::take_ok).flatten().is_none(), "the answer is filed once");
assert!(host.borrow().is_open::<HostedPrint>(), "a held Print keeps the dialog open");
assert!(print_disabled(&fixture), "Print waits disabled for the app's answer");
assert_eq!(host.borrow().held_state(id), Some(HeldOk::Waiting));
on_print(&host, |dialog| dialog.answer_ok(Err(Label::from(REFUSED))));
assert_eq!(host.borrow().held_state(id), Some(HeldOk::Refused(Label::from(REFUSED))));
fixture.idle(4);
assert!(host.borrow().is_open::<HostedPrint>(), "a refusal keeps the dialog open");
assert!(fixture.by_label(REFUSED).is_some(), "the refusal shows under the rows");
assert!(!print_disabled(&fixture), "a refusal enables Print again");
let grayscale = fixture.by_label("Grayscale").expect("the Grayscale check box");
fixture.click(&grayscale).idle(4);
assert!(fixture.by_label(REFUSED).is_none(), "a changed value ends the refusal");
assert_eq!(host.borrow().held_state(id), None, "nothing is held once the refusal ended");
let print = fixture.by_label("Print").expect("the Print button");
fixture.click(&print).idle(4);
let filed = on_print(&host, HostedPrint::take_ok).flatten().expect("Print files again");
assert!(filed.settings.grayscale, "the held answer has the changed value");
on_print(&host, |dialog| dialog.answer_ok(Ok(())));
assert_eq!(host.borrow().held_state(id), Some(HeldOk::Accepted), "the accepted Print closes at the next pass");
fixture.idle(4);
let answered = host.borrow_mut().take::<HostedPrint>().and_then(DialogResult::ok).expect("the accepted Print closes the dialog");
assert_eq!(answered.finish, PrintFinish::Print);
assert!(answered.settings.grayscale, "the dialog closes with the held answer");
}
/// Taking back a held Print, as the app does when its Save as PDF picker is cancelled, enables Print again with the
/// values kept and no refusal, and the next Print files again.
#[trial]
fn a_withdrawn_print_enables_print_again_with_the_values_kept() {
let twice = Rc::new(Cell::new(false));
let (mut fixture, host) = held_print(&twice);
let grayscale = fixture.by_label("Grayscale").expect("the Grayscale check box");
fixture.click(&grayscale).idle(4);
let print = fixture.by_label("Print").expect("the Print button");
fixture.click(&print).idle(4);
assert!(on_print(&host, HostedPrint::take_ok).flatten().is_some(), "Print files the held answer");
assert!(print_disabled(&fixture), "Print waits disabled for the app's answer");
on_print(&host, HostedPrint::release_ok);
assert_eq!(host.borrow().held_state(dialog_id("print")), None, "nothing is held and no refusal stands");
fixture.idle(4);
assert!(host.borrow().is_open::<HostedPrint>(), "the dialog stays open");
assert!(!print_disabled(&fixture), "Print is enabled again");
assert_eq!(on_print(&host, |dialog| dialog.state().settings.grayscale), Some(true), "the values stay");
let print = fixture.by_label("Print").expect("the Print button");
fixture.click(&print).idle(4);
assert!(on_print(&host, HostedPrint::take_ok).flatten().is_some(), "the next Print files again");
}
/// Letter paper in points.
const LETTER: Vec2 = Vec2::new(612.0, 792.0);
/// A sheet of two pages: a picture turned a quarter counter-clockwise, and a page with no picture yet that hangs over
/// the paper's right edge. The turned page's picture keeps its top edge up the cell's left side, the stand-in shows its
/// number, and both are cut at the paper's edge.
#[trial]
fn a_sheet_of_pages_places_each_page_inside_the_paper() {
// The cell x 72..312, y 72..432: the picture's top-left is the cell's bottom-left, its top-right the cell's top-left.
let turned = [pos2(72.0, 432.0), pos2(72.0, 72.0), pos2(312.0, 72.0), pos2(312.0, 432.0)];
// x 400..700 on paper 612 wide; the centre (550, 600) stays on the paper.
let overhanging = [pos2(400.0, 500.0), pos2(700.0, 500.0), pos2(700.0, 700.0), pos2(400.0, 700.0)];
let made = Rc::new(Cell::new(None::<TextureId>));
let seen = Rc::clone(&made);
let mut settings = Settings::default();
let mut fields = DialogFields::default();
let printers = vec![Printer::new("Office")];
let mut fixture = Fixture::new(move |ui| {
let texture = picture(ui).id;
seen.set(Some(texture));
let whole = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0));
let pages = vec![SheetPage::new(turned, "1").picture(texture, whole), SheetPage::new(overhanging, "2")];
let sheet = PrintSheet::pages(LETTER, pages, "Letter, 2 pages".into());
let _ = PrintDialog::new(Bind::bound(&mut settings), &printers, Bind::bound(&mut fields), &sheet).layout(PrintLayout::Document).show(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0));
fixture.settle();
assert!(fixture.by_label("Image box").is_none(), "a sheet of pages has no image box to drag");
let room = fixture.by_label("Print preview image").expect("the preview is in the access tree").rect;
let scale = (room.width() / LETTER.x).min(room.height() / LETTER.y);
let origin = room.center() - LETTER * scale / 2.0;
let screen = |at: Pos2| origin + at.to_vec2() * scale;
let paper = Rect::from_min_size(origin, LETTER * scale);
let shapes = fixture.frame_shapes();
let texture = made.get().expect("the page picture was made");
let quad = shapes
.iter()
.find_map(|shape| match shape {
Shape::Mesh(mesh) if mesh.texture_id == texture => Some(mesh.clone()),
_ => None,
})
.expect("the first page is painted as a textured quad");
let corners: Vec<Pos2> = quad.vertices.iter().map(|vertex| vertex.pos).collect();
let expected: Vec<Pos2> = turned.iter().map(|corner| screen(*corner)).collect();
assert_eq!(corners.len(), 4, "one quad: {corners:?}");
assert!(corners.iter().zip(&expected).all(|(at, want)| (*at - *want).length() < 0.01), "the quad's corners {corners:?} are {expected:?}");
let uvs: Vec<Pos2> = quad.vertices.iter().map(|vertex| vertex.uv).collect();
assert_eq!(uvs, vec![pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)], "the picture's corners pair with the page's in order");
let reach = screen(pos2(700.0, 700.0));
let stand_in = shapes.iter().any(|shape| match shape {
Shape::Mesh(mesh) => mesh.texture_id != texture && mesh.vertices.iter().any(|vertex| (vertex.pos - reach).length() < 0.5),
_ => false,
});
assert!(stand_in, "the page with no picture is painted as a stand-in");
let number = fixture.texts().iter().find(|run| run.text == "2").expect("the stand-in shows its number");
assert!((number.rect.center() - screen(pos2(550.0, 600.0))).length() < 1.0, "the number is centred on the page: {:?}", number.rect);
assert!(paper.expand(0.5).contains_rect(number.clip), "the page is cut at the paper's edge: clip {:?}, paper {paper:?}", number.clip);
assert!(!number.clip.contains(reach), "the overhang past the paper is not shown");
}
+1
View File
@@ -3,4 +3,5 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod dialog;
mod panel;
mod print;
+55
View File
@@ -0,0 +1,55 @@
//! The print panel: a printer whose own dialog decides the job.
use std::cell::RefCell;
use std::rc::Rc;
use craft_print::ui::{Destination, PrintPanel, Printer, Settings};
use craft_ui::contract::{Bind, Role};
use craft_ui::testing::{Fixture, trial};
use egui::Vec2;
/// The note of the printer whose own dialog decides the job.
const NOTE: &str = "The browser's print dialog sets copies, collate, two-sided and colour.";
/// The job controls the printer's own dialog decides.
const JOB_CONTROLS: [&str; 4] = ["Copies", "Collate", "Grayscale", "Two-sided"];
/// Whether each of the job controls is disabled.
fn disabled(fixture: &Fixture) -> [bool; 4] {
JOB_CONTROLS.map(|label| {
let control = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} control shows"));
fixture.tree().is_disabled_key(control.node)
})
}
/// Picking a printer with its own dialog disables Copies, Collate, Grayscale and Two-sided and shows its note; picking
/// one without enables them again.
#[trial]
fn a_printer_with_its_own_dialog_disables_the_job_controls() {
let settings = Rc::new(RefCell::new(Settings::default()));
settings.borrow_mut().destination = Destination::Printer("Office".into());
let shown = Rc::clone(&settings);
let printers = vec![Printer::new("Office"), Printer::new("Browser").own_dialog(NOTE)];
let mut fixture = Fixture::new(move |ui| {
let _ = PrintPanel::new(Bind::bound(&mut *shown.borrow_mut()), &printers).show(ui);
});
fixture.room(Vec2::new(900.0, 700.0));
fixture.settle();
assert_eq!(disabled(&fixture), [false; 4], "a printer without its own dialog leaves the job controls enabled");
assert!(fixture.by_label(NOTE).is_none(), "no note without the printer's own dialog");
let pick = |fixture: &mut Fixture, from: &str, to: &str| {
let list = fixture.by_role(Role::COMBO_BOX).into_iter().find(|list| fixture.tree().value_of(list.node) == Some(from));
let list = list.unwrap_or_else(|| panic!("the printer list shows {from}"));
fixture.click(&list).idle(3);
let entry = fixture.by_label(to).unwrap_or_else(|| panic!("the list offers {to}"));
fixture.click(&entry).idle(3);
};
pick(&mut fixture, "Office", "Browser");
assert_eq!(settings.borrow().destination, Destination::Printer("Browser".into()), "the pick chose the browser");
assert_eq!(disabled(&fixture), [true; 4], "the printer's own dialog decides the job controls");
assert!(fixture.by_label(NOTE).is_some(), "its note shows under them");
pick(&mut fixture, "Browser", "Office");
assert_eq!(disabled(&fixture), [false; 4], "a printer without its own dialog enables them again");
}
+20 -8
View File
@@ -1,6 +1,6 @@
//! Printer discovery and the chosen queue.
use craft_print::ui::{Discover, Feedback, Printer, State};
use craft_print::ui::{Destination, Discover, Feedback, Printer, State};
use craft_ui::testing::trial;
use std::sync::mpsc::channel;
@@ -17,18 +17,19 @@ fn finds(printers: Vec<Printer>) -> Discover {
})
}
/// A rediscovery keeps the chosen queue while it exists, blocks the job while printers are being found, and drops a
/// queue that is gone.
/// A rediscovery keeps the chosen queue while it exists, blocks the job while printers are being found, and replaces a
/// queue that is gone. Save as PDF waits for no discovery and no rediscovery replaces it.
#[trial]
fn discovery_preserves_choice_and_blocks_stale_or_removed_queues() {
let ctx = egui::Context::default();
let mut state = State::default();
state.settings.printer = "Chosen".into();
let printer = |name: &str| Destination::Printer(name.into());
state.settings.destination = printer("Chosen");
let discover = finds(vec![queue("Default", true), queue("Chosen", false)]);
assert!(state.refresh(&discover));
assert!(!state.ready());
assert!(!state.ready(), "a printer waits for the discovery");
state.poll(&ctx);
assert_eq!(state.settings.printer, "Chosen");
assert_eq!(state.settings.destination, printer("Chosen"));
assert!(state.ready());
let empty = finds(Vec::new());
assert!(state.refresh(&empty));
@@ -36,8 +37,19 @@ fn discovery_preserves_choice_and_blocks_stale_or_removed_queues() {
state.poll(&ctx);
assert!(!state.ready());
assert_eq!(state.message, Some(Feedback::NoPrinters));
assert!(state.settings.printer.is_empty());
assert_eq!(state.settings.destination, printer(""), "a printer that is no longer listed is replaced");
assert!(state.refresh(&discover));
state.poll(&ctx);
assert_eq!(state.settings.printer, "Default");
assert_eq!(state.settings.destination, printer("Default"));
state.settings.destination = Destination::File;
assert!(state.refresh(&empty));
assert!(state.ready(), "Save as PDF does not wait for the discovery");
state.poll(&ctx);
assert_eq!(state.settings.destination, Destination::File, "a discovery does not replace Save as PDF");
assert_eq!(state.message, Some(Feedback::NoPrinters));
assert!(state.ready());
let (_job, outcome) = channel();
assert!(state.begin(outcome).is_ok());
assert!(!state.ready(), "Save as PDF waits while a job runs");
}
+4 -1
View File
@@ -94,7 +94,10 @@ impl<T> HeldAnswer<T> {
/// Takes back the held OK without a refusal: nothing is held, OK is enabled again, and the values stay.
pub fn withdraw(&mut self) {
todo!("L-177")
self.filed = None;
self.untaken = false;
self.accepted = false;
self.refused = None;
}
/// Ends the refusal shown so far (the values it refused changed).
@@ -75,7 +75,7 @@ name = "Printer"
old = "craft_print::ui::Printer"
new = "craft_print::ui::Printer"
status = "same"
note = "`#[non_exhaustive]`: `Printer::new(name)`, `label(..)` and `is_default(..)`."
note = "`#[non_exhaustive]`: `Printer::new(name)`, `label(..)`, `is_default(..)` and `own_dialog(note)`, for a printer whose driver shows its own dialog: the panel disables its job controls and shows the note."
[[type]]
name = "Duplex"
@@ -89,7 +89,14 @@ name = "Settings"
old = "craft_print::ui::Settings"
new = "craft_print::ui::Settings"
status = "same"
note = "`#[non_exhaustive]`: start from `Settings::default()` and set the fields."
note = "`#[non_exhaustive]`: start from `Settings::default()` and set the fields. `printer: String` is `destination: Destination` (`Printer(name)` or `File`, Save as PDF); `collate: bool` is new."
[[type]]
name = "Destination"
old = ""
new = "craft_print::ui::Destination"
status = "replaced"
note = "Where a job goes: `Printer(name)` or `File` (Save as PDF). `File` is ready while no job runs and `poll` keeps it."
[[type]]
name = "Discover"
@@ -156,14 +163,28 @@ name = "PrintPanel"
old = ""
new = "craft_print::ui::PrintPanel"
status = "replaced"
note = "A pattern on `FieldGroup`: `PrintPanel::new(Bind<Settings>, &[Printer])` with `discovering(bool)` and `busy(bool)`; `State::run` shows it. The 32 to 230 width clamp is gone: the panel sizes from its content."
note = "A pattern on `FieldGroup`: `PrintPanel::new(Bind<Settings>, &[Printer])` with `discovering(bool)`, `busy(bool)`, `driver(DriverControls)`, `destinations(Destinations)`, `duplex_by_layout(bool)`, `page(Option<Vec2>)` and `page_error(Option<String>)`; `State::run` shows it. The list edits `Settings::destination`; Copies, Collate and Grayscale share a row. The 32 to 230 width clamp is gone: the panel sizes from its content."
[[type]]
name = "DriverControls"
old = ""
new = "craft_print::ui::DriverControls"
status = "replaced"
note = "`#[non_exhaustive]`, replaces the panel's `driver: bool`: `None`, `Properties` (Properties… after Refresh) or `Page` (Print Settings…, Portrait/Landscape and the page line)."
[[type]]
name = "Destinations"
old = ""
new = "craft_print::ui::Destinations"
status = "replaced"
note = "`#[non_exhaustive]`: `Printers`, or `PrintersAndFile` with Save as PDF after the printers."
[[type]]
name = "PrintPanelOutput"
old = ""
new = "craft_print::ui::PrintPanelOutput"
status = "replaced"
note = "`{ response, refresh }`; `refresh` is the Refresh button pressed this pass."
note = "`#[non_exhaustive]` `{ response, refresh, printer_chosen, settings_clicked, turned }`; `refresh` is the Refresh button pressed this pass, `printer_chosen: Option<Destination>` the destination picked this pass."
# One entry per renamed, removed or reshaped setter or constructor.