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
6 changes: 4 additions & 2 deletions crates/assistant/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4062,12 +4062,14 @@ fn list_layers_includes_web_tile_layers() {
assert!(radar.is_some_and(|t| t["url"].as_str().is_some_and(|u| u.contains("LAYERS=a") && !u.contains("s3cret"))), "{out}");
assert!(s.run("map.tiles", &Value::Null).unwrap().to_string().contains("apikey=s3cret"));
let ctx = tools::context(&s);
assert!(ctx.contains("\"Rain radar\" (index ") && ctx.contains("raster, overlay, hidden)"), "{ctx}");
// On top of the map's layers, as a new layer goes (#808): over Cities.
assert!(ctx.contains("\"Rain radar\" (index ") && ctx.contains("raster, overlay, over \"Cities\", hidden)"), "{ctx}");
assert_eq!(radar.map(|t| t["over"].clone()), Some(json!("Cities")), "{out}");
// A long name (commands and project files cap them, but not everything that builds a map) is
// cut, not the index and flags after it.
if let Some(t) = s.map_mut().tiles.iter_mut().find(|t| t.name == "Rain radar") {
t.name = "r".repeat(5000);
}
let ctx = tools::context(&s);
assert!(ctx.contains("characters in all)\" (index ") && ctx.contains("raster, overlay, hidden)"), "{ctx}");
assert!(ctx.contains("characters in all)\" (index ") && ctx.contains("raster, overlay, over \"Cities\", hidden)"), "{ctx}");
}
9 changes: 7 additions & 2 deletions crates/assistant/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub fn defs() -> Vec<ToolDef> {
vec![
ToolDef {
name: "list_layers",
description: "Everything about the open project in one call: its path and unsaved changes, the view (centre, lon/lat extent, scale, projection), the active layer, its layers in table-of-contents order, top first (id, name, group, type, source, lon/lat extent, feature count, selection, definition query, renderer, labels, fields, visibility), its web tile layers (XYZ, WMS, vector tiles; index 0 on top, changed with map.setTiles), basemap, tables and layouts with their map frames.",
description: "Everything about the open project in one call: its path and unsaved changes, the view (centre, lon/lat extent, scale, projection), the active layer, its layers in table-of-contents order, top first (id, name, group, type, source, lon/lat extent, feature count, selection, definition query, renderer, labels, fields, visibility), its web tile layers (XYZ, WMS, vector tiles; index 0 on top, each with the layer it's drawn over, changed with map.setTiles), basemap, tables and layouts with their map frames.",
schema: json!({
"type": "object",
"properties": {
Expand Down Expand Up @@ -721,14 +721,19 @@ pub fn context(s: &Session) -> String {
out.push_str(&format!("\n… and {} more (list_layers lists them all).", m.layers.len() - 60));
}
if !m.tiles.is_empty() {
out.push_str("\nWeb tile layers under them (top first, index for map.setTiles):");
out.push_str("\nWeb tile layers (top first, index for map.setTiles), each drawn over the layer it names, or under them all:");
}
let slots = m.tile_slots();
for (i, t) in m.tiles.iter().enumerate() {
// The name is clipped, not the line: the index and flags after it are what the model needs.
let mut line = format!("\n- \"{}\" (index {i}, {}", clip(&t.name, 200), t.kind.code());
if t.overlay {
line.push_str(", overlay");
}
match slots.get(i).copied().flatten().and_then(|id| m.layer(id)) {
Some(l) => line.push_str(&format!(", over \"{}\"", clip(&l.name, 200))),
None => line.push_str(", under the layers"),
}
if !t.visible {
line.push_str(", hidden");
} else if let Some(e) = &t.error {
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ fn move_group(s: &mut Session, p: &Value) -> CmdResult {

fn ungroup(s: &mut Session, p: &Value) -> CmdResult {
let id = group_id(s.map(), p)?;
// The tile layers over the group stay over its layers, where they were.
s.map_mut().settle_tiles();
s.map_mut().groups.retain(|g| g.id != id);
Ok(Value::Null)
}
Expand Down
7 changes: 6 additions & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,10 @@ fn template(p: &Project) -> Project {
rl.embedded = None;
}
}
m.layers.retain(|l| !l.is_raster() || l.raster.as_ref().is_some_and(|r| r.path.is_some()));
let dropped: Vec<u32> =
m.layers.iter().filter(|l| l.is_raster() && l.raster.as_ref().is_none_or(|r| r.path.is_none())).map(|l| l.id).collect();
m.release_tiles(&dropped);
m.layers.retain(|l| !dropped.contains(&l.id));
}
for t in &mut t.tables {
t.features.clear();
Expand Down Expand Up @@ -565,6 +568,8 @@ fn package_map(s: &Session, mobile: bool, tol: f64) -> Result<Vec<u8>, String> {
if mobile {
// Groups folded into their layers: a hidden group's layers are dropped with the others.
m.bake_groups();
let hidden: Vec<u32> = m.layers.iter().filter(|l| !l.visible).map(|l| l.id).collect();
m.release_tiles(&hidden);
m.layers.retain(|l| l.visible);
for l in &mut m.layers {
if l.is_raster() || tol <= 0.0 {
Expand Down
12 changes: 8 additions & 4 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -964,7 +964,7 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult {
return Err(format!("{path}: the web app reads PMTiles archives from web addresses (Home › Add › Basemap › Add Tile Layer)"));
}
let full = std::path::absolute(path).map(|p| p.display().to_string()).map_err(|e| format!("{path}: {e}"))?;
let mut q = json!({"url": full, "kind": "pmtiles"});
let mut q = json!({"url": full, "kind": "pmtiles", "top": true});
if let Some(n) = ps(p, "name") {
q["name"] = json!(n);
}
Expand All @@ -978,7 +978,7 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult {
let full = std::path::absolute(path).map(|p| p.display().to_string()).map_err(|e| format!("{path}: {e}"))?;
// Read now, so a file that isn't an archive is said at once rather than when it draws.
crate::render::rustgis_tiles::mbtiles::info(&full)?;
let mut q = json!({"url": full, "kind": "mbtiles"});
let mut q = json!({"url": full, "kind": "mbtiles", "top": true});
if let Some(n) = ps(p, "name") {
q["name"] = json!(n);
}
Expand Down Expand Up @@ -2418,7 +2418,7 @@ pub(crate) fn add_url(s: &mut Session, p: &Value) -> CmdResult {
if scan {
return Err(format!("{url}: a PMTiles archive is tiles, not a picture: it can't be opened as a scan"));
}
let mut q = json!({"url": url, "kind": "pmtiles"});
let mut q = json!({"url": url, "kind": "pmtiles", "top": true});
if let Some(n) = ps(p, "name") {
q["name"] = json!(n);
}
Expand Down Expand Up @@ -2522,7 +2522,7 @@ pub fn is_tiff_url(url: &str) -> bool {
pub(crate) fn add_cog(s: &mut Session, p: &Value, url: &str) -> CmdResult {
let stem = cog_name(url);
let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&stem);
let mut q = json!({"url": url, "kind": "cog", "name": name});
let mut q = json!({"url": url, "kind": "cog", "name": name, "top": true});
// A dated address's span and steps (see map.addTiles).
for k in ["start", "end", "unit", "interval", "dates"] {
if let Some(v) = p.get(k) {
Expand Down Expand Up @@ -2725,6 +2725,8 @@ pub(crate) fn legends_follow_layer(s: &mut Session, old: &str, new: Option<&str>
pub(crate) fn drop_layers(s: &mut Session, ids: &[u32]) {
let m = s.map_mut();
let names: Vec<String> = m.layers.iter().filter(|l| ids.contains(&l.id)).map(|l| l.name.clone()).collect();
// The tile layers drawn over them keep their place.
m.release_tiles(ids);
m.layers.retain(|l| !ids.contains(&l.id));
for n in &names {
legends_follow_layer(s, n, None);
Expand All @@ -2736,6 +2738,8 @@ fn remove(s: &mut Session, p: &Value) -> CmdResult {
let m = s.map_mut();
// The layer that takes the place of the topmost one removed becomes the active layer.
let at = ids.iter().filter_map(|id| m.layer_index(*id)).min().ok_or("no such layer")?;
// The tile layers drawn over them keep their place.
m.release_tiles(&ids);
let mut names = Vec::new();
for id in ids {
if let Some(i) = m.layer_index(id) {
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,8 @@ fn info(s: &mut Session, p: &Value) -> CmdResult {
"id": g.id, "name": g.name, "visible": g.visible, "transparency": g.transparency,
"minScale": g.min_scale, "maxScale": g.max_scale, "layers": g.children,
})).collect::<Vec<_>>(),
// Web tile layers (XYZ, WMS, vector tiles, styles, archives) draw under the layers above.
// Web tile layers (XYZ, WMS, vector tiles, styles, archives), each drawn over the map layer
// its `over` names, or under them all.
// Their addresses lose keys and tokens: the AI Assistant sends this to its provider.
"tileLayers": super::tiles::list(s, true),
"tables": s.project.tables.iter().filter(|t| named(&t.name)).map(|t| {
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ pub(crate) fn add_named_bytes(s: &mut Session, p: &Value, name: String, bytes: V
// An MBTiles archive: held in memory and drawn as a tile layer.
if rustgis_data::mbtiles::is_mbtiles_name(&name) {
let url = crate::render::rustgis_tiles::mbtiles::register(&name, &bytes)?;
let mut q = json!({"url": url, "kind": "mbtiles"});
let mut q = json!({"url": url, "kind": "mbtiles", "top": true});
if let Some(n) = ps(p, "name") {
q["name"] = json!(n);
}
Expand Down
58 changes: 44 additions & 14 deletions crates/engine/src/cmd/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,14 +320,35 @@ fn identify(s: &mut Session, p: &Value) -> CmdResult {
None => Vec::new(),
};
let map = s.map();
let mut results: Vec<Value> = hits.iter().filter_map(|(id, row)| feature_json(map, *id, *row)).collect();
// Then the features of vector tile layers, beneath the layers; tiles are never selectable.
if matches!(mode, PopupMode::Topmost | PopupMode::Visible) && (!first_layer || results.is_empty()) {
let room = MAX_IDENTIFIED.saturating_sub(results.len());
results.extend(tile_features(s, lon, lat, tol_px, first_layer, room));
// Features and the vector tile layers' features (tiles are never selectable), in the drawing
// order of all the map's layers (#808): topmost takes the layer drawn on top of those with any.
let order = map.stack();
let place = |d: rustgis_map::Drawn| order.iter().position(|o| *o == d).unwrap_or(usize::MAX);
let mut ranked: Vec<(usize, Value)> = hits
.iter()
.filter_map(|(id, row)| Some((place(rustgis_map::Drawn::Layer(map.layer_index(*id)?)), feature_json(map, *id, *row)?)))
.collect();
let web = matches!(mode, PopupMode::Topmost | PopupMode::Visible);
if web {
// Topmost reads only those drawn over the feature found, up to the first with any.
let found = ranked.iter().map(|(at, _)| *at).min().unwrap_or(usize::MAX);
let keep = |i: usize| !first_layer || place(rustgis_map::Drawn::Tile(i)) < found;
let tiles = tile_features(s, lon, lat, tol_px, MAX_IDENTIFIED, first_layer, keep);
ranked.extend(tiles.into_iter().map(|(i, v)| (place(rustgis_map::Drawn::Tile(i)), v)));
}
// And the WMS layers drawn there are asked (their answers come later).
let asks = if matches!(mode, PopupMode::Topmost | PopupMode::Visible) && (!first_layer || results.is_empty()) {
ranked.sort_by_key(|(at, _)| *at);
let top = ranked.first().map(|(at, _)| *at);
if first_layer {
ranked.retain(|(at, _)| Some(*at) == top);
}
ranked.truncate(MAX_IDENTIFIED);
let results: Vec<Value> = ranked.into_iter().map(|(_, v)| v).collect();
// And the WMS layers drawn there are asked (their answers come later): for topmost, when
// nothing was found, or the topmost one there has a place over what was (a tile layer under
// all the map's layers, as all were before #808, isn't asked over what they found).
let over_top =
|i: usize| map.tiles.get(i).is_some_and(|t| t.over.is_some()) && top.is_some_and(|top| place(rustgis_map::Drawn::Tile(i)) < top);
let asks = if web && (!first_layer || results.is_empty() || info::topmost(s, lon, lat).is_some_and(over_top)) {
info::requests(s, lon, lat, first_layer)
} else {
Vec::new()
Expand Down Expand Up @@ -355,18 +376,27 @@ fn identify(s: &mut Session, p: &Value) -> CmdResult {
Ok(out)
}

/// The features of the vector tile layers drawn under a point, topmost layer first (only the
/// first layer with any when `first_layer`): archives, vector tiles and overlays added as data,
/// not basemaps from the catalog or MapLibre styles. The tiles looked at are those drawn there.
fn tile_features(s: &Session, lon: f64, lat: f64, tol_px: f64, first_layer: bool, limit: usize) -> Vec<Value> {
/// The features of the vector tile layers drawn under a point, topmost layer first, each with
/// its tile layer's index (only those `keep` takes; only the first layer with any when
/// `first_layer`): archives, vector tiles and overlays added as data, not basemaps from the
/// catalog or MapLibre styles. The tiles looked at are those drawn there.
fn tile_features(
s: &Session,
lon: f64,
lat: f64,
tol_px: f64,
limit: usize,
first_layer: bool,
keep: impl Fn(usize) -> bool,
) -> Vec<(usize, Value)> {
use rustgis_map::tiles::TileKind;
use rustgis_render::rustgis_tiles::{draw, mvt};
let map = s.map();
let Some((at, m_per_px)) = info::merc_at(s, lon, lat).filter(|_| limit > 0) else { return Vec::new() };
let mut out = Vec::new();
for t in &map.tiles {
for (i, t) in map.tiles.iter().enumerate() {
let data = matches!(t.kind, TileKind::PmTiles | TileKind::MbTiles | TileKind::Vector) && (t.id.is_empty() || t.overlay);
if !data || !t.draws() || t.opacity <= 0.0 {
if !data || !t.draws() || t.opacity <= 0.0 || !keep(i) {
continue;
}
let picked = draw::pick(&rustgis_render::tile_spec(t), at.x, at.y, m_per_px, tol_px as f32, limit - out.len());
Expand All @@ -384,7 +414,7 @@ fn tile_features(s: &Session, lon: f64, lat: f64, tol_px: f64, first_layer: bool
(k.clone(), json!(text))
})
.collect();
out.push(json!({"layer": format!("{} › {}", t.name, p.source_layer), "tileLayer": t.name, "sourceLayer": p.source_layer, "attributes": attrs}));
out.push((i, json!({"layer": format!("{} › {}", t.name, p.source_layer), "tileLayer": t.name, "sourceLayer": p.source_layer, "attributes": attrs})));
}
if out.len() >= limit || (first_layer && !picked.is_empty()) {
break;
Expand Down
6 changes: 6 additions & 0 deletions crates/engine/src/cmd/select_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ pub(super) fn requests(s: &Session, lon: f64, lat: f64, first_layer: bool) -> Ve
s.map().tiles.iter().filter(|t| askable(t)).filter_map(|t| next_fetch(t, lon, lat, at, m_per_px)).take(wanted).collect()
}

/// The index of the topmost WMS tile layer that can be asked what is at a point (it covers it).
pub(super) fn topmost(s: &Session, lon: f64, lat: f64) -> Option<usize> {
let (at, m_per_px) = merc_at(s, lon, lat)?;
s.map().tiles.iter().position(|t| askable(t) && next_fetch(t, lon, lat, at, m_per_px).is_some())
}

/// The answer's features as identify's results.
fn results(layer: &str, features: Vec<InfoFeature>) -> Value {
let list: Vec<Value> = features
Expand Down
Loading
Loading