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
154 changes: 127 additions & 27 deletions crates/ui-egui/src/mapview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,14 @@ pub struct Popup {
pub opened: u64,
/// The WMS layers being asked what is at the point, whose features join the list.
pub asks: Vec<Ask>,
/// When it opened: it waits for the WMS layers' answers up to [`ASK_WAIT`] from then.
since: web_time::Instant,
}

/// How long a pop-up waits for the WMS layers asked before it shows what was found: then their
/// answers join it as they come.
const ASK_WAIT: std::time::Duration = std::time::Duration::from_secs(4);

/// A WMS layer asked what is at a popup's point (GetFeatureInfo), its answer on the way: the
/// request's, or first its service's capabilities (a layer from a project doesn't know its request).
pub struct Ask {
Expand Down Expand Up @@ -123,7 +129,14 @@ impl Popup {
let request = (!capabilities).then(|| url.to_string());
asks.push(Ask { layer, also: Vec::new(), capabilities, request, slot });
}
Popup { info, at, index: 0, map, opened, asks }
Popup { info, at, index: 0, map, opened, asks, since: web_time::Instant::now() }
}

/// Whether it waits for the WMS layers asked, to show their answers and what was found
/// together, in drawing order: a layer drawn over the feature found may answer, and take its
/// place.
fn asking(&self) -> bool {
!self.asks.is_empty() && self.since.elapsed() < ASK_WAIT
Comment thread
pick2510 marked this conversation as resolved.
Resolved
}
}

Expand Down Expand Up @@ -160,7 +173,8 @@ fn with_answers(map: &rustgis_engine::map::Map, info: &Value, found: Vec<Value>)
let mut all = results_of(info);
all.extend(found);
// A tile layer's results show while it draws: one hidden since must not keep a later answer
// out. Of two layers of one name, the one drawn is the one asked.
// out. Of two layers of one name, the answers are placed by the one drawn (though
// identify.featureInfo tells its answer to the first of them, drawn or not).
let drawn = |name: &str| map.tiles.iter().position(|t| t.name == name && t.draws());
all.retain(|v| v["tileLayer"].as_str().is_none_or(|name| drawn(name).is_some()));
let stack = map.stack();
Expand Down Expand Up @@ -2999,7 +3013,8 @@ fn follow_popup(app: &mut RustGisApp) {
let here: Vec<bool> = results
.iter()
.map(|r| match home(r) {
Home::NoLayer => true,
// A tile layer's answer, while the layer draws (as `with_answers` keeps them).
Home::NoLayer => r["tileLayer"].as_str().is_none_or(|name| map.tiles.iter().any(|t| t.name == name && t.draws())),
Comment thread
pick2510 marked this conversation as resolved.
Resolved
Home::LayerGone => false,
// A streamed layer holds a window of its features: one outside it isn't gone.
Home::Layer(l) => r["fid"].as_u64().is_none_or(|fid| l.dataset.windowed || found.contains(&(l.id, fid))),
Expand Down Expand Up @@ -3098,17 +3113,28 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) {
}
let Some(pp) = &mut app.map.popup else { return };
pp.asks.extend(next);
Comment thread
pick2510 marked this conversation as resolved.
Resolved
// Answers that land while the pop-up waits for them: it shows nothing yet, so it opens on the
// top result, and selects its feature.
let waited = pp.since.elapsed() < ASK_WAIT;
Comment thread
pick2510 marked this conversation as resolved.
Resolved
Comment thread
pick2510 marked this conversation as resolved.
Resolved
if !found.is_empty()
&& let Some(info) = with_answers(app.session.map(), &pp.info, found)
{
// The result shown stays shown, wherever the answers went; the first when it was left out
// (a layer drawn higher answered, with topmost).
let before = results_of(&pp.info);
// As the pop-up shows it: an index past the end is the last result.
let index = pp.index.min(before.len().saturating_sub(1));
pp.index = index_after(&before, index, info["results"].as_array().map_or(&[][..], Vec::as_slice));
if waited {
pp.index = 0;
} else {
// The result shown stays shown, wherever the answers went; the first when it was left
// out (a layer drawn higher answered, with topmost).
let before = results_of(&pp.info);
// As the pop-up shows it: an index past the end is the last result.
let index = pp.index.min(before.len().saturating_sub(1));
pp.index = index_after(&before, index, info["results"].as_array().map(Vec::as_slice).unwrap_or_default());
}
pp.info = info;
if waited {
select_shown(app);
}
}
let Some(pp) = &mut app.map.popup else { return };
if pp.asks.is_empty() && !is_found(&pp.info) {
app.map.popup = None;
}
Expand All @@ -3123,14 +3149,22 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) {
if !rect.contains(anchor) {
return;
}
let results = pp.info["results"].as_array().map_or(0, Vec::len);
// Waiting for the WMS layers' answers, it shows none of the results yet.
let asking = pp.asking();
let results = if asking { 0 } else { pp.info["results"].as_array().map_or(0, Vec::len) };
let index = pp.index.min(results.saturating_sub(1));
let info = if results > 1 { pp.info["results"][index].clone() } else { pp.info.clone() };
let info = if asking {
Value::Null
} else if results > 1 {
pp.info["results"][index].clone()
} else {
pp.info.clone()
};
let mut step: Option<usize> = None;
let mut zoom = false;
// The feature shown, as its layer id and feature id (a raster pixel has neither).
let shown = info["layerId"].as_u64().and_then(|id| u32::try_from(id).ok()).zip(info["fid"].as_u64());
// Only WMS layers being asked so far: their names.
// Only WMS layers being asked so far, or still waited for: their names.
let waiting = !is_found(&info);
let layer = if waiting {
pp.asks.iter().map(|a| a.layer.as_str()).collect::<Vec<_>>().join(", ")
Expand Down Expand Up @@ -3305,22 +3339,27 @@ fn popup(app: &mut RustGisApp, ui: &mut Ui, rect: Rect) {
app.map.popup = None;
} else if let (Some(i), Some(pp)) = (step, &mut app.map.popup) {
pp.index = i;
// The feature shown is the one selected, as after the click. Not through `select.rows`:
// browsing a pop-up mustn't fill the undo history; the new revision redraws the map.
// Found again by its feature id: a streamed layer may have read another window since the
// click, moving the feature to another row (or out of the layer: then nothing is selected).
let shown = pp.info["results"].get(i).and_then(|r| Some((u32::try_from(r["layerId"].as_u64()?).ok()?, r["fid"].as_u64()?)));
let found = shown.and_then(|(id, fid)| {
let row = app.session.map().layer(id)?.dataset.features.iter().position(|f| f.id == fid)?;
Some((id, row))
});
if let Some((id, row)) = found {
rustgis_engine::cmd::select::set(&mut app.session, id, vec![row], rustgis_engine::cmd::select::Mode::New);
} else {
app.session.map_mut().clear_selection();
}
app.session.revision = app.session.revision.wrapping_add(1);
select_shown(app);
}
}

/// Selects the feature the pop-up shows, as after the click. Not through `select.rows`: browsing
/// a pop-up mustn't fill the undo history; the new revision redraws the map. Found again by its
/// feature id: a streamed layer may have read another window since the click, moving the feature
/// to another row (or out of the layer: then nothing is selected).
fn select_shown(app: &mut RustGisApp) {
let Some(pp) = &app.map.popup else { return };
let shown = pp.info["results"].get(pp.index).and_then(|r| Some((u32::try_from(r["layerId"].as_u64()?).ok()?, r["fid"].as_u64()?)));
let found = shown.and_then(|(id, fid)| {
let row = app.session.map().layer(id)?.dataset.features.iter().position(|f| f.id == fid)?;
Some((id, row))
});
if let Some((id, row)) = found {
rustgis_engine::cmd::select::set(&mut app.session, id, vec![row], rustgis_engine::cmd::select::Mode::New);
} else {
app.session.map_mut().clear_selection();
}
app.session.revision = app.session.revision.wrapping_add(1);
}

/// Whether an attribute value is a picture (a `data:image/png` or `jpeg` address, as a photo's
Expand Down Expand Up @@ -3987,6 +4026,52 @@ mod tests {
assert_eq!(index_after(&before, 5, &after), 0);
}

/// A pop-up asking a WMS layer waits for its answer, up to `ASK_WAIT`, before it shows what
/// was found, so a layer drawn over the feature found doesn't take its place once shown; with
/// nothing asked, it shows at once.
#[test]
fn a_popup_waits_for_the_wms_answers_a_while() {
let found = json!({"layer": "Countries", "attributes": {"name": "Switzerland"}});
let mut pp = Popup::new(found, Coord::new(8.6, 46.65), 0, 0);
assert!(!pp.asking(), "nothing asked");
pp.asks.push(Ask { layer: "Over".into(), also: Vec::new(), capabilities: false, request: None, slot: Default::default() });
assert!(pp.asking(), "asked");
if let Some(earlier) = web_time::Instant::now().checked_sub(ASK_WAIT) {
Comment thread
pick2510 marked this conversation as resolved.
Resolved
pp.since = earlier;
assert!(!pp.asking(), "waited long enough");
Comment thread
pick2510 marked this conversation as resolved.
Resolved
}
Comment thread
pick2510 marked this conversation as resolved.
Resolved
}

/// Answers that land while the pop-up waits open it on the top result, with its feature
/// selected: drawn over Countries, Over's feature comes first, and Switzerland, selected by the
/// click, no longer is.
#[test]
fn a_popup_opens_on_the_top_result_after_its_wait() {
let mut s = rustgis_engine::Session::new(rustgis_engine::sample::world_project());
let url = "https://wms.example.org/?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=over&STYLES=&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image%2Fpng";
s.run("map.addTiles", &json!({"url": url, "name": "Over", "overlay": true})).unwrap();
s.run("map.popupMode", &json!({"mode": "visible"})).unwrap();
let mut info = s.run("identify", &json!({"lon": 8.6, "lat": 46.65, "tolerancePx": 0})).unwrap();
assert_eq!(info["layer"], "Countries");
assert_eq!(info["featureInfo"][0]["tileLayer"], "Over", "{info}");
s.run("select.rows", &json!({"layer": info["layerId"], "rows": [info["row"]]})).unwrap();
// Its answer already in, not fetched.
info.as_object_mut().unwrap().remove("featureInfo");
let (map, opened) = (s.project.active_map, s.opened);
let mut app = RustGisApp::new(s);
let mut pp = Popup::new(info, Coord::new(8.6, 46.65), map, opened);
let answer = br#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Bern"},"geometry":null}]}"#;
let slot = std::sync::Arc::new(std::sync::Mutex::new(Some(Ok(answer.to_vec()))));
pp.asks.push(Ask { layer: "Over".into(), also: Vec::new(), capabilities: false, request: None, slot });
app.map.popup = Some(pp);
follow_asks(&mut app, &egui::Context::default());
let pp = app.map.popup.as_ref().unwrap();
let shown: Vec<_> =
pp.info["results"].as_array().unwrap().iter().map(|r| r["tileLayer"].as_str().or(r["layer"].as_str()).unwrap()).collect();
assert_eq!((shown, pp.index), (vec!["Over", "Countries"], 0));
assert!(app.session.map().layer_by_name("Countries").unwrap().selection.is_empty());
}

/// A WMS layer's answer comes in the drawing order (#808): drawn over Countries, its feature
/// comes first, and with topmost replaces Switzerland; drawn under the map's layers, it comes
/// after them, and topmost keeps Switzerland.
Expand Down Expand Up @@ -4027,6 +4112,21 @@ mod tests {
s.map_mut().tiles.iter_mut().filter(|t| t.name == "Over").for_each(|t| t.visible = false);
let v = with_answers(s.map(), &over, vec![answer("Under")]).unwrap();
assert_eq!(shown(&v), ["Countries", "Under"], "hidden, visible");
// Hidden with its result in the pop-up and no answer to come: the result goes at once.
s.map_mut().tiles.iter_mut().filter(|t| t.name == "Over").for_each(|t| t.visible = true);
let (map, opened) = (s.project.active_map, s.opened);
let mut app = RustGisApp::new(s);
let mut popup = Popup::new(over, Coord::new(8.6, 46.65), map, opened);
popup.index = 1;
app.map.popup = Some(popup);
app.map.popup_rev = app.session.revision.wrapping_add(1);
follow_popup(&mut app);
assert_eq!(shown(&app.map.popup.as_ref().unwrap().info), ["Over", "Countries"], "drawn, in the pop-up");
app.session.map_mut().tiles.iter_mut().filter(|t| t.name == "Over").for_each(|t| t.visible = false);
app.map.popup_rev = app.session.revision.wrapping_add(1);
follow_popup(&mut app);
let popup = app.map.popup.as_ref().unwrap();
assert_eq!((shown(&popup.info), popup.index), (vec!["Countries".to_string()], 0), "hidden, in the pop-up");
}

fn selection_harness() -> egui_kittest::Harness<'static, RustGisApp> {
Expand Down
10 changes: 7 additions & 3 deletions docs/user-guide/editing.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,17 @@ buildings`) and its attributes; tile features can't be selected or zoomed to.
They ask WMS layers too (WMS tile layers that are shown and, as far as their service's
capabilities say, queryable): RustGIS sends the service a standard GetFeatureInfo request for the
point (WMS 1.3.0 or 1.1.1, as in the layer's address), asking for GeoJSON when it offers it, else
GML, other XML, plain text or HTML, and the features it answers join the pop-up as they arrive.
GML, other XML, plain text or HTML. While it asks, the pop-up says "Asking the map service…".
When something else is under the click, it waits up to 4 seconds for every layer asked to answer,
then shows the features found and answered together, in drawing order; answers that come later
join it as they arrive. When nothing else is, it waits until an answer has features, and closes
once every layer asked has answered (or failed) without any.
When the service answers with an error in that format (swisstopo's MapServer can't write some of
its layers as GeoJSON, but answers them in GML), RustGIS asks again in the next format it offers,
and keeps asking that layer in it for the rest of the session.
Topmost asks only the highest WMS layer that can be asked at the point (one that covers it and is
queryable), and only when no feature of the map's own layers or of its vector tile layers is under
the click. A project doesn't save the request: a WMS layer from a project reads its service's
queryable), and only when it is drawn over the feature found, or nothing was found; its features
then take that feature's place. A project doesn't save the request: a WMS layer from a project reads its service's
Comment thread
pick2510 marked this conversation as resolved.
Resolved
capabilities again on its first click (once for all the map's layers from that service), so until
then Topmost takes it as one that can be asked.
`identify` lists the requests in `featureInfo`, and `identify.featureInfo` reads an answer (or, on
Expand Down
Loading