Skip to main content

mln_style/layers/
symbol_layer.rs

1// The format section overrides: the checks of where a symbol layer's
2// properties take one, and `set_overrides`, which installs
3// `format-section-override` in its paint properties. The only overridable
4// property is `text-color`.
5
6use std::sync::Arc;
7
8use crate::collections::VecSet;
9use crate::constants::{LAST_RESORT_ALPHABETIC_FONT, LAST_RESORT_PAN_UNICODE_FONT};
10use crate::expression::forms::format::FormatExpressionSection;
11use crate::expression::forms::format_section_override::{FormatSectionOverride, OverrideDefault};
12use crate::expression::value::from_expression_value;
13use crate::expression::{Dependency, Expr, Formatted, FormattedSection, GlobalStateMap, Type};
14use crate::layer::{FontStack, LayerStyle, LayerTypeInfo, SourceKind, StyleLayerType};
15use crate::layers::symbol_layer_properties::{self, SymbolLayoutProperties, SymbolPaintProperties};
16use crate::log_target;
17use crate::property::evaluated::Evaluated;
18use crate::property::expression::PropertyExpression;
19use crate::property::set::OverridableSection;
20use crate::property::table::{PropertyTable, PropertyVisitor};
21use crate::property::value::{PropertyValue, StyleValue as _};
22
23/// The `symbol` layer type.
24pub struct Symbol;
25
26impl StyleLayerType for Symbol {
27    const INFO: LayerTypeInfo = LayerTypeInfo { name: "symbol", source: SourceKind::Geometry, from_json: true };
28    const PROPERTIES: &'static PropertyTable = &symbol_layer_properties::PROPERTIES;
29
30    type LayoutProperties = SymbolLayoutProperties::Unevaluated;
31    type PaintProperties = SymbolPaintProperties::Transitionable;
32    type Extra = ();
33
34    fn visit_property<V: PropertyVisitor<LayerStyle<Self>>>(slot: usize, visitor: V) -> Option<V::Output> {
35        symbol_layer_properties::visit(slot, visitor)
36    }
37
38    fn has_section_overrides(style: &LayerStyle<Self>) -> bool {
39        SymbolLayerPaintPropertyOverrides::has_overrides(&style.layout.text_field)
40    }
41
42    fn content_elevation(style: &LayerStyle<Self>) -> Option<&PropertyValue<f32>> {
43        Some(&style.layout.symbol_height_offset)
44    }
45
46    fn populate_font_stack(style: &LayerStyle<Self>, font_stack: &mut VecSet<FontStack>) {
47        if style.layout.text_field.is_undefined() {
48            return;
49        }
50
51        match &style.layout.text_font {
52            PropertyValue::Undefined => {
53                font_stack
54                    .insert(vec![LAST_RESORT_ALPHABETIC_FONT.to_owned(), LAST_RESORT_PAN_UNICODE_FONT.to_owned()]);
55            }
56            PropertyValue::Constant(constant) => {
57                font_stack.insert(constant.clone());
58            }
59            PropertyValue::Expression(function) => {
60                for value in function.possible_outputs() {
61                    if let Some(value) = value {
62                        font_stack.insert(value);
63                    } else {
64                        tracing::warn!(
65                            target: log_target::PARSE_STYLE,
66                            layer_id = %style.id,
67                            "Layer has an invalid value for text-font and will not render text. Output \
68                             values must be contained as literals within the expression."
69                        );
70                        break;
71                    }
72                }
73            }
74        }
75    }
76}
77
78/// The alternatives of a `PropertyValue<Formatted>` or an
79/// `Evaluated<Formatted>` that `has_override` reads.
80pub enum FormattedValue<'a> {
81    Undefined,
82    Constant(&'a Formatted),
83    Expression(&'a PropertyExpression<Formatted>),
84}
85
86pub trait AsFormattedValue {
87    fn as_formatted_value(&self) -> FormattedValue<'_>;
88}
89
90impl AsFormattedValue for PropertyValue<Formatted> {
91    fn as_formatted_value(&self) -> FormattedValue<'_> {
92        match self {
93            PropertyValue::Undefined => FormattedValue::Undefined,
94            PropertyValue::Constant(c) => FormattedValue::Constant(c),
95            PropertyValue::Expression(e) => FormattedValue::Expression(e),
96        }
97    }
98}
99
100impl AsFormattedValue for Evaluated<Formatted> {
101    fn as_formatted_value(&self) -> FormattedValue<'_> {
102        match self {
103            Evaluated::Constant(c) => FormattedValue::Constant(c),
104            Evaluated::CrossFaded(faded) => FormattedValue::Constant(&faded.to),
105            Evaluated::PerFeature { expression, .. } => FormattedValue::Expression(expression),
106        }
107    }
108}
109
110/// The format section overrides of the symbol paint properties. The only
111/// overridable property is `text-color`, so the checks are written out for it
112/// rather than folded over a list of overridable properties.
113pub struct SymbolLayerPaintPropertyOverrides;
114
115impl SymbolLayerPaintPropertyOverrides {
116    /// Whether a section of `formatted` overrides a property, as the property's
117    /// `has_override` for each section type tells.
118    fn has_override(
119        formatted: &dyn AsFormattedValue,
120        section_has_override: fn(&FormattedSection) -> bool,
121        expression_section_has_override: fn(&FormatExpressionSection) -> bool,
122    ) -> bool {
123        let check_literal = |literal: &Formatted| -> bool {
124            for section in &literal.sections {
125                if section_has_override(section) {
126                    return true;
127                }
128            }
129            false
130        };
131
132        match formatted.as_formatted_value() {
133            FormattedValue::Constant(literal) => check_literal(literal),
134            FormattedValue::Expression(property) => {
135                fn check_expression<'a>(
136                    e: &'a Expr,
137                    found: &mut bool,
138                    check_literal: &dyn Fn(&Formatted) -> bool,
139                    expression_section_has_override: fn(&FormatExpressionSection) -> bool,
140                ) {
141                    if *found {
142                        return;
143                    }
144
145                    if let Some(literal) = e.literal_value()
146                        && e.ty() == Type::Formatted
147                    {
148                        let formatted_value = from_expression_value::<Formatted>(literal);
149                        if let Some(formatted_value) = formatted_value
150                            && check_literal(&formatted_value)
151                        {
152                            *found = true;
153                        }
154                    } else if let Some(format_expr) = e.as_format() {
155                        for section in format_expr.sections() {
156                            if expression_section_has_override(section) {
157                                *found = true;
158                                break;
159                            }
160                        }
161                    } else {
162                        e.each_child(&mut |child| {
163                            check_expression(child, found, check_literal, expression_section_has_override);
164                        });
165                    }
166                }
167
168                let mut expression_has_overrides = false;
169                check_expression(
170                    property.expression(),
171                    &mut expression_has_overrides,
172                    &check_literal,
173                    expression_section_has_override,
174                );
175                expression_has_overrides
176            }
177            FormattedValue::Undefined => false,
178        }
179    }
180
181    /// Whether `formatted` overrides any overridable property.
182    pub fn has_overrides(formatted: &dyn AsFormattedValue) -> bool {
183        let mut result = false;
184        result |=
185            Self::has_override(formatted, FormattedSection::has_text_color, FormatExpressionSection::has_text_color);
186        result
187    }
188}
189
190/// A `format-section-override` of the color property `property_name`, whose
191/// value is `default_value` where no section overrides it.
192pub(crate) fn format_section_override(default_value: Evaluated<crate::color::Color>, property_name: String) -> Expr {
193    let default_value = match default_value {
194        Evaluated::Constant(color) => OverrideDefault::Constant(color),
195        Evaluated::CrossFaded(faded) => OverrideDefault::Constant(faded.to),
196        Evaluated::PerFeature { expression, .. } => OverrideDefault::Expression {
197            expression: Arc::clone(expression.shared_expression()),
198            captured_global_state: expression.captured_global_state().cloned(),
199        },
200    };
201    FormatSectionOverride::new_expr(default_value, property_name)
202}
203
204pub fn set_overrides(
205    overrides: &SymbolLayoutProperties::Unevaluated,
206    overridable: &mut SymbolPaintProperties::PossiblyEvaluated,
207    unevaluated: &SymbolPaintProperties::Unevaluated,
208    global_state: Option<&Arc<GlobalStateMap>>,
209) {
210    if !SymbolLayerPaintPropertyOverrides::has_overrides(&overrides.text_field) {
211        return;
212    }
213    let value = &mut overridable.text_color;
214    // Wrapping a folded constant would drop the GlobalState dependency from
215    // the wrapper and exempt the bucket from relayout tracking.
216    if value.is_constant() {
217        let unevaluated_value = unevaluated.text_color.value();
218        if let Some(expression) = unevaluated_value.as_expression()
219            && unevaluated_value.dependencies().intersects(Dependency::GLOBAL_STATE)
220        {
221            let mut retained = expression.clone();
222            retained.capture_global_state(global_state.cloned());
223            *value =
224                Evaluated::PerFeature { expression: retained, default: SymbolPaintProperties::Defaults::text_color() };
225        }
226    }
227    let override_ = format_section_override(std::mem::take(value), "text-color".to_owned());
228    *value = Evaluated::PerFeature {
229        expression: PropertyExpression::new(Arc::new(override_)),
230        default: SymbolPaintProperties::Defaults::text_color(),
231    };
232}