diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index d6ebd2241a..1172a957b3 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -365,13 +365,13 @@ fn header(ui: &mut Ui, title: &str) { /// Draws the responsive picker and updates its color fields and live preview. /// Returns the requested action for the shared frame to confirm or cancel. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { - super::modal::fits_itself(ui); let channel = Channel::parse(&d.str("channel")).unwrap_or_default(); let web = d.bool("webOnly"); let swatches = d.bool("swatches"); let p = picked(d); let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color); let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color); + super::modal::fits_itself(ui); let (side, values_w, button_w, stacked) = layout_size(ui); let field_w = side + SLIDER_GAP + SLIDER_W; let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w }; diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index 582bd65a0d..26f9dda1a4 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -83,24 +83,32 @@ pub(crate) fn over_parent(ctx: &egui::Context) { } /// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, -/// and the window drawn in the pass before was not one opened over it ([`over_parent`]). +/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]). fn opened(ctx: &egui::Context, id: Id) -> bool { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|m| { - // The window drawn in the pass before, if another. - let before = - m.get_temp::<(u64, Id)>(Id::unique(LAST_KEY)).filter(|&(at, other)| other != id && at.saturating_add(1) == pass).map(|(_, other)| other); - m.insert_temp(Id::unique(LAST_KEY), (pass, id)); + // The windows drawn in this pass so far and in the pass before. + let (at, now, prev) = m.get_temp::<(u64, Vec, Vec)>(Id::unique(LAST_KEY)).unwrap_or_default(); + let (mut now, prev) = if at == pass { + (now, prev) + } else if at.saturating_add(1) == pass { + (vec![], now) + } else { + (vec![], vec![]) + }; + let before: Vec = prev.iter().copied().filter(|&other| other != id).collect(); + now.push(id); + m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev)); let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); if last != u64::MAX && last.saturating_add(1) >= pass { return false; } // Shown again as the window opened over it closed. - if before.is_some_and(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + if before.iter().any(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { return false; } - // Opened over the window drawn in the pass before, it holds that one; otherwise none. - match before.filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { + // Opened over the window drawn last in the pass before, it holds that one; otherwise none. + match before.last().copied().filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { Some(under) => { m.insert_temp(id.with(HOLDS_KEY), under); } @@ -175,7 +183,8 @@ const WHOLE_KEY: &str = "modal-whole"; const SHOWN_KEY: &str = "modal-shown"; const TOP_ROWS_KEY: &str = "modal-top-rows"; const TOP_WHOLE_KEY: &str = "modal-top-whole"; -/// For all modal windows: the pass the last one was drawn in and its id (`LAST_KEY`), and the pass +/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass +/// and of those drawn in the pass before it (`LAST_KEY`), and the pass /// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). /// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). const LAST_KEY: &str = "modal-last"; @@ -350,10 +359,11 @@ mod tests { } /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal - /// window named `open` open, if any: a heading and 60 rows, in [`scrolled_rows`] when - /// `in_rows`. A window named "over …" is opened over the one before it ([`over_parent`]). - /// Returns whether a first row could be seen in the last frame (inside the screen and its clip). - fn first_row_seen(ctx: &egui::Context, open: Option<&str>, in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { + /// windows named in `open` open, in that order: the first a heading and 60 rows, in + /// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is + /// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in + /// the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); let add = |ui: &mut egui::Ui| { for i in 0..60 { @@ -367,13 +377,15 @@ mod tests { let input = egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() }; let mut out = ctx.run_ui(input, |ui| { - if let Some(name) = open { + for (i, &name) in open.iter().enumerate() { if name.starts_with("over ") { over_parent(ui.ctx()); } show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| { heading(ui, "Top"); - if in_rows { + if i > 0 { + ui.label("Alert"); + } else if in_rows { scrolled_rows(ui, "rows", add); } else { add(ui); @@ -411,32 +423,34 @@ mod tests { let ctx = egui::Context::default(); crate::theme::apply(&ctx, Default::default()); let mut time = 0.0; - assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); - assert!(!first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); - first_row_seen(&ctx, None, in_rows, vec![], &mut time, 2); - assert!(first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); } } #[test] fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it - // did not close. A window that another replaced did close. + // did not close. A window that another replaced did close. Either may have shown an alert + // of its own, drawn after it in the same passes. + let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)]; let mut wrong = vec![]; for in_rows in [false, true] { - for (other, kept) in [("over B", true), ("C", false)] { + for (other, kept) in others { let ctx = egui::Context::default(); crate::theme::apply(&ctx, Default::default()); let mut time = 0.0; - first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4); - if first_row_seen(&ctx, Some("A"), in_rows, wheel_down(), &mut time, 60) { + first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); } - if !first_row_seen(&ctx, Some(other), in_rows, vec![], &mut time, 4) { - wrong.push(format!("rows {in_rows}: {other} does not open at its top")); + if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: {other:?} does not open at its top")); } - if first_row_seen(&ctx, Some("A"), in_rows, vec![], &mut time, 4) == kept { - wrong.push(format!("rows {in_rows}: after {other}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { + wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); } } } @@ -455,6 +469,7 @@ mod tests { let mut text = String::from("12"); let mut time = 0.0; let mut field = None; + let mut focus_given = false; let mut seen = vec![]; for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] { let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); @@ -477,8 +492,11 @@ mod tests { }); }); out.textures_delta.clear(); - if let Some(id) = field.filter(|_| ctx.memory(|m| m.focused()).is_none()) { + // The field is given the focus once, after the first frame; a resize that took it + // away would leave the keys typed after it untaken. + if let Some(id) = field.filter(|_| !focus_given) { ctx.memory_mut(|m| m.request_focus(id)); + focus_given = true; } } let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs index d5db06b17d..01c9456fa2 100644 --- a/crates/ui-egui/src/dialogs/tests_scroll.rs +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -1,6 +1,7 @@ //! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of //! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests //! can find it. + use egui::{Pos2, Rect, Shape, vec2}; use serde_json::json; use vectorcraft_engine::Session; @@ -66,9 +67,13 @@ fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { source: egui::MouseWheelSource::Unknown, modifiers: egui::Modifiers::NONE, }; - let (_, w) = window(&ctx); - let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body: None, whole: [false; 2] }; - let at = whole_bar(&before).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); + let (id, w) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole }; + // On the window's upright bar, else on its body's bar, else on its sideways bar, else at + // its right edge. + let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width()); + let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]); } let (id, window) = window(&ctx); @@ -117,16 +122,7 @@ fn whole_bar(shown: &Shown) -> Option { /// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and /// its clip). fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> { - fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { - match s { - Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), - Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), - _ => {} - } - } - let mut texts = vec![]; - shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts)); - texts + texts(shown) .into_iter() .filter(|(s, ..)| labels.contains(&s.as_str())) .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) @@ -347,21 +343,101 @@ fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() { assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top"); } +/// Open Import Shortcut Set on a set of two shortcuts. +fn open_shortcut_import(app: &mut VectorcraftApp) { + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; + crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); +} + #[test] fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() { // Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An // 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt. - let open: Open = |app| { - let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; - crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); - }; - let wide = show_in(open, vec2(1280.0, 900.0), false); + let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false); let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0)); assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window); assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll"); - let shown = show_in(open, screen.size(), false); + let shown = show_in(open_shortcut_import, screen.size(), false); assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); assert_eq!(shown.whole, [true, false], "it scrolls sideways only"); let sideways: Vec = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect(); assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false)); } + +#[test] +fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() { + // In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right + // edge, the text drawn furthest right in a large window can be seen. + let opens: [(&str, Open); 3] = [ + ("Import Shortcut Set", open_shortcut_import), + ("Keyboard Shortcuts", crate::shortcut_editor::open), + ("Preferences", |app| crate::prefs_dialog::open(app, None)), + ]; + let mut wrong = vec![]; + for (name, open) in opens { + let wide = show_in(open, vec2(1600.0, 1000.0), false); + let Some((right, _)) = texts(&wide) + .into_iter() + .filter(|(_, r, _)| wide.window.contains_rect(*r)) + .map(|(s, r, _)| (s, r.right())) + .max_by(|a, b| a.1.total_cmp(&b.1)) + else { + wrong.push(format!("{name}: no text in the large window")); + continue; + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0)); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + // Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge. + let seen = + |shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r)); + let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width()); + if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) { + let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::>(); + wrong.push(format!( + "{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}", + screen.size(), + shown.window, + shown.whole, + seen(&shown), + at(&shown), + seen(&scrolled), + at(&scrolled), + bars(&shown, true, true) + )); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Every text the dialog drew, with its rectangle and its clip. +fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> { + fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out)); + out +} + +#[test] +fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() { + // Check Spelling draws its buttons inside its body: in a window too short for it, the heading + // stays in view and the buttons scroll with the body. + let open: Open = |app| { + check_spelling::open(app).unwrap(); + }; + let tall = show_in(open, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round())); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole); + assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view"); + assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down"); +}