Skip to main content

mln_runtime/
style.rs

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