diff --git a/AGENTS.md b/AGENTS.md index edf5913a37..69f4a3ce3e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -192,12 +192,15 @@ command leaves the lists that name it, such as `ON_A_COPY`, the policy tables an at nothing. A literal that isn't a command goes in its `EXEMPT` list with a reason (file and host names ending in a `NOT_IDS` word need none), and an `EXEMPT` entry the source no longer holds fails it too. -The tests `every_control_can_be_reached_*` (`crates/ui-egui/src/layout_reach.rs`, Linux) show each ribbon tab, Workflows section -and listed pane, dialog and main view with English labels 40% longer (labels that hold a placeholder, and text -that isn't passed through `tl!` or `tl_raw!`, keep their length), at 1280×720 and the smallest window, -and fail on a control that lies on another or that scrolling doesn't bring into view: let the row wrap, scroll or -shrink rather than listing it. `KNOWN` holds the problems there are; take lines out, don't add them. A new pane, -dialog or main view goes in the test's lists, with how to tell it is shown. +The tests `every_control_can_be_reached_*` (`crates/ui-egui/src/layout_reach/desktop.rs`, and the phone's in +`crates/ui-touch/src/layout_reach.rs`; Linux) show each ribbon tab, Workflows section and listed pane, dialog and +main view, and each of the phone's sheets, with every English word 40% longer (labels that hold a placeholder, and +text that isn't passed through `tl!` or `tl_raw!`, keep their length), at 1280×720 and the smallest window (360×760 +and 800×360 on the phone). They open each menu, list and context menu on them in turn, and fail on a control that +lies on another or that scrolling doesn't bring into view, and on text painted on other text: let the row wrap, +scroll or shrink rather than listing it. `KNOWN` holds the problems there are; take lines out, don't add them. A +new pane, dialog, main view or sheet goes in the test's lists, with how to tell it is shown; a control drawn by +hand gives itself a role and name (`widget_info`), or the test can't see it. While you work, `cargo xtask changed` runs the same checks on only the packages your branch changes and those that depend on them (and `test-hygiene` on the whole workspace, and formatting, `layers`, `attribution` and `rows` when packages are checked; `attribution` also when only non-code files change), or everything when a diff --git a/Cargo.lock b/Cargo.lock index 244adedc28..86571bbf8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5566,6 +5566,7 @@ name = "rustgis-ui-touch" version = "0.9.0" dependencies = [ "egui", + "egui_kittest", "rustgis-ui-egui", "serde_json", "web-time", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index faeaa52f41..636edef82b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -42,6 +42,10 @@ sha2 = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { version = "1.1", features = ["process", "fs"] } +[features] +# The layout check (`layout_reach`) for other crates' tests: the phone's surfaces in `rustgis-ui-touch`. +testing = [] + [dev-dependencies] tempfile = "3" # PDF downloads drawn off the frame (#2336). diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index e2842a0410..d27bf253e8 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -175,8 +175,16 @@ fn card(ui: &mut Ui, t: &Tokens, title: &str, sub: &str, icon: &str) -> bool { let thumb = Rect::from_min_size(r.min + vec2(12.0, 12.0), vec2(176.0, 86.0)); ui.painter().rect_filled(thumb, CornerRadius::same(6), t.canvas); icons::paint(ui.painter(), Rect::from_center_size(thumb.center(), vec2(48.0, 48.0)), icon, t.icon, t.accent); - ui.painter().text(pos2(r.min.x + 14.0, r.min.y + 116.0), Align2::LEFT_CENTER, tl!(title), semibold(13.5), t.text); - ui.painter().text(pos2(r.min.x + 14.0, r.min.y + 136.0), Align2::LEFT_CENTER, tl!(sub), regular(11.5), t.text_dim); + // Within the card: the title on one line, the line under it on two, cut short past that. + let fit = |text: &str, font: egui::FontId, color, rows: usize| { + let mut job = egui::text::LayoutJob::simple(text.to_string(), font, color, r.width() - 28.0); + job.wrap.max_rows = rows; + ui.fonts_mut(|f| f.layout_job(job)) + }; + let title = fit(tl!(title), semibold(13.5), t.text, 1); + let below = pos2(r.min.x + 14.0, r.min.y + 116.0 - title.size().y / 2.0); + ui.painter().galley(below, title.clone(), t.text); + ui.painter().galley(below + vec2(0.0, title.size().y + 3.0), fit(tl!(sub), regular(11.5), t.text_dim, 2), t.text_dim); resp.clicked() } diff --git a/crates/ui-egui/src/catalogsui.rs b/crates/ui-egui/src/catalogsui.rs index cc1a67ef07..cf4dc9a732 100644 --- a/crates/ui-egui/src/catalogsui.rs +++ b/crates/ui-egui/src/catalogsui.rs @@ -75,7 +75,7 @@ impl Default for State { } fn fetch(url: &str) -> Answer { - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] crate::layout_reach::downloaded(); let slot: Answer = Slot::default(); let land = slot.clone(); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index edf3b6f64f..6226a7378a 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -393,166 +393,14 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { ui.painter().line_segment([pos2(r.min.x - 10.0, r.min.y), pos2(r.max.x + 10.0, r.min.y)], Stroke::new(1.0, t.border)); ui.horizontal_centered(|ui| { ui.spacing_mut().item_spacing = vec2(10.0, 0.0); - if let Some(jump) = &mut app.ui.history_jump { - let action = if jump.command == "edit.undo" { tl_raw!("Undo") } else { tl_raw!("Redo") }; - ui.label(crate::i18n::fmt( - "{action} {done} of {total}", - &[("action", action), ("done", &jump.done.to_string()), ("total", &jump.total.to_string())], - )); - let cancel = ui.small_button(tl!("Cancel")).on_hover_text(tl!("Stop at the state reached so far")); - // A press and its release may arrive in different frames. - jump.cancel_pressed = cancel.is_pointer_button_down_on(); - if cancel.clicked() { - app.ui.history_jump = None; - } - sep(ui, &t); - } - // Scale: typed (1:12,345, 12345, 25k, …) and set with Enter, or picked from the - // list. Esc, or clicking away, leaves the map's scale as it was. - let scale = app.session.scale(); - let shown = rustgis_engine::map::graphics::scale_ratio(scale); - let mut text = app.ui.scale_text.take().unwrap_or_else(|| shown.clone()); - let mut edit = egui::TextEdit::singleline(&mut text).id_salt("status_scale").desired_width(96.0).show(ui); - // Clicking in selects the scale, so typing replaces it. - if edit.response.gained_focus() { - let end = edit.galley.text().chars().count(); - edit.state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(end)))); - edit.state.store(ui.ctx(), edit.response.id); - } - let r = edit.response.response.on_hover_text(tl!("Type a scale, such as 1:12,345, 12345 or 25k, and press Enter")); - // The box's own focus, not the window's: switching windows keeps a half-typed scale. - if ui.ctx().memory(|m| m.has_focus(r.id)) { - app.ui.scale_text = Some(text); - } else if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && text != shown { - match parse_scale(&text) { - Some(s) => { - let _ = app.run("map.setScale", json!({"scale": s})); - } - None => app.session.notify(crate::i18n::fmt("'{text}' isn't a scale: type one such as 1:12,345", &[("text", &text)]), true), - } - } - let presets = ui.add(egui::Button::new("▾").small().frame(false)).on_hover_text(tl!("Common scales")); - egui::Popup::menu(&presets).show(|ui| { - for s in [ - 5_000.0, - 25_000.0, - 100_000.0, - 500_000.0, - 1_000_000.0, - 5_000_000.0, - 10_000_000.0, - 25_000_000.0, - 50_000_000.0, - 100_000_000.0, - ] { - if ui.selectable_label(false, format!("1:{}", crate::ribbon::fmt_thousands(s))).clicked() { - let _ = app.run("map.setScale", json!({"scale": s})); - ui.close(); - } - } + // The readouts take the room the right-hand group leaves (as wide as it was last + // frame) and scroll sideways past it in a narrow window, rather than run under it. + let right = egui::Id::unique("status_right_width"); + let room = ui.available_width() - ui.data(|d| d.get_temp::(right)).unwrap_or(0.0) - 10.0; + let size = vec2(room.max(0.0), ui.available_height()); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + crate::widgets::scrolling_row(ui, "status_readouts", |ui| readouts(app, ui, &t)); }); - // The map's zoom level, bearing and pitch; clicking them on a turned or tilted map - // faces north and looks straight down again. - let cam = app.session.map().camera; - let zoom = app.session.zoom().map_or_else(|| "—".to_string(), |z| format!("{z:.1}")); - let text = crate::i18n::fmt( - "Zoom {z} · Bearing {b}° · Pitch {p}°", - // Rounded first, then + 0.0: a bearing just below zero reads 0, not -0. - &[ - ("z", &zoom), - ("b", &format!("{:.0}", cam.bearing.round() + 0.0)), - ("p", &format!("{:.0}", cam.pitch.round() + 0.0)), - ], - ); - let level = cam.bearing.round() == 0.0 && cam.pitch.round() == 0.0; - let resp = ui.add( - egui::Label::new(egui::RichText::new(text).monospace().size(11.5).color(if level { t.text_dim } else { t.accent_text })) - .sense(Sense::click()), - ); - let resp = resp.on_hover_text(tl!( - "Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top of the map faces, clockwise from north. Pitch: the tilt from looking straight down. Click to reset bearing and pitch." - )); - if resp.clicked() && !level { - let _ = app.run("map.resetNorth", json!({})); - } - // The pointer's coordinates and the map's coordinate system change on a click, so - // they are buttons, framed to look it. The two buttons' padding takes what the three - // narrower gaps give up, so the bar, full in a narrow window, stays about as wide. - let (gap, padding) = (ui.spacing().item_spacing.x, ui.spacing().button_padding.x); - ui.spacing_mut().item_spacing.x = 6.0; - ui.spacing_mut().button_padding.x = 3.0; - sep(ui, &t); - // Pointer coordinates. - let format = app.map.coord_format; - let earth = app.session.map().body().is_earth(); - // Kept after the pointer leaves the map, so a click here still shows the position; - // dimmed then, to tell it from a live one. - let kept = app.map.kept_pointer_lonlat(app.session.map().instance_id(), app.session.opened); - let live = app.map.pointer_lonlat.is_some(); - // Layer coordinates name their system, the active layer's, which the map's beside - // them isn't. - let system = format.system(app.session.map(), app.session.active_layer); - let mut text = format.readout(kept, earth, system.as_ref()); - // Named only beside a position: with none yet, the dash stands alone. - if let Some(s) = system.as_ref().filter(|_| format == crate::CoordReadout::Layer && kept.is_some()) { - text = format!("{text} {}", s.name()); - } - // Dimmed, not disabled: in its frame, disabled text would look like a button that is off. - let color = if live { t.text } else { t.text_dim }; - let resp = ui.add(egui::Button::new(egui::RichText::new(text).monospace().size(11.5).color(color)).small()); - if resp.on_hover_text(format.hover()).clicked() { - let _ = app.run("ui.coordinateFormat", Value::Null); - } - let projection = match &app.session.map().projection { - rustgis_engine::map::Projection::Globe => tl!("WGS 84 / Globe").to_string(), - rustgis_engine::map::Projection::WebMercator => tl!("WGS 84 / Web Mercator").to_string(), - p => tl!(p.label().as_str()).to_string(), - }; - let resp = ui.add(egui::Button::new(egui::RichText::new(projection).size(11.0)).small()); - if resp.on_hover_text(tl!("Change the map's coordinate system")).clicked() { - let _ = app.run("ui.dialog", json!({"name": "coordinateSystem"})); - } - ui.spacing_mut().item_spacing.x = gap; - ui.spacing_mut().button_padding.x = padding; - sep(ui, &t); - let n = app.session.map().selection_count(); - ui.label( - egui::RichText::new(crate::i18n::fmt("Selected Features: {n}", &[("n", &n.to_string())])).size(11.5).color(if n > 0 { - t.accent_text - } else { - t.text_dim - }), - ); - if n > 0 { - let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - icons::paint(ui.painter(), r, "clear_sel", t.icon, t.accent); - if resp.on_hover_text(tl!("Clear selection")).clicked() { - let _ = app.run("select.clear", Value::Null); - } - } - // An export writing its file: its progress and Cancel. - #[cfg(not(target_arch = "wasm32"))] - if app.export_job.is_some() { - sep(ui, &t); - crate::exportjob::status(app, ui, &t); - } - // A file read for Add Data, or a layer's features for Load All. - #[cfg(not(target_arch = "wasm32"))] - if crate::readjob::showing(app) { - sep(ui, &t); - crate::readjob::status(app, ui, &t); - } - #[cfg(not(target_arch = "wasm32"))] - source_open_status(app, ui, &t); - // Data cubes' summaries plugin commands left to read off the frame (#3183). - #[cfg(not(target_arch = "wasm32"))] - summaries_status(app, ui, &t); - crate::geocodeui::status(app, ui); - // Downloads and windows being read off the frame, each with its Cancel. - if !app.ui.downloads.is_empty() || window_reads_under_way(app) { - sep(ui, &t); - downloads_status(app, ui, &t); - } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // The CPU/GPU backend toggle, then the frame rate (live while the map moves, // "— fps" when idle), then the last render's cost. @@ -633,6 +481,9 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { if ui.small_button(tl!("Messages")).on_hover_text(tl!("Review messages and failed network requests")).clicked() { app.ui.open_right(crate::RightPane::DiagnosticLog); } + // What the readouts leave room for: this group without the notice, which is cut to fit. + let width = ui.min_rect().width(); + ui.data_mut(|d| d.insert_temp(right, width)); // Cut to the room left (the whole notice on hover), so it doesn't run // over the selection count and coordinates. A click opens its history. if let Some(running) = crate::pluginstart::running(app) { @@ -656,6 +507,157 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { }); } +/// The status bar's readouts and the work under way, left to right: the scale, the camera, the +/// pointer's coordinates and the map's system, the selection, and jobs with their Cancel. +fn readouts(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { + ui.spacing_mut().item_spacing = vec2(10.0, 0.0); + if let Some(jump) = &mut app.ui.history_jump { + let action = if jump.command == "edit.undo" { tl_raw!("Undo") } else { tl_raw!("Redo") }; + ui.label(crate::i18n::fmt( + "{action} {done} of {total}", + &[("action", action), ("done", &jump.done.to_string()), ("total", &jump.total.to_string())], + )); + let cancel = ui.small_button(tl!("Cancel")).on_hover_text(tl!("Stop at the state reached so far")); + // A press and its release may arrive in different frames. + jump.cancel_pressed = cancel.is_pointer_button_down_on(); + if cancel.clicked() { + app.ui.history_jump = None; + } + sep(ui, t); + } + // Scale: typed (1:12,345, 12345, 25k, …) and set with Enter, or picked from the + // list. Esc, or clicking away, leaves the map's scale as it was. + let scale = app.session.scale(); + let shown = rustgis_engine::map::graphics::scale_ratio(scale); + let mut text = app.ui.scale_text.take().unwrap_or_else(|| shown.clone()); + let mut edit = egui::TextEdit::singleline(&mut text).id_salt("status_scale").desired_width(96.0).show(ui); + // Clicking in selects the scale, so typing replaces it. + if edit.response.gained_focus() { + let end = edit.galley.text().chars().count(); + edit.state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(end)))); + edit.state.store(ui.ctx(), edit.response.id); + } + let r = edit.response.response.on_hover_text(tl!("Type a scale, such as 1:12,345, 12345 or 25k, and press Enter")); + // The box's own focus, not the window's: switching windows keeps a half-typed scale. + if ui.ctx().memory(|m| m.has_focus(r.id)) { + app.ui.scale_text = Some(text); + } else if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && text != shown { + match parse_scale(&text) { + Some(s) => { + let _ = app.run("map.setScale", json!({"scale": s})); + } + None => app.session.notify(crate::i18n::fmt("'{text}' isn't a scale: type one such as 1:12,345", &[("text", &text)]), true), + } + } + let presets = ui.add(egui::Button::new("▾").small().frame(false)).on_hover_text(tl!("Common scales")); + egui::Popup::menu(&presets).show(|ui| { + for s in + [5_000.0, 25_000.0, 100_000.0, 500_000.0, 1_000_000.0, 5_000_000.0, 10_000_000.0, 25_000_000.0, 50_000_000.0, 100_000_000.0] + { + if ui.selectable_label(false, format!("1:{}", crate::ribbon::fmt_thousands(s))).clicked() { + let _ = app.run("map.setScale", json!({"scale": s})); + ui.close(); + } + } + }); + // The map's zoom level, bearing and pitch; clicking them on a turned or tilted map + // faces north and looks straight down again. + let cam = app.session.map().camera; + let zoom = app.session.zoom().map_or_else(|| "—".to_string(), |z| format!("{z:.1}")); + let text = crate::i18n::fmt( + "Zoom {z} · Bearing {b}° · Pitch {p}°", + // Rounded first, then + 0.0: a bearing just below zero reads 0, not -0. + &[("z", &zoom), ("b", &format!("{:.0}", cam.bearing.round() + 0.0)), ("p", &format!("{:.0}", cam.pitch.round() + 0.0))], + ); + let level = cam.bearing.round() == 0.0 && cam.pitch.round() == 0.0; + let resp = ui.add( + egui::Label::new(egui::RichText::new(text).monospace().size(11.5).color(if level { t.text_dim } else { t.accent_text })) + .sense(Sense::click()), + ); + let resp = resp.on_hover_text(tl!( + "Zoom: the map's zoom level, as web maps count it. Bearing: the direction the top of the map faces, clockwise from north. Pitch: the tilt from looking straight down. Click to reset bearing and pitch." + )); + if resp.clicked() && !level { + let _ = app.run("map.resetNorth", json!({})); + } + // The pointer's coordinates and the map's coordinate system change on a click, so + // they are buttons, framed to look it. The two buttons' padding takes what the three + // narrower gaps give up, so the bar, full in a narrow window, stays about as wide. + let (gap, padding) = (ui.spacing().item_spacing.x, ui.spacing().button_padding.x); + ui.spacing_mut().item_spacing.x = 6.0; + ui.spacing_mut().button_padding.x = 3.0; + sep(ui, t); + // Pointer coordinates. + let format = app.map.coord_format; + let earth = app.session.map().body().is_earth(); + // Kept after the pointer leaves the map, so a click here still shows the position; + // dimmed then, to tell it from a live one. + let kept = app.map.kept_pointer_lonlat(app.session.map().instance_id(), app.session.opened); + let live = app.map.pointer_lonlat.is_some(); + // Layer coordinates name their system, the active layer's, which the map's beside + // them isn't. + let system = format.system(app.session.map(), app.session.active_layer); + let mut text = format.readout(kept, earth, system.as_ref()); + // Named only beside a position: with none yet, the dash stands alone. + if let Some(s) = system.as_ref().filter(|_| format == crate::CoordReadout::Layer && kept.is_some()) { + text = format!("{text} {}", s.name()); + } + // Dimmed, not disabled: in its frame, disabled text would look like a button that is off. + let color = if live { t.text } else { t.text_dim }; + let resp = ui.add(egui::Button::new(egui::RichText::new(text).monospace().size(11.5).color(color)).small()); + if resp.on_hover_text(format.hover()).clicked() { + let _ = app.run("ui.coordinateFormat", Value::Null); + } + let projection = match &app.session.map().projection { + rustgis_engine::map::Projection::Globe => tl!("WGS 84 / Globe").to_string(), + rustgis_engine::map::Projection::WebMercator => tl!("WGS 84 / Web Mercator").to_string(), + p => tl!(p.label().as_str()).to_string(), + }; + let resp = ui.add(egui::Button::new(egui::RichText::new(projection).size(11.0)).small()); + if resp.on_hover_text(tl!("Change the map's coordinate system")).clicked() { + let _ = app.run("ui.dialog", json!({"name": "coordinateSystem"})); + } + ui.spacing_mut().item_spacing.x = gap; + ui.spacing_mut().button_padding.x = padding; + sep(ui, t); + let n = app.session.map().selection_count(); + ui.label(egui::RichText::new(crate::i18n::fmt("Selected Features: {n}", &[("n", &n.to_string())])).size(11.5).color(if n > 0 { + t.accent_text + } else { + t.text_dim + })); + if n > 0 { + let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); + icons::paint(ui.painter(), r, "clear_sel", t.icon, t.accent); + if resp.on_hover_text(tl!("Clear selection")).clicked() { + let _ = app.run("select.clear", Value::Null); + } + } + // An export writing its file: its progress and Cancel. + #[cfg(not(target_arch = "wasm32"))] + if app.export_job.is_some() { + sep(ui, t); + crate::exportjob::status(app, ui, t); + } + // A file read for Add Data, or a layer's features for Load All. + #[cfg(not(target_arch = "wasm32"))] + if crate::readjob::showing(app) { + sep(ui, t); + crate::readjob::status(app, ui, t); + } + #[cfg(not(target_arch = "wasm32"))] + source_open_status(app, ui, t); + // Data cubes' summaries plugin commands left to read off the frame (#3183). + #[cfg(not(target_arch = "wasm32"))] + summaries_status(app, ui, t); + crate::geocodeui::status(app, ui); + // Downloads and windows being read off the frame, each with its Cancel. + if !app.ui.downloads.is_empty() || window_reads_under_way(app) { + sep(ui, t); + downloads_status(app, ui, t); + } +} + /// How the strip of work running off the frame is drawn: in the desktop's status bar, or at a /// finger's size for a shell with its own interface ([`RustGisApp::chrome`]). #[derive(Clone, Copy)] diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index a09027eb56..5e5f4a5bd2 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -386,7 +386,7 @@ pub fn tr(lang: Lang, s: &str) -> &str { return t; } if lang == Lang::EN { - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] if pseudo::on() { return pseudo::pad(s); } @@ -421,7 +421,7 @@ pub fn tr_raw(lang: Lang, s: &str) -> &str { return t; } if lang == Lang::EN { - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] if pseudo::on() { return pseudo::pad(s); } @@ -753,15 +753,15 @@ macro_rules! tl_raw { #[cfg(test)] mod boundary_tests; -#[cfg(all(test, target_os = "linux"))] +#[cfg(all(any(test, feature = "testing"), target_os = "linux"))] pub(crate) mod pseudo; /// Whether the layout tests' long English is on, on this thread; never outside them. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn pseudo_on() -> bool { - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] return pseudo::on(); - #[cfg(not(all(test, target_os = "linux")))] + #[cfg(not(all(any(test, feature = "testing"), target_os = "linux")))] false } #[cfg(test)] diff --git a/crates/ui-egui/src/i18n/pseudo.rs b/crates/ui-egui/src/i18n/pseudo.rs index cc749b58a0..f7551f7364 100644 --- a/crates/ui-egui/src/i18n/pseudo.rs +++ b/crates/ui-egui/src/i18n/pseudo.rs @@ -1,4 +1,4 @@ -//! A stand-in for a long language: English with each line about 40% longer. Layout tests draw the +//! A stand-in for a long language: English with each word about 40% longer. Layout tests draw the //! interface in it, so a label that only fits in English fails them without a translation or a //! font of its own. @@ -21,19 +21,34 @@ pub(crate) fn set(on: bool) { ON.set(on); } -/// `s` padded: each line grows by 40% of its length. A line with a placeholder is left alone, +/// `s` padded: each word grows by 40% of its length. A line with a placeholder is left alone, /// since what fills it isn't translated. pub(crate) fn pad(s: &str) -> &'static str { PADDED.with_borrow_mut(|seen| { if let Some(done) = seen.get(s) { return *done; } + // Each word grows, as in a language whose words run long: a label cut to its first word + // grows too. Each word padded is kept as well, so a row wrapped mid-label is put back a + // word at a time. + let mut words: Vec<(String, String)> = Vec::new(); + let mut word = |w: &str| match w.chars().any(char::is_alphabetic) { + true => { + let padded = format!("{w}{}", "o".repeat((w.chars().count() * 2).div_ceil(5))); + words.push((w.to_string(), padded.clone())); + padded + } + false => w.to_string(), + }; let line = |l: &str| match l.trim().is_empty() || l.contains('{') { true => l.to_string(), - false => format!("{l}{}", "o".repeat((l.chars().count() * 2).div_ceil(5))), + false => l.split(' ').map(&mut word).collect::>().join(" "), }; let padded: &'static str = Box::leak(s.split('\n').map(line).collect::>().join("\n").into_boxed_str()); seen.insert(s.to_string(), padded); + for (w, p) in words { + seen.entry(w).or_insert_with(|| Box::leak(p.into_boxed_str())); + } padded }) } @@ -84,5 +99,9 @@ mod tests { assert_eq!(super::unpadded(long), "Goodbye"); assert_eq!(super::unpadded(&format!("{short} {long}")), "Go Goodbye"); assert_eq!(super::replace_words("GooGoo", "Goo", "Go"), "GooGoo"); + // A row of a wrapped label holds some of its words: each is put back. + let words = super::pad("Single Symbol"); + let first = words.split(' ').next().unwrap_or_default(); + assert_eq!(super::unpadded(first), "Single"); } } diff --git a/crates/ui-egui/src/layout_reach.rs b/crates/ui-egui/src/layout_reach.rs index 0b260490e0..3b052e40da 100644 --- a/crates/ui-egui/src/layout_reach.rs +++ b/crates/ui-egui/src/layout_reach.rs @@ -1,26 +1,110 @@ -//! Every control on a surface can be reached: none lies on another, and none is cut off where -//! scrolling doesn't bring it into view. Drawn in a stand-in for a long language -//! ([`crate::i18n::pseudo`]), at the smallest window the desktop app allows and at a laptop's. +//! Every control on a surface can be reached: none lies on another, none is cut off where +//! scrolling doesn't bring it into view, and no text is painted on other text; the same for each +//! menu on it, opened in turn. Drawn in a stand-in for a long language ([`crate::i18n::pseudo`]). +//! +//! The desktop's surfaces are in `desktop`; the phone's, in `rustgis-ui-touch`, which reaches +//! this through the `testing` feature and drives its own window ([`Window`]). //! //! It runs on Linux only: what a surface says differs a little by platform (shortcuts, tools found), //! and one is enough to see a row that doesn't fit. //! -//! What it can't see: text painted without a widget, menus until they are opened, and the phone. +//! What it can't see: text in an image (a map's labels are the map's), a menu within a menu, and a +//! popup given an id of its own. +use crate::RustGisApp; use crate::i18n::pseudo; -use crate::{LeftPane, RightPane, RustGisApp}; use egui::accesskit::{Action, ActionRequest, Role, TreeId}; use egui::{Event, Id, LayerId, Rect, Vec2, vec2}; -use egui_kittest::kittest::NodeT; -use serde_json::{Value, json}; -use std::cell::Cell; -use std::collections::{BTreeSet, HashMap}; +use serde_json::Value; +use std::cell::{Cell, RefCell}; +use std::collections::{BTreeSet, HashMap, HashSet}; thread_local! { /// Downloads started on this thread through `fetch_within` or the catalogs' `fetch`, so a /// surface that downloads that way as it opens fails however quickly the download ends. Code /// that calls `cache::download` itself isn't counted. static DOWNLOADS: Cell = const { Cell::new(0) }; + /// The text painted in the last frame, read before the frame ends: its output has no layers. + static PAINTED: RefCell> = const { RefCell::new(Vec::new()) }; + /// The role and name of each widget the last frame gave one (`widget_info`). + static NAMED: RefCell> = RefCell::new(HashMap::new()); +} + +/// The window a surface is shown in: the app, run a frame at a time (as `egui_kittest`'s harness +/// runs one), each frame ending in [`keep_frame`]. +pub trait Window { + /// The window's context. + fn ctx(&self) -> &egui::Context; + /// The app it shows. + fn app(&mut self) -> &mut RustGisApp; + /// Runs `steps` frames. + fn run_steps(&mut self, steps: usize); + /// Queues `event` for the next frame. + fn event(&mut self, event: Event); + /// Makes the window `size`. + fn set_size(&mut self, size: Vec2); +} + +/// A line of text painted in a frame: a control's label, or text painted without one. +#[derive(Clone, Debug)] +struct Painted { + layer: LayerId, + text: String, + /// Where it is, cut to its clip rectangle: empty when it is out of view. + rect: Rect, + /// All of it, in view or not. + full: Rect, + /// What clips it: two lines clipped alike are in the same scrolled area. + clip: Rect, +} + +/// Keeps what the check reads of this frame: the text painted, and each widget's role and name. +/// The window calls it at the end of each frame, after the app has drawn. +pub fn keep_frame(ctx: &egui::Context) { + let ids: Vec = ctx.viewport(|v| v.this_pass.widgets.layers().flat_map(|(_, w)| w.iter().map(|w| w.id)).collect()); + let named = ids + .into_iter() + .filter(|id| ctx.has_accesskit_node(*id)) + .filter_map(|id| { + let found = ctx.accesskit_node_builder(id, |node| { + let label = node.label().or_else(|| node.placeholder()).unwrap_or_default().to_string(); + (node.role(), label) + }); + found.map(|named| (id, named)) + }) + .collect(); + NAMED.set(named); + let mut layers: HashSet = ctx.memory(|m| m.areas().visible_layer_ids().into_iter().collect()); + layers.insert(LayerId::background()); + ctx.viewport(|v| layers.extend(v.this_pass.widgets.layers().map(|(l, _)| *l))); + let mut out = Vec::new(); + ctx.graphics(|g| { + for layer in layers { + for s in g.get(layer).into_iter().flat_map(|list| list.all_entries()) { + text_rows(layer, s.clip_rect, &s.shape, &mut out); + } + } + }); + PAINTED.set(out); +} + +/// The rows of text in `shape`, cut to `clip`. +fn text_rows(layer: LayerId, clip: Rect, shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| text_rows(layer, clip, s, out)), + egui::Shape::Text(t) if t.angle == 0.0 && t.opacity_factor > 0.0 => { + for row in &t.galley.rows { + let text: String = row.row.glyphs.iter().map(|g| g.chr).collect(); + // Spaces before a label leave room for its icon, painted there. + let full = row.rect_without_leading_space().translate(t.pos.to_vec2()); + let rect = full.intersect(clip); + if !text.trim().is_empty() && full.width() > SLACK && full.height() > SLACK { + out.push(Painted { layer, text, rect, full, clip }); + } + } + } + _ => {} + } } /// Counts a download started. @@ -28,22 +112,9 @@ pub(crate) fn downloaded() { DOWNLOADS.set(DOWNLOADS.get() + 1); } -type Harness<'a> = egui_kittest::Harness<'a, RustGisApp>; - -/// A laptop's window, then the desktop app's smallest (`with_min_inner_size` in `apps/rustgis`). -const SIZES: [Vec2; 2] = [vec2(1280.0, 720.0), vec2(900.0, 560.0)]; -/// The surfaces are tested in this many parts, side by side. -const PARTS: usize = 4; /// How much of a control may be covered or cut off: rounding and borders. const SLACK: f32 = 2.5; -/// Problems there are today, as [`problems`] names them. Only take lines out: a new problem is -/// fixed, not listed, and a line whose problem is gone fails the test. -const KNOWN: &[&str] = &[ - // A pane this wide leaves the map less room than one tab. - r#"pane Notebook at 900: cut off Button "World""#, -]; - /// A control drawn in the last frame. #[derive(Clone)] struct Control { @@ -69,41 +140,21 @@ impl Control { } } -/// Whether a user works a widget of this role. +/// Whether a user works a widget of this role. Not an edge that resizes a panel or window: those +/// lie along other controls by design, and meet at corners. fn interactive(role: Role) -> bool { - use Role::*; - matches!( - role, - Button - | CheckBox - | RadioButton - | ComboBox - | Link - | TextInput - | MultilineTextInput - | Slider - | SpinButton - | ColorWell - | Switch - | MenuItem - | Tab - ) + egui::accessibility::is_input(role) && role != Role::Splitter } /// The controls drawn in the last frame. -fn controls(h: &Harness) -> Vec { - let mut named = HashMap::new(); - for node in h.root().children_recursive() { - let node = node.accesskit_node(); - let label = node.label().or_else(|| node.placeholder().map(String::from)).unwrap_or_default(); - named.insert(node.locate().0.0, (node.role(), label)); - } - h.ctx.viewport(|v| { +fn controls(h: &dyn Window) -> Vec { + let named = NAMED.with_borrow(|n| n.clone()); + h.ctx().viewport(|v| { let widgets = v.prev_pass.widgets.layers().flat_map(|(layer, widgets)| widgets.iter().map(move |w| (*layer, w))); widgets .filter(|(_, w)| w.visible && w.rect.is_finite() && w.rect.width() > SLACK && w.rect.height() > SLACK) .filter_map(|(layer, w)| { - let (role, label) = named.get(&w.id.value())?.clone(); + let (role, label) = named.get(&w.id)?.clone(); interactive(role).then_some(Control { id: w.id, parent: w.parent_id, @@ -153,7 +204,7 @@ fn lie_on(a: &Control, b: &Control, both: Rect) -> bool { /// Scrolls the control into view, as a screen reader asks for it. `None` when it is gone then; /// else it where it is then, and the controls it lies on there. -fn cut_after_scrolling(h: &mut Harness, id: Id) -> Option<(Control, Vec)> { +fn cut_after_scrolling(h: &mut dyn Window, id: Id) -> Option<(Control, Vec)> { let request = ActionRequest { action: Action::ScrollIntoView, target_tree: TreeId::ROOT, target_node: id.accesskit_id(), data: None }; h.event(Event::AccessKitActionRequest(request)); h.run_steps(3); @@ -166,25 +217,80 @@ fn cut_after_scrolling(h: &mut Harness, id: Id) -> Option<(Control, Vec /// may have. Each costs a scroll; a surface with more fails rather than leaving some unchecked. const MOST_CLIPS: usize = 80; -/// Where each control of the bare window is, and what of it is in view. -type Bare = HashMap; +/// What the bare window shows: where each control is and what of it is in view, and the text +/// painted, with where. +#[derive(Default)] +struct Bare { + controls: HashMap, + /// Each caption, by layer, text and place, with how many times it is painted there. + texts: HashMap<(LayerId, String, [i32; 4]), usize>, + /// Layers left out altogether: under a menu, what the surface shows. + under: HashSet, +} + +impl Bare { + /// What the harness shows now. + fn of(h: &dyn Window) -> Self { + let controls = controls(h).iter().map(|c| (c.id, (c.rect, c.seen))).collect(); + let mut texts = HashMap::new(); + PAINTED.with_borrow(|p| p.iter().for_each(|t| *texts.entry((t.layer, t.text.clone(), corners(t.full))).or_default() += 1)); + Bare { controls, texts, under: HashSet::new() } + } +} + +/// `r`'s corners, to the pixel. +fn corners(r: Rect) -> [i32; 4] { + [r.min.x, r.min.y, r.max.x, r.max.y].map(|v| v.round() as i32) +} /// Whether `c` is where the bare window has it, so its own surfaces test it. fn unmoved(bare: &Bare, c: &Control) -> bool { - bare.get(&c.id).is_some_and(|(rect, seen)| { + bare.controls.get(&c.id).is_some_and(|(rect, seen)| { let same = |a: Rect, b: Rect| (a.min - b.min).length() < 0.5 && (a.max - b.max).length() < 0.5; same(*rect, c.rect) && same(*seen, c.seen) }) } +/// Text painted on other text in the last frame, in the part of each in view: a caption over a +/// caption, a label run past its control's edge onto the next. Text the bare window shows where it +/// shows it is left to the surfaces of the whole window, as its controls are. +fn text_on_text(at: &str, whole_window: bool, bare: &Bare) -> BTreeSet { + let texts: Vec = PAINTED.with_borrow(|p| p.iter().filter(|t| !bare.under.contains(&t.layer)).cloned().collect()); + // Which are the bare window's, each of its captions matched once: one more like it is new. + let mut left = bare.texts.clone(); + let window: Vec = texts + .iter() + .map(|t| { + let n = left.get_mut(&(t.layer, t.text.clone(), corners(t.full))); + !whole_window && n.is_some_and(|n| std::mem::replace(n, n.saturating_sub(1)) > 0) + }) + .collect(); + let mut found = BTreeSet::new(); + for (i, a) in texts.iter().enumerate() { + for (j, b) in texts.iter().enumerate().skip(i + 1) { + // In the same scrolled area, whole, wherever it is scrolled: a row out of view counts. + let both = if a.clip == b.clip { a.full.intersect(b.full) } else { a.rect.intersect(b.rect) }; + // A halo or shadow is the same text again, a pixel or two off; the same text in the same + // place is two captions drawn on each other. + let apart = (a.full.center() - b.full.center()).length(); + let halo = a.text == b.text && apart > 0.1 && apart < 3.0; + if a.layer != b.layer || both.width() <= SLACK || both.height() <= SLACK || halo || (window[i] && window[j]) { + continue; + } + let (a, b) = if (a.full.min.y, a.full.min.x) <= (b.full.min.y, b.full.min.x) { (a, b) } else { (b, a) }; + found.insert(format!("{at}: text \"{}\" on text \"{}\"", pseudo::unpadded(&a.text), pseudo::unpadded(&b.text))); + } + } + found +} + /// The problems on the surface shown, each as `surface at width: what control`. -fn problems(h: &mut Harness, surface: &str, bare: &Bare) -> Vec { - let at = format!("{surface} at {}", h.ctx.content_rect().width()); +fn problems(h: &mut dyn Window, surface: &str, whole_window: bool, bare: &Bare) -> Vec { + let at = format!("{surface} at {}", h.ctx().content_rect().width()); let mut found = Vec::new(); - let all = controls(h); - // What the bare window shows (the header, the ribbon, the Layers pane) is tested on the ribbon's - // own surfaces, not again on each of the rest, unless this surface moves or narrows it. - let whole_window = surface.starts_with("ribbon ") || surface.starts_with("start "); + let all: Vec = controls(h).into_iter().filter(|c| !bare.under.contains(&c.layer)).collect(); + // What the bare window shows (the header, the ribbon, the Layers pane) is tested on the surfaces + // of the whole window, not again on each of the rest, unless this surface moves or narrows it. let here: Vec<&Control> = all.iter().filter(|c| whole_window || !unmoved(bare, c)).collect(); // Each pair once, by its controls: two pairs of the same names are two problems. let mut overlaps: HashMap<(u64, u64), String> = HashMap::new(); @@ -240,11 +346,18 @@ fn problems(h: &mut Harness, surface: &str, bare: &Bare) -> Vec { } } } + // Text painted on other text: before the probes, and after each for rows it scrolled into + // view. + let on_text = text_on_text(&at, whole_window, bare); + found.extend(on_text.iter().cloned()); // Scrolled into view, a control is checked again for lying on another: one out of view had no // part in view to compare. - let mut probe = |h: &mut Harness, c: &Control, more: &str, found: &mut Vec| match cut_after_scrolling(h, c.id) { + // Text on text each probe brings into view, before the next scrolls it away again. + let mut scrolled = BTreeSet::new(); + let mut probe = |h: &mut dyn Window, c: &Control, more: &str, found: &mut Vec| match cut_after_scrolling(h, c.id) { None => found.push(format!("{at}: gone when scrolled to {}{more}", c.name())), Some((now, on)) => { + scrolled.extend(text_on_text(&at, whole_window, bare)); if now.cut().max_elem() > SLACK { found.push(format!("{at}: cut off {}{more}", c.name())); } @@ -277,6 +390,7 @@ fn problems(h: &mut Harness, surface: &str, bare: &Bare) -> Vec { probe(h, tallest, "", &mut found); } } + found.extend(scrolled.difference(&on_text).cloned()); let mut overlaps: Vec = overlaps.into_values().collect(); overlaps.sort(); found.extend(overlaps); @@ -292,463 +406,222 @@ fn problems(h: &mut Harness, surface: &str, bare: &Bare) -> Vec { .collect() } -/// The command that opens each pane. A new pane doesn't compile until it has one here, or `None` -/// where it needs what the sample project hasn't got. -fn pane_command(pane: RightPane) -> Option<&'static str> { - Some(match pane { - RightPane::Geoprocessing => "ui.pane.geoprocessing", - RightPane::Symbology => "ui.pane.symbology", - RightPane::History => "ui.pane.history", - RightPane::Editing => "ui.pane.editing", - RightPane::Annotation => "ui.pane.annotation", - RightPane::Design => "ui.pane.design", - RightPane::Script => "ui.pane.script", - RightPane::Tasks => "ui.pane.tasks", - RightPane::Jobs => "ui.pane.jobs", - RightPane::Profile => "ui.pane.profile", - RightPane::TimeSeries => "ui.pane.timeSeries", - RightPane::Diagnostics => "ui.pane.diagnostics", - RightPane::DiagnosticLog => "ui.pane.diagnosticLog", - RightPane::Infographics => "ui.pane.infographics", - RightPane::Report => "ui.pane.report", - RightPane::Presentation => "ui.pane.presentation", - RightPane::Notebook => "ui.pane.notebook", - RightPane::Assistant => "ui.pane.assistant", - RightPane::Shares => "ui.pane.shares", - RightPane::Sql => "ui.pane.sql", - RightPane::Directions => "ui.pane.directions", - RightPane::Bookmarks => "ui.pane.bookmarks", - RightPane::Format => "ui.pane.format", - RightPane::Labeling => "ui.pane.labeling", - RightPane::LayerProperties => "ui.pane.layerProperties", - // Opened by section, by service and by a plugin: the first two are surfaces of their own. - RightPane::Workflows | RightPane::WebData | RightPane::Plugin => return None, - }) +/// The menus on the surface shown, each opened in turn: the problems in each, as +/// `surface at width: in the menu of control: what control`. +/// +/// A menu is found by its popup: egui keeps a popup open only while it is drawn, so one opened for +/// a control stays open only when the control has one (`Popup::menu`, a combo box, a context +/// menu). A popup given an id of its own isn't found, nor a menu within a menu. +fn menus(h: &mut dyn Window, surface: &str, whole_window: bool, bare: &Bare) -> Vec { + let at = format!("{surface} at {}", h.ctx().content_rect().width()); + let mut found = Vec::new(); + let before = controls(h); + let mut shown = Bare::of(h); + // Every layer drawn on: a menu draws on one of its own. + let drawn = |h: &dyn Window| -> HashSet { + // An empty list (nothing to pick yet) is open too: its area is shown. + let mut layers: HashSet = h.ctx().memory(|m| m.areas().visible_layer_ids().into_iter().collect()); + layers.extend(controls(h).iter().map(|c| c.layer)); + layers.extend(PAINTED.with_borrow(|p| p.iter().map(|t| t.layer).collect::>())); + layers + }; + let layers = drawn(h); + shown.under = layers.clone(); + let mut openers: Vec = before.iter().filter(|c| whole_window || !unmoved(bare, c)).cloned().collect(); + openers.sort_by(|a, b| (a.rect.min.y, a.rect.min.x).partial_cmp(&(b.rect.min.y, b.rect.min.x)).unwrap_or(std::cmp::Ordering::Equal)); + for c in openers { + let popup = c.id.with("popup"); + egui::Popup::open_id(h.ctx(), popup); + // Opened, a long menu takes a few frames to settle: its first is laid out to measure it. + h.run_steps(4); + if !egui::Popup::is_id_open(h.ctx(), popup) { + continue; + } + // A context menu opens where it is clicked: open it so. + if drawn(h).is_subset(&layers) { + egui::Popup::close_all(h.ctx()); + h.run_steps(1); + // Scrolled into view first, as a user would: checking the surface can have scrolled its + // list so the row is a sliver at the edge. + let Some((now, _)) = cut_after_scrolling(h, c.id) else { continue }; + let pos = now.seen.center(); + h.event(Event::PointerMoved(pos)); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }); + h.run_steps(1); + } + h.run_steps(4); + } + let menu = format!("{at}: in the menu of {}: ", c.name()); + // Its own popup, open and drawn: a click that opened another's isn't this menu. + if !egui::Popup::is_id_open(h.ctx(), popup) || drawn(h).is_subset(&layers) { + found.push(format!("{menu}it doesn't open")); + } else { + // Only the menu's own controls and text: what was shown before is the surface's. + for p in problems(h, "menu", false, &shown) { + found.push(format!("{menu}{}", p.split_once(": ").map_or(p.as_str(), |(_, what)| what))); + } + } + egui::Popup::close_all(h.ctx()); + h.event(Event::PointerGone); + h.run_steps(2); + } + found } -const PANES: [RightPane; 25] = [ - RightPane::Geoprocessing, - RightPane::Symbology, - RightPane::History, - RightPane::Editing, - RightPane::Annotation, - RightPane::Design, - RightPane::Script, - RightPane::Tasks, - RightPane::Jobs, - RightPane::Profile, - RightPane::TimeSeries, - RightPane::Diagnostics, - RightPane::DiagnosticLog, - RightPane::Infographics, - RightPane::Report, - RightPane::Presentation, - RightPane::Notebook, - RightPane::Assistant, - RightPane::Shares, - RightPane::Sql, - RightPane::Directions, - RightPane::Bookmarks, - RightPane::Format, - RightPane::Labeling, - RightPane::LayerProperties, -]; - -/// The dialogs that open on the sample project. Natural Earth isn't one: it downloads as it opens. -const DIALOGS: &[&str] = &[ - "selectByAttributes", - "goToXY", - "createPointXY", - "bookmark", - "addField", - "calculateField", - "calculateGeometry", - "renameLayer", - "renameMap", - "coordinateSystem", - "projectProperties", - "defineProjection", - "addShapefile", - "camera", - "addTiles", - "basemap", - "body", - "addSample", - "layerTemplate", - "addPolyline", - "addCsv", - "addDxf", - "findPlace", - "geocode", - "addUrl", - "addService", - "addDatabase", - "zarr", - "exportLayer", - "saveProject", - "exportOrbit", - "publicationWizard", - "opendata", - "sourcecoop", -]; - -/// A surface: its name, the commands that show it, and how to tell it is shown. -/// The start page's pages tested. -const START_PAGES: [&str; 2] = ["open", "about"]; - -type Surface = (String, Vec<(&'static str, Value)>, Box bool>); - -/// Every surface tested: its name and the commands that show it. -fn surfaces() -> Vec { - let cities = ("layer.select", json!({"layer": "Cities"})); - let mut all: Vec = Vec::new(); - // The Imagery extension's tab too: it is on by default. - let imagery = rustgis_engine::extensions::tab_id("imagery"); - for tab in crate::ribbon::TABS.into_iter().map(String::from).chain([imagery]) { - let name = format!("ribbon {}", tab.trim_start_matches("extension:")); - all.push((name, vec![("ui.tab", json!({"tab": tab.clone()}))], Box::new(move |a| a.ui.tab == tab))); - } - for pane in PANES { - let commands = pane_command(pane).map(|id| vec![cities.clone(), (id, Value::Null)]).unwrap_or_default(); - all.push((format!("pane {pane:?}"), commands, Box::new(move |a| a.ui.right == Some(pane)))); - } - for tab in ["general", "source", "display", "query", "time"] { - let topic = crate::layerprops::Topic::parse(tab); - all.push(( - format!("layer properties {tab}"), - vec![cities.clone(), ("ui.pane.layerProperties", json!({"tab": tab}))], - Box::new(move |a| a.ui.right == Some(RightPane::LayerProperties) && Some(a.ui.layer_properties_tab) == topic), - )); +/// A surface: what a user sees at once, such as a pane, a dialog or a phone's sheet. +pub struct Surface { + /// Its name, which starts each problem found on it. + pub name: String, + /// The commands that show it, run on a fresh app. + pub commands: Vec<(&'static str, Value)>, + /// What else readies it, after the commands: a page picked, a sheet raised in egui's memory. + pub then: Box, + /// Whether it is shown. + pub shown: Box bool>, + /// It is the whole window (a ribbon tab, the start page): what the bare window shows is tested + /// on it, rather than left to the surfaces that are. + pub whole: bool, + /// It shows the window as it is with nothing opened (the first ribbon tab, the phone's map), + /// so it needn't show a control the bare window hasn't got. + pub bare: bool, +} + +impl Surface { + /// `name`, shown by `commands` and shown while `shown` says so. + pub fn new( + name: impl Into, + commands: Vec<(&'static str, Value)>, + shown: impl Fn(&RustGisApp, &egui::Context) -> bool + 'static, + ) -> Self { + Surface { name: name.into(), commands, then: Box::new(|_, _| {}), shown: Box::new(shown), whole: false, bare: false } } - for (section, _) in crate::analysispane::SECTIONS { - all.push(( - format!("workflows {section}"), - vec![cities.clone(), ("ui.pane.workflows", json!({"section": section}))], - Box::new(move |a| a.ui.right == Some(RightPane::Workflows) && a.workflow.section == *section), - )); + + /// Readied by `then` after its commands. + pub fn then(mut self, then: impl Fn(&mut RustGisApp, &egui::Context) + 'static) -> Self { + self.then = Box::new(then); + self } - for name in DIALOGS { - // A Web Data service opens in the right pane. - let shown: Box bool> = match crate::panes::web_data_name(name) { - Some(service) => Box::new(move |a| a.ui.right == Some(RightPane::WebData) && a.ui.web_data == service), - None => Box::new(move |a| a.dialogs.open == Some(*name)), - }; - all.push((format!("dialog {name}"), vec![cities.clone(), ("ui.dialog", json!({"name": name, "layer": "Cities"}))], shown)); + + /// The whole window: see [`Surface::whole`]. + pub fn whole(mut self) -> Self { + self.whole = true; + self } - let table = ("table.open", json!({"layer": "Cities"})); - let layout = ("layout.new", json!({"page": "a4", "template": "map"})); - let designer = ("ui.modelDesigner", Value::Null); - let symbology = ("ui.pane.symbology", Value::Null); - let with_pane = |a: &RustGisApp| a.ui.right.is_some(); - // A script longer than the pane: the box grows to the buttons, which must stay in reach. - all.push(( - "pane Script, long script".into(), - vec![("ui.pane.script", Value::Null)], - Box::new(|a| a.ui.right == Some(RightPane::Script)), - )); - all.push(("left catalog".into(), vec![("ui.pane.catalog", Value::Null)], Box::new(|a| a.ui.left == Some(LeftPane::Catalog)))); - all.push(("left sources".into(), vec![("ui.pane.sources", Value::Null)], Box::new(|a| a.ui.left == Some(LeftPane::Sources)))); - all.push(("view table".into(), vec![table.clone()], Box::new(|a| a.session.table_layer.is_some()))); - all.push(( - "view table, pane".into(), - vec![table, cities.clone(), symbology.clone()], - Box::new(move |a| a.session.table_layer.is_some() && with_pane(a)), - )); - all.push(("view layout".into(), vec![layout.clone()], Box::new(|a| a.session.active_layout.is_some()))); - all.push(( - "view layout, pane".into(), - vec![layout, ("ui.pane.format", Value::Null)], - Box::new(move |a| a.session.active_layout.is_some() && with_pane(a)), - )); - all.push(("view designer".into(), vec![designer.clone()], Box::new(|a| a.mb.shown()))); - all.push(("view designer, pane".into(), vec![designer, cities, symbology], Box::new(move |a| a.mb.shown() && with_pane(a)))); - for page in START_PAGES { - all.push(( - format!("start {page}"), - vec![("ui.backstage", json!({"open": true}))], - Box::new(move |a| a.ui.backstage && a.ui.backstage_page == page), - )); + + /// The bare window: see [`Surface::bare`]. + pub fn bare(mut self) -> Self { + self.whole = true; + self.bare = true; + self } - all +} + +/// Where surfaces are tested: the window's sizes, the problems known there, and the app. +pub struct Suite { + /// The window's sizes, each surface shown at every one. + pub sizes: Vec, + /// Problems there are today, as the test names them. Only take lines out: a new problem is + /// fixed, not listed, and a line whose problem is gone fails the test. + pub known: &'static [&'static str], + /// The fewest controls read on a surface, on average: reading few would pass as few problems. + pub min_controls: usize, + /// A fresh app for the surface named. + pub app: fn(&str) -> RustGisApp, } /// Shows `surface` in a fresh app; an error when it isn't shown or starts a download. -fn open(h: &mut Harness, (surface, commands, shown): &Surface) -> Result<(), String> { +fn open(h: &mut dyn Window, suite: &Suite, surface: &Surface) -> Result<(), String> { + let name = &surface.name; let downloads = DOWNLOADS.get(); // A fresh app in the same window: fonts are loaded once, and nothing stays open. - *h.state_mut() = app(surface); - h.ctx.memory_mut(|m| { + *h.app() = (suite.app)(name); + h.ctx().memory_mut(|m| { m.data.clear(); m.reset_areas(); }); - h.set_size(SIZES[0]); - h.run_steps(3); - for (id, params) in commands { - h.state_mut().run(id, params.clone()).map_err(|e| format!("{surface}: {id}: {e}"))?; + if let Some(size) = suite.sizes.first() { + h.set_size(*size); } - if let Some(page) = START_PAGES.into_iter().find(|p| *surface == format!("start {p}")) { - h.state_mut().ui.backstage_page = page; + h.run_steps(3); + for (id, params) in &surface.commands { + h.app().run(id, params.clone()).map_err(|e| format!("{name}: {id}: {e}"))?; } + let ctx = h.ctx().clone(); + (surface.then)(h.app(), &ctx); h.run_steps(4); if DOWNLOADS.get() > downloads { - return Err(format!("{surface}: it downloads as it opens")); + return Err(format!("{name}: it downloads as it opens")); } - if !shown(h.state()) { Err(format!("{surface}: not shown")) } else { Ok(()) } + if !(surface.shown)(h.app(), &ctx) { Err(format!("{name}: not shown")) } else { Ok(()) } } -/// Shows every [`PARTS`]th surface at each size and compares the problems found with [`KNOWN`]. -fn check(part: usize) { +/// Shows each surface in `window` at each of the suite's sizes, in a stand-in for a long language, +/// and compares the problems found, on it and in its menus, with those the suite knows. +/// +/// # Panics +/// +/// On a problem found that the suite doesn't know, on one it knows that is gone, and on a surface +/// that doesn't open: it is a test's body. +pub fn run(window: &mut dyn Window, suite: &Suite, surfaces: Vec) { + assert!(!suite.sizes.is_empty(), "a suite shows its surfaces at one size at least"); + // Back as it was however this ends, a failed check included. + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + pseudo::set(self.0); + } + } + let _restore = Restore(pseudo::on()); pseudo::set(true); - let mut h = harness(); + let h = window; // The window with nothing opened: a surface shows controls it hasn't got. - let bare: Surface = ("bare".into(), Vec::new(), Box::new(|_| true)); - let opened = open(&mut h, &bare); + let opened = open(h, suite, &Surface::new("bare", Vec::new(), |_, _| true)); assert!(opened.is_ok(), "{opened:?}"); - let bare: Vec = SIZES + let bare: Vec = suite + .sizes .iter() .map(|size| { h.set_size(*size); h.run_steps(3); - controls(&h).iter().map(|c| (c.id, (c.rect, c.seen))).collect() + Bare::of(h) }) .collect(); let (mut found, mut tested, mut read) = (BTreeSet::new(), BTreeSet::new(), 0); - for surface in surfaces().into_iter().skip(part).step_by(PARTS) { - let opened = open(&mut h, &surface); + for surface in &surfaces { + let opened = open(h, suite, surface); assert!(opened.is_ok(), "{opened:?}"); - let (name, _, shown) = &surface; - for (size, bare) in SIZES.into_iter().zip(&bare) { - h.set_size(size); + let name = &surface.name; + for (size, bare) in suite.sizes.iter().zip(&bare) { + h.set_size(*size); h.run_steps(3); - assert!(shown(h.state()), "{name} at {}: not shown", size.x); - let all = controls(&h); - // Home is the tab the bare window shows. - let own = *name == format!("ribbon {}", crate::ribbon::TABS[0]) || all.iter().any(|c| !bare.contains_key(&c.id)); + let ctx = h.ctx().clone(); + assert!((surface.shown)(h.app(), &ctx), "{name} at {}: not shown", size.x); + let all = controls(h); + let own = surface.bare || all.iter().any(|c| !bare.controls.contains_key(&c.id)); assert!(own, "{name} at {}: shows no control of its own", size.x); read += all.len(); - found.extend(problems(&mut h, name, bare)); + found.extend(problems(h, name, surface.whole, bare)); + found.extend(menus(h, name, surface.whole, bare)); } tested.insert(name.clone()); } - pseudo::set(false); - assert!(!tested.is_empty(), "part {part} has no surfaces"); + assert!(!tested.is_empty(), "no surfaces to test"); + assert_eq!(tested.len(), surfaces.len(), "two surfaces share a name"); // Reading few of the controls would pass as few problems. - let each = read / (tested.len() * SIZES.len()); - assert!(each >= MIN_CONTROLS, "only {each} controls were read on a surface, on average"); + let each = read / (tested.len() * suite.sizes.len()); + assert!(each >= suite.min_controls, "only {each} controls were read on a surface, on average"); let known: BTreeSet = - KNOWN.iter().filter(|k| tested.iter().any(|s| k.starts_with(&format!("{s} at ")))).map(|k| k.to_string()).collect(); + suite.known.iter().filter(|k| tested.iter().any(|s| k.starts_with(&format!("{s} at ")))).map(|k| k.to_string()).collect(); let new: Vec<&String> = found.difference(&known).collect(); assert!( new.is_empty(), - "controls that overlap, or that scrolling doesn't bring into view. Let the row wrap, scroll or shrink; don't add it to KNOWN:\n{new:#?}" + "controls or text that overlap, or controls that scrolling doesn't bring into view. Let the row wrap, scroll or shrink; don't list it as known:\n{new:#?}" ); let gone: Vec<&String> = known.difference(&found).collect(); - assert!(gone.is_empty(), "no longer there: take these out of KNOWN:\n{gone:#?}"); + assert!(gone.is_empty(), "no longer there: take these out of the known problems:\n{gone:#?}"); } -/// The app's window, with the sample project. -fn harness() -> Harness<'static> { - let mut h: Harness = egui_kittest::Harness::builder().with_size(SIZES[0]).with_step_dt(0.25).build_ui_state( - |ui, app: &mut RustGisApp| { - let ctx = ui.ctx().clone(); - app.logic(&ctx); - app.ui(ui); - }, - RustGisApp::with_sample(), - ); - h.run_steps(6); - h -} - -/// The fewest controls read on a surface, on average: a map with a pane open shows more. -const MIN_CONTROLS: usize = 60; - -/// The sample project's app, with what differs between machines or costs time taken out. -fn app(surface: &str) -> RustGisApp { - let mut app = RustGisApp::with_sample(); - // Drawing the map is half the time, and no control is in it. Infographics reads the layers shown. - if surface != format!("pane {:?}", RightPane::Infographics) { - for layer in &mut app.session.map_mut().layers { - layer.visible = false; - } - app.session.map_mut().basemap = Default::default(); - } - app.assistant.agents_found = Some(Default::default()); - if surface == "pane Script, long script" { - app.workflow.script = (0..80).map(|i| format!("map.zoomIn {{\"step\": {i}}}\n")).collect(); - } - app.ui.left = Some(LeftPane::Contents); - app.ui.language = "en".into(); - app -} - -#[test] -fn every_control_can_be_reached_0() { - check(0); -} - -#[test] -fn every_control_can_be_reached_1() { - check(1); -} - -#[test] -fn every_control_can_be_reached_2() { - check(2); -} - -#[test] -fn every_control_can_be_reached_3() { - check(3); -} - -/// Every surface is named once, so [`KNOWN`] lines mean one thing, and every line names one. -#[test] -fn known_problems_name_surfaces() { - let names: Vec = surfaces().into_iter().map(|(name, ..)| name).collect(); - assert_eq!(names.iter().collect::>().len(), names.len()); - for line in KNOWN { - assert!(names.iter().any(|n| SIZES.iter().any(|s| line.starts_with(&format!("{n} at {}: ", s.x)))), "{line}: no such surface"); - } - assert!(PANES.iter().all(|p| pane_command(*p).is_some())); -} - -/// The test sees a problem of each kind, and a surface that doesn't open, so a test that stopped -/// seeing them doesn't pass. -#[test] -fn problems_are_seen() { - let draw = |add: fn(&mut egui::Ui)| { - let mut h: Harness = egui_kittest::Harness::builder() - .with_size(vec2(300.0, 400.0)) - .build_ui_state(move |ui, _: &mut RustGisApp| add(ui), RustGisApp::with_sample()); - h.run_steps(3); - problems(&mut h, "start test", &Bare::new()) - }; - const LABELS: [&str; 3] = ["A first long label", "A second long label", "A third long label"]; - let wide = |ui: &mut egui::Ui| { - ui.horizontal(|ui| LABELS.map(|l| ui.button(l))); - }; - assert_eq!(draw(wide), ["start test at 300: cut off Button \"A third long label\""]); - // The same row is fine where it scrolls. - let scrolled = |ui: &mut egui::Ui| { - egui::ScrollArea::horizontal().show(ui, |ui| ui.horizontal(|ui| LABELS.map(|l| ui.button(l)))); - }; - assert_eq!(draw(scrolled), Vec::::new()); - let on_top = |ui: &mut egui::Ui| { - ui.put(Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Under")); - ui.put(Rect::from_min_size(egui::pos2(90.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Over")); - // A small button wholly on another is still on it. - ui.put(Rect::from_min_size(egui::pos2(20.0, 80.0), vec2(120.0, 30.0)), egui::Button::new("Wide")); - ui.put(Rect::from_min_size(egui::pos2(40.0, 86.0), vec2(16.0, 16.0)), egui::Button::new("x")); - }; - // Two pairs of the same names: two lines. - let twice = |ui: &mut egui::Ui| { - for y in [20.0, 80.0] { - ui.put(Rect::from_min_size(egui::pos2(20.0, y), vec2(120.0, 30.0)), egui::Button::new("Delete")); - ui.put(Rect::from_min_size(egui::pos2(90.0, y), vec2(120.0, 30.0)), egui::Button::new("Rename")); - } - }; - assert_eq!( - draw(twice), - [ - "start test at 300: overlap Button \"Delete\" and Button \"Rename\"", - "start test at 300: overlap Button \"Delete\" and Button \"Rename\" (2)" - ] - ); - // Named as a tab and its close button, but not one on the other's end: still on each other. - let named = |ui: &mut egui::Ui| { - ui.put(Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Project")); - ui.put(Rect::from_min_size(egui::pos2(90.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Close Project")); - }; - assert_eq!(draw(named), ["start test at 300: overlap Button \"Project\" and Button \"Close Project\""]); - assert_eq!( - draw(on_top), - ["start test at 300: overlap Button \"Under\" and Button \"Over\"", "start test at 300: overlap Button \"Wide\" and Button \"x\""] - ); - // Two buttons on each other below the scrolled-to part of a list, and a control taller than - // the list beside a short one further down: both found once scrolled to. - let list = |ui: &mut egui::Ui| { - egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { - ui.add_space(400.0); - let at = ui.cursor().min; - ui.put(Rect::from_min_size(at, vec2(120.0, 30.0)), egui::Button::new("Lower")); - ui.put(Rect::from_min_size(at + vec2(60.0, 0.0), vec2(120.0, 30.0)), egui::Button::new("Upper")); - ui.add_space(40.0); - }); - }; - assert_eq!(draw(list), ["start test at 300: overlap Button \"Lower\" and Button \"Upper\""]); - // Two on each other between other rows below the visible part, which are the ones scrolled to. - let middle = |ui: &mut egui::Ui| { - egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { - ui.add_space(300.0); - let at = ui.cursor().min; - ui.put(Rect::from_min_size(at, vec2(120.0, 30.0)), egui::Button::new("First")); - ui.put(Rect::from_min_size(at + vec2(60.0, 0.0), vec2(120.0, 30.0)), egui::Button::new("Second")); - ui.add_space(40.0); - let _ = ui.add_sized(vec2(120.0, 60.0), egui::Button::new("Tallest")); - for _ in 0..3 { - let _ = ui.button("Row"); - } - }); - }; - assert_eq!(draw(middle), ["start test at 300: overlap Button \"First\" and Button \"Second\""]); - let tall = |ui: &mut egui::Ui| { - egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { - let _ = ui.add_sized(vec2(120.0, 300.0), egui::Button::new("Tall")); - ui.add_space(40.0); - let _ = ui.add_sized(vec2(120.0, 30.0), egui::Button::new("Short")); - }); - }; - assert_eq!(draw(tall), ["start test at 300: cut off Button \"Tall\" and 1 more"]); - // On a surface other than the ribbon's, a control the bare window hasn't got, or has - // elsewhere, is checked wherever it is, at the top too. - let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( - |ui, _: &mut RustGisApp| { - ui.horizontal(|ui| LABELS.map(|l| ui.button(l))); - }, - RustGisApp::with_sample(), - ); - h.run_steps(3); - assert_eq!(problems(&mut h, "pane test", &Bare::new()), ["pane test at 300: cut off Button \"A third long label\""]); - let bare = controls(&h).iter().map(|c| (c.id, (c.rect, c.seen))).collect(); - assert_eq!(problems(&mut h, "pane test", &bare), Vec::::new(), "what the bare window shows is left to the ribbon's surfaces"); - // A control of the surface on one of the window's, which stays where it was, is on it. - let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( - |ui, on: &mut RustGisApp| { - ui.put(Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Window's")); - if on.ui.backstage { - ui.put(Rect::from_min_size(egui::pos2(90.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Surface's")); - } - }, - RustGisApp::with_sample(), - ); - h.run_steps(3); - let bare = controls(&h).iter().map(|c| (c.id, (c.rect, c.seen))).collect(); - h.state_mut().ui.backstage = true; - h.run_steps(3); - assert_eq!(problems(&mut h, "pane test", &bare), ["pane test at 300: overlap Button \"Window's\" and Button \"Surface's\""]); - // And one it lies on only once scrolled to: a control of the window over the middle of a list. - let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( - |ui, on: &mut RustGisApp| { - let top = ui.cursor().min; - if on.ui.backstage { - egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { - ui.add_space(400.0); - let _ = ui.add_sized(vec2(120.0, 30.0), egui::Button::new("Deep")); - ui.add_space(400.0); - }); - } - ui.put(Rect::from_min_size(top + vec2(0.0, 85.0), vec2(120.0, 30.0)), egui::Button::new("Window's")); - }, - RustGisApp::with_sample(), - ); - h.run_steps(3); - let bare = controls(&h).iter().map(|c| (c.id, (c.rect, c.seen))).collect(); - h.state_mut().ui.backstage = true; - h.run_steps(3); - assert_eq!(problems(&mut h, "pane test", &bare), ["pane test at 300: overlap Button \"Deep\" and Button \"Window's\""]); - // A command that succeeds without showing what it should. - let mut h = harness(); - let unopened: Surface = ("pane Tools".into(), vec![("ui.tab", json!({"tab": "Data"}))], Box::new(|a| a.ui.right.is_some())); - assert_eq!(open(&mut h, &unopened), Err("pane Tools: not shown".into())); -} +#[cfg(test)] +mod desktop; diff --git a/crates/ui-egui/src/layout_reach/desktop.rs b/crates/ui-egui/src/layout_reach/desktop.rs new file mode 100644 index 0000000000..1daef78aba --- /dev/null +++ b/crates/ui-egui/src/layout_reach/desktop.rs @@ -0,0 +1,505 @@ +//! The desktop window's surfaces: each ribbon tab, Workflows section, listed pane, dialog and main +//! view, and the start page. + +use super::*; +use crate::{LeftPane, RightPane}; +use serde_json::json; + +/// A laptop's window, then the desktop app's smallest (`with_min_inner_size` in `apps/rustgis`). +const SIZES: [Vec2; 2] = [vec2(1280.0, 720.0), vec2(900.0, 560.0)]; +/// The surfaces are tested in this many parts, side by side. +const PARTS: usize = 4; + +/// Problems there are today, as [`problems`] names them. Only take lines out: a new problem is +/// fixed, not listed, and a line whose problem is gone fails the test. +const KNOWN: &[&str] = &[]; + +/// The command that opens each pane. A new pane doesn't compile until it has one here, or `None` +/// where it needs what the sample project hasn't got. +fn pane_command(pane: RightPane) -> Option<&'static str> { + Some(match pane { + RightPane::Geoprocessing => "ui.pane.geoprocessing", + RightPane::Symbology => "ui.pane.symbology", + RightPane::History => "ui.pane.history", + RightPane::Editing => "ui.pane.editing", + RightPane::Annotation => "ui.pane.annotation", + RightPane::Design => "ui.pane.design", + RightPane::Script => "ui.pane.script", + RightPane::Tasks => "ui.pane.tasks", + RightPane::Jobs => "ui.pane.jobs", + RightPane::Profile => "ui.pane.profile", + RightPane::TimeSeries => "ui.pane.timeSeries", + RightPane::Diagnostics => "ui.pane.diagnostics", + RightPane::DiagnosticLog => "ui.pane.diagnosticLog", + RightPane::Infographics => "ui.pane.infographics", + RightPane::Report => "ui.pane.report", + RightPane::Presentation => "ui.pane.presentation", + RightPane::Notebook => "ui.pane.notebook", + RightPane::Assistant => "ui.pane.assistant", + RightPane::Shares => "ui.pane.shares", + RightPane::Sql => "ui.pane.sql", + RightPane::Directions => "ui.pane.directions", + RightPane::Bookmarks => "ui.pane.bookmarks", + RightPane::Format => "ui.pane.format", + RightPane::Labeling => "ui.pane.labeling", + RightPane::LayerProperties => "ui.pane.layerProperties", + // Opened by section, by service and by a plugin: the first two are surfaces of their own. + RightPane::Workflows | RightPane::WebData | RightPane::Plugin => return None, + }) +} + +const PANES: [RightPane; 25] = [ + RightPane::Geoprocessing, + RightPane::Symbology, + RightPane::History, + RightPane::Editing, + RightPane::Annotation, + RightPane::Design, + RightPane::Script, + RightPane::Tasks, + RightPane::Jobs, + RightPane::Profile, + RightPane::TimeSeries, + RightPane::Diagnostics, + RightPane::DiagnosticLog, + RightPane::Infographics, + RightPane::Report, + RightPane::Presentation, + RightPane::Notebook, + RightPane::Assistant, + RightPane::Shares, + RightPane::Sql, + RightPane::Directions, + RightPane::Bookmarks, + RightPane::Format, + RightPane::Labeling, + RightPane::LayerProperties, +]; + +/// The dialogs that open on the sample project. Natural Earth isn't one: it downloads as it opens. +const DIALOGS: &[&str] = &[ + "selectByAttributes", + "goToXY", + "createPointXY", + "bookmark", + "addField", + "calculateField", + "calculateGeometry", + "renameLayer", + "renameMap", + "coordinateSystem", + "projectProperties", + "defineProjection", + "addShapefile", + "camera", + "addTiles", + "basemap", + "body", + "addSample", + "layerTemplate", + "addPolyline", + "addCsv", + "addDxf", + "findPlace", + "geocode", + "addUrl", + "addService", + "addDatabase", + "zarr", + "exportLayer", + "saveProject", + "exportOrbit", + "publicationWizard", + "opendata", + "sourcecoop", +]; + +/// The start page's pages tested. +const START_PAGES: [&str; 2] = ["open", "about"]; + +/// Every surface tested. +fn surfaces() -> Vec { + let cities = ("layer.select", json!({"layer": "Cities"})); + let mut all: Vec = Vec::new(); + // The Imagery extension's tab too: it is on by default. + let imagery = rustgis_engine::extensions::tab_id("imagery"); + for tab in crate::ribbon::TABS.into_iter().map(String::from).chain([imagery]) { + let name = format!("ribbon {}", tab.trim_start_matches("extension:")); + // Home is the tab the bare window shows. + let home = tab == crate::ribbon::TABS[0]; + let surface = Surface::new(name, vec![("ui.tab", json!({"tab": tab.clone()}))], move |a, _| a.ui.tab == tab); + all.push(if home { surface.bare() } else { surface.whole() }); + } + for pane in PANES { + let commands = pane_command(pane).map(|id| vec![cities.clone(), (id, Value::Null)]).unwrap_or_default(); + all.push(Surface::new(format!("pane {pane:?}"), commands, move |a, _| a.ui.right == Some(pane))); + } + for tab in ["general", "source", "display", "query", "time"] { + let topic = crate::layerprops::Topic::parse(tab); + all.push(Surface::new( + format!("layer properties {tab}"), + vec![cities.clone(), ("ui.pane.layerProperties", json!({"tab": tab}))], + move |a, _| a.ui.right == Some(RightPane::LayerProperties) && Some(a.ui.layer_properties_tab) == topic, + )); + } + for (section, _) in crate::analysispane::SECTIONS { + all.push(Surface::new( + format!("workflows {section}"), + vec![cities.clone(), ("ui.pane.workflows", json!({"section": section}))], + move |a, _| a.ui.right == Some(RightPane::Workflows) && a.workflow.section == *section, + )); + } + for name in DIALOGS { + let commands = vec![cities.clone(), ("ui.dialog", json!({"name": name, "layer": "Cities"}))]; + // A Web Data service opens in the right pane. + all.push(match crate::panes::web_data_name(name) { + Some(service) => Surface::new(format!("dialog {name}"), commands, move |a, _| { + a.ui.right == Some(RightPane::WebData) && a.ui.web_data == service + }), + None => Surface::new(format!("dialog {name}"), commands, move |a, _| a.dialogs.open == Some(*name)), + }); + } + let table = ("table.open", json!({"layer": "Cities"})); + let layout = ("layout.new", json!({"page": "a4", "template": "map"})); + let designer = ("ui.modelDesigner", Value::Null); + let symbology = ("ui.pane.symbology", Value::Null); + let with_pane = |a: &RustGisApp| a.ui.right.is_some(); + // A script longer than the pane: the box grows to the buttons, which must stay in reach. + all.push(Surface::new("pane Script, long script", vec![("ui.pane.script", Value::Null)], |a, _| a.ui.right == Some(RightPane::Script))); + all.push(Surface::new("left catalog", vec![("ui.pane.catalog", Value::Null)], |a, _| a.ui.left == Some(LeftPane::Catalog))); + all.push(Surface::new("left sources", vec![("ui.pane.sources", Value::Null)], |a, _| a.ui.left == Some(LeftPane::Sources))); + all.push(Surface::new("view table", vec![table.clone()], |a, _| a.session.table_layer.is_some())); + all.push(Surface::new("view table, pane", vec![table, cities.clone(), symbology.clone()], move |a, _| { + a.session.table_layer.is_some() && with_pane(a) + })); + all.push(Surface::new("view layout", vec![layout.clone()], |a, _| a.session.active_layout.is_some())); + all.push(Surface::new("view layout, pane", vec![layout, ("ui.pane.format", Value::Null)], move |a, _| { + a.session.active_layout.is_some() && with_pane(a) + })); + all.push(Surface::new("view designer", vec![designer.clone()], |a, _| a.mb.shown())); + all.push(Surface::new("view designer, pane", vec![designer, cities, symbology], move |a, _| a.mb.shown() && with_pane(a))); + for page in START_PAGES { + let surface = Surface::new(format!("start {page}"), vec![("ui.backstage", json!({"open": true}))], move |a, _| { + a.ui.backstage && a.ui.backstage_page == page + }); + all.push(surface.whole().then(move |a, _| a.ui.backstage_page = page)); + } + all +} + +type Harness<'a> = egui_kittest::Harness<'a, RustGisApp>; + +impl Window for Harness<'_> { + fn ctx(&self) -> &egui::Context { + &self.ctx + } + + fn app(&mut self) -> &mut RustGisApp { + self.state_mut() + } + + fn run_steps(&mut self, steps: usize) { + egui_kittest::Harness::run_steps(self, steps); + } + + fn event(&mut self, event: Event) { + egui_kittest::Harness::event(self, event); + } + + fn set_size(&mut self, size: Vec2) { + egui_kittest::Harness::set_size(self, size); + } +} + +/// The app's window, keeping what the check reads of each frame. +fn harness() -> Harness<'static> { + let mut h: Harness = egui_kittest::Harness::builder().with_size(SIZES[0]).with_step_dt(0.25).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + keep_frame(&ctx); + }, + app("bare"), + ); + h.run_steps(6); + h +} + +/// Where the desktop's surfaces are tested. +fn suite() -> Suite { + Suite { sizes: SIZES.to_vec(), known: KNOWN, min_controls: MIN_CONTROLS, app } +} + +/// Tests every [`PARTS`]th surface. +fn check(part: usize) { + run(&mut harness(), &suite(), surfaces().into_iter().skip(part).step_by(PARTS).collect()); +} + +/// The fewest controls read on a surface, on average: a map with a pane open shows more. +const MIN_CONTROLS: usize = 60; + +/// The sample project's app, with what differs between machines or costs time taken out. +fn app(surface: &str) -> RustGisApp { + let mut app = RustGisApp::with_sample(); + // Drawing the map is half the time, and no control is in it. Infographics reads the layers shown. + if surface != format!("pane {:?}", RightPane::Infographics) { + for layer in &mut app.session.map_mut().layers { + layer.visible = false; + } + app.session.map_mut().basemap = Default::default(); + } else { + // Its labels are the map's, placed by the labeling engine. + for layer in &mut app.session.map_mut().layers { + layer.labels.enabled = false; + } + } + app.assistant.agents_found = Some(Default::default()); + if surface == "pane Script, long script" { + app.workflow.script = (0..80).map(|i| format!("map.zoomIn {{\"step\": {i}}}\n")).collect(); + } + app.ui.left = Some(LeftPane::Contents); + app.ui.language = "en".into(); + app +} + +#[test] +fn every_control_can_be_reached_0() { + check(0); +} + +#[test] +fn every_control_can_be_reached_1() { + check(1); +} + +#[test] +fn every_control_can_be_reached_2() { + check(2); +} + +#[test] +fn every_control_can_be_reached_3() { + check(3); +} + +/// Every surface is named once, so [`KNOWN`] lines mean one thing, and every line names one. +#[test] +fn known_problems_name_surfaces() { + let names: Vec = surfaces().into_iter().map(|s| s.name).collect(); + assert_eq!(names.iter().collect::>().len(), names.len()); + for line in KNOWN { + assert!(names.iter().any(|n| SIZES.iter().any(|s| line.starts_with(&format!("{n} at {}: ", s.x)))), "{line}: no such surface"); + } + assert!(PANES.iter().all(|p| pane_command(*p).is_some())); +} + +/// The test sees a problem of each kind, and a surface that doesn't open, so a test that stopped +/// seeing them doesn't pass. +#[test] +fn problems_are_seen() { + let draw = |add: fn(&mut egui::Ui)| { + let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( + move |ui, _: &mut RustGisApp| { + add(ui); + keep_frame(ui.ctx()); + }, + RustGisApp::with_sample(), + ); + h.run_steps(3); + problems(&mut h, "start test", true, &Bare::default()) + }; + const LABELS: [&str; 3] = ["A first long label", "A second long label", "A third long label"]; + let wide = |ui: &mut egui::Ui| { + ui.horizontal(|ui| LABELS.map(|l| ui.button(l))); + }; + assert_eq!(draw(wide), ["start test at 300: cut off Button \"A third long label\""]); + // The same row is fine where it scrolls. + let scrolled = |ui: &mut egui::Ui| { + egui::ScrollArea::horizontal().show(ui, |ui| ui.horizontal(|ui| LABELS.map(|l| ui.button(l)))); + }; + assert_eq!(draw(scrolled), Vec::::new()); + let on_top = |ui: &mut egui::Ui| { + ui.put(Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Under")); + ui.put(Rect::from_min_size(egui::pos2(90.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Over")); + // A small button wholly on another is still on it. + ui.put(Rect::from_min_size(egui::pos2(20.0, 80.0), vec2(120.0, 30.0)), egui::Button::new("Wide")); + ui.put(Rect::from_min_size(egui::pos2(40.0, 86.0), vec2(16.0, 16.0)), egui::Button::new("x")); + }; + // Two pairs of the same names: two lines. + let twice = |ui: &mut egui::Ui| { + for y in [20.0, 80.0] { + ui.put(Rect::from_min_size(egui::pos2(20.0, y), vec2(120.0, 30.0)), egui::Button::new("Delete")); + ui.put(Rect::from_min_size(egui::pos2(90.0, y), vec2(120.0, 30.0)), egui::Button::new("Rename")); + } + }; + assert_eq!( + draw(twice), + [ + "start test at 300: overlap Button \"Delete\" and Button \"Rename\"", + "start test at 300: overlap Button \"Delete\" and Button \"Rename\" (2)" + ] + ); + // Named as a tab and its close button, but not one on the other's end: still on each other. + let named = |ui: &mut egui::Ui| { + ui.put(Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Project")); + ui.put(Rect::from_min_size(egui::pos2(90.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Close Project")); + }; + assert_eq!(draw(named), ["start test at 300: overlap Button \"Project\" and Button \"Close Project\""]); + assert_eq!( + draw(on_top), + ["start test at 300: overlap Button \"Under\" and Button \"Over\"", "start test at 300: overlap Button \"Wide\" and Button \"x\""] + ); + // Two buttons on each other below the scrolled-to part of a list, and a control taller than + // the list beside a short one further down: both found once scrolled to. + let list = |ui: &mut egui::Ui| { + egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + ui.add_space(400.0); + let at = ui.cursor().min; + ui.put(Rect::from_min_size(at, vec2(120.0, 30.0)), egui::Button::new("Lower")); + ui.put(Rect::from_min_size(at + vec2(60.0, 0.0), vec2(120.0, 30.0)), egui::Button::new("Upper")); + ui.add_space(40.0); + }); + }; + assert_eq!(draw(list), ["start test at 300: overlap Button \"Lower\" and Button \"Upper\""]); + // Two on each other between other rows below the visible part, which are the ones scrolled to. + let middle = |ui: &mut egui::Ui| { + egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + ui.add_space(300.0); + let at = ui.cursor().min; + ui.put(Rect::from_min_size(at, vec2(120.0, 30.0)), egui::Button::new("First")); + ui.put(Rect::from_min_size(at + vec2(60.0, 0.0), vec2(120.0, 30.0)), egui::Button::new("Second")); + ui.add_space(40.0); + let _ = ui.add_sized(vec2(120.0, 60.0), egui::Button::new("Tallest")); + for _ in 0..3 { + let _ = ui.button("Row"); + } + }); + }; + assert_eq!(draw(middle), ["start test at 300: overlap Button \"First\" and Button \"Second\""]); + let tall = |ui: &mut egui::Ui| { + egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + let _ = ui.add_sized(vec2(120.0, 300.0), egui::Button::new("Tall")); + ui.add_space(40.0); + let _ = ui.add_sized(vec2(120.0, 30.0), egui::Button::new("Short")); + }); + }; + assert_eq!(draw(tall), ["start test at 300: cut off Button \"Tall\" and 1 more"]); + // On a surface other than the ribbon's, a control the bare window hasn't got, or has + // elsewhere, is checked wherever it is, at the top too. + let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( + |ui, _: &mut RustGisApp| { + ui.horizontal(|ui| LABELS.map(|l| ui.button(l))); + keep_frame(ui.ctx()); + }, + RustGisApp::with_sample(), + ); + h.run_steps(3); + assert_eq!(problems(&mut h, "pane test", false, &Bare::default()), ["pane test at 300: cut off Button \"A third long label\""]); + let bare = Bare::of(&h); + assert_eq!( + problems(&mut h, "pane test", false, &bare), + Vec::::new(), + "what the bare window shows is left to the ribbon's surfaces" + ); + // A control of the surface on one of the window's, which stays where it was, is on it. + let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( + |ui, on: &mut RustGisApp| { + ui.put(Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Window's")); + if on.ui.backstage { + ui.put(Rect::from_min_size(egui::pos2(90.0, 20.0), vec2(120.0, 30.0)), egui::Button::new("Surface's")); + } + keep_frame(ui.ctx()); + }, + RustGisApp::with_sample(), + ); + h.run_steps(3); + let bare = Bare::of(&h); + h.state_mut().ui.backstage = true; + h.run_steps(3); + assert_eq!(problems(&mut h, "pane test", false, &bare), ["pane test at 300: overlap Button \"Window's\" and Button \"Surface's\""]); + // And one it lies on only once scrolled to: a control of the window over the middle of a list. + let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( + |ui, on: &mut RustGisApp| { + let top = ui.cursor().min; + if on.ui.backstage { + egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + ui.add_space(400.0); + let _ = ui.add_sized(vec2(120.0, 30.0), egui::Button::new("Deep")); + ui.add_space(400.0); + }); + } + ui.put(Rect::from_min_size(top + vec2(0.0, 85.0), vec2(120.0, 30.0)), egui::Button::new("Window's")); + keep_frame(ui.ctx()); + }, + RustGisApp::with_sample(), + ); + h.run_steps(3); + let bare = Bare::of(&h); + h.state_mut().ui.backstage = true; + h.run_steps(3); + assert_eq!( + problems(&mut h, "pane test", false, &bare), + ["pane test at 300: text \"Window's\" on text \"Deep\"", "pane test at 300: overlap Button \"Deep\" and Button \"Window's\""], + "their labels too, once scrolled to" + ); + // Text painted on text, with no control: a caption run into the next. + let painted = |ui: &mut egui::Ui| { + let font = egui::FontId::proportional(14.0); + ui.painter().text(egui::pos2(20.0, 20.0), egui::Align2::LEFT_TOP, "First caption", font.clone(), egui::Color32::WHITE); + ui.painter().text(egui::pos2(70.0, 22.0), egui::Align2::LEFT_TOP, "Second caption", font, egui::Color32::WHITE); + }; + assert_eq!(draw(painted), ["start test at 300: text \"First caption\" on text \"Second caption\""]); + // Captions on each other in a row of a list out of view, which no probe scrolls to: compared + // whole, as they are in the same scrolled area. + let hidden = |ui: &mut egui::Ui| { + egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + ui.add_space(300.0); + let at = ui.cursor().min; + let font = egui::FontId::proportional(14.0); + ui.painter().text(at, egui::Align2::LEFT_TOP, "Hidden first", font.clone(), egui::Color32::WHITE); + ui.painter().text(at + vec2(40.0, 2.0), egui::Align2::LEFT_TOP, "Hidden second", font, egui::Color32::WHITE); + ui.add_space(300.0); + }); + }; + assert_eq!(draw(hidden), ["start test at 300: text \"Hidden first\" on text \"Hidden second\""]); + // A menu longer than the window, and a context menu with two items on each other: each found + // once it is opened. + let menu = |add: fn(&mut egui::Ui)| { + let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state( + move |ui, _: &mut RustGisApp| { + add(ui); + keep_frame(ui.ctx()); + }, + RustGisApp::with_sample(), + ); + h.run_steps(3); + menus(&mut h, "pane test", false, &Bare::default()) + }; + let long = |ui: &mut egui::Ui| { + let button = ui.button("Long menu"); + egui::Popup::menu(&button).show(|ui| { + for i in 0..40 { + let _ = ui.button(format!("Item {i}")); + } + }); + }; + let found = menu(long); + assert!( + !found.is_empty() + && found.iter().all(|f| f.starts_with("pane test at 300: in the menu of Button \"Long menu\": cut off Button \"Item ")), + "{found:?}" + ); + let context = |ui: &mut egui::Ui| { + let _ = ui.button("Row").context_menu(|ui| { + let at = ui.cursor().min; + ui.put(Rect::from_min_size(at, vec2(120.0, 24.0)), egui::Button::new("Rename")); + ui.put(Rect::from_min_size(at + vec2(60.0, 0.0), vec2(120.0, 24.0)), egui::Button::new("Delete")); + }); + }; + assert_eq!(menu(context), ["pane test at 300: in the menu of Button \"Row\": overlap Button \"Rename\" and Button \"Delete\""]); + // A command that succeeds without showing what it should. + let mut h = harness(); + let unopened = Surface::new("pane Tools", vec![("ui.tab", json!({"tab": "Data"}))], |a, _| a.ui.right.is_some()); + assert_eq!(open(&mut h, &suite(), &unopened), Err("pane Tools: not shown".into())); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f9f581bc56..b1fe8e5571 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -77,8 +77,10 @@ mod mapview; mod markerimages; mod markerpick; pub use markerpick::{MarkerImage, marker_file_too_large}; -#[cfg(all(test, target_os = "linux"))] -mod layout_reach; +/// The check that every control and line of text on a surface can be reached, for this crate's +/// tests and, through the `testing` feature, the phone's. +#[cfg(all(any(test, feature = "testing"), target_os = "linux"))] +pub mod layout_reach; mod matchcount; mod measure_units; mod modeldesigner; @@ -874,7 +876,7 @@ pub(crate) fn fetch_within( timeout: Option, ceiling: Reach, ) -> Slot, Reach), String>> { - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] crate::layout_reach::downloaded(); let slot: Slot, Reach), String>> = Slot::default(); let land = slot.clone(); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index dd6acff8b0..ac97524393 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4205,8 +4205,13 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: // A plugin's pick waiting for the map says what it waits for instead. let hint = crate::pluginpanel::pick_hint(app).or_else(|| hint.filter(|_| !measuring).map(|h| tl!(h).to_string())); if let Some(h) = hint { - let g = p.layout_no_wrap(h, regular(12.0), Color32::WHITE); - let bg = Rect::from_center_size(pos2(rect.center().x, rect.max.y - 26.0), g.size() + vec2(22.0, 10.0)); + // Clear of the scale bar at the bottom left: between it and the same room on the right, + // wrapped to fit; on a map too narrow for that, above it. + let room = rect.width() - 2.0 * SCALE_BAR_ROOM; + let (wrap, bottom) = if room >= 160.0 { (room - 22.0, rect.max.y - 13.5) } else { (rect.width() - 62.0, rect.max.y - 48.0) }; + let g = p.layout(h, regular(12.0), Color32::WHITE, wrap.max(60.0)); + let size = g.size() + vec2(22.0, 10.0); + let bg = Rect::from_min_size(pos2(rect.center().x - size.x / 2.0, bottom - size.y), size); p.rect_filled(bg, CornerRadius::same(12), Color32::from_black_alpha(160)); p.galley(bg.center() - g.size() / 2.0, g, Color32::WHITE); } @@ -4298,6 +4303,10 @@ fn scale_bar(app: &RustGisApp, p: &egui::Painter, rect: Rect, t: &Tokens) { ); } +/// How far from the map's left edge the scale bar reaches at most, with a gap: its bar is up to 130 +/// points long, from 18 in, on a background 10 wider. +const SCALE_BAR_ROOM: f32 = 168.0; + /// The shortest map with room for the north arrow (top left, to 51 points down) and the scale /// bar (its 42 points at the bottom left) apart. const SCALE_BAR_MIN_HEIGHT: f32 = 100.0; @@ -4959,9 +4968,21 @@ fn model_tab_name(app: &RustGisApp) -> Option { app.mb.open.then(|| if app.mb.name.trim().is_empty() { tl!("Untitled model").to_string() } else { app.mb.name.trim().to_string() }) } -/// A view tab's width: its name, icon, padding and close button. -fn view_tab_w(ui: &Ui, name: &str) -> f32 { - crate::widgets::text_w(ui, name, regular(12.0)) + 46.0 + TAB_CLOSE_W +/// A view tab's width: its name, icon, padding and close button, but no wider than `most`, the +/// strip, so a map too narrow for the whole name still shows the tab (its name cut short). +fn view_tab_w(ui: &Ui, name: &str, most: f32) -> f32 { + (crate::widgets::text_w(ui, name, regular(12.0)) + 46.0 + TAB_CLOSE_W).min(most) +} + +/// A view tab's name after its icon, cut short with an ellipsis where the tab is too narrow for it. +fn paint_tab_name(ui: &Ui, tr: Rect, name: &str, is: bool, t: &Tokens) { + let (font, color) = if is { (semibold(12.0), t.text) } else { (regular(12.0), t.text_dim) }; + let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); + // From after the icon to a gap before the close button: a little more than the name measured + // in the regular face, as the tab in view draws it in semibold. + job.wrap = egui::text::TextWrapping::truncate_at_width((tr.width() - 28.0 - TAB_CLOSE_W - 6.0).max(0.0)); + let galley = ui.painter().layout_job(job); + ui.painter().galley(pos2(tr.min.x + 28.0, tr.center().y - galley.size().y / 2.0), galley, color); } /// Takes the next view tab's room in the row, `w` wide, and returns its rectangle below the @@ -4994,7 +5015,7 @@ fn view_tabs(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let tabs = tabs.chain(p.layouts.iter().enumerate().map(|(i, l)| ((1, i), &l.name))).chain(model.iter().map(|n| ((2, 0), n))); let (mut start, mut span) = (0.0, (0.0, 0.0)); for (tab, n) in tabs { - let w = view_tab_w(ui, n) + 2.0; + let w = view_tab_w(ui, n, room) + 2.0; if tab == in_view { span = (start, w); } @@ -5010,7 +5031,7 @@ fn view_tabs(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let strip_area = crate::ribbon::arrow_scroll_area(&mut tabs_ui, t, "view_tabs", area, tips, |ui| { ui.horizontal(|ui| { ui.spacing_mut().item_spacing = vec2(2.0, 0.0); - close = view_tab_row(app, ui, t, follow); + close = view_tab_row(app, ui, t, follow, room); }); }); crate::widgets::yield_touch_drag(ui.ctx(), strip_area); @@ -5031,16 +5052,16 @@ fn view_tabs(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } } -/// The view tabs in a row: maps, layouts, then Model Designer. The one in view scrolls into sight -/// while `follow` says so. The map or layout whose close button was clicked, to confirm. -fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> Option { +/// The view tabs in a row: maps, layouts, then Model Designer, each at most `most` wide. The one in +/// view scrolls into sight while `follow` says so. The map or layout whose close button was clicked, to confirm. +fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool, most: f32) -> Option { let names: Vec = app.session.project.maps.iter().map(|m| m.name.clone()).collect(); let active = if app.session.active_layout.is_some() || app.mb.shown() { usize::MAX } else { app.session.project.active_map }; // A tab's close button asks to delete its map or layout. let mut close: Option = None; let mut map_tabs = Vec::with_capacity(names.len()); for (i, n) in names.iter().enumerate() { - let tr = alloc_view_tab(ui, view_tab_w(ui, n)); + let tr = alloc_view_tab(ui, view_tab_w(ui, n, most)); let resp = ui.interact(tr, egui::Id::unique(("maptab", i)), crate::widgets::reorder_sense(ui, true)); // Painted, so named for screen readers (and tests). resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, n)); @@ -5064,13 +5085,7 @@ fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> ui.painter().rect_filled(tr, CornerRadius { nw: 6, ne: 6, sw: 0, se: 0 }, t.hover); } icons::paint(ui.painter(), Rect::from_center_size(pos2(tr.min.x + 15.0, tr.center().y), vec2(15.0, 15.0)), "map", t.icon, t.accent); - ui.painter().text( - pos2(tr.min.x + 28.0, tr.center().y), - Align2::LEFT_CENTER, - n, - if is { semibold(12.0) } else { regular(12.0) }, - if is { t.text } else { t.text_dim }, - ); + paint_tab_name(ui, tr, n, is, t); // Over the tab's fill, so painted after it. if tab_close(ui, t, tr, egui::Id::unique(("maptab_close", i)), is, !last, tip) { close = Some(Deletion::Map(n.clone())); @@ -5091,7 +5106,7 @@ fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> let layouts: Vec = app.session.project.layouts.iter().map(|l| l.name.clone()).collect(); let mut layout_tabs = Vec::with_capacity(layouts.len()); for (i, n) in layouts.iter().enumerate() { - let tr = alloc_view_tab(ui, view_tab_w(ui, n)); + let tr = alloc_view_tab(ui, view_tab_w(ui, n, most)); let resp = ui.interact(tr, egui::Id::unique(("layouttab", i)), crate::widgets::reorder_sense(ui, true)); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, n)); let dragging = drag_tab(ui, &resp, true, n); @@ -5117,13 +5132,7 @@ fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> t.icon, t.accent, ); - ui.painter().text( - pos2(tr.min.x + 28.0, tr.center().y), - Align2::LEFT_CENTER, - n, - if is { semibold(12.0) } else { regular(12.0) }, - if is { t.text } else { t.text_dim }, - ); + paint_tab_name(ui, tr, n, is, t); // Over the tab's fill, so painted after it. if tab_close(ui, t, tr, egui::Id::unique(("layouttab_close", i)), is, true, tl!("Delete Layout")) { close = Some(Deletion::Layout(n.clone())); @@ -5140,7 +5149,7 @@ fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> } // Model Designer, after the layouts. if let Some(n) = model_tab_name(app) { - let tr = alloc_view_tab(ui, view_tab_w(ui, &n)); + let tr = alloc_view_tab(ui, view_tab_w(ui, &n, most)); let resp = ui.interact(tr, egui::Id::unique("modeltab"), Sense::click()); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &n)); let is = app.mb.shown(); @@ -5164,13 +5173,7 @@ fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> t.icon, t.accent, ); - ui.painter().text( - pos2(tr.min.x + 28.0, tr.center().y), - Align2::LEFT_CENTER, - &n, - if is { semibold(12.0) } else { regular(12.0) }, - if is { t.text } else { t.text_dim }, - ); + paint_tab_name(ui, tr, &n, is, t); if tab_close(ui, t, tr, egui::Id::unique("modeltab_close"), is, true, tl!("Close Model Designer")) { let _ = app.run("ui.modelDesigner", json!({"close": true})); } diff --git a/crates/ui-egui/src/modeldesigner.rs b/crates/ui-egui/src/modeldesigner.rs index 5197847981..b3faf01abd 100644 --- a/crates/ui-egui/src/modeldesigner.rs +++ b/crates/ui-egui/src/modeldesigner.rs @@ -692,9 +692,11 @@ fn toolbar(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, problems: &[model::Pro } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { // A shell with its own interface has no view tabs: the way back to the map comes first, - // finger-sized. - let back = egui::Button::new(tl!("Back to the map")).min_size(vec2(0.0, crate::chrome::FINGER)); - if app.chrome.is_some() && ui.add(back).clicked() { + // finger-sized; its map icon alone where its words would leave the rest of the toolbar + // less room than one of its buttons, so they can still be scrolled into view. + let words = crate::widgets::text_w(ui, tl!("Back to the map"), egui::TextStyle::Button.resolve(ui.style())); + let narrow = ui.available_width() - words - 2.0 * ui.spacing().button_padding.x < 160.0; + if app.chrome.is_some() && finger_back(ui, t, narrow).clicked() { app.mb.active = false; // Opened over a layout, the layout would show in its place. A close that fails is // said by `run`, as any command's failure is. @@ -796,6 +798,21 @@ fn toolbar(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, problems: &[model::Pro }); } +/// The phone's way back to the map, a finger tall: in words, or its map icon alone when `narrow`. +fn finger_back(ui: &mut Ui, t: &Tokens, narrow: bool) -> egui::Response { + let label = tl!("Back to the map"); + if !narrow { + return ui.add(egui::Button::new(label).min_size(vec2(0.0, crate::chrome::FINGER))); + } + let side = crate::chrome::FINGER; + let (rect, resp) = ui.allocate_exact_size(vec2(side, side), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let fill = if resp.is_pointer_button_down_on() { t.pressed } else { t.input }; + ui.painter().rect_filled(rect.shrink(2.0), egui::CornerRadius::same(8), fill); + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(24.0, 24.0)), "map", t.icon, t.accent); + resp.on_hover_text(label) +} + /// The tools, by toolbox, to drag onto the canvas (or click to add). fn palette_ui(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, canvas: Rect) { crate::widgets::search_field(ui, &mut app.mb.search, tl!("Search tools")); @@ -998,13 +1015,12 @@ fn canvas_ui(app: &mut RustGisApp, ui: &mut Ui, rect: Rect, t: &Tokens, problems } } if app.mb.graph.nodes.is_empty() { - painter.text( - rect.center(), - Align2::CENTER_CENTER, - tl!("Drag a tool from the palette to start building, or add an input layer."), - regular(13.0), - t.text_dim, - ); + // Wrapped to the canvas, so a long language keeps it off the palette beside it. + let hint = tl!("Drag a tool from the palette to start building, or add an input layer."); + let mut job = egui::text::LayoutJob::simple(hint.to_string(), regular(13.0), t.text_dim, (rect.width() - 40.0).max(80.0)); + job.halign = egui::Align::Center; + let galley = painter.layout_job(job); + painter.galley(rect.center() - vec2(0.0, galley.size().y / 2.0), galley, t.text_dim); } let z = view.zoom; let node_of = |g: &ModelGraph, id: &str| g.nodes.iter().position(|n| n.id == id); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 5e7f298163..061cbb50c2 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3697,7 +3697,7 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { /// (`shown_below`), not when the Locate… error drawn below it already says it. fn geolibre_passed_over(app: &RustGisApp, ui: &mut Ui, t: &Tokens, shown_below: bool) { // None under the layout tests, as `geolibre_status` says: what a machine has installed differs. - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] if crate::i18n::pseudo::on() { return; } @@ -4788,7 +4788,11 @@ fn symbology(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { _ => "proportional", }; let sel = if app.ui.symbology_pending.is_some() { *code == "unique" } else { cur_kind == *label }; - let (r, resp) = ui.allocate_exact_size(vec2(68.0, 56.0), Sense::click()); + // The caption is the label's first word; the button grows to it where a language's + // first word runs long, and the row wraps. + let short = tl!(label).split(' ').next().unwrap_or(label); + let width = (crate::widgets::text_w(ui, short, regular(11.0)) + 12.0).max(68.0); + let (r, resp) = ui.allocate_exact_size(vec2(width, 56.0), Sense::click()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, sel, tl!(*label))); ui.painter().rect_filled( r, @@ -4814,7 +4818,6 @@ fn symbology(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { t.icon, t.accent, ); - let short = tl!(label).split(' ').next().unwrap_or(label); ui.painter().text(pos2(r.center().x, r.max.y - 11.0), Align2::CENTER_CENTER, short, regular(11.0), t.text); if resp.on_hover_text(tl!(*label)).clicked() && !sel { if *code == "unique" && !all.is_empty() { @@ -5386,7 +5389,7 @@ fn transparency_drag(app: &mut RustGisApp, ui: &Ui, r: &egui::Response, l: &Laye /// The GeoLibre runner's status, as `gp::geolibre_status` gives it. The layout tests see none /// installed on every machine, as most people first do. fn geolibre_status() -> Value { - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] if crate::i18n::pseudo::on() { return json!({"supported": true, "web": false, "available": false, "installed": false, "tools": 0}); } @@ -5396,7 +5399,7 @@ fn geolibre_status() -> Value { /// The GeoLibre runner's tools, as `gp::geolibre_tools` gives them: none under the layout tests, /// as [`geolibre_status`] says. pub(crate) fn geolibre_tools() -> &'static [rustgis_engine::analysis::ToolSpec] { - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] if crate::i18n::pseudo::on() { return &[]; } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 7c7f6b0989..ab98c9a628 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -990,6 +990,9 @@ fn web_basemaps(ui: &mut Ui, app: &mut RustGisApp, t: &Tokens) { }; ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = 4.0; + // Each whole, so a narrow menu puts the link on a line of its own rather than wrapping + // both into each other. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); ui.label(egui::RichText::new(ask).weak().small()); let resp = ui.add(egui::Link::new(egui::RichText::new(link).small().color(t.accent))); if resp.on_hover_text(hint).clicked() { @@ -1687,8 +1690,7 @@ fn graphics_and_text_group(app: &mut RustGisApp, ui: &mut Ui) { text_tool && dynamic, true, ); - egui::Popup::menu(&resp).show(|ui| { - ui.set_min_width(crate::widgets::MENU_MIN_W); + crate::widgets::show_menu(&resp, egui::PopupCloseBehavior::CloseOnClick, |ui| { for &(token, what) in rustgis_engine::map::graphics::TOKENS { if ui.button(format!("{} {token}", tl!(what))).clicked() { app.map.cancel_sketch(); @@ -3397,16 +3399,6 @@ fn share_groups(app: &mut RustGisApp, ui: &mut Ui) { json!({"kind": "styles"}), false, ); - small( - ui, - app, - "symbology", - "Color Ramps", - "Save the project's custom color ramps to a color ramp file.", - "ui.saveItem", - json!({"kind": "ramps"}), - false, - ); }); col(ui, |ui| { small( @@ -3420,6 +3412,16 @@ fn share_groups(app: &mut RustGisApp, ui: &mut Ui) { false, ); small(ui, app, "run", "Task Item", "Save the last task as a task file.", "ui.saveItem", json!({"kind": "task"}), false); + small( + ui, + app, + "symbology", + "Color Ramps", + "Save the project's custom color ramps to a color ramp file.", + "ui.saveItem", + json!({"kind": "ramps"}), + false, + ); }); }); } @@ -6105,7 +6107,8 @@ mod tests { /// One tab's groups on `app`, as the ribbon draws them. fn tab_harness(app: RustGisApp, tab: fn(&mut RustGisApp, &mut Ui)) -> egui_kittest::Harness<'static, RustGisApp> { let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(2400.0, 300.0)).build_ui_state( + // Tall enough for the menus opened from the tab: a shorter window makes them scroll. + let mut h = egui_kittest::Harness::builder().with_size(vec2(2400.0, 900.0)).build_ui_state( move |ui, app: &mut RustGisApp| { if !fonts { crate::theme::install_fonts(ui.ctx(), &[], None); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 3e876f4b9f..bdb3849430 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1036,7 +1036,7 @@ pub fn install_fonts( current: Option, ) { // Layout tests measure with egui's own faces: an installed face differs from machine to machine. - #[cfg(all(test, target_os = "linux"))] + #[cfg(all(any(test, feature = "testing"), target_os = "linux"))] if crate::i18n::pseudo::on() { let mut fonts = FontDefinitions::default(); let mut regular = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 450990ec08..ac1baf8f47 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -585,10 +585,7 @@ fn big_split_menu_with( if primary.clicked() { let _ = app.run_by_user(id, params); } - egui::Popup::menu(&arrow).close_behavior(close).show(|ui| { - ui.set_min_width(MENU_MIN_W); - menu(ui, app); - }); + show_menu(&arrow, close, |ui| menu(ui, app)); (primary, arrow) } @@ -660,20 +657,14 @@ fn small_button( /// A large button that opens a menu. pub fn big_menu(ui: &mut Ui, app: &mut RustGisApp, icon: &str, label: &str, desc: &str, menu: impl FnOnce(&mut Ui, &mut RustGisApp)) { let resp = big(ui, app, icon, label, desc, "ui.menu", Value::Null, false, true); - egui::Popup::menu(&resp).show(|ui| { - ui.set_min_width(MENU_MIN_W); - menu(ui, app); - }); + show_menu(&resp, egui::PopupCloseBehavior::CloseOnClick, |ui| menu(ui, app)); } /// A large button that opens a menu with editable controls (text boxes, checkboxes, sliders). /// Clicks inside keep it open; action buttons close it themselves (`ui.close()`). pub fn big_form_menu(ui: &mut Ui, app: &mut RustGisApp, icon: &str, label: &str, desc: &str, menu: impl FnOnce(&mut Ui, &mut RustGisApp)) { let resp = big(ui, app, icon, label, desc, "ui.menu", Value::Null, false, true); - egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(MENU_MIN_W); - menu(ui, app); - }); + show_menu(&resp, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| menu(ui, app)); } /// A small button that opens a menu. @@ -718,10 +709,38 @@ fn small_menu_with( let on_list = crate::completion::pressed_over_menu(ui.ctx()); let close = if on_list && close == egui::PopupCloseBehavior::CloseOnClickOutside { egui::PopupCloseBehavior::IgnoreClicks } else { close }; - egui::Popup::menu(&resp).close_behavior(close).show(|ui| { + show_menu(&resp, close, |ui| menu(ui, app)); +} + +/// Shows the menu `opener` opens, closed as `close` says. Where the menu was taller than the +/// window has room for under `opener`, its body scrolls, so it opens there with its last rows in +/// reach in a short window or a long language; a menu that fits is laid out as it always was. It +/// scrolls by the wheel, a drag and Tab, without a scroll bar: a click on a bar inside the menu +/// would be a click that closes it. +pub(crate) fn show_menu(opener: &Response, close: egui::PopupCloseBehavior, add: impl FnOnce(&mut Ui) -> R) -> Option { + let ctx = opener.ctx.clone(); + // Less the menu's frame, above and below, and a gap from the window's edge. + let room = (ctx.content_rect().bottom() - opener.rect.bottom() - 24.0).max(120.0); + // The menu's height last frame. + let tall = opener.id.with("menu_body_height"); + let scrolls = ctx.data(|d| d.get_temp::(tall)).is_some_and(|h| h > room); + let shown = egui::Popup::menu(opener).close_behavior(close).show(|ui| { ui.set_min_width(MENU_MIN_W); - menu(ui, app); + if scrolls { + let scroll = egui::ScrollArea::vertical() + .max_height(room) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) + .show(ui, add); + ctx.data_mut(|d| d.insert_temp(tall, scroll.content_size.y)); + return scroll.inner; + } + let top = ui.cursor().min.y; + let inner = add(ui); + let height = ui.min_rect().max.y - top; + ctx.data_mut(|d| d.insert_temp(tall, height)); + inner }); + shown.map(|r| r.inner) } /// A frameless button as a row of a menu or list. Such a button paints nothing behind its text, @@ -1116,6 +1135,56 @@ pub fn picked_colour(hsva: egui::ecolor::Hsva, before: egui::ecolor::Hsva, old: mod tests { use egui_kittest::kittest::Queryable; + /// A menu taller than the room under its button scrolls, and still closes as a menu does: not as + /// it scrolls, but on a click in a row that doesn't close it itself, and on a click outside. + #[test] + fn a_menu_that_scrolls_closes_as_a_menu_does() { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(300.0, 300.0)).build_ui(|ui| { + let opener = ui.button("Open"); + super::show_menu(&opener, egui::PopupCloseBehavior::CloseOnClick, |ui| { + for i in 0..30 { + let _ = ui.button(format!("Row {i}")); + } + }); + }); + let open = |h: &mut egui_kittest::Harness<'_>| { + h.get_by_label("Open").click(); + // Laid out once to measure it, then scrolled. + h.run_steps(4); + assert!(h.query_by_label("Row 1").is_some(), "the menu opens"); + }; + open(&mut h); + let top = h.get_by_label("Row 1").rect().min.y; + h.hover_at(h.get_by_label("Row 1").rect().center()); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -60.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }); + h.run_steps(3); + assert!(h.query_by_label("Row 1").is_some_and(|row| row.rect().min.y < top), "it scrolls and stays open"); + h.get_by_label("Row 3").click(); + h.run_steps(3); + assert!(h.query_by_label("Row 3").is_none(), "a click in a row closes it"); + open(&mut h); + let outside = egui::pos2(295.0, 295.0); + h.event(egui::Event::PointerMoved(outside)); + h.run(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { + pos: outside, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + h.run(); + } + h.run_steps(2); + assert!(h.query_by_label("Row 1").is_none(), "a click outside closes it"); + } + /// A toolbar control reached with Tab past the row's visible part is scrolled into view, so /// Enter doesn't press a button out of sight. #[test] diff --git a/crates/ui-touch/Cargo.toml b/crates/ui-touch/Cargo.toml index 51abf6bd1e..5d55914445 100644 --- a/crates/ui-touch/Cargo.toml +++ b/crates/ui-touch/Cargo.toml @@ -14,3 +14,8 @@ egui = { workspace = true } serde_json = { workspace = true } # Today's date and this moment, for the form's calendar. web-time = { workspace = true } + +[dev-dependencies] +# The layout check, for the phone's surfaces. +rustgis-ui-egui = { workspace = true, features = ["testing"] } +egui_kittest = { workspace = true } diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index 2be3f4fda2..7549bde9e0 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -238,6 +238,7 @@ pub(crate) fn strip(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { assistant::stop(app); } let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), TARGET), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Show the Assistant"))); let mut job = egui::text::LayoutJob::simple_singleline(doing(app), egui::FontId::proportional(14.0), t.text); job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width().max(0.0)); let galley = ui.painter().layout_job(job); diff --git a/crates/ui-touch/src/layout_reach.rs b/crates/ui-touch/src/layout_reach.rs new file mode 100644 index 0000000000..28011550b5 --- /dev/null +++ b/crates/ui-touch/src/layout_reach.rs @@ -0,0 +1,95 @@ +//! Every control on the phone's surfaces can be reached, in a long language, upright and on its +//! side: the map with nothing raised, each sheet, and the views the Layers sheet opens. The check +//! is the desktop's (`rustgis_ui_egui::layout_reach`). + +use super::*; +use rustgis_ui_egui::layout_reach::{Suite, Surface, Window, keep_frame, run}; + +/// A small phone upright, and on its side. +const SIZES: [Vec2; 2] = [Vec2::new(360.0, 760.0), Vec2::new(800.0, 360.0)]; + +/// Problems there are today, as the check names them. Only take lines out. +const KNOWN: &[&str] = &[]; + +/// The fewest controls read on a surface, on average: the bar and the map's buttons, and a sheet's. +const MIN_CONTROLS: usize = 6; + +/// The sample project in the touch interface, its map not drawn: no control is in it. +fn app(_surface: &str) -> RustGisApp { + let mut app = RustGisApp::with_sample(); + app.chrome = Some(chrome); + for layer in &mut app.session.map_mut().layers { + layer.visible = false; + } + app.session.map_mut().basemap = Default::default(); + app.ui.language = "en".into(); + app +} + +/// `name`: the sheet `shown` raised after `commands`. +fn sheet_surface(name: &str, commands: Vec<(&'static str, Value)>, shown: Sheet) -> Surface { + Surface::new(name, commands, move |_, ctx| sheet(ctx) == shown).then(move |_, ctx| set_sheet(ctx, shown)) +} + +/// Every surface of the phone tested. +fn surfaces() -> Vec { + let layout = ("layout.new", json!({"page": "a4", "template": "map"})); + vec![ + Surface::new("phone map", Vec::new(), |_, ctx| sheet(ctx) == Sheet::None).bare(), + sheet_surface("phone layers", Vec::new(), Sheet::Layers), + // With a layout, the sheet lists the project's views too. + sheet_surface("phone layers, views", vec![layout], Sheet::Layers), + sheet_surface("phone more", Vec::new(), Sheet::More), + // The position's rows, shown while it is. + sheet_surface("phone more, position", Vec::new(), Sheet::More).then(|app, ctx| { + app.locate = true; + set_sheet(ctx, Sheet::More); + }), + sheet_surface("phone capture point", vec![("layer.select", json!({"layer": "Cities"}))], Sheet::Capture), + sheet_surface("phone capture polygon", vec![("layer.select", json!({"layer": "Countries"}))], Sheet::Capture), + // Until a provider is set up, its settings. + Surface::new("phone assistant", Vec::new(), |_, ctx| sheet(ctx) == Sheet::Assistant) + .then(|_, ctx| assistant::raise(ctx, assistant::Height::Full)), + Surface::new("phone designer", vec![("ui.modelDesigner", Value::Null)], |app, _| app.mb.shown()), + ] +} + +/// The phone's window: the app in the touch interface, run a frame at a time. +struct Phone(egui_kittest::Harness<'static, RustGisApp>); + +impl Window for Phone { + fn ctx(&self) -> &egui::Context { + &self.0.ctx + } + + fn app(&mut self) -> &mut RustGisApp { + self.0.state_mut() + } + + fn run_steps(&mut self, steps: usize) { + self.0.run_steps(steps); + } + + fn event(&mut self, event: egui::Event) { + self.0.event(event); + } + + fn set_size(&mut self, size: Vec2) { + self.0.set_size(size); + } +} + +#[test] +fn every_control_can_be_reached_on_a_phone() { + let harness = egui_kittest::Harness::builder().with_size(SIZES[0]).with_step_dt(0.25).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + keep_frame(&ctx); + }, + app("bare"), + ); + let suite = Suite { sizes: SIZES.to_vec(), known: KNOWN, min_controls: MIN_CONTROLS, app }; + run(&mut Phone(harness), &suite, surfaces()); +} diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 5f0dab846b..468fbc359e 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -32,6 +32,8 @@ mod assistant; mod copies; mod edit; mod form; +#[cfg(all(test, target_os = "linux"))] +mod layout_reach; mod photos; mod track; @@ -468,7 +470,10 @@ fn bar(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, shown: Sheet) { /// up. Says whether it was tapped. fn layers_button(ui: &mut Ui, t: &Tokens, map: Rect, on: bool) -> bool { let rect = Rect::from_min_size(egui::pos2(map.max.x - TARGET - 8.0, map.min.y + 8.0), Vec2::splat(TARGET)); - let response = ui.interact(rect, egui::Id::unique("touch_layers_button"), Sense::click()).on_hover_text(tl!("Layers")); + let response = ui.interact(rect, egui::Id::unique("touch_layers_button"), Sense::click()); + // Painted, so named for screen readers (and tests). + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, tl!("Layers"))); + let response = response.on_hover_text(tl!("Layers")); let fill = if on { t.checked } else if response.is_pointer_button_down_on() { @@ -486,6 +491,7 @@ fn layers_button(ui: &mut Ui, t: &Tokens, map: Rect, on: bool) -> bool { /// was tapped. fn bar_button(ui: &mut Ui, t: &Tokens, icon: &str, label: &str, on: bool) -> bool { let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), BAR), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, label)); let response = response.on_hover_text(label); if on || response.is_pointer_button_down_on() { ui.painter().rect_filled(rect.shrink(4.0), CornerRadius::same(8), if on { t.checked } else { t.pressed }); @@ -570,6 +576,7 @@ fn swiped(ui: &Ui, row: &egui::Response) -> Option { /// tapped. fn icon_button(ui: &mut Ui, t: &Tokens, icon: &str, hint: &str) -> bool { let (rect, response) = ui.allocate_exact_size(Vec2::splat(TARGET), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, hint)); let response = response.on_hover_text(hint); if response.is_pointer_button_down_on() { ui.painter().rect_filled(rect.shrink(4.0), CornerRadius::same(8), t.pressed); @@ -657,7 +664,6 @@ fn views(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { /// acted on, and its last button zooms to it. fn layers(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { heading(ui, t, tl!("Layers")); - views(app, ui, t); // Read first: a row's button runs a command, which changes the lists it is drawn from. let map = app.session.map(); let active = app.session.active_layer; @@ -666,11 +672,15 @@ fn layers(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { map.layers.iter().map(|l| (Row::Layer(l.id), l.name.clone(), l.visible, active == Some(l.id))).collect(); rows.extend(map.tiles.iter().enumerate().map(|(i, tile)| (Row::Tile(i), tile.name.clone(), tile.visible, picked == Some(i)))); if rows.is_empty() { + views(app, ui, t); ui.label(RichText::new(tl!("This map has no layers yet. Add Data puts one on it.")).color(t.text_dim)); ui.add_space(8.0); return; } + // The views scroll with the rows: on a phone on its side the sheet is short, and together they + // leave the list a finger's height at least. egui::ScrollArea::vertical().auto_shrink([false, true]).show(ui, |ui| { + views(app, ui, t); for (row, name, visible, chosen) in rows { ui.horizontal(|ui| { ui.set_min_height(TARGET); @@ -690,6 +700,7 @@ fn layers(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } // The name takes the room between the two buttons, cut short when it is long. let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), TARGET), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, chosen, &name)); if chosen { ui.painter().rect_filled(rect, CornerRadius::same(6), t.checked); } @@ -712,6 +723,8 @@ fn layers(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { /// An icon button that shows a state: drawn dim when `on` is false. Says whether it was tapped. fn toggle_button(ui: &mut Ui, t: &Tokens, icon: &str, hint: &str, on: bool) -> bool { let (rect, response) = ui.allocate_exact_size(Vec2::splat(TARGET), Sense::click()); + // Named for what a tap does, which says the state too. + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, hint)); let response = response.on_hover_text(hint); if response.is_pointer_button_down_on() { ui.painter().rect_filled(rect.shrink(4.0), CornerRadius::same(8), t.pressed); @@ -1994,6 +2007,7 @@ fn copies_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context /// A row of a sheet's list: an icon and a label, as wide as the sheet. Says whether it was tapped. fn row(ui: &mut Ui, t: &Tokens, icon: &str, label: &str) -> bool { let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), TARGET), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if response.is_pointer_button_down_on() { ui.painter().rect_filled(rect, CornerRadius::same(6), t.pressed); }