Skip to main content

mln_style/
style.rs

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