Skip to main content

slint_interpreter/
eval_layout.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! Dispatch for `Expression::ExtraBuiltinFunctionCall` — layout helper
5//! functions generated by the LLR's layout lowering pass.
6
7use crate::Value;
8use crate::eval::{EvalContext, eval_expression};
9use i_slint_compiler::llr::Expression;
10use i_slint_core::SharedVector;
11use i_slint_core::layout::{
12    BoxLayoutData, FlexboxLayoutData, FlexboxLayoutItemInfo, GridLayoutData, GridLayoutInputData,
13    LayoutInfo, LayoutItemInfo, Padding,
14};
15use i_slint_core::model::Model;
16use i_slint_core::slice::Slice;
17
18// ── Value → layout-type converters ──────────────────────────────────────────
19
20fn to_f32(v: &Value) -> f32 {
21    match v {
22        Value::Number(n) => *n as f32,
23        _ => 0.,
24    }
25}
26
27fn to_padding(v: &Value) -> Padding {
28    let Value::Struct(s) = v else { return Padding::default() };
29    let f = |k| match s.get_field(k) {
30        Some(Value::Number(n)) => *n as f32,
31        _ => 0.,
32    };
33    Padding { begin: f("begin"), end: f("end") }
34}
35
36fn to_enum<T: std::str::FromStr + Default>(v: &Value) -> T {
37    match v {
38        Value::EnumerationValue(_, n) => n.parse().unwrap_or_default(),
39        _ => T::default(),
40    }
41}
42
43fn to_cells(v: &Value) -> Vec<LayoutItemInfo> {
44    let Value::Model(m) = v else { return Vec::new() };
45    (0..m.row_count())
46        .filter_map(|i| {
47            let Value::Struct(s) = m.row_data(i)? else { return None };
48            let c = s.get_field("constraint")?;
49            Some(LayoutItemInfo { constraint: c.clone().try_into().unwrap_or_default() })
50        })
51        .collect()
52}
53
54/// Convert one `Value::Struct` produced by the LLR's flexbox lowering:
55/// a `FlexboxLayoutItemInfo` with a `constraint` and a nested `props` field.
56/// `Struct::get_field` normalizes identifiers, so the kebab-case keys the
57/// lowering emits match regardless of spelling.
58pub(crate) fn flexbox_item_info_from_struct(s: &crate::api::Struct) -> FlexboxLayoutItemInfo {
59    let constraint: LayoutInfo =
60        s.get_field("constraint").cloned().and_then(|v| v.try_into().ok()).unwrap_or_default();
61    let props = match s.get_field("props") {
62        Some(Value::Struct(p)) => flex_props_from_struct(p),
63        _ => Default::default(),
64    };
65    FlexboxLayoutItemInfo { constraint, props }
66}
67
68/// Convert one `Value::Struct` produced by the LLR's flexbox lowering for a
69/// `FlexItemProps`.
70pub(crate) fn flex_props_from_struct(
71    s: &crate::api::Struct,
72) -> i_slint_core::layout::FlexItemProps {
73    let f = |k: &str| -> f32 {
74        match s.get_field(k) {
75            Some(Value::Number(n)) => *n as f32,
76            _ => 0.,
77        }
78    };
79    // An absent flex-basis means auto (-1 like core's Default); an
80    // explicit 0 must pass through, it requests a zero base size.
81    let flex_basis = match s.get_field("flex-basis") {
82        Some(Value::Number(n)) => *n as f32,
83        _ => -1.,
84    };
85    i_slint_core::layout::FlexItemProps {
86        flex_grow: f("flex-grow"),
87        flex_shrink: f("flex-shrink"),
88        flex_basis,
89        cross_axis_self_alignment: s
90            .get_field("cross-axis-self-alignment")
91            .map(to_enum)
92            .unwrap_or_default(),
93        flex_order: match s.get_field("flex-order") {
94            Some(Value::Number(n)) => *n as i32,
95            _ => 0,
96        },
97    }
98}
99
100fn to_flex_props(v: &Value) -> Vec<i_slint_core::layout::FlexItemProps> {
101    let Value::Model(m) = v else { return Vec::new() };
102    (0..m.row_count())
103        .filter_map(|i| {
104            let Value::Struct(s) = m.row_data(i)? else { return None };
105            Some(flex_props_from_struct(&s))
106        })
107        .collect()
108}
109
110fn to_u32_vec(v: &Value) -> Vec<u32> {
111    let Value::Model(m) = v else { return Vec::new() };
112    (0..m.row_count())
113        .filter_map(|i| match m.row_data(i)? {
114            Value::Number(n) => Some(n as u32),
115            _ => None,
116        })
117        .collect()
118}
119
120fn to_grid_input_data(v: &Value) -> Vec<GridLayoutInputData> {
121    let Value::Model(m) = v else { return Vec::new() };
122    (0..m.row_count())
123        .filter_map(|i| {
124            let Value::Struct(s) = m.row_data(i)? else { return None };
125            let f = |k: &str| match s.get_field(k) {
126                Some(Value::Number(n)) => *n as f32,
127                _ => 0.,
128            };
129            Some(GridLayoutInputData {
130                new_row: matches!(s.get_field("new_row"), Some(Value::Bool(true))),
131                col: f("col"),
132                row: f("row"),
133                colspan: f("colspan"),
134                rowspan: f("rowspan"),
135            })
136        })
137        .collect()
138}
139
140fn to_array_of_u16(v: &Value) -> SharedVector<u16> {
141    match v {
142        Value::ArrayOfU16(v) => v.clone(),
143        _ => Default::default(),
144    }
145}
146
147fn to_dialog_roles(v: &Value) -> Vec<i_slint_core::items::DialogButtonRole> {
148    let Value::Model(m) = v else { return Vec::new() };
149    (0..m.row_count())
150        .filter_map(|i| match m.row_data(i)? {
151            Value::EnumerationValue(_, n) => n.parse().ok(),
152            _ => None,
153        })
154        .collect()
155}
156
157fn sf32(s: &crate::api::Struct, k: &str) -> f32 {
158    match s.get_field(k) {
159        Some(Value::Number(n)) => *n as f32,
160        _ => 0.,
161    }
162}
163
164// ── Dispatch ────────────────────────────────────────────────────────────────
165
166pub(crate) fn call_extra_builtin(
167    ctx: &mut EvalContext,
168    name: &str,
169    arguments: &[Expression],
170) -> Value {
171    let a: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
172
173    match name {
174        "box_layout_info" => {
175            let c = to_cells(&a[0]);
176            i_slint_core::layout::box_layout_info(
177                Slice::from_slice(&c),
178                to_f32(&a[1]),
179                &to_padding(&a[2]),
180                to_enum(&a[3]),
181            )
182            .into()
183        }
184        "box_layout_info_ortho" => {
185            let c = to_cells(&a[0]);
186            i_slint_core::layout::box_layout_info_ortho(Slice::from_slice(&c), &to_padding(&a[1]))
187                .into()
188        }
189        "organize_dialog_button_layout" => {
190            let input = to_grid_input_data(&a[0]);
191            let roles = to_dialog_roles(&a[1]);
192            Value::ArrayOfU16(i_slint_core::layout::organize_dialog_button_layout(
193                Slice::from_slice(&input),
194                Slice::from_slice(&roles),
195            ))
196        }
197        "organize_grid_layout" => {
198            let (input, ri, rs) = (to_grid_input_data(&a[0]), to_u32_vec(&a[1]), to_u32_vec(&a[2]));
199            Value::ArrayOfU16(i_slint_core::layout::organize_grid_layout(
200                Slice::from_slice(&input),
201                Slice::from_slice(&ri),
202                Slice::from_slice(&rs),
203            ))
204        }
205        "grid_layout_info" => {
206            let (c, ri, rs) = (to_cells(&a[1]), to_u32_vec(&a[2]), to_u32_vec(&a[3]));
207            i_slint_core::layout::grid_layout_info(
208                to_array_of_u16(&a[0]),
209                Slice::from_slice(&c),
210                Slice::from_slice(&ri),
211                Slice::from_slice(&rs),
212                to_f32(&a[4]),
213                &to_padding(&a[5]),
214                to_enum(&a[6]),
215            )
216            .into()
217        }
218        "solve_grid_layout" => {
219            let (c, ri, rs) = (to_cells(&a[1]), to_u32_vec(&a[3]), to_u32_vec(&a[4]));
220            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
221            Value::LayoutCache(i_slint_core::layout::solve_grid_layout(
222                &GridLayoutData {
223                    size: sf32(s, "size"),
224                    spacing: sf32(s, "spacing"),
225                    padding: s.get_field("padding").map(to_padding).unwrap_or_default(),
226                    organized_data: s
227                        .get_field("organized_data")
228                        .map(to_array_of_u16)
229                        .unwrap_or_default(),
230                },
231                Slice::from_slice(&c),
232                to_enum(&a[2]),
233                Slice::from_slice(&ri),
234                Slice::from_slice(&rs),
235            ))
236        }
237        "solve_box_layout" => {
238            let ri = to_u32_vec(&a[1]);
239            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
240            let cells = s.get_field("cells").map(to_cells).unwrap_or_default();
241            Value::LayoutCache(i_slint_core::layout::solve_box_layout(
242                &BoxLayoutData {
243                    size: sf32(s, "size"),
244                    spacing: sf32(s, "spacing"),
245                    padding: s.get_field("padding").map(to_padding).unwrap_or_default(),
246                    alignment: s.get_field("alignment").map(to_enum).unwrap_or_default(),
247                    cells: Slice::from_slice(&cells),
248                },
249                Slice::from_slice(&ri),
250            ))
251        }
252        "solve_box_layout_ortho" => {
253            let ri = to_u32_vec(&a[1]);
254            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
255            let cells = s.get_field("cells").map(to_cells).unwrap_or_default();
256            Value::LayoutCache(i_slint_core::layout::solve_box_layout_ortho(
257                &i_slint_core::layout::BoxLayoutOrthoData {
258                    size: sf32(s, "size"),
259                    padding: s.get_field("padding").map(to_padding).unwrap_or_default(),
260                    cross_axis_alignment: s
261                        .get_field("cross_axis_alignment")
262                        .map(to_enum)
263                        .unwrap_or_default(),
264                    cells: Slice::from_slice(&cells),
265                },
266                Slice::from_slice(&ri),
267            ))
268        }
269        "solve_flexbox_layout" => {
270            let ri = to_u32_vec(&a[1]);
271            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
272            let (ch, cv) = (
273                s.get_field("cells_h").map(to_cells).unwrap_or_default(),
274                s.get_field("cells_v").map(to_cells).unwrap_or_default(),
275            );
276            let fp = s.get_field("flex_props").map(to_flex_props).unwrap_or_default();
277            Value::LayoutCache(i_slint_core::layout::solve_flexbox_layout(
278                &FlexboxLayoutData {
279                    width: sf32(s, "width"),
280                    height: sf32(s, "height"),
281                    spacing_h: sf32(s, "spacing_h"),
282                    spacing_v: sf32(s, "spacing_v"),
283                    padding_h: s.get_field("padding_h").map(to_padding).unwrap_or_default(),
284                    padding_v: s.get_field("padding_v").map(to_padding).unwrap_or_default(),
285                    alignment: s.get_field("alignment").map(to_enum).unwrap_or_default(),
286                    direction: s.get_field("direction").map(to_enum).unwrap_or_default(),
287                    cross_axis_line_alignment: s
288                        .get_field("cross_axis_line_alignment")
289                        .map(to_enum)
290                        .unwrap_or_default(),
291                    cross_axis_alignment: s
292                        .get_field("cross_axis_alignment")
293                        .map(to_enum)
294                        .unwrap_or_default(),
295                    flex_wrap: s.get_field("flex_wrap").map(to_enum).unwrap_or_default(),
296                    cells_h: Slice::from_slice(&ch),
297                    cells_v: Slice::from_slice(&cv),
298                    flex_props: Slice::from_slice(&fp),
299                },
300                Slice::from_slice(&ri),
301            ))
302        }
303        "flexbox_layout_info_main_axis" => {
304            let cells = to_cells(&a[0]);
305            let fp = to_flex_props(&a[1]);
306            i_slint_core::layout::flexbox_layout_info_main_axis(
307                Slice::from_slice(&cells),
308                Slice::from_slice(&fp),
309                to_f32(&a[2]),
310                &to_padding(&a[3]),
311                to_enum(&a[4]),
312            )
313            .into()
314        }
315        "flexbox_layout_unwrapped_main" => {
316            let cells = to_cells(&a[0]);
317            let fp = to_flex_props(&a[1]);
318            Value::Number(i_slint_core::layout::flexbox_layout_unwrapped_main(
319                Slice::from_slice(&cells),
320                Slice::from_slice(&fp),
321                to_f32(&a[2]),
322                &to_padding(&a[3]),
323            ) as f64)
324        }
325        "flexbox_layout_info_cross_axis" => {
326            let (ch, cv) = (to_cells(&a[0]), to_cells(&a[1]));
327            let fp = to_flex_props(&a[2]);
328            i_slint_core::layout::flexbox_layout_info_cross_axis(
329                Slice::from_slice(&ch),
330                Slice::from_slice(&cv),
331                Slice::from_slice(&fp),
332                to_f32(&a[3]),
333                to_f32(&a[4]),
334                &to_padding(&a[5]),
335                &to_padding(&a[6]),
336                to_enum(&a[7]),
337                to_enum(&a[8]),
338                to_f32(&a[9]),
339            )
340            .into()
341        }
342        other => unimplemented!("ExtraBuiltinFunctionCall `{other}`"),
343    }
344}
345
346/// Interpret [`Expression::SolveFlexboxLayoutWithMeasure`].
347///
348/// Taffy calls the measure callback with exactly one of width/height known
349/// (the cross axis); we then re-evaluate that cell's perpendicular layout
350/// info with the `measure_known_w` / `measure_known_h` local set to the
351/// assigned dimension. Cells without a known cross-axis size fall back to
352/// the `default_cells` preferred size.
353pub(crate) fn solve_flexbox_layout_with_measure(ctx: &mut EvalContext, expr: &Expression) -> Value {
354    let Expression::SolveFlexboxLayoutWithMeasure {
355        data,
356        repeater_indices,
357        measure_cells,
358        default_cells,
359        cells_variables,
360    } = expr
361    else {
362        return Value::Void;
363    };
364    let ri = to_u32_vec(&eval_expression(ctx, repeater_indices));
365    let data = eval_expression(ctx, data);
366    let Value::Struct(s) = &data else { return Value::LayoutCache(Default::default()) };
367    let (ch, cv) = (
368        s.get_field("cells_h").map(to_cells).unwrap_or_default(),
369        s.get_field("cells_v").map(to_cells).unwrap_or_default(),
370    );
371    let fp = s.get_field("flex_props").map(to_flex_props).unwrap_or_default();
372
373    let eval_info = |ctx: &mut EvalContext, e: &Expression| -> LayoutInfo {
374        eval_expression(ctx, e).try_into().unwrap_or_default()
375    };
376
377    // Flatten `measure_cells` into one entry per taffy cell. Static cells carry
378    // their `(h_info, v_info)` expressions; a repeater expands to one instance
379    // per row (re-measured through its own item tree at the assigned cross size).
380    // When there is no repeater (`cells_variables` is `None`) this is exactly
381    // `measure_cells`, and the per-cell defaults come from `default_cells`;
382    // otherwise the defaults come from the flat `cells_h`/`cells_v` arrays.
383    enum FlatCell<'a> {
384        Static(&'a Expression, &'a Expression),
385        Repeated(vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>),
386    }
387    let mut flat: Vec<FlatCell> = Vec::with_capacity(measure_cells.len());
388    for item in measure_cells {
389        match item {
390            itertools::Either::Left((h_info, v_info)) => {
391                flat.push(FlatCell::Static(h_info, v_info))
392            }
393            itertools::Either::Right(repeater) => {
394                if let Some(current) = ctx.current.as_ref() {
395                    let rep = &current.repeaters[repeater.repeater_index];
396                    rep.track_instance_changes();
397                    flat.extend(rep.instances_vec().into_iter().map(FlatCell::Repeated));
398                }
399            }
400        }
401    }
402
403    // Preferred (default-constraint) size per cell, used when taffy asks for a
404    // dimension without a known cross-axis size. With a repeater, read the flat
405    // cell arrays (which include the expanded instances); otherwise evaluate the
406    // per-element `default_cells`.
407    let (mut pref_w, mut pref_h) = (Vec::new(), Vec::new());
408    if cells_variables.is_some() {
409        pref_w.extend(ch.iter().map(|c| c.constraint.preferred_bounded()));
410        pref_h.extend(cv.iter().map(|c| c.constraint.preferred_bounded()));
411    } else {
412        for item in default_cells {
413            if let itertools::Either::Left((h_info, v_info)) = item {
414                pref_w.push(eval_info(ctx, h_info).preferred_bounded());
415                pref_h.push(eval_info(ctx, v_info).preferred_bounded());
416            }
417        }
418    }
419
420    let mut measure = |index: usize, known_w: Option<f32>, known_h: Option<f32>| -> (f32, f32) {
421        let w = known_w.unwrap_or_else(|| pref_w.get(index).copied().unwrap_or(0f32));
422        let h = known_h.unwrap_or_else(|| pref_h.get(index).copied().unwrap_or(0f32));
423        match (known_w.is_some() && known_h.is_none(), flat.get(index)) {
424            (true, Some(FlatCell::Static(_, v_info))) => {
425                ctx.locals.insert("measure_known_w".into(), Value::Number(w as f64));
426                return (w, eval_info(ctx, v_info).preferred_bounded());
427            }
428            (true, Some(FlatCell::Repeated(instance))) => {
429                let nh = instance
430                    .as_pin_ref()
431                    .flexbox_layout_item_info_at_cross_width(w)
432                    .constraint
433                    .preferred_bounded();
434                return (w, nh);
435            }
436            _ => {}
437        }
438        if known_h.is_some() && known_w.is_none() {
439            match flat.get(index) {
440                Some(FlatCell::Static(h_info, _)) => {
441                    ctx.locals.insert("measure_known_h".into(), Value::Number(h as f64));
442                    let nw = eval_info(ctx, h_info).preferred_bounded();
443                    return (nw, h);
444                }
445                Some(FlatCell::Repeated(instance)) => {
446                    let nw = instance
447                        .as_pin_ref()
448                        .flexbox_layout_item_info_at_cross_height(h)
449                        .constraint
450                        .preferred_bounded();
451                    return (nw, h);
452                }
453                _ => {}
454            }
455        }
456        (w, h)
457    };
458
459    Value::LayoutCache(i_slint_core::layout::solve_flexbox_layout_with_measure(
460        &FlexboxLayoutData {
461            width: sf32(s, "width"),
462            height: sf32(s, "height"),
463            spacing_h: sf32(s, "spacing_h"),
464            spacing_v: sf32(s, "spacing_v"),
465            padding_h: s.get_field("padding_h").map(to_padding).unwrap_or_default(),
466            padding_v: s.get_field("padding_v").map(to_padding).unwrap_or_default(),
467            alignment: s.get_field("alignment").map(to_enum).unwrap_or_default(),
468            direction: s.get_field("direction").map(to_enum).unwrap_or_default(),
469            cross_axis_line_alignment: s
470                .get_field("cross_axis_line_alignment")
471                .map(to_enum)
472                .unwrap_or_default(),
473            cross_axis_alignment: s
474                .get_field("cross_axis_alignment")
475                .map(to_enum)
476                .unwrap_or_default(),
477            flex_wrap: s.get_field("flex_wrap").map(to_enum).unwrap_or_default(),
478            cells_h: Slice::from_slice(&ch),
479            cells_v: Slice::from_slice(&cv),
480            flex_props: Slice::from_slice(&fp),
481        },
482        Slice::from_slice(&ri),
483        Some(&mut measure),
484    ))
485}