Skip to main content

mln_runtime/
style.rs

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