Framework follow-ups F-1..F-4 (L-205): HostedPrint::take_settings_clicked; choice rows separated_at with a story; PrintPreviewOutput::paper_px and HostedPrint::take_paper_px; ScriptedFiles::failing_writes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dylan M. Taylor
2026-11-18 10:55:06 -05:00
co-authored by Claude Opus 5.5
parent 6b2742f9c3
commit 7ee6bb9793
8 changed files with 225 additions and 26 deletions
+18 -8
View File
@@ -7,7 +7,7 @@
//! one; otherwise the service starts it in the last folder it remembers for the
//! [`PickRequest::purpose`]. It applies the extension policy to a saved name before the app sees it.
use std::collections::{HashMap, VecDeque};
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
@@ -357,6 +357,8 @@ struct ScriptState {
open: Vec<(PickId, PickRequest)>,
answered: Vec<PickAnswer>,
files: HashMap<PathBuf, Vec<u8>>,
/// Paths a write to is refused ([`ScriptedFiles::failing_writes`]).
refused: HashSet<PathBuf>,
}
impl ScriptedFiles {
@@ -395,6 +397,14 @@ impl ScriptedFiles {
self
}
/// Refuses every write to `path`: [`Files::write`] returns [`FileError::PermissionDenied`] for it and keeps the
/// bytes it had. Other paths write as before.
#[must_use]
pub fn failing_writes(self, path: impl Into<PathBuf>) -> Self {
self.state().refused.insert(path.into());
self
}
/// Queues the answer of the next pick that has none yet.
pub fn queue(&self, picked: Picked) {
self.state().queued.push_back(picked);
@@ -450,11 +460,8 @@ impl Files for ScriptedFiles {
let id = PickId(state.next);
let suggested = (state.save_suggested && request.kind == PickKind::Save).then(|| Self::suggested(&request));
state.asked.push(request.clone());
let picked = if state.held {
state.queued.pop_front()
} else {
Some(suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled))
};
let picked =
if state.held { state.queued.pop_front() } else { Some(suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled)) };
match picked {
Some(picked) => state.answered.push(PickAnswer { id, request, picked }),
None => state.open.push((id, request)),
@@ -484,7 +491,11 @@ impl Files for ScriptedFiles {
// Kept in memory whatever the intent; no page takes the bytes.
fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
self.state().files.insert(path.to_owned(), bytes.to_vec());
let mut state = self.state();
if state.refused.contains(path) {
return Err(FileError::PermissionDenied(path.to_owned()));
}
state.files.insert(path.to_owned(), bytes.to_vec());
Ok(false)
}
@@ -515,4 +526,3 @@ fn with_path(e: std::io::Error, path: &Path) -> FileError {
other => other,
}
}
+13
View File
@@ -263,6 +263,19 @@ mod tests {
const APP: AppInfo = AppInfo { id: "test", name: "Test", version: "1.0" };
/// A write to a path set with `failing_writes` returns the refused-write error and keeps what the path held; every
/// other path writes: a refusal that wrote anyway, or that refused every path, would test a failed save on the
/// wrong path.
#[test]
fn failing_writes_refuse_only_their_path() {
let files = ScriptedFiles::new().with_file("/docs/a.pdf", b"old".to_vec()).failing_writes("/docs/a.pdf");
let refused = files.write(std::path::Path::new("/docs/a.pdf"), b"new", WriteIntent::Save);
assert_eq!(refused, Err(FileError::PermissionDenied("/docs/a.pdf".into())));
assert_eq!(files.file(std::path::Path::new("/docs/a.pdf")).as_deref(), Some(&b"old"[..]), "the refused write kept the old bytes");
assert_eq!(files.write(std::path::Path::new("/docs/b.pdf"), b"new", WriteIntent::Save), Ok(false));
assert_eq!(files.file(std::path::Path::new("/docs/b.pdf")).as_deref(), Some(&b"new"[..]));
}
#[cfg(feature = "ui")]
#[test]
fn installed_host_survives_a_memory_reset() {
+50 -2
View File
@@ -595,7 +595,16 @@ impl Component for PrintPreview<'_> {
}
fn finish(self, cx: Cx<'_, Self>) -> PrintPreviewOutput {
PrintPreviewOutput { edit: cx.edit_response() }
let scale = cx.env.scale().0;
let paper_px = match &self.sheet.content {
SheetContent::Message(_) => None,
_ => self.place(cx.rect).map(|place| {
let size = place.rect(Rect::from_min_size(Pos2::ZERO, self.sheet.paper)).size();
// A float to integer cast saturates and maps NaN to zero, so an odd size cannot wrap.
[(size.x * scale).round() as u32, (size.y * scale).round() as u32]
}),
};
PrintPreviewOutput { edit: cx.edit_response(), paper_px }
}
}
@@ -605,6 +614,9 @@ 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>,
/// The page box as drawn this pass, in physical pixels (its rect times `pixels_per_point`, rounded, saturating).
/// `None` before the preview is drawn, while the paper has no area, and for a message in place of a sheet.
paper_px: Option<[u32; 2]>,
}
impl Outcome for PrintPreviewOutput {
@@ -692,8 +704,13 @@ pub struct PrintDialogOutput {
pub moved: EditEvents<egui::Pos2>,
/// The panel's Refresh was pressed.
pub refresh: bool,
/// The panel's Properties… was pressed.
pub(crate) settings_clicked: bool,
/// The dialog's requests of the host.
pub requests: HostRequests,
/// The preview's page box as drawn this pass, in physical pixels: the size to render previews at. `None` before it
/// is drawn.
pub paper_px: Option<[u32; 2]>,
/// The pager press made this pass.
pub preview_step: Option<PagerStep>,
/// The destination the user picked in the panel this pass.
@@ -774,11 +791,15 @@ impl<'a> PrintDialog<'a> {
}
let mut moved = EditEvents::new();
let mut refresh = false;
let mut settings_clicked = false;
let mut paper_px = None;
let mut preview_step = None;
let mut printer_chosen = None;
let shown = form.show(ui, |ui, form, values| {
moved = EditEvents::new();
refresh = false;
settings_clicked = false;
paper_px = None;
preview_step = None;
printer_chosen = None;
// A measuring run closes nothing: the real run of the same pass makes the close.
@@ -807,6 +828,7 @@ impl<'a> PrintDialog<'a> {
.duplex_by_layout(duplex_by_layout)
.show(ui);
refresh |= panel.refresh;
settings_clicked |= panel.settings_clicked;
if panel.printer_chosen.is_some() {
printer_chosen = panel.printer_chosen;
}
@@ -820,6 +842,7 @@ impl<'a> PrintDialog<'a> {
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);
paper_px = preview.paper_px;
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));
@@ -871,7 +894,9 @@ impl<'a> PrintDialog<'a> {
finish,
moved,
refresh,
settings_clicked,
requests: shown.requests,
paper_px,
preview_step,
printer_chosen,
held,
@@ -907,6 +932,10 @@ pub struct HostedPrint {
sheet: Option<PrintSheet>,
moves: Vec<EditEvent<egui::Pos2>>,
refresh: bool,
/// The panel's Properties… press, not taken yet.
settings_clicked: bool,
/// The page box the preview drew, in physical pixels, not taken yet.
paper_px: Option<[u32; 2]>,
requests: HostRequests,
json_form: Option<Box<JsonForm>>,
layout: PrintLayout,
@@ -935,6 +964,8 @@ impl HostedPrint {
sheet: None,
moves: Vec::new(),
refresh: true,
settings_clicked: false,
paper_px: None,
requests: HostRequests::new(),
json_form: None,
layout: PrintLayout::Image,
@@ -961,6 +992,19 @@ impl HostedPrint {
std::mem::take(&mut self.refresh)
}
/// Whether the panel's Properties… was pressed since the last call: the app opens the driver's options. The press is
/// filed in the pass that receives it and taken once.
pub fn take_settings_clicked(&mut self) -> bool {
std::mem::take(&mut self.settings_clicked)
}
/// The page box the preview drew, in physical pixels (width, height), for the app to render the preview at. It is
/// filed in the pass that drew the preview and taken once: `None` until the next pass that draws it, and while the
/// preview shows a message or a paper with no area.
pub fn take_paper_px(&mut self) -> Option<[u32; 2]> {
self.paper_px.take()
}
/// Asks for a printer list again on the next pass, as Refresh does: the list the app sent was not the system's
/// (its spooler was busy).
pub fn request_refresh(&mut self) {
@@ -1140,9 +1184,13 @@ impl StackDialog for HostedPrint {
dialog = dialog.refusal(refusal);
}
let shown = dialog.show(ui);
let PrintDialogOutput { closed, finish, moved, refresh, requests, printer_chosen, held, .. } = shown;
let PrintDialogOutput { closed, finish, moved, refresh, settings_clicked, paper_px, requests, printer_chosen, held, .. } = shown;
self.moves.extend(moved);
if paper_px.is_some() {
self.paper_px = paper_px;
}
self.refresh |= refresh;
self.settings_clicked |= settings_clicked;
if printer_chosen.is_some() {
self.printer_chosen = printer_chosen;
}
+56 -2
View File
@@ -5,12 +5,14 @@ use std::rc::Rc;
use std::sync::mpsc::channel;
use craft_behavior::EditEvent;
use craft_print::ui::{Destination, HostedPrint, PrintDialog, PrintFinish, PrintLayout, PrintSheet, Printer, Settings, SheetPage, State};
use craft_print::ui::{
Destination, DriverControls, HostedPrint, PrintDialog, PrintFinish, PrintLayout, PrintSheet, Printer, Settings, SheetPage, State,
};
use craft_ui::contract::Bind;
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::runtime::env::{Label, Scale};
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
use egui::{Color32, ColorImage, Pos2, Rect, Shape, TextureId, Ui, Vec2, pos2, vec2};
@@ -295,3 +297,55 @@ fn a_sheet_of_pages_places_each_page_inside_the_paper() {
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");
}
/// Properties… on a hosted print dialog is filed in the pass that receives the press and taken once, in a frame that
/// runs twice too: a press taken again, or lost to the second pass, leaves the app opening the driver's options twice
/// or never.
#[trial]
fn a_properties_press_is_taken_once() {
let twice = Rc::new(Cell::new(true));
let (mut fixture, host) = held_print(&twice);
on_print(&host, |dialog| dialog.set_driver(DriverControls::Properties));
fixture.idle(4);
assert_eq!(on_print(&host, HostedPrint::take_settings_clicked), Some(false), "nothing is pressed yet");
let properties = fixture.by_label("Properties…").expect("the Properties… button");
fixture.click(&properties);
assert_eq!(fixture.passes(), 2, "the frame ran a second pass");
fixture.idle(4);
assert_eq!(on_print(&host, HostedPrint::take_settings_clicked), Some(true), "the press is filed for the app");
assert_eq!(on_print(&host, HostedPrint::take_settings_clicked), Some(false), "the press is taken once");
fixture.idle(4);
assert_eq!(on_print(&host, HostedPrint::take_settings_clicked), Some(false), "later passes file no press");
}
/// The page box the hosted dialog drew at `scale` pixels per point, taken from the dialog.
fn paper_px_at(scale: f32) -> [u32; 2] {
let twice = Rc::new(Cell::new(false));
let (mut fixture, host) = held_print(&twice);
fixture.scale(Scale::new(scale));
fixture.idle(4);
on_print(&host, HostedPrint::take_paper_px).flatten().expect("the page box is reported once drawn")
}
/// The preview reports the page box it drew, in physical pixels, so the app renders previews at that size. The preview's
/// width is fixed in points, so the same dialog at twice the scale has a box twice as large, within a pixel. A constant,
/// or a box in points, would not follow the scale.
#[trial]
fn the_paper_box_follows_the_scale() {
let [one_w, one_h] = paper_px_at(1.0);
let [two_w, two_h] = paper_px_at(2.0);
assert!(one_w > 0 && one_h > 0, "a box at scale 1: {one_w}×{one_h}");
assert!(two_w.abs_diff(one_w * 2) <= 1 && two_h.abs_diff(one_h * 2) <= 1, "{one_w}×{one_h} at 1.0, {two_w}×{two_h} at 2.0");
}
/// The page box is filed in the pass that draws it and taken once: `None` after, until the next pass that draws it.
#[trial]
fn the_paper_box_is_taken_once() {
let twice = Rc::new(Cell::new(false));
let (mut fixture, host) = held_print(&twice);
let first = on_print(&host, HostedPrint::take_paper_px).flatten();
assert!(first.is_some(), "the box is filed once the dialog is drawn");
assert_eq!(on_print(&host, HostedPrint::take_paper_px), Some(None), "the box is taken once");
fixture.idle(2);
assert_eq!(on_print(&host, HostedPrint::take_paper_px).flatten(), first, "the next drawn pass files it again");
}
@@ -491,6 +491,8 @@ pub(crate) struct RowOptions {
option_descriptions: Vec<(String, Label)>,
/// The row's select has a search field.
searchable: bool,
/// The indexes of the options a choice row draws a separator before ([`Param::separated_at`]).
separated_at: Vec<usize>,
/// The keys a change of the row's value removes ([`Param::resets`]).
resets: Vec<String>,
}
@@ -665,6 +667,18 @@ impl Param {
self
}
/// Draws a separator line before the option at `index` in a choice row's open list, between two groups of options
/// (standard and custom paper sizes). Repeat the call for each group start. An `index` of 0, or past the last
/// option, draws nothing: a separator sits between options.
#[must_use]
pub fn separated_at(mut self, index: usize) -> Self {
let separated = &mut self.options.get_or_insert_default().separated_at;
if !separated.contains(&index) {
separated.push(index);
}
self
}
/// The keys of the rows that depend on this one (Match Color's source layer on its source document): changing this
/// row's value to a different one, through the row, automation (`set_param_field`) or a host answer, removes them,
/// so those rows start over from their default. Setting the value it holds keeps them.
@@ -1052,6 +1066,11 @@ impl RowOptions {
self.searchable
}
/// Whether a choice row's list has a separator before the option at `index`.
pub(crate) fn separated_before(&self, index: usize) -> bool {
self.separated_at.contains(&index)
}
/// The units of a number row.
pub(crate) fn units(&self) -> Option<&UnitChoices> {
self.units.as_ref()
@@ -246,11 +246,8 @@ impl<'a> ParamRows<'a> {
})
};
let shown = if read_only { with_env(ui, |scope| scope.read_only = Some(true), group) } else { group(ui) };
let (pick_color, path, eyedropper, listing, out_of_range, action) = if read_only {
Default::default()
} else {
(pass.color, pass.path, pass.eyedropper, pass.listing, pass.out_of_range, pass.action)
};
let (pick_color, path, eyedropper, listing, out_of_range, action) =
if read_only { Default::default() } else { (pass.color, pass.path, pass.eyedropper, pass.listing, pass.out_of_range, pass.action) };
ParamRowsOutput { response: shown.output, changed, values, pick_color, path, eyedropper, listing, out_of_range, action, edited }
}
}
@@ -601,8 +598,15 @@ impl<'p> Pass<'p> {
fn choice(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)]) {
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
let entries: Vec<Entry<String>> = options.iter().map(|(id, label)| option_entry(line.param, id, label)).collect();
let searchable = line.param.option().searchable();
let row = line.param.option();
let mut entries: Vec<Entry<String>> = Vec::with_capacity(options.len());
for (at, (id, label)) in options.iter().enumerate() {
if at > 0 && row.separated_before(at) {
entries.push(Entry::separator());
}
entries.push(option_entry(line.param, id, label));
}
let searchable = row.searchable();
line.show(ui, |ui| {
let mut select = Select::new(line.name.clone(), Bind::given(value.clone()), &entries);
if searchable {
@@ -89,13 +89,7 @@ fn param_rows_enable_off(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
/// Options with descriptions and a disabled option with its reason, on a Choice row and a Radio row.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_option_descriptions(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let modes = || {
vec![
("fast".to_owned(), "Fast".into()),
("accurate".to_owned(), "Accurate".into()),
("cloud".to_owned(), "Cloud".into()),
]
};
let modes = || vec![("fast".to_owned(), "Fast".into()), ("accurate".to_owned(), "Accurate".into()), ("cloud".to_owned(), "Cloud".into())];
let described = |param: Param| {
param
.option_description("fast", "Lower accuracy, finishes in seconds")
@@ -110,6 +104,20 @@ fn param_rows_option_descriptions(ui: &mut Ui, data: &mut StoryData) -> StoryOut
ParamRows::new("Recognize Text", &params, Bind::bound(fields)).show(ui).into()
}
/// A Choice row whose open list has a separator line between the standard paper sizes and the custom one.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_choice_separated(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let sizes = vec![
("letter".to_owned(), "Letter".into()),
("legal".to_owned(), "Legal".into()),
("a4".to_owned(), "A4".into()),
("custom".to_owned(), "Custom".into()),
];
let params = vec![Param::new("paper", "Paper Size", ParamKind::choice(sizes, Some("letter".to_owned()))).separated_at(3)];
let fields = data.value("fields", DialogFields::new());
ParamRows::new("Page Setup", &params, Bind::bound(fields)).show(ui).into()
}
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = params();
@@ -234,6 +234,49 @@ fn a_blend_row_steps_and_picks_by_its_keys_inside_the_dialog() {
assert_eq!(held().as_deref(), Some("multiply"), "Down on the closed list skips the greyed mode");
}
/// The y of each thin horizontal line in `shapes`.
fn rule_ys(shapes: &[egui::Shape]) -> Vec<f32> {
shapes
.iter()
.filter_map(|shape| match shape {
egui::Shape::LineSegment { points, .. } if points[0].y == points[1].y => Some(points[0].y),
egui::Shape::Rect(rect) if rect.rect.height() <= 2.0 && rect.rect.width() > 20.0 => Some(rect.rect.center().y),
_ => None,
})
.collect()
}
/// `separated_at(index)` draws the framework's list separator before that option of a choice row's open list and
/// between no other two: a separator placed by the wrong index, or one drawn on every option, would split the standard
/// paper sizes from the wrong neighbour.
#[trial]
fn a_choice_row_draws_its_separator_before_the_named_option() {
let sizes: Vec<(String, Label)> = [("letter", "Letter"), ("legal", "Legal"), ("a4", "A4"), ("custom", "Custom")]
.into_iter()
.map(|(id, label)| (id.to_owned(), label.into()))
.collect();
let params = vec![Param::new("paper", "Paper Size", ParamKind::choice(sizes, Some("letter".to_owned()))).separated_at(3)];
let values = Rc::new(RefCell::new(DialogFields::new()));
let shown = values.clone();
let mut fixture = Fixture::new(move |ui| {
let _ = ParamRows::new("Page Setup", &params, Bind::bound(&mut *shown.borrow_mut())).show(ui);
});
fixture.room(Vec2::new(1200.0, 800.0));
fixture.settle();
let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the choice field shows");
fixture.click(&field);
fixture.idle(3);
let line_of = |fixture: &Fixture, text: &str| {
let run = fixture.texts().iter().rev().find(|run| run.text == text).unwrap_or_else(|| panic!("the list shows {text}"));
run.rect
};
let (legal, a4, custom) = (line_of(&fixture, "Legal"), line_of(&fixture, "A4"), line_of(&fixture, "Custom"));
let ys = rule_ys(&fixture.frame_shapes());
assert!(ys.iter().any(|y| *y > a4.bottom() && *y < custom.top()), "a line between A4 and Custom: {ys:?}, A4 {a4:?}, Custom {custom:?}");
assert!(!ys.iter().any(|y| *y > legal.bottom() && *y < a4.top()), "no line between Legal and A4: {ys:?}");
}
/// A pattern row shows the first pattern for a stored id the rows lack without writing it, a pick writes the pattern's
/// id, and a group header takes no pick.
#[trial]