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    /// Invalidates host-dependent (`Dependency::HOST`) expression functions so
406    /// affected layers re-evaluate and affected sources re-lay out. An empty
407    /// list invalidates all host-dependent functions.
408    pub fn invalidate_expression_functions(&self, names: Vec<String>) -> Result<Completion<Applied>, Error> {
409        self.command(move |map| {
410            if names.is_empty() {
411                map.invalidate_expression_functions(None);
412            } else {
413                let refs: Vec<&str> = names.iter().map(String::as_str).collect();
414                map.invalidate_expression_functions(Some(&refs));
415            }
416            Ok(())
417        })
418    }
419
420    // MARK: - Sources
421
422    /// A source of the style, or `None` when the style has no such source.
423    pub fn style_source(&self, source_id: impl Into<String>) -> Result<Completion<Option<SourceInfo>>, Error> {
424        let source_id = source_id.into();
425        self.query(move |map| Ok(map.source(&source_id).map(|source| source_info(map.registry(), source))))
426    }
427
428    /// The style's sources, in style order.
429    pub fn style_sources(&self) -> Result<Completion<Vec<SourceInfo>>, Error> {
430        self.query(|map| Ok(map.sources().map(|source| source_info(map.registry(), source)).collect()))
431    }
432
433    /// Sets whether a source keeps its tiles out of the persistent cache.
434    pub fn set_style_source_volatile(
435        &self,
436        source_id: impl Into<String>,
437        is_volatile: bool,
438    ) -> Result<Completion<Applied>, Error> {
439        let source_id = source_id.into();
440        self.command(move |map| {
441            require_loaded(map)?;
442            let mut common = *find_source(map, &source_id)?.common();
443            common.volatile = is_volatile;
444            map.edit_style(|style| style.apply(Edit::SetSourceCommon { id: source_id, common }))
445        })
446    }
447
448    // MARK: - GeoJSON sources
449
450    /// Adds a GeoJSON source with no data and `options`, which stay fixed
451    /// for as long as the style holds it.
452    ///
453    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
454    /// option out of range, and completes with it for cluster properties
455    /// that don't parse.
456    pub fn add_geojson_source(
457        &self,
458        source_id: impl Into<String>,
459        options: GeoJsonSourceOptions,
460    ) -> Result<Completion<Applied>, Error> {
461        options.check()?;
462        let source_id = source_id.into();
463        self.command(move |map| {
464            let functions = Arc::clone(map.style().registry().functions());
465            let options = options.into_core(&functions)?;
466            require_new_source(map, &source_id)?;
467            map.add_source(geojson_source(&source_id, Arc::new(options)))
468        })
469    }
470
471    /// Makes a GeoJSON source load its data from `url`. Data that a
472    /// [`set_geojson_source_data`](Self::set_geojson_source_data) sent before
473    /// and that isn't ready yet is cancelled.
474    pub fn set_geojson_source_url(
475        &self,
476        source_id: impl Into<String>,
477        url: impl Into<String>,
478    ) -> Result<Completion<Applied>, Error> {
479        let (source_id, url) = (source_id.into(), url.into());
480        self.send(
481            move |entry, outbox| {
482                require_loaded(&entry.core)?;
483                let edit = GeoJsonSourceType::set_url(source_id.clone(), url);
484                entry.core.edit_style(|style| style.apply(edit))?;
485                if let Some((_, resolver)) =
486                    entry.geojson_updates.0.get_mut(&source_id).and_then(|update| update.waiting.take())
487                {
488                    outbox.resolve(resolver, Err(Error::cancelled("the source's URL replaced its data")));
489                }
490                Ok(())
491            },
492            |(), entry| entry.applied(),
493        )
494    }
495
496    /// Replaces the data of a GeoJSON source with the GeoJSON text `json`, a
497    /// feature collection, feature or geometry.
498    ///
499    /// The runtime's thread parses the data, and a background thread
500    /// prepares it with the source's options; the command completes once
501    /// the source holds it. Later commands don't wait for it. While the
502    /// source is still preparing earlier data, only the newest data waits
503    /// to follow it. With synchronous tiling on, the command prepares the
504    /// data before later commands run.
505    ///
506    /// Completes with [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when the
507    /// style has no such source, with `InvalidArgument` when it isn't a
508    /// GeoJSON source, when `json` isn't GeoJSON, or when the source clusters
509    /// and the data isn't a feature collection of points, and with
510    /// `Cancelled` when newer data replaces it while it waits, or when the
511    /// source's URL, its removal, a style load or the map's release replaces
512    /// the source's data before it is ready.
513    pub fn set_geojson_source_data(
514        &self,
515        source_id: impl Into<String>,
516        json: impl Into<String>,
517    ) -> Result<Completion<Applied>, Error> {
518        let (source_id, json) = (source_id.into(), json.into());
519        self.post(move |core, outbox, id, sequence, resolver| {
520            if !core.maps.contains_key(&id) {
521                return outbox.resolve(resolver, Err(missing_map()));
522            }
523            let background = core.background();
524            apply_command(
525                core,
526                id,
527                sequence,
528                outbox,
529                move |entry, outbox| match queue_geojson(entry, id, &source_id, &json, resolver, background, outbox) {
530                    Ok(installed) => installed,
531                    Err((error, resolver)) => {
532                        outbox.resolve(resolver, Err(error));
533                        None
534                    }
535                },
536                |_, installed, applied, outbox| {
537                    if let Some(resolver) = installed {
538                        outbox.resolve(resolver, Ok(applied));
539                    }
540                },
541            );
542        })
543    }
544
545    /// Sets whether a GeoJSON source builds its tiles while the map renders,
546    /// in place of the `synchronousUpdate` of the source's JSON.
547    pub fn set_geojson_source_synchronous_tiling(
548        &self,
549        source_id: impl Into<String>,
550        enabled: bool,
551    ) -> Result<Completion<Applied>, Error> {
552        let source_id = source_id.into();
553        self.command(move |map| {
554            require_loaded(map)?;
555            map.edit_style(|style| style.apply(GeoJsonSourceType::set_synchronous(source_id, enabled)))
556        })
557    }
558
559    // MARK: - Images
560
561    /// Adds `image` to the style, or replaces the image with its ID.
562    pub fn set_style_image(&self, image: StyleImage) -> Result<Completion<Applied>, Error> {
563        self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::AddImage(Arc::new(image)))))
564    }
565
566    /// Removes an image from the style. Completes with
567    /// [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when the style has no
568    /// such image.
569    pub fn remove_style_image(&self, image_id: impl Into<String>) -> Result<Completion<Applied>, Error> {
570        let image_id = image_id.into();
571        self.command(move |map| {
572            map.edit_loaded_style(|style| {
573                if style.image(&image_id).is_none() {
574                    return Err(Error::not_found(format!("style image {} does not exist", quote(&image_id))));
575                }
576                style.apply(Edit::RemoveImage(image_id))
577            })
578        })
579    }
580
581    /// An image of the style, or `None` when the style has no such image.
582    pub fn style_image(&self, image_id: impl Into<String>) -> Result<Completion<Option<Arc<StyleImage>>>, Error> {
583        let image_id = image_id.into();
584        self.query(move |map| Ok(map.style().image(&image_id).cloned()))
585    }
586
587    // MARK: - Image sources
588
589    /// Adds an image source that shows `image` at `coordinates`, its four
590    /// corners clockwise from the top left.
591    pub fn add_image_source(
592        &self,
593        source_id: impl Into<String>,
594        coordinates: [LatLng; 4],
595        image: PremultipliedImage,
596    ) -> Result<Completion<Applied>, Error> {
597        let source_id = source_id.into();
598        self.command(move |map| {
599            require_new_source(map, &source_id)?;
600            let options = ImageSourceOptions { url: None, coordinates };
601            let data = SourceData::<ImageSourceType>::with_description(options, Arc::new(image));
602            map.add_source(Source::new(&source_id, data))
603        })
604    }
605
606    /// Makes an image source load its image from `url`.
607    pub fn set_image_source_url(
608        &self,
609        source_id: impl Into<String>,
610        url: impl Into<String>,
611    ) -> Result<Completion<Applied>, Error> {
612        let (source_id, url) = (source_id.into(), url.into());
613        self.command(move |map| {
614            require_loaded(map)?;
615            map.edit_style(|style| style.apply(ImageSourceType::set_url(source_id, url)))
616        })
617    }
618
619    /// Replaces the image of an image source.
620    pub fn set_image_source_image(
621        &self,
622        source_id: impl Into<String>,
623        image: PremultipliedImage,
624    ) -> Result<Completion<Applied>, Error> {
625        let source_id = source_id.into();
626        self.command(move |map| {
627            require_loaded(map)?;
628            map.edit_style(|style| style.apply(set_image(source_id, image)))
629        })
630    }
631
632    /// Moves the image of an image source to `coordinates`, its four corners
633    /// clockwise from the top left.
634    pub fn set_image_source_coordinates(
635        &self,
636        source_id: impl Into<String>,
637        coordinates: [LatLng; 4],
638    ) -> Result<Completion<Applied>, Error> {
639        let source_id = source_id.into();
640        self.command(move |map| {
641            require_loaded(map)?;
642            map.edit_style(|style| style.apply(ImageSourceType::set_coordinates(source_id, coordinates)))
643        })
644    }
645
646    /// The corners of an image source's image, clockwise from the top left.
647    pub fn image_source_coordinates(&self, source_id: impl Into<String>) -> Result<Completion<[LatLng; 4]>, Error> {
648        let source_id = source_id.into();
649        self.query(move |map| Ok(image_data(map, &source_id)?.options.coordinates))
650    }
651
652    // MARK: - Layers
653
654    /// A layer of the style, or `None` when the style has no such layer.
655    pub fn style_layer(&self, layer_id: impl Into<String>) -> Result<Completion<Option<LayerInfo>>, Error> {
656        let layer_id = layer_id.into();
657        self.query(move |map| Ok(map.style().layer(&layer_id).map(layer_info)))
658    }
659
660    /// The style's layers, from bottom to top.
661    pub fn style_layers(&self) -> Result<Completion<Vec<LayerInfo>>, Error> {
662        self.query(|map| Ok(map.style().layers().map(layer_info).collect()))
663    }
664
665    /// Moves a layer below `before_layer_id`, or above every layer. See
666    /// `Style::move_layer` for the errors.
667    pub fn move_style_layer(
668        &self,
669        layer_id: impl Into<String>,
670        before_layer_id: Option<String>,
671    ) -> Result<Completion<Applied>, Error> {
672        let layer_id = layer_id.into();
673        self.command(move |map| map.edit_loaded_style(|style| style.move_layer(&layer_id, before_layer_id.as_deref())))
674    }
675
676    // MARK: - Transitions
677
678    /// Sets the default transition of the style's paint properties.
679    pub fn set_style_transition_options(&self, options: TransitionOptions) -> Result<Completion<Applied>, Error> {
680        self.command(move |map| map.edit_loaded_style(|style| style.apply(Edit::SetTransition(options))))
681    }
682
683    /// The default transition of the style's paint properties.
684    pub fn style_transition_options(&self) -> Result<Completion<TransitionOptions>, Error> {
685        self.query(|map| Ok(map.style().transition_options()))
686    }
687}
688
689/// Takes new data for the GeoJSON source `source_id`: builds it now with
690/// synchronous tiling on, and returns its resolver for the command to
691/// resolve once it ran; otherwise starts building it, or leaves it waiting
692/// behind the data being built. An error returns the resolver with it.
693fn queue_geojson(
694    entry: &mut MapEntry,
695    map_id: MapId,
696    source_id: &str,
697    json: &str,
698    resolver: Resolver<Applied>,
699    background: Background,
700    outbox: &mut Outbox,
701) -> Result<Option<Resolver<Applied>>, (Error, Resolver<Applied>)> {
702    let found = (|| {
703        require_loaded(&entry.core)?;
704        let data = geojson_data(&entry.core, source_id)?;
705        let geojson = parse_geojson(json)?;
706        if data.options.options.cluster {
707            check_clusterable(&geojson, data.options.options.filter.is_some())?;
708        }
709        let instance = find_source(&entry.core, source_id)?.instance();
710        let building = BuildFor::new(&entry.core, &data.options.options);
711        Ok((instance, data.load, building, data.options.synchronous_update, geojson))
712    })();
713    let (instance, load, building, synchronous, geojson) = match found {
714        Ok(found) => found,
715        Err(error) => return Err((error, resolver)),
716    };
717    if synchronous {
718        return match building.build(geojson) {
719            Ok(data) => {
720                let edit = set_data(source_id, Some(data));
721                match entry.core.edit_style(|style| style.apply(edit)) {
722                    Ok(()) => Ok(Some(resolver)),
723                    Err(error) => Err((error, resolver)),
724                }
725            }
726            Err(error) => Err((error, resolver)),
727        };
728    }
729    let update = entry.geojson_updates.0.entry(source_id.to_owned()).or_insert_with(|| GeoJsonUpdate {
730        instance,
731        building: None,
732        waiting: None,
733    });
734    if update.building.is_none() {
735        update.instance = instance;
736        start_geojson(update, map_id, source_id.to_owned(), (building, load), geojson, resolver, background);
737    } else if let Some((_, replaced)) = update.waiting.replace((geojson, resolver)) {
738        outbox.resolve(replaced, Err(Error::cancelled("newer data for the source replaced it")));
739    }
740    Ok(None)
741}
742
743/// What GeoJSON data is built for: a source's options, and how lng/lat maps
744/// to the world square of the map that draws it.
745struct BuildFor {
746    options: Arc<GeoJSONOptions>,
747    world: WorldMapping,
748}
749
750impl BuildFor {
751    /// Data for a source of `options` that `map` draws.
752    fn new(map: &mln_engine::map::Map, options: &Arc<GeoJSONOptions>) -> Self {
753        BuildFor { options: Arc::clone(options), world: map.transform_state().view().world().clone() }
754    }
755
756    /// The data of `geojson`, tiled in the world square.
757    fn build(&self, geojson: GeoJson) -> Result<Arc<dyn GeoJSONData>, Error> {
758        create_geojson_data_in(geojson, &self.options, &self.world)
759    }
760}
761
762/// Builds `geojson` as `building` says for `update`'s source, whose data is
763/// at `load`, on a background thread, then installs it from the runtime's
764/// thread.
765fn start_geojson(
766    update: &mut GeoJsonUpdate,
767    map_id: MapId,
768    source_id: String,
769    (building, load): (BuildFor, u64),
770    geojson: GeoJson,
771    resolver: Resolver<Applied>,
772    background: Background,
773) {
774    // Numbers each build, so a build that something replaced finds no
775    // completion of its own.
776    static BUILDS: AtomicU64 = AtomicU64::new(0);
777    let build = BUILDS.fetch_add(1, Ordering::Relaxed);
778    update.building = Some((build, resolver));
779    let next = background.clone();
780    background.pool.spawn(move || {
781        let data = building.build(geojson);
782        post(&background.queue, move |core, outbox| {
783            install_geojson(core, map_id, &source_id, (build, load), data, next, outbox);
784        });
785    });
786}
787
788/// What data for the source `id` is built for, and the data's load, if it's
789/// the GeoJSON source `instance`.
790fn current_geojson(map: &mln_engine::map::Map, id: &str, instance: SourceInstance) -> Option<(BuildFor, u64)> {
791    let source = map.source(id).filter(|source| source.instance() == instance)?;
792    let data = SourceData::<GeoJsonSourceType>::recover(source)?;
793    Some((BuildFor::new(map, &data.options.options), data.load))
794}
795
796/// Installs data that a background thread built, unless something replaced
797/// the source's data while it was built, then starts the data that waits.
798fn install_geojson(
799    core: &mut RuntimeCore,
800    map_id: MapId,
801    source_id: &str,
802    (build, load): (u64, u64),
803    data: Result<Arc<dyn GeoJSONData>, Error>,
804    background: Background,
805    outbox: &mut Outbox,
806) {
807    flush(core, map_id, outbox);
808    let Some(entry) = core.maps.get_mut(&map_id) else { return };
809    let Some(update) = entry.geojson_updates.0.get_mut(source_id) else { return };
810    let Some((_, resolver)) = update.building.take_if(|(building, _)| *building == build) else { return };
811    let current = current_geojson(&entry.core, source_id, update.instance);
812    let installed = match data {
813        Err(error) => Err(error),
814        Ok(_) if current.as_ref().is_none_or(|(_, current_load)| *current_load != load) => {
815            Err(Error::cancelled("the source's data was replaced before this data was ready"))
816        }
817        Ok(data) => {
818            let edit = set_data(source_id, Some(data));
819            entry.core.edit_style(|style| style.apply(edit))
820        }
821    };
822    match (update.waiting.take(), current_geojson(&entry.core, source_id, update.instance)) {
823        (Some((geojson, next)), Some(current)) => {
824            start_geojson(update, map_id, source_id.to_owned(), current, geojson, next, background);
825        }
826        (Some((_, next)), None) => outbox.resolve(next, Err(Error::cancelled("the source left the style"))),
827        (None, _) => {
828            entry.geojson_updates.0.remove(source_id);
829        }
830    }
831    flush(core, map_id, outbox);
832    let Some(entry) = core.maps.get(&map_id) else { return };
833    outbox.resolve(resolver, installed.map(|()| entry.applied()));
834}