Skip to main content

slint_interpreter/
eval.rs

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