From 963d410bc14f059b2ab1dadad290d012c9314dc7 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 23:42:00 -0500 Subject: [PATCH 1/7] fix(ui): release sweep follow-ups (ui) The interface's deferred review points from the release quality sweep: the SQL Server geodatabase form's certificate, instance and typed-value handling and ui.connection's ignored keys; Command Search forgetting its row when closed; one selection for a double-click with a typed radius; STAC asset rows made once as a document lands, with singular counts and subnormals counted as rounded; plugin reasons kept in logical order; a layout dash drawn solid is said; extension.list gives place; whole-float geoBoundaries unit counts; and smaller cleanups, test pins and user guide corrections. --- crates/engine/src/cmd/block_model.rs | 2 +- .../engine/src/cmd/layout/publication/mod.rs | 2 +- .../src/cmd/layout/publication/sheet.rs | 4 + crates/engine/src/extensions.rs | 14 ++ crates/engine/src/received.rs | 8 + crates/render/src/layout.rs | 7 +- crates/render/src/layout/tests.rs | 21 ++ crates/tiles/src/boundaries.rs | 16 +- crates/ui-egui/src/assistant.rs | 2 +- crates/ui-egui/src/chrome.rs | 36 ++- crates/ui-egui/src/connectionui.rs | 116 +++++++++- crates/ui-egui/src/dialogs.rs | 45 ++-- crates/ui-egui/src/exportjob.rs | 7 +- crates/ui-egui/src/extensionsui.rs | 3 +- crates/ui-egui/src/fieldvalues.rs | 16 +- crates/ui-egui/src/lib.rs | 35 ++- crates/ui-egui/src/mapview.rs | 30 ++- crates/ui-egui/src/panes.rs | 45 +++- crates/ui-egui/src/pluginsui.rs | 19 +- crates/ui-egui/src/portalsui.rs | 56 ++++- crates/ui-egui/src/publicationwizard/map.rs | 8 +- crates/ui-egui/src/readjob.rs | 2 - crates/ui-egui/src/ribbon.rs | 9 +- crates/ui-egui/src/scriptcomplete.rs | 12 +- crates/ui-egui/src/stacui.rs | 215 +++++++++++++----- crates/ui-egui/src/vertexedit.rs | 13 +- docs/user-guide/analysis.md | 4 +- docs/user-guide/index.md | 4 +- docs/user-guide/layouts.md | 2 +- docs/user-guide/maps.md | 26 +-- 30 files changed, 608 insertions(+), 171 deletions(-) diff --git a/crates/engine/src/cmd/block_model.rs b/crates/engine/src/cmd/block_model.rs index f39b570e92..c8d943d53e 100644 --- a/crates/engine/src/cmd/block_model.rs +++ b/crates/engine/src/cmd/block_model.rs @@ -167,7 +167,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result CmdResu let (center, scale) = fit_frame(s.map(), &extent, rectangle.as_ref(), whole_globe, (inner_w, inner_h)) .ok_or("the extent can't be drawn on the map's projection")?; // A name given past the limit is refused, as layout.new refuses it, not cut (#2639). - let given = crate::cmd::within("name", "a layout's name", ps(p, "name").unwrap_or("Publication").trim(), crate::cmd::MAX_NAME)?; + let given = crate::cmd::within("name", "a layout's name", ps(p, "name").unwrap_or(PUBLICATION_NAME).trim(), crate::cmd::MAX_NAME)?; let (name, name_cut) = unique_name(s, "New Publication Layout", "the name given", &given); let mut l = Layout::new(name.clone(), w, h); (l.decimal_comma, l.paper) = (comma, page_colour); diff --git a/crates/engine/src/cmd/layout/publication/sheet.rs b/crates/engine/src/cmd/layout/publication/sheet.rs index d881d2c479..0a75733da1 100644 --- a/crates/engine/src/cmd/layout/publication/sheet.rs +++ b/crates/engine/src/cmd/layout/publication/sheet.rs @@ -63,6 +63,10 @@ pub const PUBLICATION_DEFAULT_CREDIT: &str = "Made with RustGIS · {date}"; /// give them. pub const PUBLICATION_HEADINGS: [&str; 2] = ["Sources", "Cartographic reference"]; +/// The publication's layout name when `"name"` doesn't give one (numbered when a layout already +/// has it): data, not translated. +pub const PUBLICATION_NAME: &str = "Publication"; + /// The cartographic reference's lines when `"reference"` isn't given, with a graticule or without /// one (`{projection}`, `{datum}` and `{grid}` are filled with the sheet's). pub fn publication_default_reference(graticule: bool) -> [&'static str; 2] { diff --git a/crates/engine/src/extensions.rs b/crates/engine/src/extensions.rs index e3abc0d844..d578d400e2 100644 --- a/crates/engine/src/extensions.rs +++ b/crates/engine/src/extensions.rs @@ -211,6 +211,8 @@ impl State { "name": e.name, "description": e.description, "tab": e.tab, + // Where its buttons are when it has no tab of its own. + "place": e.place, "enabled": self.is_on(e.id), "default": e.default_on, "chosen": self.chosen.get(e.id), @@ -246,6 +248,18 @@ mod tests { } } + #[test] + fn the_list_says_where_an_extension_without_a_tab_is() { + let list = State::default().list(); + let entry = |id: &str| list.as_array().and_then(|l| l.iter().find(|e| e["id"] == id)).cloned().unwrap_or_default(); + let assistant = entry("assistant"); + assert_eq!(assistant["place"], "Analyze › AI"); + assert!(assistant["tab"].is_null()); + let imagery = entry("imagery"); + assert!(imagery["place"].is_null()); + assert!(!imagery["tab"].is_null()); + } + #[test] fn a_session_of_its_own_has_every_extension_on_and_the_apps_start_at_the_defaults() { const { assert!(!IMAGERY.default_on) }; diff --git a/crates/engine/src/received.rs b/crates/engine/src/received.rs index 894c91caea..d45718bbeb 100644 --- a/crates/engine/src/received.rs +++ b/crates/engine/src/received.rs @@ -38,6 +38,14 @@ impl Session { pub fn receiving(&mut self, reach: Option) -> Option { std::mem::replace(&mut self.received, reach) } + + /// The reach the files opened next are read as from, as `receiving` last set it. + /// + /// Returns: + /// The reach set, or `None` when files are read as this computer's own. + pub fn received_reach(&self) -> Option { + self.received + } } /// What a file names on this computer or the local network, gathered as it is read diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 3f99508b41..38dde9a1f4 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -783,9 +783,14 @@ fn draw_page( /// `stroke` dashed along `path` by an element's pattern (points, at `ppp` pixels a point), as a /// line layer's stroke is ([`crate::dash_steps`]): solid when it has none, or when the pattern is -/// under a pixel a round or would cut the path into too many dashes. +/// under a pixel a round or would cut the path into too many dashes, which is counted as a line +/// layer's is ([`crate::approximations::dashes_drawn_solid`]) and said with the page. fn dashed(stroke: Stroke, dash: Option<&rustgis_map::symbology::Dash>, ppp: f64, path: &tiny_skia::Path) -> Stroke { + let asked = dash.is_some(); let dash = dash.and_then(|d| crate::dash_steps(d, ppp as f32, path)).and_then(|steps| tiny_skia::StrokeDash::new(steps, 0.0)); + if asked && dash.is_none() { + crate::approximations::dashes_drawn_solid(); + } Stroke { dash, ..stroke } } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 1a50e73b57..8b54469072 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -3601,6 +3601,27 @@ fn dashed_lines_and_outlines_have_gaps() { assert!(round(&png(oval(dash))) >= 20, "{}", round(&png(oval(dash)))); } +/// A layout element's dash pattern under a pixel a round is drawn solid and said once with the +/// page; a pattern that can be drawn says nothing. +#[test] +fn a_layout_dash_drawn_solid_is_said() { + let rect = |steps: &[f32]| ElementKind::Rectangle { + fill: Rgba::new(0, 0, 0, 0), + outline: Rgba::rgb(0, 0, 0), + width: 2.0, + radius: 0.0, + dash: rustgis_map::symbology::Dash::new(steps), + }; + let dashes = + |said: &crate::ShadowsSaid| said.notices.iter().filter(|n| n.contains("dashed line(s) drawn solid")).cloned().collect::>(); + let (_, said) = crate::shadows_said(|| render(&shape_page(rect(&[0.1, 0.1])), &mut [], 96.0, &PageInfo::default()).unwrap()); + let solid = dashes(&said); + assert_eq!(solid.len(), 1, "{said:?}"); + assert!(solid[0].contains(": 1 dashed line(s)"), "{solid:?}"); + let (_, said) = crate::shadows_said(|| render(&shape_page(rect(&[6.0, 6.0])), &mut [], 96.0, &PageInfo::default()).unwrap()); + assert!(dashes(&said).is_empty(), "{said:?}"); +} + /// A dashed box round a turned text, on one page (#1763): the picture has the box's gaps and /// the text running down the page inside it; the recorded page (the PDF's) keeps the dashes as /// pieces and the text as glyphs; the SVG writes the dash array and the turn. diff --git a/crates/tiles/src/boundaries.rs b/crates/tiles/src/boundaries.rs index 2b9af2ddcf..53c8355498 100644 --- a/crates/tiles/src/boundaries.rs +++ b/crates/tiles/src/boundaries.rs @@ -51,6 +51,8 @@ fn catalogue_url(level: &str) -> String { /// Available countries at one level, with a unit count when the service supplies one. /// Reject the entire catalogue on any malformed country entry: skipping it would incorrectly /// mark that country's level unavailable. The caller offers unknown levels and explains why. +/// A count that isn't a non-negative whole number (as a number, `26.0` included, or as text) is +/// treated as absent: the level is still offered, without a count. pub fn parse_availability(bytes: &[u8]) -> Result>, String> { let v: Value = serde_json::from_slice(bytes).map_err(|_| "the geoBoundaries list isn't JSON".to_string())?; v.as_array() @@ -59,7 +61,11 @@ pub fn parse_availability(bytes: &[u8]) -> Result = hits.iter().take(40).map(|h| (h, search_disabled(app, &h.0))).collect(); let runnable = shown.iter().filter(|(_, why)| why.is_none()).count(); + // A new query or a palette opened again starts from the first row, scrolled to. + let reset = !matches!(&cursor, Some(c) if c.query == q && c.pass + 1 >= pass); let row = match &cursor { - Some(c) if c.query == q && c.pass + 1 >= pass => c.row, + Some(c) if !reset => c.row, _ => 0, }; let row = step_row(row, runnable, down, up); @@ -2044,7 +2046,7 @@ pub fn command_search(app: &mut RustGisApp, ctx: &egui::Context) { if !resp.hovered() { ui.painter().set(under, egui::Shape::rect_filled(resp.rect, CornerRadius::same(5), t.selection)); } - if down || up { + if down || up || reset { resp.scroll_to_me(None); } } @@ -2109,6 +2111,8 @@ pub fn command_search(app: &mut RustGisApp, ctx: &egui::Context) { } else { ctx.memory_mut(|m| m.surrender_focus(edit_id)); app.ui.command_search_composing = false; + // Opened again, even on the next pass, it starts from the first row. + ctx.data_mut(|d| d.remove::(cursor_id)); } } @@ -2427,6 +2431,34 @@ mod tests { } } + /// Command Search closed with a row picked and opened again on the next pass starts from the + /// first row: Enter runs it, not the row picked before. + #[test] + fn command_search_opened_again_starts_from_the_first_row() { + use crate::RightPane; + let mut app = RustGisApp::with_sample(); + app.session.run("layer.select", &json!({"layer": "Cities"})).unwrap(); + app.ui.command_search = Some("ui.pane.la".into()); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(800.0, 600.0)) + .build_ui_state(|ui, app: &mut RustGisApp| command_search(app, ui.ctx()), app); + h.run(); + h.key_press(Key::ArrowDown); + h.run(); + h.key_press(Key::Escape); + h.step(); + assert!(h.state().ui.command_search.is_none(), "Escape closes the palette"); + // The picked row is forgotten as it closes: a palette opened again in the very next pass + // (a harness step runs two) would otherwise take it back. + let kept: Option = h.ctx.data(|d| d.get_temp(egui::Id::unique("command_search_cursor"))); + assert!(kept.is_none(), "the picked row is kept after closing: {:?}", kept.map(|c| c.row)); + h.state_mut().ui.command_search = Some("ui.pane.la".into()); + h.key_press(Key::Enter); + h.step(); + h.run(); + assert_eq!(h.state().ui.right, Some(RightPane::Labeling), "the first row runs"); + } + /// Ctrl (⌘) with a digit runs that row of Command Search; one past the list does nothing. #[test] fn command_search_number_keys_run_their_row() { diff --git a/crates/ui-egui/src/connectionui.rs b/crates/ui-egui/src/connectionui.rs index 872adfc7c2..e54aa5aa32 100644 --- a/crates/ui-egui/src/connectionui.rs +++ b/crates/ui-egui/src/connectionui.rs @@ -445,10 +445,18 @@ pub(crate) fn parse_mssql(address: &str) -> Option { /// The address the geodatabase form makes, or why it can't. fn form_address(st: &State) -> Result { - use rustgis_engine::data::source::sdefile::{SdeConnection, mssql_address}; + use rustgis_engine::data::{ + address::percent_decode, + source::sdefile::{SdeConnection, mssql_address}, + }; if st.server.trim().is_empty() { return Err(tl!("Type the server").into()); } + // `host\instance,port`: a backslash with nothing after it would connect on the default route. + let host_instance = st.server.split(',').next().unwrap_or(""); + if host_instance.rsplit_once('\\').is_some_and(|(_, instance)| instance.trim().is_empty()) { + return Err(tl!("The instance after the backslash is empty: name it, or take the backslash out").into()); + } let windows = st.sign_in == "windows"; // No user is Windows sign-in to the engine: a database user must be named. if !windows && st.user.trim().is_empty() { @@ -470,8 +478,23 @@ fn form_address(st: &State) -> Result { if keys().any(|k| k == "instance") { return Err(tl!("Put the instance in Server, not in Options").into()); } - if keys().any(|k| k == "trust-server-certificate" || k == "trustservercertificate") { - return Err(tl!("Tick Trust the server's certificate instead of typing it in Options").into()); + // A certificate key read as `parse_mssql` reads it: a value the engine takes belongs in the + // box; any other value is a typo the box can't stand for. + for kv in options.split('&') { + let (key, value) = kv.split_once('=').unwrap_or((kv, "")); + let key = key.trim().to_ascii_lowercase().replace('_', "-"); + if key != "trust-server-certificate" && key != "trustservercertificate" { + continue; + } + return Err(match percent_decode(value.trim()).to_ascii_lowercase().as_str() { + "true" | "yes" | "1" | "false" | "no" | "0" => { + tl!("Tick Trust the server's certificate instead of typing it in Options").into() + } + _ => tl!( + "The certificate option in Options has a value SQL Server doesn't take (true or false): fix it, or delete it from Options" + ) + .into(), + }); } for option in [options, if st.trust_cert { "trust-server-certificate=true" } else { "" }] { if !option.is_empty() { @@ -538,7 +561,11 @@ pub(crate) fn use_form(st: &mut State, server: Option<&str>, database: Option<&s Ok(_) => {} } st.sign_in = std::mem::take(&mut filled.sign_in); - st.user = std::mem::take(&mut filled.user); + // An address without a user (Windows sign-in) keeps the hidden User box's text; it is + // never sent for Windows sign-in. + if !filled.user.is_empty() { + st.user = std::mem::take(&mut filled.user); + } st.server = std::mem::take(&mut filled.server); st.database = std::mem::take(&mut filled.database); st.trust_cert = filled.trust_cert; @@ -688,6 +715,12 @@ pub(crate) fn fill_from_sde(app: &mut RustGisApp, path: &str) -> Result<(), Stri st.trust_cert = false; st.form_options.clear(); } + // A password typed for the same server and user is still the one to send. + let same = !windows + && !st.server.trim().is_empty() + && st.server.trim().eq_ignore_ascii_case(text("server").trim()) + && st.sign_in != "windows" + && st.user.trim() == text("user").trim(); st.server = text("server"); st.database = text("database"); st.sign_in = if windows { "windows" } else { "sql" }.into(); @@ -696,12 +729,17 @@ pub(crate) fn fill_from_sde(app: &mut RustGisApp, path: &str) -> Result<(), Stri if st.id.is_none() && !st.typed_name { st.name = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); } - st.password.clear(); - st.remember = false; + if !same { + st.password.clear(); + st.remember = false; + } + let kept = same && !st.password.is_empty(); st.test = None; app.dialogs.error = None; let next = if windows { tl!("This file signs in as the Windows user: Save, or Test to check the connection.") + } else if kept { + tl!("The password typed is kept: Save, or Test to check the connection.") } else if app.ui.connection.user.is_empty() { tl!("Type the user and the password, then Save.") } else { @@ -2320,6 +2358,27 @@ mod tests { } let fine = State { form_options: "encrypt=strict&connect-timeout=30".into(), ..gdb_form("sql") }; assert!(form_error(&fine).is_none()); + // A certificate value the engine takes belongs in the box; any other is a typo to fix, + // which ticking the box wouldn't clear. + let typo = State { form_options: "trust-server-certificate=maybe".into(), ..gdb_form("sql") }; + assert_eq!( + form_error(&typo).as_deref(), + Some( + "The certificate option in Options has a value SQL Server doesn't take (true or false): fix it, or delete it from Options" + ) + ); + let typed = State { form_options: "trust-server-certificate=true".into(), ..gdb_form("sql") }; + assert_eq!(form_error(&typed).as_deref(), Some("Tick Trust the server's certificate instead of typing it in Options")); + // An empty instance after the backslash would connect on the default route. + for server in ["gis-db\\", "gis-db\\,1433", "gis-db\\ "] { + let empty = State { server: server.into(), ..gdb_form("sql") }; + assert_eq!( + form_error(&empty).as_deref(), + Some("The instance after the backslash is empty: name it, or take the backslash out"), + "{server}" + ); + } + assert!(form_error(&State { server: "gis-db\\GIS,1433".into(), ..gdb_form("sql") }).is_none()); // Address mode is never checked against the form. st.form = false; assert!(form_error(&st).is_none()); @@ -2467,6 +2526,51 @@ mod tests { assert!(!app.dialogs.info.as_deref().unwrap_or("").contains("previous server")); } + #[test] + fn form_keys_outside_a_sql_server_form_are_refused() { + let mut app = RustGisApp::with_sample(); + for p in [ + json!({"kind": "sqlserver", "sdeFile": "x.sde"}), + json!({"kind": "postgres", "form": true}), + json!({"kind": "sqlserver", "server": "gis-db"}), + ] { + let e = app.run("ui.connection", p.clone()).unwrap_err(); + assert!(e.contains("SQL Server geodatabase form"), "{p}: {e}"); + } + app.run("ui.connection", json!({"kind": "sqlserver", "form": true, "server": "gis-db"})).unwrap(); + assert!(app.ui.connection.form); + assert_eq!(app.ui.connection.server, "gis-db"); + } + + #[test] + fn a_sde_file_for_the_same_server_and_user_keeps_a_typed_password() { + let mut app = RustGisApp::with_sample(); + app.run("ui.connection", json!({"kind": "sqlserver", "form": true, "sdeFile": sde_fixture("sqlserver-dbauth-nosave.sde")})) + .unwrap(); + app.ui.connection.password = "typed".into(); + fill_from_sde(&mut app, &sde_fixture("sqlserver-dbauth-nosave.sde")).unwrap(); + assert_eq!(app.ui.connection.password, "typed"); + let info = app.dialogs.info.clone().unwrap_or_default(); + assert!(!info.contains("the password, then Save"), "{info}"); + // One for another server clears it. + app.ui.connection.server = "elsewhere".into(); + fill_from_sde(&mut app, &sde_fixture("sqlserver-dbauth-nosave.sde")).unwrap(); + assert!(app.ui.connection.password.is_empty()); + assert!(app.dialogs.info.as_deref().is_some_and(|i| i.contains("the password, then Save")), "{:?}", app.dialogs.info); + } + + #[test] + fn windows_sign_in_keeps_the_typed_user_through_the_address() { + let mut st = State { user: "sde".into(), ..gdb_form("windows") }; + swap_form(&mut st).unwrap(); + assert!(!st.form); + swap_form(&mut st).unwrap(); + assert!(st.form); + assert_eq!((st.sign_in.as_str(), st.user.as_str()), ("windows", "sde")); + // Still never sent for Windows sign-in. + assert!(!form_address(&st).unwrap().contains("sde@")); + } + #[test] fn a_sde_file_that_is_refused_says_why_and_leaves_the_form_as_it_was() { let mut app = RustGisApp::with_sample(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6f46962c5c..90cdcc78aa 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -824,17 +824,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { }); close = buttons(app, ui, "Apply", |app| { // Empty keeps the current value; anything else must be a number. - let n = |s: &str, what: &str| -> Result, String> { - let s = s.trim(); - if s.is_empty() { - return Ok(None); - } - s.parse::() - .ok() - .filter(|v| v.is_finite()) - .map(Some) - .ok_or_else(|| crate::i18n::fmt("{what} must be a number", &[("what", tl_raw!(what))])) - }; + let n = parse_number_field; let (lon, lat, scale) = (n(&app.dialogs.a, "Longitude")?, n(&app.dialogs.b, "Latitude")?, n(&app.dialogs.c, "Scale")?); app.run("map.camera", json!({"lon": lon, "lat": lat, "scale": scale})).map(|_| ()) }); @@ -870,10 +860,8 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { ("height", "Height", &d.d), ("speed", "Frame time", &d.e), ] { - let v = v.trim(); - if !v.is_empty() { - let n = v.parse::().ok().filter(|n| n.is_finite()); - p[key] = json!(n.ok_or_else(|| crate::i18n::fmt("{what} must be a number", &[("what", tl_raw!(label))]))?); + if let Some(n) = parse_number_field(v, label)? { + p[key] = json!(n); } } picked = !app.run("ui.exportOrbit", p)?.is_null(); @@ -2894,15 +2882,22 @@ fn add_tiles(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { p[key] = json!(v.trim()); } } - if let Some(z) = parse_max_zoom(&app.dialogs.c)? { + if let Some(z) = parse_number_field(&app.dialogs.c, "Maximum zoom")? { p["maxZoom"] = json!(z); } app.run("map.addTiles", p).map(|_| ()) }) } -/// Parses an optional finite number for Add Tile Layer's Maximum zoom field. -fn parse_max_zoom(text: &str) -> Result, String> { +/// Parses a dialog's optional number field. +/// +/// Args: +/// text: What was typed; surrounding spaces are ignored. +/// what: The field's English name, translated in the message. +/// +/// Returns: +/// `None` for an empty field, the number for a finite one, or "{what} must be a number". +fn parse_number_field(text: &str, what: &str) -> Result, String> { let s = text.trim(); if s.is_empty() { return Ok(None); @@ -2911,7 +2906,7 @@ fn parse_max_zoom(text: &str) -> Result, String> { .ok() .filter(|z| z.is_finite()) .map(Some) - .ok_or_else(|| crate::i18n::fmt("{what} must be a number", &[("what", tl_raw!("Maximum zoom"))])) + .ok_or_else(|| crate::i18n::fmt("{what} must be a number", &[("what", tl_raw!(what))])) } /// A dialog's multi-line text box. [`buttons`] takes Enter to confirm the dialog, so only @@ -5865,12 +5860,12 @@ mod tests { assert!(parse_whole_number("1.5").is_err()); assert!(parse_whole_number("1,2").is_err()); - assert_eq!(parse_max_zoom(""), Ok(None)); - assert_eq!(parse_max_zoom(" "), Ok(None)); - assert_eq!(parse_max_zoom("18"), Ok(Some(18.0))); - assert!(parse_max_zoom("abc").is_err()); - assert!(parse_max_zoom("NaN").is_err()); - assert!(parse_max_zoom("inf").is_err()); + assert_eq!(parse_number_field("", "Maximum zoom"), Ok(None)); + assert_eq!(parse_number_field(" ", "Maximum zoom"), Ok(None)); + assert_eq!(parse_number_field("18", "Maximum zoom"), Ok(Some(18.0))); + assert!(parse_number_field("abc", "Maximum zoom").is_err()); + assert!(parse_number_field("NaN", "Maximum zoom").is_err()); + assert!(parse_number_field("inf", "Maximum zoom").is_err()); } /// `add_for_editing` rejects decimal row limits like `"1.5"`, and Add Tile Layer rejects diff --git a/crates/ui-egui/src/exportjob.rs b/crates/ui-egui/src/exportjob.rs index 506d778e0c..bd3e5153a1 100644 --- a/crates/ui-egui/src/exportjob.rs +++ b/crates/ui-egui/src/exportjob.rs @@ -48,10 +48,7 @@ pub fn idle(app: &RustGisApp) -> Result<(), String> { // A read or table edit on its own thread changes the data only when it lands: an export now // would write the data without it. if let Some(read) = crate::readjob::under_way(app) { - return Err(crate::i18n::fmt( - "{read} is still running: wait for it, or cancel it, then export, so the file holds what it changes.", - &[("read", tl_raw!(read))], - )); + return Err(crate::i18n::fmt("{read} is queued or running: wait for it, or cancel it, then export.", &[("read", tl_raw!(read))])); } Ok(()) } @@ -209,7 +206,7 @@ mod tests { app.run("edit.setValue", json!({"table": "ranks", "row": 0, "field": "score", "value": 5})).unwrap(); assert_eq!(crate::readjob::under_way(&app), Some("Edit Attribute"), "the edit runs on the reads worker"); let refused = app.run("share.exportTable", export.clone()).unwrap_err(); - assert!(refused.starts_with("Edit Attribute is still running"), "{refused}"); + assert!(refused.starts_with("Edit Attribute is queued or running"), "{refused}"); assert!(app.export_job.is_none() && !path.exists()); let end = std::time::Instant::now() + std::time::Duration::from_secs(30); while crate::readjob::land(&mut app) { diff --git a/crates/ui-egui/src/extensionsui.rs b/crates/ui-egui/src/extensionsui.rs index 5dc2aeecc9..fbc309a7b1 100644 --- a/crates/ui-egui/src/extensionsui.rs +++ b/crates/ui-egui/src/extensionsui.rs @@ -34,7 +34,8 @@ pub fn load(app: &mut RustGisApp) { /// Whether command `id` belongs to an extension that is off: no button, menu item or search /// row offers it. pub(crate) fn hidden(app: &RustGisApp, id: &str) -> bool { - app.session.extensions().blocks(id).is_some() + // As `blocks` answers, without making its message: this runs once per row. + extensions::owner(id).is_some_and(|e| !app.session.extensions().is_on(e.id)) } /// Closes the panes of extensions that are off: one open as it was turned off, or brought back diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index 40c1405089..f038d08136 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -98,10 +98,8 @@ impl Form { }; self.choose(&field.name); // Where the field came from: a value picked goes there (a clause with a gap in it is - // filled, not added to). - if self.cursor.as_ref().is_none_or(|(was, held)| *was != at || held != text) { - self.cursor = Some((at, text.to_string())); - } + // filled, not added to). `accept` checks the text is still as it was. + self.cursor = Some((at, text.to_string())); } /// The values of field `field` of `ds`, as written, and where they were read from. Read as @@ -112,9 +110,12 @@ impl Form { fn list(&mut self, ds: &Dataset, field: usize, frame: u64) -> (Rc<[String]>, ValuesRead) { let open = self.drawn.is_some_and(|was| was + 1 >= frame); self.drawn = Some(frame); + // The rows' and fields' keys, made once: to check what is held, and for a new read. + let keys = || (ds.features.allocation_key(), fields_key(ds)); + let mut made = None; if !open { - let (rows, fields) = (ds.features.allocation_key(), fields_key(ds)); - let held = |r: &Read| r.fields == fields && r.rows.ptr_eq(&rows) && r.from.view == ds.windowed; + let (rows, fields) = made.get_or_insert_with(keys); + let held = |r: &Read| r.fields == *fields && r.rows.ptr_eq(rows) && r.from.view == ds.windowed; if !self.read.as_ref().is_some_and(held) { self.read = None; } @@ -129,7 +130,8 @@ impl Form { let got = query::field_values(ds, field, query::VALUES_READ); let from = ValuesRead::of(&got, ds); let written = got.values.into_iter().map(|v| v.written).collect(); - Read { rows: ds.features.allocation_key(), fields: fields_key(ds), from, written } + let (rows, fields) = made.take().unwrap_or_else(keys); + Read { rows, fields, from, written } }); let name = ds.fields.get(field).map(|f| f.name.as_str()).unwrap_or_default(); self.said = read.written.is_empty().then(|| { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 034179d13d..2bfe9858b5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2852,7 +2852,11 @@ impl RustGisApp { }; } match name.strip_prefix(DELIMITED_PICK) { - // A cancelled picker opens nothing; its request's options end with it. + // A cancelled picker opens nothing; its request's options end with it. No shell sends + // a bare `DELIMITED_PICK` now (the web's `read_together` and the phone's `waits` answer + // only DXF and marker requests), but without this arm an empty name would fall through + // to `open_bytes_with("")`. It clears `pending_csv` whatever it holds, so a shell that + // sends it must not race a newer Add Delimited Text request. Some("") => { self.ui.pending_csv = None; Ok(Value::Null) @@ -3610,8 +3614,7 @@ impl RustGisApp { } let opening_file = self.ui.opening_file; // A downloaded project is read, once answered, as received from where it came from. - let reach = self.session.receiving(None); - self.session.receiving(reach); + let reach = self.session.received_reach(); saveprompt::ask(self, saveprompt::Discard::Replace(id.to_string(), params, opening_file, reach)); return Ok(Value::Null); } @@ -5083,6 +5086,20 @@ impl RustGisApp { // frame; it's added when it lands. A PMTiles archive is a tile layer, never downloaded. "ui.addUrl" => return self.add_url(p, None, None), "ui.connection" => { + // The form's keys are for a SQL Server geodatabase form only: given anywhere else + // they would be ignored without a word. + let form = p.get("form").and_then(Value::as_bool) == Some(true); + let kind = match p.get("id").and_then(Value::as_str) { + Some(id) => self.session.connections.find(id).map(|c| c.kind.clone()), + None => Some(p.get("kind").and_then(Value::as_str).unwrap_or("service").to_owned()), + }; + let form_keys = ["sdeFile", "server", "database"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + if (form_keys && !form) || (form && kind.as_deref().is_some_and(|k| k != "sqlserver")) { + return Err(tl!( + "form, server, database and sdeFile are for a SQL Server geodatabase form: give \"kind\": \"sqlserver\" and \"form\": true" + ) + .into()); + } if let Some(id) = p.get("id").and_then(Value::as_str) { connectionui::open_edit(self, id)?; } else { @@ -7723,8 +7740,11 @@ impl RustGisApp { if let Some(id) = name.strip_prefix(DXF_PICK).and_then(|p| p.split_once(':')).and_then(|(id, _)| id.parse::().ok()) { self.ui.pending_dxf.remove(&id); } - // So does the request a held answer was for: its options or command aren't left - // for a later, unrelated file to be opened with. + // So does an Add Delimited Text answer's request (its options aren't left for a + // later, unrelated file), and a plain file's (its command isn't). The other held + // kinds keep theirs: SCRIPT, SHAPEFILE, MARKER, ASSISTANT, TOOL_FILE and SHORTCUT + // answers end no request, `pending_shapefile` is read without being taken, and + // marker ids are checked when an answer lands. if name.starts_with(DELIMITED_PICK) { self.ui.pending_csv = None; } else if !name.starts_with('\u{1}') { @@ -10999,9 +11019,14 @@ mod peer_output_tests { h.step(); assert_eq!(h.state().ui.pending_open, None); h.state_mut().ui.pending_csv = Some(json!({"x": "lon", "y": "lat"})); + let mark = h.state().session.notice_mark(); inbox.lock().unwrap().push((format!("{DELIMITED_PICK}places.csv"), b"lon,lat\n1,2\n".to_vec())); h.step(); assert!(h.state().ui.pending_csv.is_none(), "a held Add Delimited Text answer ends its request"); + // Held, not opened: no dialog, and said. + assert!(h.state().dialogs.open.is_none(), "{:?}", h.state().dialogs.open); + let notices = h.state().session.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("Another file wasn't opened")), "got: {notices:?}"); assert_eq!(h.state().session.map().layers.len(), layers, "nothing is added to the project about to be replaced"); assert_eq!(h.state().session.map().name, "Unsaved Map"); } diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index eb90a7e364..1e8487765e 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -1529,6 +1529,9 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { && interacting && !hold && !app.map.motion_dropped + // The frame that just came back was declined by the GPU: a new GPU job now would only be + // declined again and thrown away. + && !declined_now && (motion.is_some() || gpu_vector) // The scene on screen follows the camera while its successor is drawn. && (!gpu_vector || (cam_only && app.map.gpu_frame.as_ref().is_some_and(|f| !f.has_images && f.follows(&cam)))) @@ -2757,7 +2760,7 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect } return; } - if tool == Tool::SelectRadius && resp.clicked() && !app.map.radius_text.trim().is_empty() { + if tool == Tool::SelectRadius && resp.clicked() && !resp.double_clicked() && !app.map.radius_text.trim().is_empty() { let result = (|| { let radius = crate::measure_units::parse_distance(&app.map.radius_text, app.ui.measurement_imperial)?; let Some(radius) = radius else { @@ -4852,8 +4855,9 @@ fn view_tab_w(ui: &Ui, name: &str) -> f32 { crate::widgets::text_w(ui, name, regular(12.0)) + 46.0 + TAB_CLOSE_W } -/// The next view tab's place in the row, `w` wide, below the strip's top margin. -fn next_view_tab(ui: &mut Ui, w: f32) -> Rect { +/// Takes the next view tab's room in the row, `w` wide, and returns its rectangle below the +/// strip's top margin. +fn alloc_view_tab(ui: &mut Ui, w: f32) -> Rect { let (r, _) = ui.allocate_exact_size(vec2(w, 30.0), Sense::hover()); Rect::from_min_max(pos2(r.min.x, r.min.y + 4.0), r.max) } @@ -4927,7 +4931,7 @@ fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> let mut close: Option = None; let mut map_tabs = Vec::with_capacity(names.len()); for (i, n) in names.iter().enumerate() { - let tr = next_view_tab(ui, view_tab_w(ui, n)); + let tr = alloc_view_tab(ui, view_tab_w(ui, n)); 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)); @@ -4978,7 +4982,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 = next_view_tab(ui, view_tab_w(ui, n)); + let tr = alloc_view_tab(ui, view_tab_w(ui, n)); 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); @@ -5027,7 +5031,7 @@ fn view_tab_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, follow: bool) -> } // ModelBuilder, after the layouts. if let Some(n) = model_tab_name(app) { - let tr = next_view_tab(ui, view_tab_w(ui, &n)); + let tr = alloc_view_tab(ui, view_tab_w(ui, &n)); 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(); @@ -6661,6 +6665,20 @@ mod tests { assert!(selection_rows(&h).is_empty()); } + /// A double-click with a typed radius selects once: the second click of the pair is the + /// double-click, which the tool takes without selecting again. + #[test] + fn typed_radius_double_click_selects_once() { + let mut h = selection_harness(); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + h.state_mut().map.radius_text = "1000".into(); + h.run(); + let depth = h.state().session.undo_depth(); + selection_click(&mut h, [0.5, 0.5]); + selection_click(&mut h, [0.5, 0.5]); + assert_eq!(h.state().session.undo_depth(), depth + 1, "one selection step for the pair"); + } + /// A circle near a local projection's boundary has valid extrema but an invalid arc. #[test] fn typed_radius_rejects_the_same_projection_boundary_as_drag() { diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 1799469712..e7b7afa1a3 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -2082,13 +2082,19 @@ fn linked_note(l: &Layer, other: Option<(String, String, Option)>) -> Opti Some(match other { Some((note, detail, tint)) if !note.is_empty() => { let inner = note.trim().trim_start_matches('(').trim_end_matches(')'); - (crate::i18n::fmt("(linked, {note})", &[("note", inner)]), format!("{linked}\n{detail}"), tint) + (crate::i18n::fmt("(linked, {note})", &[("note", inner)]), join_lines(&linked, &detail), tint) } - Some((_, detail, tint)) => (tl!("(linked)").to_string(), format!("{linked}\n{detail}"), tint), + Some((_, detail, tint)) => (tl!("(linked)").to_string(), join_lines(&linked, &detail), tint), None => (tl!("(linked)").to_string(), linked, None), }) } +/// `first` with `second` on the line below it, or `first` alone when `second` is empty (no +/// trailing line break in a hover text). +fn join_lines(first: &str, second: &str) -> String { + if second.is_empty() { first.to_owned() } else { format!("{first}\n{second}") } +} + /// A layer's row and, expanded, its legend; returns the rectangle of both. With `reorder` off /// (the list is filtered or children are sorted by name) the row can't be dragged. fn layer_row(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, scale: f64, reorder: bool, t: &Tokens) -> Rect { @@ -3957,7 +3963,8 @@ pub(crate) fn field_suggestions<'a>( value.clear(); value.push_str(field); response.mark_changed(); - } else if !value.split([',', ';']).any(|part| part.trim() == field) { + } else if !value.split([',', ';']).any(|part| part.trim().to_lowercase() == field.to_lowercase()) { + // Tools match field names regardless of case, so `Name` after `name` is the same field. let separator = if value.contains(';') { ';' } else { ',' }; if !value.trim_end().ends_with([',', ';']) { value.push(separator); @@ -8783,6 +8790,38 @@ pub(crate) mod tests { assert_eq!(h.state(), "new_column,population,typed_column"); } + /// The Flat-area hovers say "flatter than 4°" and "from 1 to 32" in words, as `tl!` looks + /// the text up by them: a change to `Flats::SLOPE` or `Flats::MAX_SIZE` changes those two + /// hover texts and `docs/user-guide/data.md` with it. + #[test] + fn the_flat_area_hovers_name_the_flats_constants() { + assert_eq!(Flats::SLOPE, 4.0); + assert_eq!(Flats::MAX_SIZE, 32); + } + + #[test] + fn a_linked_note_with_no_other_detail_has_no_trailing_line() { + assert_eq!(join_lines("Linked", ""), "Linked"); + assert_eq!(join_lines("Linked", "Read only"), "Linked\nRead only"); + } + + #[test] + fn field_suggestions_skip_a_name_already_typed_in_another_case() { + use egui_kittest::kittest::Queryable; + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 150.0)).build_ui_state( + |ui, value: &mut String| { + field_suggestions(ui, egui::Id::unique("fields"), value, "Fields", "", ["name", "population"].into_iter(), true); + }, + String::from("Population"), + ); + h.run_steps(3); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(3); + h.get_by_label("population").click(); + h.run_steps(3); + assert_eq!(h.state(), "Population"); + } + /// A run opened again from the History pane (#539) fills its tool's form as the form would /// have it: a standalone table, given by its id, by its name and picked by its id; numbers /// and choices as text; what wasn't given left alone. diff --git a/crates/ui-egui/src/pluginsui.rs b/crates/ui-egui/src/pluginsui.rs index c4051463a1..74b2a8b815 100644 --- a/crates/ui-egui/src/pluginsui.rs +++ b/crates/ui-egui/src/pluginsui.rs @@ -69,6 +69,7 @@ pub struct Confirm { /// Installed tab with why, until it loads or the user removes it. struct Unloaded { saved: Saved, + /// Why, in logical order: shaped once by the message it goes into, or when painted alone. reason: String, } @@ -401,14 +402,14 @@ fn start_restore(app: &mut RustGisApp, s: Saved, ctx: Option, ret use base64::Engine; let got = base64::engine::general_purpose::STANDARD .decode(data) - .map_err(|e| crate::i18n::fmt("its copy kept in the browser is damaged: {error}", &[("error", &e.to_string())])); + .map_err(|e| crate::i18n::fmt_raw("its copy kept in the browser is damaged: {error}", &[("error", &e.to_string())])); finish_restore(app, s, got, retry); } else if let Some(url) = s.url.clone() { let slot = fetch(app, &url, rp::package::MAX_PACKAGE, ctx); app.plugins.jobs.push(Job::Restore { saved: s, slot, retry }); } else { // Not made by an install: a record edited by hand. - let reason = tl!("the browser kept neither a copy of it nor where to download it").to_string(); + let reason = tl_raw!("the browser kept neither a copy of it nor where to download it").to_string(); finish_restore(app, s, Err(reason), retry); } } @@ -419,7 +420,7 @@ fn finish_restore(app: &mut RustGisApp, s: Saved, got: Result, String>, let r = got.and_then(|bytes| { let sha = rp::package::sha256_hex(&bytes); if !sha.eq_ignore_ascii_case(&s.sha256) { - return Err(tl!("it changed since it was installed: install it again from the Plugin Manager").to_string()); + return Err(tl_raw!("it changed since it was installed: install it again from the Plugin Manager").to_string()); } rustgis_engine::cmd::plugins::install_bytes(&bytes) }); @@ -889,7 +890,7 @@ fn installed_tab(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { }); }); chip(ui, t, tl!("Not loaded"), t.red); - ui.label(egui::RichText::new(reason).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::shaped(reason)).size(11.5).color(t.text_dim)); }); } match act { @@ -1594,6 +1595,16 @@ mod tests { assert!(h.query_by_label("Retry").is_none()); } + /// Why a plugin wasn't loaded is kept in logical order, so the message it goes into shapes + /// it once. + #[test] + fn an_unloaded_plugin_s_reason_is_kept_in_logical_order() { + let mut app = RustGisApp::with_sample(); + start_restore(&mut app, Saved { url: None, data: None, ..record("bare", "0") }, None, false); + let reason = app.plugins.unloaded.first().map(|u| u.reason.clone()); + assert_eq!(reason.as_deref(), Some(tl_raw!("the browser kept neither a copy of it nor where to download it"))); + } + /// Removing an unloaded plugin erases what it kept, and when that fails it stays listed (#1261). #[test] fn plugin_settings_are_erased_when_an_unloaded_plugin_is_removed() { diff --git a/crates/ui-egui/src/portalsui.rs b/crates/ui-egui/src/portalsui.rs index 2402dbd50a..fbaef4da48 100644 --- a/crates/ui-egui/src/portalsui.rs +++ b/crates/ui-egui/src/portalsui.rs @@ -135,9 +135,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { app.ui.portals.countries_error = match r.and_then(|b| boundaries::parse_countries(&b)) { Ok(c) if c.is_empty() => Some(tl!("geoBoundaries listed no countries: type a country's code").to_string()), Ok(c) => { - app.ui.portals.country_search = - c.iter().map(|(iso, name)| (iso.clone(), (name.clone(), format!("{name} {iso}").to_lowercase()))).collect(); - app.ui.portals.countries = c; + set_countries(&mut app.ui.portals, c); None } Err(e) => Some(crate::i18n::fmt("The country list couldn't be read ({e}): type a country's code", &[("e", &e)])), @@ -290,12 +288,7 @@ pub fn boundaries(app: &mut RustGisApp, ui: &mut egui::Ui) { .labelled_by(input_label.id); let needle = st.country_filter.trim().to_lowercase(); for (iso, name) in &st.countries { - let cached = st.country_search.get(iso).filter(|(original, _)| original == name); - let matches = cached.map_or_else( - || format!("{name} {iso}").to_lowercase().contains(&needle), - |(_, search)| search.contains(&needle), - ); - if !matches { + if !country_matches(st, iso, name, &needle) { continue; } if ui.selectable_value(&mut st.country, iso.clone(), format!("{name} ({iso})")).clicked() { @@ -376,6 +369,34 @@ pub fn boundaries(app: &mut RustGisApp, ui: &mut egui::Ui) { status(app, ui); } +/// Takes geoBoundaries' country list, with each country's search text made once. +/// +/// Args: +/// st: The dialog's state. +/// countries: Each country's code and name. +fn set_countries(st: &mut State, countries: Vec<(String, String)>) { + st.country_search = countries.iter().map(|(iso, name)| (iso.clone(), (name.clone(), format!("{name} {iso}").to_lowercase()))).collect(); + st.countries = countries; +} + +/// Whether the country `iso` named `name` matches the search `needle` (lower case): by the text +/// cached for it while its name is still the one received, else made now. +/// +/// Args: +/// st: The dialog's state. +/// iso: The country's code. +/// name: The country's name as listed. +/// needle: The search typed, in lower case. +/// +/// Returns: +/// True when the name or code holds the search. +fn country_matches(st: &State, iso: &str, name: &str, needle: &str) -> bool { + match st.country_search.get(iso).filter(|(original, _)| original == name) { + Some((_, search)) => search.contains(needle), + None => format!("{name} {iso}").to_lowercase().contains(needle), + } +} + #[cfg(test)] mod tests { use super::*; @@ -407,7 +428,7 @@ mod tests { assert!(h.get_by_label("ADM3 — third-level divisions").accesskit_node().is_disabled()); h.get_by_label("ADM1 — 26 units").click(); h.run(); - h.state_mut().ui.portals.countries = vec![("PER".into(), "Peru".into()), ("POL".into(), "Poland".into())]; + set_countries(&mut h.state_mut().ui.portals, vec![("PER".into(), "Peru".into()), ("POL".into(), "Poland".into())]); h.step(); h.get_by_label("Country").click(); h.run(); @@ -423,6 +444,21 @@ mod tests { assert!(h.get_by_label("Add").accesskit_node().is_disabled()); } + /// The country filter reads the search text cached with the list, and makes it anew for a + /// name changed since. + #[test] + fn the_country_filter_reads_the_cached_search_text() { + let mut st = State::default(); + set_countries(&mut st, vec![("PER".into(), "Peru".into()), ("POL".into(), "Poland".into())]); + assert!(country_matches(&st, "PER", "Peru", "per")); + assert!(!country_matches(&st, "POL", "Poland", "per")); + assert!(country_matches(&st, "POL", "Poland", "pol")); + // A name changed without the cache: the cached text is for the old name, so not read. + st.countries[1].1 = "Polska".into(); + assert!(country_matches(&st, "POL", "Polska", "polska")); + assert!(!country_matches(&st, "POL", "Polska", "poland")); + } + /// Availability lands even with no dialog open and a failed level never disables choices. #[test] fn availability_lands_independently_of_boundary_downloads() { diff --git a/crates/ui-egui/src/publicationwizard/map.rs b/crates/ui-egui/src/publicationwizard/map.rs index e0710155fe..b5cf9c31f9 100644 --- a/crates/ui-egui/src/publicationwizard/map.rs +++ b/crates/ui-egui/src/publicationwizard/map.rs @@ -1,6 +1,7 @@ //! The wizard's map step. use super::*; use crate::dialogs::MapOwner; +use rustgis_engine::cmd::layout::PUBLICATION_NAME; use rustgis_engine::cmd::workspace::view_extent; use rustgis_engine::map::Layer; @@ -20,9 +21,6 @@ pub enum Area { Coordinates, } -/// The name `layout.publication` gives when none is: data, not translated. -const DEFAULT_NAME: &str = "Publication"; - /// What a side with no length (a point, a straight line) is widened to, in degrees; on the ±180 or /// ±90 edge half of it is cut off again. const MIN_SIDE: f64 = 0.01; @@ -182,7 +180,7 @@ pub(super) fn map_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { ui.end_row(); } let label = ui.label(tl!("Name")); - ui.add(egui::TextEdit::singleline(&mut d.name).hint_text(DEFAULT_NAME).desired_width(field_width(ui))).labelled_by(label.id); + ui.add(egui::TextEdit::singleline(&mut d.name).hint_text(PUBLICATION_NAME).desired_width(field_width(ui))).labelled_by(label.id); ui.end_row(); }); } @@ -190,7 +188,7 @@ pub(super) fn map_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { /// How the review names the layout: as typed, or as the command names one given no name, saying /// when it numbers it because a layout has that name. pub(super) fn name_label(s: &Session, name: &str) -> String { - let name = Some(name.trim()).filter(|n| !n.is_empty()).unwrap_or(DEFAULT_NAME); + let name = Some(name.trim()).filter(|n| !n.is_empty()).unwrap_or(PUBLICATION_NAME); if s.project.layouts.iter().any(|l| l.name.eq_ignore_ascii_case(name)) { i18n::fmt("{name} (numbered: a layout has that name)", &[("name", name)]) } else { diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 2e6a613430..bed6c31085 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -184,8 +184,6 @@ fn run_presented( preview: Option, ) -> Result { if !app.reads_off_frame { - // Release any preview snapshot before running inline so it does not pin the rows' `Arc`. - drop(preview); // Read here and now: what its file holds now is what it reads. if matches!(command, "layer.reloadData" | "map.reloadTiles") { crate::diskwatch::reading(app, command, &p); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index c0f4861cae..2fcf4dec6e 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -4584,9 +4584,10 @@ impl RasterMaskForm { } } -/// Where [`raster_mask_form`] keeps the draft of layer `layer` on map `map` (its -/// `instance_id`): a layer's id is its map's own, so another map's layer of that id has its own. -fn raster_mask_form_id(map: u64, layer: u32) -> egui::Id { +/// Where [`raster_mask_form`] keeps the draft of layer `layer` on map `map` (each by its +/// `instance_id`): a layer's map-local id is reused after a removal, so a layer added later never +/// picks up a removed one's draft, and another map's layer has its own. +fn raster_mask_form_id(map: u64, layer: u64) -> egui::Id { egui::Id::unique(("raster_mask_form", map, layer)) } @@ -4615,7 +4616,7 @@ pub(crate) fn raster_mask_form(ui: &mut Ui, app: &mut RustGisApp, layer: &rustgi ui.label(egui::RichText::new(tl!("Add a raster to mask by its values.")).small().weak()); return; } - let id = raster_mask_form_id(app.session.map().instance_id(), layer.id); + let id = raster_mask_form_id(app.session.map().instance_id(), layer.instance_id()); let kept = ui.data(|d| d.get_temp::<(RasterMaskForm, Option)>(id)); let (mut f, started) = raster_mask_draft(kept, layer.raster_mask.as_ref(), &rasters[0]); ui.label(egui::RichText::new(tl!("Where a raster's values are in a range:")).small().weak()); diff --git a/crates/ui-egui/src/scriptcomplete.rs b/crates/ui-egui/src/scriptcomplete.rs index cab877c95e..74fdb916f3 100644 --- a/crates/ui-egui/src/scriptcomplete.rs +++ b/crates/ui-egui/src/scriptcomplete.rs @@ -1848,7 +1848,8 @@ mod tests { type_in(&mut h, "labels.sty"); let (label, said) = read(&h).expect("a row named"); assert_eq!(label, "labels.style"); - assert_eq!(said, super::help(&h.state().session, "labels.style").unwrap().spoken()); + // A built-in command's description is its translated label and nothing more. + assert_eq!(said, tl!("Text Symbol")); h.key_press(egui::Key::Escape); h.run(); assert_eq!(read(&h), None, "closed: no row named"); @@ -1856,7 +1857,14 @@ mod tests { type_in(&mut h, r#"select.byAttributes {"layer": "Countries", "where": "\"pop_"#); let (label, said) = read(&h).expect("a row named"); assert_eq!(label, "pop_est"); - assert!(!said.is_empty(), "the field's type"); + let field_type = h + .state() + .session + .map() + .layer_by_name("Countries") + .and_then(|l| l.dataset.fields.iter().find(|f| f.name == "pop_est").map(|f| f.ty)) + .expect("the sample's Countries has pop_est"); + assert_eq!(said, tl!(field_type.label()), "the field's type"); } /// The key of what a list's rows say (`rows_key`): a layer list's moves with a layer's count diff --git a/crates/ui-egui/src/stacui.rs b/crates/ui-egui/src/stacui.rs index 8bca33a3ca..fbc5628c29 100644 --- a/crates/ui-egui/src/stacui.rs +++ b/crates/ui-egui/src/stacui.rs @@ -433,7 +433,79 @@ enum Raw { /// `source` is the address the document was read from, with the reach it was read under: its /// relative links resolve against the address, and its asset addresses are held to the reach. /// None when the pane shows what RustGIS read instead. - Shown { text: String, drawn: usize, note: Option, doc: serde_json::Value, source: Option<(String, Reach)> }, + /// `assets` are the formatted page's asset rows, made once as the document lands. + Shown { + text: String, + drawn: usize, + note: Option, + doc: serde_json::Value, + source: Option<(String, Reach)>, + assets: Vec, + }, +} + +/// One asset row of the formatted page, made once when the document lands: resolving and +/// checking an address as long as the document each frame would cost more than the row is worth. +#[derive(Debug, Clone, PartialEq)] +struct AssetRow { + /// The asset's whole key, the row's identity. + key: String, + /// The key cut to a line, as shown. + shown: String, + /// Its title, type and roles, on one line. + detail: String, + /// The document's own address for it, a relative one resolved against the address the + /// document was read from: what Add to map and Copy link take. None when it has none or it + /// can't be resolved. + href: Option, + /// Whether the document gave an address at all (one that couldn't be resolved is said). + written: bool, + /// The address offered to the browser: where the item may read it from and it needs no signing. + web: Option, + /// The address cut to a line, as shown and on hover. + cut: Option, +} + +/// The formatted page's asset rows of `doc` (up to [`FORMATTED_ROWS`]), read from `source` (or +/// what RustGIS read of `item` when None). +fn asset_rows(doc: &serde_json::Value, source: Option<(&str, Reach)>, item: &Item) -> Vec { + let Some(assets) = doc.get("assets").and_then(|a| a.as_object()) else { return Vec::new() }; + let base = source.map(|(b, _)| b); + assets + .iter() + .take(FORMATTED_ROWS) + .map(|(key, a)| { + let part = |k: &str| a.get(k).filter(|v| !v.is_null()).map(short_value); + let detail = [part("title"), part("type"), part("roles")].into_iter().flatten().collect::>().join(" · "); + // As written when the document has no address of its own. A document read from an + // address names its assets by it: one that can't be resolved (too long, or not an + // address) has none, so no action is offered for it. + let href = a.get("href").and_then(|h| h.as_str()).and_then(|h| match base { + Some(b) => stac::resolve_document_href(b, h), + None => Some(h.to_string()), + }); + let web = href + .as_deref() + .filter(|h| document_asset_allowed(item, key, h, source).is_ok()) + // Judged, and linked, by the address itself: a login binding wraps it. + .map(rustgis_engine::data::login_address::inner) + .filter(|h| address::is_https(h) || h.get(..7).is_some_and(|s| s.eq_ignore_ascii_case("http://"))) + .filter(|h| !stac::needs_signing(h)) + .map(str::to_string); + // Shown cut: laying out an address as long as the read cap each frame would cost more + // than the row is worth. + let cut = href.as_deref().map(|h| short_value(&serde_json::Value::String(h.chars().take(SHORT_VALUE_CHARS + 1).collect()))); + AssetRow { + key: key.clone(), + shown: short_value(&serde_json::Value::String(key.chars().take(SHORT_VALUE_CHARS + 1).collect())), + detail, + href, + written: a.get("href").is_some(), + web, + cut, + } + }) + .collect() } /// An item's preview picture: being fetched, shown, or not to be had. @@ -2261,7 +2333,7 @@ fn results(app: &mut RustGisApp, ui: &mut egui::Ui) { if st.details == Some(i) && let Some(j) = st.json.as_ref().filter(|j| j.item == i) { - let did = inspector(ui, j, item); + let did = inspector(ui, j); view = view.or(did.tab); (copy, cancel) = (copy || did.copy, cancel || did.cancel); if let Some((key, href)) = did.add { @@ -2448,7 +2520,9 @@ fn rounded_numbers(bytes: &[u8]) -> usize { } /// Whether the number written as `token` is not kept exactly: a whole number outside `i64` and -/// `u64`, or one with more than 15 significant digits in its mantissa. +/// `u64`, one with more than 15 significant digits in its mantissa, or a nonzero one smaller than +/// the smallest normal double (a subnormal such as `1.2345e-320` keeps fewer digits than were +/// written, and `1e-400` reads as zero). fn is_rounded(token: &str) -> bool { let plain = token.trim_start_matches('-'); let mantissa = plain.split(['e', 'E']).next().unwrap_or(""); @@ -2457,9 +2531,10 @@ fn is_rounded(token: &str) -> bool { return plain.len() > 1 && token.parse::().is_err() && token.parse::().is_err(); } let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); - // A number with a nonzero digit that reads as zero (`1e-400`) has lost everything. - let to_zero = !digits.trim_matches('0').is_empty() && token.parse::().is_ok_and(|v| v == 0.0); - to_zero || digits.trim_matches('0').len() > 15 + // A nonzero number below the normal range keeps fewer digits (a subnormal) or none at all. + let nonzero = !digits.trim_matches('0').is_empty(); + let underflows = nonzero && token.parse::().is_ok_and(|v| v.abs() < f64::MIN_POSITIVE); + underflows || digits.trim_matches('0').len() > 15 } /// The most bytes the pretty-printed document may take. Indentation can multiply a small document @@ -2523,7 +2598,8 @@ fn start_json(app: &mut RustGisApp, i: usize) { let trimmed = |why: String| { let (text, drawn, doc) = trimmed_text(&item); let note = raw_note(&text, drawn, Some(why)); - Raw::Shown { text, drawn, note, doc, source: None } + let assets = asset_rows(&doc, None, &item); + Raw::Shown { text, drawn, note, doc, source: None, assets } }; let Some(url) = item.url.clone() else { let why = if item.url_too_long { @@ -2566,10 +2642,14 @@ fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { }; let raw = match r { Ok(Landed { text, drawn, doc, rounded, source }) => { - let why = (rounded > 0) - .then(|| i18n::fmt("{n} numbers have more digits than are kept and are shown rounded.", &[("n", &rounded.to_string())])); + let why = match rounded { + 0 => None, + 1 => Some(tl!("1 number has more digits than are kept and is shown rounded.").to_string()), + n => Some(i18n::fmt("{n} numbers have more digits than are kept and are shown rounded.", &[("n", &n.to_string())])), + }; let note = raw_note(&text, drawn, why); - Raw::Shown { text, drawn, note, doc, source: Some(source) } + let assets = asset_rows(&doc, Some((source.0.as_str(), source.1)), &item); + Raw::Shown { text, drawn, note, doc, source: Some(source), assets } } Err(e) => { let (text, drawn, doc) = trimmed_text(&item); @@ -2578,7 +2658,8 @@ fn poll_json(app: &mut RustGisApp, ctx: &egui::Context) { &[("e", &e)], ); let note = raw_note(&text, drawn, Some(why)); - Raw::Shown { text, drawn, note, doc, source: None } + let assets = asset_rows(&doc, None, &item); + Raw::Shown { text, drawn, note, doc, source: None, assets } } }; app.ui.stac.json = Some(JsonView { item: i, text_tab, raw }); @@ -2597,7 +2678,7 @@ struct Inspected { /// The inspector under an open card: the Formatted and JSON tabs, then the tab shown, or a /// spinner and Cancel while the document is read. -fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { +fn inspector(ui: &mut egui::Ui, view: &JsonView) -> Inspected { let mut did = Inspected::default(); ui.horizontal(|ui| { if ui.add(egui::Button::new(tl!("Formatted")).selected(!view.text_tab)).clicked() { @@ -2618,7 +2699,7 @@ fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { did.cancel = ui.button(tl!("Cancel")).clicked(); }); } - Raw::Shown { text, drawn, note, doc, source } => { + Raw::Shown { text, drawn, note, doc, source, assets } => { if let Some(note) = note { ui.label(egui::RichText::new(note).small().weak()); } @@ -2636,7 +2717,7 @@ fn inspector(ui: &mut egui::Ui, view: &JsonView, item: &Item) -> Inspected { ui.add(egui::TextEdit::multiline(&mut shown).code_editor().desired_width(f32::INFINITY).interactive(true)); }); } else { - did.add = formatted(ui, view.item, doc, source.as_ref().map(|(b, r)| (b.as_str(), *r)), item); + did.add = formatted(ui, view.item, doc, assets); } } } @@ -2686,6 +2767,15 @@ fn short_value(v: &serde_json::Value) -> String { short } +/// The line under a section cut at [`FORMATTED_ROWS`]: how many rows more the document has. +fn more_not_shown(n: usize) -> String { + if n == 1 { + tl!("1 more is not shown: see JSON").to_string() + } else { + i18n::fmt("{n} more are not shown: see JSON", &[("n", &n.to_string())]) + } +} + /// A titled section of two-column rows (a label and a value): the rows given, and how many more /// the document had. fn section(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, title: &str, rows: Vec<(String, String)>, total: usize) { @@ -2702,21 +2792,13 @@ fn section(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, title: } }); if total > rows.len() { - let more = (total - rows.len()).to_string(); - ui.label(egui::RichText::new(i18n::fmt("{n} more are not shown: see JSON", &[("n", &more)])).small().weak()); + ui.label(egui::RichText::new(more_not_shown(total - rows.len())).small().weak()); } } -/// An item's document laid out as a page: what it is, its properties, its assets and its links. -/// Only what the document holds is drawn; a section it lacks is left out. -fn formatted( - ui: &mut egui::Ui, - id: usize, - doc: &serde_json::Value, - source: Option<(&str, Reach)>, - item: &Item, -) -> Option<(String, String)> { - let base = source.map(|(b, _)| b); +/// An item's document laid out as a page: what it is, its properties, its assets (`rows`, made as +/// it landed) and its links. Only what the document holds is drawn; a section it lacks is left out. +fn formatted(ui: &mut egui::Ui, id: usize, doc: &serde_json::Value, rows: &[AssetRow]) -> Option<(String, String)> { let field = |k: &str| doc.get(k).filter(|v| !v.is_null()).map(short_value); let head: Vec<(String, String)> = [ (tl!("ID"), field("id")), @@ -2742,51 +2824,29 @@ fn formatted( if let Some(assets) = doc.get("assets").and_then(|a| a.as_object()) { ui.add_space(4.0); ui.label(egui::RichText::new(tl!("Assets")).strong()); - for (key, a) in assets.iter().take(FORMATTED_ROWS) { - let part = |k: &str| a.get(k).filter(|v| !v.is_null()).map(short_value); - let detail = [part("title"), part("type"), part("roles")].into_iter().flatten().collect::>().join(" · "); - // The document's own address for the asset, a relative one resolved against the address - // the document was read from (as written when the document has no address). The full address, not the - // shortened label, is what Copy link takes. - let href = a.get("href").and_then(|h| h.as_str()).and_then(|h| match base { - // A document read from an address names its assets by it: one that can't be resolved - // (too long, or not an address) has none, so no action is offered for it. - Some(b) => stac::resolve_document_href(b, h), - None => Some(h.to_string()), - }); - // Offered to the browser only where the item may read it from and it needs no signing. - let web = href - .clone() - .filter(|h| document_asset_allowed(item, key, h, source).is_ok()) - // Judged, and linked, by the address itself: a login binding wraps it. - .map(|h| rustgis_engine::data::login_address::inner(&h).to_string()) - .filter(|h| address::is_https(h) || h.get(..7).is_some_and(|s| s.eq_ignore_ascii_case("http://"))) - .filter(|h| !stac::needs_signing(h)); + for row in rows { + let AssetRow { key, shown, detail, href, written, web, cut } = row; ui.push_id(("stac_asset", id, key), |ui| { - // A key can be as long as the document; the whole one stays the row's identity. - let shown = short_value(&serde_json::Value::String(key.chars().take(SHORT_VALUE_CHARS + 1).collect())); ui.label(egui::RichText::new(shown).small().strong()); if !detail.is_empty() { ui.add(egui::Label::new(egui::RichText::new(detail).small().weak()).wrap()); } - // Hovers show the cut form too: laying out an address as long as the read cap each - // frame would cost more than the row is worth. Copy link takes the whole address. - let cut = href.as_ref().map(|h| short_value(&serde_json::Value::String(h.clone()))); - if let Some(c) = &cut { + // Hovers show the cut form too. Copy link takes the whole address. + if let Some(c) = cut { ui.add(egui::Label::new(egui::RichText::new(c).small().weak()).truncate()).on_hover_text(c); } ui.horizontal(|ui| { // The address added is the one shown in this row; a row with none has nothing to add. let button = egui::Button::new(tl!("Add to map")).small(); if ui.add_enabled(href.is_some(), button).on_hover_text(tl!("Add this asset to the map")).clicked() - && let Some(h) = &href + && let Some(h) = href { add = Some((key.clone(), h.clone())); } - if let Some(h) = &web { + if let Some(h) = web { ui.hyperlink_to(egui::RichText::new(tl!("Download")).small(), h).on_hover_text(cut.as_deref().unwrap_or_default()); } - if href.is_none() && a.get("href").is_some() { + if href.is_none() && *written { // Never silent: say why the row has no actions. ui.label( egui::RichText::new(tl!("No address: it can't be read or resolved against the document's address")) @@ -2794,7 +2854,7 @@ fn formatted( .weak(), ); } - if let Some(h) = &href + if let Some(h) = href && ui.add(egui::Button::new(tl!("Copy link")).small()).on_hover_text(cut.as_deref().unwrap_or_default()).clicked() { // A login binding is not part of the address. @@ -2804,8 +2864,7 @@ fn formatted( }); } if assets.len() > FORMATTED_ROWS { - let more = (assets.len() - FORMATTED_ROWS).to_string(); - ui.label(egui::RichText::new(i18n::fmt("{n} more are not shown: see JSON", &[("n", &more)])).small().weak()); + ui.label(egui::RichText::new(more_not_shown(assets.len() - FORMATTED_ROWS)).small().weak()); } } if let Some(links) = doc.get("links").and_then(|l| l.as_array()) { @@ -4248,6 +4307,40 @@ mod tests { assert!(notices.iter().any(|n| n.contains("Reading https://stac.example/a.tif")), "{notices:?}"); } + /// The asset rows are made once as the document lands: a relative address resolved against + /// where it was read, and one that needs signing offered to the map but not as a download. + #[test] + fn a_landed_documents_asset_rows_are_resolved_once() { + let item = json_test_item(true); + let doc = json!({ + "type": "Feature", "id": "scene-1", "collection": "c", + "assets": { + "relative": {"href": "./b.tif", "title": "B"}, + "signed": {"href": "https://acct.blob.core.windows.net/c/a.tif"}, + }, + }); + let base = "https://stac.example/api/collections/c/items/scene-1"; + let rows = asset_rows(&doc, Some((base, Reach::Public)), &item); + assert_eq!(rows.len(), 2); + let relative = &rows[0]; + assert_eq!(relative.key, "relative"); + assert_eq!(relative.detail, "B"); + assert_eq!(relative.href.as_deref(), Some("https://stac.example/api/collections/c/items/b.tif")); + assert_eq!(relative.web, relative.href); + assert_eq!(relative.cut, relative.href); + let signed = &rows[1]; + assert_eq!(signed.href.as_deref(), Some("https://acct.blob.core.windows.net/c/a.tif")); + assert_eq!(signed.web, None, "it needs signing first"); + // A document with no assets has no rows. + assert!(asset_rows(&json!({"type": "Feature"}), None, &item).is_empty()); + } + + #[test] + fn one_row_more_is_said_in_the_singular() { + assert_eq!(more_not_shown(1), "1 more is not shown: see JSON"); + assert_eq!(more_not_shown(50), "50 more are not shown: see JSON"); + } + #[test] fn a_document_that_is_not_this_item_or_is_over_the_cap_falls_back_with_the_reason() { let _turn = crate::fetching::turn(); @@ -4288,6 +4381,12 @@ mod tests { assert_eq!(rounded_numbers(b"[0.12345678901234567890123, 0.1234567890123456]"), 2); assert_eq!(rounded_numbers(b"[0.123456789012345]"), 0, "15 digits are kept"); assert_eq!(rounded_numbers(b"[1e-400, 0.0, 0e5, 0.000]"), 1, "only the nonzero number that reads as zero counts"); + // A subnormal keeps fewer digits than were written; the smallest normals don't. + assert!(is_rounded("1.2345e-320")); + assert!(is_rounded("-1.2345e-320")); + assert!(is_rounded("1e-400")); + assert!(!is_rounded("2.3e-308")); + assert!(!is_rounded("0.0")); assert_eq!(rounded_numbers(b"[0.1000000000000000055511151231257827, 1.2345678901234567890e5]"), 2); // Valid JSON with a number no float holds is named, not called "not JSON". let err = raw_text(br#"{"a": 1e400}"#).unwrap_err(); diff --git a/crates/ui-egui/src/vertexedit.rs b/crates/ui-egui/src/vertexedit.rs index cf94dfb562..c66b1feee1 100644 --- a/crates/ui-egui/src/vertexedit.rs +++ b/crates/ui-egui/src/vertexedit.rs @@ -273,6 +273,13 @@ fn own_placing(app: &RustGisApp, id: u32) -> bool { !on_globe(app) && m.layer(id).and_then(|l| Placing::of(&flat, false, l)).is_some_and(|p| p.is_identity()) } +/// The layers whose selected features Edit Vertices handles: visible feature layers with a +/// selection, held in memory. `targets`, `unplaced_targets` and `unplaced_signature` all read +/// them from here, so the unplaced count matches the handles. +fn edited_layers(m: &rustgis_engine::map::Map) -> impl Iterator { + m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) +} + /// The features whose vertices the tool edits: the selected features of visible feature layers /// held in memory (a layer read in place from its file can't be edited), when editing is on, in /// view coordinates ([`Placing`]). @@ -283,7 +290,7 @@ fn targets(app: &RustGisApp) -> Vec<(u32, usize, Cow<'_, Geometry>)> { } let (flat, globe) = (m.flat(), on_globe(app)); let mut out = Vec::new(); - for l in m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) { + for l in edited_layers(m) { let Some(placing) = Placing::of(&flat, globe, l) else { continue }; for r in &l.selection { if out.len() >= MAX_FEATURES { @@ -325,7 +332,7 @@ fn unplaced_targets(app: &RustGisApp) -> Unplaced { let mut found = Unplaced { rows: Vec::new(), more: false, visited: Vec::new() }; let mut placed = 0usize; let (flat, globe) = (m.flat(), on_globe(app)); - for l in m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) { + for l in edited_layers(m) { let placing = Placing::of(&flat, globe, l); let mut visited = 0; for r in &l.selection { @@ -364,7 +371,7 @@ fn unplaced_signature(app: &RustGisApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.project.active_map.hash(&mut h); m.projection.hash(&mut h); - for l in m.layers.iter().filter(|l| m.shows(l) && !l.selection.is_empty() && !l.is_raster() && !l.graphics && !l.is_streamed()) { + for l in edited_layers(m) { let rows = l.dataset.features.allocation_key().as_ptr() as usize; let revisions = (l.instance_id(), l.replacement_revision(), l.geometry_rev, rows); let visited = app.map.vertex_unplaced_visited.iter().find(|(id, _)| *id == l.instance_id()).map_or(0, |(_, n)| *n); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 83c185e3e4..e8b4da9bf4 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -4,8 +4,8 @@ **Home › Select** picks features by clicking or dragging a box. Open **Select options** to choose **Select by Polygon** (click vertices; click the first vertex or double-click to finish), **Select by -Lasso** (drag a freehand outline), or **Select by Radius**. For a radius, enter a distance and click -its centre, or drag from the centre to an edge. A drag replaces the box's value; click another +Lasso** (drag a freehand outline), or **Select by Radius**. For a radius, enter a distance (up to +5,000 km) and click its centre, or drag from the centre to an edge. A drag replaces the box's value; click another centre to reuse that distance or edit the box to correct it. Bare numbers use metres or feet, following the measurement setting; `m`, `km`, `ft` and `mi` suffixes select units explicitly. Use a decimal point and no thousands separators. Shift adds to the selection; Ctrl/Cmd removes; diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index fc707dc628..e11be7d63d 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -588,8 +588,8 @@ back its typing, not the project's last change. scrolled in. Click a layer in the Layers pane and ++delete++ removes it (Undo brings it back), whatever is selected on the map; click or scroll the map and it deletes the selected features again. When ++delete++ has nothing to act on, a notice says why. In the -[attribute table](analysis.md#the-attribute-table) the arrow keys move between cells; on the map -they pan it, and in a layout they nudge the selected element. +[attribute table](analysis.md#the-attribute-table) the arrow keys move between cells (and +++shift++ with an arrow does nothing there); on the map they pan it, and in a layout they nudge the selected element. Copy and Paste follow it too. In the Layers pane they copy and paste the selected layers, as **Copy Layer** and **Paste Layer** in a layer's menu do: the copies go above the active layer, or at the diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 862d52f240..6564590cd4 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -66,7 +66,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu the area stays as made); an area crossing ±180° isn't taken (a view that crosses it is cut there, as with View), and the choice is off for a map on the globe. The **elements** are what is drawn around the map: the locator (the default, named as what it will - be, a globe, an inset, both or none), the north arrow (auto, always or none) and its style, the + be, a globe, an inset, an inset and a globe, or none), the north arrow (auto, always or none) and its style, the legend or not and its title, the colorbar, the scale bar with its units and style, and the frame grid or not (without it the default reference leaves the graticule out; the map's own graticule is still drawn when on). **Advanced**, closed at first, holds the finer settings, its header diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 97f5922807..88c742e321 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -73,7 +73,7 @@ with the Pan tool, to turn the map about the centre of the view (to the right tu and to tilt it (up tilts it further), as in MapLibre; or hold ++shift++ and press ++arrow-left++ or ++arrow-right++ to turn it, ++arrow-up++ or ++arrow-down++ to tilt it (after a click or a scroll in the [attribute table](analysis.md#the-attribute-table), the arrow keys move between its cells -instead). The north arrow turns with the map to point north and leans back as it tilts; click +instead, and ++shift++ with an arrow does nothing there). The north arrow turns with the map to point north and leans back as it tilts; click it to face north and look straight down again. The bearing (the compass direction the top of the view faces, in degrees clockwise from north) and the pitch (the tilt from looking straight down, 0 to 85 degrees) work as in MapLibre. They are saved with the project, its bookmarks and bookmark @@ -424,18 +424,18 @@ and longitude. Scripts set the format with `ui.coordinateFormat={"format":"utm"} doesn't know, say from a newer RustGIS, reads in map coordinates with a notice, and stays saved until you pick a format. -`map.convertPosition` gives a place in all of these forms at once, without moving the map, for -scripts, Python and the AI Assistant. It takes the place as `map.goToXY` does: `lon` and `lat` -(numbers, or degrees, minutes and seconds), or a `position` written in any form the search box -reads, and says what it assumed the same way. It answers with `lon` and `lat`, `decimal` and -`dms` as the readout writes them, `grid` (`utm`, or `ups` in the polar areas), the reference in -`utm` or `ups` (whichever `grid` names; the other is `null`), the UTM `zone` and latitude `band` -(`null` in UPS), `hemisphere`, `easting` and `northing` in meters, and `mgrs` spaced as the -readout writes it and `mgrsCompact` in one word. `digits` (0 to 5, 5 by default) sets the MGRS -precision, from 100 km to 1 m. As in the readouts, the `utm` and `ups` text round to the meter -while MGRS truncates, so the two can differ by a meter; `easting` and `northing` give the place -to the millimeter (truncated). Every key is always there, `null` where it has no value; on -another body's map the grids are `null`, and `note` says why. +`map.convertPosition` gives a place in all of these forms but map and layer coordinates at once, +without moving the map, for scripts, Python and the AI Assistant. It takes the place as `map.goToXY` +does: `lon` and `lat` (numbers, or degrees, minutes and seconds), or a `position` written in any +form the search box reads, and says what it assumed the same way. It answers with `lon` and `lat`, +`decimal` and `dms` as the readout writes them, `grid` (`utm`, or `ups` in the polar areas), the +reference in `utm` or `ups` (whichever `grid` names; the other is `null`), the UTM `zone` and +latitude `band` (`null` in UPS), `hemisphere`, `easting` and `northing` in meters, and `mgrs` spaced +as the readout writes it and `mgrsCompact` in one word. `digits` (0 to 5, 5 by default) sets the +MGRS precision, from 100 km to 1 m. As in the readouts, the `utm` and `ups` text round to the meter +while MGRS truncates, so the two can differ by a meter; `easting` and `northing` give the place to +the millimeter (truncated). Every key is always there, `null` where it has no value; on another +body's map the grids are `null`, and `note` says why. ``` rustgis-cli run --cmd 'map.convertPosition={"position":"18TWL8395907350"}' From 32622a096340058c1a26200a9089c41d9d521768 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 01:10:56 -0500 Subject: [PATCH 2/7] fix(ui): review follow-ups for the ui sweep A typed-radius double-click is skipped only when its second click keeps the first click's selection mode, so Shift then Ctrl still selects twice. The field suggestions' duplicate check uses the ASCII case rule field_index uses. A geoBoundaries count of 2^64 is no count. The block squeeze notice gives the most-squeezed figure. --- crates/engine/src/cmd/block_model.rs | 2 +- crates/tiles/src/boundaries.rs | 5 +++-- crates/ui-egui/src/mapview.rs | 30 ++++++++++++++++++++++++++-- crates/ui-egui/src/panes.rs | 5 +++-- 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/block_model.rs b/crates/engine/src/cmd/block_model.rs index c8d943d53e..2c77e4703c 100644 --- a/crates/engine/src/cmd/block_model.rs +++ b/crates/engine/src/cmd/block_model.rs @@ -167,7 +167,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result, radius_preview: Option<(Coord, f64, Vec>)>, radius_text: String, + /// The selection mode of the last click that selected with a typed radius: the second click of + /// a double-click selects again only with another mode (Shift then Ctrl, say). + radius_click_mode: &'static str, radius_imperial: bool, /// A finished measurement stays on screen until the next click. sketch_done: bool, @@ -464,6 +467,7 @@ impl Default for MapView { selection_gesture: None, radius_preview: None, radius_text: String::new(), + radius_click_mode: "", radius_imperial: false, sketch_done: false, split_mode: false, @@ -2760,7 +2764,12 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect } return; } - if tool == Tool::SelectRadius && resp.clicked() && !resp.double_clicked() && !app.map.radius_text.trim().is_empty() { + // A double-click's second click selects again only when its mode changed (egui's double-click + // doesn't look at the modifiers); with the same mode it would add a second, identical step. + let mode = selection_mode(ui); + let repeated = resp.double_clicked() && app.map.radius_click_mode == mode; + if tool == Tool::SelectRadius && resp.clicked() && !repeated && !app.map.radius_text.trim().is_empty() { + app.map.radius_click_mode = mode; let result = (|| { let radius = crate::measure_units::parse_distance(&app.map.radius_text, app.ui.measurement_imperial)?; let Some(radius) = radius else { @@ -2773,7 +2782,7 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect let center = selection_coord(app, rect, point, &Flat::of(&app.session.map().projection))?; radius_outline(app, rect, center, radius)?; // The app dispatcher reports command failures; only pre-dispatch errors escape here. - let _ = app.run("select.byRadius", json!({"lon":center.x,"lat":center.y,"radius":radius,"mode":selection_mode(ui)})); + let _ = app.run("select.byRadius", json!({"lon":center.x,"lat":center.y,"radius":radius,"mode":mode})); Ok(()) })(); app.map.cancel_sketch(); @@ -6679,6 +6688,23 @@ mod tests { assert_eq!(h.state().session.undo_depth(), depth + 1, "one selection step for the pair"); } + /// A quick second click with another mode (Ctrl to remove) is its own selection, though egui + /// reads the pair as a double-click. + #[test] + fn typed_radius_quick_click_with_another_mode_selects_again() { + let mut h = selection_harness(); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + h.state_mut().map.radius_text = "1000".into(); + h.run(); + let at = selection_screen(&h, [0.5, 0.5]); + selection_pointer(&mut h, at, Some(true), egui::Modifiers::NONE); + selection_pointer(&mut h, at, Some(false), egui::Modifiers::NONE); + assert_eq!(selection_rows(&h), vec![0]); + selection_pointer(&mut h, at, Some(true), egui::Modifiers::COMMAND); + selection_pointer(&mut h, at, Some(false), egui::Modifiers::COMMAND); + assert!(selection_rows(&h).is_empty(), "the Ctrl click removed it: {:?}", selection_rows(&h)); + } + /// A circle near a local projection's boundary has valid extrema but an invalid arc. #[test] fn typed_radius_rejects_the_same_projection_boundary_as_drag() { diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index e7b7afa1a3..29af4767b1 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3963,8 +3963,9 @@ pub(crate) fn field_suggestions<'a>( value.clear(); value.push_str(field); response.mark_changed(); - } else if !value.split([',', ';']).any(|part| part.trim().to_lowercase() == field.to_lowercase()) { - // Tools match field names regardless of case, so `Name` after `name` is the same field. + } else if !value.split([',', ';']).any(|part| part.trim().eq_ignore_ascii_case(field)) { + // Tools find a field regardless of ASCII case (`Dataset::field_index`), so `Name` after + // `name` is the same field. let separator = if value.contains(';') { ';' } else { ',' }; if !value.trim_end().ends_with([',', ';']) { value.push(separator); From 9d992f72e9f364e2c803acc4d66892c70c2e27c1 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 01:30:29 -0500 Subject: [PATCH 3/7] fix(ui): say unreadable geoBoundaries unit counts parse_availability also returns how many counts given couldn't be read, and the boundaries dialog says them in one notice a level, so a level offered without its count is never silent. The typed-radius click mode is cleared after any click that didn't select by radius, so a stale mode can't skip a later selection. --- crates/tiles/src/boundaries.rs | 29 ++++++++++++++++++++--------- crates/ui-egui/src/mapview.rs | 4 ++++ crates/ui-egui/src/portalsui.rs | 32 +++++++++++++++++++++++++++++++- 3 files changed, 55 insertions(+), 10 deletions(-) diff --git a/crates/tiles/src/boundaries.rs b/crates/tiles/src/boundaries.rs index c152cc034c..0c39971c29 100644 --- a/crates/tiles/src/boundaries.rs +++ b/crates/tiles/src/boundaries.rs @@ -48,27 +48,36 @@ fn catalogue_url(level: &str) -> String { format!("{API}/ALL/{level}/") } -/// Available countries at one level, with a unit count when the service supplies one. +/// Available countries at one level, with a unit count when the service supplies one, and how +/// many counts given couldn't be read. /// Reject the entire catalogue on any malformed country entry: skipping it would incorrectly /// mark that country's level unavailable. The caller offers unknown levels and explains why. /// A count that isn't a non-negative whole number (as a number, `26.0` included, or as text) is -/// treated as absent: the level is still offered, without a count. -pub fn parse_availability(bytes: &[u8]) -> Result>, String> { +/// treated as absent: the level is still offered, without a count, and the count is in the +/// number returned for the caller to say. A missing or null count is none to read. +pub fn parse_availability(bytes: &[u8]) -> Result<(std::collections::BTreeMap>, usize), String> { let v: Value = serde_json::from_slice(bytes).map_err(|_| "the geoBoundaries list isn't JSON".to_string())?; - v.as_array() + let mut unreadable = 0usize; + let available = v + .as_array() .ok_or_else(|| "the geoBoundaries list isn't a list".to_string())? .iter() .map(|entry| { let iso = country(entry.get("boundaryISO").and_then(Value::as_str).ok_or("missing country code")?) .map_err(|_| "the geoBoundaries list has an invalid country code")?; - let count = entry.get("admUnitCount").and_then(|n| { + let given = entry.get("admUnitCount").filter(|n| !n.is_null()); + let count = given.and_then(|n| { n.as_u64() .or_else(|| n.as_f64().filter(|f| f.fract() == 0.0 && (0.0..u64::MAX as f64).contains(f)).map(|f| f as u64)) - .or_else(|| n.as_str()?.parse().ok()) + .or_else(|| n.as_str()?.trim().parse().ok()) }); + if given.is_some() && count.is_none() { + unreadable += 1; + } Ok((iso, count)) }) - .collect() + .collect::>()?; + Ok((available, unreadable)) } /// A country's level, as the API describes it. @@ -137,7 +146,8 @@ mod tests { #[test] fn availability_keeps_counts_and_rejects_unreadable_catalogues() { let list = br#"[{"boundaryISO":"PER","admUnitCount":"196"},{"boundaryISO":"CHE","admUnitCount":26},{"boundaryISO":"KEN"}]"#; - let parsed = parse_availability(list).unwrap(); + let (parsed, unreadable) = parse_availability(list).unwrap(); + assert_eq!(unreadable, 0, "every count given is read"); assert_eq!(parsed.get("PER"), Some(&Some(196))); assert_eq!(parsed.get("CHE"), Some(&Some(26))); assert_eq!(parsed.get("KEN"), Some(&None)); @@ -145,7 +155,8 @@ mod tests { // A whole number written as a float is a count; a negative or unreadable one is none, // and the country is still listed. let odd = br#"[{"boundaryISO":"CHE","admUnitCount":26.0},{"boundaryISO":"PER","admUnitCount":-3},{"boundaryISO":"KEN","admUnitCount":"x"},{"boundaryISO":"NZL","admUnitCount":2.5},{"boundaryISO":"FJI","admUnitCount":18446744073709551616.0}]"#; - let parsed = parse_availability(odd).unwrap(); + let (parsed, unreadable) = parse_availability(odd).unwrap(); + assert_eq!(unreadable, 4, "-3, x, 2.5 and 2^64 are counted as unreadable"); assert_eq!(parsed.get("CHE"), Some(&Some(26))); assert_eq!(parsed.get("PER"), Some(&None)); assert_eq!(parsed.get("KEN"), Some(&None)); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index a38d1bb495..079ffa8c8c 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -2791,6 +2791,10 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect } return; } + // The mode kept is only ever the last click's that selected by radius. + if resp.clicked() { + app.map.radius_click_mode = ""; + } // Both drag tools consume ordinary clicks and double-clicks without identifying or zooming. if resp.double_clicked() { app.map.cancel_sketch(); diff --git a/crates/ui-egui/src/portalsui.rs b/crates/ui-egui/src/portalsui.rs index fbaef4da48..9c3e7d5c7d 100644 --- a/crates/ui-egui/src/portalsui.rs +++ b/crates/ui-egui/src/portalsui.rs @@ -85,6 +85,8 @@ fn fetch_catalogue(url: &str) -> Answer { /// Lands the answers. pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { + // Counts a catalogue gave that couldn't be read: said once per level, after the borrow. + let mut unread: Vec<(usize, usize)> = Vec::new(); app.ui.portals.level_waiting.retain(|(level, slot)| { let Some(result) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() else { ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -95,9 +97,12 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { (app.ui.portals.availability.get_mut(*level), app.ui.portals.availability_errors.get_mut(*level)) { match result { - Ok(available) => { + Ok((available, unreadable)) => { *catalogue = Some(available); *error = None; + if unreadable > 0 { + unread.push((*level, unreadable)); + } } Err(reason) => { *catalogue = None; @@ -107,6 +112,13 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } false }); + for (level, n) in unread { + let text = crate::i18n::fmt( + "geoBoundaries ADM{level}: {n} countries' unit counts couldn't be read (not a whole number), so their levels are offered without a count", + &[("level", &level.to_string()), ("n", &n.to_string())], + ); + app.session.notify(text, false); + } let Some((_, slot)) = &app.ui.portals.waiting else { return }; let Some(r) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() else { ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -459,6 +471,22 @@ mod tests { assert!(!country_matches(&st, "POL", "Polska", "poland")); } + /// Counts a catalogue gives that can't be read are said, one notice for the level. + #[test] + fn unreadable_unit_counts_are_said() { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let answer = |result| std::sync::Arc::new(std::sync::Mutex::new(Some(result))); + let list = + br#"[{"boundaryISO":"PER","admUnitCount":"x"},{"boundaryISO":"CHE","admUnitCount":-3},{"boundaryISO":"KEN","admUnitCount":4}]"#; + app.ui.portals.level_waiting = vec![(1, answer(Ok((list.to_vec(), Reach::Public))))]; + let mark = app.session.notice_mark(); + poll(&mut app, &egui::Context::default()); + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("geoBoundaries ADM1: 2 countries' unit counts couldn't be read"), "{said:?}"); + assert_eq!(app.ui.portals.availability[1].as_ref().and_then(|a| a.get("PER")), Some(&None), "still offered"); + } + /// Availability lands even with no dialog open and a failed level never disables choices. #[test] fn availability_lands_independently_of_boundary_downloads() { @@ -471,7 +499,9 @@ mod tests { (4, answer(Err("offline".to_string()))), (5, answer(Ok((b"{}".to_vec(), Reach::Public)))), ]; + let mark = app.session.notice_mark(); poll(&mut app, &egui::Context::default()); + assert!(app.session.notices_since(mark).is_empty(), "clean counts say nothing"); assert_eq!(app.ui.portals.availability[2].as_ref().unwrap().get("PER"), Some(&Some(196))); assert!(!app.ui.portals.availability[3].as_ref().unwrap().contains_key("PER")); assert!(app.ui.portals.availability[4].is_none()); From 5220c46e5b66077840f9ab2ee9235e7b1fc28da1 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 02:03:07 -0500 Subject: [PATCH 4/7] fix(ui): keep a typed-radius click's mode only for a sent selection The mode a double-click's second click is compared with is kept only once select.byRadius is sent, and only for egui's double-click window, so a refused radius or an older click with another tool never skips a selection. --- crates/ui-egui/src/mapview.rs | 41 +++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 079ffa8c8c..735d45a3e1 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -309,9 +309,10 @@ pub struct MapView { selection_gesture: Option, radius_preview: Option<(Coord, f64, Vec>)>, radius_text: String, - /// The selection mode of the last click that selected with a typed radius: the second click of - /// a double-click selects again only with another mode (Shift then Ctrl, say). - radius_click_mode: &'static str, + /// The selection mode and input time of the last click that selected with a typed radius: the + /// second click of a double-click right after it selects again only with another mode (Shift + /// then Ctrl, say). + radius_click: Option<(&'static str, f64)>, radius_imperial: bool, /// A finished measurement stays on screen until the next click. sketch_done: bool, @@ -467,7 +468,7 @@ impl Default for MapView { selection_gesture: None, radius_preview: None, radius_text: String::new(), - radius_click_mode: "", + radius_click: None, radius_imperial: false, sketch_done: false, split_mode: false, @@ -2766,10 +2767,17 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect } // A double-click's second click selects again only when its mode changed (egui's double-click // doesn't look at the modifiers); with the same mode it would add a second, identical step. + // Only a radius click within the double-click delay counts, so a mode kept from an older click + // (another tool, a refused radius) never skips one. let mode = selection_mode(ui); - let repeated = resp.double_clicked() && app.map.radius_click_mode == mode; + let now = ui.input(|i| i.time); + // egui times a double-click from the first release to the second press; twice its delay + // covers the second click's own length. + let window = 2.0 * ui.ctx().options(|o| o.input_options.max_double_click_delay); + let repeated = resp.double_clicked() && app.map.radius_click.is_some_and(|(was, at)| was == mode && now - at <= window); if tool == Tool::SelectRadius && resp.clicked() && !repeated && !app.map.radius_text.trim().is_empty() { - app.map.radius_click_mode = mode; + // Kept only once the selection is sent below: a refused radius leaves none. + app.map.radius_click = None; let result = (|| { let radius = crate::measure_units::parse_distance(&app.map.radius_text, app.ui.measurement_imperial)?; let Some(radius) = radius else { @@ -2783,6 +2791,7 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect radius_outline(app, rect, center, radius)?; // The app dispatcher reports command failures; only pre-dispatch errors escape here. let _ = app.run("select.byRadius", json!({"lon":center.x,"lat":center.y,"radius":radius,"mode":mode})); + app.map.radius_click = Some((mode, now)); Ok(()) })(); app.map.cancel_sketch(); @@ -2793,7 +2802,7 @@ fn selection_interact(app: &mut RustGisApp, ui: &Ui, resp: &egui::Response, rect } // The mode kept is only ever the last click's that selected by radius. if resp.clicked() { - app.map.radius_click_mode = ""; + app.map.radius_click = None; } // Both drag tools consume ordinary clicks and double-clicks without identifying or zooming. if resp.double_clicked() { @@ -6692,6 +6701,24 @@ mod tests { assert_eq!(h.state().session.undo_depth(), depth + 1, "one selection step for the pair"); } + /// A click whose radius was refused keeps no mode: a quick same-mode click after the radius is + /// fixed still selects. + #[test] + fn typed_radius_refused_click_keeps_no_mode() { + let mut h = selection_harness(); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + h.state_mut().map.radius_text = "99999 km".into(); + h.run(); + let at = selection_screen(&h, [0.5, 0.5]); + selection_pointer(&mut h, at, Some(true), egui::Modifiers::NONE); + selection_pointer(&mut h, at, Some(false), egui::Modifiers::NONE); + assert!(selection_rows(&h).is_empty(), "over 5,000 km is refused"); + h.state_mut().map.radius_text = "1000".into(); + selection_pointer(&mut h, at, Some(true), egui::Modifiers::NONE); + selection_pointer(&mut h, at, Some(false), egui::Modifiers::NONE); + assert_eq!(selection_rows(&h), vec![0]); + } + /// A quick second click with another mode (Ctrl to remove) is its own selection, though egui /// reads the pair as a double-click. #[test] From 008262b605432767ba380404a46ff917c68dc6b3 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 02:22:45 -0500 Subject: [PATCH 5/7] fix(ui): end a radius click's mode with another tool; singular count Any tool other than Select by Radius clears the kept radius click, so a quick click after switching back always selects. The geoBoundaries notice says one unreadable count in the singular, and names the rule as a non-negative whole number. --- crates/ui-egui/src/mapview.rs | 27 +++++++++++++++++++++++++++ crates/ui-egui/src/portalsui.rs | 23 +++++++++++++++++++---- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 735d45a3e1..2d5267e094 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -3040,6 +3040,11 @@ fn interact(app: &mut RustGisApp, ui: &mut Ui, resp: &egui::Response, rect: Rect app.map.kept_lonlat = Some((c, app.session.map().instance_id(), app.session.opened)); } let tool = app.session.tool; + // A radius click's mode is for the next click of a typed-radius double-click only: any other + // tool ends it (a click the radius branch doesn't take ends it there). + if tool != Tool::SelectRadius { + app.map.radius_click = None; + } if resp.secondary_clicked() && let Some(c) = resp.interact_pointer_pos().and_then(|p| screen_to_lonlat(app, rect, p)) { @@ -6719,6 +6724,28 @@ mod tests { assert_eq!(selection_rows(&h), vec![0]); } + /// Another tool in between ends a radius click's mode: a quick same-mode radius click after + /// switching back still selects. + #[test] + fn typed_radius_mode_ends_with_another_tool() { + let mut h = selection_harness(); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + h.state_mut().map.radius_text = "1000".into(); + h.run(); + let at = selection_screen(&h, [0.5, 0.5]); + selection_pointer(&mut h, at, Some(true), egui::Modifiers::NONE); + selection_pointer(&mut h, at, Some(false), egui::Modifiers::NONE); + assert_eq!(selection_rows(&h), vec![0]); + h.state_mut().run("select.clear", json!({})).unwrap(); + h.state_mut().run("tool.set", json!({"tool":"explore"})).unwrap(); + h.step(); + assert!(h.state().map.radius_click.is_none(), "another tool ends it"); + h.state_mut().run("tool.set", json!({"tool":"selectRadius"})).unwrap(); + selection_pointer(&mut h, at, Some(true), egui::Modifiers::NONE); + selection_pointer(&mut h, at, Some(false), egui::Modifiers::NONE); + assert_eq!(selection_rows(&h), vec![0], "the quick click after switching back selects"); + } + /// A quick second click with another mode (Ctrl to remove) is its own selection, though egui /// reads the pair as a double-click. #[test] diff --git a/crates/ui-egui/src/portalsui.rs b/crates/ui-egui/src/portalsui.rs index 9c3e7d5c7d..c00ff8219b 100644 --- a/crates/ui-egui/src/portalsui.rs +++ b/crates/ui-egui/src/portalsui.rs @@ -113,10 +113,18 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { false }); for (level, n) in unread { - let text = crate::i18n::fmt( - "geoBoundaries ADM{level}: {n} countries' unit counts couldn't be read (not a whole number), so their levels are offered without a count", - &[("level", &level.to_string()), ("n", &n.to_string())], - ); + let level = level.to_string(); + let text = if n == 1 { + crate::i18n::fmt( + "geoBoundaries ADM{level}: 1 country's unit count couldn't be read (not a non-negative whole number), so its level is offered without a count", + &[("level", &level)], + ) + } else { + crate::i18n::fmt( + "geoBoundaries ADM{level}: {n} countries' unit counts couldn't be read (not a non-negative whole number), so their levels are offered without a count", + &[("level", &level), ("n", &n.to_string())], + ) + }; app.session.notify(text, false); } let Some((_, slot)) = &app.ui.portals.waiting else { return }; @@ -485,6 +493,13 @@ mod tests { assert_eq!(said.len(), 1, "{said:?}"); assert!(said[0].starts_with("geoBoundaries ADM1: 2 countries' unit counts couldn't be read"), "{said:?}"); assert_eq!(app.ui.portals.availability[1].as_ref().and_then(|a| a.get("PER")), Some(&None), "still offered"); + // One is said in the singular. + let list = br#"[{"boundaryISO":"PER","admUnitCount":"x"}]"#; + app.ui.portals.level_waiting = vec![(2, answer(Ok((list.to_vec(), Reach::Public))))]; + let mark = app.session.notice_mark(); + poll(&mut app, &egui::Context::default()); + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.first().is_some_and(|s| s.starts_with("geoBoundaries ADM2: 1 country's unit count couldn't be read")), "{said:?}"); } /// Availability lands even with no dialog open and a failed level never disables choices. From 45a86c467b04610c5b8a3c83d65f9815b1802e02 Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 02:50:09 -0500 Subject: [PATCH 6/7] fix(ui): say to delete a certificate option typed in Options The geodatabase form refuses a certificate key in Options whatever the box says, so ticking the box alone never cleared the error. Each message now says to delete the entry: a value turning trust on is the box ticked, one turning it off is the box left unticked (not ticked, as before), and any other value is one SQL Server doesn't take. --- crates/ui-egui/src/connectionui.rs | 31 +++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/connectionui.rs b/crates/ui-egui/src/connectionui.rs index e54aa5aa32..292faaaa23 100644 --- a/crates/ui-egui/src/connectionui.rs +++ b/crates/ui-egui/src/connectionui.rs @@ -478,8 +478,10 @@ fn form_address(st: &State) -> Result { if keys().any(|k| k == "instance") { return Err(tl!("Put the instance in Server, not in Options").into()); } - // A certificate key read as `parse_mssql` reads it: a value the engine takes belongs in the - // box; any other value is a typo the box can't stand for. + // A certificate key in Options is refused whatever the box says (ticking the box doesn't + // remove it), so each message says to delete the entry: read as `parse_mssql` reads it, a + // value turning trust on is the box ticked, one turning it off the box left as it is, and any + // other value is one SQL Server doesn't take. for kv in options.split('&') { let (key, value) = kv.split_once('=').unwrap_or((kv, "")); let key = key.trim().to_ascii_lowercase().replace('_', "-"); @@ -487,11 +489,14 @@ fn form_address(st: &State) -> Result { continue; } return Err(match percent_decode(value.trim()).to_ascii_lowercase().as_str() { - "true" | "yes" | "1" | "false" | "no" | "0" => { - tl!("Tick Trust the server's certificate instead of typing it in Options").into() + "true" | "yes" | "1" => { + tl!("Delete the certificate option from Options and tick Trust the server's certificate instead").into() + } + "false" | "no" | "0" => { + tl!("Delete the certificate option from Options: leaving Trust the server's certificate unticked does the same").into() } _ => tl!( - "The certificate option in Options has a value SQL Server doesn't take (true or false): fix it, or delete it from Options" + "The certificate option in Options has a value SQL Server doesn't take: delete it from Options, and tick Trust the server's certificate if you want it" ) .into(), }); @@ -2364,11 +2369,23 @@ mod tests { assert_eq!( form_error(&typo).as_deref(), Some( - "The certificate option in Options has a value SQL Server doesn't take (true or false): fix it, or delete it from Options" + "The certificate option in Options has a value SQL Server doesn't take: delete it from Options, and tick Trust the server's certificate if you want it" ) ); let typed = State { form_options: "trust-server-certificate=true".into(), ..gdb_form("sql") }; - assert_eq!(form_error(&typed).as_deref(), Some("Tick Trust the server's certificate instead of typing it in Options")); + assert_eq!( + form_error(&typed).as_deref(), + Some("Delete the certificate option from Options and tick Trust the server's certificate instead") + ); + // Ticking the box doesn't clear the entry, so the message still says to delete it. + let ticked = State { trust_cert: true, form_options: "trust-server-certificate=true".into(), ..gdb_form("sql") }; + assert!(form_error(&ticked).is_some_and(|e| e.starts_with("Delete the certificate option"))); + // A value turning trust off is the box left unticked, not ticked. + let off = State { form_options: "TrustServerCertificate=no".into(), ..gdb_form("sql") }; + assert_eq!( + form_error(&off).as_deref(), + Some("Delete the certificate option from Options: leaving Trust the server's certificate unticked does the same") + ); // An empty instance after the backslash would connect on the default route. for server in ["gis-db\\", "gis-db\\,1433", "gis-db\\ "] { let empty = State { server: server.into(), ..gdb_form("sql") }; From a09a2e6f41c7ca37ee53c33c47db300d54362d8d Mon Sep 17 00:00:00 2001 From: giswqs Date: Mon, 30 Nov 2026 03:16:48 -0500 Subject: [PATCH 7/7] fix(ui): say unreadable unit counts in one notice for every level The boundaries dialog gathers the unreadable geoBoundaries unit counts of the catalogues it reads and says them in one notice, with the levels named, once no catalogue is still being read: one notice per kind. --- crates/ui-egui/src/portalsui.rs | 37 +++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/portalsui.rs b/crates/ui-egui/src/portalsui.rs index c00ff8219b..9dbad536bb 100644 --- a/crates/ui-egui/src/portalsui.rs +++ b/crates/ui-egui/src/portalsui.rs @@ -39,6 +39,9 @@ pub struct State { /// Each successful catalogue is authoritative only for its own level. availability: [Option>>; 6], availability_errors: [Option; 6], + /// Unit counts the catalogues landed so far couldn't be read, by level: said in one notice + /// once no level is still being read. + unread_counts: std::collections::BTreeMap, level_waiting: Vec<(usize, Answer)>, pub level: String, waiting: Option<(Asked, Answer)>, @@ -60,6 +63,7 @@ impl Default for State { country_search: Default::default(), availability: Default::default(), availability_errors: Default::default(), + unread_counts: Default::default(), level_waiting: Vec::new(), level: "ADM1".into(), waiting: None, @@ -85,8 +89,6 @@ fn fetch_catalogue(url: &str) -> Answer { /// Lands the answers. pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { - // Counts a catalogue gave that couldn't be read: said once per level, after the borrow. - let mut unread: Vec<(usize, usize)> = Vec::new(); app.ui.portals.level_waiting.retain(|(level, slot)| { let Some(result) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() else { ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -101,7 +103,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { *catalogue = Some(available); *error = None; if unreadable > 0 { - unread.push((*level, unreadable)); + app.ui.portals.unread_counts.insert(*level, unreadable); } } Err(reason) => { @@ -112,17 +114,20 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } false }); - for (level, n) in unread { - let level = level.to_string(); + // One notice for every catalogue's unreadable counts, once none is still being read. + if app.ui.portals.level_waiting.is_empty() && !app.ui.portals.unread_counts.is_empty() { + let unread = std::mem::take(&mut app.ui.portals.unread_counts); + let n: usize = unread.values().sum(); + let levels = unread.keys().map(|l| format!("ADM{l}")).collect::>().join(", "); let text = if n == 1 { crate::i18n::fmt( - "geoBoundaries ADM{level}: 1 country's unit count couldn't be read (not a non-negative whole number), so its level is offered without a count", - &[("level", &level)], + "geoBoundaries {levels}: 1 country's unit count couldn't be read (not a non-negative whole number), so its level is offered without a count", + &[("levels", &levels)], ) } else { crate::i18n::fmt( - "geoBoundaries ADM{level}: {n} countries' unit counts couldn't be read (not a non-negative whole number), so their levels are offered without a count", - &[("level", &level), ("n", &n.to_string())], + "geoBoundaries {levels}: {n} countries' unit counts couldn't be read (not a non-negative whole number), so their levels are offered without a count", + &[("levels", &levels), ("n", &n.to_string())], ) }; app.session.notify(text, false); @@ -500,6 +505,20 @@ mod tests { poll(&mut app, &egui::Context::default()); let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.first().is_some_and(|s| s.starts_with("geoBoundaries ADM2: 1 country's unit count couldn't be read")), "{said:?}"); + // Several levels with unreadable counts are said in one notice, once none is still read. + let pending = std::sync::Arc::new(std::sync::Mutex::new(None)); + app.ui.portals.level_waiting = + vec![(3, answer(Ok((list.to_vec(), Reach::Public)))), (4, answer(Ok((list.to_vec(), Reach::Public)))), (5, pending.clone())]; + let mark = app.session.notice_mark(); + poll(&mut app, &egui::Context::default()); + assert!(app.session.notices_since(mark).is_empty(), "one level is still being read"); + if let Ok(mut slot) = pending.lock() { + *slot = Some(Ok((b"[]".to_vec(), Reach::Public))); + } + poll(&mut app, &egui::Context::default()); + let said: Vec = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("geoBoundaries ADM3, ADM4: 2 countries' unit counts couldn't be read"), "{said:?}"); } /// Availability lands even with no dialog open and a failed level never disables choices.