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