Skip to main content

mln_runtime/
style.rs

1//! The map handle's style commands: sources and their data, custom sources,
2//! images, layers, the light, the global state and transitions.
3
4use std::collections::HashMap;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Weak};
7
8use geojson::GeoJSON;
9use mln_actor::scheduler;
10use mln_style::image::Impl as StyleImage;
11use mln_style::source::{Source, same_source, set_volatile};
12use mln_style::sources::custom_geometry_source::{self, TileOptions};
13use mln_style::sources::geojson_source::GeoJSONData;
14use mln_style::sources::image_source::ImageSource;
15use mln_style::sources::{
16    CustomGeometrySource, CustomVectorSource, GeoJSONOptions, GeoJSONSource, RasterDEMSource, RasterSource,
17    TileDataFormat, TileSource, UrlOrTileset, VectorSource, custom_vector_source,
18};
19use mln_style::{Style, TransitionOptions};
20use mln_tile_id::CanonicalTileID;
21use mln_util::error::Error;
22use mln_util::geo::{LatLng, LatLngBounds};
23use mln_util::image::PremultipliedImage;
24use mln_util::immutable::Immutable;
25use mln_util::range::Range;
26use mln_util::tileset::{RasterEncoding, Scheme, VectorEncoding};
27
28use crate::completion::{Completion, Resolver};
29use crate::map::{Applied, Map, MapEntry, MapId, apply_command, flush, missing_map, style_not_loaded};
30use crate::runtime::{Outbox, RuntimeCore, post};
31
32/// The kind of a style source.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum SourceKind {
35    Vector,
36    Raster,
37    RasterDem,
38    GeoJson,
39    Image,
40    CustomGeometry,
41    CustomVector,
42}
43
44/// The tiles that a source lists in the style itself, rather than at a URL.
45#[derive(Clone, Debug, PartialEq)]
46pub struct SourceTiles {
47    pub urls: Vec<String>,
48    pub zoom_range: Range<u8>,
49    pub scheme: Scheme,
50    pub bounds: Option<LatLngBounds>,
51    pub vector_encoding: Option<VectorEncoding>,
52    pub raster_encoding: Option<RasterEncoding>,
53}
54
55/// The options of a GeoJSON source, which stay fixed for as long as the
56/// style holds it. The defaults are the style specification's.
57#[derive(Clone, Debug, PartialEq)]
58pub struct GeoJsonSourceOptions {
59    /// The lowest zoom level that the source has tiles for.
60    pub min_zoom: u8,
61    /// The highest zoom level that the source has tiles for, at most 24.
62    pub max_zoom: u8,
63    /// How far geometry simplifies, in tile pixels: finite and not negative.
64    pub tolerance: f64,
65    /// How far each tile reaches past its edges, in tile pixels, at most 512.
66    pub buffer: u16,
67    /// Whether line features carry their length, for `line-progress`.
68    pub line_metrics: bool,
69    /// Whether points gather into clusters.
70    pub cluster: bool,
71    /// How far apart points cluster, in pixels, at most 4095.
72    pub cluster_radius: u16,
73    /// The highest zoom level that clusters points, at most 30.
74    pub cluster_max_zoom: u8,
75    /// How many points make a cluster.
76    pub cluster_min_points: usize,
77    /// The
78    /// [`clusterProperties`](https://maplibre.org/maplibre-style-spec/sources/#clusterproperties)
79    /// object as JSON text, which the runtime's thread parses.
80    pub cluster_properties: Option<String>,
81    pub attribution: Option<String>,
82}
83
84impl Default for GeoJsonSourceOptions {
85    fn default() -> Self {
86        GeoJsonSourceOptions::from_core(&GeoJSONOptions::default())
87    }
88}
89
90impl GeoJsonSourceOptions {
91    fn from_core(options: &GeoJSONOptions) -> Self {
92        GeoJsonSourceOptions {
93            min_zoom: options.minzoom,
94            max_zoom: options.maxzoom,
95            tolerance: options.tolerance,
96            buffer: options.buffer,
97            line_metrics: options.line_metrics,
98            cluster: options.cluster,
99            cluster_radius: options.cluster_radius,
100            cluster_max_zoom: options.cluster_max_zoom,
101            cluster_min_points: options.cluster_min_points,
102            cluster_properties: cluster_properties_json(options),
103            attribution: options.attribution.clone(),
104        }
105    }
106
107    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
108    /// option out of range.
109    fn check(&self) -> Result<(), Error> {
110        // Tiling stops at zoom 24, and a cluster ID holds its zoom level plus
111        // one in five bits.
112        if self.max_zoom > 24 {
113            return Err(Error::invalid_argument("max_zoom must be an integer within [0, 24]"));
114        }
115        if self.cluster_max_zoom > 30 {
116            return Err(Error::invalid_argument("cluster_max_zoom must be an integer within [0, 30]"));
117        }
118        if self.min_zoom > self.max_zoom {
119            return Err(Error::invalid_argument("min_zoom must be less than or equal to max_zoom"));
120        }
121        if !self.tolerance.is_finite() || self.tolerance < 0.0 {
122            return Err(Error::invalid_argument("tolerance must be finite and non-negative"));
123        }
124        if self.buffer > 512 {
125            return Err(Error::invalid_argument("buffer must be at most 512"));
126        }
127        if self.cluster_radius > 4095 {
128            return Err(Error::invalid_argument("cluster_radius must be at most 4095"));
129        }
130        Ok(())
131    }
132
133    /// Parses the cluster properties on this thread, for a caller that must
134    /// reject them before it sends the source, which
135    /// [`Map::add_geojson_source`] otherwise parses on the runtime's thread.
136    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for
137    /// text that isn't a `clusterProperties` object.
138    pub fn check_cluster_properties(&self) -> Result<(), Error> {
139        self.cluster_properties.as_deref().map_or(Ok(()), |json| parse_cluster_properties(json).map(drop))
140    }
141
142    /// The core's options, with the cluster properties parsed.
143    fn into_core(self) -> Result<GeoJSONOptions, Error> {
144        let cluster_properties = match &self.cluster_properties {
145            Some(json) => parse_cluster_properties(json)?,
146            None => mln_style::sources::geojson_source::ClusterProperties::default(),
147        };
148        Ok(GeoJSONOptions {
149            minzoom: self.min_zoom,
150            maxzoom: self.max_zoom,
151            tolerance: self.tolerance,
152            buffer: self.buffer,
153            line_metrics: self.line_metrics,
154            cluster: self.cluster,
155            cluster_radius: self.cluster_radius,
156            cluster_max_zoom: self.cluster_max_zoom,
157            cluster_min_points: self.cluster_min_points,
158            cluster_properties,
159            attribution: self.attribution,
160            ..GeoJSONOptions::default()
161        })
162    }
163}
164
165/// Parses a `clusterProperties` object through the style's conversion of a
166/// GeoJSON source, as its one member. Fails with
167/// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for text that isn't
168/// such an object.
169fn parse_cluster_properties(json: &str) -> Result<mln_style::sources::geojson_source::ClusterProperties, Error> {
170    let value: serde_json::Value = serde_json::from_str(json)
171        .map_err(|error| Error::invalid_argument(format!("cluster_properties is not valid JSON: {error}")))?;
172    if !value.is_object() {
173        return Err(Error::invalid_argument("cluster_properties must contain a JSON object"));
174    }
175    let wrapper = serde_json::json!({ "clusterProperties": value });
176    let mut error = mln_conversion::Error::default();
177    let options = <GeoJSONOptions as mln_style::conversion::Converter>::convert(
178        &mln_conversion::Convertible::from(&wrapper),
179        &mut error,
180    )
181    .ok_or_else(|| Error::invalid_argument(format!("GeoJSON source options: {}", error.message)))?;
182    Ok(options.cluster_properties)
183}
184
185/// A source of the map's style.
186#[derive(Clone, Debug)]
187pub struct SourceInfo {
188    pub id: String,
189    pub kind: SourceKind,
190    pub is_volatile: bool,
191    /// The source's attribution. A tile source with a URL has none until its
192    /// TileJSON loads.
193    pub attribution: Option<String>,
194    pub url: Option<String>,
195    /// The tiles a tile source lists in the style itself.
196    pub tiles: Option<SourceTiles>,
197    /// A tile source's tile size.
198    pub tile_size: Option<u16>,
199    /// A vector source's tile format.
200    pub vector_encoding: Option<VectorEncoding>,
201    pub geojson: Option<GeoJsonSourceOptions>,
202}
203
204/// A layer of the map's style.
205#[derive(Clone, Debug, PartialEq)]
206pub struct LayerInfo {
207    pub id: String,
208    /// The layer's [type](https://maplibre.org/maplibre-style-spec/layers/#type),
209    /// such as `fill`.
210    pub layer_type: &'static str,
211    /// The source's ID, for a layer that takes one.
212    pub source_id: Option<String>,
213    /// The layer of a vector source that the layer draws.
214    pub source_layer: Option<String>,
215    pub min_zoom: Option<f64>,
216    pub max_zoom: Option<f64>,
217    pub visible: bool,
218}
219
220/// The callbacks of a custom source, which run on a library thread. A map
221/// asks for a tile with `fetch_tile`, and answers come back through the
222/// source's commands, such as
223/// [`Map::set_custom_geometry_source_tile_data`]. `cancel_tile` reports that
224/// the map no longer needs a tile.
225///
226/// The callbacks drop once the source has left the style and no call is
227/// running, so the source's last call happens before then.
228pub struct CustomSourceCallbacks {
229    pub fetch_tile: Box<dyn Fn(CanonicalTileID) + Send + Sync>,
230    pub cancel_tile: Option<Box<dyn Fn(CanonicalTileID) + Send + Sync>>,
231}
232
233impl std::fmt::Debug for CustomSourceCallbacks {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.debug_struct("CustomSourceCallbacks")
236            .field("cancel_tile", &self.cancel_tile.is_some())
237            .finish_non_exhaustive()
238    }
239}
240
241/// The core's tile functions over `callbacks`, which the map holds weakly,
242/// so that they drop when the map lets go of the source rather than when
243/// the core's background loader does.
244fn tile_functions(
245    callbacks: &Arc<CustomSourceCallbacks>,
246) -> (Option<mln_style::custom_tile_loader::TileFunction>, Option<mln_style::custom_tile_loader::TileFunction>) {
247    let fetch: Weak<CustomSourceCallbacks> = Arc::downgrade(callbacks);
248    let fetch = Arc::new(move |tile: &CanonicalTileID| {
249        if let Some(callbacks) = fetch.upgrade() {
250            (callbacks.fetch_tile)(*tile);
251        }
252    });
253    let cancel = callbacks.cancel_tile.as_ref().map(|_| {
254        let cancel = Arc::downgrade(callbacks);
255        let cancel: mln_style::custom_tile_loader::TileFunction = Arc::new(move |tile: &CanonicalTileID| {
256            if let Some(callback) = cancel.upgrade().as_ref().and_then(|callbacks| callbacks.cancel_tile.as_ref()) {
257                callback(*tile);
258            }
259        });
260        cancel
261    });
262    (Some(fetch), cancel)
263}
264
265/// A custom source that a command added, and the callbacks that the map
266/// holds for it.
267struct CallbackSource {
268    id: String,
269    source: Box<dyn Source>,
270    /// Held only to be dropped: the core's tile functions hold the
271    /// callbacks weakly.
272    _callbacks: Arc<CustomSourceCallbacks>,
273}
274
275/// The custom sources of a map, whose callbacks it lets go of once their
276/// source leaves the style.
277#[derive(Default)]
278pub(crate) struct CallbackSources(Vec<CallbackSource>);
279
280/// GeoJSON data for one source: the data being built, and the newest data
281/// that waits to follow it.
282struct GeoJsonUpdate {
283    source: GeoJSONSource,
284    /// The build in progress, by its number, and its completion, which
285    /// resolves when the data is installed or when something replaced the
286    /// source's data first.
287    building: Option<(u64, Resolver<Applied>)>,
288    waiting: Option<(GeoJSON, Resolver<Applied>)>,
289}
290
291/// The GeoJSON sources whose new data is still being built, by source ID.
292#[derive(Default)]
293pub(crate) struct GeoJsonUpdates(HashMap<String, GeoJsonUpdate>);
294
295/// Lets go of the callbacks of the sources that left the style, and cancels
296/// the GeoJSON data that waits for sources that left. The callbacks drop
297/// from the outbox, so before the completions that follow, and with the
298/// runtime's state unborrowed.
299pub(crate) fn reconcile(entry: &mut MapEntry, outbox: &mut Outbox) {
300    let style = entry.core.style();
301    let present = |id: &str, source: &dyn Source| style.get_source(id).is_some_and(|found| same_source(found, source));
302    let (kept, gone): (Vec<_>, Vec<_>) =
303        std::mem::take(&mut entry.callback_sources.0).into_iter().partition(|held| present(&held.id, &*held.source));
304    entry.callback_sources.0 = kept;
305    if !gone.is_empty() {
306        outbox.push(move || drop(gone));
307    }
308    entry.geojson_updates.0.retain(|id, update| {
309        if present(id, &update.source) {
310            return true;
311        }
312        let cancelled = || Err(Error::cancelled("the source left the style before its data was ready"));
313        if let Some((_, resolver)) = update.building.take() {
314            outbox.resolve(resolver, cancelled());
315        }
316        if let Some((_, resolver)) = update.waiting.take() {
317            outbox.resolve(resolver, cancelled());
318        }
319        false
320    });
321}
322
323/// Lets go of everything a released map's sources hold, before its release
324/// completes.
325pub(crate) fn release(entry: &mut MapEntry, outbox: &mut Outbox) {
326    let held = std::mem::take(&mut entry.callback_sources.0);
327    if !held.is_empty() {
328        outbox.push(move || drop(held));
329    }
330    for (_, mut update) in entry.geojson_updates.0.drain() {
331        let cancelled = || Err(Error::cancelled("the map was released before the data was ready"));
332        if let Some((_, resolver)) = update.building.take() {
333            outbox.resolve(resolver, cancelled());
334        }
335        if let Some((_, resolver)) = update.waiting.take() {
336            outbox.resolve(resolver, cancelled());
337        }
338    }
339}
340
341fn quote(id: &str) -> String {
342    format!("\"{id}\"")
343}
344
345fn require_loaded(style: &Style) -> Result<(), Error> {
346    if style.is_loaded() { Ok(()) } else { Err(style_not_loaded()) }
347}
348
349fn source_not_found(id: &str) -> Error {
350    Error::not_found(format!("source {} does not exist", quote(id)))
351}
352
353fn find_source<'a>(style: &'a Style, id: &str) -> Result<&'a dyn Source, Error> {
354    style.get_source(id).ok_or_else(|| source_not_found(id))
355}
356
357/// The source `id` as a `T`, which `kind` names in the error for a source of
358/// another kind, as in `source "water" is not a GeoJSON source`.
359fn find_source_as<'a, T: 'static>(style: &'a Style, id: &str, kind: &str) -> Result<&'a T, Error> {
360    find_source(style, id)?
361        .as_any()
362        .downcast_ref::<T>()
363        .ok_or_else(|| Error::invalid_argument(format!("source {} is not {kind}", quote(id))))
364}
365
366fn require_new_source(style: &Style, id: &str) -> Result<(), Error> {
367    require_loaded(style)?;
368    if style.get_source(id).is_some() {
369        return Err(Error::already_exists(format!("source {} already exists", quote(id))));
370    }
371    Ok(())
372}
373
374fn tile_source(source: &dyn Source) -> Option<&TileSource> {
375    let any = source.as_any();
376    if let Some(vector) = any.downcast_ref::<VectorSource>() {
377        Some(vector.tile_source())
378    } else if let Some(raster) = any.downcast_ref::<RasterSource>() {
379        Some(raster.tile_source())
380    } else {
381        any.downcast_ref::<RasterDEMSource>().map(RasterDEMSource::tile_source)
382    }
383}
384
385fn source_kind(source: &dyn Source) -> Option<SourceKind> {
386    let any = source.as_any();
387    Some(if any.is::<VectorSource>() {
388        SourceKind::Vector
389    } else if any.is::<RasterSource>() {
390        SourceKind::Raster
391    } else if any.is::<RasterDEMSource>() {
392        SourceKind::RasterDem
393    } else if any.is::<GeoJSONSource>() {
394        SourceKind::GeoJson
395    } else if any.is::<ImageSource>() {
396        SourceKind::Image
397    } else if any.is::<CustomGeometrySource>() {
398        SourceKind::CustomGeometry
399    } else if any.is::<CustomVectorSource>() {
400        SourceKind::CustomVector
401    } else {
402        return None;
403    })
404}
405
406/// The `clusterProperties` of `options` as a JSON object.
407fn cluster_properties_json(options: &GeoJSONOptions) -> Option<String> {
408    if options.cluster_properties.is_empty() {
409        return None;
410    }
411    let members = options
412        .cluster_properties
413        .iter()
414        .map(|(key, (map, reduce))| {
415            let pair = feature::Value::Array(vec![reduce.serialize(), map.serialize()]);
416            (key.clone(), mln_conversion::value_to_json(&pair))
417        })
418        .collect::<serde_json::Map<_, _>>();
419    Some(serde_json::Value::Object(members).to_string())
420}
421
422fn source_info(source: &dyn Source) -> Option<SourceInfo> {
423    let kind = source_kind(source)?;
424    let any = source.as_any();
425    let url = if let Some(tiles) = tile_source(source) {
426        tiles.get_url()
427    } else if let Some(geojson) = any.downcast_ref::<GeoJSONSource>() {
428        geojson.get_url()
429    } else {
430        any.downcast_ref::<ImageSource>().and_then(ImageSource::get_url)
431    };
432    let geojson =
433        any.downcast_ref::<GeoJSONSource>().map(|geojson| GeoJsonSourceOptions::from_core(&geojson.get_options()));
434    let mut info = SourceInfo {
435        id: source.get_id(),
436        kind,
437        is_volatile: source.is_volatile(),
438        attribution: source.get_attribution().filter(|attribution| !attribution.is_empty()),
439        url,
440        tiles: None,
441        tile_size: None,
442        vector_encoding: None,
443        geojson,
444    };
445    if let Some(tile_source) = tile_source(source) {
446        info.tile_size = Some(tile_source.get_tile_size());
447        info.vector_encoding = any.downcast_ref::<VectorSource>().map(VectorSource::get_encoding);
448        if let UrlOrTileset::Tileset(tileset) = tile_source.get_url_or_tileset() {
449            info.vector_encoding = tileset.vector_encoding.or(info.vector_encoding);
450            info.tiles = Some(SourceTiles {
451                urls: tileset.tiles.clone(),
452                zoom_range: tileset.zoom_range,
453                scheme: tileset.scheme,
454                bounds: tileset.bounds,
455                vector_encoding: tileset.vector_encoding,
456                raster_encoding: tileset.raster_encoding,
457            });
458        }
459    }
460    Some(info)
461}
462
463fn layer_info(layer: &dyn mln_style::Layer) -> LayerInfo {
464    LayerInfo {
465        id: layer.get_id(),
466        layer_type: layer.get_type_info().type_,
467        source_id: Some(layer.get_source_id()).filter(|id| !id.is_empty()),
468        source_layer: Some(layer.get_source_layer()).filter(|id| !id.is_empty()),
469        min_zoom: Some(f64::from(layer.get_min_zoom())).filter(|zoom| zoom.is_finite()),
470        max_zoom: Some(f64::from(layer.get_max_zoom())).filter(|zoom| zoom.is_finite()),
471        visible: layer.get_visibility() != mln_style_types::VisibilityType::None,
472    }
473}
474
475/// Parses GeoJSON text, on the runtime's thread.
476fn parse_geojson(json: &str) -> Result<GeoJSON, Error> {
477    let document: serde_json::Value = serde_json::from_str(json)
478        .map_err(|error| Error::invalid_argument(format!("GeoJSON data is not valid JSON: {error}")))?;
479    let mut error = mln_conversion::Error::default();
480    mln_conversion::to_geojson(&mln_conversion::Convertible::from(&document), &mut error)
481        .ok_or_else(|| Error::invalid_argument(format!("GeoJSON data is invalid: {}", error.message)))
482}
483
484fn geometry_name(geometry: &geometry::Geometry<f64>) -> &'static str {
485    match geometry {
486        geometry::Geometry::Empty => "empty",
487        geometry::Geometry::Point(_) => "point",
488        geometry::Geometry::MultiPoint(_) => "multi-point",
489        geometry::Geometry::LineString(_) => "line string",
490        geometry::Geometry::MultiLineString(_) => "multi-line string",
491        geometry::Geometry::Polygon(_) => "polygon",
492        geometry::Geometry::MultiPolygon(_) => "multi-polygon",
493        geometry::Geometry::GeometryCollection(_) => "geometry collection",
494    }
495}
496
497/// Clustering reads a feature collection of points, so a clustered source
498/// refuses other data up front, naming what it found. An empty collection
499/// holds nothing to cluster.
500fn check_clusterable(geojson: &GeoJSON) -> Result<(), Error> {
501    let features = match geojson {
502        GeoJSON::FeatureCollection(features) => features,
503        other => {
504            let found = if matches!(other, GeoJSON::Feature(_)) { "a single feature" } else { "a bare geometry" };
505            return Err(Error::invalid_argument(format!(
506                "clustered GeoJSON data requires a feature collection; the data is {found}"
507            )));
508        }
509    };
510    match features.iter().position(|feature| !matches!(feature.geometry, geometry::Geometry::Point(_))) {
511        None => Ok(()),
512        Some(index) => Err(Error::invalid_argument(format!(
513            "clustered GeoJSON data requires point geometry on every feature; feature {index} has {} geometry",
514            geometry_name(&features[index].geometry)
515        ))),
516    }
517}
518
519/// The features a custom geometry tile draws: its core draws only a feature
520/// collection, so a lone feature or geometry becomes one.
521fn feature_collection(geojson: GeoJSON) -> GeoJSON {
522    match geojson {
523        GeoJSON::FeatureCollection(_) => geojson,
524        GeoJSON::Feature(feature) => GeoJSON::FeatureCollection(vec![feature]),
525        GeoJSON::Geometry(geometry) => GeoJSON::FeatureCollection(vec![feature::Feature::new(geometry)]),
526    }
527}
528
529impl Map {
530    // MARK: - Global state
531
532    /// Sets the value `name` that the style's `global-state` expressions
533    /// read, from JSON. See `Style::set_global_state_property_json`.
534    pub fn set_global_state_property(
535        &self,
536        name: impl Into<String>,
537        json: impl Into<String>,
538    ) -> Result<Completion<Applied>, Error> {
539        let (name, json) = (name.into(), json.into());
540        self.command(move |map| map.style_mut().set_global_state_property_json(&name, &json))
541    }
542
543    /// The style's global state as a JSON object.
544    pub fn global_state(&self) -> Result<Completion<String>, Error> {
545        self.query(|map| Ok(map.style().global_state_json()))
546    }
547
548    // MARK: - Sources
549
550    /// A source of the style, or `None` when the style has no such source.
551    pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
552        let source_id = source_id.into();
553        self.query(move |map| Ok(map.style().get_source(&source_id).and_then(source_info)))
554    }
555
556    /// The style's sources, in style order.
557    pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
558        self.query(|map| Ok(map.style().get_sources().into_iter().filter_map(source_info).collect()))
559    }
560
561    /// Sets whether a source keeps its tiles out of the persistent cache.
562    pub fn set_style_source_volatile(
563        &self,
564        source_id: impl Into<String>,
565        is_volatile: bool,
566    ) -> Result<Completion<Applied>, Error> {
567        let source_id = source_id.into();
568        self.command(move |map| {
569            let style = map.style_mut();
570            require_loaded(style)?;
571            set_volatile(find_source(style, &source_id)?, is_volatile);
572            Ok(())
573        })
574    }
575
576    // MARK: - GeoJSON sources
577
578    /// Adds a GeoJSON source with no data and `options`, which stay fixed
579    /// for as long as the style holds it.
580    ///
581    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
582    /// option out of range, and completes with it for cluster properties
583    /// that don't parse.
584    pub fn add_geojson_source(
585        &self,
586        source_id: impl Into<String>,
587        options: GeoJsonSourceOptions,
588    ) -> Result<Completion<Applied>, Error> {
589        options.check()?;
590        let source_id = source_id.into();
591        self.command(move |map| {
592            let options = options.into_core()?;
593            let style = map.style_mut();
594            require_new_source(style, &source_id)?;
595            style.add_source(Box::new(GeoJSONSource::new(source_id, Arc::new(options))))
596        })
597    }
598
599    /// Makes a GeoJSON source load its data from `url`. Data that a
600    /// [`set_geojson_source_data`](Self::set_geojson_source_data) sent before
601    /// and that isn't ready yet is cancelled.
602    pub fn set_geojson_source_url(
603        &self,
604        source_id: impl Into<String>,
605        url: impl Into<String>,
606    ) -> Result<Completion<Applied>, Error> {
607        let (source_id, url) = (source_id.into(), url.into());
608        self.send(
609            move |entry, outbox| {
610                let style = entry.core.style();
611                require_loaded(style)?;
612                find_source_as::<GeoJSONSource>(style, &source_id, "a GeoJSON source")?.set_url(&url);
613                if let Some((_, resolver)) =
614                    entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
615                {
616                    outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
617                }
618                Ok(())
619            },
620            |(), entry| entry.applied(),
621        )
622    }
623
624    /// Replaces the data of a GeoJSON source with the GeoJSON text `json`, a
625    /// feature collection, feature or geometry.
626    ///
627    /// The runtime's thread parses the data, and a background thread
628    /// prepares it with the source's options; the command completes once
629    /// the source holds it. Later commands don't wait for it. While the
630    /// source is still preparing earlier data, only the newest data waits
631    /// to follow it. With synchronous tiling on, the command prepares the
632    /// data before later commands run.
633    ///
634    /// Completes with [`ErrorKind::NotFound`](mln_util::ErrorKind) when the
635    /// style has no such source, with `InvalidArgument` when it isn't a
636    /// GeoJSON source, when `json` isn't GeoJSON, or when the source clusters
637    /// and the data isn't a feature collection of points, and with
638    /// `Cancelled` when newer data replaces it while it waits, or when the
639    /// source's URL, its removal, a style load or the map's release replaces
640    /// the source's data before it is ready.
641    pub fn set_geojson_source_data(
642        &self,
643        source_id: impl Into<String>,
644        json: impl Into<String>,
645    ) -> Result<Completion<Applied>, Error> {
646        let (source_id, json) = (source_id.into(), json.into());
647        self.shared.send(move |core, outbox, id, sequence, resolver| {
648            if !core.maps.contains_key(&id) {
649                return outbox.resolve(resolver, Err(missing_map()));
650            }
651            let run_loop = core.run_loop.clone();
652            apply_command(
653                core,
654                id,
655                sequence,
656                outbox,
657                move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, run_loop, outbox) {
658                    Ok(installed) => installed,
659                    Err((error, resolver)) => {
660                        outbox.resolve(resolver, Err(error));
661                        None
662                    }
663                },
664                |_, installed, applied, outbox| {
665                    if let Some(resolver) = installed {
666                        outbox.resolve(resolver, Ok(applied));
667                    }
668                },
669            );
670        })
671    }
672
673    /// Sets whether a GeoJSON source builds its tiles while the map renders,
674    /// in place of the `synchronousUpdate` of the source's JSON.
675    pub fn set_geojson_source_synchronous_tiling(
676        &self,
677        source_id: impl Into<String>,
678        enabled: bool,
679    ) -> Result<Completion<Applied>, Error> {
680        let source_id = source_id.into();
681        self.command(move |map| {
682            let style = map.style_mut();
683            require_loaded(style)?;
684            find_source_as::<GeoJSONSource>(style, &source_id, "a GeoJSON source")?
685                .set_override_synchronous_update(enabled);
686            Ok(())
687        })
688    }
689
690    // MARK: - Custom sources
691
692    /// Adds a source whose GeoJSON tiles come from `callbacks`. The map
693    /// holds the callbacks until the source leaves the style, by its
694    /// removal, a style load or the map's release, and drops them before
695    /// the command that removed it completes. A command that fails drops
696    /// them before it completes.
697    pub fn add_custom_geometry_source(
698        &self,
699        source_id: impl Into<String>,
700        callbacks: CustomSourceCallbacks,
701        zoom_range: Range<u8>,
702        tile_options: TileOptions,
703    ) -> Result<Completion<Applied>, Error> {
704        let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
705        self.send(
706            move |entry, outbox| {
707                add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks| {
708                    let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
709                    let options = custom_geometry_source::Options {
710                        fetch_tile_function,
711                        cancel_tile_function,
712                        zoom_range,
713                        tile_options,
714                    };
715                    let source = CustomGeometrySource::new(id, options)
716                        .map_err(|error| Error::invalid_argument(error.to_string()))?;
717                    Ok(Box::new(source))
718                })
719            },
720            |(), entry| entry.applied(),
721        )
722    }
723
724    /// Adds a source whose vector tiles come from `callbacks`, which the map
725    /// holds as [`add_custom_geometry_source`](Self::add_custom_geometry_source)
726    /// says.
727    pub fn add_custom_vector_source(
728        &self,
729        source_id: impl Into<String>,
730        callbacks: CustomSourceCallbacks,
731        zoom_range: Range<u8>,
732    ) -> Result<Completion<Applied>, Error> {
733        let (source_id, callbacks) = (source_id.into(), Arc::new(callbacks));
734        self.send(
735            move |entry, outbox| {
736                add_callback_source(entry, outbox, source_id, callbacks, |id, callbacks| {
737                    let (fetch_tile_function, cancel_tile_function) = tile_functions(callbacks);
738                    let options =
739                        custom_vector_source::Options { fetch_tile_function, cancel_tile_function, zoom_range };
740                    Ok(Box::new(CustomVectorSource::new(id, options)))
741                })
742            },
743            |(), entry| entry.applied(),
744        )
745    }
746
747    /// Sets the data of a tile of a custom geometry source from GeoJSON text:
748    /// a feature collection, feature or geometry. The source ignores data
749    /// for a tile it hasn't asked for, or has since cancelled.
750    pub fn set_custom_geometry_source_tile_data(
751        &self,
752        source_id: impl Into<String>,
753        tile_id: CanonicalTileID,
754        json: impl Into<String>,
755    ) -> Result<Completion<Applied>, Error> {
756        let (source_id, json) = (source_id.into(), json.into());
757        self.command(move |map| {
758            let geojson = feature_collection(parse_geojson(&json)?);
759            custom_geometry(map.style(), &source_id)?.set_tile_data(tile_id, geojson);
760            Ok(())
761        })
762    }
763
764    /// Reports that a tile of a custom geometry source failed to load.
765    pub fn set_custom_geometry_source_tile_error(
766        &self,
767        source_id: impl Into<String>,
768        tile_id: CanonicalTileID,
769        message: impl Into<String>,
770    ) -> Result<Completion<Applied>, Error> {
771        let (source_id, message) = (source_id.into(), message.into());
772        self.command(move |map| {
773            custom_geometry(map.style(), &source_id)?.set_tile_error(tile_id, Error::native(message));
774            Ok(())
775        })
776    }
777
778    /// Makes a custom geometry source ask for a tile again when the map needs
779    /// it.
780    pub fn invalidate_custom_geometry_source_tile(
781        &self,
782        source_id: impl Into<String>,
783        tile_id: CanonicalTileID,
784    ) -> Result<Completion<Applied>, Error> {
785        let source_id = source_id.into();
786        self.command(move |map| {
787            custom_geometry(map.style(), &source_id)?.invalidate_tile(tile_id);
788            Ok(())
789        })
790    }
791
792    /// Makes a custom geometry source ask again for the tiles in `bounds`
793    /// that the map still needs.
794    pub fn invalidate_custom_geometry_source_region(
795        &self,
796        source_id: impl Into<String>,
797        bounds: LatLngBounds,
798    ) -> Result<Completion<Applied>, Error> {
799        let source_id = source_id.into();
800        self.command(move |map| {
801            custom_geometry(map.style(), &source_id)?.invalidate_region(bounds);
802            Ok(())
803        })
804    }
805
806    /// Sets the data of a tile of a custom vector source: its bytes in
807    /// `format`, or `None` for a tile without data. The source ignores data
808    /// for a tile it hasn't asked for, or has since cancelled.
809    pub fn set_custom_vector_source_tile_data(
810        &self,
811        source_id: impl Into<String>,
812        tile_id: CanonicalTileID,
813        data: Option<Vec<u8>>,
814        format: TileDataFormat,
815    ) -> Result<Completion<Applied>, Error> {
816        let source_id = source_id.into();
817        self.command(move |map| {
818            custom_vector(map.style(), &source_id)?.set_tile_data(tile_id, data.map(Arc::new), format);
819            Ok(())
820        })
821    }
822
823    /// Reports that a tile of a custom vector source failed to load.
824    pub fn set_custom_vector_source_tile_error(
825        &self,
826        source_id: impl Into<String>,
827        tile_id: CanonicalTileID,
828        message: impl Into<String>,
829    ) -> Result<Completion<Applied>, Error> {
830        let (source_id, message) = (source_id.into(), message.into());
831        self.command(move |map| {
832            custom_vector(map.style(), &source_id)?.set_tile_error(tile_id, Error::native(message));
833            Ok(())
834        })
835    }
836
837    /// Makes a custom vector source ask for a tile again when the map needs
838    /// it.
839    pub fn invalidate_custom_vector_source_tile(
840        &self,
841        source_id: impl Into<String>,
842        tile_id: CanonicalTileID,
843    ) -> Result<Completion<Applied>, Error> {
844        let source_id = source_id.into();
845        self.command(move |map| {
846            custom_vector(map.style(), &source_id)?.invalidate_tile(tile_id);
847            Ok(())
848        })
849    }
850
851    /// Makes a custom vector source ask again for the tiles in `bounds` that
852    /// the map still needs.
853    pub fn invalidate_custom_vector_source_region(
854        &self,
855        source_id: impl Into<String>,
856        bounds: LatLngBounds,
857    ) -> Result<Completion<Applied>, Error> {
858        let source_id = source_id.into();
859        self.command(move |map| {
860            custom_vector(map.style(), &source_id)?.invalidate_region(bounds);
861            Ok(())
862        })
863    }
864
865    // MARK: - Images
866
867    /// Adds `image` to the style, or replaces the image with its ID.
868    pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
869        self.command(move |map| {
870            let style = map.style_mut();
871            require_loaded(style)?;
872            style.add_image(Arc::new(image));
873            Ok(())
874        })
875    }
876
877    /// Removes an image from the style. Completes with
878    /// [`ErrorKind::NotFound`](mln_util::ErrorKind) when the style has no
879    /// such image.
880    pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
881        let image_id = image_id.into();
882        self.command(move |map| {
883            let style = map.style_mut();
884            require_loaded(style)?;
885            if style.get_image(&image_id).is_none() {
886                return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
887            }
888            style.remove_image(&image_id);
889            Ok(())
890        })
891    }
892
893    /// An image of the style, or `None` when the style has no such image.
894    pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Immutable<StyleImage>>>, Error> {
895        let image_id = image_id.into();
896        self.query(move |map| Ok(map.style().get_image(&image_id)))
897    }
898
899    // MARK: - Image sources
900
901    /// Adds an image source that shows `image` at `coordinates`, its four
902    /// corners clockwise from the top left.
903    pub fn add_image_source(
904        &self,
905        source_id: impl Into<String>,
906        coordinates: [LatLng; 4],
907        image: PremultipliedImage,
908    ) -> Result<Completion<Applied>, Error> {
909        let source_id = source_id.into();
910        self.command(move |map| {
911            let style = map.style_mut();
912            require_new_source(style, &source_id)?;
913            let source = ImageSource::new(source_id, coordinates);
914            source.set_image(image);
915            style.add_source(Box::new(source))
916        })
917    }
918
919    /// Makes an image source load its image from `url`.
920    pub fn set_image_source_url(
921        &self,
922        source_id: impl Into<String>,
923        url: impl Into<String>,
924    ) -> Result<Completion<Applied>, Error> {
925        let (source_id, url) = (source_id.into(), url.into());
926        self.command(move |map| {
927            let style = map.style();
928            require_loaded(style)?;
929            find_source_as::<ImageSource>(style, &source_id, "an image source")?.set_url(&url);
930            Ok(())
931        })
932    }
933
934    /// Replaces the image of an image source.
935    pub fn set_image_source_image(
936        &self,
937        source_id: impl Into<String>,
938        image: PremultipliedImage,
939    ) -> Result<Completion<Applied>, Error> {
940        let source_id = source_id.into();
941        self.command(move |map| {
942            let style = map.style();
943            require_loaded(style)?;
944            find_source_as::<ImageSource>(style, &source_id, "an image source")?.set_image(image);
945            Ok(())
946        })
947    }
948
949    /// Moves the image of an image source to `coordinates`, its four corners
950    /// clockwise from the top left.
951    pub fn set_image_source_coordinates(
952        &self,
953        source_id: impl Into<String>,
954        coordinates: [LatLng; 4],
955    ) -> Result<Completion<Applied>, Error> {
956        let source_id = source_id.into();
957        self.command(move |map| {
958            let style = map.style();
959            require_loaded(style)?;
960            find_source_as::<ImageSource>(style, &source_id, "an image source")?.set_coordinates(coordinates);
961            Ok(())
962        })
963    }
964
965    /// The corners of an image source's image, clockwise from the top left.
966    pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
967        let source_id = source_id.into();
968        self.query(move |map| {
969            Ok(find_source_as::<ImageSource>(map.style(), &source_id, "an image source")?.get_coordinates())
970        })
971    }
972
973    // MARK: - Layers
974
975    /// A layer of the style, or `None` when the style has no such layer.
976    pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
977        let layer_id = layer_id.into();
978        self.query(move |map| Ok(map.style().get_layer(&layer_id).map(layer_info)))
979    }
980
981    /// The style's layers, from bottom to top.
982    pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
983        self.query(|map| Ok(map.style().get_layers().into_iter().map(layer_info).collect()))
984    }
985
986    /// Moves a layer below `before_layer_id`, or above every layer. See
987    /// `Style::move_layer` for the errors.
988    pub fn move_style_layer(
989        &self,
990        layer_id: impl Into<String>,
991        before_layer_id: Option<String>,
992    ) -> Result<Completion<Applied>, Error> {
993        let layer_id = layer_id.into();
994        self.command(move |map| map.style_mut().move_layer(&layer_id, before_layer_id.as_deref()))
995    }
996
997    // MARK: - Transitions
998
999    /// Sets the default transition of the style's paint properties.
1000    pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
1001        self.command(move |map| {
1002            let style = map.style_mut();
1003            require_loaded(style)?;
1004            style.set_transition_options(&options);
1005            Ok(())
1006        })
1007    }
1008
1009    /// The default transition of the style's paint properties.
1010    pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
1011        self.query(|map| Ok(map.style().get_transition_options()))
1012    }
1013}
1014
1015/// Adds the custom source that `make` makes over `callbacks`, and holds the
1016/// callbacks for as long as the style holds the source. When the add fails,
1017/// the callbacks drop from the outbox, with the runtime's state unborrowed.
1018fn add_callback_source(
1019    entry: &mut MapEntry,
1020    outbox: &mut Outbox,
1021    id: String,
1022    callbacks: Arc<CustomSourceCallbacks>,
1023    make: impl FnOnce(String, &Arc<CustomSourceCallbacks>) -> Result<Box<dyn Source>, Error>,
1024) -> Result<(), Error> {
1025    let style = entry.core.style_mut();
1026    let added = require_new_source(style, &id).and_then(|()| {
1027        let source = make(id.clone(), &callbacks)?;
1028        // The style takes a handle of the source, and the map keeps another
1029        // to know it by.
1030        let held = clone_source(&*source)?;
1031        style.add_source(source)?;
1032        Ok(held)
1033    });
1034    match added {
1035        Ok(source) => {
1036            entry.callback_sources.0.push(CallbackSource { id, source, _callbacks: callbacks });
1037            Ok(())
1038        }
1039        Err(error) => {
1040            outbox.push(move || drop(callbacks));
1041            Err(error)
1042        }
1043    }
1044}
1045
1046/// Another handle to a custom source.
1047fn clone_source(source: &dyn Source) -> Result<Box<dyn Source>, Error> {
1048    let any = source.as_any();
1049    if let Some(geometry) = any.downcast_ref::<CustomGeometrySource>() {
1050        Ok(Box::new(geometry.clone()))
1051    } else if let Some(vector) = any.downcast_ref::<CustomVectorSource>() {
1052        Ok(Box::new(vector.clone()))
1053    } else {
1054        Err(Error::invalid_argument("not a custom source"))
1055    }
1056}
1057
1058fn custom_geometry<'a>(style: &'a Style, id: &str) -> Result<&'a CustomGeometrySource, Error> {
1059    find_source_as(style, id, "a custom geometry source")
1060}
1061
1062fn custom_vector<'a>(style: &'a Style, id: &str) -> Result<&'a CustomVectorSource, Error> {
1063    find_source_as(style, id, "a custom vector source")
1064}
1065
1066/// Takes new data for the GeoJSON source `source_id`: builds it now with
1067/// synchronous tiling on, and returns its resolver for the command to
1068/// resolve once it ran; otherwise starts building it, or leaves it waiting
1069/// behind the data being built. An error returns the resolver with it.
1070#[allow(clippy::too_many_arguments)]
1071fn queue_geojson(
1072    entry: &mut MapEntry,
1073    map_id: MapId,
1074    source_id: &str,
1075    json: &str,
1076    resolver: Resolver<Applied>,
1077    run_loop: mln_actor::RunLoopHandle,
1078    outbox: &mut Outbox,
1079) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
1080    let found = (|| {
1081        let style = entry.core.style();
1082        require_loaded(style)?;
1083        let source = find_source_as::<GeoJSONSource>(style, source_id, "a GeoJSON source")?.clone();
1084        let geojson = parse_geojson(json)?;
1085        if source.get_options().cluster {
1086            check_clusterable(&geojson)?;
1087        }
1088        Ok((source, geojson))
1089    })();
1090    let (source, geojson) = match found {
1091        Ok(found) => found,
1092        Err(error) => return Err((error, resolver)),
1093    };
1094    if source.is_update_synchronous() {
1095        return match source.data_builder().build(&geojson) {
1096            Ok(data) => {
1097                source.set_geojson_data(Some(data));
1098                Ok(Some(resolver))
1099            }
1100            Err(error) => Err((error, resolver)),
1101        };
1102    }
1103    let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
1104        source: source.clone(),
1105        building: None,
1106        waiting: None,
1107    });
1108    if update.building.is_none() {
1109        update.source = source;
1110        start_geojson(update, map_id, source_id.to_owned(), geojson, resolver, run_loop);
1111    } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
1112        outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
1113    }
1114    Ok(None)
1115}
1116
1117/// Builds `geojson` for `update`'s source on a background thread, then
1118/// installs it from the runtime's thread.
1119fn start_geojson(
1120    update: &mut GeoJsonUpdate,
1121    map_id: MapId,
1122    source_id: String,
1123    geojson: GeoJSON,
1124    resolver: Resolver<Applied>,
1125    run_loop: mln_actor::RunLoopHandle,
1126) {
1127    // Numbers each build, so a build that something replaced finds no
1128    // completion of its own.
1129    static BUILDS: AtomicU64 = AtomicU64::new(0);
1130    let build = BUILDS.fetch_add(1, Ordering::Relaxed);
1131    update.building = Some((build, resolver));
1132    let builder = update.source.data_builder();
1133    let generation = update.source.data_generation();
1134    let next = run_loop.clone();
1135    scheduler::get_background().schedule(Box::new(move || {
1136        let data = builder.build(&geojson);
1137        post(&run_loop, move |core, outbox| {
1138            install_geojson(core, map_id, &source_id, (build, generation), data, next, outbox);
1139        });
1140    }));
1141}
1142
1143/// Installs data that a background thread built, unless something replaced
1144/// the source's data while it was built, then starts the data that waits.
1145fn install_geojson(
1146    core: &mut RuntimeCore,
1147    map_id: MapId,
1148    source_id: &str,
1149    (build, generation): (u64, u64),
1150    data: Result<Arc<dyn GeoJSONData>, Error>,
1151    run_loop: mln_actor::RunLoopHandle,
1152    outbox: &mut Outbox,
1153) {
1154    flush(core, map_id, outbox);
1155    let Some(entry) = core.maps.get_mut(&map_id) else { return };
1156    let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
1157    let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
1158    let current = entry.core.style().get_source(source_id).is_some_and(|found| same_source(found, &update.source));
1159    let installed = match data {
1160        Err(error) => Err(error),
1161        Ok(_) if !current || update.source.data_generation() != generation => {
1162            Err(Error::cancelled("the source's data was replaced before this data was ready"))
1163        }
1164        Ok(data) => {
1165            update.source.set_geojson_data(Some(data));
1166            Ok(())
1167        }
1168    };
1169    match update.waiting.take() {
1170        Some((geojson, next)) if current => {
1171            start_geojson(update, map_id, source_id.to_owned(), geojson, next, run_loop);
1172        }
1173        Some((_, next)) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
1174        None => {
1175            entry.geojson_updates.0.remove(source_id);
1176        }
1177    }
1178    flush(core, map_id, outbox);
1179    let Some(entry) = core.maps.get(&map_id) else { return };
1180    outbox.resolve(resolver, installed.map(|()| entry.applied()));
1181}