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