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