Skip to main content

slint_interpreter/
eval.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
4use crate::api::{SetPropertyError, Struct, Value};
5use crate::dynamic_item_tree::{CallbackHandler, InstanceRef};
6use core::ffi::c_void;
7use core::pin::Pin;
8use corelib::graphics::{
9    ConicGradientBrush, GradientStop, LinearGradientBrush, PathElement, RadialGradientBrush,
10};
11use corelib::input::FocusReason;
12use corelib::items::{ItemRc, ItemRef, PropertyAnimation, WindowItem};
13use corelib::menus::{Menu, MenuFromItemTree};
14use corelib::model::{Model, ModelExt, ModelRc, VecModel};
15use corelib::rtti::AnimatedBindingKind;
16use corelib::window::{WindowInner, WindowKind};
17use corelib::{Brush, Color, PathData, SharedString, SharedVector};
18use i_slint_compiler::diagnostics::Spanned;
19use i_slint_compiler::expression_tree::{
20    BuiltinFunction, Callable, EasingCurve, Expression, MinMaxOp, MouseCursorInner,
21    Path as ExprPath, PathElement as ExprPathElement,
22};
23use i_slint_compiler::langtype::{ConstantExpression, Type};
24use i_slint_compiler::namedreference::NamedReference;
25use i_slint_compiler::object_tree::ElementRc;
26use i_slint_core::api::ToSharedString;
27use i_slint_core::{self as corelib};
28use smol_str::SmolStr;
29use std::collections::HashMap;
30use std::rc::Rc;
31
32pub trait ErasedPropertyInfo {
33    fn get(&self, item: Pin<ItemRef>) -> Value;
34    fn set(
35        &self,
36        item: Pin<ItemRef>,
37        value: Value,
38        animation: Option<PropertyAnimation>,
39    ) -> Result<(), ()>;
40    fn set_binding(
41        &self,
42        item: Pin<ItemRef>,
43        binding: Box<dyn Fn() -> Value>,
44        animation: AnimatedBindingKind,
45    );
46    fn offset(&self) -> usize;
47
48    #[cfg(slint_debug_property)]
49    fn set_debug_name(&self, item: Pin<ItemRef>, name: String);
50
51    /// Safety: Property2 must be a (pinned) pointer to a `Property<T>`
52    /// where T is the same T as the one represented by this property.
53    unsafe fn link_two_ways(&self, item: Pin<ItemRef>, property2: *const c_void);
54
55    fn prepare_for_two_way_binding(&self, item: Pin<ItemRef>) -> Pin<Rc<corelib::Property<Value>>>;
56
57    fn link_two_way_with_map(
58        &self,
59        item: Pin<ItemRef>,
60        property2: Pin<Rc<corelib::Property<Value>>>,
61        map: Option<Rc<dyn corelib::rtti::TwoWayBindingMapping<Value>>>,
62    );
63
64    fn link_two_way_to_model_data(
65        &self,
66        item: Pin<ItemRef>,
67        getter: Box<dyn Fn() -> Option<Value>>,
68        setter: Box<dyn Fn(&Value)>,
69    );
70}
71
72impl<Item: vtable::HasStaticVTable<corelib::items::ItemVTable>> ErasedPropertyInfo
73    for &'static dyn corelib::rtti::PropertyInfo<Item, Value>
74{
75    fn get(&self, item: Pin<ItemRef>) -> Value {
76        (*self).get(ItemRef::downcast_pin(item).unwrap()).unwrap()
77    }
78    fn set(
79        &self,
80        item: Pin<ItemRef>,
81        value: Value,
82        animation: Option<PropertyAnimation>,
83    ) -> Result<(), ()> {
84        (*self).set(ItemRef::downcast_pin(item).unwrap(), value, animation)
85    }
86    fn set_binding(
87        &self,
88        item: Pin<ItemRef>,
89        binding: Box<dyn Fn() -> Value>,
90        animation: AnimatedBindingKind,
91    ) {
92        (*self).set_binding(ItemRef::downcast_pin(item).unwrap(), binding, animation).unwrap();
93    }
94    fn offset(&self) -> usize {
95        (*self).offset()
96    }
97    #[cfg(slint_debug_property)]
98    fn set_debug_name(&self, item: Pin<ItemRef>, name: String) {
99        (*self).set_debug_name(ItemRef::downcast_pin(item).unwrap(), name);
100    }
101    unsafe fn link_two_ways(&self, item: Pin<ItemRef>, property2: *const c_void) {
102        // Safety: ErasedPropertyInfo::link_two_ways and PropertyInfo::link_two_ways have the same safety requirement
103        unsafe { (*self).link_two_ways(ItemRef::downcast_pin(item).unwrap(), property2) }
104    }
105
106    fn prepare_for_two_way_binding(&self, item: Pin<ItemRef>) -> Pin<Rc<corelib::Property<Value>>> {
107        (*self).prepare_for_two_way_binding(ItemRef::downcast_pin(item).unwrap())
108    }
109
110    fn link_two_way_with_map(
111        &self,
112        item: Pin<ItemRef>,
113        property2: Pin<Rc<corelib::Property<Value>>>,
114        map: Option<Rc<dyn corelib::rtti::TwoWayBindingMapping<Value>>>,
115    ) {
116        (*self).link_two_way_with_map(ItemRef::downcast_pin(item).unwrap(), property2, map)
117    }
118
119    fn link_two_way_to_model_data(
120        &self,
121        item: Pin<ItemRef>,
122        getter: Box<dyn Fn() -> Option<Value>>,
123        setter: Box<dyn Fn(&Value)>,
124    ) {
125        (*self).link_two_way_to_model_data(ItemRef::downcast_pin(item).unwrap(), getter, setter)
126    }
127}
128
129pub trait ErasedCallbackInfo {
130    fn call(&self, item: Pin<ItemRef>, args: &[Value]) -> Value;
131    fn set_handler(&self, item: Pin<ItemRef>, handler: Box<dyn Fn(&[Value]) -> Value>);
132}
133
134impl<Item: vtable::HasStaticVTable<corelib::items::ItemVTable>> ErasedCallbackInfo
135    for &'static dyn corelib::rtti::CallbackInfo<Item, Value>
136{
137    fn call(&self, item: Pin<ItemRef>, args: &[Value]) -> Value {
138        (*self).call(ItemRef::downcast_pin(item).unwrap(), args).unwrap()
139    }
140
141    fn set_handler(&self, item: Pin<ItemRef>, handler: Box<dyn Fn(&[Value]) -> Value>) {
142        (*self).set_handler(ItemRef::downcast_pin(item).unwrap(), handler).unwrap()
143    }
144}
145
146impl corelib::rtti::ValueType for Value {}
147
148#[derive(Clone)]
149pub(crate) enum ComponentInstance<'a, 'id> {
150    InstanceRef(InstanceRef<'a, 'id>),
151    GlobalComponent(Pin<Rc<dyn crate::global_component::GlobalComponent>>),
152}
153
154/// The local variable needed for binding evaluation
155pub struct EvalLocalContext<'a, 'id> {
156    local_variables: HashMap<SmolStr, Value>,
157    function_arguments: Vec<Value>,
158    pub(crate) component_instance: InstanceRef<'a, 'id>,
159    /// When Some, a return statement was executed and one must stop evaluating
160    return_value: Option<Value>,
161}
162
163impl<'a, 'id> EvalLocalContext<'a, 'id> {
164    pub fn from_component_instance(component: InstanceRef<'a, 'id>) -> Self {
165        Self {
166            local_variables: Default::default(),
167            function_arguments: Default::default(),
168            component_instance: component,
169            return_value: None,
170        }
171    }
172
173    /// Create a context for a function and passing the arguments
174    pub fn from_function_arguments(
175        component: InstanceRef<'a, 'id>,
176        function_arguments: Vec<Value>,
177    ) -> Self {
178        Self {
179            component_instance: component,
180            function_arguments,
181            local_variables: Default::default(),
182            return_value: None,
183        }
184    }
185}
186
187/// Evaluate `expression` as a length / number and return the resulting f32.
188/// Caller's responsibility to only pass length-typed expressions.
189fn eval_to_f32(expression: &Expression, local_context: &mut EvalLocalContext) -> f32 {
190    match eval_expression(expression, local_context) {
191        Value::Number(n) => n as f32,
192        other => unreachable!("expected length-typed expression; got {other:?} for {expression:?}"),
193    }
194}
195
196/// Evaluate an expression and return a Value as the result of this expression
197pub fn eval_expression(expression: &Expression, local_context: &mut EvalLocalContext) -> Value {
198    if let Some(r) = &local_context.return_value {
199        return r.clone();
200    }
201    match expression {
202        Expression::Invalid => panic!("invalid expression while evaluating"),
203        Expression::Uncompiled(_) => panic!("uncompiled expression while evaluating"),
204        Expression::StringLiteral(s) => Value::String(s.as_str().into()),
205        Expression::NumberLiteral(n, _unit) => Value::Number(*n),
206        Expression::BoolLiteral(b) => Value::Bool(*b),
207        Expression::ElementReference(_) => todo!(
208            "Element references are only supported in the context of built-in function calls at the moment"
209        ),
210        Expression::PropertyReference(nr) => load_property_helper(
211            &ComponentInstance::InstanceRef(local_context.component_instance),
212            &nr.element(),
213            nr.name(),
214        )
215        .unwrap(),
216        Expression::RepeaterIndexReference { element } => load_property_helper(
217            &ComponentInstance::InstanceRef(local_context.component_instance),
218            &element.upgrade().unwrap().borrow().base_type.as_component().root_element,
219            crate::dynamic_item_tree::SPECIAL_PROPERTY_INDEX,
220        )
221        .unwrap(),
222        Expression::RepeaterModelReference { element } => {
223            let value = load_property_helper(
224                &ComponentInstance::InstanceRef(local_context.component_instance),
225                &element.upgrade().unwrap().borrow().base_type.as_component().root_element,
226                crate::dynamic_item_tree::SPECIAL_PROPERTY_MODEL_DATA,
227            )
228            .unwrap();
229            if matches!(value, Value::Void) {
230                // Uninitialized model data (because the model returned None) should still be initialized to the default value of the type
231                default_value_for_type(&expression.ty())
232            } else {
233                value
234            }
235        }
236        Expression::FunctionParameterReference { index, .. } => {
237            local_context.function_arguments[*index].clone()
238        }
239        Expression::StructFieldAccess { base, name } => {
240            if let Value::Struct(o) = eval_expression(base, local_context) {
241                o.get_field(name).cloned().unwrap_or(Value::Void)
242            } else {
243                Value::Void
244            }
245        }
246        Expression::ArrayIndex { array, index } => {
247            let array = eval_expression(array, local_context);
248            let index = eval_expression(index, local_context);
249            match (array, index) {
250                (Value::Model(model), Value::Number(index)) => model
251                    .row_data_tracked(index as isize as usize)
252                    .unwrap_or_else(|| default_value_for_type(&expression.ty())),
253                _ => Value::Void,
254            }
255        }
256        Expression::Cast { from, to } => cast_value(eval_expression(from, local_context), to),
257        Expression::CodeBlock(sub) => {
258            let mut v = Value::Void;
259            for e in sub {
260                v = eval_expression(e, local_context);
261                if let Some(r) = &local_context.return_value {
262                    return r.clone();
263                }
264            }
265            v
266        }
267        Expression::FunctionCall { function, arguments, source_location } => match &function {
268            Callable::Function(nr) => {
269                let is_item_member = nr
270                    .element()
271                    .borrow()
272                    .native_class()
273                    .is_some_and(|n| n.properties.contains_key(nr.name()));
274                if is_item_member {
275                    call_item_member_function(nr, local_context)
276                } else {
277                    let args = arguments
278                        .iter()
279                        .map(|e| eval_expression(e, local_context))
280                        .collect::<Vec<_>>();
281                    call_function(
282                        &ComponentInstance::InstanceRef(local_context.component_instance),
283                        &nr.element(),
284                        nr.name(),
285                        args,
286                    )
287                    .unwrap()
288                }
289            }
290            Callable::Callback(nr) => {
291                let args =
292                    arguments.iter().map(|e| eval_expression(e, local_context)).collect::<Vec<_>>();
293                invoke_callback(
294                    &ComponentInstance::InstanceRef(local_context.component_instance),
295                    &nr.element(),
296                    nr.name(),
297                    &args,
298                )
299                .unwrap()
300            }
301            Callable::Builtin(f) => {
302                call_builtin_function(f.clone(), arguments, local_context, source_location)
303            }
304        },
305        Expression::SelfAssignment { lhs, rhs, op, .. } => {
306            let rhs = eval_expression(rhs, local_context);
307            eval_assignment(lhs, *op, rhs, local_context);
308            Value::Void
309        }
310        Expression::BinaryExpression { lhs, rhs, op } => {
311            let lhs = eval_expression(lhs, local_context);
312            // && and || short circuit like in the generated code, or else side
313            // effects in the rhs would run in the interpreter only
314            match (op, &lhs) {
315                ('&', Value::Bool(false)) => return Value::Bool(false),
316                ('|', Value::Bool(true)) => return Value::Bool(true),
317                _ => {}
318            }
319            let rhs = eval_expression(rhs, local_context);
320
321            match (op, lhs, rhs) {
322                ('+', Value::String(mut a), Value::String(b)) => {
323                    a.push_str(b.as_str());
324                    Value::String(a)
325                }
326                ('+', Value::Number(a), Value::Number(b)) => Value::Number(a + b),
327                ('+', a @ Value::Struct(_), b @ Value::Struct(_)) => {
328                    let a: Option<corelib::layout::LayoutInfo> = a.try_into().ok();
329                    let b: Option<corelib::layout::LayoutInfo> = b.try_into().ok();
330                    if let (Some(a), Some(b)) = (a, b) {
331                        a.merge(&b).into()
332                    } else {
333                        panic!("unsupported {a:?} {op} {b:?}");
334                    }
335                }
336                ('-', Value::Number(a), Value::Number(b)) => Value::Number(a - b),
337                ('/', Value::Number(a), Value::Number(b)) => Value::Number(a / b),
338                ('*', Value::Number(a), Value::Number(b)) => Value::Number(a * b),
339                ('<', Value::Number(a), Value::Number(b)) => Value::Bool(a < b),
340                ('>', Value::Number(a), Value::Number(b)) => Value::Bool(a > b),
341                ('≤', Value::Number(a), Value::Number(b)) => Value::Bool(a <= b),
342                ('≥', Value::Number(a), Value::Number(b)) => Value::Bool(a >= b),
343                ('<', Value::String(a), Value::String(b)) => Value::Bool(a < b),
344                ('>', Value::String(a), Value::String(b)) => Value::Bool(a > b),
345                ('≤', Value::String(a), Value::String(b)) => Value::Bool(a <= b),
346                ('≥', Value::String(a), Value::String(b)) => Value::Bool(a >= b),
347                ('=', a, b) => Value::Bool(a == b),
348                ('!', a, b) => Value::Bool(a != b),
349                ('&', Value::Bool(a), Value::Bool(b)) => Value::Bool(a && b),
350                ('|', Value::Bool(a), Value::Bool(b)) => Value::Bool(a || b),
351                (op, lhs, rhs) => panic!("unsupported {lhs:?} {op} {rhs:?}"),
352            }
353        }
354        Expression::UnaryOp { sub, op } => {
355            let sub = eval_expression(sub, local_context);
356            eval_unary_op(sub, *op).unwrap_or_else(|sub| panic!("unsupported {op} {sub:?}"))
357        }
358        Expression::ImageReference { resource_ref, nine_slice, .. } => {
359            let mut image = match resource_ref {
360                i_slint_compiler::expression_tree::ImageReference::None => Ok(Default::default()),
361                i_slint_compiler::expression_tree::ImageReference::DataUri(data_uri) => {
362                    i_slint_compiler::data_uri::decode_data_uri(data_uri)
363                        .ok()
364                        .and_then(|(data, extension)| {
365                            corelib::graphics::load_image_from_data_uri(data_uri, &data, &extension)
366                                .ok()
367                        })
368                        .ok_or_else(Default::default)
369                }
370                i_slint_compiler::expression_tree::ImageReference::Url(url)
371                    if url.scheme() == "builtin" =>
372                {
373                    let path = std::path::Path::new(url.as_str());
374                    i_slint_compiler::fileaccess::load_file(path)
375                        .and_then(|virtual_file| virtual_file.builtin_contents)
376                        .map(|virtual_file| {
377                            let extension = path.extension().unwrap().to_str().unwrap();
378                            corelib::graphics::load_image_from_embedded_data(
379                                corelib::slice::Slice::from_slice(virtual_file),
380                                corelib::slice::Slice::from_slice(extension.as_bytes()),
381                            )
382                        })
383                        .ok_or_else(Default::default)
384                }
385                i_slint_compiler::expression_tree::ImageReference::Path(path) => {
386                    corelib::graphics::Image::load_from_path(std::path::Path::new(path))
387                }
388                i_slint_compiler::expression_tree::ImageReference::Url(url) => {
389                    #[cfg(target_arch = "wasm32")]
390                    {
391                        corelib::graphics::load_as_html_image(url.as_str())
392                    }
393                    // URL image references only work on the web, where the browser fetches them.
394                    #[cfg(not(target_arch = "wasm32"))]
395                    {
396                        let _ = url;
397                        Err(Default::default())
398                    }
399                }
400                i_slint_compiler::expression_tree::ImageReference::EmbeddedData { .. } => {
401                    todo!()
402                }
403                i_slint_compiler::expression_tree::ImageReference::EmbeddedTexture { .. } => {
404                    todo!()
405                }
406            }
407            .unwrap_or_else(|_| {
408                eprintln!("Could not load image {resource_ref:?}");
409                Default::default()
410            });
411            if let Some(n) = nine_slice {
412                image.set_nine_slice_edges(n[0], n[1], n[2], n[3]);
413            }
414            Value::Image(image)
415        }
416        Expression::Condition { condition, true_expr, false_expr } => {
417            match eval_expression(condition, local_context).try_into() as Result<bool, _> {
418                Ok(true) => eval_expression(true_expr, local_context),
419                Ok(false) => eval_expression(false_expr, local_context),
420                _ => local_context
421                    .return_value
422                    .clone()
423                    .expect("conditional expression did not evaluate to boolean"),
424            }
425        }
426        Expression::Array { values, .. } => {
427            Value::Model(ModelRc::new(corelib::model::SharedVectorModel::from(
428                values
429                    .iter()
430                    .map(|e| eval_expression(e, local_context))
431                    .collect::<SharedVector<_>>(),
432            )))
433        }
434        Expression::Struct { values, .. } => Value::Struct(
435            values
436                .iter()
437                .map(|(k, v)| (k.to_string(), eval_expression(v, local_context)))
438                .collect(),
439        ),
440        Expression::PathData(data) => Value::PathData(convert_path(data, local_context)),
441        Expression::StoreLocalVariable { name, value } => {
442            let value = eval_expression(value, local_context);
443            local_context.local_variables.insert(name.clone(), value);
444            Value::Void
445        }
446        Expression::ReadLocalVariable { name, .. } => {
447            local_context.local_variables.get(name).unwrap().clone()
448        }
449        Expression::EasingCurve(curve) => Value::EasingCurve(match curve {
450            EasingCurve::Linear => corelib::animations::EasingCurve::Linear,
451            EasingCurve::EaseInElastic => corelib::animations::EasingCurve::EaseInElastic,
452            EasingCurve::EaseOutElastic => corelib::animations::EasingCurve::EaseOutElastic,
453            EasingCurve::EaseInOutElastic => corelib::animations::EasingCurve::EaseInOutElastic,
454            EasingCurve::EaseInBounce => corelib::animations::EasingCurve::EaseInBounce,
455            EasingCurve::EaseOutBounce => corelib::animations::EasingCurve::EaseOutBounce,
456            EasingCurve::EaseInOutBounce => corelib::animations::EasingCurve::EaseInOutBounce,
457            EasingCurve::CubicBezier(a, b, c, d) => {
458                corelib::animations::EasingCurve::CubicBezier([*a, *b, *c, *d])
459            }
460        }),
461        Expression::MouseCursor(cursor) => Value::MouseCursorInner(match cursor {
462            MouseCursorInner::BuiltIn(cursor) => corelib::cursor::MouseCursorInner::BuiltIn(
463                eval_expression(cursor, local_context).try_into().unwrap(),
464            ),
465            MouseCursorInner::CustomMouseCursor { image, hotspot_x, hotspot_y } => {
466                let image = eval_expression(image, local_context).try_into().unwrap();
467                let hotspot_x = eval_expression(hotspot_x, local_context).try_into().unwrap();
468                let hotspot_y = eval_expression(hotspot_y, local_context).try_into().unwrap();
469
470                corelib::cursor::MouseCursorInner::CustomMouseCursor { image, hotspot_x, hotspot_y }
471            }
472        }),
473        Expression::LinearGradient { angle, stops } => {
474            let angle = eval_expression(angle, local_context);
475            Value::Brush(Brush::LinearGradient(LinearGradientBrush::new(
476                angle.try_into().unwrap(),
477                stops.iter().map(|(color, stop)| {
478                    let color = eval_expression(color, local_context).try_into().unwrap();
479                    let position = eval_expression(stop, local_context).try_into().unwrap();
480                    GradientStop { color, position }
481                }),
482            )))
483        }
484        Expression::RadialGradient { stops, center, radius } => {
485            let mut g = RadialGradientBrush::new_circle(stops.iter().map(|(color, stop)| {
486                let color = eval_expression(color, local_context).try_into().unwrap();
487                let position = eval_expression(stop, local_context).try_into().unwrap();
488                GradientStop { color, position }
489            }));
490            if let Some((cx, cy)) = center {
491                let cx: f32 = eval_expression(cx, local_context).try_into().unwrap();
492                let cy: f32 = eval_expression(cy, local_context).try_into().unwrap();
493                g = g.with_center(cx, cy);
494            }
495            if let Some(r) = radius {
496                let r: f32 = eval_expression(r, local_context).try_into().unwrap();
497                g = g.with_radius(r);
498            }
499            Value::Brush(Brush::RadialGradient(g))
500        }
501        Expression::ConicGradient { from_angle, stops, center } => {
502            let from_angle: f32 = eval_expression(from_angle, local_context).try_into().unwrap();
503            let mut g = ConicGradientBrush::new(
504                from_angle,
505                stops.iter().map(|(color, stop)| {
506                    let color = eval_expression(color, local_context).try_into().unwrap();
507                    let position = eval_expression(stop, local_context).try_into().unwrap();
508                    GradientStop { color, position }
509                }),
510            );
511            if let Some((cx, cy)) = center {
512                let cx: f32 = eval_expression(cx, local_context).try_into().unwrap();
513                let cy: f32 = eval_expression(cy, local_context).try_into().unwrap();
514                g = g.with_center(cx, cy);
515            }
516            Value::Brush(Brush::ConicGradient(g))
517        }
518        Expression::EnumerationValue(value) => {
519            Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
520        }
521        Expression::Keys(ks) => {
522            let mut modifiers = i_slint_core::input::KeyboardModifiers::default();
523            modifiers.alt = ks.modifiers.alt;
524            modifiers.control = ks.modifiers.control;
525            modifiers.shift = ks.modifiers.shift;
526            modifiers.meta = ks.modifiers.meta;
527
528            Value::Keys(i_slint_core::input::make_keys(
529                SharedString::from(&*ks.key),
530                modifiers,
531                ks.ignore_shift,
532                ks.ignore_alt,
533                ks.is_physical,
534            ))
535        }
536        Expression::ReturnStatement(x) => {
537            let val = x.as_ref().map_or(Value::Void, |x| eval_expression(x, local_context));
538            if local_context.return_value.is_none() {
539                local_context.return_value = Some(val);
540            }
541            local_context.return_value.clone().unwrap()
542        }
543        Expression::LayoutCacheAccess {
544            layout_cache_prop,
545            index,
546            repeater_index,
547            entries_per_item,
548        } => {
549            let cache = load_property_helper(
550                &ComponentInstance::InstanceRef(local_context.component_instance),
551                &layout_cache_prop.element(),
552                layout_cache_prop.name(),
553            )
554            .unwrap();
555            if let Value::LayoutCache(cache) = cache {
556                // Coordinate cache
557                if let Some(ri) = repeater_index {
558                    let offset: usize = eval_expression(ri, local_context).try_into().unwrap();
559                    Value::Number(
560                        cache
561                            .get((cache[*index] as usize) + offset * entries_per_item)
562                            .copied()
563                            .unwrap_or(0.)
564                            .into(),
565                    )
566                } else {
567                    Value::Number(cache[*index].into())
568                }
569            } else if let Value::ArrayOfU16(cache) = cache {
570                // Organized Data cache
571                if let Some(ri) = repeater_index {
572                    let offset: usize = eval_expression(ri, local_context).try_into().unwrap();
573                    Value::Number(
574                        cache
575                            .get((cache[*index] as usize) + offset * entries_per_item)
576                            .copied()
577                            .unwrap_or(0)
578                            .into(),
579                    )
580                } else {
581                    Value::Number(cache[*index].into())
582                }
583            } else {
584                panic!("invalid layout cache")
585            }
586        }
587        Expression::GridRepeaterCacheAccess {
588            layout_cache_prop,
589            index,
590            repeater_index,
591            stride,
592            child_offset,
593            inner_repeater_index,
594            entries_per_item,
595        } => {
596            let cache = load_property_helper(
597                &ComponentInstance::InstanceRef(local_context.component_instance),
598                &layout_cache_prop.element(),
599                layout_cache_prop.name(),
600            )
601            .unwrap();
602            if let Value::LayoutCache(cache) = cache {
603                // Coordinate cache
604                let row_idx: usize =
605                    eval_expression(repeater_index, local_context).try_into().unwrap();
606                let stride_val: usize = eval_expression(stride, local_context).try_into().unwrap();
607                if let Some(inner_ri) = inner_repeater_index {
608                    let inner_offset: usize =
609                        eval_expression(inner_ri, local_context).try_into().unwrap();
610                    let base = cache[*index] as usize;
611                    let data_idx = base
612                        + row_idx * stride_val
613                        + *child_offset
614                        + inner_offset * *entries_per_item;
615                    Value::Number(cache.get(data_idx).copied().unwrap_or(0.).into())
616                } else {
617                    let base = cache[*index] as usize;
618                    let data_idx = base + row_idx * stride_val + *child_offset;
619                    Value::Number(cache.get(data_idx).copied().unwrap_or(0.).into())
620                }
621            } else if let Value::ArrayOfU16(cache) = cache {
622                // Organized Data cache
623                let row_idx: usize =
624                    eval_expression(repeater_index, local_context).try_into().unwrap();
625                let stride_val: usize = eval_expression(stride, local_context).try_into().unwrap();
626                if let Some(inner_ri) = inner_repeater_index {
627                    let inner_offset: usize =
628                        eval_expression(inner_ri, local_context).try_into().unwrap();
629                    let base = cache[*index] as usize;
630                    let data_idx = base
631                        + row_idx * stride_val
632                        + *child_offset
633                        + inner_offset * *entries_per_item;
634                    Value::Number(cache.get(data_idx).copied().unwrap_or(0).into())
635                } else {
636                    let base = cache[*index] as usize;
637                    let data_idx = base + row_idx * stride_val + *child_offset;
638                    Value::Number(cache.get(data_idx).copied().unwrap_or(0).into())
639                }
640            } else {
641                panic!("invalid layout cache")
642            }
643        }
644        Expression::ComputeBoxLayoutInfo { layout, orientation, cross_axis_size } => {
645            let cross = cross_axis_size.as_deref().map(|e| eval_to_f32(e, local_context));
646            crate::eval_layout::compute_box_layout_info(layout, *orientation, local_context, cross)
647        }
648        Expression::ComputeGridLayoutInfo {
649            layout_organized_data_prop,
650            layout,
651            orientation,
652            cross_axis_size,
653        } => {
654            let cross = cross_axis_size.as_deref().map(|e| eval_to_f32(e, local_context));
655            let cache = load_property_helper(
656                &ComponentInstance::InstanceRef(local_context.component_instance),
657                &layout_organized_data_prop.element(),
658                layout_organized_data_prop.name(),
659            )
660            .unwrap();
661            if let Value::ArrayOfU16(organized_data) = cache {
662                crate::eval_layout::compute_grid_layout_info(
663                    layout,
664                    &organized_data,
665                    *orientation,
666                    local_context,
667                    cross,
668                )
669            } else {
670                panic!("invalid layout organized data cache")
671            }
672        }
673        Expression::OrganizeGridLayout(lay) => {
674            crate::eval_layout::organize_grid_layout(lay, local_context)
675        }
676        Expression::SolveBoxLayout(lay, o) => {
677            crate::eval_layout::solve_box_layout(lay, *o, local_context)
678        }
679        Expression::SolveGridLayout { layout_organized_data_prop, layout, orientation } => {
680            let cache = load_property_helper(
681                &ComponentInstance::InstanceRef(local_context.component_instance),
682                &layout_organized_data_prop.element(),
683                layout_organized_data_prop.name(),
684            )
685            .unwrap();
686            if let Value::ArrayOfU16(organized_data) = cache {
687                crate::eval_layout::solve_grid_layout(
688                    &organized_data,
689                    layout,
690                    *orientation,
691                    local_context,
692                )
693            } else {
694                panic!("invalid layout organized data cache")
695            }
696        }
697        Expression::SolveFlexboxLayout(layout) => {
698            crate::eval_layout::solve_flexbox_layout(layout, local_context)
699        }
700        Expression::ComputeFlexboxLayoutInfo { layout, orientation, cross_axis_size } => {
701            let cross = cross_axis_size.as_deref().map(|e| eval_to_f32(e, local_context));
702            crate::eval_layout::compute_flexbox_layout_info(
703                layout,
704                *orientation,
705                local_context,
706                cross,
707            )
708        }
709        Expression::MinMax { ty: _, op, lhs, rhs } => {
710            let Value::Number(lhs) = eval_expression(lhs, local_context) else {
711                return local_context
712                    .return_value
713                    .clone()
714                    .expect("minmax lhs expression did not evaluate to number");
715            };
716            let Value::Number(rhs) = eval_expression(rhs, local_context) else {
717                return local_context
718                    .return_value
719                    .clone()
720                    .expect("minmax rhs expression did not evaluate to number");
721            };
722            match op {
723                MinMaxOp::Min => Value::Number(lhs.min(rhs)),
724                MinMaxOp::Max => Value::Number(lhs.max(rhs)),
725            }
726        }
727        Expression::EmptyComponentFactory => Value::ComponentFactory(Default::default()),
728        Expression::EmptyDataTransfer => Value::DataTransfer(Default::default()),
729        Expression::DebugHook { expression, id: _id, .. } => {
730            #[cfg(feature = "internal")]
731            {
732                if let Some(hook_value) = crate::debug_hook::trigger_debug_hook(
733                    &local_context.component_instance,
734                    _id.clone(),
735                ) {
736                    return hook_value;
737                }
738            }
739
740            eval_expression(expression, local_context)
741        }
742    }
743}
744
745fn call_builtin_function(
746    f: BuiltinFunction,
747    arguments: &[Expression],
748    local_context: &mut EvalLocalContext,
749    source_location: &Option<i_slint_compiler::diagnostics::SourceLocation>,
750) -> Value {
751    match f {
752        BuiltinFunction::GetWindowScaleFactor => Value::Number(
753            local_context.component_instance.access_window(|window| window.scale_factor()) as _,
754        ),
755        BuiltinFunction::GetWindowDefaultFontSize => Value::Number({
756            let component = local_context.component_instance;
757            let item_comp = component.self_weak().get().unwrap().upgrade().unwrap();
758            WindowItem::resolved_default_font_size(vtable::VRc::into_dyn(item_comp)).get() as _
759        }),
760        BuiltinFunction::AnimationTick => {
761            Value::Number(i_slint_core::animations::animation_tick() as f64)
762        }
763        BuiltinFunction::Debug => {
764            use corelib::debug_log::*;
765
766            let to_print: SharedString =
767                eval_expression(&arguments[0], local_context).try_into().unwrap();
768            let location = source_location.as_ref().and_then(|location| {
769                location.source_file().map(|file| {
770                    let (line, column) = file.line_column(
771                        location.span.offset,
772                        i_slint_compiler::diagnostics::ByteFormat::Utf8,
773                    );
774                    let path = file.path().to_string_lossy();
775                    (line, column, path)
776                })
777            });
778            let location = location.as_ref().map(|(line, column, path)| LogMessageLocation {
779                path,
780                line: *line,
781                column: *column,
782            });
783            let root_weak =
784                vtable::VWeak::into_dyn(local_context.component_instance.root_weak().clone());
785            if let Some(root) = root_weak.upgrade()
786                && let Some(ctx) = corelib::window::context_for_root(&root)
787            {
788                ctx.dispatch_log_message(LogMessage::new(
789                    LogMessageSource::SlintCode,
790                    location,
791                    format_args!("{to_print}"),
792                ));
793            } else {
794                log_message(LogMessage::new(
795                    LogMessageSource::SlintCode,
796                    location,
797                    format_args!("{to_print}"),
798                ));
799            }
800            Value::Void
801        }
802        BuiltinFunction::DecimalSeparator => Value::String(
803            local_context
804                .component_instance
805                .access_window(|window| window.context().locale_decimal_separator())
806                .into(),
807        ),
808        BuiltinFunction::Mod => {
809            let mut to_num = |e| -> f64 { eval_expression(e, local_context).try_into().unwrap() };
810            Value::Number(to_num(&arguments[0]).rem_euclid(to_num(&arguments[1])))
811        }
812        BuiltinFunction::Round => {
813            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
814            Value::Number(x.round())
815        }
816        BuiltinFunction::Ceil => {
817            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
818            Value::Number(x.ceil())
819        }
820        BuiltinFunction::Floor => {
821            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
822            Value::Number(x.floor())
823        }
824        BuiltinFunction::Sqrt => {
825            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
826            Value::Number(x.sqrt())
827        }
828        BuiltinFunction::Abs => {
829            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
830            Value::Number(x.abs())
831        }
832        BuiltinFunction::Sin => {
833            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
834            Value::Number(x.to_radians().sin())
835        }
836        BuiltinFunction::Cos => {
837            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
838            Value::Number(x.to_radians().cos())
839        }
840        BuiltinFunction::Tan => {
841            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
842            Value::Number(x.to_radians().tan())
843        }
844        BuiltinFunction::ASin => {
845            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
846            Value::Number(x.asin().to_degrees())
847        }
848        BuiltinFunction::ACos => {
849            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
850            Value::Number(x.acos().to_degrees())
851        }
852        BuiltinFunction::ATan => {
853            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
854            Value::Number(x.atan().to_degrees())
855        }
856        BuiltinFunction::ATan2 => {
857            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
858            let y: f64 = eval_expression(&arguments[1], local_context).try_into().unwrap();
859            Value::Number(x.atan2(y).to_degrees())
860        }
861        BuiltinFunction::Log => {
862            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
863            let y: f64 = eval_expression(&arguments[1], local_context).try_into().unwrap();
864            Value::Number(x.log(y))
865        }
866        BuiltinFunction::Ln => {
867            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
868            Value::Number(x.ln())
869        }
870        BuiltinFunction::Pow => {
871            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
872            let y: f64 = eval_expression(&arguments[1], local_context).try_into().unwrap();
873            Value::Number(x.powf(y))
874        }
875        BuiltinFunction::Exp => {
876            let x: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
877            Value::Number(x.exp())
878        }
879        BuiltinFunction::ToFixed => {
880            let n: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
881            let digits: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
882            let digits: usize = digits.max(0) as usize;
883            Value::String(i_slint_core::string::shared_string_from_number_fixed(n, digits))
884        }
885        BuiltinFunction::ToPrecision => {
886            let n: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
887            let precision: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
888            let precision: usize = precision.max(0) as usize;
889            Value::String(i_slint_core::string::shared_string_from_number_precision(n, precision))
890        }
891        BuiltinFunction::ToStringUnlocalized => {
892            let n: f64 = eval_expression(&arguments[0], local_context).try_into().unwrap();
893            Value::String(i_slint_core::string::shared_string_from_number_unlocalized(n))
894        }
895        BuiltinFunction::SetFocusItem => {
896            if arguments.len() != 1 {
897                panic!("internal error: incorrect argument count to SetFocusItem")
898            }
899            let component = local_context.component_instance;
900            if let Expression::ElementReference(focus_item) = &arguments[0] {
901                generativity::make_guard!(guard);
902
903                let focus_item = focus_item.upgrade().unwrap();
904                let enclosing_component =
905                    enclosing_component_for_element(&focus_item, component, guard);
906                let description = enclosing_component.description;
907
908                let item_info = &description.items[focus_item.borrow().id.as_str()];
909
910                let focus_item_comp =
911                    enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
912
913                component.access_window(|window| {
914                    window.set_focus_item(
915                        &corelib::items::ItemRc::new(
916                            vtable::VRc::into_dyn(focus_item_comp),
917                            item_info.item_index(),
918                        ),
919                        true,
920                        FocusReason::Programmatic,
921                    )
922                });
923                Value::Void
924            } else {
925                panic!("internal error: argument to SetFocusItem must be an element")
926            }
927        }
928        BuiltinFunction::ClearFocusItem => {
929            if arguments.len() != 1 {
930                panic!("internal error: incorrect argument count to SetFocusItem")
931            }
932            let component = local_context.component_instance;
933            if let Expression::ElementReference(focus_item) = &arguments[0] {
934                generativity::make_guard!(guard);
935
936                let focus_item = focus_item.upgrade().unwrap();
937                let enclosing_component =
938                    enclosing_component_for_element(&focus_item, component, guard);
939                let description = enclosing_component.description;
940
941                let item_info = &description.items[focus_item.borrow().id.as_str()];
942
943                let focus_item_comp =
944                    enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
945
946                component.access_window(|window| {
947                    window.set_focus_item(
948                        &corelib::items::ItemRc::new(
949                            vtable::VRc::into_dyn(focus_item_comp),
950                            item_info.item_index(),
951                        ),
952                        false,
953                        FocusReason::Programmatic,
954                    )
955                });
956                Value::Void
957            } else {
958                panic!("internal error: argument to ClearFocusItem must be an element")
959            }
960        }
961        BuiltinFunction::ShowPopupWindow => {
962            if arguments.len() != 1 {
963                panic!("internal error: incorrect argument count to ShowPopupWindow")
964            }
965            let component = local_context.component_instance;
966            if let Expression::ElementReference(popup_window) = &arguments[0] {
967                let popup_window = popup_window.upgrade().unwrap();
968                let pop_comp = popup_window.borrow().enclosing_component.upgrade().unwrap();
969                let parent_component = {
970                    let parent_elem = pop_comp.parent_element().unwrap();
971                    parent_elem.borrow().enclosing_component.upgrade().unwrap()
972                };
973                let popup_list = parent_component.popup_windows.borrow();
974                let popup =
975                    popup_list.iter().find(|p| Rc::ptr_eq(&p.component, &pop_comp)).unwrap();
976
977                generativity::make_guard!(guard);
978                let enclosing_component =
979                    enclosing_component_for_element(&popup.parent_element, component, guard);
980                let parent_item_info = &enclosing_component.description.items
981                    [popup.parent_element.borrow().id.as_str()];
982                let parent_item_comp =
983                    enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
984                let parent_item = corelib::items::ItemRc::new(
985                    vtable::VRc::into_dyn(parent_item_comp),
986                    parent_item_info.item_index(),
987                );
988
989                let close_policy = Value::EnumerationValue(
990                    popup.close_policy.enumeration.name.to_string(),
991                    popup.close_policy.to_string(),
992                )
993                .try_into()
994                .expect("Invalid internal enumeration representation for close policy");
995                let popup_x = popup.x.clone();
996                let popup_y = popup.y.clone();
997
998                crate::dynamic_item_tree::show_popup(
999                    popup_window,
1000                    enclosing_component,
1001                    popup,
1002                    move |instance_ref| {
1003                        let comp = ComponentInstance::InstanceRef(instance_ref);
1004                        let x = load_property_helper(&comp, &popup_x.element(), popup_x.name())
1005                            .unwrap();
1006                        let y = load_property_helper(&comp, &popup_y.element(), popup_y.name())
1007                            .unwrap();
1008                        corelib::api::LogicalPosition::new(
1009                            x.try_into().unwrap(),
1010                            y.try_into().unwrap(),
1011                        )
1012                    },
1013                    close_policy,
1014                    (*enclosing_component.self_weak().get().unwrap()).clone(),
1015                    component.window_adapter(),
1016                    &parent_item,
1017                );
1018                Value::Void
1019            } else {
1020                panic!("internal error: argument to ShowPopupWindow must be an element")
1021            }
1022        }
1023        BuiltinFunction::ClosePopupWindow => {
1024            let component = local_context.component_instance;
1025            if let Expression::ElementReference(popup_window) = &arguments[0] {
1026                let popup_window = popup_window.upgrade().unwrap();
1027                let pop_comp = popup_window.borrow().enclosing_component.upgrade().unwrap();
1028                let parent_component = {
1029                    let parent_elem = pop_comp.parent_element().unwrap();
1030                    parent_elem.borrow().enclosing_component.upgrade().unwrap()
1031                };
1032                let popup_list = parent_component.popup_windows.borrow();
1033                let popup =
1034                    popup_list.iter().find(|p| Rc::ptr_eq(&p.component, &pop_comp)).unwrap();
1035
1036                generativity::make_guard!(guard);
1037                let enclosing_component =
1038                    enclosing_component_for_element(&popup.parent_element, component, guard);
1039                crate::dynamic_item_tree::close_popup(
1040                    popup_window,
1041                    enclosing_component,
1042                    enclosing_component.window_adapter(),
1043                );
1044
1045                Value::Void
1046            } else {
1047                panic!("internal error: argument to ClosePopupWindow must be an element")
1048            }
1049        }
1050        BuiltinFunction::ShowPopupMenu | BuiltinFunction::ShowPopupMenuInternal => {
1051            let [Expression::ElementReference(element), entries, position] = arguments else {
1052                panic!("internal error: incorrect argument count to ShowPopupMenu")
1053            };
1054            let position = eval_expression(position, local_context)
1055                .try_into()
1056                .expect("internal error: popup menu position argument should be a point");
1057
1058            let component = local_context.component_instance;
1059            let elem = element.upgrade().unwrap();
1060            generativity::make_guard!(guard);
1061            let enclosing_component = enclosing_component_for_element(&elem, component, guard);
1062            let description = enclosing_component.description;
1063            let item_info = &description.items[elem.borrow().id.as_str()];
1064            let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1065            let item_tree = vtable::VRc::into_dyn(item_comp);
1066            let item_rc = corelib::items::ItemRc::new(item_tree.clone(), item_info.item_index());
1067
1068            generativity::make_guard!(guard);
1069            let compiled = enclosing_component.description.popup_menu_description.unerase(guard);
1070            let extra_data = enclosing_component
1071                .description
1072                .extra_data_offset
1073                .apply(enclosing_component.as_ref());
1074            let inst = crate::dynamic_item_tree::instantiate(
1075                compiled.clone(),
1076                Some((*enclosing_component.self_weak().get().unwrap()).clone()),
1077                None,
1078                Some(&crate::dynamic_item_tree::WindowOptions::UseExistingWindow(
1079                    component.window_adapter(),
1080                )),
1081                extra_data.globals.get().unwrap().clone(),
1082            );
1083
1084            generativity::make_guard!(guard);
1085            let inst_ref = inst.unerase(guard);
1086            if let Expression::ElementReference(e) = entries {
1087                let menu_item_tree =
1088                    e.upgrade().unwrap().borrow().enclosing_component.upgrade().unwrap();
1089                let menu_item_tree = crate::dynamic_item_tree::make_menu_item_tree(
1090                    &menu_item_tree,
1091                    &enclosing_component,
1092                    None,
1093                    None,
1094                );
1095
1096                if component.access_window(|window| {
1097                    window.show_native_popup_menu(
1098                        vtable::VRc::into_dyn(menu_item_tree.clone()),
1099                        position,
1100                        &item_rc,
1101                    )
1102                }) {
1103                    return Value::Void;
1104                }
1105
1106                let (entries, sub_menu, activated) = menu_item_tree_properties(menu_item_tree);
1107
1108                compiled.set_binding(inst_ref.borrow(), "entries", entries).unwrap();
1109                compiled.set_callback_handler(inst_ref.borrow(), "sub-menu", sub_menu).unwrap();
1110                compiled.set_callback_handler(inst_ref.borrow(), "activated", activated).unwrap();
1111            } else {
1112                let entries = eval_expression(entries, local_context);
1113                compiled.set_property(inst_ref.borrow(), "entries", entries).unwrap();
1114                let item_weak = item_rc.downgrade();
1115                compiled
1116                    .set_callback_handler(
1117                        inst_ref.borrow(),
1118                        "sub-menu",
1119                        Box::new(move |args: &[Value]| -> Value {
1120                            item_weak
1121                                .upgrade()
1122                                .unwrap()
1123                                .downcast::<corelib::items::ContextMenu>()
1124                                .unwrap()
1125                                .sub_menu
1126                                .call(&(args[0].clone().try_into().unwrap(),))
1127                                .into()
1128                        }),
1129                    )
1130                    .unwrap();
1131                let item_weak = item_rc.downgrade();
1132                compiled
1133                    .set_callback_handler(
1134                        inst_ref.borrow(),
1135                        "activated",
1136                        Box::new(move |args: &[Value]| -> Value {
1137                            item_weak
1138                                .upgrade()
1139                                .unwrap()
1140                                .downcast::<corelib::items::ContextMenu>()
1141                                .unwrap()
1142                                .activated
1143                                .call(&(args[0].clone().try_into().unwrap(),));
1144                            Value::Void
1145                        }),
1146                    )
1147                    .unwrap();
1148            }
1149            let item_weak = item_rc.downgrade();
1150            compiled
1151                .set_callback_handler(
1152                    inst_ref.borrow(),
1153                    "close-popup",
1154                    Box::new(move |_args: &[Value]| -> Value {
1155                        let Some(item_rc) = item_weak.upgrade() else { return Value::Void };
1156                        if let Some(id) = item_rc
1157                            .downcast::<corelib::items::ContextMenu>()
1158                            .unwrap()
1159                            .popup_id
1160                            .take()
1161                        {
1162                            WindowInner::from_pub(item_rc.window_adapter().unwrap().window())
1163                                .close_popup(id);
1164                        }
1165                        Value::Void
1166                    }),
1167                )
1168                .unwrap();
1169            component.access_window(|window| {
1170                let context_menu_elem = item_rc.downcast::<corelib::items::ContextMenu>().unwrap();
1171                if let Some(old_id) = context_menu_elem.popup_id.take() {
1172                    window.close_popup(old_id)
1173                }
1174                let id = window.show_popup(
1175                    &vtable::VRc::into_dyn(inst.clone()),
1176                    Box::new(move || position),
1177                    corelib::items::PopupClosePolicy::CloseOnClickOutside,
1178                    &item_rc,
1179                    WindowKind::Menu,
1180                    Box::new(|_| {}),
1181                );
1182                context_menu_elem.popup_id.set(Some(id));
1183            });
1184            inst.run_setup_code();
1185            Value::Void
1186        }
1187        BuiltinFunction::SetSelectionOffsets => {
1188            if arguments.len() != 3 {
1189                panic!("internal error: incorrect argument count to select range function call")
1190            }
1191            let component = local_context.component_instance;
1192            if let Expression::ElementReference(element) = &arguments[0] {
1193                generativity::make_guard!(guard);
1194
1195                let elem = element.upgrade().unwrap();
1196                let enclosing_component = enclosing_component_for_element(&elem, component, guard);
1197                let description = enclosing_component.description;
1198                let item_info = &description.items[elem.borrow().id.as_str()];
1199                let item_ref =
1200                    unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
1201
1202                let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1203                let item_rc = corelib::items::ItemRc::new(
1204                    vtable::VRc::into_dyn(item_comp),
1205                    item_info.item_index(),
1206                );
1207
1208                let window_adapter = component.window_adapter();
1209
1210                // TODO: Make this generic through RTTI
1211                if let Some(textinput) =
1212                    ItemRef::downcast_pin::<corelib::items::TextInput>(item_ref)
1213                {
1214                    let start: i32 =
1215                        eval_expression(&arguments[1], local_context).try_into().expect(
1216                            "internal error: second argument to set-selection-offsets must be an integer",
1217                        );
1218                    let end: i32 = eval_expression(&arguments[2], local_context).try_into().expect(
1219                        "internal error: third argument to set-selection-offsets must be an integer",
1220                    );
1221
1222                    textinput.set_selection_offsets(&window_adapter, &item_rc, start, end);
1223                } else {
1224                    panic!(
1225                        "internal error: member function called on element that doesn't have it: {}",
1226                        elem.borrow().original_name()
1227                    )
1228                }
1229
1230                Value::Void
1231            } else {
1232                panic!("internal error: first argument to set-selection-offsets must be an element")
1233            }
1234        }
1235        BuiltinFunction::ItemFontMetrics => {
1236            if arguments.len() != 1 {
1237                panic!(
1238                    "internal error: incorrect argument count to item font metrics function call"
1239                )
1240            }
1241            let component = local_context.component_instance;
1242            if let Expression::ElementReference(element) = &arguments[0] {
1243                generativity::make_guard!(guard);
1244
1245                let elem = element.upgrade().unwrap();
1246                let enclosing_component = enclosing_component_for_element(&elem, component, guard);
1247                let description = enclosing_component.description;
1248                let item_info = &description.items[elem.borrow().id.as_str()];
1249                let item_ref =
1250                    unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
1251                let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1252                let item_rc = corelib::items::ItemRc::new(
1253                    vtable::VRc::into_dyn(item_comp),
1254                    item_info.item_index(),
1255                );
1256                let window_adapter = component.window_adapter();
1257                let metrics = i_slint_core::items::slint_text_item_fontmetrics(
1258                    &window_adapter,
1259                    item_ref,
1260                    &item_rc,
1261                );
1262                metrics.into()
1263            } else {
1264                panic!("internal error: argument to item-font-metrics must be an element")
1265            }
1266        }
1267        BuiltinFunction::StringIsFloat => {
1268            if arguments.len() != 1 {
1269                panic!("internal error: incorrect argument count to StringIsFloat")
1270            }
1271            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1272                Value::Bool(<f64 as core::str::FromStr>::from_str(s.as_str()).is_ok())
1273            } else {
1274                panic!("Argument not a string");
1275            }
1276        }
1277        BuiltinFunction::StringToFloat => {
1278            if arguments.len() != 1 {
1279                panic!("internal error: incorrect argument count to StringToFloat")
1280            }
1281            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1282                Value::Number(core::str::FromStr::from_str(s.as_str()).unwrap_or(0.))
1283            } else {
1284                panic!("Argument not a string");
1285            }
1286        }
1287        BuiltinFunction::StringIsEmpty => {
1288            if arguments.len() != 1 {
1289                panic!("internal error: incorrect argument count to StringIsEmpty")
1290            }
1291            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1292                Value::Bool(s.is_empty())
1293            } else {
1294                panic!("Argument not a string");
1295            }
1296        }
1297        BuiltinFunction::StringCharacterCount => {
1298            if arguments.len() != 1 {
1299                panic!("internal error: incorrect argument count to StringCharacterCount")
1300            }
1301            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1302                Value::Number(
1303                    unicode_segmentation::UnicodeSegmentation::graphemes(s.as_str(), true).count()
1304                        as f64,
1305                )
1306            } else {
1307                panic!("Argument not a string");
1308            }
1309        }
1310        BuiltinFunction::StringToLowercase => {
1311            if arguments.len() != 1 {
1312                panic!("internal error: incorrect argument count to StringToLowercase")
1313            }
1314            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1315                Value::String(s.to_lowercase().into())
1316            } else {
1317                panic!("Argument not a string");
1318            }
1319        }
1320        BuiltinFunction::StringToUppercase => {
1321            if arguments.len() != 1 {
1322                panic!("internal error: incorrect argument count to StringToUppercase")
1323            }
1324            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1325                Value::String(s.to_uppercase().into())
1326            } else {
1327                panic!("Argument not a string");
1328            }
1329        }
1330        BuiltinFunction::StringStartsWith => {
1331            if arguments.len() != 2 {
1332                panic!("internal error: incorrect argument count to StringStartsWith")
1333            }
1334            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1335                if let Value::String(pat) = eval_expression(&arguments[1], local_context) {
1336                    Value::Bool(s.starts_with(pat.as_str()))
1337                } else {
1338                    panic!("Second argument not a string");
1339                }
1340            } else {
1341                panic!("First argument not a string");
1342            }
1343        }
1344        BuiltinFunction::StringEndsWith => {
1345            if arguments.len() != 2 {
1346                panic!("internal error: incorrect argument count to StringEndsWith")
1347            }
1348            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1349                if let Value::String(pat) = eval_expression(&arguments[1], local_context) {
1350                    Value::Bool(s.ends_with(pat.as_str()))
1351                } else {
1352                    panic!("Second argument not a string");
1353                }
1354            } else {
1355                panic!("First argument not a string");
1356            }
1357        }
1358        BuiltinFunction::KeysToString => {
1359            if arguments.len() != 1 {
1360                panic!("internal error: incorrect argument count to KeysToString")
1361            }
1362            let Value::Keys(keys) = eval_expression(&arguments[0], local_context) else {
1363                panic!("Argument is not of type keys");
1364            };
1365            Value::String(ToSharedString::to_shared_string(&keys))
1366        }
1367        BuiltinFunction::ColorRgbaStruct => {
1368            if arguments.len() != 1 {
1369                panic!("internal error: incorrect argument count to ColorRGBAComponents")
1370            }
1371            if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1372                let color = brush.color();
1373                let values = IntoIterator::into_iter([
1374                    ("red".to_string(), Value::Number(color.red().into())),
1375                    ("green".to_string(), Value::Number(color.green().into())),
1376                    ("blue".to_string(), Value::Number(color.blue().into())),
1377                    ("alpha".to_string(), Value::Number(color.alpha().into())),
1378                ])
1379                .collect();
1380                Value::Struct(values)
1381            } else {
1382                panic!("First argument not a color");
1383            }
1384        }
1385        BuiltinFunction::ColorHsvaStruct => {
1386            if arguments.len() != 1 {
1387                panic!("internal error: incorrect argument count to ColorHSVAComponents")
1388            }
1389            if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1390                let color = brush.color().to_hsva();
1391                let values = IntoIterator::into_iter([
1392                    ("hue".to_string(), Value::Number(color.hue.into())),
1393                    ("saturation".to_string(), Value::Number(color.saturation.into())),
1394                    ("value".to_string(), Value::Number(color.value.into())),
1395                    ("alpha".to_string(), Value::Number(color.alpha.into())),
1396                ])
1397                .collect();
1398                Value::Struct(values)
1399            } else {
1400                panic!("First argument not a color");
1401            }
1402        }
1403        BuiltinFunction::ColorOklchStruct => {
1404            if arguments.len() != 1 {
1405                panic!("internal error: incorrect argument count to ColorOklchStruct")
1406            }
1407            if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1408                let color = brush.color().to_oklch();
1409                let values = IntoIterator::into_iter([
1410                    ("lightness".to_string(), Value::Number(color.lightness.into())),
1411                    ("chroma".to_string(), Value::Number(color.chroma.into())),
1412                    ("hue".to_string(), Value::Number(color.hue.into())),
1413                    ("alpha".to_string(), Value::Number(color.alpha.into())),
1414                ])
1415                .collect();
1416                Value::Struct(values)
1417            } else {
1418                panic!("First argument not a color");
1419            }
1420        }
1421        BuiltinFunction::ColorBrighter => {
1422            if arguments.len() != 2 {
1423                panic!("internal error: incorrect argument count to ColorBrighter")
1424            }
1425            if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1426                if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1427                    brush.brighter(factor as _).into()
1428                } else {
1429                    panic!("Second argument not a number");
1430                }
1431            } else {
1432                panic!("First argument not a color");
1433            }
1434        }
1435        BuiltinFunction::ColorDarker => {
1436            if arguments.len() != 2 {
1437                panic!("internal error: incorrect argument count to ColorDarker")
1438            }
1439            if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1440                if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1441                    brush.darker(factor as _).into()
1442                } else {
1443                    panic!("Second argument not a number");
1444                }
1445            } else {
1446                panic!("First argument not a color");
1447            }
1448        }
1449        BuiltinFunction::ColorTransparentize => {
1450            if arguments.len() != 2 {
1451                panic!("internal error: incorrect argument count to ColorFaded")
1452            }
1453            if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1454                if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1455                    brush.transparentize(factor as _).into()
1456                } else {
1457                    panic!("Second argument not a number");
1458                }
1459            } else {
1460                panic!("First argument not a color");
1461            }
1462        }
1463        BuiltinFunction::ColorMix => {
1464            if arguments.len() != 3 {
1465                panic!("internal error: incorrect argument count to ColorMix")
1466            }
1467
1468            let arg0 = eval_expression(&arguments[0], local_context);
1469            let arg1 = eval_expression(&arguments[1], local_context);
1470            let arg2 = eval_expression(&arguments[2], local_context);
1471
1472            if !matches!(arg0, Value::Brush(Brush::SolidColor(_))) {
1473                panic!("First argument not a color");
1474            }
1475            if !matches!(arg1, Value::Brush(Brush::SolidColor(_))) {
1476                panic!("Second argument not a color");
1477            }
1478            if !matches!(arg2, Value::Number(_)) {
1479                panic!("Third argument not a number");
1480            }
1481
1482            let (
1483                Value::Brush(Brush::SolidColor(color_a)),
1484                Value::Brush(Brush::SolidColor(color_b)),
1485                Value::Number(factor),
1486            ) = (arg0, arg1, arg2)
1487            else {
1488                unreachable!()
1489            };
1490
1491            color_a.mix(&color_b, factor as _).into()
1492        }
1493        BuiltinFunction::ColorWithAlpha => {
1494            if arguments.len() != 2 {
1495                panic!("internal error: incorrect argument count to ColorWithAlpha")
1496            }
1497            if let Value::Brush(brush) = eval_expression(&arguments[0], local_context) {
1498                if let Value::Number(factor) = eval_expression(&arguments[1], local_context) {
1499                    brush.with_alpha(factor as _).into()
1500                } else {
1501                    panic!("Second argument not a number");
1502                }
1503            } else {
1504                panic!("First argument not a color");
1505            }
1506        }
1507        BuiltinFunction::ImageSize => {
1508            if arguments.len() != 1 {
1509                panic!("internal error: incorrect argument count to ImageSize")
1510            }
1511            if let Value::Image(img) = eval_expression(&arguments[0], local_context) {
1512                let size = img.size();
1513                let values = IntoIterator::into_iter([
1514                    ("width".to_string(), Value::Number(size.width as f64)),
1515                    ("height".to_string(), Value::Number(size.height as f64)),
1516                ])
1517                .collect();
1518                Value::Struct(values)
1519            } else {
1520                panic!("First argument not an image");
1521            }
1522        }
1523        BuiltinFunction::ArrayLength => {
1524            if arguments.len() != 1 {
1525                panic!("internal error: incorrect argument count to ArrayLength")
1526            }
1527            match eval_expression(&arguments[0], local_context) {
1528                Value::Model(model) => {
1529                    model.model_tracker().track_row_count_changes();
1530                    Value::Number(model.row_count() as f64)
1531                }
1532                _ => {
1533                    panic!("First argument not an array: {:?}", arguments[0]);
1534                }
1535            }
1536        }
1537        BuiltinFunction::ArrayPush => {
1538            if arguments.len() != 2 {
1539                panic!("internal error: incorrect argument count to ArrayPush")
1540            }
1541
1542            let model = match eval_expression(&arguments[0], local_context) {
1543                Value::Model(m) => m,
1544                _ => panic!("First argument not an array: {:?}", arguments[0]),
1545            };
1546            let value = eval_expression(&arguments[1], local_context);
1547
1548            model.push_row(value);
1549
1550            Value::Void
1551        }
1552        BuiltinFunction::ArrayRemove => {
1553            if arguments.len() != 2 {
1554                panic!("internal error: incorrect argument count to ArrayRemove")
1555            }
1556
1557            let model = match eval_expression(&arguments[0], local_context) {
1558                Value::Model(m) => m,
1559                _ => panic!("First argument not an array: {:?}", arguments[0]),
1560            };
1561            let index = match eval_expression(&arguments[1], local_context) {
1562                Value::Number(i) => i,
1563                _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1564            };
1565
1566            model.remove_row(index as isize);
1567
1568            Value::Void
1569        }
1570
1571        BuiltinFunction::ArrayInsert => {
1572            if arguments.len() != 3 {
1573                panic!("internal error: incorrect argument count to ArrayInsert")
1574            }
1575
1576            let model = match eval_expression(&arguments[0], local_context) {
1577                Value::Model(m) => m,
1578                _ => panic!("First argument not an array: {:?}", arguments[0]),
1579            };
1580            let index = match eval_expression(&arguments[1], local_context) {
1581                Value::Number(i) => i,
1582                _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1583            };
1584
1585            let value = eval_expression(&arguments[2], local_context);
1586            model.insert_row(index as isize, value);
1587
1588            Value::Void
1589        }
1590        BuiltinFunction::Rgb => {
1591            let r: i32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1592            let g: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1593            let b: i32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1594            let a: f32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1595            let r: u8 = r.clamp(0, 255) as u8;
1596            let g: u8 = g.clamp(0, 255) as u8;
1597            let b: u8 = b.clamp(0, 255) as u8;
1598            let a: u8 = (255. * a).clamp(0., 255.) as u8;
1599            Value::Brush(Brush::SolidColor(Color::from_argb_u8(a, r, g, b)))
1600        }
1601        BuiltinFunction::Hsv => {
1602            let h: f32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1603            let s: f32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1604            let v: f32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1605            let a: f32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1606            let a = (1. * a).clamp(0., 1.);
1607            Value::Brush(Brush::SolidColor(Color::from_hsva(h, s, v, a)))
1608        }
1609        BuiltinFunction::Oklch => {
1610            let l: f32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1611            let c: f32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1612            let h: f32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1613            let a: f32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1614            let l = l.clamp(0., 1.);
1615            let c = c.max(0.);
1616            let a = a.clamp(0., 1.);
1617            Value::Brush(Brush::SolidColor(Color::from_oklch(l, c, h, a)))
1618        }
1619        BuiltinFunction::ColorScheme => {
1620            let root_weak =
1621                vtable::VWeak::into_dyn(local_context.component_instance.root_weak().clone());
1622            let root = root_weak.upgrade().unwrap();
1623            corelib::window::context_for_root(&root)
1624                .map_or(corelib::items::ColorScheme::Unknown, |ctx| ctx.color_scheme(Some(&root)))
1625                .into()
1626        }
1627        BuiltinFunction::AccentColor => {
1628            let root_weak =
1629                vtable::VWeak::into_dyn(local_context.component_instance.root_weak().clone());
1630            let root = root_weak.upgrade().unwrap();
1631            Value::Brush(corelib::Brush::SolidColor(corelib::window::accent_color(&root)))
1632        }
1633        BuiltinFunction::SupportsNativeMenuBar => local_context
1634            .component_instance
1635            .window_adapter()
1636            .internal(corelib::InternalToken)
1637            .is_some_and(|x| x.supports_native_menu_bar())
1638            .into(),
1639        BuiltinFunction::SetupMenuBar => {
1640            let component = local_context.component_instance;
1641            let [
1642                Expression::PropertyReference(entries_nr),
1643                Expression::PropertyReference(sub_menu_nr),
1644                Expression::PropertyReference(activated_nr),
1645                Expression::ElementReference(item_tree_root),
1646                Expression::BoolLiteral(no_native),
1647                condition,
1648                visible,
1649                ..,
1650            ] = arguments
1651            else {
1652                panic!("internal error: incorrect argument count to SetupMenuBar")
1653            };
1654
1655            let menu_item_tree =
1656                item_tree_root.upgrade().unwrap().borrow().enclosing_component.upgrade().unwrap();
1657            let menu_item_tree = crate::dynamic_item_tree::make_menu_item_tree(
1658                &menu_item_tree,
1659                &component,
1660                Some(condition),
1661                Some(visible),
1662            );
1663
1664            let window_adapter = component.window_adapter();
1665            let window_inner = WindowInner::from_pub(window_adapter.window());
1666            let menubar = vtable::VRc::into_dyn(vtable::VRc::clone(&menu_item_tree));
1667            window_inner.setup_menubar_shortcuts(vtable::VRc::clone(&menubar));
1668
1669            if !no_native && window_inner.supports_native_menu_bar() {
1670                window_inner.setup_menubar(menubar);
1671                return Value::Void;
1672            }
1673
1674            let (entries, sub_menu, activated) = menu_item_tree_properties(menu_item_tree);
1675
1676            assert_eq!(
1677                entries_nr.element().borrow().id,
1678                component.description.original.root_element.borrow().id,
1679                "entries need to be in the main element"
1680            );
1681            local_context
1682                .component_instance
1683                .description
1684                .set_binding(component.borrow(), entries_nr.name(), entries)
1685                .unwrap();
1686            let i = &ComponentInstance::InstanceRef(local_context.component_instance);
1687            set_callback_handler(i, &sub_menu_nr.element(), sub_menu_nr.name(), sub_menu).unwrap();
1688            set_callback_handler(i, &activated_nr.element(), activated_nr.name(), activated)
1689                .unwrap();
1690
1691            Value::Void
1692        }
1693        BuiltinFunction::SetupSystemTrayIcon => {
1694            let [
1695                Expression::ElementReference(system_tray_elem),
1696                Expression::ElementReference(item_tree_root),
1697                rest @ ..,
1698            ] = arguments
1699            else {
1700                panic!("internal error: incorrect argument count to SetupSystemTrayIcon")
1701            };
1702
1703            let component = local_context.component_instance;
1704            let elem = system_tray_elem.upgrade().unwrap();
1705            generativity::make_guard!(guard);
1706            let enclosing_component = enclosing_component_for_element(&elem, component, guard);
1707            let description = enclosing_component.description;
1708            let item_info = &description.items[elem.borrow().id.as_str()];
1709            let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1710            let item_tree = vtable::VRc::into_dyn(item_comp);
1711            let item_rc = corelib::items::ItemRc::new(item_tree.clone(), item_info.item_index());
1712
1713            let menu_item_tree_component =
1714                item_tree_root.upgrade().unwrap().borrow().enclosing_component.upgrade().unwrap();
1715            let menu_vrc = crate::dynamic_item_tree::make_menu_item_tree(
1716                &menu_item_tree_component,
1717                &enclosing_component,
1718                rest.first(),
1719                None,
1720            );
1721
1722            let system_tray =
1723                item_rc.downcast::<corelib::items::SystemTrayIcon>().expect("SystemTrayIcon item");
1724            system_tray.as_pin_ref().set_menu(&item_rc, vtable::VRc::into_dyn(menu_vrc));
1725
1726            Value::Void
1727        }
1728        BuiltinFunction::MonthDayCount => {
1729            let m: u32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1730            let y: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1731            Value::Number(i_slint_core::date_time::month_day_count(m, y).unwrap_or(0) as f64)
1732        }
1733        BuiltinFunction::MonthOffset => {
1734            let m: u32 = eval_expression(&arguments[0], local_context).try_into().unwrap();
1735            let y: i32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1736
1737            Value::Number(i_slint_core::date_time::month_offset(m, y) as f64)
1738        }
1739        BuiltinFunction::FormatDate => {
1740            let f: SharedString = eval_expression(&arguments[0], local_context).try_into().unwrap();
1741            let d: u32 = eval_expression(&arguments[1], local_context).try_into().unwrap();
1742            let m: u32 = eval_expression(&arguments[2], local_context).try_into().unwrap();
1743            let y: i32 = eval_expression(&arguments[3], local_context).try_into().unwrap();
1744
1745            Value::String(i_slint_core::date_time::format_date(&f, d, m, y))
1746        }
1747        BuiltinFunction::DateNow => Value::Model(ModelRc::new(VecModel::from(
1748            i_slint_core::date_time::date_now()
1749                .into_iter()
1750                .map(|x| Value::Number(x as f64))
1751                .collect::<Vec<_>>(),
1752        ))),
1753        BuiltinFunction::ValidDate => {
1754            let d: SharedString = eval_expression(&arguments[0], local_context).try_into().unwrap();
1755            let f: SharedString = eval_expression(&arguments[1], local_context).try_into().unwrap();
1756            Value::Bool(i_slint_core::date_time::parse_date(d.as_str(), f.as_str()).is_some())
1757        }
1758        BuiltinFunction::ParseDate => {
1759            let d: SharedString = eval_expression(&arguments[0], local_context).try_into().unwrap();
1760            let f: SharedString = eval_expression(&arguments[1], local_context).try_into().unwrap();
1761
1762            Value::Model(ModelRc::new(
1763                i_slint_core::date_time::parse_date(d.as_str(), f.as_str())
1764                    .map(|x| {
1765                        VecModel::from(
1766                            x.into_iter().map(|x| Value::Number(x as f64)).collect::<Vec<_>>(),
1767                        )
1768                    })
1769                    .unwrap_or_default(),
1770            ))
1771        }
1772        BuiltinFunction::TextInputFocused => Value::Bool(
1773            local_context.component_instance.access_window(|window| window.text_input_focused())
1774                as _,
1775        ),
1776        BuiltinFunction::SetTextInputFocused => {
1777            local_context.component_instance.access_window(|window| {
1778                window.set_text_input_focused(
1779                    eval_expression(&arguments[0], local_context).try_into().unwrap(),
1780                )
1781            });
1782            Value::Void
1783        }
1784        BuiltinFunction::ImplicitLayoutInfo(orient) => {
1785            let component = local_context.component_instance;
1786            if let [Expression::ElementReference(item), constraint_expr] = arguments {
1787                generativity::make_guard!(guard);
1788
1789                let constraint: f32 =
1790                    eval_expression(constraint_expr, local_context).try_into().unwrap_or(-1.);
1791
1792                let item = item.upgrade().unwrap();
1793                let enclosing_component = enclosing_component_for_element(&item, component, guard);
1794                let description = enclosing_component.description;
1795                let item_info = &description.items[item.borrow().id.as_str()];
1796                let item_ref =
1797                    unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
1798                let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1799                let window_adapter = component.window_adapter();
1800                item_ref
1801                    .as_ref()
1802                    .layout_info(
1803                        crate::eval_layout::to_runtime(orient),
1804                        constraint,
1805                        &window_adapter,
1806                        &ItemRc::new(vtable::VRc::into_dyn(item_comp), item_info.item_index()),
1807                    )
1808                    .into()
1809            } else {
1810                panic!("internal error: incorrect arguments to ImplicitLayoutInfo {arguments:?}");
1811            }
1812        }
1813        BuiltinFunction::ItemAbsolutePosition => {
1814            if arguments.len() != 1 {
1815                panic!("internal error: incorrect argument count to ItemAbsolutePosition")
1816            }
1817
1818            let component = local_context.component_instance;
1819
1820            if let Expression::ElementReference(item) = &arguments[0] {
1821                generativity::make_guard!(guard);
1822
1823                let item = item.upgrade().unwrap();
1824                let enclosing_component = enclosing_component_for_element(&item, component, guard);
1825                let description = enclosing_component.description;
1826
1827                let item_info = &description.items[item.borrow().id.as_str()];
1828
1829                let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1830
1831                let item_rc = corelib::items::ItemRc::new(
1832                    vtable::VRc::into_dyn(item_comp),
1833                    item_info.item_index(),
1834                );
1835
1836                // Map the item's own geometry origin through the ancestor transforms so the
1837                // result is the item's absolute position (not its parent's).
1838                item_rc.map_to_window(item_rc.geometry().origin).to_untyped().into()
1839            } else {
1840                panic!("internal error: argument to SetFocusItem must be an element")
1841            }
1842        }
1843        BuiltinFunction::RegisterCustomFontByPath => {
1844            if arguments.len() != 1 {
1845                panic!("internal error: incorrect argument count to RegisterCustomFontByPath")
1846            }
1847            let component = local_context.component_instance;
1848            if let Value::String(s) = eval_expression(&arguments[0], local_context) {
1849                // If the window adapter can't be created, log and skip the registration
1850                // instead of panicking: the same error resurfaces when the window is
1851                // actually used.
1852                let result = component.try_window_adapter().map_err(|e| e.to_string()).and_then(
1853                    |window_adapter| {
1854                        window_adapter
1855                            .renderer()
1856                            .register_font_from_path(&std::path::PathBuf::from(s.as_str()))
1857                            .map_err(|e| format!("Cannot load custom font {}: {e}", s.as_str()))
1858                    },
1859                );
1860                if let Err(err) = result {
1861                    corelib::debug_log!("{err}");
1862                }
1863                Value::Void
1864            } else {
1865                panic!("Argument not a string");
1866            }
1867        }
1868        BuiltinFunction::RegisterCustomFontByMemory | BuiltinFunction::RegisterBitmapFont => {
1869            unimplemented!()
1870        }
1871        BuiltinFunction::Translate => {
1872            let original: SharedString =
1873                eval_expression(&arguments[0], local_context).try_into().unwrap();
1874            let context: SharedString =
1875                eval_expression(&arguments[1], local_context).try_into().unwrap();
1876            let domain: SharedString =
1877                eval_expression(&arguments[2], local_context).try_into().unwrap();
1878            let args = eval_expression(&arguments[3], local_context);
1879            let Value::Model(args) = args else { panic!("Args to translate not a model {args:?}") };
1880            struct StringModelWrapper(ModelRc<Value>);
1881            impl corelib::translations::FormatArgs for StringModelWrapper {
1882                type Output<'a> = SharedString;
1883                fn from_index(&self, index: usize) -> Option<SharedString> {
1884                    self.0.row_data(index).map(|x| x.try_into().unwrap())
1885                }
1886            }
1887            Value::String(corelib::translations::translate(
1888                &original,
1889                &context,
1890                &domain,
1891                &StringModelWrapper(args),
1892                eval_expression(&arguments[4], local_context).try_into().unwrap(),
1893                &SharedString::try_from(eval_expression(&arguments[5], local_context)).unwrap(),
1894            ))
1895        }
1896        BuiltinFunction::Use24HourFormat => Value::Bool(corelib::date_time::use_24_hour_format()),
1897        BuiltinFunction::UpdateTimers => {
1898            crate::dynamic_item_tree::update_timers(local_context.component_instance);
1899            Value::Void
1900        }
1901        BuiltinFunction::DetectOperatingSystem => i_slint_core::detect_operating_system().into(),
1902        // start and stop are unreachable because they are lowered to simple assignment of running
1903        BuiltinFunction::StartTimer => unreachable!(),
1904        BuiltinFunction::StopTimer => unreachable!(),
1905        BuiltinFunction::RestartTimer => {
1906            if let [Expression::ElementReference(timer_element)] = arguments {
1907                crate::dynamic_item_tree::restart_timer(
1908                    timer_element.clone(),
1909                    local_context.component_instance,
1910                );
1911
1912                Value::Void
1913            } else {
1914                panic!("internal error: argument to RestartTimer must be an element")
1915            }
1916        }
1917        BuiltinFunction::OpenUrl => {
1918            let url: SharedString =
1919                eval_expression(&arguments[0], local_context).try_into().unwrap();
1920            let window_adapter = local_context.component_instance.window_adapter();
1921            Value::Bool(corelib::open_url(&url, window_adapter.window()).is_ok())
1922        }
1923        BuiltinFunction::MacosBringAllWindowsToFront => {
1924            corelib::macos_bring_all_windows_to_front();
1925            Value::Void
1926        }
1927        BuiltinFunction::ParseMarkdown => {
1928            let format_string: SharedString =
1929                eval_expression(&arguments[0], local_context).try_into().unwrap();
1930            let args: ModelRc<corelib::styled_text::StyledText> =
1931                eval_expression(&arguments[1], local_context).try_into().unwrap();
1932            Value::StyledText(corelib::styled_text::parse_markdown(
1933                &format_string,
1934                &args.iter().collect::<Vec<_>>(),
1935            ))
1936        }
1937        BuiltinFunction::StringToStyledText => {
1938            let string: SharedString =
1939                eval_expression(&arguments[0], local_context).try_into().unwrap();
1940            Value::StyledText(corelib::styled_text::string_to_styled_text(string.to_string()))
1941        }
1942        BuiltinFunction::ColorToStyledText => {
1943            let color: corelib::Color =
1944                eval_expression(&arguments[0], local_context).try_into().unwrap();
1945            Value::StyledText(corelib::styled_text::color_to_styled_text(color))
1946        }
1947    }
1948}
1949
1950fn call_item_member_function(nr: &NamedReference, local_context: &mut EvalLocalContext) -> Value {
1951    let component = local_context.component_instance;
1952    let elem = nr.element();
1953    let name = nr.name().as_str();
1954    generativity::make_guard!(guard);
1955    let enclosing_component = enclosing_component_for_element(&elem, component, guard);
1956    let description = enclosing_component.description;
1957    let item_info = &description.items[elem.borrow().id.as_str()];
1958    let item_ref = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
1959
1960    let item_comp = enclosing_component.self_weak().get().unwrap().upgrade().unwrap();
1961    let item_rc =
1962        corelib::items::ItemRc::new(vtable::VRc::into_dyn(item_comp), item_info.item_index());
1963
1964    let window_adapter = component.window_adapter();
1965
1966    // TODO: Make this generic through RTTI
1967    if let Some(textinput) = ItemRef::downcast_pin::<corelib::items::TextInput>(item_ref) {
1968        match name {
1969            "select-all" => textinput.select_all(&window_adapter, &item_rc),
1970            "clear-selection" => textinput.clear_selection(&window_adapter, &item_rc),
1971            "cut" => textinput.cut(&window_adapter, &item_rc),
1972            "copy" => textinput.copy(&window_adapter, &item_rc),
1973            "paste" => textinput.paste(&window_adapter, &item_rc),
1974            "undo" => textinput.undo(&window_adapter, &item_rc),
1975            "redo" => textinput.redo(&window_adapter, &item_rc),
1976            _ => panic!("internal: Unknown member function {name} called on TextInput"),
1977        }
1978    } else if let Some(s) = ItemRef::downcast_pin::<corelib::items::SwipeGestureHandler>(item_ref) {
1979        match name {
1980            "cancel" => s.cancel(&window_adapter, &item_rc),
1981            _ => panic!("internal: Unknown member function {name} called on SwipeGestureHandler"),
1982        }
1983    } else if let Some(s) = ItemRef::downcast_pin::<corelib::items::ContextMenu>(item_ref) {
1984        match name {
1985            "close" => s.close(&window_adapter, &item_rc),
1986            "is-open" => return Value::Bool(s.is_open(&window_adapter, &item_rc)),
1987            _ => {
1988                panic!("internal: Unknown member function {name} called on ContextMenu")
1989            }
1990        }
1991    } else if let Some(s) = ItemRef::downcast_pin::<corelib::items::WindowItem>(item_ref) {
1992        match name {
1993            "hide" => s.hide(&window_adapter, &item_rc),
1994            "close" => return Value::Bool(s.close(&window_adapter, &item_rc)),
1995            _ => {
1996                panic!("internal: Unknown member function {name} called on WindowItem")
1997            }
1998        }
1999    } else {
2000        panic!(
2001            "internal error: member function {name} called on element that doesn't have it: {}",
2002            elem.borrow().original_name()
2003        )
2004    }
2005
2006    Value::Void
2007}
2008
2009fn eval_assignment(lhs: &Expression, op: char, rhs: Value, local_context: &mut EvalLocalContext) {
2010    let eval = |lhs| match (lhs, &rhs, op) {
2011        (Value::String(ref mut a), Value::String(b), '+') => {
2012            a.push_str(b.as_str());
2013            Value::String(a.clone())
2014        }
2015        (Value::Number(a), Value::Number(b), '+') => Value::Number(a + b),
2016        (Value::Number(a), Value::Number(b), '-') => Value::Number(a - b),
2017        (Value::Number(a), Value::Number(b), '/') => Value::Number(a / b),
2018        (Value::Number(a), Value::Number(b), '*') => Value::Number(a * b),
2019        (lhs, rhs, op) => panic!("unsupported {lhs:?} {op} {rhs:?}"),
2020    };
2021    match lhs {
2022        Expression::PropertyReference(nr) => {
2023            let element = nr.element();
2024            generativity::make_guard!(guard);
2025            let enclosing_component = enclosing_component_instance_for_element(
2026                &element,
2027                &ComponentInstance::InstanceRef(local_context.component_instance),
2028                guard,
2029            );
2030
2031            match enclosing_component {
2032                ComponentInstance::InstanceRef(enclosing_component) => {
2033                    if op == '=' {
2034                        store_property(enclosing_component, &element, nr.name(), rhs).unwrap();
2035                        return;
2036                    }
2037
2038                    let component = element.borrow().enclosing_component.upgrade().unwrap();
2039                    if element.borrow().id == component.root_element.borrow().id
2040                        && let Some(x) =
2041                            enclosing_component.description.custom_properties.get(nr.name())
2042                    {
2043                        unsafe {
2044                            let p =
2045                                Pin::new_unchecked(&*enclosing_component.as_ptr().add(x.offset));
2046                            x.prop.set(p, eval(x.prop.get(p).unwrap()), None).unwrap();
2047                        }
2048                        return;
2049                    }
2050                    let item_info =
2051                        &enclosing_component.description.items[element.borrow().id.as_str()];
2052                    let item =
2053                        unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2054                    let p = &item_info.rtti.properties[nr.name().as_str()];
2055                    p.set(item, eval(p.get(item)), None).unwrap();
2056                }
2057                ComponentInstance::GlobalComponent(global) => {
2058                    let val = if op == '=' {
2059                        rhs
2060                    } else {
2061                        eval(global.as_ref().get_property(nr.name()).unwrap())
2062                    };
2063                    global.as_ref().set_property(nr.name(), val).unwrap();
2064                }
2065            }
2066        }
2067        Expression::StructFieldAccess { base, name } => {
2068            if let Value::Struct(mut o) = eval_expression(base, local_context) {
2069                let mut r = o.get_field(name).unwrap().clone();
2070                r = if op == '=' { rhs } else { eval(std::mem::take(&mut r)) };
2071                o.set_field(name.to_string(), r);
2072                eval_assignment(base, '=', Value::Struct(o), local_context)
2073            }
2074        }
2075        Expression::RepeaterModelReference { element } => {
2076            let element = element.upgrade().unwrap();
2077            let component_instance = local_context.component_instance;
2078            generativity::make_guard!(g1);
2079            let enclosing_component =
2080                enclosing_component_for_element(&element, component_instance, g1);
2081            // we need a 'static Repeater component in order to call model_set_row_data, so get it.
2082            // Safety: This is the only 'static Id in scope.
2083            let static_guard =
2084                unsafe { generativity::Guard::new(generativity::Id::<'static>::new()) };
2085            let repeater = crate::dynamic_item_tree::get_repeater_by_name(
2086                enclosing_component,
2087                element.borrow().id.as_str(),
2088                static_guard,
2089            );
2090            repeater.0.model_set_row_data(
2091                eval_expression(
2092                    &Expression::RepeaterIndexReference { element: Rc::downgrade(&element) },
2093                    local_context,
2094                )
2095                .try_into()
2096                .unwrap(),
2097                if op == '=' {
2098                    rhs
2099                } else {
2100                    eval(eval_expression(
2101                        &Expression::RepeaterModelReference { element: Rc::downgrade(&element) },
2102                        local_context,
2103                    ))
2104                },
2105            )
2106        }
2107        Expression::ArrayIndex { array, index } => {
2108            let array = eval_expression(array, local_context);
2109            let index = eval_expression(index, local_context);
2110            match (array, index) {
2111                (Value::Model(model), Value::Number(index)) => {
2112                    if index >= 0. && (index as usize) < model.row_count() {
2113                        let index = index as usize;
2114                        if op == '=' {
2115                            model.set_row_data(index, rhs);
2116                        } else {
2117                            model.set_row_data(
2118                                index,
2119                                eval(
2120                                    model
2121                                        .row_data(index)
2122                                        .unwrap_or_else(|| default_value_for_type(&lhs.ty())),
2123                                ),
2124                            );
2125                        }
2126                    }
2127                }
2128                _ => {
2129                    eprintln!("Attempting to write into an array that cannot be written");
2130                }
2131            }
2132        }
2133        _ => panic!("typechecking should make sure this was a PropertyReference"),
2134    }
2135}
2136
2137pub fn load_property(component: InstanceRef, element: &ElementRc, name: &str) -> Result<Value, ()> {
2138    load_property_helper(&ComponentInstance::InstanceRef(component), element, name)
2139}
2140
2141fn load_property_helper(
2142    component_instance: &ComponentInstance,
2143    element: &ElementRc,
2144    name: &str,
2145) -> Result<Value, ()> {
2146    generativity::make_guard!(guard);
2147    match enclosing_component_instance_for_element(element, component_instance, guard) {
2148        ComponentInstance::InstanceRef(enclosing_component) => {
2149            let element = element.borrow();
2150            if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2151            {
2152                if let Some(x) = enclosing_component.description.custom_properties.get(name) {
2153                    return unsafe {
2154                        x.prop.get(Pin::new_unchecked(&*enclosing_component.as_ptr().add(x.offset)))
2155                    };
2156                } else if enclosing_component.description.original.is_global() {
2157                    return Err(());
2158                }
2159            };
2160            let item_info = enclosing_component
2161                .description
2162                .items
2163                .get(element.id.as_str())
2164                .unwrap_or_else(|| panic!("Unknown element for {}.{}", element.id, name));
2165            core::mem::drop(element);
2166            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2167            Ok(item_info.rtti.properties.get(name).ok_or(())?.get(item))
2168        }
2169        ComponentInstance::GlobalComponent(glob) => glob.as_ref().get_property(name),
2170    }
2171}
2172
2173pub fn store_property(
2174    component_instance: InstanceRef,
2175    element: &ElementRc,
2176    name: &str,
2177    mut value: Value,
2178) -> Result<(), SetPropertyError> {
2179    generativity::make_guard!(guard);
2180    match enclosing_component_instance_for_element(
2181        element,
2182        &ComponentInstance::InstanceRef(component_instance),
2183        guard,
2184    ) {
2185        ComponentInstance::InstanceRef(enclosing_component) => {
2186            let maybe_animation = match element.borrow().bindings.get(name) {
2187                Some(b) => crate::dynamic_item_tree::animation_for_property(
2188                    enclosing_component,
2189                    &b.borrow().animation,
2190                ),
2191                None => {
2192                    crate::dynamic_item_tree::animation_for_property(enclosing_component, &None)
2193                }
2194            };
2195
2196            let component = element.borrow().enclosing_component.upgrade().unwrap();
2197            if element.borrow().id == component.root_element.borrow().id {
2198                if let Some(x) = enclosing_component.description.custom_properties.get(name) {
2199                    if let Some(orig_decl) = enclosing_component
2200                        .description
2201                        .original
2202                        .root_element
2203                        .borrow()
2204                        .property_declarations
2205                        .get(name)
2206                    {
2207                        // Do an extra type checking because PropertyInfo::set won't do it for custom structures or array
2208                        if !check_value_type(&mut value, &orig_decl.property_type) {
2209                            return Err(SetPropertyError::WrongType);
2210                        }
2211                    }
2212                    unsafe {
2213                        let p = Pin::new_unchecked(&*enclosing_component.as_ptr().add(x.offset));
2214                        return x
2215                            .prop
2216                            .set(p, value, maybe_animation.as_animation())
2217                            .map_err(|()| SetPropertyError::WrongType);
2218                    }
2219                } else if enclosing_component.description.original.is_global() {
2220                    return Err(SetPropertyError::NoSuchProperty);
2221                }
2222            };
2223            let item_info = &enclosing_component.description.items[element.borrow().id.as_str()];
2224            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2225            let p = &item_info.rtti.properties.get(name).ok_or(SetPropertyError::NoSuchProperty)?;
2226            p.set(item, value, maybe_animation.as_animation())
2227                .map_err(|()| SetPropertyError::WrongType)?;
2228        }
2229        ComponentInstance::GlobalComponent(glob) => {
2230            glob.as_ref().set_property(name, value)?;
2231        }
2232    }
2233    Ok(())
2234}
2235
2236/// Return true if the Value can be used for a property of the given type
2237fn check_value_type(value: &mut Value, ty: &Type) -> bool {
2238    match ty {
2239        Type::Void => true,
2240        Type::Invalid
2241        | Type::InferredProperty
2242        | Type::InferredCallback
2243        | Type::Callback { .. }
2244        | Type::Function { .. }
2245        | Type::ElementReference => panic!("not valid property type"),
2246        Type::Float32 => matches!(value, Value::Number(_)),
2247        Type::Int32 => matches!(value, Value::Number(_)),
2248        Type::String => matches!(value, Value::String(_)),
2249        Type::Color => matches!(value, Value::Brush(_)),
2250        Type::UnitProduct(_)
2251        | Type::Duration
2252        | Type::PhysicalLength
2253        | Type::LogicalLength
2254        | Type::Rem
2255        | Type::Angle
2256        | Type::Percent => matches!(value, Value::Number(_)),
2257        Type::Image => matches!(value, Value::Image(_)),
2258        Type::Bool => matches!(value, Value::Bool(_)),
2259        Type::Model => {
2260            matches!(value, Value::Model(_) | Value::Bool(_) | Value::Number(_))
2261        }
2262        Type::PathData => matches!(value, Value::PathData(_)),
2263        Type::Easing => matches!(value, Value::EasingCurve(_)),
2264        Type::MouseCursor => matches!(value, Value::MouseCursorInner(_)),
2265        Type::Brush => matches!(value, Value::Brush(_)),
2266        Type::Array(inner) => {
2267            matches!(value, Value::Model(m) if m.iter().all(|mut v| check_value_type(&mut v, inner)))
2268        }
2269        Type::Struct(s) => {
2270            let Value::Struct(str) = value else { return false };
2271            if !str
2272                .0
2273                .iter_mut()
2274                .all(|(k, v)| s.fields.get(k).is_some_and(|ty| check_value_type(v, ty)))
2275            {
2276                return false;
2277            }
2278            for k in s.fields.keys() {
2279                str.0.entry(k.clone()).or_insert_with(|| default_value_for_struct_field(s, k));
2280            }
2281            true
2282        }
2283        Type::Enumeration(en) => {
2284            matches!(value, Value::EnumerationValue(name, _) if name == en.name.as_str())
2285        }
2286        Type::Keys => matches!(value, Value::Keys(_)),
2287        Type::LayoutCache => matches!(value, Value::LayoutCache(_)),
2288        Type::ArrayOfU16 => matches!(value, Value::ArrayOfU16(_)),
2289        Type::ComponentFactory => matches!(value, Value::ComponentFactory(_)),
2290        Type::StyledText => matches!(value, Value::StyledText(_)),
2291        Type::DataTransfer => matches!(value, Value::DataTransfer(_)),
2292    }
2293}
2294
2295pub(crate) fn invoke_callback(
2296    component_instance: &ComponentInstance,
2297    element: &ElementRc,
2298    callback_name: &SmolStr,
2299    args: &[Value],
2300) -> Option<Value> {
2301    generativity::make_guard!(guard);
2302    match enclosing_component_instance_for_element(element, component_instance, guard) {
2303        ComponentInstance::InstanceRef(enclosing_component) => {
2304            // Keep the component alive while the callback runs: the callback may close the popup
2305            // that owns this callback, and Callback::call() restores the handler after returning.
2306            let _component_guard = enclosing_component
2307                .self_weak()
2308                .get()
2309                .expect("component self weak must be initialized before invoking callbacks")
2310                .upgrade()
2311                .expect("component must be alive while invoking callbacks");
2312            let description = enclosing_component.description;
2313            let element = element.borrow();
2314            if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2315            {
2316                if let Some(callback_offset) = description.custom_callbacks.get(callback_name) {
2317                    if let Some(tracker_offset) = description.callback_trackers.get(callback_name) {
2318                        tracker_offset.apply_pin(enclosing_component.instance).get();
2319                    }
2320                    let callback = callback_offset.apply(&*enclosing_component.instance);
2321                    let res = callback.call(args);
2322                    return Some(if res != Value::Void {
2323                        res
2324                    } else if let Some(Type::Callback(callback)) = description
2325                        .original
2326                        .root_element
2327                        .borrow()
2328                        .property_declarations
2329                        .get(callback_name)
2330                        .map(|d| &d.property_type)
2331                    {
2332                        // If the callback was not set, the return value will be Value::Void, but we need
2333                        // to make sure that the value is actually of the right type as returned by the
2334                        // callback, otherwise we will get panics later
2335                        default_value_for_type(&callback.return_type)
2336                    } else {
2337                        res
2338                    });
2339                } else if enclosing_component.description.original.is_global() {
2340                    return None;
2341                }
2342            };
2343            let item_info = &description.items[element.id.as_str()];
2344            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2345            item_info
2346                .rtti
2347                .callbacks
2348                .get(callback_name.as_str())
2349                .map(|callback| callback.call(item, args))
2350        }
2351        ComponentInstance::GlobalComponent(global) => {
2352            Some(global.as_ref().invoke_callback(callback_name, args).unwrap())
2353        }
2354    }
2355}
2356
2357pub(crate) fn set_callback_handler(
2358    component_instance: &ComponentInstance,
2359    element: &ElementRc,
2360    callback_name: &str,
2361    handler: CallbackHandler,
2362) -> Result<(), ()> {
2363    generativity::make_guard!(guard);
2364    match enclosing_component_instance_for_element(element, component_instance, guard) {
2365        ComponentInstance::InstanceRef(enclosing_component) => {
2366            let description = enclosing_component.description;
2367            let element = element.borrow();
2368            if element.id == element.enclosing_component.upgrade().unwrap().root_element.borrow().id
2369            {
2370                if let Some(callback_offset) = description.custom_callbacks.get(callback_name) {
2371                    let callback = callback_offset.apply(&*enclosing_component.instance);
2372                    callback.set_handler(handler);
2373                    if let Some(tracker_offset) = description.callback_trackers.get(callback_name) {
2374                        tracker_offset.apply_pin(enclosing_component.instance).mark_dirty();
2375                    }
2376                    return Ok(());
2377                } else if enclosing_component.description.original.is_global() {
2378                    return Err(());
2379                }
2380            };
2381            let item_info = &description.items[element.id.as_str()];
2382            let item = unsafe { item_info.item_from_item_tree(enclosing_component.as_ptr()) };
2383            if let Some(callback) = item_info.rtti.callbacks.get(callback_name) {
2384                callback.set_handler(item, handler);
2385                Ok(())
2386            } else {
2387                Err(())
2388            }
2389        }
2390        ComponentInstance::GlobalComponent(global) => {
2391            global.as_ref().set_callback_handler(callback_name, handler)
2392        }
2393    }
2394}
2395
2396/// Invoke the function.
2397///
2398/// Return None if the function don't exist
2399pub(crate) fn call_function(
2400    component_instance: &ComponentInstance,
2401    element: &ElementRc,
2402    function_name: &str,
2403    args: Vec<Value>,
2404) -> Option<Value> {
2405    generativity::make_guard!(guard);
2406    match enclosing_component_instance_for_element(element, component_instance, guard) {
2407        ComponentInstance::InstanceRef(c) => {
2408            // Keep the component alive while the function runs: the function may close the popup
2409            // that owns this function or callbacks it invokes.
2410            let _component_guard = c
2411                .self_weak()
2412                .get()
2413                .expect("component self weak must be initialized before invoking functions")
2414                .upgrade()
2415                .expect("component must be alive while invoking functions");
2416            let mut ctx = EvalLocalContext::from_function_arguments(c, args);
2417            eval_expression(
2418                &element.borrow().bindings.get(function_name)?.borrow().expression,
2419                &mut ctx,
2420            )
2421            .into()
2422        }
2423        ComponentInstance::GlobalComponent(g) => g.as_ref().eval_function(function_name, args).ok(),
2424    }
2425}
2426
2427/// Return the component instance which hold the given element.
2428/// Does not take in account the global component.
2429pub fn enclosing_component_for_element<'a, 'old_id, 'new_id>(
2430    element: &'a ElementRc,
2431    component: InstanceRef<'a, 'old_id>,
2432    _guard: generativity::Guard<'new_id>,
2433) -> InstanceRef<'a, 'new_id> {
2434    let enclosing = &element.borrow().enclosing_component.upgrade().unwrap();
2435    if Rc::ptr_eq(enclosing, &component.description.original) {
2436        // Safety: new_id is an unique id
2437        unsafe {
2438            std::mem::transmute::<InstanceRef<'a, 'old_id>, InstanceRef<'a, 'new_id>>(component)
2439        }
2440    } else {
2441        assert!(!enclosing.is_global());
2442        // Safety: this is the only place we use this 'static lifetime in this function and nothing is returned with it
2443        // For some reason we can't make a new guard here because the compiler thinks we are returning that
2444        // (it assumes that the 'id must outlive 'a , which is not true)
2445        let static_guard = unsafe { generativity::Guard::new(generativity::Id::<'static>::new()) };
2446
2447        let parent_instance = component
2448            .parent_instance(static_guard)
2449            .expect("accessing deleted parent (issue #6426)");
2450        enclosing_component_for_element(element, parent_instance, _guard)
2451    }
2452}
2453
2454/// Return the component instance which hold the given element.
2455/// The difference with enclosing_component_for_element is that it takes the GlobalComponent into account.
2456pub(crate) fn enclosing_component_instance_for_element<'a, 'new_id>(
2457    element: &'a ElementRc,
2458    component_instance: &ComponentInstance<'a, '_>,
2459    guard: generativity::Guard<'new_id>,
2460) -> ComponentInstance<'a, 'new_id> {
2461    let enclosing = &element.borrow().enclosing_component.upgrade().unwrap();
2462    match component_instance {
2463        ComponentInstance::InstanceRef(component) => {
2464            if enclosing.is_global() && !Rc::ptr_eq(enclosing, &component.description.original) {
2465                ComponentInstance::GlobalComponent(
2466                    component
2467                        .description
2468                        .extra_data_offset
2469                        .apply(component.instance.get_ref())
2470                        .globals
2471                        .get()
2472                        .unwrap()
2473                        .get(enclosing.root_element.borrow().id.as_str())
2474                        .unwrap(),
2475                )
2476            } else {
2477                ComponentInstance::InstanceRef(enclosing_component_for_element(
2478                    element, *component, guard,
2479                ))
2480            }
2481        }
2482        ComponentInstance::GlobalComponent(global) => {
2483            //assert!(Rc::ptr_eq(enclosing, &global.component));
2484            ComponentInstance::GlobalComponent(global.clone())
2485        }
2486    }
2487}
2488
2489pub fn new_struct_with_bindings<ElementType: 'static + Default + corelib::rtti::BuiltinItem>(
2490    bindings: &i_slint_compiler::object_tree::BindingsMap,
2491    local_context: &mut EvalLocalContext,
2492) -> ElementType {
2493    let mut element = ElementType::default();
2494    for (prop, info) in ElementType::fields::<Value>().into_iter() {
2495        if let Some(binding) = &bindings.get(prop) {
2496            let value = eval_expression(&binding.borrow(), local_context);
2497            info.set_field(&mut element, value).unwrap();
2498        }
2499    }
2500    element
2501}
2502
2503fn convert_from_lyon_path<'a>(
2504    events_it: impl IntoIterator<Item = &'a i_slint_compiler::expression_tree::Expression>,
2505    points_it: impl IntoIterator<Item = &'a i_slint_compiler::expression_tree::Expression>,
2506    local_context: &mut EvalLocalContext,
2507) -> PathData {
2508    let events = events_it
2509        .into_iter()
2510        .map(|event_expr| eval_expression(event_expr, local_context).try_into().unwrap())
2511        .collect::<SharedVector<_>>();
2512
2513    let points = points_it
2514        .into_iter()
2515        .map(|point_expr| {
2516            let point_value = eval_expression(point_expr, local_context);
2517            let point_struct: Struct = point_value.try_into().unwrap();
2518            let mut point = i_slint_core::graphics::Point::default();
2519            let x: f64 = point_struct.get_field("x").unwrap().clone().try_into().unwrap();
2520            let y: f64 = point_struct.get_field("y").unwrap().clone().try_into().unwrap();
2521            point.x = x as _;
2522            point.y = y as _;
2523            point
2524        })
2525        .collect::<SharedVector<_>>();
2526
2527    PathData::Events(events, points)
2528}
2529
2530pub fn convert_path(path: &ExprPath, local_context: &mut EvalLocalContext) -> PathData {
2531    match path {
2532        ExprPath::Elements(elements) => PathData::Elements(
2533            elements
2534                .iter()
2535                .map(|element| convert_path_element(element, local_context))
2536                .collect::<SharedVector<PathElement>>(),
2537        ),
2538        ExprPath::Events(events, points) => {
2539            convert_from_lyon_path(events.iter(), points.iter(), local_context)
2540        }
2541        ExprPath::Commands(commands) => {
2542            if let Value::String(commands) = eval_expression(commands, local_context) {
2543                PathData::Commands(commands)
2544            } else {
2545                panic!("binding to path commands does not evaluate to string");
2546            }
2547        }
2548    }
2549}
2550
2551fn convert_path_element(
2552    expr_element: &ExprPathElement,
2553    local_context: &mut EvalLocalContext,
2554) -> PathElement {
2555    match expr_element.element_type.native_class.class_name.as_str() {
2556        "MoveTo" => {
2557            PathElement::MoveTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2558        }
2559        "LineTo" => {
2560            PathElement::LineTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2561        }
2562        "ArcTo" => {
2563            PathElement::ArcTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2564        }
2565        "CubicTo" => {
2566            PathElement::CubicTo(new_struct_with_bindings(&expr_element.bindings, local_context))
2567        }
2568        "QuadraticTo" => PathElement::QuadraticTo(new_struct_with_bindings(
2569            &expr_element.bindings,
2570            local_context,
2571        )),
2572        "Close" => PathElement::Close,
2573        _ => panic!(
2574            "Cannot create unsupported path element {}",
2575            expr_element.element_type.native_class.class_name
2576        ),
2577    }
2578}
2579
2580/// Create a value suitable as the default value of a given type
2581pub fn default_value_for_type(ty: &Type) -> Value {
2582    match ty {
2583        Type::Float32 | Type::Int32 => Value::Number(0.),
2584        Type::String => Value::String(Default::default()),
2585        Type::Color | Type::Brush => Value::Brush(Default::default()),
2586        Type::Duration | Type::Angle | Type::PhysicalLength | Type::LogicalLength | Type::Rem => {
2587            Value::Number(0.)
2588        }
2589        Type::Image => Value::Image(Default::default()),
2590        Type::Bool => Value::Bool(false),
2591        Type::Callback { .. } => Value::Void,
2592        Type::Struct(s) => Value::Struct(
2593            s.fields
2594                .keys()
2595                .map(|n| (n.to_string(), default_value_for_struct_field(s, n)))
2596                .collect::<Struct>(),
2597        ),
2598        Type::Array(_) | Type::Model => Value::Model(Default::default()),
2599        Type::Percent => Value::Number(0.),
2600        Type::Enumeration(e) => Value::EnumerationValue(
2601            e.name.to_string(),
2602            e.values.get(e.default_value).unwrap().to_string(),
2603        ),
2604        Type::Keys => Value::Keys(Default::default()),
2605        Type::DataTransfer => Value::DataTransfer(Default::default()),
2606        Type::Easing => Value::EasingCurve(Default::default()),
2607        Type::MouseCursor => Value::MouseCursorInner(Default::default()),
2608        Type::Void | Type::Invalid => Value::Void,
2609        Type::UnitProduct(_) => Value::Number(0.),
2610        Type::PathData => Value::PathData(Default::default()),
2611        Type::LayoutCache => Value::LayoutCache(Default::default()),
2612        Type::ArrayOfU16 => Value::ArrayOfU16(Default::default()),
2613        Type::ComponentFactory => Value::ComponentFactory(Default::default()),
2614        Type::InferredProperty
2615        | Type::InferredCallback
2616        | Type::ElementReference
2617        | Type::Function { .. } => {
2618            panic!("There can't be such property")
2619        }
2620        Type::StyledText => Value::StyledText(Default::default()),
2621    }
2622}
2623
2624/// Create a value for the default of a struct field:
2625/// the user-declared default value (`struct Foo { bar: int = 42 }`) if there is one,
2626/// otherwise the default value for the field's type.
2627pub fn default_value_for_struct_field(
2628    s: &i_slint_compiler::langtype::Struct,
2629    field_name: &str,
2630) -> Value {
2631    match s.field_defaults.get(field_name) {
2632        Some(expr) => eval_constant_expression(expr),
2633        None => default_value_for_type(
2634            s.fields.get(field_name).expect("default value requested for unknown struct field"),
2635        ),
2636    }
2637}
2638
2639/// Convert a value to the given type, as [`Expression::Cast`] does
2640fn cast_value(value: Value, to: &Type) -> Value {
2641    match (value, to) {
2642        (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
2643        (Value::Number(n), Type::String) => {
2644            Value::String(i_slint_core::string::shared_string_from_number(n))
2645        }
2646        (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
2647        (Value::Brush(brush), Type::Color) => brush.color().into(),
2648        (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
2649        (v, _) => v,
2650    }
2651}
2652
2653/// Apply a unary operator to a value; returns the unmodified value as the error
2654/// for unsupported combinations
2655fn eval_unary_op(sub: Value, op: char) -> Result<Value, Value> {
2656    match (sub, op) {
2657        (Value::Number(a), '+') => Ok(Value::Number(a)),
2658        (Value::Number(a), '-') => Ok(Value::Number(-a)),
2659        (Value::Bool(a), '!') => Ok(Value::Bool(!a)),
2660        (sub, _) => Err(sub),
2661    }
2662}
2663
2664/// Evaluate a constant expression as stored in [`i_slint_compiler::langtype::Struct::field_defaults`],
2665/// which needs no evaluation context.
2666/// Mirrors [`eval_expression`] for the corresponding expressions.
2667fn eval_constant_expression(expr: &ConstantExpression) -> Value {
2668    match expr {
2669        ConstantExpression::StringLiteral(s) => Value::String(s.as_str().into()),
2670        ConstantExpression::NumberLiteral(n, _unit) => Value::Number(*n),
2671        ConstantExpression::BoolLiteral(b) => Value::Bool(*b),
2672        ConstantExpression::EnumerationValue(value) => {
2673            Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
2674        }
2675        ConstantExpression::Cast { from, to } => cast_value(eval_constant_expression(from), to),
2676        ConstantExpression::UnaryOp { sub, op } => {
2677            // The resolver only accepts the unary operators on matching operand types
2678            eval_unary_op(eval_constant_expression(sub), *op)
2679                .unwrap_or_else(|sub| panic!("unsupported {op} {sub:?}"))
2680        }
2681        ConstantExpression::Struct { values, .. } => Value::Struct(
2682            values
2683                .iter()
2684                .map(|(k, v)| (k.to_string(), eval_constant_expression(v)))
2685                .collect::<Struct>(),
2686        ),
2687        ConstantExpression::Array { values, .. } => {
2688            Value::Model(ModelRc::new(corelib::model::SharedVectorModel::from(
2689                values.iter().map(eval_constant_expression).collect::<SharedVector<_>>(),
2690            )))
2691        }
2692    }
2693}
2694
2695fn menu_item_tree_properties(
2696    context_menu_item_tree: vtable::VRc<i_slint_core::menus::MenuVTable, MenuFromItemTree>,
2697) -> (Box<dyn Fn() -> Value>, CallbackHandler, CallbackHandler) {
2698    let context_menu_item_tree_ = context_menu_item_tree.clone();
2699    let entries = Box::new(move || {
2700        let mut entries = SharedVector::default();
2701        context_menu_item_tree_.sub_menu(None, &mut entries);
2702        Value::Model(ModelRc::new(VecModel::from(
2703            entries.into_iter().map(Value::from).collect::<Vec<_>>(),
2704        )))
2705    });
2706    let context_menu_item_tree_ = context_menu_item_tree.clone();
2707    let sub_menu = Box::new(move |args: &[Value]| -> Value {
2708        let mut entries = SharedVector::default();
2709        context_menu_item_tree_.sub_menu(Some(&args[0].clone().try_into().unwrap()), &mut entries);
2710        Value::Model(ModelRc::new(VecModel::from(
2711            entries.into_iter().map(Value::from).collect::<Vec<_>>(),
2712        )))
2713    });
2714    let activated = Box::new(move |args: &[Value]| -> Value {
2715        context_menu_item_tree.activate(&args[0].clone().try_into().unwrap());
2716        Value::Void
2717    });
2718    (entries, sub_menu, activated)
2719}