1use crate::error::BasemapError;
20use crate::tile_fetcher::{local_path, TileCoord, TileUrls};
21use serde_json::{json, Map, Value};
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum TileKind {
26 Raster,
27 Vector,
28}
29
30impl TileKind {
31 pub fn parse(s: &str) -> Result<TileKind, BasemapError> {
33 match s {
34 "raster" => Ok(TileKind::Raster),
35 "vector" => Ok(TileKind::Vector),
36 _ => Err(BasemapError::InvalidInput(format!("type must be \"raster\" or \"vector\", not {s:?}"))),
37 }
38 }
39
40 pub fn name(self) -> &'static str {
42 match self {
43 TileKind::Raster => "raster",
44 TileKind::Vector => "vector",
45 }
46 }
47}
48
49#[derive(Clone, Debug, Default)]
52pub struct TileStyleOptions {
53 pub kind: Option<TileKind>,
55 pub tile_size: Option<u32>,
57 pub scheme: Option<String>,
59 pub minzoom: Option<u8>,
60 pub maxzoom: Option<u8>,
61 pub attribution: Option<String>,
62 pub source_layers: Option<Vec<String>>,
64 pub paint: Map<String, Value>,
67}
68
69#[derive(Debug, PartialEq)]
71enum Input {
72 Pmtiles(String),
74 Template(String),
75 MapServer(String),
76 VectorTileServer(String),
77 Resource(String),
79}
80
81fn classify(s: &str) -> Input {
82 let s = s.trim();
83 if let Some(inner) = s.strip_prefix("pmtiles://") {
84 return Input::Pmtiles(inner.to_owned());
85 }
86 let path = s.split(['?', '#']).next().unwrap_or(s).to_ascii_lowercase();
87 if path.ends_with(".pmtiles") {
88 return Input::Pmtiles(s.to_owned());
89 }
90 if ["{z}", "{quadkey}", "{bbox-epsg-3857}", "{TileMatrix}"].iter().any(|t| s.contains(t)) {
91 return Input::Template(s.to_owned());
92 }
93 let trimmed = path.trim_end_matches('/');
94 let base = || s.split(['?', '#']).next().unwrap_or(s).trim_end_matches('/').to_owned();
95 if trimmed.ends_with("/mapserver") {
96 return Input::MapServer(base());
97 }
98 if trimmed.ends_with("/vectortileserver") {
99 return Input::VectorTileServer(base());
100 }
101 Input::Resource(s.to_owned())
102}
103
104pub(crate) fn vector_tile_server(s: &str) -> Option<String> {
106 match classify(s) {
107 Input::VectorTileServer(base) => Some(base),
108 _ => None,
109 }
110}
111
112fn is_http(s: &str) -> bool {
113 s.starts_with("http://") || s.starts_with("https://")
114}
115
116pub(crate) async fn tile_style(
118 input: &str,
119 opts: &TileStyleOptions,
120 client: &reqwest::Client,
121 auth_token: Option<&str>,
122) -> Result<(String, Vec<String>), BasemapError> {
123 let want = |found: TileKind, what: &str| match opts.kind {
124 Some(k) if k != found => Err(BasemapError::InvalidInput(format!(
125 "{what} holds {} tiles, not {}",
126 found.name(),
127 k.name()
128 ))),
129 _ => Ok(()),
130 };
131 match classify(input) {
132 Input::Pmtiles(url) => {
133 let url = archive_url(&url)?;
134 let reader = crate::open_pmtiles(&url, client).await?;
135 let header = reader.get_header();
136 let kind = match header.tile_type {
137 pmtiles::TileType::Mvt => TileKind::Vector,
138 pmtiles::TileType::Png | pmtiles::TileType::Jpeg | pmtiles::TileType::Webp | pmtiles::TileType::Avif => {
139 TileKind::Raster
140 }
141 pmtiles::TileType::Mlt => {
142 return Err(BasemapError::InvalidInput(format!(
143 "{input}: MapLibre Tiles (MLT) are not supported yet"
144 )))
145 }
146 pmtiles::TileType::Unknown => {
147 return Err(BasemapError::InvalidInput(format!("{input}: unknown tile type in the archive")))
148 }
149 };
150 want(kind, "the archive")?;
151 let meta: Value = reader
152 .get_metadata()
153 .await
154 .ok()
155 .and_then(|m| serde_json::from_str(&m).ok())
156 .unwrap_or_default();
157 let mut source = json!({"type": kind.name(), "url": format!("pmtiles://{url}")});
158 if kind == TileKind::Raster {
159 source["tileSize"] = json!(opts.tile_size.unwrap_or(256));
160 }
161 if let Some(a) = meta["attribution"].as_str() {
162 source["attribution"] = json!(a);
163 }
164 Ok(build_style(kind, source, vector_layer_ids(&meta), opts))
165 }
166 Input::Template(template) => {
167 let urls = TileUrls { templates: vec![template.clone()], tms: opts.scheme.as_deref() == Some("tms") };
168 let (kind, names) = match opts.kind.or_else(|| kind_from_template(&template)) {
169 Some(TileKind::Raster) => (TileKind::Raster, Vec::new()),
170 Some(TileKind::Vector) if opts.source_layers.is_some() => (TileKind::Vector, Vec::new()),
171 _ => probe(&urls, opts, client, auth_token).await?,
172 };
173 want(kind, "the tile URL")?;
174 let mut source = json!({"type": kind.name(), "tiles": [template]});
175 if kind == TileKind::Raster {
176 source["tileSize"] = json!(opts.tile_size.unwrap_or(256));
177 }
178 Ok(build_style(kind, source, names, opts))
179 }
180 Input::MapServer(base) => {
181 want(TileKind::Raster, "an ArcGIS MapServer")?;
182 let source = json!({
183 "type": "raster",
184 "tiles": [format!("{base}/tile/{{z}}/{{y}}/{{x}}")],
185 "tileSize": opts.tile_size.unwrap_or(256),
186 });
187 Ok(build_style(TileKind::Raster, source, Vec::new(), opts))
188 }
189 Input::VectorTileServer(base) => {
190 want(TileKind::Vector, "an ArcGIS VectorTileServer")?;
191 let (style, url) = load_json(&format!("{base}/resources/styles/root.json"), client, auth_token).await?;
192 Ok((absolutize(style, &url).to_string(), Vec::new()))
193 }
194 Input::Resource(r) => {
195 let (v, url) = load_json(&r, client, auth_token).await?;
196 if v.get("layers").is_some() {
197 return Ok((absolutize(v, &url).to_string(), Vec::new()));
198 }
199 if v.get("tiles").is_none() {
200 return Err(BasemapError::StyleParseError(format!(
201 "{r} is neither a MapLibre style (no \"layers\") nor a TileJSON (no \"tiles\")"
202 )));
203 }
204 let format = v["format"].as_str().unwrap_or("");
206 let found = if v.get("vector_layers").is_some() || matches!(format, "pbf" | "mvt") {
207 TileKind::Vector
208 } else {
209 TileKind::Raster
210 };
211 let kind = opts.kind.unwrap_or(found);
212 let source_url = if is_http(&url) { url.clone() } else { r.clone() };
213 let mut source = json!({"type": kind.name(), "url": source_url});
214 if !is_http(&url) {
215 source = v.clone();
217 source["type"] = json!(kind.name());
218 if let Some(o) = source.as_object_mut() {
219 o.retain(|k, _| {
220 matches!(k.as_str(), "type" | "tiles" | "minzoom" | "maxzoom" | "bounds" | "scheme" | "tileSize" | "attribution")
221 });
222 }
223 }
224 Ok(build_style(kind, source, vector_layer_ids(&v), opts))
225 }
226 }
227}
228
229pub(crate) async fn resolve_style_input(
233 input: &str,
234 client: &reqwest::Client,
235 auth_token: Option<&str>,
236) -> Result<String, BasemapError> {
237 let named = crate::providers::bare_name_style(input)?;
238 let input = match &named {
239 Some(style) if style.trim_start().starts_with('{') => return Ok(style.clone()),
240 Some(url) => url.as_str(),
241 None => input,
242 };
243 tile_style(input, &TileStyleOptions::default(), client, auth_token).await.map(|(s, _)| s)
244}
245
246fn archive_url(url: &str) -> Result<String, BasemapError> {
249 if is_http(url) || url.starts_with("file://") {
250 return Ok(url.to_owned());
251 }
252 let path = std::fs::canonicalize(url)
253 .map_err(|e| BasemapError::InvalidInput(format!("PMTiles archive {url}: {e}")))?;
254 reqwest::Url::from_file_path(&path)
255 .map(|u| u.to_string())
256 .map_err(|_| BasemapError::InvalidInput(format!("PMTiles archive {url}: not an absolute path")))
257}
258
259fn kind_from_template(t: &str) -> Option<TileKind> {
260 if t.contains("{bbox-epsg-3857}") {
261 return Some(TileKind::Raster);
262 }
263 let path = t.split('?').next().unwrap_or(t).to_ascii_lowercase();
264 let ext = path.rsplit('.').next().unwrap_or("");
265 match ext {
266 "png" | "jpg" | "jpeg" | "webp" | "avif" | "gif" => Some(TileKind::Raster),
267 "pbf" | "mvt" => Some(TileKind::Vector),
268 _ => None,
269 }
270}
271
272async fn probe(
275 urls: &TileUrls,
276 opts: &TileStyleOptions,
277 client: &reqwest::Client,
278 auth_token: Option<&str>,
279) -> Result<(TileKind, Vec<String>), BasemapError> {
280 let url = urls.url(TileCoord { z: opts.minzoom.unwrap_or(0), x: 0, y: 0 }, 1.0);
281 let mut req = client.get(&url);
282 if let Some(t) = auth_token {
283 req = req.header("Authorization", format!("Bearer {t}"));
284 }
285 let hint = "; give type = \"raster\" or \"vector\" (and source_layers for vector tiles)";
286 let resp = req
287 .send()
288 .await
289 .map_err(|e| BasemapError::InvalidInput(format!("could not fetch a tile to detect its type ({url}: {e}){hint}")))?;
290 if !resp.status().is_success() {
291 return Err(BasemapError::InvalidInput(format!(
292 "could not fetch a tile to detect its type ({url}: HTTP {}){hint}",
293 resp.status()
294 )));
295 }
296 let bytes = resp.bytes().await.map_err(|e| BasemapError::InvalidInput(format!("{url}: {e}")))?;
297 let b = &bytes[..];
298 let image = b.starts_with(&[0x89, b'P', b'N', b'G'])
299 || b.starts_with(&[0xff, 0xd8, 0xff])
300 || b.starts_with(b"GIF8")
301 || (b.len() > 12 && &b[..4] == b"RIFF" && &b[8..12] == b"WEBP")
302 || (b.len() > 12 && &b[4..8] == b"ftyp");
303 if image {
304 return Ok((TileKind::Raster, Vec::new()));
305 }
306 let tile = crate::vector::mvt::decode(b)
307 .map_err(|e| BasemapError::InvalidInput(format!("{url}: neither an image nor a vector tile ({e}){hint}")))?;
308 let mut names: Vec<String> = tile.layers.into_keys().collect();
309 names.sort();
310 if names.is_empty() {
311 return Err(BasemapError::InvalidInput(format!("{url}: the probed vector tile is empty{hint}")));
312 }
313 Ok((TileKind::Vector, names))
314}
315
316fn vector_layer_ids(v: &Value) -> Vec<String> {
317 v["vector_layers"]
318 .as_array()
319 .map(|a| a.iter().filter_map(|l| l["id"].as_str().map(str::to_owned)).collect())
320 .unwrap_or_default()
321}
322
323const PALETTE: [&str; 10] =
325 ["#4e79a7", "#f28e2b", "#e15759", "#76b7b2", "#59a14f", "#edc948", "#b07aa1", "#ff9da7", "#9c755f", "#bab0ac"];
326
327fn build_style(kind: TileKind, mut source: Value, names: Vec<String>, opts: &TileStyleOptions) -> (String, Vec<String>) {
331 if let Some(s) = &opts.scheme {
332 source["scheme"] = json!(s);
333 }
334 if let Some(z) = opts.minzoom {
335 source["minzoom"] = json!(z);
336 }
337 if let Some(z) = opts.maxzoom {
338 source["maxzoom"] = json!(z);
339 }
340 if let Some(t) = opts.tile_size {
341 source["tileSize"] = json!(t);
342 }
343 if let Some(a) = &opts.attribution {
344 source["attribution"] = json!(a);
345 }
346 let mut dropped = Vec::new();
347 let layers = match kind {
348 TileKind::Raster => {
349 dropped.extend(opts.paint.keys().cloned());
350 vec![json!({"id": "raster", "type": "raster", "source": "tiles"})]
351 }
352 TileKind::Vector => {
353 let names = opts.source_layers.clone().unwrap_or(names);
354 let paint_for = |prefix: &str, defaults: Value| {
355 let mut p = defaults;
356 for (k, v) in &opts.paint {
357 if k.starts_with(prefix) {
358 p[k] = v.clone();
359 }
360 }
361 p
362 };
363 dropped.extend(
364 opts.paint.keys().filter(|k| !["fill-", "line-", "circle-"].iter().any(|p| k.starts_with(p))).cloned(),
365 );
366 let colour = |i: usize| PALETTE[i % PALETTE.len()];
367 let mut layers = Vec::new();
368 for (i, n) in names.iter().enumerate() {
369 layers.push(json!({
370 "id": format!("{n}-fill"), "type": "fill", "source": "tiles", "source-layer": n,
371 "filter": ["==", "$type", "Polygon"],
372 "paint": paint_for("fill-", json!({"fill-color": colour(i), "fill-opacity": 0.4})),
373 }));
374 }
375 for (i, n) in names.iter().enumerate() {
376 layers.push(json!({
377 "id": format!("{n}-line"), "type": "line", "source": "tiles", "source-layer": n,
378 "filter": ["!=", "$type", "Point"],
379 "paint": paint_for("line-", json!({"line-color": colour(i), "line-width": 1})),
380 }));
381 }
382 for (i, n) in names.iter().enumerate() {
383 layers.push(json!({
384 "id": format!("{n}-circle"), "type": "circle", "source": "tiles", "source-layer": n,
385 "filter": ["==", "$type", "Point"],
386 "paint": paint_for("circle-", json!({
387 "circle-color": colour(i), "circle-radius": 3,
388 "circle-stroke-color": "#ffffff", "circle-stroke-width": 1,
389 })),
390 }));
391 }
392 layers
393 }
394 };
395 let style = json!({"version": 8, "sources": {"tiles": source}, "layers": layers});
396 (style.to_string(), dropped)
397}
398
399async fn load_json(
402 input: &str,
403 client: &reqwest::Client,
404 auth_token: Option<&str>,
405) -> Result<(Value, String), BasemapError> {
406 if is_http(input) {
407 let mut req = client.get(input);
408 if let Some(token) = auth_token {
409 req = req.header("Authorization", format!("Bearer {token}"));
410 }
411 let resp = req
412 .send()
413 .await
414 .map_err(|_| BasemapError::StyleFetchFailed { url: input.to_owned(), status: 0 })?;
415 if !resp.status().is_success() {
416 return Err(BasemapError::StyleFetchFailed { url: input.to_owned(), status: resp.status().as_u16() });
417 }
418 let url = resp.url().to_string();
419 let text = resp
420 .text()
421 .await
422 .map_err(|_| BasemapError::StyleParseError("could not read style response body".into()))?;
423 let v = serde_json::from_str(&text).map_err(|e| BasemapError::StyleParseError(format!("{input}: {e}")))?;
424 return Ok((v, url));
425 }
426 let path = local_path(input);
427 let text = std::fs::read_to_string(&path).map_err(|_| {
428 BasemapError::InvalidInput(format!(
429 "style {input:?} is not a style, a tile URL, a .pmtiles archive or an existing file"
430 ))
431 })?;
432 let v = serde_json::from_str(&text).map_err(|e| BasemapError::StyleParseError(format!("{input}: {e}")))?;
433 let url = std::fs::canonicalize(&path)
434 .ok()
435 .and_then(|p| reqwest::Url::from_file_path(p).ok())
436 .map(|u| u.to_string())
437 .unwrap_or_else(|| input.to_owned());
438 Ok((v, url))
439}
440
441fn absolutize(mut style: Value, base: &str) -> Value {
444 let abs = |u: &str| match u.strip_prefix("pmtiles://") {
445 Some(inner) => format!("pmtiles://{}", crate::resolve_url(inner, Some(base))),
446 None => crate::resolve_url(u, Some(base)),
447 };
448 if let Some(sources) = style["sources"].as_object_mut() {
449 for src in sources.values_mut() {
450 for key in ["url", "data"] {
451 if let Some(u) = src[key].as_str().map(abs) {
452 src[key] = json!(u);
453 }
454 }
455 if let Some(tiles) = src["tiles"].as_array_mut() {
456 for t in tiles.iter_mut() {
457 if let Some(u) = t.as_str().map(abs) {
458 *t = json!(u);
459 }
460 }
461 }
462 }
463 }
464 if let Some(u) = style["glyphs"].as_str().map(abs) {
465 style["glyphs"] = json!(u);
466 }
467 match &mut style["sprite"] {
468 Value::String(u) => *u = abs(u),
469 Value::Array(sprites) => {
470 for s in sprites.iter_mut() {
471 if let Some(u) = s["url"].as_str().map(abs) {
472 s["url"] = json!(u);
473 }
474 }
475 }
476 _ => {}
477 }
478 style
479}
480
481#[cfg(test)]
482mod tests {
483 use super::*;
484
485 #[test]
486 fn inputs_are_classified() {
487 assert_eq!(classify("pmtiles://https://x/a.pmtiles"), Input::Pmtiles("https://x/a.pmtiles".into()));
488 assert_eq!(classify("data/area.PMTiles"), Input::Pmtiles("data/area.PMTiles".into()));
489 assert_eq!(classify("https://x/a.pmtiles?v=2"), Input::Pmtiles("https://x/a.pmtiles?v=2".into()));
490 assert_eq!(classify("https://t/{z}/{x}/{y}.png"), Input::Template("https://t/{z}/{x}/{y}.png".into()));
491 assert_eq!(
492 classify("https://s/arcgis/rest/services/World_Imagery/MapServer/"),
493 Input::MapServer("https://s/arcgis/rest/services/World_Imagery/MapServer".into())
494 );
495 assert_eq!(
496 classify("https://s/arcgis/rest/services/B/VectorTileServer?f=json"),
497 Input::VectorTileServer("https://s/arcgis/rest/services/B/VectorTileServer".into())
498 );
499 assert_eq!(classify("https://x/style.json"), Input::Resource("https://x/style.json".into()));
500 }
501
502 #[test]
503 fn template_kind_from_extension() {
504 assert_eq!(kind_from_template("https://t/{z}/{x}/{y}.png"), Some(TileKind::Raster));
505 assert_eq!(kind_from_template("https://t/{z}/{x}/{y}.pbf?key=1"), Some(TileKind::Vector));
506 assert_eq!(kind_from_template("https://w?BBOX={bbox-epsg-3857}"), Some(TileKind::Raster));
507 assert_eq!(kind_from_template("https://t/{z}/{x}/{y}"), None);
508 }
509
510 #[test]
511 fn default_vector_style_and_paint() {
512 let mut opts = TileStyleOptions::default();
513 opts.paint.insert("fill-color".into(), json!("#123456"));
514 opts.paint.insert("text-color".into(), json!("#000"));
515 let (s, dropped) =
516 build_style(TileKind::Vector, json!({"type": "vector", "tiles": ["t"]}), vec!["roads".into(), "water".into()], &opts);
517 let v: Value = serde_json::from_str(&s).unwrap();
518 let ids: Vec<&str> = v["layers"].as_array().unwrap().iter().map(|l| l["id"].as_str().unwrap()).collect();
519 assert_eq!(ids, ["roads-fill", "water-fill", "roads-line", "water-line", "roads-circle", "water-circle"]);
520 assert_eq!(v["layers"][0]["paint"]["fill-color"], "#123456");
521 assert_eq!(v["layers"][2]["paint"]["line-color"], PALETTE[0]);
522 assert_eq!(dropped, ["text-color"]);
523 crate::style::validate_maplibre_style(&s).unwrap();
524 }
525
526 #[test]
527 fn relative_urls_become_absolute() {
528 let style = json!({
529 "sources": {"esri": {"type": "vector", "url": "../../"}, "p": {"type": "vector", "url": "pmtiles://a.pmtiles"}},
530 "sprite": "../sprites/sprite", "glyphs": "../fonts/{fontstack}/{range}.pbf",
531 });
532 let v = absolutize(style, "https://h/s/VectorTileServer/resources/styles/root.json");
533 assert_eq!(v["sources"]["esri"]["url"], "https://h/s/VectorTileServer/");
534 assert_eq!(v["sources"]["p"]["url"], "pmtiles://https://h/s/VectorTileServer/resources/styles/a.pmtiles");
535 assert_eq!(v["sprite"], "https://h/s/VectorTileServer/resources/sprites/sprite");
536 assert_eq!(v["glyphs"], "https://h/s/VectorTileServer/resources/fonts/{fontstack}/{range}.pbf");
537 }
538}