diff --git a/AGENTS.md b/AGENTS.md index 397b9b4164..edf5913a37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -192,6 +192,12 @@ 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. 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/crates/ui-egui/src/catalogsui.rs b/crates/ui-egui/src/catalogsui.rs index b7b0dd5fd2..9d252f6627 100644 --- a/crates/ui-egui/src/catalogsui.rs +++ b/crates/ui-egui/src/catalogsui.rs @@ -75,6 +75,8 @@ impl Default for State { } fn fetch(url: &str) -> Answer { + #[cfg(all(test, target_os = "linux"))] + crate::layout_reach::downloaded(); let slot: Answer = Slot::default(); let land = slot.clone(); cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 35704e1230..a09027eb56 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -386,6 +386,10 @@ pub fn tr(lang: Lang, s: &str) -> &str { return t; } if lang == Lang::EN { + #[cfg(all(test, target_os = "linux"))] + if pseudo::on() { + return pseudo::pad(s); + } return s; } plugin_tr(lang, s).unwrap_or(s) @@ -417,6 +421,10 @@ pub fn tr_raw(lang: Lang, s: &str) -> &str { return t; } if lang == Lang::EN { + #[cfg(all(test, target_os = "linux"))] + if pseudo::on() { + return pseudo::pad(s); + } return s; } plugin_tr_raw(lang, s).unwrap_or(s) @@ -745,5 +753,16 @@ macro_rules! tl_raw { #[cfg(test)] mod boundary_tests; +#[cfg(all(test, 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"))] + return pseudo::on(); + #[cfg(not(all(test, target_os = "linux")))] + false +} #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/i18n/pseudo.rs b/crates/ui-egui/src/i18n/pseudo.rs new file mode 100644 index 0000000000..cc749b58a0 --- /dev/null +++ b/crates/ui-egui/src/i18n/pseudo.rs @@ -0,0 +1,88 @@ +//! A stand-in for a long language: English with each line 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. + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; + +thread_local! { + static ON: Cell = const { Cell::new(false) }; + /// The padded text of each string drawn. Leaked, so a label can keep borrowing it. + static PADDED: RefCell> = RefCell::default(); +} + +/// Whether this thread draws English padded. +pub(crate) fn on() -> bool { + ON.get() +} + +/// Turns padding on or off for this thread. +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, +/// 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; + } + 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))), + }; + let padded: &'static str = Box::leak(s.split('\n').map(line).collect::>().join("\n").into_boxed_str()); + seen.insert(s.to_string(), padded); + padded + }) +} + +/// `padded` with each padded string in it put back as it was: a whole label, or one built around +/// padded words, such as `▶ Run`. +pub(crate) fn unpadded(padded: &str) -> String { + // An accessible name joins a label's lines with a space. + let mut text = padded.replace('\n', " "); + PADDED.with_borrow(|seen| { + let mut pairs: Vec<(String, String)> = + seen.iter().filter(|(s, p)| s.as_str() != **p).map(|(s, p)| (p.replace('\n', " "), s.replace('\n', " "))).collect(); + // The longest first, so a padded phrase isn't undone a word at a time. + pairs.sort_by_key(|(p, _)| std::cmp::Reverse(p.len())); + // A whole label first; else the padded words in it, where they aren't part of a longer word + // (so `Goo` isn't undone inside `Goodbye`). + if let Some((_, s)) = pairs.iter().find(|(p, _)| *p == text) { + text = s.clone(); + return; + } + for (p, s) in pairs { + text = replace_words(&text, &p, &s); + } + }); + text +} + +/// `text` with each `from` that isn't next to a letter or digit replaced by `to`. +fn replace_words(text: &str, from: &str, to: &str) -> String { + let word = |c: Option| c.is_some_and(char::is_alphanumeric); + let (mut out, mut last) = (String::new(), 0); + // The letters either side come from the whole text, so a match beside a kept one still sees them. + for (at, _) in text.match_indices(from) { + let (before, after) = (text[..at].chars().next_back(), text[at + from.len()..].chars().next()); + out.push_str(&text[last..at]); + out.push_str(if word(before) || word(after) { from } else { to }); + last = at + from.len(); + } + out + &text[last..] +} + +#[cfg(test)] +mod tests { + /// A padded word isn't undone inside a longer one. + #[test] + fn unpadding_keeps_to_whole_words() { + let (long, short) = (super::pad("Goodbye"), super::pad("Go")); + assert_eq!(super::unpadded(long), "Goodbye"); + assert_eq!(super::unpadded(&format!("{short} {long}")), "Go Goodbye"); + assert_eq!(super::replace_words("GooGoo", "Goo", "Go"), "GooGoo"); + } +} diff --git a/crates/ui-egui/src/layout_reach.rs b/crates/ui-egui/src/layout_reach.rs new file mode 100644 index 0000000000..ce0d3cbbb1 --- /dev/null +++ b/crates/ui-egui/src/layout_reach.rs @@ -0,0 +1,907 @@ +//! 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. +//! +//! 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. + +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}; + +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) }; +} + +/// Counts a download started. +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] = &[ + r#"dialog sourcecoop at 1280: cut off Button "List Products""#, + r#"dialog sourcecoop at 900: cut off Button "List Products""#, + r#"layer properties display at 1280: cut off SpinButton "Transparency""#, + r#"layer properties display at 900: cut off SpinButton "Transparency""#, + r#"pane Assistant at 1280: cut off Button "Show""#, + r#"pane Assistant at 1280: cut off Button "Which 5 countries have the largest GDP?" and 4 more"#, + r#"pane Assistant at 900: cut off Button "Show""#, + r#"pane Assistant at 900: cut off Button "Which 5 countries have the largest GDP?""#, + r#"pane Assistant at 900: cut off Button "Zoom to Tokyo" and 3 more"#, + r#"pane Design at 1280: cut off ComboBox "Destination key""#, + r#"pane Design at 1280: cut off ComboBox "Origin key""#, + r#"pane Design at 900: cut off ComboBox "Destination key""#, + r#"pane Design at 900: cut off ComboBox "Origin key""#, + r#"pane Geoprocessing at 1280: cut off Button "Aggregate Points to Grid""#, + r#"pane Geoprocessing at 1280: cut off Button "Buffer""#, + r#"pane Geoprocessing at 1280: cut off Button "Calculate Geometry Attributes""#, + r#"pane Geoprocessing at 1280: cut off Button "Check DEM""#, + r#"pane Geoprocessing at 1280: cut off Button "Check Geometry""#, + r#"pane Geoprocessing at 1280: cut off Button "Clip""#, + r#"pane Geoprocessing at 1280: cut off Button "Dissolve""#, + r#"pane Geoprocessing at 1280: cut off Button "Erase""#, + r#"pane Geoprocessing at 1280: cut off Button "Export Features""#, + r#"pane Geoprocessing at 1280: cut off Button "Feature Envelope To Polygon""#, + r#"pane Geoprocessing at 1280: cut off Button "Feature To Point""#, + r#"pane Geoprocessing at 1280: cut off Button "Feature Vertices To Points""#, + r#"pane Geoprocessing at 1280: cut off Button "Generate Tessellation""#, + r#"pane Geoprocessing at 1280: cut off Button "IDW Interpolation""#, + r#"pane Geoprocessing at 1280: cut off Button "Identity""#, + r#"pane Geoprocessing at 1280: cut off Button "Install Whitebox and GeoLibre tools""#, + r#"pane Geoprocessing at 1280: cut off Button "Intersect""#, + r#"pane Geoprocessing at 1280: cut off Button "Join Field""#, + r#"pane Geoprocessing at 1280: cut off Button "Kernel Density""#, + r#"pane Geoprocessing at 1280: cut off Button "Merge""#, + r#"pane Geoprocessing at 1280: cut off Button "Minimum Bounding Geometry""#, + r#"pane Geoprocessing at 1280: cut off Button "Near""#, + r#"pane Geoprocessing at 1280: cut off Button "OD Cost Matrix""#, + r#"pane Geoprocessing at 1280: cut off Button "Ordinary Kriging""#, + r#"pane Geoprocessing at 1280: cut off Button "Pivot Table""#, + r#"pane Geoprocessing at 1280: cut off Button "Points Along Lines""#, + r#"pane Geoprocessing at 1280: cut off Button "Polygon To Line""#, + r#"pane Geoprocessing at 1280: cut off Button "Raster to PMTiles""#, + r#"pane Geoprocessing at 1280: cut off Button "Repair Geometry""#, + r#"pane Geoprocessing at 1280: cut off Button "Select Layer By Attribute""#, + r#"pane Geoprocessing at 1280: cut off Button "Select Layer By Location""#, + r#"pane Geoprocessing at 1280: cut off Button "Service Area""#, + r#"pane Geoprocessing at 1280: cut off Button "Simplify""#, + r#"pane Geoprocessing at 1280: cut off Button "Spatial Join""#, + r#"pane Geoprocessing at 1280: cut off Button "Split Line At Vertices""#, + r#"pane Geoprocessing at 1280: cut off Button "Split""#, + r#"pane Geoprocessing at 1280: cut off Button "Summarize Within""#, + r#"pane Geoprocessing at 1280: cut off Button "Summary Statistics""#, + r#"pane Geoprocessing at 1280: cut off Button "Symmetrical Difference""#, + r#"pane Geoprocessing at 1280: cut off Button "Tabulate Area""#, + r#"pane Geoprocessing at 1280: cut off Button "Tabulate Intersection""#, + r#"pane Geoprocessing at 1280: cut off Button "Texture Shading""#, + r#"pane Geoprocessing at 1280: cut off Button "Tissot's Indicatrix""#, + r#"pane Geoprocessing at 1280: cut off Button "Union""#, + r#"pane Geoprocessing at 1280: cut off Button "Unsplit Line""#, + r#"pane Geoprocessing at 1280: cut off Button "Update""#, + r#"pane Geoprocessing at 1280: cut off Button "Vector to PMTiles""#, + r#"pane Geoprocessing at 1280: cut off Button "XY Table To Point""#, + r#"pane Geoprocessing at 1280: cut off Button "Zonal Statistics""#, + r#"pane Geoprocessing at 900: cut off Button "Aggregate Points to Grid""#, + r#"pane Geoprocessing at 900: cut off Button "Buffer""#, + r#"pane Geoprocessing at 900: cut off Button "Calculate Geometry Attributes""#, + r#"pane Geoprocessing at 900: cut off Button "Check DEM""#, + r#"pane Geoprocessing at 900: cut off Button "Check Geometry""#, + r#"pane Geoprocessing at 900: cut off Button "Clip""#, + r#"pane Geoprocessing at 900: cut off Button "Dissolve""#, + r#"pane Geoprocessing at 900: cut off Button "Erase""#, + r#"pane Geoprocessing at 900: cut off Button "Export Features""#, + r#"pane Geoprocessing at 900: cut off Button "Feature Envelope To Polygon""#, + r#"pane Geoprocessing at 900: cut off Button "Feature To Point""#, + r#"pane Geoprocessing at 900: cut off Button "Feature Vertices To Points""#, + r#"pane Geoprocessing at 900: cut off Button "Generate Tessellation""#, + r#"pane Geoprocessing at 900: cut off Button "IDW Interpolation""#, + r#"pane Geoprocessing at 900: cut off Button "Identity""#, + r#"pane Geoprocessing at 900: cut off Button "Install Whitebox and GeoLibre tools""#, + r#"pane Geoprocessing at 900: cut off Button "Intersect""#, + r#"pane Geoprocessing at 900: cut off Button "Join Field""#, + r#"pane Geoprocessing at 900: cut off Button "Kernel Density""#, + r#"pane Geoprocessing at 900: cut off Button "Merge""#, + r#"pane Geoprocessing at 900: cut off Button "Minimum Bounding Geometry""#, + r#"pane Geoprocessing at 900: cut off Button "Near""#, + r#"pane Geoprocessing at 900: cut off Button "OD Cost Matrix""#, + r#"pane Geoprocessing at 900: cut off Button "Ordinary Kriging""#, + r#"pane Geoprocessing at 900: cut off Button "Pivot Table""#, + r#"pane Geoprocessing at 900: cut off Button "Points Along Lines""#, + r#"pane Geoprocessing at 900: cut off Button "Polygon To Line""#, + r#"pane Geoprocessing at 900: cut off Button "Raster to PMTiles""#, + r#"pane Geoprocessing at 900: cut off Button "Repair Geometry""#, + r#"pane Geoprocessing at 900: cut off Button "Select Layer By Attribute""#, + r#"pane Geoprocessing at 900: cut off Button "Select Layer By Location""#, + r#"pane Geoprocessing at 900: cut off Button "Service Area""#, + r#"pane Geoprocessing at 900: cut off Button "Simplify""#, + r#"pane Geoprocessing at 900: cut off Button "Spatial Join""#, + r#"pane Geoprocessing at 900: cut off Button "Split Line At Vertices""#, + r#"pane Geoprocessing at 900: cut off Button "Split""#, + r#"pane Geoprocessing at 900: cut off Button "Summarize Within""#, + r#"pane Geoprocessing at 900: cut off Button "Summary Statistics""#, + r#"pane Geoprocessing at 900: cut off Button "Symmetrical Difference""#, + r#"pane Geoprocessing at 900: cut off Button "Tabulate Area""#, + r#"pane Geoprocessing at 900: cut off Button "Tabulate Intersection""#, + r#"pane Geoprocessing at 900: cut off Button "Texture Shading""#, + r#"pane Geoprocessing at 900: cut off Button "Tissot's Indicatrix""#, + r#"pane Geoprocessing at 900: cut off Button "Union""#, + r#"pane Geoprocessing at 900: cut off Button "Unsplit Line""#, + r#"pane Geoprocessing at 900: cut off Button "Update""#, + r#"pane Geoprocessing at 900: cut off Button "Vector to PMTiles""#, + r#"pane Geoprocessing at 900: cut off Button "XY Table To Point""#, + r#"pane Geoprocessing at 900: cut off Button "Zonal Statistics""#, + r#"pane Labeling at 1280: overlap Button "Move Down" and Button "Remove""#, + r#"pane Labeling at 900: overlap Button "Move Down" and Button "Remove""#, + r#"pane Notebook at 900: cut off Button "World""#, + r#"pane Script at 1280: cut off Button "Clear""#, + r#"pane Script at 900: cut off Button "Clear""#, + r#"pane Symbology at 1280: cut off SpinButton "Transparency""#, + r#"pane Symbology at 900: cut off SpinButton "Transparency""#, + r#"ribbon Settings at 1280: cut off CheckBox "Download Datum Grids""#, + r#"ribbon Settings at 900: cut off CheckBox "Download Datum Grids""#, + r#"start open at 1280: cut off Button "QGIS Project…""#, + r#"start open at 900: cut off Button "GeoLibre Project…""#, + r#"start open at 900: cut off Button "Open…""#, + r#"start open at 900: cut off Button "QGIS Project…""#, + r#"view designer at 1280: cut off Button "Copy Command""#, + r#"view designer at 900: cut off Button "Copy Command""#, + r#"view designer at 900: cut off Button "Export…""#, + r#"view designer at 900: cut off Button "Fit""#, + r#"view designer at 900: cut off Button "Import…""#, + r#"view designer, pane at 1280: cut off Button "Copy Command""#, + r#"view designer, pane at 1280: cut off Button "Export…""#, + r#"view designer, pane at 1280: cut off Button "Import…""#, + r#"view designer, pane at 1280: cut off SpinButton "Transparency""#, + r#"view designer, pane at 900: cut off Button "Arrange""#, + r#"view designer, pane at 900: cut off Button "Copy Command""#, + r#"view designer, pane at 900: cut off Button "Export…""#, + r#"view designer, pane at 900: cut off Button "Fit""#, + r#"view designer, pane at 900: cut off Button "Import…""#, + r#"view designer, pane at 900: cut off Button "Open""#, + r#"view designer, pane at 900: cut off Button "Save""#, + r#"view designer, pane at 900: cut off Button "▶ Run""#, + r#"view designer, pane at 900: cut off SpinButton "Transparency""#, + r#"view table at 900: cut off Button "×""#, + r#"view table at 900: cut off CheckBox "Selected only""#, + r#"view table at 900: cut off TextInput "Filter rows…""#, + r#"view table, pane at 1280: cut off Button "×""#, + r#"view table, pane at 1280: cut off CheckBox "Selected only""#, + r#"view table, pane at 1280: cut off SpinButton "Transparency""#, + r#"view table, pane at 1280: cut off TextInput "Filter rows…""#, + r#"view table, pane at 900: cut off Button "Add field""#, + r#"view table, pane at 900: cut off Button "Calculate Geometry""#, + r#"view table, pane at 900: cut off Button "Calculate field""#, + r#"view table, pane at 900: cut off Button "Clear selection""#, + r#"view table, pane at 900: cut off Button "Delete selected rows""#, + r#"view table, pane at 900: cut off Button "Select By Attributes""#, + r#"view table, pane at 900: cut off Button "Switch selection""#, + r#"view table, pane at 900: cut off Button "Zoom to selection""#, + r#"view table, pane at 900: cut off Button "×""#, + r#"view table, pane at 900: cut off CheckBox "Selected only""#, + r#"view table, pane at 900: cut off SpinButton "Transparency""#, + r#"view table, pane at 900: cut off TextInput "Filter rows…""#, + r#"workflows trend at 1280: cut off ComboBox "Test""#, + r#"workflows trend at 1280: cut off RadioButton "One layer: a Zarr variable or a raster's bands""#, + r#"workflows trend at 1280: cut off TextInput "Dates""#, + r#"workflows trend at 900: cut off ComboBox "Test""#, + r#"workflows trend at 900: cut off RadioButton "One layer: a Zarr variable or a raster's bands""#, + r#"workflows trend at 900: cut off TextInput "Dates""#, +]; + +/// A control drawn in the last frame. +#[derive(Clone)] +struct Control { + id: Id, + parent: Id, + layer: LayerId, + /// All of it. + rect: Rect, + /// The part its clip rectangle leaves. + seen: Rect, + role: Role, + label: String, +} + +impl Control { + /// How much of its width and height is cut off. + fn cut(&self) -> Vec2 { + (self.rect.size() - self.seen.size().max(Vec2::ZERO)).max(Vec2::ZERO) + } + + fn name(&self) -> String { + format!("{:?} \"{}\"", self.role, pseudo::unpadded(&self.label)) + } +} + +/// Whether a user works a widget of this role. +fn interactive(role: Role) -> bool { + use Role::*; + matches!( + role, + Button + | CheckBox + | RadioButton + | ComboBox + | Link + | TextInput + | MultilineTextInput + | Slider + | SpinButton + | ColorWell + | Switch + | MenuItem + | Tab + ) +} + +/// 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| { + 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(); + interactive(role).then_some(Control { + id: w.id, + parent: w.parent_id, + layer, + rect: w.rect, + seen: w.interact_rect, + role, + label, + }) + }) + .collect() + }) +} + +/// Whether `a` and `b` lie on each other where they shouldn't. +fn overlap(a: &Control, b: &Control) -> bool { + lie_on(a, b, a.seen.intersect(b.seen)) +} + +/// Whether `a` and `b`, in the same scrolled area, lie on each other wherever it is scrolled: their +/// whole rectangles, in view or not. +fn overlap_whole(a: &Control, b: &Control) -> bool { + lie_on(a, b, a.rect.intersect(b.rect)) +} + +/// Whether `a` and `b` lie on each other over `both` where they shouldn't. +fn lie_on(a: &Control, b: &Control, both: Rect) -> bool { + if a.layer != b.layer || a.parent == b.id || b.parent == a.id || both.width() <= SLACK || both.height() <= SLACK { + return false; + } + // A tab's own close button: small, on the tab, and named for it. + let closes = |tab: &Control, close: &Control| { + tab.rect.expand(0.5).contains_rect(close.rect) + && close.rect.width() <= 20.0 + && pseudo::unpadded(&close.label) == format!("Close {}", pseudo::unpadded(&tab.label)) + }; + // An arrow that scrolls a strip lies on the end of what it scrolls: narrow, as tall as the + // strip, with the control it covers inside its height. + let scrolls = |arrow: &Control, under: &Control| { + arrow.rect.width() <= 26.0 + && arrow.rect.expand2(vec2(0.0, SLACK)).y_range().contains(under.rect.min.y) + && arrow.rect.expand2(vec2(0.0, SLACK)).y_range().contains(under.rect.max.y) + && pseudo::unpadded(&arrow.label).starts_with("Scroll the ") + }; + !(closes(a, b) || closes(b, a) || scrolls(a, b) || scrolls(b, a)) +} + +/// 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)> { + 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); + let now = controls(h); + let it = now.iter().find(|c| c.id == id)?; + Some((it.clone(), now.iter().filter(|o| o.id != id && overlap(it, o)).cloned().collect())) +} + +/// The most controls cut off sideways, and places that cut them off at the top or bottom, a surface +/// 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; + +/// 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)| { + 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) + }) +} + +/// 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()); + 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 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(); + let mut note = |a: &Control, b: &Control| { + // Named in the order drawn, so one pair is one line however it was found. + let (a, b) = if (a.rect.min.y, a.rect.min.x) <= (b.rect.min.y, b.rect.min.x) { (a, b) } else { (b, a) }; + let ids = (a.id.value().min(b.id.value()), a.id.value().max(b.id.value())); + overlaps.entry(ids).or_insert_with(|| format!("{at}: overlap {} and {}", a.name(), b.name())); + }; + // The window's own controls, left where they are, aren't checked again, but nothing of this + // surface may lie on them. + let kept: Vec<&Control> = all.iter().filter(|c| !whole_window && unmoved(bare, c)).collect(); + for (i, a) in here.iter().enumerate() { + for b in here[i + 1..].iter().chain(&kept).filter(|b| overlap(a, b)) { + note(a, b); + } + } + // Controls cut off by the same edge are in the same clipped area: scrolling to the one furthest + // past it shows whether that area scrolls. + // (furthest past the edge, tallest, how many). + let mut clips: HashMap<(LayerId, [i32; 4]), (&Control, &Control, usize)> = HashMap::new(); + // The controls each edge cuts: in one scrolled area, so they are compared whole. + let mut members: HashMap<(LayerId, [i32; 4]), Vec<&Control>> = HashMap::new(); + for c in here.iter().filter(|c| c.cut().x <= SLACK && c.cut().y > SLACK) { + let past = |e: f32, v: f32, sign: f32| if (v - e) * sign > SLACK { e.round() as i32 } else { i32::MIN }; + let edges = [ + past(c.seen.min.x, c.rect.min.x, -1.0), + past(c.seen.max.x, c.rect.max.x, 1.0), + past(c.seen.min.y, c.rect.min.y, -1.0), + past(c.seen.max.y, c.rect.max.y, 1.0), + ]; + // How far past the edge: these are cut on one axis, so their cut is that distance. + let beyond = |c: &Control| c.cut().length(); + members.entry((c.layer, edges)).or_default().push(c); + let entry = clips.entry((c.layer, edges)).or_insert((c, c, 0)); + entry.2 += 1; + if beyond(c) > beyond(entry.0) { + entry.0 = c; + } + // The tallest too: one too tall for the area never fits, wherever it is scrolled. + if c.rect.height() > entry.1.rect.height() { + entry.1 = c; + } + } + assert!(clips.len() <= MOST_CLIPS, "{at}: {} places clip controls; check them in parts", clips.len()); + for group in members.values() { + for (i, a) in group.iter().enumerate() { + for b in group[i + 1..].iter().filter(|b| overlap_whole(a, b)) { + note(a, b); + } + } + } + // 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) { + None => found.push(format!("{at}: gone when scrolled to {}{more}", c.name())), + Some((now, on)) => { + if now.cut().max_elem() > SLACK { + found.push(format!("{at}: cut off {}{more}", c.name())); + } + // Against the window's unmoved controls too: what is scrolled to is the surface's. + for o in &on { + note(&now, o); + } + } + }; + // Cut off sideways: each is scrolled to, since a row that doesn't scroll can share its edge with + // one that does. Cut off at the bottom or top, they are mostly the rows of a list that scrolls. + let mut sideways: Vec<&&Control> = here.iter().filter(|c| c.cut().x > SLACK).collect(); + // In the order drawn, as the clipped areas below. + sideways.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)); + assert!(sideways.len() <= MOST_CLIPS, "{at}: {} controls are cut off sideways; check them in parts", sideways.len()); + for c in sideways { + probe(h, c, "", &mut found); + } + // In the order drawn: each scroll leaves its area where it stopped, so the order must not + // change from run to run. + let mut clips: Vec<_> = clips.into_values().collect(); + clips.sort_by(|a, b| { + (a.0.rect.min.y, a.0.rect.min.x).partial_cmp(&(b.0.rect.min.y, b.0.rect.min.x)).unwrap_or(std::cmp::Ordering::Equal) + }); + for (furthest, tallest, n) in clips { + // How many it cuts: an area that cuts off one more is a new problem. + let more = if n > 1 { format!(" and {} more", n - 1) } else { String::new() }; + probe(h, furthest, &more, &mut found); + if tallest.id != furthest.id { + probe(h, tallest, "", &mut found); + } + } + let mut overlaps: Vec = overlaps.into_values().collect(); + overlaps.sort(); + found.extend(overlaps); + // Two controls of one name can't share a line. + let mut seen: HashMap = HashMap::new(); + found + .into_iter() + .map(|f| { + let n = seen.entry(f.clone()).or_default(); + *n += 1; + if *n == 1 { f } else { format!("{f} ({n})") } + }) + .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, + }) +} + +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), + )); + } + 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), + )); + } + 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)); + } + 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(); + 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), + )); + } + all +} + +/// 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> { + 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| { + 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(page) = START_PAGES.into_iter().find(|p| *surface == format!("start {p}")) { + h.state_mut().ui.backstage_page = page; + } + h.run_steps(4); + if DOWNLOADS.get() > downloads { + return Err(format!("{surface}: it downloads as it opens")); + } + if !shown(h.state()) { Err(format!("{surface}: not shown")) } else { Ok(()) } +} + +/// Shows every [`PARTS`]th surface at each size and compares the problems found with [`KNOWN`]. +fn check(part: usize) { + pseudo::set(true); + let mut h = harness(); + // 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); + assert!(opened.is_ok(), "{opened:?}"); + let bare: Vec = SIZES + .iter() + .map(|size| { + h.set_size(*size); + h.run_steps(3); + controls(&h).iter().map(|c| (c.id, (c.rect, c.seen))).collect() + }) + .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); + assert!(opened.is_ok(), "{opened:?}"); + let (name, _, shown) = &surface; + for (size, bare) in SIZES.into_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)); + assert!(own, "{name} at {}: shows no control of its own", size.x); + read += all.len(); + found.extend(problems(&mut h, name, bare)); + } + tested.insert(name.clone()); + } + pseudo::set(false); + assert!(!tested.is_empty(), "part {part} has no surfaces"); + // 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 known: BTreeSet = + 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:#?}" + ); + let gone: Vec<&String> = known.difference(&found).collect(); + assert!(gone.is_empty(), "no longer there: take these out of KNOWN:\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()); + 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())); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0f9c4d1a59..f9f581bc56 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -77,6 +77,8 @@ mod mapview; mod markerimages; mod markerpick; pub use markerpick::{MarkerImage, marker_file_too_large}; +#[cfg(all(test, target_os = "linux"))] +mod layout_reach; mod matchcount; mod measure_units; mod modeldesigner; @@ -872,6 +874,8 @@ pub(crate) fn fetch_within( timeout: Option, ceiling: Reach, ) -> Slot, Reach), String>> { + #[cfg(all(test, target_os = "linux"))] + crate::layout_reach::downloaded(); let slot: Slot, Reach), String>> = Slot::default(); let land = slot.clone(); let done: cache::FetchedDone = Box::new(move |r| { diff --git a/crates/ui-egui/src/modeldesigner.rs b/crates/ui-egui/src/modeldesigner.rs index 038c589aac..41a1341b9f 100644 --- a/crates/ui-egui/src/modeldesigner.rs +++ b/crates/ui-egui/src/modeldesigner.rs @@ -823,7 +823,7 @@ fn palette_ui(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, canvas: Rect) { for tool in rustgis_engine::analysis::external_tools_of(rustgis_engine::plugins::tools::SOURCE).iter().filter(|x| matches(x)) { push(format!("{} › {}", tl!("Plugins"), tool.toolbox.rsplit(" › ").next().unwrap_or(tool.toolbox)), true, tool); } - let external = rustgis_engine::cmd::gp::geolibre_tools(); + let external = crate::panes::geolibre_tools(); for (k, tool) in external.iter().filter(|x| matches(x)).enumerate() { // A thousand tools: by category, closed until opened, and only the first matches. if !q.is_empty() && k >= 80 { diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 59ee7eeab0..7f002d7904 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3541,7 +3541,7 @@ pub(crate) fn poll_geolibre_install(app: &mut RustGisApp, ctx: &egui::Context) { save("geolibre_runner", &path); } app.gp.install_error = None; - let count = rustgis_engine::cmd::gp::geolibre_status()["tools"].as_u64().unwrap_or(0); + let count = geolibre_status()["tools"].as_u64().unwrap_or(0); let key = if count == 1 { "GeoLibre tool installed: {count} tool" } else { "GeoLibre tools installed: {count} tools" }; app.session.notify(crate::i18n::fmt(key, &[("count", &count.to_string())]), false); } @@ -3579,7 +3579,7 @@ fn geolibre_install_progress(ui: &mut Ui, install: &std::sync::Mutex) { fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { // Read directly, not through Session::run: a command each frame would bump the session's // revision and make the views redraw. The status itself is cached in the runner module. - let status = rustgis_engine::cmd::gp::geolibre_status(); + let status = geolibre_status(); if status["supported"] != true { // A phone's build leaves the suite out (its runner is a program, which a phone's apps // can't start): said where the card would be, so the tools aren't simply missing (#1902). @@ -3696,6 +3696,11 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { /// and, while another runner is in use, under the tools' heading. Once: on the card /// (`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"))] + if crate::i18n::pseudo::on() { + return; + } let Some(note) = rustgis_engine::cmd::gp::geolibre_passed_over() else { return }; if shown_below && app.gp.install_error.as_deref() == Some(note.as_str()) { return; @@ -3708,7 +3713,7 @@ fn geolibre_passed_over(app: &RustGisApp, ui: &mut Ui, t: &Tokens, shown_below: /// put in place (not one of the user's own, found with Locate… or on the `PATH`); in the /// browser, the loaded tools, which then stop loading at startup. fn geolibre_uninstall(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { - let status = rustgis_engine::cmd::gp::geolibre_status(); + let status = geolibre_status(); let web = status["web"] == true; if !web && status["installed"] != true { return; @@ -4043,7 +4048,7 @@ fn geoprocessing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { // The GeoLibre suite: a thousand tools, so its toolboxes stay closed until opened (or, // without the runner, a card says where to get it). Above the built-in tools when // browsing, so it isn't lost below them; after them when searching. - let external = rustgis_engine::cmd::gp::geolibre_tools(); + let external = geolibre_tools(); let geolibre_section = |app: &mut RustGisApp, ui: &mut Ui| { if external.is_empty() { if q.is_empty() { @@ -4067,7 +4072,9 @@ fn geoprocessing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { #[cfg(not(target_arch = "wasm32"))] if let Some(e) = &app.gp.language_error { ui.label(egui::RichText::new(e).size(11.0).color(t.red)); - } else if let Some(e) = rustgis_engine::cmd::gp::geolibre_language_error(crate::i18n::current().code()) { + } else if let Some(e) = + rustgis_engine::cmd::gp::geolibre_language_error(crate::i18n::current().code()).filter(|_| !crate::i18n::pseudo_on()) + { let e = crate::i18n::fmt("The kept tool translations can't be read: {error}", &[("error", &e)]); ui.label(egui::RichText::new(e).size(11.0).color(t.red)); } @@ -5370,6 +5377,26 @@ 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"))] + if crate::i18n::pseudo::on() { + return json!({"supported": true, "web": false, "available": false, "installed": false, "tools": 0}); + } + rustgis_engine::cmd::gp::geolibre_status() +} + +/// 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"))] + if crate::i18n::pseudo::on() { + return &[]; + } + rustgis_engine::cmd::gp::geolibre_tools() +} + /// The classification methods in alphabetical order of their names in the interface language. fn methods_by_name() -> Vec { let mut m = ClassMethod::ALL.to_vec(); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 79e924f5ae..3e876f4b9f 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1035,6 +1035,17 @@ pub fn install_fonts( extra: &[(String, Arc, Option)], current: Option, ) { + // Layout tests measure with egui's own faces: an installed face differs from machine to machine. + #[cfg(all(test, 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(); + regular.push("Hack".into()); + fonts.families.insert(FontFamily::Proportional, regular.clone()); + fonts.families.insert(FontFamily::Name("semibold".into()), regular); + ctx.set_fonts(fonts); + return; + } let f = rustgis_engine::render::fonts::ui_fonts(); let mut fonts = FontDefinitions::default(); fonts.font_data.insert("ui".into(), Arc::new(FontData::from_owned(f.regular.clone())));