Skip to main content

mln_expression/
format_expression.rs

1// Ports include/mln/style/expression/format_expression.hpp and
2// src/mln/style/expression/format_expression.cpp.
3
4use crate::expression::{
5    Dependency, EvaluationContext, EvaluationError, EvaluationResult, Expression, ExpressionBase,
6    Kind, downcast,
7};
8use crate::formatted::{
9    FontStack, Formatted, FormattedSection, K_FORMATTED_SECTION_FONT_SCALE,
10    K_FORMATTED_SECTION_TEXT_COLOR, K_FORMATTED_SECTION_TEXT_FONT,
11};
12use crate::parsing_context::{ParseResult, ParsingContext};
13use crate::type_::Type;
14use crate::value::{Value, from_expression_value, to_string, type_of};
15use maplibre_native_base::{Value as MbglValue, ValueObject};
16use mln_conversion::Convertible;
17use mln_util::Color;
18use std::sync::Arc;
19
20/// `FormatExpressionSection`.
21#[derive(Clone)]
22pub struct FormatExpressionSection {
23    /// Content can be expression that evaluates to String or Image.
24    pub content: Arc<dyn Expression>,
25
26    // Text related section options.
27    pub font_scale: Option<Arc<dyn Expression>>,
28    pub text_font: Option<Arc<dyn Expression>>,
29    pub text_color: Option<Arc<dyn Expression>>,
30}
31
32impl FormatExpressionSection {
33    pub fn new(content: Box<dyn Expression>) -> Self {
34        FormatExpressionSection {
35            content: Arc::from(content),
36            font_scale: None,
37            text_font: None,
38            text_color: None,
39        }
40    }
41
42    pub fn set_text_section_options(
43        &mut self,
44        font_scale: Option<Box<dyn Expression>>,
45        text_font: Option<Box<dyn Expression>>,
46        text_color: Option<Box<dyn Expression>>,
47    ) {
48        if let Some(font_scale) = font_scale {
49            self.font_scale = Some(Arc::from(font_scale));
50        }
51        if let Some(text_font) = text_font {
52            self.text_font = Some(Arc::from(text_font));
53        }
54        if let Some(text_color) = text_color {
55            self.text_color = Some(Arc::from(text_color));
56        }
57    }
58
59    fn deps(&self) -> Dependency {
60        let opt = |e: &Option<Arc<dyn Expression>>| e.as_ref().map_or(Dependency::NONE, |e| e.dependencies());
61        self.content.dependencies() | opt(&self.font_scale) | opt(&self.text_font) | opt(&self.text_color)
62    }
63}
64
65pub struct FormatExpression {
66    base: ExpressionBase,
67    sections: Vec<FormatExpressionSection>,
68}
69
70fn opt_equal(l: &Option<Arc<dyn Expression>>, r: &Option<Arc<dyn Expression>>) -> bool {
71    match (l, r) {
72        (Some(l), Some(r)) => l.equals(&**r),
73        (None, None) => true,
74        _ => false,
75    }
76}
77
78impl FormatExpression {
79    pub fn new(sections: Vec<FormatExpressionSection>) -> Self {
80        let deps = sections.iter().fold(Dependency::NONE, |a, s| a | s.deps());
81        FormatExpression {
82            base: ExpressionBase::new(Kind::FormatExpression, Type::Formatted, deps),
83            sections,
84        }
85    }
86
87    pub fn get_sections(&self) -> &[FormatExpressionSection] {
88        &self.sections
89    }
90
91    pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
92        let args_length = value.array_length();
93        if args_length < 2 {
94            ctx.error("Expected at least one argument.".to_owned());
95            return None;
96        }
97
98        if value.array_member(1).is_object() {
99            ctx.error("First argument must be an image or text section.".to_owned());
100            return None;
101        }
102
103        let mut sections: Vec<FormatExpressionSection> = Vec::new();
104        let mut next_token_may_be_object = false;
105        for i in 1..args_length {
106            let arg = value.array_member(i);
107
108            if next_token_may_be_object && arg.is_object() {
109                next_token_may_be_object = false;
110
111                let mut font_scale = None;
112                if let Some(option) = arg.object_member(K_FORMATTED_SECTION_FONT_SCALE) {
113                    font_scale = Some(ctx.parse(&option, 1, Some(Type::Number), None)?);
114                }
115
116                let mut text_font = None;
117                if let Some(option) = arg.object_member(K_FORMATTED_SECTION_TEXT_FONT) {
118                    text_font = Some(ctx.parse(&option, 1, Some(Type::array(Type::String)), None)?);
119                }
120
121                let mut text_color = None;
122                if let Some(option) = arg.object_member(K_FORMATTED_SECTION_TEXT_COLOR) {
123                    text_color = Some(ctx.parse(&option, 1, Some(Type::Color), None)?);
124                }
125
126                sections
127                    .last_mut()
128                    .expect("a section before its options")
129                    .set_text_section_options(font_scale, text_font, text_color);
130            } else {
131                let Some(parsed_arg) = ctx.parse(&arg, 1, Some(Type::Value), None) else {
132                    ctx.error("Cannot parse formatted section.".to_owned());
133                    return None;
134                };
135
136                next_token_may_be_object = true;
137                sections.push(FormatExpressionSection::new(parsed_arg));
138            }
139        }
140
141        Some(Box::new(FormatExpression::new(sections)))
142    }
143}
144
145impl Expression for FormatExpression {
146    fn base(&self) -> &ExpressionBase {
147        &self.base
148    }
149
150    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
151        let mut evaluated_sections = Vec::new();
152        for section in &self.sections {
153            let content_result = section.content.evaluate(params)?;
154
155            let evaluated_text;
156            if type_of(&content_result) == Type::Image {
157                let Value::Image(image) = &content_result else { unreachable!() };
158                // Omit sections with empty image ids.
159                if !image.id().is_empty() {
160                    evaluated_sections.push(FormattedSection::from_image(image.clone()));
161                }
162                // Continue evaluation of a next section, as the image section
163                // does not have section options.
164                continue;
165            } else {
166                // `toString(Value)` always produces a string.
167                evaluated_text = to_string(&content_result);
168            }
169
170            let mut evaluated_font_scale = None;
171            if let Some(font_scale) = &section.font_scale {
172                let font_scale_result = font_scale.evaluate(params)?;
173                evaluated_font_scale = Some(font_scale_result.as_number().expect("numeric font-scale"));
174            }
175
176            let mut evaluated_text_font: Option<FontStack> = None;
177            if let Some(text_font) = &section.text_font {
178                let text_font_result = text_font.evaluate(params)?;
179                let Some(text_font_value) = from_expression_value::<Vec<String>>(&text_font_result) else {
180                    return Err(EvaluationError::new(
181                        "Format text-font option must evaluate to an array of strings",
182                    ));
183                };
184                evaluated_text_font = Some(text_font_value);
185            }
186
187            let mut evaluated_text_color = None;
188            if let Some(text_color) = &section.text_color {
189                let text_color_result = text_color.evaluate(params)?;
190
191                evaluated_text_color = from_expression_value::<Color>(&text_color_result);
192                if evaluated_text_color.is_none() {
193                    return Err(EvaluationError::new("Format text-color option must evaluate to Color"));
194                }
195            }
196            evaluated_sections.push(FormattedSection::new(
197                evaluated_text,
198                evaluated_font_scale,
199                evaluated_text_font,
200                evaluated_text_color,
201            ));
202        }
203        Ok(Value::Formatted(Formatted::new(evaluated_sections)))
204    }
205
206    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
207        for section in &self.sections {
208            visit(&*section.content);
209            if let Some(font_scale) = &section.font_scale {
210                visit(&**font_scale);
211            }
212            if let Some(text_font) = &section.text_font {
213                visit(&**text_font);
214            }
215            if let Some(text_color) = &section.text_color {
216                visit(&**text_color);
217            }
218        }
219    }
220
221    fn equals(&self, e: &dyn Expression) -> bool {
222        if e.get_kind() == Kind::FormatExpression {
223            let rhs = downcast::<FormatExpression>(e).expect("FormatExpression");
224            if self.sections.len() != rhs.sections.len() {
225                return false;
226            }
227            for (lhs_section, rhs_section) in self.sections.iter().zip(&rhs.sections) {
228                if !lhs_section.content.equals(&*rhs_section.content) {
229                    return false;
230                }
231                if !opt_equal(&lhs_section.font_scale, &rhs_section.font_scale)
232                    || !opt_equal(&lhs_section.text_font, &rhs_section.text_font)
233                    || !opt_equal(&lhs_section.text_color, &rhs_section.text_color)
234                {
235                    return false;
236                }
237            }
238            return true;
239        }
240        false
241    }
242
243    fn possible_outputs(&self) -> Vec<Option<Value>> {
244        // Technically the combinatoric set of all children
245        // Usually, this.text will be undefined anyway
246        vec![None]
247    }
248
249    fn serialize(&self) -> MbglValue {
250        let mut serialized = vec![MbglValue::String(self.get_operator())];
251        for section in &self.sections {
252            serialized.push(section.content.serialize());
253            let mut options = ValueObject::new();
254            if let Some(font_scale) = &section.font_scale {
255                options.insert(K_FORMATTED_SECTION_FONT_SCALE.to_owned(), font_scale.serialize());
256            }
257            if let Some(text_font) = &section.text_font {
258                options.insert(K_FORMATTED_SECTION_TEXT_FONT.to_owned(), text_font.serialize());
259            }
260            if let Some(text_color) = &section.text_color {
261                options.insert(K_FORMATTED_SECTION_TEXT_COLOR.to_owned(), text_color.serialize());
262            }
263            serialized.push(MbglValue::Object(options));
264        }
265        MbglValue::Array(serialized)
266    }
267
268    fn get_operator(&self) -> String {
269        "format".to_owned()
270    }
271}