From cfa17266df445f7772a6431eac386bcfab2b4ff3 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:31:23 +0700 Subject: [PATCH] appearance-w13: net change of 1 commits - appearance-w13: written from its sheet --- crates/ui-egui/src/dialogs/symbol_delete.rs | 150 +++++------ crates/ui-egui/src/dialogs/symbol_options.rs | 254 ++++++++----------- 2 files changed, 185 insertions(+), 219 deletions(-) diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs index c515f7274b..666e0bd6a1 100644 --- a/crates/ui-egui/src/dialogs/symbol_delete.rs +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -2,16 +2,15 @@ //! selected symbol?" with Yes and No ([`KIND`]); a symbol with placed instances gets Expand //! Instances, Delete Instances and Cancel ([`USED`]). //! -//! Fields: `name` (the symbol) and `doc` (the [`vectorcraft_engine::DocState::uid`] of the document -//! it was asked in). Yes or either Instances button deletes the symbol only while that document is +//! The question carries the [`vectorcraft_engine::DocState::uid`] of the document it was asked in and +//! the symbol names. Yes or either Instances button deletes the symbol only while that document is //! the active one and still has the symbol; an unused symbol that has gained instances since asks //! the in-use question instead. +use craft_ui::dialog::{PromptChoice, StandardPrompt}; use serde_json::{Value, json}; -use super::{DialogResult, DialogSpec}; use crate::VectorcraftApp; -use crate::state::Dialog; /// The dialog kind of the question for a symbol no instance uses. pub const KIND: &str = "deleteSymbol"; @@ -19,32 +18,25 @@ pub const KIND: &str = "deleteSymbol"; /// The dialog kind of the question for a symbol with placed instances. pub const USED: &str = "deleteUsedSymbol"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |d| { - if d.fields.get("names").and_then(Value::as_array).is_some_and(|n| n.len() > 1) { - tl!("Delete the selected symbols?") - } else { - tl!("Delete the selected symbol?") - } - .into() - }, - body: |_, _, _| false, - confirm: confirm_unused, - ok: Some("Yes"), - cancel: Some("No"), - max_width: Some(420.0), - ..DialogSpec::FORM -}; +/// The symbols a delete question is about. +enum Target { + One(String), + Many(Vec), +} -pub(super) const USED_SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted.").into(), - body: |_, _, _| false, - confirm: confirm_used, - ok: Some("Expand Instances"), - discard: Some("Delete Instances"), - max_width: Some(420.0), - ..DialogSpec::FORM -}; +/// What a delete question carries back in its answer: the document it was asked in, the symbols, and +/// whether it is the in-use question. +struct Ask { + doc: u64, + target: Target, + used: bool, +} + +/// The delete questions. One type for both, so the host's per-type result never mixes with another +/// area's prompt; the [`Ask`] tag tells them apart. +pub(crate) struct SymbolQuestion(pub(crate) StandardPrompt); + +crate::dialogs::confirm::wrapped_dialog!(SymbolQuestion, KIND); /// Delete Symbol for symbol `name` of the active document. A symbol with instances always asks /// what becomes of them; an unused one is deleted at once with `now` (Alt-click on the panel's @@ -58,7 +50,7 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { app.status(e); } } - Some(n) => open(app, if n == 0 { KIND } else { USED }, name, uid), + Some(n) => open(app, Ask { doc: uid, target: Target::One(name.to_string()), used: n > 0 }), } } @@ -71,12 +63,12 @@ pub(crate) fn ask_many(app: &mut VectorcraftApp, names: &[String], now: bool) { // An error already went to the status bar. let _ = delete_unused(app, uid, names); } else { - app.ui.dialog = Some(Dialog::new(KIND, json!({ "names": names, "doc": uid }))); + open(app, Ask { doc: uid, target: Target::Many(names.to_vec()), used: false }); } } /// Deletes those of `names` that are still unused in document `uid` while it is the active one. -fn delete_unused(app: &mut VectorcraftApp, uid: u64, names: &[String]) -> DialogResult { +fn delete_unused(app: &mut VectorcraftApp, uid: u64, names: &[String]) -> Result { if app.session.active().map(|st| st.uid) != Some(uid) { return Ok(Value::Null); } @@ -93,8 +85,39 @@ fn delete_unused(app: &mut VectorcraftApp, uid: u64, names: &[String]) -> Dialog r } -fn open(app: &mut VectorcraftApp, kind: &str, name: &str, uid: u64) { - app.ui.dialog = Some(Dialog::new(kind, json!({ "name": name, "doc": uid }))); +/// Opens the question `ask` describes. +fn open(app: &mut VectorcraftApp, ask: Ask) { + let prompt = if ask.used { + StandardPrompt::custom(tl!("One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted.")) + .button(PromptChoice::Proceed, tl!("Expand Instances")) + .button(PromptChoice::Alternate, tl!("Delete Instances")) + .button(PromptChoice::Cancel, tl!("Cancel")) + } else { + let plural = matches!(&ask.target, Target::Many(names) if names.len() > 1); + StandardPrompt::custom(if plural { tl!("Delete the selected symbols?") } else { tl!("Delete the selected symbol?") }) + .button(PromptChoice::Proceed, tl!("Yes")) + .button(PromptChoice::Cancel, tl!("No")) + }; + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.open(SymbolQuestion(prompt.tag(ask)))); + } +} + +/// Runs the answer of a delete question, once per frame. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + // The host lock is released before any command runs. + let Some(mut answer) = dialogs.with(|host| host.take::()).and_then(|result| result.ok()) else { return }; + let Some(ask) = answer.take_tag::() else { return }; + let r = match (ask.used, answer.choice) { + (false, PromptChoice::Proceed) => confirm_unused(app, ask), + (true, PromptChoice::Proceed) => confirm_used(app, ask, true), + (true, PromptChoice::Alternate) => confirm_used(app, ask, false), + _ => return, + }; + if let Err(e) = r { + app.status(e); + } } /// How many instances symbol `name` has, while the document `uid` is the active one and has the @@ -107,51 +130,28 @@ fn instances(app: &mut VectorcraftApp, uid: u64, name: &str) -> Option { list["symbols"].as_array()?.iter().find(|s| s["name"].as_str() == Some(name)).map(|s| s["instances"].as_u64().unwrap_or(0)) } -/// The document and symbol `d` asks about. -fn target(d: &Dialog) -> (u64, String) { - (d.fields.get("doc").and_then(Value::as_u64).unwrap_or(0), d.str("name")) -} - /// Yes: deletes the symbol, or asks the in-use question when it has gained instances. -fn confirm_unused(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - app.ui.dialog = None; - let (uid, name) = target(d); - if let Some(names) = d.fields.get("names").and_then(|v| serde_json::from_value::>(v.clone()).ok()) { - return delete_unused(app, uid, &names); - } - match instances(app, uid, &name) { - None => Ok(Value::Null), - Some(0) => app.run("symbol.delete", json!({ "name": name })), - Some(_) => { - open(app, USED, &name, uid); - Ok(Value::Null) - } +fn confirm_unused(app: &mut VectorcraftApp, ask: Ask) -> Result { + let Ask { doc, target, .. } = ask; + match target { + Target::Many(names) => delete_unused(app, doc, &names), + Target::One(name) => match instances(app, doc, &name) { + None => Ok(Value::Null), + Some(0) => app.run("symbol.delete", json!({ "name": name })), + Some(_) => { + open(app, Ask { doc, target: Target::One(name), used: true }); + Ok(Value::Null) + } + }, } } -/// Expand Instances (OK) turns the instances into ordinary art; Delete Instances (`discard`) -/// removes them. Either one deletes the symbol in one undo step. -fn confirm_used(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - app.ui.dialog = None; - let (uid, name) = target(d); - if instances(app, uid, &name).is_none() { +/// Expand Instances turns the instances into ordinary art; Delete Instances removes them. Either one +/// deletes the symbol in one undo step. +fn confirm_used(app: &mut VectorcraftApp, ask: Ask, expand: bool) -> Result { + let Target::One(name) = ask.target else { return Ok(Value::Null) }; + if instances(app, ask.doc, &name).is_none() { return Ok(Value::Null); } - app.run("symbol.delete", json!({ "name": name, "expandInstances": !d.bool("discard") })) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The question for the symbols Select All Unused picked is plural (#4918). - #[test] - fn several_symbols_get_the_plural_question() { - let one = Dialog::new(KIND, json!({"name": "A", "doc": 1})); - let many = Dialog::new(KIND, json!({"names": ["A", "B"], "doc": 1})); - assert_eq!((SPEC.heading)(&one), "Delete the selected symbol?"); - assert_eq!((SPEC.heading)(&many), "Delete the selected symbols?"); - let picked_one = Dialog::new(KIND, json!({"names": ["A"], "doc": 1})); - assert_eq!((SPEC.heading)(&picked_one), "Delete the selected symbol?"); - } + app.run("symbol.delete", json!({ "name": name, "expandInstances": expand })) } diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 9d73ad769d..a708945fb2 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -7,18 +7,18 @@ //! (percent of the symbol's size, -1600..1600: below 0 or above 100 for a guide outside the art), //! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; -//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an -//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art). +//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol). Whether the dialog edits an existing +//! symbol, and whether a new symbol leaves the selection as ordinary art, are held by its OK. //! Help: //! . -use serde_json::{Map, Value, json}; +use craft_ui::contract::{Bind, Outcome as _}; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft_ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; +use craft_ui::runtime::env::{Label, UnitKind}; +use serde_json::{Value, json}; -use super::swatch_options::{grid, label}; -use super::{DialogSpec, form}; use crate::VectorcraftApp; -use crate::state::Dialog; -use crate::widgets; /// The dialog kind of Symbol Options. pub const KIND: &str = "symbolOptions"; @@ -29,46 +29,109 @@ const SLICE_KEYS: [&str; 4] = ["sliceLeft", "sliceTop", "sliceRight", "sliceBott /// A guide field's value when the dialog has none: a quarter of the symbol's size, in percent. const DEFAULT_SLICE_PERCENT: f64 = 25.0; -/// The field that keeps the guides the dialog opened with, as fractions, in `[left, top, right, -/// bottom]` order. -const SLICE_OPENED: &str = "__sliceOpened"; - /// The range of a guide field, in percent: a guide may lie outside the art, up to /// [`vectorcraft_doc::MAX_GUIDE_FRACTION`] times its size from its edge. const SLICE_PERCENT_RANGE: std::ops::RangeInclusive = -vectorcraft_doc::MAX_GUIDE_FRACTION * 100.0..=vectorcraft_doc::MAX_GUIDE_FRACTION * 100.0; -/// The 9-slice dialog fields for `guides` (percent of the symbol's size, unrounded; a quarter each -/// when off). -fn slice_fields(guides: Option) -> Map { +/// Sets the 9-slice fields for `guides` (percent of the symbol's size, unrounded; a quarter each when +/// off) and returns the guides as fractions, `[left, top, right, bottom]`, for [`slice_params`]. +fn slice_fields(fields: &mut DialogFields, guides: Option) -> [f64; 4] { let g = guides.unwrap_or_default(); - let mut m = Map::new(); - m.insert("nineSlice".into(), json!(guides.is_some())); + fields.set("nineSlice", FieldValue::Bool(guides.is_some())); let opened = [g.left, g.top, g.right, g.bottom]; for (key, v) in SLICE_KEYS.iter().zip(opened) { - m.insert((*key).to_string(), json!(v * 100.0)); + fields.set(*key, FieldValue::Number(v * 100.0)); } - m.insert(SLICE_OPENED.into(), json!(opened)); - m + opened } /// The guides the dialog's fields describe, as the `nineSlice` / `nineSliceGuides` params. A field -/// still showing the guide it opened with gives that guide exactly. -fn slice_params(d: &Dialog) -> Value { - let opened = d.fields.get(SLICE_OPENED).and_then(Value::as_array); +/// still showing the guide it opened with (`opened`) gives that guide exactly. +fn slice_params(fields: &DialogFields, opened: [f64; 4]) -> Value { let [l, t, r, b] = std::array::from_fn(|i| { - let percent = d.f64(SLICE_KEYS[i], DEFAULT_SLICE_PERCENT); - match opened.and_then(|a| a.get(i)).and_then(Value::as_f64) { - Some(g) if g * 100.0 == percent => g, - _ => percent / 100.0, - } + let percent = fields.number(SLICE_KEYS[i]).unwrap_or(DEFAULT_SLICE_PERCENT); + if opened[i] * 100.0 == percent { opened[i] } else { percent / 100.0 } }); - if d.bool("nineSlice") { json!({ "nineSlice": true, "nineSliceGuides": [l, t, r, b] }) } else { json!({ "nineSlice": false }) } + if fields.bool("nineSlice").unwrap_or(false) { json!({ "nineSlice": true, "nineSliceGuides": [l, t, r, b] }) } else { json!({ "nineSlice": false }) } } -/// Export Type choices: (value, label). The reference app's default is Movie Clip. -const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic", "Graphic")]; +/// The dialog's rows. `name` is what the name field shows when it has no value. +fn rows(name: &str) -> Vec { + // The reference app's default Export Type is Movie Clip. + let export = vec![("movieClip".to_string(), Label::from(tl!("Movie Clip"))), ("graphic".to_string(), Label::from(tl!("Graphic")))]; + // A dynamic symbol's instances may change the appearance of parts of its art and stay linked. + let kind = vec![("dynamic".to_string(), Label::from(tl!("Dynamic Symbol"))), ("static".to_string(), Label::from(tl!("Static Symbol")))]; + let mut rows = vec![ + Param::new("name", tl!("Name:"), ParamKind::text(name)), + Param::new("exportType", tl!("Export Type:"), ParamKind::choice(export, Some("movieClip".to_string()))), + Param::new("type", tl!("Symbol Type:"), ParamKind::radio(kind, Some("dynamic".to_string()))), + Param::custom("registration", tl!("Registration:"), |ui, fields, _| { + let at = fields.int("registration").and_then(|i| usize::try_from(i).ok()).and_then(|i| Anchor9::ALL.get(i).copied()).unwrap_or(Anchor9::Centre); + let shown = ReferencePoint::new(tl!("Registration:"), Bind::given(at)).look(ReferencePointLook::Squares).show(ui); + if let Some(i) = shown.value().and_then(|picked| Anchor9::ALL.iter().position(|a| a == picked)) { + fields.set("registration", FieldValue::Int(i as i64)); + } + shown.response().clone() + }) + .opens_with(FieldValue::Int(4)), + Param::new("nineSlice", tl!("Enable Guides for 9-Slice Scaling"), ParamKind::bool(false)), + ]; + for (key, label) in SLICE_KEYS.into_iter().zip([tl!("Left:"), tl!("Top:"), tl!("Right:"), tl!("Bottom:")]) { + rows.push( + Param::number(key, label, DEFAULT_SLICE_PERCENT, 1.0, 3) + .unit(UnitKind::Percent) + .bounds(Some(*SLICE_PERCENT_RANGE.start()), Some(*SLICE_PERCENT_RANGE.end())) + .visible_when("nineSlice", true), + ); + } + rows.push(Param::new("alignToPixelGrid", tl!("Align to Pixel Grid"), ParamKind::bool(false))); + rows +} -pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; +/// Opens Symbol Options on `fields`. OK makes a new symbol, or, with `edit` (the symbol being +/// edited), applies the fields to it; `keep_art` leaves the selection as ordinary art for a new one; +/// `opened` are the guides the dialog opened with. +fn open_dialog( + app: &mut VectorcraftApp, + fields: DialogFields, + edit: Option, + keep_art: bool, + opened: [f64; 4], +) -> Result { + let ctx = app.ui_ctx.clone().ok_or("no window")?; + let name = fields.text("name").unwrap_or_default().to_string(); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name))); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> { + let f = &result.fields; + let name = f.text("name").unwrap_or_default().trim().to_string(); + if name.is_empty() { + return Err("name is empty".into()); + } + let from = edit.as_deref().unwrap_or(&name); + let mut params = json!({ + "name": from, + "exportType": f.text("exportType").unwrap_or_default(), + "type": f.text("type").unwrap_or_default(), + "registration": f.int("registration").unwrap_or(4), + "alignToPixelGrid": f.bool("alignToPixelGrid").unwrap_or(false), + }); + merge(&mut params, slice_params(f, opened)); + if edit.is_some() { + if from != name { + params["newName"] = json!(name); + } + app.run("symbol.options", params) + } else { + if keep_art { + params["keepArt"] = json!(true); + } + app.run("symbol.new", params) + } + .map(|_| ()) + }; + crate::dialogs::host::open_held(app, dialog, ok).ok_or("no window")?; + Ok(Value::Null) +} /// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves /// the selection as ordinary art instead of replacing it with an instance. @@ -77,21 +140,14 @@ pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result { if st.selection.is_empty() { return Err("nothing selected".into()); } - let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = json!({ - "name": name, - "exportType": "movieClip", - "type": "dynamic", - "registration": 4, - "alignToPixelGrid": false, - "__edit": false, - "__keepArt": keep_art, - }); - if let Some(o) = fields.as_object_mut() { - o.extend(slice_fields(None)); - } - app.ui.dialog = Some(Dialog::new(KIND, fields)); - Ok(Value::Null) + let mut fields = DialogFields::new(); + fields.set("name", FieldValue::Text(st.doc.unique_symbol_name("New Symbol"))); + fields.set("exportType", FieldValue::Text("movieClip".into())); + fields.set("type", FieldValue::Text("dynamic".into())); + fields.set("registration", FieldValue::Int(4)); + fields.set("alignToPixelGrid", FieldValue::Bool(false)); + let opened = slice_fields(&mut fields, None); + open_dialog(app, fields, None, keep_art, opened) } /// Open Symbol Options on an existing symbol (`name`, else the Symbols panel's current). @@ -113,104 +169,14 @@ pub fn open_edit(app: &mut VectorcraftApp, name: Option<&str>) -> Result bool { - grid(ui, |ui| { - label(ui, tl!("Name:")); - form::text(ui, d, "name", 190.0); - ui.end_row(); - label(ui, tl!("Export Type:")); - let cur = d.str("exportType"); - let shown = EXPORT_TYPES.iter().find(|(v, _)| *v == cur).map_or(EXPORT_TYPES[0].1, |(_, l)| *l); - let labels = EXPORT_TYPES.map(|(_, l)| l); - if let Some((value, _)) = widgets::dropdown(ui, "symbol-export-type", shown, &labels, 190.0).and_then(|i| EXPORT_TYPES.get(i)) { - d.fields.insert("exportType".into(), json!(value)); - } - ui.end_row(); - label(ui, tl!("Symbol Type:")); - // A dynamic symbol's instances may change the appearance of parts of its art and stay linked. - ui.horizontal(|ui| { - let cur = d.str("type"); - for (value, text) in [("dynamic", tl!("Dynamic Symbol")), ("static", tl!("Static Symbol"))] { - if widgets::radio(ui, text, cur == value, true) { - d.fields.insert("type".into(), json!(value)); - } - } - }); - ui.end_row(); - label(ui, tl!("Registration:")); - let cur = d.fields.get("registration").and_then(Value::as_u64).unwrap_or(4) as usize; - if let Some(i) = widgets::reference_point_named(ui, cur, tl!("Registration:")) { - d.fields.insert("registration".into(), json!(i)); - } - ui.end_row(); - label(ui, ""); - form::check(ui, d, "nineSlice", tl!("Enable Guides for 9-Slice Scaling")); - ui.end_row(); - if d.bool("nineSlice") { - for (key, text) in SLICE_KEYS.into_iter().zip([tl!("Left:"), tl!("Top:"), tl!("Right:"), tl!("Bottom:")]) { - label(ui, text); - let v = d.f64(key, DEFAULT_SLICE_PERCENT); - if let Some(n) = widgets::range_field(ui, ("dlg-field", key), v, SLICE_PERCENT_RANGE, "%", 3, 64.0) { - d.fields.insert(key.into(), json!(n)); - } - ui.end_row(); - } - } - label(ui, ""); - form::check(ui, d, "alignToPixelGrid", tl!("Align to Pixel Grid")); - ui.end_row(); - }); - false -} - -/// OK: make a new symbol, or apply name / Export Type / Registration on an existing one. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let name = d.str("name"); - let name = name.trim(); - if name.is_empty() { - return Err("name is empty".into()); - } - let export = d.str("exportType"); - let kind = d.str("type"); - let registration = d.fields.get("registration").and_then(Value::as_u64).unwrap_or(4); - let edit = d.fields.get("__edit").and_then(Value::as_bool).unwrap_or(false); - let pixel = d.bool("alignToPixelGrid"); - let r = if edit { - let from = d.fields.get("__from").and_then(Value::as_str).unwrap_or(name); - let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); - merge(&mut params, slice_params(d)); - if from != name { - params["newName"] = json!(name); - } - app.run("symbol.options", params) - } else { - let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); - merge(&mut params, slice_params(d)); - if d.bool("__keepArt") { - params["keepArt"] = json!(true); - } - app.run("symbol.new", params) - }; - if r.is_ok() { - app.ui.dialog = None; - } - r + let mut fields = DialogFields::new(); + fields.set("name", FieldValue::Text(name.clone())); + fields.set("exportType", FieldValue::Text(export.to_string())); + fields.set("type", FieldValue::Text(kind.into())); + fields.set("registration", FieldValue::Int(registration as i64)); + fields.set("alignToPixelGrid", FieldValue::Bool(st.doc.symbol_pixel_aligned(&name))); + let opened = slice_fields(&mut fields, st.doc.symbol_nine_slice(&name)); + open_dialog(app, fields, Some(name), false, opened) } /// Copy the keys of the object `extra` into the object `into`.