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