Skip to main content

slint_interpreter/
globals.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//! Storage for `global <Name> { … }` runtime instances.
5//!
6//! Created once per root instance and shared across the sub-component tree.
7//! Globals carry properties, callbacks and functions, but no items or children.
8
9use crate::erased::{SubComponentCallback, SubComponentProperty};
10use crate::eval::{EvalContext, eval_expression};
11use crate::prelude::*;
12use i_slint_compiler::llr::{CompilationUnit, GlobalIdx, LocalMemberIndex};
13use i_slint_core::rtti;
14use typed_index_collections::TiVec;
15
16/// Name-based access to a native (builtin) global like `NativeStyleMetrics`,
17/// whose state lives in a backend-provided struct instead of interpreter
18/// `Property<Value>` slots.
19pub trait NativeGlobal {
20    fn get_property(self: Pin<&Self>, name: &str) -> Option<Value>;
21    fn set_property(
22        self: Pin<&Self>,
23        name: &str,
24        value: Value,
25        animation: Option<i_slint_core::items::PropertyAnimation>,
26    ) -> Result<(), ()>;
27    fn invoke_callback(self: Pin<&Self>, name: &str, args: &[Value]) -> Option<Value>;
28    fn set_callback_handler(
29        self: Pin<&Self>,
30        name: &str,
31        handler: Box<dyn Fn(&[Value]) -> Value>,
32    ) -> Result<(), ()>;
33    fn prepare_property_for_two_way_binding(
34        self: Pin<&Self>,
35        name: &str,
36    ) -> Option<Pin<Rc<Property<Value>>>>;
37}
38
39impl<T: rtti::BuiltinGlobal + 'static> NativeGlobal for T {
40    fn get_property(self: Pin<&Self>, name: &str) -> Option<Value> {
41        let (_, prop) = T::properties::<Value>().into_iter().find(|(k, _)| *k == name)?;
42        prop.get(self).ok()
43    }
44
45    fn set_property(
46        self: Pin<&Self>,
47        name: &str,
48        value: Value,
49        animation: Option<i_slint_core::items::PropertyAnimation>,
50    ) -> Result<(), ()> {
51        let (_, prop) = T::properties::<Value>().into_iter().find(|(k, _)| *k == name).ok_or(())?;
52        prop.set(self, value, animation)
53    }
54
55    fn invoke_callback(self: Pin<&Self>, name: &str, args: &[Value]) -> Option<Value> {
56        let (_, cb) = T::callbacks::<Value>().into_iter().find(|(k, _)| *k == name)?;
57        cb.call(self, args).ok()
58    }
59
60    fn set_callback_handler(
61        self: Pin<&Self>,
62        name: &str,
63        handler: Box<dyn Fn(&[Value]) -> Value>,
64    ) -> Result<(), ()> {
65        let (_, cb) = T::callbacks::<Value>().into_iter().find(|(k, _)| *k == name).ok_or(())?;
66        cb.set_handler(self, handler)
67    }
68
69    fn prepare_property_for_two_way_binding(
70        self: Pin<&Self>,
71        name: &str,
72    ) -> Option<Pin<Rc<Property<Value>>>> {
73        let (_, prop) = T::properties::<Value>().into_iter().find(|(k, _)| *k == name)?;
74        Some(prop.prepare_for_two_way_binding(self))
75    }
76}
77
78/// Instantiate the backend-provided global with the given class name.
79/// `None` when the selected backend has no native global of that name.
80fn instantiate_native_global(class_name: &str) -> Option<Pin<Rc<dyn NativeGlobal>>> {
81    trait Helper {
82        fn instantiate(_name: &str) -> Option<Pin<Rc<dyn NativeGlobal>>> {
83            None
84        }
85    }
86    impl Helper for () {}
87    impl<T: rtti::BuiltinGlobal + 'static, Next: Helper> Helper for (T, Next) {
88        fn instantiate(name: &str) -> Option<Pin<Rc<dyn NativeGlobal>>> {
89            if name == T::name() { Some(T::new()) } else { Next::instantiate(name) }
90        }
91    }
92    <i_slint_backend_selector::NativeGlobals as Helper>::instantiate(class_name)
93}
94
95pub struct GlobalInstance {
96    pub compilation_unit: Rc<CompilationUnit>,
97    pub global_idx: GlobalIdx,
98    pub properties: TiVec<i_slint_compiler::llr::PropertyIdx, SubComponentProperty>,
99    pub callbacks: TiVec<i_slint_compiler::llr::CallbackIdx, SubComponentCallback>,
100    /// `Property<()>` per callback with `needs_tracker`; see
101    /// `SubComponentInstance::callback_trackers`.
102    pub callback_trackers: TiVec<
103        i_slint_compiler::llr::CallbackIdx,
104        Option<Pin<Rc<i_slint_core::properties::Property<()>>>>,
105    >,
106    /// One `ChangeTracker` per entry of the global's `change_callbacks`.
107    pub change_trackers: Vec<i_slint_core::properties::ChangeTracker>,
108    /// Backend-provided state for a builtin global (`NativeStyleMetrics`,
109    /// `NativePalette`, …); access goes by member name through the rtti
110    /// tables. The interpreter-level slots above stay empty.
111    pub native: Option<Pin<Rc<dyn NativeGlobal>>>,
112}
113
114/// All globals for one root component.
115pub struct GlobalStorage {
116    globals: TiVec<GlobalIdx, Option<Rc<GlobalInstance>>>,
117    /// The owning instance, so global bindings can reach the window.
118    pub root: OnceCell<vtable::VWeak<ItemTreeVTable, Instance>>,
119    pub context: SlintContext,
120    pub resources: Rc<crate::component::Resources>,
121    /// Set through [`ComponentInstance::set_debug_hook_callback`]; see [`crate::debug_hook`].
122    pub debug_hook_callback: RefCell<Option<crate::debug_hook::DebugHookCallback>>,
123}
124
125impl GlobalStorage {
126    /// Allocate one `GlobalInstance` per declared global.
127    /// Bindings are installed separately by [`install_global_bindings`].
128    pub fn new(
129        compilation_unit: &Rc<CompilationUnit>,
130        context: SlintContext,
131        resources: Rc<crate::component::Resources>,
132    ) -> Self {
133        let globals = compilation_unit
134            .globals
135            .iter_enumerated()
136            .map(|(idx, global)| {
137                if global.is_builtin {
138                    // Backends without a matching native global leave the
139                    // slot empty and reads produce `Value::Void`.
140                    let native = instantiate_native_global(&global.name)?;
141                    return Some(Rc::new(GlobalInstance {
142                        compilation_unit: compilation_unit.clone(),
143                        global_idx: idx,
144                        properties: TiVec::new(),
145                        callbacks: TiVec::new(),
146                        callback_trackers: TiVec::new(),
147                        change_trackers: Vec::new(),
148                        native: Some(native),
149                    }));
150                }
151                let properties = global
152                    .properties
153                    .iter()
154                    .map(|p| Rc::pin(Property::new(crate::eval::default_value_for_type(&p.ty))))
155                    .collect();
156                let callbacks =
157                    global.callbacks.iter().map(|_| Rc::pin(Callback::default())).collect();
158                let callback_trackers = global
159                    .callbacks
160                    .iter()
161                    .map(|c| {
162                        c.needs_tracker
163                            .then(|| Rc::pin(i_slint_core::properties::Property::new(())))
164                    })
165                    .collect();
166                Some(Rc::new(GlobalInstance {
167                    compilation_unit: compilation_unit.clone(),
168                    global_idx: idx,
169                    properties,
170                    callbacks,
171                    callback_trackers,
172                    change_trackers: core::iter::repeat_with(Default::default)
173                        .take(global.change_callbacks.len())
174                        .collect(),
175                    native: None,
176                }))
177            })
178            .collect();
179        Self {
180            globals,
181            root: OnceCell::new(),
182            context,
183            resources,
184            debug_hook_callback: RefCell::new(None),
185        }
186    }
187
188    pub fn get(&self, idx: GlobalIdx) -> Option<&Rc<GlobalInstance>> {
189        self.globals.get(idx)?.as_ref()
190    }
191
192    /// Look up a non-builtin global by its exported name (or alias).
193    /// Returns the matching `GlobalComponent` and its runtime `GlobalInstance`.
194    pub fn find_by_name<'a>(
195        &'a self,
196        compilation_unit: &'a CompilationUnit,
197        name: &str,
198    ) -> Option<(&'a i_slint_compiler::llr::GlobalComponent, &'a Rc<GlobalInstance>)> {
199        let needle = i_slint_compiler::names::normalize_identifier(name);
200        for (idx, global) in compilation_unit.globals.iter_enumerated() {
201            if !global.exported {
202                continue;
203            }
204            let name_matches =
205                i_slint_compiler::names::normalize_identifier(&global.name) == needle;
206            let alias_matches = global
207                .aliases
208                .iter()
209                .any(|a| i_slint_compiler::names::normalize_identifier(a) == needle);
210            if name_matches || alias_matches {
211                return self.get(idx).map(|inst| (global, inst));
212            }
213        }
214        None
215    }
216}
217
218/// Install every global's `init_values`, then in a second pass the change
219/// trackers for `changed X => { … }` handlers, so trackers observe the
220/// fully initialized values (matching the sub-component ordering).
221pub fn install_global_bindings(storage: &Rc<GlobalStorage>) {
222    for g in storage.globals.iter().flatten() {
223        install_for_global(g, storage);
224    }
225    for g in storage.globals.iter().flatten() {
226        install_global_change_trackers(g, storage);
227    }
228}
229
230fn install_global_change_trackers(g: &Rc<GlobalInstance>, storage: &Rc<GlobalStorage>) {
231    let cu = g.compilation_unit.clone();
232    let global = &cu.globals[g.global_idx];
233    for (idx, (prop_idx, expr)) in global.change_callbacks.iter().enumerate() {
234        let weak_storage_get = Rc::downgrade(storage);
235        let weak_storage_set = Rc::downgrade(storage);
236        let global_idx = g.global_idx;
237        let prop_idx = *prop_idx;
238        let notify_expr = expr.borrow().clone();
239        g.change_trackers[idx].init(
240            (),
241            move |()| -> Value {
242                let Some(st) = weak_storage_get.upgrade() else { return Value::Void };
243                let Some(gi) = st.get(global_idx) else { return Value::Void };
244                Pin::as_ref(&gi.properties[prop_idx]).get()
245            },
246            {
247                let cu = cu.clone();
248                move |(), _| {
249                    let Some(st) = weak_storage_set.upgrade() else { return };
250                    let mut ctx = EvalContext::for_global(Rc::downgrade(&st), cu.clone());
251                    eval_expression(&mut ctx, &notify_expr);
252                }
253            },
254        );
255    }
256}
257
258fn install_for_global(g: &Rc<GlobalInstance>, storage: &Rc<GlobalStorage>) {
259    if g.native.is_some() {
260        // Native globals carry their own state; there are no interpreted
261        // init values to install.
262        return;
263    }
264    let cu = g.compilation_unit.clone();
265    let global = &cu.globals[g.global_idx];
266    for (member, binding) in &global.init_values {
267        let expr = binding.expression.borrow().clone();
268        let weak_storage = Rc::downgrade(storage);
269
270        match member {
271            LocalMemberIndex::Property(idx) => {
272                let prop = Pin::as_ref(&g.properties[*idx]);
273                if binding.kind == i_slint_compiler::llr::BindingKind::Constant {
274                    let mut ctx = EvalContext::for_global(weak_storage.clone(), cu.clone());
275                    prop.set(eval_expression(&mut ctx, &expr));
276                    continue;
277                }
278                let expr = expr.clone();
279                let cu = cu.clone();
280                prop.set_binding(move || {
281                    let mut ctx = EvalContext::for_global(weak_storage.clone(), cu.clone());
282                    eval_expression(&mut ctx, &expr)
283                });
284            }
285            LocalMemberIndex::Callback(idx) => {
286                let cb = Pin::as_ref(&g.callbacks[*idx]);
287                let expr = expr.clone();
288                let cu = cu.clone();
289                let arg_types = global.callbacks[*idx].args.clone();
290                cb.set_handler(move |args: &[Value]| -> Value {
291                    let mut ctx = EvalContext::for_global(weak_storage.clone(), cu.clone());
292                    ctx.function_arg_types = arg_types.clone();
293                    ctx.function_arguments = args.to_vec();
294                    eval_expression(&mut ctx, &expr)
295                });
296            }
297            LocalMemberIndex::Function(_)
298            | LocalMemberIndex::Native { .. }
299            | LocalMemberIndex::Repeater(_)
300            | LocalMemberIndex::Timer(_) => {
301                // Function bodies live on `GlobalComponent::functions[*].code`.
302                // Natives and timers don't appear on globals.
303            }
304        }
305    }
306}