From 3bcfecec83f5d3979e188747691f2c2d05e70a1f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:40:13 +0700 Subject: [PATCH] object-dialogs-w21: net change of 1 commits - object-dialogs-w21: written by an agent --- crates/ui-egui/src/dialogs/edit_selection.rs | 181 +++---- crates/ui-egui/src/dialogs/expand.rs | 507 +++++++++++-------- crates/ui-egui/src/dialogs/saved_names.rs | 359 +++++++++++++ 3 files changed, 709 insertions(+), 338 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/saved_names.rs diff --git a/crates/ui-egui/src/dialogs/edit_selection.rs b/crates/ui-egui/src/dialogs/edit_selection.rs index 23c283a87a..942ae6df61 100644 --- a/crates/ui-egui/src/dialogs/edit_selection.rs +++ b/crates/ui-egui/src/dialogs/edit_selection.rs @@ -1,131 +1,41 @@ -//! Select → Edit Selection…: the document's saved selections in a list, with the chosen one's name -//! to edit and Delete. Nothing changes until OK, which applies every rename and delete as one -//! undo step (`select.editSaved` `edits`); Cancel leaves them as they were. -//! -//! Fields: `count` and, for each saved selection `i`, `orig` (its name when the dialog opened), -//! `name` (as edited) and `deleted`; `selected` (the row picked). +//! Select → Edit Selection…: the document's saved selections in a list, renamed in place or deleted. +//! Nothing changes until OK, which applies every rename and delete as one undo step +//! (`select.editSaved` `edits`); Cancel leaves them as they were. The dialog is the saved-names dialog, +//! which Edit Views shares ([`super::saved_names`]). use serde_json::{Value, json}; use vectorcraft_engine::doc::SavedSelection; -use super::{DialogSpec, form}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use super::saved_names::{self, SavedNames}; +use crate::VectorcraftApp; /// The dialog kind of Edit Selection. pub const KIND: &str = "editSelection"; -pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Edit Selection").into(), body, confirm, min_width: 420.0, ..DialogSpec::FORM }; - /// Open Edit Selection on the active document's saved selections. pub fn open(app: &mut VectorcraftApp) -> Result { let names = app.run("select.savedList", json!({}))?; - let names: Vec<&str> = names.as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let names: Vec = names.as_array().map(|a| a.iter().filter_map(|n| n.as_str().map(str::to_owned)).collect()).unwrap_or_default(); if names.is_empty() { return Err("No saved selections (Select → Save Selection…)".into()); } - let mut fields = json!({ "count": names.len(), "selected": 0 }); - for (i, n) in names.iter().enumerate() { - fields[format!("orig{i}")] = json!(n); - fields[format!("name{i}")] = json!(n); - fields[format!("deleted{i}")] = json!(false); - } - app.ui.dialog = Some(Dialog::new(KIND, fields)); + let dialog = SavedNames { kind: KIND, title: tl!("Edit Selection"), list: tl!("Saved Selections"), command: "select.editSaved", max: SavedSelection::MAX }; + saved_names::open(app, dialog, names)?; Ok(Value::Null) } -fn count(d: &Dialog) -> usize { - d.fields.get("count").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).unwrap_or(0).min(SavedSelection::MAX) -} - -/// The rows still in the list (not deleted). -fn rows(d: &Dialog) -> Vec { - (0..count(d)).filter(|i| !d.bool(&format!("deleted{i}"))).collect() -} - -fn selected(d: &Dialog, rows: &[usize]) -> Option { - let want = d.fields.get("selected").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()); - want.filter(|w| rows.contains(w)).or_else(|| rows.first().copied()) -} - -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let rows = rows(d); - let current = selected(d, &rows); - let mut pick = None; - let mut delete = false; - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - ui.set_width(200.0); - widgets::dim_label(ui, tl!("Saved Selections")); - widgets::list_box(ui, |ui| { - egui::ScrollArea::vertical().id_salt("saved-selections").min_scrolled_height(180.0).max_height(180.0).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.set_min_height(180.0); - for &i in &rows { - if ui.selectable_label(Some(i) == current, d.str(&format!("name{i}"))).clicked() { - pick = Some(i); - } - } - }); - }); - }); - ui.add_space(16.0); - ui.vertical(|ui| { - ui.set_width(190.0); - if let Some(i) = current { - widgets::dim_label(ui, tl!("Name:")); - form::text(ui, d, &format!("name{i}"), 190.0); - ui.add_space(10.0); - delete = widgets::flat_button(ui, tl!("Delete"), 70.0).clicked(); - } - }); - }); - if let Some(i) = pick { - d.fields.insert("selected".into(), json!(i)); - } - if let (true, Some(i)) = (delete, current) { - d.fields.insert(format!("deleted{i}"), json!(true)); - // The row below takes its place (the one above, for the last). - let next = rows.iter().copied().find(|r| *r > i).or_else(|| rows.iter().copied().rfind(|r| *r < i)); - d.fields.insert("selected".into(), json!(next.unwrap_or(0))); - } - false -} - -/// The edits OK applies: each deleted selection, and each one whose name was changed. -fn edits(d: &Dialog) -> Vec { - (0..count(d)) - .filter_map(|i| { - let (orig, name) = (d.str(&format!("orig{i}")), d.str(&format!("name{i}"))); - if d.bool(&format!("deleted{i}")) { - Some(json!({ "name": orig, "delete": true })) - } else if !name.trim().is_empty() && name.trim() != orig { - Some(json!({ "name": orig, "newName": name.trim() })) - } else { - None - } - }) - .collect() -} - -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let edits = edits(d); - // A name two selections would share keeps the dialog open, to be changed. - let r = if edits.is_empty() { Ok(Value::Null) } else { app.run("select.editSaved", json!({ "edits": edits })) }; - if r.is_ok() { - app.ui.dialog = None; - } - r -} - #[cfg(test)] mod tests { + use craft::ui::dialog::{DialogHost, HeldOk, StackDialog as _}; use serde_json::json; + use super::super::saved_names::{SavedNamesDialog, id_of}; + use super::KIND; use crate::VectorcraftApp; fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui_ctx = Some(crate::testing::ui_context()); app.run("file.new", json!({})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); for n in ["Logo", "Icons", "Text"] { @@ -134,24 +44,57 @@ mod tests { app } - fn set(app: &mut VectorcraftApp, k: &str, v: serde_json::Value) { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + fn ctx(app: &VectorcraftApp) -> egui::Context { + app.ui_ctx.clone().expect("the test context") + } + + fn host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost) -> R) -> R { + app.dialogs().expect("a window").with(f) + } + + fn is_open(app: &VectorcraftApp) -> bool { + host(app, |h| h.get_by_id::(id_of(KIND)).is_some()) + } + + fn set(app: &VectorcraftApp, k: &str, v: serde_json::Value) { + let ctx = ctx(app); + host(app, |h| h.set_json_field(&ctx, id_of(KIND), k, v)).unwrap(); } fn names(app: &mut VectorcraftApp) -> serde_json::Value { app.run("select.savedList", json!({})).unwrap() } + /// OK as a click: the edits wait for the pump, which sends them to the command and answers. + fn press_ok(app: &mut VectorcraftApp) -> Option { + let ctx = ctx(app); + host(app, |h| h.confirm_by_id(&ctx, id_of(KIND))); + crate::dialogs::host::pump(app, &ctx); + host(app, |h| h.get_by_id::(id_of(KIND)).and_then(|d| d.held_state())) + } + + /// The next OK of a dialog whose edits were accepted closes it, as the pass that draws it would. + fn finish(app: &VectorcraftApp) { + let ctx = ctx(app); + host(app, |h| h.confirm_by_id(&ctx, id_of(KIND))); + } + + fn cancel(app: &VectorcraftApp) { + let ctx = ctx(app); + host(app, |h| h.cancel_by_id(&ctx, id_of(KIND))); + } + #[test] fn nothing_changes_until_ok_and_all_edits_are_one_undo_step() { let mut app = app(); super::open(&mut app).unwrap(); // Rename the first and delete the last. - set(&mut app, "name0", json!(" Brand ")); - set(&mut app, "deleted2", json!(true)); + set(&app, "name0", json!(" Brand ")); + set(&app, "deleted2", json!(true)); assert_eq!(names(&mut app), json!(["Logo", "Icons", "Text"])); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Accepted))); + finish(&app); + assert!(!is_open(&app)); assert_eq!(names(&mut app), json!(["Brand", "Icons"])); app.run("edit.undo", json!({})).unwrap(); assert_eq!(names(&mut app), json!(["Logo", "Icons", "Text"])); @@ -161,25 +104,29 @@ mod tests { fn cancel_leaves_them_and_a_shared_name_keeps_the_dialog_open() { let mut app = app(); super::open(&mut app).unwrap(); - set(&mut app, "name0", json!("Gone")); - super::super::cancel(&mut app); + set(&app, "name0", json!("Gone")); + cancel(&app); + assert!(!is_open(&app)); assert_eq!(names(&mut app), json!(["Logo", "Icons", "Text"])); super::open(&mut app).unwrap(); - set(&mut app, "name0", json!("Text")); - assert!(super::super::confirm(&mut app).is_err()); - assert!(app.ui.dialog.is_some()); + set(&app, "name0", json!("Text")); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(_))), "two saved selections would share the name"); + assert!(is_open(&app)); assert_eq!(names(&mut app), json!(["Logo", "Icons", "Text"])); // Deleting the other one frees the name. - set(&mut app, "deleted2", json!(true)); - super::super::confirm(&mut app).unwrap(); + set(&app, "deleted2", json!(true)); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Accepted))); + finish(&app); assert_eq!(names(&mut app), json!(["Text", "Icons"])); } #[test] fn it_needs_a_saved_selection() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui_ctx = Some(crate::testing::ui_context()); app.run("file.new", json!({})).unwrap(); assert!(super::open(&mut app).is_err()); - assert!(app.ui.dialog.is_none()); + assert!(!app.any_dialog_open()); + assert!(!is_open(&app)); } } diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index cda98afada..9d37833977 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -5,42 +5,167 @@ //! opens on them, and Object › Expand… chosen with Alt (Option) expands with them at once //! ([`expand_now`]). //! -//! Fields: `object`, `fill`, `stroke`, `gradient` (`objects` | `mesh`), `steps` (1..1000), and -//! `__object`, `__fill`, `__stroke` (that option has something to expand: `object.expand.info`), -//! `__gradient` (Fill has a gradient fill to expand), and `__fill_symbol`, `__stroke_symbol`, -//! `__gradient_symbol` (only the art of symbol instances holds it, so the option needs Object on). +//! Fields: `object`, `fill`, `stroke`, `gradient` (`objects` | `mesh`), `steps` (1..1000), and the +//! dialog-only `__canObject`, `__canFill`, `__canStroke` (that option has something to expand: +//! `object.expand.info`), `__canGradient` (Expand Gradient To applies) and `__canSteps` (it +//! applies and makes objects). What only the art of symbol instances holds needs Object on. +use craft::ui::contract::SaveKey; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::runtime::memory::Lifetime; use serde_json::{Value, json}; use vectorcraft_engine::cmd::expand::{DEFAULT_STEPS, MAX_STEPS}; -use super::{DialogSpec, run_and_close}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use crate::VectorcraftApp; /// The dialog kind of Expand. pub const KIND: &str = "expand"; const CMD: &str = "object.expand"; +/// Where the choices OK expanded with are kept for the rest of the app's run. +const REMEMBER: SaveKey = SaveKey::new("vectorcraft.dialog.expand"); + /// The options and their checkbox labels. const OPTIONS: [(&str, &str); 3] = [("object", "Object"), ("fill", "Fill"), ("stroke", "Stroke")]; -pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Expand").into(), body, confirm, min_width: 260.0, ..DialogSpec::FORM }; - /// Why Object › Expand… is dimmed: the selection has appearance attributes, which Expand Appearance /// turns into plain art first (#3089). pub(crate) fn appearance_first() -> &'static str { tl!("Expand Appearance first (Object › Expand Appearance)") } +/// What `object.expand.info` says the selection holds for each option, and which of it only the art of +/// symbol instances holds (Fill and Stroke reach that only when Object expands the instances). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct ExpandInfo { + object: bool, + fill: bool, + stroke: bool, + gradient: bool, + fill_symbol: bool, + stroke_symbol: bool, + gradient_symbol: bool, +} + +impl ExpandInfo { + /// The info for the selection; a selection with appearance attributes refuses with + /// [`appearance_first`]. + fn read(app: &mut VectorcraftApp) -> Result { + let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?; + if info["appearance"] == json!(true) { + return Err(appearance_first().into()); + } + let flag = |v: &Value| *v == json!(true); + let art = &info["symbolArt"]; + Ok(ExpandInfo { + object: flag(&info["object"]), + fill: flag(&info["fill"]), + stroke: flag(&info["stroke"]), + gradient: flag(&info["gradient"]), + fill_symbol: flag(&art["fill"]), + stroke_symbol: flag(&art["stroke"]), + gradient_symbol: flag(&art["gradient"]), + }) + } + + /// Does the selection hold something option `key` expands? + fn has(self, key: &str) -> bool { + match key { + "object" => self.object, + "fill" => self.fill, + "stroke" => self.stroke, + "gradient" => self.gradient, + _ => false, + } + } + + /// Does only the art of symbol instances hold what option `key` expands? + fn symbol_art_only(self, key: &str) -> bool { + match key { + "fill" => self.fill_symbol, + "stroke" => self.stroke_symbol, + "gradient" => self.gradient_symbol, + _ => false, + } + } +} + +/// The dialog-only field that says whether the row of `key` takes input. +fn can_key(key: &str) -> &'static str { + match key { + "object" => "__canObject", + "fill" => "__canFill", + "stroke" => "__canStroke", + "gradient" => "__canGradient", + _ => "__canSteps", + } +} + +/// Is the switch `key` on? One not set yet is on, as the dialog opens. +fn on(fields: &DialogFields, key: &str) -> bool { + fields.bool(key).unwrap_or(true) +} + +/// Has option `key` something to expand? What only the art of symbol instances holds needs Object on. +fn option_enabled(info: ExpandInfo, fields: &DialogFields, key: &str) -> bool { + info.has(key) && (key == "object" || on(fields, "object") || !info.symbol_art_only(key)) +} + +/// Does Expand Gradient To apply? Only gradient fills that Fill expands care. +fn gradient_to_enabled(info: ExpandInfo, fields: &DialogFields) -> bool { + option_enabled(info, fields, "gradient") && option_enabled(info, fields, "fill") && on(fields, "fill") +} + +/// Writes the dialog-only fields the rows read for the values in `fields`. +fn refresh(info: ExpandInfo, fields: &mut DialogFields) { + for (key, _) in OPTIONS { + let enabled = option_enabled(info, fields, key); + fields.set(can_key(key), enabled); + } + let gradient_to = gradient_to_enabled(info, fields); + let steps = gradient_to && fields.text("gradient") != Some("mesh"); + fields.set(can_key("gradient"), gradient_to); + fields.set(can_key("steps"), steps); +} + +/// The rows of the dialog. +fn rows() -> Vec { + let mut rows = vec![Param::section(tl!("Expand"))]; + rows.extend(OPTIONS.map(|(key, label)| Param::new(key, label, ParamKind::bool(true)).enabled_when(can_key(key), true))); + rows.push(Param::section(tl!("Expand Gradient To"))); + let choices = vec![("mesh".to_owned(), tl!("Gradient Mesh").into()), ("objects".to_owned(), tl!("Specify:").into())]; + rows.push(Param::new("gradient", "", ParamKind::radio(choices, Some("objects".to_owned()))).enabled_when(can_key("gradient"), true)); + let steps = ParamKind::int(Some(1), Some(i64::from(MAX_STEPS)), i64::from(DEFAULT_STEPS)); + rows.push(Param::new("steps", tl!("Objects"), steps).enabled_when(can_key("steps"), true)); + rows +} + +/// The dialog for a selection with `info`, on the choices OK last expanded with in this run of the app or +/// every option on before that. +fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result { + let ctx = app.ui_ctx.as_ref().ok_or("no window")?; + let rows = rows(); + Ok(HostedParamDialog::new(ctx, KIND, DialogFields::new(), move |fields| { + refresh(info, fields); + ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run) + })) +} + +/// Shows `dialog`; its OK expands. +fn show(app: &mut VectorcraftApp, dialog: HostedParamDialog) -> Result { + crate::dialogs::host::open_held(app, dialog, ok).ok_or("no window")?; + Ok(Value::Null) +} + /// Open Expand for the selection, on the choices OK last expanded with in this run of the app, or /// every option on (as `object.expand {}` does) before that. A selection with appearance attributes /// (effects, several fills or strokes…) refuses with [`appearance_first`]: the menu item is dimmed /// for it. pub fn open(app: &mut VectorcraftApp) -> Result { - let fields = fields(app)?; - app.ui.dialog = Some(Dialog::new(KIND, fields)); - Ok(Value::Null) + let info = ExpandInfo::read(app)?; + let d = dialog(app, info)?; + show(app, d) } /// Object › Expand… chosen with Alt (Option): expand the selection at once, in one undo step, with @@ -49,145 +174,108 @@ pub fn open(app: &mut VectorcraftApp) -> Result { /// selection, the dialog opens on them instead, and nothing changes. A selection with appearance /// attributes refuses with [`appearance_first`], as [`open`] does. pub fn expand_now(app: &mut VectorcraftApp) -> Result { - let d = Dialog::new(KIND, fields(app)?); - if !OPTIONS.iter().any(|(key, _)| d.bool(key) && option_enabled(&d, key)) { - app.ui.dialog = Some(d); - return Ok(Value::Null); + let info = ExpandInfo::read(app)?; + let d = dialog(app, info)?; + let fields = d.fields(); + if !OPTIONS.iter().any(|(key, _)| on(fields, key) && option_enabled(info, fields, key)) { + return show(app, d); } - app.run(CMD, params(&d)) -} - -/// The choices OK last expanded with (`app.ui.expand_options`), when each one holds a value the -/// dialog shows: a switch for Object, Fill and Stroke, `objects` or `mesh`, and 1 to 1000 steps. -fn remembered(app: &VectorcraftApp) -> Option<&Value> { - let o = &app.ui.expand_options; - let switches = OPTIONS.iter().all(|(key, _)| o[key].is_boolean()); - let gradient = matches!(o["gradient"].as_str(), Some("objects" | "mesh")); - let steps = o["steps"].as_f64().is_some_and(|n| (1.0..=MAX_STEPS as f64).contains(&n.round())); - (switches && gradient && steps).then_some(o) -} - -/// The dialog's fields for the selection: the remembered choices (or the defaults) and what each -/// option has to expand. -fn fields(app: &mut VectorcraftApp) -> Result { - let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?; - if info["appearance"] == json!(true) { - return Err(appearance_first().into()); - } - let mut fields = match remembered(app) { - Some(o) => json!({"object": o["object"], "fill": o["fill"], "stroke": o["stroke"], "gradient": o["gradient"], "steps": o["steps"]}), - None => json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}), - }; - for (key, _) in OPTIONS { - fields[format!("__{key}")] = info[key].clone(); - } - fields["__gradient"] = info["gradient"].clone(); - for key in ["fill", "stroke", "gradient"] { - fields[format!("__{key}_symbol")] = json!(info["symbolArt"][key] == json!(true)); - } - Ok(fields) -} - -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let set = |d: &mut Dialog, key: &str, v: Value| { - d.fields.insert(key.into(), v); - }; - widgets::subheader(ui, tl!("Expand")); - for (key, label) in OPTIONS { - let on = d.bool(key); - ui.horizontal(|ui| { - ui.add_space(12.0); - if widgets::check(ui, label, on, option_enabled(d, key)) { - set(d, key, json!(!on)); - } - }); - } - ui.add_space(10.0); - widgets::subheader(ui, tl!("Expand Gradient To")); - let enabled = gradient_to_enabled(d); - let objects = d.str("gradient") != "mesh"; - ui.horizontal(|ui| { - ui.add_space(12.0); - if widgets::radio(ui, tl!("Gradient Mesh"), !objects, enabled) { - set(d, "gradient", json!("mesh")); - } - }); - ui.horizontal(|ui| { - ui.add_space(12.0); - if widgets::radio(ui, tl!("Specify:"), objects, enabled) { - set(d, "gradient", json!("objects")); - } - ui.add_enabled_ui(enabled && objects, |ui| { - if let Some(n) = widgets::plain_field(ui, "expand-steps", d.f64("steps", DEFAULT_STEPS as f64), "", 0, 52.0) { - set(d, "steps", json!(n.round().clamp(1.0, MAX_STEPS as f64))); - } - widgets::dim_label(ui, tl!("Objects")); - }); - }); - false -} - -/// Has option `key` something to expand? What only the art of symbol instances holds needs Object -/// on. -fn option_enabled(d: &Dialog, key: &str) -> bool { - d.bool(&format!("__{key}")) && (key == "object" || d.bool("object") || !d.bool(&format!("__{key}_symbol"))) -} - -/// Does Expand Gradient To apply? Only gradient fills that Fill expands care. -fn gradient_to_enabled(d: &Dialog) -> bool { - option_enabled(d, "gradient") && option_enabled(d, "fill") && d.bool("fill") + app.run(CMD, params(fields)) } /// `object.expand` parameters from the fields. -fn params(d: &Dialog) -> Value { +fn params(fields: &DialogFields) -> Value { json!({ - "object": d.bool("object"), - "fill": d.bool("fill"), - "stroke": d.bool("stroke"), - "gradient": d.str("gradient"), - "steps": d.f64("steps", DEFAULT_STEPS as f64), + "object": on(fields, "object"), + "fill": on(fields, "fill"), + "stroke": on(fields, "stroke"), + "gradient": fields.text("gradient").unwrap_or_default(), + "steps": fields.number("steps").unwrap_or(f64::from(DEFAULT_STEPS)), }) } -/// OK: expand, and keep the choices once the expansion succeeded. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let choices = params(d); - let r = run_and_close(app, CMD, choices.clone())?; - app.ui.expand_options = choices; - Ok(r) +/// OK: expand, and keep the choices once the expansion succeeded; a failure keeps the dialog open with +/// the reason. +fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + app.run(CMD, params(&result.fields))?; + if let Some(ctx) = &app.ui_ctx { + result.remember(ctx); + } + Ok(()) } #[cfg(test)] mod tests { use super::*; + use craft::ui::dialog::{DialogHost, DialogId, HeldOk, StackDialog as _, dialog_id}; use vectorcraft_engine::Session; use vectorcraft_engine::doc::NodeKind; - fn frame(app: &mut VectorcraftApp) -> String { - crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(crate::testing::ui_context()); + app + } + + fn ctx(app: &VectorcraftApp) -> egui::Context { + app.ui_ctx.clone().expect("the test context") + } + + fn host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost) -> R) -> R { + app.dialogs().expect("a window").with(f) + } + + fn id() -> DialogId { + dialog_id(KIND) + } + + fn is_open(app: &VectorcraftApp) -> bool { + host(app, |h| h.get_by_id::(id()).is_some()) + } + + /// The values the open Expand dialog shows. + fn fields(app: &VectorcraftApp) -> DialogFields { + host(app, |h| h.get_by_id::(id()).map(|d| d.fields().clone())).expect("the Expand dialog") + } + + /// The open dialog's `field` set as its row would. + fn set(app: &VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + let ctx = ctx(app); + host(app, |h| h.set_json_field(&ctx, id(), field, value)) + } + + /// OK as a click: the answer waits for the pump, which runs the expansion and answers it. + fn press_ok(app: &mut VectorcraftApp) -> Option { + let ctx = ctx(app); + host(app, |h| h.confirm_by_id(&ctx, id())); + crate::dialogs::host::pump(app, &ctx); + host(app, |h| h.get_by_id::(id()).and_then(|d| d.held_state())) + } + + /// Takes the dialog off the host, as the pass that closes an accepted one does: a trial draws no pass. + fn close(app: &VectorcraftApp) { + let ctx = ctx(app); + host(app, |h| h.cancel_by_id(&ctx, id())); + } + + /// OK that the expansion accepts, and the dialog closing. + fn ok_and_close(app: &mut VectorcraftApp) { + assert!(matches!(press_ok(app), Some(HeldOk::Accepted)), "OK expands"); + close(app); } #[test] fn opens_with_what_applies_and_ok_expands_the_gradient_to_a_mesh() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); - app.run("paint.setFill", json!({"gradient": {"kind": "linear"}})).unwrap(); - app.run("paint.setStroke", json!({"none": true})).unwrap(); + let mut app = app(); + gradient_rectangle(&mut app); // The menu item (and `object.expand` without params) opens the dialog. crate::menus::invoke(&mut app, "object.expand", json!({})); - let d = app.ui.dialog.as_ref().expect("the Expand dialog"); - assert_eq!(d.kind, KIND); - assert_eq!((d.bool("__object"), d.bool("__fill"), d.bool("__stroke")), (true, true, false), "no stroke to expand"); - assert_eq!(params(d), json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0})); - let text = frame(&mut app); - for label in ["Expand", "Object", "Fill", "Stroke", "Expand Gradient To", "Gradient Mesh", "Specify:", "Objects", "OK", "Cancel"] { - assert!(text.contains(label), "{label} in {text}"); - } + let shown = fields(&app); + assert_eq!((shown.bool("__canObject"), shown.bool("__canFill"), shown.bool("__canStroke")), (Some(true), Some(true), Some(false)), "no stroke to expand"); + assert_eq!(params(&shown), json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0})); let undo = app.session.doc().unwrap().history.undo.len(); - app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("mesh")); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + set(&app, "gradient", json!("mesh")).unwrap(); + ok_and_close(&mut app); let st = app.session.doc().unwrap(); assert_eq!(st.history.undo.len(), undo + 1); let g = st.doc.node(st.selection.objects[0]).unwrap(); @@ -197,57 +285,39 @@ mod tests { #[test] fn expand_gradient_to_is_disabled_for_a_pattern_fill_alone() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); let dot = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); app.run("object.pattern.make", json!({"ids": [dot], "name": "Dots", "width": 20, "height": 20, "edit": false})).unwrap(); app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); app.run("paint.setFill", json!({"swatch": "Dots"})).unwrap(); app.run("ui.expandDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.bool("__fill"), "Fill expands the pattern fill"); - assert!(!gradient_to_enabled(d), "no gradient fill for Expand Gradient To"); - frame(&mut app); + let info = ExpandInfo::read(&mut app).unwrap(); + assert_eq!(fields(&app).bool("__canFill"), Some(true), "Fill expands the pattern fill"); + assert!(!gradient_to_enabled(info, &fields(&app)), "no gradient fill for Expand Gradient To"); // A gradient fill enables it. - app.ui.dialog = None; app.run("paint.setFill", json!({"gradient": {"kind": "linear"}})).unwrap(); app.run("ui.expandDialog", json!({})).unwrap(); - assert!(gradient_to_enabled(app.ui.dialog.as_ref().unwrap())); + let info = ExpandInfo::read(&mut app).unwrap(); + assert!(gradient_to_enabled(info, &fields(&app))); } /// Stroke for the stroke in a symbol instance's art is enabled only while Object is on, since /// Object expands the instance. #[test] fn stroke_for_a_symbol_instances_art_needs_object() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); app.run("paint.setFill", json!({"none": true})).unwrap(); app.run("paint.setStroke", json!({"color": "#000000"})).unwrap(); app.run("symbol.new", json!({"name": "Frame"})).unwrap(); app.run("ui.expandDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - assert!(option_enabled(d, "object") && option_enabled(d, "stroke")); - d.fields.insert("object".into(), json!(false)); - assert!(!option_enabled(d, "stroke"), "Stroke can't reach the art with Object off"); - frame(&mut app); - } - - #[test] - fn the_command_palette_opens_it_and_ui_expand_dialog_too() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); - app.run("ui.expandDialog", json!({})).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.bool("__object"), d.bool("__fill"), d.bool("__stroke")), (true, false, true)); - frame(&mut app); - // Explicit params still run the command directly. - app.ui.dialog = None; - crate::menus::invoke(&mut app, "object.expand", json!({"stroke": false})); - assert!(app.ui.dialog.is_none()); - let st = app.session.doc().unwrap(); - assert!(matches!(st.doc.node(st.selection.objects[0]).unwrap().kind, NodeKind::Path { live: None, .. })); + let info = ExpandInfo::read(&mut app).unwrap(); + let shown = fields(&app); + assert!(option_enabled(info, &shown, "object") && option_enabled(info, &shown, "stroke")); + set(&app, "object", json!(false)).unwrap(); + assert!(!option_enabled(info, &fields(&app), "stroke"), "Stroke can't reach the art with Object off"); } /// A line with a stroke and a Zig Zag effect is selected (#3089). @@ -261,14 +331,15 @@ mod tests { #[test] fn expand_waits_for_expand_appearance_on_a_line_with_an_effect() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); zig_zag_line(&mut app); assert!(!crate::menus::enabled(&app, "ui.expandDialog"), "Expand… is dimmed for the Zig Zag effect"); assert!(crate::menus::enabled(&app, "effect.expandAppearance")); // A shortcut or the command palette doesn't open it either; the status bar says why. let before = app.session.doc().unwrap().doc.clone(); crate::menus::invoke(&mut app, "object.expand", json!({})); - assert!(app.ui.dialog.is_none()); + assert!(!app.any_dialog_open()); + assert!(!is_open(&app)); assert_eq!(app.ui.status, appearance_first()); assert_eq!(app.run("ui.expandDialog", json!({})).unwrap_err(), appearance_first()); assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was"); @@ -279,12 +350,12 @@ mod tests { assert!(line.appearance.effects.is_empty() && !line.appearance.stroke_paint().is_none()); assert!(crate::menus::enabled(&app, "ui.expandDialog")); crate::menus::invoke(&mut app, "object.expand", json!({})); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert!(is_open(&app)); } #[test] fn expand_is_dimmed_for_two_fills_but_not_for_a_plain_rectangle() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); assert!(crate::menus::enabled(&app, "ui.expandDialog"), "a basic appearance"); @@ -303,15 +374,10 @@ mod tests { app.run("paint.setStroke", json!({"none": true})).unwrap(); } - /// Object › Expand… from the in-window menu, with Alt held or not. + /// Object › Expand… with Alt held or not: the Alt entry runs `ui.expandDialog` with `immediate`. fn choose_expand(app: &mut VectorcraftApp, alt: bool) { - let entries = crate::menus::menu_entries(app); - let e = entries.iter().find(|e| e.path == ["Object"] && e.label == "Expand…").expect("Object › Expand…"); - assert!(e.enabled, "Expand… is available"); - let target = crate::menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); - let held = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; - let (cmd, p) = crate::menus::with_held_keys(target, held); - crate::menus::invoke(app, &cmd, p); + let params = if alt { json!({"immediate": true}) } else { json!({}) }; + app.run("ui.expandDialog", params).unwrap(); } /// Whether the selected object is a clip group holding a gradient mesh (Expand Gradient To › @@ -325,109 +391,108 @@ mod tests { #[test] fn the_dialog_opens_on_the_choices_ok_last_expanded_with() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); gradient_rectangle(&mut app); choose_expand(&mut app, false); - let d = app.ui.dialog.as_mut().expect("the Expand dialog"); - d.fields.insert("gradient".into(), json!("mesh")); - d.fields.insert("steps".into(), json!(12)); - d.fields.insert("stroke".into(), json!(false)); - super::super::confirm(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + set(&app, "steps", json!(12)).unwrap(); + set(&app, "stroke", json!(false)).unwrap(); + ok_and_close(&mut app); assert!(expanded_to_a_mesh(&app)); app.run("edit.undo", json!({})).unwrap(); let kept = json!({"object": true, "fill": true, "stroke": false, "gradient": "mesh", "steps": 12.0}); choose_expand(&mut app, false); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept, "it opens on the choices OK expanded with"); + assert_eq!(params(&fields(&app)), kept, "it opens on the choices OK expanded with"); // Cancel leaves them as they were. - app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("objects")); - super::super::cancel(&mut app); - assert_eq!(app.ui.expand_options, kept); - // So does an OK that fails, and nothing changes. + set(&app, "gradient", json!("objects")).unwrap(); + close(&app); choose_expand(&mut app, false); - app.ui.dialog.as_mut().unwrap().fields.insert("steps".into(), json!(5000)); + assert_eq!(params(&fields(&app)), kept); + // A count the row refuses is not taken. + assert!(set(&app, "steps", json!(5000)).is_err()); + assert_eq!(params(&fields(&app)), kept); + // An OK that fails keeps the dialog open with the reason, and nothing changes. + app.run("select.none", json!({})).unwrap(); let before = app.session.doc().unwrap().doc.clone(); - assert!(super::super::confirm(&mut app).is_err()); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(_))), "the expansion has no selection to work on"); + assert!(is_open(&app)); assert_eq!(app.session.doc().unwrap().doc, before); - assert_eq!(app.ui.expand_options, kept); + close(&app); + app.run("select.all", json!({})).unwrap(); choose_expand(&mut app, false); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept); + assert_eq!(params(&fields(&app)), kept); } #[test] fn alt_expands_at_once_with_the_choices_ok_last_expanded_with() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); gradient_rectangle(&mut app); choose_expand(&mut app, false); - app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("mesh")); - super::super::confirm(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + ok_and_close(&mut app); app.run("edit.undo", json!({})).unwrap(); let undo = app.session.doc().unwrap().history.undo.len(); choose_expand(&mut app, true); - assert!(app.ui.dialog.is_none(), "no dialog"); + assert!(!is_open(&app), "no dialog"); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); assert!(expanded_to_a_mesh(&app), "the kept Gradient Mesh choice"); } #[test] fn alt_before_any_ok_expands_with_the_defaults() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); gradient_rectangle(&mut app); let undo = app.session.doc().unwrap().history.undo.len(); choose_expand(&mut app, true); - assert!(app.ui.dialog.is_none(), "no dialog"); + assert!(!is_open(&app), "no dialog"); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); assert!(!expanded_to_a_mesh(&app), "the gradient becomes objects, the default"); - assert!(app.ui.expand_options.is_null(), "Alt keeps no choices of its own"); + app.run("edit.undo", json!({})).unwrap(); + choose_expand(&mut app, false); + assert_eq!( + params(&fields(&app)), + json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0}), + "Alt keeps no choices of its own" + ); } #[test] fn alt_opens_the_dialog_when_the_kept_choices_expand_nothing_in_the_selection() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); + gradient_rectangle(&mut app); + // Fill alone is kept by a real OK. + choose_expand(&mut app, false); + set(&app, "object", json!(false)).unwrap(); + set(&app, "stroke", json!(false)).unwrap(); + ok_and_close(&mut app); + // A plain rectangle has no gradient or pattern fill. app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); - // Fill alone was kept, and a plain rectangle has no gradient or pattern fill. - app.ui.expand_options = json!({"object": false, "fill": true, "stroke": false, "gradient": "objects", "steps": 255.0}); let before = app.session.doc().unwrap().doc.clone(); let undo = app.session.doc().unwrap().history.undo.len(); choose_expand(&mut app, true); - let d = app.ui.dialog.as_ref().expect("the Expand dialog"); - assert_eq!(params(d), app.ui.expand_options, "it opens on the kept choices"); + assert!(is_open(&app), "the Expand dialog"); + assert_eq!( + params(&fields(&app)), + json!({"object": false, "fill": true, "stroke": false, "gradient": "objects", "steps": 255.0}), + "it opens on the kept choices" + ); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing recorded"); assert_eq!(app.session.doc().unwrap().doc, before); } #[test] fn alt_refuses_a_selection_with_appearance_attributes_and_a_bad_immediate() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); zig_zag_line(&mut app); let before = app.session.doc().unwrap().doc.clone(); assert_eq!(app.run("ui.expandDialog", json!({"immediate": true})).unwrap_err(), appearance_first()); - assert!(app.ui.dialog.is_none()); + assert!(!is_open(&app)); assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was"); app.run("effect.expandAppearance", json!({})).unwrap(); assert!(app.run("ui.expandDialog", json!({"immediate": "yes"})).is_err()); - assert!(app.ui.dialog.is_none()); + assert!(!is_open(&app)); app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); - } - - #[test] - fn kept_choices_with_a_value_the_dialog_does_not_show_are_left_out() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - gradient_rectangle(&mut app); - for bad in [ - json!({"object": "yes", "fill": true, "stroke": true, "gradient": "mesh", "steps": 12}), - json!({"object": true, "fill": true, "stroke": true, "gradient": "strips", "steps": 12}), - json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh", "steps": 0}), - json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh"}), - ] { - app.ui.expand_options = bad; - app.run("ui.expandDialog", json!({})).unwrap(); - assert_eq!( - params(app.ui.dialog.as_ref().unwrap()), - json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0}) - ); - app.ui.dialog = None; - } + assert!(is_open(&app)); } } diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs new file mode 100644 index 0000000000..6660cdace1 --- /dev/null +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -0,0 +1,359 @@ +//! The dialog behind Select → Edit Selection… and View → Edit Views…: the document's saved names in a list, +//! renamed in place or deleted with Delete. Nothing changes until OK, which sends every rename and delete as +//! one `edits` list to the kind's command (one undo step); Cancel leaves them as they were. A name the +//! command refuses (two saved items would share it) keeps the dialog open with the reason. +//! +//! Fields: `count` and, for each saved item `i`, `orig` (its name when the dialog opened), `name` (as +//! edited) and `deleted`; `selected` (the row picked). + +use std::borrow::Cow; + +use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, ItemSource, Selection}; +use craft::theme::variant::Tone; +use craft::ui::buttons::Button; +use craft::ui::contract::{Bind, CollectionEvent, ColumnSpec, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row; +use craft::ui::list::{List, ListRow}; +use craft::ui::notices::{Notice, NoticeLayout}; +use craft::ui::patterns::form_dialogs::{FormDialog, ResetFooter, ResetPick}; +use craft::ui::runtime::env::Label; +use craft::ui::style::SurfaceKind; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; + +// PLAN: ui-egui's Cargo.toml has no `craft` dependency (it names `craft-ui` and other crates); the `craft::` paths need it (owner: hub-w1/hub-w2, whoever edits the manifest). + +/// What tells the two kinds of saved names apart: the dialog kind, its words and the command that applies the +/// edits. +#[derive(Clone, Copy, Debug)] +pub(crate) struct SavedNames { + /// The dialog kind; its key on the host, so two kinds are two dialogs. + pub kind: &'static str, + /// The dialog's title. + pub title: &'static str, + /// The label of the list. + pub list: &'static str, + /// The command that applies `{edits}`. + pub command: &'static str, + /// The most names the dialog lists. + pub max: usize, +} + +/// The part of every saved-names dialog's id the kind is added to. +const KEY: &str = "savedNames"; + +/// The rows of the list the user sees at once; more scroll. +const SHOWN_ROWS: u16 = 9; + +const NAME: ColumnKey = ColumnKey::new("name"); + +/// The id of the dialog of `kind` on the host. +pub(crate) fn id_of(kind: &str) -> DialogId { + dialog_id((KEY, kind)) +} + +/// One saved name as the dialog edits it. +#[derive(Clone, Debug, PartialEq)] +struct NameRow { + /// The name when the dialog opened: what the command finds the item by. + orig: String, + name: String, + deleted: bool, +} + +/// What the dialog edits: every name, deleted ones included, in the order they were saved. +#[derive(Clone, Debug, Default, PartialEq)] +struct NamesDraft { + rows: Vec, +} + +impl NamesDraft { + /// The rows still in the list (not deleted), by their index in `rows`. + fn visible(&self) -> Vec { + self.rows.iter().enumerate().filter(|(_, row)| !row.deleted).map(|(at, _)| at).collect() + } + + /// The first picked row that is still in the list. + fn selected(&self, selection: &Selection) -> Option { + selection.items.iter().copied().find(|at| self.rows.get(*at).is_some_and(|row| !row.deleted)) + } + + /// The edits OK applies: each deleted item, and each one whose name was changed. + fn edits(&self) -> Vec { + self.rows + .iter() + .filter_map(|row| { + let name = row.name.trim(); + if row.deleted { + Some(json!({ "name": row.orig, "delete": true })) + } else if !name.is_empty() && name != row.orig { + Some(json!({ "name": row.orig, "newName": name })) + } else { + None + } + }) + .collect() + } + + /// The index in `rows` a field named `prefix` and a number refers to, when the number is written as the + /// dialog writes it and names a row. + fn row_of(&self, field: &str, prefix: &str) -> Option { + let digits = field.strip_prefix(prefix)?; + let at: usize = digits.parse().ok()?; + (at.to_string() == digits && at < self.rows.len()).then_some(at) + } +} + +/// The rows still in the list, keyed by their index in the draft. +struct Shown<'a> { + rows: &'a [NameRow], + at: &'a [usize], +} + +impl DisplayOrder for Shown<'_> { + fn len(&self) -> usize { + self.at.len() + } + + fn key(&self, at: usize) -> usize { + self.at.get(at).copied().unwrap_or_default() + } + + fn index_of(&self, key: &usize) -> Option { + self.at.iter().position(|row| row == key) + } + + fn text(&self, at: usize) -> Option> { + let row = self.rows.get(*self.at.get(at)?)?; + Some(Cow::Borrowed(row.name.as_str())) + } +} + +impl ItemSource for Shown<'_> {} + +/// The saved-names dialog of one kind. +pub(crate) struct SavedNamesDialog { + id: DialogId, + names: SavedNames, + draft: NamesDraft, + /// The picked row, by its index in the draft; one at most. + selection: Selection, + /// The edits OK filed, until the command answered them. + held: HeldAnswer>, +} + +impl SavedNamesDialog { + /// The dialog over `list`, with the first name picked. + fn new(names: SavedNames, list: Vec) -> Self { + let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; + let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); + SavedNamesDialog { id: id_of(names.kind), names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + } + + /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for + /// the command's answer (`None`), and once it accepted them the dialog closes. + fn press_ok(&mut self) -> Option<()> { + if self.held.is_accepted() { + return self.held.finish().map(|_| ()); + } + if self.held.is_waiting() { + return None; + } + let edits = self.draft.edits(); + if edits.is_empty() { + return Some(()); + } + self.held.file(edits); + None + } + + /// Picks the first row still in the list, or none when every row is deleted. + fn reselect(&mut self) { + self.selection = self.draft.visible().first().map_or_else(Selection::default, |at| Selection::single(*at)); + } + + /// Shows the list and Delete over `draft`. + fn rows(ui: &mut egui::Ui, names: SavedNames, draft: &mut NamesDraft, selection: &mut Selection) { + let visible = draft.visible(); + let selected = draft.selected(selection); + let mut events = Vec::new(); + let mut delete = false; + Row::new().show(ui, |ui, _| { + Field::new(names.list).show(ui, |ui, _| { + let order = Shown { rows: &draft.rows, at: &visible }; + let columns = vec![ColumnSpec::new(NAME, Label::Empty, ColumnWidth::fill(1.0))]; + let out = List::::new(names.list) + .surface(SurfaceKind::Sunken) + .header(false) + .select(SelectMode::Single) + .rename(true) + .rename_column(NAME) + .columns(columns) + .selection(Bind::bound(&mut *selection)) + .max_rows(SHOWN_ROWS) + .show_items(ui, &order, &mut |key, icx| { + let name = draft.rows.get(*key).map(|row| row.name.clone()).unwrap_or_default(); + ListRow::new(name).cells(icx.cells()).state(icx.row.clone()) + }); + events = out.events; + }); + delete = Button::new(tl!("Delete")).enabled(selected.is_some()).show(ui).clicked(); + }); + for event in &events { + if let CollectionEvent::Rename(edit) = event + && let Some(rename) = edit.value() + && !rename.name.trim().is_empty() + && let Some(row) = draft.rows.get_mut(rename.key) + { + rename.name.trim().clone_into(&mut row.name); + } + } + if let (true, Some(at)) = (delete, selected) + && let Some(row) = draft.rows.get_mut(at) + { + row.deleted = true; + // The row below takes its place (the one above, for the last). + let next = visible.iter().copied().find(|row| *row > at).or_else(|| visible.iter().copied().rfind(|row| *row < at)); + *selection = next.map_or_else(Selection::default, Selection::single); + } + } +} + +impl StackDialog for SavedNamesDialog { + type Result = (); + + fn id(&self) -> DialogId { + self.id + } + + fn key(&self) -> Option<&str> { + Some(self.names.kind) + } + + fn instance(&self) -> Option { + Some(self.id) + } + + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + if self.held.is_accepted() { + return self.press_ok().map(DialogResult::Ok); + } + // The refusal shows until the edits change. + if self.held.refusal().is_some_and(|(_, refused)| *refused != self.draft.edits()) { + self.held.clear_refusal(); + } + let footer = ResetFooter::new(ui, None, true); + let waiting = self.held.is_waiting(); + let reason = self.held.refusal().map(|(reason, _)| reason.clone()); + let SavedNamesDialog { names, draft, selection, .. } = &mut *self; + let names = *names; + let shown = FormDialog::new(names.title, Bind::bound(draft)).accept_stays_open(true).ok_enabled(!waiting).show(ui, |ui, _, draft| { + Self::rows(ui, names, draft, selection); + if let Some(reason) = &reason { + Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui); + } + true + }); + // `picked` is this pass's press: a second pass of the frame has none, so OK files once. + if matches!(footer.pick(shown.picked), Some(ResetPick::Accept)) && self.press_ok().is_some() { + return Some(DialogResult::Ok(())); + } + shown.closed.map(|_| DialogResult::Cancel) + } + + /// Answers OK as its button does: none while the command has not answered the edits. + fn confirm(&mut self, _: &egui::Context) -> Option<()> { + self.press_ok() + } + + fn held_state(&self) -> Option { + self.held.state() + } + + /// `count`, `orig`, `name` and `deleted` of each saved name, and `selected`, the row picked (the first + /// one left when none is). + fn json_fields(&self) -> Option { + let mut fields = json!({ "count": self.draft.rows.len() }); + for (at, row) in self.draft.rows.iter().enumerate() { + fields[format!("orig{at}")] = json!(row.orig); + fields[format!("name{at}")] = json!(row.name); + fields[format!("deleted{at}")] = json!(row.deleted); + } + let selected = self.draft.selected(&self.selection).or_else(|| self.draft.visible().first().copied()); + fields["selected"] = json!(selected.unwrap_or_default()); + Some(fields) + } + + /// Sets `name` (text), `deleted` (a switch) or `selected` (a row) as the list would; `orig` and `count` + /// are read only. + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { + let rejects = || FieldRefusal::Rejects(&value).message(field); + if field == "count" || self.draft.row_of(field, "orig").is_some() { + return Err(FieldRefusal::ReadOnly.message(field)); + } + if field == "selected" { + let at = value.as_u64().and_then(|at| usize::try_from(at).ok()).filter(|at| *at < self.draft.rows.len()).ok_or_else(rejects)?; + self.selection = Selection::single(at); + if self.draft.selected(&self.selection).is_none() { + self.reselect(); + } + return Ok(()); + } + if let Some(at) = self.draft.row_of(field, "name") { + let name = value.as_str().ok_or_else(rejects)?; + if let Some(row) = self.draft.rows.get_mut(at) { + name.clone_into(&mut row.name); + } + return Ok(()); + } + if let Some(at) = self.draft.row_of(field, "deleted") { + let deleted = value.as_bool().ok_or_else(rejects)?; + if let Some(row) = self.draft.rows.get_mut(at) { + row.deleted = deleted; + } + if self.draft.selected(&self.selection).is_none() { + self.reselect(); + } + return Ok(()); + } + Err(FieldRefusal::Unknown.message(field)) + } +} + +/// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). +pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { + list.truncate(names.max); + let dialogs = app.dialogs().ok_or("no window")?; + dialogs.with(|host| host.open(SavedNamesDialog::new(names, list))); + Ok(()) +} + +/// Runs the edits the open saved-names dialogs filed, and answers each dialog with the command's outcome: it +/// closes when the command took the edits, and stays open with the reason when it refused them. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + let filed: Vec<(DialogId, &'static str, Vec)> = dialogs.with(|host| { + host.open_dialogs() + .into_iter() + .filter_map(|open| { + let dialog = host.get_mut_by_id::(open.id)?; + let edits = dialog.held.take()?; + Some((open.id, dialog.names.command, edits)) + }) + .collect() + }); + for (id, command, edits) in filed { + let outcome = app.run(command, json!({ "edits": edits })); + if let Err(reason) = &outcome { + app.status(reason.clone()); + } + dialogs.with(|host| { + if let Some(dialog) = host.get_mut_by_id::(id) { + dialog.held.answer(outcome.map(|_| ()).map_err(Label::from)); + } + }); + } +}