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