1use 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
16pub 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
78fn 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 pub callback_trackers: TiVec<
103 i_slint_compiler::llr::CallbackIdx,
104 Option<Pin<Rc<i_slint_core::properties::Property<()>>>>,
105 >,
106 pub change_trackers: Vec<i_slint_core::properties::ChangeTracker>,
108 pub native: Option<Pin<Rc<dyn NativeGlobal>>>,
112}
113
114pub struct GlobalStorage {
116 globals: TiVec<GlobalIdx, Option<Rc<GlobalInstance>>>,
117 pub root: OnceCell<vtable::VWeak<ItemTreeVTable, Instance>>,
119 pub context: SlintContext,
120 pub resources: Rc<crate::component::Resources>,
121 pub debug_hook_callback: RefCell<Option<crate::debug_hook::DebugHookCallback>>,
123}
124
125impl GlobalStorage {
126 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 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 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
218pub 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, ¬ify_expr);
252 }
253 },
254 );
255 }
256}
257
258fn install_for_global(g: &Rc<GlobalInstance>, storage: &Rc<GlobalStorage>) {
259 if g.native.is_some() {
260 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 }
304 }
305 }
306}