mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Merge pull request #10092 from dotCooCoo/fix/simplify-smooth-dialog-host
MCP: the Simplify and Smooth sliders show in ui.inspect and answer ui.dialog
This commit is contained in:
3 files changed
+301
-1
No files matched your search
@@ -18,7 +18,8 @@
|
||||
//! - `ui.find`: the controls of the window's access tree that match a name or role
|
||||
//! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}`
|
||||
//! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by
|
||||
//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`)
|
||||
//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`), and by
|
||||
//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders
|
||||
//! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, focus?}` (without a path the
|
||||
//! PNG comes back in the reply)
|
||||
//! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly
|
||||
@@ -152,6 +153,10 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
}
|
||||
let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host)));
|
||||
crate::dialogs::javascript_files::show_selected(app, &mut dialogs);
|
||||
// The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it.
|
||||
if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) {
|
||||
open.insert(0, strip);
|
||||
}
|
||||
json!({
|
||||
"scriptRunning": app.session.script_running(),
|
||||
"scriptReport": app.session.shown_script_report(),
|
||||
@@ -1437,6 +1442,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
|
||||
if crate::prefs_dialog::is_open(app) && (p["dialog"] == "preferences" || (top && dialogs.with(|host| host.stack().is_empty()))) {
|
||||
return wrap(preferences_method(app, method, p));
|
||||
}
|
||||
// The Simplify and Smooth sliders are the app's own strip over the canvas, not hosted dialogs: they take a
|
||||
// request that names them, or the top dialog while no hosted dialog is open.
|
||||
let hosted_open = dialogs.with(|host| !host.stack().is_empty());
|
||||
if let Some(r) = crate::dialogs::simplify_slider::dialog_method(app, method, p, hosted_open) {
|
||||
return wrap(r);
|
||||
}
|
||||
// The dialog asked for is `dialog`, the top one when it is missing.
|
||||
let mut params = if p.is_object() { p.clone() } else { json!({}) };
|
||||
if params.get("dialog").is_none_or(Value::is_null) {
|
||||
|
||||
@@ -13,11 +13,14 @@
|
||||
|
||||
// PLAN: the framework paths below (`craft_ui_widgets`, `craft_ui_contract`, `craft_behavior`) and
|
||||
// `LivePreview`'s module are assumed; no app file imports them yet.
|
||||
use craft::automation::dialogs::MAX_DIALOG_FIELDS;
|
||||
use craft::automation::protocol::Params;
|
||||
use craft::behavior::overlay::{Align, Side};
|
||||
use craft::behavior::{CanvasView, IconId};
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::overlay::{Anchor, Dismiss, Outside, Place};
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::dialog_id;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::popover::Popover;
|
||||
use craft::ui::primitives::IconSpec;
|
||||
@@ -78,6 +81,20 @@ impl StripKind {
|
||||
StripKind::Smooth => SMOOTH_AUTO_LEVEL,
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog key `ui.inspect` lists the strip under, which `ui.dialog.set`, `ui.dialog.confirm` and
|
||||
/// `ui.dialog.cancel` take as `dialog`.
|
||||
pub(crate) fn key(self) -> &'static str {
|
||||
match self {
|
||||
StripKind::Simplify => "simplifySlider",
|
||||
StripKind::Smooth => "smoothSlider",
|
||||
}
|
||||
}
|
||||
|
||||
/// The id `ui.inspect` lists the strip under: the one a hosted dialog with the same key has, as a decimal string.
|
||||
fn id(self) -> String {
|
||||
dialog_id(self.key()).value().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// An open slider strip: the level the canvas previews, the selection's bounds from before any
|
||||
@@ -210,6 +227,132 @@ pub(crate) fn more_options(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
Ok(json!({ "tolerance": tolerance }))
|
||||
}
|
||||
|
||||
/// The open strip as `ui.inspect` lists a dialog, `{id, parent, key, fields: {level}}`; `None` when no strip shows.
|
||||
pub(crate) fn inspected(app: &VectorcraftApp) -> Option<Value> {
|
||||
let strip = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?;
|
||||
let kind = strip.kind;
|
||||
Some(json!({ "id": kind.id(), "parent": null, "key": kind.key(), "fields": { "level": strip.level() } }))
|
||||
}
|
||||
|
||||
/// The level a `ui.dialog.set` on a strip of `kind` asks for: field `level`, a number from 0 to 100, as `field` and
|
||||
/// `value` or as the last item of `fields`. `None` when it sets nothing.
|
||||
fn requested_level(kind: StripKind, params: &Value) -> Result<Option<f64>, String> {
|
||||
let level = |field: &Value, value: &Value| {
|
||||
let field = field.as_str().ok_or("`field` is not a string")?;
|
||||
if field != "level" {
|
||||
return Err(format!("the {} slider has no field `{field}`", kind.label()));
|
||||
}
|
||||
match value.as_f64() {
|
||||
Some(level) if (0.0..=100.0).contains(&level) => Ok(level),
|
||||
_ => Err("`level` must be a number from 0 to 100".to_string()),
|
||||
}
|
||||
};
|
||||
let Some(list) = params.get("fields") else {
|
||||
return match params.get("field") {
|
||||
Some(field) => level(field, params.get("value").unwrap_or(&Value::Null)).map(Some),
|
||||
None if params.get("value").is_some() => Err("missing `field`".into()),
|
||||
None => Ok(None),
|
||||
};
|
||||
};
|
||||
if params.get("field").is_some() || params.get("value").is_some() {
|
||||
return Err("`fields` takes the place of `field` and `value`".into());
|
||||
}
|
||||
let items = list.as_array().ok_or("`fields` is not a list")?;
|
||||
if items.len() > MAX_DIALOG_FIELDS {
|
||||
return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len()));
|
||||
}
|
||||
let mut last = None;
|
||||
for item in items {
|
||||
last = Some(level(item.get("field").unwrap_or(&Value::Null), item.get("value").unwrap_or(&Value::Null))?);
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
/// `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` (`method`) when `params.dialog` names the open strip:
|
||||
/// its key or the id [`inspected`] lists, or `"top"` (or no `dialog`) while `hosted_open` is false. `None` for any
|
||||
/// other dialog.
|
||||
///
|
||||
/// `ui.dialog.set {field: "level", value}` moves the slider and previews the level, then answers with `action`
|
||||
/// (`confirm` or `cancel`) when one is given; a set it refuses leaves the slider as it was. `ui.dialog.confirm` keeps
|
||||
/// the preview as one undo step, as Enter does, and `ui.dialog.cancel` puts the paths back, as Escape does.
|
||||
pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Value, hosted_open: bool) -> Option<Result<Value, String>> {
|
||||
let kind = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?.kind;
|
||||
let ours = match params.get("dialog") {
|
||||
None | Some(Value::Null) => !hosted_open,
|
||||
Some(Value::String(named)) if named == "top" => !hosted_open,
|
||||
Some(Value::String(named)) => named == kind.key() || *named == kind.id(),
|
||||
Some(named) => named.as_u64().is_some_and(|id| id.to_string() == kind.id()),
|
||||
};
|
||||
if !ours {
|
||||
return None;
|
||||
}
|
||||
let keys: &[&str] = match method {
|
||||
"ui.dialog.set" => &["dialog", "field", "value", "fields", "action"],
|
||||
"ui.dialog.confirm" | "ui.dialog.cancel" => &["dialog"],
|
||||
_ => return None,
|
||||
};
|
||||
if let Err(e) = Params(params).only(None, keys) {
|
||||
return Some(Err(e));
|
||||
}
|
||||
let answer = match (method, params.get("action")) {
|
||||
("ui.dialog.confirm", _) => Some(true),
|
||||
("ui.dialog.cancel", _) => Some(false),
|
||||
(_, None | Some(Value::Null)) => None,
|
||||
(_, Some(action)) if action == "confirm" => Some(true),
|
||||
(_, Some(action)) if action == "cancel" => Some(false),
|
||||
(_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())),
|
||||
};
|
||||
let level = if method == "ui.dialog.set" {
|
||||
match requested_level(kind, params) {
|
||||
Ok(None) if answer.is_none() => return Some(Err("missing `field`".into())),
|
||||
Ok(level) => level,
|
||||
Err(e) => return Some(Err(e)),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut strip = app.object_dialogs.strip.take()?;
|
||||
if let Some(level) = level {
|
||||
let before = strip.level;
|
||||
strip.level = level;
|
||||
let params = strip.params();
|
||||
let ran = strip.preview.run(app, true, kind.label(), kind.cmd(), ¶ms);
|
||||
// Nothing ran: the canvas already previews this level, or another edit holds the interaction.
|
||||
let shown = || {
|
||||
app.session
|
||||
.active()
|
||||
.and_then(|doc| doc.interaction.as_ref()?.preview.as_ref())
|
||||
.is_some_and(|(cmd, showing)| cmd == kind.cmd() && showing == ¶ms)
|
||||
};
|
||||
let error = match ran {
|
||||
Some(Err(e)) => Some(e),
|
||||
None if !shown() => Some(tl!("Finish the active edit first.").to_owned()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(e) = error {
|
||||
strip.level = before;
|
||||
app.object_dialogs.strip = Some(strip);
|
||||
return Some(Err(e));
|
||||
}
|
||||
}
|
||||
app.object_dialogs.strip = Some(strip);
|
||||
let set = inspected(app).unwrap_or(Value::Null);
|
||||
let Some(answer) = answer else { return Some(Ok(set)) };
|
||||
let strip = app.object_dialogs.strip.take()?;
|
||||
let result = if answer {
|
||||
let params = strip.params();
|
||||
strip.preview.commit(app, kind.cmd(), params).map(|_| Value::Null)
|
||||
} else {
|
||||
strip.cancel(app);
|
||||
Ok(Value::Null)
|
||||
};
|
||||
// A set with an `action` replies `{dialog, result}`: the slider as the set left it, and the answer's result.
|
||||
Some(match (method, result) {
|
||||
("ui.dialog.set", Ok(result)) => Ok(json!({ "dialog": set, "result": result })),
|
||||
(_, result) => result,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the strip hangs: a point under the lowest corner on screen of the selection's bounds from
|
||||
/// before the preview, centred on them, kept on the canvas.
|
||||
fn anchor_rect(view: &CanvasView, bounds: Option<Rect>) -> ScreenRect {
|
||||
|
||||
@@ -326,3 +326,149 @@ fn path_sliders_close_when_file_revert_restores_the_artwork() {
|
||||
assert!(app.session.in_interaction());
|
||||
}
|
||||
}
|
||||
|
||||
/// The two sliders: the dialog key `ui.inspect` lists, the menu command that opens it and its undo step's name.
|
||||
const PATH_SLIDERS: [(&str, &str, &str); 2] =
|
||||
[("simplifySlider", "object.path.simplify", "Simplify"), ("smoothSlider", "object.path.smooth", "Smooth")];
|
||||
|
||||
/// One control channel request, answered at once.
|
||||
fn control(app: &mut VectorcraftApp, method: &str, params: serde_json::Value) -> serde_json::Value {
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let (req, _) = craft::automation::ControlRequest::new(method, params);
|
||||
let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method} answered later") };
|
||||
r
|
||||
}
|
||||
|
||||
/// The open dialog `key` in `ui.inspect`'s `dialogs`.
|
||||
fn inspected_dialog(app: &mut VectorcraftApp, key: &str) -> Option<serde_json::Value> {
|
||||
let r = control(app, "ui.inspect", json!({}));
|
||||
r["result"]["dialogs"].as_array()?.iter().find(|d| d["key"] == key).cloned()
|
||||
}
|
||||
|
||||
/// Both sliders show in `ui.inspect` as the dialog their params text names, with field `level`. `ui.dialog.set`
|
||||
/// moves the slider and previews the level, and `ui.dialog.confirm` keeps the result as one undo step.
|
||||
#[test]
|
||||
fn path_sliders_show_in_ui_inspect_and_ui_dialog_confirm_keeps_the_level() {
|
||||
for (key, command, label) in PATH_SLIDERS {
|
||||
let mut app = app_with_dense_path();
|
||||
let undo_len = app.session.doc().unwrap().history.undo.len();
|
||||
crate::menus::invoke(&mut app, command, json!({}));
|
||||
settle(&mut app);
|
||||
let open = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"));
|
||||
assert!(open["fields"]["level"].is_number(), "{open}");
|
||||
|
||||
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert_eq!(r["result"]["fields"]["level"], 20.0, "{r}");
|
||||
let preview = app.session.doc().unwrap().interaction.as_ref().and_then(|it| it.preview.clone()).map(|p| p.1);
|
||||
assert_eq!(preview, Some(json!({"level": 20.0})), "{key}");
|
||||
settle(&mut app);
|
||||
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(json!(20.0)), "{key}");
|
||||
|
||||
let r = control(&mut app, "ui.dialog.confirm", json!({"dialog": key}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert!(inspected_dialog(&mut app, key).is_none(), "{key}");
|
||||
assert!(!app.session.in_interaction(), "{key}");
|
||||
let history = &app.session.doc().unwrap().history;
|
||||
assert_eq!(history.undo.len(), undo_len + 1, "{key}");
|
||||
assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A repeated level succeeds, but another active edit blocks a set and leaves the slider's level unchanged.
|
||||
#[test]
|
||||
fn path_sliders_refuse_a_set_when_another_edit_owns_the_interaction() {
|
||||
for (key, command, _) in PATH_SLIDERS {
|
||||
let mut app = app_with_dense_path();
|
||||
crate::menus::invoke(&mut app, command, json!({}));
|
||||
settle(&mut app);
|
||||
for _ in 0..2 {
|
||||
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 30}));
|
||||
assert_eq!(r["ok"], true, "{key}: {r}");
|
||||
}
|
||||
let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone();
|
||||
app.session.cancel_interaction().unwrap();
|
||||
app.begin_interaction("Other").unwrap();
|
||||
|
||||
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20}));
|
||||
assert_eq!(r["ok"], false, "{key}: {r}");
|
||||
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key}");
|
||||
settle(&mut app);
|
||||
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level), "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.dialog.set` with `action` sets the level and answers in one request, replying `{dialog, result}` with the
|
||||
/// slider as the set left it: `confirm` keeps the level as one undo step, and `cancel` puts the paths back.
|
||||
#[test]
|
||||
fn path_sliders_answer_a_set_with_an_action_in_one_request() {
|
||||
for (key, command, label) in PATH_SLIDERS {
|
||||
for action in ["confirm", "cancel"] {
|
||||
let mut app = app_with_dense_path();
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let undo_len = app.session.doc().unwrap().history.undo.len();
|
||||
crate::menus::invoke(&mut app, command, json!({}));
|
||||
settle(&mut app);
|
||||
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "fields": [{"field": "level", "value": 30}], "action": action}));
|
||||
assert_eq!(r["ok"], true, "{key} {action}: {r}");
|
||||
assert_eq!(r["result"]["dialog"]["key"], key, "{r}");
|
||||
assert_eq!(r["result"]["dialog"]["fields"]["level"], 30.0, "{r}");
|
||||
assert!(r["result"].get("result").is_some(), "{r}");
|
||||
assert!(inspected_dialog(&mut app, key).is_none(), "{key} {action}");
|
||||
assert!(!app.session.in_interaction(), "{key} {action}");
|
||||
let history = &app.session.doc().unwrap().history;
|
||||
if action == "confirm" {
|
||||
assert_eq!(history.undo.len(), undo_len + 1, "{key}");
|
||||
assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}");
|
||||
} else {
|
||||
assert_eq!(history.undo.len(), undo_len, "{key}");
|
||||
assert_eq!(app.session.active().unwrap().doc, before, "{key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With a hosted dialog open over a slider, `ui.inspect` lists the slider first, and `"top"` names the hosted dialog.
|
||||
#[test]
|
||||
fn path_sliders_list_below_a_hosted_dialog_that_top_names() {
|
||||
let mut app = app_with_dense_path();
|
||||
crate::menus::invoke(&mut app, "object.path.simplify", json!({}));
|
||||
settle(&mut app);
|
||||
app.run("ui.javascriptFilesDialog", json!({})).unwrap();
|
||||
let r = control(&mut app, "ui.inspect", json!({}));
|
||||
let open = r["result"]["dialogs"].as_array().cloned().unwrap_or_default();
|
||||
assert!(open.len() >= 2 && open[0]["key"] == "simplifySlider", "{open:?}");
|
||||
let r = control(&mut app, "ui.dialog.cancel", json!({"dialog": "top"}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert!(inspected_dialog(&mut app, "simplifySlider").is_some(), "the hosted dialog closed, the slider stays");
|
||||
let r = control(&mut app, "ui.inspect", json!({}));
|
||||
assert_eq!(r["result"]["dialogs"].as_array().map(Vec::len), Some(open.len() - 1), "{r}");
|
||||
}
|
||||
|
||||
/// `ui.dialog.cancel` on the top dialog puts the paths back, as Escape does. A level outside 0..100, a value that
|
||||
/// isn't a number and another field are refused, and the slider keeps its level.
|
||||
#[test]
|
||||
fn path_sliders_answer_ui_dialog_cancel_and_refuse_bad_fields() {
|
||||
for (key, command, _) in PATH_SLIDERS {
|
||||
let mut app = app_with_dense_path();
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let undo_len = app.session.doc().unwrap().history.undo.len();
|
||||
crate::menus::invoke(&mut app, command, json!({}));
|
||||
settle(&mut app);
|
||||
let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone();
|
||||
for bad in [json!({"field": "level", "value": 101}), json!({"field": "level", "value": "20"}), json!({"field": "tolerance", "value": 2})] {
|
||||
let mut params = bad.clone();
|
||||
params["dialog"] = json!(key);
|
||||
let r = control(&mut app, "ui.dialog.set", params);
|
||||
assert_eq!(r["ok"], false, "{key} {bad}: {r}");
|
||||
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key} {bad}");
|
||||
}
|
||||
|
||||
let r = control(&mut app, "ui.dialog.cancel", json!({}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert!(inspected_dialog(&mut app, key).is_none(), "{key}");
|
||||
assert!(!app.session.in_interaction(), "{key}");
|
||||
assert_eq!(app.session.active().unwrap().doc, before, "{key}");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len, "{key}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user