Skip to main content

mln_plugin/
source.rs

1//! Safe, host-agnostic traits and async [`TileRequest`] handle for source plugins.
2
3use crate::backend::TileRequestBackend;
4use crate::error::Result;
5use crate::types::{CanonicalTileId, LatLngBounds, RasterEncoding, TileNecessity, TileScheme, TileTimes};
6
7// ---------------------------------------------------------------------------
8// Options & callback info
9// ---------------------------------------------------------------------------
10
11/// GeoJSON tiling defaults for a [`SourceKindOptions::Geometry`] plugin source.
12#[derive(Clone, Copy, Debug, Default)]
13pub struct GeometrySourceOptions {
14    pub buffer: Option<u32>,
15    pub tolerance: Option<f64>,
16    pub clip: Option<bool>,
17    pub wrap: Option<bool>,
18}
19
20impl GeometrySourceOptions {
21    #[must_use]
22    pub const fn new() -> Self {
23        Self { buffer: None, tolerance: None, clip: None, wrap: None }
24    }
25
26    #[must_use]
27    pub const fn buffer(mut self, buffer: u32) -> Self {
28        self.buffer = Some(buffer);
29        self
30    }
31
32    #[must_use]
33    pub const fn tolerance(mut self, tolerance: f64) -> Self {
34        self.tolerance = Some(tolerance);
35        self
36    }
37
38    #[must_use]
39    pub const fn clip(mut self, clip: bool) -> Self {
40        self.clip = Some(clip);
41        self
42    }
43
44    #[must_use]
45    pub const fn wrap(mut self, wrap: bool) -> Self {
46        self.wrap = Some(wrap);
47        self
48    }
49}
50
51/// Elevation defaults for a [`SourceKindOptions::RasterDem`] plugin source.
52#[derive(Clone, Copy, Debug, Default)]
53pub struct RasterDemSourceOptions {
54    pub encoding: Option<RasterEncoding>,
55}
56
57impl RasterDemSourceOptions {
58    #[must_use]
59    pub const fn new() -> Self {
60        Self { encoding: None }
61    }
62
63    #[must_use]
64    pub const fn encoding(mut self, encoding: RasterEncoding) -> Self {
65        self.encoding = Some(encoding);
66        self
67    }
68}
69
70/// Kind of tiles a plugin source supplies together with its kind-specific defaults.
71#[derive(Clone, Copy, Debug)]
72pub enum SourceKindOptions {
73    Geometry(GeometrySourceOptions),
74    Raster,
75    RasterDem(RasterDemSourceOptions),
76}
77
78/// Configuration and defaults for registering a [`SourcePlugin`].
79///
80/// When style JSON creates a source of this type, standard members (`minzoom`,
81/// `maxzoom`, `tileSize`, `scheme`, `bounds`, `attribution`, and kind-specific
82/// members such as `encoding`, `buffer`, `tolerance`, `clip`, and `wrap`)
83/// override these defaults for that source instance, while the raw JSON object
84/// is passed to [`SourcePlugin::fetch_tile`] and [`SourcePlugin::cancel_tile`].
85#[derive(Clone, Copy, Debug)]
86pub struct SourceTypeOptions<'a> {
87    pub name: &'a str,
88    pub kind: SourceKindOptions,
89    pub min_zoom: Option<f64>,
90    pub max_zoom: Option<f64>,
91    pub tile_size: Option<u32>,
92    pub scheme: Option<TileScheme>,
93    pub bounds: Option<LatLngBounds>,
94    pub attribution: Option<&'a str>,
95    pub fetches_optional: Option<bool>,
96}
97
98impl<'a> SourceTypeOptions<'a> {
99    #[must_use]
100    pub const fn new(name: &'a str, kind: SourceKindOptions) -> Self {
101        Self {
102            name,
103            kind,
104            min_zoom: None,
105            max_zoom: None,
106            tile_size: None,
107            scheme: None,
108            bounds: None,
109            attribution: None,
110            fetches_optional: None,
111        }
112    }
113
114    /// Creates options for a geometry (GeoJSON / MVT / MLT) plugin source with default tiling options.
115    #[must_use]
116    pub const fn geometry(name: &'a str) -> Self {
117        Self::new(name, SourceKindOptions::Geometry(GeometrySourceOptions::new()))
118    }
119
120    /// Creates options for a raster image plugin source.
121    #[must_use]
122    pub const fn raster(name: &'a str) -> Self {
123        Self::new(name, SourceKindOptions::Raster)
124    }
125
126    /// Creates options for a raster-DEM plugin source with default elevation options.
127    #[must_use]
128    pub const fn raster_dem(name: &'a str) -> Self {
129        Self::new(name, SourceKindOptions::RasterDem(RasterDemSourceOptions::new()))
130    }
131
132    #[must_use]
133    pub const fn min_zoom(mut self, min_zoom: f64) -> Self {
134        self.min_zoom = Some(min_zoom);
135        self
136    }
137
138    #[must_use]
139    pub const fn max_zoom(mut self, max_zoom: f64) -> Self {
140        self.max_zoom = Some(max_zoom);
141        self
142    }
143
144    #[must_use]
145    pub const fn tile_size(mut self, tile_size: u32) -> Self {
146        self.tile_size = Some(tile_size);
147        self
148    }
149
150    #[must_use]
151    pub const fn scheme(mut self, scheme: TileScheme) -> Self {
152        self.scheme = Some(scheme);
153        self
154    }
155
156    #[must_use]
157    pub const fn bounds(mut self, bounds: LatLngBounds) -> Self {
158        self.bounds = Some(bounds);
159        self
160    }
161
162    #[must_use]
163    pub const fn attribution(mut self, attribution: &'a str) -> Self {
164        self.attribution = Some(attribution);
165        self
166    }
167
168    #[must_use]
169    pub const fn fetches_optional(mut self, fetches_optional: bool) -> Self {
170        self.fetches_optional = Some(fetches_optional);
171        self
172    }
173}
174
175/// Answer passed to [`TileRequest::deliver`].
176#[derive(Clone, Copy, Debug)]
177pub enum TileResponse<'a> {
178    /// UTF-8 GeoJSON payload for a geometry source.
179    GeoJson { json: &'a str, times: TileTimes },
180    /// Mapbox Vector Tile bytes for a geometry source; empty delivers an empty tile.
181    Mvt { bytes: &'a [u8], times: TileTimes },
182    /// MapLibre Tile bytes for a geometry source; empty delivers an empty tile.
183    Mlt { bytes: &'a [u8], times: TileTimes },
184    /// Encoded image bytes (PNG, JPEG, or WebP) for a raster or raster-dem source.
185    EncodedImage { bytes: &'a [u8], times: TileTimes },
186    /// Valid empty tile for any source kind.
187    Empty { times: TileTimes },
188    /// No tile at this ID; allows the map to fall back to ancestor tiles.
189    Missing,
190    /// Tile load failure with message and retry flag.
191    Error { message: &'a str, retrying: bool },
192}
193
194impl<'a> TileResponse<'a> {
195    #[must_use]
196    pub const fn geojson(json: &'a str) -> Self {
197        Self::GeoJson { json, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
198    }
199
200    #[must_use]
201    pub const fn mvt(bytes: &'a [u8]) -> Self {
202        Self::Mvt { bytes, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
203    }
204
205    #[must_use]
206    pub const fn mlt(bytes: &'a [u8]) -> Self {
207        Self::Mlt { bytes, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
208    }
209
210    #[must_use]
211    pub const fn encoded_image(bytes: &'a [u8]) -> Self {
212        Self::EncodedImage { bytes, times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
213    }
214
215    #[must_use]
216    pub const fn empty() -> Self {
217        Self::Empty { times: TileTimes { modified_unix_ms: None, expires_unix_ms: None } }
218    }
219
220    #[must_use]
221    pub const fn error(message: &'a str, retrying: bool) -> Self {
222        Self::Error { message, retrying }
223    }
224}
225
226/// Borrowed metadata passed to [`SourcePlugin::fetch_tile`].
227#[derive(Clone, Copy, Debug)]
228pub struct TileFetchInfo<'a> {
229    pub source_id: &'a str,
230    pub options_json: &'a str,
231    pub tile_id: CanonicalTileId,
232    pub necessity: TileNecessity,
233}
234
235/// Borrowed metadata passed to [`SourcePlugin::cancel_tile`].
236#[derive(Clone, Copy, Debug)]
237pub struct TileCancelInfo<'a> {
238    pub source_id: &'a str,
239    pub options_json: &'a str,
240    pub tile_id: CanonicalTileId,
241}
242
243// ---------------------------------------------------------------------------
244// Async TileRequest RAII handle
245// ---------------------------------------------------------------------------
246
247/// Owned async tile delivery handle passed to [`SourcePlugin::fetch_tile`].
248///
249/// May be sent to any thread and answered asynchronously via [`Self::deliver`].
250/// Dropping without answering releases the request cleanly (treated by the
251/// renderer as missing/cancelled).
252#[derive(Debug)]
253pub struct TileRequest {
254    backend: Box<dyn TileRequestBackend>,
255}
256
257impl TileRequest {
258    #[doc(hidden)]
259    #[must_use]
260    pub fn from_backend(backend: Box<dyn TileRequestBackend>) -> Self {
261        Self { backend }
262    }
263
264    /// Delivers `response` to the renderer and consumes this request.
265    pub fn deliver(self, response: TileResponse<'_>) -> Result<()> {
266        self.backend.deliver(response)
267    }
268}
269
270// ---------------------------------------------------------------------------
271// SourcePlugin trait
272// ---------------------------------------------------------------------------
273
274/// Custom tile source type implemented against the MapLibre Plugin SDK.
275pub trait SourcePlugin: Send + Sync + 'static {
276    /// Returns the source type's name, data kind, and default tiling options.
277    fn options(&self) -> SourceTypeOptions<'_>;
278
279    /// Called when the renderer needs a tile.
280    ///
281    /// Answer synchronously or move `request` to another thread/task and call
282    /// [`TileRequest::deliver`].
283    fn fetch_tile(&self, info: TileFetchInfo<'_>, request: TileRequest);
284
285    /// Called when the renderer no longer needs a previously requested tile.
286    fn cancel_tile(&self, _info: TileCancelInfo<'_>) {}
287}