From dde515552d80287207b40e9da36ef77e776f2f54 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 07:04:18 -0800 Subject: [PATCH 1/3] Fix #5941: scroll bars show while the pointer is elsewhere Most scrolling lists in panels and dialogs (Swatches, History, Artboards, Graphic Styles, Preferences and others) used egui's default floating scroll bar, which draws nothing until the pointer is over the list, so nothing showed that a list had more rows. The theme now gives every scroll area the slim bar that menus, the Layers list and panel bodies already use: it shows whenever there is more to scroll to, in a column of its own beside the rows. Scroll areas that set their own style keep it. The toolbar's and the dock icon column's 2 pt scroll line now shows at rest too, and still never grows wider than 4 pt (#808). The Color Picker's swatch list leaves room for the bar inside the list instead of widening the dialog. The Glyphs panel's grids count their columns in the room beside the bar while their rows run past the list, so the last cell of a row no longer pushes the bar past the panel's edge, and use the whole width when the rows fit. --- crates/ui-egui/src/dialogs/color_picker.rs | 5 +- .../ui-egui/src/dialogs/color_picker/tests.rs | 47 +++++++ crates/ui-egui/src/panels/glyphs.rs | 131 +++++++++++++++++- crates/ui-egui/src/prefs_dialog/tests.rs | 47 +++++++ crates/ui-egui/src/theme.rs | 3 + crates/ui-egui/src/widgets/dropdowns.rs | 11 +- crates/ui-egui/src/widgets/look_tests.rs | 81 +++++++++++ 7 files changed, 315 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index f86ee17f51..c16d8d9e6e 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -663,8 +663,9 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo ui.add_space(4.0); widgets::list_box(ui, |ui| { let max_h = (side - 28.0).max(1.0); - egui::ScrollArea::vertical().id_salt("cp-swatches").max_height(max_h).show(ui, |ui| { - ui.set_width(list_w - 8.0); + // The rows take the list's width less its scroll bar's column. + egui::ScrollArea::vertical().id_salt("cp-swatches").max_width(list_w - 8.0).max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { + ui.set_width(ui.available_width()); let cur = d.str("library"); if cur.is_empty() || cur == swatchlib::DOCUMENT_SWATCHES { let Some(st) = app.session.active() else { diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 0786df7ca9..79864f8d13 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -775,6 +775,53 @@ fn compact_picker_shrinks_then_scrolls_without_enlarging_the_window() { } } +/// #5941: in a window short enough to scroll the picker, at any width, its scroll bar shows +/// inside the window and the content fits beside it: no label is cut off at the side. +#[test] +fn a_scrolling_picker_shows_its_bar_and_fits_its_content_beside_it() { + fn sideways_clipped(shape: &egui::Shape, clip: Rect, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + let rows_shown = clip.top() <= r.top() && r.bottom() <= clip.bottom(); + if rows_shown && !t.galley.text().trim().is_empty() && (r.left() < clip.left() - 1.0 || r.right() > clip.right() + 1.0) { + out.push(format!("{:?} {r:?} in {clip:?}", t.galley.text())); + } + } + egui::Shape::Vec(v) => v.iter().for_each(|s| sideways_clipped(s, clip, out)), + _ => {} + } + } + for width in (400..=800).step_by(8) { + let size = vec2(width as f32, 380.0); + let (ctx, mut app) = (context(), app()); + app.run("ui.colorPicker", json!({"color": "#0000ff"})).unwrap(); + settled(&ctx, &mut app, size); + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let mut clipped = vec![]; + for s in &out.shapes { + sideways_clipped(&s.shape, s.clip_rect, &mut clipped); + } + assert!(clipped.is_empty(), "{size:?}: {clipped:?}"); + let outer = ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", KIND)))).unwrap(); + assert!(outer.left() >= -0.5 && outer.right() <= size.x + 0.5, "{size:?}: the window {outer:?} stays on screen"); + // The content's scroll bar: a narrow filled rectangle taller than a row, inside the window. + let mut bars = vec![]; + let mut walk = vec![]; + out.shapes.iter().for_each(|c| walk.push(c.shape.clone())); + while let Some(s) = walk.pop() { + match s { + egui::Shape::Vec(v) => walk.extend(v), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + _ => {} + } + } + assert!(bars.iter().any(|b| outer.contains_rect(*b)), "{size:?}: the content scrolls and its bar shows in {outer:?}: {bars:?}"); + } +} + /// Type all three Lab components through the numeric fields, then apply the picked color. #[test] fn native_lab_entry_in_color_picker() { diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 355b75f01b..888fca34fb 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -61,6 +61,18 @@ fn nudge_cell(index: usize, delta: i32) -> usize { (index as i32 + delta).clamp(0, last) as usize } +/// The cells in a row of a grid `w` wide that holds `count` cells of side `cell` in a list at most +/// `list_h` tall. When the rows run past the list, its scroll bar takes a column of its own and the +/// cells go beside it; when they fit, the cells take the whole width. +fn grid_cols(ui: &Ui, w: f32, cell: f32, count: usize, list_h: f32) -> usize { + let fit = |room: f32| ((room / cell).floor() as usize).max(1); + let gap = ui.spacing().item_spacing.y; + let cols = fit(w); + // The height `ScrollArea::show_rows` gives the rows: the gaps between them, none after the last. + let content_h = count.div_ceil(cols) as f32 * (cell + gap) - gap; + if list_h.min(ui.available_height()).ceil() < content_h { fit(w - ui.spacing().scroll.allocated_width()) } else { cols } +} + /// Character subsets offered by the Show menu. const SUBSETS: [(&str, u32, u32); 7] = [ ("Entire Font", 0, 0x10FFFF), @@ -372,10 +384,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (chars, unencoded) = grid_glyphs(&face, category.and_then(|i| face.glyph_categories().get(i)), subset, (lo, hi)); let total = chars.len() + unencoded.len(); let cell = CELL_STEPS[cell_index(app)]; - let cols = ((w / cell).floor() as usize).max(1); - let rows = total.div_ceil(cols); let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; let list_h = widgets::panel_list_height(ui, (ui.available_height() - 64.0).max(cell * 3.0), 33.0); + let cols = grid_cols(ui, w, cell, total, list_h); + let rows = total.div_ceil(cols); let hover_id = egui::Id::unique("gl-hover"); let selected = selected_char(app); // What a double-click on an unencoded glyph can do to the selected character. @@ -603,10 +615,10 @@ fn alternates(app: &mut VectorcraftApp, ui: &mut Ui, w: f32) { default: false, })); let cell = CELL_STEPS[cell_index(app)]; - let cols = ((w / cell).floor() as usize).max(1); - let rows = list.len().div_ceil(cols); let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; let list_h = widgets::panel_list_height(ui, (ui.available_height() - 64.0).max(cell * 3.0), 33.0); + let cols = grid_cols(ui, w, cell, list.len(), list_h); + let rows = list.len().div_ceil(cols); let mut pick = None; // A scroll position of its own for each character, so the grid starts at the top for another. let area = egui::ScrollArea::vertical() @@ -2476,6 +2488,117 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); } + /// The panel drawn `width` by `height` after a few frames (the scroll bar fades in): the left + /// edge of its scroll bar, when one is drawn, the grid's cells and the rectangle they are + /// clipped to. + fn grid_with_bar(ctx: &egui::Context, app: &mut VectorcraftApp, width: f32, height: f32, time: &mut f64) -> (Option, Vec, Rect) { + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + let mut shapes = vec![]; + let mut clip = Rect::NOTHING; + for _ in 0..4 { + *time += 0.5; + let raw = + egui::RawInput { time: Some(*time), screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width, height))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + shapes.clear(); + for c in out.shapes { + if !squares(std::slice::from_ref(&c.shape)).is_empty() { + clip = c.clip_rect; + } + flat(c.shape, &mut shapes); + } + } + // The bar's track and handle: narrow filled rectangles taller than a cell. + let bar = shapes + .iter() + .filter_map(|s| match s { + Shape::Rect(r) if r.fill != Color32::TRANSPARENT && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => Some(r.rect.left()), + _ => None, + }) + .min_by(f32::total_cmp); + (bar, squares(&shapes), clip) + } + + /// #5941: the grid's cells go beside its scroll bar. At every panel width the bar shows and the + /// last cell of a row ends before it. + #[test] + fn the_grids_cells_end_before_its_scroll_bar() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let (mut app, id) = editing("\u{628}"); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + for width in 240..=300 { + let (bar, cells, _) = grid_with_bar(&ctx, &mut app, width as f32, 420.0, &mut time); + // Cells wider than the room beside the bar push the bar past the panel's edge. + let Some(bar) = bar else { panic!("width {width}: the grid scrolls and shows its bar") }; + assert!(!cells.is_empty(), "width {width}: the grid is drawn"); + let last = cells.iter().map(|r| r.right()).fold(f32::MIN, f32::max); + assert!(last <= bar - 1.0, "width {width}: the last cell ends at {last}, the bar starts at {bar}"); + } + } + + /// #5941: Alternates for Current Selection lays out its cells the same way. While its rows run + /// past the list, the cells end before the scroll bar; while they fit, no bar shows and the + /// cells fill the whole width. + #[test] + fn the_alternates_grid_leaves_room_for_its_scroll_bar_only_while_it_scrolls() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let (mut app, id) = editing("xay"); + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + select(&mut app, 2, 2); + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + set_pstate(&ctx, "gl-subset", SUBSETS.len()); + let mut time = 0.0; + let (mut scrolled, mut fitted) = (0, 0); + // The largest cells, so seven glyphs fill two to four rows. In a panel 360 pt tall, three + // rows of them run past the list; in one 640 pt tall, they fit. The sweep covers panel + // widths at three heights, then the heights around the one where three rows just fit. + let cell = CELL_STEPS[CELL_STEPS.len() - 1]; + set_cell_index(&mut app, CELL_STEPS.len() - 1); + let sizes = [360, 420, 640].into_iter().flat_map(|h| (240..=320).map(move |w| (w, h))).chain((360..=420).map(|h| (290, h))); + for (width, height) in sizes { + let (bar, cells, clip) = grid_with_bar(&ctx, &mut app, width as f32, height as f32, &mut time); + assert!(!cells.is_empty(), "{width}×{height}: the grid is drawn"); + let last = cells.iter().map(|r| r.right()).fold(f32::MIN, f32::max); + let left = cells.iter().map(|r| r.left()).fold(f32::MAX, f32::min); + let row = cells.iter().filter(|r| (r.top() - cells[0].top()).abs() < 1.0).count(); + // The cells a row holds across the whole width. + let room = (((width as f32 - 2.0 * left) / cell).floor() as usize).clamp(1, 7); + if let Some(bar) = bar { + scrolled += 1; + assert!(last <= bar - 1.0, "{width}×{height}: the last cell ends at {last}, the bar starts at {bar}"); + // Rows narrowed for the bar only when full-width rows would not fit either. + if row < room { + let step = cells.iter().map(|r| r.top() - cells[0].top()).filter(|d| *d > 1.0).fold(f32::MAX, f32::min); + let full = 7usize.div_ceil(room) as f32 * step - (step - cell); + assert!(full > clip.height() + 0.5, "{width}×{height}: {room} to a row would fit in {full} pt, the list is {}", clip.height()); + } + } else { + fitted += 1; + // Without a bar every cell shows whole; a grid that runs past its list would need one. + assert_eq!(cells.len(), 7, "{width}×{height}: a and its six alternates all show"); + let bottom = cells.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); + assert!( + bottom <= clip.bottom() + 0.5 && last <= clip.right() + 0.5, + "{width}×{height}: the cells end at ({last}, {bottom}), inside the list {clip:?}" + ); + assert_eq!(row, room, "{width}×{height}: without a bar a row takes the whole width (cells from {left})"); + } + } + assert!(scrolled > 0 && fitted > 0, "both layouts are drawn: {scrolled} scrolled, {fitted} fitted"); + } + /// Show › Entire Font also lists the glyphs no character maps. #[test] fn entire_font_lists_the_unencoded_glyphs() { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index f7c676d441..9b3792ea6b 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -163,6 +163,53 @@ fn app() -> VectorcraftApp { VectorcraftApp::new(Session::new(), Services::default()) } +/// #5941: a page whose settings run past the bottom of the list showed no scroll bar, so a setting +/// lower on the page was easy to miss. Every page that scrolls shows its bar inside the window, and +/// no label is cut off at the side. +#[test] +fn a_page_that_scrolls_shows_its_bar() { + fn walk(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>, bars: &mut Vec) { + match shape { + egui::Shape::Text(t) if !t.galley.text().trim().is_empty() => texts.push((t.galley.text().into(), t.visual_bounding_rect(), clip)), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, texts, bars)), + _ => {} + } + } + let mut scrolled = 0; + for cat in PREF_CATEGORIES { + let mut a = app(); + open(&mut a, Some(cat)); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let (mut texts, mut bars) = (vec![], vec![]); + for time in [0.0, 0.25, 0.5, 0.75] { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); + let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + (texts, bars) = (vec![], vec![]); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); + } + let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-preferences"))).expect("the dialog window is shown"); + // A label below its clip: the page runs past the bottom of the list. + let scrolls = texts.iter().any(|(_, r, clip)| window.contains_rect(*clip) && r.top() >= clip.bottom()); + if scrolls { + scrolled += 1; + assert!(bars.iter().any(|b| window.contains_rect(*b)), "{cat}: the page scrolls and its bar shows in {window:?}: {bars:?}"); + } + let cut: Vec<_> = texts + .iter() + .filter(|(_, r, clip)| clip.y_range().contains(r.center().y) && (r.left() < clip.left() - 1.0 || r.right() > clip.right() + 1.0)) + .filter(|(_, r, _)| window.intersects(*r)) + .map(|(s, r, clip)| format!("{s:?} {r:?} in {clip:?}")) + .collect(); + assert!(cut.is_empty(), "{cat}: labels cut off at the side: {cut:?}"); + } + assert!(scrolled > 0, "at least one page runs past the bottom of its list"); +} + #[test] fn dialog_ok_applies_prefs_and_ui_fields() { let mut a = app(); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index eeb00ceb62..2314e00e78 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -645,6 +645,9 @@ pub fn apply_with(ctx: &egui::Context, b: Brightness, accent: Accent, scheme: Sc s.spacing.interact_size = egui::vec2(24.0, 24.0); s.spacing.menu_margin = egui::Margin::same(6); s.spacing.slider_width = 120.0; + // Every scroll area shows its bar while it has more to show, in a column of its own, + // not only while the pointer is over it (#5941). + s.spacing.scroll = crate::widgets::list_scroll_style(); s.text_styles = [ (TextStyle::Small, FontId::proportional(11.0)), (TextStyle::Body, FontId::proportional(13.0)), diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 7f088f25ef..431bc4e8f9 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -369,6 +369,8 @@ pub(crate) fn menu_room_either(below: f32, above: f32, tallest: f32) -> f32 { /// The scroll bar of a menu's list: slim, in a column of its own beside the items, so it never /// covers what sits at their right end (shortcuts, submenu arrows, a font's favourite star). +/// `theme::apply` makes it the style of every scroll area that does not set its own, so the bar +/// shows whenever there is more to scroll to (#5941). pub fn list_scroll_style() -> egui::style::ScrollStyle { egui::style::ScrollStyle { bar_width: 6.0, bar_inner_margin: 2.0, ..egui::style::ScrollStyle::solid() } } @@ -561,18 +563,19 @@ fn show_shortened_rows(ui: &Ui, painted: usize) { } /// A column of tool or panel buttons (the toolbar, the dock's icon column) that scrolls when the -/// window is too short for it: with the mouse wheel, or the scroll bar shown while the pointer is -/// over it. +/// window is too short for it: with the mouse wheel, or with its scroll bar. /// Its scroll bar stays a slim line at the edge, even while scrolled or dragged, so it never covers -/// the buttons (#808). +/// the buttons (#808). The line shows while the pointer is elsewhere too (#5941). pub fn strip_scroll(ui: &mut Ui, id: &str, add_contents: impl FnOnce(&mut Ui) -> R) -> R { ui.scope(|ui| { + let floating = egui::style::ScrollStyle::floating(); ui.spacing_mut().scroll = egui::style::ScrollStyle { bar_width: 4.0, floating_width: 2.0, bar_inner_margin: 0.0, bar_outer_margin: 1.0, - ..egui::style::ScrollStyle::floating() + dormant_handle_opacity: floating.active_handle_opacity, + ..floating }; egui::ScrollArea::vertical().id_salt(id).auto_shrink([false, true]).show(ui, add_contents).inner }) diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 274861386b..df12c8ed54 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -67,6 +67,87 @@ fn the_strip_scroll_bar_stays_a_slim_line_while_the_pointer_is_on_it() { assert!(widest > 0.0, "the scroll bar is drawn"); assert!(widest <= 4.5, "the scroll bar is {widest} points wide"); } + +/// The filled rectangles of a scroll bar drawn at the right of `content` in `shapes`: narrow +/// rectangles that start at or past the content's right edge. +fn bar_rects(shapes: &[egui::Shape], content: Rect, widest: f32) -> Vec<(Rect, Color32)> { + shapes + .iter() + .filter_map(|s| match s { + egui::Shape::Rect(r) + if r.fill != Color32::TRANSPARENT && r.rect.width() <= widest && r.rect.height() > 4.0 && r.rect.min.x >= content.right() - 0.5 => + { + Some((r.rect, r.fill)) + } + _ => None, + }) + .collect() +} + +// Regression test for #5941: a scrolling list in a panel or a dialog showed no scroll bar until the +// pointer came over it, so nothing told the user that the list had more rows. In every brightness +// the bar shows while the pointer is elsewhere, in a column of its own beside the rows, and its +// handle stands out from its track. +#[test] +fn a_scroll_bar_shows_while_the_pointer_is_elsewhere() { + for brightness in theme::Brightness::ALL { + let ctx = themed(brightness); + let rows = std::cell::Cell::new(Rect::NOTHING); + let mut add = |ui: &mut Ui| { + ui.allocate_ui(vec2(160.0, 200.0), |ui| { + egui::ScrollArea::vertical().id_salt("list").auto_shrink([false, false]).show(ui, |ui| { + for i in 0..40 { + ui.label(format!("Row {i}")); + } + rows.set(ui.max_rect()); + }); + }); + }; + frame(&ctx, 0.0, vec![egui::Event::PointerMoved(pos2(500.0, 350.0))], &mut add); + let shapes = frame(&ctx, 1.0, vec![], &mut add); + let rows = rows.get(); + assert!(rows.width() < 160.0, "{brightness:?}: the rows leave a column for the bar: {rows:?}"); + let bar = bar_rects(&shapes, rows, 10.0); + let (Some(track), Some(handle)) = + (bar.iter().max_by(|a, b| a.0.height().total_cmp(&b.0.height())), bar.iter().min_by(|a, b| a.0.height().total_cmp(&b.0.height()))) + else { + panic!("{brightness:?}: the scroll bar is drawn at rest: {bar:?}"); + }; + assert!(handle.0.height() < track.0.height(), "{brightness:?}: a handle on a track: {bar:?}"); + assert_eq!(handle.1.a(), 255, "{brightness:?}: the handle is opaque: {:?}", handle.1); + let gap = (i32::from(handle.1.r()) - i32::from(track.1.r())).abs(); + assert!(gap >= 24, "{brightness:?}: handle {:?} on track {:?}", handle.1, track.1); + } +} + +// Regression test for #5941: the toolbar's and the dock icon column's scroll bar showed nothing +// until the pointer came over the column. Its slim line shows at rest, still at most 4 points +// wide (#808). +#[test] +fn the_strip_scroll_bar_shows_while_the_pointer_is_elsewhere() { + let ctx = themed(Default::default()); + let column = std::cell::Cell::new(Rect::NOTHING); + let mut add = |ui: &mut Ui| { + column.set( + ui.allocate_ui(vec2(80.0, 200.0), |ui| { + strip_scroll(ui, "strip", |ui| { + for i in 0..40 { + ui.label(format!("Tool {i}")); + } + }); + }) + .response + .rect, + ); + }; + frame(&ctx, 0.0, vec![egui::Event::PointerMoved(pos2(500.0, 350.0))], &mut add); + let shapes = frame(&ctx, 1.0, vec![], &mut add); + let column = column.get(); + // The bar lies along the column's right edge, inside it. + let buttons = Rect::from_min_max(column.min, pos2(column.right() - 6.0, column.bottom())); + let bar = bar_rects(&shapes, buttons, 4.5); + assert!(!bar.is_empty(), "the slim scroll bar is drawn at rest"); +} // Regression test for #900: a number field with a spinner and a preset list drew as three // boxes side by side: its text box was a point taller than the 26-point row, and each joint had // two borders. From ae1afda79d579c709ce9bc9b394545cdf35fc760 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:35:39 -0800 Subject: [PATCH 2/3] Fix #5941: dialogs too large for the window scroll instead of running off the screen A dialog taller than the app window was drawn past its top and bottom edges, with no scroll bar, so its first options and its buttons could not be reached. At 1024 by 480 this happened to SVG, EPS and DXF Options, Save PDF, Save for Web, Export for Screens, Print, Preferences, Keyboard Shortcuts, New Document and Find Font. - The body of a shared dialog scrolls while the dialog would be taller than the window, and its heading and buttons stay in view. - A dialog window without such a body (Preferences, Keyboard Shortcuts, New Document, Find Font) scrolls as a whole while it is taller or wider than the window, at the 800 by 500 minimum window size too. - Dialogs that already size their lists from the window's height (Character and Paragraph Style Options, the Color Picker, Import Shortcut Set and the dialogs that use scrolled_rows) are not scrolled again. - A dialog that is closed and opened again starts at its top, for its scrolling body, its scrolled_rows and the window as a whole, instead of where it was left. - Save for Web in a window narrower than its full layout (800 pt, the smallest window) draws its preview panes narrower, down to 240 pt, so the settings column and the buttons stay in view instead of scrolling off to the side. - A field being edited keeps its text and focus when the window is resized so that the dialog starts or stops scrolling: its contents keep their ids either way. Tests: the Save for Web settings and the Print sections show their bar at rest; the export option dialogs at 1024 by 480 stay on screen with their buttons in view and their bar drawn; Preferences, Keyboard Shortcuts, New Document and Find Font at 800 by 500 stay on screen with their bar drawn; Save for Web at 800 by 500 shows its settings and buttons and no sideways bar; a modal window scrolled with the wheel opens again at its top, both when it scrolls as a whole and when its rows scroll; a field keeps its id when the body or the window starts or stops scrolling. The Print test that types into Scale W picks W as the leftmost of the matching fields, since the accessibility tree lists its nodes in no particular order. --- crates/ui-egui/src/dialogs.rs | 9 +- .../ui-egui/src/dialogs/char_style_options.rs | 1 + crates/ui-egui/src/dialogs/color_picker.rs | 1 + crates/ui-egui/src/dialogs/modal.rs | 269 ++++++++++++++++-- .../ui-egui/src/dialogs/para_style_options.rs | 1 + crates/ui-egui/src/dialogs/save_for_web.rs | 28 +- crates/ui-egui/src/dialogs/shortcut_import.rs | 1 + crates/ui-egui/src/dialogs/tests_print.rs | 8 +- crates/ui-egui/src/dialogs/tests_scroll.rs | 186 ++++++++++++ 9 files changed, 475 insertions(+), 29 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tests_scroll.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..a316a940bc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -856,14 +856,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } + // A body taller than the window has room for scrolls, so the heading and the buttons stay + // in view. if let Some(body) = spec.body_with_actions { - match body(app, ui, &mut d) { + match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { DialogAction::None => {} DialogAction::Confirm => ok = true, DialogAction::Cancel => cancel = true, } } else { - cancel = (spec.body)(app, ui, &mut d); + cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { @@ -1050,3 +1052,6 @@ mod tests_shortcut_import; #[cfg(test)] mod tests_warp; + +#[cfg(test)] +mod tests_scroll; diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 02515a3b89..c3a913d990 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index c16d8d9e6e..7a3fead117 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -354,6 +354,7 @@ 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"); diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index f72383068e..b3ab0efde9 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -2,8 +2,9 @@ //! window with no title bar that opens centred and moves by dragging its heading (the band from its //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows -//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons -//! stay in view. +//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its +//! heading and buttons stay in view. A window without such rows that is still too tall or too wide +//! for the screen scrolls as a whole on that axis. use egui::{Id, Rect, Vec2}; @@ -25,6 +26,16 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); }); + // Not drawn in the pass before this one: the window just opened, and what scrolls in it starts + // at its top, wherever it was left when the window last closed. + let pass = ctx.cumulative_pass_nr(); + let last = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass)); + if last == u64::MAX || last.saturating_add(1) < pass { + ctx.data_mut(|m| { + m.insert_temp(id.with(TOP_ROWS_KEY), true); + m.insert_temp(id.with(TOP_WHOLE_KEY), true); + }); + } let shown = egui::Window::new(title) .id(id) .order(egui::Order::Foreground) @@ -33,11 +44,43 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .title_bar(false) .anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin))) - .show(ctx, add)?; - keep_rest(ctx, id, shown.response.rect.height()); + .show(ctx, |ui| { + // A window whose contents are wider than the screen has room for, or taller without + // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, + // so none of it is out of reach. The contents keep their ids whether the window scrolls + // or not, so a field being edited keeps its text when that changes. + let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); + let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); + let (r, contents) = if wide || tall { + let room = whole_room(ctx, margin); + let mut area = egui::ScrollArea::new([wide, tall]); + if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let out = area + .id_salt("modal-whole") + .max_width(room.x) + .max_height(room.y) + .min_scrolled_width(room.x) + .min_scrolled_height(room.y) + .show(ui, |ui| ui.scope_builder(scope, add).inner); + (out.inner, out.content_size) + } else { + let r = ui.scope_builder(scope, add).inner; + (r, ui.min_rect().size()) + }; + ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); + r + })?; + keep_rest(ctx, id, shown.response.rect.height(), margin); shown.inner } +/// The room for the contents of a modal window with `margin` inside its frame. +fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { + (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) +} + /// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of /// the app would get. pub(crate) fn backdrop() -> egui::LayerId { @@ -73,34 +116,119 @@ pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } -/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall -/// the rest of it was when last drawn. +/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this +/// frame, and how tall the rest of it was when last drawn. const ROWS_KEY: &str = "modal-rows"; const REST_KEY: &str = "modal-rest"; +/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to +/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). +const OWN_ROWS_KEY: &str = "modal-own-rows"; +const OWN_BEFORE_KEY: &str = "modal-own-before"; +/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. +const BODY_KEY: &str = "modal-body"; +/// Under a modal window's id: how large its contents would be without scrolling as a whole, this +/// frame. +const CONTENTS_KEY: &str = "modal-contents"; +/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on +/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). +const TALL_KEY: &str = "modal-tall"; +const WHOLE_KEY: &str = "modal-whole"; +/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened, +/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so +/// they start at the top when they first do. +const SHOWN_KEY: &str = "modal-shown"; +const TOP_ROWS_KEY: &str = "modal-top-rows"; +const TOP_WHOLE_KEY: &str = "modal-top-whole"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as /// last drawn (a frame late, as only the drawn window knows its height). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + fits_itself(ui); + let (r, drawn, _) = rows(ui, salt, true, add); + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); + r +} + +/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing +/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window +/// scroll them again. +pub(crate) fn fits_itself(ui: &egui::Ui) { + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); +} + +/// The body of a shared dialog window. While the window would be taller than the screen has room +/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; +/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. +pub(crate) fn body_rows(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let id = ui.layer_id().id; + let own = ui.ctx().data(|m| m.get_temp::(id.with(OWN_BEFORE_KEY))).unwrap_or(false); + let tall = !own && ui.ctx().data(|m| m.get_temp::(id.with(TALL_KEY))).unwrap_or(false); + let (r, drawn, body) = rows(ui, "dialog-body", tall, add); + if !ui.ctx().data(|m| m.get_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false) { + ui.ctx().data_mut(|m| { + m.insert_temp(id.with(ROWS_KEY), drawn); + m.insert_temp(id.with(BODY_KEY), body); + }); + } + r +} + +/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their +/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling. +/// Rows that do not `scroll` are as tall as they are, with no +/// scroll area (which would take the scroll requests of their fields from the window's). The rows +/// keep their ids either way, so a field being edited keeps its text when they start or stop +/// scrolling. +fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { let id = ui.layer_id().id; let rest = ui.ctx().data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0); + let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); + if !scroll { + let rows = ui.scope_builder(scope, add); + let height = rows.response.rect.height(); + return (rows.inner, height, height); + } // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. - let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner); - ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height())); - rows.inner + let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room); + if ui.ctx().data_mut(|m| m.remove_temp::(id.with(TOP_ROWS_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner)); + (rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y) } -/// After modal window `id` is drawn `height` tall: keep the height of all of it but its -/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just -/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit -/// without waiting for input. -fn keep_rest(ctx: &egui::Context, id: Id, height: f32) { - let Some(rows) = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))) else { return }; - let rest = (height - rows).max(0.0); - let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); - if (used - rest).abs() > 0.5 { +/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height +/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different +/// one (the window just opened, or what is around them changed), the next frame is drawn at once, +/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll +/// while the window would be taller than the screen has room for without them scrolling; a window +/// without rows that scroll scrolls as a whole while its contents would be taller than the room, +/// and any window scrolls sideways while its contents would be wider. +fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { + let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); + let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); + let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); + let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); + ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); + let room = whole_room(ctx, margin); + let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; + let tall = match (rows, body) { + (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, + _ => false, + }; + let whole = [!own && contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; + let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); + let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); + let mut repaint = tall != was_tall || whole != was_whole; + if let Some(rows) = rows { + let rest = (height - rows).max(0.0); + let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); + repaint |= (used - rest).abs() > 0.5; + } + if repaint { ctx.request_repaint(); } } @@ -146,4 +274,109 @@ mod tests { // Larger than the screen: its top left stays in view. assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0)); } + + /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with a modal + /// window open when `open`: a heading and 60 rows, in [`scrolled_rows`] when `in_rows`. Returns + /// whether the first row could be seen in the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: bool, 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 { + ui.label(format!("Row {i}")); + } + }; + let mut events = Some(events); + let mut seen = false; + for _ in 0..frames { + *time += 1.0 / 60.0; + 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 open { + show(ui.ctx(), "Test", Id::unique("modal-reopen-test"), 0.0, 8, |ui| { + heading(ui, "Top"); + if in_rows { + scrolled_rows(ui, "rows", add); + } else { + add(ui); + } + }); + } + }); + out.textures_delta.clear(); + seen = out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r) + } + _ => false, + }); + } + seen + } + + #[test] + fn a_window_that_scrolled_opens_again_at_its_top() { + for in_rows in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + assert!(first_row_seen(&ctx, true, in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + let events = vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel]; + assert!(!first_row_seen(&ctx, true, in_rows, events, &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, false, in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, true, in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + } + } + + #[test] + fn a_field_keeps_its_id_when_the_window_starts_or_stops_scrolling() { + // A field's typed text and focus are kept under its id, so the id must not change when the + // screen's height changes whether the body or the window scrolls. + for in_body in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let window = Id::unique("modal-field-id-test"); + let mut time = 0.0; + let mut field_at = |height: f32| { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); + let mut field = None; + for _ in 0..4 { + time += 1.0 / 60.0; + let input = egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + show(ui.ctx(), "Test", window, 0.0, 8, |ui| { + heading(ui, "Top"); + let add = |ui: &mut egui::Ui| { + let r = ui.text_edit_singleline(&mut String::from("12")); + for i in 0..30 { + ui.label(format!("Row {i}")); + } + r.id + }; + field = Some(if in_body { body_rows(ui, add) } else { add(ui) }); + }); + }); + out.textures_delta.clear(); + } + let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; + let scrolls = ctx.data(|m| m.get_temp::(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1])); + (field, scrolls) + }; + let (tall_id, tall_scrolls) = field_at(900.0); + let (short_id, short_scrolls) = field_at(300.0); + let (again_id, again_scrolls) = field_at(900.0); + assert!(!tall_scrolls && short_scrolls && !again_scrolls, "body {in_body}: only the short screen scrolls"); + assert!(tall_id.is_some(), "body {in_body}: the field is drawn"); + assert_eq!(tall_id, short_id, "body {in_body}: the field keeps its id when the window starts scrolling"); + assert_eq!(short_id, again_id, "body {in_body}: the field keeps its id when the window stops scrolling"); + } + } } diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index d63d43be89..65c1838419 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 589d1dfdce..09d0f0e881 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -52,6 +52,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// The preview area (panes and their captions) and the settings column. const PREVIEW_W: f32 = 620.0; +/// The narrowest the panes get in a narrow window. +const MIN_PREVIEW_W: f32 = 240.0; const PREVIEW_H: f32 = 470.0; const SIDE_W: f32 = 296.0; const GAP: f32 = 16.0; @@ -532,10 +534,18 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } let settings = settings_of(app, d); let mut browser = false; - ui.horizontal_top(|ui| { + // In a window too narrow for both, the panes are narrower, so the settings beside them and the + // buttons below stay in view. The room is the screen's (the window's own width follows what it + // drew last), less a column for the bar of the body when it scrolls; the settings column is as + // wide as it was drawn last. + let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - ui.spacing().scroll.allocated_width(); + let rest_id = egui::Id::unique("save-for-web-beside-panes"); + let rest = ui.ctx().data(|m| m.get_temp::(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W); + let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W); + let row = ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(PREVIEW_W); - browser = preview_area(app, ui, d, &settings); + ui.set_width(preview_w); + browser = preview_area(app, ui, d, &settings, preview_w); }); ui.add_space(GAP); ui.vertical(|ui| { @@ -543,6 +553,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); + let drawn = row.response.rect.width() - preview_w; + if ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) != drawn { + ui.ctx().request_repaint(); + } optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); @@ -550,16 +564,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was -/// clicked. -fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result) -> bool { +/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in +/// Browser was clicked. +fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result, width: f32) -> bool { let t = Tokens::get(ui.ctx()); let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2); if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) { d.fields.insert("__view".into(), json!(VIEWS[i])); } ui.add_space(4.0); - let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag()); + let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag()); let pan_id = egui::Id::unique("save-for-web-pan"); let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default(); if resp.dragged() { diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 0516695233..e6c9a6ee0a 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { + crate::dialogs::modal::fits_itself(ui); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index cad38bb984..00b45e0db7 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None }) } -/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out. +/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out. fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) { let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; screen.run(app, vec![]); let out = screen.run(app, vec![]); let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; - let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))); + // W is left of H on their row (the tree lists its nodes in no particular order). + let w = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))) + .min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0))); screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]); screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]); screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]); diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs new file mode 100644 index 0000000000..65df0bc400 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -0,0 +1,186 @@ +//! Dialogs in a short or narrow window: options that run past their list show its scroll bar at +//! rest, and a dialog too large for the window scrolls instead of running off the screen. +use egui::{Pos2, Rect, Shape, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use super::*; + +type Open = fn(&mut VectorcraftApp); + +/// What a dialog drew: the shapes, and the dialog window's rectangle. +struct Shown { + shapes: Vec, + window: Rect, +} + +/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away +/// from the dialog), and draw it until it settles. +fn show_in(open: Open, size: egui::Vec2) -> Shown { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + open(&mut app); + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut shapes = vec![]; + for i in 0..12 { + let events = if i == 0 { vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))] } else { vec![] }; + let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(f64::from(i)), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(&mut app, ui.ctx())); + out.textures_delta.clear(); + shapes = out.shapes; + } + let window = ctx.memory(|m| { + m.areas() + .visible_layer_ids() + .into_iter() + .filter(|l| l.order == egui::Order::Foreground) + .filter_map(|l| m.area_rect(l.id)) + .max_by(|a, b| a.area().total_cmp(&b.area())) + }); + Shown { shapes, window: window.unwrap_or(Rect::NOTHING) } +} + +/// Filled upright bars 4 to 10 pt wide and taller than 12 pt (vertical scroll bars and their +/// handles) inside the dialog window. +fn bars(shown: &Shown) -> Vec { + fn walk(s: &Shape, clip: Rect, out: &mut Vec) { + match s { + Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT && (4.0..=10.0).contains(&r.rect.width()) && r.rect.height() > 12.0 => { + if clip.contains_rect(r.rect) { + out.push(r.rect); + } + } + 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.retain(|r| shown.window.expand(0.5).contains_rect(*r)); + out +} + +/// 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 + .into_iter() + .filter(|(s, ..)| labels.contains(&s.as_str())) + .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) + .collect() +} + +#[test] +fn the_export_options_that_run_past_their_list_show_its_bar_at_rest() { + let opens: [(&str, Open); 2] = [ + ("Save for Web", |app| { + save_for_web::open(app).unwrap(); + }), + ("Print", |app| { + print::open(app).unwrap(); + }), + ]; + for (name, open) in opens { + let shown = show_in(open, vec2(1280.0, 900.0)); + assert!(!bars(&shown).is_empty(), "{name}: the settings scroll and their bar is drawn at rest"); + } +} + +#[test] +fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() { + let opens: [(&str, Open, &[&str]); 6] = [ + ("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]), + ("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]), + ("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]), + ( + "Save PDF", + |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + }, + &["Cancel"], + ), + ( + "Save for Web", + |app| { + save_for_web::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ("Export for Screens", export_for_screens::open, &["Cancel"]), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0)); + assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window); + let shown = show_in(open, screen.size()); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + let found = buttons(&shown, screen, labels); + assert_eq!(found.len(), labels.len(), "{name}: {found:?}"); + assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}"); + assert!(!bars(&shown).is_empty(), "{name}: the body scrolls and its bar is drawn"); + } +} + +#[test] +fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() { + let open: Open = |app| { + save_for_web::open(app).unwrap(); + }; + // The app window's smallest size. + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let shown = show_in(open, screen.size()); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + let found = buttons(&shown, screen, &["Optimize to File Size…", "Cancel", "Done"]); + assert_eq!(found.len(), 3, "{found:?}"); + assert!(found.iter().all(|(_, seen)| *seen), "the settings and the buttons stay in view: {found:?}"); + assert!(!bars(&shown).is_empty(), "the settings scroll and their bar is drawn"); + // A sideways bar: flat, and wider than any slider in the dialog. + fn sideways(s: &Shape, out: &mut Vec) { + match s { + Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT && (4.0..=10.0).contains(&r.rect.height()) && r.rect.width() > 300.0 => { + out.push(r.rect) + } + Shape::Vec(v) => v.iter().for_each(|s| sideways(s, out)), + _ => {} + } + } + let mut found = vec![]; + shown.shapes.iter().for_each(|c| sideways(&c.shape, &mut found)); + assert!(found.is_empty(), "the dialog fits the window's width and does not scroll sideways: {found:?}"); +} + +#[test] +fn a_window_too_large_for_the_screen_scrolls_as_a_whole() { + let opens: [(&str, Open); 4] = [ + ("Preferences", |app| crate::prefs_dialog::open(app, None)), + ("Keyboard Shortcuts", crate::shortcut_editor::open), + ("New Document", new_document::open), + ("Find Font", crate::find_font::open), + ]; + // The app window's smallest size. + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + for (name, open) in opens { + let tall = show_in(open, vec2(1280.0, 900.0)); + assert!( + tall.window.height() > screen.height() || tall.window.width() > screen.width(), + "{name}: the dialog is larger than the small window ({:?})", + tall.window + ); + let shown = show_in(open, screen.size()); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + assert!(!bars(&shown).is_empty(), "{name}: the dialog scrolls and its bar is drawn"); + } +} From 9135a981862ea6f22a03397c8ae46144d4a401f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:28:32 -0800 Subject: [PATCH 3/3] Revert dialog scrolling; it moves to its own pull request This reverts commit ae1afda79d579c709ce9bc9b394545cdf35fc760. Dialogs that are too large for the window are handled in a separate pull request. --- crates/ui-egui/src/dialogs.rs | 9 +- .../ui-egui/src/dialogs/char_style_options.rs | 1 - crates/ui-egui/src/dialogs/color_picker.rs | 1 - crates/ui-egui/src/dialogs/modal.rs | 269 ++---------------- .../ui-egui/src/dialogs/para_style_options.rs | 1 - crates/ui-egui/src/dialogs/save_for_web.rs | 28 +- crates/ui-egui/src/dialogs/shortcut_import.rs | 1 - crates/ui-egui/src/dialogs/tests_print.rs | 8 +- crates/ui-egui/src/dialogs/tests_scroll.rs | 186 ------------ 9 files changed, 29 insertions(+), 475 deletions(-) delete mode 100644 crates/ui-egui/src/dialogs/tests_scroll.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a316a940bc..9e54eb12f6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -856,16 +856,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } - // A body taller than the window has room for scrolls, so the heading and the buttons stay - // in view. if let Some(body) = spec.body_with_actions { - match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { + match body(app, ui, &mut d) { DialogAction::None => {} DialogAction::Confirm => ok = true, DialogAction::Cancel => cancel = true, } } else { - cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); + cancel = (spec.body)(app, ui, &mut d); } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { @@ -1052,6 +1050,3 @@ mod tests_shortcut_import; #[cfg(test)] mod tests_warp; - -#[cfg(test)] -mod tests_scroll; diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index c3a913d990..02515a3b89 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1036,7 +1036,6 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 7a3fead117..c16d8d9e6e 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -354,7 +354,6 @@ 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"); diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index b3ab0efde9..f72383068e 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -2,9 +2,8 @@ //! window with no title bar that opens centred and moves by dragging its heading (the band from its //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows -//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its -//! heading and buttons stay in view. A window without such rows that is still too tall or too wide -//! for the screen scrolls as a whole on that axis. +//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons +//! stay in view. use egui::{Id, Rect, Vec2}; @@ -26,16 +25,6 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); }); - // Not drawn in the pass before this one: the window just opened, and what scrolls in it starts - // at its top, wherever it was left when the window last closed. - let pass = ctx.cumulative_pass_nr(); - let last = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass)); - if last == u64::MAX || last.saturating_add(1) < pass { - ctx.data_mut(|m| { - m.insert_temp(id.with(TOP_ROWS_KEY), true); - m.insert_temp(id.with(TOP_WHOLE_KEY), true); - }); - } let shown = egui::Window::new(title) .id(id) .order(egui::Order::Foreground) @@ -44,43 +33,11 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .title_bar(false) .anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin))) - .show(ctx, |ui| { - // A window whose contents are wider than the screen has room for, or taller without - // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, - // so none of it is out of reach. The contents keep their ids whether the window scrolls - // or not, so a field being edited keeps its text when that changes. - let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); - let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); - let (r, contents) = if wide || tall { - let room = whole_room(ctx, margin); - let mut area = egui::ScrollArea::new([wide, tall]); - if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { - area = area.scroll_offset(Vec2::ZERO); - } - let out = area - .id_salt("modal-whole") - .max_width(room.x) - .max_height(room.y) - .min_scrolled_width(room.x) - .min_scrolled_height(room.y) - .show(ui, |ui| ui.scope_builder(scope, add).inner); - (out.inner, out.content_size) - } else { - let r = ui.scope_builder(scope, add).inner; - (r, ui.min_rect().size()) - }; - ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); - r - })?; - keep_rest(ctx, id, shown.response.rect.height(), margin); + .show(ctx, add)?; + keep_rest(ctx, id, shown.response.rect.height()); shown.inner } -/// The room for the contents of a modal window with `margin` inside its frame. -fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { - (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) -} - /// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of /// the app would get. pub(crate) fn backdrop() -> egui::LayerId { @@ -116,119 +73,34 @@ pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } -/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this -/// frame, and how tall the rest of it was when last drawn. +/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall +/// the rest of it was when last drawn. const ROWS_KEY: &str = "modal-rows"; const REST_KEY: &str = "modal-rest"; -/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to -/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). -const OWN_ROWS_KEY: &str = "modal-own-rows"; -const OWN_BEFORE_KEY: &str = "modal-own-before"; -/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. -const BODY_KEY: &str = "modal-body"; -/// Under a modal window's id: how large its contents would be without scrolling as a whole, this -/// frame. -const CONTENTS_KEY: &str = "modal-contents"; -/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on -/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). -const TALL_KEY: &str = "modal-tall"; -const WHOLE_KEY: &str = "modal-whole"; -/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened, -/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so -/// they start at the top when they first do. -const SHOWN_KEY: &str = "modal-shown"; -const TOP_ROWS_KEY: &str = "modal-top-rows"; -const TOP_WHOLE_KEY: &str = "modal-top-whole"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as /// last drawn (a frame late, as only the drawn window knows its height). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - fits_itself(ui); - let (r, drawn, _) = rows(ui, salt, true, add); - ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); - r -} - -/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing -/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window -/// scroll them again. -pub(crate) fn fits_itself(ui: &egui::Ui) { - ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); -} - -/// The body of a shared dialog window. While the window would be taller than the screen has room -/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; -/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. -pub(crate) fn body_rows(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - let id = ui.layer_id().id; - let own = ui.ctx().data(|m| m.get_temp::(id.with(OWN_BEFORE_KEY))).unwrap_or(false); - let tall = !own && ui.ctx().data(|m| m.get_temp::(id.with(TALL_KEY))).unwrap_or(false); - let (r, drawn, body) = rows(ui, "dialog-body", tall, add); - if !ui.ctx().data(|m| m.get_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false) { - ui.ctx().data_mut(|m| { - m.insert_temp(id.with(ROWS_KEY), drawn); - m.insert_temp(id.with(BODY_KEY), body); - }); - } - r -} - -/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their -/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling. -/// Rows that do not `scroll` are as tall as they are, with no -/// scroll area (which would take the scroll requests of their fields from the window's). The rows -/// keep their ids either way, so a field being edited keeps its text when they start or stop -/// scrolling. -fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { let id = ui.layer_id().id; let rest = ui.ctx().data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0); - let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); - if !scroll { - let rows = ui.scope_builder(scope, add); - let height = rows.response.rect.height(); - return (rows.inner, height, height); - } // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. - let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room); - if ui.ctx().data_mut(|m| m.remove_temp::(id.with(TOP_ROWS_KEY))).is_some() { - area = area.scroll_offset(Vec2::ZERO); - } - let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner)); - (rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y) + let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner); + ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height())); + rows.inner } -/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height -/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different -/// one (the window just opened, or what is around them changed), the next frame is drawn at once, -/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll -/// while the window would be taller than the screen has room for without them scrolling; a window -/// without rows that scroll scrolls as a whole while its contents would be taller than the room, -/// and any window scrolls sideways while its contents would be wider. -fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { - let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); - let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); - let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); - let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); - ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); - let room = whole_room(ctx, margin); - let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; - let tall = match (rows, body) { - (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, - _ => false, - }; - let whole = [!own && contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; - let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); - let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); - let mut repaint = tall != was_tall || whole != was_whole; - if let Some(rows) = rows { - let rest = (height - rows).max(0.0); - let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); - repaint |= (used - rest).abs() > 0.5; - } - if repaint { +/// After modal window `id` is drawn `height` tall: keep the height of all of it but its +/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just +/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit +/// without waiting for input. +fn keep_rest(ctx: &egui::Context, id: Id, height: f32) { + let Some(rows) = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))) else { return }; + let rest = (height - rows).max(0.0); + let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); + if (used - rest).abs() > 0.5 { ctx.request_repaint(); } } @@ -274,109 +146,4 @@ mod tests { // Larger than the screen: its top left stays in view. assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0)); } - - /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with a modal - /// window open when `open`: a heading and 60 rows, in [`scrolled_rows`] when `in_rows`. Returns - /// whether the first row could be seen in the last frame (inside the screen and its clip). - fn first_row_seen(ctx: &egui::Context, open: bool, 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 { - ui.label(format!("Row {i}")); - } - }; - let mut events = Some(events); - let mut seen = false; - for _ in 0..frames { - *time += 1.0 / 60.0; - 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 open { - show(ui.ctx(), "Test", Id::unique("modal-reopen-test"), 0.0, 8, |ui| { - heading(ui, "Top"); - if in_rows { - scrolled_rows(ui, "rows", add); - } else { - add(ui); - } - }); - } - }); - out.textures_delta.clear(); - seen = out.shapes.iter().any(|c| match &c.shape { - egui::Shape::Text(t) => { - let r = t.visual_bounding_rect(); - t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r) - } - _ => false, - }); - } - seen - } - - #[test] - fn a_window_that_scrolled_opens_again_at_its_top() { - for in_rows in [false, true] { - let ctx = egui::Context::default(); - crate::theme::apply(&ctx, Default::default()); - let mut time = 0.0; - assert!(first_row_seen(&ctx, true, in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); - let wheel = egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -3000.0), - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Unknown, - modifiers: egui::Modifiers::NONE, - }; - let events = vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel]; - assert!(!first_row_seen(&ctx, true, in_rows, events, &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); - first_row_seen(&ctx, false, in_rows, vec![], &mut time, 2); - assert!(first_row_seen(&ctx, true, in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); - } - } - - #[test] - fn a_field_keeps_its_id_when_the_window_starts_or_stops_scrolling() { - // A field's typed text and focus are kept under its id, so the id must not change when the - // screen's height changes whether the body or the window scrolls. - for in_body in [false, true] { - let ctx = egui::Context::default(); - crate::theme::apply(&ctx, Default::default()); - let window = Id::unique("modal-field-id-test"); - let mut time = 0.0; - let mut field_at = |height: f32| { - let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); - let mut field = None; - for _ in 0..4 { - time += 1.0 / 60.0; - let input = egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - show(ui.ctx(), "Test", window, 0.0, 8, |ui| { - heading(ui, "Top"); - let add = |ui: &mut egui::Ui| { - let r = ui.text_edit_singleline(&mut String::from("12")); - for i in 0..30 { - ui.label(format!("Row {i}")); - } - r.id - }; - field = Some(if in_body { body_rows(ui, add) } else { add(ui) }); - }); - }); - out.textures_delta.clear(); - } - let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; - let scrolls = ctx.data(|m| m.get_temp::(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1])); - (field, scrolls) - }; - let (tall_id, tall_scrolls) = field_at(900.0); - let (short_id, short_scrolls) = field_at(300.0); - let (again_id, again_scrolls) = field_at(900.0); - assert!(!tall_scrolls && short_scrolls && !again_scrolls, "body {in_body}: only the short screen scrolls"); - assert!(tall_id.is_some(), "body {in_body}: the field is drawn"); - assert_eq!(tall_id, short_id, "body {in_body}: the field keeps its id when the window starts scrolling"); - assert_eq!(short_id, again_id, "body {in_body}: the field keeps its id when the window stops scrolling"); - } - } } diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 65c1838419..d63d43be89 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -982,7 +982,6 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 09d0f0e881..589d1dfdce 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -52,8 +52,6 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// The preview area (panes and their captions) and the settings column. const PREVIEW_W: f32 = 620.0; -/// The narrowest the panes get in a narrow window. -const MIN_PREVIEW_W: f32 = 240.0; const PREVIEW_H: f32 = 470.0; const SIDE_W: f32 = 296.0; const GAP: f32 = 16.0; @@ -534,18 +532,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } let settings = settings_of(app, d); let mut browser = false; - // In a window too narrow for both, the panes are narrower, so the settings beside them and the - // buttons below stay in view. The room is the screen's (the window's own width follows what it - // drew last), less a column for the bar of the body when it scrolls; the settings column is as - // wide as it was drawn last. - let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - ui.spacing().scroll.allocated_width(); - let rest_id = egui::Id::unique("save-for-web-beside-panes"); - let rest = ui.ctx().data(|m| m.get_temp::(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W); - let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W); - let row = ui.horizontal_top(|ui| { + ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(preview_w); - browser = preview_area(app, ui, d, &settings, preview_w); + ui.set_width(PREVIEW_W); + browser = preview_area(app, ui, d, &settings); }); ui.add_space(GAP); ui.vertical(|ui| { @@ -553,10 +543,6 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); - let drawn = row.response.rect.width() - preview_w; - if ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) != drawn { - ui.ctx().request_repaint(); - } optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); @@ -564,16 +550,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in -/// Browser was clicked. -fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result, width: f32) -> bool { +/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was +/// clicked. +fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result) -> bool { let t = Tokens::get(ui.ctx()); let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2); if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) { d.fields.insert("__view".into(), json!(VIEWS[i])); } ui.add_space(4.0); - let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag()); + let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag()); let pan_id = egui::Id::unique("save-for-web-pan"); let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default(); if resp.dragged() { diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index e6c9a6ee0a..0516695233 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -670,7 +670,6 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { - crate::dialogs::modal::fits_itself(ui); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 00b45e0db7..cad38bb984 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -428,17 +428,13 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None }) } -/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out. +/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out. fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) { let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; screen.run(app, vec![]); let out = screen.run(app, vec![]); let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; - // W is left of H on their row (the tree lists its nodes in no particular order). - let w = nodes - .iter() - .filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))) - .min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0))); + let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))); screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]); screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]); screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]); diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs deleted file mode 100644 index 65df0bc400..0000000000 --- a/crates/ui-egui/src/dialogs/tests_scroll.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! Dialogs in a short or narrow window: options that run past their list show its scroll bar at -//! rest, and a dialog too large for the window scrolls instead of running off the screen. -use egui::{Pos2, Rect, Shape, vec2}; -use serde_json::json; -use vectorcraft_engine::Session; - -use super::*; - -type Open = fn(&mut VectorcraftApp); - -/// What a dialog drew: the shapes, and the dialog window's rectangle. -struct Shown { - shapes: Vec, - window: Rect, -} - -/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away -/// from the dialog), and draw it until it settles. -fn show_in(open: Open, size: egui::Vec2) -> Shown { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); - app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, Default::default()); - open(&mut app); - let screen = Rect::from_min_size(Pos2::ZERO, size); - let mut shapes = vec![]; - for i in 0..12 { - let events = if i == 0 { vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))] } else { vec![] }; - let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(f64::from(i)), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| show(&mut app, ui.ctx())); - out.textures_delta.clear(); - shapes = out.shapes; - } - let window = ctx.memory(|m| { - m.areas() - .visible_layer_ids() - .into_iter() - .filter(|l| l.order == egui::Order::Foreground) - .filter_map(|l| m.area_rect(l.id)) - .max_by(|a, b| a.area().total_cmp(&b.area())) - }); - Shown { shapes, window: window.unwrap_or(Rect::NOTHING) } -} - -/// Filled upright bars 4 to 10 pt wide and taller than 12 pt (vertical scroll bars and their -/// handles) inside the dialog window. -fn bars(shown: &Shown) -> Vec { - fn walk(s: &Shape, clip: Rect, out: &mut Vec) { - match s { - Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT && (4.0..=10.0).contains(&r.rect.width()) && r.rect.height() > 12.0 => { - if clip.contains_rect(r.rect) { - out.push(r.rect); - } - } - 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.retain(|r| shown.window.expand(0.5).contains_rect(*r)); - out -} - -/// 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 - .into_iter() - .filter(|(s, ..)| labels.contains(&s.as_str())) - .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) - .collect() -} - -#[test] -fn the_export_options_that_run_past_their_list_show_its_bar_at_rest() { - let opens: [(&str, Open); 2] = [ - ("Save for Web", |app| { - save_for_web::open(app).unwrap(); - }), - ("Print", |app| { - print::open(app).unwrap(); - }), - ]; - for (name, open) in opens { - let shown = show_in(open, vec2(1280.0, 900.0)); - assert!(!bars(&shown).is_empty(), "{name}: the settings scroll and their bar is drawn at rest"); - } -} - -#[test] -fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() { - let opens: [(&str, Open, &[&str]); 6] = [ - ("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]), - ("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]), - ("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]), - ( - "Save PDF", - |app| { - save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); - }, - &["Cancel"], - ), - ( - "Save for Web", - |app| { - save_for_web::open(app).unwrap(); - }, - &["Cancel", "Done"], - ), - ("Export for Screens", export_for_screens::open, &["Cancel"]), - ]; - let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0)); - for (name, open, labels) in opens { - let tall = show_in(open, vec2(1280.0, 900.0)); - assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window); - let shown = show_in(open, screen.size()); - assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); - let found = buttons(&shown, screen, labels); - assert_eq!(found.len(), labels.len(), "{name}: {found:?}"); - assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}"); - assert!(!bars(&shown).is_empty(), "{name}: the body scrolls and its bar is drawn"); - } -} - -#[test] -fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() { - let open: Open = |app| { - save_for_web::open(app).unwrap(); - }; - // The app window's smallest size. - let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); - let shown = show_in(open, screen.size()); - assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); - let found = buttons(&shown, screen, &["Optimize to File Size…", "Cancel", "Done"]); - assert_eq!(found.len(), 3, "{found:?}"); - assert!(found.iter().all(|(_, seen)| *seen), "the settings and the buttons stay in view: {found:?}"); - assert!(!bars(&shown).is_empty(), "the settings scroll and their bar is drawn"); - // A sideways bar: flat, and wider than any slider in the dialog. - fn sideways(s: &Shape, out: &mut Vec) { - match s { - Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT && (4.0..=10.0).contains(&r.rect.height()) && r.rect.width() > 300.0 => { - out.push(r.rect) - } - Shape::Vec(v) => v.iter().for_each(|s| sideways(s, out)), - _ => {} - } - } - let mut found = vec![]; - shown.shapes.iter().for_each(|c| sideways(&c.shape, &mut found)); - assert!(found.is_empty(), "the dialog fits the window's width and does not scroll sideways: {found:?}"); -} - -#[test] -fn a_window_too_large_for_the_screen_scrolls_as_a_whole() { - let opens: [(&str, Open); 4] = [ - ("Preferences", |app| crate::prefs_dialog::open(app, None)), - ("Keyboard Shortcuts", crate::shortcut_editor::open), - ("New Document", new_document::open), - ("Find Font", crate::find_font::open), - ]; - // The app window's smallest size. - let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); - for (name, open) in opens { - let tall = show_in(open, vec2(1280.0, 900.0)); - assert!( - tall.window.height() > screen.height() || tall.window.width() > screen.width(), - "{name}: the dialog is larger than the small window ({:?})", - tall.window - ); - let shown = show_in(open, screen.size()); - assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); - assert!(!bars(&shown).is_empty(), "{name}: the dialog scrolls and its bar is drawn"); - } -}