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