Skip to main content

basemapper_core/
style.rs

1use crate::error::BasemapError;
2use serde_json::Value;
3
4#[derive(Debug, Clone)]
5pub enum StyleInput {
6    Url(String),
7    InlineJson(String),
8}
9
10impl StyleInput {
11    pub fn detect(s: &str) -> Self {
12        if s.trim_start().starts_with('{') {
13            StyleInput::InlineJson(s.to_owned())
14        } else {
15            StyleInput::Url(s.to_owned())
16        }
17    }
18
19    /// The style JSON: inline JSON as is; otherwise a style URL or file is
20    /// loaded, or a style is built for tile data (see [`crate::tile_style()`]).
21    pub async fn resolve(
22        &self,
23        client: &reqwest::Client,
24        auth_token: Option<&str>,
25    ) -> Result<String, BasemapError> {
26        match self {
27            StyleInput::InlineJson(json) => Ok(json.clone()),
28            StyleInput::Url(url) => crate::tile_style::resolve_style_input(url, client, auth_token).await,
29        }
30    }
31}
32
33/// Validate a resolved MapLibre GL style JSON string.
34pub fn validate_maplibre_style(json: &str) -> Result<(), BasemapError> {
35    let v: Value =
36        serde_json::from_str(json).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
37    let version = v.get("version").and_then(Value::as_u64);
38    if version != Some(8) {
39        return Err(BasemapError::StyleParseError(
40            "MapLibre GL style must have \"version\": 8".into(),
41        ));
42    }
43    if v.get("sources").is_none() {
44        return Err(BasemapError::StyleParseError(
45            "MapLibre GL style missing required \"sources\" field".into(),
46        ));
47    }
48    let layers = v.get("layers").and_then(Value::as_array).ok_or_else(|| {
49        BasemapError::StyleParseError("MapLibre GL style missing \"layers\" array".into())
50    })?;
51    for (i, layer) in layers.iter().enumerate() {
52        if layer.get("id").is_none() {
53            return Err(BasemapError::StyleParseError(format!(
54                "layer[{i}]: missing required field 'id'"
55            )));
56        }
57        if layer.get("type").is_none() {
58            return Err(BasemapError::StyleParseError(format!(
59                "layer[{i}]: missing required field 'type'"
60            )));
61        }
62    }
63    Ok(())
64}
65
66/// Whether layer id `id` matches `pattern`: `*` matches any run of
67/// characters, `?` any one; anything else matches itself.
68pub fn layer_matches(pattern: &str, id: &str) -> bool {
69    let (p, t): (Vec<char>, Vec<char>) = (pattern.chars().collect(), id.chars().collect());
70    let (mut pi, mut ti) = (0, 0);
71    let (mut star, mut mark) = (None, 0);
72    while ti < t.len() {
73        if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
74            pi += 1;
75            ti += 1;
76        } else if pi < p.len() && p[pi] == '*' {
77            star = Some(pi);
78            mark = ti;
79            pi += 1;
80        } else if let Some(s) = star {
81            pi = s + 1;
82            mark += 1;
83            ti = mark;
84        } else {
85            return false;
86        }
87    }
88    p[pi..].iter().all(|&c| c == '*')
89}
90
91/// Filter the style JSON's "layers" array: plain ids or patterns (`*`, `?`)
92/// keep the layers they match, `-`-prefixed ones drop them. Returns the
93/// style and the patterns that matched no layer. Sources, sprite and glyphs
94/// are kept as they are.
95pub fn filter_layers(style_json: &str, layers: &[String]) -> Result<(String, Vec<String>), BasemapError> {
96    if layers.is_empty() {
97        return Ok((style_json.to_owned(), Vec::new()));
98    }
99    let mut style: Value = serde_json::from_str(style_json).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
100    let all_negative = layers.iter().all(|l| l.starts_with('-'));
101    let patterns: Vec<&str> = layers.iter().map(|l| l.strip_prefix('-').unwrap_or(l.as_str())).collect();
102    let mut used = vec![false; patterns.len()];
103    if let Some(arr) = style.get_mut("layers").and_then(Value::as_array_mut) {
104        arr.retain(|layer| {
105            let id = layer.get("id").and_then(Value::as_str).unwrap_or("");
106            let mut hit = false;
107            for (i, p) in patterns.iter().enumerate() {
108                if layer_matches(p, id) {
109                    used[i] = true;
110                    hit = true;
111                }
112            }
113            hit != all_negative
114        });
115    }
116    let unmatched = layers.iter().zip(&used).filter(|(_, u)| !**u).map(|(l, _)| l.clone()).collect();
117    let json = serde_json::to_string(&style).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
118    Ok((json, unmatched))
119}
120
121/// As [`filter_layers`], without the unmatched patterns.
122pub fn filter_style_layers(style_json: &str, layers: &[String]) -> Result<String, BasemapError> {
123    filter_layers(style_json, layers).map(|(s, _)| s)
124}
125
126#[cfg(test)]
127mod pattern_tests {
128    use super::*;
129
130    #[test]
131    fn wildcards_match_layer_ids() {
132        assert!(layer_matches("label_*", "label_city"));
133        assert!(layer_matches("*_casing", "highway_motorway_casing"));
134        assert!(layer_matches("Road/*", "Road/Major/1"));
135        assert!(layer_matches("road_?", "road_1"));
136        assert!(layer_matches("water", "water"));
137        assert!(!layer_matches("water", "waterway"));
138        assert!(!layer_matches("label_*", "road_label"));
139        assert!(layer_matches("*", ""));
140    }
141
142    #[test]
143    fn filter_reports_unmatched_patterns() {
144        let s = r#"{"version":8,"sources":{},"layers":[{"id":"label_city","type":"symbol"},{"id":"water","type":"fill"}]}"#;
145        let strs = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
146        let (out, unmatched) = filter_layers(s, &strs(&["-label_*", "-roads*"])).unwrap();
147        assert!(!out.contains("label_city") && out.contains("water"));
148        assert_eq!(unmatched, ["-roads*"]);
149        let (out, unmatched) = filter_layers(s, &strs(&["water", "lab?l_*"])).unwrap();
150        assert!(out.contains("label_city") && out.contains("water") && unmatched.is_empty());
151    }
152}