mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! Vector, raster and raster-dem sources: tiles from a tileset that the
//! style lists, that the TileJSON at the source's URL gives, or both, the
//! style's members winning. One generic type registers as all three.

use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::sync::Arc;

use crate::constants;
use crate::conversion::tileset::{convert_tileset, optional_member};
use crate::conversion::{Convertible, Error};
use crate::expression::Functions;
use crate::layer::SourceKind;
use crate::source::{Source, SourceData, SourceTypeInfo, StyleSourceType};
use crate::tileset::{PartialTileset, Tileset};

/// Which of the tileset source types a [`TilesetSourceType`] is.
pub trait TilesetKind: Send + Sync + 'static {
    const INFO: SourceTypeInfo;
}

pub struct VectorKind;
pub struct RasterKind;
pub struct RasterDemKind;

impl TilesetKind for VectorKind {
    const INFO: SourceTypeInfo = SourceTypeInfo { name: "vector", layer_kind: SourceKind::Geometry, from_json: true };
}

impl TilesetKind for RasterKind {
    const INFO: SourceTypeInfo = SourceTypeInfo { name: "raster", layer_kind: SourceKind::Raster, from_json: true };
}

impl TilesetKind for RasterDemKind {
    const INFO: SourceTypeInfo =
        SourceTypeInfo { name: "raster-dem", layer_kind: SourceKind::RasterDem, from_json: true };
}

/// A source type whose tiles a tileset lists.
pub struct TilesetSourceType<K>(PhantomData<fn() -> K>);

pub type VectorSourceType = TilesetSourceType<VectorKind>;
pub type RasterSourceType = TilesetSourceType<RasterKind>;
pub type RasterDemSourceType = TilesetSourceType<RasterDemKind>;

/// A tileset source's options.
#[derive(Clone, Debug, PartialEq)]
pub struct TilesetSourceOptions {
    /// The URL of the source's TileJSON.
    pub url: Option<String>,
    /// The style's tileset members, which win over those of the TileJSON at
    /// `url`.
    pub tileset: PartialTileset,
    /// The size of the source's tiles, in pixels.
    pub tile_size: u16,
    /// A vector source's `promoteId`: the properties whose values are its
    /// features' ids.
    pub promote_id: Option<Arc<PromoteId>>,
}

/// A vector source's `promoteId`: the property whose value is each feature's
/// id, in place of the id the tile gives it. A feature without the property
/// has no id.
#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
pub enum PromoteId {
    /// The property of every source layer's features.
    Property(String),
    /// The property of each source layer's features, by source layer. The
    /// features of a source layer it doesn't name keep their ids.
    ByLayer(BTreeMap<String, String>),
}

impl PromoteId {
    /// The property whose value is the id of `source_layer`'s features;
    /// `None` where they keep their ids.
    #[must_use]
    pub fn property(&self, source_layer: &str) -> Option<&str> {
        match self {
            PromoteId::Property(property) => Some(property),
            PromoteId::ByLayer(properties) => properties.get(source_layer).map(String::as_str),
        }
    }

    /// `value`, a property name or an object of each source layer's.
    fn convert(value: &Convertible<'_>) -> Option<PromoteId> {
        if !value.is_object() {
            return value.to_string().map(PromoteId::Property);
        }
        let mut properties = BTreeMap::new();
        let mut valid = true;
        value.each_member(|layer, property| {
            match property.to_string() {
                Some(property) => {
                    properties.insert(layer.to_owned(), property);
                }
                None => valid = false,
            }
            None
        });
        valid.then_some(PromoteId::ByLayer(properties))
    }
}

impl TilesetSourceOptions {
    /// The tileset the style lists, for a source without a URL.
    #[must_use]
    pub fn inline_tileset(&self) -> Option<Tileset> {
        self.url.is_none().then(|| self.tileset.clone().into())
    }

    /// The source's tileset once `tilejson`, the TileJSON at its URL, loads:
    /// the style's members over the document's, for a source whose tiles
    /// are of the kind `tiles`.
    ///
    /// # Errors
    ///
    /// When `tilejson` isn't a valid TileJSON, or neither it nor the style
    /// lists tiles.
    pub fn tileset_with_tilejson(&self, tilejson: &[u8], tiles: SourceKind) -> Result<Tileset, String> {
        let document: serde_json::Value = serde_json::from_slice(tilejson).map_err(|e| e.to_string())?;
        let document = convert_tileset(&Convertible::from(&document), tiles)?;
        let tileset = self.tileset.clone().or(document);
        if tileset.tiles.is_none() {
            return Err("source must have tiles".to_owned());
        }
        Ok(tileset.into())
    }
}

/// The options of a raster, raster-dem or vector source, whose tiles are of
/// the kind `tiles`, from its style JSON: the TileJSON at its `url`, its own
/// TileJSON members, or both.
fn convert_options(value: &Convertible<'_>, tiles: SourceKind) -> Result<TilesetSourceOptions, String> {
    let url = optional_member(value, "url", Convertible::to_string)?;
    let tileset = convert_tileset(value, tiles)?;
    if url.is_none() && tileset.tiles.is_none() {
        return Err("source must have a url or tiles".to_owned());
    }
    let tile_size = optional_member(value, "tileSize", |size| {
        size.to_number().filter(|size| (0.0..=f32::from(u16::MAX)).contains(size)).map(|size| size as u16)
    })?;
    // A vector source's tiles are always the default size.
    let tile_size = if tiles == SourceKind::Geometry {
        constants::TILE_SIZE_I
    } else {
        tile_size.unwrap_or(constants::TILE_SIZE_I)
    };
    let promote_id = match tiles {
        SourceKind::Geometry => optional_member(value, "promoteId", PromoteId::convert)?.map(Arc::new),
        _ => None,
    };
    Ok(TilesetSourceOptions { url, tileset, tile_size, promote_id })
}

impl<K: TilesetKind> StyleSourceType for TilesetSourceType<K> {
    const INFO: SourceTypeInfo = K::INFO;

    type Options = TilesetSourceOptions;

    fn from_json(value: &Convertible<'_>, _functions: &Arc<Functions>, error: &mut Error) -> Option<SourceData<Self>> {
        match convert_options(value, K::INFO.layer_kind) {
            Ok(options) => Some(SourceData::new(options)),
            Err(message) => {
                error.message = message;
                None
            }
        }
    }
}

fn tileset_source<K: TilesetKind>(id: &str, url: Option<String>, tileset: PartialTileset, tile_size: u16) -> Source {
    Source::new(
        id,
        SourceData::<TilesetSourceType<K>>::new(TilesetSourceOptions { url, tileset, tile_size, promote_id: None }),
    )
}

/// A vector source: the TileJSON at `url`, the members of `tileset`, or
/// both, `tileset`'s winning.
#[must_use]
pub fn vector_source(id: &str, url: Option<String>, tileset: PartialTileset) -> Source {
    tileset_source::<VectorKind>(id, url, tileset, constants::TILE_SIZE_I)
}

/// A raster source of tiles `tile_size` pixels wide, as [`vector_source`].
#[must_use]
pub fn raster_source(id: &str, url: Option<String>, tileset: PartialTileset, tile_size: u16) -> Source {
    tileset_source::<RasterKind>(id, url, tileset, tile_size)
}

/// A raster-dem source of tiles `tile_size` pixels wide, as
/// [`vector_source`].
#[must_use]
pub fn raster_dem_source(id: &str, url: Option<String>, tileset: PartialTileset, tile_size: u16) -> Source {
    tileset_source::<RasterDemKind>(id, url, tileset, tile_size)
}