Skip to main content

i_slint_compiler/passes/
lower_timers.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//! This pass transforms the Timer element into a timer in the Component
5
6use crate::diagnostics::BuildDiagnostics;
7use crate::expression_tree::{BuiltinFunction, Callable, Expression, NamedReference};
8use crate::langtype::ElementType;
9use crate::object_tree::*;
10use smol_str::SmolStr;
11use std::rc::Rc;
12
13pub fn lower_timers(component: &Rc<Component>, diag: &mut BuildDiagnostics) {
14    visit_all_expressions(component, |e, _| {
15        e.visit_recursive_mut(&mut |e| {
16            if let Expression::FunctionCall { function, arguments, .. } = e {
17                if let Callable::Builtin(BuiltinFunction::StartTimer | BuiltinFunction::StopTimer) =
18                    function
19                    && let [Expression::ElementReference(timer)] = arguments.as_slice()
20                {
21                    *e = Expression::SelfAssignment {
22                        lhs: Box::new(Expression::PropertyReference(NamedReference::new(
23                            &timer.upgrade().unwrap(),
24                            SmolStr::new_static("running"),
25                        ))),
26                        rhs: Box::new(Expression::BoolLiteral(matches!(
27                            function,
28                            Callable::Builtin(BuiltinFunction::StartTimer)
29                        ))),
30                        op: '=',
31                        node: None,
32                    }
33                }
34            }
35        });
36    });
37
38    recurse_elem_including_sub_components_no_borrow(
39        component,
40        &None,
41        &mut |elem, parent_element: &Option<ElementRc>| {
42            let is_timer = matches!(&elem.borrow().base_type, ElementType::Builtin(base_type) if base_type.name == "Timer");
43            if is_timer {
44                lower_timer(elem, parent_element.as_ref(), diag);
45            }
46            Some(elem.clone())
47        },
48    )
49}
50
51fn lower_timer(
52    timer_element: &ElementRc,
53    parent_element: Option<&ElementRc>,
54    diag: &mut BuildDiagnostics,
55) {
56    let parent_component = timer_element.borrow().enclosing_component.upgrade().unwrap();
57    let Some(parent_element) = parent_element else {
58        diag.push_error("A component cannot inherit from Timer".into(), &*timer_element.borrow());
59        return;
60    };
61
62    if Rc::ptr_eq(&parent_component.root_element, timer_element) {
63        diag.push_error(
64            "Timer cannot be directly repeated or conditional".into(),
65            &*timer_element.borrow(),
66        );
67        return;
68    }
69
70    if !timer_element.borrow().is_binding_set("interval", true) {
71        diag.push_error(
72            "Timer must have a binding set for its 'interval' property".into(),
73            &*timer_element.borrow(),
74        );
75        return;
76    }
77
78    // Remove the timer_element from its parent
79    let mut parent_element_borrowed = parent_element.borrow_mut();
80    let index = parent_element_borrowed
81        .children
82        .iter()
83        .position(|child| Rc::ptr_eq(child, timer_element))
84        .expect("Timer must be a child of its parent");
85    let removed = parent_element_borrowed.children.remove(index);
86    parent_component.optimized_elements.borrow_mut().push(removed);
87    drop(parent_element_borrowed);
88    if let Some(parent_cip) = &mut *parent_component.child_insertion_point.borrow_mut()
89        && Rc::ptr_eq(&parent_cip.parent, parent_element)
90        && parent_cip.insertion_index > index
91    {
92        parent_cip.insertion_index -= 1;
93    }
94
95    let running = NamedReference::new(timer_element, SmolStr::new_static("running"));
96    running.mark_as_set();
97
98    parent_component.timers.borrow_mut().push(Timer {
99        interval: NamedReference::new(timer_element, SmolStr::new_static("interval")),
100        running,
101        triggered: NamedReference::new(timer_element, SmolStr::new_static("triggered")),
102        element: Rc::downgrade(timer_element),
103    });
104    let update_timers = Expression::FunctionCall {
105        function: BuiltinFunction::UpdateTimers.into(),
106        arguments: Vec::new(),
107        source_location: None,
108    };
109    let change_callbacks = &mut timer_element.borrow_mut().change_callbacks;
110    change_callbacks.entry("running".into()).or_default().borrow_mut().push(update_timers.clone());
111    change_callbacks.entry("interval".into()).or_default().borrow_mut().push(update_timers);
112}