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::lower_layout_expression::MEASURE_KNOWN_W_LOCAL;
10use i_slint_compiler::llr::{BoxMeasureCell, Expression, FlexboxMeasureCell};
11use i_slint_core::SharedVector;
12use i_slint_core::layout::{
13    BoxLayoutData, FlexboxLayoutData, FlexboxLayoutItemInfo, GridLayoutData, GridLayoutInputData,
14    LayoutInfo, LayoutItemInfo, Padding,
15};
16use i_slint_core::model::Model;
17use i_slint_core::slice::Slice;
18
19// ── Value → layout-type converters ──────────────────────────────────────────
20
21fn to_f32(v: &Value) -> f32 {
22    match v {
23        Value::Number(n) => *n as f32,
24        _ => 0.,
25    }
26}
27
28fn to_padding(v: &Value) -> Padding {
29    let Value::Struct(s) = v else { return Padding::default() };
30    let f = |k| match s.get_field(k) {
31        Some(Value::Number(n)) => *n as f32,
32        _ => 0.,
33    };
34    Padding { begin: f("begin"), end: f("end") }
35}
36
37fn to_enum<T: std::str::FromStr + Default>(v: &Value) -> T {
38    match v {
39        Value::EnumerationValue(_, n) => n.parse().unwrap_or_default(),
40        _ => T::default(),
41    }
42}
43
44fn to_cells(v: &Value) -> Vec<LayoutItemInfo> {
45    let Value::Model(m) = v else { return Vec::new() };
46    (0..m.row_count())
47        .filter_map(|i| {
48            let Value::Struct(s) = m.row_data(i)? else { return None };
49            let c = s.get_field("constraint")?;
50            Some(LayoutItemInfo {
51                constraint: c.clone().try_into().unwrap_or_default(),
52                // Only set for a box layout's cross-axis cells; absent means `auto`.
53                cross_axis_self_alignment: s
54                    .get_field("cross-axis-self-alignment")
55                    .map(to_enum)
56                    .unwrap_or_default(),
57                // Only set for a box layout's main-axis cells; absent means 0.
58                layout_order: match s.get_field("layout-order") {
59                    Some(Value::Number(n)) => *n as i32,
60                    _ => 0,
61                },
62            })
63        })
64        .collect()
65}
66
67/// Convert one `Value::Struct` produced by the LLR's flexbox lowering:
68/// a `FlexboxLayoutItemInfo` with a `constraint` and a nested `props` field.
69/// `Struct::get_field` normalizes identifiers, so the kebab-case keys the
70/// lowering emits match regardless of spelling.
71pub(crate) fn flexbox_item_info_from_struct(s: &crate::api::Struct) -> FlexboxLayoutItemInfo {
72    let constraint: LayoutInfo =
73        s.get_field("constraint").cloned().and_then(|v| v.try_into().ok()).unwrap_or_default();
74    let props = match s.get_field("props") {
75        Some(Value::Struct(p)) => flex_props_from_struct(p),
76        _ => Default::default(),
77    };
78    FlexboxLayoutItemInfo { constraint, props }
79}
80
81/// Convert one `Value::Struct` produced by the LLR's flexbox lowering for a
82/// `FlexItemProps`.
83pub(crate) fn flex_props_from_struct(
84    s: &crate::api::Struct,
85) -> i_slint_core::layout::FlexItemProps {
86    i_slint_core::layout::FlexItemProps {
87        cross_axis_self_alignment: s
88            .get_field("cross-axis-self-alignment")
89            .map(to_enum)
90            .unwrap_or_default(),
91        layout_order: match s.get_field("layout-order") {
92            Some(Value::Number(n)) => *n as i32,
93            _ => 0,
94        },
95    }
96}
97
98fn to_flex_props(v: &Value) -> Vec<i_slint_core::layout::FlexItemProps> {
99    let Value::Model(m) = v else { return Vec::new() };
100    (0..m.row_count())
101        .filter_map(|i| {
102            let Value::Struct(s) = m.row_data(i)? else { return None };
103            Some(flex_props_from_struct(&s))
104        })
105        .collect()
106}
107
108fn to_u32_vec(v: &Value) -> Vec<u32> {
109    let Value::Model(m) = v else { return Vec::new() };
110    (0..m.row_count())
111        .filter_map(|i| match m.row_data(i)? {
112            Value::Number(n) => Some(n as u32),
113            _ => None,
114        })
115        .collect()
116}
117
118fn to_grid_input_data(v: &Value) -> Vec<GridLayoutInputData> {
119    let Value::Model(m) = v else { return Vec::new() };
120    (0..m.row_count())
121        .filter_map(|i| {
122            let Value::Struct(s) = m.row_data(i)? else { return None };
123            let f = |k: &str| match s.get_field(k) {
124                Some(Value::Number(n)) => *n as f32,
125                _ => 0.,
126            };
127            Some(GridLayoutInputData {
128                new_row: matches!(s.get_field("new-row"), Some(Value::Bool(true))),
129                col: f("col"),
130                row: f("row"),
131                colspan: f("colspan"),
132                rowspan: f("rowspan"),
133            })
134        })
135        .collect()
136}
137
138fn to_array_of_u16(v: &Value) -> SharedVector<u16> {
139    match v {
140        Value::ArrayOfU16(v) => v.clone(),
141        _ => Default::default(),
142    }
143}
144
145fn to_dialog_roles(v: &Value) -> Vec<i_slint_core::items::DialogButtonRole> {
146    let Value::Model(m) = v else { return Vec::new() };
147    (0..m.row_count())
148        .filter_map(|i| match m.row_data(i)? {
149            Value::EnumerationValue(_, n) => n.parse().ok(),
150            _ => None,
151        })
152        .collect()
153}
154
155fn sf32(s: &crate::api::Struct, k: &str) -> f32 {
156    match s.get_field(k) {
157        Some(Value::Number(n)) => *n as f32,
158        _ => 0.,
159    }
160}
161
162// ── Dispatch ────────────────────────────────────────────────────────────────
163
164pub(crate) fn call_extra_builtin(
165    ctx: &mut EvalContext,
166    name: &str,
167    arguments: &[Expression],
168) -> Value {
169    let a: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
170
171    match name {
172        "box_layout_info" => {
173            let c = to_cells(&a[0]);
174            i_slint_core::layout::box_layout_info(
175                Slice::from_slice(&c),
176                to_f32(&a[1]),
177                &to_padding(&a[2]),
178                to_enum(&a[3]),
179            )
180            .into()
181        }
182        "box_layout_info_ortho" => {
183            let c = to_cells(&a[0]);
184            i_slint_core::layout::box_layout_info_ortho(Slice::from_slice(&c), &to_padding(&a[1]))
185                .into()
186        }
187        "organize_dialog_button_layout" => {
188            let input = to_grid_input_data(&a[0]);
189            let roles = to_dialog_roles(&a[1]);
190            Value::ArrayOfU16(i_slint_core::layout::organize_dialog_button_layout(
191                Slice::from_slice(&input),
192                Slice::from_slice(&roles),
193            ))
194        }
195        "organize_grid_layout" => {
196            let (input, ri, rs) = (to_grid_input_data(&a[0]), to_u32_vec(&a[1]), to_u32_vec(&a[2]));
197            Value::ArrayOfU16(i_slint_core::layout::organize_grid_layout(
198                Slice::from_slice(&input),
199                Slice::from_slice(&ri),
200                Slice::from_slice(&rs),
201            ))
202        }
203        "grid_layout_info" => {
204            let (c, ri, rs) = (to_cells(&a[1]), to_u32_vec(&a[2]), to_u32_vec(&a[3]));
205            i_slint_core::layout::grid_layout_info(
206                to_array_of_u16(&a[0]),
207                Slice::from_slice(&c),
208                Slice::from_slice(&ri),
209                Slice::from_slice(&rs),
210                to_f32(&a[4]),
211                &to_padding(&a[5]),
212                to_enum(&a[6]),
213            )
214            .into()
215        }
216        "solve_grid_layout" => {
217            let (c, ri, rs) = (to_cells(&a[1]), to_u32_vec(&a[3]), to_u32_vec(&a[4]));
218            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
219            Value::LayoutCache(i_slint_core::layout::solve_grid_layout(
220                &GridLayoutData {
221                    size: sf32(s, "size"),
222                    spacing: sf32(s, "spacing"),
223                    padding: s.get_field("padding").map(to_padding).unwrap_or_default(),
224                    organized_data: s
225                        .get_field("organized-data")
226                        .map(to_array_of_u16)
227                        .unwrap_or_default(),
228                },
229                Slice::from_slice(&c),
230                to_enum(&a[2]),
231                Slice::from_slice(&ri),
232                Slice::from_slice(&rs),
233            ))
234        }
235        "solve_box_layout" => {
236            let ri = to_u32_vec(&a[1]);
237            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
238            let cells = s.get_field("cells").map(to_cells).unwrap_or_default();
239            Value::LayoutCache(i_slint_core::layout::solve_box_layout(
240                &BoxLayoutData {
241                    size: sf32(s, "size"),
242                    spacing: sf32(s, "spacing"),
243                    padding: s.get_field("padding").map(to_padding).unwrap_or_default(),
244                    alignment: s.get_field("alignment").map(to_enum).unwrap_or_default(),
245                    cells: Slice::from_slice(&cells),
246                },
247                Slice::from_slice(&ri),
248            ))
249        }
250        "solve_box_layout_ortho" => {
251            let ri = to_u32_vec(&a[1]);
252            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
253            let cells = s.get_field("cells").map(to_cells).unwrap_or_default();
254            Value::LayoutCache(i_slint_core::layout::solve_box_layout_ortho(
255                &i_slint_core::layout::BoxLayoutOrthoData {
256                    size: sf32(s, "size"),
257                    padding: s.get_field("padding").map(to_padding).unwrap_or_default(),
258                    cross_axis_alignment: s
259                        .get_field("cross-axis-alignment")
260                        .map(to_enum)
261                        .unwrap_or_default(),
262                    cells: Slice::from_slice(&cells),
263                },
264                Slice::from_slice(&ri),
265            ))
266        }
267        "solve_flexbox_layout" => {
268            let ri = to_u32_vec(&a[1]);
269            let Value::Struct(s) = &a[0] else { return Value::LayoutCache(Default::default()) };
270            let (ch, cv) = (
271                s.get_field("cells-h").map(to_cells).unwrap_or_default(),
272                s.get_field("cells-v").map(to_cells).unwrap_or_default(),
273            );
274            let fp = s.get_field("flex-props").map(to_flex_props).unwrap_or_default();
275            Value::LayoutCache(i_slint_core::layout::solve_flexbox_layout(
276                &FlexboxLayoutData {
277                    width: sf32(s, "width"),
278                    height: sf32(s, "height"),
279                    spacing_h: sf32(s, "spacing_h"),
280                    spacing_v: sf32(s, "spacing_v"),
281                    padding_h: s.get_field("padding-h").map(to_padding).unwrap_or_default(),
282                    padding_v: s.get_field("padding-v").map(to_padding).unwrap_or_default(),
283                    alignment: s.get_field("alignment").map(to_enum).unwrap_or_default(),
284                    direction: s.get_field("direction").map(to_enum).unwrap_or_default(),
285                    cross_axis_line_alignment: s
286                        .get_field("cross-axis-line-alignment")
287                        .map(to_enum)
288                        .unwrap_or_default(),
289                    cross_axis_alignment: s
290                        .get_field("cross-axis-alignment")
291                        .map(to_enum)
292                        .unwrap_or_default(),
293                    flex_wrap: s.get_field("flex-wrap").map(to_enum).unwrap_or_default(),
294                    cells_h: Slice::from_slice(&ch),
295                    cells_v: Slice::from_slice(&cv),
296                    flex_props: Slice::from_slice(&fp),
297                },
298                Slice::from_slice(&ri),
299            ))
300        }
301        "flexbox_layout_info_main_axis" => {
302            let cells = to_cells(&a[0]);
303            i_slint_core::layout::flexbox_layout_info_main_axis(
304                Slice::from_slice(&cells),
305                to_f32(&a[1]),
306                &to_padding(&a[2]),
307                to_enum(&a[3]),
308            )
309            .into()
310        }
311        "flexbox_layout_unwrapped_main" => {
312            let cells = to_cells(&a[0]);
313            Value::Number(i_slint_core::layout::flexbox_layout_unwrapped_main(
314                Slice::from_slice(&cells),
315                to_f32(&a[1]),
316                &to_padding(&a[2]),
317            ) as f64)
318        }
319        "flexbox_layout_info_cross_axis" => {
320            let (ch, cv) = (to_cells(&a[0]), to_cells(&a[1]));
321            let fp = to_flex_props(&a[2]);
322            i_slint_core::layout::flexbox_layout_info_cross_axis(
323                Slice::from_slice(&ch),
324                Slice::from_slice(&cv),
325                Slice::from_slice(&fp),
326                to_f32(&a[3]),
327                to_f32(&a[4]),
328                &to_padding(&a[5]),
329                &to_padding(&a[6]),
330                to_enum(&a[7]),
331                to_enum(&a[8]),
332                to_enum(&a[9]),
333                to_f32(&a[10]),
334            )
335            .into()
336        }
337        other => unimplemented!("ExtraBuiltinFunctionCall `{other}`"),
338    }
339}
340
341fn eval_info(ctx: &mut EvalContext, e: &Expression) -> LayoutInfo {
342    eval_expression(ctx, e).try_into().unwrap_or_default()
343}
344
345/// One flexbox cell as seen by the measure callback, after expanding
346/// repeaters (a repeater contributes one entry per instance).
347enum FlatCell<'a> {
348    Static {
349        v_info: &'a Expression,
350    },
351    Repeated(vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>),
352    /// Not height-for-width: the pre-resolved sizes are already correct.
353    Fixed,
354}
355
356/// Flatten `measure_cells` into one entry per taffy cell. Static cells carry
357/// their `v_info` expression; a repeater expands to one instance per row
358/// (re-measured through its own item tree at the assigned width).
359fn flatten_measure_cells<'a>(
360    ctx: &mut EvalContext,
361    measure_cells: &'a [FlexboxMeasureCell],
362) -> Vec<FlatCell<'a>> {
363    let mut flat: Vec<FlatCell> = Vec::with_capacity(measure_cells.len());
364    for item in measure_cells {
365        match item {
366            FlexboxMeasureCell::Static { v_info } => flat.push(FlatCell::Static { v_info }),
367            FlexboxMeasureCell::Repeated(repeater) => {
368                if let Some(current) = ctx.current.as_ref() {
369                    let rep = &current.repeaters[repeater.repeater_index];
370                    rep.track_instance_changes();
371                    flat.extend(rep.instances_vec().into_iter().map(FlatCell::Repeated));
372                }
373            }
374            FlexboxMeasureCell::Fixed => flat.push(FlatCell::Fixed),
375        }
376    }
377    flat
378}
379
380/// Measure callback body shared by the solve and cross-axis-info paths:
381/// re-evaluate the cell's vertical layout info with the `measure_known_w`
382/// local set to the width taffy assigned (a width it did not assign,
383/// `known_w == false`, arrives pre-resolved to the cell's preferred width, and
384/// serves a probe with neither dimension known, see `FlexboxMeasureFn` in
385/// i-slint-core). With the height known, no dimension depends on it.
386fn measure_flexbox_cell(
387    ctx: &mut EvalContext,
388    flat: &[FlatCell],
389    index: usize,
390    w: f32,
391    h: f32,
392    known_h: bool,
393) -> (f32, f32) {
394    let Some(cell) = flat.get(index) else { return (w, h) };
395    if known_h {
396        return (w, h);
397    }
398    match cell {
399        FlatCell::Static { v_info } => {
400            let prev = ctx.locals.insert(MEASURE_KNOWN_W_LOCAL.into(), Value::Number(w as f64));
401            let info = eval_info(ctx, v_info);
402            crate::eval::restore_local(ctx, MEASURE_KNOWN_W_LOCAL, prev);
403            (w, info.preferred_bounded())
404        }
405        FlatCell::Repeated(instance) => (
406            w,
407            instance
408                .as_pin_ref()
409                .flexbox_layout_item_info_at_cross_width(w)
410                .constraint
411                .preferred_bounded(),
412        ),
413        FlatCell::Fixed => (w, h),
414    }
415}
416
417/// Interpret [`Expression::SolveFlexboxLayoutWithMeasure`].
418pub(crate) fn solve_flexbox_layout_with_measure(ctx: &mut EvalContext, expr: &Expression) -> Value {
419    let Expression::SolveFlexboxLayoutWithMeasure { data, repeater_indices, measure_cells } = expr
420    else {
421        return Value::Void;
422    };
423    let ri = to_u32_vec(&eval_expression(ctx, repeater_indices));
424    let data = eval_expression(ctx, data);
425    let Value::Struct(s) = &data else { return Value::LayoutCache(Default::default()) };
426    let (ch, cv) = (
427        s.get_field("cells-h").map(to_cells).unwrap_or_default(),
428        s.get_field("cells-v").map(to_cells).unwrap_or_default(),
429    );
430    let fp = s.get_field("flex-props").map(to_flex_props).unwrap_or_default();
431
432    let flat = flatten_measure_cells(ctx, measure_cells);
433    let mut measure = |index: usize, w: f32, h: f32, _known_w: bool, known_h: bool| {
434        measure_flexbox_cell(ctx, &flat, index, w, h, known_h)
435    };
436
437    Value::LayoutCache(i_slint_core::layout::solve_flexbox_layout_with_measure(
438        &FlexboxLayoutData {
439            width: sf32(s, "width"),
440            height: sf32(s, "height"),
441            spacing_h: sf32(s, "spacing_h"),
442            spacing_v: sf32(s, "spacing_v"),
443            padding_h: s.get_field("padding-h").map(to_padding).unwrap_or_default(),
444            padding_v: s.get_field("padding-v").map(to_padding).unwrap_or_default(),
445            alignment: s.get_field("alignment").map(to_enum).unwrap_or_default(),
446            direction: s.get_field("direction").map(to_enum).unwrap_or_default(),
447            cross_axis_line_alignment: s
448                .get_field("cross-axis-line-alignment")
449                .map(to_enum)
450                .unwrap_or_default(),
451            cross_axis_alignment: s
452                .get_field("cross-axis-alignment")
453                .map(to_enum)
454                .unwrap_or_default(),
455            flex_wrap: s.get_field("flex-wrap").map(to_enum).unwrap_or_default(),
456            cells_h: Slice::from_slice(&ch),
457            cells_v: Slice::from_slice(&cv),
458            flex_props: Slice::from_slice(&fp),
459        },
460        Slice::from_slice(&ri),
461        Some(&mut measure),
462    ))
463}
464
465/// Interpret [`Expression::BoxLayoutInfoOrthoWithMeasure`]: solve the box
466/// layout's main axis at the known width, then fold the cells' vertical infos
467/// with `box_layout_info_ortho`, measuring each height-for-width cell at its
468/// solved width.
469pub(crate) fn box_layout_info_ortho_with_measure(
470    ctx: &mut EvalContext,
471    expr: &Expression,
472) -> Value {
473    use i_slint_core::model::RepeatedItemTree;
474    let Expression::BoxLayoutInfoOrthoWithMeasure { solve_data, padding_ortho, measure_cells } =
475        expr
476    else {
477        return Value::Void;
478    };
479    let data = eval_expression(ctx, solve_data);
480    let Value::Struct(s) = &data else { return LayoutInfo::default().into() };
481    let cells = s.get_field("cells").map(to_cells).unwrap_or_default();
482    let solved = i_slint_core::layout::solve_box_layout(
483        &BoxLayoutData {
484            size: sf32(s, "size"),
485            spacing: sf32(s, "spacing"),
486            padding: s.get_field("padding").map(to_padding).unwrap_or_default(),
487            alignment: s.get_field("alignment").map(to_enum).unwrap_or_default(),
488            cells: Slice::from_slice(&cells),
489        },
490        Slice::from_slice(&[]),
491    );
492    let solved_size = |cursor: usize| solved.as_slice().get(cursor * 2 + 1).copied().unwrap_or(0.);
493    let mut out_cells: Vec<LayoutItemInfo> = Vec::with_capacity(cells.len());
494    let mut cursor = 0usize;
495    for cell in measure_cells {
496        match cell {
497            BoxMeasureCell::Static { info } => {
498                let prev = ctx.locals.insert(
499                    MEASURE_KNOWN_W_LOCAL.into(),
500                    Value::Number(solved_size(cursor) as f64),
501                );
502                let constraint = eval_info(ctx, info);
503                crate::eval::restore_local(ctx, MEASURE_KNOWN_W_LOCAL, prev);
504                out_cells.push(LayoutItemInfo { constraint, ..Default::default() });
505                cursor += 1;
506            }
507            BoxMeasureCell::Repeated(repeater) => {
508                let Some(current) = ctx.current.as_ref() else {
509                    // Without an instance, the repeater's cell count is
510                    // unknown, so the later cells' solved sizes can't be
511                    // located either.
512                    debug_assert!(false, "measure pass evaluated without a current instance");
513                    return LayoutInfo::default().into();
514                };
515                let rep = &current.repeaters[repeater.repeater_index];
516                rep.track_instance_changes();
517                for instance in rep.instances_vec() {
518                    out_cells.push(
519                        instance.as_pin_ref().layout_item_info_at_cross_width(solved_size(cursor)),
520                    );
521                    cursor += 1;
522                }
523            }
524        }
525    }
526    i_slint_core::layout::box_layout_info_ortho(
527        Slice::from_slice(&out_cells),
528        &to_padding(&eval_expression(ctx, padding_ortho)),
529    )
530    .into()
531}
532
533/// Interpret [`Expression::FlexboxLayoutInfoCrossAxisWithMeasure`]: the
534/// `flexbox_layout_info_cross_axis` builtin plus the measure callback, so
535/// height-for-width cells are measured at the main-axis size taffy assigns
536/// them rather than at the container size the cells were pre-measured at.
537pub(crate) fn flexbox_layout_info_cross_axis_with_measure(
538    ctx: &mut EvalContext,
539    expr: &Expression,
540) -> Value {
541    let Expression::FlexboxLayoutInfoCrossAxisWithMeasure { arguments, measure_cells } = expr
542    else {
543        return Value::Void;
544    };
545    let a: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
546    let (ch, cv) = (to_cells(&a[0]), to_cells(&a[1]));
547    let fp = to_flex_props(&a[2]);
548    let flat = flatten_measure_cells(ctx, measure_cells);
549    let mut measure = |index: usize, w: f32, h: f32, _known_w: bool, known_h: bool| {
550        measure_flexbox_cell(ctx, &flat, index, w, h, known_h)
551    };
552    i_slint_core::layout::flexbox_layout_info_cross_axis_with_measure(
553        Slice::from_slice(&ch),
554        Slice::from_slice(&cv),
555        Slice::from_slice(&fp),
556        to_f32(&a[3]),
557        to_f32(&a[4]),
558        &to_padding(&a[5]),
559        &to_padding(&a[6]),
560        to_enum(&a[7]),
561        to_enum(&a[8]),
562        to_enum(&a[9]),
563        to_f32(&a[10]),
564        Some(&mut measure),
565    )
566    .into()
567}