Skip to main content

mln_expression/
formatted.rs

1// Ports include/mln/style/expression/formatted.hpp and
2// src/mln/style/expression/formatted.cpp (incl.
3// `Converter<expression::Formatted>`).
4
5use crate::image::Image;
6use maplibre_native_base::{Value as MbglValue, ValueObject};
7use mln_conversion::{Convertible, Error};
8use mln_util::Color;
9
10pub const K_FORMATTED_SECTION_FONT_SCALE: &str = "font-scale";
11pub const K_FORMATTED_SECTION_TEXT_FONT: &str = "text-font";
12pub const K_FORMATTED_SECTION_TEXT_COLOR: &str = "text-color";
13
14/// `mln::FontStack` (include/mln/util/font_stack.hpp): an array of font
15/// names.
16// TODO(port): move to mln_util with the rest of util/font_stack.hpp.
17pub type FontStack = Vec<String>;
18
19/// `mln::fontStackToString`.
20pub fn font_stack_to_string(font_stack: &FontStack) -> String {
21    font_stack.join(",")
22}
23
24/// `expression::FormattedSection`.
25#[derive(Clone, Debug, Default, PartialEq)]
26pub struct FormattedSection {
27    pub text: String,
28    pub image: Option<Image>,
29    pub font_scale: Option<f64>,
30    pub font_stack: Option<FontStack>,
31    pub text_color: Option<Color>,
32}
33
34impl FormattedSection {
35    pub fn new(
36        text: String,
37        font_scale: Option<f64>,
38        font_stack: Option<FontStack>,
39        text_color: Option<Color>,
40    ) -> Self {
41        FormattedSection {
42            text,
43            image: None,
44            font_scale,
45            font_stack,
46            text_color,
47        }
48    }
49
50    pub fn from_image(image: Image) -> Self {
51        FormattedSection {
52            image: Some(image),
53            ..Default::default()
54        }
55    }
56}
57
58/// `expression::Formatted`.
59#[derive(Clone, Debug, Default)]
60pub struct Formatted {
61    pub sections: Vec<FormattedSection>,
62}
63
64impl PartialEq for Formatted {
65    fn eq(&self, other: &Self) -> bool {
66        if other.sections.len() != self.sections.len() {
67            return false;
68        }
69        for (this_section, other_section) in self.sections.iter().zip(&other.sections) {
70            if this_section.text != other_section.text
71                || this_section.image != other_section.image
72                || this_section.font_scale != other_section.font_scale
73                || this_section.font_stack != other_section.font_stack
74                || this_section.text_color != other_section.text_color
75            {
76                return false;
77            }
78        }
79        true
80    }
81}
82
83impl Formatted {
84    /// `Formatted(const char* plainU8String)`.
85    pub fn from_plain(plain_u8_string: &str) -> Self {
86        Formatted {
87            sections: vec![FormattedSection::new(
88                plain_u8_string.to_owned(),
89                None,
90                None,
91                None,
92            )],
93        }
94    }
95
96    pub fn new(sections: Vec<FormattedSection>) -> Self {
97        Formatted { sections }
98    }
99
100    pub fn to_string(&self) -> String {
101        let mut result = String::new();
102        for section in &self.sections {
103            result += &section.text;
104        }
105        result
106    }
107
108    pub fn to_object(&self) -> MbglValue {
109        let mut result = ValueObject::new();
110        let mut section_values = Vec::with_capacity(self.sections.len());
111        for section in &self.sections {
112            let mut serialized_section = ValueObject::new();
113            serialized_section.insert("text".to_owned(), MbglValue::String(section.text.clone()));
114            serialized_section.insert(
115                "scale".to_owned(),
116                section.font_scale.map_or(MbglValue::Null, MbglValue::Double),
117            );
118            serialized_section.insert(
119                "fontStack".to_owned(),
120                section
121                    .font_stack
122                    .as_ref()
123                    .map_or(MbglValue::Null, |f| MbglValue::String(font_stack_to_string(f))),
124            );
125            serialized_section.insert(
126                "textColor".to_owned(),
127                section
128                    .text_color
129                    .as_ref()
130                    .map_or(MbglValue::Null, Color::to_object),
131            );
132            serialized_section.insert(
133                "image".to_owned(),
134                section.image.as_ref().map_or(MbglValue::Null, Image::to_value),
135            );
136            section_values.push(MbglValue::Object(serialized_section));
137        }
138        result.insert("sections".to_owned(), MbglValue::Array(section_values));
139        MbglValue::Object(result)
140    }
141
142    pub fn empty(&self) -> bool {
143        if self.sections.is_empty() {
144            return true;
145        }
146
147        !self
148            .sections
149            .iter()
150            .any(|section| !section.text.is_empty() || section.image.as_ref().is_some_and(|i| !i.empty()))
151    }
152}
153
154/// `Converter<Color>` (src/mln/style/conversion/constant.cpp), which the
155/// Formatted converter uses.
156fn convert_color(value: &Convertible<'_>, error: &mut Error) -> Option<Color> {
157    let Some(string) = value.to_string() else {
158        error.message = "value must be a string".to_owned();
159        return None;
160    };
161
162    let color = Color::parse(&string);
163    if color.is_none() {
164        error.message = "value must be a valid color".to_owned();
165        return None;
166    }
167    color
168}
169
170/// `Converter<expression::Formatted>`.
171pub fn convert_formatted(value: &Convertible<'_>, error: &mut Error) -> Option<Formatted> {
172    if value.is_array() {
173        let mut sections = Vec::new();
174        for i in 0..value.array_length() {
175            let section = value.array_member(i);
176            let section_length = section.array_length();
177            if section_length < 1 {
178                error.message =
179                    "Section has to contain a text and std::optional parameters or an image."
180                        .to_owned();
181                return None;
182            }
183
184            let first_element = section.array_member(0);
185            if first_element.is_array() {
186                if first_element.array_length() < 2 {
187                    error.message = "Image section has to contain image name.".to_owned();
188                    return None;
189                }
190
191                let image_op = first_element.array_member(0).to_string();
192                if image_op.as_deref() != Some("image") {
193                    error.message = "Serialized image section has to contain 'image' operator.".to_owned();
194                    return None;
195                }
196
197                let Some(image_arg) = first_element.array_member(1).to_string() else {
198                    error.message =
199                        "Serialized image section argument has to be of a String type.".to_owned();
200                    return None;
201                };
202
203                sections.push(FormattedSection::from_image(Image::new(image_arg)));
204                continue;
205            }
206
207            let Some(section_text) = first_element.to_string() else {
208                error.message = "Section has to contain a text.".to_owned();
209                return None;
210            };
211
212            let mut font_scale = None;
213            let mut text_font = None;
214            let mut text_color = None;
215            if section_length > 1 {
216                let section_params = section.array_member(1);
217                if !section_params.is_object() {
218                    error.message = "Parameters have to be enclosed in an object.".to_owned();
219                    return None;
220                }
221
222                if let Some(font_scale_member) = section_params.object_member(K_FORMATTED_SECTION_FONT_SCALE) {
223                    font_scale = font_scale_member.to_double();
224                }
225
226                if let Some(text_font_member) = section_params.object_member(K_FORMATTED_SECTION_TEXT_FONT) {
227                    if text_font_member.is_array() {
228                        let mut fonts_vector = Vec::new();
229                        for j in 0..text_font_member.array_length() {
230                            if let Some(font) = text_font_member.array_member(j).to_string() {
231                                fonts_vector.push(font);
232                            } else {
233                                error.message = "Font has to be a string.".to_owned();
234                                return None;
235                            }
236                        }
237                        text_font = Some(fonts_vector);
238                    } else {
239                        error.message = "Font stack has to be an array.".to_owned();
240                        return None;
241                    }
242                }
243
244                if let Some(text_color_member) = section_params.object_member(K_FORMATTED_SECTION_TEXT_COLOR) {
245                    text_color = convert_color(&text_color_member, error);
246                    text_color?;
247                }
248            }
249
250            sections.push(FormattedSection::new(section_text, font_scale, text_font, text_color));
251        }
252        Some(Formatted::new(sections))
253    } else if let Some(result) = value.to_string() {
254        Some(Formatted::from_plain(&result))
255    } else {
256        error.message = "Formatted must be plain string or array type.".to_owned();
257        None
258    }
259}