Skip to main content

i_slint_compiler/passes/
flickable.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//! Flickable pass
5//!
6//! The Flickable element is special in the sense that it has a viewport
7//! which is not exposed. This passes create the viewport and fixes all property access
8//!
9//! It will also initialize proper geometry
10//! This pass must be called before the materialize_fake_properties as it going to be generate
11//! binding reference to fake properties
12
13use crate::expression_tree::{BindingExpression, Expression, MinMaxOp, NamedReference};
14use crate::langtype::{ElementType, NativeClass, Type};
15use crate::layout::is_layout;
16use crate::object_tree::{Component, Element, ElementRc};
17use crate::typeregister::TypeRegister;
18use core::cell::RefCell;
19use smol_str::{SmolStr, format_smolstr};
20use std::rc::Rc;
21
22pub fn is_flickable_element(element: &ElementRc) -> bool {
23    matches!(&element.borrow().base_type, ElementType::Builtin(n) if n.name == "Flickable")
24}
25
26pub fn handle_flickable(root_component: &Rc<Component>, tr: &TypeRegister) {
27    let mut native_empty = tr.empty_type().as_builtin().native_class.clone();
28    while let Some(p) = native_empty.parent.clone() {
29        native_empty = p;
30    }
31
32    crate::object_tree::recurse_elem_including_sub_components(
33        root_component,
34        &(),
35        &mut |elem: &ElementRc, _| {
36            if !is_flickable_element(elem) {
37                return;
38            }
39
40            fixup_geometry(elem);
41            create_viewport_element(elem, &native_empty);
42        },
43    )
44}
45
46fn create_viewport_element(flickable: &ElementRc, native_empty: &Rc<NativeClass>) {
47    let children = std::mem::take(&mut flickable.borrow_mut().children);
48    let is_listview = children
49        .iter()
50        .find_map(|c| c.borrow().repeated.as_ref().and_then(|r| r.is_listview.clone()));
51
52    if let Some(listview) = &is_listview {
53        // Fox Listview, we don't bind the y property to the geometry because for large listview, we want to support coordinate with more precision than f32
54        // so the actual geometry is relative to the Flickable instead of the viewport
55        // We still assign a binding to the y property in case it is read by someone
56        for c in &children {
57            if c.borrow().repeated.is_none() {
58                // Normally should not happen, listview should only have one children, and it should be repeated
59                continue;
60            }
61            let ElementType::Component(base) = c.borrow().base_type.clone() else { continue };
62            let inner_elem = &base.root_element;
63            let new_y = crate::layout::create_new_prop(
64                inner_elem,
65                SmolStr::new_static("actual-y"),
66                Type::LogicalLength,
67            );
68            new_y.mark_as_set();
69            inner_elem.borrow_mut().bindings.insert(
70                "y".into(),
71                RefCell::new(
72                    Expression::BinaryExpression {
73                        lhs: Expression::PropertyReference(new_y.clone()).into(),
74                        rhs: Expression::PropertyReference(listview.viewport_y.clone()).into(),
75                        op: '-',
76                    }
77                    .into(),
78                ),
79            );
80            inner_elem.borrow_mut().geometry_props.as_mut().unwrap().y = new_y;
81        }
82    }
83
84    let viewport = Element::make_rc(Element {
85        id: format_smolstr!("{}-viewport", flickable.borrow().id),
86        base_type: ElementType::Native(native_empty.clone()),
87        children,
88        enclosing_component: flickable.borrow().enclosing_component.clone(),
89        is_flickable_viewport: true,
90        ..Element::default()
91    });
92    let element_type = flickable.borrow().base_type.clone();
93    for prop in element_type.as_builtin().properties.keys() {
94        // bind the viewport's property to the flickable property, such as:  `width <=> parent.viewport-width`
95        if let Some(vp_prop) = prop.strip_prefix("viewport-") {
96            if is_listview.is_some() && matches!(vp_prop, "y" | "height") {
97                //don't bind viewport-y for ListView because the layout is handled by the runtime
98                continue;
99            }
100            viewport.borrow_mut().bindings.insert(
101                vp_prop.into(),
102                BindingExpression::new_two_way(NamedReference::new(flickable, prop.clone()).into())
103                    .into(),
104            );
105        }
106    }
107    viewport
108        .borrow()
109        .property_analysis
110        .borrow_mut()
111        .entry("y".into())
112        .or_default()
113        .is_set_externally = true;
114    viewport
115        .borrow()
116        .property_analysis
117        .borrow_mut()
118        .entry("x".into())
119        .or_default()
120        .is_set_externally = true;
121
122    let enclosing_component = flickable.borrow().enclosing_component.upgrade().unwrap();
123    if let Some(insertion_point) = &mut *enclosing_component.child_insertion_point.borrow_mut()
124        && std::rc::Rc::ptr_eq(&insertion_point.parent, flickable)
125    {
126        insertion_point.parent = viewport.clone()
127    }
128
129    flickable.borrow_mut().children.push(viewport);
130}
131
132fn fixup_geometry(flickable_elem: &ElementRc) {
133    let forward_minmax_of = |prop: &'static str, op: MinMaxOp| {
134        set_binding_if_not_explicit(flickable_elem, prop, || {
135            flickable_elem
136                .borrow()
137                .children
138                .iter()
139                .filter(|x| is_layout(&x.borrow().base_type))
140                // FIXME: we should ideally add runtime code to merge layout info of all elements that are repeated (#407)
141                .filter(|x| x.borrow().repeated.is_none())
142                .map(|x| {
143                    Expression::PropertyReference(NamedReference::new(x, SmolStr::new_static(prop)))
144                })
145                .reduce(|lhs, rhs| crate::builtin_macros::min_max_expression(lhs, rhs, op))
146        })
147    };
148
149    if !flickable_elem.borrow().bindings.contains_key("height") {
150        forward_minmax_of("max-height", MinMaxOp::Min);
151        forward_minmax_of("preferred-height", MinMaxOp::Min);
152    }
153    if !flickable_elem.borrow().bindings.contains_key("width") {
154        forward_minmax_of("max-width", MinMaxOp::Min);
155        forward_minmax_of("preferred-width", MinMaxOp::Min);
156    }
157    set_binding_if_not_explicit(flickable_elem, "viewport-width", || {
158        Some(
159            flickable_elem
160                .borrow()
161                .children
162                .iter()
163                .filter(|x| is_layout(&x.borrow().base_type))
164                // FIXME: (#407)
165                .filter(|x| x.borrow().repeated.is_none())
166                .map(|x| {
167                    Expression::PropertyReference(NamedReference::new(
168                        x,
169                        SmolStr::new_static("min-width"),
170                    ))
171                })
172                .fold(
173                    Expression::PropertyReference(NamedReference::new(
174                        flickable_elem,
175                        SmolStr::new_static("width"),
176                    )),
177                    |lhs, rhs| crate::builtin_macros::min_max_expression(lhs, rhs, MinMaxOp::Max),
178                ),
179        )
180    });
181    set_binding_if_not_explicit(flickable_elem, "viewport-height", || {
182        Some(
183            flickable_elem
184                .borrow()
185                .children
186                .iter()
187                .filter(|x| is_layout(&x.borrow().base_type))
188                // FIXME: (#407)
189                .filter(|x| x.borrow().repeated.is_none())
190                .map(|x| {
191                    Expression::PropertyReference(NamedReference::new(
192                        x,
193                        SmolStr::new_static("min-height"),
194                    ))
195                })
196                .fold(
197                    Expression::PropertyReference(NamedReference::new(
198                        flickable_elem,
199                        SmolStr::new_static("height"),
200                    )),
201                    |lhs, rhs| crate::builtin_macros::min_max_expression(lhs, rhs, MinMaxOp::Max),
202                ),
203        )
204    });
205}
206
207/// Set the property binding on the given element to the given expression (computed lazily).
208/// The parameter to the lazily calculation is the element's children
209fn set_binding_if_not_explicit(
210    elem: &ElementRc,
211    property: &str,
212    expression: impl FnOnce() -> Option<Expression>,
213) {
214    // we can't use `set_binding_if_not_set` directly because `expression()` may borrow `elem`
215    if elem.borrow().bindings.get(property).is_none_or(|b| !b.borrow().has_binding())
216        && let Some(e) = expression()
217    {
218        elem.borrow_mut().set_binding_if_not_set(property.into(), || e);
219    }
220}