Skip to main content

slint_interpreter/
eval.rs

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