Skip to main content

i_slint_compiler/passes/
visible.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//! Pass that lowers synthetic `visible` properties to Clip element
5
6use smol_str::{SmolStr, format_smolstr};
7use std::cell::RefCell;
8use std::rc::Rc;
9use std::sync::Arc;
10
11use crate::diagnostics::BuildDiagnostics;
12use crate::expression_tree::{Expression, NamedReference};
13use crate::langtype::{ElementType, NativeClass, PropertyLookupMode, Type};
14use crate::object_tree::{self, Component, Element, ElementRc};
15use crate::typeregister::TypeRegister;
16
17pub fn handle_visible(
18    component: &Rc<Component>,
19    type_register: &TypeRegister,
20    diag: &mut BuildDiagnostics,
21) {
22    // SystemTrayIcon uses `visible` as a real reactive property (toggling the tray
23    // icon's presence) rather than the lower-to-Clip layout sugar. Skip the
24    // warning + lowering for tray-rooted components. The language bindings'
25    // `show()`/`hide()` write `visible` directly on the native item, behind the
26    // compiler's back — mark it as externally set so bindings reading it aren't
27    // const-folded to its initial value.
28    if component.inherits_system_tray_icon() {
29        component
30            .root_element
31            .borrow()
32            .property_analysis
33            .borrow_mut()
34            .entry(SmolStr::new_static("visible"))
35            .or_default()
36            .is_set_externally = true;
37        return;
38    }
39
40    if let Some(b) = component.root_element.borrow().binding("visible") {
41        diag.push_warning(
42            "The visible property cannot be used on the root element, it will not be applied"
43                .into(),
44            &*b,
45        );
46    }
47
48    let native_clip =
49        type_register.lookup_builtin_element("Clip").unwrap().as_builtin().native_class.clone();
50
51    crate::object_tree::recurse_elem_including_sub_components(
52        component,
53        &(),
54        &mut |elem: &ElementRc, _| {
55            let is_lowered_from_visible_property = elem.borrow().native_class().is_some_and(|n| {
56                Arc::ptr_eq(&n, &native_clip) && elem.borrow().id.ends_with("-visibility")
57            });
58            if is_lowered_from_visible_property {
59                // This is the element we just created. Skip it.
60                return;
61            }
62
63            let old_children = {
64                let mut elem = elem.borrow_mut();
65                let new_children = Vec::with_capacity(elem.children.len());
66                std::mem::replace(&mut elem.children, new_children)
67            };
68
69            let has_visible_binding = |e: &ElementRc| {
70                e.borrow()
71                    .base_type
72                    .lookup_property("visible", PropertyLookupMode::ComponentLocal)
73                    .property_type
74                    != Type::Invalid
75                    && (e.borrow().binding("visible").is_some()
76                        || e.borrow()
77                            .property_analysis
78                            .borrow()
79                            .get("visible")
80                            .is_some_and(|a| a.is_set || a.is_linked))
81            };
82
83            for mut child in old_children {
84                if child.borrow().repeated.is_some() {
85                    let root_elem = child.borrow().base_type.as_component().root_element.clone();
86                    if has_visible_binding(&root_elem) {
87                        let clip_elem = create_visibility_element(&root_elem, &native_clip);
88                        object_tree::inject_element_as_repeated_element(&child, clip_elem.clone());
89                        // The width and the height must be null
90                        let d = NamedReference::new(&clip_elem, SmolStr::new_static("dummy"));
91                        clip_elem.borrow_mut().geometry_props.as_mut().unwrap().width = d.clone();
92                        clip_elem.borrow_mut().geometry_props.as_mut().unwrap().height = d;
93                    }
94                } else if has_visible_binding(&child) {
95                    let new_child = create_visibility_element(&child, &native_clip);
96                    // The injected element takes the child's place among the z-sorted siblings
97                    new_child.borrow_mut().z_order = child.borrow_mut().z_order.take();
98                    new_child.borrow_mut().children.push(child);
99                    child = new_child;
100                }
101
102                elem.borrow_mut().children.push(child);
103            }
104        },
105    );
106}
107
108fn create_visibility_element(child: &ElementRc, native_clip: &Arc<NativeClass>) -> ElementRc {
109    let element = Element {
110        id: format_smolstr!("{}-visibility", child.borrow().id),
111        base_type: ElementType::Native(native_clip.clone()),
112        enclosing_component: child.borrow().enclosing_component.clone(),
113        bindings: [
114            (
115                SmolStr::new_static("clip"),
116                RefCell::new(
117                    Expression::UnaryOp {
118                        sub: Box::new(Expression::PropertyReference(NamedReference::new(
119                            child,
120                            SmolStr::new_static("visible"),
121                        ))),
122                        op: '!',
123                    }
124                    .into(),
125                ),
126            ),
127            (
128                SmolStr::new_static("is-visibility-clip"),
129                RefCell::new(Expression::BoolLiteral(true).into()),
130            ),
131        ]
132        .into_iter()
133        .collect(),
134        is_injected_wrapper_element: true,
135        ..Default::default()
136    };
137    Element::make_rc(element)
138}