mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Layers of any type: a style's [`Layer`]s and their list ([`LayerList`]),
//! their conversion from style JSON ([`convert_layer`]), and the contract a
//! layer type implements ([`StyleLayerType`]).

// A layer cannot point back at the style that owns it, so a style edits a
// copy of its layer (`Style::update_layer`) and keeps the copy if the
// layer's style data changed. A change copies the style data when it is
// shared, as it is while the style still holds the original, and leaves it
// alone when the value doesn't change.

use std::any::Any;
use std::sync::Arc;

use crate::collections::VecSet;
use crate::conversion::{Converter, Convertible, Error, convert};
use crate::expression::{
    Dependency, EvaluationContext, Expr, Functions, GlobalStateMap, ParsingContext, Type, from_expression_value,
};
use crate::feature::{Value, ValueObject};
use crate::filter::{Filter, convert_filter};
use crate::log_target;
use crate::member::Members;
use crate::property::table::{SetPropertyError, StyleProperty};
use crate::registry::{MemberValue, StyleRegistry};
use crate::types::VisibilityType;

mod convert;
mod list;
mod type_;

pub use convert::convert_layer;
pub(crate) use convert::{InvalidProperty, convert_layer_with, set_paint_properties};
pub use list::LayerList;
pub use type_::{
    ErasedLayerStyle, ErasedStyleLayerType, LayerBase, LayerStyle, LayerTypeEntry, LayerTypeInfo, LayoutSet,
    NoProperties, PaintSet, SourceKind, StyleLayerType, style_entry,
};

pub(crate) type FontStack = Vec<String>;

/// The font stacks `layers` use, found by statically evaluating their
/// `text-font` values.
pub fn font_stacks<L: AsRef<dyn ErasedLayerStyle>>(layers: impl IntoIterator<Item = L>) -> VecSet<FontStack> {
    let mut result = VecSet::new();
    for layer in layers {
        layer.as_ref().populate_font_stack(&mut result);
    }
    result
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PropertyScope {
    Paint,
    Layout,
}

/// A layer from the MapLibre Style Spec, of any layer type: its style data,
/// and the expression functions its property values parse against. A clone
/// shares them until either changes.
#[derive(Clone)]
pub struct Layer {
    style: Arc<dyn ErasedLayerStyle>,
    functions: Arc<Functions>,
    /// What the layer keeps alive for its style data, which only refers to
    /// it (see [`Layer::from_style_holding`]).
    held: Option<Arc<dyn Any + Send + Sync>>,
}

impl Layer {
    /// A layer of the type named `type_` in `registry`, named `id`, of the
    /// source `source`, with every property undefined.
    ///
    /// # Errors
    ///
    /// When `registry` has no layer type named `type_`, or one whose layers
    /// can't be made by name, such as a type whose style data needs an
    /// object from the caller.
    pub fn new(registry: &StyleRegistry, type_: &str, id: &str, source: &str) -> Result<Layer, crate::error::Error> {
        let Some(layer_type) = registry.layer_type(type_) else {
            return Err(crate::error::Error::invalid_argument(format!("unknown layer type '{type_}'")));
        };
        if !layer_type.info().from_json {
            return Err(crate::error::Error::invalid_argument(format!(
                "layer type '{type_}' can't be created by name"
            )));
        }
        Ok(Layer::from_style(layer_type.create(id, source), Arc::clone(registry.functions())))
    }

    /// The layer of `style`, whose property values parse against
    /// `functions`.
    #[must_use]
    pub fn from_style(style: Arc<dyn ErasedLayerStyle>, functions: Arc<Functions>) -> Layer {
        Layer { style, functions, held: None }
    }

    /// The layer of `style`, as [`Layer::from_style`] makes, that also keeps
    /// `held` alive while it or a copy of it lives: for style data that
    /// refers to an object only weakly, so that a renderer holding the data
    /// doesn't keep the object.
    #[must_use]
    pub fn from_style_holding(
        style: Arc<dyn ErasedLayerStyle>,
        functions: Arc<Functions>,
        held: Arc<dyn Any + Send + Sync>,
    ) -> Layer {
        Layer { style, functions, held: Some(held) }
    }

    #[must_use]
    pub fn style(&self) -> &Arc<dyn ErasedLayerStyle> {
        &self.style
    }

    /// Changes the base members, copying the style data if it is shared.
    fn mutate_base(&mut self, f: &mut dyn FnMut(&mut LayerBase)) {
        self.style.layer_type().mutate_base(&mut self.style, f);
    }

    #[must_use]
    pub fn property(&self, name: &str) -> StyleProperty {
        self.style.property(name)
    }

    /// The expression functions that the layer's property values, filter and
    /// visibility parse against.
    #[must_use]
    pub fn functions(&self) -> &Arc<Functions> {
        &self.functions
    }

    #[must_use]
    pub fn serialize(&self) -> Value {
        let mut result = ValueObject::new();
        result.insert("id".to_owned(), Value::String(self.id().to_owned()));
        result.insert("type".to_owned(), Value::String(self.info().name.to_owned()));

        let source = self.source_id();
        if !source.is_empty() {
            result.insert("source".to_owned(), Value::String(source.to_owned()));
        }

        let source_layer = self.source_layer();
        if !source_layer.is_empty() {
            result.insert("source-layer".to_owned(), Value::String(source_layer.to_owned()));
        }

        if self.filter().is_set() {
            result.insert("filter".to_owned(), self.filter().serialize());
        }

        if self.min_zoom() != f64::NEG_INFINITY {
            result.insert("minzoom".to_owned(), Value::Double(self.min_zoom()));
        }

        if self.max_zoom() != f64::INFINITY {
            result.insert("maxzoom".to_owned(), Value::Double(self.max_zoom()));
        }

        if let Some(expression) = &self.style.base().visibility_expression {
            let mut layout = ValueObject::new();
            layout.insert("visibility".to_owned(), expression.serialize());
            result.insert("layout".to_owned(), Value::Object(layout));
        } else if self.visibility() == VisibilityType::None {
            let mut layout = ValueObject::new();
            layout.insert("visibility".to_owned(), Value::String("none".to_owned()));
            result.insert("layout".to_owned(), Value::Object(layout));
        }

        self.style.serialize_properties(&mut result);
        self.style.base().members.serialize(&mut result);
        Value::Object(result)
    }

    /// The layer's extension members.
    #[must_use]
    pub fn members(&self) -> &Members {
        &self.style.base().members
    }

    /// Sets the extension member `name` to `value`, or with `None` unsets
    /// it, copying the style data only when the member changes.
    pub(crate) fn set_member(&mut self, name: &str, value: Option<MemberValue>) {
        let held = self.members().json(name);
        if held == value.as_ref().map(|(json, _)| json) {
            return;
        }
        let mut value = value;
        self.mutate_base(&mut |base| base.members.set(name, value.take()));
    }

    /// A layer named `id` with this layer's members and properties but its
    /// paint properties, which keeps alive what this layer does.
    #[must_use]
    pub fn clone_ref(&self, id: &str) -> Layer {
        Layer {
            style: self.style.copy_without_paint(id),
            functions: Arc::clone(&self.functions),
            held: self.held.clone(),
        }
    }

    /// Sets the property `name` (a property of the layer's type, its
    /// `<name>-transition`, or a member every layer has) from a style JSON
    /// value. Returns why it fails.
    pub fn set_property(
        &mut self,
        name: &str,
        value: &Convertible<'_>,
        _scope: Option<PropertyScope>,
    ) -> Option<Error> {
        let layer_type = self.style.layer_type();
        let mut error = match layer_type.set_property(&mut self.style, name, value, &self.functions) {
            Ok(()) => return None,
            Err(SetPropertyError::Invalid(error)) => error,
            Err(SetPropertyError::Unknown) => {
                Error::new(format!("layer '{}' doesn't support property '{}'", self.id(), name))
            }
        };
        if name == "visibility" {
            return self.set_visibility_value(value);
        }
        if name == "minzoom" {
            if let Some(zoom) = convert::<f64>(value, &mut error) {
                self.set_min_zoom(zoom);
                return None;
            }
        } else if name == "maxzoom" {
            if let Some(zoom) = convert::<f64>(value, &mut error) {
                self.set_max_zoom(zoom);
                return None;
            }
        } else if name == "filter" {
            if let Some(filter) = convert_filter(value, &self.functions, &mut error) {
                self.set_filter(&filter);
                return None;
            }
        } else if name == "source-layer" {
            if let Some(source_layer) = convert::<String>(value, &mut error) {
                if self.info().source == SourceKind::None {
                    tracing::warn!(
                        target: log_target::GENERAL,
                        layer_id = %self.style.base().id,
                        "'source-layer' property cannot be set on the layer"
                    );
                    return None;
                }
                self.set_source_layer(&source_layer);
                return None;
            }
        } else if name == "source"
            && let Some(source_id) = convert::<String>(value, &mut error)
        {
            if self.info().source == SourceKind::None {
                tracing::warn!(
                    target: log_target::GENERAL,
                    layer_id = %self.style.base().id,
                    "'source' property cannot be set on the layer"
                );
                return None;
            }
            self.set_source_id(&source_id);
            return None;
        }
        Some(error)
    }

    fn set_visibility_value(&mut self, value: &Convertible<'_>) -> Option<Error> {
        if value.is_undefined() {
            self.set_visibility(VisibilityType::Visible);
            return None;
        }

        if value.is_array() {
            // Per the style specification, visibility expressions may only use "global-state".
            let mut ctx = ParsingContext::with_expected(&self.functions, Type::String);
            let Some(parsed) = ctx.parse_expression(value, None) else {
                return Some(Error::new(ctx.combined_errors()));
            };
            let allowed = Dependency::GLOBAL_STATE | Dependency::BIND | Dependency::VAR;
            if (parsed.dependencies() | allowed) != allowed {
                return Some(Error::new(r#"visibility expressions may only use the "global-state" expression"#));
            }

            // The layer may not belong to a style yet, so its global state is not
            // available here. The style reevaluates the expression when the layer
            // is added or changed.
            let expression: Arc<Expr> = Arc::from(parsed);
            self.mutate_base(&mut |base| base.visibility_expression = Some(Arc::clone(&expression)));
            return None;
        }

        let mut error = Error::default();
        let visibility = <VisibilityType as Converter>::convert(value, &mut error);
        match visibility {
            Some(visibility) => {
                self.set_visibility(visibility);
                None
            }
            None => Some(error),
        }
    }

    #[must_use]
    pub fn id(&self) -> &str {
        &self.style.base().id
    }

    #[must_use]
    pub fn source_id(&self) -> &str {
        &self.style.base().source
    }

    #[must_use]
    pub fn source_layer(&self) -> &str {
        &self.style.base().source_layer
    }

    pub fn set_source_layer(&mut self, source_layer: &str) {
        if self.style.base().source_layer == source_layer {
            return;
        }
        self.mutate_base(&mut |base| base.source_layer = source_layer.to_owned());
    }

    pub fn set_source_id(&mut self, source_id: &str) {
        if self.style.base().source == source_id {
            return;
        }
        self.mutate_base(&mut |base| base.source = source_id.to_owned());
    }

    #[must_use]
    pub fn filter(&self) -> Filter {
        self.style.base().filter.clone()
    }

    pub fn set_filter(&mut self, filter: &Filter) {
        if self.style.base().filter == *filter {
            return;
        }
        self.mutate_base(&mut |base| base.filter = filter.clone());
    }

    #[must_use]
    pub fn visibility(&self) -> VisibilityType {
        self.style.base().visibility
    }

    pub fn set_visibility(&mut self, value: VisibilityType) {
        if value == self.visibility() && self.style.base().visibility_expression.is_none() {
            return;
        }
        self.mutate_base(&mut |base| {
            base.visibility = value;
            // Setting a constant visibility replaces any visibility expression.
            base.visibility_expression = None;
        });
    }

    /// Re-evaluates the layer's visibility expression (a "visibility" layout
    /// value using "global-state"), if any, against the given global state.
    pub fn reevaluate_visibility(&mut self, global_state: &GlobalStateMap) {
        let Some(expression) = &self.style.base().visibility_expression else {
            return;
        };
        let value = evaluate_visibility_expression(expression.as_ref(), global_state);
        if value == self.style.base().visibility {
            return;
        }
        self.mutate_base(&mut |base| base.visibility = value);
    }

    /// The serialized visibility expression, or a null value when the
    /// visibility is a constant.
    #[must_use]
    pub fn visibility_expression(&self) -> Value {
        match &self.style.base().visibility_expression {
            Some(expression) => expression.serialize(),
            None => Value::Null,
        }
    }

    #[must_use]
    pub fn min_zoom(&self) -> f64 {
        self.style.base().min_zoom
    }

    #[must_use]
    pub fn max_zoom(&self) -> f64 {
        self.style.base().max_zoom
    }

    pub fn set_min_zoom(&mut self, min_zoom: f64) {
        if self.min_zoom() == min_zoom {
            return;
        }
        self.mutate_base(&mut |base| base.min_zoom = min_zoom);
    }

    pub fn set_max_zoom(&mut self, max_zoom: f64) {
        if self.max_zoom() == max_zoom {
            return;
        }
        self.mutate_base(&mut |base| base.max_zoom = max_zoom);
    }

    #[must_use]
    pub fn info(&self) -> LayerTypeInfo {
        self.style.info()
    }
}

fn evaluate_visibility_expression(expression: &Expr, global_state: &GlobalStateMap) -> VisibilityType {
    let result = expression.evaluate(&EvaluationContext::default().with_global_state(Some(global_state)));
    if let Ok(result) = result
        && let Some(string) = from_expression_value::<String>(&result)
        && let Ok(visibility) = string.parse::<VisibilityType>()
    {
        return visibility;
    }
    tracing::warn!(
        target: log_target::PARSE_STYLE,
        r#"visibility expression did not evaluate to "visible" or "none"; defaulting to "visible""#
    );
    VisibilityType::Visible
}

// Prints what tells layers apart rather than every property.
impl std::fmt::Debug for Layer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Layer")
            .field("id", &self.style.base().id)
            .field("type", &self.info().name)
            .finish_non_exhaustive()
    }
}