Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion crates/tiles/src/boundaries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,34 @@ pub fn meta_url(country: &str, level: &str) -> String {

/// The address of every country's ADM0 entry (a list of countries).
pub fn countries_url() -> String {
format!("{API}/ALL/ADM0/")
catalogue_url("ADM0")
}

/// The address of all countries available at a validated administrative level.
pub fn level_url(level: &str) -> Result<String, String> {
Ok(catalogue_url(&self::level(level)?))
}

/// The shared address shape; callers supply a validated level or the fixed country level.
fn catalogue_url(level: &str) -> String {
format!("{API}/ALL/{level}/")
}

/// 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.
pub fn parse_availability(bytes: &[u8]) -> Result<std::collections::BTreeMap<String, Option<u64>>, String> {
let v: Value = serde_json::from_slice(bytes).map_err(|_| "the geoBoundaries list isn't JSON".to_string())?;
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| n.as_u64().or_else(|| n.as_str()?.parse().ok()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

admUnitCount values that aren't a non-negative integer (a float like 26.0, a negative number, a non-numeric string) become None, so the level shows its plain label with no count and no note. The unit count is optional, so this is not a crash or a wrong answer, but it is a field dropped without a word, which the "Never silent" rule asks to be said. Either accept the float form (n.as_f64() with a whole-number check) or leave it as is and say in the doc comment that a count that isn't a whole number is treated as absent. The test at line 137 covers the string and missing forms but not a malformed count.

Confidence: medium (depends on whether geoBoundaries ever sends non-integer counts).

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The count is optional display metadata: unsupported count forms leave the level offered without a count, while downloaded features and level availability are unchanged. I’m leaving the explicit documentation and malformed-count case for the release quality pass.

Ok((iso, count))
})
.collect()
}

/// A country's level, as the API describes it.
Expand Down Expand Up @@ -101,6 +128,21 @@ fn direct(url: &str) -> String {
mod tests {
use super::*;

#[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();
assert_eq!(parsed.get("PER"), Some(&Some(196)));
assert_eq!(parsed.get("CHE"), Some(&Some(26)));
assert_eq!(parsed.get("KEN"), Some(&None));
assert!(!parsed.contains_key("NZL"));
assert!(parse_availability(b"{}").is_err());
assert!(parse_availability(br#"[{"boundaryName":"Peru"}]"#).is_err());
assert!(parse_availability(br#"[{"boundaryISO":"?"}]"#).is_err());
assert_eq!(level_url("3").unwrap(), format!("{API}/ALL/ADM3/"));
assert!(level_url("ADM6").is_err());
}

#[test]
fn requests_and_answers() {
assert_eq!(country(" che ").unwrap(), "CHE");
Expand Down
229 changes: 217 additions & 12 deletions crates/ui-egui/src/portalsui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ pub struct State {
countries_asked: bool,
pub countries_error: Option<String>,
pub country: String,
country_filter: String,
/// Names as received, with their search text cached once per country list.
country_search: std::collections::BTreeMap<String, (String, String)>,
/// Each successful catalogue is authoritative only for its own level.
availability: [Option<std::collections::BTreeMap<String, Option<u64>>>; 6],
availability_errors: [Option<String>; 6],
level_waiting: Vec<(usize, Answer)>,
pub level: String,
waiting: Option<(Asked, Answer)>,
pub error: Option<String>,
Expand All @@ -49,6 +56,11 @@ impl Default for State {
countries_asked: false,
countries_error: None,
country: String::new(),
country_filter: String::new(),
country_search: Default::default(),
availability: Default::default(),
availability_errors: Default::default(),
level_waiting: Vec::new(),
level: "ADM1".into(),
waiting: None,
error: None,
Expand All @@ -63,8 +75,38 @@ fn fetch(url: &str, ceiling: Reach) -> Answer {
crate::fetch_within(url, cache::MAX_DOWNLOAD, None, ceiling)
}

/// Catalogues are small metadata lists, not feature downloads. Keep even an oversized service
/// answer bounded independently of the large data-download allowance.
const MAX_CATALOGUE: usize = 4 << 20;

fn fetch_catalogue(url: &str) -> Answer {
crate::fetch_within(url, MAX_CATALOGUE, None, Reach::Local)
}

/// Lands the answers.
pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) {
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));
return true;
};
let result = result.and_then(|(bytes, _)| boundaries::parse_availability(&bytes));
if let (Some(catalogue), Some(error)) =
(app.ui.portals.availability.get_mut(*level), app.ui.portals.availability_errors.get_mut(*level))
{
match result {
Ok(available) => {
*catalogue = Some(available);
*error = None;
}
Err(reason) => {
*catalogue = None;
*error = Some(reason);
}
}
}
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));
Expand Down Expand Up @@ -93,6 +135,8 @@ 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;
None
}
Expand Down Expand Up @@ -185,14 +229,40 @@ pub fn osm(app: &mut RustGisApp, ui: &mut egui::Ui) {
status(app, ui);
}

/// A successfully read catalogue is authoritative for its level. Unknown catalogues and
/// invalid or unfinished country codes leave the choices open for normal input validation.
fn level_info(st: &State, level: &str) -> (bool, Option<u64>) {
let Ok(country) = boundaries::country(&st.country) else {
return (true, None);
};
let catalogue =
level.strip_prefix("ADM").and_then(|n| n.parse::<usize>().ok()).and_then(|n| st.availability.get(n)).and_then(Option::as_ref);
match catalogue {
Some(c) => (c.contains_key(&country), c.get(&country).copied().flatten()),
None => (true, None),
}
}

/// Explains a disabled choice with the country's name when the country list is available.
fn missing_level(st: &State, level: &str) -> String {
let country = boundaries::country(&st.country).unwrap_or_else(|_| st.country.clone());
let name = st.countries.iter().find(|(iso, _)| *iso == country).map_or(country.as_str(), |(_, name)| name.as_str());
crate::i18n::fmt("geoBoundaries has no {level} for {country}", &[("level", level), ("country", name)])
}

/// Boundaries: a country's administrative areas at a level, from geoBoundaries.
pub fn boundaries(app: &mut RustGisApp, ui: &mut egui::Ui) {
ui.label(egui::RichText::new(tl!("A country's administrative boundaries from geoBoundaries (CC BY 4.0): the country itself (ADM0), its first-level divisions (ADM1, such as states) and finer ones.")).weak());
ui.label(egui::RichText::new(tl!("A country's administrative boundaries from geoBoundaries (CC BY 4.0): the country itself (ADM0), its first-level divisions (ADM1) and finer ones.")).weak());
let busy = app.ui.portals.waiting.is_some();
// The country list, asked for once.
if !app.ui.portals.countries_asked && !busy {
app.ui.portals.countries_asked = true;
app.ui.portals.waiting = Some((Asked::Countries, fetch(&boundaries::countries_url(), Reach::Local)));
for level in 1..=5 {
if let Ok(url) = boundaries::level_url(&level.to_string()) {
app.ui.portals.level_waiting.push((level, fetch_catalogue(&url)));
}
}
app.ui.portals.waiting = Some((Asked::Countries, fetch_catalogue(&boundaries::countries_url())));
}
if let Some(e) = &app.ui.portals.countries_error {
ui.label(egui::RichText::new(e).small().weak());
Expand All @@ -203,23 +273,38 @@ pub fn boundaries(app: &mut RustGisApp, ui: &mut egui::Ui) {
if st.countries.is_empty() {
ui.add(egui::TextEdit::singleline(&mut st.country).hint_text("CHE").desired_width(260.0)).labelled_by(input_label.id);
} else {
let selected = boundaries::country(&st.country).ok();
let shown = st
.countries
.iter()
.find(|(iso, _)| *iso == st.country)
.find(|(iso, _)| Some(iso.as_str()) == selected.as_deref())
.map(|(iso, n)| format!("{n} ({iso})"))
.unwrap_or_else(|| tl!("Choose a country").to_string());
egui::ComboBox::from_id_salt("gb_country")
.selected_text(shown)
.width(260.0)
.height(360.0)
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show_ui(ui, |ui| {
ui.add(egui::TextEdit::singleline(&mut st.country_filter).hint_text(tl!("Search countries")))
.labelled_by(input_label.id);
let needle = st.country_filter.trim().to_lowercase();
for (iso, name) in &st.countries {
ui.selectable_value(&mut st.country, iso.clone(), format!("{name} ({iso})"));
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 {
continue;
}
if ui.selectable_value(&mut st.country, iso.clone(), format!("{name} ({iso})")).clicked() {
ui.close();
}
}
})
.response
.on_hover_text(tl!("Country"));
.labelled_by(input_label.id);
}
ui.end_row();
let input_label = ui.label(tl!("Level"));
Expand All @@ -229,20 +314,55 @@ pub fn boundaries(app: &mut RustGisApp, ui: &mut egui::Ui) {
.show_ui(ui, |ui| {
for (l, label) in [
("ADM0", "ADM0 — the country"),
("ADM1", "ADM1 — states, provinces"),
("ADM2", "ADM2 — districts, counties"),
("ADM3", "ADM3"),
("ADM4", "ADM4"),
("ADM5", "ADM5"),
("ADM1", "ADM1 — first-level divisions"),
("ADM2", "ADM2 — second-level divisions"),
("ADM3", "ADM3 — third-level divisions"),
("ADM4", "ADM4 — fourth-level divisions"),
("ADM5", "ADM5 — fifth-level divisions"),
] {
ui.selectable_value(&mut st.level, l.to_string(), tl!(label));
let (available, count) = level_info(st, l);
let shown = count.map_or_else(
|| tl!(label).to_string(),
|n| {
let key = if n == 1 { "{level} — {count} unit" } else { "{level} — {count} units" };
crate::i18n::fmt(key, &[("level", l), ("count", &n.to_string())])
},
);
let response = ui.add_enabled(available, egui::Button::selectable(st.level == l, shown));
if response.clicked() {
st.level = l.to_string();
}
if !available {
response.on_disabled_hover_text(missing_level(st, l));
}
}
})
.response
.labelled_by(input_label.id);
ui.end_row();
});
if ui.add_enabled(!busy, egui::Button::new(tl!("Add"))).clicked() {
let st = &app.ui.portals;
let (available, _) = level_info(st, &st.level);
if let Some(error) = st
.level
.strip_prefix("ADM")
.and_then(|n| n.parse::<usize>().ok())
.and_then(|n| st.availability_errors.get(n))
.and_then(Option::as_ref)
{
ui.small(crate::i18n::fmt(
"Availability for {level} couldn't be read ({error}); this level remains offered without unit counts.",
&[("level", &st.level), ("error", error)],
));
}
if !available {
ui.small(missing_level(st, &st.level));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor nits, grouped:

  • The loop at line 260 uses if let Ok(url) = boundaries::level_url(...). level_url can't fail for 1..=5, so the Err arm is dead. Building the URL from catalogue_url through a loop over ["ADM1", …, "ADM5"] or stating the expectation with expect isn't allowed here, so the simplest is a filter_map with a comment, or just boundaries::level_url(&level.to_string()) mapped with a clear reason.
  • The same disabled reason is shown twice for the selected level: the ui.small(missing_level(...)) note here and the Add button's disabled hover text at line 363. One is enough.

These are quality points and can wait for the release quality pass.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the inline reason makes it available without hovering a disabled control, including to keyboard and screen-reader users; the hover also explains the button state in context. The guarded call to the shared fallible URL helper handles the fixed range without a panic. I’ll retain both choices.

}
if ui
.add_enabled(!busy && available, egui::Button::new(tl!("Add")))
.on_disabled_hover_text(if available { tl!("Downloading…").to_string() } else { missing_level(st, &st.level) })
.clicked()
{
let st = &app.ui.portals;
match boundaries::country(&st.country).and_then(|c| Ok((c, boundaries::level(&st.level)?))) {
Ok((c, l)) => {
Expand All @@ -261,6 +381,91 @@ mod tests {
use super::*;
use rustgis_engine::render::rustgis_tiles::address::Origin;

/// Exercises the actual Web Data pane: normalized typed codes, disabled levels and
/// country filtering retain their accessible labels and affect the Add action.
#[test]
fn boundary_picker_filters_and_keeps_typed_codes_available() {
use egui_kittest::kittest::{By, NodeT, Queryable};
let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default()));
app.ui.portals.countries_asked = true;
app.ui.portals.country = " per ".into();
app.ui.portals.availability[1] = Some(std::collections::BTreeMap::from([("PER".into(), Some(26))]));
app.ui.portals.availability[3] = Some(Default::default());
app.run("ui.dialog", json!({"name":"boundaries"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut RustGisApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run();
assert!(!h.get_by_label("Add").accesskit_node().is_disabled());
h.get_by_label("Level").click();
h.run();
assert!(!h.get_by_label("ADM1 — 26 units").accesskit_node().is_disabled());
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())];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The picker test sets countries directly, so country_search (the cache that poll fills when the list arrives, line 138) stays empty. Only the fallback format!(...).to_lowercase() path is exercised. The cached path, including its filter(|(original, _)| original == name) guard, that real sessions take on every frame has no test. Suggest one setter that both poll and tests call, so the cache is always built with the list, and an assertion on a match through the cached path (e.g. filtering "per" finds Peru through the cache).

Confidence: high that the cached path is untested; the risk is a regression that the current tests would not catch.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cached-path coverage is a useful addition. The current fallback also supports callers that supply or change the public country list directly. I’m leaving the additional cache-path test for the release quality pass.

h.step();
h.get_by_label("Country").click();
h.run();
let input = h.get(By::new().role(egui::accesskit::Role::TextInput).label("Country"));
input.click();
h.run();
h.get(By::new().role(egui::accesskit::Role::TextInput).label("Country")).type_text("pol");
h.run();
assert!(h.query_by_label("Peru (PER)").is_none());
h.get_by_label("Poland (POL)").click();
h.run();
assert_eq!(h.state().ui.portals.country, "POL");
assert!(h.get_by_label("Add").accesskit_node().is_disabled());
}

/// Availability lands even with no dialog open and a failed level never disables choices.
#[test]
fn availability_lands_independently_of_boundary_downloads() {
use egui_kittest::kittest::Queryable;
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)));
app.ui.portals.level_waiting = vec![
(2, answer(Ok((br#"[{"boundaryISO":"PER","admUnitCount":"196"}]"#.to_vec(), Reach::Public)))),
(3, answer(Ok((b"[]".to_vec(), Reach::Public)))),
(4, answer(Err("offline".to_string()))),
(5, answer(Ok((b"{}".to_vec(), Reach::Public)))),
];
poll(&mut app, &egui::Context::default());
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());
assert_eq!(app.ui.portals.availability_errors[4].as_deref(), Some("offline"));
assert_eq!(app.ui.portals.availability_errors[5].as_deref(), Some("the geoBoundaries list isn't a list"));
assert!(app.ui.portals.level_waiting.is_empty());
app.ui.portals.countries_asked = true;
app.ui.portals.country = "PER".into();
app.run("ui.dialog", json!({"name":"boundaries"})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut RustGisApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run();
assert!(h.query_by_label_contains("couldn't be read").is_none());
for (level, reason) in [("ADM4", "offline"), ("ADM5", "the geoBoundaries list isn't a list")] {
h.state_mut().ui.portals.level = level.into();
h.run();
let note = crate::i18n::fmt(
"Availability for {level} couldn't be read ({error}); this level remains offered without unit counts.",
&[("level", level), ("error", reason)],
);
assert!(h.query_by_label(&note).is_some(), "{note}");
assert!(level_info(&h.state().ui.portals, level).0);
}
}

/// The boundaries geoBoundaries' description names are read within the reach the description
/// was read at: only from the internet when it came from there; from a description read on the
/// local network (a mirror at its name), from a private address too.
Expand Down
7 changes: 5 additions & 2 deletions docs/user-guide/web-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -494,8 +494,11 @@ a larger area is better read from an extract (`.osm.pbf`). `"url"` names another
when the public one is busy.

**Home › Add › Web Data › Boundaries…** (`boundaries.add`) adds a country's administrative boundaries from
[geoBoundaries](https://www.geoboundaries.org) (CC BY 4.0): the country itself (`ADM0`), its states
or provinces (`ADM1`) and finer divisions down to `ADM5` where they exist, simplified for the map.
[geoBoundaries](https://www.geoboundaries.org) (CC BY 4.0): the country itself (`ADM0`), its first-level
divisions (`ADM1`) and finer divisions down to `ADM5` where they exist, simplified for the map.
Filter the country list by name or ISO code. Once a level's catalogue arrives, its unit count is
shown and levels unavailable for the country are disabled with a reason. If a catalogue cannot be
read, its levels remain offered and the selected level shows why its availability is unknown.
`boundaries.countries` lists the countries.

```sh
Expand Down
Loading