diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 9b65d0b96a..c7317f1a6b 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -177,8 +177,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.run("script.run", script) } -fn growth_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { - app.ui.dialog = None; +/// Continue: the run goes on, and the ScriptUI dialog the question was asked over, when its +/// `show()` has not ended, opens again as it was. +fn growth_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let showing = app.session.script_window_showing(); + app.ui.dialog = super::parent(d).filter(|p| showing.as_ref().is_some_and(|w| super::script_window::is_open_for(p, w))); app.session.script_continue(); Ok(Value::Null) } diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 158a86ea5b..88d53cac21 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -76,6 +76,7 @@ fn shown(app: &VectorcraftApp, ctx: &egui::Context) -> Option<(Arc DialogAction { let Some((w, waiting)) = shown(app, ui.ctx()) else { return DialogAction::None }; + move_drafts(&w, d); let mut events = Vec::new(); let (width, height) = w.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); @@ -118,11 +119,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc events.retain(|e| !matches!(e, UiEvent::Click(_))); app.status(e); } + note_draft_places(&w, d); let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, _ => Vec::new(), }; - queue.extend(events.iter().map(event_fields)); + queue.extend(events.iter().map(|e| event_fields(&w, e))); if !waiting || queue.is_empty() { if !queue.is_empty() { d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); @@ -133,12 +135,48 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc if !queue.is_empty() { d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); } - if let Value::Object(fields) = next { + if let Value::Object(mut fields) = next { + // The control the event was given to, found again in the dialog as the handlers that ran + // since left it. + let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| control_at(&w, &p)); + if let Some(i) = at { + fields.insert("control".into(), json!(i)); + } d.fields.extend(fields); } DialogAction::Confirm } +/// The field of a queued event that holds where its control sits in the dialog ([`place_of`]). +const PLACE_KEY: &str = "place"; + +/// Where control `i` sits in the dialog `w`: its position among its container's controls, after +/// its container's own position, and so on up to the dialog. `add` puts a new control after the +/// others in its container, so a handler that adds controls leaves the place of every other one +/// as it was, while its index in the dialog's list of elements can move. +fn place_of(w: &ScriptUiDialog, mut i: usize) -> Vec { + let mut place = Vec::new(); + while i > 0 { + let Some(n) = w.nodes.get(i) else { return Vec::new() }; + place.push(w.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); + if n.parent >= i { + return Vec::new(); + } + i = n.parent; + } + place.reverse(); + place +} + +/// The index of the control at `place` ([`place_of`]) in the dialog `w`, if it has one. +fn control_at(w: &ScriptUiDialog, place: &[usize]) -> Option { + let mut at = 0; + for &k in place { + at = w.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; + } + (at > 0).then_some(at) +} + /// The field that holds the events the person gave in one frame that the script has not had yet; /// the script takes one event each time it waits. const QUEUE_KEY: &str = "queued"; @@ -202,6 +240,37 @@ fn draft_key(i: usize) -> String { format!("text{i}") } +/// The field that holds, for each text typed in an edit field, where the field sat ([`place_of`]) +/// in the dialog the text was typed in. +const DRAFT_PLACES_KEY: &str = "draftPlaces"; + +/// Records where the field of each typed text sits in the dialog `w`, for [`move_drafts`]. +fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { + let places: serde_json::Map = + (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(place_of(w, i)))).collect(); + if places.is_empty() { + d.fields.remove(DRAFT_PLACES_KEY); + } else { + d.fields.insert(DRAFT_PLACES_KEY.into(), Value::Object(places)); + } +} + +/// Puts each typed text that [`note_draft_places`] recorded under the index its field has in the +/// dialog `w`, which moves when a handler adds controls before the field. A text whose field the +/// dialog no longer has is dropped. +fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { + let Some(Value::Object(places)) = d.fields.remove(DRAFT_PLACES_KEY) else { return }; + let mut moved = Vec::new(); + for (key, place) in places { + let Some(text) = d.fields.remove(&key) else { continue }; + let at = serde_json::from_value::>(place).ok().and_then(|p| control_at(w, &p)); + if let Some(i) = at.filter(|i| w.nodes.get(*i).is_some_and(|n| n.kind == UiKind::EditText)) { + moved.push((draft_key(i), text)); + } + } + d.fields.extend(moved); +} + /// The text of the visible static text just before control `i` in its container: the visible prompt /// of an edit field, a list box or a drop-down list, which screen readers call one without a name /// by. Empty when there is none. @@ -369,16 +438,21 @@ fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (us None } -/// `event` as the dialog's `event`, `control` and `value` fields. -fn event_fields(event: &UiEvent) -> Value { +/// `event` in the dialog `w` as the dialog's `event`, `control` and `value` fields, and for a +/// click or a change, the control's place ([`PLACE_KEY`]). +fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { let (name, control, value) = match event { - UiEvent::Click(i) => ("click", json!(i), Value::Null), - UiEvent::Change(i, UiValue::Text(t)) => ("change", json!(i), json!(t)), - UiEvent::Change(i, UiValue::Number(v)) => ("change", json!(i), json!(v)), - UiEvent::Change(i, UiValue::Index(k)) => ("change", json!(i), json!(k)), - UiEvent::Close => ("close", Value::Null, Value::Null), + UiEvent::Click(i) => ("click", Some(*i), Value::Null), + UiEvent::Change(i, UiValue::Text(t)) => ("change", Some(*i), json!(t)), + UiEvent::Change(i, UiValue::Number(v)) => ("change", Some(*i), json!(v)), + UiEvent::Change(i, UiValue::Index(k)) => ("change", Some(*i), json!(k)), + UiEvent::Close => ("close", None, Value::Null), }; - json!({"event": name, "control": control, "value": value}) + let mut fields = json!({"event": name, "control": control, "value": value}); + if let Some(i) = control { + fields[PLACE_KEY] = json!(place_of(w, i)); + } + fields } /// The event in the dialog's fields, for the dialog `w`. @@ -416,10 +490,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { vectorcraft_engine::script::scriptui::check_event(&w, event.clone())?; let mut events = vec![event]; let open = app.ui.dialog.as_mut().filter(|open| open.kind == KIND); - if let Some(open) = open - && matches!(events[0], UiEvent::Click(_) | UiEvent::Close) - { - commit_drafts(&w, open, &mut events)?; + if let Some(open) = open { + move_drafts(&w, open); + let committed = if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { commit_drafts(&w, open, &mut events) } else { Ok(()) }; + note_draft_places(&w, open); + committed?; } let mut events = events.into_iter(); if let Some(first) = events.next() { @@ -429,7 +504,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { for k in ["event", "control", "value"] { open.fields.remove(k); } - let later: Vec = events.map(|e| event_fields(&e)).collect(); + let later: Vec = events.map(|e| event_fields(&w, &e)).collect(); if !later.is_empty() { let mut queue = match open.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, @@ -450,7 +525,10 @@ pub(crate) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), Str let Some(w) = app.session.script_window() else { return Ok(()) }; let click = w.cancel_element.map(UiEvent::Click).filter(|e| vectorcraft_engine::script::scriptui::check_event(&w, e.clone()).is_ok()); let mut events = vec![click.unwrap_or(UiEvent::Close)]; - commit_drafts(&w, d, &mut events)?; + move_drafts(&w, d); + let committed = commit_drafts(&w, d, &mut events); + note_draft_places(&w, d); + committed?; let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, _ => Vec::new(), @@ -461,7 +539,7 @@ pub(crate) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), Str { let _ = app.session.script_window_answer(first); } - queue.extend(events.map(|e| event_fields(&e))); + queue.extend(events.map(|e| event_fields(&w, &e))); if !queue.is_empty() { d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 27e74d820e..b51385713a 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -77,6 +77,21 @@ fn ask(app: &mut VectorcraftApp) -> bool { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::NOTICE_KIND) { app.ui.dialog = None; } + // A run past its growth allowance asks about it first, also when its ScriptUI dialog waits + // again. The question keeps the dialog of the show() the run is in, with its queued events and + // typed text, for Continue to show again. + if app.session.script_waiting() { + let window = app.ui.dialog.take_if(|d| d.kind == script_window::KIND); + if app.ui.dialog.is_none() { + let showing = app.session.script_window_showing(); + let mut fields = json!({}); + if let Some(window) = window.filter(|d| showing.as_ref().is_some_and(|w| script_window::is_open_for(d, w))) { + fields[crate::dialogs::PARENT] = serde_json::to_value(window).unwrap_or_default(); + } + app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, fields)); + } + return true; + } if let Some(window) = app.session.script_window() { // A dialog the script showed after closing the one that is open replaces it. if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND && !script_window::is_open_for(d, &window)) { @@ -91,19 +106,10 @@ fn ask(app: &mut VectorcraftApp) -> bool { } return true; } - // While a handler runs, the ScriptUI dialog stays open, until its show() ends or the run asks - // about its growth. - if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) - && (app.session.script_waiting() || app.session.script_window_showing().is_none()) - { + // While a handler runs, the ScriptUI dialog stays open, until its show() ends. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) && app.session.script_window_showing().is_none() { app.ui.dialog = None; } - if app.session.script_waiting() { - if app.ui.dialog.is_none() { - app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); - } - return true; - } false } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 0b750438b0..ad6533004a 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -395,6 +395,95 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_t assert!(!until_window(&mut app)); } +#[test] +fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var p = w.add('panel'); var e = w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); \ + e.onChange = function () { p.add('statictext', undefined, 'Added'); }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("text2".into(), json!("typed")); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app), "the script takes the text and waits again"); + let w = app.session.script_window().unwrap(); + assert_eq!(w.nodes[4].text, "OK", "the handler added a control before OK"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +#[test] +fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'a'); var g = w.add('button', undefined, 'Grow'); \ + w.add('button', undefined, 'OK'); g.onClick = function () { vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); \ + for (var k = 0; k < 17; k++) { vc.run('select.all'); vc.run('edit.duplicate'); } }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "Grow"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text1".into(), json!("typed")); + d.fields.insert("queued".into(), json!([{"event": "click", "control": 3, "value": null}])); + for _ in 0..10_000 { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == dialogs::script_run::GROWTH_KIND) { + break; + } + assert!(app.session.script_running(), "the run asks about its growth"); + script_runs::poll(&mut app); + } + let question = app.ui.dialog.clone().expect("the growth question"); + assert_eq!(question.kind, dialogs::script_run::GROWTH_KIND); + dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("Continue shows the dialog again"); + assert_eq!(d.kind, KIND); + assert_eq!(d.fields.get("text1"), Some(&json!("typed")), "with the text typed in its field"); + assert!(d.fields.contains_key("queued"), "and the click still queued"); + assert!(until_window(&mut app), "the script waits at its dialog again"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the typed text and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +#[test] +fn a_typed_text_stays_with_its_field_after_a_handler_adds_a_control_before_it_and_the_run_grows() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var p = w.add('panel'); var e = w.add('edittext', undefined, 'a'); \ + var g = w.add('button', undefined, 'Grow'); w.add('button', undefined, 'OK'); g.onClick = function () { \ + p.add('statictext', undefined, 'Added'); vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); \ + for (var k = 0; k < 17; k++) { vc.run('select.all'); vc.run('edit.duplicate'); } }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Grow"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text2".into(), json!("typed")); + d.fields.insert("queued".into(), json!([{"event": "click", "control": 4, "value": null, "place": [3]}])); + frame(&mut app, Vec::new()); + for _ in 0..10_000 { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == dialogs::script_run::GROWTH_KIND) { + break; + } + assert!(app.session.script_running(), "the run asks about its growth"); + script_runs::poll(&mut app); + } + dialogs::confirm(&mut app).unwrap(); + assert!(until_window(&mut app), "the script waits at its dialog again"); + assert_eq!(app.session.script_window().unwrap().nodes[3].text, "a", "the handler added a control before the edit field"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the typed text and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + #[test] fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 951edebb05..d376a5623b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2945,7 +2945,10 @@ which ends the run as `script.stop` does. It stays open while one of its handler returns. Enter outside a field clicks the default button, also with the keyboard focus on a slider or another control that Enter does not click. Escape clicks the cancel button, or closes the dialog when it has none. Quitting while it waits, or while one of its handlers runs, -asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. +asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. When a +handler takes the run past the growth limit, the question to continue opens over the dialog, and Continue shows the +dialog again with those events and the text typed in its fields. An event that waits for the script goes to the control +it was given to, and a typed text stays in its field, also after a handler adds controls before that one. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the script the text still typed in the dialog's fields. When one of those texts is longer than 16 KiB, the script gets