diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs index 52a86dc167..f4770a6419 100644 --- a/crates/ui-egui/src/dialogs/brush_delete.rs +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -2,39 +2,62 @@ //! use, else Remove Strokes or Cancel. Yes and Remove Strokes run `brush.delete`, which leaves the //! strokes that used the brushes as plain strokes. //! -//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use), -//! `params` (the `brush.delete` params) and `__doc` (the uid of the document it asks about). +//! The question is a prompt on the window's dialog host; [`pump`] reads its answer each frame. +use craft_ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; use serde_json::{Value, json}; -use super::{DialogAction, DialogSpec}; use crate::VectorcraftApp; -use crate::state::Dialog; -use crate::widgets; -/// The dialog kind of the Delete Brush question. -pub const KIND: &str = "brushDelete"; +/// The Delete Brush prompt; `StandardPrompt` has one id and one result type for every custom prompt, +/// so each question is a type of its own. +pub struct BrushDeleteQuestion(StandardPrompt); -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |d| d.str("message"), body_with_actions: Some(body), confirm, ok: None, max_width: Some(540.0), ..DialogSpec::FORM }; +// PLAN: assumed `prompt_wrapper!(Wrapper)` in dialogs/confirm.rs (widgets-w10): the delegating +// `impl StackDialog` over the wrapper's one `StandardPrompt` field. +super::confirm::prompt_wrapper!(BrushDeleteQuestion); + +/// What the question is about: the document it was asked in, the `brush.delete` params and whether a +/// stroke uses one of the brushes. +struct BrushDeleteAsk { + doc: Option, + params: Value, + used: bool, +} /// Ask whether to delete the brushes `params` names (`used`: one of them is in use). pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { - let message = if used { - tl!("Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes?") + let Some(dialogs) = app.dialogs() else { + app.status("no window"); + return; + }; + let (message, yes, no) = if used { + ( + tl!("Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes?"), + tl!("Remove Strokes"), + tl!("Cancel"), + ) } else { - tl!("Delete the selected brushes?") + (tl!("Delete the selected brushes?"), tl!("Yes"), tl!("No")) }; let doc = app.session.active().map(|d| d.uid); - app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message, DOC: doc}))); + let prompt = StandardPrompt::custom(message) + .button(PromptChoice::Proceed, yes) + .button(PromptChoice::Cancel, no) + .tag(BrushDeleteAsk { doc, params, used }); + dialogs.with(|host| host.open(BrushDeleteQuestion(prompt))); } -/// The field that holds the uid of the document the question is about. -const DOC: &str = "__doc"; - -/// Whether a stroke uses one of `names` (`brush.unused`), or `None` when the query fails. +/// Whether a stroke uses one of `names` (`brush.unused`). `None` when the query fails: the reason is +/// in the status bar and the caller changes nothing. pub fn used(app: &mut VectorcraftApp, names: &[String]) -> Option { - let unused = app.run("brush.unused", json!({})).ok()?; + let unused = match app.run("brush.unused", json!({})) { + Ok(unused) => unused, + Err(e) => { + app.status(e); + return None; + } + }; let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); Some(names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name)))) } @@ -47,44 +70,35 @@ fn names(params: &Value) -> Vec { } } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { - let mut action = DialogAction::None; - ui.horizontal(|ui| { - if d.bool("used") { - if widgets::primary_button_enabled(ui, tl!("Remove Strokes"), true).clicked() { - action = DialogAction::Confirm; - } - if widgets::secondary_button(ui, tl!("Cancel")).clicked() { - action = DialogAction::Cancel; - } - } else { - if widgets::primary_button_enabled(ui, tl!("Yes"), true).clicked() { - action = DialogAction::Confirm; - } - if widgets::secondary_button(ui, tl!("No")).clicked() { - action = DialogAction::Cancel; - } - } - }); - action +/// Runs the command of the answer the question got this frame. Only Yes and Remove Strokes act. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) else { return }; + if answer.choice != PromptChoice::Proceed { + return; + } + if let Some(ask) = answer.take_tag::() { + confirm(app, ask); + } } -/// Closes before running, so a dialog the command opens stays open. Yes on brushes that a stroke -/// has started to use since the question opened asks again with Remove Strokes and Cancel. When -/// another document has become the active one, it closes as Cancel does and deletes nothing. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); - if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { - app.ui.dialog = None; - return Ok(json!({})); +/// Yes on brushes that a stroke has started to use since the question opened asks again with Remove +/// Strokes and Cancel. When another document has become the active one, nothing is deleted. +fn confirm(app: &mut VectorcraftApp, question: BrushDeleteAsk) { + if question.doc != app.session.active().map(|doc| doc.uid) { + return; } - if !d.bool("used") && used(app, &names(¶ms)) == Some(true) { - ask(app, params, true); - return Ok(json!({})); + if !question.used { + match used(app, &names(&question.params)) { + None => return, + Some(true) => return ask(app, question.params, true), + Some(false) => {} + } + } + if let Err(e) = app.run("brush.delete", question.params) { + app.status(e); } - app.ui.dialog = None; - app.run("brush.delete", params) } #[cfg(test)] -mod tests; +pub(super) mod tests; diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index 4092d63387..d4eb093d5d 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -1,106 +1,88 @@ -use egui::{Pos2, Rect, pos2, vec2}; +use craft_ui::dialog::StackDialog; use serde_json::json; use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; use super::*; -fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec, time: f64) -> egui::FullOutput { - let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); - let input = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); - out.textures_delta.clear(); - out -} - -fn press(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { - frame(ctx, app, vec![], time); - let out = frame(ctx, app, vec![], time + 0.1); - let nodes = &out.platform_output.accesskit_update.as_ref().expect("dialog accessibility tree").nodes; - let button = nodes.iter().find(|(_, node)| node.label().map(str::trim) == Some(label)); - let bounds = button.and_then(|(_, node)| node.bounds()).expect("visible button"); - let at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); - let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true), button(false)], time + 0.2); -} - -fn context() -> egui::Context { - let ctx = egui::Context::default(); - ctx.enable_accesskit(); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, Default::default()); - ctx -} - -#[test] -fn visible_yes_and_no_buttons_control_unused_deletion() { +/// An app with a window context for the dialog host and no document. +pub(in crate::dialogs) fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); - let ctx = context(); - let before = app.session.active().unwrap().history.undo.len(); - ask(&mut app, json!({"name": name}), false); - press(&ctx, &mut app, "No", 0.0); - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.active().unwrap().history.undo.len(), before); - assert!(app.run("brush.get", json!({"name": name})).is_ok()); - ask(&mut app, json!({"name": name}), false); - press(&ctx, &mut app, "Yes", 1.0); - assert!(app.run("brush.get", json!({"name": name})).is_err()); - assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); + app.ui_ctx = Some(egui::Context::default()); + app +} + +/// Answers the open question `D` the way its button does (`Some(choice)`: the button of that choice, +/// `None`: Cancel's close), then runs the module's `pump`. +pub(in crate::dialogs) fn answer(app: &mut VectorcraftApp, choice: Option<&str>, pump: fn(&mut VectorcraftApp, &egui::Context)) { + let ctx = app.ui_ctx.clone().unwrap(); + app.dialogs().unwrap().with(|host| { + let id = host.get::().expect("the question is open").id(); + match choice { + Some(choice) => { + host.set_json_field(&ctx, id, "choice", json!(choice)).unwrap(); + assert!(host.confirm_by_id(&ctx, id)); + } + None => assert!(host.cancel_by_id(&ctx, id)), + } + }); + pump(app, &ctx); +} + +/// The `used` flag of the Delete Brush question that is open, if one is. +fn open_question(app: &VectorcraftApp) -> Option { + app.dialogs().unwrap().with(|host| host.get::().and_then(|q| q.0.tag_as::()).map(|ask| ask.used)) } #[test] fn yes_asks_again_when_a_stroke_started_using_the_brush() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let name = "10 pt. Oval"; - let ctx = context(); ask(&mut app, json!({"names": [name]}), false); let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); app.run("brush.apply", json!({"name": name})).unwrap(); let before = app.session.active().unwrap().history.undo.len(); - press(&ctx, &mut app, "Yes", 0.0); - assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && d.bool("used")), "asks again with Remove Strokes"); + answer::(&mut app, Some("proceed"), pump); + assert_eq!(open_question(&app), Some(true), "asks again with Remove Strokes"); assert_eq!(app.session.active().unwrap().history.undo.len(), before); let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); assert_eq!(stroke.brush.as_deref(), Some(name)); - press(&ctx, &mut app, "Remove Strokes", 1.0); + answer::(&mut app, Some("proceed"), pump); assert!(app.run("brush.get", json!({"name": name})).is_err()); } #[test] fn yes_deletes_nothing_after_another_document_became_active() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); - let ctx = context(); ask(&mut app, json!({"name": name}), false); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); app.run("document.activate", json!({"index": 1})).unwrap(); - press(&ctx, &mut app, "Yes", 0.0); - assert!(app.ui.dialog.is_none()); + answer::(&mut app, Some("proceed"), pump); + assert_eq!(open_question(&app), None); assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the second document keeps the brush"); app.run("document.activate", json!({"index": 0})).unwrap(); assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the first document keeps the brush"); } +/// Remove Strokes runs `brush.delete` and the strokes stay as plain strokes; Cancel changes nothing. #[test] -fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { - for choice in ["Cancel", "Remove Strokes"] { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); +fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() { + for choice in [None, Some("proceed")] { + let mut app = app(); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); let name = "10 pt. Oval"; app.run("brush.apply", json!({"name": name})).unwrap(); let before = app.session.active().unwrap().history.undo.len(); - let ctx = context(); ask(&mut app, json!({"name": name}), true); - press(&ctx, &mut app, choice, 0.0); - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice != "Cancel")); + answer::(&mut app, choice, pump); + assert_eq!(open_question(&app), None); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice.is_some())); let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); - assert_eq!(stroke.brush.as_deref(), (choice == "Cancel").then_some(name)); + assert_eq!(stroke.brush.as_deref(), choice.is_none().then_some(name)); assert!(stroke.width > 0.0); } } diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index f8b25e8249..98b4079c07 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -1,8 +1,8 @@ //! Brush Options (double-click a brush in the Brushes panel, or the panel menu's Brush Options…). //! Calligraphic Brush Options: Name, then Angle, Roundness and Size, each Fixed, Random, Pressure, //! Tilt, Bearing or Rotation with its Variation, over live previews of the nib and of a stroke -//! (light, heavy, light pressure). Bristle Brush Options: Name (typing stops at [`Bristle::MAX_NAME_CHARS`] -//! characters), Shape and the bristle sliders. Scatter, Art and Pattern Brush Options: see +//! (light, heavy, light pressure). Bristle Brush Options: Name (a new bristle brush name that is too +//! long is refused at OK), Shape and the bristle sliders. Scatter, Art and Pattern Brush Options: see //! [`super::brush_art_options`]. OK runs `brush.options` (strokes painted with the brush update); //! a name another brush has, or a new bristle brush name that is too long, keeps the dialog open. //! @@ -25,22 +25,33 @@ //! runs `brush.objectOptions` with the values changed since it opened: the paths change and the //! brush stays as it is. OK after another document has become the active one changes nothing. -use egui::{Color32, Sense, Stroke, pos2, vec2}; +use std::sync::Arc; + +use craft_ui::contract::{Bind, ContentPainterCx, Entry, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::{Picture, PictureSize}; +use craft_ui::form::Field; +use craft_ui::layout_components::Row; +use craft_ui::list::{ThumbAspect, ThumbSize}; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult, SliderScale}; +use craft_ui::pickers::Select; +use craft_ui::runtime::env::{Label, UnitKind}; +use craft_ui::text::NumberField; +use egui::{Color32, Rect, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{Bristle, Brush, BrushKind, Calligraphic, Variation}; -use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; +use vectorcraft_doc::{AppearanceItem, Document, NodeId, NodeKind}; -use super::swatch_options::{grid, label}; -use super::{DialogSpec, brush_art_options, form}; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::{VectorcraftApp, widgets}; +use super::{brush_art_options, form, host}; +use crate::VectorcraftApp; -/// The dialog kind of Brush Options. +// PLAN: the `craft_ui::…` import paths above follow the framework crates' module layout; the app tree +// has no other user of these components yet. `brush_art_options::{params, edited_def, fields, +// reconcile_pattern_choices, heading, rows}` are called with `&DialogFields` where they took `&Dialog`, +// and `app.session.general_unit()` is taken to be the framework's `UnitKind`. + +/// The dialog key of Brush Options. pub const KIND: &str = "brushOptions"; -pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm: ok, min_width: 440.0, inputs: |_| &["tips"], ..DialogSpec::FORM }; - /// The field of a Brush Options dialog that New Brush opened. const CREATE: &str = "__create"; @@ -59,6 +70,9 @@ const OPENED: &str = "__opened"; /// The field of such a dialog holding the uid of the document it opened in. const DOC: &str = "__doc"; +/// The field of such a dialog holding the option keys a path can set for itself. +const KEYS: &str = "__keys"; + /// Calligraphic values: (field, label, suffix, decimals), in [`Calligraphic::RANGES`] order. const CALLI: [(&str, &str, &str, usize); 3] = [("angle", "Angle:", "°", 0), ("roundness", "Roundness:", "%", 0), ("size", "Size:", " pt", 1)]; @@ -85,24 +99,42 @@ const SHAPES: [(&str, &str); 10] = [ ("flatFan", "Flat Fan"), ]; -/// Width of the bristle dialog's label column. -const LABEL_W: f32 = 112.0; +/// The string in field `key`, empty when it has none. +fn string(d: &DialogFields, key: &str) -> String { + d.text(key).unwrap_or_default().to_string() +} -/// Widths of the nib preview and of the whole preview row. -const NIB_W: f32 = 120.0; -const STROKE_W: f32 = 400.0; +/// The flag in field `key`, false when it has none. +fn flag(d: &DialogFields, key: &str) -> bool { + d.bool(key).unwrap_or(false) +} -fn heading(d: &Dialog) -> String { - if d.bool(OBJECT) { - return tl!("Options of Selected Object").into(); - } - match d.str("__type").as_str() { - "bristle" => tl!("Bristle Brush Options").into(), - "calligraphic" => tl!("Calligraphic Brush Options").into(), - ty => brush_art_options::heading(ty).into(), +/// The JSON value a private marker or an edited definition is kept as in field `key`. +fn json<'a>(d: &'a DialogFields, key: &str) -> Option<&'a Value> { + match d.get(key)? { + FieldValue::Json(value) => Some(value), + _ => None, } } +/// The uid of the active document, in the form the `__doc` field keeps it. +fn active_uid(app: &VectorcraftApp) -> Option { + app.session.active().and_then(|doc| i64::try_from(doc.uid).ok()) +} + +/// The title of Brush Options for brush type `ty`. +fn title(ty: &str, object: bool) -> String { + if object { + return tl!("Options of Selected Object").to_string(); + } + match ty { + "bristle" => tl!("Bristle Brush Options").to_string(), + "calligraphic" => tl!("Calligraphic Brush Options").to_string(), + ty => brush_art_options::heading(ty).to_string(), + } +} + +/// The key of the field holding the variation mode of value `key`. pub(super) fn mode_key(key: &str) -> String { format!("{key}Mode") } @@ -125,7 +157,31 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result, object_keys: Option<&[&str]>) -> Result { + let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default(); + let object = object_keys.is_some(); + let ctx = app.ui_ctx.clone().ok_or("no window")?; + // Modal: no edit changes the document while the dialog is open, so the previews read this snapshot. + let doc = app.session.active().map(|st| st.doc.clone()); + let rows = rows(ty, object, doc, app.session.general_unit()); + let title = Label::from(title(ty, object)); + let mut initial = form::fields_of(&rows, f); + if let Some(keys) = object_keys { + let opened = object_params(&initial, keys); + initial.set(OPENED, FieldValue::Json(Value::Object(opened))); + initial.set(KEYS, FieldValue::Json(json!(keys))); + } + // PLAN: `HostedParamDialog::new` takes (ctx, key, fields, build); the sheet's (KIND, title, build) has no such form. + let dialog = + HostedParamDialog::new(&ctx, KIND, initial, move |fields| ParamDialog::new(KIND, title.clone(), rows.clone()).values(Bind::bound(fields))) + .held_ok(); + host::open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -231,16 +287,11 @@ pub fn open_object(app: &mut VectorcraftApp) -> Result { f.insert(OBJECT.into(), json!(true)); f.insert(TARGETS.into(), targets); f.insert(DOC.into(), json!(doc)); - let mut d = Dialog { kind: KIND.into(), fields: f }; - let opened = object_params(&d, b.kind.stroke_option_keys()); - d.fields.insert(OPENED.into(), Value::Object(opened)); - d.fields.insert("__keys".into(), json!(b.kind.stroke_option_keys())); - app.ui.dialog = Some(d); - Ok(Value::Null) + open_dialog(app, &f, Some(b.kind.stroke_option_keys())) } /// The fields' `brush.options` params that a path can set for itself (`keys`). -fn object_params(d: &Dialog, keys: &[&str]) -> Map { +fn object_params(d: &DialogFields, keys: &[&str]) -> Map { match params(d) { Value::Object(p) => p.into_iter().filter(|(k, _)| keys.contains(&k.as_str())).collect(), _ => Map::new(), @@ -262,23 +313,19 @@ fn changed_part(was: Option<&Value>, now: Value) -> Option { } /// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the -/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. When -/// another document has become the active one, it closes as Cancel does and changes nothing. -fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result { - if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { - app.ui.dialog = None; - return Ok(json!({})); +/// values changed since it opened ([`changed_part`]). When another document has become the active +/// one, it closes as Cancel does and changes nothing. +fn confirm_object(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> { + if d.int(DOC) != active_uid(app) { + return Ok(()); } - let keys: Vec = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let keys: Vec = json(d, KEYS).and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); - let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); + let opened = json(d, OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); let changed: Map = object_params(d, &keys).into_iter().filter_map(|(k, v)| changed_part(opened.get(&k), v).map(|v| (k, v))).collect(); - let r = app.run("brush.objectOptions", json!({ "ids": d.fields.get(TARGETS).cloned().unwrap_or_default(), "params": changed })); - if r.is_ok() { - app.ui.dialog = None; - } - r + let targets = json(d, TARGETS).cloned().unwrap_or_default(); + app.run("brush.objectOptions", json!({ "ids": targets, "params": changed })).map(|_| ()) } /// Open the Brush Options of a new brush of type `ty` (`calligraphic` | `scatter` | `art` | @@ -316,18 +363,16 @@ pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option) - if let Some(ids) = ids { f.insert(IDS.into(), ids); } - app.ui.dialog = Some(Dialog { kind: KIND.into(), fields: f }); - Ok(Value::Null) + open_dialog(app, &f, None) } /// OK of a new brush's Brush Options: `brush.new` with the type, the name, the values set, the art /// the dialog opened with (`art` or `side` of `__def`, which the preview draws) and the dropped -/// art's ids. A selection changed or cleared while the dialog is open does not change the art. The -/// dialog closes once the brush is made. -fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result { +/// art's ids. A selection changed or cleared while the dialog is open does not change the art. +fn create(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> { let mut brush_params = params(d); - if d.str("__type") == "pattern" { - if d.str("sideTile") == "none" { + if string(d, "__type") == "pattern" { + if string(d, "sideTile") == "none" { return Err("You must choose a side pattern.".into()); } let preview = brush_art_options::edited_def(d); @@ -355,29 +400,27 @@ fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result { } } } - if let Some(def) = d.fields.get("__def") { + if let Some(def) = json(d, "__def") { for key in ["art", "side"] { if let Some(art) = def.get(key).filter(|v| !v.is_null() && brush_params.get(key).is_none_or(Value::is_null)) { brush_params[key] = art.clone(); } } } - let mut p = json!({ "type": d.str("__type"), "name": d.str("name").trim(), "params": brush_params }); - if let Some(ids) = d.fields.get(IDS) { + let mut p = json!({ "type": string(d, "__type"), "name": string(d, "name").trim(), "params": brush_params }); + if let Some(ids) = json(d, IDS) { p["ids"] = ids.clone(); } - let r = app.run("brush.new", p); - if r.is_ok() { - app.ui.dialog = None; - } - r + app.run("brush.new", p).map(|_| ()) } -/// OK: make the new brush when New Brush opened the dialog, else edit the brush. -fn ok(app: &mut VectorcraftApp, d: &Dialog) -> Result { - if d.bool(CREATE) { +/// OK: make the new brush when New Brush opened the dialog, else edit the brush. A refusal keeps the +/// dialog open with the reason under its rows. +fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { + let d = &answer.fields; + if flag(d, CREATE) { create(app, d) - } else if d.bool(OBJECT) { + } else if flag(d, OBJECT) { confirm_object(app, d) } else { confirm(app, d) @@ -385,30 +428,24 @@ fn ok(app: &mut VectorcraftApp, d: &Dialog) -> Result { } /// The value of field `key` within `range`. -pub(super) fn clamped(d: &Dialog, key: &str, (lo, hi): (f64, f64)) -> f64 { - d.f64(key, lo).clamp(lo, hi) -} - -/// Is `d` Scatter, Art or Pattern Brush Options with Colorization Tips open? Escape then closes -/// Tips, not the dialog. -pub(crate) fn tips_open(d: &Dialog) -> bool { - d.kind == KIND && d.bool("tips") && !matches!(d.str("__type").as_str(), "bristle" | "calligraphic") +pub(super) fn clamped(fields: &DialogFields, key: &str, (lo, hi): (f64, f64)) -> f64 { + fields.number(key).unwrap_or(lo).clamp(lo, hi) } /// The Calligraphic brush the fields describe. -fn calligraphic(d: &Dialog) -> Calligraphic { +fn calligraphic(d: &DialogFields) -> Calligraphic { let value = |i: usize| CALLI.get(i).zip(Calligraphic::RANGES.get(i)).map_or(0.0, |((key, ..), r)| clamped(d, key, *r)); let variation = |i: usize| CALLI.get(i).zip(Calligraphic::MAX_VARIATION.get(i)).map_or(0.0, |((key, ..), max)| clamped(d, &variation_key(key), (0.0, *max))); - let mode = |i: usize| CALLI.get(i).and_then(|(key, ..)| Variation::parse(&d.str(&mode_key(key)))).unwrap_or_default(); + let mode = |i: usize| CALLI.get(i).and_then(|(key, ..)| Variation::parse(&string(d, &mode_key(key)))).unwrap_or_default(); Calligraphic { angle: value(0), roundness: value(1), size: value(2), variation: [0, 1, 2].map(variation), modes: Some([0, 1, 2].map(mode)) } } /// `brush.options` params from the fields. -fn params(d: &Dialog) -> Value { - match d.str("__type").as_str() { +fn params(d: &DialogFields) -> Value { + match string(d, "__type").as_str() { "bristle" => { - let mut p = json!({ "shape": d.str("shape"), "size": clamped(d, "size", Bristle::SIZE_RANGE) }); + let mut p = json!({ "shape": string(d, "shape"), "size": clamped(d, "size", Bristle::SIZE_RANGE) }); for (key, _, range) in BRISTLE { p[key] = json!(clamped(d, key, range)); } @@ -419,92 +456,129 @@ fn params(d: &Dialog) -> Value { } } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - // Options of Selected Object sets a path's settings, not the brush, so it has no name. - if !d.bool(OBJECT) { - grid(ui, |ui| { - label(ui, tl!("Name:")); - let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; - form::text_edit_limited(ui, d, "name", 240.0, max); - ui.end_row(); - }); - ui.add_space(10.0); +/// The rows of Brush Options for brush type `ty`: the Name (not for Options of Selected Object, which +/// sets a path's settings, not the brush) and the type's own rows. `doc` gives the previews the +/// resources (patterns, symbols…) the art uses. +fn rows(ty: &str, object: bool, doc: Option>, unit: UnitKind) -> Vec { + let mut rows = Vec::new(); + if !object { + rows.push(Param::new("name", tl!("Name:"), ParamKind::text(""))); } - match d.str("__type").as_str() { - "bristle" => bristle_body(app, ui, d), - "calligraphic" => calligraphic_body(app, ui, d), - _ => brush_art_options::body(app, ui, d), + match ty { + "bristle" => rows.extend(bristle_rows(doc, unit)), + "calligraphic" => rows.extend(calligraphic_rows(doc)), + _ => rows.extend(brush_art_options::rows(ty, object)), } - false + rows } -fn calligraphic_body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - let c = calligraphic(d); - ui.horizontal(|ui| { - nib_preview(ui, &c, vec2(NIB_W, 84.0)); - ui.add_space(8.0); - stroke_preview(app, ui, "calligraphic", serde_json::to_value(&c).unwrap_or_default(), vec2(STROKE_W - NIB_W - 8.0, 84.0)); +/// The Calligraphic rows: the nib and stroke previews, then Angle, Roundness and Size. +fn calligraphic_rows(doc: Option>) -> Vec { + let values = CALLI.into_iter().enumerate().filter_map(|(i, (key, label, suffix, decimals))| { + let (range, max) = (*Calligraphic::RANGES.get(i)?, *Calligraphic::MAX_VARIATION.get(i)?); + Some(variation_row(key, tl!(label).into(), suffix, decimals, range, max)) }); - ui.add_space(12.0); - egui::Grid::new("brush-options-calli").num_columns(5).spacing([8.0, 8.0]).show(ui, |ui| { - for (i, (key, text, suffix, decimals)) in CALLI.into_iter().enumerate() { - let (Some(&range), Some(&max)) = (Calligraphic::RANGES.get(i), Calligraphic::MAX_VARIATION.get(i)) else { continue }; - label(ui, tl!(text)); - if let Some(v) = widgets::range_field(ui, ("brush-value", key), clamped(d, key, range), range.0..=range.1, suffix, decimals, 64.0) { - d.fields.insert(key.into(), json!(v)); + std::iter::once(preview_row(doc, "calligraphic")).chain(values).collect() +} + +/// The Bristle rows: Shape, Size in the document's unit, the five sliders, then the stroke preview. +fn bristle_rows(doc: Option>, unit: UnitKind) -> Vec { + let shapes = SHAPES.into_iter().map(|(id, label)| (id.to_string(), Label::from(tl!(label)))).collect(); + let (lo, hi) = Bristle::SIZE_RANGE; + let mut rows = vec![ + Param::new("shape", tl!("Shape:"), ParamKind::choice(shapes, Some("roundPoint".into()))), + Param::new("size", tl!("Size:"), ParamKind::number(Some(lo), Some(hi), lo, 1.0, 1)).unit(unit), + ]; + rows.extend(BRISTLE.into_iter().map(|(key, label, (lo, hi))| Param::new(key, tl!(label), ParamKind::range(lo, hi, lo, SliderScale::Linear)))); + rows.push(preview_row(doc, "bristle")); + rows +} + +/// One Calligraphic value: its number, the mode of its variation, and (enabled while the mode is not +/// Fixed) the variation's amount. Automation sets the three fields through the one row. +fn variation_row(key: &'static str, label: Label, suffix: &'static str, decimals: usize, range: (f64, f64), max: f64) -> Param { + let (mode_id, variation_id) = (mode_key(key), variation_key(key)); + let entries: Vec> = Variation::offered(key == "size").iter().map(|m| Entry::new(m.id().to_string(), m.label())).collect(); + let companions = [mode_id.clone(), variation_id.clone()]; + let name = label.clone(); + Param::custom(key, label, move |ui, d, _| { + let mode = string(d, &mode_id); + let mut edits: Vec<(String, FieldValue)> = Vec::new(); + let shown = Row::new().show(ui, |ui, _| { + let typed = NumberField::new(name.clone(), Bind::given(Some(clamped(d, key, range)))) + .range(range.0..=range.1) + .unit(suffix) + .fixed_decimals(decimals as _) + .id_salt("value") + .show(ui); + if let Some(Some(v)) = typed.edit.value() { + edits.push((key.to_string(), FieldValue::Number(v.clamp(range.0, range.1)))); } - let mode = Variation::parse(&d.str(&mode_key(key))).unwrap_or_default(); - let offered = Variation::offered(key == "size"); - let labels: Vec<&str> = offered.iter().map(|m| m.label()).collect(); - if let Some(m) = widgets::dropdown(ui, ("brush-mode", key), mode.label(), &labels, 104.0).and_then(|i| offered.get(i)) { - d.fields.insert(mode_key(key), json!(m.id())); + if let Some(picked) = Select::new(name.clone(), Bind::given(mode.clone()), &entries).id_salt("mode").show(ui).value() { + edits.push((mode_id.clone(), FieldValue::Text(picked.clone()))); } - label(ui, tl!("Variation:")); - let vkey = variation_key(key); - ui.add_enabled_ui(mode != Variation::Fixed, |ui| { - if let Some(v) = widgets::range_field(ui, ("brush-var", key), clamped(d, &vkey, (0.0, max)), 0.0..=max, suffix, decimals, 64.0) { - d.fields.insert(vkey.clone(), json!(v)); + Field::new(tl!("Variation:")).id_salt("variation").show(ui, |ui, _| { + // PLAN: assumed the common `disabled(bool)` builder. + let typed = NumberField::new(tl!("Variation:"), Bind::given(Some(clamped(d, &variation_id, (0.0, max))))) + .range(0.0..=max) + .unit(suffix) + .fixed_decimals(decimals as _) + .disabled(mode == Variation::Fixed.id()) + .id_salt("amount") + .show(ui); + if let Some(Some(v)) = typed.edit.value() { + edits.push((variation_id.clone(), FieldValue::Number(v.clamp(0.0, max)))); } }); - ui.end_row(); + }); + for (field, value) in edits { + d.set(field, value); } - }); + shown.output + }) + .companions(companions) + .full_width() } -fn bristle_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - form::choice(ui, d, "shape", tl!("Shape:"), (LABEL_W, 150.0), &SHAPES); - widgets::label_row(ui, tl!("Size:"), LABEL_W, |ui| { - form::length(ui, d, "size", app.session.general_unit(), 80.0); - }); - let rail = Tokens::get(ui.ctx()).input_border; - for (key, text, (lo, hi)) in BRISTLE { - widgets::label_row(ui, tl!(text), LABEL_W, |ui| form::slider_field_named(ui, d, key, tl!(text), lo..=hi, "%", &|_| rail)); - } - ui.add_space(8.0); - let p = params(d); - stroke_preview(app, ui, "bristle", p, vec2(STROKE_W, 64.0)); +/// The previews: for a Calligraphic brush the nib, and for both types a stroke painted with the brush +/// the fields describe (light, heavy, light pressure), with the resources of `doc`. +fn preview_row(doc: Option>, ty: &'static str) -> Param { + Param::custom("preview", "", move |ui, d, _| { + let nib = (ty == "calligraphic").then(|| calligraphic(d)); + let def = match &nib { + Some(c) => serde_json::to_value(c).unwrap_or_default(), + None => params(d), + }; + let (doc, extent) = (doc.as_deref(), PictureSize::Sample(ThumbSize::Large)); + Row::new() + .show(ui, |ui, _| { + if let Some(c) = &nib { + Picture::painter("", ThumbAspect::new(10, 7), |cx, rect| nib_preview(cx, rect, c)).extent(extent).show(ui); + } + let wide = if nib.is_some() { ThumbAspect::new(34, 10) } else { ThumbAspect::new(48, 10) }; + Picture::painter("", wide, |cx, rect| stroke_preview(cx, rect, doc, ty, def.clone())).extent(extent).show(ui); + }) + .output + }) + .full_width() } /// A stroke painted with the brush the fields describe (type `ty`, definition fields `def`), with -/// the active document's resources (the patterns, symbols… its art uses). -pub(super) fn stroke_preview(app: &VectorcraftApp, ui: &mut egui::Ui, ty: &str, def: Value, size: egui::Vec2) { +/// the resources (the patterns, symbols… its art uses) of `doc`. +pub(super) fn stroke_preview(cx: &ContentPainterCx, rect: Rect, doc: Option<&Document>, ty: &str, def: Value) { let mut def = match def { Value::Object(o) => o, _ => Map::new(), }; def.insert("name".into(), json!("preview")); def.insert("type".into(), json!(ty)); - let (r, _) = ui.allocate_exact_size(size, Sense::hover()); - crate::panels::brushes::definition_chip(ui, r, app.session.active(), &Value::Object(def)); - ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).input_border), egui::StrokeKind::Inside); + crate::panels::brushes::paint_definition(cx, rect, doc, &Value::Object(def)); } /// The nib of `c` at its values (black), and — for values that vary — at their lightest and /// heaviest (grey), on white like the brush previews, its largest nib filling the box. -fn nib_preview(ui: &mut egui::Ui, c: &Calligraphic, size: egui::Vec2) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(size, Sense::hover()); - let p = ui.painter_at(r); +fn nib_preview(cx: &ContentPainterCx, r: Rect, c: &Calligraphic) { + let p = &cx.painter; p.rect_filled(r, 0.0, Color32::WHITE); let guide = Stroke::new(1.0, Color32::from_gray(220)); p.line_segment([pos2(r.left(), r.center().y), pos2(r.right(), r.center().y)], guide); @@ -536,18 +610,13 @@ fn nib_preview(ui: &mut egui::Ui, c: &Calligraphic, size: egui::Vec2) { .collect(); p.add(egui::Shape::convex_polygon(pts, fill, Stroke::NONE)); } - p.rect_stroke(r, 0.0, Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); } /// OK: edit the brush (and rename it). A name another brush has, or a new bristle brush name that /// is too long, keeps the dialog open. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let name = d.str("name").trim().to_string(); - let r = app.run("brush.options", json!({ "name": d.str("__brush"), "newName": name, "params": params(d) })); - if r.is_ok() { - app.ui.dialog = None; - } - r +fn confirm(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> { + let name = string(d, "name").trim().to_string(); + app.run("brush.options", json!({ "name": string(d, "__brush"), "newName": name, "params": params(d) })).map(|_| ()) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs index f1ebf1083f..a770801797 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -4,40 +4,35 @@ //! with `applyToStrokes: false`, which keeps the brush and its strokes as they were and adds a copy //! of the brush with the new art. //! -//! Fields: `name` (the brush), `ids` (the art), `apply` (set by the button pressed) and `__doc` (the -//! uid of the document it asks about). +//! The question is a prompt on the window's dialog host; [`pump`] reads its answer each frame. +use craft_ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; use serde_json::{Value, json}; -use super::{DialogAction, DialogSpec}; use crate::VectorcraftApp; -use crate::state::Dialog; -use crate::widgets; -/// The dialog kind of the question. -pub const KIND: &str = "brushReplaceArt"; +/// The Replace Brush Art prompt; `StandardPrompt` has one id and one result type for every custom +/// prompt, so each question is a type of its own. +pub struct ReplaceArtQuestion(StandardPrompt); -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| { - tl!("Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?") - .to_string() - }, - body_with_actions: Some(body), - confirm, - ok: None, - max_width: Some(540.0), - ..DialogSpec::FORM -}; +// PLAN: assumed `prompt_wrapper!(Wrapper)` in dialogs/confirm.rs (widgets-w10): the delegating +// `impl StackDialog` over the wrapper's one `StandardPrompt` field. +super::confirm::prompt_wrapper!(ReplaceArtQuestion); -/// The field that holds the uid of the document the question is about. -const DOC: &str = "__doc"; +/// What the question is about: the document it was asked in, the brush and the art. +struct ReplaceArtAsk { + doc: Option, + name: String, + ids: Vec, +} /// Replace the art of brush `name` with the objects `ids`: at once when no stroke uses the brush, /// else after asking whether the strokes take the new art. Art the brush cannot take (art with no /// width, say) is refused before anything asks, with the reason in the status bar. pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { let params = json!({"name": name, "ids": ids}); - if super::brush_delete::used(app, &[name.to_string()]) != Some(true) { + let Some(used) = super::brush_delete::used(app, &[name.to_string()]) else { return }; + if !used { if let Err(e) = app.run("brush.replaceArt", params) { app.status(e); } @@ -59,41 +54,44 @@ pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { /// Ask whether the strokes that use brush `name` take the art of the objects `ids`. pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { + let Some(dialogs) = app.dialogs() else { + app.status("no window"); + return; + }; let doc = app.session.active().map(|d| d.uid); - app.ui.dialog = Some(Dialog::new(KIND, json!({"name": name, "ids": ids, "apply": true, DOC: doc}))); + let prompt = StandardPrompt::custom(tl!( + "Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?" + )) + .button(PromptChoice::Proceed, tl!("Apply to Strokes")) + .button(PromptChoice::Alternate, tl!("Leave Strokes")) + .button(PromptChoice::Cancel, tl!("Cancel")) + .tag(ReplaceArtAsk { doc, name: name.to_string(), ids: ids.to_vec() }); + dialogs.with(|host| host.open(ReplaceArtQuestion(prompt))); } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { - let mut action = DialogAction::None; - ui.horizontal(|ui| { - if widgets::primary_button_enabled(ui, tl!("Apply to Strokes"), true).clicked() { - d.fields.insert("apply".into(), json!(true)); - action = DialogAction::Confirm; - } - if widgets::secondary_button(ui, tl!("Leave Strokes")).clicked() { - d.fields.insert("apply".into(), json!(false)); - action = DialogAction::Confirm; - } - if widgets::secondary_button(ui, tl!("Cancel")).clicked() { - action = DialogAction::Cancel; - } - }); - action -} - -/// Closes before running. When another document has become the active one, it closes as Cancel does -/// and changes no brush. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - app.ui.dialog = None; - if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { - return Ok(json!({})); +/// Runs the command of the answer the question got this frame; Cancel and any other close do nothing. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) else { return }; + let apply = match answer.choice { + PromptChoice::Proceed => true, + PromptChoice::Alternate => false, + _ => return, + }; + if let Some(ask) = answer.take_tag::() { + confirm(app, ask, apply); + } +} + +/// Runs `brush.replaceArt`. When another document has become the active one, no brush changes. +fn confirm(app: &mut VectorcraftApp, question: ReplaceArtAsk, apply: bool) { + if question.doc != app.session.active().map(|doc| doc.uid) { + return; + } + let params = json!({"name": question.name, "ids": question.ids, "applyToStrokes": apply}); + if let Err(e) = app.run("brush.replaceArt", params) { + app.status(e); } - let params = json!({ - "name": d.fields.get("name").cloned().unwrap_or(Value::Null), - "ids": d.fields.get("ids").cloned().unwrap_or_else(|| json!([])), - "applyToStrokes": d.bool("apply"), - }); - app.run("brush.replaceArt", params) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs index f42b7805c2..054e24a6b6 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art/tests.rs @@ -1,37 +1,9 @@ -use egui::{Pos2, Rect, pos2, vec2}; use serde_json::json; use vectorcraft_doc::NodeId; -use vectorcraft_engine::Session; +use super::super::brush_delete::tests::{answer, app}; use super::*; -fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec, time: f64) -> egui::FullOutput { - let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); - let input = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); - out.textures_delta.clear(); - out -} - -fn press(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { - frame(ctx, app, vec![], time); - let out = frame(ctx, app, vec![], time + 0.1); - let nodes = &out.platform_output.accesskit_update.as_ref().expect("dialog accessibility tree").nodes; - let button = nodes.iter().find(|(_, node)| node.label().map(str::trim) == Some(label)); - let bounds = button.and_then(|(_, node)| node.bounds()).expect("visible button"); - let at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); - let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true), button(false)], time + 0.2); -} - -fn context() -> egui::Context { - let ctx = egui::Context::default(); - ctx.enable_accesskit(); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, Default::default()); - ctx -} - fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 { app.run("shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap() } @@ -41,6 +13,11 @@ fn art_height(app: &mut VectorcraftApp, name: &str) -> f64 { art.geometric_bounds().unwrap().height() } +/// Is the Replace Brush Art question open? +fn asks(app: &VectorcraftApp) -> bool { + app.dialogs().unwrap().with(|host| host.get::().is_some()) +} + /// An art brush "Bar" (40 × 8 pt) painting a path, and a 40 × 20 pt rectangle: → (path, rectangle). fn used_brush(app: &mut VectorcraftApp) -> (NodeId, u64) { app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); @@ -53,63 +30,51 @@ fn used_brush(app: &mut VectorcraftApp) -> (NodeId, u64) { #[test] fn an_unused_brush_takes_the_art_without_asking() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); let bar = rect(&mut app, 10.0, 10.0, 40.0, 8.0); app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [bar]})).unwrap(); let tall = rect(&mut app, 10.0, 40.0, 40.0, 20.0); replace(&mut app, "Bar", &[tall]); - assert!(app.ui.dialog.is_none()); + assert!(!asks(&app)); assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6); } +/// Each answer of the question runs its command: Apply to Strokes gives the brush the new art and +/// the strokes redraw with it, Leave Strokes adds a copy and keeps the brush, Cancel changes nothing. #[test] -fn apply_to_strokes_gives_the_brush_the_new_art() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let (path, tall) = used_brush(&mut app); - replace(&mut app, "Bar", &[tall]); - assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND), "strokes use Bar: it asks"); - let ctx = context(); - let before = app.session.active().unwrap().history.undo.len(); - press(&ctx, &mut app, "Apply to Strokes", 0.0); - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); - assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6); - let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); - assert_eq!(stroke.brush.as_deref(), Some("Bar")); -} - -#[test] -fn leave_strokes_adds_a_copy_and_cancel_changes_nothing() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let (path, tall) = used_brush(&mut app); - let ctx = context(); - let before = app.session.active().unwrap().history.undo.len(); - replace(&mut app, "Bar", &[tall]); - press(&ctx, &mut app, "Cancel", 0.0); - assert!(app.ui.dialog.is_none()); - assert_eq!(app.session.active().unwrap().history.undo.len(), before); - assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); - replace(&mut app, "Bar", &[tall]); - press(&ctx, &mut app, "Leave Strokes", 1.0); - assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); - assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "Bar stays as it was"); - assert!((art_height(&mut app, "Bar copy") - 20.0).abs() < 1e-6); - let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); - assert_eq!(stroke.brush.as_deref(), Some("Bar")); +fn each_answer_runs_its_command() { + // (answer, undo steps added, height of Bar, height of Bar copy) + let table = [(Some("proceed"), 1, 20.0, None), (Some("alternate"), 1, 8.0, Some(20.0)), (None, 0, 8.0, None)]; + for (choice, steps, bar, copy) in table { + let mut app = app(); + let (path, tall) = used_brush(&mut app); + let before = app.session.active().unwrap().history.undo.len(); + replace(&mut app, "Bar", &[tall]); + assert!(asks(&app), "strokes use Bar: it asks"); + answer::(&mut app, choice, pump); + assert!(!asks(&app)); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + steps, "{choice:?}"); + assert!((art_height(&mut app, "Bar") - bar).abs() < 1e-6, "{choice:?}"); + if let Some(copy) = copy { + assert!((art_height(&mut app, "Bar copy") - copy).abs() < 1e-6); + } + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), Some("Bar"), "{choice:?}"); + } } /// Art a used brush cannot take is refused before the question: no dialog, the reason in the status /// bar, and the document and its undo history as they were. #[test] fn art_with_no_width_is_refused_before_it_asks() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); let _ = used_brush(&mut app); let flat = app.run("shape.line", json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap(); let st = app.session.active().unwrap(); let (doc, steps) = (st.doc.clone(), st.history.undo.len()); replace(&mut app, "Bar", &[flat]); - assert!(app.ui.dialog.is_none(), "nothing asks"); + assert!(!asks(&app), "nothing asks"); assert!(app.ui.status.contains("the selected art has no width"), "{}", app.ui.status); let st = app.session.active().unwrap(); assert!(st.interaction.is_none()); @@ -119,15 +84,14 @@ fn art_with_no_width_is_refused_before_it_asks() { #[test] fn a_button_changes_no_brush_after_another_document_became_active() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); let (_, tall) = used_brush(&mut app); - let ctx = context(); replace(&mut app, "Bar", &[tall]); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); app.run("document.activate", json!({"index": 0})).unwrap(); app.run("document.activate", json!({"index": 1})).unwrap(); - press(&ctx, &mut app, "Apply to Strokes", 0.0); - assert!(app.ui.dialog.is_none()); + answer::(&mut app, Some("proceed"), pump); + assert!(!asks(&app)); app.run("document.activate", json!({"index": 0})).unwrap(); assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6); } diff --git a/crates/ui-egui/src/dialogs/new_brush.rs b/crates/ui-egui/src/dialogs/new_brush.rs index 6ec926c07c..0e7f012ab7 100644 --- a/crates/ui-egui/src/dialogs/new_brush.rs +++ b/crates/ui-egui/src/dialogs/new_brush.rs @@ -3,21 +3,21 @@ //! dropped. OK opens that type's Brush Options for the new brush //! ([`super::brush_options::open_new`]), whose OK makes it; Cancel makes nothing. //! -//! Fields: `type` (`calligraphic` | `scatter` | `art` | `bristle` | `pattern`), `__art` (art is -//! selected or was dropped) and `__ids` (the ids of the dropped art; without it, the selection's). +//! Fields: `type` (`calligraphic` | `scatter` | `art` | `bristle` | `pattern`) and `__art` (art is +//! selected or was dropped). The ids of the dropped art (without them, the selection's) stay with +//! the dialog's OK. +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::Label; use serde_json::{Value, json}; -use super::{DialogSpec, brush_options}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use super::{brush_options, host}; +use crate::VectorcraftApp; -/// The dialog kind of New Brush. +/// The dialog key of New Brush. pub const KIND: &str = "newBrush"; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("New Brush").into(), body, confirm, ok_enabled: Some(ok_enabled), min_width: 300.0, ..DialogSpec::FORM }; - /// The brush types, in the Brushes panel's order. const TYPES: [&str; 5] = ["calligraphic", "scatter", "art", "bristle", "pattern"]; @@ -29,11 +29,16 @@ pub fn open(app: &mut VectorcraftApp, ids: Option) -> Result ids.as_array().is_some_and(|a| !a.is_empty()), None => !st.selection.is_empty(), }; - let mut f = json!({ "type": if art { "art" } else { "calligraphic" }, "__art": art }); - if let Some(ids) = ids { - f["__ids"] = ids; - } - app.ui.dialog = Some(Dialog::new(KIND, f)); + let ctx = app.ui_ctx.clone().ok_or("no window")?; + let fields = DialogFields::from_pairs([ + ("type", FieldValue::Text(if art { "art" } else { "calligraphic" }.into())), + ("__art", FieldValue::Bool(art)), + ]); + let (rows, title) = (params(art), Label::from(tl!("New Brush"))); + // PLAN: `HostedParamDialog::new` takes (ctx, key, fields, build); the sheet's (KIND, title, build) has no such form. + let dialog = + HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), rows.clone()).values(Bind::bound(f))).held_ok(); + host::open_held(app, dialog, move |app, answer| confirm(app, &answer.fields, ids.clone())).ok_or("no window")?; Ok(Value::Null) } @@ -43,60 +48,49 @@ fn needs_art(ty: &str) -> bool { } /// The type the fields choose: `type`, or Calligraphic when it names none. -fn chosen(d: &Dialog) -> &'static str { - let ty = d.str("type"); +fn chosen(d: &DialogFields) -> &'static str { + let ty = d.text("type").unwrap_or_default(); TYPES.into_iter().find(|t| *t == ty).unwrap_or("calligraphic") } -fn ok_enabled(_: &VectorcraftApp, d: &Dialog) -> bool { - d.bool("__art") || !needs_art(chosen(d)) -} - -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// The rows: the five types, those that need art off when there is none, and the note that says why. +fn params(art: bool) -> Vec { let labels = [tl!("Calligraphic Brush"), tl!("Scatter Brush"), tl!("Art Brush"), tl!("Bristle Brush"), tl!("Pattern Brush")]; - let (art, cur) = (d.bool("__art"), chosen(d)); - for (ty, label) in TYPES.into_iter().zip(labels) { - if widgets::radio(ui, label, cur == ty, art || !needs_art(ty)) { - d.fields.insert("type".into(), json!(ty)); - } - } + let options = TYPES.into_iter().zip(labels).map(|(ty, label)| (ty.to_string(), Label::from(label))).collect(); + let mut kind = Param::new("type", "", ParamKind::radio(options, Some("calligraphic".into()))); if !art { - ui.add_space(6.0); - widgets::dim_label(ui, tl!("Select art to make a scatter, art or pattern brush.")); + kind = kind.disabled_options(TYPES.into_iter().filter(|ty| needs_art(ty))); } - false + vec![ + kind, + Param::read_only_text("note", "", tl!("Select art to make a scatter, art or pattern brush.")).full_width().visible_when("__art", false), + ] } /// OK: the chosen type's Brush Options for the new brush. A type that needs art, without art, -/// keeps the dialog open. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { +/// keeps the dialog open (automation can set such a type without art). +fn confirm(app: &mut VectorcraftApp, d: &DialogFields, ids: Option) -> Result<(), String> { let ty = chosen(d); - if needs_art(ty) && !d.bool("__art") { + if needs_art(ty) && !d.bool("__art").unwrap_or(false) { return Err("nothing selected".into()); } - brush_options::open_new(app, ty, d.fields.get("__ids").cloned()) + brush_options::open_new(app, ty, ids).map(|_| ()) } #[cfg(test)] mod tests { + use craft_ui::dialog::StackDialog; use vectorcraft_engine::Session; use super::*; - use crate::widgets::accessibility_tests::{named, tree}; fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(egui::Context::default()); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app } - fn set(app: &mut VectorcraftApp, fields: Value) { - let d = app.ui.dialog.as_mut().unwrap(); - for (k, v) in fields.as_object().unwrap() { - d.fields.insert(k.clone(), v.clone()); - } - } - fn library(app: &mut VectorcraftApp) -> Vec<(String, String)> { crate::panels::brushes::brushes(app).0 } @@ -105,29 +99,29 @@ mod tests { app.session.active().unwrap().history.undo.len() } - /// Which of the five types screen readers find on, in the dialog's order. - fn types_on(app: &mut VectorcraftApp) -> Vec { - let t = tree(|ui| super::super::show(app, ui.ctx())); - ["Calligraphic Brush", "Scatter Brush", "Art Brush", "Bristle Brush", "Pattern Brush"].map(|l| !named(&t, l).is_disabled()).to_vec() + /// The values of the open hosted dialog. + fn open_fields(app: &VectorcraftApp) -> DialogFields { + app.dialogs().unwrap().with(|h| h.get::().expect("a hosted dialog is open").fields().clone()) } - /// With nothing selected, Scatter, Art and Pattern are off, New Brush starts on Calligraphic, - /// and OK on one of them keeps the dialog open. With art selected, every type is on and New - /// Brush starts on Art. - #[test] - fn scatter_art_and_pattern_brushes_need_art() { - let mut app = app(); - app.run("ui.newBrush", json!({})).unwrap(); - assert_eq!(types_on(&mut app), [true, false, false, true, false]); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("type"), "calligraphic"); - set(&mut app, json!({"type": "art"})); - assert_eq!(super::super::confirm(&mut app), Err("nothing selected".into())); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); - app.ui.dialog = None; - app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); - app.run("ui.newBrush", json!({})).unwrap(); - assert_eq!(types_on(&mut app), [true; 5]); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("type"), "art"); + fn is_open(app: &VectorcraftApp) -> bool { + app.dialogs().unwrap().with(|h| h.get::().is_some()) + } + + /// Sets `values` on the open hosted dialog, presses OK, then runs the held-dialog pump and a frame, + /// which closes the dialog the answer was for. + fn press_ok(app: &mut VectorcraftApp, values: Value) { + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + host.with(|h| { + let id = h.get::().expect("a hosted dialog is open").id(); + for (key, value) in values.as_object().unwrap() { + h.set_json_field(&ctx, id, key, value.clone()).unwrap(); + } + assert!(h.confirm_by_id(&ctx, id)); + }); + super::super::host::pump(app, &ctx); + let _ = ctx.run_ui(Default::default(), |ui| host.with(|h| h.run(ui))); } /// OK opens the chosen type's Brush Options for a new brush, named New Brush; their OK @@ -138,18 +132,14 @@ mod tests { app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); let (before, steps) = (library(&mut app), undo_steps(&app)); app.run("ui.newBrush", json!({})).unwrap(); - set(&mut app, json!({"type": "scatter"})); - super::super::confirm(&mut app).unwrap(); - let d = app.ui.dialog.as_ref().expect("Scatter Brush Options"); - assert_eq!((d.kind.as_str(), d.str("__type"), d.str("name")), (super::brush_options::KIND, "scatter".into(), "New Scatter Brush".into())); - assert!(d.fields["__def"]["art"].is_object(), "the selected art, for the preview"); - let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); - assert!(text.contains("Scatter Brush Options") && text.contains("Spacing:"), "{text}"); + press_ok(&mut app, json!({"type": "scatter"})); + let d = open_fields(&app); + assert_eq!((d.text("__type"), d.text("name")), (Some("scatter"), Some("New Scatter Brush"))); + assert!(matches!(d.get("__def"), Some(FieldValue::Json(def)) if def["art"].is_object()), "the selected art, for the preview"); assert_eq!(library(&mut app), before, "no brush until OK"); // The name is trimmed, and a name another brush has gets a number, as `brush.new` gives it. - set(&mut app, json!({"name": " Dots ", "sizeMin": 40, "spacingMin": 150})); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + press_ok(&mut app, json!({"name": " Dots ", "sizeMin": 40, "spacingMin": 150})); + assert!(!is_open(&app)); assert_eq!(library(&mut app)[before.len()..], [("Dots 2".to_string(), "scatter".to_string())]); let def = app.run("brush.get", json!({"name": "Dots 2"})).unwrap(); assert_eq!((&def["size"][0], &def["spacing"][0]), (&json!(40.0), &json!(150.0))); @@ -157,11 +147,9 @@ mod tests { assert_eq!(undo_steps(&app), steps + 1); // A Calligraphic brush, with no art. app.run("ui.newBrush", json!({})).unwrap(); - set(&mut app, json!({"type": "calligraphic"})); - super::super::confirm(&mut app).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("name"), "New Calligraphic Brush"); - set(&mut app, json!({"size": 9})); - super::super::confirm(&mut app).unwrap(); + press_ok(&mut app, json!({"type": "calligraphic"})); + assert_eq!(open_fields(&app).text("name"), Some("New Calligraphic Brush")); + press_ok(&mut app, json!({"size": 9})); let def = app.run("brush.get", json!({"name": "New Calligraphic Brush"})).unwrap(); assert_eq!((&def["type"], &def["size"]), (&json!("calligraphic"), &json!(9.0))); } @@ -175,41 +163,21 @@ mod tests { let mut app = app(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); app.run("ui.newBrush", json!({})).unwrap(); - set(&mut app, json!({"type": ty})); - super::super::confirm(&mut app).unwrap(); - let captured = app.ui.dialog.as_ref().unwrap().fields["__def"][key].clone(); + press_ok(&mut app, json!({"type": ty})); + let Some(FieldValue::Json(def)) = open_fields(&app).get("__def").cloned() else { panic!("{ty}: no definition") }; + let captured = def[key].clone(); assert!(captured.is_object(), "{ty}"); if change == "select.set" { app.run("shape.ellipse", json!({"x": 100, "y": 50, "width": 120, "height": 90})).unwrap(); } else { app.run("select.none", json!({})).unwrap(); } - super::super::confirm(&mut app).unwrap_or_else(|e| panic!("{ty} after {change}: {e}")); - assert!(app.ui.dialog.is_none(), "{ty} after {change}"); + press_ok(&mut app, json!({})); + assert!(!is_open(&app), "{ty} after {change}"); let name = format!("New {}{} Brush", ty[..1].to_uppercase(), &ty[1..]); let def = app.run("brush.get", json!({ "name": name })).unwrap(); assert_eq!(def[key], captured, "{ty} after {change}"); } } } - - /// Cancel in New Brush, or in the Brush Options it opens, adds no brush and no undo step. - #[test] - fn cancel_adds_no_brush() { - let mut app = app(); - app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); - let before = (library(&mut app), undo_steps(&app)); - app.run("ui.newBrush", json!({})).unwrap(); - super::super::cancel(&mut app); - assert!(app.ui.dialog.is_none()); - for ty in TYPES { - app.run("ui.newBrush", json!({})).unwrap(); - set(&mut app, json!({"type": ty})); - super::super::confirm(&mut app).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::brush_options::KIND), "{ty}"); - super::super::cancel(&mut app); - assert!(app.ui.dialog.is_none(), "{ty}"); - assert_eq!((library(&mut app), undo_steps(&app)), before, "{ty}"); - } - } }