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
use std::{
    ops::Deref,
    slice::Iter,
};

pub use euclid::Rect;

use crate::{
    geometry::Length,
    measure::Phase,
    scaled::Scaled,
};

#[derive(PartialEq, Clone, Debug)]
pub enum Size {
    Inner,
    Fill,
    FillMinimum,
    Percentage(Length),
    Pixels(Length),
    RootPercentage(Length),
    InnerPercentage(Length),
    DynamicCalculations(Box<Vec<DynamicCalculation>>),
}

impl Default for Size {
    fn default() -> Self {
        Self::Inner
    }
}

impl Size {
    pub fn inner_sized(&self) -> bool {
        matches!(
            self,
            Self::Inner | Self::FillMinimum | Self::InnerPercentage(_)
        )
    }

    pub fn inner_percentage_sized(&self) -> bool {
        matches!(self, Self::InnerPercentage(_))
    }

    pub fn pretty(&self) -> String {
        match self {
            Size::Inner => "auto".to_string(),
            Size::Pixels(s) => format!("{}", s.get()),
            Size::DynamicCalculations(calcs) => format!(
                "calc({})",
                calcs
                    .iter()
                    .map(|c| c.to_string())
                    .collect::<Vec<String>>()
                    .join(" ")
            ),
            Size::Percentage(p) => format!("{}%", p.get()),
            Size::Fill => "fill".to_string(),
            Size::FillMinimum => "fill-min".to_string(),
            Size::RootPercentage(p) => format!("{}% of root", p.get()),
            Size::InnerPercentage(p) => format!("{}% of auto", p.get()),
        }
    }

    pub fn eval(
        &self,
        parent_value: f32,
        available_parent_value: f32,
        parent_margin: f32,
        root_value: f32,
        phase: Phase,
    ) -> Option<f32> {
        match self {
            Size::Pixels(px) => Some(px.get() + parent_margin),
            Size::Percentage(per) => Some(parent_value / 100.0 * per.get()),
            Size::DynamicCalculations(calculations) => {
                Some(run_calculations(calculations.deref(), parent_value).unwrap_or(0.0))
            }
            Size::Fill => Some(available_parent_value),
            Size::FillMinimum => {
                if phase == Phase::Initial {
                    None
                } else {
                    Some(available_parent_value)
                }
            }
            Size::RootPercentage(per) => Some(root_value / 100.0 * per.get()),
            _ => None,
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn min_max(
        &self,
        value: f32,
        parent_value: f32,
        available_parent_value: f32,
        single_margin: f32,
        margin: f32,
        minimum: &Self,
        maximum: &Self,
        root_value: f32,
        phase: Phase,
    ) -> f32 {
        let value = self
            .eval(
                parent_value,
                available_parent_value,
                margin,
                root_value,
                phase,
            )
            .unwrap_or(value + margin);

        let minimum_value = minimum
            .eval(
                parent_value,
                available_parent_value,
                margin,
                root_value,
                phase,
            )
            .map(|v| v + single_margin);
        let maximum_value = maximum.eval(
            parent_value,
            available_parent_value,
            margin,
            root_value,
            phase,
        );

        let mut final_value = value;

        if let Some(minimum_value) = minimum_value {
            if minimum_value > final_value {
                final_value = minimum_value;
            }
        }

        if let Some(maximum_value) = maximum_value {
            if final_value > maximum_value {
                final_value = maximum_value
            }
        }

        final_value
    }

    pub fn most_fitting_size<'a>(&self, size: &'a f32, available_size: &'a f32) -> &'a f32 {
        match self {
            Self::Inner | Self::InnerPercentage(_) => available_size,
            _ => size,
        }
    }
}

impl Scaled for Size {
    fn scale(&mut self, scale_factor: f32) {
        match self {
            Size::Pixels(s) => *s *= scale_factor,
            Size::DynamicCalculations(calcs) => {
                calcs.iter_mut().for_each(|calc| calc.scale(scale_factor));
            }
            _ => (),
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum DynamicCalculation {
    Sub,
    Mul,
    Div,
    Add,
    Percentage(f32),
    Pixels(f32),
}

impl Scaled for DynamicCalculation {
    fn scale(&mut self, scale_factor: f32) {
        if let DynamicCalculation::Pixels(s) = self {
            *s *= scale_factor;
        }
    }
}

impl std::fmt::Display for DynamicCalculation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DynamicCalculation::Sub => f.write_str("-"),
            DynamicCalculation::Mul => f.write_str("*"),
            DynamicCalculation::Div => f.write_str("/"),
            DynamicCalculation::Add => f.write_str("+"),
            DynamicCalculation::Percentage(p) => f.write_fmt(format_args!("{p}%")),
            DynamicCalculation::Pixels(s) => f.write_fmt(format_args!("{s}")),
        }
    }
}

/// [Operator-precedence parser](https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method)
struct DynamicCalculationEvaluator<'a> {
    calcs: Iter<'a, DynamicCalculation>,
    parent_value: f32,
    current: Option<&'a DynamicCalculation>,
}

impl<'a> DynamicCalculationEvaluator<'a> {
    pub fn new(calcs: Iter<'a, DynamicCalculation>, parent_value: f32) -> Self {
        Self {
            calcs,
            parent_value,
            current: None,
        }
    }

    pub fn evaluate(&mut self) -> Option<f32> {
        // Parse and evaluate the expression
        let value = self.parse_expression(0);

        // Return the result if there are no more tokens
        match self.current {
            Some(_) => None,
            None => value,
        }
    }

    /// Parse and evaluate the expression with operator precedence and following grammar:
    /// ```ebnf
    ///     expression = value, { operator, value } ;
    ///     operator   = "+" | "-" | "*" | "/" ;
    /// ```
    fn parse_expression(&mut self, min_precedence: usize) -> Option<f32> {
        // Parse left-hand side value
        self.current = self.calcs.next();
        let mut lhs = self.parse_value()?;

        while let Some(operator_precedence) = self.operator_precedence() {
            // Return if minimal precedence is reached.
            if operator_precedence < min_precedence {
                return Some(lhs);
            }

            // Save operator to apply after parsing right-hand side value.
            let operator = self.current?;

            // Parse right-hand side value.
            //
            // Next precedence is the current precedence + 1
            // because all operators are left associative.
            let rhs = self.parse_expression(operator_precedence + 1)?;

            // Apply operator
            match operator {
                DynamicCalculation::Add => lhs += rhs,
                DynamicCalculation::Sub => lhs -= rhs,
                DynamicCalculation::Mul => lhs *= rhs,
                DynamicCalculation::Div => lhs /= rhs,
                // Precedence will return None for other tokens
                // and loop will break if it's not an operator
                _ => unreachable!(),
            }
        }

        Some(lhs)
    }

    /// Parse and evaluate the value with the following grammar:
    /// ```ebnf
    ///     value      = percentage | pixels ;
    ///     percentage = number, "%" ;
    ///     pixels     = number ;
    /// ```
    fn parse_value(&mut self) -> Option<f32> {
        match self.current? {
            DynamicCalculation::Percentage(value) => {
                self.current = self.calcs.next();
                Some((self.parent_value / 100.0 * value).round())
            }
            DynamicCalculation::Pixels(value) => {
                self.current = self.calcs.next();
                Some(*value)
            }
            _ => None,
        }
    }

    /// Get the precedence of the operator if current token is an operator or None otherwise.
    fn operator_precedence(&self) -> Option<usize> {
        match self.current? {
            DynamicCalculation::Add | DynamicCalculation::Sub => Some(1),
            DynamicCalculation::Mul | DynamicCalculation::Div => Some(2),
            _ => None,
        }
    }
}

/// Calculate dynamic expression with operator precedence.
/// This value could be for example the width of a node's parent area.
pub fn run_calculations(calcs: &[DynamicCalculation], value: f32) -> Option<f32> {
    DynamicCalculationEvaluator::new(calcs.iter(), value).evaluate()
}