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