Dialogs: a number field left on text that is not a number restores the value before it

Typing a number into a dialog's number field, then text that is not a
number, then leaving the field cancels the typing. These dialogs read
the field with value(), which ignores the cancel, so they kept the last
number typed. They now read events.landed(), as the tool option form
does since #9750, and take back the value the cancel restores.

- Rearrange Artboards, Layer Options, Define Perspective Grid, Bullets
  and Numbering, PNG Options, Composite Fonts, Graph Data, Print, Transform
  Each, Width Point Edit, Split Into Grid and the gradient stop popover.
- Layer Options for several layers sends no Dim Images value when the
  canceled typing began with the field unset.
- Bullets and Numbering puts a blank field back to blank.
- Graph Data's Column Width gives back every column's own width.
- Width Point Edit: an edit of Side 1, Side 2 or Total Width that ends
  in a cancel (Escape, or leaving the field on text that is not a
  number) puts back the side widths from before the edit, but only the
  sides that still hold the edit's last value. Canceling Total Width
  after a 0 keeps unequal sides unequal. With several points selected,
  each point gets back its own widths, also when the field showed no
  common width and the edit was the wheel turned over the held field
  and then Escape. OK no longer applies the canceled width.
- Width Point Edit, Graph Data's Column Width and Layer Options' Dim
  Images to put values back only when the user canceled the edit. A
  value set by anything else while an edit runs stays: ui.dialog.set
  (in Graph Data also a per-column width set through widths), and in
  Width Point Edit a link toggle or an edit of the other set of sides,
  even when it sets the same value as the canceled edit.
This commit is contained in:
dotCooCoo
2026-11-29 01:45:01 -08:00
parent 5f92d8987f
commit 84dc59e4df
18 changed files with 1272 additions and 69 deletions
@@ -27,7 +27,7 @@
use std::borrow::Cow;
use std::sync::{Arc, Weak};
use craft::behavior::{Mixed, Selection, SelectionChange, keyed};
use craft::behavior::{EditEvent, EditEvents, Mixed, Selection, SelectionChange, keyed};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
@@ -317,8 +317,20 @@ impl BulletsDialog {
fn level(&mut self, ui: &mut Ui) {
let value = self.fields.get("listLevel").and_then(Value::as_f64);
let edit = NumberField::new(tl!("Level:"), Bind::given(value)).range(1.0..=LIST_LEVELS as f64).commit_decimals(0).show(ui);
if let Some(Some(v)) = edit.value().copied() {
self.fields.insert("listLevel".into(), json!(v));
self.land("listLevel", &edit.edit.events);
}
/// Sets `key` to the number its field's `events` leave: the number entered or the number a canceled edit
/// restores, and no number where a canceled edit restores a blank field.
fn land(&mut self, key: &str, events: &EditEvents<Option<f64>>) {
match events.landed() {
Some(Some(v)) => {
self.fields.insert(key.into(), json!(v));
}
Some(None) if matches!(events.ended(), Some(EditEvent::Cancel { .. })) => {
self.fields.remove(key);
}
_ => {}
}
}
@@ -393,9 +405,7 @@ impl BulletsDialog {
.enabled(on == Some(true))
.id_salt("startNumber")
.show(ui);
if let Some(Some(v)) = edit.value().copied() {
self.fields.insert("startNumber".into(), json!(v));
}
self.land("startNumber", &edit.edit.events);
});
}
@@ -415,9 +425,7 @@ impl BulletsDialog {
fn indent(&mut self, ui: &mut Ui, key: &'static str, label: &'static str) {
let value = self.fields.get(key).and_then(Value::as_f64);
let edit = NumberField::length(label, Bind::given(value), self.lengths).range(INDENTS).show(ui);
if let Some(Some(v)) = edit.value().copied() {
self.fields.insert(key.into(), json!(v));
}
self.land(key, &edit.edit.events);
}
}
@@ -1239,4 +1247,41 @@ mod tests {
ok(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Dot).at_level(3)));
}
/// Leaving Level, Start at or an indent on text that is not a number cancels the typing: the field goes back to
/// the number it had before it, or to blank where the paragraphs differ, and so does the type.
#[test]
fn a_canceled_number_edit_restores_the_field_and_the_type() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let (mut app, id) = app();
app.run("text.setFormat", json!({"number": "arabic"})).unwrap();
app.run("text.setFormat", json!({"ids": [id], "leftIndent": 30, "start": 0, "end": 0})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1800.0));
panel.app().run("ui.bulletsAndNumbering", json!({})).unwrap();
panel.frame();
set(&mut panel.app(), "startAt", json!(true));
panel.frame();
assert!(fields(&panel.app()).get("leftIndent").is_none(), "the paragraphs' left indents differ: blank");
let state = |panel: &Panel| {
let app = panel.app();
(sent(&app), first(&app, id))
};
for name in ["Level:", "Start at:", "Left Indent:", "First Line Indent:"] {
let before = state(&panel);
panel.click_role(name, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("7");
assert_ne!(state(&panel).0, before.0, "typing into {name} proposes a number");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "leaving {name} keeps the dialog open");
assert_eq!(state(&panel), before, "leaving {name} on text that is not a number restores it");
}
}
}
@@ -719,7 +719,7 @@ fn percent<'r>(list: ListRow<'r>, spec: &Percent, value: f64, at: usize, edits:
let Percent { column, label, range, edit } = spec;
let (edit, field) = (*edit, NumberField::new(*label, Bind::given(Some(value))).range((*range).clone()).unit("%"));
list.cell_field(column.clone(), field, move |out| {
if let Some(Some(v)) = out.edit.value().copied() {
if let Some(Some(v)) = out.edit.events.landed().copied() {
edits.borrow_mut().push((at, edit(v)));
}
})
@@ -650,6 +650,36 @@ fn a_highlighted_part_style_applies_only_once_it_is_chosen() {
assert_ne!(parts(&p), before, "Enter sets the style");
}
/// Leaving a part's Size or Baseline on text that is not a number cancels the typing, and the part goes back to the
/// value it had before it.
#[test]
fn a_canceled_part_percentage_restores_the_part() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let mut p = Panel::new(app(), crate::tests::picks::dialogs);
p.room(egui::vec2(1280.0, 1100.0));
open(&mut p.app()).unwrap();
new_font(&mut p.app());
p.frame();
p.frame();
let parts = |p: &Panel| dialog(&mut p.app(), |d| d.font().map(|f| f.parts.clone()));
for name in ["Size", "Baseline"] {
let before = parts(&p);
p.click_role(name, Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("37");
assert_ne!(parts(&p), before, "typing into {name} proposes a value");
p.type_text("x");
p.key(Key::Tab, Modifiers::NONE);
p.frame();
assert!(is_open(&p.app()), "leaving {name} keeps the dialog open");
assert_eq!(parts(&p), before, "leaving {name} on text that is not a number restores the part");
}
}
#[test]
fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() {
let mut app = app();
+30 -2
View File
@@ -524,12 +524,13 @@ fn swatches(ui: &mut Ui, feed: &Feed, filed: &mut Filed) {
filed.swatch = at.and_then(|i| feed.swatches.get(i)).cloned();
}
/// A percent field named `label` over `value`; the number the user entered in this pass.
/// A percent field named `label` over `value`; the number the user entered in this pass, or the number a canceled
/// typing gives back.
fn percent_field(ui: &mut Ui, label: String, value: f64) -> Option<f64> {
let field = Field::new(label.clone()).show(ui, |ui, _| {
NumberField::new(label.clone(), Bind::given(Some(value))).unit_kind(UnitKind::Percent).range(0.0..=100.0).step(1.0).show(ui)
});
field.inner?.value().copied().flatten()
field.inner?.edit.events.landed().copied().flatten()
}
/// The popover's size before it has been drawn, for placing it.
@@ -869,6 +870,33 @@ mod tests {
assert!(set(&app, "color", json!("red")).is_err());
}
/// Leaving Opacity or Location on text that is not a number cancels the typing, and OK then leaves the stop as it
/// was.
#[test]
fn a_canceled_opacity_or_location_leaves_the_stop_as_it_was() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
for name in ["Opacity", "Location"] {
let mut panel = Panel::new(app(), crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open_popover(&mut panel.app());
panel.frame();
let before = stops(&panel.app());
panel.click_role(name, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("40");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "leaving {name} keeps the popover open");
confirm(&mut panel.app());
assert_eq!(stops(&panel.app()), before, "OK after leaving {name} on text that is not a number leaves the stop as it was");
}
}
#[test]
fn the_popover_discards_a_pending_edit_after_selecting_other_art() {
let mut app = app();
+106 -7
View File
@@ -20,7 +20,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use craft::behavior::{EditEvent, NumberCodec};
use craft::behavior::{CancelReason, EditEvent, NumberCodec};
use craft::host::{PickRequest, Picked};
use craft::table::ui::{
CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions,
@@ -140,6 +140,8 @@ struct Lines {
columns: LineIndex,
/// The own width of the column whose edge a drag holds, as it was when the drag began.
resize_from: Option<Option<u64>>,
/// Cell Style's Column Width and the columns' own widths, as they were when typing a Column Width began.
width_from: Option<(u64, Vec<Option<u64>>)>,
}
impl Lines {
@@ -149,6 +151,7 @@ impl Lines {
rows: LineIndex::uniform(ROW_H, 0),
columns: LineIndex::uniform(digits_px(DEFAULT_WIDTH), MAX_COLS as u32),
resize_from: None,
width_from: None,
}
}
@@ -633,16 +636,31 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool {
let field = whole(&units, tl!("Number of Decimals"), values.decimals.unwrap_or(DEFAULT_DECIMALS), MAX_DECIMALS)
.enabled(values.decimals.is_some())
.show(ui);
if let Some(n) = digits(field.edit.value().copied().flatten(), MAX_DECIMALS) {
if let Some(n) = digits(field.edit.events.landed().copied().flatten(), MAX_DECIMALS) {
values.decimals = Some(n);
}
Text::new(tl!("Column Width:")).show(ui);
let field = whole(&units, tl!("Column Width"), width(values), MAX_WIDTH).show(ui);
// A value entered with Enter sets every column, also when it is the width shown. Leaving the
// field without a new value keeps the columns' own widths.
let typed = digits(field.edit.value().copied().flatten(), MAX_WIDTH);
if typed.is_some() || field.edit.submitted {
set_width(values, typed.unwrap_or_else(|| width(values)));
let events = &field.edit.events;
if events.began() {
lines.width_from = Some((values.width, values.widths.clone()));
}
if let Some(reason) = events.cancel_reason() {
// A user rollback restores Cell Style's width and the columns' own widths; other cancels keep the host's values.
if let Some((shown, own)) = lines.width_from.take().filter(|_| matches!(reason, CancelReason::Escape | CancelReason::Blur)) {
values.width = shown;
values.widths = own;
}
} else {
// A value entered with Enter sets every column, also when it is the width shown. Leaving the
// field without a new value keeps the columns' own widths.
let typed = digits(events.value().copied().flatten(), MAX_WIDTH);
if typed.is_some() || field.edit.submitted {
set_width(values, typed.unwrap_or_else(|| width(values)));
}
if events.ended().is_some() {
lines.width_from = None;
}
}
});
lines.sync(extent(values, active(state)), values);
@@ -830,6 +848,9 @@ impl StackDialog for GraphDataDialog {
load(&self.sheet, &self.state, &mut self.entry);
}
}
if matches!(field, "width" | "widths") {
self.lines.width_from = None;
}
Ok(())
}
}
@@ -1399,4 +1420,82 @@ mod tests {
edit(&app, |d| set_col_digits(&mut d.sheet, 1, 4));
assert_eq!(read(&app, |d| (col_digits(&d.sheet, 1), col_digits(&d.sheet, 3))), (4, 7), "a drag after it gives that column its own width");
}
/// Leaving Number of Decimals or Column Width on text that is not a number cancels the typing: the decimals go back
/// to what they were, and so do Column Width and the widths columns were given of their own.
#[test]
fn a_canceled_cell_style_number_restores_the_decimals_and_the_widths() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let (app, _) = app_with(",a,b\nQ1,1,2", "column");
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open(&mut panel.app()).unwrap();
panel.frame();
set_field(&panel.app(), "decimals", json!(2)).unwrap();
edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4));
panel.frame();
let style = |panel: &Panel| read(&panel.app(), |d| (d.sheet.decimals, d.sheet.width, d.sheet.widths.clone()));
for name in ["Number of Decimals", "Column Width"] {
let before = style(&panel);
panel.click_role(name, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("5");
assert_ne!(style(&panel), before, "typing into {name} proposes a value");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert_eq!(style(&panel), before, "leaving {name} on text that is not a number restores Cell Style");
}
}
/// An outside Column Width replaces a running edit and keeps the columns at the assigned width.
#[test]
fn an_outside_column_width_survives_a_running_edit() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let (app, _) = app_with(",a,b\nQ1,1,2", "column");
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open(&mut panel.app()).unwrap();
panel.frame();
edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4));
panel.frame();
panel.click_role("Column Width", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("5");
set_field(&panel.app(), "width", json!(13)).unwrap();
let assigned = read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone()));
panel.frame();
assert_eq!(read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone())), assigned, "the host's column widths survive cancellation");
}
/// Outside per-column widths survive invalid Column Width text.
#[test]
fn an_outside_per_column_width_survives_a_running_edit() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let (app, _) = app_with(",a,b\nQ1,1,2", "column");
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open(&mut panel.app()).unwrap();
panel.frame();
panel.click_role("Column Width", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("5");
set_field(&panel.app(), "widths", json!([null, 13, null])).unwrap();
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert_eq!(read(&panel.app(), |d| d.sheet.widths.clone()), vec![None, Some(13), None], "invalid Column Width text preserves assigned widths");
}
}
+83 -1
View File
@@ -11,6 +11,7 @@
use std::cell::RefCell;
use craft::behavior::CancelReason;
// PLAN: `craft::color_ui` and `craft::theme` need the `craft` facade (feature `color-ui`) in ui-egui's Cargo.toml, which has only `craft-ui`; the owner of the craft-libs pin adds it.
use craft::color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
use craft::theme::Srgba;
@@ -72,6 +73,8 @@ pub(crate) struct LayerOptionsValue {
ids: Vec<u64>,
/// The fields set in the dialog, by its controls or `ui.dialog.set`.
set: Vec<&'static str>,
/// While a typed percentage runs: whether the percentage was set in the dialog when the typing began.
dim_set_before_typing: Option<bool>,
opened: Option<Opened>,
}
@@ -93,6 +96,7 @@ impl Default for LayerOptionsValue {
mode: "edit",
ids: Vec::new(),
set: Vec::new(),
dim_set_before_typing: None,
opened: None,
}
}
@@ -362,10 +366,22 @@ fn body(ui: &mut egui::Ui, v: &mut LayerOptionsValue, requested: &RefCell<Option
.unit_kind(UnitKind::Percent)
.enabled(v.dim_images)
.show(ui);
if let Some(Some(percent)) = field.edit.value().copied() {
let events = &field.edit.events;
if events.began() {
v.dim_set_before_typing = Some(v.is_set("dimPercent"));
}
if let Some(Some(percent)) = events.landed().copied() {
v.dim_percent = percent;
v.mark("dimPercent");
}
// A user rollback restores the percentage's mark; other cancels keep the host's mark.
if events.ended().is_some() {
if matches!(events.cancel_reason(), Some(CancelReason::Escape | CancelReason::Blur)) && v.dim_set_before_typing == Some(false)
{
v.set.retain(|field| *field != "dimPercent");
}
v.dim_set_before_typing = None;
}
});
}
});
@@ -898,6 +914,72 @@ mod tests {
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
}
/// Leaving the Dim Images percentage on text that is not a number cancels the typing: the field goes back to the
/// percentage it had before it, and for several layers OK still leaves each layer's own percentage alone.
#[test]
fn a_canceled_dim_percentage_restores_it_and_sends_nothing_for_several_layers() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
for many in [false, true] {
let mut app = app();
app.run("layer.new", json!({})).unwrap();
let ids: Vec<u64> = app.session.active().unwrap().doc.layers.iter().map(|l| l.id.0).collect();
for (id, percent) in ids.iter().zip([30, 70]) {
app.run("layer.setProps", json!({"ids": [id], "dimImages": percent})).unwrap();
}
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 900.0));
let edited = if many { ids.clone() } else { vec![ids[0]] };
panel.app().run("ui.layerOptions", json!({"ids": edited})).unwrap();
panel.frame();
let state = |panel: &Panel| {
let app = panel.app();
(fields(&app), current_params(&app))
};
let before = state(&panel);
panel.click_role("Dim Images to:", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("45");
assert_ne!(state(&panel).0, before.0, "typing proposes a percentage");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(panel.app().any_dialog_open(), "leaving the field keeps the dialog open");
assert_eq!(state(&panel), before, "leaving the field on text that is not a number restores the percentage, several layers: {many}");
}
}
/// An outside percentage replaces a running edit and stays marked for every layer on OK.
#[test]
fn an_outside_dim_percentage_survives_a_running_edit() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let mut app = app();
app.run("layer.new", json!({})).unwrap();
let ids: Vec<u64> = app.session.active().unwrap().doc.layers.iter().map(|l| l.id.0).collect();
for (id, percent) in ids.iter().zip([30, 70]) {
app.run("layer.setProps", json!({"ids": [id], "dimImages": percent})).unwrap();
}
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 900.0));
panel.app().run("ui.layerOptions", json!({"ids": ids})).unwrap();
panel.frame();
panel.click_role("Dim Images to:", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("45");
set(&mut panel.app(), "dimPercent", json!(60));
let assigned = current_params(&panel.app());
panel.frame();
assert_eq!(current_params(&panel.app()), assigned, "the host's percentage stays marked after cancellation");
ok(&mut panel.app());
for id in ids {
assert!(matches!(layer(&panel.app(), NodeId(id)).kind, NodeKind::Layer { dim_images: Some(60), .. }), "OK applies the host's percentage");
}
}
#[test]
fn layer_options_and_new_layers_follow_their_document() {
for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] {
+2 -2
View File
@@ -237,7 +237,7 @@ pub(crate) fn split_fields(width: f64, height: f64) -> DialogFields {
/// One cell of Split Into Grid's grid: a labelled number field. A count (`lengths` is `None`) is a whole number;
/// the others are lengths. A cell whose visible label repeats another's carries its axis in its name, so the visible
/// label only describes it. Returns the value typed this pass.
/// label only describes it. Returns the value typed this pass, or the value a canceled typing gives back.
fn cell(ui: &mut egui::Ui, label: &'static str, name: String, describes: bool, value: f64, lengths: Option<LengthUnits>) -> Option<f64> {
let role = if describes { FieldLabelRole::Describes } else { FieldLabelRole::Names };
let mut edited = None;
@@ -247,7 +247,7 @@ fn cell(ui: &mut egui::Ui, label: &'static str, name: String, describes: bool, v
Some(l) => NumberField::length(name.clone(), bind, l).show(ui),
None => NumberField::new(name.clone(), bind).range(1.0..=500.0).commit_decimals(0).show(ui),
};
edited = out.value().copied().flatten();
edited = out.edit.events.landed().copied().flatten();
});
edited
}
@@ -328,7 +328,7 @@ impl Pass<'_> {
Row::new().id_salt("custom-scale").show(ui, |ui, _| {
for (i, label) in [word("Artboard:"), word("Real World:")].into_iter().enumerate() {
let field = NumberField::new(label, Bind::given(Some(scale[i]))).range(SCALE_RANGE).show(ui);
if let Some(v) = field.edit.value().copied().flatten() {
if let Some(v) = field.edit.events.landed().copied().flatten() {
draft.def.scale[i] = v;
}
}
@@ -346,7 +346,7 @@ impl Pass<'_> {
let label = word("Viewing Angle:");
row(ui, &label, "angle", |ui| {
let field = NumberField::new(label.clone(), Bind::given(Some(draft.def.angle))).unit_kind(UnitKind::Degrees);
if let Some(v) = field.range(0.01..=89.99).enabled(kind != 1).show(ui).edit.value().copied().flatten() {
if let Some(v) = field.range(0.01..=89.99).enabled(kind != 1).show(ui).edit.events.landed().copied().flatten() {
draft.def.angle = v;
}
});
@@ -357,7 +357,7 @@ impl Pass<'_> {
Row::new().id_salt("third-vp-row").show(ui, |ui, _| {
for (i, axis) in ["X:", "Y:"].into_iter().enumerate() {
let field = NumberField::length(word(axis), Bind::given(Some(draft.def.third_vp[i])), lengths).enabled(kind == 3);
if let Some(v) = field.show(ui).edit.value().copied().flatten() {
if let Some(v) = field.show(ui).edit.events.landed().copied().flatten() {
draft.def.third_vp[i] = v;
}
}
@@ -386,7 +386,7 @@ fn choose<T: craft::behavior::Value>(ui: &mut egui::Ui, name: &str, salt: &str,
fn length(ui: &mut egui::Ui, name: &str, salt: &str, value: &mut f64, lengths: LengthUnits) {
let label = word(name);
row(ui, &label, salt, |ui| {
if let Some(v) = NumberField::length(label.clone(), Bind::given(Some(*value)), lengths).show(ui).edit.value().copied().flatten() {
if let Some(v) = NumberField::length(label.clone(), Bind::given(Some(*value)), lengths).show(ui).edit.events.landed().copied().flatten() {
*value = v;
}
});
+1 -1
View File
@@ -230,7 +230,7 @@ fn resolution_row() -> Param {
.step(1.0)
.unit_kind(UnitKind::PixelsPerInch)
.show(ui);
typed = field.edit.value().copied().flatten();
typed = field.edit.events.landed().copied().flatten();
}
});
if let Some(i) = picked {
+1 -1
View File
@@ -925,7 +925,7 @@ fn ink_table(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut craft::ui::pa
.enabled(!process)
.id_salt(("print-ink", name, k))
.show(ui);
if let Some(Some(x)) = typed.edit.value() {
if let Some(Some(x)) = typed.edit.events.landed() {
set_ink(fields, name, k, json!(x));
}
}
@@ -228,13 +228,13 @@ fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, selected:
Field::new(count).id_salt("columns").enabled(v.is_grid()).show(ui, |ui, _| {
let most = artboards.max(1) as f64;
let field = NumberField::new(count, Bind::given(Some(v.columns))).range(1.0..=most).step(1.0).show(ui);
if let Some(Some(columns)) = field.edit.value().copied() {
if let Some(Some(columns)) = field.edit.events.landed().copied() {
v.columns = columns.round().clamp(1.0, most);
}
});
Field::new(tl!("Spacing:")).id_salt("spacing").show(ui, |ui, _| {
let field = NumberField::length(tl!("Spacing:"), Bind::given(Some(v.spacing)), lengths).show(ui);
if let Some(Some(spacing)) = field.edit.value().copied() {
if let Some(Some(spacing)) = field.edit.events.landed().copied() {
v.spacing = spacing;
}
});
@@ -733,4 +733,31 @@ mod tests {
.collect();
assert_eq!(starts, [Point::new(500.0, 300.0), Point::new(610.0, 300.0)]);
}
/// Leaving Columns or Spacing on text that is not a number cancels the typing, and the field goes back to the value
/// it had before it.
#[test]
fn a_canceled_columns_or_spacing_edit_restores_the_value_before_it() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
for (name, key) in [("Columns:", "columns"), ("Spacing:", "spacing")] {
let mut panel = Panel::new(app(4), crate::tests::picks::dialogs);
panel.room(egui::vec2(900.0, 900.0));
open_from_menu(&mut panel.app());
set(&panel.app(), &[("layout", json!("gridByRow"))]).unwrap();
panel.frame();
let before = fields(&panel.app());
panel.click_role(name, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("3");
assert_ne!(fields(&panel.app())[key], before[key], "typing into {name} proposes a value");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(panel.app().any_dialog_open(), "leaving {name} keeps the dialog open");
assert_eq!(fields(&panel.app()), before, "leaving {name} on text that is not a number restores its value");
}
}
}
+61
View File
@@ -477,6 +477,36 @@ fn split_into_grid_opens_at_the_selections_size_and_previews() {
assert_eq!(objects(&app), 6);
}
/// Leaving a Split Into Grid field on text that is not a number cancels the typing, and the grid goes back to what it
/// was before it.
#[test]
fn a_canceled_split_into_grid_number_restores_the_grid() {
use craft::ui::contract::Role as Control;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 112, "height": 62})).unwrap();
app.run("select.all", json!({})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
assert!(super::object_dialogs::open_from_menu(&mut panel.app(), "object.path.splitIntoGrid"));
panel.frame();
for name in ["Rows:", "Height:", "Rows: Gutter:", "Columns: Total:"] {
let before = fields(&panel.app());
panel.click_role(name, Control::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("4");
assert_ne!(fields(&panel.app()), before, "typing into {name} proposes a value");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "leaving {name} keeps the dialog open");
assert_eq!(fields(&panel.app()), before, "leaving {name} on text that is not a number restores the grid");
}
}
#[test]
fn the_transform_effect_dialog_has_its_controls_previews_them_and_shows_them_again() {
let mut app = app();
@@ -751,6 +781,37 @@ fn transform_each_absolute_measures_the_compound_a_member_stands_for() {
assert_eq!((num(&app, "absH"), num(&app, "absV")), (100.0, 100.0), "the compound's size, not the member's");
}
/// Leaving a Transform Each number field on text that is not a number cancels the typing, and the field goes back to
/// the value it had before it.
#[test]
fn a_canceled_transform_each_number_restores_the_value_before_it() {
use craft::ui::contract::Role as Control;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap();
app.run("select.all", json!({})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
open_each(&mut panel.app(), false);
panel.frame();
let state = |panel: &Panel| fields(&panel.app());
for name in ["Scale Horizontal:", "Move Vertical:", "Angle:"] {
let before = state(&panel);
panel.click_role(name, Control::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("30");
assert_ne!(state(&panel), before, "typing into {name} proposes a value");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "leaving {name} keeps the dialog open");
assert_eq!(state(&panel), before, "leaving {name} on text that is not a number restores it");
}
}
/// The corners in the open dialog, and those of the first object's first effect.
fn free_distort_corners(app: &VectorcraftApp) -> (Value, Value) {
let s = app.session.active().unwrap();
@@ -265,6 +265,40 @@ fn a_highlighted_raster_option_applies_only_once_it_is_chosen() {
}
}
/// Leaving PNG Options' Other resolution on text that is not a number cancels the typing, and the field goes back to
/// the resolution it had before it.
#[test]
fn a_canceled_other_resolution_restores_the_resolution_before_it() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use vectorcraft_engine::cmd::fileio::FORMATS;
use crate::tests::panel_harness::Panel;
let mut app = VectorcraftApp::new(Session::new(), Services::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
let format = FORMATS.iter().find(|f| f.id == "png").unwrap();
super::png_options::open(&mut panel.app(), format, json!({"format": "png", "path": "/out/a.png"}));
panel.frame();
set(&mut panel.app(), "__otherPpi", json!(true));
set(&mut panel.app(), "ppi", json!(100.0));
panel.frame();
let fields = |panel: &Panel| on_top(&panel.app(), |h, _, at| h.open_dialogs().into_iter().find(|d| d.id == at).and_then(|d| d.fields)).flatten();
let before = fields(&panel);
assert_eq!(before.as_ref().and_then(|f| f["ppi"].as_f64()), Some(100.0));
panel.click_role("Resolution:", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("250");
assert_ne!(fields(&panel), before, "typing proposes a resolution");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(fields(&panel).is_some(), "leaving the field keeps the dialog open");
assert_eq!(fields(&panel), before, "leaving the field on text that is not a number restores the resolution");
}
/// The role and name of each node of the window's accessibility tree, in a frame drawn once the dialogs have settled.
fn access_names(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::Role, String)> {
super::tests::settle(app);
@@ -259,6 +259,39 @@ fn a_highlighted_define_grid_choice_applies_only_once_it_is_chosen() {
}
}
/// Leaving a Define Grid number field on text that is not a number cancels the typing, and the field goes back to the
/// value it had before it.
#[test]
fn a_canceled_define_grid_number_edit_restores_the_value_before_it() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.run("perspective.grid.preset", json!({"kind": 3})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
panel.app().run("ui.perspectiveGridDialog", json!({})).unwrap();
panel.frame();
set(&mut panel.app(), "scale", json!([1, 3])).unwrap();
panel.frame();
let fields = |panel: &Panel| host(&panel.app(), |h| h.open_dialogs().pop().and_then(|d| d.fields));
for name in ["Artboard:", "Real World:", "Gridline every:", "Viewing Angle:", "Viewing Distance:", "Horizon Height:", "X:", "Y:"] {
let before = fields(&panel);
panel.click_role(name, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("7");
assert_ne!(fields(&panel), before, "typing into {name} proposes a value");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert_eq!(kind(&panel.app()).as_deref(), Some(super::perspective_grid::KIND), "leaving {name} keeps the dialog open");
assert_eq!(fields(&panel), before, "leaving {name} on text that is not a number restores its value");
}
}
#[test]
fn enter_is_ok_in_define_grid_and_save_grid_as_preset() {
let mut app = app();
+41
View File
@@ -620,3 +620,44 @@ fn every_number_and_length_field_is_named() {
}
}
}
/// Leaving an ink's Frequency or Angle on text that is not a number cancels the typing, and the ink goes back to the
/// value it had before it.
#[test]
fn a_canceled_ink_frequency_or_angle_restores_the_ink() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let (app, _) = app();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1600.0, 1200.0));
panel.app().run("swatch.new", json!({"name": "Gold", "color": {"model": "cmyk", "c": 0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
panel.app().run("file.print", json!({})).unwrap();
panel.frame();
set(&mut panel.app(), "section", json!("Output"));
set(&mut panel.app(), "output.mode", json!("separations"));
panel.frame();
let inks = |panel: &Panel| fields(&panel.app())["output"]["inks"].clone();
for (name, typed) in [("Frequency Gold", "60"), ("Angle Gold", "45")] {
panel.click_role(name, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(typed);
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
}
let before = inks(&panel);
assert_eq!((before[0]["frequency"].as_f64(), before[0]["angle"].as_f64()), (Some(60.0), Some(45.0)));
for name in ["Frequency Gold", "Angle Gold"] {
panel.click_role(name, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("30");
assert_ne!(inks(&panel), before, "typing into {name} proposes a value");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "leaving {name} keeps the dialog open");
assert_eq!(inks(&panel), before, "leaving {name} on text that is not a number restores the ink");
}
}
+10 -4
View File
@@ -312,7 +312,7 @@ enum Measure {
/// One captioned side: a slider over `rail` and a number field in ±`limit`, `value` being none
/// while the objects differ (the field reads Mixed). `caption` is the row (Scale or Move) and the
/// visible label; the label repeats in each row, so it only describes the controls, and their
/// names start with the row. Returns the value the user set this pass.
/// names start with the row. Returns the value the user set this pass, or the value a canceled typing gives back.
fn side(
ui: &mut Ui,
key: &'static str,
@@ -337,7 +337,7 @@ fn side(
Measure::Percent => NumberField::new(name.clone(), Bind::given(shown)).unit_kind(UnitKind::Percent),
Measure::Length(lengths) => NumberField::length(name.clone(), Bind::given(shown), lengths),
};
let typed = field.range(-limit..=limit).id_salt("field").show(ui).edit.value().cloned().flatten();
let typed = field.range(-limit..=limit).id_salt("field").show(ui).edit.events.landed().cloned().flatten();
edit = typed.or(dragged);
});
});
@@ -361,8 +361,14 @@ fn rotate_row(ui: &mut Ui, angle: f64) -> Option<f64> {
Field::new(tl!("Angle:")).id_salt("rotate").show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let dialed = AngleDial::new(Bind::given(angle)).label(tl!("Angle:")).range(-360.0..=360.0).show(ui).value().copied();
let typed =
NumberField::new(tl!("Angle:"), Bind::given(Some(angle))).unit_kind(UnitKind::Degrees).show(ui).edit.value().cloned().flatten();
let typed = NumberField::new(tl!("Angle:"), Bind::given(Some(angle)))
.unit_kind(UnitKind::Degrees)
.show(ui)
.edit
.events
.landed()
.cloned()
.flatten();
edit = typed.or(dialed);
});
});
+145 -35
View File
@@ -37,7 +37,7 @@
//! another document is active; the dialog stays open and says why.
// PLAN: the app's manifest depends on `craft-ui`, not on the `craft` facade, so the `craft::` paths below need hub-w2's manifest change.
use craft::behavior::Mixed;
use craft::behavior::{CancelReason, Mixed};
use craft::theme::variant::Tone;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
@@ -51,6 +51,7 @@ use craft::ui::runtime::overlay::CloseReason;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::text::{NumberField, link_toggle};
use serde_json::{Value, json};
use std::sync::Arc;
use vectorcraft_doc::{Unit, WidthProfile};
use vectorcraft_engine::doc::NodeId;
use vectorcraft_engine::width_point_pair;
@@ -106,13 +107,21 @@ fn halves(app: &VectorcraftApp, id: u64, index: usize) -> Option<(usize, usize)>
/// One of several width points being edited: its profile index, its place, its side widths
/// (points) and the sets of side widths that edit it, `[incoming, outgoing]` (both for a continuous
/// point).
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Debug)]
struct Entry {
index: usize,
t: f64,
left: f64,
right: f64,
sets: [bool; 2],
writes: Writes,
}
// Equality compares the values OK and Delete answer on, excluding write identities.
impl PartialEq for Entry {
fn eq(&self, other: &Self) -> bool {
self.index == other.index && self.t == other.t && self.left == other.left && self.right == other.right && self.sets == other.sets
}
}
/// What set `set` of `es` shows: Side 1, Side 2 and Total Width, each none where the points differ.
@@ -147,10 +156,36 @@ fn edited_pair(left: f64, right: f64, edit: Edit, linked: bool) -> (f64, f64) {
(l.max(0.0), r.max(0.0))
}
/// The identities of the last writes to each side, separate from value equality.
#[derive(Clone, Debug, Default)]
struct Writes([Option<Arc<()>>; 2]);
/// Assigns a side and gives the write a fresh identity, including assignments of equal values.
fn write_side(current: &mut f64, identity: &mut Option<Arc<()>>, value: f64) {
*current = value;
*identity = Some(Arc::new(()));
}
/// Applies an edit, records the sides it writes, and returns which sides were written.
fn write_pair(left: &mut f64, right: &mut f64, writes: &mut Writes, edit: Edit, linked: bool) -> [bool; 2] {
let values = edited_pair(*left, *right, edit, linked);
let written = match edit {
Edit::Side1(_) => [true, linked],
Edit::Side2(_) => [linked, true],
Edit::Total(_) => [true; 2],
};
for (((current, identity), value), written) in [left, right].into_iter().zip(&mut writes.0).zip([values.0, values.1]).zip(written) {
if written {
write_side(current, identity, value);
}
}
written
}
/// Apply `edit` to every point that set `set` edits.
fn apply(es: &mut [Entry], set: usize, edit: Edit, linked: bool) {
for e in es.iter_mut().filter(|e| e.sets[set]) {
(e.left, e.right) = edited_pair(e.left, e.right, edit, linked);
write_pair(&mut e.left, &mut e.right, &mut e.writes, edit, linked);
}
}
@@ -247,35 +282,43 @@ fn target(app: &VectorcraftApp, id: u64, indices: &Value) -> Result<Resolved, St
let half = st.width / 2.0;
let entry = |i: usize| {
let (t, l, r) = points[i];
Entry { index: i, t, left: l * half, right: r * half, sets: sets(&pairs, i) }
Entry { index: i, t, left: l * half, right: r * half, sets: sets(&pairs, i), writes: Writes::default() }
};
Ok(Resolved::Several(picked.into_iter().map(entry).collect()))
}
/// The two side widths of one set (points) and whether the link keeps them equal.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Debug)]
struct Sides {
left: f64,
right: f64,
linked: bool,
writes: Writes,
}
// Equality compares the values OK and Delete answer on, excluding write identities.
impl PartialEq for Sides {
fn eq(&self, other: &Self) -> bool {
self.left == other.left && self.right == other.right && self.linked == other.linked
}
}
impl Sides {
/// The widths `left` and `right`, linked when they are equal.
fn of(left: f64, right: f64) -> Self {
Sides { left, right, linked: (left - right).abs() < 1e-9 }
Sides { left, right, linked: (left - right).abs() < 1e-9, writes: Writes::default() }
}
/// Applies `edit` as entering it in the field does.
fn edit(&mut self, edit: Edit) {
(self.left, self.right) = edited_pair(self.left, self.right, edit, self.linked);
write_pair(&mut self.left, &mut self.right, &mut self.writes, edit, self.linked);
}
/// Turns the link on or off; on, Side 2 takes Side 1's width.
fn link(&mut self, on: bool) {
self.linked = on;
if on {
self.right = self.left;
write_side(&mut self.right, &mut self.writes.0[1], self.left);
}
}
}
@@ -387,6 +430,66 @@ struct Filed {
form: Form,
}
/// An entry's opening widths and the identities of the gesture's last writes.
struct GestureEntry {
index: usize,
opening: [f64; 2],
last: Writes,
}
/// A field's opening widths and last writes, in increasing entry order.
#[derive(Default)]
struct Gesture {
entries: Vec<GestureEntry>,
}
impl Gesture {
/// Applies a proposal or restores sides whose last write still belongs to this gesture.
fn land<'a>(
&mut self,
field: FieldEdit,
edit: fn(f64) -> Edit,
linked: bool,
entries: impl Iterator<Item = (usize, &'a mut f64, &'a mut f64, &'a mut Writes)>,
) {
if field.value.is_none() && !field.ended {
return;
}
let starts = field.cancel.is_none() && field.value.is_some() && self.entries.is_empty();
let mut at = 0;
// Entry indices and set membership stay fixed during a gesture. Both walks are ordered.
for (index, left, right, writes) in entries {
if starts {
self.entries.push(GestureEntry { index, opening: [*left, *right], last: Writes::default() });
}
while self.entries.get(at).is_some_and(|saved| saved.index < index) {
at += 1;
}
let Some(saved) = self.entries.get_mut(at).filter(|saved| saved.index == index) else { continue };
at += 1;
if matches!(field.cancel, Some(CancelReason::Escape | CancelReason::Blur)) {
for (((current, identity), opening), last) in [left, right].into_iter().zip(&mut writes.0).zip(saved.opening).zip(&saved.last.0) {
if identity.as_ref().zip(last.as_ref()).is_some_and(|(current, last)| Arc::ptr_eq(current, last)) {
write_side(current, identity, opening);
}
}
} else if field.cancel.is_none()
&& let Some(value) = field.value
{
let written = write_pair(left, right, writes, edit(value), linked);
for ((last, current), written) in saved.last.0.iter_mut().zip(&writes.0).zip(written) {
if written {
*last = current.clone();
}
}
}
}
if field.ended {
self.entries.clear();
}
}
}
/// The Width Point Edit dialog on the window's dialog host.
pub(crate) struct WidthPointDialog {
id: DialogId,
@@ -397,60 +500,65 @@ pub(crate) struct WidthPointDialog {
held: HeldAnswer<Filed>,
/// The answer automation's `choice` names for the next confirm.
choice: Pressed,
/// Per-field gesture state outside the values OK and Delete compare.
gestures: [[Gesture; 3]; 2],
}
impl WidthPointDialog {
fn new(form: Form, lengths: LengthUnits) -> Self {
WidthPointDialog { id: dialog_id(KIND), form, lengths, held: HeldAnswer::new(), choice: Pressed::Ok }
WidthPointDialog { id: dialog_id(KIND), form, lengths, held: HeldAnswer::new(), choice: Pressed::Ok, gestures: Default::default() }
}
}
/// A width field's proposed value and gesture ending.
#[derive(Clone, Copy, Default)]
struct FieldEdit {
value: Option<f64>,
ended: bool,
cancel: Option<CancelReason>,
}
/// One set of side widths: Side 1 with its link, Side 2 and Total Width, showing `values` (none is
/// mixed). Returns the edit entered and the link's new state.
fn set_rows(ui: &mut egui::Ui, title: &Label, lengths: LengthUnits, values: [Option<f64>; 3], linked: bool) -> (Option<Edit>, Option<bool>) {
let (mut edit, mut link) = (None, None);
/// mixed). Returns each field's edit and gesture ending and the link's new state.
fn set_rows(ui: &mut egui::Ui, title: &Label, lengths: LengthUnits, values: [Option<f64>; 3], linked: bool) -> ([FieldEdit; 3], Option<bool>) {
let (mut edits, mut link) = ([FieldEdit::default(); 3], None);
let field = |ui: &mut egui::Ui, caption: &Label, value: Option<f64>| {
let bind = match value {
Some(v) => Bind::<Option<f64>>::given(Some(v)),
None => Bind::<Option<f64>>::given(Mixed::Mixed),
};
NumberField::length(caption.clone(), bind, lengths).range(0.0..=MAX_WIDTH).show(ui).value().copied().flatten()
let events = NumberField::length(caption.clone(), bind, lengths).range(0.0..=MAX_WIDTH).show(ui).edit.events;
FieldEdit { value: events.landed().copied().flatten(), ended: events.ended().is_some(), cancel: events.cancel_reason() }
};
FieldGroup::new(title.clone()).show(ui, |ui, _| {
let (side1, side2, total) = (word(tl!("Side 1")), word(tl!("Side 2")), word(tl!("Total Width")));
Field::new(side1.clone()).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
if let Some(v) = field(ui, &side1, values[0]) {
edit = Some(Edit::Side1(v));
}
edits[0] = field(ui, &side1, values[0]);
let toggle = link_toggle(word(tl!("Keep both sides the same width")), Bind::given(linked)).show(ui);
link = toggle.value().copied();
});
});
Field::new(side2.clone()).show(ui, |ui, _| {
if let Some(v) = field(ui, &side2, values[1]) {
edit = Some(Edit::Side2(v));
}
edits[1] = field(ui, &side2, values[1]);
});
Field::new(total.clone()).show(ui, |ui, _| {
if let Some(v) = field(ui, &total, values[2]) {
edit = Some(Edit::Total(v));
}
edits[2] = field(ui, &total, values[2]);
});
});
(edit, link)
(edits, link)
}
/// The rows of the dialog; whether the values can be accepted.
fn body(ui: &mut egui::Ui, form: &mut Form, lengths: LengthUnits, refusal: Option<&Label>) -> bool {
fn body(ui: &mut egui::Ui, form: &mut Form, gestures: &mut [[Gesture; 3]; 2], lengths: LengthUnits, refusal: Option<&Label>) -> bool {
let titles = if form.target.sets() > 1 { [word(tl!("Incoming")), word(tl!("Outgoing"))] } else { [word(tl!("Width Point Edit")), Label::Empty] };
match &mut form.target {
Target::One { sides, out, single, .. } => {
let rows = |ui: &mut egui::Ui, title: &Label, sides: &mut Sides| {
let mut rows = |ui: &mut egui::Ui, set: usize, sides: &mut Sides| {
let values = [Some(sides.left), Some(sides.right), Some(sides.left + sides.right)];
let (edit, link) = set_rows(ui, title, lengths, values, sides.linked);
if let Some(edit) = edit {
sides.edit(edit);
let (edits, link) = set_rows(ui, &titles[set], lengths, values, sides.linked);
for ((field, edit), gesture) in edits.into_iter().zip([Edit::Side1, Edit::Side2, Edit::Total]).zip(&mut gestures[set]) {
gesture.land(field, edit, sides.linked, std::iter::once((set, &mut sides.left, &mut sides.right, &mut sides.writes)));
}
if let Some(on) = link {
sides.link(on);
@@ -458,8 +566,8 @@ fn body(ui: &mut egui::Ui, form: &mut Form, lengths: LengthUnits, refusal: Optio
};
match out {
Some((_, out)) => {
crate::panels::section(titles[0].clone()).show(ui, |ui, _| rows(ui, &titles[0], sides));
crate::panels::section(titles[1].clone()).show(ui, |ui, _| rows(ui, &titles[1], out));
crate::panels::section(titles[0].clone()).show(ui, |ui, _| rows(ui, 0, sides));
crate::panels::section(titles[1].clone()).show(ui, |ui, _| rows(ui, 1, out));
crate::panels::section(word(tl!("Single Width Only"))).show(ui, |ui, _| {
RadioGroup::new(word(tl!("Single Width Only")), Bind::bound(single)).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
@@ -472,14 +580,15 @@ fn body(ui: &mut egui::Ui, form: &mut Form, lengths: LengthUnits, refusal: Optio
});
});
}
None => rows(ui, &titles[0], sides),
None => rows(ui, 0, sides),
}
}
Target::Several { points, discontinuous, linked, .. } => {
let mut rows = |ui: &mut egui::Ui, set: usize| {
let (edit, link) = set_rows(ui, &titles[set], lengths, shown(points, set), linked[set]);
if let Some(edit) = edit {
apply(points, set, edit, linked[set]);
let (edits, link) = set_rows(ui, &titles[set], lengths, shown(points, set), linked[set]);
for ((field, edit), gesture) in edits.into_iter().zip([Edit::Side1, Edit::Side2, Edit::Total]).zip(&mut gestures[set]) {
let entries = points.iter_mut().filter(|e| e.sets[set]).map(|e| (e.index, &mut e.left, &mut e.right, &mut e.writes));
gesture.land(field, edit, linked[set], entries);
}
if let Some(on) = link {
linked[set] = on;
@@ -523,6 +632,7 @@ impl StackDialog for WidthPointDialog {
let footer = ResetFooter::new(ui, None, false);
let refusal = self.held.refusal().filter(|(_, filed)| filed.form == self.form).map(|(reason, _)| reason.clone());
let lengths = self.lengths;
let gestures = &mut self.gestures;
let shown = FormDialog::new(word(tl!("Width Point Edit")), Bind::bound(&mut self.form))
.alt_resets(false)
.accept_stays_open(true)
@@ -533,7 +643,7 @@ impl StackDialog for WidthPointDialog {
if finish && !craft::ui::runtime::measure::active(ui.ctx()) {
cx.request_close_as(CloseReason::Activated);
}
body(ui, form, lengths, refusal.as_ref())
body(ui, form, gestures, lengths, refusal.as_ref())
});
// `picked` is this pass's press: a second pass of the frame has none, so a press is filed once.
let pressed = match footer.pick(shown.picked) {
@@ -1,8 +1,12 @@
use super::*;
use craft::ui::contract::Role;
use craft::ui::dialog::DialogHost;
use egui::{Key, Modifiers};
use vectorcraft_engine::Session;
use vectorcraft_tools::{PointerEvent, PointerKind};
use crate::tests::panel_harness::Panel;
/// A 10 pt line from (100, 150) to (300, 150) with a 4 + 4 pt width point in the middle.
fn app() -> (VectorcraftApp, u64) {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
@@ -128,6 +132,609 @@ fn double_click_opens_it_and_ok_sets_the_widths() {
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CancelFixture {
One,
Asymmetric,
Several,
Pair,
Pairs,
Mixed,
MixedPair,
Shared,
}
impl CancelFixture {
fn name(self) -> &'static str {
match self {
Self::One => "one",
Self::Asymmetric => "asymmetric",
Self::Several => "several",
Self::Pair => "pair",
Self::Pairs => "pairs",
Self::Mixed => "mixed",
Self::MixedPair => "mixed_pair",
Self::Shared => "shared",
}
}
fn several(self) -> bool {
matches!(self, Self::Several | Self::Pairs | Self::Mixed | Self::MixedPair | Self::Shared)
}
fn mixed(self) -> bool {
matches!(self, Self::Mixed | Self::MixedPair)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CancelAction {
None,
Same,
Other,
OwnedOther,
Outgoing,
Adjust,
AdjustSame,
Link,
Unlink,
Click,
Commit,
CommitTotal,
EqualAssignment,
EqualOutgoingAssignment,
EqualOutgoingGesture,
}
struct CancelCase {
name: String,
fixture: CancelFixture,
set: usize,
field: usize,
linked: bool,
action: CancelAction,
escape: bool,
}
fn cancel_cases() -> Vec<CancelCase> {
let mut cases = vec![
CancelCase {
name: "asymmetric_zero_total".to_owned(),
fixture: CancelFixture::Asymmetric,
set: 0,
field: 2,
linked: false,
action: CancelAction::None,
escape: false,
},
CancelCase {
name: "common_linked_side".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: true,
action: CancelAction::None,
escape: false,
},
CancelCase {
name: "outside_same_side1".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 0,
linked: true,
action: CancelAction::Same,
escape: false,
},
CancelCase {
name: "outside_same_side2".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 1,
linked: true,
action: CancelAction::Same,
escape: false,
},
CancelCase {
name: "outside_same_common_side".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: true,
action: CancelAction::Same,
escape: false,
},
CancelCase {
name: "outside_other_side_one".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 0,
linked: false,
action: CancelAction::Other,
escape: false,
},
CancelCase {
name: "outside_other_side_several".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: false,
action: CancelAction::Other,
escape: false,
},
CancelCase {
name: "outside_written_side_one".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 0,
linked: true,
action: CancelAction::OwnedOther,
escape: false,
},
CancelCase {
name: "outside_written_side_several".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: true,
action: CancelAction::OwnedOther,
escape: false,
},
CancelCase {
name: "outside_outgoing_one".to_owned(),
fixture: CancelFixture::Pair,
set: 0,
field: 0,
linked: true,
action: CancelAction::Outgoing,
escape: false,
},
CancelCase {
name: "outside_outgoing_several".to_owned(),
fixture: CancelFixture::Pairs,
set: 0,
field: 0,
linked: false,
action: CancelAction::Outgoing,
escape: false,
},
CancelCase {
name: "outside_adjust_one".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 0,
linked: true,
action: CancelAction::Adjust,
escape: false,
},
CancelCase {
name: "outside_adjust_several".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: false,
action: CancelAction::Adjust,
escape: false,
},
CancelCase {
name: "outside_adjust_same_one".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 0,
linked: true,
action: CancelAction::AdjustSame,
escape: false,
},
CancelCase {
name: "outside_adjust_same_several".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: false,
action: CancelAction::AdjustSame,
escape: false,
},
CancelCase {
name: "outside_link_one".to_owned(),
fixture: CancelFixture::Asymmetric,
set: 0,
field: 0,
linked: false,
action: CancelAction::Link,
escape: false,
},
CancelCase {
name: "outside_link_several".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: false,
action: CancelAction::Link,
escape: false,
},
CancelCase {
name: "outside_out_link_one".to_owned(),
fixture: CancelFixture::Pair,
set: 1,
field: 0,
linked: false,
action: CancelAction::Link,
escape: false,
},
CancelCase {
name: "outside_out_link_several".to_owned(),
fixture: CancelFixture::Pairs,
set: 1,
field: 0,
linked: false,
action: CancelAction::Link,
escape: false,
},
CancelCase {
name: "unlink_during_linked_edit".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 0,
linked: true,
action: CancelAction::Unlink,
escape: false,
},
CancelCase {
name: "click_link_one".to_owned(),
fixture: CancelFixture::Asymmetric,
set: 0,
field: 0,
linked: false,
action: CancelAction::Click,
escape: false,
},
CancelCase {
name: "click_link_several".to_owned(),
fixture: CancelFixture::Several,
set: 0,
field: 0,
linked: false,
action: CancelAction::Click,
escape: false,
},
CancelCase {
name: "after_side_commit".to_owned(),
fixture: CancelFixture::One,
set: 0,
field: 1,
linked: false,
action: CancelAction::Commit,
escape: false,
},
CancelCase {
name: "after_total_commit".to_owned(),
fixture: CancelFixture::Asymmetric,
set: 0,
field: 0,
linked: false,
action: CancelAction::CommitTotal,
escape: false,
},
];
for fixture in [CancelFixture::One, CancelFixture::Pair, CancelFixture::Pairs] {
for set in 0..if fixture == CancelFixture::One { 1 } else { 2 } {
for field in 0..3 {
for escape in [false, true] {
let fixture_name = fixture.name();
let name = format!("{fixture_name}_set{set}_field{field}_{}", if escape { "escape" } else { "blur" });
cases.push(CancelCase { name, fixture, set, field, linked: false, action: CancelAction::None, escape });
}
}
}
}
for field in 0..3 {
cases.push(CancelCase {
name: format!("linked_one_field{field}"),
fixture: CancelFixture::One,
set: 0,
field,
linked: true,
action: CancelAction::None,
escape: false,
});
for (fixture, set) in [(CancelFixture::Mixed, 0), (CancelFixture::MixedPair, 0), (CancelFixture::MixedPair, 1)] {
let fixture_name = fixture.name();
cases.push(CancelCase {
name: format!("{fixture_name}_set{set}_field{field}"),
fixture,
set,
field,
linked: false,
action: CancelAction::None,
escape: true,
});
}
}
for (name, fixture, action, linked) in [
("outside_equal_side_one", CancelFixture::One, CancelAction::EqualAssignment, false),
("outside_equal_side_several", CancelFixture::Shared, CancelAction::EqualOutgoingAssignment, false),
("other_set_equal_gesture_shared_point", CancelFixture::Shared, CancelAction::EqualOutgoingGesture, false),
("outside_equal_link_write", CancelFixture::One, CancelAction::Link, true),
] {
cases.push(CancelCase { name: name.to_owned(), fixture, set: 0, field: 0, linked, action, escape: false });
}
cases
}
struct CancelSetup {
panel: Panel,
id: u64,
selected: Vec<(usize, [bool; 2])>,
expected_points: Vec<(f64, f64, f64)>,
}
fn cancel_fixture(case: &CancelCase) -> CancelSetup {
let (mut app, id) = match case.fixture {
CancelFixture::One | CancelFixture::Asymmetric | CancelFixture::Pairs => app(),
CancelFixture::Pair => pair_app(),
_ => three_app(),
};
if case.fixture == CancelFixture::Asymmetric {
app.run("stroke.widthPoint.set", json!({"id": id, "t": 0.5, "left": 6, "right": 2})).unwrap();
}
if matches!(case.fixture, CancelFixture::Pairs | CancelFixture::MixedPair | CancelFixture::Shared) {
let profile = if case.fixture == CancelFixture::Pairs {
json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.25, 0.4, 1.2], [0.75, 0.8, 0.4], [0.75, 0.4, 1.2], [1, 1, 1]])
} else if case.fixture == CancelFixture::Shared {
json!([[0, 1, 1], [0.25, 0.8, 0.8], [0.5, 0.8, 0.8], [0.75, 0.8, 0.4], [0.75, 0.8, 1.2], [1, 1, 1]])
} else {
json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.5, 0.8, 0.8], [0.75, 0.4, 1.2], [0.75, 0.6, 0.8], [1, 1, 1]])
};
app.run("stroke.widthProfile.set", json!({"ids": [id], "points": profile})).unwrap();
}
let selected = match case.fixture {
CancelFixture::Pairs => vec![(1, [true, false]), (2, [false, true]), (3, [true, false]), (4, [false, true])],
CancelFixture::MixedPair | CancelFixture::Shared => vec![(1, [true, true]), (3, [true, false]), (4, [false, true])],
CancelFixture::Mixed => vec![(1, [true, true]), (3, [true, true])],
CancelFixture::Several => vec![(1, [true, true]), (2, [true, true])],
CancelFixture::Pair => vec![(1, [true, false]), (2, [false, true])],
_ => vec![(1, [true, true])],
};
let expected_points = points(&app, id);
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(900.0, 900.0));
let target = match case.fixture {
CancelFixture::Pairs | CancelFixture::MixedPair | CancelFixture::Mixed | CancelFixture::Shared => json!({"id": id, "indices": [1, 3]}),
CancelFixture::Several => json!({"id": id, "indices": [1, 2]}),
_ => json!({"id": id, "index": 1}),
};
open(&mut panel.app(), &target).unwrap();
panel.frame();
set(&panel.app(), SET_KEYS[case.set][3], json!(case.linked));
panel.frame();
CancelSetup { panel, id, selected, expected_points }
}
fn commit_before_cancel(panel: &mut Panel, case: &CancelCase, expected_points: &mut [(f64, f64, f64)]) {
let name = &case.name;
if matches!(case.action, CancelAction::Commit | CancelAction::CommitTotal) {
let previous = if case.action == CancelAction::Commit { "Side 1" } else { "Total Width" };
panel.click_role(previous, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("12");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
let committed = fields(&panel.app());
let sides = if case.action == CancelAction::Commit { [12.0, 4.0] } else { [9.0, 3.0] };
assert_eq!((committed["side1"].clone(), committed["side2"].clone()), (json!(sides[0]), json!(sides[1])), "{name}: commit lands");
expected_points[1].1 = sides[0] / 5.0;
expected_points[1].2 = sides[1] / 5.0;
}
}
fn propose_canceled_width(panel: &mut Panel, case: &CancelCase, before: &Value) {
let name = &case.name;
let caption = ["Side 1", "Side 2", "Total Width"][case.field];
if before.get("outSide1").is_some() {
panel.click_role_nth(caption, Role::SPIN_BUTTON, case.set);
} else {
panel.click_role(caption, Role::SPIN_BUTTON);
}
panel.key(Key::A, Modifiers::COMMAND);
let proposal = if name == "asymmetric_zero_total" || name == "common_linked_side" {
"0"
} else if case.action == CancelAction::CommitTotal {
"7"
} else {
"9"
};
panel.type_text(proposal);
if case.fixture.mixed() {
propose_mixed_canceled_width(panel, name, before);
} else if case.escape {
assert_ne!(fields(&panel.app()), *before, "{name}: the gesture proposes widths");
cancel_typed_width_by_blur(panel, name, before, "blur cancellation restores widths");
press_and_wheel_width(panel);
}
assert_ne!(fields(&panel.app()), *before, "{name}: the gesture proposes widths");
}
fn propose_mixed_canceled_width(panel: &mut Panel, name: &str, before: &Value) {
assert_eq!(fields(&panel.app()), *before, "{name}: mixed typing waits for commit");
cancel_typed_width_by_blur(panel, name, before, "invalid typing preserves mixed widths");
press_and_wheel_width(panel);
}
fn cancel_typed_width_by_blur(panel: &mut Panel, name: &str, before: &Value, message: &str) {
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert_eq!(fields(&panel.app()), *before, "{name}: {message}");
}
fn press_and_wheel_width(panel: &mut Panel) {
let at = panel.ctx().input(|i| i.pointer.latest_pos()).expect("the field was clicked");
panel.frame_with(vec![craft::ui::testing::pointer::press(at)]);
panel.frame_with(vec![craft::ui::testing::pointer::wheel_lines(1.0)]);
}
fn outside_cancel_action(
panel: &mut Panel,
case: &CancelCase,
selected: &[(usize, [bool; 2])],
expected: &mut Value,
expected_points: &mut [(f64, f64, f64)],
) {
let keys = SET_KEYS[case.set];
match case.action {
CancelAction::EqualAssignment | CancelAction::EqualOutgoingAssignment | CancelAction::EqualOutgoingGesture => {
equal_cancel_action(panel, case, selected, expected, expected_points);
}
CancelAction::Same | CancelAction::Other | CancelAction::OwnedOther | CancelAction::Outgoing => {
if case.action == CancelAction::OwnedOther {
set(&panel.app(), keys[3], json!(false));
expected[keys[3]] = json!(false);
}
let (assigned_set, assigned_side) = match case.action {
CancelAction::Same => (case.set, case.field),
CancelAction::Other | CancelAction::OwnedOther => (case.set, 1),
_ => (1, 0),
};
set(&panel.app(), SET_KEYS[assigned_set][assigned_side], json!(13));
for &(index, sets) in selected {
if sets[assigned_set] {
if assigned_side == 0 || (case.action == CancelAction::Same && case.linked) {
expected_points[index].1 = 2.6;
}
if assigned_side == 1 || (case.action == CancelAction::Same && case.linked) {
expected_points[index].2 = 2.6;
}
}
}
}
CancelAction::Adjust | CancelAction::AdjustSame => {
let on = case.action == CancelAction::Adjust;
set(&panel.app(), "adjustAdjoining", json!(on));
expected["adjustAdjoining"] = json!(on);
}
CancelAction::Link | CancelAction::Unlink => {
let on = case.action == CancelAction::Link;
set(&panel.app(), keys[3], json!(on));
expected[keys[3]] = json!(on);
if on && !case.fixture.several() {
expected_points[if case.set == 0 { 1 } else { 2 }].2 = 1.8;
}
}
_ => {}
}
}
fn equal_cancel_action(
panel: &mut Panel,
case: &CancelCase,
selected: &[(usize, [bool; 2])],
expected: &mut Value,
expected_points: &mut [(f64, f64, f64)],
) {
let set_index = usize::from(case.action != CancelAction::EqualAssignment);
set(&panel.app(), SET_KEYS[set_index][3], json!(false));
expected[SET_KEYS[set_index][3]] = json!(false);
if case.action == CancelAction::EqualOutgoingGesture {
host(&panel.app(), |host| {
let dialog = host.get_mut::<WidthPointDialog>().unwrap();
let Target::Several { points, linked, .. } = &mut dialog.form.target else { panic!("several points are selected") };
let entries = points.iter_mut().filter(|e| e.sets[set_index]).map(|e| (e.index, &mut e.left, &mut e.right, &mut e.writes));
let commit = FieldEdit { value: Some(9.0), ended: true, cancel: None };
dialog.gestures[set_index][0].land(commit, Edit::Side1, linked[set_index], entries);
});
} else {
set(&panel.app(), SET_KEYS[set_index][0], json!(9));
}
for &(index, sets) in selected {
if sets[set_index] {
expected_points[index].1 = 1.8;
}
}
}
fn end_canceled_width(panel: &mut Panel, case: &CancelCase, expected: &mut Value, expected_points: &mut [(f64, f64, f64)]) {
let name = &case.name;
let keys = SET_KEYS[case.set];
if case.action == CancelAction::Same {
let assigned = fields(&panel.app());
panel.frame();
assert_eq!(fields(&panel.app()), assigned, "{name}: HostChanged preserves the assigned fields");
} else if case.action == CancelAction::Click {
panel.type_text("x");
panel.click_role_nth("Keep both sides the same width", Role::BUTTON, case.set);
expected[keys[3]] = json!(true);
if !case.fixture.several() {
expected_points[1].2 = expected_points[1].1;
}
} else {
if !case.fixture.mixed() && !case.escape {
panel.type_text("x");
}
panel.key(if case.escape { Key::Escape } else { Key::Tab }, Modifiers::NONE);
if case.escape {
panel.release();
}
}
panel.frame();
}
fn expected_cancel_fields(
fixture: CancelFixture,
before: &Value,
selected: &[(usize, [bool; 2])],
expected_points: &[(f64, f64, f64)],
expected: &mut Value,
) {
for (set, keys) in SET_KEYS.iter().enumerate().take(if before.get("outSide1").is_some() { 2 } else { 1 }) {
let widths: Vec<_> = selected
.iter()
.filter(|(_, sets)| sets[set])
.map(|&(index, _)| [expected_points[index].1 * 5.0, expected_points[index].2 * 5.0])
.collect();
for field in 0..if fixture.several() { 3 } else { 2 } {
let values: Vec<_> = widths.iter().map(|sides| if field == 2 { sides[0] + sides[1] } else { sides[field] }).collect();
expected[keys[field]] = if values.iter().all(|v| (v - values[0]).abs() < SAME_WIDTH) { json!(values[0]) } else { Value::Null };
}
}
}
/// Canceled gestures restore their own widths and preserve independent assignments.
#[test]
fn canceled_width_gestures_restore_only_their_writes() {
for case in cancel_cases() {
let name = &case.name;
let CancelSetup { mut panel, id, selected, mut expected_points } = cancel_fixture(&case);
commit_before_cancel(&mut panel, &case, &mut expected_points);
let before = fields(&panel.app());
let mut expected = before.clone();
propose_canceled_width(&mut panel, &case, &before);
outside_cancel_action(&mut panel, &case, &selected, &mut expected, &mut expected_points);
end_canceled_width(&mut panel, &case, &mut expected, &mut expected_points);
assert!(is_open(&panel.app()), "{name}: cancellation keeps the dialog open");
expected_cancel_fields(case.fixture, &before, &selected, &expected_points, &mut expected);
assert_eq!(fields(&panel.app()), expected, "{name}: cancellation restores only the gesture's writes");
ok(&mut panel.app()).unwrap();
assert!(!is_open(&panel.app()), "{name}: OK closes the dialog");
assert_eq!(points(&panel.app(), id), expected_points, "{name}: OK applies the restored widths and outside assignments");
}
}
/// Canceling a large selection restores every entry without a timing requirement.
#[test]
fn canceled_width_gesture_restores_two_thousand_selected_points() {
let mut points: Vec<Entry> = (0..2_000)
.map(|index| Entry { index, t: index as f64 / 2_000.0, left: index as f64 + 1.0, right: 4.0, sets: [true; 2], writes: Writes::default() })
.collect();
let opening = points.clone();
let mut gesture = Gesture::default();
let proposal = FieldEdit { value: Some(9.0), ended: false, cancel: None };
gesture.land(proposal, Edit::Side1, false, points.iter_mut().map(|e| (e.index, &mut e.left, &mut e.right, &mut e.writes)));
assert!(points.iter().all(|e| e.left == 9.0));
let cancel = FieldEdit { value: None, ended: true, cancel: Some(CancelReason::Blur) };
gesture.land(cancel, Edit::Side1, false, points.iter_mut().map(|e| (e.index, &mut e.left, &mut e.right, &mut e.writes)));
assert_eq!(points, opening);
assert!(gesture.entries.is_empty());
}
#[test]
fn delete_removes_the_point() {
let (mut app, id) = app();