Skip to main content

basemapper_core/
features.rs

1//! Labels and map features: select parts of a style to stack basemaps.
2//!
3//! Every style layer is either a label (a `symbol` layer: text and icons)
4//! or not, and belongs to one *feature*: water, roads, buildings, ... (see
5//! [`FEATURES`]). `labels` keeps all layers, drops the labels or keeps only
6//! them; `features` keeps or drops features. The two combine:
7//! `features = ["roads"]` with labels only is the road names.
8//!
9//! A layer's feature comes from its vector tile `source-layer`, through
10//! tables for the common schemas (OpenMapTiles: OpenFreeMap, Stadia,
11//! MapTiler; Protomaps: CARTO; Shortbread: VersaTiles), then keywords that
12//! also cover Esri's descriptive layer names (`"Water area"`, `"Road"`),
13//! then keywords in the layer id. Raster tiles have their labels drawn in;
14//! catalogue basemaps with label-free or label-only tiles switch to those
15//! (see [`crate::providers`]).
16
17use crate::BasemapError;
18use serde_json::Value;
19
20/// The features layers are sorted into, with what each covers.
21pub const FEATURES: &[(&str, &str)] = &[
22    ("background", "the background colour and the land underneath everything"),
23    ("water", "oceans, lakes, rivers and their names"),
24    ("landcover", "land cover and land use: forest, grass, farmland, residential, industrial"),
25    ("parks", "parks and protected areas"),
26    ("buildings", "buildings and house numbers"),
27    ("roads", "roads, paths, bridges, tunnels, ferries and runways, with their names and shields"),
28    ("rail", "railways and transit lines"),
29    ("boundaries", "country and region boundaries"),
30    ("places", "place names: countries, regions, cities, towns, neighbourhoods"),
31    ("poi", "points of interest: shops, schools, airports, landmarks"),
32    ("terrain", "hillshade, relief, contours and elevations"),
33    ("other", "layers that fit none of the above"),
34];
35
36/// Which labels to keep.
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub enum Labels {
39    /// Every layer (the default).
40    #[default]
41    All,
42    /// No labels: the map without text and icons.
43    None,
44    /// Only the labels, on a transparent background, to stack over another map.
45    Only,
46}
47
48impl Labels {
49    /// `"all"` (or `"true"`), `"none"` (or `"false"`), `"only"`.
50    pub fn parse(s: &str) -> Result<Labels, BasemapError> {
51        match s.to_ascii_lowercase().as_str() {
52            "all" | "true" => Ok(Labels::All),
53            "none" | "false" => Ok(Labels::None),
54            "only" => Ok(Labels::Only),
55            _ => Err(BasemapError::InvalidInput(format!("labels must be TRUE, FALSE or \"only\", not {s:?}"))),
56        }
57    }
58}
59
60fn exact(source_layer: &str) -> Option<&'static str> {
61    Some(match source_layer {
62        // OpenMapTiles, Protomaps, Shortbread
63        "water" | "waterway" | "water_name" | "ocean" | "water_polygons" | "water_lines" | "water_polygons_labels"
64        | "water_lines_labels" | "dam_lines" | "dam_polygons" => "water",
65        "landcover" | "landuse" | "land" | "sites" | "globallandcover" => "landcover",
66        "earth" => "background",
67        "park" => "parks",
68        "building" | "buildings" | "housenumber" | "addresses" => "buildings",
69        "transportation" | "transportation_name" | "aeroway" | "roads" | "streets" | "street_polygons"
70        | "streets_polygons_labels" | "street_labels" | "street_labels_points" | "bridges" | "pier_lines"
71        | "pier_polygons" | "ferries" | "aerialways" => "roads",
72        "transit" | "public_transport" => "rail",
73        "boundary" | "boundaries" | "boundary_labels" => "boundaries",
74        "place" | "places" | "place_labels" => "places",
75        "poi" | "pois" | "aerodrome_label" => "poi",
76        "mountain_peak" | "contour" | "contours" | "contour_line" | "hillshade" => "terrain",
77        _ => return None,
78    })
79}
80
81/// Keywords in a source-layer name or layer id (lowercase), in order.
82fn keywords(s: &str) -> Option<&'static str> {
83    if s.is_empty() {
84        return None;
85    }
86    let has = |words: &[&str]| words.iter().any(|w| s.contains(w));
87    if has(&["contour", "hillshade", "relief", "elevation", "landform", "peak", "terrain"]) {
88        return Some("terrain");
89    }
90    if has(&["point of interest", "poi", "landmark"]) || s.ends_with(" place") {
91        return Some("poi");
92    }
93    if s == "land" || has(&["earth", "background"]) {
94        return Some("background");
95    }
96    if has(&["rail", "transit", "subway", "tram", "metro"]) {
97        return Some("rail");
98    }
99    if has(&["boundary", "border", "disputed"]) {
100        return Some("boundaries");
101    }
102    if has(&["admin"]) {
103        return Some(if has(&["park", "forest"]) { "parks" } else { "places" });
104    }
105    if has(&["water and wastewater"]) {
106        return Some("landcover");
107    }
108    if has(&["water", "marine", "ocean", "river", "lake", "stream", "canal", "bathymetry", "coastline"]) {
109        return Some("water");
110    }
111    if has(&["building", "parcel", "address", "housenumber"]) {
112        return Some("buildings");
113    }
114    if has(&[
115        "road", "street", "highway", "motorway", "trail", "path", "pedestrian", "ferry", "bridge", "tunnel",
116        "transportation", "airport", "aeroway", "runway", "exit", "freight", "pavement", "shield",
117    ]) {
118        return Some("roads");
119    }
120    if has(&["city", "town", "village", "hamlet", "neighborhood", "neighbourhood", "suburb", "continent", "country", "place"]) {
121        return Some("places");
122    }
123    if has(&["park", "golf", "cemetery", "zoo", "indigenous", "protected", "reserve", "garden"]) && !has(&["parking"]) {
124        return Some("parks");
125    }
126    if has(&[
127        "landcover", "landuse", "forest", "wood", "vegetation", "grass", "tree", "shrub", "beach", "sand", "urban",
128        "residential", "industr", "farm", "glacier", "ice", "wetland", "retail", "commercial", "education", "medical",
129        "government", "military", "emergency", "finance", "port", "special area", "openspace", "parking",
130    ]) {
131        return Some("landcover");
132    }
133    None
134}
135
136/// The feature a style layer belongs to (one of [`FEATURES`]).
137pub fn layer_feature(layer: &Value) -> &'static str {
138    let id = layer["id"].as_str().unwrap_or("").to_ascii_lowercase();
139    match layer["type"].as_str().unwrap_or("") {
140        "background" => return "background",
141        "hillshade" | "color-relief" => return "terrain",
142        "raster" => {
143            let source = layer["source"].as_str().unwrap_or("").to_ascii_lowercase();
144            let terrain = ["shade", "relief", "hill", "terrain", "dem"].iter().any(|k| id.contains(k) || source.contains(k));
145            return if terrain { "terrain" } else { "other" };
146        }
147        _ => {}
148    }
149    let original = layer["source-layer"].as_str().unwrap_or("");
150    if original == "Land" {
151        return "background"; // Esri's land base (Shortbread's "land" is land use)
152    }
153    let sl = original.to_ascii_lowercase();
154    let sl = sl.strip_suffix("/label").unwrap_or(&sl);
155    let feature = exact(sl).or_else(|| keywords(sl)).or_else(|| keywords(&id)).unwrap_or("other");
156    // OpenMapTiles and Protomaps keep rail with the roads, and parks in land use.
157    let id_has = |words: &[&str]| words.iter().any(|w| id.contains(w));
158    match feature {
159        "roads" if id_has(&["rail", "transit", "subway", "tram"]) => "rail",
160        "landcover" if id_has(&["park", "nature_reserve", "protected"]) && !id_has(&["parking"]) => "parks",
161        f => f,
162    }
163}
164
165/// Whether a style layer is a label (text or icons).
166pub fn is_label(layer: &Value) -> bool {
167    layer["type"].as_str() == Some("symbol")
168}
169
170/// A feature name as given (`"Roads"`, `"building"`) to its [`FEATURES`] name.
171fn feature_name(name: &str) -> Result<&'static str, BasemapError> {
172    let n = name.trim().to_ascii_lowercase();
173    let n = n.as_str();
174    FEATURES
175        .iter()
176        .map(|(f, _)| *f)
177        .find(|f| *f == n || f.strip_suffix('s') == Some(n) || (*f == "boundaries" && n == "boundary") || (*f == "poi" && n == "pois"))
178        .ok_or_else(|| {
179            let all: Vec<&str> = FEATURES.iter().map(|(f, _)| *f).collect();
180            BasemapError::InvalidInput(format!("unknown feature {name:?}; features are {}", all.join(", ")))
181        })
182}
183
184/// A `features` filter: the feature names, and whether they are kept (plain
185/// names) or dropped (`-`-prefixed).
186fn parse_features(features: &[String]) -> Result<(Vec<&'static str>, bool), BasemapError> {
187    let negative = features.iter().filter(|f| f.starts_with('-')).count();
188    if negative != 0 && negative != features.len() {
189        return Err(BasemapError::InvalidLayerFilter(
190            "features mixes kept and dropped (-) features; use one mode only".into(),
191        ));
192    }
193    let names = features.iter().map(|f| feature_name(f.trim_start_matches('-'))).collect::<Result<_, _>>()?;
194    Ok((names, negative == 0))
195}
196
197/// Check a `features` filter without applying it.
198pub fn validate_features(features: &[String]) -> Result<(), BasemapError> {
199    parse_features(features).map(|_| ())
200}
201
202/// What [`select`] keeps of a style.
203#[derive(Debug, Clone)]
204pub struct Selection {
205    /// The style with the selected layers (or the switched raster tiles).
206    pub style: String,
207    /// Whether no layer is left.
208    pub empty: bool,
209    /// The features the style's layers belong to, before selection.
210    pub present: Vec<&'static str>,
211    /// Requested feature names no layer of the style belongs to.
212    pub unmatched: Vec<String>,
213}
214
215/// `style_json` with only the layers `labels` and `features` select. A
216/// catalogue raster basemap switches to its label-free or label-only tiles
217/// instead. A selection may leave no layer ([`select_layers`] makes that an
218/// error).
219pub fn select(style_json: &str, labels: Labels, features: &[String]) -> Result<Selection, BasemapError> {
220    let unchanged = |style: &str| Selection { style: style.to_owned(), empty: false, present: Vec::new(), unmatched: Vec::new() };
221    if labels == Labels::All && features.is_empty() {
222        return Ok(unchanged(style_json));
223    }
224    let (names, keep) = parse_features(features)?;
225    let mut style: Value = serde_json::from_str(style_json).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
226
227    if let Some(variants) = style.pointer("/metadata/basemapper:raster").cloned() {
228        let name = variants["provider"].as_str().unwrap_or("this basemap");
229        if !features.is_empty() {
230            return Err(BasemapError::InvalidInput(format!(
231                "features select parts of vector styles; {name} is raster tiles (use its vector form or another \
232                 basemap, or filter one style of a stack with basemap_provider(..., features =))"
233            )));
234        }
235        let tiles = match labels {
236            Labels::All => return Ok(unchanged(style_json)),
237            Labels::None if variants["has_labels"] == false => return Ok(unchanged(style_json)),
238            Labels::None => variants.get("nolabels").ok_or_else(|| {
239                BasemapError::InvalidInput(format!(
240                    "{name} raster tiles have their labels drawn in, with no label-free version; use its vector form or another basemap"
241                ))
242            })?,
243            Labels::Only => variants.get("labels").ok_or_else(|| {
244                BasemapError::InvalidInput(format!("{name} has no label-only raster tiles"))
245            })?,
246        };
247        style["sources"]["raster"]["tiles"] = tiles.clone();
248        if let Some(m) = style["metadata"].as_object_mut() {
249            m.remove("basemapper:raster");
250            if labels == Labels::Only {
251                // Labels to stack over another map: no background fill.
252                m.insert("basemapper:transparent".into(), Value::Bool(true));
253            }
254        }
255        let style = serde_json::to_string(&style).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
256        return Ok(unchanged(&style));
257    }
258
259    let Some(layers) = style.get_mut("layers").and_then(Value::as_array_mut) else {
260        return Ok(unchanged(style_json));
261    };
262    let mut present: Vec<&'static str> = Vec::new();
263    for l in layers.iter() {
264        let f = layer_feature(l);
265        if !present.contains(&f) {
266            present.push(f);
267        }
268    }
269    let unmatched = names.iter().filter(|n| !present.contains(n)).map(|n| n.to_string()).collect();
270    layers.retain(|l| {
271        let label_ok = match labels {
272            Labels::All => true,
273            Labels::None => !is_label(l),
274            Labels::Only => is_label(l),
275        };
276        label_ok && (names.is_empty() || names.contains(&layer_feature(l)) == keep)
277    });
278    let empty = layers.is_empty();
279    let style = serde_json::to_string(&style).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
280    Ok(Selection { style, empty, present, unmatched })
281}
282
283/// As [`select`], with a selection that leaves nothing to draw an error that
284/// lists the style's features.
285pub fn select_layers(style_json: &str, labels: Labels, features: &[String]) -> Result<String, BasemapError> {
286    let s = select(style_json, labels, features)?;
287    if s.empty {
288        return Err(BasemapError::InvalidLayerFilter(format!(
289            "labels and features leave nothing of this style to draw; its features are {}",
290            s.present.join(", ")
291        )));
292    }
293    Ok(s.style)
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299    use serde_json::json;
300
301    fn f(ty: &str, id: &str, sl: &str) -> &'static str {
302        layer_feature(&json!({"id": id, "type": ty, "source-layer": sl}))
303    }
304
305    #[test]
306    fn schemas_map_to_features() {
307        // OpenMapTiles (OpenFreeMap, Stadia, MapTiler)
308        assert_eq!(f("fill", "water", "water"), "water");
309        assert_eq!(f("line", "road_minor", "transportation"), "roads");
310        assert_eq!(f("line", "railway_transit", "transportation"), "rail");
311        assert_eq!(f("symbol", "highway-name-major", "transportation_name"), "roads");
312        assert_eq!(f("fill", "landuse_residential", "landuse"), "landcover");
313        assert_eq!(f("fill", "park", "park"), "parks");
314        assert_eq!(f("symbol", "label_city", "place"), "places");
315        assert_eq!(f("symbol", "airport", "aerodrome_label"), "poi");
316        // Protomaps (CARTO)
317        assert_eq!(f("fill", "earth", "earth"), "background");
318        assert_eq!(f("fill", "landuse_park", "landuse"), "parks");
319        assert_eq!(f("line", "roads_rail", "roads"), "rail");
320        assert_eq!(f("symbol", "places_locality", "places"), "places");
321        // Shortbread (VersaTiles)
322        assert_eq!(f("fill", "water-ocean", "ocean"), "water");
323        assert_eq!(f("line", "street-primary", "streets"), "roads");
324        assert_eq!(f("symbol", "label-place-city", "place_labels"), "places");
325        // Esri
326        assert_eq!(f("fill", "Water area/1", "Water area large scale"), "water");
327        assert_eq!(f("line", "Road/Major/1", "Road"), "roads");
328        assert_eq!(f("line", "Railroad/1", "Railroad"), "rail");
329        assert_eq!(f("fill", "Building/1", "Building"), "buildings");
330        assert_eq!(f("fill", "Admin0 forest or park/1", "Admin0 forest or park"), "parks");
331        assert_eq!(f("symbol", "City large scale/x", "City large scale"), "places");
332        assert_eq!(f("symbol", "Transportation place/x", "Transportation place"), "poi");
333        assert_eq!(f("line", "Boundary line/Admin0", "Boundary line"), "boundaries");
334        assert_eq!(f("fill", "Land/1", "Land"), "background");
335        assert_eq!(f("fill", "Industry/1", "Industry"), "landcover");
336        assert_eq!(f("symbol", "Water area/label/x", "Water area/label"), "water");
337        assert_eq!(f("fill", "Water and wastewater/1", "Water and wastewater"), "landcover");
338        // Layer types
339        assert_eq!(layer_feature(&json!({"id": "bg", "type": "background"})), "background");
340        assert_eq!(layer_feature(&json!({"id": "natural_earth", "type": "raster", "source": "ne2_shaded"})), "terrain");
341        assert_eq!(layer_feature(&json!({"id": "raster", "type": "raster", "source": "raster"})), "other");
342        assert_eq!(f("fill", "zcta-fill", "zcta"), "other");
343    }
344
345    fn style() -> String {
346        json!({"version": 8, "sources": {}, "layers": [
347            {"id": "bg", "type": "background"},
348            {"id": "water", "type": "fill", "source": "s", "source-layer": "water"},
349            {"id": "road", "type": "line", "source": "s", "source-layer": "transportation"},
350            {"id": "road-name", "type": "symbol", "source": "s", "source-layer": "transportation_name"},
351            {"id": "city", "type": "symbol", "source": "s", "source-layer": "place"},
352        ]})
353        .to_string()
354    }
355
356    fn ids(s: &str) -> Vec<String> {
357        let v: Value = serde_json::from_str(s).unwrap();
358        v["layers"].as_array().unwrap().iter().map(|l| l["id"].as_str().unwrap().to_owned()).collect()
359    }
360
361    fn strs(v: &[&str]) -> Vec<String> {
362        v.iter().map(|s| s.to_string()).collect()
363    }
364
365    #[test]
366    fn labels_and_features_combine() {
367        let s = style();
368        assert_eq!(select_layers(&s, Labels::All, &[]).unwrap(), s);
369        assert_eq!(ids(&select_layers(&s, Labels::None, &[]).unwrap()), ["bg", "water", "road"]);
370        assert_eq!(ids(&select_layers(&s, Labels::Only, &[]).unwrap()), ["road-name", "city"]);
371        assert_eq!(ids(&select_layers(&s, Labels::All, &strs(&["roads"])).unwrap()), ["road", "road-name"]);
372        assert_eq!(ids(&select_layers(&s, Labels::Only, &strs(&["Road"])).unwrap()), ["road-name"]);
373        assert_eq!(ids(&select_layers(&s, Labels::None, &strs(&["-water", "-background"])).unwrap()), ["road"]);
374        assert!(select_layers(&s, Labels::All, &strs(&["roads", "-water"])).is_err());
375        let e = select_layers(&s, Labels::All, &strs(&["highways"])).unwrap_err().to_string();
376        assert!(e.contains("features are background, water"), "{e}");
377        let e = select_layers(&s, Labels::Only, &strs(&["water"])).unwrap_err().to_string();
378        assert!(e.contains("its features are background, water, roads, places"), "{e}");
379    }
380
381    #[test]
382    fn unmatched_features_are_reported() {
383        let s = select(&style(), Labels::All, &strs(&["-parks", "-water"])).unwrap();
384        assert_eq!(s.unmatched, ["parks"]);
385        assert!(!s.empty);
386        let s = select(&style(), Labels::Only, &strs(&["water"])).unwrap();
387        assert!(s.empty && s.unmatched.is_empty());
388    }
389
390    #[test]
391    fn raster_variants_switch_tiles() {
392        let s = json!({"version": 8, "metadata": {"basemapper:raster": {
393                "provider": "X.Y", "has_labels": true, "nolabels": ["n"], "labels": ["l"]}},
394            "sources": {"raster": {"type": "raster", "tiles": ["a"]}},
395            "layers": [{"id": "raster", "type": "raster", "source": "raster"}]})
396        .to_string();
397        let tiles = |s: &str| serde_json::from_str::<Value>(s).unwrap()["sources"]["raster"]["tiles"].clone();
398        assert_eq!(tiles(&select_layers(&s, Labels::None, &[]).unwrap()), json!(["n"]));
399        let only: Value = serde_json::from_str(&select_layers(&s, Labels::Only, &[]).unwrap()).unwrap();
400        assert_eq!(only["sources"]["raster"]["tiles"], json!(["l"]));
401        assert_eq!(only["metadata"]["basemapper:transparent"], true, "label tiles stack without a background");
402        assert!(select_layers(&s, Labels::All, &strs(&["water"])).unwrap_err().to_string().contains("raster tiles"));
403        let baked = s.replace(r#""nolabels":["n"],"#, "");
404        assert!(select_layers(&baked, Labels::None, &[]).unwrap_err().to_string().contains("drawn in"));
405    }
406}