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)
This commit is contained in:
aiongg
2026-11-15 04:46:06 +00:00
parent b8cbaab7fa
commit 2b38e14dee
16 changed files with 1194 additions and 201 deletions
+75 -23
View File
@@ -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<SwatchPainter>,
changed: bool,
canvas: Option<egui::Id>,
/// 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<serde_json::Value> {
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<Value> {
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::<Srgba>(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<Self::Result> {
let _ = ctx;
todo!("dl.K36")
/// Answers the current values, as OK does.
fn confirm(&mut self, _ctx: &egui::Context) -> Option<Self::Result> {
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<DialogResult<PatternFillOptions>> {
let words = Env::of(ui).words::<PatternWords>();
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;
+1 -1
View File
@@ -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<f64> = -180.0..=180.0;
pub(super) const ANGLE_RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
type SwatchPaintFn = Arc<dyn Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync>;
+130 -40
View File
@@ -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::<Memory>(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<UnitKind>],
) {
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<Item = UnitKind> {
[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<Item = UnitKind> + 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<Option<Memory>>,
) -> bool {
let document = values.units.unwrap_or_else(pixels_only);
let entries: Vec<Entry<UnitKind>> = 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<Entry<UnitKind>> = 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<serde_json::Value> {
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<Value> {
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<UnitKind> = 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::<UnitKind>(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<Self::Result> {
let _ = ctx;
todo!("dl.K36")
self.recall(ctx);
let env = Env::of_root(ctx);
let shape = answer(&self.options, &env.words::<CreateShapeWords>(), &env.units()).ok()?;
let key = save_key(self.options.kind);
set_saved_value::<Memory>(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::<Memory>));
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::<Memory>(&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),
+3
View File
@@ -43,3 +43,6 @@ mod transform_fields;
// draw-presets
mod presets;
// dialogs-w13
mod pattern_fill;
+41
View File
@@ -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<PatternSwatch> {
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::<PatternFillDialog>(&ctx), "OK is enabled");
let options = host.take::<PatternFillDialog>().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(()));
}
+70 -2
View File
@@ -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<CreatedShape> {
assert!(host.confirm::<CreateShapeDialog>(ctx), "OK is enabled");
host.take::<CreateShapeDialog>().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::<CreateShapeDialog>(&ctx));
assert_eq!(host.take::<CreateShapeDialog>(), 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");
}
+34 -6
View File
@@ -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()
}
}
@@ -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::<LastValid>();
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<Vec<Guide>, 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<GuideRect> {
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<Entry<GuideLayoutPreset>> = 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<T: PartialEq + Copy>(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<T: Copy>(names: &[(T, &'static str)], value: &Value) -> Option<T> {
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<GuideColor> {
let color = serde_json::from_value::<Srgba>(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<GuideLength> {
let number = value.get("value")?.as_f64().filter(|number| *number >= 0.0)?;
let unit = serde_json::from_value::<UnitKind>(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<GuideGroup> {
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<Build>,
preview: Option<Vec<Guide>>,
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<Self::Result> {
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<Self::Result> {
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<serde_json::Value> {
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<Value> {
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<DialogResult<GuideLayoutResult>> {
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) {
@@ -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<Bind<'a, bool>>,
/// 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<SaveKey>,
/// 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::<GuideDialogWords>();
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<NewGuideValues> {
let remembered = saved_value::<Option<Remembered>>(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<Build>,
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<Label>,
/// Whether the remembered values were recalled into `values`: once, before the first show, OK or set reads them.
recalled: bool,
}
impl HostedNewGuideDialog {
/// A dialog opening with `values`; `build` makes it over the values (`NewGuideDialog::new` or `edit`).
pub fn new(values: NewGuideValues, build: impl for<'b> Fn(Bind<'b, NewGuideValues>) -> NewGuideDialog<'b> + Send + 'static) -> Self {
HostedNewGuideDialog { id: dialog_id("guides.newGuide"), values, build: Box::new(build), requests: HostRequests::new(), open: true }
HostedNewGuideDialog {
id: dialog_id("guides.newGuide"),
values,
build: Box::new(build),
requests: HostRequests::new(),
open: true,
error: None,
recalled: false,
}
}
/// Replaces the opening values with the remembered ones, once, as the dialog's first pass would: automation may
/// set or confirm before any pass.
fn recall(&mut self, ctx: &egui::Context) {
if std::mem::replace(&mut self.recalled, true) {
return;
}
let memory = (self.build)(Bind::bound(&mut self.values)).memory_key().cloned();
if let Some(remembered) = memory.and_then(|key| recall(ctx, &key)) {
self.values = remembered;
}
}
/// The values the dialog shows.
@@ -241,10 +334,10 @@ impl HostedNewGuideDialog {
&self.values
}
/// Shows `error` above the fields: the app's message when it refused the position.
/// Shows `error` above the fields from the next pass on: the app's message when it refused the position, such as
/// Edit Selected Guides' check of each pass. `None` shows the one `build` gives, if any.
pub fn set_error(&mut self, error: Option<Label>) {
let _ = error;
todo!("dl.K36")
self.error = error;
}
/// What the dialog asked of the host and the host's answers: take the colour request, answer it.
@@ -256,18 +349,56 @@ impl HostedNewGuideDialog {
impl StackDialog for HostedNewGuideDialog {
type Result = Guide;
/// Answers the guide OK makes, and stores a new guide's values under its `remember` key as OK does.
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K36")
self.recall(ctx);
let (memory, edit, key) = {
let dialog = (self.build)(Bind::bound(&mut self.values));
(dialog.memory_key().cloned(), dialog.edit.clone(), dialog.key)
};
if let Some(memory) = &memory {
store(ctx, memory, &self.values);
}
Some(guide_of(&self.values, edit.as_ref(), key))
}
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K36")
/// `orientation` (`horizontal` or `vertical`), `position` in the ruler unit as the Position field shows it, and
/// `color` in the `Srgba` form.
fn json_fields(&self) -> Option<Value> {
let units = (self.build)(Bind::given(self.values)).units;
let orientation = if self.values.along == Axis::Y { "vertical" } else { "horizontal" };
Some(json!({
"orientation": orientation,
"position": ruler_position(&units, &self.values),
"color": color_json(self.values.color),
}))
}
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: `position` is in the ruler unit and held to the guide limit; `color` picks the
/// named colour it matches, else Custom.
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> {
self.recall(ctx);
let units = (self.build)(Bind::bound(&mut self.values)).units;
let rejects = || FieldRefusal::Rejects(&value).message(field);
let values = &mut self.values;
match field {
"orientation" => {
values.along = match value.as_str() {
Some("horizontal") => Axis::X,
Some("vertical") => Axis::Y,
_ => return Err(rejects()),
}
}
"position" => {
let typed = value.as_f64().ok_or_else(rejects)?;
if !set_ruler_position(&units, values, typed) {
return Err(rejects());
}
}
"color" => values.color = read_color(&value).ok_or_else(rejects)?,
_ => return Err(FieldRefusal::Unknown.message(field)),
}
Ok(())
}
fn id(&self) -> DialogId {
@@ -275,7 +406,13 @@ impl StackDialog for HostedNewGuideDialog {
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Guide>> {
let shown = (self.build)(Bind::bound(&mut self.values)).answers(self.requests.take_answers()).show(ui);
self.recall(ui.ctx());
let mut dialog = (self.build)(Bind::bound(&mut self.values)).answers(self.requests.take_answers()).opened(Bind::bound(&mut self.open));
dialog.recalled = true;
if self.error.is_some() {
dialog.error = self.error.clone();
}
let shown = dialog.show(ui);
self.requests.extend(shown.requests);
match (shown.result, shown.closed) {
(Some(guide), _) => Some(DialogResult::Ok(guide)),
@@ -1,12 +1,13 @@
//! Trials of the guide dialogs.
#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")]
use super::{GUIDE_LAYOUT_COLOR_KEY, GuideLayoutDialog, GuideLayoutValues, GuideRect, GuideUnits};
use crate::canvas_data::GuideColor;
use crate::contract::Bind;
use super::{GUIDE_LAYOUT_COLOR_KEY, GuideLayoutDialog, GuideLayoutValues, GuideRect, GuideUnits, NewGuideDialog, NewGuideValues};
use crate::canvas_data::{Guide, GuideColor};
use crate::contract::{Bind, SaveKey};
use crate::runtime::env::UnitKind;
use crate::runtime::requests::ColorRequest;
use crate::testing::{Fixture, trial};
use craft_behavior::Axis;
use craft_theme::Rgba;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -37,7 +38,7 @@ fn the_preview_check_box_under_the_side_buttons_starts_on_at_every_open() {
assert!(!previewing.get(), "with Preview off the dialog previews nothing");
fixture.key(egui::Key::Escape, egui::Modifiers::NONE).idle(4);
assert!(!open.get(), "Escape closes the dialog");
// A closed dialog's shown memory goes after 3 passes and 0.5 s.
// Past its exit fade the closed dialog shows nothing and has ended its shown life: the next open is a first pass.
fixture.advance(1.0).idle(4);
open.set(true);
fixture.settle();
@@ -73,3 +74,56 @@ fn a_click_on_the_custom_colour_swatch_asks_the_picker_at_that_colour() {
fixture.settle();
assert!(fixture.by_label("Custom…").is_none(), "a named colour shows no swatch");
}
const REMEMBERED_GUIDE: SaveKey = SaveKey::new("craft_ui_trials.new_guide");
/// S-D1: OK stores a new guide's axis, position and colour under its `remember` key, and the next open starts from them
/// whatever values the app passes; Cancel stores nothing.
#[trial]
fn a_new_guide_remembers_its_confirmed_values_for_the_next_open() {
let open = Rc::new(Cell::new(true));
let values = Rc::new(RefCell::new(NewGuideValues::new(Axis::X, 0.0, GuideColor::Magenta)));
let made: Rc<RefCell<Vec<Guide>>> = Rc::default();
let (opened, held, seen) = (Rc::clone(&open), Rc::clone(&values), Rc::clone(&made));
let mut fixture = Fixture::new(move |ui| {
let units = GuideUnits::new(UnitKind::Pixels, 3000.0, 2000.0, 300.0);
let mut is_open = opened.get();
let mut current = held.borrow_mut();
let shown = NewGuideDialog::new(units, Bind::bound(&mut *current)).remember(REMEMBERED_GUIDE).opened(Bind::bound(&mut is_open)).show(ui);
opened.set(is_open);
seen.borrow_mut().extend(shown.result);
});
// The app opens the dialog again with its own default values. Past its exit fade the closed dialog shows nothing
// and has ended its shown life, so the reopen is a first pass.
let reopen = |fixture: &mut Fixture| {
fixture.advance(1.0).idle(4);
*values.borrow_mut() = NewGuideValues::default();
open.set(true);
fixture.settle();
};
fixture.settle();
assert_eq!(*values.borrow(), NewGuideValues::new(Axis::X, 0.0, GuideColor::Magenta), "with nothing remembered the opening values stand");
let vertical = fixture.by_label("Vertical").expect("the orientation offers Vertical");
fixture.click(&vertical).settle();
let position = fixture.by_label("Position").expect("the Position field");
fixture.click(&position).settle();
fixture.key(egui::Key::A, egui::Modifiers::COMMAND);
fixture.type_text("120");
fixture.key(egui::Key::Enter, egui::Modifiers::NONE).settle();
assert!(!open.get(), "Enter is OK");
let confirmed: Vec<_> = made.borrow().iter().map(|guide| (guide.along, guide.position, guide.color)).collect();
assert_eq!(confirmed, [(Axis::Y, 120.0, Some(GuideColor::Magenta.rgba()))], "OK makes the guide of the edited values");
reopen(&mut fixture);
assert_eq!(*values.borrow(), NewGuideValues::new(Axis::Y, 120.0, GuideColor::Magenta), "the next open starts from the confirmed values");
let horizontal = fixture.by_label("Horizontal").expect("the orientation offers Horizontal");
fixture.click(&horizontal).settle();
assert_eq!(values.borrow().along, Axis::X, "the click edits the values");
fixture.key(egui::Key::Escape, egui::Modifiers::NONE).idle(4);
assert!(!open.get(), "Escape cancels");
assert_eq!(made.borrow().len(), 1, "Cancel makes no guide");
reopen(&mut fixture);
assert_eq!(*values.borrow(), NewGuideValues::new(Axis::Y, 120.0, GuideColor::Magenta), "Cancel stored nothing: the OK'd values come back");
}
@@ -134,26 +134,55 @@ pub struct LinkedSize {
relative: bool,
chain: bool,
points_per_inch: f64,
/// The document's column size, which makes Columns a width unit; `None` offers no Columns.
columns: Option<ColumnSize>,
/// Whether the width shows Columns while the height keeps `unit`. Only ever on with `columns` set.
width_in_columns: bool,
typed: Option<Typed>,
}
impl LinkedSize {
/// Sets the width of the column of the rows' fields.
/// The document's column size (the Units preference's column width and gutter), which lets the width be shown in
/// [`UnitKind::Columns`]. Without it the width offers no Columns.
#[must_use]
pub fn column_size(mut self, size: ColumnSize) -> Self {
let _ = (&mut self, size);
todo!("dl.K37")
self.columns = Some(size);
self
}
/// The unit the width is shown in.
/// The column size the width converts Columns through, when it has one.
pub fn columns(&self) -> Option<ColumnSize> {
self.columns
}
/// The unit the width field shows: Columns while the width-only override is on, else the shared
/// [`unit`](Self::unit).
pub fn width_unit(&self) -> UnitKind {
todo!("dl.K37")
self.side_unit(Side::Width)
}
/// Shows the width in `unit`; `false` when the size has no such unit.
/// Shows the width in `unit`. Columns turns the width-only override on (and is refused without a column size);
/// any other length turns it off and sets the shared unit as [`set_unit`](Self::set_unit) does. Returns `false`
/// and changes nothing for a kind the width cannot show.
pub fn set_width_unit(&mut self, unit: UnitKind) -> bool {
let _ = unit;
todo!("dl.K37")
if unit == UnitKind::Columns {
if self.columns.is_some() {
self.width_in_columns = true;
}
return self.columns.is_some();
}
let length = self.set_unit(unit);
if length {
self.width_in_columns = false;
}
length
}
/// Whether the resolution differs from the one the dialog opened with. The opening value is the clamped one
/// (see [`opening_resolution`](Self::opening_resolution)), so a document whose own resolution lies outside the
/// range reads unchanged until the user edits it, and the app keeps the document's value.
pub fn resolution_changed(&self) -> bool {
self.ppi != self.original_ppi
}
/// Fields for a document of size `original` at 72 ppi, in pixels and pixels per inch, locked, resampling and
@@ -171,6 +200,8 @@ impl LinkedSize {
relative: false,
chain: true,
points_per_inch: UnitKind::POINTS_PER_INCH,
columns: None,
width_in_columns: false,
typed: None,
}
}
@@ -248,7 +279,7 @@ impl LinkedSize {
self.relative
}
/// The unit the width and height fields show.
/// The unit the height field shows, and the width field unless it shows Columns: what the results report.
pub fn unit(&self) -> UnitKind {
self.unit
}
@@ -298,10 +329,30 @@ impl LinkedSize {
self.typed = None;
}
/// Whether the width and height fields take input: in pixels and percent they need Resample on, since only
/// resampling changes the pixel count.
/// Whether the height field, and the width field while it shows the shared unit, take input: in pixels and
/// percent they need Resample on, since only resampling changes the pixel count.
pub fn is_editable(&self) -> bool {
self.resampling || !is_pixel_unit(self.unit)
self.side_editable(Side::Height)
}
/// Whether the width field takes input: as [`is_editable`](Self::is_editable), with a Columns width counting as
/// a physical size.
pub fn is_width_editable(&self) -> bool {
self.side_editable(Side::Width)
}
fn side_editable(&self, side: Side) -> bool {
self.resampling || !is_pixel_unit(self.side_unit(side))
}
/// The unit `side`'s field shows.
fn side_unit(&self, side: Side) -> UnitKind {
if self.column_conversion(side).is_some() { UnitKind::Columns } else { self.unit }
}
/// The column size `side` converts through: the width's while it shows Columns.
fn column_conversion(&self, side: Side) -> Option<ColumnSize> {
self.columns.filter(|_| side == Side::Width && self.width_in_columns)
}
/// The width in the current unit (the change in width, in a relative size), unrounded.
@@ -371,12 +422,31 @@ impl LinkedSize {
fn range(&self, side: Side) -> RangeInclusive<f64> {
let original = pixels_along(self.original, side);
let limit = self.unit_value(MAX_DOCUMENT_SIDE, original);
if self.relative { -limit..=limit } else { self.unit_value(1.0, original).min(self.shown(side))..=limit }
if self.relative {
let limit = self.unit_value(side, MAX_DOCUMENT_SIDE, original, true);
-limit..=limit
} else {
let limit = self.unit_value(side, MAX_DOCUMENT_SIDE, original, false);
self.unit_value(side, 1.0, original, false).min(self.shown(side))..=limit
}
}
fn unit_value(&self, pixels: f64, original: f64) -> f64 {
self.unit.from_pixels(pixels, original, self.ppi, self.points_per_inch).unwrap_or(pixels)
/// `pixels` along `side` in the unit its field shows; a `relative` value is a change in size, which matters to
/// Columns only (the gutter is counted between columns, not per column).
fn unit_value(&self, side: Side, pixels: f64, original: f64, relative: bool) -> f64 {
match self.column_conversion(side) {
Some(columns) => columns.columns(pixels / self.ppi.max(1.0) * self.points_per_inch, relative),
None => self.unit.from_pixels(pixels, original, self.ppi, self.points_per_inch).unwrap_or(pixels),
}
}
/// A value of `side`'s field as pixels; the inverse of `unit_value`. `None` for a shared unit that is not a pixel
/// or length unit.
fn unit_pixels(&self, side: Side, value: f64, original: f64, relative: bool) -> Option<f64> {
match self.column_conversion(side) {
Some(columns) => Some(columns.points(value, relative) / self.points_per_inch * self.ppi.max(1.0)),
None => self.unit.to_pixels(value, original, self.ppi, self.points_per_inch),
}
}
/// The field's value in the current unit: the value typed last while the pixel size it made stands, else the
@@ -384,7 +454,7 @@ impl LinkedSize {
fn shown(&self, side: Side) -> f64 {
if let Some(typed) = &self.typed
&& typed.side == side
&& typed.unit == self.unit
&& typed.unit == self.side_unit(side)
&& typed.relative == self.relative
&& typed.size == self.current
&& typed.ppi == self.ppi
@@ -392,7 +462,7 @@ impl LinkedSize {
return typed.value;
}
let (current, original) = (pixels_along(self.current, side), pixels_along(self.original, side));
self.unit_value(if self.relative { current - original } else { current }, original)
self.unit_value(side, if self.relative { current - original } else { current }, original, self.relative)
}
fn edit(&mut self, side: Side, value: f64) {
@@ -400,10 +470,10 @@ impl LinkedSize {
return;
}
let (current, original) = (pixels_along(self.current, side), pixels_along(self.original, side));
let Some(pixels) = self.unit.to_pixels(value, original, self.ppi, self.points_per_inch) else { return };
let Some(pixels) = self.unit_pixels(side, value, original, self.relative) else { return };
self.typed = None;
if !self.resampling {
if !is_pixel_unit(self.unit) && pixels > 0.0 {
if !is_pixel_unit(self.side_unit(side)) && pixels > 0.0 {
self.ppi = (self.ppi * current / pixels).clamp(*PPI_RANGE.start(), *PPI_RANGE.end());
self.current = self.original;
self.remember(side, value);
@@ -416,7 +486,7 @@ impl LinkedSize {
}
fn remember(&mut self, side: Side, value: f64) {
self.typed = Some(Typed { side, value, unit: self.unit, relative: self.relative, size: self.current, ppi: self.ppi });
self.typed = Some(Typed { side, value, unit: self.side_unit(side), relative: self.relative, size: self.current, ppi: self.ppi });
}
/// Sets one side in pixels, scaling the other by the opening ratio when locked.
@@ -4,7 +4,7 @@
use super::FormDialog;
use super::size_model::{LinkedSize, MAX_DOCUMENT_SIDE};
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use crate::dialog::DialogResult;
use crate::dialog::{DialogResult, FieldRefusal};
use crate::display::Text;
use crate::form::{Field, FieldGroup};
use crate::layout_components::{Row, Stack};
@@ -133,8 +133,10 @@ impl Resample {
}
}
/// What fills the area a larger canvas adds.
#[derive(Clone, Debug, PartialEq)]
/// What fills the area a larger canvas adds. Serialised camelCase (`"background"`, `{"other": [r, g, b]}`), the
/// form automation reads and writes.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CanvasExtension {
/// The foreground colour.
@@ -170,6 +172,11 @@ impl CanvasExtension {
/// The list entries for a canvas whose current extension is `current`: the five named colours, `Other` while it is
/// the current one, and Transparent for a document with no background (`has_background` false).
pub fn entries(words: &SizingWords, current: &CanvasExtension, has_background: bool) -> Vec<Entry<CanvasExtension>> {
Self::offered(current, has_background).into_iter().map(|extension| Entry::new(extension.clone(), extension.label(words))).collect()
}
/// The extensions the list offers, in its order: what [`entries`](Self::entries) shows and automation may pick.
fn offered(current: &CanvasExtension, has_background: bool) -> Vec<CanvasExtension> {
let mut list =
vec![CanvasExtension::Foreground, CanvasExtension::Background, CanvasExtension::White, CanvasExtension::Black, CanvasExtension::Gray];
if matches!(current, CanvasExtension::Other(_)) {
@@ -178,7 +185,7 @@ impl CanvasExtension {
if !has_background {
list.push(CanvasExtension::Transparent);
}
list.into_iter().map(|extension| Entry::new(extension.clone(), extension.label(words))).collect()
list
}
}
@@ -226,6 +233,42 @@ fn size_valid(size: PixelSize) -> bool {
side(size.width) && side(size.height)
}
/// The automation fields of the width and height rows both dialogs share: `width` and `height` in the unit their
/// field shows, as typing in the field is; `unit`, the shared unit; and `widthUnit`, the unit the width shows.
fn size_json(size: &LinkedSize) -> serde_json::Map<String, serde_json::Value> {
let mut fields = serde_json::Map::new();
fields.insert("width".into(), serde_json::json!(size.width()));
fields.insert("height".into(), serde_json::json!(size.height()));
fields.insert("unit".into(), serde_json::json!(size.unit()));
fields.insert("widthUnit".into(), serde_json::json!(size.width_unit()));
fields
}
/// Sets one of [`size_json`]'s fields through the setter its row calls; `None` when `field` is not one of them. A
/// side whose row is disabled (pixels with Resample off) refuses as inactive.
fn set_size_json(size: &mut LinkedSize, field: &str, value: &serde_json::Value) -> Option<Result<(), String>> {
let rejects = || FieldRefusal::Rejects(value).message(field);
let kind = || serde_json::from_value::<UnitKind>(value.clone()).map_err(|_| rejects());
Some(match field {
"width" | "height" => {
let editable = if field == "width" { size.is_width_editable() } else { size.is_editable() };
if !editable {
return Some(Err(FieldRefusal::Inactive.message(field)));
}
let Some(number) = value.as_f64() else { return Some(Err(rejects())) };
if field == "width" {
size.set_width(number);
} else {
size.set_height(number);
}
Ok(())
}
"unit" => kind().and_then(|kind| if size.set_unit(kind) { Ok(()) } else { Err(rejects()) }),
"widthUnit" => kind().and_then(|kind| if size.set_width_unit(kind) { Ok(()) } else { Err(rejects()) }),
_ => return None,
})
}
/// A size dialog on `FormDialog`: `rows` edits the values and `answer` makes the result from them at OK. OK, Cancel
/// and Alt-for-Reset follow `ParamDialog`; OK is refused while the pixel size is empty or over the limit.
pub(super) fn show_form<'a, S: SizeForm + Default, R>(
@@ -253,6 +296,8 @@ pub(super) struct Kit {
units: Units,
link: Label,
lengths: Vec<Entry<UnitKind>>,
/// `lengths` and Columns: what the width offers when the values carry a column size.
widths: Vec<Entry<UnitKind>>,
resolutions: Vec<Entry<UnitKind>>,
}
@@ -275,11 +320,16 @@ impl Kit {
pub(super) fn new(ui: &Ui) -> Self {
let env = Env::of(ui);
let units = env.units();
let entries = |kinds: &[UnitKind]| kinds.iter().map(|kind| Entry::new(*kind, Label::from(units.symbol(*kind)))).collect();
let entries =
|kinds: &[UnitKind]| -> Vec<Entry<UnitKind>> { kinds.iter().map(|kind| Entry::new(*kind, Label::from(units.symbol(*kind)))).collect() };
let lengths = entries(&LENGTH_UNITS);
let mut widths = lengths.clone();
widths.extend(entries(&[UnitKind::Columns]));
Kit {
words: env.words::<SizingWords>(),
link: LinkMode::Ratio.label(&env.words::<LinkedWords>()),
lengths: entries(&LENGTH_UNITS),
lengths,
widths,
resolutions: entries(&RESOLUTION_UNITS),
units,
}
@@ -355,8 +405,9 @@ impl Kit {
/// One number with its unit, over the model.
fn row(&self, ui: &mut Ui, size: &mut LinkedSize, which: Dimension) {
let words = &self.words;
let widths = if size.columns().is_some() { &self.widths } else { &self.lengths };
let (name, unit_name, value, range, unit, entries, salt) = match which {
Dimension::Width => (&words.width, &words.width_unit, size.width(), size.width_range(), size.unit(), &self.lengths, "width"),
Dimension::Width => (&words.width, &words.width_unit, size.width(), size.width_range(), size.width_unit(), widths, "width"),
Dimension::Height => (&words.height, &words.height_unit, size.height(), size.height_range(), size.unit(), &self.lengths, "height"),
Dimension::Resolution => (
&words.resolution,
@@ -368,7 +419,11 @@ impl Kit {
"resolution",
),
};
let editable = !matches!(which, Dimension::Width | Dimension::Height) || size.is_editable();
let editable = match which {
Dimension::Width => size.is_width_editable(),
Dimension::Height => size.is_editable(),
Dimension::Resolution => true,
};
let mut field = Field::new(name.clone()).id_salt(salt);
if !editable {
field = field.tooltip(words.resample_off.clone());
@@ -389,7 +444,8 @@ impl Kit {
}
if let Some(kind) = shown.unit.value().copied() {
match which {
Dimension::Width | Dimension::Height => size.set_unit(kind),
Dimension::Width => size.set_width_unit(kind),
Dimension::Height => size.set_unit(kind),
Dimension::Resolution => size.set_resolution_unit(kind),
};
}
@@ -1,9 +1,10 @@
//! `CanvasSize`: the Canvas Size dialog.
use super::{CanvasExtension, Kit, LinkedSize, SizeForm, SizingOutput, show_form};
use super::{CanvasExtension, Kit, LinkedSize, SizeForm, SizingOutput, set_size_json, show_form, size_json, size_valid};
use crate::choice::Checkbox;
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use serde_json::json;
use crate::form::Field;
use crate::pickers::{Anchor9, ReferencePoint, Select};
use crate::runtime::env::{ColumnSize, UnitKind};
@@ -40,11 +41,28 @@ pub struct CanvasSizeValues {
}
impl CanvasSizeValues {
/// Sets the width of the column of the rows' fields, so the dialog lines up with its siblings.
/// The document's column size (the Units preference's column width and gutter): the Width row offers Columns,
/// converted through it as in Image Size. Without one the row offers no Columns.
#[must_use]
pub fn column_size(mut self, size: ColumnSize) -> Self {
let _ = (&mut self, size);
todo!("dl.K37")
self.size = self.size.column_size(size);
self
}
/// What OK answers with for these values.
fn result(&self) -> CanvasSizeResult {
CanvasSizeResult {
size: self.size.pixels(),
unit: self.size.unit(),
relative: self.size.is_relative(),
anchor: self.anchor,
extension: self.fill(),
}
}
/// The extension the canvas fills with: Transparent for a document with no background, whatever was set.
fn fill(&self) -> CanvasExtension {
if self.has_background { self.extension.clone() } else { CanvasExtension::Transparent }
}
/// The values for a canvas of `size` pixels, at 72 pixels per inch, in pixels, anchored at the centre and filling
@@ -165,9 +183,7 @@ impl<'a> CanvasSize<'a> {
|ui, state| {
let size = state.size.original();
let has_background = state.has_background;
if !has_background {
state.extension = CanvasExtension::Transparent;
}
state.extension = state.fill();
kit.readout(ui, &words.current_size, kit.file_size(size, bytes_per_pixel), None);
kit.readout(ui, &words.current_width, kit.pixels(size.width), None);
kit.readout(ui, &words.current_height, kit.pixels(size.height), None);
@@ -195,13 +211,7 @@ impl<'a> CanvasSize<'a> {
}
});
},
|state| CanvasSizeResult {
size: state.size.pixels(),
unit: state.size.unit(),
relative: state.size.is_relative(),
anchor: state.anchor,
extension: state.extension.clone(),
},
CanvasSizeValues::result,
)
}
}
@@ -252,18 +262,45 @@ const KEY: &str = "sizing.canvasSize";
impl StackDialog for HostedCanvasSize {
type Result = CanvasSizeResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K36")
/// Answers what OK answers; `None` while OK is refused (a side out of range).
fn confirm(&mut self, _ctx: &egui::Context) -> Option<Self::Result> {
size_valid(self.values.pixels()).then(|| self.values.result())
}
/// `width`, `height`, `unit` and `widthUnit` (as the size rows show them), `relative`, `anchor` and `extension`.
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K36")
let values = &self.values;
let mut fields = size_json(&values.size);
fields.insert("relative".into(), json!(values.size.is_relative()));
fields.insert("anchor".into(), json!(values.anchor));
fields.insert("extension".into(), json!(values.fill()));
Some(serde_json::Value::Object(fields))
}
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 through the setter its row calls. `extension` takes one the list offers, and refuses as
/// inactive for a document with no background (the list is off).
fn set_json_field(&mut self, _ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let values = &mut self.values;
if let Some(done) = set_size_json(&mut values.size, field, &value) {
return done;
}
let rejects = || FieldRefusal::Rejects(&value).message(field);
match field {
"relative" => values.size.relative(value.as_bool().ok_or_else(rejects)?),
"anchor" => values.anchor = serde_json::from_value::<Anchor9>(value.clone()).map_err(|_| rejects())?,
"extension" => {
if !values.has_background {
return Err(FieldRefusal::Inactive.message(field));
}
let extension = serde_json::from_value::<CanvasExtension>(value.clone()).map_err(|_| rejects())?;
if !CanvasExtension::offered(&values.extension, true).contains(&extension) {
return Err(rejects());
}
values.extension = extension;
}
_ => return Err(FieldRefusal::Unknown.message(field)),
}
Ok(())
}
fn id(&self) -> DialogId {
@@ -1,9 +1,10 @@
//! `ImageSize`: the Image Size dialog.
use super::{Kit, LinkedSize, Resample, SizeForm, SizingOutput, show_form};
use super::{Kit, LinkedSize, Resample, SizeForm, SizingOutput, set_size_json, show_form, size_json, size_valid};
use crate::choice::Checkbox;
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use serde_json::json;
use crate::form::Field;
use crate::pickers::Select;
use crate::runtime::env::{ColumnSize, UnitKind};
@@ -26,7 +27,8 @@ pub struct ImageSizeResult {
pub resample: Option<Resample>,
/// Whether layer effects scale with the image.
pub scale_styles: bool,
/// Whether the resolution was edited, so the app resamples at the new resolution.
/// Whether the resolution differs from the opening one. The opening resolution is held to the dialog's range, so
/// while this is `false` the app keeps the document's own resolution, which may lie outside it.
pub resolution_changed: bool,
}
@@ -43,11 +45,25 @@ pub struct ImageSizeValues {
}
impl ImageSizeValues {
/// Sets the width of the column of the rows' fields, so the dialog lines up with its siblings.
/// The document's column size (the Units preference's column width and gutter): the Width row offers Columns,
/// converted through it. Without one the row offers no Columns.
#[must_use]
pub fn column_size(mut self, size: ColumnSize) -> Self {
let _ = (&mut self, size);
todo!("dl.K37")
self.size = self.size.column_size(size);
self
}
/// What OK answers with for these values.
fn result(&self) -> ImageSizeResult {
ImageSizeResult {
size: self.size.pixels(),
pixels_per_inch: self.size.pixels_per_inch(),
unit: self.size.unit(),
resolution_unit: self.size.resolution_unit(),
resample: self.size.is_resampling().then_some(self.method),
scale_styles: self.scale_styles,
resolution_changed: self.size.resolution_changed(),
}
}
/// The values for a document of `size` pixels, at 72 pixels per inch, in pixels, resampling automatically with
@@ -200,15 +216,7 @@ impl<'a> ImageSize<'a> {
state.scale_styles = on;
}
},
|state| ImageSizeResult {
size: state.size.pixels(),
pixels_per_inch: state.size.pixels_per_inch(),
unit: state.size.unit(),
resolution_unit: state.size.resolution_unit(),
resample: state.size.is_resampling().then_some(state.method),
scale_styles: state.scale_styles,
resolution_changed: false, // P3(dialogs-w13): dl.K36
},
ImageSizeValues::result,
)
}
}
@@ -259,18 +267,70 @@ const KEY: &str = "sizing.imageSize";
impl StackDialog for HostedImageSize {
type Result = ImageSizeResult;
fn confirm(&mut self, ctx: &egui::Context) -> Option<Self::Result> {
let _ = ctx;
todo!("dl.K36")
/// Answers what OK answers; `None` while OK is refused (a side out of range).
fn confirm(&mut self, _ctx: &egui::Context) -> Option<Self::Result> {
size_valid(self.values.pixels()).then(|| self.values.result())
}
/// `width`, `height`, `unit` and `widthUnit` (as the size rows show them), `resolution`, `resolutionUnit`,
/// `resample` (the method, `null` while Resample is off), `constrain` and `scaleStyles`.
fn json_fields(&self) -> Option<serde_json::Value> {
todo!("dl.K36")
let values = &self.values;
let mut fields = size_json(&values.size);
fields.insert("resolution".into(), json!(values.size.resolution()));
fields.insert("resolutionUnit".into(), json!(values.size.resolution_unit()));
fields.insert("resample".into(), json!(values.size.is_resampling().then_some(values.method)));
fields.insert("constrain".into(), json!(values.size.is_linked()));
fields.insert("scaleStyles".into(), json!(values.scale_styles));
Some(serde_json::Value::Object(fields))
}
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 through the setter its row calls. The chain and Scale Styles refuse as inactive while their
/// rows are disabled; `resample` takes a method the dialog lists or `null` (Resample off).
fn set_json_field(&mut self, _ctx: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
let methods = (self.build)(Bind::bound(&mut self.values)).methods;
let values = &mut self.values;
if let Some(done) = set_size_json(&mut values.size, field, &value) {
return done;
}
let rejects = || FieldRefusal::Rejects(&value).message(field);
match field {
"resolution" => {
let number = value.as_f64().ok_or_else(rejects)?;
values.size.set_resolution(number);
}
"resolutionUnit" => {
let kind = serde_json::from_value::<UnitKind>(value.clone()).map_err(|_| rejects())?;
if !values.size.set_resolution_unit(kind) {
return Err(rejects());
}
}
"resample" if value.is_null() => values.size.resampling(false),
"resample" => {
let method = serde_json::from_value::<Resample>(value.clone()).map_err(|_| rejects())?;
if !methods.is_empty() && !methods.contains(&method) {
return Err(rejects());
}
values.size.resampling(true);
values.method = method;
}
"constrain" => {
let on = value.as_bool().ok_or_else(rejects)?;
if !values.size.is_resampling() {
return Err(FieldRefusal::Inactive.message(field));
}
values.size.lock(on);
}
"scaleStyles" => {
let on = value.as_bool().ok_or_else(rejects)?;
if !values.size.is_linked() {
return Err(FieldRefusal::Inactive.message(field));
}
values.scale_styles = on;
}
_ => return Err(FieldRefusal::Unknown.message(field)),
}
Ok(())
}
fn id(&self) -> DialogId {
@@ -4,11 +4,14 @@
use craft_behavior::PixelSize;
use craft_ui::dialog::{DialogHost, DialogResult, StackDialog};
use craft_ui::patterns::form_dialogs::{
AboutInfo, AboutLink, CanvasSize, CanvasSizeValues, Credits, ExportOptions, ExportOptionsKind, FormatOptions, HostedAbout, HostedCanvasSize,
HostedExportAs, HostedFormatOptions, JpegOptions,
AboutInfo, AboutLink, CanvasSize, CanvasSizeValues, Credits, ExportOptions, ExportOptionsKind, FormatOptions, GuideLayoutDialog, GuideLayoutValues,
GuideRect, GuideUnits, HostedAbout, HostedCanvasSize, HostedExportAs, HostedFormatOptions, HostedGuideLayoutDialog, HostedImageSize,
HostedNewGuideDialog, ImageSize, ImageSizeValues, JpegOptions, NewGuideDialog, NewGuideValues,
};
use craft_ui::runtime::env::UnitKind;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Vec2};
use serde_json::{Value, json};
use std::cell::RefCell;
use std::fmt::Debug;
use std::path::PathBuf;
@@ -26,6 +29,45 @@ fn canvas_size() -> HostedCanvasSize {
HostedCanvasSize::new(CanvasSizeValues::new(PICTURE), |values| CanvasSize::new(values))
}
#[allow(clippy::redundant_closure, reason = "the builder must be generic over the bind's lifetime, which the bare path is not")]
fn image_size() -> HostedImageSize {
HostedImageSize::new(ImageSizeValues::new(PICTURE), |values| ImageSize::new(values))
}
/// The document of the guide dialogs: 3000 × 2000 px at 300 ppi, measured in pixels.
fn guide_units() -> GuideUnits {
GuideUnits::new(UnitKind::Pixels, 3000.0, 2000.0, 300.0)
}
fn guide_layout() -> HostedGuideLayoutDialog {
HostedGuideLayoutDialog::new(GuideLayoutValues::default(), |values| {
GuideLayoutDialog::new(guide_units(), GuideRect::new(0.0, 0.0, 3000.0, 2000.0), values)
})
}
fn new_guide() -> HostedNewGuideDialog {
HostedNewGuideDialog::new(NewGuideValues::default(), |values| NewGuideDialog::new(guide_units(), values))
}
/// Drives `dialog` as automation does, before any pass: the host lists its fields with `field` among them, an unknown
/// field is refused and changes nothing, `field` takes `value` and is listed with it, and OK answers. Returns the
/// answer.
fn automate<D: StackDialog>(dialog: D, field: &str, value: Value) -> Option<D::Result> {
let ctx = egui::Context::default();
let mut host = DialogHost::new();
let id = host.open(dialog);
let listed = |host: &DialogHost| host.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields);
let before = listed(&host).unwrap_or(Value::Null);
assert!(before.get(field).is_some(), "{field} is listed in {before}");
assert!(host.set_json_field(&ctx, id, "noSuchField", json!(1)).is_err(), "an unknown field is refused");
assert_eq!(listed(&host).unwrap_or(Value::Null), before, "a refused field changes nothing");
assert_eq!(host.set_json_field(&ctx, id, field, value.clone()), Ok(()), "{field} takes {value}");
assert_eq!(listed(&host).and_then(|fields| fields.get(field).cloned()), Some(value), "{field} is listed with the set value");
assert!(host.confirm::<D>(&ctx), "OK is enabled");
assert!(host.is_empty(), "OK closes the dialog");
host.take::<D>().and_then(DialogResult::ok)
}
/// A fixture that runs `host` every pass, in a room large enough for every form.
fn fixture(host: &Rc<RefCell<DialogHost>>) -> Fixture {
let shown = Rc::clone(host);
@@ -85,6 +127,17 @@ fn hosted_forms_answer_ok_with_their_values() {
fixture.click(&website).idle(4);
let link = host.borrow_mut().get_mut::<HostedAbout>().and_then(HostedAbout::take_link);
assert_eq!(link.as_deref(), Some("https://example.org"), "the link waits for the app");
// PatternFillDialog and CreateShapeDialog live in craft-draw, which depends on this crate; their automation is
// driven in craft-draw's tests/it (shape_drag.rs, pattern_fill.rs).
let image = automate(image_size(), "width", json!(800.0)).map(|result| result.size);
assert_eq!(image, Some(PixelSize::new(800, 450)), "Image Size answers the set width, the height following the lock");
let canvas = automate(canvas_size(), "width", json!(2000.0)).map(|result| result.size);
assert_eq!(canvas, Some(PixelSize::new(2000, 900)), "Canvas Size answers the set width; its sides are not linked");
let layout = automate(guide_layout(), "centerColumns", json!(true)).map(|result| (result.options.center_columns, result.guides.is_empty()));
assert_eq!(layout, Some((true, false)), "Guide Layout answers its options and the guides they make");
let guide = automate(new_guide(), "position", json!(250.0)).map(|guide| guide.position);
assert_eq!(guide, Some(250.0), "New Guide answers the guide at the set position");
}
#[trial]
@@ -2,7 +2,7 @@
use craft_behavior::PixelSize;
use craft_ui::patterns::form_dialogs::LinkedSize;
use craft_ui::runtime::env::UnitKind;
use craft_ui::runtime::env::{ColumnSize, UnitKind};
use craft_ui::testing::trial;
fn document() -> LinkedSize {
@@ -51,3 +51,95 @@ fn without_resampling_a_physical_size_changes_the_resolution() {
assert!((size.pixels_per_inch() - 150.0).abs() < 1e-9);
assert!((size.height() - 800.0 / 150.0).abs() < 1e-9);
}
/// PhotoCraft #9260: a document above the resolution range opens clamped, and the clamped value counts as the opening
/// one, so the app keeps the document's own resolution until the user edits the resolution.
#[trial]
fn an_untouched_resolution_outside_the_range_is_not_reported_as_changed() {
let mut size = document().opening_resolution(50_000.0);
assert_eq!(size.pixels_per_inch(), 30_000.0, "the field shows the clamped resolution");
assert!(!size.resolution_changed(), "an untouched resolution is not a change");
size.set_width(600.0);
assert!(!size.resolution_changed(), "a pixel edit with Resample on keeps the resolution");
size.set_resolution(300.0);
assert!(size.resolution_changed(), "an edit of the resolution is a change");
}
/// The 180 pt / 12 pt column size of the Units preference.
const COLUMNS: ColumnSize = ColumnSize { width: 180.0, gutter: 12.0 };
fn close(actual: f64, expected: f64) -> bool {
(actual - expected).abs() < 1e-9
}
/// Columns on the width convert through the column size: `n` columns are `n·180 + (n−1)·12` points, at the document's
/// resolution, both ways. A relative change keeps 0 at 0 and its sign, a degenerate column size falls back to
/// 180 pt / 12 pt, the height keeps the shared unit, and with Resample off a Columns width changes the resolution.
#[trial]
fn columns_on_the_width_convert_through_the_column_size() {
for ppi in [72.0, 144.0] {
for columns in [1.0, 2.0, 3.0, 0.5] {
let pixels = (columns * 192.0 - 12.0) * ppi / 72.0;
let mut typed = document().opening_resolution(ppi).column_size(COLUMNS);
assert!(typed.set_width_unit(UnitKind::Columns));
typed.set_width(columns);
assert_eq!(f64::from(typed.pixels().width), pixels, "{columns} col at {ppi} ppi as pixels");
let mut read = LinkedSize::new(PixelSize::new(pixels as u32, 800)).opening_resolution(ppi).column_size(COLUMNS);
assert!(read.set_width_unit(UnitKind::Columns));
assert!(close(read.width(), columns), "{pixels} px at {ppi} ppi reads {columns} col, not {}", read.width());
}
}
let mut relative = document().column_size(COLUMNS);
relative.relative(true);
relative.lock(false);
assert!(relative.set_width_unit(UnitKind::Columns));
assert_eq!(relative.width(), 0.0, "no change reads 0 columns, not the gutter");
relative.set_width(0.0);
assert_eq!(pixels(&relative), (1200, 800), "a change of 0 columns changes nothing");
relative.set_width(-1.0);
assert_eq!(pixels(&relative).0, 1020, "a change of -1 column takes one column width off");
assert!(relative.set_width_unit(UnitKind::Pixels));
relative.set_width(-372.0);
assert!(relative.set_width_unit(UnitKind::Columns));
assert!(close(relative.width(), -2.0), "a shrink of two columns reads -2, not {}", relative.width());
let degenerate = [
ColumnSize { width: 0.0, gutter: f64::NAN },
ColumnSize { width: f64::NAN, gutter: f64::INFINITY },
ColumnSize { width: -5.0, gutter: f64::NAN },
];
for column_size in degenerate {
let mut size = document().column_size(column_size);
assert!(size.set_width_unit(UnitKind::Columns));
size.set_width(2.0);
assert_eq!(pixels(&size).0, 372, "{column_size:?} converts as 180 pt / 12 pt");
assert!(size.width().is_finite());
}
let mut no_gutter = document().column_size(ColumnSize { width: 100.0, gutter: -4.0 });
assert!(no_gutter.set_width_unit(UnitKind::Columns));
no_gutter.set_width(2.0);
assert_eq!(pixels(&no_gutter).0, 200, "a negative gutter counts as none");
let mut shared = document();
assert!(!shared.set_width_unit(UnitKind::Columns), "without a column size the width offers no Columns");
assert_eq!(shared.width_unit(), UnitKind::Pixels);
let mut shared = shared.column_size(COLUMNS);
assert!(shared.set_unit(UnitKind::Inches));
assert!(shared.set_width_unit(UnitKind::Columns));
assert_eq!((shared.width_unit(), shared.unit()), (UnitKind::Columns, UnitKind::Inches), "the height keeps the shared unit");
assert!(close(shared.height(), 800.0 / 72.0), "the height still reads in inches");
assert!(shared.set_width_unit(UnitKind::Pixels));
assert_eq!((shared.width_unit(), shared.unit()), (UnitKind::Pixels, UnitKind::Pixels), "another unit turns Columns off and sets both");
let mut fixed = document().column_size(COLUMNS);
fixed.resampling(false);
assert!(fixed.set_width_unit(UnitKind::Columns));
assert!(!fixed.is_editable(), "the height in pixels takes no input with Resample off");
assert!(fixed.is_width_editable(), "a Columns width is a physical size");
fixed.set_width(2.0);
assert_eq!(pixels(&fixed), (1200, 800), "the pixel count stays");
assert!(close(fixed.pixels_per_inch(), 72.0 * 1200.0 / 372.0), "the resolution follows the width");
assert!(fixed.resolution_changed());
}