Skip to main content

mln_style/sources/
tileset.rs

1//! Vector, raster and raster-dem sources: tiles from a tileset that the
2//! style lists, that the TileJSON at the source's URL gives, or both, the
3//! style's members winning. One generic type registers as all three.
4
5use std::collections::BTreeMap;
6use std::marker::PhantomData;
7use std::sync::Arc;
8
9use crate::constants;
10use crate::conversion::tileset::{convert_tileset, optional_member};
11use crate::conversion::{Convertible, Error};
12use crate::expression::Functions;
13use crate::layer::SourceKind;
14use crate::source::{Source, SourceData, SourceTypeInfo, StyleSourceType};
15use crate::tileset::{PartialTileset, Tileset};
16
17/// Which of the tileset source types a [`TilesetSourceType`] is.
18pub trait TilesetKind: Send + Sync + 'static {
19    const INFO: SourceTypeInfo;
20}
21
22pub struct VectorKind;
23pub struct RasterKind;
24pub struct RasterDemKind;
25
26impl TilesetKind for VectorKind {
27    const INFO: SourceTypeInfo = SourceTypeInfo { name: "vector", layer_kind: SourceKind::Geometry, from_json: true };
28}
29
30impl TilesetKind for RasterKind {
31    const INFO: SourceTypeInfo = SourceTypeInfo { name: "raster", layer_kind: SourceKind::Raster, from_json: true };
32}
33
34impl TilesetKind for RasterDemKind {
35    const INFO: SourceTypeInfo =
36        SourceTypeInfo { name: "raster-dem", layer_kind: SourceKind::RasterDem, from_json: true };
37}
38
39/// A source type whose tiles a tileset lists.
40pub struct TilesetSourceType<K>(PhantomData<fn() -> K>);
41
42pub type VectorSourceType = TilesetSourceType<VectorKind>;
43pub type RasterSourceType = TilesetSourceType<RasterKind>;
44pub type RasterDemSourceType = TilesetSourceType<RasterDemKind>;
45
46/// A tileset source's options.
47#[derive(Clone, Debug, PartialEq)]
48pub struct TilesetSourceOptions {
49    /// The URL of the source's TileJSON.
50    pub url: Option<String>,
51    /// The style's tileset members, which win over those of the TileJSON at
52    /// `url`.
53    pub tileset: PartialTileset,
54    /// The size of the source's tiles, in pixels.
55    pub tile_size: u16,
56    /// A vector source's `promoteId`: the properties whose values are its
57    /// features' ids.
58    pub promote_id: Option<Arc<PromoteId>>,
59}
60
61/// A vector source's `promoteId`: the property whose value is each feature's
62/// id, in place of the id the tile gives it. A feature without the property
63/// has no id.
64#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
65pub enum PromoteId {
66    /// The property of every source layer's features.
67    Property(String),
68    /// The property of each source layer's features, by source layer. The
69    /// features of a source layer it doesn't name keep their ids.
70    ByLayer(BTreeMap<String, String>),
71}
72
73impl PromoteId {
74    /// The property whose value is the id of `source_layer`'s features;
75    /// `None` where they keep their ids.
76    #[must_use]
77    pub fn property(&self, source_layer: &str) -> Option<&str> {
78        match self {
79            PromoteId::Property(property) => Some(property),
80            PromoteId::ByLayer(properties) => properties.get(source_layer).map(String::as_str),
81        }
82    }
83
84    /// `value`, a property name or an object of each source layer's.
85    fn convert(value: &Convertible<'_>) -> Option<PromoteId> {
86        if !value.is_object() {
87            return value.to_string().map(PromoteId::Property);
88        }
89        let mut properties = BTreeMap::new();
90        let mut valid = true;
91        value.each_member(|layer, property| {
92            match property.to_string() {
93                Some(property) => {
94                    properties.insert(layer.to_owned(), property);
95                }
96                None => valid = false,
97            }
98            None
99        });
100        valid.then_some(PromoteId::ByLayer(properties))
101    }
102}
103
104impl TilesetSourceOptions {
105    /// The tileset the style lists, for a source without a URL.
106    #[must_use]
107    pub fn inline_tileset(&self) -> Option<Tileset> {
108        self.url.is_none().then(|| self.tileset.clone().into())
109    }
110
111    /// The source's tileset once `tilejson`, the TileJSON at its URL, loads:
112    /// the style's members over the document's, for a source whose tiles
113    /// are of the kind `tiles`.
114    ///
115    /// # Errors
116    ///
117    /// When `tilejson` isn't a valid TileJSON, or neither it nor the style
118    /// lists tiles.
119    pub fn tileset_with_tilejson(&self, tilejson: &[u8], tiles: SourceKind) -> Result<Tileset, String> {
120        let document: serde_json::Value = serde_json::from_slice(tilejson).map_err(|e| e.to_string())?;
121        let document = convert_tileset(&Convertible::from(&document), tiles)?;
122        let tileset = self.tileset.clone().or(document);
123        if tileset.tiles.is_none() {
124            return Err("source must have tiles".to_owned());
125        }
126        Ok(tileset.into())
127    }
128}
129
130/// The options of a raster, raster-dem or vector source, whose tiles are of
131/// the kind `tiles`, from its style JSON: the TileJSON at its `url`, its own
132/// TileJSON members, or both.
133fn convert_options(value: &Convertible<'_>, tiles: SourceKind) -> Result<TilesetSourceOptions, String> {
134    let url = optional_member(value, "url", Convertible::to_string)?;
135    let tileset = convert_tileset(value, tiles)?;
136    if url.is_none() && tileset.tiles.is_none() {
137        return Err("source must have a url or tiles".to_owned());
138    }
139    let tile_size = optional_member(value, "tileSize", |size| {
140        size.to_number().filter(|size| (0.0..=f32::from(u16::MAX)).contains(size)).map(|size| size as u16)
141    })?;
142    // A vector source's tiles are always the default size.
143    let tile_size = if tiles == SourceKind::Geometry {
144        constants::TILE_SIZE_I
145    } else {
146        tile_size.unwrap_or(constants::TILE_SIZE_I)
147    };
148    let promote_id = match tiles {
149        SourceKind::Geometry => optional_member(value, "promoteId", PromoteId::convert)?.map(Arc::new),
150        _ => None,
151    };
152    Ok(TilesetSourceOptions { url, tileset, tile_size, promote_id })
153}
154
155impl<K: TilesetKind> StyleSourceType for TilesetSourceType<K> {
156    const INFO: SourceTypeInfo = K::INFO;
157
158    type Options = TilesetSourceOptions;
159
160    fn from_json(value: &Convertible<'_>, _functions: &Arc<Functions>, error: &mut Error) -> Option<SourceData<Self>> {
161        match convert_options(value, K::INFO.layer_kind) {
162            Ok(options) => Some(SourceData::new(options)),
163            Err(message) => {
164                error.message = message;
165                None
166            }
167        }
168    }
169}
170
171fn tileset_source<K: TilesetKind>(id: &str, url: Option<String>, tileset: PartialTileset, tile_size: u16) -> Source {
172    Source::new(
173        id,
174        SourceData::<TilesetSourceType<K>>::new(TilesetSourceOptions { url, tileset, tile_size, promote_id: None }),
175    )
176}
177
178/// A vector source: the TileJSON at `url`, the members of `tileset`, or
179/// both, `tileset`'s winning.
180#[must_use]
181pub fn vector_source(id: &str, url: Option<String>, tileset: PartialTileset) -> Source {
182    tileset_source::<VectorKind>(id, url, tileset, constants::TILE_SIZE_I)
183}
184
185/// A raster source of tiles `tile_size` pixels wide, as [`vector_source`].
186#[must_use]
187pub fn raster_source(id: &str, url: Option<String>, tileset: PartialTileset, tile_size: u16) -> Source {
188    tileset_source::<RasterKind>(id, url, tileset, tile_size)
189}
190
191/// A raster-dem source of tiles `tile_size` pixels wide, as
192/// [`vector_source`].
193#[must_use]
194pub fn raster_dem_source(id: &str, url: Option<String>, tileset: PartialTileset, tile_size: u16) -> Source {
195    tileset_source::<RasterDemKind>(id, url, tileset, tile_size)
196}