From 2b38e14dee1919f82eee57b0a7c252849e5e4c39 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 15 Nov 2026 04:46:06 +0000 Subject: [PATCH] dialogs-w13: net change of 5 commits - dialogs-w13: written by an agent - dialogs-w13: finished by an agent - dialogs-w13: review fixes (review-1) - Integration: draw's screen tests keep framework-01-w11's presets module beside pattern_fill - dialogs-w13: guides trials say why a reopen is a first pass (dialogs run round) --- crates/draw/src/ui/pattern/dialog.rs | 98 +++++++-- crates/draw/src/ui/pattern/editor.rs | 2 +- crates/draw/src/ui/shape_drag/dialog.rs | 170 +++++++++++---- crates/draw/tests/it/main.rs | 3 + crates/draw/tests/it/pattern_fill.rs | 41 ++++ crates/draw/tests/it/shape_drag.rs | 72 ++++++- crates/ui-contract/src/runtime/env/units.rs | 40 +++- .../src/patterns/form_dialogs/guides.rs | 196 ++++++++++++++++-- .../patterns/form_dialogs/guides/new_guide.rs | 189 ++++++++++++++--- .../patterns/form_dialogs/guides/trials.rs | 62 +++++- .../src/patterns/form_dialogs/size_model.rs | 112 ++++++++-- .../src/patterns/form_dialogs/sizing.rs | 74 ++++++- .../patterns/form_dialogs/sizing/canvas.rs | 81 ++++++-- .../src/patterns/form_dialogs/sizing/image.rs | 104 ++++++++-- .../tests/it/form_dialogs/hosted.rs | 57 ++++- .../tests/it/form_dialogs/size_model.rs | 94 ++++++++- 16 files changed, 1194 insertions(+), 201 deletions(-) create mode 100644 crates/draw/tests/it/pattern_fill.rs diff --git a/crates/draw/src/ui/pattern/dialog.rs b/crates/draw/src/ui/pattern/dialog.rs index 170bd8ac2..9f9ffb737 100644 --- a/crates/draw/src/ui/pattern/dialog.rs +++ b/crates/draw/src/ui/pattern/dialog.rs @@ -1,13 +1,16 @@ //! [`PatternFillDialog`]. -use super::editor::SwatchPainter; -use super::{PatternFillEditor, PatternFillOptions, PatternSwatch, PatternWords}; -use craft_ui::contract::Bind; -use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use super::editor::{ANGLE_RANGE, SwatchPainter}; +use super::{PatternColors, PatternFillEditor, PatternFillOptions, PatternSwatch, PatternWords}; +use craft_theme::Srgba; +use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _}; +use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft_ui::layout_components::Stack; use craft_ui::patterns::form_dialogs::FormDialog; use craft_ui::primitives::ContentPainterCx; use craft_ui::runtime::env::Env; use egui::{Rect, Ui}; +use serde_json::{Value, json}; /// Photoshop's Pattern Fill dialog (Layer, New Fill Layer, Pattern...; a Pattern Fill layer's thumbnail; Layer Content /// Options): [`PatternFillEditor`] in bitmap mode with OK and Cancel. No Preview check box: the app previews live @@ -25,6 +28,8 @@ pub struct PatternFillDialog { thumbnails: Option, changed: bool, canvas: Option, + /// Whether the dialog is open: bound to the form's open state, so the host's dialog closes with it. + open: bool, } impl PatternFillDialog { @@ -38,6 +43,7 @@ impl PatternFillDialog { thumbnails: None, changed: false, canvas: None, + open: true, } } @@ -56,10 +62,11 @@ impl PatternFillDialog { self } - /// Sets the pattern's phase, as the app's canvas drag does (M-12). + /// Sets the pattern's phase, as the app's canvas drag does (M-12); [`changed`](Self::changed) reports it so the + /// app refreshes its preview. pub fn set_phase(&mut self, phase: [f64; 2]) { - let _ = phase; - todo!("dl.K38") + self.current.phase = phase; + self.changed = true; } /// The values the fields show now, for the app's live preview. @@ -82,18 +89,55 @@ impl PatternFillDialog { impl StackDialog for PatternFillDialog { type Result = PatternFillOptions; - fn json_fields(&self) -> Option { - todo!("dl.K36") + /// `pattern`, `scale`, `angle`, `link`, `phase` (`[x, y]`) and `colors` (`{foreground, background}` in the + /// `Srgba` form, `null` in bitmap mode). + fn json_fields(&self) -> Option { + let options = &self.current; + let colors = options.colors.map(|colors| json!({ "foreground": colors.foreground, "background": colors.background })); + Some(json!({ + "pattern": options.pattern, + "scale": options.scale, + "angle": options.angle, + "link": options.link, + "phase": options.phase, + "colors": colors, + })) } - fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> { - let _ = (ctx, field, value); - todo!("dl.K36") + /// Sets a field as the editor's row does: `pattern` takes one of the swatches, `scale` and `angle` are held to + /// their ranges. The bitmap rows (`scale`, `angle`, `link`, `phase`) refuse as inactive in preset mode, and + /// `colors` in bitmap mode. + fn set_json_field(&mut self, _ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { + let rejects = || FieldRefusal::Rejects(&value).message(field); + let preset = self.current.colors.is_some(); + let bitmap_row = matches!(field, "scale" | "angle" | "link" | "phase"); + if (bitmap_row && preset) || (field == "colors" && !preset) { + return Err(FieldRefusal::Inactive.message(field)); + } + let options = &mut self.current; + match field { + "pattern" => { + let pattern = value.as_str().filter(|id| self.swatches.iter().any(|swatch| swatch.id == *id)).ok_or_else(rejects)?; + options.pattern = pattern.to_owned(); + } + "scale" => options.scale = value.as_f64().ok_or_else(rejects)?.clamp(*PatternFillOptions::SCALE.start(), *PatternFillOptions::SCALE.end()), + "angle" => options.angle = value.as_f64().ok_or_else(rejects)?.clamp(*ANGLE_RANGE.start(), *ANGLE_RANGE.end()), + "link" => options.link = value.as_bool().ok_or_else(rejects)?, + "phase" => options.phase = serde_json::from_value::<[f64; 2]>(value.clone()).map_err(|_| rejects())?, + "colors" => { + let color = |key: &str| value.get(key).and_then(|color| serde_json::from_value::(color.clone()).ok()); + let (Some(foreground), Some(background)) = (color("foreground"), color("background")) else { return Err(rejects()) }; + options.colors = Some(PatternColors::new(foreground, background)); + } + _ => return Err(FieldRefusal::Unknown.message(field)), + } + self.changed = true; + Ok(()) } - fn confirm(&mut self, ctx: &egui::Context) -> Option { - let _ = ctx; - todo!("dl.K36") + /// Answers the current values, as OK does. + fn confirm(&mut self, _ctx: &egui::Context) -> Option { + Some(self.current.clone()) } fn id(&self) -> DialogId { @@ -102,15 +146,23 @@ impl StackDialog for PatternFillDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let words = Env::of(ui).words::(); - let PatternFillDialog { current, swatches, thumbnails, changed, canvas, .. } = self; - let _ = canvas; // P3(dialogs-w13): dl.K38 pass_canvas_gesture while Link with Layer is on. + let PatternFillDialog { current, swatches, thumbnails, changed, canvas, open, .. } = self; let before = current.clone(); - let shown = FormDialog::new(words.title.clone(), Bind::bound(&mut *current)).show(ui, |ui, _, value| { - let mut editor = PatternFillEditor::new(words.pattern.clone(), Bind::bound(value), swatches); - if let Some(painter) = thumbnails.clone() { - editor = editor.thumbnails(move |cx, rect, swatch| painter.paint(cx, rect, swatch)); - } - editor.show(ui); + let form = FormDialog::new(words.title.clone(), Bind::bound(&mut *current)).opened(Bind::bound(open)); + let shown = form.show(ui, |ui, _, value| { + // While Link with Layer is on, a drag on the document moves the pattern: the modal layer lets that press + // through to the canvas, and the app's drag sets the phase. + let link = value.link && value.colors.is_none(); + Stack::new().show(ui, |ui, cx| { + if let (Some(canvas), true) = (*canvas, link) { + cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY); + } + let mut editor = PatternFillEditor::new(words.pattern.clone(), Bind::bound(&mut *value), swatches); + if let Some(painter) = thumbnails.clone() { + editor = editor.thumbnails(move |cx, rect, swatch| painter.paint(cx, rect, swatch)); + } + editor.show(ui); + }); true }); *changed = *current != before; diff --git a/crates/draw/src/ui/pattern/editor.rs b/crates/draw/src/ui/pattern/editor.rs index 07553c0ba..cd7700773 100644 --- a/crates/draw/src/ui/pattern/editor.rs +++ b/crates/draw/src/ui/pattern/editor.rs @@ -19,7 +19,7 @@ use craft_ui::value_drag::AngleDial; use egui::{Rect, Response, Ui}; /// The angle of the dial runs over half a turn each way. -const ANGLE_RANGE: std::ops::RangeInclusive = -180.0..=180.0; +pub(super) const ANGLE_RANGE: std::ops::RangeInclusive = -180.0..=180.0; type SwatchPaintFn = Arc, Rect, &PatternSwatch) + Send + Sync>; diff --git a/crates/draw/src/ui/shape_drag/dialog.rs b/crates/draw/src/ui/shape_drag/dialog.rs index e5316d278..554900769 100644 --- a/crates/draw/src/ui/shape_drag/dialog.rs +++ b/crates/draw/src/ui/shape_drag/dialog.rs @@ -9,18 +9,19 @@ use craft_behavior::Mixed; use craft_theme::variant::Tone; use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, Entry, Props as _, Remember as _, Show as _, ShowContainer as _}; -use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::notices::{Notice, NoticeLayout}; use craft_ui::patterns::form_dialogs::{FormDialog, GuideUnits}; use craft_ui::pickers::UnitSelect; use craft_ui::runtime::env::{Env, Label, UnitKind, Units}; -use craft_ui::runtime::memory::SaveKey; +use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft_ui::sections::DialogRole; use craft_ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; use egui::Ui; use kurbo::{Point, Rect}; use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use super::ShapeKind; use super::words::CreateShapeWords; @@ -36,8 +37,8 @@ const MAX_RADIUS: f64 = 10_000.0; /// What Create Shape opens with: the kind, the clicked point and the document's units, and the /// values the fields start from. The dialog replaces width, height, From Center and the star ratio -/// with the remembered ones for the kind on its first pass unless [`recalled`](Self::recalled) is -/// set. +/// with the remembered ones for the kind before its first pass, OK or field set, unless +/// [`recalled`](Self::recalled) is set. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct CreateShapeOptions { @@ -162,6 +163,8 @@ pub struct CreateShapeDialog { options: CreateShapeOptions, /// Each size field's unit for this opening. units: [UnitKind; 2], + /// Whether the dialog is open: bound to the form's open state, so the host's dialog closes with it. + open: bool, } /// The document a dialog without [`CreateShapeOptions::units`] measures in: pixels, with no percent. @@ -269,7 +272,17 @@ impl CreateShapeDialog { /// Create Shape with `options`. pub fn new(options: CreateShapeOptions) -> Self { let ruler = options.units.map_or(UnitKind::Pixels, |units| units.ruler); - CreateShapeDialog { id: dialog_id("shape.create"), options, units: [ruler; 2] } + CreateShapeDialog { id: dialog_id("shape.create"), options, units: [ruler; 2], open: true } + } + + /// Puts the kind's remembered values over the opening ones, once, before the first show, OK or set reads them: + /// automation may set or confirm before any pass. + fn recall(&mut self, ctx: &egui::Context) { + if std::mem::replace(&mut self.options.recalled, true) { + return; + } + let memory = saved_value::(ctx, &save_key(self.options.kind)); + recalled(&mut self.options, &memory); } /// Whether `kind` has a Create dialog: every kind but Line and Custom (PhotoCraft has none for @@ -294,9 +307,8 @@ fn size_field( document: &GuideUnits, entries: &[Entry], ) { - let extent = if axis == 0 { document.width_px } else { document.height_px }; - let pixels = if axis == 0 { size.0 } else { size.1 }; - let shown = document.from_pixels(pixels, *unit, extent).unwrap_or(0.0); + let extent = extent_of(document, axis); + let shown = shown_size(document, axis, *unit, *size); let (low, high) = ( document.from_pixels(*CreateShapeOptions::SIZE.start(), *unit, extent), document.from_pixels(*CreateShapeOptions::SIZE.end(), *unit, extent), @@ -311,20 +323,40 @@ fn size_field( } if let Some(value) = out.edit.value().copied().flatten() && shown_places(value, *unit) != shown_places(shown, *unit) - && let Some(px) = document.to_pixels(length(value, *unit), extent) { - let px = thousandths(px); - if axis == 0 { - size.0 = px; - } else { - size.1 = px; - } + set_size(document, axis, *unit, size, value); } } -/// The units a shape's size is entered in: pixels, a percentage of the document and the physical lengths. -fn length_units() -> impl Iterator { - [UnitKind::Pixels, UnitKind::Percent].into_iter().chain(UnitKind::LENGTHS) +/// The pixels a percentage of size field `axis` is of: the document's width or height. +fn extent_of(document: &GuideUnits, axis: usize) -> f64 { + if axis == 0 { document.width_px } else { document.height_px } +} + +/// Size field `axis`'s value in `unit`, as the field shows it. +fn shown_size(document: &GuideUnits, axis: usize, unit: UnitKind, size: (f64, f64)) -> f64 { + let pixels = if axis == 0 { size.0 } else { size.1 }; + document.from_pixels(pixels, unit, extent_of(document, axis)).unwrap_or(0.0) +} + +/// Sets size field `axis` from `value` in `unit`, kept to a thousandth of a pixel, as a commit in the field does; +/// `false` and nothing changes when `value` does not convert. +fn set_size(document: &GuideUnits, axis: usize, unit: UnitKind, size: &mut (f64, f64), value: f64) -> bool { + let Some(px) = document.to_pixels(length(value, unit), extent_of(document, axis)) else { return false }; + let px = thousandths(px); + if axis == 0 { + size.0 = px; + } else { + size.1 = px; + } + true +} + +/// The units a shape's size is entered in: pixels, a percentage of the document and the physical lengths. Percent +/// needs the document (`values.units`). +fn length_units(values: &CreateShapeOptions) -> impl Iterator + use<> { + let percent = values.units.is_some(); + [UnitKind::Pixels, UnitKind::Percent].into_iter().chain(UnitKind::LENGTHS).filter(move |kind| percent || *kind != UnitKind::Percent) } /// `value` in `unit` as a length the document converts. @@ -342,10 +374,7 @@ fn body( latest: &RefCell>, ) -> bool { let document = values.units.unwrap_or_else(pixels_only); - let entries: Vec> = length_units() - .filter(|kind| values.units.is_some() || *kind != UnitKind::Percent) - .map(|kind| Entry::new(kind, Label::from(numbers.symbol(kind)))) - .collect(); + let entries: Vec> = length_units(values).map(|kind| Entry::new(kind, Label::from(numbers.symbol(kind)))).collect(); let kind = values.kind; let name = match kind { ShapeKind::RoundedRectangle => &words.rounded_rectangle, @@ -424,18 +453,84 @@ fn body( impl StackDialog for CreateShapeDialog { type Result = CreatedShape; - fn json_fields(&self) -> Option { - todo!("dl.K36") + /// `width` and `height` in the unit their field shows, `widthUnit` and `heightUnit`, `radii` (top-left, + /// top-right, bottom-right, bottom-left, in pixels), `linkRadii`, `sides`, `starRatio` (in percent, as its + /// field shows it) and `fromCenter`. + fn json_fields(&self) -> Option { + let o = &self.options; + let document = o.units.unwrap_or_else(pixels_only); + Some(json!({ + "width": shown_size(&document, 0, self.units[0], o.size), + "height": shown_size(&document, 1, self.units[1], o.size), + "widthUnit": self.units[0], + "heightUnit": self.units[1], + "radii": o.radii, + "linkRadii": o.link_radii, + "sides": o.sides, + "starRatio": (o.star_ratio * 100.0).clamp(1.0, 100.0), + "fromCenter": o.from_center, + })) } - fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> { - let _ = (ctx, field, value); - todo!("dl.K36") + /// Sets a field as its row does, from the remembered values on. The radius rows answer only for a rectangle, and + /// Sides and Star Ratio only for a polygon or star; elsewhere they refuse as inactive. Linked radii take four + /// equal values. + fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { + self.recall(ctx); + let rejects = || FieldRefusal::Rejects(&value).message(field); + let kind = self.options.kind; + let rect = matches!(kind, ShapeKind::Rectangle | ShapeKind::RoundedRectangle); + let polygon = matches!(kind, ShapeKind::Polygon | ShapeKind::Star); + let shown = match field { + "radii" | "linkRadii" => rect, + "sides" | "starRatio" => polygon, + _ => true, + }; + if !shown { + return Err(FieldRefusal::Inactive.message(field)); + } + let document = self.options.units.unwrap_or_else(pixels_only); + let offered: Vec = length_units(&self.options).collect(); + let o = &mut self.options; + match field { + "width" | "height" => { + let axis = usize::from(field == "height"); + let number = value.as_f64().ok_or_else(rejects)?; + if !set_size(&document, axis, self.units[axis], &mut o.size, number) { + return Err(rejects()); + } + } + "widthUnit" | "heightUnit" => { + let unit = serde_json::from_value::(value.clone()).ok().filter(|unit| offered.contains(unit)).ok_or_else(rejects)?; + self.units[usize::from(field == "heightUnit")] = unit; + } + "radii" => { + let radii = serde_json::from_value::<[f64; 4]>(value.clone()).map_err(|_| rejects())?; + if radii.iter().any(|radius| !radius.is_finite()) || (o.link_radii && radii.iter().any(|radius| *radius != radii[0])) { + return Err(rejects()); + } + o.radii = radii.map(|radius| radius.clamp(0.0, MAX_RADIUS)); + } + "linkRadii" => o.link_radii = value.as_bool().ok_or_else(rejects)?, + "sides" => { + let sides = value.as_f64().ok_or_else(rejects)?; + o.sides = sides.round().clamp(f64::from(*SIDES.start()), f64::from(*SIDES.end())) as u32; + } + "starRatio" => o.star_ratio = (value.as_f64().ok_or_else(rejects)?.clamp(1.0, 100.0) / 100.0).clamp(0.01, 1.0), + "fromCenter" => o.from_center = value.as_bool().ok_or_else(rejects)?, + _ => return Err(FieldRefusal::Unknown.message(field)), + } + Ok(()) } + /// Answers the shape OK makes and remembers the kind's values as OK does; `None` while OK is refused. fn confirm(&mut self, ctx: &egui::Context) -> Option { - let _ = ctx; - todo!("dl.K36") + self.recall(ctx); + let env = Env::of_root(ctx); + let shape = answer(&self.options, &env.words::(), &env.units()).ok()?; + let key = save_key(self.options.kind); + set_saved_value::(ctx, &key, remembered(&self.options, &shape)); + Some(shape) } fn id(&self) -> DialogId { @@ -458,11 +553,13 @@ impl StackDialog for CreateShapeDialog { .as_str() .to_owned(), ); - let key = save_key(self.options.kind); + self.recall(ui.ctx()); + let write_key = save_key(self.options.kind); let latest = Rc::new(RefCell::new(None::)); - let (write, write_key) = (Rc::clone(&latest), key.clone()); - let CreateShapeDialog { options, units, .. } = self; + let write = Rc::clone(&latest); + let CreateShapeDialog { options, units, open, .. } = self; let shown = FormDialog::new(title, Bind::bound(options)) + .opened(Bind::bound(open)) .alt_resets(false) .shaped(move |dialog| { dialog.on_pick(move |button, cx| { @@ -473,14 +570,7 @@ impl StackDialog for CreateShapeDialog { } }) }) - .show(ui, |ui, form, values| { - if form.first() && !values.recalled { - values.recalled = true; - let memory = form.saved::(&key).clone(); - recalled(values, &memory); - } - body(ui, values, units, &words, &numbers, &latest) - }); + .show(ui, |ui, _, values| body(ui, values, units, &words, &numbers, &latest)); match (shown.accepted, shown.closed) { (Some(values), _) => answer(&values, &words, &numbers).ok().map(DialogResult::Ok), (None, Some(_)) => Some(DialogResult::Cancel), diff --git a/crates/draw/tests/it/main.rs b/crates/draw/tests/it/main.rs index a5d75cb9d..3bc60110e 100644 --- a/crates/draw/tests/it/main.rs +++ b/crates/draw/tests/it/main.rs @@ -43,3 +43,6 @@ mod transform_fields; // draw-presets mod presets; + +// dialogs-w13 +mod pattern_fill; diff --git a/crates/draw/tests/it/pattern_fill.rs b/crates/draw/tests/it/pattern_fill.rs new file mode 100644 index 000000000..e7e391690 --- /dev/null +++ b/crates/draw/tests/it/pattern_fill.rs @@ -0,0 +1,41 @@ +//! The Pattern Fill dialog's automation: its fields, set and confirmed through the host. + +use craft_draw::ui::pattern::{PatternColors, PatternFillDialog, PatternFillOptions, PatternSwatch}; +use craft_theme::Srgba; +use craft_ui::dialog::{DialogHost, DialogId, DialogResult}; +use craft_ui::testing::trial; +use serde_json::{Value, json}; + +fn swatches() -> Vec { + vec![PatternSwatch::new("bubbles", "Bubbles"), PatternSwatch::new("dots", "Dots")] +} + +fn fields(host: &DialogHost, id: DialogId) -> Value { + host.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields).unwrap_or(Value::Null) +} + +/// A bitmap pattern lists its fields, refuses an unknown or malformed one, takes a scale held to its range, and OK +/// answers the set values; a preset pattern refuses the bitmap rows as inactive. +#[trial] +fn pattern_fill_automation_lists_sets_and_confirms_its_fields() { + let ctx = egui::Context::default(); + let mut host = DialogHost::new(); + + let id = host.open(PatternFillDialog::new(PatternFillOptions::bitmap("bubbles"), swatches())); + assert_eq!(fields(&host, id)["scale"], json!(100.0), "the opening scale is listed"); + assert!(host.set_json_field(&ctx, id, "depth", json!(3)).is_err(), "an unknown field is refused"); + assert!(host.set_json_field(&ctx, id, "pattern", json!("missing")).is_err(), "a pattern the app does not offer is refused"); + assert_eq!(host.set_json_field(&ctx, id, "scale", json!(250)), Ok(())); + assert_eq!(host.set_json_field(&ctx, id, "scale", json!(5000)), Ok(()), "a scale past the range is held to it"); + assert_eq!(fields(&host, id)["scale"], json!(*PatternFillOptions::SCALE.end())); + assert_eq!(host.set_json_field(&ctx, id, "scale", json!(250)), Ok(())); + assert_eq!(host.set_json_field(&ctx, id, "pattern", json!("dots")), Ok(())); + assert!(host.confirm::(&ctx), "OK is enabled"); + let options = host.take::().and_then(DialogResult::ok).expect("OK answers the options"); + assert_eq!((options.pattern.as_str(), options.scale), ("dots", 250.0), "the answer carries the set values"); + + let colors = PatternColors::new(Srgba::BLACK, Srgba::WHITE); + let id = host.open(PatternFillDialog::new(PatternFillOptions::preset("bubbles", colors), swatches())); + assert!(host.set_json_field(&ctx, id, "scale", json!(200)).is_err(), "a bitmap row is inactive in preset mode"); + assert_eq!(host.set_json_field(&ctx, id, "colors", json!({ "foreground": Srgba::WHITE, "background": Srgba::BLACK })), Ok(())); +} diff --git a/crates/draw/tests/it/shape_drag.rs b/crates/draw/tests/it/shape_drag.rs index 4afcaa2ca..b1551888d 100644 --- a/crates/draw/tests/it/shape_drag.rs +++ b/crates/draw/tests/it/shape_drag.rs @@ -1,9 +1,12 @@ //! The Shape tools and the Create Shape dialog. The view maps one document unit to one screen point. use craft_behavior::CanvasView; -use craft_behavior::kurbo::Point; -use craft_draw::ui::shape_drag::{ShapeDragOptions, ShapeDragTool, ShapeKind}; +use craft_behavior::kurbo::{Point, Rect}; +use craft_draw::geometry::shape::ShapeGeometry; +use craft_draw::ui::shape_drag::{CreateShapeDialog, CreateShapeOptions, CreatedShape, ShapeDragOptions, ShapeDragTool, ShapeKind}; +use craft_ui::dialog::{DialogHost, DialogId, DialogResult}; use craft_ui::testing::{ToolFixture, trial}; +use serde_json::{Value, json}; /// The view of a canvas filling `room`, with its middle at the document's middle. fn room_view(room: egui::Rect) -> CanvasView { @@ -20,3 +23,68 @@ fn tool(kind: ShapeKind) -> ShapeDragTool { fn the_shape_tool_owes_the_canvas_what_every_tool_owes() { ToolFixture::with_view("Shape", tool(ShapeKind::Rectangle), room_view, |_, _| {}).check(); } + +/// Opens Create Shape for a click of `kind` at (10, 20) and returns its id. +fn open_create(host: &mut DialogHost, kind: ShapeKind) -> DialogId { + host.open(CreateShapeDialog::new(CreateShapeOptions::initial(kind, Point::new(10.0, 20.0)))) +} + +/// The fields automation lists for the open dialog `id`. +fn fields(host: &DialogHost, id: DialogId) -> Value { + host.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields).unwrap_or(Value::Null) +} + +/// OK through the host; the shape it answered. +fn confirm(host: &mut DialogHost, ctx: &egui::Context) -> Option { + assert!(host.confirm::(ctx), "OK is enabled"); + host.take::().and_then(DialogResult::ok) +} + +/// The bounds and star ratio of a polygon or star. +fn star_of(shape: &CreatedShape) -> Option<(Rect, f64)> { + match shape.geometry { + ShapeGeometry::Polygon { rect, star_ratio, .. } => Some((rect, star_ratio)), + _ => None, + } +} + +/// OK remembers width, height, From Center and the star ratio for the kind, and the next open of that kind starts +/// from them (before any pass, as automation meets it); Cancel remembers nothing; the unit picked for a field is not +/// remembered; another kind keeps its own memory. +#[trial] +fn create_shape_ok_remembers_the_size_and_cancel_and_a_picked_unit_do_not() { + let ctx = egui::Context::default(); + let mut host = DialogHost::new(); + + let id = open_create(&mut host, ShapeKind::Star); + assert_eq!(fields(&host, id)["width"], json!(100.0), "a first open starts at 100 × 100 px"); + for (field, value) in [("width", json!(250)), ("height", json!(80)), ("starRatio", json!(40)), ("fromCenter", json!(true))] { + assert_eq!(host.set_json_field(&ctx, id, field, value), Ok(()), "{field} takes its value"); + } + assert!(host.set_json_field(&ctx, id, "depth", json!(3)).is_err(), "an unknown field is refused"); + assert_eq!(host.set_json_field(&ctx, id, "widthUnit", json!("inches")), Ok(())); + let listed = fields(&host, id); + assert_eq!((listed["widthUnit"].clone(), listed["height"].clone()), (json!("inches"), json!(80.0)), "the set values are listed"); + let shape = confirm(&mut host, &ctx).expect("OK answers the shape"); + let centred = Rect::new(10.0 - 125.0, 20.0 - 40.0, 10.0 + 125.0, 20.0 + 40.0); + assert_eq!(star_of(&shape), Some((centred, 0.4)), "the answer carries the set values, centred on the click"); + assert!(shape.from_center); + + let id = open_create(&mut host, ShapeKind::Star); + assert_eq!(host.set_json_field(&ctx, id, "width", json!(300)), Ok(())); + let listed = fields(&host, id); + assert_eq!(listed["widthUnit"], json!("pixels"), "the picked unit is not remembered: the width is in pixels again"); + assert_eq!((listed["height"].clone(), listed["starRatio"].clone(), listed["fromCenter"].clone()), (json!(80.0), json!(40.0), json!(true))); + assert_eq!(host.set_json_field(&ctx, id, "fromCenter", json!(false)), Ok(())); + assert!(host.cancel::(&ctx)); + assert_eq!(host.take::(), Some(DialogResult::Cancel)); + + open_create(&mut host, ShapeKind::Star); + let shape = confirm(&mut host, &ctx).expect("OK before any pass answers the remembered values"); + assert_eq!(star_of(&shape), Some((centred, 0.4)), "Cancel remembered nothing: the OK'd size and ratio come back"); + assert!(shape.from_center); + + open_create(&mut host, ShapeKind::Ellipse); + let ellipse = confirm(&mut host, &ctx).expect("an ellipse answers"); + assert_eq!(ellipse.geometry.bounds(), Rect::new(10.0, 20.0, 110.0, 120.0), "an ellipse keeps its own memory: the defaults"); +} diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index 3ed9ec8a4..38cb1a35a 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -201,16 +201,43 @@ pub struct ColumnSize { } impl ColumnSize { + /// The column width used when the given one is not a finite number above 0. + const FALLBACK_WIDTH: f64 = 180.0; + /// The gutter used when the given one is not finite. + const FALLBACK_GUTTER: f64 = 12.0; + + /// The width and gutter the conversion uses: the fallbacks the field docs name, so a degenerate preference + /// never divides by zero. + fn sane(self) -> (f64, f64) { + let width = if self.width.is_finite() && self.width > 0.0 { self.width } else { Self::FALLBACK_WIDTH }; + let gutter = if self.gutter.is_finite() { self.gutter.max(0.0) } else { Self::FALLBACK_GUTTER }; + (width, gutter) + } + /// `columns` columns as points; a `relative` change converts the span of `|columns|` with its sign, and 0 stays 0. pub fn points(self, columns: f64, relative: bool) -> f64 { - let _ = (columns, relative); - todo!("dl.K14") + let (width, gutter) = self.sane(); + let span = |n: f64| n * (width + gutter) - gutter; + if !relative { + return span(columns); + } + if columns == 0.0 { + return 0.0; + } + columns.signum() * span(columns.abs()).max(0.0) } /// `points` as columns; the inverse of [`points`](Self::points). pub fn columns(self, points: f64, relative: bool) -> f64 { - let _ = (points, relative); - todo!("dl.K14") + let (width, gutter) = self.sane(); + let count = |p: f64| (p + gutter) / (width + gutter); + if !relative { + return count(points); + } + if points == 0.0 { + return 0.0; + } + points.signum() * count(points.abs()) } } @@ -257,9 +284,10 @@ pub struct Units { impl Units { /// The codec of a zoom field in percent: the percent reader, up to two decimals (the zoom ladder has rungs such as - /// 66.67 %). + /// 66.67 %), with zoom typing (`a/b` as a ratio, a second separator cutting the text), so every zoom field reads + /// typed text by the same rules. pub fn zoom_codec(&self) -> NumberCodec { - NumberCodec::new(self.reader(Some(UnitKind::Percent)), ZOOM_DECIMALS) + NumberCodec::new(self.reader(Some(UnitKind::Percent)), ZOOM_DECIMALS).zoom_typing() } } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/guides.rs b/crates/ui-patterns/src/patterns/form_dialogs/guides.rs index 616a34931..f6e25a985 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/guides.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/guides.rs @@ -26,9 +26,9 @@ use super::{FormDialog, HostRequests}; use crate::canvas_data::{Guide, GuideColor}; use crate::choice::Checkbox; -use crate::contract::{Bind, EditResponse, Entry, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _}; +use crate::contract::{Bind, EditResponse, Entry, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _, Sizing}; -use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use crate::display::Text; use crate::form::{Field, FieldGroup}; @@ -36,7 +36,7 @@ use crate::form::{Field, FieldGroup}; use crate::notices::{Notice, NoticeLayout}; use crate::pickers::Select; -use crate::runtime::env::{Env, Label, Units}; +use crate::runtime::env::{Env, Label, UnitKind, Units}; use crate::runtime::overlay::CloseReason; use crate::sections::GroupBox; @@ -46,6 +46,7 @@ use craft_theme::variant::Tone; use craft_theme::{Rgba, Srgba}; use egui::{Response, Ui}; +use serde_json::{Value, json}; use std::cell::{Cell, RefCell}; @@ -342,8 +343,7 @@ impl<'a> GuideLayoutDialog<'a> { apply_color_answers(form.take_answers(), GUIDE_LAYOUT_COLOR_KEY, &mut values.color); measure.unparsed.set(false); layout_rows(ui, &measure, &rows, values, form.requests()); - let rects = targets(&values.options, &document, &artboards); - let made = values.options.lines(&rects, &existing, &units, first_key, Some(values.color.rgba())); + let made = layout_guides(values, &units, &document, &artboards, &existing, first_key); let remembered = form.memory::(); let ok = match made { Ok(guides) => { @@ -369,6 +369,20 @@ impl<'a> GuideLayoutDialog<'a> { } } +/// The guides OK commits for `values`: the layout over its targets, in its colour, beside the `existing` guides. The +/// dialog's body and the hosted dialog's `confirm` both answer with it. +fn layout_guides( + values: &GuideLayoutValues, + units: &GuideUnits, + document: &GuideRect, + artboards: &[GuideRect], + existing: &[Guide], + first_key: u64, +) -> Result, GuideLayoutError> { + let rects = targets(&values.options, document, artboards); + values.options.lines(&rects, existing, units, first_key, Some(values.color.rgba())) +} + /// The rectangles the layout fills for its target. fn targets(options: &GuideLayoutOptions, document: &GuideRect, artboards: &[GuideRect]) -> Vec { match options.target { @@ -404,8 +418,14 @@ fn layout_rows(ui: &mut Ui, measure: &Measure<'_>, form: &Form<'_>, values: &mut values.options.clear_existing = on; } }); - if !values.options.same_fields(&before) && values.options.preset == before.preset { - values.options.preset = GuideLayoutPreset::Custom; + turn_custom(&mut values.options, &before); +} + +/// Turns the preset to Custom when a layout field changed from `before` and the preset did not: an edit leaves the +/// preset, a preset pick does not. Changing target, colour or Preview is no layout field. +fn turn_custom(options: &mut GuideLayoutOptions, before: &GuideLayoutOptions) { + if !options.same_fields(before) && options.preset == before.preset { + options.preset = GuideLayoutPreset::Custom; } } @@ -419,13 +439,88 @@ fn preset_row(ui: &mut Ui, words: &GuideDialogWords, options: &mut GuideLayoutOp let entries: Vec> = GuideLayoutPreset::ALL.into_iter().map(|preset| Entry::new(preset, preset.label(words))).collect(); let current = options.preset; Field::new(words.preset.clone()).show(ui, |ui, _| { - if let Some(picked) = Select::new(words.preset.clone(), Bind::given(current), &entries).show(ui).value().copied() { - picked.apply(options); - options.preset = picked; + if let Some(picked) = Select::new(words.preset.clone(), Bind::given(current), &entries).sizing(Sizing::Content).show(ui).value().copied() { + pick_preset(options, picked); } }); } +/// Applies `preset` to `options` as a pick in the Preset list does. +fn pick_preset(options: &mut GuideLayoutOptions, preset: GuideLayoutPreset) { + preset.apply(options); + options.preset = preset; +} + +/// The automation names of the presets. +const PRESET_NAMES: [(GuideLayoutPreset, &str); 4] = [ + (GuideLayoutPreset::Custom, "custom"), + (GuideLayoutPreset::FiveColumnsThreeRows, "fiveColumnsThreeRows"), + (GuideLayoutPreset::EightColumns, "eightColumns"), + (GuideLayoutPreset::TwelveColumns, "twelveColumns"), +]; + +/// The automation names of the targets. +const TARGET_NAMES: [(GuideTarget, &str); 2] = [(GuideTarget::Document, "document"), (GuideTarget::SelectedArtboards, "selectedArtboards")]; + +/// The automation name of `item` in `names`. +fn name_of(names: &[(T, &'static str)], item: T) -> Value { + names.iter().find(|(named, _)| *named == item).map_or(Value::Null, |(_, name)| json!(name)) +} + +/// The item `value` names in `names`. +fn named(names: &[(T, &'static str)], value: &Value) -> Option { + let name = value.as_str()?; + names.iter().find(|(_, named)| *named == name).map(|(item, _)| *item) +} + +/// A guide colour as automation reads it: the colour in the `Srgba` form. +fn color_json(color: GuideColor) -> Value { + json!(Srgba::from(color.rgba())) +} + +/// The guide colour `value` gives in the `Srgba` form: a named colour when it is one, else Custom, as the colour +/// row shows a picked colour. +fn read_color(value: &Value) -> Option { + let color = serde_json::from_value::(value.clone()).ok()?; + Some(GuideColor::from_rgba(color.to_rgba())) +} + +/// A layout length as automation reads it: `{value, unit}`. +fn length_json(length: GuideLength) -> Value { + json!({ "value": length.value, "unit": length.unit }) +} + +/// The length `value` gives as `{value, unit}`: a number of at least 0 in pixels, percent or a length unit, what the +/// layout fields take. +fn read_length(value: &Value) -> Option { + let number = value.get("value")?.as_f64().filter(|number| *number >= 0.0)?; + let unit = serde_json::from_value::(value.get("unit")?.clone()).ok()?; + let takes = matches!(unit, UnitKind::Pixels | UnitKind::Percent) || UnitKind::LENGTHS.contains(&unit); + takes.then_some(GuideLength::new(number, unit)) +} + +/// A column or row group as automation reads it: `{enabled, number, size, gutter}`, `size` `null` for automatic. +fn group_json(group: &GuideGroup) -> Value { + json!({ + "enabled": group.enabled, + "number": group.number, + "size": group.size.map(length_json), + "gutter": length_json(group.gutter), + }) +} + +/// The group `value` gives as [`group_json`] writes it; `number` 1 to [`MAX_COUNT`]. +fn read_group(value: &Value) -> Option { + let enabled = value.get("enabled")?.as_bool()?; + let number = value.get("number")?.as_u64().and_then(|number| u32::try_from(number).ok()).filter(|number| (1..=MAX_COUNT).contains(number))?; + let size = match value.get("size")? { + Value::Null => None, + size => Some(read_length(size)?), + }; + let gutter = read_length(value.get("gutter")?)?; + Some(GuideGroup::new(enabled, number, size, gutter)) +} + fn target_row(ui: &mut Ui, words: &GuideDialogWords, options: &mut GuideLayoutOptions, artboards: bool) { let mut entries = vec![Entry::new(GuideTarget::Document, words.document.clone())]; if artboards { @@ -433,7 +528,7 @@ fn target_row(ui: &mut Ui, words: &GuideDialogWords, options: &mut GuideLayoutOp } let current = options.target; Field::new(words.target.clone()).show(ui, |ui, _| { - if let Some(picked) = Select::new(words.target.clone(), Bind::given(current), &entries).show(ui).value().copied() { + if let Some(picked) = Select::new(words.target.clone(), Bind::given(current), &entries).sizing(Sizing::Content).show(ui).value().copied() { options.target = picked; } }); @@ -508,9 +603,11 @@ pub struct HostedGuideLayoutDialog { build: Box, preview: Option>, requests: HostRequests, - /// Whether the dialog is open: bound to the dialog's `opened` prop. - #[allow(dead_code)] // P3(dialogs-w13): dl.K36 + /// Whether the dialog is open: bound to the dialog's `opened` prop, so the host's dialog closes with it. open: bool, + /// The Preview check box, bound to the dialog's `preview` prop so automation reads and sets it. Starts on, as + /// the unbound dialog does at every open. + preview_on: bool, } impl HostedGuideLayoutDialog { @@ -523,6 +620,7 @@ impl HostedGuideLayoutDialog { preview: None, requests: HostRequests::new(), open: true, + preview_on: true, } } @@ -545,18 +643,68 @@ impl HostedGuideLayoutDialog { impl StackDialog for HostedGuideLayoutDialog { type Result = GuideLayoutResult; - fn confirm(&mut self, ctx: &egui::Context) -> Option { - let _ = ctx; - todo!("dl.K36") + /// Answers what OK answers: the guide list of [`layout_guides`]; `None` while the layout is invalid. + fn confirm(&mut self, _ctx: &egui::Context) -> Option { + let GuideLayoutDialog { units, document, artboards, existing, first_key, .. } = (self.build)(Bind::bound(&mut self.values)); + let values = self.values; + let guides = layout_guides(&values, &units, &document, &artboards, &existing, first_key).ok()?; + Some(GuideLayoutResult { options: values.options, guides, color: values.color.rgba() }) } - fn json_fields(&self) -> Option { - todo!("dl.K36") + /// `preset`, `target`, `columns` and `rows` (`{enabled, number, size, gutter}`), `marginEnabled`, `margin` (top, + /// left, bottom, right), `centerColumns`, `clearExisting`, `color` and `preview`. A length is `{value, unit}`. + fn json_fields(&self) -> Option { + let options = &self.values.options; + Some(json!({ + "preset": name_of(&PRESET_NAMES, options.preset), + "target": name_of(&TARGET_NAMES, options.target), + "columns": group_json(&options.columns), + "rows": group_json(&options.rows), + "marginEnabled": options.margin_enabled, + "margin": options.margin.map(length_json), + "centerColumns": options.center_columns, + "clearExisting": options.clear_existing, + "color": color_json(self.values.color), + "preview": self.preview_on, + })) } - fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> { - let _ = (ctx, field, value); - todo!("dl.K36") + /// Sets a field as its row does: `preset` applies the preset, an edit of a layout field turns the preset to + /// Custom, and `target` takes Selected Artboards only while the dialog lists it. + fn set_json_field(&mut self, _ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { + let has_artboards = !(self.build)(Bind::bound(&mut self.values)).artboards.is_empty(); + let rejects = || FieldRefusal::Rejects(&value).message(field); + let before = self.values.options; + let options = &mut self.values.options; + let flag = || value.as_bool().ok_or_else(rejects); + match field { + "preset" => pick_preset(options, named(&PRESET_NAMES, &value).ok_or_else(rejects)?), + "target" => match named(&TARGET_NAMES, &value) { + Some(GuideTarget::SelectedArtboards) if !has_artboards => return Err(rejects()), + Some(target) => options.target = target, + None => return Err(rejects()), + }, + "columns" => options.columns = read_group(&value).ok_or_else(rejects)?, + "rows" => options.rows = read_group(&value).ok_or_else(rejects)?, + "marginEnabled" => options.margin_enabled = flag()?, + "margin" => { + let sides = value.as_array().filter(|sides| sides.len() == 4).ok_or_else(rejects)?; + let mut margin = options.margin; + for (side, length) in margin.iter_mut().zip(sides) { + *side = read_length(length).ok_or_else(rejects)?; + } + options.margin = margin; + } + "centerColumns" => options.center_columns = flag()?, + "clearExisting" => options.clear_existing = flag()?, + "color" => self.values.color = read_color(&value).ok_or_else(rejects)?, + "preview" => self.preview_on = flag()?, + _ => return Err(FieldRefusal::Unknown.message(field)), + } + if field != "preset" { + turn_custom(&mut self.values.options, &before); + } + Ok(()) } fn id(&self) -> DialogId { @@ -564,7 +712,11 @@ impl StackDialog for HostedGuideLayoutDialog { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { - let shown = (self.build)(Bind::bound(&mut self.values)).answers(self.requests.take_answers()).show(ui); + let shown = (self.build)(Bind::bound(&mut self.values)) + .answers(self.requests.take_answers()) + .opened(Bind::bound(&mut self.open)) + .preview(Bind::bound(&mut self.preview_on)) + .show(ui); self.preview = shown.preview; self.requests.extend(shown.requests); match (shown.result, shown.closed) { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/guides/new_guide.rs b/crates/ui-patterns/src/patterns/form_dialogs/guides/new_guide.rs index 32b4ad679..23afb1a0b 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/guides/new_guide.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/guides/new_guide.rs @@ -3,13 +3,16 @@ use super::layout::{GuideLength, GuideUnits}; use crate::runtime::requests::HostAnswer; -use super::{FormDialog, GUIDE_LIMIT, GuideDialogWords, HostRequests, NEW_GUIDE_COLOR_KEY, apply_color_answers, color_row}; +use super::{FormDialog, GUIDE_LIMIT, GuideDialogWords, HostRequests, NEW_GUIDE_COLOR_KEY, apply_color_answers, color_json, color_row, read_color}; use crate::canvas_data::{Guide, GuideColor, GuideKey}; use crate::choice::Segmented; use crate::contract::{Bind, Entry, NoValue, Outcome, SaveKey, Show as _, ShowContainer as _}; -use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use crate::runtime::memory::{saved_value, set_saved_value}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use crate::form::{Field, FieldGroup}; @@ -112,15 +115,34 @@ pub struct NewGuideDialog<'a> { /// Binds the open state to `open`. #[prop(name = "opened")] open: Option>, - /// Saves the values under `key` for the next open. + /// Remembers a new guide's values under `key`: the remembered values replace the opening ones, and OK stores the + /// confirmed ones for the next open. Edit Selected Guides neither recalls nor stores. #[prop] remember: Option, + /// Whether the values already start from the remembered ones, so the first pass recalls nothing: a hosted + /// dialog recalls before any pass, and automation may have set a field since. + recalled: bool, } impl<'a> NewGuideDialog<'a> { /// New Guide over `values`, for a document measured in `units`. pub fn new(units: GuideUnits, values: Bind<'a, NewGuideValues>) -> Self { - NewGuideDialog { units, values, edit: None, key: GuideKey::new(0), error: None, answers: Vec::new(), open: None, remember: None } + NewGuideDialog { + units, + values, + edit: None, + key: GuideKey::new(0), + error: None, + answers: Vec::new(), + open: None, + remember: None, + recalled: false, + } + } + + /// The key the values are remembered under: a new guide's `remember`, none for an edit. + fn memory_key(&self) -> Option<&SaveKey> { + self.remember.as_ref().filter(|_| self.edit.is_none()) } /// Edit Selected Guides for `guide`, which is drawn in `preference` when it has no colour of its own: the @@ -131,8 +153,8 @@ impl<'a> NewGuideDialog<'a> { /// Shows the dialog. pub fn show(self, ui: &mut Ui) -> NewGuideOutput { - let NewGuideDialog { units, values, edit, key, error, answers, open, remember } = self; - let _ = &remember; // P3(dialogs-w13): dl.K36 + let memory = self.memory_key().cloned(); + let NewGuideDialog { units, values, edit, key, error, answers, open, recalled, .. } = self; let env = Env::of(ui); let words = env.words::(); let number_units = env.units(); @@ -147,6 +169,9 @@ impl<'a> NewGuideDialog<'a> { if let (true, Some((guide, preference))) = (first, &edit) { *values = NewGuideValues::of_guide(guide, *preference); } + if let (true, false, Some(remembered)) = (first, recalled, memory.as_ref().and_then(|key| recall(ui.ctx(), key))) { + *values = remembered; + } apply_color_answers(form.take_answers(), NEW_GUIDE_COLOR_KEY, &mut values.color); if let Some(message) = &error { Notice::new(Tone::Bad, message.clone()).layout(NoticeLayout::Inline).show(ui); @@ -164,11 +189,37 @@ impl<'a> NewGuideDialog<'a> { }); parsed }); - let result = shown.accepted.map(|values| guide_of(&values, edit.as_ref(), key)); + let result = shown.accepted.map(|values| { + if let Some(memory) = &memory { + store(ui.ctx(), memory, &values); + } + guide_of(&values, edit.as_ref(), key) + }); NewGuideOutput { response: shown.response, closed: shown.closed, result, requests: shown.requests } } } +/// What New Guide remembers under its `remember` key: the last confirmed new guide's values. Its own type because +/// [`GuideColor`] has no serde form; the colour is kept as its bytes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct Remembered { + along: Axis, + position_px: f64, + color: [u8; 4], +} + +/// The values remembered under `key`, once a new guide was confirmed with it. +fn recall(ctx: &egui::Context, key: &SaveKey) -> Option { + let remembered = saved_value::>(ctx, key)?; + Some(NewGuideValues::new(remembered.along, remembered.position_px, GuideColor::from_rgba(Rgba(remembered.color)))) +} + +/// Stores `values` under `key` for the next open. +fn store(ctx: &egui::Context, key: &SaveKey, values: &NewGuideValues) { + let remembered = Remembered { along: values.along, position_px: values.position_px, color: values.color.rgba().0 }; + set_saved_value(ctx, key, Some(remembered)); +} + /// The guide the values make: the edited guide with the values applied, or a new guide with `key`. An edited guide /// with no colour of its own stays so while the colour is still the preference it opened with. fn guide_of(values: &NewGuideValues, edit: Option<&(Guide, Rgba)>, key: GuideKey) -> Guide { @@ -180,11 +231,30 @@ fn guide_of(values: &NewGuideValues, edit: Option<&(Guide, Rgba)>, key: GuideKey Guide { along: values.along, position: values.position_px, color, ..base } } +/// The extent a position's percent is of: the document's width for a vertical guide, its height for a horizontal one. +fn position_extent(units: &GuideUnits, along: Axis) -> f64 { + if along == Axis::Y { units.width_px } else { units.height_px } +} + +/// The position in the ruler unit, as the Position field shows it. +fn ruler_position(units: &GuideUnits, values: &NewGuideValues) -> f64 { + units.from_pixels(values.position_px, units.ruler, position_extent(units, values.along)).unwrap_or(0.0) +} + +/// Sets the position from `typed` in the ruler unit, held to the guide limit, as a commit in the Position field +/// does; `false` and nothing changes when `typed` does not convert. +fn set_ruler_position(units: &GuideUnits, values: &mut NewGuideValues, typed: f64) -> bool { + let extent = position_extent(units, values.along); + let Some(px) = units.to_pixels(GuideLength::new(typed, units.ruler), extent) else { return false }; + values.position_px = px.clamp(-GUIDE_LIMIT, GUIDE_LIMIT); + true +} + /// The Position row; `false` while its text does not parse. fn position_row(ui: &mut Ui, words: &GuideDialogWords, numbers: &Units, units: &GuideUnits, values: &mut NewGuideValues, focus_here: bool) -> bool { let ruler = units.ruler; - let extent = if values.along == Axis::Y { units.width_px } else { units.height_px }; - let shown = units.from_pixels(values.position_px, ruler, extent).unwrap_or(0.0); + let extent = position_extent(units, values.along); + let shown = ruler_position(units, values); let high = units.from_pixels(GUIDE_LIMIT, ruler, extent).filter(|v| v.is_finite()).unwrap_or(GUIDE_LIMIT).abs(); let places = *ruler.decimals().end(); Field::new(words.position.clone()) @@ -201,9 +271,8 @@ fn position_row(ui: &mut Ui, words: &GuideDialogWords, numbers: &Units, units: & } if let Some(Some(typed)) = field.value().copied() { let scale = 10f64.powi(i32::try_from(places).unwrap_or(0)); - let changed = (typed * scale).round() != (shown * scale).round(); - if let (true, Some(px)) = (changed, units.to_pixels(GuideLength::new(typed, ruler), extent)) { - values.position_px = px.clamp(-GUIDE_LIMIT, GUIDE_LIMIT); + if (typed * scale).round() != (shown * scale).round() { + set_ruler_position(units, values, typed); } } !field.unparsed @@ -225,15 +294,39 @@ pub struct HostedNewGuideDialog { values: NewGuideValues, build: Box, requests: HostRequests, - /// Whether the dialog is open: bound to the dialog's `opened` prop. - #[allow(dead_code)] // P3(dialogs-w13): dl.K36 + /// Whether the dialog is open: bound to the dialog's `opened` prop, so the host's dialog closes with it. open: bool, + /// The app's message shown above the fields, set with [`set_error`](Self::set_error); it replaces the one + /// `build` gives while set. + error: Option