Skip to main content

mln_style/style/
mod.rs

1use std::sync::Arc;
2
3use crate::conversion::Convertible;
4use crate::crs::WorldMapping;
5use crate::error::Error;
6use crate::expression::GlobalStateMap;
7use crate::feature::Value;
8use crate::filter::Filter;
9use crate::font_face::FontFaces;
10use crate::geo::LatLng;
11use crate::layer::{Layer, LayerList, SourceKind};
12use crate::light::Light;
13use crate::member::{Members, Place, is_extension_member};
14use crate::projection::Projection;
15use crate::property::transition::TransitionOptions;
16use crate::registry::StyleRegistry;
17use crate::sky::Sky;
18use crate::source::{Source, SourceList};
19use crate::sprite::Sprite;
20use crate::style::edit::Edit;
21use crate::style::parse::Parser;
22use crate::terrain::Terrain;
23use crate::{image, log_target, sort};
24
25pub mod diff;
26pub(crate) mod edit;
27pub(crate) mod json;
28pub(crate) mod parse;
29#[cfg(test)]
30mod tests;
31
32/// The camera that a style's root properties set: `center`, `centerAltitude`,
33/// `zoom`, `bearing`, `pitch` and `roll`. A parsed style sets every member,
34/// to the style spec's default where the document leaves it out; an empty
35/// style sets none.
36#[derive(Clone, Copy, Debug, Default, PartialEq)]
37pub struct StyleCamera {
38    pub center: Option<LatLng>,
39    /// In meters above sea level.
40    pub center_altitude: Option<f64>,
41    pub zoom: Option<f64>,
42    /// In degrees.
43    pub bearing: Option<f64>,
44    /// In degrees.
45    pub pitch: Option<f64>,
46    /// In degrees.
47    pub roll: Option<f64>,
48}
49
50/// Why a style failed to load.
51#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
52#[error("{0}")]
53pub enum StyleLoadError {
54    /// The style document isn't a valid style.
55    Parse(String),
56    /// The style's request failed, such as with a 404 or a missing file.
57    Load(String),
58}
59
60impl StyleLoadError {
61    /// What failed, for people.
62    #[must_use]
63    pub fn message(&self) -> &str {
64        match self {
65            StyleLoadError::Parse(message) | StyleLoadError::Load(message) => message,
66        }
67    }
68}
69
70/// The images of a style, sorted by id.
71pub(crate) type ImageList = Vec<Arc<image::StyleImage>>;
72
73/// A version of a map's style: what a style document describes, after the
74/// edits made since.
75///
76/// A style is a value. [`apply`](Self::apply) makes an [`Edit`]; nothing
77/// else changes it. Its parts (layers, sources, images, light, sky,
78/// terrain, projection, global state, extension members and the document's
79/// own members) sit behind their own `Arc`s, so a clone is cheap and an edit
80/// copies only the part it changes. Two versions whose part `Arc`s are the
81/// same pointer have the same part, which
82/// [`is_same_version`](Self::is_same_version) and
83/// [`StyleDiff::between`](crate::diff::StyleDiff::between) read.
84#[derive(Clone)]
85pub struct Style {
86    registry: Arc<StyleRegistry>,
87    /// The document, for the root properties that edits don't change.
88    json: Arc<str>,
89    name: Arc<str>,
90    default_camera: StyleCamera,
91    layers: Arc<LayerList>,
92    /// The sources, in the order they were added.
93    sources: Arc<SourceList>,
94    images: Arc<ImageList>,
95    light: Arc<Light>,
96    sky: Option<Arc<Sky>>,
97    terrain: Option<Arc<Terrain>>,
98    projection: Arc<Projection>,
99    /// The root's extension members.
100    members: Arc<Members>,
101    transition: TransitionOptions,
102    /// What the `global-state` expressions read.
103    global_state: Arc<GlobalStateMap>,
104    /// The defaults that the document's root `state` gives.
105    global_state_defaults: Arc<GlobalStateMap>,
106    sprites: Arc<[Sprite]>,
107    glyph_url: Arc<str>,
108    /// The document's `font-faces`, if it has them.
109    font_faces: Option<Arc<FontFaces>>,
110}
111
112// The map and a renderer on another thread share versions.
113const _: () = {
114    const fn assert_send_sync<T: Send + Sync>() {}
115    assert_send_sync::<Style>();
116};
117
118impl std::fmt::Debug for Style {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct("Style")
121            .field("name", &self.name)
122            .field("layers", &self.layers)
123            .field("sources", &self.sources)
124            .finish_non_exhaustive()
125    }
126}
127
128impl Style {
129    /// An empty style whose JSON, layers and filters parse against
130    /// `registry`.
131    #[must_use]
132    pub fn new(registry: Arc<StyleRegistry>) -> Self {
133        Style {
134            registry,
135            json: Arc::from(""),
136            name: Arc::from(""),
137            default_camera: StyleCamera::default(),
138            layers: Arc::default(),
139            sources: Arc::default(),
140            images: Arc::default(),
141            light: Arc::default(),
142            sky: None,
143            terrain: None,
144            projection: Arc::default(),
145            members: Arc::default(),
146            transition: TransitionOptions::default(),
147            global_state: Arc::default(),
148            global_state_defaults: Arc::default(),
149            sprites: Arc::from([]),
150            glyph_url: Arc::from(""),
151            font_faces: None,
152        }
153    }
154
155    /// The style that the style document `json` describes, parsed against
156    /// `registry`. Fails with why `json` isn't a style.
157    pub fn from_json(registry: &Arc<StyleRegistry>, json: &str) -> Result<Style, Error> {
158        let mut parser = Parser::new(registry);
159        parser.parse(json)?;
160
161        let mut style = Style::new(Arc::clone(registry));
162        style.json = Arc::from(json);
163        style.transition = parser.transition;
164        style.global_state_defaults = Arc::new(std::mem::take(&mut parser.global_state_defaults));
165        style.global_state = Arc::clone(&style.global_state_defaults);
166
167        let mut sources = SourceList::default();
168        for source in std::mem::take(&mut parser.sources) {
169            // A parsed style cannot contain duplicate source ids (they are
170            // object keys).
171            if sources.get(source.id()).is_some() {
172                tracing::error!(target: log_target::PARSE_STYLE, source_id = %source.id(), "Source already exists");
173                continue;
174            }
175            sources.set(source);
176        }
177        style.sources = Arc::new(sources);
178
179        // The parser drops duplicate layer ids, so the layers go in at once
180        // without `AddLayer`'s lookup. A layer incompatible with its source
181        // is logged and skipped.
182        let global_state = Arc::clone(&style.global_state);
183        let mut layers = LayerList::default();
184        layers.extend(std::mem::take(&mut parser.layers).into_iter().filter_map(|mut layer| {
185            if let Err(error) = check_layer_source(&style.sources, &layer) {
186                tracing::error!(target: log_target::PARSE_STYLE, %error, "Layer is invalid");
187                return None;
188            }
189            layer.reevaluate_visibility(&global_state);
190            Some(layer)
191        }));
192        style.layers = Arc::new(layers);
193
194        style.name = Arc::from(parser.name.as_str());
195        style.default_camera = StyleCamera {
196            center: Some(parser.lat_lng),
197            center_altitude: Some(parser.center_altitude),
198            zoom: Some(parser.zoom),
199            bearing: Some(parser.bearing),
200            pitch: Some(parser.pitch),
201            roll: Some(parser.roll),
202        };
203
204        style.light = Arc::new(std::mem::take(&mut parser.light));
205        style.sky = parser.sky.take().map(Arc::new);
206        style.terrain = parser
207            .terrain
208            .take()
209            .filter(|terrain| match check_terrain(&style.sources, terrain) {
210                Ok(()) => true,
211                Err(error) => {
212                    tracing::error!(target: log_target::PARSE_STYLE, %error, "Terrain is invalid");
213                    false
214                }
215            })
216            .map(Arc::new);
217        style.projection = Arc::new(std::mem::take(&mut parser.projection));
218        style.capture_projection_global_state(None);
219        style.members = Arc::new(std::mem::take(&mut parser.members));
220
221        style.sprites = Arc::from(std::mem::take(&mut parser.sprites));
222        style.glyph_url = Arc::from(parser.glyph_url.as_str());
223        style.font_faces = parser.font_faces.take();
224        Ok(style)
225    }
226
227    #[must_use]
228    pub fn registry(&self) -> &Arc<StyleRegistry> {
229        &self.registry
230    }
231
232    /// The style document, without the edits made since it parsed.
233    #[must_use]
234    pub fn json(&self) -> &str {
235        &self.json
236    }
237
238    /// The document's sprites.
239    #[must_use]
240    pub fn sprites(&self) -> &[Sprite] {
241        &self.sprites
242    }
243
244    #[must_use]
245    pub fn name(&self) -> &str {
246        &self.name
247    }
248
249    #[must_use]
250    pub fn default_camera(&self) -> StyleCamera {
251        self.default_camera
252    }
253
254    #[must_use]
255    pub fn glyph_url(&self) -> &str {
256        &self.glyph_url
257    }
258
259    #[must_use]
260    pub fn font_faces(&self) -> Option<&Arc<FontFaces>> {
261        self.font_faces.as_ref()
262    }
263
264    #[must_use]
265    pub fn transition_options(&self) -> TransitionOptions {
266        self.transition
267    }
268
269    #[must_use]
270    pub fn light(&self) -> &Arc<Light> {
271        &self.light
272    }
273
274    #[must_use]
275    pub fn sky(&self) -> Option<&Arc<Sky>> {
276        self.sky.as_ref()
277    }
278
279    #[must_use]
280    pub fn terrain(&self) -> Option<&Arc<Terrain>> {
281        self.terrain.as_ref()
282    }
283
284    #[must_use]
285    pub fn projection(&self) -> &Arc<Projection> {
286        &self.projection
287    }
288
289    /// How lng/lat maps to the world square that the style is drawn in: the
290    /// mapping of the registered projection that its projection names, if
291    /// the registry has it, else Mercator's.
292    #[must_use]
293    pub fn world(&self) -> WorldMapping {
294        self.registry.world(&self.projection)
295    }
296
297    /// The extension members of the style's root.
298    #[must_use]
299    pub fn members(&self) -> &Arc<Members> {
300        &self.members
301    }
302
303    /// What the style's `global-state` expressions read.
304    #[must_use]
305    pub fn global_state(&self) -> &Arc<GlobalStateMap> {
306        &self.global_state
307    }
308
309    /// The defaults that the style's root `state` gives.
310    #[must_use]
311    pub fn global_state_defaults(&self) -> &Arc<GlobalStateMap> {
312        &self.global_state_defaults
313    }
314
315    /// The images, sorted by id.
316    #[must_use]
317    pub fn images(&self) -> &Arc<Vec<Arc<image::StyleImage>>> {
318        &self.images
319    }
320
321    #[must_use]
322    pub fn image(&self, id: &str) -> Option<&Arc<image::StyleImage>> {
323        self.images.iter().find(|image| image.id == id)
324    }
325
326    /// The style's sources, in the order they were added.
327    #[must_use]
328    pub fn sources(&self) -> &Arc<SourceList> {
329        &self.sources
330    }
331
332    /// The source `id`.
333    #[must_use]
334    pub fn source(&self, id: &str) -> Option<&Source> {
335        self.sources.get(id)
336    }
337
338    /// The layers in drawing order, bottom first.
339    #[must_use]
340    pub fn layer_list(&self) -> &Arc<LayerList> {
341        &self.layers
342    }
343
344    /// The layers, bottom first.
345    pub fn layers(&self) -> impl DoubleEndedIterator<Item = &Layer> + ExactSizeIterator {
346        self.layers.iter()
347    }
348
349    /// The place of the layer `id` in drawing order, bottom first.
350    #[must_use]
351    pub fn layer_index(&self, layer_id: &str) -> Option<usize> {
352        self.layers.index_of(layer_id)
353    }
354
355    #[must_use]
356    pub fn layer(&self, layer_id: &str) -> Option<&Layer> {
357        self.layers.get(layer_id)
358    }
359
360    /// Makes `edit`. Fails with [`ErrorKind::NotFound`](crate::error::ErrorKind)
361    /// for a layer the style lacks, with `AlreadyExists` for a layer id it
362    /// has, and with `InvalidArgument` for a value that doesn't fit, and
363    /// leaves the style as it was when it fails. An edit that changes
364    /// nothing leaves every part's `Arc` as it was.
365    pub fn apply(&mut self, edit: Edit) -> Result<(), Error> {
366        match edit {
367            Edit::AddLayer { mut layer, before } => {
368                check_layer_source(&self.sources, &layer)?;
369                if self.layers.get(layer.id()).is_some() {
370                    return Err(Error::already_exists(format!("Layer {} already exists", layer.id())));
371                }
372                // The global state is not available while the layer itself is parsed.
373                layer.reevaluate_visibility(&self.global_state);
374                let inserted = Arc::make_mut(&mut self.layers).insert_before(layer, before.as_deref());
375                debug_assert!(inserted.is_ok());
376            }
377            Edit::RemoveLayer(id) => {
378                if self.layers.get(&id).is_none() {
379                    return Err(layer_not_found(&id));
380                }
381                Arc::make_mut(&mut self.layers).remove(&id);
382            }
383            Edit::MoveLayer { id, before } => {
384                if self.layers.get(&id).is_none() {
385                    return Err(layer_not_found(&id));
386                }
387                if before.as_deref() == Some(id.as_str()) {
388                    return Ok(());
389                }
390                Arc::make_mut(&mut self.layers).move_before(&id, before.as_deref());
391            }
392            Edit::SetLayer(layer) => {
393                check_layer_source(&self.sources, &layer)?;
394                let id = layer.id().to_owned();
395                self.update_layer(&id, |old| {
396                    *old = layer;
397                    Ok(())
398                })?;
399            }
400            Edit::SetLayerProperty { layer, name, value } => {
401                let sources = Arc::clone(&self.sources);
402                let registry = Arc::clone(&self.registry);
403                self.update_layer(&layer, |target| {
404                    set_layer_property(&registry, target, &name, &value)?;
405                    check_layer_source(&sources, target)
406                })?;
407            }
408            Edit::SetLayerFilter { layer, filter } => {
409                self.update_layer(&layer, |target| {
410                    target.set_filter(&filter);
411                    Ok(())
412                })?;
413            }
414            Edit::SetLayerZoomRange { layer, min, max } => {
415                self.update_layer(&layer, |target| {
416                    target.set_min_zoom(min);
417                    target.set_max_zoom(max);
418                    Ok(())
419                })?;
420            }
421            Edit::SetLayerVisibility { layer, visibility } => {
422                self.update_layer(&layer, |target| {
423                    target.set_visibility(visibility);
424                    Ok(())
425                })?;
426            }
427            Edit::SetLight(light) => self.light = Arc::new(light),
428            Edit::SetSky(sky) => self.sky = sky.map(Arc::new),
429            Edit::SetTerrain(terrain) => {
430                if let Some(terrain) = &terrain {
431                    check_terrain(&self.sources, terrain)?;
432                }
433                if self.terrain.as_deref() != terrain.as_ref() {
434                    self.terrain = terrain.map(Arc::new);
435                }
436            }
437            Edit::SetProjection(projection) => {
438                self.projection = Arc::new(projection);
439                self.capture_projection_global_state(None);
440            }
441            Edit::SetMember { name, value } => {
442                let value = self
443                    .registry
444                    .member_value(Place::Root, &name, &Convertible::from(&value))
445                    .map_err(|error| Error::invalid_argument(error.message))?;
446                if self.members.json(&name) != value.as_ref().map(|(json, _)| json) {
447                    Arc::make_mut(&mut self.members).set(&name, value);
448                }
449            }
450            Edit::SetTransition(options) => self.transition = options,
451            Edit::SetGlobalState { name, value } => self.set_global_state(&name, &value),
452            Edit::SetGlobalStateDefaults(defaults) => {
453                self.global_state_defaults = Arc::new(defaults);
454                self.global_state = Arc::clone(&self.global_state_defaults);
455                self.reevaluate_layer_visibilities();
456                self.capture_projection_global_state(None);
457            }
458            Edit::AddImage(image) => {
459                let images = Arc::make_mut(&mut self.images);
460                let index = images.partition_point(|other| other.id < image.id);
461                if images.get(index).is_some_and(|other| other.id == image.id) {
462                    images[index] = image;
463                } else {
464                    images.insert(index, image);
465                }
466            }
467            Edit::RemoveImage(id) => {
468                let Some(index) = self.images.iter().position(|image| image.id == id) else {
469                    tracing::warn!(target: log_target::GENERAL, image_id = %id, "Image is not present in style, cannot remove");
470                    return Ok(());
471                };
472                Arc::make_mut(&mut self.images).remove(index);
473            }
474            Edit::AddImages(images) => self.add_images(images),
475            Edit::AddSource(source) => {
476                if self.sources.get(source.id()).is_some() {
477                    return Err(Error::already_exists(format!("source \"{}\" already exists", source.id())));
478                }
479                for layer in self.layers.iter().filter(|layer| layer.source_id() == source.id()) {
480                    check_source_feeds(&source, layer)?;
481                }
482                Arc::make_mut(&mut self.sources).set(source);
483            }
484            Edit::RemoveSource(id) => {
485                if self.sources.get(&id).is_none() {
486                    return Err(source_not_found(&id));
487                }
488                Arc::make_mut(&mut self.sources).remove(&id);
489            }
490            Edit::SetSourceDescription { id, instance, load, description } => {
491                let Some(source) = self.sources.get(&id) else { return Ok(()) };
492                if source.instance() != instance || source.data().load() != load {
493                    return Ok(());
494                }
495                let source = source.with_description(description);
496                Arc::make_mut(&mut self.sources).set(source);
497            }
498            Edit::SetSourceCommon { id, common } => {
499                let source = self.sources.get(&id).ok_or_else(|| source_not_found(&id))?;
500                if *source.common() != common {
501                    let source = source.with_common(common);
502                    Arc::make_mut(&mut self.sources).set(source);
503                }
504            }
505            Edit::UpdateSource { id, update } => {
506                let source = self.sources.get(&id).ok_or_else(|| source_not_found(&id))?;
507                let instance = source.instance();
508                if let Some(source) = update(source)? {
509                    debug_assert!(source.id() == id && source.instance() == instance, "an update keeps its source");
510                    Arc::make_mut(&mut self.sources).set(source);
511                }
512            }
513        }
514        Ok(())
515    }
516
517    /// Whether `other` is the same version as `self`: every part is the same
518    /// `Arc`, and the transitions are equal. O(1): it walks nothing.
519    #[must_use]
520    pub fn is_same_version(&self, other: &Style) -> bool {
521        fn same_option<T: ?Sized>(a: Option<&Arc<T>>, b: Option<&Arc<T>>) -> bool {
522            match (a, b) {
523                (Some(a), Some(b)) => Arc::ptr_eq(a, b),
524                (None, None) => true,
525                _ => false,
526            }
527        }
528        Arc::ptr_eq(&self.layers, &other.layers)
529            && Arc::ptr_eq(&self.sources, &other.sources)
530            && Arc::ptr_eq(&self.images, &other.images)
531            && Arc::ptr_eq(&self.light, &other.light)
532            && same_option(self.sky.as_ref(), other.sky.as_ref())
533            && same_option(self.terrain.as_ref(), other.terrain.as_ref())
534            && Arc::ptr_eq(&self.projection, &other.projection)
535            && Arc::ptr_eq(&self.members, &other.members)
536            && self.transition == other.transition
537            && Arc::ptr_eq(&self.global_state, &other.global_state)
538            && Arc::ptr_eq(&self.registry, &other.registry)
539            && Arc::ptr_eq(&self.json, &other.json)
540            && Arc::ptr_eq(&self.name, &other.name)
541            && self.default_camera == other.default_camera
542            && Arc::ptr_eq(&self.sprites, &other.sprites)
543            && Arc::ptr_eq(&self.glyph_url, &other.glyph_url)
544            && same_option(self.font_faces.as_ref(), other.font_faces.as_ref())
545            && Arc::ptr_eq(&self.global_state_defaults, &other.global_state_defaults)
546    }
547
548    /// Calls `f` with a copy of the layer `id`, and keeps the copy if `f`
549    /// succeeded and changed the layer's style data, with its visibility
550    /// re-evaluated.
551    fn update_layer(&mut self, id: &str, f: impl FnOnce(&mut Layer) -> Result<(), Error>) -> Result<(), Error> {
552        let Some((index, layer)) = self.layers.get_full(id) else {
553            return Err(layer_not_found(id));
554        };
555        let mut copy = layer.clone();
556        f(&mut copy)?;
557        if !Arc::ptr_eq(layer.style(), copy.style()) {
558            copy.reevaluate_visibility(&self.global_state);
559            Arc::make_mut(&mut self.layers).replace(index, copy);
560        }
561        Ok(())
562    }
563
564    /// Sets a global state property. A null value resets the property to the
565    /// default that the style's root `state` gives (or null).
566    fn set_global_state(&mut self, property: &str, value: &Value) {
567        let mut new_value = value;
568        if matches!(value, Value::Null)
569            && let Some(default) = self.global_state_defaults.get(property)
570        {
571            new_value = default;
572        }
573        if self.global_state.get(property).is_some_and(|current| state_values_equal(current, new_value)) {
574            return;
575        }
576        Arc::make_mut(&mut self.global_state).insert(property.to_owned(), new_value.clone());
577        self.reevaluate_layer_visibilities();
578        self.capture_projection_global_state(Some(property));
579    }
580
581    /// Gives the projection the current global state if it reads the
582    /// property `changed` (any property when `None`), as a new `Arc` so the
583    /// map shares it with the transform again.
584    fn capture_projection_global_state(&mut self, changed: Option<&str>) {
585        if self.projection.reads_global_state(changed) {
586            Arc::make_mut(&mut self.projection).capture_global_state(&self.global_state);
587        }
588    }
589
590    /// Re-evaluates the visibility expressions of all layers against the
591    /// current global state.
592    fn reevaluate_layer_visibilities(&mut self) {
593        let mut changed = Vec::new();
594        for (index, layer) in self.layers.iter().enumerate() {
595            let mut copy = layer.clone();
596            copy.reevaluate_visibility(&self.global_state);
597            if !Arc::ptr_eq(layer.style(), copy.style()) {
598                changed.push((index, copy));
599            }
600        }
601        if changed.is_empty() {
602            return;
603        }
604        let layers = Arc::make_mut(&mut self.layers);
605        for (index, layer) in changed {
606            layers.replace(index, layer);
607        }
608    }
609
610    /// Adds a sprite's images, each replacing the image with its id.
611    fn add_images(&mut self, images: Vec<Arc<image::StyleImage>>) {
612        let mut new_images = (*self.images).clone();
613        let mut remaining = Vec::new();
614        for image in images {
615            let first = new_images.partition_point(|a| a.id < image.id);
616            if first < new_images.len() && image.id == new_images[first].id {
617                new_images[first] = image;
618            } else {
619                remaining.push(image);
620            }
621        }
622        new_images.extend(remaining);
623        sort::sort_by(&mut new_images, |a, b| a.id.cmp(&b.id));
624        self.images = Arc::new(new_images);
625    }
626}
627
628fn source_not_found(id: &str) -> Error {
629    Error::not_found(format!("source \"{id}\" does not exist"))
630}
631
632/// Sets the property `name` of `layer` to the style JSON `value`: a layer
633/// type's property or transition, `filter`, `minzoom`, `maxzoom`, `source`
634/// or `source-layer`, where null resets the ones with a default, or an
635/// extension member, which null unsets.
636fn set_layer_property(
637    registry: &StyleRegistry,
638    layer: &mut Layer,
639    name: &str,
640    value: &serde_json::Value,
641) -> Result<(), Error> {
642    let type_info = layer.info();
643    let id = layer.id().to_owned();
644    if is_extension_member(name) {
645        let value = registry
646            .member_value(Place::Layer, name, &Convertible::from(value))
647            .map_err(|error| Error::invalid_argument(format!("layer \"{id}\": {}", error.message)))?;
648        layer.set_member(name, value);
649        return Ok(());
650    }
651    if (name == "source" || name == "source-layer") && type_info.source == SourceKind::None {
652        // A layer that takes no source would ignore the value.
653        return Err(Error::invalid_argument(format!("{} layer \"{id}\" does not take a {name}", type_info.name)));
654    }
655    match name {
656        "filter" if value.is_null() => layer.set_filter(&Filter::default()),
657        "minzoom" if value.is_null() => layer.set_min_zoom(f64::NEG_INFINITY),
658        "maxzoom" if value.is_null() => layer.set_max_zoom(f64::INFINITY),
659        _ => {
660            if let Some(error) = layer.set_property(name, &Convertible::from(value), None) {
661                let context = format!("property \"{name}\" of layer \"{id}\"");
662                return Err(Error::invalid_argument(format!("{context}: {}", error.message)));
663            }
664        }
665    }
666    Ok(())
667}
668
669fn layer_not_found(id: &str) -> Error {
670    Error::not_found(format!("layer \"{id}\" does not exist"))
671}
672
673/// Fails when `layer`'s source is in `sources` and doesn't feed layers of
674/// the layer's type.
675fn check_layer_source(sources: &SourceList, layer: &Layer) -> Result<(), Error> {
676    match sources.get(layer.source_id()) {
677        Some(source) => check_source_feeds(source, layer),
678        None => Ok(()),
679    }
680}
681
682/// Fails when `layer` takes a source and `source` doesn't feed layers of its
683/// type.
684fn check_source_feeds(source: &Source, layer: &Layer) -> Result<(), Error> {
685    let kind = layer.info().source;
686    if !matches!(kind, SourceKind::None | SourceKind::Any) && source.info().layer_kind != kind {
687        let message = format!("Layer '{}' is not compatible with source '{}'", layer.id(), source.id());
688        return Err(Error::invalid_argument(message));
689    }
690    Ok(())
691}
692
693/// Fails when `terrain`'s exaggeration isn't a finite number of at least 0, or
694/// its source is in `sources` and isn't a `raster-dem` source. A source the
695/// style lacks passes: the terrain waits for a source with that id.
696fn check_terrain(sources: &SourceList, terrain: &Terrain) -> Result<(), Error> {
697    if !(terrain.exaggeration >= 0.0 && terrain.exaggeration.is_finite()) {
698        return Err(Error::invalid_argument("Terrain exaggeration must be a finite number of at least 0"));
699    }
700    if let Some(source) = sources.get(&terrain.source)
701        && source.info().layer_kind != SourceKind::RasterDem
702    {
703        let message = format!("Terrain source '{}' is not a raster-dem source", terrain.source);
704        return Err(Error::invalid_argument(message));
705    }
706    Ok(())
707}
708
709/// Equality on state values that, unlike the exact-type variant equality,
710/// treats numerically equal numbers of different arithmetic types as equal
711/// (e.g. a style default parsed as an integer vs. a runtime-set double).
712fn state_values_equal(a: &Value, b: &Value) -> bool {
713    fn to_double(v: &Value) -> Option<f64> {
714        match v {
715            Value::Uint(u) => Some(*u as f64),
716            Value::Int(i) => Some(*i as f64),
717            Value::Double(d) => Some(*d),
718            _ => None,
719        }
720    }
721    if let Some(a) = to_double(a) {
722        return match to_double(b) {
723            Some(b) => a == b,
724            None => false,
725        };
726    }
727    match (a, b) {
728        (Value::Array(array_a), Value::Array(array_b)) => {
729            array_a.len() == array_b.len() && array_a.iter().zip(array_b.iter()).all(|(x, y)| state_values_equal(x, y))
730        }
731        (Value::Object(object_a), Value::Object(object_b)) => {
732            if object_a.len() != object_b.len() {
733                return false;
734            }
735            object_a.iter().all(|(key, value)| match object_b.get(key) {
736                Some(other) => state_values_equal(value, other),
737                None => false,
738            })
739        }
740        _ => a == b,
741    }
742}