Skip to main content

mln_style/sources/
image.rs

1//! Image sources: an image, from the source's URL or the API, drawn between
2//! four corner coordinates.
3
4use std::sync::Arc;
5
6use crate::Edit;
7use crate::conversion::{Convertible, Error};
8use crate::expression::Functions;
9use crate::geo::LatLng;
10use crate::layer::SourceKind;
11use crate::source::{Source, SourceData, SourceTypeInfo, StyleSourceType};
12
13/// The image source type.
14pub struct ImageSourceType;
15
16/// An image source's options.
17#[derive(Clone, Debug, PartialEq)]
18pub struct ImageSourceOptions {
19    /// The URL of the source's image, if it loads it from one.
20    pub url: Option<String>,
21    /// The image's corners: top left, top right, bottom right, bottom left.
22    pub coordinates: [LatLng; 4],
23}
24
25impl StyleSourceType for ImageSourceType {
26    const INFO: SourceTypeInfo = SourceTypeInfo { name: "image", layer_kind: SourceKind::Raster, from_json: true };
27
28    type Options = ImageSourceOptions;
29
30    fn from_json(value: &Convertible<'_>, _functions: &Arc<Functions>, error: &mut Error) -> Option<SourceData<Self>> {
31        crate::conversion::source::convert_image_source(value, error)
32    }
33}
34
35impl ImageSourceType {
36    /// The edit that makes the image source `id` load its image from `url`.
37    /// Its image stays until the URL's arrives.
38    pub fn set_url(id: impl Into<String>, url: impl Into<String>) -> Edit {
39        let url = url.into();
40        Edit::update_source::<Self>(id, "an image source", |data| {
41            data.options.url = Some(url);
42            data.load += 1;
43            true
44        })
45    }
46
47    /// The edit that moves the corners of the image source `id`: top left,
48    /// top right, bottom right, bottom left.
49    pub fn set_coordinates(id: impl Into<String>, coordinates: [LatLng; 4]) -> Edit {
50        Edit::update_source::<Self>(id, "an image source", move |data| {
51            data.options.coordinates = coordinates;
52            true
53        })
54    }
55}
56
57/// An image source with its corners at `coordinates` and no image until it
58/// gets one or a URL.
59#[must_use]
60pub fn image_source(id: &str, coordinates: [LatLng; 4]) -> Source {
61    Source::new(id, SourceData::<ImageSourceType>::new(ImageSourceOptions { url: None, coordinates }))
62}