diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs
index a3142fd01f..47b3928b06 100644
--- a/crates/ui-egui/src/dialogs/envelope.rs
+++ b/crates/ui-egui/src/dialogs/envelope.rs
@@ -13,18 +13,33 @@
//!
//! The Control bar's envelope controls ([`control_bar`]) live here too.
//!
-//! Every dialog also has `preview`. They open with the selected envelope's values
-//! (`object.envelope.info`); the menu items and shortcuts of Make with Warp and Make with Mesh
-//! open the Reset variant while an envelope is selected, as the reference app's do.
+//! They open with the selected envelope's values (`object.envelope.info`); the menu items and
+//! shortcuts of Make with Warp and Make with Mesh open the Reset variant while an envelope is
+//! selected, as the reference app's do.
-use serde_json::{Value, json};
+use std::ops::RangeInclusive;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use craft::behavior::IconId;
+use craft::ui::buttons::{Button, IconButton};
+use craft::ui::choice::{Radio, RadioGroup};
+use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, clicked};
+use craft::ui::dialog::DialogId;
+use craft::ui::display::Divider;
+use craft::ui::form::Field;
+use craft::ui::layout_components::Row;
+use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
+use craft::ui::pickers::Select;
+use craft::ui::runtime::env::Label;
+use craft::ui::text::NumberField;
+use serde_json::{Map, Value, json};
use vectorcraft_doc::{EnvelopeKind, NodeKind};
-use vectorcraft_render::effects::WARP_STYLES;
-use super::{DialogSpec, form};
-use crate::state::Dialog;
-use crate::theme::Tokens;
-use crate::{VectorcraftApp, widgets};
+use super::form::{fields_of, json_of};
+use super::host::{HeldOptions, open_held_with};
+use super::preview::LivePreview;
+use super::warp_effect::{percent_param, row_label, static_style, style_entries, style_param};
+use crate::VectorcraftApp;
/// The dialog kinds.
pub const WARP: &str = "envelopeWarp";
@@ -37,19 +52,79 @@ const MAKE_MESH: &str = "object.envelope.makeWithMesh";
const RESET_MESH: &str = "object.envelope.resetWithMesh";
const OPTIONS_CMD: &str = "object.envelope.options";
-/// Width of the label column.
-const LABEL_W: f32 = 84.0;
+/// Counts the opens, so a held Cancel of an earlier dialog leaves a later one's preview alone.
+static OPENED: AtomicU64 = AtomicU64::new(0);
-pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, preview: true, min_width: 340.0, ..DialogSpec::FORM };
+/// The open envelope dialog and the preview it keeps on the canvas.
+pub(crate) struct Open {
+ /// The hosted dialog.
+ pub id: DialogId,
+ /// Which of the three dialogs it is.
+ pub kind: &'static str,
+ /// The envelope the dialog previews.
+ pub preview: LivePreview,
+ // PLAN: ef.C11's `Open` has no `generation`; the same kind reopened has the same id, so the id cannot tell the held Cancel of the replaced dialog from the new one's.
+ /// Which open this is ([`OPENED`]).
+ pub generation: u64,
+}
-fn heading(d: &Dialog) -> String {
- match d.kind.as_str() {
- WARP => tl!("Warp Options"),
- MESH if d.bool("reset") => tl!("Reset Envelope Mesh"),
- MESH => tl!("Envelope Mesh"),
- _ => tl!("Envelope Options"),
+/// The dialog's title.
+fn heading(kind: &str, reset: bool) -> Label {
+ Label::from(
+ match kind {
+ WARP => tl!("Warp Options"),
+ MESH if reset => tl!("Reset Envelope Mesh"),
+ MESH => tl!("Envelope Mesh"),
+ _ => tl!("Envelope Options"),
+ }
+ .to_string(),
+ )
+}
+
+/// A whole-number row clamped to 1..50.
+fn count(key: &str, label: Label) -> Param {
+ Param::new(key, label, ParamKind::int(Some(1), Some(50), 4))
+}
+
+/// A check box row.
+fn check(key: &str, label: Label, default: bool) -> Param {
+ Param::new(key, label, ParamKind::bool(default))
+}
+
+/// A group of radio buttons without a title over `(id, label)` options.
+fn choices(key: &str, options: [(&str, Label); 2]) -> Param {
+ let options = options.into_iter().map(|(id, label)| (id.to_owned(), label)).collect();
+ Param::new(key, Label::Empty, ParamKind::radio(options, None))
+}
+
+/// The rows of the dialog `kind`.
+fn params(kind: &str, fields: &DialogFields) -> Vec {
+ match kind {
+ WARP => vec![
+ style_param("style", fields.text("style").unwrap_or("arc")),
+ choices("horizontal", [("horizontal", row_label(tl!("Horizontal"))), ("vertical", row_label(tl!("Vertical")))]),
+ percent_param("bend", row_label(tl!("Bend:")), 50.0),
+ Param::section(row_label(tl!("Distortion"))),
+ percent_param("h", row_label(tl!("Horizontal:")), 0.0),
+ percent_param("v", row_label(tl!("Vertical:")), 0.0),
+ ],
+ MESH => vec![
+ count("rows", row_label(tl!("Rows:"))),
+ count("cols", row_label(tl!("Columns:"))),
+ check("maintainShape", row_label(tl!("Maintain Envelope Shape")), true).visible_when("reset", true),
+ ],
+ _ => vec![
+ Param::section(row_label(tl!("Rasters"))),
+ check("antiAlias", row_label(tl!("Anti-Alias")), true),
+ Param::section(row_label(tl!("Preserve Shape Using:"))),
+ choices("preserveShape", [("clippingMask", row_label(tl!("Clipping Mask"))), ("transparency", row_label(tl!("Transparency")))]),
+ Param::new("fidelity", row_label(tl!("Fidelity:")), ParamKind::range(0.0, 100.0, 50.0, craft::ui::value_drag::SliderScale::Linear)),
+ check("distortAppearance", row_label(tl!("Distort Appearance")), false),
+ // Gradients and patterns bend only with the appearance.
+ check("distortLinearGradients", row_label(tl!("Distort Linear Gradients")), false).enabled_when("distortAppearance", true),
+ check("distortPatternFills", row_label(tl!("Distort Pattern Fills")), false).enabled_when("distortAppearance", true),
+ ],
}
- .into()
}
/// Does the menu item of command `id` open one of these dialogs?
@@ -71,18 +146,15 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result {
let own = |k: &str, d: f64| if warp { num(k, d) } else { d };
let style = if warp { info["style"].clone() } else { json!("arc") };
let horizontal = !warp || info["horizontal"] != false;
- (
- WARP,
- json!({"reset": envelope, "style": style, "horizontal": horizontal, "bend": own("bend", 50.0), "h": own("h", 0.0), "v": own("v", 0.0), "preview": true}),
- )
+ (WARP, json!({"reset": envelope, "style": style, "horizontal": horizontal, "bend": own("bend", 50.0), "h": own("h", 0.0), "v": own("v", 0.0)}))
}
MAKE_MESH | RESET_MESH => {
let mesh = info["type"] == "mesh";
- let own = |k: &str| if mesh { num(k, 4.0) } else { 4.0 };
- (MESH, json!({"reset": envelope, "rows": own("rows"), "cols": own("cols"), "maintainShape": true, "preview": true}))
+ let own = |k: &str| if mesh { info[k].as_i64().unwrap_or(4) } else { 4 };
+ (MESH, json!({"reset": envelope, "rows": own("rows"), "cols": own("cols"), "maintainShape": true}))
}
OPTIONS_CMD => {
- let mut f = json!({"__envelope": envelope, "preview": envelope});
+ let mut f = json!({"__envelope": envelope});
for k in ["antiAlias", "preserveShape", "fidelity", "distortAppearance", "distortLinearGradients", "distortPatternFills"] {
f[k] = info[k].clone();
}
@@ -90,138 +162,102 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result {
}
_ => return Err(format!("`{id}` has no envelope dialog")),
};
- app.ui.dialog = Some(Dialog::new(kind, fields));
+ open_dialog(app, kind, fields.as_object().cloned().unwrap_or_default(), envelope)
+}
+
+/// Opens the hosted dialog `kind` over `values`, replacing an open envelope dialog; with no envelope selected the
+/// Options dialog sets the defaults for new envelopes and has nothing to preview.
+fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map, envelope: bool) -> Result {
+ let ctx = app.ui_ctx.clone().ok_or("no window")?;
+ if let Some(previous) = app.effect_dialogs.envelope.take() {
+ previous.preview.cancel(app);
+ if let Some(dialogs) = app.dialogs() {
+ dialogs.with(|host| host.cancel_by_id(&ctx, previous.id));
+ }
+ }
+ let fields = fields_of(¶ms(kind, &DialogFields::new()), &values);
+ let dialog = HostedParamDialog::command(&ctx, kind, fields, move |fields| {
+ let reset = fields.bool("reset").unwrap_or(false);
+ ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope)
+ });
+ let generation = OPENED.fetch_add(1, Ordering::Relaxed);
+ let cancel = Box::new(move |app: &mut VectorcraftApp| {
+ if app.effect_dialogs.envelope.as_ref().is_some_and(|open| open.generation == generation)
+ && let Some(open) = app.effect_dialogs.envelope.take()
+ {
+ open.preview.cancel(app);
+ }
+ });
+ let ok = move |app: &mut VectorcraftApp, result: &ParamResult| accept(app, kind, result);
+ let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
+ app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
Ok(Value::Null)
}
+/// OK: keeps the preview as one undo step. A refused command keeps the dialog open.
+fn accept(app: &mut VectorcraftApp, kind: &'static str, result: &ParamResult) -> Result<(), String> {
+ let (cmd, p, _) = command(kind, &json_of(¶ms(kind, &result.fields), &result.fields));
+ let Some(Open { id, generation, preview, .. }) = app.effect_dialogs.envelope.take() else {
+ return Err("the envelope dialog is gone".into());
+ };
+ match preview.commit(app, cmd, p) {
+ Ok(_) => Ok(()),
+ Err(e) => {
+ // The attempt ended the preview; the next pass starts a new one over the same values. Nothing to undo
+ // when no interaction was open, so the answer is not needed.
+ let _ = app.session.cancel_interaction();
+ app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
+ Err(e)
+ }
+ }
+}
+
/// The command OK runs, its parameters and the preview's undo label.
-fn command(d: &Dialog) -> (&'static str, Value, &'static str) {
- let reset = d.bool("reset");
- match d.kind.as_str() {
+fn command(kind: &str, f: &Map) -> (&'static str, Value, &'static str) {
+ let num = |k: &str, d: f64| f.get(k).and_then(Value::as_f64).unwrap_or(d);
+ let flag = |k: &str, d: bool| f.get(k).and_then(Value::as_bool).unwrap_or(d);
+ let reset = flag("reset", false);
+ match kind {
WARP => {
- let p = json!({"style": d.str("style"), "horizontal": d.bool("horizontal"), "bend": d.f64("bend", 50.0), "h": d.f64("h", 0.0), "v": d.f64("v", 0.0)});
+ let style = f.get("style").and_then(Value::as_str).unwrap_or("arc");
+ let p = json!({"style": style, "horizontal": flag("horizontal", true), "bend": num("bend", 50.0), "h": num("h", 0.0), "v": num("v", 0.0)});
if reset { (RESET_WARP, p, "Reset with Warp") } else { (MAKE_WARP, p, "Make Envelope") }
}
MESH => {
- let p = json!({"rows": d.f64("rows", 4.0), "cols": d.f64("cols", 4.0)});
+ let p = json!({"rows": num("rows", 4.0), "cols": num("cols", 4.0)});
if reset {
let mut p = p;
- p["maintainShape"] = json!(d.bool("maintainShape"));
+ p["maintainShape"] = json!(flag("maintainShape", true));
(RESET_MESH, p, "Reset with Mesh")
} else {
(MAKE_MESH, p, "Make Envelope")
}
}
_ => {
- let mut p = json!({"fidelity": d.f64("fidelity", 50.0), "preserveShape": d.str("preserveShape")});
+ let preserve = f.get("preserveShape").and_then(Value::as_str).unwrap_or("clippingMask");
+ let mut p = json!({"fidelity": num("fidelity", 50.0), "preserveShape": preserve});
for k in ["antiAlias", "distortAppearance", "distortLinearGradients", "distortPatternFills"] {
- p[k] = json!(d.bool(k));
+ p[k] = json!(flag(k, false));
}
(OPTIONS_CMD, p, "Envelope Options")
}
}
}
-fn set(d: &mut Dialog, key: &str, v: Value) {
- d.fields.insert(key.into(), v);
-}
-
-/// A −100..100 % slider row.
-fn percent(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) {
- let rail = Tokens::get(ui.ctx()).input_border;
- form::slider_w(ui, d, (key, label, LABEL_W), -100.0..=100.0, "%", &move |_| rail);
-}
-
-/// A whole number field row clamped to 1..50.
-fn count(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) {
- widgets::label_row(ui, label, LABEL_W, |ui| {
- if let Some(n) = widgets::range_field(ui, ("env-count", key), d.f64(key, 4.0), 1.0..=50.0, "", 0, 60.0) {
- set(d, key, json!(n));
- }
+/// Runs the preview of the open envelope dialog from its values, once per frame: its Preview box decides whether the
+/// canvas shows them. The dialog's Cancel rolls the preview back through the held record's cancel.
+pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
+ let Some(mut open) = app.effect_dialogs.envelope.take() else { return };
+ let shown = app.dialogs().and_then(|dialogs| {
+ dialogs.with(|host| host.get_mut_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))
});
-}
-
-fn warp_body(ui: &mut egui::Ui, d: &mut Dialog) {
- let styles: Vec<(&str, &str)> = WARP_STYLES.iter().map(|(id, label)| (*id, label.trim_end_matches('…'))).collect();
- form::choice(ui, d, "style", tl!("Style:"), (LABEL_W, 160.0), &styles);
- let horizontal = d.bool("horizontal");
- widgets::label_row(ui, "", LABEL_W, |ui| {
- for (h, label) in [(true, tl!("Horizontal")), (false, tl!("Vertical"))] {
- if widgets::radio(ui, label, horizontal == h, true) {
- set(d, "horizontal", json!(h));
- }
- ui.add_space(10.0);
- }
- });
- percent(ui, d, "bend", tl!("Bend:"));
- ui.add_space(6.0);
- widgets::subheader(ui, tl!("Distortion"));
- percent(ui, d, "h", tl!("Horizontal:"));
- percent(ui, d, "v", tl!("Vertical:"));
-}
-
-fn mesh_body(ui: &mut egui::Ui, d: &mut Dialog) {
- count(ui, d, "rows", tl!("Rows:"));
- count(ui, d, "cols", tl!("Columns:"));
- if d.bool("reset") {
- ui.add_space(4.0);
- form::check(ui, d, "maintainShape", tl!("Maintain Envelope Shape"));
+ if let Some((on, fields)) = shown {
+ let (cmd, p, label) = command(open.kind, &json_of(¶ms(open.kind, &fields), &fields));
+ // PLAN: the sheet's `LivePreview::run` has no undo label; wg.A20's contract row passes one first.
+ // The answer is not used: a refused preview is reported on the status line.
+ open.preview.run(app, on, label, cmd, &p);
}
-}
-
-fn options_body(ui: &mut egui::Ui, d: &mut Dialog) {
- widgets::subheader(ui, tl!("Rasters"));
- ui.horizontal(|ui| {
- ui.add_space(12.0);
- form::check(ui, d, "antiAlias", tl!("Anti-Alias"));
- });
- ui.add_space(4.0);
- widgets::subheader(ui, tl!("Preserve Shape Using:"));
- let clip = d.str("preserveShape") != "transparency";
- ui.horizontal(|ui| {
- ui.add_space(12.0);
- for (value, label) in [("clippingMask", tl!("Clipping Mask")), ("transparency", tl!("Transparency"))] {
- if widgets::radio(ui, label, clip == (value == "clippingMask"), true) {
- set(d, "preserveShape", json!(value));
- }
- ui.add_space(10.0);
- }
- });
- ui.add_space(4.0);
- let rail = Tokens::get(ui.ctx()).input_border;
- form::slider_w(ui, d, ("fidelity", tl!("Fidelity:"), LABEL_W), 0.0..=100.0, "", &move |_| rail);
- ui.add_space(4.0);
- form::check(ui, d, "distortAppearance", tl!("Distort Appearance"));
- // Gradients and patterns bend only with the appearance.
- let appearance = d.bool("distortAppearance");
- for (key, label) in [("distortLinearGradients", tl!("Distort Linear Gradients")), ("distortPatternFills", tl!("Distort Pattern Fills"))] {
- let on = d.bool(key);
- ui.horizontal(|ui| {
- ui.add_space(20.0);
- if widgets::check(ui, label, on, appearance) {
- set(d, key, json!(!on));
- }
- });
- }
-}
-
-fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
- match d.kind.as_str() {
- WARP => warp_body(ui, d),
- MESH => mesh_body(ui, d),
- _ => options_body(ui, d),
- }
- // With no envelope selected, Envelope Options sets the defaults: nothing to preview.
- if d.kind != OPTIONS || d.bool("__envelope") {
- let (cmd, p, label) = command(d);
- form::preview(app, ui, d, label, cmd, p);
- }
- false
-}
-
-fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result {
- let (cmd, p, _) = command(d);
- form::commit_preview(app, cmd, p)
+ app.effect_dialogs.envelope = Some(open);
}
/// What the Control bar shows for the selected envelope.
@@ -248,60 +284,82 @@ fn bar_of(app: &VectorcraftApp) -> Option<(bool, Bar)> {
Some((*editing, bar))
}
+/// One member of the bar's envelope group: it leaves the bar whole, with the others of its rank, when the row is short.
+fn member(ui: &mut egui::Ui, mut body: impl FnMut(&mut egui::Ui)) {
+ Row::new().gap(Gap::Item).fit_rank(crate::chrome::rank::GROUP).show(ui, |ui, _| body(ui));
+}
+
+/// A labelled whole-number field of the bar over `range`; the value a commit gave.
+fn field(ui: &mut egui::Ui, key: &'static str, caption: Label, value: f64, range: RangeInclusive, unit: Option<&'static str>) -> Option {
+ let mut committed = None;
+ Field::new(caption.clone()).id_salt(key).show(ui, |ui, _| {
+ let mut number = NumberField::new(caption.clone(), Bind::given(Some(value))).range(range.clone()).commit_decimals(0);
+ if let Some(unit) = unit {
+ number = number.unit(unit);
+ }
+ if let Some(&n) = number.show(ui).edit.events.committed() {
+ committed = n;
+ }
+ });
+ committed
+}
+
/// The Control bar's envelope controls (as in the reference app) while an envelope, or content
/// whose envelope is being edited, is selected: Edit Envelope / Edit Contents; a warp's style,
/// orientation, bend and distortions, or a mesh's rows and columns; Reset Envelope Shape; and
-/// Envelope Options. The two editing buttons, each label with its menu or field, each radio button
-/// and each other button show only while the row has room for them and `reserve` after them, and
-/// the controls after one left out are left out too.
-pub fn control_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: f32) {
+/// Envelope Options. Each control is a member of the bar that leaves it whole when the row is short.
+pub fn control_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
let Some((editing, bar)) = bar_of(app) else { return };
- let mut run: Option<(&str, Value)> = None;
- let mut fit = crate::chrome::Fit::new(reserve);
- crate::chrome::group_separator(ui);
- if fit.room(ui, &[24.0, 24.0]) {
+ let mut run: Option<(&'static str, Value)> = None;
+ let mut options = false;
+ member(ui, |ui| {
+ Divider::vertical().show(ui);
for (contents, icon, tip) in [(false, "dc-mesh", tl!("Edit Envelope")), (true, "shapes", tl!("Edit Contents"))] {
- if widgets::icon_button(ui, icon, tip, editing == contents, 24.0).clicked() && editing != contents {
+ let name = row_label(tip);
+ let button = IconButton::new(IconId::new(icon)).label(name.clone()).tooltip(name).selected(editing == contents).show(ui);
+ if clicked(&button) && editing != contents {
run = Some(("object.envelope.editContents", json!({ "editing": contents })));
}
}
- if ui.available_width() >= 4.0 {
- ui.add_space(4.0);
- }
- }
- let field = |ui: &mut egui::Ui, fit: &mut crate::chrome::Fit, key: &str, label: &str, value: f64, suffix: &str| {
- if !fit.room(ui, &[widgets::dim_label_width(ui, label), 46.0]) {
- return None;
- }
- widgets::dim_label(ui, label);
- widgets::plain_field(ui, ("cb-envelope", key), value, suffix, 0, 46.0)
- };
+ });
match &bar {
Bar::Warp { style, bend, h, v, horizontal } => {
- let styles: Vec<&str> = WARP_STYLES.iter().map(|(_, l)| l.trim_end_matches('…')).collect();
- let current = WARP_STYLES.iter().find(|(id, _)| id == style).map_or(style.as_str(), |(_, l)| l.trim_end_matches('…'));
- if fit.room(ui, &[widgets::dim_label_width(ui, tl!("Style:")), 110.0]) {
- widgets::dim_label(ui, tl!("Style:"));
- if let Some((id, _)) = widgets::dropdown(ui, "cb-envelope-style", current, &styles, 110.0).and_then(|i| WARP_STYLES.get(i)) {
- run = Some((OPTIONS_CMD, json!({ "style": id })));
- }
- }
- for (h, label) in [(true, tl!("Horizontal")), (false, tl!("Vertical"))] {
- if fit.room(ui, &[widgets::choice_width(ui, label)]) && widgets::radio(ui, label, *horizontal == h, true) {
+ member(ui, |ui| {
+ let entries = style_entries(false);
+ let caption = row_label(tl!("Style:"));
+ Field::new(caption.clone()).id_salt("style").show(ui, |ui, _| {
+ let pick = Select::new(caption.clone(), Bind::given(static_style(style)), &entries).show(ui);
+ if let Some(&id) = pick.events.committed() {
+ run = Some((OPTIONS_CMD, json!({ "style": id })));
+ }
+ });
+ });
+ member(ui, |ui| {
+ let group = RadioGroup::new(row_label(tl!("Warp Options")), Bind::given(*horizontal)).show(ui, |ui, _| {
+ Row::new().gap(Gap::Item).show(ui, |ui, _| {
+ Radio::new(true).label(row_label(tl!("Horizontal"))).show(ui);
+ Radio::new(false).label(row_label(tl!("Vertical"))).show(ui);
+ });
+ });
+ if let Some(&h) = group.output.events.committed() {
run = Some((OPTIONS_CMD, json!({ "horizontal": h })));
}
- }
+ });
for (key, label, value) in [("bend", tl!("Bend:"), *bend), ("h", tl!("H:"), *h), ("v", tl!("V:"), *v)] {
- if let Some(n) = field(ui, &mut fit, key, label, value, "%") {
- run = Some((OPTIONS_CMD, json!({ key: n.round().clamp(-100.0, 100.0) })));
- }
+ member(ui, |ui| {
+ if let Some(n) = field(ui, key, row_label(label), value, -100.0..=100.0, Some("%")) {
+ run = Some((OPTIONS_CMD, json!({ key: n.round().clamp(-100.0, 100.0) })));
+ }
+ });
}
}
Bar::Mesh { rows, cols } => {
for (key, label, value) in [("rows", tl!("Rows:"), *rows), ("cols", tl!("Columns:"), *cols)] {
- if let Some(n) = field(ui, &mut fit, key, label, f64::from(value), "") {
- run = Some((RESET_MESH, json!({ key: n.round().clamp(1.0, 50.0), "maintainShape": true })));
- }
+ member(ui, |ui| {
+ if let Some(n) = field(ui, key, row_label(label), f64::from(value), 1.0..=50.0, None) {
+ run = Some((RESET_MESH, json!({ key: n.round().clamp(1.0, 50.0), "maintainShape": true })));
+ }
+ });
}
}
Bar::TopObject => {}
@@ -312,13 +370,19 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: f32) {
Bar::Mesh { .. } => Some((RESET_MESH, json!({"maintainShape": false}))),
Bar::TopObject => None,
};
- if let Some(r) = reset
- && fit.room(ui, &[widgets::flat_button_fit_width(ui, tl!("Reset"), 50.0)])
- && widgets::flat_button_fit(ui, tl!("Reset"), 50.0).on_hover_text(tl!("Reset Envelope Shape")).clicked()
- {
- run = Some(r);
+ if let Some(reset) = reset {
+ member(ui, |ui| {
+ let button = Button::new(row_label(tl!("Reset"))).tooltip(row_label(tl!("Reset Envelope Shape"))).show(ui);
+ if clicked(&button) {
+ run = Some(reset.clone());
+ }
+ });
}
- if fit.room(ui, &[24.0]) && widgets::icon_button(ui, "dc-options", tl!("Envelope Options"), false, 24.0).clicked() {
+ member(ui, |ui| {
+ let name = row_label(tl!("Envelope Options"));
+ options |= clicked(&IconButton::new(IconId::new("dc-options")).label(name.clone()).tooltip(name).show(ui));
+ });
+ if options {
crate::menus::invoke(app, OPTIONS_CMD, json!({}));
}
if let Some((cmd, p)) = run
@@ -330,48 +394,51 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: f32) {
#[cfg(test)]
mod tests {
+ use std::cell::RefCell;
+ use std::rc::Rc;
+
+ use super::super::tests_warp::{accept, dismiss, host, json_fields, open_ids, pump, set, windowed};
use super::*;
use vectorcraft_doc::live::EnvelopeKind;
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_engine::Session;
fn app_with_rect() -> (VectorcraftApp, NodeId) {
- let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("select.all", json!({})).unwrap();
(app, NodeId(id))
}
- fn frame(app: &mut VectorcraftApp) {
- let ctx = egui::Context::default();
- crate::theme::install_fonts(&ctx);
- let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx()));
- out.textures_delta.clear();
- }
-
fn envelope(app: &VectorcraftApp) -> (NodeId, vectorcraft_doc::Node) {
let st = app.session.doc().unwrap();
let id = st.selection.objects[0];
(id, st.doc.node(id).unwrap().clone())
}
+ /// The open envelope dialog.
+ fn dialog(app: &VectorcraftApp) -> DialogId {
+ app.effect_dialogs.envelope.as_ref().map(|open| open.id).expect("an open envelope dialog")
+ }
+
#[test]
fn warp_dialog_previews_and_ok_keeps_one_step() {
let (mut app, rect) = app_with_rect();
crate::menus::invoke(&mut app, MAKE_WARP, json!({}));
- assert_eq!(app.ui.dialog.as_ref().map(|d| (d.kind.as_str(), d.fields["reset"].clone())), Some((WARP, json!(false))));
- frame(&mut app);
+ let id = dialog(&app);
+ assert_eq!(app.effect_dialogs.envelope.as_ref().map(|open| open.kind), Some(WARP));
+ assert_eq!(json_fields(&app, id)["reset"], json!(false));
+ pump(&mut app);
// The preview made the envelope already.
assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { .. }));
- let d = app.ui.dialog.as_mut().unwrap();
- d.fields.insert("style".into(), json!("flag"));
- d.fields.insert("horizontal".into(), json!(false));
- d.fields.insert("bend".into(), json!(-30));
- frame(&mut app);
+ set(&app, id, "style", json!("flag"));
+ set(&app, id, "horizontal", json!("vertical"));
+ set(&app, id, "bend", json!(-30));
+ pump(&mut app);
let undo = app.session.doc().unwrap().history.undo.len();
- super::super::confirm(&mut app).unwrap();
- assert!(app.ui.dialog.is_none());
+ accept(&mut app, id);
+ assert!(open_ids(&app).is_empty());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
let (_, n) = envelope(&app);
match &n.kind {
@@ -384,9 +451,10 @@ mod tests {
}
// With the envelope selected, the same item resets it, starting from its values.
crate::menus::invoke(&mut app, MAKE_WARP, json!({}));
- let d = app.ui.dialog.as_ref().unwrap();
- assert_eq!((d.fields["reset"].clone(), d.fields["style"].clone(), d.fields["bend"].clone()), (json!(true), json!("flag"), json!(-30.0)));
- crate::dialogs::cancel(&mut app);
+ let id = dialog(&app);
+ let fields = json_fields(&app, id);
+ assert_eq!((fields["reset"].clone(), fields["style"].clone(), fields["bend"].as_f64()), (json!(true), json!("flag"), Some(-30.0)));
+ dismiss(&mut app, id);
assert!(
matches!(envelope(&app).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. })),
"cancel rolls back"
@@ -419,17 +487,19 @@ mod tests {
let (mut app, _) = app_with_rect();
app.run(MAKE_WARP, json!({"style": "arc", "bend": 50})).unwrap();
app.run("ui.menuDialog", json!({"command": RESET_MESH})).unwrap();
- assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(MESH));
- frame(&mut app);
+ let id = dialog(&app);
+ assert_eq!(app.effect_dialogs.envelope.as_ref().map(|open| open.kind), Some(MESH));
+ pump(&mut app);
assert!(
matches!(envelope(&app).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 4, cols: 4, .. })),
"previewed"
);
- crate::dialogs::cancel(&mut app);
+ dismiss(&mut app, id);
assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. })));
app.run("ui.menuDialog", json!({"command": RESET_MESH})).unwrap();
- app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), json!(2));
- super::super::confirm(&mut app).unwrap();
+ let id = dialog(&app);
+ set(&app, id, "rows", json!(2));
+ accept(&mut app, id);
assert!(
matches!(envelope(&app).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 2, cols: 4, .. }))
);
@@ -441,22 +511,23 @@ mod tests {
app.run(MAKE_WARP, json!({})).unwrap();
app.run("object.envelope.options", json!({"fidelity": 80, "distortPatternFills": true})).unwrap();
crate::menus::invoke(&mut app, OPTIONS_CMD, json!({}));
- let d = app.ui.dialog.as_mut().unwrap();
- assert_eq!((d.fields["fidelity"].clone(), d.fields["distortPatternFills"].clone()), (json!(80.0), json!(true)));
- d.fields.insert("preserveShape".into(), json!("transparency"));
- frame(&mut app);
- super::super::confirm(&mut app).unwrap();
+ let id = dialog(&app);
+ let fields = json_fields(&app, id);
+ assert_eq!((fields["fidelity"].as_f64(), fields["distortPatternFills"].clone()), (Some(80.0), json!(true)));
+ set(&app, id, "preserveShape", json!("transparency"));
+ pump(&mut app);
+ accept(&mut app, id);
let info = app.session.execute("object.envelope.info", &json!({})).unwrap();
assert_eq!((info["preserveShape"].clone(), info["fidelity"].clone()), (json!("transparency"), json!(80.0)));
// Nothing selected: the defaults for new envelopes, no preview.
app.run("select.none", json!({})).unwrap();
crate::menus::invoke(&mut app, OPTIONS_CMD, json!({}));
- let d = app.ui.dialog.as_mut().unwrap();
- assert_eq!(d.fields["preview"], json!(false));
- d.fields.insert("distortAppearance".into(), json!(false));
- frame(&mut app);
+ let id = dialog(&app);
+ assert_eq!(host(&app, |h| h.get_mut_by_id::(id).map(|d| d.is_previewing())), Some(false));
+ set(&app, id, "distortAppearance", json!(false));
+ pump(&mut app);
assert!(!app.session.in_interaction());
- super::super::confirm(&mut app).unwrap();
+ accept(&mut app, id);
assert_eq!(app.session.execute("object.envelope.info", &json!({})).unwrap()["distortAppearance"], json!(false));
}
@@ -471,58 +542,23 @@ mod tests {
assert!(crate::menus::shortcut_of("object.envelope.editContents").is_none(), "its reference shortcut is Paste in Place's here");
}
- /// One Control bar frame with `events`; the rectangles of its 24 pt icon buttons, left to right.
- fn bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec {
- let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1800.0, 600.0)));
- let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| crate::chrome::control_bar(app, ui));
- out.textures_delta.clear();
- let mut r: Vec = ctx.viewport(|vp| {
- vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == egui::vec2(24.0, 24.0)).map(|w| w.rect).collect()
- });
- r.sort_by(|a, b| a.left().total_cmp(&b.left()));
- r
- }
-
#[test]
fn the_control_bar_switches_to_edit_contents_and_back() {
let (mut app, rect) = app_with_rect();
app.run(MAKE_WARP, json!({"style": "arch"})).unwrap();
assert!(bar_of(&app).is_some_and(|(editing, bar)| !editing && matches!(bar, Bar::Warp { ref style, .. } if style == "arch")));
- let ctx = egui::Context::default();
- crate::theme::install_fonts(&ctx);
- let click = |app: &mut VectorcraftApp, at: egui::Pos2| {
- let button =
- |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
- bar_frame(app, &ctx, vec![egui::Event::PointerMoved(at), button(true)]);
- bar_frame(app, &ctx, vec![button(false)]);
- };
- bar_frame(&mut app, &ctx, vec![]);
- let buttons = bar_frame(&mut app, &ctx, vec![]);
- // Edit Envelope, Edit Contents come first.
- click(&mut app, buttons[1].center());
- assert_eq!(app.session.doc().unwrap().selection.objects, vec![rect], "Edit Contents selects the content");
- assert!(bar_of(&app).is_some_and(|(editing, _)| editing), "the content keeps the envelope's controls");
- let buttons = bar_frame(&mut app, &ctx, vec![]);
- click(&mut app, buttons[0].center());
- assert!(bar_of(&app).is_some_and(|(editing, _)| !editing));
- // A mesh envelope shows its rows and columns instead.
- app.run(RESET_MESH, json!({"rows": 3, "cols": 2})).unwrap();
- assert_eq!(bar_of(&app).map(|b| b.1), Some(Bar::Mesh { rows: 3, cols: 2 }));
- bar_frame(&mut app, &ctx, vec![]);
- }
-
- #[test]
- fn the_control_bar_shows_mesh_rows_and_columns_after_a_warp_point_is_moved() {
- let (mut app, _) = app_with_rect();
- app.run(MAKE_WARP, json!({"style": "arc", "bend": 50})).unwrap();
- assert!(bar_of(&app).is_some_and(|(_, bar)| matches!(bar, Bar::Warp { ref style, .. } if style == "arc")));
- let (id, warp) = envelope(&app);
- let grid = vectorcraft_doc::live::warp_grid(&warp).unwrap();
- let p = grid.points[6].p;
- app.run("object.mesh.movePoint", json!({"id": id.0, "index": 6, "x": p.x + 10.0, "y": p.y + 10.0})).unwrap();
- assert_eq!(bar_of(&app), Some((false, Bar::Mesh { rows: grid.rows, cols: grid.cols })));
- let ctx = egui::Context::default();
- crate::theme::install_fonts(&ctx);
- bar_frame(&mut app, &ctx, vec![]);
+ let app = Rc::new(RefCell::new(app));
+ let shown = Rc::clone(&app);
+ let mut fixture = craft::ui::testing::Fixture::new(move |ui| crate::chrome::control_bar(&mut shown.borrow_mut(), ui));
+ fixture.frame(Vec::new());
+ fixture.frame(Vec::new());
+ let contents = fixture.by_label("Edit Contents").expect("the Edit Contents button");
+ fixture.click(&contents);
+ assert_eq!(app.borrow().session.doc().unwrap().selection.objects, vec![rect], "Edit Contents selects the content");
+ assert!(bar_of(&app.borrow()).is_some_and(|(editing, _)| editing), "the content keeps the envelope's controls");
+ fixture.frame(Vec::new());
+ let envelope = fixture.by_label("Edit Envelope").expect("the Edit Envelope button");
+ fixture.click(&envelope);
+ assert!(bar_of(&app.borrow()).is_some_and(|(editing, _)| !editing));
}
}
diff --git a/crates/ui-egui/src/dialogs/tests_warp.rs b/crates/ui-egui/src/dialogs/tests_warp.rs
index 21d3e8e1a4..9a944f1cbf 100644
--- a/crates/ui-egui/src/dialogs/tests_warp.rs
+++ b/crates/ui-egui/src/dialogs/tests_warp.rs
@@ -1,107 +1,83 @@
-//! Effect > Warp uses the existing modal and live-effect commands, without changing envelope art.
-use egui::{Event, Pos2, Rect, Shape, pos2, vec2};
+//! Effect > Warp uses the existing modal and live-effect commands, without changing envelope art. The dialogs are the
+//! hosted ones: values go in through the host's `set_json_field`, as `ui.dialog.set` sets them, and a frame is the
+//! app's dialog pump.
+use craft::ui::dialog::{DialogHost, DialogId};
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
use super::*;
+/// `app` with a window, so its dialogs open on the host.
+pub(super) fn windowed(mut app: VectorcraftApp) -> VectorcraftApp {
+ app.ui_ctx = Some(crate::testing::ui_context());
+ app
+}
+
fn app() -> (VectorcraftApp, NodeId) {
- let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 50, "y": 60, "width": 120, "height": 80})).unwrap()["id"].as_u64().unwrap();
(app, NodeId(id))
}
-fn context() -> egui::Context {
- let ctx = egui::Context::default();
- crate::theme::install_fonts(&ctx);
- crate::theme::apply(&ctx, Default::default());
- ctx
+fn ctx_of(app: &VectorcraftApp) -> egui::Context {
+ app.ui_ctx.clone().expect("a window")
}
-fn frame_output(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput {
- let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 800.0))), events, ..Default::default() };
- let mut output = ctx.run_ui(input, |ui| show(app, ui.ctx()));
- output.textures_delta.clear();
- output
+pub(super) fn host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost) -> R) -> R {
+ app.dialogs().expect("a window").with(f)
}
-fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect)> {
- let output = frame_output(app, ctx, events);
- fn collect(shape: &Shape, clip: Rect, texts: &mut Vec<(String, Rect)>) {
- match shape {
- Shape::Text(text) => {
- let rect = text.visual_bounding_rect();
- if clip.contains(rect.center()) {
- texts.push((text.galley.text().to_string(), rect));
- }
- }
- Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, clip, texts)),
- _ => {}
- }
- }
- let mut texts = vec![];
- for shape in &output.shapes {
- collect(&shape.shape, shape.clip_rect, &mut texts);
- }
- texts
+/// One frame of the app's dialog pump.
+pub(super) fn pump(app: &mut VectorcraftApp) {
+ let ctx = ctx_of(app);
+ super::host::pump(app, &ctx);
}
-fn settle(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, Rect)> {
- for _ in 0..3 {
- frame(app, ctx, vec![]);
- }
- frame(app, ctx, vec![])
+/// The ids of the open dialogs, the top one last.
+pub(super) fn open_ids(app: &VectorcraftApp) -> Vec {
+ host(app, |h| h.open_dialogs()).into_iter().map(|d| d.id).collect()
}
-fn click_text(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
- let texts = frame(app, ctx, vec![]);
- let at = texts.iter().find(|(text, _)| text == label).unwrap_or_else(|| panic!("missing {label:?}: {texts:?}")).1.center();
- click_at(app, ctx, at);
+/// The values the dialog `id` reports for a script.
+pub(super) fn json_fields(app: &VectorcraftApp, id: DialogId) -> Value {
+ host(app, |h| h.open_dialogs()).into_iter().find(|d| d.id == id).and_then(|d| d.fields).expect("an open dialog with fields")
}
-fn click_at(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2) {
- for event in [
- Event::PointerMoved(at),
- Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() },
- Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() },
- ] {
- frame(app, ctx, vec![event]);
- }
+/// Sets a field of the dialog `id` as `ui.dialog.set` does.
+pub(super) fn set(app: &VectorcraftApp, id: DialogId, field: &str, value: Value) {
+ let ctx = ctx_of(app);
+ host(app, |h| h.set_json_field(&ctx, id, field, value)).unwrap_or_else(|e| panic!("{field}: {e}"));
}
-fn set(app: &mut VectorcraftApp, values: Value) {
- // Supply dialog inputs as the control channel does; the production frame previews them.
- app.ui.dialog.as_mut().unwrap().fields.extend(values.as_object().unwrap().clone());
+/// Answers the dialog `id` with OK: the held answer is filed, the app's pump runs it, and the next confirm closes the
+/// dialog with it.
+pub(super) fn accept(app: &mut VectorcraftApp, id: DialogId) {
+ let ctx = ctx_of(app);
+ host(app, |h| h.confirm_by_id(&ctx, id));
+ pump(app);
+ host(app, |h| h.confirm_by_id(&ctx, id));
+ pump(app);
}
-#[test]
-fn warp_options_controls_cover_every_existing_style() {
- for (style, label) in vectorcraft_effects::WARP_STYLES {
- let (mut app, _) = app();
- app.run("effect.dialog", json!({"effect": format!("warp.{style}"), "item": null})).unwrap();
- let ctx = context();
- let texts = settle(&mut app, &ctx);
- for want in [
- "Warp Options",
- "Style:",
- label.trim_end_matches('…'),
- "Horizontal",
- "Vertical",
- "Bend:",
- "Distortion",
- "Horizontal:",
- "Vertical:",
- "Preview",
- "OK",
- "Cancel",
- ] {
- assert!(texts.iter().any(|(text, _)| text == want), "{style}: missing {want:?}: {texts:?}");
- }
- assert!(!texts.iter().any(|(text, _)| text == "Orientation:"));
- cancel(&mut app);
- }
+/// Cancels the dialog `id`; the pump rolls back what it previewed.
+pub(super) fn dismiss(app: &mut VectorcraftApp, id: DialogId) {
+ let ctx = ctx_of(app);
+ host(app, |h| h.cancel_by_id(&ctx, id));
+ pump(app);
+}
+
+fn effect_dialog(app: &VectorcraftApp) -> DialogId {
+ app.effect_dialogs.effect.as_ref().map(|open| open.id).expect("an open Effect dialog")
+}
+
+/// Answers the Edit or Add New prompt the Effect menu asks.
+fn answer_prompt(app: &mut VectorcraftApp, choice: &str) {
+ let prompt = *open_ids(app).last().expect("the Edit or Add New prompt");
+ set(app, prompt, "choice", json!(choice));
+ pump(app);
+ pump(app);
}
#[test]
@@ -116,13 +92,14 @@ fn warp_options_style_orientation_clicks_preview_and_cancel_preserve_redo() {
let redo = app.session.doc().unwrap().history.redo.len();
assert_eq!(redo, 1);
app.run("effect.dialog", json!({"effect": "warp.arc", "item": null})).unwrap();
- let ctx = context();
- settle(&mut app, &ctx);
- click_text(&mut app, &ctx, "Arc");
- click_text(&mut app, &ctx, "Arc Lower");
- click_text(&mut app, &ctx, "Vertical");
- set(&mut app, json!({"bend": -30.0, "horizontal": 20.0, "vertical": -15.0}));
- frame(&mut app, &ctx, vec![Event::PointerMoved(pos2(10.0, 10.0))]);
+ let dialog = effect_dialog(&app);
+ set(&app, dialog, "style", json!("arcLower"));
+ set(&app, dialog, "styleChosen", json!(true));
+ set(&app, dialog, "orientation", json!("vertical"));
+ for (field, value) in [("bend", -30.0), ("horizontal", 20.0), ("vertical", -15.0)] {
+ set(&app, dialog, field, json!(value));
+ }
+ pump(&mut app);
let state = app.session.doc().unwrap();
let effects = &state.doc.node(id).unwrap().appearance.effects;
assert_eq!(effects.len(), 1);
@@ -132,13 +109,13 @@ fn warp_options_style_orientation_clicks_preview_and_cancel_preserve_redo() {
assert_eq!(effects[0].params["horizontal"], 20.0);
assert_eq!(effects[0].params["vertical"], -15.0);
assert_eq!(state.history.undo.len(), undo);
- click_text(&mut app, &ctx, "Cancel");
+ dismiss(&mut app, dialog);
let state = app.session.doc().unwrap();
assert_eq!(state.doc, before);
assert_eq!(state.selection, selection);
assert_eq!((state.history.undo.len(), state.history.redo.len()), (undo, redo));
assert!(!state.is_dirty());
- assert!(!app.session.in_interaction() && app.ui.dialog.is_none());
+ assert!(!app.session.in_interaction() && open_ids(&app).is_empty());
app.run("edit.redo", json!({})).unwrap();
assert_ne!(app.session.doc().unwrap().doc, before, "the original Redo remains usable");
}
@@ -157,14 +134,13 @@ fn warp_options_existing_style_edit_keeps_stack_target_visibility_and_history()
let undo = app.session.doc().unwrap().history.undo.len();
let last_effect = app.last_effect.clone();
app.run("effect.dialog", json!({"effect": "warp.arc", "index": 1, "item": item})).unwrap();
- assert_eq!(app.ui.dialog.as_ref().unwrap().fields["bend"], -25.0);
- let ctx = context();
- settle(&mut app, &ctx);
- click_text(&mut app, &ctx, "Arc");
- click_text(&mut app, &ctx, "Arc Lower");
- set(&mut app, json!({"bend": 35.0}));
- frame(&mut app, &ctx, vec![]);
- click_text(&mut app, &ctx, "OK");
+ let dialog = effect_dialog(&app);
+ assert_eq!(json_fields(&app, dialog)["bend"], -25.0);
+ set(&app, dialog, "style", json!("arcLower"));
+ set(&app, dialog, "styleChosen", json!(true));
+ set(&app, dialog, "bend", json!(35.0));
+ pump(&mut app);
+ accept(&mut app, dialog);
let state = app.session.doc().unwrap();
let target = item.as_u64().map(|n| n as usize);
let old = before.node(id).unwrap().appearance.effects_at(target).unwrap();
@@ -192,220 +168,42 @@ fn warp_options_existing_style_edit_keeps_stack_target_visibility_and_history()
fn warp_dialog_remembers_last_confirmed_sliders() {
let (mut app, _) = app();
app.run("effect.dialog", json!({"effect": "warp.arc", "item": null})).unwrap();
- let ctx = context();
- settle(&mut app, &ctx);
- set(&mut app, json!({"bend": -40.0, "horizontal": 12.0, "vertical": -8.0, "orientation": "vertical"}));
- confirm(&mut app).unwrap();
+ let first = effect_dialog(&app);
+ for (field, value) in [("bend", json!(-40.0)), ("horizontal", json!(12.0)), ("vertical", json!(-8.0)), ("orientation", json!("vertical"))] {
+ set(&app, first, field, value);
+ }
+ accept(&mut app, first);
app.run("effect.dialog", json!({"effect": "warp.flag", "item": null})).unwrap();
- settle(&mut app, &ctx);
- let d = app.ui.dialog.as_ref().unwrap();
- assert_eq!(d.str("__effect"), "warp.flag");
- assert_eq!(d.f64("bend", 0.0), -40.0);
- assert_eq!(d.f64("horizontal", 0.0), 12.0);
- assert_eq!(d.f64("vertical", 0.0), -8.0);
- assert_eq!(d.str("orientation"), "vertical");
-}
-
-#[test]
-fn warp_options_preview_toggle_and_ok_use_latest_values() {
- let (mut app, id) = app();
- let before = app.session.doc().unwrap().doc.clone();
- let undo = app.session.doc().unwrap().history.undo.len();
- app.run("effect.dialog", json!({"effect": "warp.arc", "item": null})).unwrap();
- let ctx = context();
- settle(&mut app, &ctx);
- // Exercise the checkbox transition; assigning its stored boolean bypasses the click.
- click_text(&mut app, &ctx, "Preview");
- assert!(!app.ui.dialog.as_ref().unwrap().bool("preview"));
- assert_eq!(app.session.doc().unwrap().doc, before, "clicking Preview off rolls back");
- set(&mut app, json!({"bend": 75.0}));
- frame(&mut app, &ctx, vec![]);
- assert_eq!(app.session.doc().unwrap().doc, before, "turning Preview off rolls back");
- click_text(&mut app, &ctx, "Preview");
- assert!(app.ui.dialog.as_ref().unwrap().bool("preview"));
- assert_eq!(app.session.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params["bend"], 75.0);
- set(&mut app, json!({"bend": -40.0}));
- confirm(&mut app).unwrap();
- let state = app.session.doc().unwrap();
- assert_eq!(state.doc.node(id).unwrap().appearance.effects[0].params["bend"], -40.0);
- assert_eq!(state.history.undo.len(), undo + 1);
- assert_eq!(app.last_effect.as_ref().unwrap().1["bend"], -40.0);
- app.run("edit.undo", json!({})).unwrap();
- assert_eq!(app.session.doc().unwrap().doc, before);
-}
-
-/// Locate the actual painted number beside its row label, without requesting widget focus.
-fn click_number(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
- let texts = frame(app, ctx, vec![]);
- let row = texts.iter().find(|(text, _)| text == label).unwrap().1;
- let number = texts
- .iter()
- .find(|(text, rect)| {
- rect.left() > row.right() && (rect.center().y - row.center().y).abs() < 6.0 && text.trim_end_matches('%').parse::().is_ok()
- })
- .unwrap_or_else(|| panic!("no numeric field beside {label}: {texts:?}"));
- click_at(app, ctx, number.1.center());
-}
-
-fn replace_number(text: &str) -> Vec {
- let modifiers = egui::Modifiers { ctrl: true, command: true, ..Default::default() };
- vec![
- Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers },
- Event::Key { key: egui::Key::A, physical_key: None, pressed: false, repeat: false, modifiers },
- Event::Text(text.into()),
- ]
-}
-
-#[test]
-fn warp_options_numeric_entry_immediate_accept_uses_latest_values() {
- for preview in [true, false] {
- for enter in [true, false] {
- let (mut app, id) = app();
- app.session.doc_mut().unwrap().mark_saved();
- let before = app.session.doc().unwrap().doc.clone();
- let selection = app.session.doc().unwrap().selection.clone();
- let undo = app.session.doc().unwrap().history.undo.len();
- app.run("effect.dialog", json!({"effect": "warp.arc", "item": null})).unwrap();
- let ctx = context();
- settle(&mut app, &ctx);
- if !preview {
- click_text(&mut app, &ctx, "Preview");
- assert_eq!(app.session.doc().unwrap().doc, before);
- }
- // Actual keyboard input: moving to the next field commits the previous one.
- click_number(&mut app, &ctx, "Horizontal:");
- frame(&mut app, &ctx, replace_number("23%"));
- click_number(&mut app, &ctx, "Vertical:");
- frame(&mut app, &ctx, replace_number("-19%"));
- click_number(&mut app, &ctx, "Bend:");
- let texts = frame(&mut app, &ctx, vec![]);
- let ok = texts.iter().find(|(text, _)| text == "OK").unwrap().1.center();
- if preview {
- let effect = &app.session.doc().unwrap().doc.node(id).unwrap().appearance.effects[0];
- assert_eq!(effect.params["horizontal"], 23.0);
- assert_eq!(effect.params["vertical"], -19.0);
- assert_eq!(effect.params["bend"], 50.0);
- } else {
- assert_eq!(app.session.doc().unwrap().doc, before, "typing with Preview off must not edit the document");
- }
- assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
- let mut events = replace_number("-37%");
- if enter {
- // The final Text and Enter arrive in the same frame, with no idle preview first.
- events.push(Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
- }
- frame(&mut app, &ctx, events);
- if !enter {
- // Click immediately after typing; don't blur the field through another control.
- click_at(&mut app, &ctx, ok);
- }
- assert!(app.ui.dialog.is_none() && !app.session.in_interaction(), "preview={preview}, enter={enter}");
- let state = app.session.doc().unwrap();
- let effects = &state.doc.node(id).unwrap().appearance.effects;
- assert_eq!(effects.len(), 1);
- assert_eq!(effects[0].id, "warp.arc");
- assert_eq!(effects[0].params["bend"], -37.0);
- assert_eq!(effects[0].params["horizontal"], 23.0);
- assert_eq!(effects[0].params["vertical"], -19.0);
- assert_eq!(effects[0].params["orientation"], "horizontal");
- assert_eq!(state.selection, selection);
- assert_eq!(state.history.undo.len(), undo + 1);
- assert_eq!(app.last_effect.as_ref().unwrap().1["bend"], -37.0);
- let after = state.doc.clone();
- app.run("edit.undo", json!({})).unwrap();
- assert_eq!(app.session.doc().unwrap().doc, before);
- assert!(!app.session.doc().unwrap().is_dirty());
- app.run("edit.redo", json!({})).unwrap();
- assert_eq!(app.session.doc().unwrap().doc, after);
- }
- }
-}
-
-#[test]
-fn warp_options_slider_drag_previews_exact_parameter_and_cancel_restores() {
- let (mut app, id) = app();
- app.session.doc_mut().unwrap().mark_saved();
- let before = app.session.doc().unwrap().doc.clone();
- let selection = app.session.doc().unwrap().selection.clone();
- let undo = app.session.doc().unwrap().history.undo.len();
- app.run("effect.dialog", json!({"effect": "warp.arc", "item": null})).unwrap();
- let ctx = context();
- let texts = settle(&mut app, &ctx);
- let row = texts.iter().find(|(text, _)| text == "Bend:").unwrap().1;
- // The real color_slider paints one outlined rail in this row. Locate that painted rail,
- // not a hardcoded screen position or an injected dialog value.
- fn rail(shape: &Shape, clip: Rect, row: Rect) -> Option {
- match shape {
- Shape::Rect(shape)
- if shape.rect.width() > 80.0
- && (shape.rect.height() - 7.0).abs() < 0.1
- && shape.rect.left() > row.right()
- && (shape.rect.center().y - row.center().y).abs() < 6.0
- && clip.contains(shape.rect.center()) =>
- {
- Some(shape.rect)
- }
- Shape::Vec(shapes) => shapes.iter().find_map(|shape| rail(shape, clip, row)),
- _ => None,
- }
- }
- let output = frame_output(&mut app, &ctx, vec![]);
- let bar = output.shapes.iter().find_map(|shape| rail(&shape.shape, shape.clip_rect, row)).expect("Bend must have a visible slider rail");
- let from = pos2(bar.left() + 0.75 * bar.width(), bar.center().y);
- let to = pos2(bar.left() + 0.25 * bar.width(), bar.center().y);
- frame(&mut app, &ctx, vec![Event::PointerMoved(from)]);
- frame(
- &mut app,
- &ctx,
- vec![Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }],
- );
- frame(&mut app, &ctx, vec![Event::PointerMoved(to)]);
- let effect = &app.session.doc().unwrap().doc.node(id).unwrap().appearance.effects[0];
- assert_eq!(effect.params["bend"], -50.0, "the held slider must update the actual live effect");
- assert_eq!(effect.params["horizontal"], 0.0);
- assert_eq!(effect.params["vertical"], 0.0);
- assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
- frame(
- &mut app,
- &ctx,
- vec![Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }],
- );
- assert_eq!(app.session.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params["bend"], -50.0);
- click_text(&mut app, &ctx, "Cancel");
- let state = app.session.doc().unwrap();
- assert_eq!(state.doc, before);
- assert_eq!(state.selection, selection);
- assert_eq!(state.history.undo.len(), undo);
- assert!(!state.is_dirty());
- assert!(app.ui.dialog.is_none() && !app.session.in_interaction());
+ let fields = json_fields(&app, effect_dialog(&app));
+ assert_eq!(fields["style"], "flag");
+ assert_eq!(fields["bend"], -40.0);
+ assert_eq!(fields["horizontal"], 12.0);
+ assert_eq!(fields["vertical"], -8.0);
+ assert_eq!(fields["orientation"], "vertical");
}
/// The edit the Warp dialog test makes: the Bend field, the style, or none.
-fn make_warp_edit(app: &mut VectorcraftApp, ctx: &egui::Context, edit: &str) {
+fn make_warp_edit(app: &mut VectorcraftApp, dialog: DialogId, edit: &str) {
match edit {
- "bend" => {
- click_number(app, ctx, "Bend:");
- frame(app, ctx, replace_number("25%"));
- // Blur via the existing orientation choice; it stays Horizontal.
- click_text(app, ctx, "Horizontal");
- }
+ "bend" => set(app, dialog, "bend", json!(25.0)),
"style" => {
- click_text(app, ctx, "Arc");
- click_text(app, ctx, "Arc Lower");
+ set(app, dialog, "style", json!("arcLower"));
+ set(app, dialog, "styleChosen", json!(true));
}
_ => {}
}
+ pump(app);
}
-/// OK or Cancel was clicked: the document, the history and Redo as each leaves them.
+/// OK or Cancel was answered: the document, the history and Redo as each leaves them.
fn finish_warp_dialog(
app: &mut VectorcraftApp,
- accept: bool,
+ approved: bool,
(before, expected): (&std::sync::Arc, &std::sync::Arc),
(undo, redo): (usize, usize),
) {
let state = app.session.doc().unwrap();
- if accept {
+ if approved {
// Whole-document equality also checks both targets, sibling effects and
// the first visible / second hidden Warp. Existing OK history stays one step.
assert_eq!(state.doc.as_ref(), expected.as_ref());
@@ -428,7 +226,7 @@ fn finish_warp_dialog(
fn warp_options_mixed_styles_change_only_after_explicit_style_choice() {
for item in [Value::Null, json!(1)] {
for edit in ["none", "bend", "style"] {
- for accept in [false, true] {
+ for approved in [false, true] {
let (mut app, first) = app();
for effect in ["path.offsetPath", "warp.arc", "stylize.roundCorners"] {
app.run("effect.apply", json!({"effect": effect, "item": item})).unwrap();
@@ -460,163 +258,35 @@ fn warp_options_mixed_styles_change_only_after_explicit_style_choice() {
}
}
// Ordinary Effect menu route: first object's Arc is already present, then Edit.
- app.run("effect.dialog", json!({"effect": "warp.arc", "item": item})).unwrap();
- assert_eq!(app.ui.dialog.as_ref().unwrap().kind, effect::EXISTS);
- let ctx = context();
- settle(&mut app, &ctx);
- click_text(&mut app, &ctx, "Edit");
- settle(&mut app, &ctx);
+ let asked = app.run("effect.dialog", json!({"effect": "warp.arc", "item": item})).unwrap();
+ assert_eq!(asked["pending"], "effectExists");
+ answer_prompt(&mut app, "edit");
+ let dialog = effect_dialog(&app);
assert_eq!(app.session.doc().unwrap().doc, before, "opening must not broadcast the first target's style");
- make_warp_edit(&mut app, &ctx, edit);
+ make_warp_edit(&mut app, dialog, edit);
assert_eq!(app.session.doc().unwrap().doc, expected, "edit={edit}, item={item}");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
- click_text(&mut app, &ctx, "Preview");
- assert!(!app.ui.dialog.as_ref().unwrap().bool("preview"));
+ set(&app, dialog, "preview", json!(false));
+ pump(&mut app);
assert_eq!(app.session.doc().unwrap().doc, before);
- click_text(&mut app, &ctx, "Preview");
- assert!(app.ui.dialog.as_ref().unwrap().bool("preview"));
+ set(&app, dialog, "preview", json!(true));
+ pump(&mut app);
assert_eq!(app.session.doc().unwrap().doc, expected, "Style intent survives Preview off/on");
- click_text(&mut app, &ctx, if accept { "OK" } else { "Cancel" });
- assert!(app.ui.dialog.is_none() && !app.session.in_interaction());
+ if approved {
+ accept(&mut app, dialog);
+ } else {
+ dismiss(&mut app, dialog);
+ }
+ assert!(open_ids(&app).is_empty() && !app.session.in_interaction());
let state = app.session.doc().unwrap();
assert_eq!(state.selection, selection);
assert_eq!(app.last_effect, last_effect);
- finish_warp_dialog(&mut app, accept, (&before, &expected), (undo, redo));
+ finish_warp_dialog(&mut app, approved, (&before, &expected), (undo, redo));
}
}
}
}
-fn warp_key(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) {
- frame(app, ctx, vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]);
- frame(
- app,
- ctx,
- vec![Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }, Event::ModifiersChanged(egui::Modifiers::NONE)],
- );
-}
-
-fn tab_to_warp_control(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, modifiers: egui::Modifiers) -> egui::Id {
- // The popup container is also a Tab stop: its rectangle contains every option.
- // Require the real widget's focus announcement as well as its visible label.
- for _ in 0..32 {
- let mut events = frame_output(
- app,
- ctx,
- vec![Event::ModifiersChanged(modifiers), Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers }],
- )
- .platform_output
- .events;
- events.extend(
- frame_output(
- app,
- ctx,
- vec![
- Event::Key { key: egui::Key::Tab, physical_key: None, pressed: false, repeat: false, modifiers },
- Event::ModifiersChanged(egui::Modifiers::NONE),
- ],
- )
- .platform_output
- .events,
- );
- if !events.iter().any(|event| {
- let egui::output::OutputEvent::FocusGained(info) = event else { return false };
- info.enabled
- && match info.role {
- egui::Role::ComboBox => info.current_text_value.as_deref() == Some(label),
- egui::Role::Button => info.label.as_deref() == Some(label),
- _ => false,
- }
- }) {
- continue;
- }
- let texts = frame(app, ctx, vec![]);
- let at = texts.iter().find(|(text, _)| text == label).unwrap_or_else(|| panic!("missing keyboard target {label}")).1.center();
- if let Some(id) = ctx.memory(|m| m.focused())
- && ctx.read_response(id).is_some_and(|response| response.rect.contains(at) && ctx.layer_id_at(at) == Some(response.layer_id))
- {
- return id;
- }
- }
- panic!("Tab traversal did not focus {label}");
-}
-
-/// With Preview on the Style choice shows on the art in an interaction; off, the document is as it was.
-fn check_style_preview(app: &VectorcraftApp, preview: bool, id: NodeId, before: &std::sync::Arc) {
- let state = app.session.doc().unwrap();
- if preview {
- assert_eq!(state.doc.node(id).unwrap().appearance.effects[0].id, "warp.arcLower");
- assert!(app.session.in_interaction());
- } else {
- assert_eq!(state.doc.as_ref(), before.as_ref());
- assert!(!state.is_dirty() && !app.session.in_interaction());
- }
-}
-
-#[test]
-fn warp_options_style_keyboard_enter_does_not_accept_dialog() {
- for preview in [true, false] {
- let (mut app, id) = app();
- app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap();
- let moved = app.session.doc().unwrap().doc.clone();
- app.run("edit.undo", json!({})).unwrap();
- app.session.doc_mut().unwrap().mark_saved();
- let before = app.session.doc().unwrap().doc.clone();
- let selection = app.session.doc().unwrap().selection.clone();
- let entries = |items: &[vectorcraft_engine::HistoryEntry]| {
- items.iter().map(|entry| (entry.label.clone(), entry.doc.clone(), entry.selection.clone())).collect::>()
- };
- let undo = entries(&app.session.doc().unwrap().history.undo);
- let redo = entries(&app.session.doc().unwrap().history.redo);
- assert_eq!(redo.len(), 1);
- let last_effect = app.last_effect.clone();
- app.run("effect.dialog", json!({"effect": "warp.arc", "item": null})).unwrap();
- let ctx = context();
- settle(&mut app, &ctx);
- if !preview {
- click_text(&mut app, &ctx, "Preview");
- }
- assert_eq!(app.ui.dialog.as_ref().unwrap().bool("preview"), preview);
- let style_id = tab_to_warp_control(&mut app, &ctx, "Arc", egui::Modifiers::SHIFT);
- // Both directions are actual key events, including returning to the Style combo.
- warp_key(&mut app, &ctx, egui::Key::Tab, egui::Modifiers::NONE);
- assert_ne!(ctx.memory(|m| m.focused()), Some(style_id));
- warp_key(&mut app, &ctx, egui::Key::Tab, egui::Modifiers::SHIFT);
- assert_eq!(ctx.memory(|m| m.focused()), Some(style_id));
- assert!(!craft_ui::ComboBox::is_open(&ctx, style_id));
- warp_key(&mut app, &ctx, egui::Key::Enter, egui::Modifiers::NONE);
- assert!(app.ui.dialog.is_some(), "WARP_STYLE_ENTER_OPEN: opening Style must not accept Warp Options");
- assert!(craft_ui::ComboBox::is_open(&ctx, style_id));
- assert_eq!(app.ui.dialog.as_ref().unwrap().str("__effect"), "warp.arc");
- assert_eq!(entries(&app.session.doc().unwrap().history.undo), undo);
- assert_eq!(entries(&app.session.doc().unwrap().history.redo), redo);
- assert_eq!(app.last_effect, last_effect);
-
- tab_to_warp_control(&mut app, &ctx, "Arc Lower", egui::Modifiers::NONE);
- warp_key(&mut app, &ctx, egui::Key::Enter, egui::Modifiers::NONE);
- assert!(app.ui.dialog.is_some(), "WARP_STYLE_ENTER_CHOICE: choosing Style must not accept Warp Options");
- assert!(!craft_ui::ComboBox::is_open(&ctx, style_id));
- assert_eq!(app.ui.dialog.as_ref().unwrap().str("__effect"), "warp.arcLower");
- assert!(app.ui.dialog.as_ref().unwrap().bool("__warp_style_changed"));
- let state = app.session.doc().unwrap();
- assert_eq!(state.selection, selection);
- assert_eq!(entries(&state.history.undo), undo);
- assert_eq!(entries(&state.history.redo), redo);
- assert_eq!(app.last_effect, last_effect);
- check_style_preview(&app, preview, id, &before);
- click_text(&mut app, &ctx, "Cancel");
- let state = app.session.doc().unwrap();
- assert_eq!(state.doc, before);
- assert_eq!(state.selection, selection);
- assert_eq!(entries(&state.history.undo), undo);
- assert_eq!(entries(&state.history.redo), redo);
- assert!(!state.is_dirty());
- assert!(app.ui.dialog.is_none() && !app.session.in_interaction());
- app.run("edit.redo", json!({})).unwrap();
- assert_eq!(app.session.doc().unwrap().doc, moved);
- }
-}
-
/// Warp Options editing the Warps of two objects, one new and one saved without a map version,
/// changes the Bend of both and keeps each one's own `version`.
#[test]
@@ -631,15 +301,13 @@ fn warp_options_edit_keeps_each_targets_map_version() {
p.remove("version");
}
app.run("select.set", json!({"ids": [first.0, second.0]})).unwrap();
- app.run("effect.dialog", json!({"effect": "warp.arc"})).unwrap();
- assert_eq!(app.ui.dialog.as_ref().unwrap().kind, effect::EXISTS);
- let ctx = context();
- settle(&mut app, &ctx);
- click_text(&mut app, &ctx, "Edit");
- settle(&mut app, &ctx);
- make_warp_edit(&mut app, &ctx, "bend");
- click_text(&mut app, &ctx, "OK");
- assert!(app.ui.dialog.is_none());
+ let asked = app.run("effect.dialog", json!({"effect": "warp.arc"})).unwrap();
+ assert_eq!(asked["pending"], "effectExists");
+ answer_prompt(&mut app, "edit");
+ let dialog = effect_dialog(&app);
+ make_warp_edit(&mut app, dialog, "bend");
+ accept(&mut app, dialog);
+ assert!(open_ids(&app).is_empty());
let doc = app.session.doc().unwrap().doc.clone();
let params = |id: NodeId| doc.node(id).unwrap().appearance.effects[0].params.clone();
assert_eq!((¶ms(first)["bend"], ¶ms(first)["version"]), (&json!(25.0), &json!(vectorcraft_doc::live::WARP_NET)));
diff --git a/crates/ui-egui/src/dialogs/warp_effect.rs b/crates/ui-egui/src/dialogs/warp_effect.rs
index e8ef2bb6b7..3e9031a766 100644
--- a/crates/ui-egui/src/dialogs/warp_effect.rs
+++ b/crates/ui-egui/src/dialogs/warp_effect.rs
@@ -1,109 +1,128 @@
-//! Effect > Warp controls. The style remains an effect ID; Envelope Warp has a different schema.
-use egui::{Pos2, Rect, Stroke, vec2};
-use serde_json::{Map, Value, json};
+//! Effect > Warp rows and the Style row Envelope Warp shares. The style remains an effect ID; Envelope Warp has a
+//! different schema.
+use std::sync::LazyLock;
+
+use craft::ui::contract::{Bind, Entry, Show as _};
+use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind};
+use craft::ui::pickers::Select;
+use craft::ui::primitives::{Glyph, IconSpec};
+use craft::ui::runtime::env::{Label, UnitKind};
+use craft::ui::style::UiTokens;
+use craft::ui::value_drag::SliderScale;
+use egui::{Color32, Painter, Pos2, Rect, Stroke};
use vectorcraft_effects::{WARP_STYLES, WarpNet, WarpStyle};
-use super::form;
-use crate::state::Dialog;
-use crate::theme::Tokens;
-use crate::widgets;
+use super::effect_params::{EffectCx, own_choices};
-const REMEMBERED: [&str; 4] = ["bend", "horizontal", "vertical", "orientation"];
+/// The field a Style pick records that the user chose a style (the Warp effect sends `warpStyle` only then).
+const STYLE_CHOSEN: &str = "styleChosen";
pub(super) fn is_warp(id: &str) -> bool {
id.strip_prefix("warp.").and_then(WarpStyle::from_id).is_some()
}
-/// Slider and orientation values to seed the next new Warp Options dialog.
-pub(super) fn remembered_params(d: &Dialog) -> Value {
- let kept = REMEMBERED.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())));
- Value::Object(kept.collect())
-}
-
-/// Last confirmed warp settings over the catalog defaults for a new dialog.
-pub(super) fn merge_remembered(fields: &mut Map, remembered: Option<&Value>) {
- let Some(obj) = remembered.and_then(Value::as_object) else { return };
- for key in REMEMBERED {
- if let Some(v) = obj.get(key) {
- fields.insert(key.into(), v.clone());
- }
- }
-}
-
-fn shown(label: &str) -> String {
+pub(super) fn shown(label: &str) -> String {
tl!(label).trim_end_matches('…').to_string()
}
+/// A row label from its translated text: the form adds the colon.
+pub(super) fn row_label(translated: &str) -> Label {
+ Label::from(translated.trim_end_matches(':').to_string())
+}
+
+/// A -100 to 100 % slider row.
+pub(super) fn percent_param(key: &str, label: Label, default: f64) -> Param {
+ Param::new(key, label, ParamKind::range(-100.0, 100.0, default, SliderScale::Linear)).unit(UnitKind::Percent)
+}
+
/// An original three-by-three grid, bent by VectorCraft's own warp map. No reference icon artwork.
-fn style_preview(ui: &mut egui::Ui, suffix: &str) {
- let (rect, _) = ui.allocate_exact_size(vec2(30.0, 22.0), egui::Sense::hover());
- let Some(style) = WarpStyle::from_id(suffix) else { return };
- // The map new warps take, on a box 0.55 times as high as it is wide.
- let net = WarpNet::new(style, 0.45, 0.0, 0.0, 2.0, 1.1, false);
- let mut lines = vec![];
- let mut bounds = Rect::NOTHING;
- for vertical in [false, true] {
- for fixed in [-1.0, 0.0, 1.0] {
- let line: Vec = (0..=16)
- .map(|i| {
- let along = -1.0 + f64::from(i) / 8.0;
- let (x, y) = if vertical { (fixed, along) } else { (along, fixed) };
- let q = net.at((x + 1.0) / 2.0, (y + 1.0) / 2.0);
- let p = Pos2::new(q.x as f32, q.y as f32);
- bounds.extend_with(p);
- p
- })
- .collect();
- lines.push(line);
+pub(super) struct WarpGlyph(&'static str);
+
+impl Glyph for WarpGlyph {
+ fn paint(&self, painter: &Painter, _tokens: &UiTokens, rect: Rect, color: Color32, _mirrored: bool) {
+ let Some(style) = WarpStyle::from_id(self.0) else { return };
+ // The map new warps take, on a box 0.55 times as high as it is wide.
+ let net = WarpNet::new(style, 0.45, 0.0, 0.0, 2.0, 1.1, false);
+ let mut lines = vec![];
+ let mut bounds = Rect::NOTHING;
+ for vertical in [false, true] {
+ for fixed in [-1.0, 0.0, 1.0] {
+ let line: Vec = (0..=16)
+ .map(|i| {
+ let along = -1.0 + f64::from(i) / 8.0;
+ let (x, y) = if vertical { (fixed, along) } else { (along, fixed) };
+ let q = net.at((x + 1.0) / 2.0, (y + 1.0) / 2.0);
+ let p = Pos2::new(q.x as f32, q.y as f32);
+ bounds.extend_with(p);
+ p
+ })
+ .collect();
+ lines.push(line);
+ }
+ }
+ let room = rect.shrink(2.0);
+ let scale = (room.width() / bounds.width().max(0.001)).min(room.height() / bounds.height().max(0.001));
+ let stroke = Stroke::new(1.0, color);
+ for line in lines {
+ let points = line.into_iter().map(|p| room.center() + (p - bounds.center()) * scale).collect();
+ painter.add(egui::Shape::line(points, stroke));
}
- }
- let room = rect.shrink(2.0);
- let scale = (room.width() / bounds.width().max(0.001)).min(room.height() / bounds.height().max(0.001));
- let stroke = Stroke::new(1.0, Tokens::get(ui.ctx()).text);
- for line in lines {
- let points = line.into_iter().map(|p| room.center() + (p - bounds.center()) * scale).collect();
- ui.painter().add(egui::Shape::line(points, stroke));
}
}
-pub(super) fn body(ui: &mut egui::Ui, d: &mut Dialog) {
- const LABEL_W: f32 = 84.0;
- let id = d.str("__effect");
- let suffix = id.strip_prefix("warp.").unwrap_or_default();
- let current = WARP_STYLES.iter().find(|(style, _)| *style == suffix).map_or_else(|| suffix.to_string(), |(_, label)| shown(label));
- widgets::label_row(ui, tl!("Style:"), LABEL_W, |ui| {
- style_preview(ui, suffix);
- if let Some((style, label)) = widgets::combo(ui, "warp-style", ¤t, 170.0, |ui| {
- let mut chosen = None;
- for (style, label) in WARP_STYLES {
- ui.horizontal(|ui| {
- style_preview(ui, style);
- if ui.add(egui::Button::selectable(style == suffix, shown(label))).clicked() {
- chosen = Some((style, label));
- ui.close();
- }
- });
- }
- chosen
- }) {
- d.fields.insert("__effect".into(), json!(format!("warp.{style}")));
- d.fields.insert("__warp_style_changed".into(), json!(true));
- d.fields.insert("__label".into(), json!(label.trim_end_matches('…')));
- }
- });
- let orientation = d.str("orientation");
- widgets::label_row(ui, "", LABEL_W, |ui| {
- for (label, value) in super::effect::own_choices(&id, "orientation", false).unwrap_or_default() {
- if widgets::radio(ui, label, orientation == value, true) {
- d.fields.insert("orientation".into(), json!(value));
- }
- }
- });
- let rail = Tokens::get(ui.ctx()).input_border;
- form::slider_w(ui, d, ("bend", tl!("Bend:"), LABEL_W), -100.0..=100.0, "%", &move |_| rail);
- ui.add_space(6.0);
- widgets::subheader(ui, tl!("Distortion"));
- for (key, label) in [("horizontal", tl!("Horizontal:")), ("vertical", tl!("Vertical:"))] {
- form::slider_w(ui, d, (key, label, LABEL_W), -100.0..=100.0, "%", &move |_| rail);
- }
+/// One glyph per entry of `WARP_STYLES`, in its order.
+static WARP_GLYPHS: LazyLock> = LazyLock::new(|| WARP_STYLES.iter().map(|&(style, _)| WarpGlyph(style)).collect());
+
+/// The entries of a Style select, one per warp style; `icons` adds the grid glyph of the style.
+pub(super) fn style_entries(icons: bool) -> Vec> {
+ WARP_STYLES
+ .iter()
+ .zip(WARP_GLYPHS.iter())
+ .map(|(&(style, label), glyph)| {
+ let entry = Entry::new(style, Label::from(shown(label)));
+ if icons { entry.icon(IconSpec::glyph(glyph)) } else { entry }
+ })
+ .collect()
+}
+
+/// The `WARP_STYLES` suffix `id` names; the first style for an id that names none.
+pub(super) fn static_style(id: &str) -> &'static str {
+ WARP_STYLES.iter().find(|(style, _)| *style == id).or(WARP_STYLES.first()).map_or("arc", |(style, _)| *style)
+}
+
+/// The Style row: a select over the warp styles, each with its grid glyph (the closed face shows the held one). A pick
+/// writes the style suffix under `key` and `true` under `styleChosen`, so a mixed selection changes style only once one
+/// was chosen. `current` is the style the row opens on.
+pub(crate) fn style_param(key: &str, current: &str) -> Param {
+ let field = key.to_owned();
+ Param::custom(key, row_label(tl!("Style:")), move |ui, fields, _| {
+ let held = static_style(fields.text(&field).unwrap_or_default());
+ let entries = style_entries(true);
+ let out = Select::new(row_label(tl!("Style:")), Bind::given(held), &entries).show(ui);
+ if let Some(&style) = out.events.committed().filter(|&&style| style != held) {
+ fields.set(field.as_str(), style);
+ fields.set(STYLE_CHOSEN, true);
+ }
+ out.response
+ })
+ .companions([STYLE_CHOSEN])
+ .opens_with(static_style(current))
+}
+
+/// The rows of the Warp effect dialog.
+pub(super) fn params(cx: &EffectCx, fields: &DialogFields) -> Vec {
+ let current = fields.text("style").unwrap_or_else(|| cx.id.strip_prefix("warp.").unwrap_or_default());
+ let orientation = own_choices(&cx.id, "orientation", false)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|(label, value)| (value.to_owned(), Label::from(tl!(label).to_string())))
+ .collect();
+ vec![
+ style_param("style", current),
+ Param::new("orientation", Label::Empty, ParamKind::radio(orientation, None)),
+ percent_param("bend", row_label(tl!("Bend:")), 50.0),
+ Param::section(row_label(tl!("Distortion"))),
+ percent_param("horizontal", row_label(tl!("Horizontal:")), 0.0),
+ percent_param("vertical", row_label(tl!("Vertical:")), 0.0),
+ ]
}