Skip to main content

mln_style/expression/forms/
image.rs

1use std::cell::Cell;
2
3use crate::collections::VecSet;
4use crate::conversion::Convertible;
5use crate::expression::image::Image;
6use crate::expression::parse::{ParseResult, ParsingContext};
7use crate::expression::type_::Type;
8use crate::expression::value::{Value, to_string};
9use crate::expression::{EvaluationContext, EvaluationResult, Expr, Node};
10use crate::feature::Value as FeatureValue;
11
12/// Collects the images that `image` expressions find unavailable. An
13/// evaluation whose [`EvaluationContext`] carries both the available images
14/// and a collector records each non-empty id it doesn't find. A tile layout
15/// asks for these images too, so that it is redone when one is added, even
16/// where a `coalesce` fell back past it.
17#[derive(Default)]
18pub struct UnavailableImages {
19    // A `Cell`, as evaluation reaches the collector through a shared
20    // context; `record` takes the set out and puts it back.
21    ids: Cell<VecSet<String>>,
22}
23
24impl UnavailableImages {
25    #[must_use]
26    pub fn new() -> Self {
27        UnavailableImages::default()
28    }
29
30    fn record(&self, id: &str) {
31        let mut ids = self.ids.take();
32        if !ids.contains(id) {
33            ids.insert(id.to_owned());
34        }
35        self.ids.set(ids);
36    }
37
38    /// The images recorded.
39    #[must_use]
40    pub fn into_inner(self) -> VecSet<String> {
41        self.ids.into_inner()
42    }
43}
44
45/// `["image", id]`: the image of an id, and whether it is available.
46#[derive(Clone, PartialEq, mln_wire::Wire)]
47pub struct ImageExpression {
48    image_id: Expr,
49}
50
51impl ImageExpression {
52    #[must_use]
53    pub fn new_expr(image_id: Expr) -> Expr {
54        Expr::new(Node::Image(Box::new(ImageExpression { image_id })))
55    }
56
57    pub(crate) fn image_id(&self) -> &Expr {
58        &self.image_id
59    }
60
61    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
62        if value.array_length() != 2 {
63            ctx.error("Expected two arguments.".to_owned());
64            return None;
65        }
66
67        // Parse expression that evaluates to image id.
68        let image_id_arg = value.array_member(1);
69        let image_id_expr = ctx.parse(&image_id_arg, 1, Some(Type::String), None)?;
70
71        Some(ImageExpression::new_expr(image_id_expr))
72    }
73
74    pub(crate) fn evaluate(&self, ctx: &EvaluationContext<'_>) -> EvaluationResult {
75        let image_id_result = self.image_id.evaluate(ctx)?;
76
77        // Any value converts to a string.
78        let evaluated_image_id = to_string(&image_id_result);
79
80        let Some(available_images) = ctx.available_images else {
81            return Ok(Value::Image(Image::with_available(evaluated_image_id, false)));
82        };
83        let available = available_images.contains(&evaluated_image_id);
84        if !available
85            && !evaluated_image_id.is_empty()
86            && let Some(unavailable_images) = ctx.unavailable_images
87        {
88            unavailable_images.record(&evaluated_image_id);
89        }
90        Ok(Value::Image(Image::with_available(evaluated_image_id, available)))
91    }
92
93    pub(crate) fn serialize(&self) -> FeatureValue {
94        FeatureValue::Array(vec![FeatureValue::String("image".to_owned()), self.image_id.serialize()])
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::expression::Functions;
102
103    /// Three images, of which a coalesce passes over the first two.
104    fn coalesce() -> Expr {
105        let document = serde_json::json!(["coalesce", ["image", "late"], ["image", ""], ["image", "fallback"]]);
106        ParsingContext::with_expected(&Functions::with_builtins(), Type::Image)
107            .parse_expression(&Convertible::from(&document), None)
108            .unwrap()
109    }
110
111    fn evaluate(expression: &Expr, available: Option<&VecSet<String>>, unavailable: Option<&UnavailableImages>) {
112        let context = EvaluationContext::new(0.0).with_available_images(available).with_unavailable_images(unavailable);
113        expression.evaluate(&context).unwrap();
114    }
115
116    #[test]
117    fn records_the_named_images_coalesce_passes_over_once() {
118        let available: VecSet<String> = ["fallback".to_owned()].into_iter().collect();
119        let unavailable = UnavailableImages::new();
120        evaluate(&coalesce(), Some(&available), Some(&unavailable));
121        evaluate(&coalesce(), Some(&available), Some(&unavailable));
122        assert_eq!(unavailable.into_inner().into_iter().collect::<Vec<_>>(), ["late"]);
123    }
124
125    #[test]
126    fn records_nothing_without_available_images() {
127        let unavailable = UnavailableImages::new();
128        evaluate(&coalesce(), None, Some(&unavailable));
129        assert!(unavailable.into_inner().is_empty());
130    }
131
132    #[test]
133    fn collectors_record_only_their_own_evaluations() {
134        let (first, second) = (UnavailableImages::new(), UnavailableImages::new());
135        evaluate(&coalesce(), Some(&VecSet::new()), Some(&first));
136        evaluate(&coalesce(), Some(&VecSet::new()), None);
137        assert_eq!(first.into_inner().len(), 2);
138        assert!(second.into_inner().is_empty());
139    }
140}